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 |
|---|---|---|---|---|---|---|---|---|
onnx/onnx | helper.py | make_optional_type_proto | make_optional_type_proto | Makes an optional TypeProto. | [
"Makes",
"an",
"optional",
"TypeProto."
] | def make_optional_type_proto(inner_type_proto: TypeProto) -> TypeProto:
type_proto = TypeProto()
type_proto.optional_type.elem_type.CopyFrom(inner_type_proto)
return type_proto | ['def', 'make_optional_type_proto(inner_type_proto:', 'TypeProto)', '->', 'TypeProto:', 'type_proto', '=', 'TypeProto()', 'type_proto.optional_type.elem_type.CopyFrom(inner_type_proto)', 'return', 'type_proto'] | 756,402 |
sunishsheth2009/ChatterBot | ma.py | putmask | putmask | putmask(a, mask, values) sets a where mask is true. | [
"putmask(a,",
"mask,",
"values)",
"sets",
"a",
"where",
"mask",
"is",
"true."
] | def putmask(a, mask, values):
if mask is nomask:
return
numeric.putmask(a.raw_data(), mask, values)
m = getmask(a)
if m is nomask:
return
a.unshare_mask()
numeric.putmask(a.raw_mask(), mask, 0) | ['def', 'putmask(a,', 'mask,', 'values):', 'if', 'mask', 'is', 'nomask:', 'return', 'numeric.putmask(a.raw_data(),', 'mask,', 'values)', 'm', '=', 'getmask(a)', 'if', 'm', 'is', 'nomask:', 'return', 'a.unshare_mask()', 'numeric.putmask(a.raw_mask(),', 'mask,', '0)'] | 532,324 |
YuriyGuts/snake-ai-reinforcement | entities.py | Snake.turn_right | turn_right | At the next step, take a right turn relative to the current direction. | [
"At",
"the",
"next",
"step,",
"take",
"a",
"right",
"turn",
"relative",
"to",
"the",
"current",
"direction."
] | def turn_right(self):
direction_idx = self.directions.index(self.direction)
self.direction = self.directions[(direction_idx + 1) % len(self.directions)] | ['def', 'turn_right(self):', 'direction_idx', '=', 'self.directions.index(self.direction)', 'self.direction', '=', 'self.directions[(direction_idx', '+', '1)', '%', 'len(self.directions)]'] | 352,158 |
PacktPublishing/Hands-On-Artificial--for-Banking | range.py | RangeIndex.stop | stop | The value of the `stop` parameter. | [
"The",
"value",
"of",
"the",
"`stop`",
"parameter."
] | def stop(self):
return self._range.stop | ['def', 'stop(self):', 'return', 'self._range.stop'] | 236,720 |
jxhe/unify-parameter-efficient-tuning | modeling_funnel.py | FunnelAttentionStructure.post_attention_pooling | post_attention_pooling | Pool the proper parts of `attention_inputs` after the attention layer. | [
"Pool",
"the",
"proper",
"parts",
"of",
"`attention_inputs`",
"after",
"the",
"attention",
"layer."
] | def post_attention_pooling(self, attention_inputs):
(position_embeds, token_type_mat, attention_mask, cls_mask) = attention_inputs
if self.config.pool_q_only:
self.pooling_mult *= 2
if self.config.attention_type == 'factorized':
position_embeds = position_embeds[:2] + self.stride_poo... | ['def', 'post_attention_pooling(self,', 'attention_inputs):', '(position_embeds,', 'token_type_mat,', 'attention_mask,', 'cls_mask)', '=', 'attention_inputs', 'if', 'self.config.pool_q_only:', 'self.pooling_mult', '*=', '2', 'if', 'self.config.attention_type', '==', "'factorized':", 'position_embeds', '=', 'position_em... | 948,889 |
scikit-learn/scikit-learn | test_validation.py | test_check_array_array_api_has_non_finite | test_check_array_array_api_has_non_finite | Checks that Array API arrays checks non-finite correctly. | [
"Checks",
"that",
"Array",
"API",
"arrays",
"checks",
"non-finite",
"correctly."
] | def test_check_array_array_api_has_non_finite(array_namespace):
xp = pytest.importorskip(array_namespace)
X_nan = xp.asarray([[xp.nan, 1, 0], [0, xp.nan, 3]], dtype=xp.float32)
with config_context(array_api_dispatch=True):
with pytest.raises(ValueError, match='Input contains NaN.'):
chec... | ['def', 'test_check_array_array_api_has_non_finite(array_namespace):', 'xp', '=', 'pytest.importorskip(array_namespace)', 'X_nan', '=', 'xp.asarray([[xp.nan,', '1,', '0],', '[0,', 'xp.nan,', '3]],', 'dtype=xp.float32)', 'with', 'config_context(array_api_dispatch=True):', 'with', 'pytest.raises(ValueError,', "match='Inp... | 854,420 |
gunthercox/ChatterBot | fst.py | BaseCursor.switch_to | switch_to | Switch to the sibling arc with the given label bytes. | [
"Switch",
"to",
"the",
"sibling",
"arc",
"with",
"the",
"given",
"label",
"bytes."
] | def switch_to(self, label):
_label = self.label
_at_last_arc = self.at_last_arc
_next_arc = self.next_arc
while True:
thislabel = _label()
if thislabel == label:
return True
if thislabel > label or _at_last_arc():
return False
_next_arc() | ['def', 'switch_to(self,', 'label):', '_label', '=', 'self.label', '_at_last_arc', '=', 'self.at_last_arc', '_next_arc', '=', 'self.next_arc', 'while', 'True:', 'thislabel', '=', '_label()', 'if', 'thislabel', '==', 'label:', 'return', 'True', 'if', 'thislabel', '>', 'label', 'or', '_at_last_arc():', 'return', 'False',... | 484,350 |
SALT-NLP/Adaptive-Compositional-Modules | retrieval_rag.py | Index.get_doc_dicts | get_doc_dicts | Returns a list of dictionaries, containing titles and text of the retrieved documents. | [
"Returns",
"a",
"list",
"of",
"dictionaries,",
"containing",
"titles",
"and",
"text",
"of",
"the",
"retrieved",
"documents."
] | def get_doc_dicts(self, doc_ids: np.ndarray) -> List[dict]:
raise NotImplementedError | ['def', 'get_doc_dicts(self,', 'doc_ids:', 'np.ndarray)', '->', 'List[dict]:', 'raise', 'NotImplementedError'] | 409,037 |
aeon-toolkit/aeon | test_differencer.py | test_differencer_same_series | test_differencer_same_series | Test transform against inverse_transform. | [
"Test",
"transform",
"against",
"inverse_transform."
] | def test_differencer_same_series(y, lags):
transformer = Differencer(lags=lags, na_handling='drop_na')
y_transform = transformer.fit_transform(y)
y_reconstructed = transformer.inverse_transform(y_transform)
_assert_array_almost_equal(y.loc[y_reconstructed.index], y_reconstructed) | ['def', 'test_differencer_same_series(y,', 'lags):', 'transformer', '=', 'Differencer(lags=lags,', "na_handling='drop_na')", 'y_transform', '=', 'transformer.fit_transform(y)', 'y_reconstructed', '=', 'transformer.inverse_transform(y_transform)', '_assert_array_almost_equal(y.loc[y_reconstructed.index],', 'y_reconstruc... | 400,035 |
google/deepvariant | run_deepvariant.py | runtime_by_region_vis_command | runtime_by_region_vis_command | Returns a runtime_by_region_vis (command, logfile=None) for subprocess. | [
"Returns",
"a",
"runtime_by_region_vis",
"(command,",
"logfile=None)",
"for",
"subprocess."
] | def runtime_by_region_vis_command(runtime_by_region_path: str):
runtime_report = os.path.join(_LOGGING_DIR.value, 'make_examples_runtime_by_region_report.html')
command = ['time', '/opt/deepvariant/bin/runtime_by_region_vis']
command.extend(['--input', '"{}"'.format(runtime_by_region_path)])
command.ext... | ['def', 'runtime_by_region_vis_command(runtime_by_region_path:', 'str):', 'runtime_report', '=', 'os.path.join(_LOGGING_DIR.value,', "'make_examples_runtime_by_region_report.html')", 'command', '=', "['time',", "'/opt/deepvariant/bin/runtime_by_region_vis']", "command.extend(['--input',", '\'"{}"\'.format(runtime_by_re... | 540,530 |
Katja-M/Python_NaturalLanguageProcessing | font_manager.py | list_fonts | list_fonts | Return a list of all fonts matching any of the extensions, found recursively under the directory. | [
"Return",
"a",
"list",
"of",
"all",
"fonts",
"matching",
"any",
"of",
"the",
"extensions,",
"found",
"recursively",
"under",
"the",
"directory."
] | def list_fonts(directory, extensions):
extensions = ['.' + ext for ext in extensions]
return [os.path.join(dirpath, filename) for (dirpath, _, filenames) in os.walk(directory) for filename in filenames if Path(filename).suffix.lower() in extensions] | ['def', 'list_fonts(directory,', 'extensions):', 'extensions', '=', "['.'", '+', 'ext', 'for', 'ext', 'in', 'extensions]', 'return', '[os.path.join(dirpath,', 'filename)', 'for', '(dirpath,', '_,', 'filenames)', 'in', 'os.walk(directory)', 'for', 'filename', 'in', 'filenames', 'if', 'Path(filename).suffix.lower()', 'in... | 864,562 |
devashish-patel/webcam-motion-detector | buffer.py | Buffer.newline | newline | Insert a line ending at the current position. | [
"Insert",
"a",
"line",
"ending",
"at",
"the",
"current",
"position."
] | def newline(self, copy_margin=True):
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | ['def', 'newline(self,', 'copy_margin=True):', 'if', 'copy_margin:', "self.insert_text('\\n'", '+', 'self.document.leading_whitespace_in_current_line)', 'else:', "self.insert_text('\\n')"] | 983,681 |
enlite-ai/maze | double.py | DoubleObservationConversion.space_to_maze | space_to_maze | Divides observation by 2. | [
"Divides",
"observation",
"by",
"2."
] | def space_to_maze(self, observation: Dict[str, int]) -> int:
observation = observation['observation']
assert observation % 2 == 0, 'Invalid observation: Must be divisible by 2'
return observation / 2 | ['def', 'space_to_maze(self,', 'observation:', 'Dict[str,', 'int])', '->', 'int:', 'observation', '=', "observation['observation']", 'assert', 'observation', '%', '2', '==', '0,', "'Invalid", 'observation:', 'Must', 'be', 'divisible', 'by', "2'", 'return', 'observation', '/', '2'] | 647,343 |
kujason/monopsr | format_checker.py | check_obj_label_format | check_obj_label_format | Checks for correct ObjectLabel format. | [
"Checks",
"for",
"correct",
"ObjectLabel",
"format."
] | def check_obj_label_format(input_data):
if not isinstance(input_data, obj_utils.ObjectLabel):
raise TypeError('Given input is not an ObjectLabel.') | ['def', 'check_obj_label_format(input_data):', 'if', 'not', 'isinstance(input_data,', 'obj_utils.ObjectLabel):', 'raise', "TypeError('Given", 'input', 'is', 'not', 'an', "ObjectLabel.')"] | 655,294 |
openai/spinningup | logx.py | EpochLogger.log_tabular | log_tabular | Log a value or possibly the mean/std/min/max values of a diagnostic. | [
"Log",
"a",
"value",
"or",
"possibly",
"the",
"mean/std/min/max",
"values",
"of",
"a",
"diagnostic."
] | def log_tabular(self, key, val=None, with_min_and_max=False, average_only=False):
if val is not None:
super().log_tabular(key, val)
else:
v = self.epoch_dict[key]
vals = np.concatenate(v) if isinstance(v[0], np.ndarray) and len(v[0].shape) > 0 else v
stats = mpi_statistics_scalar... | ['def', 'log_tabular(self,', 'key,', 'val=None,', 'with_min_and_max=False,', 'average_only=False):', 'if', 'val', 'is', 'not', 'None:', 'super().log_tabular(key,', 'val)', 'else:', 'v', '=', 'self.epoch_dict[key]', 'vals', '=', 'np.concatenate(v)', 'if', 'isinstance(v[0],', 'np.ndarray)', 'and', 'len(v[0].shape)', '>',... | 371,761 |
deepmind/dm_control | quadruped.py | Physics.torso_upright | torso_upright | Returns the dot-product of the torso z-axis and the global z-axis. | [
"Returns",
"the",
"dot-product",
"of",
"the",
"torso",
"z-axis",
"and",
"the",
"global",
"z-axis."
] | def torso_upright(self):
return np.asarray(self.named.data.xmat['torso', 'zz']) | ['def', 'torso_upright(self):', 'return', "np.asarray(self.named.data.xmat['torso',", "'zz'])"] | 165,542 |
willbradshaw/mnist-mlp | mlp_train.py | zero_bias | zero_bias | Convert the bias-unit column from a weight or delt matrix to zeros. | [
"Convert",
"the",
"bias-unit",
"column",
"from",
"a",
"weight",
"or",
"delt",
"matrix",
"to",
"zeros."
] | def zero_bias(matrix):
matrix[:, 0] = 0
return matrix | ['def', 'zero_bias(matrix):', 'matrix[:,', '0]', '=', '0', 'return', 'matrix'] | 626,061 |
microsoft/maro | event_buffer.py | EventBuffer.gen_action_event | gen_action_event | Generate an event that used to dispatch action to business engine. | [
"Generate",
"an",
"event",
"that",
"used",
"to",
"dispatch",
"action",
"to",
"business",
"engine."
] | def gen_action_event(self, tick: int, payloads: List[BaseAction]) -> CascadeEvent:
assert isinstance(payloads, list)
assert all((isinstance(p, BaseAction) for p in payloads))
return self.gen_cascade_event(tick, MaroEvents.TAKE_ACTION, payloads) | ['def', 'gen_action_event(self,', 'tick:', 'int,', 'payloads:', 'List[BaseAction])', '->', 'CascadeEvent:', 'assert', 'isinstance(payloads,', 'list)', 'assert', 'all((isinstance(p,', 'BaseAction)', 'for', 'p', 'in', 'payloads))', 'return', 'self.gen_cascade_event(tick,', 'MaroEvents.TAKE_ACTION,', 'payloads)'] | 628,448 |
rudranil723/mini-main | conftest.py | pyarrow_parser_only | pyarrow_parser_only | Fixture all of the CSV parsers using the Pyarrow engine. | [
"Fixture",
"all",
"of",
"the",
"CSV",
"parsers",
"using",
"the",
"Pyarrow",
"engine."
] | def pyarrow_parser_only(request):
return request.param() | ['def', 'pyarrow_parser_only(request):', 'return', 'request.param()'] | 267,643 |
43Carrig/recurrent_neural_networks_practice | test_example_pb2_grpc.py | TestCaseServiceServicer.SometimesSleepForever | SometimesSleepForever | Sleep forever 50% of the time, return immediately the other 50%. | [
"Sleep",
"forever",
"50%",
"of",
"the",
"time,",
"return",
"immediately",
"the",
"other",
"50%."
] | def SometimesSleepForever(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | ['def', 'SometimesSleepForever(self,', 'request,', 'context):', 'context.set_code(grpc.StatusCode.UNIMPLEMENTED)', "context.set_details('Method", 'not', "implemented!')", 'raise', "NotImplementedError('Method", 'not', "implemented!')"] | 335,130 |
eddylau328/fyp-artificial-intelligence-ac-control-device | _user_mgt.py | UserManager.delete_user | delete_user | Deletes the user identified by the specified user ID. | [
"Deletes",
"the",
"user",
"identified",
"by",
"the",
"specified",
"user",
"ID."
] | def delete_user(self, uid):
_auth_utils.validate_uid(uid, required=True)
try:
(body, http_resp) = self._client.body_and_response('post', '/accounts:delete', json={'localId': uid})
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
els... | ['def', 'delete_user(self,', 'uid):', '_auth_utils.validate_uid(uid,', 'required=True)', 'try:', '(body,', 'http_resp)', '=', "self._client.body_and_response('post',", "'/accounts:delete',", "json={'localId':", 'uid})', 'except', 'requests.exceptions.RequestException', 'as', 'error:', 'raise', '_auth_utils.handle_auth_... | 214,417 |
kubeflow/pipelines | _run_op.py | SubmitRunOp.from_json_spec | from_json_spec | Create a new instance of SubmitRunOp from a json specification. | [
"Create",
"a",
"new",
"instance",
"of",
"SubmitRunOp",
"from",
"a",
"json",
"specification."
] | def from_json_spec(cls, name: str=None, k8s_name: str=None, run_name: str=None, json_spec: str=None):
spec = json.loads(json_spec)
return cls(name=name, k8s_name=k8s_name, run_name=run_name, spec=spec) | ['def', 'from_json_spec(cls,', 'name:', 'str=None,', 'k8s_name:', 'str=None,', 'run_name:', 'str=None,', 'json_spec:', 'str=None):', 'spec', '=', 'json.loads(json_spec)', 'return', 'cls(name=name,', 'k8s_name=k8s_name,', 'run_name=run_name,', 'spec=spec)'] | 779,733 |
intel/neural-compressor | util.py | remove_init_from_model_input | remove_init_from_model_input | Remove initializer from model input. | [
"Remove",
"initializer",
"from",
"model",
"input."
] | def remove_init_from_model_input(model):
inputs = model.model.graph.input
name_to_input = {}
for inp in inputs:
name_to_input[inp.name] = inp
for initializer in model.model.graph.initializer:
if initializer.name in name_to_input:
inputs.remove(name_to_input[initializer.name]) | ['def', 'remove_init_from_model_input(model):', 'inputs', '=', 'model.model.graph.input', 'name_to_input', '=', '{}', 'for', 'inp', 'in', 'inputs:', 'name_to_input[inp.name]', '=', 'inp', 'for', 'initializer', 'in', 'model.model.graph.initializer:', 'if', 'initializer.name', 'in', 'name_to_input:', 'inputs.remove(name_... | 737,483 |
bloomberg/cnn-rnf | proc_data.py | build_data | build_data | Load and process data. | [
"Load",
"and",
"process",
"data."
] | def build_data(fnames):
revs = []
vocab = set()
corpora = []
for i in xrange(len(fnames)):
corpora.append(get_corpus(fnames[i]))
max_l = 0
for (i, corpus) in enumerate(corpora):
for [label, words] in corpus:
for word in words:
vocab.add(word)
... | ['def', 'build_data(fnames):', 'revs', '=', '[]', 'vocab', '=', 'set()', 'corpora', '=', '[]', 'for', 'i', 'in', 'xrange(len(fnames)):', 'corpora.append(get_corpus(fnames[i]))', 'max_l', '=', '0', 'for', '(i,', 'corpus)', 'in', 'enumerate(corpora):', 'for', '[label,', 'words]', 'in', 'corpus:', 'for', 'word', 'in', 'wo... | 123,811 |
greydanus/mr_london | control.py | Coverage.stop | stop | Stop measuring code coverage. | [
"Stop",
"measuring",
"code",
"coverage."
] | def stop(self):
if self._started:
self.collector.stop()
self._started = False | ['def', 'stop(self):', 'if', 'self._started:', 'self.collector.stop()', 'self._started', '=', 'False'] | 242,099 |
MycroftAI/mycroft-core | setup.py | required | required | Read requirements file and remove comments and empty lines. | [
"Read",
"requirements",
"file",
"and",
"remove",
"comments",
"and",
"empty",
"lines."
] | def required(requirements_file):
with open(os.path.join(BASEDIR, requirements_file), 'r') as f:
requirements = f.read().splitlines()
if 'MYCROFT_LOOSE_REQUIREMENTS' in os.environ:
print('USING LOOSE REQUIREMENTS!')
requirements = [r.replace('==', '>=') for r in requirements]
... | ['def', 'required(requirements_file):', 'with', 'open(os.path.join(BASEDIR,', 'requirements_file),', "'r')", 'as', 'f:', 'requirements', '=', 'f.read().splitlines()', 'if', "'MYCROFT_LOOSE_REQUIREMENTS'", 'in', 'os.environ:', "print('USING", 'LOOSE', "REQUIREMENTS!')", 'requirements', '=', "[r.replace('==',", "'>=')", ... | 290,197 |
nasimrahaman/antipasti-tf | core.py | get_global_variable | get_global_variable | Gets the global variable given a name. | [
"Gets",
"the",
"global",
"variable",
"given",
"a",
"name."
] | def get_global_variable(name, default=None):
return get_all_global_variables(as_name_variable_dict=True).get(name, default) | ['def', 'get_global_variable(name,', 'default=None):', 'return', 'get_all_global_variables(as_name_variable_dict=True).get(name,', 'default)'] | 33,464 |
MushroomRL/mushroom-rl | kinematics.py | forward_kinematics | forward_kinematics | Compute the forward kinematics of the robots. | [
"Compute",
"the",
"forward",
"kinematics",
"of",
"the",
"robots."
] | def forward_kinematics(mj_model, mj_data, q, body_name):
mj_data.qpos[:len(q)] = q
mujoco.mj_fwdPosition(mj_model, mj_data)
return (mj_data.body(body_name).xpos.copy(), mj_data.body(body_name).xmat.reshape(3, 3).copy()) | ['def', 'forward_kinematics(mj_model,', 'mj_data,', 'q,', 'body_name):', 'mj_data.qpos[:len(q)]', '=', 'q', 'mujoco.mj_fwdPosition(mj_model,', 'mj_data)', 'return', '(mj_data.body(body_name).xpos.copy(),', 'mj_data.body(body_name).xmat.reshape(3,', '3).copy())'] | 266,200 |
akandykeller/NeuralWaveMachines | test_datasets.py | TestToyDataset.compare_structures_all_the_same | compare_structures_all_the_same | Compares that the two examples are identical in structure and value. | [
"Compares",
"that",
"the",
"two",
"examples",
"are",
"identical",
"in",
"structure",
"and",
"value."
] | def compare_structures_all_the_same(self, example, batched_example):
self.assertEqual(jax.tree_structure(example), jax.tree_structure(batched_example), 'Structures should be the same.')
example['image'] = tf.image.convert_image_dtype(example['image'], dtype=batched_example['image'].dtype).numpy()
for (v1, v... | ['def', 'compare_structures_all_the_same(self,', 'example,', 'batched_example):', 'self.assertEqual(jax.tree_structure(example),', 'jax.tree_structure(batched_example),', "'Structures", 'should', 'be', 'the', "same.')", "example['image']", '=', "tf.image.convert_image_dtype(example['image'],", "dtype=batched_example['i... | 293,601 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | translate_boxes | translate_boxes | Randomly translate the boxes. | [
"Randomly",
"translate",
"the",
"boxes."
] | def translate_boxes(box, translate_x, translate_y):
with tf.name_scope('translate_boxs'):
x = box[..., 0] + translate_x
y = box[..., 1] + translate_y
box = tf.stack([x, y, box[..., 2], box[..., 3]], axis=-1)
box.set_shape([None, 4])
return box | ['def', 'translate_boxes(box,', 'translate_x,', 'translate_y):', 'with', "tf.name_scope('translate_boxs'):", 'x', '=', 'box[...,', '0]', '+', 'translate_x', 'y', '=', 'box[...,', '1]', '+', 'translate_y', 'box', '=', 'tf.stack([x,', 'y,', 'box[...,', '2],', 'box[...,', '3]],', 'axis=-1)', 'box.set_shape([None,', '4])',... | 973,398 |
bachiraoun/fullrmc | Engine.py | Engine.usedFrame | usedFrame | Stochatic engine frame in use. | [
"Stochatic",
"engine",
"frame",
"in",
"use."
] | def usedFrame(self):
return copy.deepcopy(self.__usedFrame) | ['def', 'usedFrame(self):', 'return', 'copy.deepcopy(self.__usedFrame)'] | 213,393 |
llazzaro/packyou | travis_pypi_setup.py | prepend_line | prepend_line | Rewrite a file adding a line to its beginning. | [
"Rewrite",
"a",
"file",
"adding",
"a",
"line",
"to",
"its",
"beginning."
] | def prepend_line(filepath, line):
with open(filepath) as f:
lines = f.readlines()
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines) | ['def', 'prepend_line(filepath,', 'line):', 'with', 'open(filepath)', 'as', 'f:', 'lines', '=', 'f.readlines()', 'lines.insert(0,', 'line)', 'with', 'open(filepath,', "'w')", 'as', 'f:', 'f.writelines(lines)'] | 253,800 |
facebookresearch/ReAgent | post_step.py | add_replay_buffer_post_step | add_replay_buffer_post_step | Simply add transitions to replay_buffer. | [
"Simply",
"add",
"transitions",
"to",
"replay_buffer."
] | def add_replay_buffer_post_step(replay_buffer: ReplayBuffer, env: gym.Env, replay_buffer_inserter=None):
if replay_buffer_inserter is None:
replay_buffer_inserter = make_replay_buffer_inserter(env)
def post_step(transition: Transition) -> None:
replay_buffer_inserter(replay_buffer, transition)
... | ['def', 'add_replay_buffer_post_step(replay_buffer:', 'ReplayBuffer,', 'env:', 'gym.Env,', 'replay_buffer_inserter=None):', 'if', 'replay_buffer_inserter', 'is', 'None:', 'replay_buffer_inserter', '=', 'make_replay_buffer_inserter(env)', 'def', 'post_step(transition:', 'Transition)', '->', 'None:', 'replay_buffer_inser... | 304,540 |
aws/sagemaker-python-sdk | lambda_step.py | LambdaOutput.to_request | to_request | Get the request structure for workflow service calls. | [
"Get",
"the",
"request",
"structure",
"for",
"workflow",
"service",
"calls."
] | def to_request(self) -> RequestType:
return {'OutputName': self.output_name, 'OutputType': self.output_type.value} | ['def', 'to_request(self)', '->', 'RequestType:', 'return', "{'OutputName':", 'self.output_name,', "'OutputType':", 'self.output_type.value}'] | 830,617 |
RasaHQ/rasa_core | model.py | model_fingerprint | model_fingerprint | Creates a model fingerprint from its used configuration and training data. | [
"Creates",
"a",
"model",
"fingerprint",
"from",
"its",
"used",
"configuration",
"and",
"training",
"data."
] | def model_fingerprint(config_file: Text, domain_file: Optional[Text]=None, nlu_data: Optional[Text]=None, stories: Optional[Text]=None) -> Fingerprint:
import rasa.core
import rasa_nlu
import rasa
import time
return {FINGERPRINT_CONFIG_KEY: _get_hashes_for_paths(config_file), FINGERPRINT_DOMAIN_KEY:... | ['def', 'model_fingerprint(config_file:', 'Text,', 'domain_file:', 'Optional[Text]=None,', 'nlu_data:', 'Optional[Text]=None,', 'stories:', 'Optional[Text]=None)', '->', 'Fingerprint:', 'import', 'rasa.core', 'import', 'rasa_nlu', 'import', 'rasa', 'import', 'time', 'return', '{FINGERPRINT_CONFIG_KEY:', '_get_hashes_fo... | 838,133 |
ludwig-ai/ludwig | utils.py | get_scheduler_cls | get_scheduler_cls | Get a registered hyperopt scheduler config class by name. | [
"Get",
"a",
"registered",
"hyperopt",
"scheduler",
"config",
"class",
"by",
"name."
] | def get_scheduler_cls(name: str) -> Type['BaseSchedulerConfig']:
return search_algorithm_config_registry[name] | ['def', 'get_scheduler_cls(name:', 'str)', '->', "Type['BaseSchedulerConfig']:", 'return', 'search_algorithm_config_registry[name]'] | 616,986 |
facebookresearch/CompilerGym | experiment.py | Experiment.dataframe | dataframe | Return the results as a dataframe. | [
"Return",
"the",
"results",
"as",
"a",
"dataframe."
] | def dataframe(self) -> pd.DataFrame:
dfs = []
for path in self.results_paths:
dfs.append(pd.read_csv(path))
if not dfs:
return pd.DataFrame()
return pd.concat(dfs) | ['def', 'dataframe(self)', '->', 'pd.DataFrame:', 'dfs', '=', '[]', 'for', 'path', 'in', 'self.results_paths:', 'dfs.append(pd.read_csv(path))', 'if', 'not', 'dfs:', 'return', 'pd.DataFrame()', 'return', 'pd.concat(dfs)'] | 125,739 |
googleapis/python-aiplatform | client.py | DatasetServiceClient.annotation_spec_path | annotation_spec_path | Returns a fully-qualified annotation_spec string. | [
"Returns",
"a",
"fully-qualified",
"annotation_spec",
"string."
] | def annotation_spec_path(project: str, location: str, dataset: str, annotation_spec: str) -> str:
return 'projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}'.format(project=project, location=location, dataset=dataset, annotation_spec=annotation_spec) | ['def', 'annotation_spec_path(project:', 'str,', 'location:', 'str,', 'dataset:', 'str,', 'annotation_spec:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}'.format(project=project,", 'location=location,', 'dataset=dataset,', 'annotation_sp... | 810,326 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | base.py | IndexOpsMixin.base | base | Return the base object if the memory of the underlying data is shared. | [
"Return",
"the",
"base",
"object",
"if",
"the",
"memory",
"of",
"the",
"underlying",
"data",
"is",
"shared."
] | def base(self):
warnings.warn('{obj}.base is deprecated and will be removed in a future version'.format(obj=type(self).__name__), FutureWarning, stacklevel=2)
return self.values.base | ['def', 'base(self):', "warnings.warn('{obj}.base", 'is', 'deprecated', 'and', 'will', 'be', 'removed', 'in', 'a', 'future', "version'.format(obj=type(self).__name__),", 'FutureWarning,', 'stacklevel=2)', 'return', 'self.values.base'] | 967,119 |
YannDubs/Invariant-Self-Supervised-Learning | helpers.py | average_dict | average_dict | Return a dictionary, where every value is avg over the dicts. | [
"Return",
"a",
"dictionary,",
"where",
"every",
"value",
"is",
"avg",
"over",
"the",
"dicts."
] | def average_dict(*dicts):
keys = set((k for d in dicts for k in d.keys()))
return {k: mean([d[k] for d in dicts if k in d]) for k in keys} | ['def', 'average_dict(*dicts):', 'keys', '=', 'set((k', 'for', 'd', 'in', 'dicts', 'for', 'k', 'in', 'd.keys()))', 'return', '{k:', 'mean([d[k]', 'for', 'd', 'in', 'dicts', 'if', 'k', 'in', 'd])', 'for', 'k', 'in', 'keys}'] | 245,903 |
brsynth/RetroPathRL | cli.py | RuleBurner.write_json | write_json | Write the JSON string. | [
"Write",
"the",
"JSON",
"string."
] | def write_json(self):
if self._ofile:
if self._compress:
ofh = gzip.open(self._ofile, 'wb', compresslevel=9)
else:
ofh = open(self._ofile, 'w')
else:
ofh = sys.stdout
content = '[\n' + ','.join(self._json) + '\n]' + '\n'
if self._ofile and self._compress:
... | ['def', 'write_json(self):', 'if', 'self._ofile:', 'if', 'self._compress:', 'ofh', '=', 'gzip.open(self._ofile,', "'wb',", 'compresslevel=9)', 'else:', 'ofh', '=', 'open(self._ofile,', "'w')", 'else:', 'ofh', '=', 'sys.stdout', 'content', '=', "'[\\n'", '+', "','.join(self._json)", '+', "'\\n]'", '+', "'\\n'", 'if', 's... | 841,039 |
segmind/cral | darknet.py | darknet_body | darknet_body | Darknent body having 52 Convolution2D layers. | [
"Darknent",
"body",
"having",
"52",
"Convolution2D",
"layers."
] | def darknet_body(inputs):
x = DarknetConv2D_BN_Leaky(32, (3, 3))(inputs)
x = resblock_body(x, 64, 1)
x = resblock_body(x, 128, 2)
x = resblock_body(x, 256, 8)
x = resblock_body(x, 512, 8)
x = resblock_body(x, 1024, 4)
return x | ['def', 'darknet_body(inputs):', 'x', '=', 'DarknetConv2D_BN_Leaky(32,', '(3,', '3))(inputs)', 'x', '=', 'resblock_body(x,', '64,', '1)', 'x', '=', 'resblock_body(x,', '128,', '2)', 'x', '=', 'resblock_body(x,', '256,', '8)', 'x', '=', 'resblock_body(x,', '512,', '8)', 'x', '=', 'resblock_body(x,', '1024,', '4)', 'retu... | 490,476 |
aws/sagemaker-python-sdk | processing.py | PySparkProcessor.run | run | Runs a processing job. | [
"Runs",
"a",
"processing",
"job."
] | def run(self, submit_app: str, submit_py_files: Optional[List[Union[str, PipelineVariable]]]=None, submit_jars: Optional[List[Union[str, PipelineVariable]]]=None, submit_files: Optional[List[Union[str, PipelineVariable]]]=None, inputs: Optional[List[ProcessingInput]]=None, outputs: Optional[List[ProcessingOutput]]=None... | ['def', 'run(self,', 'submit_app:', 'str,', 'submit_py_files:', 'Optional[List[Union[str,', 'PipelineVariable]]]=None,', 'submit_jars:', 'Optional[List[Union[str,', 'PipelineVariable]]]=None,', 'submit_files:', 'Optional[List[Union[str,', 'PipelineVariable]]]=None,', 'inputs:', 'Optional[List[ProcessingInput]]=None,', ... | 830,544 |
rudranil723/mini-main | conftest.py | index_flat | index_flat | index fixture, but excluding MultiIndex cases. | [
"index",
"fixture,",
"but",
"excluding",
"MultiIndex",
"cases."
] | def index_flat(request):
key = request.param
return indices_dict[key].copy() | ['def', 'index_flat(request):', 'key', '=', 'request.param', 'return', 'indices_dict[key].copy()'] | 323,129 |
EducationalTestingService/skll | test_featureset.py | TestFeatureset.test_iteration_without_dictvectorizer | test_iteration_without_dictvectorizer | Test to allow iteration only if the vectorizer is a DictVectorizer. | [
"Test",
"to",
"allow",
"iteration",
"only",
"if",
"the",
"vectorizer",
"is",
"a",
"DictVectorizer."
] | def test_iteration_without_dictvectorizer(self):
(fs, _) = make_classification_data(num_examples=100, num_features=4, num_labels=3, train_test_ratio=1.0, use_feature_hashing=True, feature_bins=2)
with self.assertRaises(ValueError):
for _ in fs:
pass | ['def', 'test_iteration_without_dictvectorizer(self):', '(fs,', '_)', '=', 'make_classification_data(num_examples=100,', 'num_features=4,', 'num_labels=3,', 'train_test_ratio=1.0,', 'use_feature_hashing=True,', 'feature_bins=2)', 'with', 'self.assertRaises(ValueError):', 'for', '_', 'in', 'fs:', 'pass'] | 885,139 |
zihuitang/medical_AI_platform | text_file.py | TextFile.close | close | Close the current file and forget everything we know about it (filename, current line number). | [
"Close",
"the",
"current",
"file",
"and",
"forget",
"everything",
"we",
"know",
"about",
"it",
"(filename,",
"current",
"line",
"number)."
] | def close(self):
file = self.file
self.file = None
self.filename = None
self.current_line = None
file.close() | ['def', 'close(self):', 'file', '=', 'self.file', 'self.file', '=', 'None', 'self.filename', '=', 'None', 'self.current_line', '=', 'None', 'file.close()'] | 282,285 |
pedrojrv/nucml | error_metrics.py | get_error_endf_exfor | get_error_endf_exfor | Calculate the error between a given dataframe of experimental datapoints to ENDF. | [
"Calculate",
"the",
"error",
"between",
"a",
"given",
"dataframe",
"of",
"experimental",
"datapoints",
"to",
"ENDF."
] | def get_error_endf_exfor(endf, df_sample, filter_energy=True):
endf_copy = endf.copy()
df = df_sample.copy()
if filter_energy:
df = df[df.Energy > endf_copy.Energy.min()]
indexes = np.arange(len(endf), len(endf) + len(df))
df.index = indexes
energy_interest = df[['Energy']]
energy_in... | ['def', 'get_error_endf_exfor(endf,', 'df_sample,', 'filter_energy=True):', 'endf_copy', '=', 'endf.copy()', 'df', '=', 'df_sample.copy()', 'if', 'filter_energy:', 'df', '=', 'df[df.Energy', '>', 'endf_copy.Energy.min()]', 'indexes', '=', 'np.arange(len(endf),', 'len(endf)', '+', 'len(df))', 'df.index', '=', 'indexes',... | 249,728 |
cackharot/suds-py3 | element.py | Element.prune | prune | Prune the branch of empty nodes. | [
"Prune",
"the",
"branch",
"of",
"empty",
"nodes."
] | def prune(self):
pruned = []
for c in self.children:
c.prune()
if c.isempty(False):
pruned.append(c)
for p in pruned:
self.children.remove(p) | ['def', 'prune(self):', 'pruned', '=', '[]', 'for', 'c', 'in', 'self.children:', 'c.prune()', 'if', 'c.isempty(False):', 'pruned.append(c)', 'for', 'p', 'in', 'pruned:', 'self.children.remove(p)'] | 360,339 |
palmettos/neat-autoencoders | distributed.py | host_is_local | host_is_local | Returns True if the hostname points to the localhost, otherwise False. | [
"Returns",
"True",
"if",
"the",
"hostname",
"points",
"to",
"the",
"localhost,",
"otherwise",
"False."
] | def host_is_local(hostname, port=22):
hostname = socket.getfqdn(hostname)
if hostname in ('localhost', '0.0.0.0', '127.0.0.1', '1.0.0.127.in-addr.arpa', '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'):
return True
localhost = socket.gethostname()
if hostname == localh... | ['def', 'host_is_local(hostname,', 'port=22):', 'hostname', '=', 'socket.getfqdn(hostname)', 'if', 'hostname', 'in', "('localhost',", "'0.0.0.0',", "'127.0.0.1',", "'1.0.0.127.in-addr.arpa',", "'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'):", 'return', 'True', 'localhost', '=', 'socket.get... | 735,170 |
astooke/rlpyt | collectors.py | GpuWaitResetCollector.collect_batch | collect_batch | Params agent_inputs and itr unused. | [
"Params",
"agent_inputs",
"and",
"itr",
"unused."
] | def collect_batch(self, agent_inputs, traj_infos, itr):
(act_ready, obs_ready) = (self.sync.act_ready, self.sync.obs_ready)
step = self.step_buffer_np
b = np.where(step.done)[0]
step.observation[b] = self.temp_observation[b]
step.done[:] = False
(agent_buf, env_buf) = (self.samples_np.agent, sel... | ['def', 'collect_batch(self,', 'agent_inputs,', 'traj_infos,', 'itr):', '(act_ready,', 'obs_ready)', '=', '(self.sync.act_ready,', 'self.sync.obs_ready)', 'step', '=', 'self.step_buffer_np', 'b', '=', 'np.where(step.done)[0]', 'step.observation[b]', '=', 'self.temp_observation[b]', 'step.done[:]', '=', 'False', '(agent... | 334,675 |
proycon/pynlpl | folia.py | Test2Sanity.test102j_declarations | test102j_declarations | Sanity Check - Declarations - Adding a declaration in other set. | [
"Sanity",
"Check",
"-",
"Declarations",
"-",
"Adding",
"a",
"declaration",
"in",
"other",
"set."
] | def test102j_declarations(self):
xml = '<?xml version="1.0"?>\n\n<FoLiA xmlns="http://ilk.uvt.nl/folia" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="test" version="{version}" generator="{generator}">\n <metadata type="native">\n <annotations>\n <gap-annotation annotator="sloot" set="gap-set"/>\n ... | ['def', 'test102j_declarations(self):', 'xml', '=', "'<?xml", 'version="1.0"?>\\n\\n<FoLiA', 'xmlns="http://ilk.uvt.nl/folia"', 'xmlns:xlink="http://www.w3.org/1999/xlink"', 'xml:id="test"', 'version="{version}"', 'generator="{generator}">\\n', '<metadata', 'type="native">\\n', '<annotations>\\n', '<gap-annotation', 'a... | 820,667 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | conftest.py | nselect_method | nselect_method | Fixture for trying all nselect methods. | [
"Fixture",
"for",
"trying",
"all",
"nselect",
"methods."
] | def nselect_method(request):
return request.param | ['def', 'nselect_method(request):', 'return', 'request.param'] | 452,409 |
matsu0228/nlp-jp | msvc.py | SystemInfo.WindowsSdkVersion | WindowsSdkVersion | Microsoft Windows SDK versions. | [
"Microsoft",
"Windows",
"SDK",
"versions."
] | def WindowsSdkVersion(self):
if self.vc_ver <= 9.0:
return ('7.0', '6.1', '6.0a')
elif self.vc_ver == 10.0:
return ('7.1', '7.0a')
elif self.vc_ver == 11.0:
return ('8.0', '8.0a')
elif self.vc_ver == 12.0:
return ('8.1', '8.1a')
elif self.vc_ver >= 14.0:
retur... | ['def', 'WindowsSdkVersion(self):', 'if', 'self.vc_ver', '<=', '9.0:', 'return', "('7.0',", "'6.1',", "'6.0a')", 'elif', 'self.vc_ver', '==', '10.0:', 'return', "('7.1',", "'7.0a')", 'elif', 'self.vc_ver', '==', '11.0:', 'return', "('8.0',", "'8.0a')", 'elif', 'self.vc_ver', '==', '12.0:', 'return', "('8.1',", "'8.1a')... | 806,116 |
tensorly/quantum | tfq_simulate_ops_test.py | InputTypesTest.test_symbol_values_type | test_symbol_values_type | Tests all three ops for the different types. | [
"Tests",
"all",
"three",
"ops",
"for",
"the",
"different",
"types."
] | def test_symbol_values_type(self, symbol_type):
qubit = cirq.GridQubit(0, 0)
circuits = util.convert_to_tensor([cirq.Circuit(cirq.H(qubit))])
symbol_names = ['symbol']
symbol_values = tf.convert_to_tensor([[1]], dtype=symbol_type)
pauli_sums = util.random_pauli_sums([qubit], 3, 1)
pauli_sums = u... | ['def', 'test_symbol_values_type(self,', 'symbol_type):', 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'circuits', '=', 'util.convert_to_tensor([cirq.Circuit(cirq.H(qubit))])', 'symbol_names', '=', "['symbol']", 'symbol_values', '=', 'tf.convert_to_tensor([[1]],', 'dtype=symbol_type)', 'pauli_sums', '=', 'util.random_pauli... | 834,730 |
asyml/texar-pytorch | bleu.py | sentence_bleu | sentence_bleu | Calculates BLEU score of a hypothesis sentence. | [
"Calculates",
"BLEU",
"score",
"of",
"a",
"hypothesis",
"sentence."
] | def sentence_bleu(references: List[MaybeList[str]], hypothesis: MaybeList[str], max_order: int=4, lowercase: bool=False, smooth: bool=False, use_bp: bool=True, return_all: bool=False) -> MaybeList[float]:
return corpus_bleu([references], [hypothesis], max_order=max_order, lowercase=lowercase, smooth=smooth, use_bp=... | ['def', 'sentence_bleu(references:', 'List[MaybeList[str]],', 'hypothesis:', 'MaybeList[str],', 'max_order:', 'int=4,', 'lowercase:', 'bool=False,', 'smooth:', 'bool=False,', 'use_bp:', 'bool=True,', 'return_all:', 'bool=False)', '->', 'MaybeList[float]:', 'return', 'corpus_bleu([references],', '[hypothesis],', 'max_or... | 925,120 |
matsu0228/nlp-jp | _base.py | _AxesBase.xaxis_inverted | xaxis_inverted | Returns *True* if the x-axis is inverted. | [
"Returns",
"*True*",
"if",
"the",
"x-axis",
"is",
"inverted."
] | def xaxis_inverted(self):
(left, right) = self.get_xlim()
return right < left | ['def', 'xaxis_inverted(self):', '(left,', 'right)', '=', 'self.get_xlim()', 'return', 'right', '<', 'left'] | 789,527 |
Katja-M/Python_NaturalLanguageProcessing | transforms.py | BboxBase.width | width | The (signed) width of the bounding box. | [
"The",
"(signed)",
"width",
"of",
"the",
"bounding",
"box."
] | def width(self):
points = self.get_points()
return points[1, 0] - points[0, 0] | ['def', 'width(self):', 'points', '=', 'self.get_points()', 'return', 'points[1,', '0]', '-', 'points[0,', '0]'] | 864,957 |
Farama-Foundation/Gymnasium | rendering.py | RenderCollectionV0.reset | reset | Reset the base environment, eventually clear the frame_list, and collect a frame. | [
"Reset",
"the",
"base",
"environment,",
"eventually",
"clear",
"the",
"frame_list,",
"and",
"collect",
"a",
"frame."
] | def reset(self, *, seed: int | None=None, options: dict[str, Any] | None=None) -> tuple[ObsType, dict[str, Any]]:
output = super().reset(seed=seed, options=options)
if self.reset_clean:
self.frame_list = []
self.frame_list.append(super().render())
return output | ['def', 'reset(self,', '*,', 'seed:', 'int', '|', 'None=None,', 'options:', 'dict[str,', 'Any]', '|', 'None=None)', '->', 'tuple[ObsType,', 'dict[str,', 'Any]]:', 'output', '=', 'super().reset(seed=seed,', 'options=options)', 'if', 'self.reset_clean:', 'self.frame_list', '=', '[]', 'self.frame_list.append(super().rende... | 573,180 |
rudranil723/mini-main | _common.py | as_file | as_file | Given a Traversable object, return that object as a path on the local file system in a context manager. | [
"Given",
"a",
"Traversable",
"object,",
"return",
"that",
"object",
"as",
"a",
"path",
"on",
"the",
"local",
"file",
"system",
"in",
"a",
"context",
"manager."
] | def as_file(path):
return _tempfile(path.read_bytes, suffix=path.name) | ['def', 'as_file(path):', 'return', '_tempfile(path.read_bytes,', 'suffix=path.name)'] | 270,413 |
tudelft3d/SUMS-Semantic-Urban-Mesh--public | batch.py | SimpleBatch.num_graphs | num_graphs | Returns the number of graphs in the batch. | [
"Returns",
"the",
"number",
"of",
"graphs",
"in",
"the",
"batch."
] | def num_graphs(self):
return self.batch[-1].item() + 1 | ['def', 'num_graphs(self):', 'return', 'self.batch[-1].item()', '+', '1'] | 910,672 |
Kvatsx/Artificial-Intelligence-Assignments | __init__.py | have_font | have_font | Check if specified system font name is available. | [
"Check",
"if",
"specified",
"system",
"font",
"name",
"is",
"available."
] | def have_font(name):
return _font_class.have_font(name) | ['def', 'have_font(name):', 'return', '_font_class.have_font(name)'] | 76,757 |
caiiiac/Machine-Learning-with-Python | patches.py | _Style.get_styles | get_styles | A class method which returns a dictionary of available styles. | [
"A",
"class",
"method",
"which",
"returns",
"a",
"dictionary",
"of",
"available",
"styles."
] | def get_styles(klass):
return klass._style_list | ['def', 'get_styles(klass):', 'return', 'klass._style_list'] | 715,792 |
openvinotoolkit/training_extensions | hyperband.py | AshaTrial.rung | rung | Rung where the trial is included. | [
"Rung",
"where",
"the",
"trial",
"is",
"included."
] | def rung(self):
return self._rung | ['def', 'rung(self):', 'return', 'self._rung'] | 919,109 |
rudranil723/mini-main | loaddata.py | Command.load_label | load_label | Load fixtures files for a given label. | [
"Load",
"fixtures",
"files",
"for",
"a",
"given",
"label."
] | def load_label(self, fixture_label):
show_progress = self.verbosity >= 3
for (fixture_file, fixture_dir, fixture_name) in self.find_fixtures(fixture_label):
(_, ser_fmt, cmp_fmt) = self.parse_name(os.path.basename(fixture_file))
(open_method, mode) = self.compression_formats[cmp_fmt]
fix... | ['def', 'load_label(self,', 'fixture_label):', 'show_progress', '=', 'self.verbosity', '>=', '3', 'for', '(fixture_file,', 'fixture_dir,', 'fixture_name)', 'in', 'self.find_fixtures(fixture_label):', '(_,', 'ser_fmt,', 'cmp_fmt)', '=', 'self.parse_name(os.path.basename(fixture_file))', '(open_method,', 'mode)', '=', 's... | 315,629 |
openvinotoolkit/training_extensions | dataset.py | ImageTilingDataset.merge_maps | merge_maps | Merge tile-level saliency maps to image-level saliency map. | [
"Merge",
"tile-level",
"saliency",
"maps",
"to",
"image-level",
"saliency",
"map."
] | def merge_maps(self, saliency_maps: List, dump_maps: bool) -> List:
if dump_maps:
return self.tile_dataset.merge_maps(saliency_maps)
else:
return [None] * self.num_samples | ['def', 'merge_maps(self,', 'saliency_maps:', 'List,', 'dump_maps:', 'bool)', '->', 'List:', 'if', 'dump_maps:', 'return', 'self.tile_dataset.merge_maps(saliency_maps)', 'else:', 'return', '[None]', '*', 'self.num_samples'] | 918,060 |
huaweicloud/trace_generation_rnn | loss_stats.py | LossStats.get_tot_examples | get_tot_examples | Return total number of examples processed since beginning. | [
"Return",
"total",
"number",
"of",
"examples",
"processed",
"since",
"beginning."
] | def get_tot_examples(self):
return self.tot_examples | ['def', 'get_tot_examples(self):', 'return', 'self.tot_examples'] | 355,980 |
43Carrig/recurrent_neural_networks_practice | _flag.py | Flag.parse | parse | Parses string and sets flag value. | [
"Parses",
"string",
"and",
"sets",
"flag",
"value."
] | def parse(self, argument):
if self.present and (not self.allow_overwrite):
raise _exceptions.IllegalFlagValueError('flag --%s=%s: already defined as %s' % (self.name, argument, self.value))
self.value = self._parse(argument)
self.present += 1 | ['def', 'parse(self,', 'argument):', 'if', 'self.present', 'and', '(not', 'self.allow_overwrite):', 'raise', "_exceptions.IllegalFlagValueError('flag", '--%s=%s:', 'already', 'defined', 'as', "%s'", '%', '(self.name,', 'argument,', 'self.value))', 'self.value', '=', 'self._parse(argument)', 'self.present', '+=', '1'] | 309,619 |
jonathanking/sidechainnet | errors.py | report_errors | report_errors | Provides a summary of errors after parsing SidechainNet data. | [
"Provides",
"a",
"summary",
"of",
"errors",
"after",
"parsing",
"SidechainNet",
"data."
] | def report_errors(pnids_errorcodes, total_pnids):
print(f'\n{total_pnids} ProteinNet IDs were processed to extract sidechain data.')
error_summarizer = sidechainnet.utils.errors.ProteinErrors()
for (pnid, error_code) in pnids_errorcodes:
error_summarizer.count(error_code, pnid)
error_summarizer.... | ['def', 'report_errors(pnids_errorcodes,', 'total_pnids):', "print(f'\\n{total_pnids}", 'ProteinNet', 'IDs', 'were', 'processed', 'to', 'extract', 'sidechain', "data.')", 'error_summarizer', '=', 'sidechainnet.utils.errors.ProteinErrors()', 'for', '(pnid,', 'error_code)', 'in', 'pnids_errorcodes:', 'error_summarizer.co... | 934,105 |
proxypoke/quickswitch-for-i3 | quickswitch.py | next_empty | next_empty | Return the lowest numbered workspace that is empty. | [
"Return",
"the",
"lowest",
"numbered",
"workspace",
"that",
"is",
"empty."
] | def next_empty():
workspaces = sorted([int(ws) for ws in get_workspaces().keys() if ws.isdecimal()])
for i in range(len(workspaces)):
if workspaces[i] != i + 1:
return str(i + 1)
return str(len(workspaces) + 1) | ['def', 'next_empty():', 'workspaces', '=', 'sorted([int(ws)', 'for', 'ws', 'in', 'get_workspaces().keys()', 'if', 'ws.isdecimal()])', 'for', 'i', 'in', 'range(len(workspaces)):', 'if', 'workspaces[i]', '!=', 'i', '+', '1:', 'return', 'str(i', '+', '1)', 'return', 'str(len(workspaces)', '+', '1)'] | 304,089 |
tobegit3hub/deep_image_model | quantize_graph.py | unique_node_name_from_input | unique_node_name_from_input | Replaces invalid characters in input names to get a unique node name. | [
"Replaces",
"invalid",
"characters",
"in",
"input",
"names",
"to",
"get",
"a",
"unique",
"node",
"name."
] | def unique_node_name_from_input(node_name):
return node_name.replace(':', '__port__').replace('^', '__hat__') | ['def', 'unique_node_name_from_input(node_name):', 'return', "node_name.replace(':',", "'__port__').replace('^',", "'__hat__')"] | 183,523 |
megvii-research/MSCL | resnet3d.py | ResNet3dLayer.train | train | Set the optimization status when training. | [
"Set",
"the",
"optimization",
"status",
"when",
"training."
] | def train(self, mode=True):
super().train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval() | ['def', 'train(self,', 'mode=True):', 'super().train(mode)', 'self._freeze_stages()', 'if', 'mode', 'and', 'self.norm_eval:', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', '_BatchNorm):', 'm.eval()'] | 264,825 |
RasaHQ/rasa | slot_mappings.py | SlotMapping.entity_is_desired | entity_is_desired | Checks whether slot should be filled by an entity in the input or not. | [
"Checks",
"whether",
"slot",
"should",
"be",
"filled",
"by",
"an",
"entity",
"in",
"the",
"input",
"or",
"not."
] | def entity_is_desired(mapping: Dict[Text, Any], tracker: 'DialogueStateTracker') -> bool:
slot_fulfils_entity_mapping = False
if tracker.latest_message:
extracted_entities = tracker.latest_message.entities
else:
extracted_entities = []
for entity in extracted_entities:
if mapping... | ['def', 'entity_is_desired(mapping:', 'Dict[Text,', 'Any],', 'tracker:', "'DialogueStateTracker')", '->', 'bool:', 'slot_fulfils_entity_mapping', '=', 'False', 'if', 'tracker.latest_message:', 'extracted_entities', '=', 'tracker.latest_message.entities', 'else:', 'extracted_entities', '=', '[]', 'for', 'entity', 'in', ... | 837,517 |
ryu-ed/SpaceInvaders_Ros | mask_test.py | MaskTypeTest.test_overlap_area__invalid_offset_arg | test_overlap_area__invalid_offset_arg | Ensure overlap_area handles invalid offset arguments correctly. | [
"Ensure",
"overlap_area",
"handles",
"invalid",
"offset",
"arguments",
"correctly."
] | def test_overlap_area__invalid_offset_arg(self):
size = (7, 2)
offset = '(0, 0)'
mask1 = pygame.mask.Mask(size)
mask2 = pygame.mask.Mask(size)
with self.assertRaises(TypeError):
overlap_count = mask1.overlap_area(mask2, offset) | ['def', 'test_overlap_area__invalid_offset_arg(self):', 'size', '=', '(7,', '2)', 'offset', '=', "'(0,", "0)'", 'mask1', '=', 'pygame.mask.Mask(size)', 'mask2', '=', 'pygame.mask.Mask(size)', 'with', 'self.assertRaises(TypeError):', 'overlap_count', '=', 'mask1.overlap_area(mask2,', 'offset)'] | 369,022 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_pyclbr.py | PyclbrTest.assertHasattr | assertHasattr | succeed iff hasattr(obj,attr) or attr in ignore. | [
"succeed",
"iff",
"hasattr(obj,attr)",
"or",
"attr",
"in",
"ignore."
] | def assertHasattr(self, obj, attr, ignore):
if attr in ignore:
return
if not hasattr(obj, attr):
print('???', attr)
self.assertTrue(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) | ['def', 'assertHasattr(self,', 'obj,', 'attr,', 'ignore):', 'if', 'attr', 'in', 'ignore:', 'return', 'if', 'not', 'hasattr(obj,', 'attr):', "print('???',", 'attr)', 'self.assertTrue(hasattr(obj,', 'attr),', "'expected", 'hasattr(%r,', "%r)'", '%', '(obj,', 'attr))'] | 376,310 |
Cihsaing/RVSL-rvsl-robust-vehicle-similarity-learning--ECCV22 | distributed_fused_adam.py | DistributedFusedAdam.revert_step | revert_step | Revert effect of previously calling partial_step. | [
"Revert",
"effect",
"of",
"previously",
"calling",
"partial_step."
] | def revert_step(self):
combined_scale = self._global_scale
if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm):
combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-06)
combined_scale = self._global_scale / min(1, combined_... | ['def', 'revert_step(self):', 'combined_scale', '=', 'self._global_scale', 'if', "self._param_group['max_grad_norm']", '>', '0', 'and', 'math.isfinite(self.L2_grad_norm):', 'combined_scale', '=', "self._param_group['max_grad_norm']", '/', '(self.L2_grad_norm', '/', 'self._global_scale', '+', '1e-06)', 'combined_scale',... | 327,066 |
Katja-M/Python_NaturalLanguageProcessing | text.py | Text.index | index | Find the index of the first occurrence of the word in the text. | [
"Find",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"of",
"the",
"word",
"in",
"the",
"text."
] | def index(self, word):
return self.tokens.index(word) | ['def', 'index(self,', 'word):', 'return', 'self.tokens.index(word)'] | 865,885 |
astooke/rlpyt | ddpg_agent.py | DdpgAgent.q_at_mu | q_at_mu | Compute Q-value for input state/observation, through the mu_model (with grad). | [
"Compute",
"Q-value",
"for",
"input",
"state/observation,",
"through",
"the",
"mu_model",
"(with",
"grad)."
] | def q_at_mu(self, observation, prev_action, prev_reward):
model_inputs = buffer_to((observation, prev_action, prev_reward), device=self.device)
mu = self.model(*model_inputs)
q = self.q_model(*model_inputs, mu)
return q.cpu() | ['def', 'q_at_mu(self,', 'observation,', 'prev_action,', 'prev_reward):', 'model_inputs', '=', 'buffer_to((observation,', 'prev_action,', 'prev_reward),', 'device=self.device)', 'mu', '=', 'self.model(*model_inputs)', 'q', '=', 'self.q_model(*model_inputs,', 'mu)', 'return', 'q.cpu()'] | 334,472 |
unixpickle/anyrl-py | rollout.py | Rollout.num_steps | num_steps | Get the total number of timesteps (not including the extra observation or previous timesteps for truncated episodes). | [
"Get",
"the",
"total",
"number",
"of",
"timesteps",
"(not",
"including",
"the",
"extra",
"observation",
"or",
"previous",
"timesteps",
"for",
"truncated",
"episodes)."
] | def num_steps(self):
return len(self.rewards) | ['def', 'num_steps(self):', 'return', 'len(self.rewards)'] | 33,656 |
georghess/voxel-mae | encoder_decoder.py | EncoderDecoder3D.encode_decode | encode_decode | Encode points with backbone and decode into a semantic segmentation map of the same size as input. | [
"Encode",
"points",
"with",
"backbone",
"and",
"decode",
"into",
"a",
"semantic",
"segmentation",
"map",
"of",
"the",
"same",
"size",
"as",
"input."
] | def encode_decode(self, points, img_metas):
x = self.extract_feat(points)
out = self._decode_head_forward_test(x, img_metas)
return out | ['def', 'encode_decode(self,', 'points,', 'img_metas):', 'x', '=', 'self.extract_feat(points)', 'out', '=', 'self._decode_head_forward_test(x,', 'img_metas)', 'return', 'out'] | 380,757 |
arshpreetsingh/quantopian-machinelearning | call_tip_widget.py | CallTipWidget.timerEvent | timerEvent | Reimplemented to hide the widget when the hide timer fires. | [
"Reimplemented",
"to",
"hide",
"the",
"widget",
"when",
"the",
"hide",
"timer",
"fires."
] | def timerEvent(self, event):
if event.timerId() == self._hide_timer.timerId():
self._hide_timer.stop()
self.hide() | ['def', 'timerEvent(self,', 'event):', 'if', 'event.timerId()', '==', 'self._hide_timer.timerId():', 'self._hide_timer.stop()', 'self.hide()'] | 892,805 |
aeon-toolkit/aeon | test_all_estimators.py | TestAllObjects.test_estimator_tags | test_estimator_tags | Check conventions on estimator tags. | [
"Check",
"conventions",
"on",
"estimator",
"tags."
] | def test_estimator_tags(self, estimator_class):
Estimator = estimator_class
assert hasattr(Estimator, 'get_class_tags')
all_tags = Estimator.get_class_tags()
assert isinstance(all_tags, dict)
assert all((isinstance(key, str) for key in all_tags.keys()))
if hasattr(Estimator, '_tags'):
ta... | ['def', 'test_estimator_tags(self,', 'estimator_class):', 'Estimator', '=', 'estimator_class', 'assert', 'hasattr(Estimator,', "'get_class_tags')", 'all_tags', '=', 'Estimator.get_class_tags()', 'assert', 'isinstance(all_tags,', 'dict)', 'assert', 'all((isinstance(key,', 'str)', 'for', 'key', 'in', 'all_tags.keys()))',... | 399,848 |
cnr-isti-vclab/TagLab | QtAlignmentToolWidget.py | QtAlignmentToolWidget.onYValueDecremented | onYValueDecremented | Callback called when the y value of the offset changes by -1. | [
"Callback",
"called",
"when",
"the",
"y",
"value",
"of",
"the",
"offset",
"changes",
"by",
"-1."
] | def onYValueDecremented(self) -> None:
self.ySlider.setValue(self.T[1] - 1) | ['def', 'onYValueDecremented(self)', '->', 'None:', 'self.ySlider.setValue(self.T[1]', '-', '1)'] | 906,787 |
tensorflow/quantum | quantum_context_test.py | QContextTest.test_global_engine_mode | test_global_engine_mode | Test getter an setter behavior for engine_mode. | [
"Test",
"getter",
"an",
"setter",
"behavior",
"for",
"engine_mode."
] | def test_global_engine_mode(self):
mode = quantum_context.get_engine_mode()
self.assertFalse(mode)
quantum_context.set_engine_mode(True)
mode = quantum_context.get_engine_mode()
self.assertTrue(mode) | ['def', 'test_global_engine_mode(self):', 'mode', '=', 'quantum_context.get_engine_mode()', 'self.assertFalse(mode)', 'quantum_context.set_engine_mode(True)', 'mode', '=', 'quantum_context.get_engine_mode()', 'self.assertTrue(mode)'] | 835,102 |
asyml/texar-pytorch | xlnet_encoder.py | XLNetEncoder.forward | forward | Compute XLNet representations for the input. | [
"Compute",
"XLNet",
"representations",
"for",
"the",
"input."
] | def forward(self, inputs: Union[torch.Tensor, torch.LongTensor], segment_ids: Optional[torch.LongTensor]=None, input_mask: Optional[torch.Tensor]=None, memory: Optional[List[torch.Tensor]]=None, permute_mask: Optional[torch.Tensor]=None, target_mapping: Optional[torch.Tensor]=None, bi_data: bool=False, clamp_len: Optio... | ['def', 'forward(self,', 'inputs:', 'Union[torch.Tensor,', 'torch.LongTensor],', 'segment_ids:', 'Optional[torch.LongTensor]=None,', 'input_mask:', 'Optional[torch.Tensor]=None,', 'memory:', 'Optional[List[torch.Tensor]]=None,', 'permute_mask:', 'Optional[torch.Tensor]=None,', 'target_mapping:', 'Optional[torch.Tensor]... | 925,240 |
alibaba-mmai-research/HiCo | misc.py | params_count | params_count | Compute the number of parameters. | [
"Compute",
"the",
"number",
"of",
"parameters."
] | def params_count(model):
return np.sum([p.numel() for p in model.parameters()]).item() | ['def', 'params_count(model):', 'return', 'np.sum([p.numel()', 'for', 'p', 'in', 'model.parameters()]).item()'] | 206,269 |
tobegit3hub/deep_image_model | timeline.py | _ChromeTraceFormatter.emit_pid | emit_pid | Adds a process metadata event to the trace. | [
"Adds",
"a",
"process",
"metadata",
"event",
"to",
"the",
"trace."
] | def emit_pid(self, name, pid):
event = {}
event['name'] = 'process_name'
event['ph'] = 'M'
event['pid'] = pid
event['args'] = {'name': name}
self._metadata.append(event) | ['def', 'emit_pid(self,', 'name,', 'pid):', 'event', '=', '{}', "event['name']", '=', "'process_name'", "event['ph']", '=', "'M'", "event['pid']", '=', 'pid', "event['args']", '=', "{'name':", 'name}', 'self._metadata.append(event)'] | 182,290 |
krfricke/rl-benchmark | transform.py | to_timeseries | to_timeseries | Convert benchmark data to timeseries data, plottable my mathplotlib. | [
"Convert",
"benchmark",
"data",
"to",
"timeseries",
"data,",
"plottable",
"my",
"mathplotlib."
] | def to_timeseries(benchmark_data, x_label='Episode', y_label='Average Episode Reward', target=rewards_by_episode, cut_x=1000000000000.0, smooth=0):
(data_experiments, data_times, data_values) = ([], [], [])
for (experiment_id, experiment_data) in enumerate(benchmark_data):
extended_results = experiment_... | ['def', 'to_timeseries(benchmark_data,', "x_label='Episode',", "y_label='Average", 'Episode', "Reward',", 'target=rewards_by_episode,', 'cut_x=1000000000000.0,', 'smooth=0):', '(data_experiments,', 'data_times,', 'data_values)', '=', '([],', '[],', '[])', 'for', '(experiment_id,', 'experiment_data)', 'in', 'enumerate(b... | 841,802 |
yuwen41200/nlp | get_vocab.py | get_vocab | get_vocab | Builds vocabulary file from field 'segmented_paragraphs' and 'segmented_question'. | [
"Builds",
"vocabulary",
"file",
"from",
"field",
"'segmented_paragraphs'",
"and",
"'segmented_question'."
] | def get_vocab(files, vocab_file):
vocab = {}
for f in files:
with open(f, 'r') as fin:
for line in fin:
obj = json.loads(line.strip())
paras = [chain(*d['segmented_paragraphs']) for d in obj['documents']]
doc_tokens = chain(*paras)
... | ['def', 'get_vocab(files,', 'vocab_file):', 'vocab', '=', '{}', 'for', 'f', 'in', 'files:', 'with', 'open(f,', "'r')", 'as', 'fin:', 'for', 'line', 'in', 'fin:', 'obj', '=', 'json.loads(line.strip())', 'paras', '=', "[chain(*d['segmented_paragraphs'])", 'for', 'd', 'in', "obj['documents']]", 'doc_tokens', '=', 'chain(*... | 808,885 |
ahthie7u/cockpit | run.py | lr_schedule | lr_schedule | Some Learning rate schedule. | [
"Some",
"Learning",
"rate",
"schedule."
] | def lr_schedule(num_epochs):
return lambda epoch: 0.0 | ['def', 'lr_schedule(num_epochs):', 'return', 'lambda', 'epoch:', '0.0'] | 493,236 |
exiawsh/StreamPETR | visual_nuscenes.py | NuScenes.get_sample_data_path | get_sample_data_path | Returns the path to a sample_data. | [
"Returns",
"the",
"path",
"to",
"a",
"sample_data."
] | def get_sample_data_path(self, sample_data_token: str) -> str:
sd_record = self.get('sample_data', sample_data_token)
return osp.join(self.dataroot, sd_record['filename']) | ['def', 'get_sample_data_path(self,', 'sample_data_token:', 'str)', '->', 'str:', 'sd_record', '=', "self.get('sample_data',", 'sample_data_token)', 'return', 'osp.join(self.dataroot,', "sd_record['filename'])"] | 910,102 |
SergiosKar/Deep-Learning-models | train_imagenet_resnet_hvd.py | fp32_trainable_vars | fp32_trainable_vars | A varible scope with custom variable getter to convert fp16 trainable variables with fp32 storage followed by fp16 cast. | [
"A",
"varible",
"scope",
"with",
"custom",
"variable",
"getter",
"to",
"convert",
"fp16",
"trainable",
"variables",
"with",
"fp32",
"storage",
"followed",
"by",
"fp16",
"cast."
] | def fp32_trainable_vars(name='fp32_vars', *args, **kwargs):
return tf.variable_scope(name, *args, custom_getter=_fp32_trainvar_getter, **kwargs) | ['def', "fp32_trainable_vars(name='fp32_vars',", '*args,', '**kwargs):', 'return', 'tf.variable_scope(name,', '*args,', 'custom_getter=_fp32_trainvar_getter,', '**kwargs)'] | 518,799 |
intelligent-environments-lab/CityLearn | building.py | DynamicsBuilding.simulate_dynamics | simulate_dynamics | Whether to predict indoor dry-bulb temperature at current `time_step`. | [
"Whether",
"to",
"predict",
"indoor",
"dry-bulb",
"temperature",
"at",
"current",
"`time_step`."
] | def simulate_dynamics(self) -> bool:
return not self.ignore_dynamics | ['def', 'simulate_dynamics(self)', '->', 'bool:', 'return', 'not', 'self.ignore_dynamics'] | 105,631 |
zihuitang/medical_AI_platform | datetime.py | date.replace | replace | Return a new date with new values for the specified fields. | [
"Return",
"a",
"new",
"date",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields."
] | def replace(self, year=None, month=None, day=None):
if year is None:
year = self._year
if month is None:
month = self._month
if day is None:
day = self._day
return date(year, month, day) | ['def', 'replace(self,', 'year=None,', 'month=None,', 'day=None):', 'if', 'year', 'is', 'None:', 'year', '=', 'self._year', 'if', 'month', 'is', 'None:', 'month', '=', 'self._month', 'if', 'day', 'is', 'None:', 'day', '=', 'self._day', 'return', 'date(year,', 'month,', 'day)'] | 280,287 |
DPerrySvendsen/COS30002 | world.py | World.transform_points | transform_points | Transform the given list of points, using the provided position, direction and scale, to object world space. | [
"Transform",
"the",
"given",
"list",
"of",
"points,",
"using",
"the",
"provided",
"position,",
"direction",
"and",
"scale,",
"to",
"object",
"world",
"space."
] | def transform_points(self, points, pos, forward, side, scale):
wld_pts = [pt.copy() for pt in points]
mat = Matrix33()
mat.scale_update(scale.x, scale.y)
mat.rotate_by_vectors_update(forward, side)
mat.translate_update(pos.x, pos.y)
mat.transform_vector2d_list(wld_pts)
return wld_pts | ['def', 'transform_points(self,', 'points,', 'pos,', 'forward,', 'side,', 'scale):', 'wld_pts', '=', '[pt.copy()', 'for', 'pt', 'in', 'points]', 'mat', '=', 'Matrix33()', 'mat.scale_update(scale.x,', 'scale.y)', 'mat.rotate_by_vectors_update(forward,', 'side)', 'mat.translate_update(pos.x,', 'pos.y)', 'mat.transform_ve... | 137,384 |
tencent-ailab/TriNet | meters.py | Meter.smoothed_value | smoothed_value | Smoothed value used for logging. | [
"Smoothed",
"value",
"used",
"for",
"logging."
] | def smoothed_value(self) -> float:
raise NotImplementedError | ['def', 'smoothed_value(self)', '->', 'float:', 'raise', 'NotImplementedError'] | 425,264 |
mme/vergeml | loader.py | Loader.num_samples | num_samples | Get the number of samples in split. | [
"Get",
"the",
"number",
"of",
"samples",
"in",
"split."
] | def num_samples(self, split: str) -> int:
return len(self.cache[split]) | ['def', 'num_samples(self,', 'split:', 'str)', '->', 'int:', 'return', 'len(self.cache[split])'] | 931,556 |
google-research/scenic | lr_schedules.py | get_learning_rate_fn | get_learning_rate_fn | Looks up for the learning rate scheduler and return lr_fn. | [
"Looks",
"up",
"for",
"the",
"learning",
"rate",
"scheduler",
"and",
"return",
"lr_fn."
] | def get_learning_rate_fn(config: ml_collections.ConfigDict):
if 'base_learning_rate' not in config.lr_configs:
raise ValueError('`base_learning_rate` has to be defined in the lr_config.')
if not config.lr_configs.base_learning_rate:
pass
if 'learning_rate_schedule' in config.lr_configs:
... | ['def', 'get_learning_rate_fn(config:', 'ml_collections.ConfigDict):', 'if', "'base_learning_rate'", 'not', 'in', 'config.lr_configs:', 'raise', "ValueError('`base_learning_rate`", 'has', 'to', 'be', 'defined', 'in', 'the', "lr_config.')", 'if', 'not', 'config.lr_configs.base_learning_rate:', 'pass', 'if', "'learning_r... | 847,610 |
Speedwagon13/CS-3600-Introduction-to-- | inspect.py | isabstract | isabstract | Return true if the object is an abstract base class (ABC). | [
"Return",
"true",
"if",
"the",
"object",
"is",
"an",
"abstract",
"base",
"class",
"(ABC)."
] | def isabstract(object):
return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) | ['def', 'isabstract(object):', 'return', 'bool(isinstance(object,', 'type)', 'and', 'object.__flags__', '&', 'TPFLAGS_IS_ABSTRACT)'] | 139,835 |
PopovicMilica/MonteCarlo_simulation_average_treatment_effect | MonteCarlo_simulation_for_average_treatment_effects_using_NNs.py | running_time | running_time | Print the time passed since start_time. | [
"Print",
"the",
"time",
"passed",
"since",
"start_time."
] | def running_time():
end_time = time.time()
hours = int((end_time - start_time) / 3600)
minutes = int((end_time - start_time) % 3600 / 60)
seconds = int(end_time - start_time - (3600 * hours + 60 * minutes))
print('Running time is: {} hours, {} minutes and {} seconds'.format(hours, minutes, seconds)) | ['def', 'running_time():', 'end_time', '=', 'time.time()', 'hours', '=', 'int((end_time', '-', 'start_time)', '/', '3600)', 'minutes', '=', 'int((end_time', '-', 'start_time)', '%', '3600', '/', '60)', 'seconds', '=', 'int(end_time', '-', 'start_time', '-', '(3600', '*', 'hours', '+', '60', '*', 'minutes))', "print('Ru... | 655,639 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_statistics.py | TestNumericTestCase.generate_substrings | generate_substrings | Return substrings we expect to see in error messages. | [
"Return",
"substrings",
"we",
"expect",
"to",
"see",
"in",
"error",
"messages."
] | def generate_substrings(self, first, second, tol, rel, idx):
(abs_err, rel_err) = _calc_errors(first, second)
substrings = ['tol=%r' % tol, 'rel=%r' % rel, 'absolute error = %r' % abs_err, 'relative error = %r' % rel_err]
if idx is not None:
substrings.append('differ at index %d' % idx)
return s... | ['def', 'generate_substrings(self,', 'first,', 'second,', 'tol,', 'rel,', 'idx):', '(abs_err,', 'rel_err)', '=', '_calc_errors(first,', 'second)', 'substrings', '=', "['tol=%r'", '%', 'tol,', "'rel=%r'", '%', 'rel,', "'absolute", 'error', '=', "%r'", '%', 'abs_err,', "'relative", 'error', '=', "%r'", '%', 'rel_err]', '... | 376,384 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.