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
Farama-Foundation/Gymnasium
utils.py
is_rng_equal
is_rng_equal
Asserts that two random number generates are equivalent.
[ "Asserts", "that", "two", "random", "number", "generates", "are", "equivalent." ]
def is_rng_equal(rng_1: np.random.Generator, rng_2: np.random.Generator): return rng_1.bit_generator.state == rng_2.bit_generator.state
['def', 'is_rng_equal(rng_1:', 'np.random.Generator,', 'rng_2:', 'np.random.Generator):', 'return', 'rng_1.bit_generator.state', '==', 'rng_2.bit_generator.state']
573,559
uber/causalml
match.py
NearestNeighborMatch.match
match
Find matches from the control group by matching on specified columns (propensity preferred).
[ "Find", "matches", "from", "the", "control", "group", "by", "matching", "on", "specified", "columns", "(propensity", "preferred)." ]
def match(self, data, treatment_col, score_cols): assert isinstance(score_cols, list), 'score_cols must be a list' treatment = data.loc[data[treatment_col] == 1, score_cols] control = data.loc[data[treatment_col] == 0, score_cols] sdcal = self.caliper * np.std(data[score_cols].values) if self.replac...
['def', 'match(self,', 'data,', 'treatment_col,', 'score_cols):', 'assert', 'isinstance(score_cols,', 'list),', "'score_cols", 'must', 'be', 'a', "list'", 'treatment', '=', 'data.loc[data[treatment_col]', '==', '1,', 'score_cols]', 'control', '=', 'data.loc[data[treatment_col]', '==', '0,', 'score_cols]', 'sdcal', '=',...
456,383
LucasAlegre/sumo-rl
traffic_signal.py
TrafficSignal.compute_reward
compute_reward
Computes the reward of the traffic signal.
[ "Computes", "the", "reward", "of", "the", "traffic", "signal." ]
def compute_reward(self): self.last_reward = self.reward_fn(self) return self.last_reward
['def', 'compute_reward(self):', 'self.last_reward', '=', 'self.reward_fn(self)', 'return', 'self.last_reward']
910,475
facebookresearch/fvcore
config.py
CfgNode.merge_from_file
merge_from_file
Merge configs from a given yaml file.
[ "Merge", "configs", "from", "a", "given", "yaml", "file." ]
def merge_from_file(self, cfg_filename: str, allow_unsafe: bool=False) -> None: loaded_cfg = self.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe) loaded_cfg = type(self)(loaded_cfg) self.merge_from_other_cfg(loaded_cfg)
['def', 'merge_from_file(self,', 'cfg_filename:', 'str,', 'allow_unsafe:', 'bool=False)', '->', 'None:', 'loaded_cfg', '=', 'self.load_yaml_with_base(cfg_filename,', 'allow_unsafe=allow_unsafe)', 'loaded_cfg', '=', 'type(self)(loaded_cfg)', 'self.merge_from_other_cfg(loaded_cfg)']
565,877
weimin17/Object-Detection_HelmetDetection
decoder_test.py
DecoderTest.testStringFromCTC
testStringFromCTC
Tests that the decoder can decode sequences including multi-codes.
[ "Tests", "that", "the", "decoder", "can", "decode", "sequences", "including", "multi-codes." ]
def testStringFromCTC(self): ctc_labels = [9, 6, 9, 1, 3, 9, 4, 9, 5, 5, 9, 5, 0, 2, 1, 3, 9, 4, 9] decode = decoder.Decoder(filename=_testdata('charset_size_10.txt')) text = decode.StringFromCTC(ctc_labels, merge_dups=True, null_label=9) self.assertEqual(text, 'farm barn')
['def', 'testStringFromCTC(self):', 'ctc_labels', '=', '[9,', '6,', '9,', '1,', '3,', '9,', '4,', '9,', '5,', '5,', '9,', '5,', '0,', '2,', '1,', '3,', '9,', '4,', '9]', 'decode', '=', "decoder.Decoder(filename=_testdata('charset_size_10.txt'))", 'text', '=', 'decode.StringFromCTC(ctc_labels,', 'merge_dups=True,', 'nul...
753,067
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_102a.py
bbox_to_activ
bbox_to_activ
Return the target of the model on `anchors` for the `bboxes`.
[ "Return", "the", "target", "of", "the", "model", "on", "`anchors`", "for", "the", "`bboxes`." ]
def bbox_to_activ(bboxes, anchors, flatten=True): if flatten: t_centers = (bboxes[..., :2] - anchors[..., :2]) / anchors[..., 2:] t_sizes = torch.log(bboxes[..., 2:] / anchors[..., 2:] + 1e-08) return torch.cat([t_centers, t_sizes], -1).div_(bboxes.new_tensor([[0.1, 0.1, 0.2, 0.2]])) els...
['def', 'bbox_to_activ(bboxes,', 'anchors,', 'flatten=True):', 'if', 'flatten:', 't_centers', '=', '(bboxes[...,', ':2]', '-', 'anchors[...,', ':2])', '/', 'anchors[...,', '2:]', 't_sizes', '=', 'torch.log(bboxes[...,', '2:]', '/', 'anchors[...,', '2:]', '+', '1e-08)', 'return', 'torch.cat([t_centers,', 't_sizes],', '-...
81,870
NoGameNoLife00/mybolg
helpers.py
resolve_ctx
resolve_ctx
Resolve current Jinja2 context and store it for general consumption.
[ "Resolve", "current", "Jinja2", "context", "and", "store", "it", "for", "general", "consumption." ]
def resolve_ctx(context): g._admin_render_ctx = context
['def', 'resolve_ctx(context):', 'g._admin_render_ctx', '=', 'context']
289,191
LucasAlegre/morl-baselines
networks.py
polyak_update
polyak_update
Polyak averaging for target network parameters.
[ "Polyak", "averaging", "for", "target", "network", "parameters." ]
def polyak_update(params: Iterable[th.nn.Parameter], target_params: Iterable[th.nn.Parameter], tau: float) -> None: for (param, target_param) in zip(params, target_params): if tau == 1: target_param.data.copy_(param.data) else: target_param.data.mul_(1.0 - tau) th...
['def', 'polyak_update(params:', 'Iterable[th.nn.Parameter],', 'target_params:', 'Iterable[th.nn.Parameter],', 'tau:', 'float)', '->', 'None:', 'for', '(param,', 'target_param)', 'in', 'zip(params,', 'target_params):', 'if', 'tau', '==', '1:', 'target_param.data.copy_(param.data)', 'else:', 'target_param.data.mul_(1.0'...
655,815
open-mmlab/mmcv
points_in_boxes.py
points_in_boxes_all
points_in_boxes_all
Find all boxes in which each point is (CUDA).
[ "Find", "all", "boxes", "in", "which", "each", "point", "is", "(CUDA)." ]
def points_in_boxes_all(points: Tensor, boxes: Tensor) -> Tensor: assert boxes.shape[0] == points.shape[0], f'Points and boxes should have the same batch size, but got {boxes.shape[0]} and {boxes.shape[0]}' assert boxes.shape[2] == 7, f'boxes dimension should be 7, but got unexpected shape {boxes.shape[2]}' ...
['def', 'points_in_boxes_all(points:', 'Tensor,', 'boxes:', 'Tensor)', '->', 'Tensor:', 'assert', 'boxes.shape[0]', '==', 'points.shape[0],', "f'Points", 'and', 'boxes', 'should', 'have', 'the', 'same', 'batch', 'size,', 'but', 'got', '{boxes.shape[0]}', 'and', "{boxes.shape[0]}'", 'assert', 'boxes.shape[2]', '==', '7,...
631,548
ryu-ed/SpaceInvaders_Ros
frontend.py
Values.copy
copy
Return a shallow copy of `self`.
[ "Return", "a", "shallow", "copy", "of", "`self`." ]
def copy(self): return self.__class__(defaults=self.__dict__)
['def', 'copy(self):', 'return', 'self.__class__(defaults=self.__dict__)']
394,734
nilearn/nilearn
test_first_level.py
test_first_level_from_bids_no_tr
test_first_level_from_bids_no_tr
Throw warning when t_r information cannot be inferred from the data and t_r=None is passed.
[ "Throw", "warning", "when", "t_r", "information", "cannot", "be", "inferred", "from", "the", "data", "and", "t_r=None", "is", "passed." ]
def test_first_level_from_bids_no_tr(tmp_path_factory): bids_dataset = _new_bids_dataset(tmp_path_factory.mktemp('no_events')) json_files = get_bids_files(main_path=bids_dataset, file_tag='bold', file_type='json') for f in json_files: os.remove(f) with pytest.warns(UserWarning, match="'t_r' not ...
['def', 'test_first_level_from_bids_no_tr(tmp_path_factory):', 'bids_dataset', '=', "_new_bids_dataset(tmp_path_factory.mktemp('no_events'))", 'json_files', '=', 'get_bids_files(main_path=bids_dataset,', "file_tag='bold',", "file_type='json')", 'for', 'f', 'in', 'json_files:', 'os.remove(f)', 'with', 'pytest.warns(User...
723,854
qiwenjjin/TANet
find.py
find_cuda
find_cuda
Finds the CUDA install path.
[ "Finds", "the", "CUDA", "install", "path." ]
def find_cuda(): cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH') if cuda_home is None: if sys.platform == 'win32': cuda_homes = glob.glob('C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*') if len(cuda_homes) == 0: cuda_home = '' ...
['def', 'find_cuda():', 'cuda_home', '=', "os.environ.get('CUDA_HOME')", 'or', "os.environ.get('CUDA_PATH')", 'if', 'cuda_home', 'is', 'None:', 'if', 'sys.platform', '==', "'win32':", 'cuda_homes', '=', "glob.glob('C:/Program", 'Files/NVIDIA', 'GPU', 'Computing', "Toolkit/CUDA/v*.*')", 'if', 'len(cuda_homes)', '==', '0...
907,192
chribsen/simple-machine-learning-examples
frame.py
DataFrame.shape
shape
Return a tuple representing the dimensionality of the DataFrame.
[ "Return", "a", "tuple", "representing", "the", "dimensionality", "of", "the", "DataFrame." ]
def shape(self): return (len(self.index), len(self.columns))
['def', 'shape(self):', 'return', '(len(self.index),', 'len(self.columns))']
935,855
alibaba/EasyCV
merge_augs.py
merge_aug_bboxes_3d
merge_aug_bboxes_3d
Merge augmented detection 3D bboxes and scores.
[ "Merge", "augmented", "detection", "3D", "bboxes", "and", "scores." ]
def merge_aug_bboxes_3d(aug_results, img_metas, test_cfg): assert len(aug_results) == len(img_metas), f'"aug_results" should have the same length as "img_metas", got len(aug_results)={len(aug_results)} and len(img_metas)={len(img_metas)}' recovered_bboxes = [] recovered_scores = [] recovered_labels = []...
['def', 'merge_aug_bboxes_3d(aug_results,', 'img_metas,', 'test_cfg):', 'assert', 'len(aug_results)', '==', 'len(img_metas),', 'f\'"aug_results"', 'should', 'have', 'the', 'same', 'length', 'as', '"img_metas",', 'got', 'len(aug_results)={len(aug_results)}', 'and', "len(img_metas)={len(img_metas)}'", 'recovered_bboxes',...
546,374
GeekLiB/keras
tensorflow_backend.py
argmin
argmin
Returns the index of the minimum value along a tensor axis.
[ "Returns", "the", "index", "of", "the", "minimum", "value", "along", "a", "tensor", "axis." ]
def argmin(x, axis=-1): if axis < 0: axis = axis % len(x.get_shape()) return tf.argmin(x, axis)
['def', 'argmin(x,', 'axis=-1):', 'if', 'axis', '<', '0:', 'axis', '=', 'axis', '%', 'len(x.get_shape())', 'return', 'tf.argmin(x,', 'axis)']
247,768
rudranil723/mini-main
coordseq.py
GEOSCoordSeq.getY
getY
Get the Y value at the given index.
[ "Get", "the", "Y", "value", "at", "the", "given", "index." ]
def getY(self, index): return self.getOrdinate(1, index)
['def', 'getY(self,', 'index):', 'return', 'self.getOrdinate(1,', 'index)']
315,264
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nav_utils.py
save_d_at_t
save_d_at_t
Save distance to goal at all time steps.
[ "Save", "distance", "to", "goal", "at", "all", "time", "steps." ]
def save_d_at_t(outputs, global_step, output_dir, metric_summary, N): d_at_t = np.concatenate(map(lambda x: x[0][:, :, 0] * 1, outputs), axis=0) (fig, axes) = utils.subplot(plt, (1, 1), (5, 5)) axes.plot(np.arange(d_at_t.shape[1]), np.mean(d_at_t, axis=0), 'r.') axes.set_xlabel('time step') axes.set...
['def', 'save_d_at_t(outputs,', 'global_step,', 'output_dir,', 'metric_summary,', 'N):', 'd_at_t', '=', 'np.concatenate(map(lambda', 'x:', 'x[0][:,', ':,', '0]', '*', '1,', 'outputs),', 'axis=0)', '(fig,', 'axes)', '=', 'utils.subplot(plt,', '(1,', '1),', '(5,', '5))', 'axes.plot(np.arange(d_at_t.shape[1]),', 'np.mean(...
53,579
lvwerra/trl
supervised_finetuning.py
prepare_sample_text
prepare_sample_text
Prepare the text from a sample of the dataset.
[ "Prepare", "the", "text", "from", "a", "sample", "of", "the", "dataset." ]
def prepare_sample_text(example): text = f"Question: {example['question']}\n\nAnswer: {example['response_j']}" return text
['def', 'prepare_sample_text(example):', 'text', '=', 'f"Question:', "{example['question']}\\n\\nAnswer:", '{example[\'response_j\']}"', 'return', 'text']
425,802
nicknochnack/RealTimeSignLanguageTFJS
base_metric.py
SegmentationMetric.detailed_results
detailed_results
Computes and returns the detailed final metric results.
[ "Computes", "and", "returns", "the", "detailed", "final", "metric", "results." ]
def detailed_results(self, is_thing=None): raise NotImplementedError('Not implemented in subclasses.')
['def', 'detailed_results(self,', 'is_thing=None):', 'raise', "NotImplementedError('Not", 'implemented', 'in', "subclasses.')"]
851,577
sunishsheth2009/ChatterBot
test_mongo_adapter.py
MongoAdapterTestCase.tearDown
tearDown
Remove the test database.
[ "Remove", "the", "test", "database." ]
def tearDown(self): self.adapter.drop()
['def', 'tearDown(self):', 'self.adapter.drop()']
485,949
caiiiac/Machine-Learning-with-Python
test_peak_finding.py
TestFindPeaks.test_find_peaks_withnoise
test_find_peaks_withnoise
Verify that peak locations are (approximately) found for a series of gaussians with added noise.
[ "Verify", "that", "peak", "locations", "are", "(approximately)", "found", "for", "a", "series", "of", "gaussians", "with", "added", "noise." ]
def test_find_peaks_withnoise(self): sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] num_points = 500 (test_data, act_locs) = _gen_gaussians_even(sigmas, num_points) widths = np.arange(0.1, max(sigmas)) noise_amp = 0.07 np.random.seed(18181911) test_data += (np.random.rand(num_points) - 0.5) * (...
['def', 'test_find_peaks_withnoise(self):', 'sigmas', '=', '[5.0,', '3.0,', '10.0,', '20.0,', '10.0,', '50.0]', 'num_points', '=', '500', '(test_data,', 'act_locs)', '=', '_gen_gaussians_even(sigmas,', 'num_points)', 'widths', '=', 'np.arange(0.1,', 'max(sigmas))', 'noise_amp', '=', '0.07', 'np.random.seed(18181911)', ...
719,865
matsu0228/nlp-jp
common.py
validate_positive_float
validate_positive_float
Validates that 'value' is a float, or can be converted to one, and is positive.
[ "Validates", "that", "'value'", "is", "a", "float,", "or", "can", "be", "converted", "to", "one,", "and", "is", "positive." ]
def validate_positive_float(option, value): errmsg = '%s must be an integer or float' % (option,) try: value = float(value) except ValueError: raise ValueError(errmsg) except TypeError: raise TypeError(errmsg) if not 0 < value < 1000000000.0: raise ValueError('%s must...
['def', 'validate_positive_float(option,', 'value):', 'errmsg', '=', "'%s", 'must', 'be', 'an', 'integer', 'or', "float'", '%', '(option,)', 'try:', 'value', '=', 'float(value)', 'except', 'ValueError:', 'raise', 'ValueError(errmsg)', 'except', 'TypeError:', 'raise', 'TypeError(errmsg)', 'if', 'not', '0', '<', 'value',...
804,792
OpenMDAO/OpenMDAO-Framework
problem_formulation.py
ArchitectureAssembly.initialize
initialize
Sets all des_vars and coupling_vars to the start values, if specified.
[ "Sets", "all", "des_vars", "and", "coupling_vars", "to", "the", "start", "values,", "if", "specified." ]
def initialize(self): self.init_parameters() self.init_coupling_vars()
['def', 'initialize(self):', 'self.init_parameters()', 'self.init_coupling_vars()']
275,972
ivanmontero/autobot
lm_seqs_dataset.py
LmSeqsDataset.remove_long_sequences
remove_long_sequences
Sequences that are too long are splitted by chunk of max_model_input_size.
[ "Sequences", "that", "are", "too", "long", "are", "splitted", "by", "chunk", "of", "max_model_input_size." ]
def remove_long_sequences(self): max_len = self.params.max_model_input_size indices = self.lengths > max_len logger.info(f'Splitting {sum(indices)} too long sequences.') def divide_chunks(l, n): return [l[i:i + n] for i in range(0, len(l), n)] new_tok_ids = [] new_lengths = [] if se...
['def', 'remove_long_sequences(self):', 'max_len', '=', 'self.params.max_model_input_size', 'indices', '=', 'self.lengths', '>', 'max_len', "logger.info(f'Splitting", '{sum(indices)}', 'too', 'long', "sequences.')", 'def', 'divide_chunks(l,', 'n):', 'return', '[l[i:i', '+', 'n]', 'for', 'i', 'in', 'range(0,', 'len(l),'...
417,685
AaronYALai/Generative_Adversarial_Networks_PyTorch
InfoGAN.py
InfoGAN_Generator.forward
forward
Input the random noise plus latent codes to generate fake images.
[ "Input", "the", "random", "noise", "plus", "latent", "codes", "to", "generate", "fake", "images." ]
def forward(self, x): x = self.fc_in(x) x = x.view(-1, self.featmap_dim, 4, 4) for layer in range(self.n_layer): conv_layer = self.convs[self.n_layer - layer - 1] if layer == self.n_layer - 1: x = F.tanh(conv_layer(x)) else: BN_layer = self.BNs[self.n_layer - ...
['def', 'forward(self,', 'x):', 'x', '=', 'self.fc_in(x)', 'x', '=', 'x.view(-1,', 'self.featmap_dim,', '4,', '4)', 'for', 'layer', 'in', 'range(self.n_layer):', 'conv_layer', '=', 'self.convs[self.n_layer', '-', 'layer', '-', '1]', 'if', 'layer', '==', 'self.n_layer', '-', '1:', 'x', '=', 'F.tanh(conv_layer(x))', 'els...
556,724
microsoft/nlp-recipes
gensen.py
Encoder.forward
forward
Propogate input through the encoder.
[ "Propogate", "input", "through", "the", "encoder." ]
def forward(self, input, lengths, return_all=False, pool='last'): embedding = self.src_embedding(input) src_emb = pack_padded_sequence(embedding, lengths, batch_first=True) if self.rnn_type == 'LSTM': (h, (h_t, _)) = self.encoder(src_emb) else: (h, h_t) = self.encoder(src_emb) if poo...
['def', 'forward(self,', 'input,', 'lengths,', 'return_all=False,', "pool='last'):", 'embedding', '=', 'self.src_embedding(input)', 'src_emb', '=', 'pack_padded_sequence(embedding,', 'lengths,', 'batch_first=True)', 'if', 'self.rnn_type', '==', "'LSTM':", '(h,', '(h_t,', '_))', '=', 'self.encoder(src_emb)', 'else:', '(...
731,262
ballaneypranav/cs50ai
generate.py
CrosswordCreator.solve
solve
Enforce node and arc consistency, and then solve the CSP.
[ "Enforce", "node", "and", "arc", "consistency,", "and", "then", "solve", "the", "CSP." ]
def solve(self): self.enforce_node_consistency() self.ac3() return self.backtrack(dict())
['def', 'solve(self):', 'self.enforce_node_consistency()', 'self.ac3()', 'return', 'self.backtrack(dict())']
192,296
georghess/voxel-mae
builder.py
build_sa_module
build_sa_module
Build PointNet2 set abstraction (SA) module.
[ "Build", "PointNet2", "set", "abstraction", "(SA)", "module." ]
def build_sa_module(cfg, *args, **kwargs): if cfg is None: cfg_ = dict(type='PointSAModule') else: if not isinstance(cfg, dict): raise TypeError('cfg must be a dict') if 'type' not in cfg: raise KeyError('the cfg dict must contain the key "type"') cfg_ = c...
['def', 'build_sa_module(cfg,', '*args,', '**kwargs):', 'if', 'cfg', 'is', 'None:', 'cfg_', '=', "dict(type='PointSAModule')", 'else:', 'if', 'not', 'isinstance(cfg,', 'dict):', 'raise', "TypeError('cfg", 'must', 'be', 'a', "dict')", 'if', "'type'", 'not', 'in', 'cfg:', 'raise', "KeyError('the", 'cfg', 'dict', 'must', ...
380,777
fcjian/LOCE
regnet.py
RegNet.get_stages_from_blocks
get_stages_from_blocks
Gets widths/stage_blocks of network at each stage.
[ "Gets", "widths/stage_blocks", "of", "network", "at", "each", "stage." ]
def get_stages_from_blocks(self, widths): width_diff = [width != width_prev for (width, width_prev) in zip(widths + [0], [0] + widths)] stage_widths = [width for (width, diff) in zip(widths, width_diff[:-1]) if diff] stage_blocks = np.diff([depth for (depth, diff) in zip(range(len(width_diff)), width_diff) ...
['def', 'get_stages_from_blocks(self,', 'widths):', 'width_diff', '=', '[width', '!=', 'width_prev', 'for', '(width,', 'width_prev)', 'in', 'zip(widths', '+', '[0],', '[0]', '+', 'widths)]', 'stage_widths', '=', '[width', 'for', '(width,', 'diff)', 'in', 'zip(widths,', 'width_diff[:-1])', 'if', 'diff]', 'stage_blocks',...
614,392
greydanus/mr_london
datastructures.py
Accept.best
best
The best match as value.
[ "The", "best", "match", "as", "value." ]
def best(self): if self: return self[0][0]
['def', 'best(self):', 'if', 'self:', 'return', 'self[0][0]']
264,028
Newbeeer/TRM
misc.py
seed_hash
seed_hash
Derive an integer hash from all args, for use as a random seed.
[ "Derive", "an", "integer", "hash", "from", "all", "args,", "for", "use", "as", "a", "random", "seed." ]
def seed_hash(*args): args_str = str(args) return int(hashlib.md5(args_str.encode('utf-8')).hexdigest(), 16) % 2 ** 31
['def', 'seed_hash(*args):', 'args_str', '=', 'str(args)', 'return', "int(hashlib.md5(args_str.encode('utf-8')).hexdigest(),", '16)', '%', '2', '**', '31']
951,633
gatapia/py_ml_utils
ast_parser.py
StrNodeVisitor.visit_Dict
visit_Dict
return a string representation of a dict.
[ "return", "a", "string", "representation", "of", "a", "dict." ]
def visit_Dict(self, node): visit = self.visit keyvals = zip(node.keys, node.values) contents = ', '.join(['%s: %s' % (visit(key), visit(value)) for (key, value) in keyvals]) return '{%s}' % contents
['def', 'visit_Dict(self,', 'node):', 'visit', '=', 'self.visit', 'keyvals', '=', 'zip(node.keys,', 'node.values)', 'contents', '=', "',", "'.join(['%s:", "%s'", '%', '(visit(key),', 'visit(value))', 'for', '(key,', 'value)', 'in', 'keyvals])', 'return', "'{%s}'", '%', 'contents']
302,646
vertical-knowledge/ripozo
manager.py
TestManagerMixin.test_delete
test_delete
Tests that a resource is deleted appropriately.
[ "Tests", "that", "a", "resource", "is", "deleted", "appropriately." ]
def test_delete(self): model = self.create_model() model_pks = self.get_model_pks(model) resp = self.manager.delete(model_pks) self.assertRaises(Exception, self.get_model, model_pks)
['def', 'test_delete(self):', 'model', '=', 'self.create_model()', 'model_pks', '=', 'self.get_model_pks(model)', 'resp', '=', 'self.manager.delete(model_pks)', 'self.assertRaises(Exception,', 'self.get_model,', 'model_pks)']
349,127
kaixindelele/DRLib
mpi_pytorch.py
sync_params
sync_params
Sync all parameters of module across all MPI processes.
[ "Sync", "all", "parameters", "of", "module", "across", "all", "MPI", "processes." ]
def sync_params(module): if num_procs() == 1: return for p in module.parameters(): p_numpy = p.data.numpy() broadcast(p_numpy)
['def', 'sync_params(module):', 'if', 'num_procs()', '==', '1:', 'return', 'for', 'p', 'in', 'module.parameters():', 'p_numpy', '=', 'p.data.numpy()', 'broadcast(p_numpy)']
552,913
omarmhaimdat/twitter_nlp_native_swift
api.py
Api.CreateList
CreateList
Creates a new list with the give name for the authenticated user.
[ "Creates", "a", "new", "list", "with", "the", "give", "name", "for", "the", "authenticated", "user." ]
def CreateList(self, name, mode=None, description=None): url = '%s/lists/create.json' % self.base_url parameters = {'name': name} if mode is not None: parameters['mode'] = mode if description is not None: parameters['description'] = description resp = self._RequestUrl(url, 'POST', da...
['def', 'CreateList(self,', 'name,', 'mode=None,', 'description=None):', 'url', '=', "'%s/lists/create.json'", '%', 'self.base_url', 'parameters', '=', "{'name':", 'name}', 'if', 'mode', 'is', 'not', 'None:', "parameters['mode']", '=', 'mode', 'if', 'description', 'is', 'not', 'None:', "parameters['description']", '=',...
955,151
whatdhack/computer_vision
yacs.py
CfgNode.key_is_deprecated
key_is_deprecated
Test if a key is deprecated.
[ "Test", "if", "a", "key", "is", "deprecated." ]
def key_is_deprecated(self, full_key): if full_key in self.__dict__[CfgNode.DEPRECATED_KEYS]: logger.warning('Deprecated config key (ignoring): {}'.format(full_key)) return True return False
['def', 'key_is_deprecated(self,', 'full_key):', 'if', 'full_key', 'in', 'self.__dict__[CfgNode.DEPRECATED_KEYS]:', "logger.warning('Deprecated", 'config', 'key', '(ignoring):', "{}'.format(full_key))", 'return', 'True', 'return', 'False']
475,709
enuguru/artificial_intelligence_and_machine_learning
egg_info.py
egg_info.write_file
write_file
Write `data` to `filename` (if not a dry run) after announcing it `what` is used in a log message to identify what is being written to the file.
[ "Write", "`data`", "to", "`filename`", "(if", "not", "a", "dry", "run)", "after", "announcing", "it", "`what`", "is", "used", "in", "a", "log", "message", "to", "identify", "what", "is", "being", "written", "to", "the", "file." ]
def write_file(self, what, filename, data): log.info('writing %s to %s', what, filename) if sys.version_info >= (3,): data = data.encode('utf-8') if not self.dry_run: f = open(filename, 'wb') f.write(data) f.close()
['def', 'write_file(self,', 'what,', 'filename,', 'data):', "log.info('writing", '%s', 'to', "%s',", 'what,', 'filename)', 'if', 'sys.version_info', '>=', '(3,):', 'data', '=', "data.encode('utf-8')", 'if', 'not', 'self.dry_run:', 'f', '=', 'open(filename,', "'wb')", 'f.write(data)', 'f.close()']
164,227
ludwig-ai/ludwig
dataset_loader.py
DatasetLoader.name
name
The name of the dataset.
[ "The", "name", "of", "the", "dataset." ]
def name(self): return self.config.name
['def', 'name(self):', 'return', 'self.config.name']
616,672
eddylau328/fyp-artificial-intelligence-ac-control-device
datetime_helpers.py
from_microseconds
from_microseconds
Convert timestamp in microseconds since the unix epoch to datetime.
[ "Convert", "timestamp", "in", "microseconds", "since", "the", "unix", "epoch", "to", "datetime." ]
def from_microseconds(value): return _UTC_EPOCH + datetime.timedelta(microseconds=value)
['def', 'from_microseconds(value):', 'return', '_UTC_EPOCH', '+', 'datetime.timedelta(microseconds=value)']
214,444
ViTAE-Transformer/ViTDet
transformer.py
DeformableDetrTransformer.gen_encoder_output_proposals
gen_encoder_output_proposals
Generate proposals from encoded memory.
[ "Generate", "proposals", "from", "encoded", "memory." ]
def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes): (N, S, C) = memory.shape proposals = [] _cur = 0 for (lvl, (H, W)) in enumerate(spatial_shapes): mask_flatten_ = memory_padding_mask[:, _cur:_cur + H * W].view(N, H, W, 1) valid_H = torch.sum(~mask_flatt...
['def', 'gen_encoder_output_proposals(self,', 'memory,', 'memory_padding_mask,', 'spatial_shapes):', '(N,', 'S,', 'C)', '=', 'memory.shape', 'proposals', '=', '[]', '_cur', '=', '0', 'for', '(lvl,', '(H,', 'W))', 'in', 'enumerate(spatial_shapes):', 'mask_flatten_', '=', 'memory_padding_mask[:,', '_cur:_cur', '+', 'H', ...
945,820
PacktPublishing/Hands-On-Artificial--for-Banking
conftest.py
nulls_fixture
nulls_fixture
Fixture for each null type in pandas.
[ "Fixture", "for", "each", "null", "type", "in", "pandas." ]
def nulls_fixture(request): return request.param
['def', 'nulls_fixture(request):', 'return', 'request.param']
235,962
BlissChapman/ICW-fMRI-GAN
reduce.py
apply_grid
apply_grid
Imposes a 3D grid on the brain volume and averages across all voxels that fall within each cell.
[ "Imposes", "a", "3D", "grid", "on", "the", "brain", "volume", "and", "averages", "across", "all", "voxels", "that", "fall", "within", "each", "cell." ]
def apply_grid(dataset, masker=None, scale=5, threshold=None): if masker is None: if isinstance(dataset, Dataset): masker = dataset.masker else: raise ValueError('If dataset is a numpy array, a masker must be provided.') grid = imageutils.create_grid(masker.volume, scale)...
['def', 'apply_grid(dataset,', 'masker=None,', 'scale=5,', 'threshold=None):', 'if', 'masker', 'is', 'None:', 'if', 'isinstance(dataset,', 'Dataset):', 'masker', '=', 'dataset.masker', 'else:', 'raise', "ValueError('If", 'dataset', 'is', 'a', 'numpy', 'array,', 'a', 'masker', 'must', 'be', "provided.')", 'grid', '=', '...
597,046
matsu0228/nlp-jp
backend_bases.py
RendererBase.option_scale_image
option_scale_image
override this method for renderers that support arbitrary affine transformations in :meth:`draw_image` (most vector backends).
[ "override", "this", "method", "for", "renderers", "that", "support", "arbitrary", "affine", "transformations", "in", ":meth:`draw_image`", "(most", "vector", "backends)." ]
def option_scale_image(self): return False
['def', 'option_scale_image(self):', 'return', 'False']
788,370
openvinotoolkit/training_extensions
graph.py
Graph.get_graph
get_graph
Get the underlying NetworkX graph.
[ "Get", "the", "underlying", "NetworkX", "graph." ]
def get_graph(self) -> Union[nx.Graph, nx.MultiDiGraph]: return self._graph
['def', 'get_graph(self)', '->', 'Union[nx.Graph,', 'nx.MultiDiGraph]:', 'return', 'self._graph']
918,514
tensorflow/agents
qtopt_cem_actions_sampler_hybrid.py
GaussianActionsSampler.refit_distribution_to
refit_distribution_to
Refits distribution according to actions with index of ind.
[ "Refits", "distribution", "according", "to", "actions", "with", "index", "of", "ind." ]
def refit_distribution_to(self, target_sample_indices, samples): def get_mean(best_samples): (mean, _) = tf.nn.moments(best_samples, axes=1) return tf.cast(mean, tf.float32) def get_var(best_samples): (_, var) = tf.nn.moments(best_samples, axes=1) return tf.cast(var, tf.float32...
['def', 'refit_distribution_to(self,', 'target_sample_indices,', 'samples):', 'def', 'get_mean(best_samples):', '(mean,', '_)', '=', 'tf.nn.moments(best_samples,', 'axes=1)', 'return', 'tf.cast(mean,', 'tf.float32)', 'def', 'get_var(best_samples):', '(_,', 'var)', '=', 'tf.nn.moments(best_samples,', 'axes=1)', 'return'...
22,890
Kvatsx/Artificial-Intelligence-Assignments
_compatibility.py
u
u
Cast to unicode DAMMIT! Written because Python2 repr always implicitly casts to a string, so we have to cast back to a unicode (and we now that we always deal with valid unicode, because we check that in the beginning).
[ "Cast", "to", "unicode", "DAMMIT!", "Written", "because", "Python2", "repr", "always", "implicitly", "casts", "to", "a", "string,", "so", "we", "have", "to", "cast", "back", "to", "a", "unicode", "(and", "we", "now", "that", "we", "always", "deal", "with",...
def u(string, errors='strict'): if isinstance(string, bytes): return unicode(string, encoding='UTF-8', errors=errors) return string
['def', 'u(string,', "errors='strict'):", 'if', 'isinstance(string,', 'bytes):', 'return', 'unicode(string,', "encoding='UTF-8',", 'errors=errors)', 'return', 'string']
39,051
scikit-learn/scikit-learn
test_openml.py
test_fetch_openml_equivalence_array_return_X_y
test_fetch_openml_equivalence_array_return_X_y
Check the behaviour of `return_X_y=True` when `as_frame=False`.
[ "Check", "the", "behaviour", "of", "`return_X_y=True`", "when", "`as_frame=False`." ]
def test_fetch_openml_equivalence_array_return_X_y(monkeypatch, data_id, parser): pytest.importorskip('pandas') _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) bunch = fetch_openml(data_id=data_id, as_frame=False, cache=False, return_X_y=False, parser=parser) (X, y) = fetch_op...
['def', 'test_fetch_openml_equivalence_array_return_X_y(monkeypatch,', 'data_id,', 'parser):', "pytest.importorskip('pandas')", '_monkey_patch_webbased_functions(monkeypatch,', 'data_id,', 'gzip_response=True)', 'bunch', '=', 'fetch_openml(data_id=data_id,', 'as_frame=False,', 'cache=False,', 'return_X_y=False,', 'pars...
852,962
google/deluca
_deep_mlp.py
rollout_parallel
rollout_parallel
rollout function parallel version.
[ "rollout", "function", "parallel", "version." ]
def rollout_parallel(controller, sim, tt, use_noise, peep, pips, loss_fn): loss = jnp.array(0.0) def rollout_partial(p): return functools.partial(rollout, controller=controller, sim=sim, tt=tt, use_noise=use_noise, peep=peep, loss_fn=loss_fn, loss=0.0)(pip=p) losses = jax.vmap(rollout_partial)(jnp....
['def', 'rollout_parallel(controller,', 'sim,', 'tt,', 'use_noise,', 'peep,', 'pips,', 'loss_fn):', 'loss', '=', 'jnp.array(0.0)', 'def', 'rollout_partial(p):', 'return', 'functools.partial(rollout,', 'controller=controller,', 'sim=sim,', 'tt=tt,', 'use_noise=use_noise,', 'peep=peep,', 'loss_fn=loss_fn,', 'loss=0.0)(pi...
537,919
suarez12138/AI-Reversi_IMP_TextDichotomy
auth.py
get_keyring_auth
get_keyring_auth
Return the tuple auth for a given url from keyring.
[ "Return", "the", "tuple", "auth", "for", "a", "given", "url", "from", "keyring." ]
def get_keyring_auth(url, username): global keyring if not url or not keyring: return None try: try: get_credential = keyring.get_credential except AttributeError: pass else: logger.debug('Getting credentials from keyring for %s', url) ...
['def', 'get_keyring_auth(url,', 'username):', 'global', 'keyring', 'if', 'not', 'url', 'or', 'not', 'keyring:', 'return', 'None', 'try:', 'try:', 'get_credential', '=', 'keyring.get_credential', 'except', 'AttributeError:', 'pass', 'else:', "logger.debug('Getting", 'credentials', 'from', 'keyring', 'for', "%s',", 'url...
98,406
yinyunie/ScenePriors
test_render_implicit.py
spherical_volumetric_function
spherical_volumetric_function
Volumetric function of a simple RGB sphere with diameter `sphere_diameter` and centroid `sphere_centroid`.
[ "Volumetric", "function", "of", "a", "simple", "RGB", "sphere", "with", "diameter", "`sphere_diameter`", "and", "centroid", "`sphere_centroid`." ]
def spherical_volumetric_function(ray_bundle: RayBundle, sphere_centroid: torch.Tensor, sphere_diameter: float, **kwargs): rays_points_world = ray_bundle_to_ray_points(ray_bundle) batch_size = rays_points_world.shape[0] surface_vectors = rays_points_world.view(batch_size, -1, 3) - sphere_centroid[:, None] ...
['def', 'spherical_volumetric_function(ray_bundle:', 'RayBundle,', 'sphere_centroid:', 'torch.Tensor,', 'sphere_diameter:', 'float,', '**kwargs):', 'rays_points_world', '=', 'ray_bundle_to_ray_points(ray_bundle)', 'batch_size', '=', 'rays_points_world.shape[0]', 'surface_vectors', '=', 'rays_points_world.view(batch_siz...
330,106
kornia/kornia
check.py
KORNIA_CHECK_SAME_DEVICES
KORNIA_CHECK_SAME_DEVICES
Check whether a list provided tensors live in the same device.
[ "Check", "whether", "a", "list", "provided", "tensors", "live", "in", "the", "same", "device." ]
def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str]=None, raises: bool=True) -> bool: KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, 'Expected a list with at least one element', raises) if not all((tensors[0].device == x.device for x in tensors)): if raises: ...
['def', 'KORNIA_CHECK_SAME_DEVICES(tensors:', 'list[Tensor],', 'msg:', 'Optional[str]=None,', 'raises:', 'bool=True)', '->', 'bool:', 'KORNIA_CHECK(isinstance(tensors,', 'list)', 'and', 'len(tensors)', '>=', '1,', "'Expected", 'a', 'list', 'with', 'at', 'least', 'one', "element',", 'raises)', 'if', 'not', 'all((tensors...
621,647
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_ae_short
rl_modelrl_ae_short
Small parameter set for autoencoders.
[ "Small", "parameter", "set", "for", "autoencoders." ]
def rl_modelrl_ae_short(): hparams = rl_modelrl_ae_base() hparams.autoencoder_train_steps //= 10 hparams.num_real_env_frames //= 5 hparams.model_train_steps //= 10 hparams.ppo_epochs_num //= 10 return hparams
['def', 'rl_modelrl_ae_short():', 'hparams', '=', 'rl_modelrl_ae_base()', 'hparams.autoencoder_train_steps', '//=', '10', 'hparams.num_real_env_frames', '//=', '5', 'hparams.model_train_steps', '//=', '10', 'hparams.ppo_epochs_num', '//=', '10', 'return', 'hparams']
966,008
omarmhaimdat/twitter_nlp_native_swift
api.py
Api.GetReplies
GetReplies
Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user.
[ "Get", "a", "sequence", "of", "status", "messages", "representing", "the", "20", "most", "recent", "replies", "(status", "updates", "prefixed", "with", "@twitterID)", "to", "the", "authenticating", "user." ]
def GetReplies(self, since_id=None, count=None, max_id=None, trim_user=False): return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=False, include_rts=False)
['def', 'GetReplies(self,', 'since_id=None,', 'count=None,', 'max_id=None,', 'trim_user=False):', 'return', 'self.GetUserTimeline(since_id=since_id,', 'count=count,', 'max_id=max_id,', 'trim_user=trim_user,', 'exclude_replies=False,', 'include_rts=False)']
955,110
dmcnamee/FlexModEHC
timer.py
timeit_debug
timeit_debug
This decorator prints the execution time for the decorated function.
[ "This", "decorator", "prints", "the", "execution", "time", "for", "the", "decorated", "function." ]
def timeit_debug(func): if config.timing and config.verbose: @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() logger.debug(' {} ran in {}s'.format(func.__name__, round(end - start, 5))) ...
['def', 'timeit_debug(func):', 'if', 'config.timing', 'and', 'config.verbose:', '@wraps(func)', 'def', 'wrapper(*args,', '**kwargs):', 'start', '=', 'time.time()', 'result', '=', 'func(*args,', '**kwargs)', 'end', '=', 'time.time()', "logger.debug('", '{}', 'ran', 'in', "{}s'.format(func.__name__,", 'round(end', '-', '...
585,231
rudranil723/mini-main
exceptions.py
ParseBaseException.line
line
Return the line of text where the exception occurred.
[ "Return", "the", "line", "of", "text", "where", "the", "exception", "occurred." ]
def line(self) -> str: return line(self.loc, self.pstr)
['def', 'line(self)', '->', 'str:', 'return', 'line(self.loc,', 'self.pstr)']
269,453
loicmarie/hands-detection
policy.py
Policy.get_initializer
get_initializer
Get initializer for RNN.
[ "Get", "initializer", "for", "RNN." ]
def get_initializer(self, batch_size, initial_state, initial_actions): logits_init = [] log_probs_init = [] for (act_dim, act_type) in self.env_spec.act_dims_and_types: sampling_dim = self.env_spec.sampling_dim(act_dim, act_type) logits_init.append(tf.zeros([batch_size, sampling_dim])) ...
['def', 'get_initializer(self,', 'batch_size,', 'initial_state,', 'initial_actions):', 'logits_init', '=', '[]', 'log_probs_init', '=', '[]', 'for', '(act_dim,', 'act_type)', 'in', 'self.env_spec.act_dims_and_types:', 'sampling_dim', '=', 'self.env_spec.sampling_dim(act_dim,', 'act_type)', 'logits_init.append(tf.zeros(...
575,120
zhiweichen0012/E2Net
viz.py
dump_dataflow_images
dump_dataflow_images
Dump or visualize images of a :class:`DataFlow`.
[ "Dump", "or", "visualize", "images", "of", "a", ":class:`DataFlow`." ]
def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): if output_dir: mkdir_p(output_dir) if viz is not None: viz = shape2d(viz) vizsize = viz[0] * viz[1] if resize is not None: resize = tuple(shape2d(...
['def', 'dump_dataflow_images(df,', 'index=0,', 'batched=True,', 'number=1000,', 'output_dir=None,', 'scale=1,', 'resize=None,', 'viz=None,', 'flipRGB=False):', 'if', 'output_dir:', 'mkdir_p(output_dir)', 'if', 'viz', 'is', 'not', 'None:', 'viz', '=', 'shape2d(viz)', 'vizsize', '=', 'viz[0]', '*', 'viz[1]', 'if', 'resi...
174,577
google-research/scenic
ops.py
get_decode_jpeg_and_random_crop
get_decode_jpeg_and_random_crop
Decode jpeg string and make a center image crop.
[ "Decode", "jpeg", "string", "and", "make", "a", "center", "image", "crop." ]
def get_decode_jpeg_and_random_crop(crop_size=None): crop_size = utils.maybe_repeat(crop_size, 2) def _decode_and_random_crop(image_data): shape = tf.image.extract_jpeg_shape(image_data)[:2] (target_height, target_width) = crop_size limit = shape - crop_size + 1 offset = tf.rand...
['def', 'get_decode_jpeg_and_random_crop(crop_size=None):', 'crop_size', '=', 'utils.maybe_repeat(crop_size,', '2)', 'def', '_decode_and_random_crop(image_data):', 'shape', '=', 'tf.image.extract_jpeg_shape(image_data)[:2]', '(target_height,', 'target_width)', '=', 'crop_size', 'limit', '=', 'shape', '-', 'crop_size', ...
846,109
intel/neural-compressor
transform.py
transform_registry
transform_registry
Class decorator used to register all transform subclasses.
[ "Class", "decorator", "used", "to", "register", "all", "transform", "subclasses." ]
def transform_registry(transform_type, process, framework): def decorator_transform(cls): for single_framework in [fwk.strip() for fwk in framework.split(',')]: assert single_framework in ['tensorflow', 'tensorflow_itex', 'mxnet', 'pytorch', 'pytorch_ipex', 'pytorch_fx', 'onnxrt_qlinearops', 'o...
['def', 'transform_registry(transform_type,', 'process,', 'framework):', 'def', 'decorator_transform(cls):', 'for', 'single_framework', 'in', '[fwk.strip()', 'for', 'fwk', 'in', "framework.split(',')]:", 'assert', 'single_framework', 'in', "['tensorflow',", "'tensorflow_itex',", "'mxnet',", "'pytorch',", "'pytorch_ipex...
738,493
facebookresearch/CompilerGym
gcc.py
system_gcc_path
system_gcc_path
Return the path of the system GCC as a string.
[ "Return", "the", "path", "of", "the", "system", "GCC", "as", "a", "string." ]
def system_gcc_path() -> str: return subprocess.check_output(['which', 'gcc'], universal_newlines=True, stderr=subprocess.DEVNULL).strip()
['def', 'system_gcc_path()', '->', 'str:', 'return', "subprocess.check_output(['which',", "'gcc'],", 'universal_newlines=True,', 'stderr=subprocess.DEVNULL).strip()']
125,966
RasaHQ/rasa
__init__.py
extract_story_graph
extract_story_graph
Loads training stories / rules from file or directory.
[ "Loads", "training", "stories", "/", "rules", "from", "file", "or", "directory." ]
def extract_story_graph(resource_name: Text, domain: 'Domain', exclusion_percentage: Optional[int]=None) -> 'StoryGraph': from rasa.shared.core.training_data.structures import StoryGraph import rasa.shared.core.training_data.loading as core_loading story_steps = core_loading.load_data_from_resource(resource...
['def', 'extract_story_graph(resource_name:', 'Text,', 'domain:', "'Domain',", 'exclusion_percentage:', 'Optional[int]=None)', '->', "'StoryGraph':", 'from', 'rasa.shared.core.training_data.structures', 'import', 'StoryGraph', 'import', 'rasa.shared.core.training_data.loading', 'as', 'core_loading', 'story_steps', '=',...
836,986
cnr-isti-vclab/TagLab
NewDataset.py
NewDataset.save_samples
save_samples
Save a figure to show the samples in the different areas.
[ "Save", "a", "figure", "to", "show", "the", "samples", "in", "the", "different", "areas." ]
def save_samples(self, filename, show_tiles=False, show_areas=True, radii=None): labelimg = self.label_image.copy() painter = QPainter(labelimg) half_tile_size = self.tile_size / 2 SAMPLE_SIZE = 20 HALF_SAMPLE_SIZE = SAMPLE_SIZE / 2 brush = QBrush(Qt.SolidPattern) brush.setColor(Qt.green) ...
['def', 'save_samples(self,', 'filename,', 'show_tiles=False,', 'show_areas=True,', 'radii=None):', 'labelimg', '=', 'self.label_image.copy()', 'painter', '=', 'QPainter(labelimg)', 'half_tile_size', '=', 'self.tile_size', '/', '2', 'SAMPLE_SIZE', '=', '20', 'HALF_SAMPLE_SIZE', '=', 'SAMPLE_SIZE', '/', '2', 'brush', '=...
906,735
eddylau328/fyp-artificial-intelligence-ac-control-device
_messaging_encoder.py
MessageEncoder.encode_webpush_fcm_options
encode_webpush_fcm_options
Encodes a ``WebpushFCMOptions`` instance into JSON.
[ "Encodes", "a", "``WebpushFCMOptions``", "instance", "into", "JSON." ]
def encode_webpush_fcm_options(cls, options): if options is None: return None result = {'link': _Validators.check_string('WebpushConfig.fcm_options.link', options.link)} result = cls.remove_null_values(result) link = result.get('link') if link is not None and (not link.startswith('https://')...
['def', 'encode_webpush_fcm_options(cls,', 'options):', 'if', 'options', 'is', 'None:', 'return', 'None', 'result', '=', "{'link':", "_Validators.check_string('WebpushConfig.fcm_options.link',", 'options.link)}', 'result', '=', 'cls.remove_null_values(result)', 'link', '=', "result.get('link')", 'if', 'link', 'is', 'no...
214,353
sktime/sktime
test_detrend.py
test_polynomial_detrending
test_polynomial_detrending
Test that transformer results agree with manual detrending.
[ "Test", "that", "transformer", "results", "agree", "with", "manual", "detrending." ]
def test_polynomial_detrending(): y = pd.Series(np.arange(20) * 0.5) + np.random.normal(0, 1, size=20) forecaster = PolynomialTrendForecaster(degree=1, with_intercept=True) transformer = Detrender(forecaster) transformer.fit(y) actual_coefs = transformer.forecaster_.regressor_.steps[-1][-1].coef_ ...
['def', 'test_polynomial_detrending():', 'y', '=', 'pd.Series(np.arange(20)', '*', '0.5)', '+', 'np.random.normal(0,', '1,', 'size=20)', 'forecaster', '=', 'PolynomialTrendForecaster(degree=1,', 'with_intercept=True)', 'transformer', '=', 'Detrender(forecaster)', 'transformer.fit(y)', 'actual_coefs', '=', 'transformer....
877,822
lixingjian/DELTA
kaldi_dir_utils.py
gen_dummy_data_dir
gen_dummy_data_dir
Generate a dummy data directory and return its meta.
[ "Generate", "a", "dummy", "data", "directory", "and", "return", "its", "meta." ]
def gen_dummy_data_dir(data_dir, num_spk, num_utt_per_spk, feat_len=100, feat_dim=40): os.makedirs(data_dir, exist_ok=True) meta = kaldi_dir.KaldiMetaData() feats = {} vads = {} for spk_idx in range(num_spk): for utt_idx in range(num_utt_per_spk): spk = str(spk_idx) u...
['def', 'gen_dummy_data_dir(data_dir,', 'num_spk,', 'num_utt_per_spk,', 'feat_len=100,', 'feat_dim=40):', 'os.makedirs(data_dir,', 'exist_ok=True)', 'meta', '=', 'kaldi_dir.KaldiMetaData()', 'feats', '=', '{}', 'vads', '=', '{}', 'for', 'spk_idx', 'in', 'range(num_spk):', 'for', 'utt_idx', 'in', 'range(num_utt_per_spk)...
537,620
Trusted-AI/adversarial-robustness-toolbox
bullseye_polytope_attack.py
loss_from_center
loss_from_center
Calculate loss from center.
[ "Calculate", "loss", "from", "center." ]
def loss_from_center(subs_net_list, target_feat_list, poison_batch, net_repeat, end2end, feature_layer) -> 'torch.Tensor': import torch if end2end: loss = torch.tensor(0.0) for (net, center_feats) in zip(subs_net_list, target_feat_list): poisons_feats: Union[List[float], 'torch.Tenso...
['def', 'loss_from_center(subs_net_list,', 'target_feat_list,', 'poison_batch,', 'net_repeat,', 'end2end,', 'feature_layer)', '->', "'torch.Tensor':", 'import', 'torch', 'if', 'end2end:', 'loss', '=', 'torch.tensor(0.0)', 'for', '(net,', 'center_feats)', 'in', 'zip(subs_net_list,', 'target_feat_list):', 'poisons_feats:...
397,672
datature/portal
folder.py
Folder.set_folders
set_folders
Update the folders attribute.
[ "Update", "the", "folders", "attribute." ]
def set_folders(self, folders): self._folders_ = folders
['def', 'set_folders(self,', 'folders):', 'self._folders_', '=', 'folders']
821,004
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
adafactor_experiments.py
afx_adafactor
afx_adafactor
Adafactor with recommended learning rate schedule.
[ "Adafactor", "with", "recommended", "learning", "rate", "schedule." ]
def afx_adafactor(): hparams = afx_adam() hparams.optimizer = 'Adafactor' hparams.learning_rate_schedule = 'rsqrt_decay' hparams.learning_rate_warmup_steps = 10000 return hparams
['def', 'afx_adafactor():', 'hparams', '=', 'afx_adam()', 'hparams.optimizer', '=', "'Adafactor'", 'hparams.learning_rate_schedule', '=', "'rsqrt_decay'", 'hparams.learning_rate_warmup_steps', '=', '10000', 'return', 'hparams']
965,741
s3prl/s3prl
sliding_attn.py
merge_padding_attm_mask
merge_padding_attm_mask
Merge `key_padding_mask` into `attn_mask`.
[ "Merge", "`key_padding_mask`", "into", "`attn_mask`." ]
def merge_padding_attm_mask(attn_mask, key_padding_mask, num_heads, tgt_len=None): if key_padding_mask is None: return attn_mask else: assert num_heads is not None if key_padding_mask.ndim == 1: key_padding_mask = mask_padding(key_padding_mask) (bsz, src_len) = key_padding_mask.s...
['def', 'merge_padding_attm_mask(attn_mask,', 'key_padding_mask,', 'num_heads,', 'tgt_len=None):', 'if', 'key_padding_mask', 'is', 'None:', 'return', 'attn_mask', 'else:', 'assert', 'num_heads', 'is', 'not', 'None', 'if', 'key_padding_mask.ndim', '==', '1:', 'key_padding_mask', '=', 'mask_padding(key_padding_mask)', '(...
327,741
Alexander-Parker/youtube_nlp
_helpers.py
string_to_scopes
string_to_scopes
Converts stringifed scopes value to a list.
[ "Converts", "stringifed", "scopes", "value", "to", "a", "list." ]
def string_to_scopes(scopes): if not scopes: return [] return scopes.split(' ')
['def', 'string_to_scopes(scopes):', 'if', 'not', 'scopes:', 'return', '[]', 'return', "scopes.split('", "')"]
970,034
43Carrig/recurrent_neural_networks_practice
context.py
Context.scope_name
scope_name
Returns scope name for the current thread.
[ "Returns", "scope", "name", "for", "the", "current", "thread." ]
def scope_name(self): return self._eager_context.scope_name
['def', 'scope_name(self):', 'return', 'self._eager_context.scope_name']
336,105
ylsung/Ladder-Side-Tuning
adapter_hypernetwork.py
AdapterLayersOneHyperNetController.get_embedding
get_embedding
Concatenates the task embedding with the embedding for the layer id and returns the final joint embedding.
[ "Concatenates", "the", "task", "embedding", "with", "the", "embedding", "for", "the", "layer", "id", "and", "returns", "the", "final", "joint", "embedding." ]
def get_embedding(self, task_embedding, layer_id, block_type): layer_id_tensor = torch.tensor([layer_id], dtype=torch.long, device=task_embedding.device) layer_embedding = self.layer_id_embeddings(layer_id_tensor) type_id_tensor = torch.tensor([block_type], dtype=torch.long, device=task_embedding.device) ...
['def', 'get_embedding(self,', 'task_embedding,', 'layer_id,', 'block_type):', 'layer_id_tensor', '=', 'torch.tensor([layer_id],', 'dtype=torch.long,', 'device=task_embedding.device)', 'layer_embedding', '=', 'self.layer_id_embeddings(layer_id_tensor)', 'type_id_tensor', '=', 'torch.tensor([block_type],', 'dtype=torch....
623,134
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
lapnorm.py
lap_normalize
lap_normalize
Perform the Laplacian pyramid normalization.
[ "Perform", "the", "Laplacian", "pyramid", "normalization." ]
def lap_normalize(img, scale_n=4): img = tf.expand_dims(img, 0) tlevels = lap_split_n(img, scale_n) tlevels = list(map(normalize_std, tlevels)) out = lap_merge(tlevels) return out[0, :, :, :]
['def', 'lap_normalize(img,', 'scale_n=4):', 'img', '=', 'tf.expand_dims(img,', '0)', 'tlevels', '=', 'lap_split_n(img,', 'scale_n)', 'tlevels', '=', 'list(map(normalize_std,', 'tlevels))', 'out', '=', 'lap_merge(tlevels)', 'return', 'out[0,', ':,', ':,', ':]']
30,819
zhihou7/HOI-CL-OneStage
build.py
get_hoi_dataset_dicts
get_hoi_dataset_dicts
Load and prepare dataset dicts for HOI detection.
[ "Load", "and", "prepare", "dataset", "dicts", "for", "HOI", "detection." ]
def get_hoi_dataset_dicts(dataset_names, filter_empty=True): assert len(dataset_names) dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in dataset_names] for (dataset_name, dicts) in zip(dataset_names, dataset_dicts): assert len(dicts), "Dataset '{}' is empty!".format(dataset_name)...
['def', 'get_hoi_dataset_dicts(dataset_names,', 'filter_empty=True):', 'assert', 'len(dataset_names)', 'dataset_dicts', '=', '[DatasetCatalog.get(dataset_name)', 'for', 'dataset_name', 'in', 'dataset_names]', 'for', '(dataset_name,', 'dicts)', 'in', 'zip(dataset_names,', 'dataset_dicts):', 'assert', 'len(dicts),', '"Da...
569,174
dguo98/DiffPruning
optimization_tf.py
create_optimizer
create_optimizer
Creates an optimizer with learning rate schedule.
[ "Creates", "an", "optimizer", "with", "learning", "rate", "schedule." ]
def create_optimizer(init_lr, num_train_steps, num_warmup_steps): learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=init_lr, decay_steps=num_train_steps, end_learning_rate=0.0) if num_warmup_steps: learning_rate_fn = WarmUp(initial_learning_rate=init_lr, decay_schedu...
['def', 'create_optimizer(init_lr,', 'num_train_steps,', 'num_warmup_steps):', 'learning_rate_fn', '=', 'tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=init_lr,', 'decay_steps=num_train_steps,', 'end_learning_rate=0.0)', 'if', 'num_warmup_steps:', 'learning_rate_fn', '=', 'WarmUp(initial_learning_r...
550,672
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Text.yview_pickplace
yview_pickplace
Obsolete function, use see.
[ "Obsolete", "function,", "use", "see." ]
def yview_pickplace(self, *what): self.tk.call((self._w, 'yview', '-pickplace') + what)
['def', 'yview_pickplace(self,', '*what):', 'self.tk.call((self._w,', "'yview',", "'-pickplace')", '+', 'what)']
377,093
FreshAirTonight/af2complex
templates.py
HmmsearchHitFeaturizer.get_templates
get_templates
Computes the templates for given query sequence (more details above).
[ "Computes", "the", "templates", "for", "given", "query", "sequence", "(more", "details", "above)." ]
def get_templates(self, query_sequence: str, hits: Sequence[parsers.TemplateHit]) -> TemplateSearchResult: logging.info('Searching for template for: %s', query_sequence) template_features = {} for template_feature_name in TEMPLATE_FEATURES: template_features[template_feature_name] = [] already_s...
['def', 'get_templates(self,', 'query_sequence:', 'str,', 'hits:', 'Sequence[parsers.TemplateHit])', '->', 'TemplateSearchResult:', "logging.info('Searching", 'for', 'template', 'for:', "%s',", 'query_sequence)', 'template_features', '=', '{}', 'for', 'template_feature_name', 'in', 'TEMPLATE_FEATURES:', 'template_featu...
400,587
gunthercox/ChatterBot
fst.py
BaseCursor.is_active
is_active
Returns True if this cursor is still active, that is it has not read past the last arc in the graph.
[ "Returns", "True", "if", "this", "cursor", "is", "still", "active,", "that", "is", "it", "has", "not", "read", "past", "the", "last", "arc", "in", "the", "graph." ]
def is_active(self): raise NotImplementedError
['def', 'is_active(self):', 'raise', 'NotImplementedError']
484,336
rifqind/Agent-Programs-3KS1
script.py
ScriptMagics.kill_bg_processes
kill_bg_processes
Kill all BG processes which are still running.
[ "Kill", "all", "BG", "processes", "which", "are", "still", "running." ]
def kill_bg_processes(self): if not self.bg_processes: return for p in self.bg_processes: if p.poll() is None: try: p.send_signal(signal.SIGINT) except: pass time.sleep(0.1) self._gc_bg_processes() if not self.bg_processes: ...
['def', 'kill_bg_processes(self):', 'if', 'not', 'self.bg_processes:', 'return', 'for', 'p', 'in', 'self.bg_processes:', 'if', 'p.poll()', 'is', 'None:', 'try:', 'p.send_signal(signal.SIGINT)', 'except:', 'pass', 'time.sleep(0.1)', 'self._gc_bg_processes()', 'if', 'not', 'self.bg_processes:', 'return', 'for', 'p', 'in'...
41,354
reihaneh-torkzadehmahani/DP-CGAN
DP_CGAN_MomentAcc.py
xavier_init
xavier_init
Xavier Function to keep the scale of the gradients roughly the same in all the layers.
[ "Xavier", "Function", "to", "keep", "the", "scale", "of", "the", "gradients", "roughly", "the", "same", "in", "all", "the", "layers." ]
def xavier_init(size): in_dim = size[0] xavier_stddev = 1.0 / tf.sqrt(in_dim / 2.0) return tf.random_normal(shape=size, stddev=xavier_stddev)
['def', 'xavier_init(size):', 'in_dim', '=', 'size[0]', 'xavier_stddev', '=', '1.0', '/', 'tf.sqrt(in_dim', '/', '2.0)', 'return', 'tf.random_normal(shape=size,', 'stddev=xavier_stddev)']
552,389
jxhe/unify-parameter-efficient-tuning
check_copies.py
split_long_line_with_indent
split_long_line_with_indent
Split the `line` so that it doesn't go over `max_per_line` and adds `indent` to new lines.
[ "Split", "the", "`line`", "so", "that", "it", "doesn't", "go", "over", "`max_per_line`", "and", "adds", "`indent`", "to", "new", "lines." ]
def split_long_line_with_indent(line, max_per_line, indent): words = line.split(' ') lines = [] current_line = words[0] for word in words[1:]: if len(f'{current_line} {word}') > max_per_line: lines.append(current_line) current_line = ' ' * indent + word else: ...
['def', 'split_long_line_with_indent(line,', 'max_per_line,', 'indent):', 'words', '=', "line.split('", "')", 'lines', '=', '[]', 'current_line', '=', 'words[0]', 'for', 'word', 'in', 'words[1:]:', 'if', "len(f'{current_line}", "{word}')", '>', 'max_per_line:', 'lines.append(current_line)', 'current_line', '=', "'", "'...
949,555
Westlake-AI/OpenBioSeq
svm_classifier.py
SVMHelper.calculate_ap
calculate_ap
Computes the AP under the precision recall curve.
[ "Computes", "the", "AP", "under", "the", "precision", "recall", "curve." ]
def calculate_ap(rec, prec): (rec, prec) = (rec.reshape(rec.size, 1), prec.reshape(prec.size, 1)) (z, o) = (np.zeros((1, 1)), np.ones((1, 1))) (mrec, mpre) = (np.vstack((z, rec, o)), np.vstack((z, prec, z))) for i in range(len(mpre) - 2, -1, -1): mpre[i] = max(mpre[i], mpre[i + 1]) indices =...
['def', 'calculate_ap(rec,', 'prec):', '(rec,', 'prec)', '=', '(rec.reshape(rec.size,', '1),', 'prec.reshape(prec.size,', '1))', '(z,', 'o)', '=', '(np.zeros((1,', '1)),', 'np.ones((1,', '1)))', '(mrec,', 'mpre)', '=', '(np.vstack((z,', 'rec,', 'o)),', 'np.vstack((z,', 'prec,', 'z)))', 'for', 'i', 'in', 'range(len(mpre...
274,872
nasimrahaman/antipasti-tf
core.py
threshold_tensor
threshold_tensor
Thresholds a tensor at a given `threshold` and casts to `as_dtype`.
[ "Thresholds", "a", "tensor", "at", "a", "given", "`threshold`", "and", "casts", "to", "`as_dtype`." ]
def threshold_tensor(tensor, threshold, as_dtype=_FLOATX, name='threshold'): return greater(tensor, threshold, as_dtype=as_dtype, name=name)
['def', 'threshold_tensor(tensor,', 'threshold,', 'as_dtype=_FLOATX,', "name='threshold'):", 'return', 'greater(tensor,', 'threshold,', 'as_dtype=as_dtype,', 'name=name)']
33,489
voxel51/fiftyone
aggregations.py
CountValues.parse_result
parse_result
Parses the output of :meth:`to_mongo`.
[ "Parses", "the", "output", "of", ":meth:`to_mongo`." ]
def parse_result(self, d): if self._field_type is not None: p = self._field_type.to_python else: p = lambda x: x if self._first is not None: count = d['count'] if not count: return (0, []) return (count, [[p(i['k']), i['count']] for i in d['result'] if i['...
['def', 'parse_result(self,', 'd):', 'if', 'self._field_type', 'is', 'not', 'None:', 'p', '=', 'self._field_type.to_python', 'else:', 'p', '=', 'lambda', 'x:', 'x', 'if', 'self._first', 'is', 'not', 'None:', 'count', '=', "d['count']", 'if', 'not', 'count:', 'return', '(0,', '[])', 'return', '(count,', "[[p(i['k']),", ...
582,684
Yuting-Gao/DisCo-pytorch
resnet.py
ecaresnet50
ecaresnet50
Constructs an ECA-ResNet-50 model.
[ "Constructs", "an", "ECA-ResNet-50", "model." ]
def ecaresnet50(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], block_args=dict(attn_layer='eca'), **kwargs) return _create_resnet('ecaresnet50', pretrained, **model_args)
['def', 'ecaresnet50(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '6,', '3],', "block_args=dict(attn_layer='eca'),", '**kwargs)', 'return', "_create_resnet('ecaresnet50',", 'pretrained,', '**model_args)']
186,856
AndrewYinLi/lstm-neural-network-spam-filter
drt.py
DrtVariableExpression
DrtVariableExpression
This is a factory method that instantiates and returns a subtype of ``DrtAbstractVariableExpression`` appropriate for the given variable.
[ "This", "is", "a", "factory", "method", "that", "instantiates", "and", "returns", "a", "subtype", "of", "``DrtAbstractVariableExpression``", "appropriate", "for", "the", "given", "variable." ]
def DrtVariableExpression(variable): if is_indvar(variable.name): return DrtIndividualVariableExpression(variable) elif is_funcvar(variable.name): return DrtFunctionVariableExpression(variable) elif is_eventvar(variable.name): return DrtEventVariableExpression(variable) else: ...
['def', 'DrtVariableExpression(variable):', 'if', 'is_indvar(variable.name):', 'return', 'DrtIndividualVariableExpression(variable)', 'elif', 'is_funcvar(variable.name):', 'return', 'DrtFunctionVariableExpression(variable)', 'elif', 'is_eventvar(variable.name):', 'return', 'DrtEventVariableExpression(variable)', 'else:...
218,233
santhoshkolloju/Abstractive-Summarization-With-Transfer-
rnn_decoders.py
AttentionRNNDecoder.output_dtype
output_dtype
Types of output of one step.
[ "Types", "of", "output", "of", "one", "step." ]
def output_dtype(self): dtype = nest.flatten(self._initial_state)[0].dtype return AttentionRNNDecoderOutput(logits=nest.map_structure(lambda _: dtype, self._rnn_output_size()), sample_id=self._helper.sample_ids_dtype, cell_output=nest.map_structure(lambda _: dtype, self._cell.output_size), attention_scores=nest...
['def', 'output_dtype(self):', 'dtype', '=', 'nest.flatten(self._initial_state)[0].dtype', 'return', 'AttentionRNNDecoderOutput(logits=nest.map_structure(lambda', '_:', 'dtype,', 'self._rnn_output_size()),', 'sample_id=self._helper.sample_ids_dtype,', 'cell_output=nest.map_structure(lambda', '_:', 'dtype,', 'self._cell...
406,201
huawei-noah/xingtian
logical_graph.py
compute_input_planes
compute_input_planes
Compute the number of input planes.
[ "Compute", "the", "number", "of", "input", "planes." ]
def compute_input_planes(input_channels, merging_strategy, inputs, abs_nodes): if len(inputs) == 0: return input_channels inplanes = 0 for i in inputs: if merging_strategy == EdgeMerge.CAT: inplanes += abs_nodes[i].outplanes else: inplanes = abs_nodes[i].outpl...
['def', 'compute_input_planes(input_channels,', 'merging_strategy,', 'inputs,', 'abs_nodes):', 'if', 'len(inputs)', '==', '0:', 'return', 'input_channels', 'inplanes', '=', '0', 'for', 'i', 'in', 'inputs:', 'if', 'merging_strategy', '==', 'EdgeMerge.CAT:', 'inplanes', '+=', 'abs_nodes[i].outplanes', 'else:', 'inplanes'...
963,002
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
videos_to_tfrecords.py
FindPatternFiles
FindPatternFiles
Recursively find all files matching a certain pattern.
[ "Recursively", "find", "all", "files", "matching", "a", "certain", "pattern." ]
def FindPatternFiles(path, view_pattern, errors): if not path: return None tf.logging.info("Recursively searching for files matching pattern '%s' in %s" % (view_pattern, path)) view_patt = re.compile('.*' + view_pattern) sequences = [] for (root, _, filenames) in os.walk(path, followlinks=Tr...
['def', 'FindPatternFiles(path,', 'view_pattern,', 'errors):', 'if', 'not', 'path:', 'return', 'None', 'tf.logging.info("Recursively', 'searching', 'for', 'files', 'matching', 'pattern', "'%s'", 'in', '%s"', '%', '(view_pattern,', 'path))', 'view_patt', '=', "re.compile('.*'", '+', 'view_pattern)', 'sequences', '=', '[...
29,573
Koushikl0l/Artificial-Intelligence
utils.py
arity
arity
The number of sub-expressions in this expression.
[ "The", "number", "of", "sub-expressions", "in", "this", "expression." ]
def arity(expression): if isinstance(expression, Expr): return len(expression.args) else: return 0
['def', 'arity(expression):', 'if', 'isinstance(expression,', 'Expr):', 'return', 'len(expression.args)', 'else:', 'return', '0']
120,266
rudranil723/mini-main
test_tgrep.py
TestSequenceFunctions.tests_rel_dominance
tests_rel_dominance
Test matching nodes based on dominance relations.
[ "Test", "matching", "nodes", "based", "on", "dominance", "relations." ]
def tests_rel_dominance(self): tree = ParentedTree.fromstring('(S (A (T x)) (B (N x)))') self.assertEqual(list(tgrep.tgrep_positions('* < T', [tree])), [[(0,)]]) self.assertEqual(list(tgrep.tgrep_positions('* < T > S', [tree])), [[(0,)]]) self.assertEqual(list(tgrep.tgrep_positions('* !< T', [tree])), [...
['def', 'tests_rel_dominance(self):', 'tree', '=', "ParentedTree.fromstring('(S", '(A', '(T', 'x))', '(B', '(N', "x)))')", "self.assertEqual(list(tgrep.tgrep_positions('*", '<', "T',", '[tree])),', '[[(0,)]])', "self.assertEqual(list(tgrep.tgrep_positions('*", '<', 'T', '>', "S',", '[tree])),', '[[(0,)]])', "self.asser...
321,868
utiasASRL/hero_radar_odometry
oxford.py
get_frames
get_frames
Retrieves all the file names within a path that match the given extension.
[ "Retrieves", "all", "the", "file", "names", "within", "a", "path", "that", "match", "the", "given", "extension." ]
def get_frames(path, extension='.png'): frames = [f for f in os.listdir(path) if extension in f] frames.sort() return frames
['def', 'get_frames(path,', "extension='.png'):", 'frames', '=', '[f', 'for', 'f', 'in', 'os.listdir(path)', 'if', 'extension', 'in', 'f]', 'frames.sort()', 'return', 'frames']
205,926
deepmind/meltingpot
paintball__king_of_the_hill.py
get_marking_line
get_marking_line
Return a line prefab to trace out the area of the hill.
[ "Return", "a", "line", "prefab", "to", "trace", "out", "the", "area", "of", "the", "hill." ]
def get_marking_line(orientation: str): if orientation == 'N': shape = LINE_NORTH elif orientation == 'E': shape = LINE_EAST elif orientation == 'S': shape = LINE_SOUTH elif orientation == 'W': shape = LINE_WEST else: raise ValueError(f'Unrecognized orientatio...
['def', 'get_marking_line(orientation:', 'str):', 'if', 'orientation', '==', "'N':", 'shape', '=', 'LINE_NORTH', 'elif', 'orientation', '==', "'E':", 'shape', '=', 'LINE_EAST', 'elif', 'orientation', '==', "'S':", 'shape', '=', 'LINE_SOUTH', 'elif', 'orientation', '==', "'W':", 'shape', '=', 'LINE_WEST', 'else:', 'rais...
285,393
bennylp/RL-Taxonomy
taxonomy.py
NodeBase.graph_rank
graph_rank
The rank of this node in the graph/cluster.
[ "The", "rank", "of", "this", "node", "in", "the", "graph/cluster." ]
def graph_rank(self): if self.year: if self.year >= 1980 and self.year < 2000: return '1980-90s' elif self.year >= 2000 and self.year < 2010: return '2000s' elif self.year >= 2010 and self.year <= 2015: return '2010-2015' else: return s...
['def', 'graph_rank(self):', 'if', 'self.year:', 'if', 'self.year', '>=', '1980', 'and', 'self.year', '<', '2000:', 'return', "'1980-90s'", 'elif', 'self.year', '>=', '2000', 'and', 'self.year', '<', '2010:', 'return', "'2000s'", 'elif', 'self.year', '>=', '2010', 'and', 'self.year', '<=', '2015:', 'return', "'2010-201...
860,829
awslabs/predictive-maintenance-using--
conftest.py
float_frame
float_frame
Fixture for DataFrame of floats with index of unique strings Columns are ['A', 'B', 'C', 'D'].
[ "Fixture", "for", "DataFrame", "of", "floats", "with", "index", "of", "unique", "strings", "Columns", "are", "['A',", "'B',", "'C',", "'D']." ]
def float_frame(): return DataFrame(tm.getSeriesData())
['def', 'float_frame():', 'return', 'DataFrame(tm.getSeriesData())']
824,127
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
T2TExperiment.continuous_decode
continuous_decode
Decode from dataset on new checkpoint.
[ "Decode", "from", "dataset", "on", "new", "checkpoint." ]
def continuous_decode(self): for _ in next_checkpoint(self._hparams.model_dir): self.decode()
['def', 'continuous_decode(self):', 'for', '_', 'in', 'next_checkpoint(self._hparams.model_dir):', 'self.decode()']
966,232
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
desc2code_test.py
Desc2codeTest.testCppPreprocess
testCppPreprocess
Check that the file correctly preprocess the code source.
[ "Check", "that", "the", "file", "correctly", "preprocess", "the", "code", "source." ]
def testCppPreprocess(self): cpp_pb = desc2code.ProgrammingDesc2codeCpp() self.assertEqual(cpp_pb.preprocess_target('firstline//comm1\nsecondline//comm2\n'), 'firstline secondline') self.assertEqual(cpp_pb.preprocess_target(CODE_CPP_IN), CODE_CPP_OUT) self.assertEqual(cpp_pb.preprocess_target(' not rem...
['def', 'testCppPreprocess(self):', 'cpp_pb', '=', 'desc2code.ProgrammingDesc2codeCpp()', "self.assertEqual(cpp_pb.preprocess_target('firstline//comm1\\nsecondline//comm2\\n'),", "'firstline", "secondline')", 'self.assertEqual(cpp_pb.preprocess_target(CODE_CPP_IN),', 'CODE_CPP_OUT)', "self.assertEqual(cpp_pb.preprocess...
964,854
blokbot-io/OpenBlok
bounding_areas.py
bounding_box_contains
bounding_box_contains
Returns true if the bounding box contains the point.
[ "Returns", "true", "if", "the", "bounding", "box", "contains", "the", "point." ]
def bounding_box_contains(top_left, bottom_right, point): if top_left[0] < point[0] < bottom_right[0] and top_left[1] < point[1] < bottom_right[1]: return True return False
['def', 'bounding_box_contains(top_left,', 'bottom_right,', 'point):', 'if', 'top_left[0]', '<', 'point[0]', '<', 'bottom_right[0]', 'and', 'top_left[1]', '<', 'point[1]', '<', 'bottom_right[1]:', 'return', 'True', 'return', 'False']
274,934
Alexander-Parker/youtube_nlp
bulk.py
_Bulk.gen_unordered
gen_unordered
Generate batches of operations, batched by type of operation, in arbitrary order.
[ "Generate", "batches", "of", "operations,", "batched", "by", "type", "of", "operation,", "in", "arbitrary", "order." ]
def gen_unordered(self): operations = [_Run(_INSERT), _Run(_UPDATE), _Run(_DELETE)] for (idx, (op_type, operation)) in enumerate(self.ops): operations[op_type].add(idx, operation) for run in operations: if run.ops: yield run
['def', 'gen_unordered(self):', 'operations', '=', '[_Run(_INSERT),', '_Run(_UPDATE),', '_Run(_DELETE)]', 'for', '(idx,', '(op_type,', 'operation))', 'in', 'enumerate(self.ops):', 'operations[op_type].add(idx,', 'operation)', 'for', 'run', 'in', 'operations:', 'if', 'run.ops:', 'yield', 'run']
970,272
sek788432/Waymo-2D-Object-Detection
single_task_trainer.py
SingleTaskTrainer.train_loop_end
train_loop_end
Actions to take once after a training loop.
[ "Actions", "to", "take", "once", "after", "a", "training", "loop." ]
def train_loop_end(self): with self.strategy.scope(): metrics = {metric.name: metric.result() for metric in self.metrics} metrics[self.train_loss.name] = self.train_loss.result() return metrics
['def', 'train_loop_end(self):', 'with', 'self.strategy.scope():', 'metrics', '=', '{metric.name:', 'metric.result()', 'for', 'metric', 'in', 'self.metrics}', 'metrics[self.train_loss.name]', '=', 'self.train_loss.result()', 'return', 'metrics']
973,857