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
google/deluca
test_simulator.py
test_simulator
test_simulator
open loop test using vmap.
[ "open", "loop", "test", "using", "vmap." ]
def test_simulator(sim, dataset, key='test'): if isinstance(dataset, str): dataset = pickle.load(open(dataset, 'rb')) test_summary = {} (x_test, y_test) = dataset.data[key] score = map_rollout_over_batch(sim, (x_test, y_test), rollout) test_summary['mae'] = score return test_summary
['def', 'test_simulator(sim,', 'dataset,', "key='test'):", 'if', 'isinstance(dataset,', 'str):', 'dataset', '=', 'pickle.load(open(dataset,', "'rb'))", 'test_summary', '=', '{}', '(x_test,', 'y_test)', '=', 'dataset.data[key]', 'score', '=', 'map_rollout_over_batch(sim,', '(x_test,', 'y_test),', 'rollout)', "test_summa...
537,941
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
logSumExp
logSumExp
Computes the log(sum(exp(t))) numerically stabily.
[ "Computes", "the", "log(sum(exp(t)))", "numerically", "stabily." ]
def logSumExp(t, axis=0, keep_dims=False): m = tf.reduce_max(t, [axis]) res = m + tf.log(tf.reduce_sum(tf.exp(t - tf.expand_dims(m, axis)), [axis])) if keep_dims: return tf.expand_dims(res, axis) else: return res
['def', 'logSumExp(t,', 'axis=0,', 'keep_dims=False):', 'm', '=', 'tf.reduce_max(t,', '[axis])', 'res', '=', 'm', '+', 'tf.log(tf.reduce_sum(tf.exp(t', '-', 'tf.expand_dims(m,', 'axis)),', '[axis]))', 'if', 'keep_dims:', 'return', 'tf.expand_dims(res,', 'axis)', 'else:', 'return', 'res']
109,548
rudranil723/mini-main
zipp.py
CompleteDirs.make
make
Given a source (filename or zipfile), return an appropriate CompleteDirs subclass.
[ "Given", "a", "source", "(filename", "or", "zipfile),", "return", "an", "appropriate", "CompleteDirs", "subclass." ]
def make(cls, source): if isinstance(source, CompleteDirs): return source if not isinstance(source, zipfile.ZipFile): return cls(_pathlib_compat(source)) if 'r' not in source.mode: cls = CompleteDirs source.__class__ = cls return source
['def', 'make(cls,', 'source):', 'if', 'isinstance(source,', 'CompleteDirs):', 'return', 'source', 'if', 'not', 'isinstance(source,', 'zipfile.ZipFile):', 'return', 'cls(_pathlib_compat(source))', 'if', "'r'", 'not', 'in', 'source.mode:', 'cls', '=', 'CompleteDirs', 'source.__class__', '=', 'cls', 'return', 'source']
270,381
ldkong1205/LaserMix
multi_scale_deform_attn.py
MultiScaleDeformableAttnFunction.backward
backward
GPU/MLU version of backward function.
[ "GPU/MLU", "version", "of", "backward", "function." ]
def backward(ctx, grad_output: torch.Tensor) -> tuple: (value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights) = ctx.saved_tensors grad_value = torch.zeros_like(value) grad_sampling_loc = torch.zeros_like(sampling_locations) grad_attn_weight = torch.zeros_like(atten...
['def', 'backward(ctx,', 'grad_output:', 'torch.Tensor)', '->', 'tuple:', '(value,', 'value_spatial_shapes,', 'value_level_start_index,', 'sampling_locations,', 'attention_weights)', '=', 'ctx.saved_tensors', 'grad_value', '=', 'torch.zeros_like(value)', 'grad_sampling_loc', '=', 'torch.zeros_like(sampling_locations)',...
624,511
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
image_embedding.py
inception_v3
inception_v3
Builds an Inception V3 subgraph for image embeddings.
[ "Builds", "an", "Inception", "V3", "subgraph", "for", "image", "embeddings." ]
def inception_v3(images, trainable=True, is_training=True, weight_decay=4e-05, stddev=0.1, dropout_keep_prob=0.8, use_batch_norm=True, batch_norm_params=None, add_summaries=True, scope='InceptionV3'): is_inception_model_training = trainable and is_training if use_batch_norm: if not batch_norm_params: ...
['def', 'inception_v3(images,', 'trainable=True,', 'is_training=True,', 'weight_decay=4e-05,', 'stddev=0.1,', 'dropout_keep_prob=0.8,', 'use_batch_norm=True,', 'batch_norm_params=None,', 'add_summaries=True,', "scope='InceptionV3'):", 'is_inception_model_training', '=', 'trainable', 'and', 'is_training', 'if', 'use_bat...
48,821
PaddlePaddle/PaddleSpeech
embedding.py
LegacyRelPositionalEncoding.extend_pe
extend_pe
Reset the positional encodings.
[ "Reset", "the", "positional", "encodings." ]
def extend_pe(self, x): if self.pe is not None: if paddle.shape(self.pe)[1] >= paddle.shape(x)[1]: return pe = paddle.zeros((paddle.shape(x)[1], self.d_model)) if self.reverse: position = paddle.arange(paddle.shape(x)[1] - 1, -1, -1.0, dtype=paddle.float32).unsqueeze(1) else:...
['def', 'extend_pe(self,', 'x):', 'if', 'self.pe', 'is', 'not', 'None:', 'if', 'paddle.shape(self.pe)[1]', '>=', 'paddle.shape(x)[1]:', 'return', 'pe', '=', 'paddle.zeros((paddle.shape(x)[1],', 'self.d_model))', 'if', 'self.reverse:', 'position', '=', 'paddle.arange(paddle.shape(x)[1]', '-', '1,', '-1,', '-1.0,', 'dtyp...
277,274
tallosan/DeWatermarker
tests_generator.py
TestDSGenerator.test_generate_dataset
test_generate_dataset
Ensure that the dataset generation method calls the correct methods, and functions as expected.
[ "Ensure", "that", "the", "dataset", "generation", "method", "calls", "the", "correct", "methods,", "and", "functions", "as", "expected." ]
def test_generate_dataset(self, mock_create_datapoint, mock_save_ds, mock_add_watermark): MOCK_ADD_WM = '<MOCK_ADD_WATERMARK>' mock_add_watermark.return_value = MOCK_ADD_WM MOCK_CREATE_DATAPOINT = {'watermarked': MOCK_ADD_WM, 'original': self.primary_image} mock_create_datapoint.return_value = MOCK_CREA...
['def', 'test_generate_dataset(self,', 'mock_create_datapoint,', 'mock_save_ds,', 'mock_add_watermark):', 'MOCK_ADD_WM', '=', "'<MOCK_ADD_WATERMARK>'", 'mock_add_watermark.return_value', '=', 'MOCK_ADD_WM', 'MOCK_CREATE_DATAPOINT', '=', "{'watermarked':", 'MOCK_ADD_WM,', "'original':", 'self.primary_image}', 'mock_crea...
549,989
OpenMDAO/OpenMDAO-Framework
kriging_surrogate.py
KrigingSurrogate.get_uncertain_value
get_uncertain_value
Returns a NormalDistribution centered around the value, with a standard deviation of 0.
[ "Returns", "a", "NormalDistribution", "centered", "around", "the", "value,", "with", "a", "standard", "deviation", "of", "0." ]
def get_uncertain_value(self, value): return NormalDistribution(value, 0.0)
['def', 'get_uncertain_value(self,', 'value):', 'return', 'NormalDistribution(value,', '0.0)']
275,600
greydanus/mr_london
pildriver.py
PILDriver.do_subtract
do_subtract
usage: subtract <image:pic1> <image:pic2> <int:offset> <float:scale> Pop the two top images, produce the scaled difference with offset.
[ "usage:", "subtract", "<image:pic1>", "<image:pic2>", "<int:offset>", "<float:scale>", "Pop", "the", "two", "top", "images,", "produce", "the", "scaled", "difference", "with", "offset." ]
def do_subtract(self): from PIL import ImageChops image1 = self.do_pop() image2 = self.do_pop() scale = float(self.do_pop()) offset = int(self.do_pop()) self.push(ImageChops.subtract(image1, image2, scale, offset))
['def', 'do_subtract(self):', 'from', 'PIL', 'import', 'ImageChops', 'image1', '=', 'self.do_pop()', 'image2', '=', 'self.do_pop()', 'scale', '=', 'float(self.do_pop())', 'offset', '=', 'int(self.do_pop())', 'self.push(ImageChops.subtract(image1,', 'image2,', 'scale,', 'offset))']
241,767
rouge8/20questions
model.py
delete_question
delete_question
Deletes a question and its weights for a particular question_id.
[ "Deletes", "a", "question", "and", "its", "weights", "for", "a", "particular", "question_id." ]
def delete_question(question_id): db.delete('questions', where='id=$question_id', vars=locals()) db.delete('data', where='question_id=$question_id', vars=locals())
['def', 'delete_question(question_id):', "db.delete('questions',", "where='id=$question_id',", 'vars=locals())', "db.delete('data',", "where='question_id=$question_id',", 'vars=locals())']
4,391
weimin17/Object-Detection_HelmetDetection
coords.py
to_sgf
to_sgf
Converts from a MiniGo coordinate to an SGF coordinate.
[ "Converts", "from", "a", "MiniGo", "coordinate", "to", "an", "SGF", "coordinate." ]
def to_sgf(coord): if coord is None: return '' return _SGF_COLUMNS[coord[1]] + _SGF_COLUMNS[coord[0]]
['def', 'to_sgf(coord):', 'if', 'coord', 'is', 'None:', 'return', "''", 'return', '_SGF_COLUMNS[coord[1]]', '+', '_SGF_COLUMNS[coord[0]]']
758,102
lhotse-speech/lhotse
but_reverb_db.py
but_reverb_db
but_reverb_db
BUT Reverb DB data preparation.
[ "BUT", "Reverb", "DB", "data", "preparation." ]
def but_reverb_db(corpus_dir: Pathlike, output_dir: Pathlike, parts: Union[str, Sequence[str]]): prepare_but_reverb_db(corpus_dir, output_dir=output_dir, parts=parts)
['def', 'but_reverb_db(corpus_dir:', 'Pathlike,', 'output_dir:', 'Pathlike,', 'parts:', 'Union[str,', 'Sequence[str]]):', 'prepare_but_reverb_db(corpus_dir,', 'output_dir=output_dir,', 'parts=parts)']
600,585
kubeflow/pipelines
executor.py
Executor.Do
Do
Executes the minio upload process.
[ "Executes", "the", "minio", "upload", "process." ]
def Do(self, input_dict: dict, output_dict: dict, exec_properties: dict): (source, bucket_name, folder_name, endpoint) = self.get_fn_args(input_dict=input_dict, exec_properties=exec_properties) minio_config = self._read_minio_creds(endpoint=endpoint) client = self._initiate_minio_client(minio_config=minio_c...
['def', 'Do(self,', 'input_dict:', 'dict,', 'output_dict:', 'dict,', 'exec_properties:', 'dict):', '(source,', 'bucket_name,', 'folder_name,', 'endpoint)', '=', 'self.get_fn_args(input_dict=input_dict,', 'exec_properties=exec_properties)', 'minio_config', '=', 'self._read_minio_creds(endpoint=endpoint)', 'client', '=',...
779,631
reihaneh-torkzadehmahani/DP-CGAN
our_dp_optimizer_MomentAcc.py
make_gaussian_optimizer_class
make_gaussian_optimizer_class
Constructs a DP optimizer with Gaussian averaging of updates.
[ "Constructs", "a", "DP", "optimizer", "with", "Gaussian", "averaging", "of", "updates." ]
def make_gaussian_optimizer_class(cls): class DPGaussianOptimizerClass(make_optimizer_class(cls)): def __init__(self, moment_accountant, l2_norm_clip, noise_multiplier, num_microbatches, unroll_microbatches=False, *args, **kwargs): dp_average_query = gaussian_query.GaussianAverageQuery(l2_norm...
['def', 'make_gaussian_optimizer_class(cls):', 'class', 'DPGaussianOptimizerClass(make_optimizer_class(cls)):', 'def', '__init__(self,', 'moment_accountant,', 'l2_norm_clip,', 'noise_multiplier,', 'num_microbatches,', 'unroll_microbatches=False,', '*args,', '**kwargs):', 'dp_average_query', '=', 'gaussian_query.Gaussia...
552,336
Z7Gao/CS181-Artificial-Intelligence
logic_utils.py
mean
mean
Return the arithmetic average of the values.
[ "Return", "the", "arithmetic", "average", "of", "the", "values." ]
def mean(values): return sum(values) / float(len(values))
['def', 'mean(values):', 'return', 'sum(values)', '/', 'float(len(values))']
220,839
ForrestPi/ObjectDetection
box_utils.py
bbox_overlaps_giou
bbox_overlaps_giou
Calculate the gious between each bbox of bboxes1 and bboxes2.
[ "Calculate", "the", "gious", "between", "each", "bbox", "of", "bboxes1", "and", "bboxes2." ]
def bbox_overlaps_giou(bboxes1, bboxes2): rows = bboxes1.shape[0] cols = bboxes2.shape[0] ious = torch.zeros((rows, cols)) if rows * cols == 0: return ious exchange = False if bboxes1.shape[0] > bboxes2.shape[0]: (bboxes1, bboxes2) = (bboxes2, bboxes1) ious = torch.zeros(...
['def', 'bbox_overlaps_giou(bboxes1,', 'bboxes2):', 'rows', '=', 'bboxes1.shape[0]', 'cols', '=', 'bboxes2.shape[0]', 'ious', '=', 'torch.zeros((rows,', 'cols))', 'if', 'rows', '*', 'cols', '==', '0:', 'return', 'ious', 'exchange', '=', 'False', 'if', 'bboxes1.shape[0]', '>', 'bboxes2.shape[0]:', '(bboxes1,', 'bboxes2)...
742,593
cvjena/PartDetectorDisovery
visualize.py
PatchVisualizer.show_blob
show_blob
This function shows a blob by trying really hard to figure out what type of blob it is, and what is the best way to visualize it.
[ "This", "function", "shows", "a", "blob", "by", "trying", "really", "hard", "to", "figure", "out", "what", "type", "of", "blob", "it", "is,", "and", "what", "is", "the", "best", "way", "to", "visualize", "it." ]
def show_blob(self, blob): if isinstance(blob, base.Blob): data = blob.data() else: data = blob bg_func = np.max if data.ndim == 4: if data.shape[0] == 1: return self.show_blobs(data[0], bg_func=bg_func) elif data.shape[-1] == 3: return self.show_m...
['def', 'show_blob(self,', 'blob):', 'if', 'isinstance(blob,', 'base.Blob):', 'data', '=', 'blob.data()', 'else:', 'data', '=', 'blob', 'bg_func', '=', 'np.max', 'if', 'data.ndim', '==', '4:', 'if', 'data.shape[0]', '==', '1:', 'return', 'self.show_blobs(data[0],', 'bg_func=bg_func)', 'elif', 'data.shape[-1]', '==', '3...
278,440
guanyuelee/midrae
eval.py
closest_line
closest_line
Compute the distance to, and parameters for, the closest line to each line in query_lines.
[ "Compute", "the", "distance", "to,", "and", "parameters", "for,", "the", "closest", "line", "to", "each", "line", "in", "query_lines." ]
def closest_line(query_lines, metric='cosine'): (h, w) = query_lines.shape[1:-1] angles = np.linspace(0, 2 * np.pi - 2 * np.pi / 10000, 10000) all_lines = np.array([data.draw_line(angle, h, w) for angle in angles]) flat_query = query_lines.reshape(query_lines.shape[0], -1) flat_all = all_lines.resha...
['def', 'closest_line(query_lines,', "metric='cosine'):", '(h,', 'w)', '=', 'query_lines.shape[1:-1]', 'angles', '=', 'np.linspace(0,', '2', '*', 'np.pi', '-', '2', '*', 'np.pi', '/', '10000,', '10000)', 'all_lines', '=', 'np.array([data.draw_line(angle,', 'h,', 'w)', 'for', 'angle', 'in', 'angles])', 'flat_query', '='...
670,311
dvlab-research/FocalsConv
oss.py
OSSPath.joinpath
joinpath
Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored).
[ "Combine", "this", "path", "with", "one", "or", "several", "arguments,", "and", "return", "a", "new", "path", "representing", "either", "a", "subpath", "(if", "all", "arguments", "are", "relative", "paths)", "or", "a", "totally", "different", "path", "(if", ...
def joinpath(self, *args): return self._make_child(args)
['def', 'joinpath(self,', '*args):', 'return', 'self._make_child(args)']
608,107
OpenMDAO/OpenMDAO-Framework
systems.py
AssemblySystem.is_differentiable
is_differentiable
Return True if analytical derivatives can be computed for this System.
[ "Return", "True", "if", "analytical", "derivatives", "can", "be", "computed", "for", "this", "System." ]
def is_differentiable(self): driver = self._comp.driver return ISolver.providedBy(self._comp.driver) or driver.__class__.__name__ == 'Driver'
['def', 'is_differentiable(self):', 'driver', '=', 'self._comp.driver', 'return', 'ISolver.providedBy(self._comp.driver)', 'or', 'driver.__class__.__name__', '==', "'Driver'"]
276,107
zihuitang/medical_AI_platform
sched.py
scheduler.empty
empty
Check whether the queue is empty.
[ "Check", "whether", "the", "queue", "is", "empty." ]
def empty(self): with self._lock: return not self._queue
['def', 'empty(self):', 'with', 'self._lock:', 'return', 'not', 'self._queue']
281,305
TonyLianLong/VAI-ReinforcementLearning
hopper.py
Physics.height
height
Returns height of torso with respect to foot.
[ "Returns", "height", "of", "torso", "with", "respect", "to", "foot." ]
def height(self): return self.named.data.xipos['torso', 'z'] - self.named.data.xipos['foot', 'z']
['def', 'height(self):', 'return', "self.named.data.xipos['torso',", "'z']", '-', "self.named.data.xipos['foot',", "'z']"]
440,871
google-research/scenic
fewshot_utils.py
FewShotEvaluator.log_fewshot_summary
log_fewshot_summary
Call `writer` with a descriptive string and the results.
[ "Call", "`writer`", "with", "a", "descriptive", "string", "and", "the", "results." ]
def log_fewshot_summary(self, writer: metric_writers.MetricWriter, step, results): (results, best_l2) = results scalars = {} for (dataset_name, result) in results.items(): for ((shots, l2), acc) in result.items(): scalars[f'zz/{dataset_name}_{shots}shot_l2={l2}'] = acc for (shots, l2...
['def', 'log_fewshot_summary(self,', 'writer:', 'metric_writers.MetricWriter,', 'step,', 'results):', '(results,', 'best_l2)', '=', 'results', 'scalars', '=', '{}', 'for', '(dataset_name,', 'result)', 'in', 'results.items():', 'for', '((shots,', 'l2),', 'acc)', 'in', 'result.items():', "scalars[f'zz/{dataset_name}_{sho...
847,680
sunishsheth2009/ChatterBot
test_stride_tricks.py
test_incompatible_shapes_raise_valueerror
test_incompatible_shapes_raise_valueerror
Check that a ValueError is raised for incompatible shapes.
[ "Check", "that", "a", "ValueError", "is", "raised", "for", "incompatible", "shapes." ]
def test_incompatible_shapes_raise_valueerror(): data = [[(3,), (4,)], [(2, 3), (2,)], [(3,), (3,), (4,)], [(1, 3, 4), (2, 3, 3)]] for input_shapes in data: assert_incompatible_shapes_raise(input_shapes) assert_incompatible_shapes_raise(input_shapes[::-1])
['def', 'test_incompatible_shapes_raise_valueerror():', 'data', '=', '[[(3,),', '(4,)],', '[(2,', '3),', '(2,)],', '[(3,),', '(3,),', '(4,)],', '[(1,', '3,', '4),', '(2,', '3,', '3)]]', 'for', 'input_shapes', 'in', 'data:', 'assert_incompatible_shapes_raise(input_shapes)', 'assert_incompatible_shapes_raise(input_shapes...
531,583
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Class.iterDecl
iterDecl
Yields the declaration for this type.
[ "Yields", "the", "declaration", "for", "this", "type." ]
def iterDecl(self): bases = ', '.join(self.iterBases()) bases = '({0})'.format(bases) if bases else '' yield 'class {0}{1}:'.format(self.name, bases)
['def', 'iterDecl(self):', 'bases', '=', "',", "'.join(self.iterBases())", 'bases', '=', "'({0})'.format(bases)", 'if', 'bases', 'else', "''", 'yield', "'class", "{0}{1}:'.format(self.name,", 'bases)']
10,769
brain-research/hyperbolictext
tools.py
load_vocabulary
load_vocabulary
Loads a vocabulary file.
[ "Loads", "a", "vocabulary", "file." ]
def load_vocabulary(filename): tf.logging.info('Reading vocabulary from %s', filename) with tf.gfile.GFile(filename, mode='r') as f: lines = list(f.readlines()) reverse_vocab = [line.decode('utf-8').strip() for line in lines] tf.logging.info('Read vocabulary of size %d', len(reverse_vocab)) ...
['def', 'load_vocabulary(filename):', "tf.logging.info('Reading", 'vocabulary', 'from', "%s',", 'filename)', 'with', 'tf.gfile.GFile(filename,', "mode='r')", 'as', 'f:', 'lines', '=', 'list(f.readlines())', 'reverse_vocab', '=', "[line.decode('utf-8').strip()", 'for', 'line', 'in', 'lines]', "tf.logging.info('Read", 'v...
228,134
santhoshkolloju/Abstractive-Summarization-With-Transfer-
metrics.py
accuracy
accuracy
Calculates the accuracy of predictions.
[ "Calculates", "the", "accuracy", "of", "predictions." ]
def accuracy(labels, preds): labels = tf.cast(labels, preds.dtype) return tf.reduce_mean(tf.to_float(tf.equal(preds, labels)))
['def', 'accuracy(labels,', 'preds):', 'labels', '=', 'tf.cast(labels,', 'preds.dtype)', 'return', 'tf.reduce_mean(tf.to_float(tf.equal(preds,', 'labels)))']
406,145
instadeepai/jumanji
types_test.py
test_timestep__restart
test_timestep__restart
Validates that restart function returns the desired TimeStep.
[ "Validates", "that", "restart", "function", "returns", "the", "desired", "TimeStep." ]
def test_timestep__restart() -> None: observation = jnp.ones(5, float) timestep = restart(observation) assert jnp.all(timestep.observation == observation) assert timestep.step_type == StepType.FIRST assert timestep.reward == 0.0 assert timestep.discount == 1.0
['def', 'test_timestep__restart()', '->', 'None:', 'observation', '=', 'jnp.ones(5,', 'float)', 'timestep', '=', 'restart(observation)', 'assert', 'jnp.all(timestep.observation', '==', 'observation)', 'assert', 'timestep.step_type', '==', 'StepType.FIRST', 'assert', 'timestep.reward', '==', '0.0', 'assert', 'timestep.d...
593,879
gablg1/ORGAN
generator.py
Generator.create_output_unit
create_output_unit
Defines the output part of the LSTM.
[ "Defines", "the", "output", "part", "of", "the", "LSTM." ]
def create_output_unit(self, params): self.Wo = tf.Variable(self.init_matrix([self.hidden_dim, self.num_emb])) self.bo = tf.Variable(self.init_matrix([self.num_emb])) params.extend([self.Wo, self.bo]) def unit(hidden_memory_tuple): (hidden_state, c_prev) = tf.unstack(hidden_memory_tuple) ...
['def', 'create_output_unit(self,', 'params):', 'self.Wo', '=', 'tf.Variable(self.init_matrix([self.hidden_dim,', 'self.num_emb]))', 'self.bo', '=', 'tf.Variable(self.init_matrix([self.num_emb]))', 'params.extend([self.Wo,', 'self.bo])', 'def', 'unit(hidden_memory_tuple):', '(hidden_state,', 'c_prev)', '=', 'tf.unstack...
776,404
eddylau328/fyp-artificial-intelligence-ac-control-device
socks.py
setdefaultproxy
setdefaultproxy
setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed.
[ "setdefaultproxy(proxytype,", "addr[,", "port[,", "rdns[,", "username[,", "password]]]])", "Sets", "a", "default", "proxy", "which", "all", "further", "socksocket", "objects", "will", "use,", "unless", "explicitly", "changed." ]
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password)
['def', 'setdefaultproxy(proxytype=None,', 'addr=None,', 'port=None,', 'rdns=True,', 'username=None,', 'password=None):', 'global', '_defaultproxy', '_defaultproxy', '=', '(proxytype,', 'addr,', 'port,', 'rdns,', 'username,', 'password)']
215,725
eddylau328/fyp-artificial-intelligence-ac-control-device
timeout.py
ExponentialTimeout.with_deadline
with_deadline
Return a copy of this teimout with the given deadline.
[ "Return", "a", "copy", "of", "this", "teimout", "with", "the", "given", "deadline." ]
def with_deadline(self, deadline): return ExponentialTimeout(initial=self._initial, maximum=self._maximum, multiplier=self._multiplier, deadline=deadline)
['def', 'with_deadline(self,', 'deadline):', 'return', 'ExponentialTimeout(initial=self._initial,', 'maximum=self._maximum,', 'multiplier=self._multiplier,', 'deadline=deadline)']
214,509
enuguru/artificial_intelligence_and_machine_learning
parser.py
PythonParser.byte_parser
byte_parser
Create a ByteParser on demand.
[ "Create", "a", "ByteParser", "on", "demand." ]
def byte_parser(self): if not self._byte_parser: self._byte_parser = ByteParser(self.text, filename=self.filename) return self._byte_parser
['def', 'byte_parser(self):', 'if', 'not', 'self._byte_parser:', 'self._byte_parser', '=', 'ByteParser(self.text,', 'filename=self.filename)', 'return', 'self._byte_parser']
157,489
aws/sagemaker-python-sdk
session.py
Session.start_monitoring_schedule
start_monitoring_schedule
Starts a monitoring schedule.
[ "Starts", "a", "monitoring", "schedule." ]
def start_monitoring_schedule(self, monitoring_schedule_name): print() print('Starting Monitoring Schedule with name: {}'.format(monitoring_schedule_name)) self.sagemaker_client.start_monitoring_schedule(MonitoringScheduleName=monitoring_schedule_name)
['def', 'start_monitoring_schedule(self,', 'monitoring_schedule_name):', 'print()', "print('Starting", 'Monitoring', 'Schedule', 'with', 'name:', "{}'.format(monitoring_schedule_name))", 'self.sagemaker_client.start_monitoring_schedule(MonitoringScheduleName=monitoring_schedule_name)']
829,597
cjrd/self-supervised-pretraining
env.py
setup_custom_environment
setup_custom_environment
Load custom environment setup by importing a Python source file or a module, and run the setup function.
[ "Load", "custom", "environment", "setup", "by", "importing", "a", "Python", "source", "file", "or", "a", "module,", "and", "run", "the", "setup", "function." ]
def setup_custom_environment(custom_module): if custom_module.endswith('.py'): module = _import_file('detectron2.utils.env.custom_module', custom_module) else: module = importlib.import_module(custom_module) assert hasattr(module, 'setup_environment') and callable(module.setup_environment), ...
['def', 'setup_custom_environment(custom_module):', 'if', "custom_module.endswith('.py'):", 'module', '=', "_import_file('detectron2.utils.env.custom_module',", 'custom_module)', 'else:', 'module', '=', 'importlib.import_module(custom_module)', 'assert', 'hasattr(module,', "'setup_environment')", 'and', 'callable(modul...
843,646
PacktPublishing/Hands-On-Artificial--for-Banking
test_peak_finding.py
TestLocalMaxima1d.test_flat_maxima
test_flat_maxima
Test if flat maxima are detected correctly.
[ "Test", "if", "flat", "maxima", "are", "detected", "correctly." ]
def test_flat_maxima(self): x = np.array([-1.3, 0, 1, 0, 2, 2, 0, 3, 3, 3, 2.99, 4, 4, 4, 4, -10, -5, -5, -5, -5, -5, -10]) (midpoints, left_edges, right_edges) = _local_maxima_1d(x) assert_equal(midpoints, np.array([2, 4, 8, 12, 18])) assert_equal(left_edges, np.array([2, 4, 7, 11, 16])) assert_equ...
['def', 'test_flat_maxima(self):', 'x', '=', 'np.array([-1.3,', '0,', '1,', '0,', '2,', '2,', '0,', '3,', '3,', '3,', '2.99,', '4,', '4,', '4,', '4,', '-10,', '-5,', '-5,', '-5,', '-5,', '-5,', '-10])', '(midpoints,', 'left_edges,', 'right_edges)', '=', '_local_maxima_1d(x)', 'assert_equal(midpoints,', 'np.array([2,', ...
203,320
zihuitang/medical_AI_platform
posixpath.py
commonpath
commonpath
Given a sequence of path names, returns the longest common sub-path.
[ "Given", "a", "sequence", "of", "path", "names,", "returns", "the", "longest", "common", "sub-path." ]
def commonpath(paths): if not paths: raise ValueError('commonpath() arg is an empty sequence') paths = tuple(map(os.fspath, paths)) if isinstance(paths[0], bytes): sep = b'/' curdir = b'.' else: sep = '/' curdir = '.' try: split_paths = [path.split(sep...
['def', 'commonpath(paths):', 'if', 'not', 'paths:', 'raise', "ValueError('commonpath()", 'arg', 'is', 'an', 'empty', "sequence')", 'paths', '=', 'tuple(map(os.fspath,', 'paths))', 'if', 'isinstance(paths[0],', 'bytes):', 'sep', '=', "b'/'", 'curdir', '=', "b'.'", 'else:', 'sep', '=', "'/'", 'curdir', '=', "'.'", 'try:...
281,157
openkinome/kinoml
test_oemodeling.py
test_update_residue_identifiers
test_update_residue_identifiers
Compare results to contain expected chains, to start with atom serial 1 and for correct residue ID handling.
[ "Compare", "results", "to", "contain", "expected", "chains,", "to", "start", "with", "atom", "serial", "1", "and", "for", "correct", "residue", "ID", "handling." ]
def test_update_residue_identifiers(package, resource, keep_protein_residue_ids, keep_chain_id, chain_ids, first_residue_id, last_residue_id): from openeye import oechem with resources.path(package, resource) as path: structure = read_molecules(str(path))[0] structure = update_residue_identifier...
['def', 'test_update_residue_identifiers(package,', 'resource,', 'keep_protein_residue_ids,', 'keep_chain_id,', 'chain_ids,', 'first_residue_id,', 'last_residue_id):', 'from', 'openeye', 'import', 'oechem', 'with', 'resources.path(package,', 'resource)', 'as', 'path:', 'structure', '=', 'read_molecules(str(path))[0]', ...
596,310
enuguru/artificial_intelligence_and_machine_
data.py
CoverageData.measured_files
measured_files
A list of all files that had been measured.
[ "A", "list", "of", "all", "files", "that", "had", "been", "measured." ]
def measured_files(self): return list(self._arcs or self._lines or {})
['def', 'measured_files(self):', 'return', 'list(self._arcs', 'or', 'self._lines', 'or', '{})']
147,666
mrahtz/learning-from-human-preferences
reward_predictor_test.py
TestRewardPredictor.test_loss
test_loss
Check that the loss is calculated correctly.
[ "Check", "that", "the", "loss", "is", "calculated", "correctly." ]
def test_loss(self): rs1 = rs2 = 100 n_frames = 20 while rs1 > 50 or rs2 > 50: s1 = 255 * np.random.normal(loc=1.0, size=(n_frames, 84, 84, 4)) s2 = 255 * np.random.normal(loc=-1.0, size=(n_frames, 84, 84, 4)) feed_dict = {self.rpn.s1: [s1], self.rpn.s2: [s2], self.rpn.training: True...
['def', 'test_loss(self):', 'rs1', '=', 'rs2', '=', '100', 'n_frames', '=', '20', 'while', 'rs1', '>', '50', 'or', 'rs2', '>', '50:', 's1', '=', '255', '*', 'np.random.normal(loc=1.0,', 'size=(n_frames,', '84,', '84,', '4))', 's2', '=', '255', '*', 'np.random.normal(loc=-1.0,', 'size=(n_frames,', '84,', '84,', '4))', '...
262,176
ludwig-ai/ludwig
base.py
DataFrameEngine.split
split
Splits the input DataFrame into sections with the given proportions.
[ "Splits", "the", "input", "DataFrame", "into", "sections", "with", "the", "given", "proportions." ]
def split(self, df, probabilities): raise NotImplementedError()
['def', 'split(self,', 'df,', 'probabilities):', 'raise', 'NotImplementedError()']
616,644
sktime/sktime
base.py
BaseResults.load_fitted_strategy
load_fitted_strategy
Load fitted strategies for all datasets and strategies iteratively.
[ "Load", "fitted", "strategies", "for", "all", "datasets", "and", "strategies", "iteratively." ]
def load_fitted_strategy(self, strategy_name, dataset_name, cv_fold): raise NotImplementedError()
['def', 'load_fitted_strategy(self,', 'strategy_name,', 'dataset_name,', 'cv_fold):', 'raise', 'NotImplementedError()']
885,813
PaccMann/fdsa
rnn.py
RNNSetMatching.forward
forward
Passes input through specified network.
[ "Passes", "input", "through", "specified", "network." ]
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.rnn(x) x = self.fc(x) return x
['def', 'forward(self,', 'x:', 'torch.Tensor)', '->', 'torch.Tensor:', 'x', '=', 'self.rnn(x)', 'x', '=', 'self.fc(x)', 'return', 'x']
560,867
PacktPublishing/Hands-on-Supervised---with-Python
base.py
RecommenderMixin.recommend_for_all_users
recommend_for_all_users
Create recommendations for all users.
[ "Create", "recommendations", "for", "all", "users." ]
def recommend_for_all_users(self, R, n=10, filter_previously_seen=False, return_scores=True, **kwargs): return (self.recommend_for_user(R, user, n=n, filter_previously_seen=filter_previously_seen, return_scores=return_scores, **kwargs) for user in xrange(R.shape[0]))
['def', 'recommend_for_all_users(self,', 'R,', 'n=10,', 'filter_previously_seen=False,', 'return_scores=True,', '**kwargs):', 'return', '(self.recommend_for_user(R,', 'user,', 'n=n,', 'filter_previously_seen=filter_previously_seen,', 'return_scores=return_scores,', '**kwargs)', 'for', 'user', 'in', 'xrange(R.shape[0]))...
205,355
apeterswu/RL4NMT
decoding.py
decode_from_file
decode_from_file
Compute predictions on entries in filename and write them out.
[ "Compute", "predictions", "on", "entries", "in", "filename", "and", "write", "them", "out." ]
def decode_from_file(estimator, filename, decode_hp, decode_to_file=None): if not decode_hp.batch_size: decode_hp.batch_size = 32 tf.logging.info('decode_hp.batch_size not specified; default=%d' % decode_hp.batch_size) hparams = estimator.params problem_id = decode_hp.problem_idx has_inp...
['def', 'decode_from_file(estimator,', 'filename,', 'decode_hp,', 'decode_to_file=None):', 'if', 'not', 'decode_hp.batch_size:', 'decode_hp.batch_size', '=', '32', "tf.logging.info('decode_hp.batch_size", 'not', 'specified;', "default=%d'", '%', 'decode_hp.batch_size)', 'hparams', '=', 'estimator.params', 'problem_id',...
331,238
Jiankun-chen/building-semantic-segmentation-of-InSAR-images
train.py
preprocess_image
preprocess_image
Preprocess a single image of layout [ height, width, depth].
[ "Preprocess", "a", "single", "image", "of", "layout", "[", "height,", "width,", "depth]." ]
def preprocess_image(image, label, is_training): if is_training: (image, label) = preprocessing.random_rescale_image_and_label(image, label, _MIN_SCALE, _MAX_SCALE) (image, label) = preprocessing.random_crop_or_pad_image_and_label(image, label, _HEIGHT, _WIDTH, _IGNORE_LABEL) (image, label) ...
['def', 'preprocess_image(image,', 'label,', 'is_training):', 'if', 'is_training:', '(image,', 'label)', '=', 'preprocessing.random_rescale_image_and_label(image,', 'label,', '_MIN_SCALE,', '_MAX_SCALE)', '(image,', 'label)', '=', 'preprocessing.random_crop_or_pad_image_and_label(image,', 'label,', '_HEIGHT,', '_WIDTH,...
410,376
LLNL/Abmarl
wrapper.py
ActorWrapper.key
key
The key is the same as the wrapped actor's key.
[ "The", "key", "is", "the", "same", "as", "the", "wrapped", "actor's", "key." ]
def key(self): return self.wrapped_component.key
['def', 'key(self):', 'return', 'self.wrapped_component.key']
405,817
facebookresearch/CompilerGym
datasets_wrappers_test.py
test_iterate_over_benchmarks_fork_shared_iterator
test_iterate_over_benchmarks_fork_shared_iterator
Test fork() using a single benchmark iterator shared between forks.
[ "Test", "fork()", "using", "a", "single", "benchmark", "iterator", "shared", "between", "forks." ]
def test_iterate_over_benchmarks_fork_shared_iterator(env: LlvmEnv): env = IterateOverBenchmarks(env=env, benchmarks=['benchmark://cbench-v1/crc32', 'benchmark://cbench-v1/qsort', 'benchmark://cbench-v1/dijkstra'], fork_shares_iterator=True) env.reset() assert env.benchmark == 'benchmark://cbench-v1/crc32' ...
['def', 'test_iterate_over_benchmarks_fork_shared_iterator(env:', 'LlvmEnv):', 'env', '=', 'IterateOverBenchmarks(env=env,', "benchmarks=['benchmark://cbench-v1/crc32',", "'benchmark://cbench-v1/qsort',", "'benchmark://cbench-v1/dijkstra'],", 'fork_shares_iterator=True)', 'env.reset()', 'assert', 'env.benchmark', '==',...
135,947
ananthpn/nlp
match_lstm.py
MatchLstm.recurrent_group
recurrent_group
Implements the Match-LSTM layer in the paper.
[ "Implements", "the", "Match-LSTM", "layer", "in", "the", "paper." ]
def recurrent_group(self, name, inputs, reverse=False): inputs.insert(0, name) seq_out = layer.recurrent_group(name=name, input=inputs, step=self._step, reverse=reverse) return seq_out
['def', 'recurrent_group(self,', 'name,', 'inputs,', 'reverse=False):', 'inputs.insert(0,', 'name)', 'seq_out', '=', 'layer.recurrent_group(name=name,', 'input=inputs,', 'step=self._step,', 'reverse=reverse)', 'return', 'seq_out']
808,450
salesforce/CodeRL
testing_utils.py
require_torch_up_to_2_gpus
require_torch_up_to_2_gpus
Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
[ "Decorator", "marking", "a", "test", "that", "requires", "0", "or", "1", "or", "2", "GPU", "setup", "(in", "PyTorch)." ]
def require_torch_up_to_2_gpus(test_case): if not is_torch_available(): return unittest.skip('test requires PyTorch')(test_case) import torch if torch.cuda.device_count() > 2: return unittest.skip('test requires 0 or 1 or 2 GPUs')(test_case) else: return test_case
['def', 'require_torch_up_to_2_gpus(test_case):', 'if', 'not', 'is_torch_available():', 'return', "unittest.skip('test", 'requires', "PyTorch')(test_case)", 'import', 'torch', 'if', 'torch.cuda.device_count()', '>', '2:', 'return', "unittest.skip('test", 'requires', '0', 'or', '1', 'or', '2', "GPUs')(test_case)", 'else...
494,107
adler-j/learned_gradient_tomography
partially_learned_gradient_descent.py
generate_data
generate_data
Generate a set of random data.
[ "Generate", "a", "set", "of", "random", "data." ]
def generate_data(validation=False): n_iter = 1 if validation else n_data x_arr = np.empty((n_iter, space.shape[0], space.shape[1], 1), dtype='float32') y_arr = np.empty((n_iter, operator.range.shape[0], operator.range.shape[1], 1), dtype='float32') x_true_arr = np.empty((n_iter, space.shape[0], space.s...
['def', 'generate_data(validation=False):', 'n_iter', '=', '1', 'if', 'validation', 'else', 'n_data', 'x_arr', '=', 'np.empty((n_iter,', 'space.shape[0],', 'space.shape[1],', '1),', "dtype='float32')", 'y_arr', '=', 'np.empty((n_iter,', 'operator.range.shape[0],', 'operator.range.shape[1],', '1),', "dtype='float32')", ...
587,890
rdipietro/mist-rnns
timitphonemerec.py
load
load
Load all standardized TIMIT data with folded phoneme labels.
[ "Load", "all", "standardized", "TIMIT", "data", "with", "folded", "phoneme", "labels." ]
def load(data_dir=DEFAULT_DATA_DIR, mfcc=True): types = ['mfcc', 'mfcc_labels'] if mfcc else ['audio', 'labels'] ret = [] for name in ['train', 'val', 'test']: for type in types: path = os.path.join(data_dir, name + '_' + type + '.npy') if not os.path.exists(path): ...
['def', 'load(data_dir=DEFAULT_DATA_DIR,', 'mfcc=True):', 'types', '=', "['mfcc',", "'mfcc_labels']", 'if', 'mfcc', 'else', "['audio',", "'labels']", 'ret', '=', '[]', 'for', 'name', 'in', "['train',", "'val',", "'test']:", 'for', 'type', 'in', 'types:', 'path', '=', 'os.path.join(data_dir,', 'name', '+', "'_'", '+', '...
271,703
Katja-M/Python_NaturalLanguageProcessing
mathtext.py
MathtextBackend.render_glyph
render_glyph
Draw a glyph described by *info* to the reference point (*ox*, *oy*).
[ "Draw", "a", "glyph", "described", "by", "*info*", "to", "the", "reference", "point", "(*ox*,", "*oy*)." ]
def render_glyph(self, ox, oy, info): raise NotImplementedError()
['def', 'render_glyph(self,', 'ox,', 'oy,', 'info):', 'raise', 'NotImplementedError()']
864,656
boostcampaitech3/level2-semantic-segmentation-level2-cv-16
stdc_head.py
STDCHead.losses
losses
Compute Detail Aggregation Loss.
[ "Compute", "Detail", "Aggregation", "Loss." ]
def losses(self, seg_logit, seg_label): seg_label = seg_label.to(self.laplacian_kernel) boundary_targets = F.conv2d(seg_label, self.laplacian_kernel, padding=1) boundary_targets = boundary_targets.clamp(min=0) boundary_targets[boundary_targets > self.boundary_threshold] = 1 boundary_targets[boundary...
['def', 'losses(self,', 'seg_logit,', 'seg_label):', 'seg_label', '=', 'seg_label.to(self.laplacian_kernel)', 'boundary_targets', '=', 'F.conv2d(seg_label,', 'self.laplacian_kernel,', 'padding=1)', 'boundary_targets', '=', 'boundary_targets.clamp(min=0)', 'boundary_targets[boundary_targets', '>', 'self.boundary_thresho...
588,828
myothida/Supervised-Machine-Learning
test_from_model.py
test_prefit_max_features
test_prefit_max_features
Check the interaction between `prefit` and `max_features`.
[ "Check", "the", "interaction", "between", "`prefit`", "and", "`max_features`." ]
def test_prefit_max_features(): estimator = RandomForestClassifier(n_estimators=5, random_state=0) estimator.fit(data, y) model = SelectFromModel(estimator, prefit=True, max_features=lambda X: X.shape[1]) err_msg = 'When `prefit=True` and `max_features` is a callable, call `fit` before calling `transfor...
['def', 'test_prefit_max_features():', 'estimator', '=', 'RandomForestClassifier(n_estimators=5,', 'random_state=0)', 'estimator.fit(data,', 'y)', 'model', '=', 'SelectFromModel(estimator,', 'prefit=True,', 'max_features=lambda', 'X:', 'X.shape[1])', 'err_msg', '=', "'When", '`prefit=True`', 'and', '`max_features`', 'i...
363,932
Rock-100/MonoDet
test_coco.py
make_mask
make_mask
Makes a donut shaped binary mask.
[ "Makes", "a", "donut", "shaped", "binary", "mask." ]
def make_mask(): H = 100 W = 100 mask = np.zeros([H, W], dtype=np.uint8) for x in range(W): for y in range(H): d = np.linalg.norm(np.array([W, H]) / 2 - np.array([x, y])) if d > 10 and d < 20: mask[y, x] = 1 return mask
['def', 'make_mask():', 'H', '=', '100', 'W', '=', '100', 'mask', '=', 'np.zeros([H,', 'W],', 'dtype=np.uint8)', 'for', 'x', 'in', 'range(W):', 'for', 'y', 'in', 'range(H):', 'd', '=', 'np.linalg.norm(np.array([W,', 'H])', '/', '2', '-', 'np.array([x,', 'y]))', 'if', 'd', '>', '10', 'and', 'd', '<', '20:', 'mask[y,', '...
655,067
NVIDIA/object-detection-tensorrt-example
model.py
maybe_mkdir
maybe_mkdir
Makes directory if it doesn't exist.
[ "Makes", "directory", "if", "it", "doesn't", "exist." ]
def maybe_mkdir(dir_path): if not os.path.exists(dir_path): os.makedirs(dir_path)
['def', 'maybe_mkdir(dir_path):', 'if', 'not', 'os.path.exists(dir_path):', 'os.makedirs(dir_path)']
748,431
jeffnyman/pacumen
grid.py
Grid.as_list
as_list
Returns a list of grid positions from the current grid, based on the key value.
[ "Returns", "a", "list", "of", "grid", "positions", "from", "the", "current", "grid,", "based", "on", "the", "key", "value." ]
def as_list(self, key=True): grid_list = [] for x in range(self.width): for y in range(self.height): if self[x][y] == key: grid_list.append((x, y)) return grid_list
['def', 'as_list(self,', 'key=True):', 'grid_list', '=', '[]', 'for', 'x', 'in', 'range(self.width):', 'for', 'y', 'in', 'range(self.height):', 'if', 'self[x][y]', '==', 'key:', 'grid_list.append((x,', 'y))', 'return', 'grid_list']
255,939
Ruturaj123/Flowchart-Detection
eval_on_adversarial.py
get_input_images
get_input_images
Gets input images for the evaluation.
[ "Gets", "input", "images", "for", "the", "evaluation." ]
def get_input_images(dataset_images): eps = FLAGS.adversarial_eps / 255 * 2.0 if FLAGS.adversarial_method == 'stepll': return stepll_adversarial_images(dataset_images, eps) elif FLAGS.adversarial_method == 'stepllnoise': return stepllnoise_adversarial_images(dataset_images, eps) elif FLA...
['def', 'get_input_images(dataset_images):', 'eps', '=', 'FLAGS.adversarial_eps', '/', '255', '*', '2.0', 'if', 'FLAGS.adversarial_method', '==', "'stepll':", 'return', 'stepll_adversarial_images(dataset_images,', 'eps)', 'elif', 'FLAGS.adversarial_method', '==', "'stepllnoise':", 'return', 'stepllnoise_adversarial_ima...
585,406
angeladai/ScanComplete
model.py
get_previous_voxel_group_features
get_previous_voxel_group_features
Extracts prev voxel group features for current voxel group.
[ "Extracts", "prev", "voxel", "group", "features", "for", "current", "voxel", "group." ]
def get_previous_voxel_group_features(context_groups, current_voxel_group): current_context = context_groups[:, :current_voxel_group, :, :, :, :] current_context = tf.transpose(current_context, [0, 2, 3, 4, 1, 5]) current_context = tf.reshape(current_context, current_context.get_shape().as_list()[:-2] + [-1...
['def', 'get_previous_voxel_group_features(context_groups,', 'current_voxel_group):', 'current_context', '=', 'context_groups[:,', ':current_voxel_group,', ':,', ':,', ':,', ':]', 'current_context', '=', 'tf.transpose(current_context,', '[0,', '2,', '3,', '4,', '1,', '5])', 'current_context', '=', 'tf.reshape(current_c...
845,855
AxeldeRomblay/MLBox
test_reader.py
test_init_reader
test_init_reader
Test init method of Reader class.
[ "Test", "init", "method", "of", "Reader", "class." ]
def test_init_reader(): reader = Reader() assert not reader.sep assert reader.header == 0 assert not reader.to_hdf5 assert reader.to_path == 'save' assert reader.verbose
['def', 'test_init_reader():', 'reader', '=', 'Reader()', 'assert', 'not', 'reader.sep', 'assert', 'reader.header', '==', '0', 'assert', 'not', 'reader.to_hdf5', 'assert', 'reader.to_path', '==', "'save'", 'assert', 'reader.verbose']
630,052
nicknochnack/RealTimeSignLanguageTFJS
run_squad_helper.py
predict_squad_customized
predict_squad_customized
Make predictions using a Bert-based squad model.
[ "Make", "predictions", "using", "a", "Bert-based", "squad", "model." ]
def predict_squad_customized(strategy, input_meta_data, predict_tfrecord_path, num_steps, squad_model): predict_dataset_fn = get_dataset_fn(predict_tfrecord_path, input_meta_data['max_seq_length'], FLAGS.predict_batch_size, is_training=False) predict_iterator = iter(strategy.distribute_datasets_from_function(pr...
['def', 'predict_squad_customized(strategy,', 'input_meta_data,', 'predict_tfrecord_path,', 'num_steps,', 'squad_model):', 'predict_dataset_fn', '=', 'get_dataset_fn(predict_tfrecord_path,', "input_meta_data['max_seq_length'],", 'FLAGS.predict_batch_size,', 'is_training=False)', 'predict_iterator', '=', 'iter(strategy....
850,310
deepmind/dm_control
suite_test.py
SuiteTest.test_task_conforms_to_spec
test_task_conforms_to_spec
Tests that the environment timesteps conform to specifications.
[ "Tests", "that", "the", "environment", "timesteps", "conform", "to", "specifications." ]
def test_task_conforms_to_spec(self, domain, task): is_benchmark = (domain, task) in suite.BENCHMARKING env = suite.load(domain, task) observation_spec = env.observation_spec() action_spec = env.action_spec() if is_benchmark: self._validate_control_range(action_spec.minimum, action_spec.maxi...
['def', 'test_task_conforms_to_spec(self,', 'domain,', 'task):', 'is_benchmark', '=', '(domain,', 'task)', 'in', 'suite.BENCHMARKING', 'env', '=', 'suite.load(domain,', 'task)', 'observation_spec', '=', 'env.observation_spec()', 'action_spec', '=', 'env.action_spec()', 'if', 'is_benchmark:', 'self._validate_control_ran...
165,579
weimin17/Object-Detection_HelmetDetection
config_util.py
log_and_save_config
log_and_save_config
Logs and writes a JSON-serializable configuration object.
[ "Logs", "and", "writes", "a", "JSON-serializable", "configuration", "object." ]
def log_and_save_config(config, output_dir): if hasattr(config, 'to_json') and callable(config.to_json): config_json = config.to_json(indent=2) else: config_json = json.dumps(config, indent=2) tf.logging.info('config: %s', config_json) tf.gfile.MakeDirs(output_dir) with tf.gfile.Open...
['def', 'log_and_save_config(config,', 'output_dir):', 'if', 'hasattr(config,', "'to_json')", 'and', 'callable(config.to_json):', 'config_json', '=', 'config.to_json(indent=2)', 'else:', 'config_json', '=', 'json.dumps(config,', 'indent=2)', "tf.logging.info('config:", "%s',", 'config_json)', 'tf.gfile.MakeDirs(output_...
761,627
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
modalities.py
AudioSpectralModality.bottom
bottom
Transform input from data space to model space.
[ "Transform", "input", "from", "data", "space", "to", "model", "space." ]
def bottom(self, x): inputs = x with tf.variable_scope(self.name): def xnet_resblock(x, filters, res_relu, name): with tf.variable_scope(name): y = common_layers.separable_conv_block(x, filters, [((1, 1), (3, 3)), ((1, 1), (3, 3))], first_relu=True, padding='SAME', force2d=T...
['def', 'bottom(self,', 'x):', 'inputs', '=', 'x', 'with', 'tf.variable_scope(self.name):', 'def', 'xnet_resblock(x,', 'filters,', 'res_relu,', 'name):', 'with', 'tf.variable_scope(name):', 'y', '=', 'common_layers.separable_conv_block(x,', 'filters,', '[((1,', '1),', '(3,', '3)),', '((1,', '1),', '(3,', '3))],', 'firs...
965,427
yinyunie/ScenePriors
experiment.py
run_training
run_training
Entry point to run the training and validation loops based on the specified config file.
[ "Entry", "point", "to", "run", "the", "training", "and", "validation", "loops", "based", "on", "the", "specified", "config", "file." ]
def run_training(cfg: DictConfig) -> None: accelerator = Accelerator(device_placement=False) logger.info(accelerator.state) device = accelerator.device logger.info(f'Running experiment on device: {device}') if accelerator.is_local_main_process: logger.info(OmegaConf.to_yaml(cfg)) if cfg....
['def', 'run_training(cfg:', 'DictConfig)', '->', 'None:', 'accelerator', '=', 'Accelerator(device_placement=False)', 'logger.info(accelerator.state)', 'device', '=', 'accelerator.device', "logger.info(f'Running", 'experiment', 'on', 'device:', "{device}')", 'if', 'accelerator.is_local_main_process:', 'logger.info(Omeg...
329,580
rudranil723/mini-main
list.py
MultipleObjectMixin.get_paginator
get_paginator
Return an instance of the paginator for this view.
[ "Return", "an", "instance", "of", "the", "paginator", "for", "this", "view." ]
def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs): return self.paginator_class(queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first_page, **kwargs)
['def', 'get_paginator(self,', 'queryset,', 'per_page,', 'orphans=0,', 'allow_empty_first_page=True,', '**kwargs):', 'return', 'self.paginator_class(queryset,', 'per_page,', 'orphans=orphans,', 'allow_empty_first_page=allow_empty_first_page,', '**kwargs)']
316,931
jonathanking/sidechainnet
models.py
BaseProteinAngleRNN.init_hidden
init_hidden
Initialize the hidden state vectors at the start of a batch iteration.
[ "Initialize", "the", "hidden", "state", "vectors", "at", "the", "start", "of", "a", "batch", "iteration." ]
def init_hidden(self, batch_size): (h, c) = (torch.zeros(self.n_layers * self.n_direction, batch_size, self.size).to(self.device_), torch.zeros(self.n_layers * self.n_direction, batch_size, self.size).to(self.device_)) return (h, c)
['def', 'init_hidden(self,', 'batch_size):', '(h,', 'c)', '=', '(torch.zeros(self.n_layers', '*', 'self.n_direction,', 'batch_size,', 'self.size).to(self.device_),', 'torch.zeros(self.n_layers', '*', 'self.n_direction,', 'batch_size,', 'self.size).to(self.device_))', 'return', '(h,', 'c)']
934,012
aws-deepracer/aws-deepracer-follow-the-leader-sample-project
login.py
reset_default
reset_default
Helper method to reset the password to the default password found on vehicle.
[ "Helper", "method", "to", "reset", "the", "password", "to", "the", "default", "password", "found", "on", "vehicle." ]
def reset_default(): webserver_node = webserver_publisher_node.get_webserver_node() if os.path.exists(DEFAULT_PASSWORD_PATH): webserver_node.get_logger().info('Default password file found') with open(DEFAULT_PASSWORD_PATH, 'r') as pwd_file: default_pass = pwd_file.readline().strip() ...
['def', 'reset_default():', 'webserver_node', '=', 'webserver_publisher_node.get_webserver_node()', 'if', 'os.path.exists(DEFAULT_PASSWORD_PATH):', "webserver_node.get_logger().info('Default", 'password', 'file', "found')", 'with', 'open(DEFAULT_PASSWORD_PATH,', "'r')", 'as', 'pwd_file:', 'default_pass', '=', 'pwd_file...
421,198
TrellixVulnTeam/Unsupervised_Learning_HFI7
objective.py
objective
objective
Generate a subclass of baselexer that accepts the Objective-C syntax extensions.
[ "Generate", "a", "subclass", "of", "baselexer", "that", "accepts", "the", "Objective-C", "syntax", "extensions." ]
def objective(baselexer): _oc_keywords = re.compile('@(?:end|implementation|protocol)') _oc_message = re.compile('\\[\\s*[a-zA-Z_]\\w*\\s+(?:[a-zA-Z_]\\w*\\s*\\]|(?:[a-zA-Z_]\\w*)?:)') class GeneratedObjectiveCVariant(baselexer): tokens = {'statements': [('@"', String, 'string'), ('@(YES|NO)', Numb...
['def', 'objective(baselexer):', '_oc_keywords', '=', "re.compile('@(?:end|implementation|protocol)')", '_oc_message', '=', "re.compile('\\\\[\\\\s*[a-zA-Z_]\\\\w*\\\\s+(?:[a-zA-Z_]\\\\w*\\\\s*\\\\]|(?:[a-zA-Z_]\\\\w*)?:)')", 'class', 'GeneratedObjectiveCVariant(baselexer):', 'tokens', '=', "{'statements':", '[(\'@"\',...
435,619
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
build_mscoco_data.py
Vocabulary.word_to_id
word_to_id
Returns the integer id of a word string.
[ "Returns", "the", "integer", "id", "of", "a", "word", "string." ]
def word_to_id(self, word): if word in self._vocab: return self._vocab[word] else: return self._unk_id
['def', 'word_to_id(self,', 'word):', 'if', 'word', 'in', 'self._vocab:', 'return', 'self._vocab[word]', 'else:', 'return', 'self._unk_id']
48,754
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
tempfile.py
gettempprefixb
gettempprefixb
The default prefix for temporary directories as bytes.
[ "The", "default", "prefix", "for", "temporary", "directories", "as", "bytes." ]
def gettempprefixb(): return _os.fsencode(gettempprefix())
['def', 'gettempprefixb():', 'return', '_os.fsencode(gettempprefix())']
429,676
rifqind/Agent-Programs-3KS1
agents.py
Environment.delete_thing
delete_thing
Remove a thing from the environment.
[ "Remove", "a", "thing", "from", "the", "environment." ]
def delete_thing(self, thing): try: self.things.remove(thing) except ValueError as e: print(e) print(' in Environment delete_thing') print(' Thing to be removed: {} at {}'.format(thing, thing.location)) print(' from list: {}'.format([(thing, thing.location) for thing i...
['def', 'delete_thing(self,', 'thing):', 'try:', 'self.things.remove(thing)', 'except', 'ValueError', 'as', 'e:', 'print(e)', "print('", 'in', 'Environment', "delete_thing')", "print('", 'Thing', 'to', 'be', 'removed:', '{}', 'at', "{}'.format(thing,", 'thing.location))', "print('", 'from', 'list:', "{}'.format([(thing...
22,149
ZhAnGToNG1/transfer_learning_cspt
test_head.py
test_fcos_head_onnx_export
test_fcos_head_onnx_export
Test fcos head get_bboxes() in ort.
[ "Test", "fcos", "head", "get_bboxes()", "in", "ort." ]
def test_fcos_head_onnx_export(): fcos_model = fcos_config() s = 128 img_metas = [{'img_shape_for_onnx': torch.Tensor([s, s]), 'img_shape': (s, s, 3), 'scale_factor': np.ones(4), 'pad_shape': (s, s, 3)}] cls_scores = [torch.rand(1, fcos_model.num_classes, s // feat_size, s // feat_size) for feat_size in...
['def', 'test_fcos_head_onnx_export():', 'fcos_model', '=', 'fcos_config()', 's', '=', '128', 'img_metas', '=', "[{'img_shape_for_onnx':", 'torch.Tensor([s,', 's]),', "'img_shape':", '(s,', 's,', '3),', "'scale_factor':", 'np.ones(4),', "'pad_shape':", '(s,', 's,', '3)}]', 'cls_scores', '=', '[torch.rand(1,', 'fcos_mod...
964,366
sarnsdev/social-alignment-data-mining
test_memory.py
f
f
A module-level function for testing purposes.
[ "A", "module-level", "function", "for", "testing", "purposes." ]
def f(x, y=1): return x ** 2 + y
['def', 'f(x,', 'y=1):', 'return', 'x', '**', '2', '+', 'y']
352,552
jbwang1997/CrossKD
dump_det_results.py
DumpDetResults.process
process
transfer tensors in predictions to CPU.
[ "transfer", "tensors", "in", "predictions", "to", "CPU." ]
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: data_samples = _to_cpu(data_samples) for data_sample in data_samples: data_sample.pop('gt_instances', None) data_sample.pop('ignored_instances', None) data_sample.pop('gt_panoptic_seg', None) if 'pred_inst...
['def', 'process(self,', 'data_batch:', 'dict,', 'data_samples:', 'Sequence[dict])', '->', 'None:', 'data_samples', '=', '_to_cpu(data_samples)', 'for', 'data_sample', 'in', 'data_samples:', "data_sample.pop('gt_instances',", 'None)', "data_sample.pop('ignored_instances',", 'None)', "data_sample.pop('gt_panoptic_seg',"...
490,876
facebookresearch/mtenv
multitask.py
MultiTask.assert_env_seed_is_set
assert_env_seed_is_set
Check that the env seed is set.
[ "Check", "that", "the", "env", "seed", "is", "set." ]
def assert_env_seed_is_set(self) -> None: assert self.np_random_env is not None, 'please call `seed()` first' self.env.assert_env_seed_is_set()
['def', 'assert_env_seed_is_set(self)', '->', 'None:', 'assert', 'self.np_random_env', 'is', 'not', 'None,', "'please", 'call', '`seed()`', "first'", 'self.env.assert_env_seed_is_set()']
642,704
mrahtz/learning-from-human-preferences
reward_predictor.py
RewardPredictorEnsemble.train
train
Train all ensemble members for one epoch.
[ "Train", "all", "ensemble", "members", "for", "one", "epoch." ]
def train(self, prefs_train, prefs_val, val_interval): print('Training/testing with %d/%d preferences' % (len(prefs_train), len(prefs_val))) start_steps = self.n_steps start_time = time.time() for (_, batch) in enumerate(batch_iter(prefs_train.prefs, batch_size=32, shuffle=True)): self.train_ste...
['def', 'train(self,', 'prefs_train,', 'prefs_val,', 'val_interval):', "print('Training/testing", 'with', '%d/%d', "preferences'", '%', '(len(prefs_train),', 'len(prefs_val)))', 'start_steps', '=', 'self.n_steps', 'start_time', '=', 'time.time()', 'for', '(_,', 'batch)', 'in', 'enumerate(batch_iter(prefs_train.prefs,',...
262,172
zihuitang/medical_AI_platform
__init__.py
Misc.grab_status
grab_status
Return None, "local" or "global" if this widget has no, a local or a global grab.
[ "Return", "None,", "\"local\"", "or", "\"global\"", "if", "this", "widget", "has", "no,", "a", "local", "or", "a", "global", "grab." ]
def grab_status(self): status = self.tk.call('grab', 'status', self._w) if status == 'none': status = None return status
['def', 'grab_status(self):', 'status', '=', "self.tk.call('grab',", "'status',", 'self._w)', 'if', 'status', '==', "'none':", 'status', '=', 'None', 'return', 'status']
284,059
open-mmlab/mmdetection3d
transforms_3d.py
RandomDropPointsColor.transform
transform
Call function to drop point colors.
[ "Call", "function", "to", "drop", "point", "colors." ]
def transform(self, input_dict: dict) -> dict: points = input_dict['points'] assert points.attribute_dims is not None and 'color' in points.attribute_dims, 'Expect points have color attribute' if np.random.rand() > 1.0 - self.drop_ratio: points.color = points.color * 0.0 return input_dict
['def', 'transform(self,', 'input_dict:', 'dict)', '->', 'dict:', 'points', '=', "input_dict['points']", 'assert', 'points.attribute_dims', 'is', 'not', 'None', 'and', "'color'", 'in', 'points.attribute_dims,', "'Expect", 'points', 'have', 'color', "attribute'", 'if', 'np.random.rand()', '>', '1.0', '-', 'self.drop_rat...
631,723
thaines/helit
dpgmm.py
DPGMM.size
size
Returns the number of samples that have been added.
[ "Returns", "the", "number", "of", "samples", "that", "have", "been", "added." ]
def size(self): dm = self.getDM() if dm != None: return dm.shape[0] else: return 0
['def', 'size(self):', 'dm', '=', 'self.getDM()', 'if', 'dm', '!=', 'None:', 'return', 'dm.shape[0]', 'else:', 'return', '0']
591,567
jimtin/Stock_Comparison
restarter.py
KernelRestarter.start
start
Start the polling of the kernel.
[ "Start", "the", "polling", "of", "the", "kernel." ]
def start(self): raise NotImplementedError('Must be implemented in a subclass')
['def', 'start(self):', 'raise', "NotImplementedError('Must", 'be', 'implemented', 'in', 'a', "subclass')"]
386,068
deepmind/meltingpot
evaluation.py
evaluate_saved_models_on_scenario
evaluate_saved_models_on_scenario
Evaluates saved models on a scenario.
[ "Evaluates", "saved", "models", "on", "a", "scenario." ]
def evaluate_saved_models_on_scenario(saved_models: Mapping[str, str], names_by_role: Mapping[str, Collection[str]], scenario: str, num_episodes: int=100, video_root: Optional[str]=None) -> pd.DataFrame: with build_saved_model_population(saved_models) as population: return evaluate_population_on_scenario(po...
['def', 'evaluate_saved_models_on_scenario(saved_models:', 'Mapping[str,', 'str],', 'names_by_role:', 'Mapping[str,', 'Collection[str]],', 'scenario:', 'str,', 'num_episodes:', 'int=100,', 'video_root:', 'Optional[str]=None)', '->', 'pd.DataFrame:', 'with', 'build_saved_model_population(saved_models)', 'as', 'populatio...
285,527
OpenMDAO/OpenMDAO-Framework
early_report.py
EarlyTestInfo.options
options
Sets additional command line options.
[ "Sets", "additional", "command", "line", "options." ]
def options(self, parser, env): parser.add_option('--report', action='store', type='string', dest='report', default='test_report.out', help="name of report file. (defaults to 'test_report.out')") parser.add_option('--quicktime', action='store', type='float', dest='quicktime', default=1.0, help='cutoff time for ...
['def', 'options(self,', 'parser,', 'env):', "parser.add_option('--report',", "action='store',", "type='string',", "dest='report',", "default='test_report.out',", 'help="name', 'of', 'report', 'file.', '(defaults', 'to', '\'test_report.out\')")', "parser.add_option('--quicktime',", "action='store',", "type='float',", "...
276,227
MANGA-UOFA/NAUS
utils.py
infer_conv_output_attrs
infer_conv_output_attrs
Get output attributes of a module with input.
[ "Get", "output", "attributes", "of", "a", "module", "with", "input." ]
def infer_conv_output_attrs(module, input_channels, input_dim, batch_size=1, max_length=8): input = torch.randn(batch_size, input_channels, max_length, input_dim) output = module(input) output_channels = output.shape[1] output_dim = output.shape[-1] return (output_channels, output_dim)
['def', 'infer_conv_output_attrs(module,', 'input_channels,', 'input_dim,', 'batch_size=1,', 'max_length=8):', 'input', '=', 'torch.randn(batch_size,', 'input_channels,', 'max_length,', 'input_dim)', 'output', '=', 'module(input)', 'output_channels', '=', 'output.shape[1]', 'output_dim', '=', 'output.shape[-1]', 'retur...
291,630
Ruturaj123/Flowchart-Detection
cli_shared.py
error
error
Generate a RichTextLines output for error.
[ "Generate", "a", "RichTextLines", "output", "for", "error." ]
def error(msg): return debugger_cli_common.rich_text_lines_from_rich_line_list([RL('ERROR: ' + msg, COLOR_RED)])
['def', 'error(msg):', 'return', "debugger_cli_common.rich_text_lines_from_rich_line_list([RL('ERROR:", "'", '+', 'msg,', 'COLOR_RED)])']
605,014
tobegit3hub/deep_image_model
analyzer_cli_test.py
AnalyzerCLIControlDepTest.testListInputsRecursiveWithControls
testListInputsRecursiveWithControls
List inputs recursively, with control inputs.
[ "List", "inputs", "recursively,", "with", "control", "inputs." ]
def testListInputsRecursiveWithControls(self): out = self._registry.dispatch_command('li', ['-c', '-r', '-t', 'control_deps/ctrl_dep_z']) self.assertEqual(['Inputs to node "control_deps/ctrl_dep_z" (Depth limit = 20, control inputs included):', '|- (1) [Mul] control_deps/z', '| |- (2) [Identity] control_deps/x...
['def', 'testListInputsRecursiveWithControls(self):', 'out', '=', "self._registry.dispatch_command('li',", "['-c',", "'-r',", "'-t',", "'control_deps/ctrl_dep_z'])", "self.assertEqual(['Inputs", 'to', 'node', '"control_deps/ctrl_dep_z"', '(Depth', 'limit', '=', '20,', 'control', 'inputs', "included):',", "'|-", '(1)', ...
182,375
rlgraph/rlgraph
test_python_memory_performance.py
TestPythonMemoryPerformance.test_rlgraph_apex_insert
test_rlgraph_apex_insert
Tests RLgraph's python memory performance.
[ "Tests", "RLgraph's", "python", "memory", "performance." ]
def test_rlgraph_apex_insert(self): memory = ApexMemory(capacity=self.capacity, alpha=1.0) records = [self.record_space.sample(size=1) for _ in range(self.inserts)] start = time.monotonic() for record in records: memory.insert_records((record['states'], record['actions'], record['reward'], recor...
['def', 'test_rlgraph_apex_insert(self):', 'memory', '=', 'ApexMemory(capacity=self.capacity,', 'alpha=1.0)', 'records', '=', '[self.record_space.sample(size=1)', 'for', '_', 'in', 'range(self.inserts)]', 'start', '=', 'time.monotonic()', 'for', 'record', 'in', 'records:', "memory.insert_records((record['states'],", "r...
862,812
RasaHQ/rasa
caching.py
TrainingCache.get_cached_output_fingerprint
get_cached_output_fingerprint
Retrieves fingerprint of output based on fingerprint key.
[ "Retrieves", "fingerprint", "of", "output", "based", "on", "fingerprint", "key." ]
def get_cached_output_fingerprint(self, fingerprint_key: Text) -> Optional[Text]: ...
['def', 'get_cached_output_fingerprint(self,', 'fingerprint_key:', 'Text)', '->', 'Optional[Text]:', '...']
836,992
nicknochnack/RealTimeSignLanguageTFJS
build_data.py
ImageReader.read_image_dims
read_image_dims
Reads the image dimensions.
[ "Reads", "the", "image", "dimensions." ]
def read_image_dims(self, image_data): image = self.decode_image(image_data) return image.shape[:2]
['def', 'read_image_dims(self,', 'image_data):', 'image', '=', 'self.decode_image(image_data)', 'return', 'image.shape[:2]']
851,570
google-research/scenic
bair_dataset.py
preprocess_eval_example
preprocess_eval_example
Preprocesses the given video for evaluation.
[ "Preprocesses", "the", "given", "video", "for", "evaluation." ]
def preprocess_eval_example(example, camera_name='image_main', dtype=tf.float32, num_frames=30, stride=1, num_clips=1, zero_centering=True): frames = example[camera_name] frames = processors.normalize_image(frames, zero_centering, dtype) clips = processors.sample_linspace_sequence(frames, num_clips, num_fra...
['def', 'preprocess_eval_example(example,', "camera_name='image_main',", 'dtype=tf.float32,', 'num_frames=30,', 'stride=1,', 'num_clips=1,', 'zero_centering=True):', 'frames', '=', 'example[camera_name]', 'frames', '=', 'processors.normalize_image(frames,', 'zero_centering,', 'dtype)', 'clips', '=', 'processors.sample_...
846,009
anonymous-iclr-2019/acai-iclr-2019
layers.py
upscale2d
upscale2d
Box upscaling (also called nearest neighbors).
[ "Box", "upscaling", "(also", "called", "nearest", "neighbors)." ]
def upscale2d(x, n): if n == 1: return x return tf.batch_to_space(tf.tile(x, [n ** 2, 1, 1, 1]), [[0, 0], [0, 0]], n)
['def', 'upscale2d(x,', 'n):', 'if', 'n', '==', '1:', 'return', 'x', 'return', 'tf.batch_to_space(tf.tile(x,', '[n', '**', '2,', '1,', '1,', '1]),', '[[0,', '0],', '[0,', '0]],', 'n)']
406,641
MycroftAI/mycroft-core
test_event_scheduler.py
TestEventScheduler.test_create
test_create
Test creating and shutting down event_scheduler.
[ "Test", "creating", "and", "shutting", "down", "event_scheduler." ]
def test_create(self, mock_open, mock_json_dump, mock_load, mock_thread): mock_load.return_value = '' mock_open.return_value = MagicMock() emitter = MagicMock() es = EventScheduler(emitter) es.shutdown() self.assertEqual(mock_json_dump.call_args[0][0], {})
['def', 'test_create(self,', 'mock_open,', 'mock_json_dump,', 'mock_load,', 'mock_thread):', 'mock_load.return_value', '=', "''", 'mock_open.return_value', '=', 'MagicMock()', 'emitter', '=', 'MagicMock()', 'es', '=', 'EventScheduler(emitter)', 'es.shutdown()', 'self.assertEqual(mock_json_dump.call_args[0][0],', '{})']
290,917
rlworkgroup/garage
benchmarks.py
register_benchmark
register_benchmark
Add a new benchmark.
[ "Add", "a", "new", "benchmark." ]
def register_benchmark(benchmark): for b in _BENCHMARKS: if b['name'] == benchmark['name']: raise ValueError('Benchmark with name %s already registered!' % b['name']) if 'tasks' in benchmark: for t in benchmark['tasks']: if 'desc' not in t: t['desc'] = rem...
['def', 'register_benchmark(benchmark):', 'for', 'b', 'in', '_BENCHMARKS:', 'if', "b['name']", '==', "benchmark['name']:", 'raise', "ValueError('Benchmark", 'with', 'name', '%s', 'already', "registered!'", '%', "b['name'])", 'if', "'tasks'", 'in', 'benchmark:', 'for', 't', 'in', "benchmark['tasks']:", 'if', "'desc'", '...
200,063
nicknochnack/RealTimeSignLanguageTFJS
shake_drop.py
shortcut
shortcut
Applies strided avg pool or zero padding to make output_filters match x.
[ "Applies", "strided", "avg", "pool", "or", "zero", "padding", "to", "make", "output_filters", "match", "x." ]
def shortcut(x, output_filters, stride): num_filters = int(x.shape[3]) if stride == 2: x = ops.avg_pool(x, 2, stride=stride, padding='SAME') if num_filters != output_filters: diff = output_filters - num_filters assert diff > 0 padding = [[0, 0], [0, 0], [0, 0], [0, diff]] ...
['def', 'shortcut(x,', 'output_filters,', 'stride):', 'num_filters', '=', 'int(x.shape[3])', 'if', 'stride', '==', '2:', 'x', '=', 'ops.avg_pool(x,', '2,', 'stride=stride,', "padding='SAME')", 'if', 'num_filters', '!=', 'output_filters:', 'diff', '=', 'output_filters', '-', 'num_filters', 'assert', 'diff', '>', '0', 'p...
851,433
blakeblackshear/frigate
image.py
intersection
intersection
Return intersection box or None if boxes do not intersect.
[ "Return", "intersection", "box", "or", "None", "if", "boxes", "do", "not", "intersect." ]
def intersection(box_a, box_b) -> Optional[list[int]]: if box_a[2] < box_b[0] or box_a[0] > box_b[2] or box_a[1] > box_b[3] or (box_a[3] < box_b[1]): return None return (max(box_a[0], box_b[0]), max(box_a[1], box_b[1]), min(box_a[2], box_b[2]), min(box_a[3], box_b[3]))
['def', 'intersection(box_a,', 'box_b)', '->', 'Optional[list[int]]:', 'if', 'box_a[2]', '<', 'box_b[0]', 'or', 'box_a[0]', '>', 'box_b[2]', 'or', 'box_a[1]', '>', 'box_b[3]', 'or', '(box_a[3]', '<', 'box_b[1]):', 'return', 'None', 'return', '(max(box_a[0],', 'box_b[0]),', 'max(box_a[1],', 'box_b[1]),', 'min(box_a[2],'...
564,509
YannDubs/Invariant-Self-Supervised-Learning
helpers.py
init_std_modules
init_std_modules
Initialize standard layers and return whether was initialized.
[ "Initialize", "standard", "layers", "and", "return", "whether", "was", "initialized." ]
def init_std_modules(module: nn.Module) -> bool: if isinstance(module, nn.modules.conv._ConvNd): variance_scaling_(module.weight) try: nn.init.zeros_(module.bias) except AttributeError: pass elif isinstance(module, nn.Linear): nn.init.trunc_normal_(module....
['def', 'init_std_modules(module:', 'nn.Module)', '->', 'bool:', 'if', 'isinstance(module,', 'nn.modules.conv._ConvNd):', 'variance_scaling_(module.weight)', 'try:', 'nn.init.zeros_(module.bias)', 'except', 'AttributeError:', 'pass', 'elif', 'isinstance(module,', 'nn.Linear):', 'nn.init.trunc_normal_(module.weight,', '...
245,898
Gguinet/semisupervised-alignment
tf_ranking_libsvm_bigNN.py
IteratorInitializerHook.after_create_session
after_create_session
Initialize the iterator after the session has been created.
[ "Initialize", "the", "iterator", "after", "the", "session", "has", "been", "created." ]
def after_create_session(self, session, coord): del coord self.iterator_initializer_fn(session)
['def', 'after_create_session(self,', 'session,', 'coord):', 'del', 'coord', 'self.iterator_initializer_fn(session)']
343,660
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
common_layers.py
reshape_like_all_dims
reshape_like_all_dims
Reshapes a to match the shape of b.
[ "Reshapes", "a", "to", "match", "the", "shape", "of", "b." ]
def reshape_like_all_dims(a, b): ret = tf.reshape(a, tf.shape(b)) if not tf.contrib.eager.in_eager_mode(): ret.set_shape(b.get_shape()) return ret
['def', 'reshape_like_all_dims(a,', 'b):', 'ret', '=', 'tf.reshape(a,', 'tf.shape(b))', 'if', 'not', 'tf.contrib.eager.in_eager_mode():', 'ret.set_shape(b.get_shape())', 'return', 'ret']
965,328
kaixin96/PANet
blob.py
zeros
zeros
Return a blob of all zeros of the given shape with the correct float or int data type.
[ "Return", "a", "blob", "of", "all", "zeros", "of", "the", "given", "shape", "with", "the", "correct", "float", "or", "int", "data", "type." ]
def zeros(shape, int32=False): return np.zeros(shape, dtype=np.int32 if int32 else np.float32)
['def', 'zeros(shape,', 'int32=False):', 'return', 'np.zeros(shape,', 'dtype=np.int32', 'if', 'int32', 'else', 'np.float32)']
778,824
caiiiac/Machine-Learning-with-Python
test_voting_classifier.py
test_majority_label_iris
test_majority_label_iris
Check classification by majority label on dataset iris.
[ "Check", "classification", "by", "majority", "label", "on", "dataset", "iris." ]
def test_majority_label_iris(): clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') scores = cross_val_score(eclf, X, y, cv=5, scoring='accuracy'...
['def', 'test_majority_label_iris():', 'clf1', '=', 'LogisticRegression(random_state=123)', 'clf2', '=', 'RandomForestClassifier(random_state=123)', 'clf3', '=', 'GaussianNB()', 'eclf', '=', "VotingClassifier(estimators=[('lr',", 'clf1),', "('rf',", 'clf2),', "('gnb',", 'clf3)],', "voting='hard')", 'scores', '=', 'cros...
720,645