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 |
|---|---|---|---|---|---|---|---|---|
enuguru/artificial_intelligence_and_machine_learning | backward.py | iternext | iternext | Get the `next` function for iterating over `seq`. | [
"Get",
"the",
"`next`",
"function",
"for",
"iterating",
"over",
"`seq`."
] | def iternext(seq):
return iter(seq).__next__ | ['def', 'iternext(seq):', 'return', 'iter(seq).__next__'] | 147,513 |
kourgeorge/project-origin | gui.py | OriginGUI.process_incoming_msg | process_incoming_msg | Handle all messages currently in the queue, if any. | [
"Handle",
"all",
"messages",
"currently",
"in",
"the",
"queue,",
"if",
"any."
] | def process_incoming_msg(self):
while self.msg_queue.qsize():
try:
self.refresh_data(self.msg_queue.get())
except Exception as exp:
print(str(exp))
pass | ['def', 'process_incoming_msg(self):', 'while', 'self.msg_queue.qsize():', 'try:', 'self.refresh_data(self.msg_queue.get())', 'except', 'Exception', 'as', 'exp:', 'print(str(exp))', 'pass'] | 295,592 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | metrics.py | sigmoid_cross_entropy_one_hot | sigmoid_cross_entropy_one_hot | Calculate sigmoid cross entropy for one-hot lanels and logits. | [
"Calculate",
"sigmoid",
"cross",
"entropy",
"for",
"one-hot",
"lanels",
"and",
"logits."
] | def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None):
with tf.variable_scope('sigmoid_cross_entropy_one_hot', values=[logits, labels]):
del weights_fn
cross_entropy = tf.losses.sigmoid_cross_entropy(multi_class_labels=labels, logits=logits)
return (cross_entropy, tf.constant(1.... | ['def', 'sigmoid_cross_entropy_one_hot(logits,', 'labels,', 'weights_fn=None):', 'with', "tf.variable_scope('sigmoid_cross_entropy_one_hot',", 'values=[logits,', 'labels]):', 'del', 'weights_fn', 'cross_entropy', '=', 'tf.losses.sigmoid_cross_entropy(multi_class_labels=labels,', 'logits=logits)', 'return', '(cross_entr... | 966,126 |
jerabaul29/Cylinder2DFlowControlDRL | Env2DCylinder.py | constant_profile | constant_profile | Time independent inflow profile. | [
"Time",
"independent",
"inflow",
"profile."
] | def constant_profile(mesh, degree):
bot = mesh.coordinates().min(axis=0)[1]
top = mesh.coordinates().max(axis=0)[1]
H = top - bot
Um = 1.5
return Expression(('-4*Um*(x[1]-bot)*(x[1]-top)/H/H', '0'), bot=bot, top=top, H=H, Um=Um, degree=degree, time=0) | ['def', 'constant_profile(mesh,', 'degree):', 'bot', '=', 'mesh.coordinates().min(axis=0)[1]', 'top', '=', 'mesh.coordinates().max(axis=0)[1]', 'H', '=', 'top', '-', 'bot', 'Um', '=', '1.5', 'return', "Expression(('-4*Um*(x[1]-bot)*(x[1]-top)/H/H',", "'0'),", 'bot=bot,', 'top=top,', 'H=H,', 'Um=Um,', 'degree=degree,', ... | 524,507 |
dpinney/eznlp | eznlp.py | subjects | subjects | Determine whether [string] is about the given subjects in [string_list]. | [
"Determine",
"whether",
"[string]",
"is",
"about",
"the",
"given",
"subjects",
"in",
"[string_list]."
] | def subjects(string, string_list):
zsl = text.ZeroShotClassifier()
res = zsl.predict(string, labels=string_list, include_labels=True, nli_template='The article is about {}.')
return res | ['def', 'subjects(string,', 'string_list):', 'zsl', '=', 'text.ZeroShotClassifier()', 'res', '=', 'zsl.predict(string,', 'labels=string_list,', 'include_labels=True,', "nli_template='The", 'article', 'is', 'about', "{}.')", 'return', 'res'] | 558,095 |
jbwang1997/CrossKD | det_tta.py | DetTTAModel.merge_preds | merge_preds | Merge batch predictions of enhanced data. | [
"Merge",
"batch",
"predictions",
"of",
"enhanced",
"data."
] | def merge_preds(self, data_samples_list: List[List[DetDataSample]]):
merged_data_samples = []
for data_samples in data_samples_list:
merged_data_samples.append(self._merge_single_sample(data_samples))
return merged_data_samples | ['def', 'merge_preds(self,', 'data_samples_list:', 'List[List[DetDataSample]]):', 'merged_data_samples', '=', '[]', 'for', 'data_samples', 'in', 'data_samples_list:', 'merged_data_samples.append(self._merge_single_sample(data_samples))', 'return', 'merged_data_samples'] | 491,601 |
ifwe/digsby | messagearea.py | should_show_time | should_show_time | Given two datetime objects, returns True if a "date status" should be shown between them. | [
"Given",
"two",
"datetime",
"objects,",
"returns",
"True",
"if",
"a",
"\"date",
"status\"",
"should",
"be",
"shown",
"between",
"them."
] | def should_show_time(tstamp1, tstamp2):
return fromutc(tstamp1).date() != fromutc(tstamp2).date() | ['def', 'should_show_time(tstamp1,', 'tstamp2):', 'return', 'fromutc(tstamp1).date()', '!=', 'fromutc(tstamp2).date()'] | 185,438 |
secretflow/secretflow | biclassification_eval_core.py | binary_clf_curve | binary_clf_curve | Calculate true and false positives per binary classification threshold (can be used for roc curve or precision/recall curve). | [
"Calculate",
"true",
"and",
"false",
"positives",
"per",
"binary",
"classification",
"threshold",
"(can",
"be",
"used",
"for",
"roc",
"curve",
"or",
"precision/recall",
"curve)."
] | def binary_clf_curve(sorted_pairs: jnp.array) -> Tuple[jnp.array, jnp.array, jnp.array]:
distinct_indices = jnp.where(jnp.diff(sorted_pairs[:, 1]))[0]
end = jnp.array([sorted_pairs.shape[0] - 1])
threshold_indices = jnp.hstack((distinct_indices, end))
thresholds = sorted_pairs[threshold_indices, 1]
... | ['def', 'binary_clf_curve(sorted_pairs:', 'jnp.array)', '->', 'Tuple[jnp.array,', 'jnp.array,', 'jnp.array]:', 'distinct_indices', '=', 'jnp.where(jnp.diff(sorted_pairs[:,', '1]))[0]', 'end', '=', 'jnp.array([sorted_pairs.shape[0]', '-', '1])', 'threshold_indices', '=', 'jnp.hstack((distinct_indices,', 'end))', 'thresh... | 856,673 |
dbash/zerowaste | regnet.py | pool2d | pool2d | Helper for building a pool2d layer. | [
"Helper",
"for",
"building",
"a",
"pool2d",
"layer."
] | def pool2d(k, *, stride=1):
assert k % 2 == 1, 'Only odd size kernels supported to avoid padding issues.'
return nn.MaxPool2d(k, stride=stride, padding=(k - 1) // 2) | ['def', 'pool2d(k,', '*,', 'stride=1):', 'assert', 'k', '%', '2', '==', '1,', "'Only", 'odd', 'size', 'kernels', 'supported', 'to', 'avoid', 'padding', "issues.'", 'return', 'nn.MaxPool2d(k,', 'stride=stride,', 'padding=(k', '-', '1)', '//', '2)'] | 971,453 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | rcsetup.py | validate_int | validate_int | Convert s to int or raise. | [
"Convert",
"s",
"to",
"int",
"or",
"raise."
] | def validate_int(s):
try:
return int(s)
except ValueError:
raise ValueError('Could not convert "%s" to int' % s) | ['def', 'validate_int(s):', 'try:', 'return', 'int(s)', 'except', 'ValueError:', 'raise', "ValueError('Could", 'not', 'convert', '"%s"', 'to', "int'", '%', 's)'] | 306,965 |
danamyu/hedgehog_detector | vgslspecs_test.py | VgslspecsTest.testXReduction | testXReduction | Test a heterogeneous series with reduction of x-dimension. | [
"Test",
"a",
"heterogeneous",
"series",
"with",
"reduction",
"of",
"x-dimension."
] | def testXReduction(self):
self.ExpectScaledSize('[Cr5,5,16 Mp2,2 Ct3,3,32 Mp3,3 Lfxs32 Lry64]', (self.batch_size, self.max_height / 6, 1, 64), 6) | ['def', 'testXReduction(self):', "self.ExpectScaledSize('[Cr5,5,16", 'Mp2,2', 'Ct3,3,32', 'Mp3,3', 'Lfxs32', "Lry64]',", '(self.batch_size,', 'self.max_height', '/', '6,', '1,', '64),', '6)'] | 590,515 |
instadeepai/jumanji | fakes_test.py | test_fake_multi_environment__step | test_fake_multi_environment__step | Validates the step function of the fake multi agent environment. | [
"Validates",
"the",
"step",
"function",
"of",
"the",
"fake",
"multi",
"agent",
"environment."
] | def test_fake_multi_environment__step(fake_multi_environment: fakes.FakeMultiEnvironment) -> None:
(state, timestep) = fake_multi_environment.reset(random.PRNGKey(0))
action = fake_multi_environment.action_spec().generate_value()
assert action.shape[0] == fake_multi_environment.num_agents
(next_state, t... | ['def', 'test_fake_multi_environment__step(fake_multi_environment:', 'fakes.FakeMultiEnvironment)', '->', 'None:', '(state,', 'timestep)', '=', 'fake_multi_environment.reset(random.PRNGKey(0))', 'action', '=', 'fake_multi_environment.action_spec().generate_value()', 'assert', 'action.shape[0]', '==', 'fake_multi_enviro... | 594,573 |
rudranil723/mini-main | remove_stale_contenttypes.py | NoFastDeleteCollector.can_fast_delete | can_fast_delete | Always load related objects to display them when showing confirmation. | [
"Always",
"load",
"related",
"objects",
"to",
"display",
"them",
"when",
"showing",
"confirmation."
] | def can_fast_delete(self, *args, **kwargs):
return False | ['def', 'can_fast_delete(self,', '*args,', '**kwargs):', 'return', 'False'] | 314,967 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | resnet_model.py | imagenet_resnet_v2_generator | imagenet_resnet_v2_generator | Generator for ImageNet ResNet v2 models. | [
"Generator",
"for",
"ImageNet",
"ResNet",
"v2",
"models."
] | def imagenet_resnet_v2_generator(block_fn, layers, num_classes, data_format=None):
if data_format is None:
data_format = 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last'
def model(inputs, is_training):
if data_format == 'channels_first':
inputs = tf.transpose(in... | ['def', 'imagenet_resnet_v2_generator(block_fn,', 'layers,', 'num_classes,', 'data_format=None):', 'if', 'data_format', 'is', 'None:', 'data_format', '=', "'channels_first'", 'if', 'tf.test.is_built_with_cuda()', 'else', "'channels_last'", 'def', 'model(inputs,', 'is_training):', 'if', 'data_format', '==', "'channels_f... | 20,173 |
jimtin/Stock_Comparison | tools.py | _Quiver.get_barbs | get_barbs | Creates x and y startpoint and endpoint pairs After finding the endpoint of each barb this zips startpoint and endpoint pairs to create 2 lists: x_values for barbs and y values for barbs :rtype: (list, list) barb_x, barb_y: list of startpoint and endpoint x_value pairs separated by a None to create the barb of the arro... | [
"Creates",
"x",
"and",
"y",
"startpoint",
"and",
"endpoint",
"pairs",
"After",
"finding",
"the",
"endpoint",
"of",
"each",
"barb",
"this",
"zips",
"startpoint",
"and",
"endpoint",
"pairs",
"to",
"create",
"2",
"lists:",
"x_values",
"for",
"barbs",
"and",
"y"... | def get_barbs(self):
self.end_x = [i + j for (i, j) in zip(self.x, self.u)]
self.end_y = [i + j for (i, j) in zip(self.y, self.v)]
empty = [None] * len(self.x)
barb_x = FigureFactory._flatten(zip(self.x, self.end_x, empty))
barb_y = FigureFactory._flatten(zip(self.y, self.end_y, empty))
return (... | ['def', 'get_barbs(self):', 'self.end_x', '=', '[i', '+', 'j', 'for', '(i,', 'j)', 'in', 'zip(self.x,', 'self.u)]', 'self.end_y', '=', '[i', '+', 'j', 'for', '(i,', 'j)', 'in', 'zip(self.y,', 'self.v)]', 'empty', '=', '[None]', '*', 'len(self.x)', 'barb_x', '=', 'FigureFactory._flatten(zip(self.x,', 'self.end_x,', 'emp... | 389,180 |
TrustAI/DeepConcolic | engine.py | Criterion.coverage | coverage | Returns a measure of the current coverage. | [
"Returns",
"a",
"measure",
"of",
"the",
"current",
"coverage."
] | def coverage(self) -> Coverage:
raise NotImplementedError | ['def', 'coverage(self)', '->', 'Coverage:', 'raise', 'NotImplementedError'] | 520,167 |
hamza-murad/AALU | discovery_v2.py | TableColumnHeaderIds.from_dict | from_dict | Initialize a TableColumnHeaderIds object from a json dictionary. | [
"Initialize",
"a",
"TableColumnHeaderIds",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds':
args = {}
valid_keys = ['id']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class TableColumnHeaderIds: ' + ', '.join(bad_keys))
if 'id' in _dict:
a... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'TableColumnHeaderIds':", 'args', '=', '{}', 'valid_keys', '=', "['id']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'TableColumnHeaderId... | 5,794 |
MushroomRL/mushroom-rl | sac.py | SACPolicy.entropy | entropy | Compute the entropy of the policy. | [
"Compute",
"the",
"entropy",
"of",
"the",
"policy."
] | def entropy(self, state=None):
return torch.mean(self.distribution(state).entropy()).detach().cpu().numpy().item() | ['def', 'entropy(self,', 'state=None):', 'return', 'torch.mean(self.distribution(state).entropy()).detach().cpu().numpy().item()'] | 265,961 |
6chaoran/nlp | dureader_eval.py | filter_dict | filter_dict | Filter a subset of the result_dict, where keys ends with 'key_tag'. | [
"Filter",
"a",
"subset",
"of",
"the",
"result_dict,",
"where",
"keys",
"ends",
"with",
"'key_tag'."
] | def filter_dict(result_dict, key_tag):
filtered = {}
for (k, v) in result_dict.items():
if k.endswith(key_tag):
filtered[k] = v
return filtered | ['def', 'filter_dict(result_dict,', 'key_tag):', 'filtered', '=', '{}', 'for', '(k,', 'v)', 'in', 'result_dict.items():', 'if', 'k.endswith(key_tag):', 'filtered[k]', '=', 'v', 'return', 'filtered'] | 808,781 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Base.toIter | toIter | Returns an iterator for the given value if it is a string. | [
"Returns",
"an",
"iterator",
"for",
"the",
"given",
"value",
"if",
"it",
"is",
"a",
"string."
] | def toIter(self, value):
try:
value + ''
except (TypeError,):
return value
else:
def wrapper(*a, **b):
yield value
return wrapper | ['def', 'toIter(self,', 'value):', 'try:', 'value', '+', "''", 'except', '(TypeError,):', 'return', 'value', 'else:', 'def', 'wrapper(*a,', '**b):', 'yield', 'value', 'return', 'wrapper'] | 10,829 |
zcablii/LSKNet | oriented_reppoints_head.py | OrientedRepPointsHead.get_targets | get_targets | Compute corresponding GT box and classification targets for proposals in initial stage. | [
"Compute",
"corresponding",
"GT",
"box",
"and",
"classification",
"targets",
"for",
"proposals",
"in",
"initial",
"stage."
] | def get_targets(self, proposals_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list=None, gt_labels_list=None, stage='init', label_channels=1, unmap_outputs=True):
assert stage in ['init', 'refine']
num_imgs = len(img_metas)
assert len(proposals_list) == len(valid_flag_list) == num_imgs
... | ['def', 'get_targets(self,', 'proposals_list,', 'valid_flag_list,', 'gt_bboxes_list,', 'img_metas,', 'gt_bboxes_ignore_list=None,', 'gt_labels_list=None,', "stage='init',", 'label_channels=1,', 'unmap_outputs=True):', 'assert', 'stage', 'in', "['init',", "'refine']", 'num_imgs', '=', 'len(img_metas)', 'assert', 'len(pr... | 616,134 |
enlite-ai/maze | random_policy.py | RandomPolicy.seed | seed | Seed the policy by setting the action space seeds. | [
"Seed",
"the",
"policy",
"by",
"setting",
"the",
"action",
"space",
"seeds."
] | def seed(self, seed: int) -> None:
rng = np.random.RandomState(seed)
for (key, action_space) in self.action_spaces_dict.items():
action_space.seed(MazeSeeding.generate_seed_from_random_state(rng))
pass | ['def', 'seed(self,', 'seed:', 'int)', '->', 'None:', 'rng', '=', 'np.random.RandomState(seed)', 'for', '(key,', 'action_space)', 'in', 'self.action_spaces_dict.items():', 'action_space.seed(MazeSeeding.generate_seed_from_random_state(rng))', 'pass'] | 646,498 |
palVikram/Machine-Learning-using-Python | opt.py | local_fill_sink | local_fill_sink | f(fill(a, b), fill(c, d), e) -> fill(c, fill(a, f(b, d, e))) f need to be an elemwise that isn't a fill. | [
"f(fill(a,",
"b),",
"fill(c,",
"d),",
"e)",
"->",
"fill(c,",
"fill(a,",
"f(b,",
"d,",
"e)))",
"f",
"need",
"to",
"be",
"an",
"elemwise",
"that",
"isn't",
"a",
"fill."
] | def local_fill_sink(node):
if not hasattr(node, 'op') or not isinstance(node.op, T.Elemwise) or node.op == T.fill:
return False
models = []
inputs = []
for input in node.inputs:
if input.owner and input.owner.op == T.fill:
models.append(input.owner.inputs[0])
inpu... | ['def', 'local_fill_sink(node):', 'if', 'not', 'hasattr(node,', "'op')", 'or', 'not', 'isinstance(node.op,', 'T.Elemwise)', 'or', 'node.op', '==', 'T.fill:', 'return', 'False', 'models', '=', '[]', 'inputs', '=', '[]', 'for', 'input', 'in', 'node.inputs:', 'if', 'input.owner', 'and', 'input.owner.op', '==', 'T.fill:', ... | 714,423 |
myothida/Supervised-Machine-Learning | test_loss.py | test_init_gradient_and_hessian_raises | test_init_gradient_and_hessian_raises | Test that init_gradient_and_hessian raises errors for invalid input. | [
"Test",
"that",
"init_gradient_and_hessian",
"raises",
"errors",
"for",
"invalid",
"input."
] | def test_init_gradient_and_hessian_raises(loss, params, err_msg):
loss = loss()
with pytest.raises((ValueError, TypeError), match=err_msg):
(gradient, hessian) = loss.init_gradient_and_hessian(n_samples=5, **params) | ['def', 'test_init_gradient_and_hessian_raises(loss,', 'params,', 'err_msg):', 'loss', '=', 'loss()', 'with', 'pytest.raises((ValueError,', 'TypeError),', 'match=err_msg):', '(gradient,', 'hessian)', '=', 'loss.init_gradient_and_hessian(n_samples=5,', '**params)'] | 364,906 |
google-research/rigl | mask_factory_test.py | MaskFactoryTest.test_mask_unsupported | test_mask_unsupported | Tests unsupported mask types. | [
"Tests",
"unsupported",
"mask",
"types."
] | def test_mask_unsupported(self):
with self.assertRaisesRegex(ValueError, 'Unknown mask type: unsupported'):
self._create_mask('unsupported') | ['def', 'test_mask_unsupported(self):', 'with', 'self.assertRaisesRegex(ValueError,', "'Unknown", 'mask', 'type:', "unsupported'):", "self._create_mask('unsupported')"] | 841,512 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | axis.py | Axis.pan | pan | Pan by *numsteps* (can be positive or negative). | [
"Pan",
"by",
"*numsteps*",
"(can",
"be",
"positive",
"or",
"negative)."
] | def pan(self, numsteps):
self.major.locator.pan(numsteps) | ['def', 'pan(self,', 'numsteps):', 'self.major.locator.pan(numsteps)'] | 306,333 |
google-research/scenic | test_detr_base_model.py | TestObjectDetectionWithMatchingModel.is_valid | is_valid | Helper function to assert that tensor `t` does not have `nan`, `inf`. | [
"Helper",
"function",
"to",
"assert",
"that",
"tensor",
"`t`",
"does",
"not",
"have",
"`nan`,",
"`inf`."
] | def is_valid(self, t):
self.assertFalse(jnp.isnan(t).any(), msg=f"Found nan's in {t}")
self.assertFalse(jnp.isinf(t).any(), msg=f"Found inf's in {t}") | ['def', 'is_valid(self,', 't):', 'self.assertFalse(jnp.isnan(t).any(),', 'msg=f"Found', "nan's", 'in', '{t}")', 'self.assertFalse(jnp.isinf(t).any(),', 'msg=f"Found', "inf's", 'in', '{t}")'] | 846,668 |
zihuitang/medical_AI_platform | __init__.py | Matcher.match_value | match_value | Try to match a single stored value (dv) with a supplied value (v). | [
"Try",
"to",
"match",
"a",
"single",
"stored",
"value",
"(dv)",
"with",
"a",
"supplied",
"value",
"(v)."
] | def match_value(self, k, dv, v):
if type(v) != type(dv):
result = False
elif type(dv) is not str or k not in self._partial_matches:
result = v == dv
else:
result = dv.find(v) >= 0
return result | ['def', 'match_value(self,', 'k,', 'dv,', 'v):', 'if', 'type(v)', '!=', 'type(dv):', 'result', '=', 'False', 'elif', 'type(dv)', 'is', 'not', 'str', 'or', 'k', 'not', 'in', 'self._partial_matches:', 'result', '=', 'v', '==', 'dv', 'else:', 'result', '=', 'dv.find(v)', '>=', '0', 'return', 'result'] | 283,844 |
google-research/scenic | box_utils.py | box_cxcywh_to_yxyx | box_cxcywh_to_yxyx | Converts boxes from [cx, cy, w, h] format into [y, x, y', x'] format. | [
"Converts",
"boxes",
"from",
"[cx,",
"cy,",
"w,",
"h]",
"format",
"into",
"[y,",
"x,",
"y',",
"x']",
"format."
] | def box_cxcywh_to_yxyx(x: Array, np_backbone: PyModule=jnp) -> Array:
(x_c, y_c, w, h) = np_backbone.split(x, 4, axis=-1)
b = [y_c - 0.5 * h, x_c - 0.5 * w, y_c + 0.5 * h, x_c + 0.5 * w]
return np_backbone.concatenate(b, axis=-1) | ['def', 'box_cxcywh_to_yxyx(x:', 'Array,', 'np_backbone:', 'PyModule=jnp)', '->', 'Array:', '(x_c,', 'y_c,', 'w,', 'h)', '=', 'np_backbone.split(x,', '4,', 'axis=-1)', 'b', '=', '[y_c', '-', '0.5', '*', 'h,', 'x_c', '-', '0.5', '*', 'w,', 'y_c', '+', '0.5', '*', 'h,', 'x_c', '+', '0.5', '*', 'w]', 'return', 'np_backbon... | 846,147 |
cesium-ml/cesium | periodic_model.py | periodic_model | periodic_model | Compute features related to the extreme points of the fitted Lomb Scargle model. | [
"Compute",
"features",
"related",
"to",
"the",
"extreme",
"points",
"of",
"the",
"fitted",
"Lomb",
"Scargle",
"model."
] | def periodic_model(lomb_model):
out_dict = {}
A = lomb_model['freq_fits'][0]['amplitude']
ph = lomb_model['freq_fits'][0]['rel_phase']
def model_f(t):
return A[0] * np.sin(2.0 * np.pi * t + ph[0]) + A[1] * np.sin(2.0 * np.pi * 2.0 * t + ph[1]) + A[2] * np.sin(2.0 * np.pi * 3.0 * t + ph[2]) + A[... | ['def', 'periodic_model(lomb_model):', 'out_dict', '=', '{}', 'A', '=', "lomb_model['freq_fits'][0]['amplitude']", 'ph', '=', "lomb_model['freq_fits'][0]['rel_phase']", 'def', 'model_f(t):', 'return', 'A[0]', '*', 'np.sin(2.0', '*', 'np.pi', '*', 't', '+', 'ph[0])', '+', 'A[1]', '*', 'np.sin(2.0', '*', 'np.pi', '*', '2... | 476,643 |
PaddlePaddle/PaddleSpeech | functional.py | mel_to_hz | mel_to_hz | Convert mel bin numbers to frequencies. | [
"Convert",
"mel",
"bin",
"numbers",
"to",
"frequencies."
] | def mel_to_hz(mel: Union[float, Tensor], htk: bool=False) -> Union[float, Tensor]:
if htk:
return 700.0 * (10.0 ** (mel / 2595.0) - 1.0)
f_min = 0.0
f_sp = 200.0 / 3
freqs = f_min + f_sp * mel
min_log_hz = 1000.0
min_log_mel = (min_log_hz - f_min) / f_sp
logstep = math.log(6.4) / 27.... | ['def', 'mel_to_hz(mel:', 'Union[float,', 'Tensor],', 'htk:', 'bool=False)', '->', 'Union[float,', 'Tensor]:', 'if', 'htk:', 'return', '700.0', '*', '(10.0', '**', '(mel', '/', '2595.0)', '-', '1.0)', 'f_min', '=', '0.0', 'f_sp', '=', '200.0', '/', '3', 'freqs', '=', 'f_min', '+', 'f_sp', '*', 'mel', 'min_log_hz', '=',... | 255,979 |
matthewkennedy5/RRNN | standard_data.py | get_train_stats | get_train_stats | Returns the mean and std of the train set as a 100-dimensional vector. | [
"Returns",
"the",
"mean",
"and",
"std",
"of",
"the",
"train",
"set",
"as",
"a",
"100-dimensional",
"vector."
] | def get_train_stats(dataset):
if os.path.isfile(NORM_STATS_FILE):
stats = pickle.load(open(NORM_STATS_FILE, 'rb'))
return stats[dataset]
print('[INFO] Calculating normalization statistics.')
ptb_train = PennTreebank('train', n_data=N_TRAIN, normalize=False)
sst_train = SST('train', n_dat... | ['def', 'get_train_stats(dataset):', 'if', 'os.path.isfile(NORM_STATS_FILE):', 'stats', '=', 'pickle.load(open(NORM_STATS_FILE,', "'rb'))", 'return', 'stats[dataset]', "print('[INFO]", 'Calculating', 'normalization', "statistics.')", 'ptb_train', '=', "PennTreebank('train',", 'n_data=N_TRAIN,', 'normalize=False)', 'sst... | 326,820 |
nosmokingbandit/watcher | plugins.py | ThreadManager.stop | stop | Release all threads and run all 'stop_thread' listeners. | [
"Release",
"all",
"threads",
"and",
"run",
"all",
"'stop_thread'",
"listeners."
] | def stop(self):
for (thread_ident, i) in self.threads.items():
self.bus.publish('stop_thread', i)
self.threads.clear() | ['def', 'stop(self):', 'for', '(thread_ident,', 'i)', 'in', 'self.threads.items():', "self.bus.publish('stop_thread',", 'i)', 'self.threads.clear()'] | 381,517 |
sktime/sktime | test_mlflow_sktime_model_export.py | test_pyfunc_raises_invalid_dict_value_type | test_pyfunc_raises_invalid_dict_value_type | Test pyfunc raises exception with invalid dict value type. | [
"Test",
"pyfunc",
"raises",
"exception",
"with",
"invalid",
"dict",
"value",
"type."
] | def test_pyfunc_raises_invalid_dict_value_type(auto_arima_model, model_path):
from mlflow.exceptions import MlflowException
from sktime.utils import mlflow_sktime
auto_arima_model.pyfunc_predict_conf = {'predict_method': 'predict'}
mlflow_sktime.save_model(sktime_model=auto_arima_model, path=model_path)... | ['def', 'test_pyfunc_raises_invalid_dict_value_type(auto_arima_model,', 'model_path):', 'from', 'mlflow.exceptions', 'import', 'MlflowException', 'from', 'sktime.utils', 'import', 'mlflow_sktime', 'auto_arima_model.pyfunc_predict_conf', '=', "{'predict_method':", "'predict'}", 'mlflow_sktime.save_model(sktime_model=aut... | 878,067 |
facebookresearch/CompilerGym | llvm_env_test.py | env | env | Create an LLVM environment. | [
"Create",
"an",
"LLVM",
"environment."
] | def env(request) -> CompilerEnv:
if request.param == 'local':
with gym.make('llvm-v0') as env:
yield env
else:
service = CompilerGymServiceConnection(llvm.LLVM_SERVICE_BINARY)
try:
with LlvmEnv(service=service.connection.url) as env:
yield env
... | ['def', 'env(request)', '->', 'CompilerEnv:', 'if', 'request.param', '==', "'local':", 'with', "gym.make('llvm-v0')", 'as', 'env:', 'yield', 'env', 'else:', 'service', '=', 'CompilerGymServiceConnection(llvm.LLVM_SERVICE_BINARY)', 'try:', 'with', 'LlvmEnv(service=service.connection.url)', 'as', 'env:', 'yield', 'env', ... | 135,843 |
unixpickle/anyrl-py | test_wrappers.py | test_downsample_rate_1 | test_downsample_rate_1 | Test DownsampleEnv with rate=1. | [
"Test",
"DownsampleEnv",
"with",
"rate=1."
] | def test_downsample_rate_1():
low = np.array([[1, 2], [3, 4]])
high = np.array([[3, 4], [5, 6]])
env = DownsampleEnv(ShapeEnv(low, high), 1)
assert (env.observation_space.low == low).all()
assert (env.observation_space.high == high).all() | ['def', 'test_downsample_rate_1():', 'low', '=', 'np.array([[1,', '2],', '[3,', '4]])', 'high', '=', 'np.array([[3,', '4],', '[5,', '6]])', 'env', '=', 'DownsampleEnv(ShapeEnv(low,', 'high),', '1)', 'assert', '(env.observation_space.low', '==', 'low).all()', 'assert', '(env.observation_space.high', '==', 'high).all()'] | 33,741 |
scikit-learn/scikit-learn | test_column_transformer.py | test_metadata_routing_no_fit_transform | test_metadata_routing_no_fit_transform | Test metadata routing when the sub-estimator doesn't implement ``fit_transform``. | [
"Test",
"metadata",
"routing",
"when",
"the",
"sub-estimator",
"doesn't",
"implement",
"``fit_transform``."
] | def test_metadata_routing_no_fit_transform():
class NoFitTransform(BaseEstimator):
def fit(self, X, y=None, sample_weight=None, metadata=None):
assert sample_weight
assert metadata
return self
def transform(self, X, sample_weight=None, metadata=None):
... | ['def', 'test_metadata_routing_no_fit_transform():', 'class', 'NoFitTransform(BaseEstimator):', 'def', 'fit(self,', 'X,', 'y=None,', 'sample_weight=None,', 'metadata=None):', 'assert', 'sample_weight', 'assert', 'metadata', 'return', 'self', 'def', 'transform(self,', 'X,', 'sample_weight=None,', 'metadata=None):', 'ass... | 852,904 |
rudranil723/mini-main | pycodestyle.py | stdin_get_value | stdin_get_value | Read the value from stdin. | [
"Read",
"the",
"value",
"from",
"stdin."
] | def stdin_get_value():
return TextIOWrapper(sys.stdin.buffer, errors='ignore').read() | ['def', 'stdin_get_value():', 'return', 'TextIOWrapper(sys.stdin.buffer,', "errors='ignore').read()"] | 314,001 |
deepmind/meltingpot | policy_factory.py | PolicyFactory.build | build | Returns a policy for the bot. | [
"Returns",
"a",
"policy",
"for",
"the",
"bot."
] | def build(self) -> policy.Policy:
return self._builder() | ['def', 'build(self)', '->', 'policy.Policy:', 'return', 'self._builder()'] | 285,536 |
43Carrig/recurrent_neural_networks_practice | hooks.py | InMemoryEvaluatorHook.after_create_session | after_create_session | Does first run which shows the eval metrics before training. | [
"Does",
"first",
"run",
"which",
"shows",
"the",
"eval",
"metrics",
"before",
"training."
] | def after_create_session(self, session, coord):
if ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS):
raise ValueError('InMemoryEvaluator does not support saveables other than global variables.')
self._var_name_to_train_var = {v.name: v for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)}
v... | ['def', 'after_create_session(self,', 'session,', 'coord):', 'if', 'ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS):', 'raise', "ValueError('InMemoryEvaluator", 'does', 'not', 'support', 'saveables', 'other', 'than', 'global', "variables.')", 'self._var_name_to_train_var', '=', '{v.name:', 'v', 'for', 'v', 'in', 'op... | 313,034 |
Kvatsx/Artificial-Intelligence-Assignments | magic_arguments.py | MagicArgumentParser.parse_argstring | parse_argstring | Split a string into an argument list and parse that argument list. | [
"Split",
"a",
"string",
"into",
"an",
"argument",
"list",
"and",
"parse",
"that",
"argument",
"list."
] | def parse_argstring(self, argstring):
argv = arg_split(argstring)
return self.parse_args(argv) | ['def', 'parse_argstring(self,', 'argstring):', 'argv', '=', 'arg_split(argstring)', 'return', 'self.parse_args(argv)'] | 38,154 |
PacktPublishing/Python-Reinforcement-Learning-Projects | mcts.py | MCTreeSearchNode.is_done | is_done | True if the last two moves were Pass or if the board_state is at a move greater than the max depth. | [
"True",
"if",
"the",
"last",
"two",
"moves",
"were",
"Pass",
"or",
"if",
"the",
"board_state",
"is",
"at",
"a",
"move",
"greater",
"than",
"the",
"max",
"depth."
] | def is_done(self):
return self.board_state.is_game_over() or self.board_state.n >= MCTSPARAMETERS.MAX_DEPTH | ['def', 'is_done(self):', 'return', 'self.board_state.is_game_over()', 'or', 'self.board_state.n', '>=', 'MCTSPARAMETERS.MAX_DEPTH'] | 297,460 |
clips/pattern | tree.py | Chunk.modifiers | modifiers | For verb phrases (VP), yields a list of the nearest adjectives and adverbs. | [
"For",
"verb",
"phrases",
"(VP),",
"yields",
"a",
"list",
"of",
"the",
"nearest",
"adjectives",
"and",
"adverbs."
] | def modifiers(self):
if self._modifiers is None:
is_modifier = lambda ch: ch.type in ('ADJP', 'ADVP') and ch.relation is None
for chunk in self.sentence.chunks:
chunk._modifiers = []
for chunk in filter(is_modifier, self.sentence.chunks):
anchor = chunk.nearest('VP')
... | ['def', 'modifiers(self):', 'if', 'self._modifiers', 'is', 'None:', 'is_modifier', '=', 'lambda', 'ch:', 'ch.type', 'in', "('ADJP',", "'ADVP')", 'and', 'ch.relation', 'is', 'None', 'for', 'chunk', 'in', 'self.sentence.chunks:', 'chunk._modifiers', '=', '[]', 'for', 'chunk', 'in', 'filter(is_modifier,', 'self.sentence.c... | 764,781 |
vt257/allnews-am | WikiExtractor.py | dropSpans | dropSpans | Drop from text the blocks identified in :param spans:, possibly nested. | [
"Drop",
"from",
"text",
"the",
"blocks",
"identified",
"in",
":param",
"spans:,",
"possibly",
"nested."
] | def dropSpans(spans, text):
spans.sort()
res = ''
offset = 0
for (s, e) in spans:
if offset <= s:
if offset < s:
res += text[offset:s]
offset = e
res += text[offset:]
return res | ['def', 'dropSpans(spans,', 'text):', 'spans.sort()', 'res', '=', "''", 'offset', '=', '0', 'for', '(s,', 'e)', 'in', 'spans:', 'if', 'offset', '<=', 's:', 'if', 'offset', '<', 's:', 'res', '+=', 'text[offset:s]', 'offset', '=', 'e', 'res', '+=', 'text[offset:]', 'return', 'res'] | 414,694 |
pdebench/PDEBench | sim_ns_incomp_2d.py | ns_sim | ns_sim | Run the actual simulation. | [
"Run",
"the",
"actual",
"simulation."
] | def ns_sim(seed: int, label: Optional[str]=None, sim_name: str='ns_sim_2d', particle_extrapolation: str='BOUNDARY', velocity_extrapolation: str='ZERO', NU: float=0.01, scale: float=10.0, smoothness: float=3.0, grid_size=(100, 100), enable_gravity: bool=False, enable_obstacles: bool=False, force_extrapolation: str='ZERO... | ['def', 'ns_sim(seed:', 'int,', 'label:', 'Optional[str]=None,', 'sim_name:', "str='ns_sim_2d',", 'particle_extrapolation:', "str='BOUNDARY',", 'velocity_extrapolation:', "str='ZERO',", 'NU:', 'float=0.01,', 'scale:', 'float=10.0,', 'smoothness:', 'float=3.0,', 'grid_size=(100,', '100),', 'enable_gravity:', 'bool=False... | 765,858 |
lebrice/Sequoia | objects.py | Actions.actions_np | actions_np | Returns the prediction/action as a numpy array. | [
"Returns",
"the",
"prediction/action",
"as",
"a",
"numpy",
"array."
] | def actions_np(self) -> np.ndarray:
if isinstance(self.y_pred, Tensor):
return self.y_pred.detach().cpu().numpy()
return np.asarray(self.y_pred) | ['def', 'actions_np(self)', '->', 'np.ndarray:', 'if', 'isinstance(self.y_pred,', 'Tensor):', 'return', 'self.y_pred.detach().cpu().numpy()', 'return', 'np.asarray(self.y_pred)'] | 344,475 |
upskyy/ContextNet | model.py | ContextNet.forward | forward | Forward propagate a `inputs` for label encoder. | [
"Forward",
"propagate",
"a",
"`inputs`",
"for",
"label",
"encoder."
] | def forward(self, inputs: Tensor, input_lengths: Tensor, targets: Tensor, target_lengths: Tensor) -> Tensor:
(encoder_output, encoder_output_lengths) = self.encoder(inputs, input_lengths)
self.decoder.rnn.flatten_parameters()
(decoder_output, _) = self.decoder(targets, target_lengths)
output = self.join... | ['def', 'forward(self,', 'inputs:', 'Tensor,', 'input_lengths:', 'Tensor,', 'targets:', 'Tensor,', 'target_lengths:', 'Tensor)', '->', 'Tensor:', '(encoder_output,', 'encoder_output_lengths)', '=', 'self.encoder(inputs,', 'input_lengths)', 'self.decoder.rnn.flatten_parameters()', '(decoder_output,', '_)', '=', 'self.de... | 136,370 |
megvii-research/MSCL | test_head.py | test_x3d_head | test_x3d_head | Test loss method, layer construction, attributes and forward function in x3d head. | [
"Test",
"loss",
"method,",
"layer",
"construction,",
"attributes",
"and",
"forward",
"function",
"in",
"x3d",
"head."
] | def test_x3d_head():
x3d_head = X3DHead(in_channels=432, num_classes=4, fc1_bias=False)
x3d_head.init_weights()
assert x3d_head.num_classes == 4
assert x3d_head.dropout_ratio == 0.5
assert x3d_head.in_channels == 432
assert x3d_head.init_std == 0.01
assert isinstance(x3d_head.dropout, nn.Dro... | ['def', 'test_x3d_head():', 'x3d_head', '=', 'X3DHead(in_channels=432,', 'num_classes=4,', 'fc1_bias=False)', 'x3d_head.init_weights()', 'assert', 'x3d_head.num_classes', '==', '4', 'assert', 'x3d_head.dropout_ratio', '==', '0.5', 'assert', 'x3d_head.in_channels', '==', '432', 'assert', 'x3d_head.init_std', '==', '0.01... | 264,987 |
matsu0228/nlp-jp | client_options.py | ClientOptions.heartbeat_frequency | heartbeat_frequency | The monitoring frequency in seconds. | [
"The",
"monitoring",
"frequency",
"in",
"seconds."
] | def heartbeat_frequency(self):
return self.__heartbeat_frequency | ['def', 'heartbeat_frequency(self):', 'return', 'self.__heartbeat_frequency'] | 804,743 |
Kvatsx/Artificial-Intelligence-Assignments | kernelapp.py | IPKernelApp.init_io | init_io | Redirect input streams and set a display hook. | [
"Redirect",
"input",
"streams",
"and",
"set",
"a",
"display",
"hook."
] | def init_io(self):
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
if sys.stdout is not None:
sys.stdout.flush()
e_stdout = None if self.quiet else sys.__stdout__
e_stderr = None if self.quiet else sys.__stderr__
sys.stdout = ou... | ['def', 'init_io(self):', 'if', 'self.outstream_class:', 'outstream_factory', '=', 'import_item(str(self.outstream_class))', 'if', 'sys.stdout', 'is', 'not', 'None:', 'sys.stdout.flush()', 'e_stdout', '=', 'None', 'if', 'self.quiet', 'else', 'sys.__stdout__', 'e_stderr', '=', 'None', 'if', 'self.quiet', 'else', 'sys.__... | 37,698 |
RasaHQ/rasa | action.py | Action.event_for_successful_execution | event_for_successful_execution | Event which should be logged for the successful execution of this action. | [
"Event",
"which",
"should",
"be",
"logged",
"for",
"the",
"successful",
"execution",
"of",
"this",
"action."
] | def event_for_successful_execution(self, prediction: PolicyPrediction) -> ActionExecuted:
return ActionExecuted(self.name(), prediction.policy_name, prediction.max_confidence, hide_rule_turn=prediction.hide_rule_turn, metadata=prediction.action_metadata) | ['def', 'event_for_successful_execution(self,', 'prediction:', 'PolicyPrediction)', '->', 'ActionExecuted:', 'return', 'ActionExecuted(self.name(),', 'prediction.policy_name,', 'prediction.max_confidence,', 'hide_rule_turn=prediction.hide_rule_turn,', 'metadata=prediction.action_metadata)'] | 836,775 |
weimin17/Object-Detection_HelmetDetection | mst_ops_test.py | MstOpsTest.testLogPartitionFunctionOneTree | testLogPartitionFunctionOneTree | Tests the log partition function with one feasible tree with score 1. | [
"Tests",
"the",
"log",
"partition",
"function",
"with",
"one",
"feasible",
"tree",
"with",
"score",
"1."
] | def testLogPartitionFunctionOneTree(self):
with self.test_session():
for forest in [False, True]:
pad = 12345.6
scores = tf.constant([[[1, pad, pad], [pad, pad, pad], [pad, pad, pad]], [[1, 0, pad], [1, 0, pad], [pad, pad, pad]], [[1, 0, 0], [1, 0, 0], [0, 1, 0]]], tf.float64)
... | ['def', 'testLogPartitionFunctionOneTree(self):', 'with', 'self.test_session():', 'for', 'forest', 'in', '[False,', 'True]:', 'pad', '=', '12345.6', 'scores', '=', 'tf.constant([[[1,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad]],', '[[1,', '0,', 'pad],', '[1,', '0,', 'pad],', '[pad,', 'pad,', 'pa... | 760,186 |
Nora0000/ADL_unsupervised_learning | prepare_data.py | segment_data | segment_data | load data frame and organize them by segments. | [
"load",
"data",
"frame",
"and",
"organize",
"them",
"by",
"segments."
] | def segment_data(data_path, seg_path, sampleRate=50, aug_number=None):
data_complex = np.load(os.path.join(data_path, 'data_complex.npy'))
times = np.loadtxt(os.path.join(data_path, 'times.txt'))
times_dt = [datetime.datetime.fromtimestamp(time) for time in times]
seg_all = [[], [], [], []]
(seg_all... | ['def', 'segment_data(data_path,', 'seg_path,', 'sampleRate=50,', 'aug_number=None):', 'data_complex', '=', 'np.load(os.path.join(data_path,', "'data_complex.npy'))", 'times', '=', 'np.loadtxt(os.path.join(data_path,', "'times.txt'))", 'times_dt', '=', '[datetime.datetime.fromtimestamp(time)', 'for', 'time', 'in', 'tim... | 40,065 |
myothida/Supervised-Machine-Learning | test_loss.py | test_loss_boundary_y_pred | test_loss_boundary_y_pred | Test boundaries of y_pred for loss functions. | [
"Test",
"boundaries",
"of",
"y_pred",
"for",
"loss",
"functions."
] | def test_loss_boundary_y_pred(loss, y_pred_success, y_pred_fail):
for y in y_pred_success:
assert loss.in_y_pred_range(np.array([y]))
for y in y_pred_fail:
assert not loss.in_y_pred_range(np.array([y])) | ['def', 'test_loss_boundary_y_pred(loss,', 'y_pred_success,', 'y_pred_fail):', 'for', 'y', 'in', 'y_pred_success:', 'assert', 'loss.in_y_pred_range(np.array([y]))', 'for', 'y', 'in', 'y_pred_fail:', 'assert', 'not', 'loss.in_y_pred_range(np.array([y]))'] | 364,890 |
Katja-M/Python_NaturalLanguageProcessing | __init__.py | is_scalar_or_string | is_scalar_or_string | Return whether the given object is a scalar or string like. | [
"Return",
"whether",
"the",
"given",
"object",
"is",
"a",
"scalar",
"or",
"string",
"like."
] | def is_scalar_or_string(val):
return isinstance(val, str) or not np.iterable(val) | ['def', 'is_scalar_or_string(val):', 'return', 'isinstance(val,', 'str)', 'or', 'not', 'np.iterable(val)'] | 865,289 |
arshpreetsingh/quantopian-machinelearning | interface.py | Waker.consume | consume | Called after the listen has woken up to do any necessary cleanup. | [
"Called",
"after",
"the",
"listen",
"has",
"woken",
"up",
"to",
"do",
"any",
"necessary",
"cleanup."
] | def consume(self):
raise NotImplementedError() | ['def', 'consume(self):', 'raise', 'NotImplementedError()'] | 834,257 |
RLE-Foundation/rllte | drqv2.py | DrQv2.update_critic | update_critic | Update the critic network. | [
"Update",
"the",
"critic",
"network."
] | def update_critic(self, obs: th.Tensor, actions: th.Tensor, rewards: th.Tensor, discount: th.Tensor, next_obs: th.Tensor) -> None:
with th.no_grad():
dist = self.policy.get_dist(next_obs)
next_actions = dist.sample(clip=self.stddev_clip)
next_obs_actions = th.concat([next_obs, next_actions],... | ['def', 'update_critic(self,', 'obs:', 'th.Tensor,', 'actions:', 'th.Tensor,', 'rewards:', 'th.Tensor,', 'discount:', 'th.Tensor,', 'next_obs:', 'th.Tensor)', '->', 'None:', 'with', 'th.no_grad():', 'dist', '=', 'self.policy.get_dist(next_obs)', 'next_actions', '=', 'dist.sample(clip=self.stddev_clip)', 'next_obs_actio... | 333,449 |
jimtin/Stock_Comparison | tdi.py | TimedeltaIndex.days | days | Number of days for each element. | [
"Number",
"of",
"days",
"for",
"each",
"element."
] | def days(self):
return self._get_field('days') | ['def', 'days(self):', 'return', "self._get_field('days')"] | 388,306 |
ChrisFugl/Intrusing-Detection-System-Attack | data.py | get_content_columns | get_content_columns | Returns the content column names. | [
"Returns",
"the",
"content",
"column",
"names."
] | def get_content_columns():
return _CONTENT | ['def', 'get_content_columns():', 'return', '_CONTENT'] | 576,435 |
MycroftAI/mycroft-core | test_mycroft_skill_get_response.py | TestMycroftSkillGetResponse.test_get_response_no_dialog | test_get_response_no_dialog | Check that when no dialog/text is provided listening is triggered. | [
"Check",
"that",
"when",
"no",
"dialog/text",
"is",
"provided",
"listening",
"is",
"triggered."
] | def test_get_response_no_dialog(self):
skill = create_skill()
skill._wait_response = mock.Mock()
skill.speak_dialog = mock.Mock()
expected_response = 'ice creamr please'
skill._wait_response.return_value = expected_response
response = skill.get_response()
self.assertEqual(response, expected_... | ['def', 'test_get_response_no_dialog(self):', 'skill', '=', 'create_skill()', 'skill._wait_response', '=', 'mock.Mock()', 'skill.speak_dialog', '=', 'mock.Mock()', 'expected_response', '=', "'ice", 'creamr', "please'", 'skill._wait_response.return_value', '=', 'expected_response', 'response', '=', 'skill.get_response()... | 290,947 |
tensorflow/agents | environment_utilities.py | tf_compute_optimal_reward | tf_compute_optimal_reward | TF wrapper around `compute_optimal_reward` to be used in `tf_metrics`. | [
"TF",
"wrapper",
"around",
"`compute_optimal_reward`",
"to",
"be",
"used",
"in",
"`tf_metrics`."
] | def tf_compute_optimal_reward(observation, per_action_reward_fns, enable_noise=False):
compute_optimal_reward_fn = functools.partial(compute_optimal_reward, per_action_reward_fns=per_action_reward_fns, enable_noise=enable_noise)
return tf.py_function(compute_optimal_reward_fn, [observation], tf.float32) | ['def', 'tf_compute_optimal_reward(observation,', 'per_action_reward_fns,', 'enable_noise=False):', 'compute_optimal_reward_fn', '=', 'functools.partial(compute_optimal_reward,', 'per_action_reward_fns=per_action_reward_fns,', 'enable_noise=enable_noise)', 'return', 'tf.py_function(compute_optimal_reward_fn,', '[observ... | 23,292 |
triaquae/triaquae | layer.py | Layer.srs | srs | Returns the Spatial Reference used in this Layer. | [
"Returns",
"the",
"Spatial",
"Reference",
"used",
"in",
"this",
"Layer."
] | def srs(self):
try:
ptr = capi.get_layer_srs(self.ptr)
return SpatialReference(srs_api.clone_srs(ptr))
except SRSException:
return None | ['def', 'srs(self):', 'try:', 'ptr', '=', 'capi.get_layer_srs(self.ptr)', 'return', 'SpatialReference(srs_api.clone_srs(ptr))', 'except', 'SRSException:', 'return', 'None'] | 357,623 |
jialeli1/lidarseg3d | data_classes.py | EvalBoxes.all | all | Returns all EvalBoxes in a list. | [
"Returns",
"all",
"EvalBoxes",
"in",
"a",
"list."
] | def all(self) -> List[EvalBoxType]:
ab = []
for sample_token in self.sample_tokens:
ab.extend(self[sample_token])
return ab | ['def', 'all(self)', '->', 'List[EvalBoxType]:', 'ab', '=', '[]', 'for', 'sample_token', 'in', 'self.sample_tokens:', 'ab.extend(self[sample_token])', 'return', 'ab'] | 601,689 |
lebrice/Sequoia | wrappers.py | relabel | relabel | Relabels the given data (from a task) so they all share the same action space. | [
"Relabels",
"the",
"given",
"data",
"(from",
"a",
"task)",
"so",
"they",
"all",
"share",
"the",
"same",
"action",
"space."
] | def relabel(data: Any, mapping: Dict[int, int]=None) -> Any:
raise NotImplementedError(f"Don't know how to relabel {data} of type {type(data)}") | ['def', 'relabel(data:', 'Any,', 'mapping:', 'Dict[int,', 'int]=None)', '->', 'Any:', 'raise', 'NotImplementedError(f"Don\'t', 'know', 'how', 'to', 'relabel', '{data}', 'of', 'type', '{type(data)}")'] | 349,679 |
googleinterns/wss | mobilenet_v3.py | mbv3_fused | mbv3_fused | Defines a single Mobilenet V3 convolution block. | [
"Defines",
"a",
"single",
"Mobilenet",
"V3",
"convolution",
"block."
] | def mbv3_fused(ef, n, k, s=1, **kwargs):
expansion_fn = functools.partial(slim.conv2d, kernel_size=k, stride=s)
return mbv3_op(ef, n, k=1, s=s, depthwise_location=None, expansion_fn=expansion_fn, **kwargs) | ['def', 'mbv3_fused(ef,', 'n,', 'k,', 's=1,', '**kwargs):', 'expansion_fn', '=', 'functools.partial(slim.conv2d,', 'kernel_size=k,', 'stride=s)', 'return', 'mbv3_op(ef,', 'n,', 'k=1,', 's=s,', 'depthwise_location=None,', 'expansion_fn=expansion_fn,', '**kwargs)'] | 960,958 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | pydoc.py | isdata | isdata | Check if an object is of a type that probably means it's data. | [
"Check",
"if",
"an",
"object",
"is",
"of",
"a",
"type",
"that",
"probably",
"means",
"it's",
"data."
] | def isdata(object):
return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)) | ['def', 'isdata(object):', 'return', 'not', '(inspect.ismodule(object)', 'or', 'inspect.isclass(object)', 'or', 'inspect.isroutine(object)', 'or', 'inspect.isframe(object)', 'or', 'inspect.istraceback(object)', 'or', 'inspect.iscode(object))'] | 429,278 |
enlite-ai/maze | test_core_envs_and_policies_basics.py | test_random_sampling | test_random_sampling | tests random sampling in hydra configured environments. | [
"tests",
"random",
"sampling",
"in",
"hydra",
"configured",
"environments."
] | def test_random_sampling(config_module: str, config: str, overrides: Dict[str, str]):
check_random_sampling(config_module, config, overrides) | ['def', 'test_random_sampling(config_module:', 'str,', 'config:', 'str,', 'overrides:', 'Dict[str,', 'str]):', 'check_random_sampling(config_module,', 'config,', 'overrides)'] | 647,130 |
zhang614/MicroGrid | layout.py | TextLayout.delete | delete | Remove this layout from its batch. | [
"Remove",
"this",
"layout",
"from",
"its",
"batch."
] | def delete(self):
for vertex_list in self._vertex_lists:
vertex_list.delete()
self._vertex_lists = []
for box in self._boxes:
box.delete(self) | ['def', 'delete(self):', 'for', 'vertex_list', 'in', 'self._vertex_lists:', 'vertex_list.delete()', 'self._vertex_lists', '=', '[]', 'for', 'box', 'in', 'self._boxes:', 'box.delete(self)'] | 668,898 |
bytedance/DeepSolid | utils.py | make_func_args | make_func_args | Correctly puts all arguments to the function together. | [
"Correctly",
"puts",
"all",
"arguments",
"to",
"the",
"function",
"together."
] | def make_func_args(params, func_state, rng, batch, has_state: bool, has_rng: bool):
func_args = (params,)
if has_state:
if func_state is None:
raise ValueError('The `func_state` is None, but the argument `has_state` is True.')
func_args += (func_state,)
if has_rng:
if rng... | ['def', 'make_func_args(params,', 'func_state,', 'rng,', 'batch,', 'has_state:', 'bool,', 'has_rng:', 'bool):', 'func_args', '=', '(params,)', 'if', 'has_state:', 'if', 'func_state', 'is', 'None:', 'raise', "ValueError('The", '`func_state`', 'is', 'None,', 'but', 'the', 'argument', '`has_state`', 'is', "True.')", 'func... | 539,976 |
PaddlePaddle/PaddleSpeech | handlers.py | ignore_and_stop | ignore_and_stop | Call in an exception handler to ignore any exception and stop further processing. | [
"Call",
"in",
"an",
"exception",
"handler",
"to",
"ignore",
"any",
"exception",
"and",
"stop",
"further",
"processing."
] | def ignore_and_stop(exn):
return False | ['def', 'ignore_and_stop(exn):', 'return', 'False'] | 276,470 |
open-mmlab/mmdetection3d | rotate_iou.py | inter | inter | Compute intersection of two rotated boxes. | [
"Compute",
"intersection",
"of",
"two",
"rotated",
"boxes."
] | def inter(rbbox1, rbbox2):
corners1 = cuda.local.array((8,), dtype=numba.float32)
corners2 = cuda.local.array((8,), dtype=numba.float32)
intersection_corners = cuda.local.array((16,), dtype=numba.float32)
rbbox_to_corners(corners1, rbbox1)
rbbox_to_corners(corners2, rbbox2)
num_intersection = qu... | ['def', 'inter(rbbox1,', 'rbbox2):', 'corners1', '=', 'cuda.local.array((8,),', 'dtype=numba.float32)', 'corners2', '=', 'cuda.local.array((8,),', 'dtype=numba.float32)', 'intersection_corners', '=', 'cuda.local.array((16,),', 'dtype=numba.float32)', 'rbbox_to_corners(corners1,', 'rbbox1)', 'rbbox_to_corners(corners2,'... | 631,778 |
LiWentomng/OrientedRepPoints | single_level.py | SingleRoIExtractor.num_inputs | num_inputs | int: Input feature map levels. | [
"int:",
"Input",
"feature",
"map",
"levels."
] | def num_inputs(self):
return len(self.featmap_strides) | ['def', 'num_inputs(self):', 'return', 'len(self.featmap_strides)'] | 776,600 |
google-research/rigl | sparse_optimizers.py | SparseDNWOptimizer.replace_with_masked_weights | replace_with_masked_weights | Replaces masked variables with masked weights. | [
"Replaces",
"masked",
"variables",
"with",
"masked",
"weights."
] | def replace_with_masked_weights(self, var_list):
weight2masked_weights = {w.name: mw for (w, mw) in zip(self.get_weights(), self.get_masked_weights())}
updated_var_list = [weight2masked_weights.get(w.name, w) for w in var_list]
return updated_var_list | ['def', 'replace_with_masked_weights(self,', 'var_list):', 'weight2masked_weights', '=', '{w.name:', 'mw', 'for', '(w,', 'mw)', 'in', 'zip(self.get_weights(),', 'self.get_masked_weights())}', 'updated_var_list', '=', '[weight2masked_weights.get(w.name,', 'w)', 'for', 'w', 'in', 'var_list]', 'return', 'updated_var_list'... | 841,338 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | cm.py | ScalarMappable.get_alpha | get_alpha | Returns ------- alpha : float Always returns 1. | [
"Returns",
"-------",
"alpha",
":",
"float",
"Always",
"returns",
"1."
] | def get_alpha(self):
return 1.0 | ['def', 'get_alpha(self):', 'return', '1.0'] | 450,287 |
PartnershipOnAI/safelife | safelife_game.py | GameState.height | height | Height of the game board. | [
"Height",
"of",
"the",
"game",
"board."
] | def height(self):
return self.board.shape[0] | ['def', 'height(self):', 'return', 'self.board.shape[0]'] | 829,241 |
yandex-research/ddpm-segmentation | feature_extractors.py | create_feature_extractor | create_feature_extractor | Create the feature extractor for <model_type> architecture. | [
"Create",
"the",
"feature",
"extractor",
"for",
"<model_type>",
"architecture."
] | def create_feature_extractor(model_type, **kwargs):
if model_type == 'ddpm':
print('Creating DDPM Feature Extractor...')
feature_extractor = FeatureExtractorDDPM(**kwargs)
elif model_type == 'mae':
print('Creating MAE Feature Extractor...')
feature_extractor = FeatureExtractorMAE... | ['def', 'create_feature_extractor(model_type,', '**kwargs):', 'if', 'model_type', '==', "'ddpm':", "print('Creating", 'DDPM', 'Feature', "Extractor...')", 'feature_extractor', '=', 'FeatureExtractorDDPM(**kwargs)', 'elif', 'model_type', '==', "'mae':", "print('Creating", 'MAE', 'Feature', "Extractor...')", 'feature_ext... | 498,946 |
rlworkgroup/garage | ppo_memorize_digits.py | ppo_memorize_digits | ppo_memorize_digits | Train PPO on MemorizeDigits-v0 environment. | [
"Train",
"PPO",
"on",
"MemorizeDigits-v0",
"environment."
] | def ppo_memorize_digits(ctxt=None, seed=1, batch_size=4000, max_episode_length=100):
set_seed(seed)
with TFTrainer(ctxt) as trainer:
env = normalize(GymEnv('MemorizeDigits-v0', is_image=True, max_episode_length=max_episode_length))
policy = CategoricalCNNPolicy(env_spec=env.spec, filters=((32, (... | ['def', 'ppo_memorize_digits(ctxt=None,', 'seed=1,', 'batch_size=4000,', 'max_episode_length=100):', 'set_seed(seed)', 'with', 'TFTrainer(ctxt)', 'as', 'trainer:', 'env', '=', "normalize(GymEnv('MemorizeDigits-v0',", 'is_image=True,', 'max_episode_length=max_episode_length))', 'policy', '=', 'CategoricalCNNPolicy(env_s... | 200,275 |
voxel51/fiftyone | stages.py | FilterLabels.only_matches | only_matches | Whether to only include samples that match the filter. | [
"Whether",
"to",
"only",
"include",
"samples",
"that",
"match",
"the",
"filter."
] | def only_matches(self):
return self._only_matches | ['def', 'only_matches(self):', 'return', 'self._only_matches'] | 583,302 |
IsoNet-cryoET/IsoNet | metadata.py | MetaData.addData | addData | Add new items to internal data. | [
"Add",
"new",
"items",
"to",
"internal",
"data."
] | def addData(self, data):
for item in data:
self.addItem(item) | ['def', 'addData(self,', 'data):', 'for', 'item', 'in', 'data:', 'self.addItem(item)'] | 246,770 |
microsoft/nni | qat_quantizer.py | update_ema | update_ema | Exponential moving average method. | [
"Exponential",
"moving",
"average",
"method."
] | def update_ema(biased_ema: Tensor, current_val: Tensor, decay: float):
return biased_ema * decay + (1 - decay) * current_val | ['def', 'update_ema(biased_ema:', 'Tensor,', 'current_val:', 'Tensor,', 'decay:', 'float):', 'return', 'biased_ema', '*', 'decay', '+', '(1', '-', 'decay)', '*', 'current_val'] | 728,500 |
Eric3911/OpenAGI | pipeline.py | DataPipeline.repeat | repeat | Repeat iterating through the dataset for the given #epochs up to the given #samples. | [
"Repeat",
"iterating",
"through",
"the",
"dataset",
"for",
"the",
"given",
"#epochs",
"up",
"to",
"the",
"given",
"#samples."
] | def repeat(self, nepochs=-1, nbatches=-1):
if nepochs > 0:
self.repetitions = nepochs
self.nsamples = nbatches
else:
self.repetitions = sys.maxsize
self.nsamples = nbatches
return self | ['def', 'repeat(self,', 'nepochs=-1,', 'nbatches=-1):', 'if', 'nepochs', '>', '0:', 'self.repetitions', '=', 'nepochs', 'self.nsamples', '=', 'nbatches', 'else:', 'self.repetitions', '=', 'sys.maxsize', 'self.nsamples', '=', 'nbatches', 'return', 'self'] | 251,076 |
43Carrig/recurrent_neural_networks_practice | wishart.py | _WishartLinearOperator.cholesky_input_output_matrices | cholesky_input_output_matrices | Boolean indicating if `Tensor` input/outputs are Cholesky factorized. | [
"Boolean",
"indicating",
"if",
"`Tensor`",
"input/outputs",
"are",
"Cholesky",
"factorized."
] | def cholesky_input_output_matrices(self):
return self._cholesky_input_output_matrices | ['def', 'cholesky_input_output_matrices(self):', 'return', 'self._cholesky_input_output_matrices'] | 312,914 |
RangiLyu/nanodet | flops_counter.py | print_model_with_flops | print_model_with_flops | Print a model with FLOPs for each layer. | [
"Print",
"a",
"model",
"with",
"FLOPs",
"for",
"each",
"layer."
] | def print_model_with_flops(model, total_flops, total_params, units='GFLOPs', precision=3, ost=sys.stdout, flush=False):
def accumulate_params(self):
if is_supported_instance(self):
return self.__params__
else:
sum = 0
for m in self.children():
sum... | ['def', 'print_model_with_flops(model,', 'total_flops,', 'total_params,', "units='GFLOPs',", 'precision=3,', 'ost=sys.stdout,', 'flush=False):', 'def', 'accumulate_params(self):', 'if', 'is_supported_instance(self):', 'return', 'self.__params__', 'else:', 'sum', '=', '0', 'for', 'm', 'in', 'self.children():', 'sum', '+... | 651,865 |
Riashat/Active-Learning-Bayesian-Convolutional-- | np_utils.py | to_categorical | to_categorical | Convert class vector (integers from 0 to nb_classes) to binary class matrix, for use with categorical_crossentropy. | [
"Convert",
"class",
"vector",
"(integers",
"from",
"0",
"to",
"nb_classes)",
"to",
"binary",
"class",
"matrix,",
"for",
"use",
"with",
"categorical_crossentropy."
] | def to_categorical(y, nb_classes=None):
y = np.asarray(y, dtype='int32')
if not nb_classes:
nb_classes = np.max(y) + 1
Y = np.zeros((len(y), nb_classes))
for i in range(len(y)):
Y[i, y[i]] = 1.0
return Y | ['def', 'to_categorical(y,', 'nb_classes=None):', 'y', '=', 'np.asarray(y,', "dtype='int32')", 'if', 'not', 'nb_classes:', 'nb_classes', '=', 'np.max(y)', '+', '1', 'Y', '=', 'np.zeros((len(y),', 'nb_classes))', 'for', 'i', 'in', 'range(len(y)):', 'Y[i,', 'y[i]]', '=', '1.0', 'return', 'Y'] | 8,707 |
google-research/scenic | utils.py | sync_model_state_across_replicas | sync_model_state_across_replicas | Sync the model_state (like batch statistics) across replicas. | [
"Sync",
"the",
"model_state",
"(like",
"batch",
"statistics)",
"across",
"replicas."
] | def sync_model_state_across_replicas(train_state: train_utils.TrainState) -> train_utils.TrainState:
if jax.tree_util.tree_leaves(train_state.model_state):
new_model_state = train_state.model_state.copy({'batch_stats': train_utils.pmap_mean(train_state.model_state['batch_stats'])})
return train_stat... | ['def', 'sync_model_state_across_replicas(train_state:', 'train_utils.TrainState)', '->', 'train_utils.TrainState:', 'if', 'jax.tree_util.tree_leaves(train_state.model_state):', 'new_model_state', '=', "train_state.model_state.copy({'batch_stats':", "train_utils.pmap_mean(train_state.model_state['batch_stats'])})", 're... | 847,089 |
open-mmlab/mmselfsup | moco.py | MoCo.extract_feat | extract_feat | Function to extract features from backbone. | [
"Function",
"to",
"extract",
"features",
"from",
"backbone."
] | def extract_feat(self, inputs: List[torch.Tensor], **kwarg) -> Tuple[torch.Tensor]:
x = self.backbone(inputs[0])
return x | ['def', 'extract_feat(self,', 'inputs:', 'List[torch.Tensor],', '**kwarg)', '->', 'Tuple[torch.Tensor]:', 'x', '=', 'self.backbone(inputs[0])', 'return', 'x'] | 240,375 |
clear-nus/MuMMI | ball_in_cup.old.py | BallInCup.get_reward | get_reward | Returns a sparse reward. | [
"Returns",
"a",
"sparse",
"reward."
] | def get_reward(self, physics):
return physics.in_target() | ['def', 'get_reward(self,', 'physics):', 'return', 'physics.in_target()'] | 265,887 |
scikit-learn-contrib/imbalanced-learn | test_param_validation.py | test_hasmethods | test_hasmethods | Check the HasMethods constraint. | [
"Check",
"the",
"HasMethods",
"constraint."
] | def test_hasmethods():
constraint = HasMethods(['a', 'b'])
class _Good:
def a(self):
pass
def b(self):
pass
class _Bad:
def a(self):
pass
assert constraint.is_satisfied_by(_Good())
assert not constraint.is_satisfied_by(_Bad())
asse... | ['def', 'test_hasmethods():', 'constraint', '=', "HasMethods(['a',", "'b'])", 'class', '_Good:', 'def', 'a(self):', 'pass', 'def', 'b(self):', 'pass', 'class', '_Bad:', 'def', 'a(self):', 'pass', 'assert', 'constraint.is_satisfied_by(_Good())', 'assert', 'not', 'constraint.is_satisfied_by(_Bad())', 'assert', 'str(const... | 610,707 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_gateway.py | TestGateway.delete_session | delete_session | Deletes a session corresponding to the given session id. | [
"Deletes",
"a",
"session",
"corresponding",
"to",
"the",
"given",
"session",
"id."
] | def delete_session(self, session_id):
with mocked_gateway:
response = self.request('DELETE', '/api/sessions/' + session_id)
self.assertEqual(response.status_code, 204)
self.assertEqual(response.reason, 'No Content') | ['def', 'delete_session(self,', 'session_id):', 'with', 'mocked_gateway:', 'response', '=', "self.request('DELETE',", "'/api/sessions/'", '+', 'session_id)', 'self.assertEqual(response.status_code,', '204)', 'self.assertEqual(response.reason,', "'No", "Content')"] | 452,344 |
jbwang1997/CrossKD | xml_style.py | XMLDataset.parse_data_info | parse_data_info | Parse raw annotation to target format. | [
"Parse",
"raw",
"annotation",
"to",
"target",
"format."
] | def parse_data_info(self, img_info: dict) -> Union[dict, List[dict]]:
data_info = {}
img_path = osp.join(self.sub_data_root, img_info['file_name'])
data_info['img_path'] = img_path
data_info['img_id'] = img_info['img_id']
data_info['xml_path'] = img_info['xml_path']
with self.file_client.get_loc... | ['def', 'parse_data_info(self,', 'img_info:', 'dict)', '->', 'Union[dict,', 'List[dict]]:', 'data_info', '=', '{}', 'img_path', '=', 'osp.join(self.sub_data_root,', "img_info['file_name'])", "data_info['img_path']", '=', 'img_path', "data_info['img_id']", '=', "img_info['img_id']", "data_info['xml_path']", '=', "img_in... | 490,755 |
nilearn/nilearn | test_signal_extraction.py | test_signals_extraction_with_labels_without_mask | test_signals_extraction_with_labels_without_mask | Test conversion between signals and images using regions defined by labels. | [
"Test",
"conversion",
"between",
"signals",
"and",
"images",
"using",
"regions",
"defined",
"by",
"labels."
] | def test_signals_extraction_with_labels_without_mask(signals, labels_data, labels_img, shape_3d_default):
data_img = signals_to_img_labels(signals=signals, labels_img=labels_img)
assert data_img.shape == shape_3d_default + (N_TIMEPOINTS,)
data = get_data(data_img)
assert np.all(data.std(axis=-1) > 0)
... | ['def', 'test_signals_extraction_with_labels_without_mask(signals,', 'labels_data,', 'labels_img,', 'shape_3d_default):', 'data_img', '=', 'signals_to_img_labels(signals=signals,', 'labels_img=labels_img)', 'assert', 'data_img.shape', '==', 'shape_3d_default', '+', '(N_TIMEPOINTS,)', 'data', '=', 'get_data(data_img)', ... | 724,251 |
googleapis/python-aiplatform | execution.py | Execution.assign_input_artifacts | assign_input_artifacts | Assigns Artifacts as inputs to this Executions. | [
"Assigns",
"Artifacts",
"as",
"inputs",
"to",
"this",
"Executions."
] | def assign_input_artifacts(self, artifacts: List[Union[artifact.Artifact, models.Model]]):
self._add_artifact(artifacts=artifacts, input=True) | ['def', 'assign_input_artifacts(self,', 'artifacts:', 'List[Union[artifact.Artifact,', 'models.Model]]):', 'self._add_artifact(artifacts=artifacts,', 'input=True)'] | 809,989 |
matsu0228/nlp-jp | __init__.py | AutoScaleConnection.attach_instances | attach_instances | Attach instances to an autoscaling group. | [
"Attach",
"instances",
"to",
"an",
"autoscaling",
"group."
] | def attach_instances(self, name, instance_ids):
params = {'AutoScalingGroupName': name}
self.build_list_params(params, instance_ids, 'InstanceIds')
return self.get_status('AttachInstances', params) | ['def', 'attach_instances(self,', 'name,', 'instance_ids):', 'params', '=', "{'AutoScalingGroupName':", 'name}', 'self.build_list_params(params,', 'instance_ids,', "'InstanceIds')", 'return', "self.get_status('AttachInstances',", 'params)'] | 784,458 |
TensorLab/tensorfx | _config.py | Configuration.master | master | Retrieves whether the current task is a master task. | [
"Retrieves",
"whether",
"the",
"current",
"task",
"is",
"a",
"master",
"task."
] | def master(self):
return self._task.type == _TASK_MASTER | ['def', 'master(self):', 'return', 'self._task.type', '==', '_TASK_MASTER'] | 365,937 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_ssl.py | ThreadedTests.test_wrong_cert | test_wrong_cert | Connecting when the server rejects the client's certificate Launch a server with CERT_REQUIRED, and check that trying to connect to it with a wrong client certificate fails. | [
"Connecting",
"when",
"the",
"server",
"rejects",
"the",
"client's",
"certificate",
"Launch",
"a",
"server",
"with",
"CERT_REQUIRED,",
"and",
"check",
"that",
"trying",
"to",
"connect",
"to",
"it",
"with",
"a",
"wrong",
"client",
"certificate",
"fails."
] | def test_wrong_cert(self):
certfile = os.path.join(os.path.dirname(__file__) or os.curdir, 'wrongcert.pem')
server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False)
with server, socket.socket() as sock, ssl.wrap_socket(sock, certfile=certfile,... | ['def', 'test_wrong_cert(self):', 'certfile', '=', 'os.path.join(os.path.dirname(__file__)', 'or', 'os.curdir,', "'wrongcert.pem')", 'server', '=', 'ThreadedEchoServer(CERTFILE,', 'certreqs=ssl.CERT_REQUIRED,', 'cacerts=CERTFILE,', 'chatty=False,', 'connectionchatty=False)', 'with', 'server,', 'socket.socket()', 'as', ... | 376,369 |
guxm2021/ALT_SpeechBrain | features.py | InputNormalization.to | to | Puts the needed tensors in the right device. | [
"Puts",
"the",
"needed",
"tensors",
"in",
"the",
"right",
"device."
] | def to(self, device):
self = super(InputNormalization, self).to(device)
self.glob_mean = self.glob_mean.to(device)
self.glob_std = self.glob_std.to(device)
for spk in self.spk_dict_mean:
self.spk_dict_mean[spk] = self.spk_dict_mean[spk].to(device)
self.spk_dict_std[spk] = self.spk_dict_s... | ['def', 'to(self,', 'device):', 'self', '=', 'super(InputNormalization,', 'self).to(device)', 'self.glob_mean', '=', 'self.glob_mean.to(device)', 'self.glob_std', '=', 'self.glob_std.to(device)', 'for', 'spk', 'in', 'self.spk_dict_mean:', 'self.spk_dict_mean[spk]', '=', 'self.spk_dict_mean[spk].to(device)', 'self.spk_d... | 415,821 |
joaquimcampos/DeepSplines | project.py | Project.load_model | load_model | Load model from a loaded checkpoint. | [
"Load",
"model",
"from",
"a",
"loaded",
"checkpoint."
] | def load_model(self, ckpt):
print('\n==> Resuming from checkpoint...')
self.net.load_state_dict(ckpt['model_state'], strict=self.training is True)
self.best_train_acc = ckpt['best_train_acc']
self.best_valid_acc = ckpt['best_valid_acc']
if self.training:
self.start_epoch = ckpt['num_epochs_f... | ['def', 'load_model(self,', 'ckpt):', "print('\\n==>", 'Resuming', 'from', "checkpoint...')", "self.net.load_state_dict(ckpt['model_state'],", 'strict=self.training', 'is', 'True)', 'self.best_train_acc', '=', "ckpt['best_train_acc']", 'self.best_valid_acc', '=', "ckpt['best_valid_acc']", 'if', 'self.training:', 'self.... | 540,080 |
thaines/helit | chunk_db.py | ChunkDB.set_params | set_params | Sets the chunk matching parameters - note that this resets the KD tree it has to build, so next convert will be computationally expensive. | [
"Sets",
"the",
"chunk",
"matching",
"parameters",
"-",
"note",
"that",
"this",
"resets",
"the",
"KD",
"tree",
"it",
"has",
"to",
"build,",
"so",
"next",
"convert",
"will",
"be",
"computationally",
"expensive."
] | def set_params(self, samples=8, angle_weight=1.0, radius_weight=1.0, density_weight=1.0):
self.samples = samples
self.radius_mult = radius_weight / angle_weight
self.density_mult = density_weight / angle_weight
self.kdtree = None | ['def', 'set_params(self,', 'samples=8,', 'angle_weight=1.0,', 'radius_weight=1.0,', 'density_weight=1.0):', 'self.samples', '=', 'samples', 'self.radius_mult', '=', 'radius_weight', '/', 'angle_weight', 'self.density_mult', '=', 'density_weight', '/', 'angle_weight', 'self.kdtree', '=', 'None'] | 591,844 |
ivanmontero/autobot | check_copies.py | blackify | blackify | Applies the black part of our `make style` command to `code`. | [
"Applies",
"the",
"black",
"part",
"of",
"our",
"`make",
"style`",
"command",
"to",
"`code`."
] | def blackify(code):
has_indent = code.startswith(' ')
if has_indent:
code = f'class Bla:\n{code}'
with tempfile.TemporaryDirectory() as d:
fname = os.path.join(d, 'tmp.py')
with open(fname, 'w', encoding='utf-8') as f:
f.write(code)
os.system(f'black -q --line-... | ['def', 'blackify(code):', 'has_indent', '=', "code.startswith('", "')", 'if', 'has_indent:', 'code', '=', "f'class", "Bla:\\n{code}'", 'with', 'tempfile.TemporaryDirectory()', 'as', 'd:', 'fname', '=', 'os.path.join(d,', "'tmp.py')", 'with', 'open(fname,', "'w',", "encoding='utf-8')", 'as', 'f:', 'f.write(code)', "os.... | 418,616 |
arshpreetsingh/quantopian-machinelearning | application.py | Application.invalidated | invalidated | True when a redraw operation has been scheduled. | [
"True",
"when",
"a",
"redraw",
"operation",
"has",
"been",
"scheduled."
] | def invalidated(self):
return self._invalidated | ['def', 'invalidated(self):', 'return', 'self._invalidated'] | 892,115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.