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 |
|---|---|---|---|---|---|---|---|---|
intel/neural-compressor | sigopt.py | SigOptTuneStrategy.params_to_tune_configs | params_to_tune_configs | Get the parameters of the tuning strategy. | [
"Get",
"the",
"parameters",
"of",
"the",
"tuning",
"strategy."
] | def params_to_tune_configs(self, params):
op_tuning_cfg = {}
calib_sampling_size_lst = self.tuning_space.root_item.get_option_by_name('calib_sampling_size').options
for (op_name_type, configs) in self.op_configs.items():
if len(configs) == 1:
op_tuning_cfg[op_name_type] = configs[0]
... | ['def', 'params_to_tune_configs(self,', 'params):', 'op_tuning_cfg', '=', '{}', 'calib_sampling_size_lst', '=', "self.tuning_space.root_item.get_option_by_name('calib_sampling_size').options", 'for', '(op_name_type,', 'configs)', 'in', 'self.op_configs.items():', 'if', 'len(configs)', '==', '1:', 'op_tuning_cfg[op_name... | 738,463 |
scikit-learn/scikit-learn | test_forest.py | test_forest_regressor_oob | test_forest_regressor_oob | Check that forest-based regressor provide an OOB score close to the score on a test set. | [
"Check",
"that",
"forest-based",
"regressor",
"provide",
"an",
"OOB",
"score",
"close",
"to",
"the",
"score",
"on",
"a",
"test",
"set."
] | def test_forest_regressor_oob(ForestRegressor, X, y, X_type, lower_bound_r2, oob_score):
X = _convert_container(X, constructor_name=X_type)
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.5, random_state=0)
regressor = ForestRegressor(n_estimators=50, bootstrap=True, oob_score=oob_sc... | ['def', 'test_forest_regressor_oob(ForestRegressor,', 'X,', 'y,', 'X_type,', 'lower_bound_r2,', 'oob_score):', 'X', '=', '_convert_container(X,', 'constructor_name=X_type)', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X,', 'y,', 'test_size=0.5,', 'random_state=0)', 'regressor', '=', 'ForestReg... | 853,164 |
loicmarie/hands-detection | real_nvp_utils.py | squeeze_2x2_ordered | squeeze_2x2_ordered | Squeezing operation with a controlled ordering. | [
"Squeezing",
"operation",
"with",
"a",
"controlled",
"ordering."
] | def squeeze_2x2_ordered(input_, reverse=False):
shape = input_.get_shape().as_list()
batch_size = shape[0]
height = shape[1]
width = shape[2]
channels = shape[3]
if reverse:
if channels % 4 != 0:
raise ValueError('Number of channels not divisible by 4.')
channels /= 4... | ['def', 'squeeze_2x2_ordered(input_,', 'reverse=False):', 'shape', '=', 'input_.get_shape().as_list()', 'batch_size', '=', 'shape[0]', 'height', '=', 'shape[1]', 'width', '=', 'shape[2]', 'channels', '=', 'shape[3]', 'if', 'reverse:', 'if', 'channels', '%', '4', '!=', '0:', 'raise', "ValueError('Number", 'of', 'channel... | 575,182 |
PaddlePaddle/Paddle3D | transformer.py | PerceptionTransformer.init_layers | init_layers | Initialize layers of the Detr3DTransformer. | [
"Initialize",
"layers",
"of",
"the",
"Detr3DTransformer."
] | def init_layers(self):
level_embeds = self.create_parameter((self.num_feature_levels, self.embed_dims))
self.add_parameter('level_embeds', level_embeds)
cams_embeds = self.create_parameter((self.num_cams, self.embed_dims))
self.add_parameter('cams_embeds', cams_embeds)
self.reference_points = nn.Lin... | ['def', 'init_layers(self):', 'level_embeds', '=', 'self.create_parameter((self.num_feature_levels,', 'self.embed_dims))', "self.add_parameter('level_embeds',", 'level_embeds)', 'cams_embeds', '=', 'self.create_parameter((self.num_cams,', 'self.embed_dims))', "self.add_parameter('cams_embeds',", 'cams_embeds)', 'self.r... | 777,854 |
lhotse-speech/lhotse | librimix.py | librimix | librimix | LibrMix source separation data preparation. | [
"LibrMix",
"source",
"separation",
"data",
"preparation."
] | def librimix(librimix_csv: Pathlike, output_dir: Pathlike, sampling_rate: int, min_segment_seconds: float, with_precomputed_mixtures: bool):
prepare_librimix(librimix_csv=librimix_csv, output_dir=output_dir, sampling_rate=sampling_rate, min_segment_seconds=min_segment_seconds, with_precomputed_mixtures=with_precomp... | ['def', 'librimix(librimix_csv:', 'Pathlike,', 'output_dir:', 'Pathlike,', 'sampling_rate:', 'int,', 'min_segment_seconds:', 'float,', 'with_precomputed_mixtures:', 'bool):', 'prepare_librimix(librimix_csv=librimix_csv,', 'output_dir=output_dir,', 'sampling_rate=sampling_rate,', 'min_segment_seconds=min_segment_seconds... | 600,613 |
enuguru/artificial_intelligence_and_machine_ | util.py | conforms_partial_ordering | conforms_partial_ordering | True if the given sorting conforms to the given partial ordering. | [
"True",
"if",
"the",
"given",
"sorting",
"conforms",
"to",
"the",
"given",
"partial",
"ordering."
] | def conforms_partial_ordering(tuples, sorted_elements):
deps = defaultdict(set)
for (parent, child) in tuples:
deps[parent].add(child)
for (i, node) in enumerate(sorted_elements):
for n in sorted_elements[i:]:
if node in deps[n]:
return False
else:
ret... | ['def', 'conforms_partial_ordering(tuples,', 'sorted_elements):', 'deps', '=', 'defaultdict(set)', 'for', '(parent,', 'child)', 'in', 'tuples:', 'deps[parent].add(child)', 'for', '(i,', 'node)', 'in', 'enumerate(sorted_elements):', 'for', 'n', 'in', 'sorted_elements[i:]:', 'if', 'node', 'in', 'deps[n]:', 'return', 'Fal... | 131,842 |
enuguru/artificial_intelligence_and_machine_ | wrappers.py | is_known_charset | is_known_charset | Checks if the given charset is known to Python. | [
"Checks",
"if",
"the",
"given",
"charset",
"is",
"known",
"to",
"Python."
] | def is_known_charset(charset):
try:
codecs.lookup(charset)
except LookupError:
return False
return True | ['def', 'is_known_charset(charset):', 'try:', 'codecs.lookup(charset)', 'except', 'LookupError:', 'return', 'False', 'return', 'True'] | 132,741 |
PJLab-ADG/LoGoNet | test_head.py | test_yolov3_head_forward | test_yolov3_head_forward | Test Yolov3 head forward() in torch and ort env. | [
"Test",
"Yolov3",
"head",
"forward()",
"in",
"torch",
"and",
"ort",
"env."
] | def test_yolov3_head_forward():
yolo_model = yolo_config()
feats = [torch.rand(1, 1, 64 // 2 ** (i + 2), 64 // 2 ** (i + 2)) for i in range(len(yolo_model.in_channels))]
wrap_model = WrapFunction(yolo_model.forward)
ort_validate(wrap_model, feats) | ['def', 'test_yolov3_head_forward():', 'yolo_model', '=', 'yolo_config()', 'feats', '=', '[torch.rand(1,', '1,', '64', '//', '2', '**', '(i', '+', '2),', '64', '//', '2', '**', '(i', '+', '2))', 'for', 'i', 'in', 'range(len(yolo_model.in_channels))]', 'wrap_model', '=', 'WrapFunction(yolo_model.forward)', 'ort_validate... | 615,481 |
rwth-i6/returnn | stereo.py | StereoHdfDataset.num_seqs | num_seqs | Returns the number of sequences of the dataset :rtype: int :return: the number of sequences of the dataset. | [
"Returns",
"the",
"number",
"of",
"sequences",
"of",
"the",
"dataset",
":rtype:",
"int",
":return:",
"the",
"number",
"of",
"sequences",
"of",
"the",
"dataset."
] | def num_seqs(self):
if self._num_seqs is not None:
return self._num_seqs
self._num_seqs = self._calculateNumberOfSequences()
return self._num_seqs | ['def', 'num_seqs(self):', 'if', 'self._num_seqs', 'is', 'not', 'None:', 'return', 'self._num_seqs', 'self._num_seqs', '=', 'self._calculateNumberOfSequences()', 'return', 'self._num_seqs'] | 346,598 |
weimin17/Object-Detection_HelmetDetection | estimator_util.py | create_model_fn | create_model_fn | Wraps model_class as an Estimator or TPUEstimator model_fn. | [
"Wraps",
"model_class",
"as",
"an",
"Estimator",
"or",
"TPUEstimator",
"model_fn."
] | def create_model_fn(model_class, hparams, use_tpu=False):
hparams = copy.deepcopy(hparams)
def model_fn(features, labels, mode, params):
if 'batch_size' in params:
hparams.batch_size = params['batch_size']
if 'labels' in features:
if labels is not None and labels is not ... | ['def', 'create_model_fn(model_class,', 'hparams,', 'use_tpu=False):', 'hparams', '=', 'copy.deepcopy(hparams)', 'def', 'model_fn(features,', 'labels,', 'mode,', 'params):', 'if', "'batch_size'", 'in', 'params:', 'hparams.batch_size', '=', "params['batch_size']", 'if', "'labels'", 'in', 'features:', 'if', 'labels', 'is... | 761,636 |
scikit-learn/scikit-learn | test_affinity_propagation.py | test_affinity_propagation_precomputed | test_affinity_propagation_precomputed | Check equality of precomputed affinity matrix to internally computed affinity matrix. | [
"Check",
"equality",
"of",
"precomputed",
"affinity",
"matrix",
"to",
"internally",
"computed",
"affinity",
"matrix."
] | def test_affinity_propagation_precomputed():
S = -euclidean_distances(X, squared=True)
preference = np.median(S) * 10
af = AffinityPropagation(preference=preference, affinity='precomputed', random_state=28)
labels_precomputed = af.fit(S).labels_
af = AffinityPropagation(preference=preference, verbos... | ['def', 'test_affinity_propagation_precomputed():', 'S', '=', '-euclidean_distances(X,', 'squared=True)', 'preference', '=', 'np.median(S)', '*', '10', 'af', '=', 'AffinityPropagation(preference=preference,', "affinity='precomputed',", 'random_state=28)', 'labels_precomputed', '=', 'af.fit(S).labels_', 'af', '=', 'Affi... | 852,818 |
eddylau328/fyp-artificial-intelligence-ac-control-device | face.py | RpcContext.add_abortion_callback | add_abortion_callback | Registers a callback to be called if the RPC is aborted. | [
"Registers",
"a",
"callback",
"to",
"be",
"called",
"if",
"the",
"RPC",
"is",
"aborted."
] | def add_abortion_callback(self, abortion_callback):
raise NotImplementedError() | ['def', 'add_abortion_callback(self,', 'abortion_callback):', 'raise', 'NotImplementedError()'] | 215,679 |
greydanus/pythonic_ocr | compiler.py | CodeGenerator.position | position | Return a human readable position for the node. | [
"Return",
"a",
"human",
"readable",
"position",
"for",
"the",
"node."
] | def position(self, node):
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv | ['def', 'position(self,', 'node):', 'rv', '=', "'line", "%d'", '%', 'node.lineno', 'if', 'self.name', 'is', 'not', 'None:', 'rv', '+=', "'", 'in', "'", '+', 'repr(self.name)', 'return', 'rv'] | 299,205 |
googleapis/python-aiplatform | test_ray_prediction.py | TestPredictionFunctionality.test_register_xgboostartifact_uri_not_gcs_uri_raise_error | test_register_xgboostartifact_uri_not_gcs_uri_raise_error | Test if a XGBoostCheckpoint upload gives ValueError. | [
"Test",
"if",
"a",
"XGBoostCheckpoint",
"upload",
"gives",
"ValueError."
] | def test_register_xgboostartifact_uri_not_gcs_uri_raise_error(self, ray_xgboost_checkpoint) -> None:
with pytest.raises(ValueError) as ve:
prediction_xgboost.register_xgboost(checkpoint=ray_xgboost_checkpoint, artifact_uri=tc.ProjectConstants._TEST_BAD_ARTIFACT_URI)
assert ve.match(regexp=".*'artifact_u... | ['def', 'test_register_xgboostartifact_uri_not_gcs_uri_raise_error(self,', 'ray_xgboost_checkpoint)', '->', 'None:', 'with', 'pytest.raises(ValueError)', 'as', 've:', 'prediction_xgboost.register_xgboost(checkpoint=ray_xgboost_checkpoint,', 'artifact_uri=tc.ProjectConstants._TEST_BAD_ARTIFACT_URI)', 'assert', 've.match... | 863,117 |
RasaHQ/rasa | story_step_builder.py | StoryStepBuilder.add_checkpoint | add_checkpoint | Add a checkpoint to story steps. | [
"Add",
"a",
"checkpoint",
"to",
"story",
"steps."
] | def add_checkpoint(self, name: Text, conditions: Optional[Dict[Text, Any]]) -> None:
if not self.current_steps:
self.start_checkpoints.append(Checkpoint(name, conditions))
else:
if conditions:
rasa.shared.utils.io.raise_warning(f'End or intermediate checkpoints do not support conditi... | ['def', 'add_checkpoint(self,', 'name:', 'Text,', 'conditions:', 'Optional[Dict[Text,', 'Any]])', '->', 'None:', 'if', 'not', 'self.current_steps:', 'self.start_checkpoints.append(Checkpoint(name,', 'conditions))', 'else:', 'if', 'conditions:', "rasa.shared.utils.io.raise_warning(f'End", 'or', 'intermediate', 'checkpoi... | 837,588 |
surafelml/adapt-mnmt | vocab_backup.py | Vocab.add_from_text | add_from_text | Fills the vocabulary from a text file. | [
"Fills",
"the",
"vocabulary",
"from",
"a",
"text",
"file."
] | def add_from_text(self, filename, tokenizer=None):
with tf.gfile.GFile(filename, mode='rb') as text:
for line in text:
line = tf.compat.as_text(line.strip())
if tokenizer:
tokens = tokenizer.tokenize(line)
else:
tokens = line.split()
... | ['def', 'add_from_text(self,', 'filename,', 'tokenizer=None):', 'with', 'tf.gfile.GFile(filename,', "mode='rb')", 'as', 'text:', 'for', 'line', 'in', 'text:', 'line', '=', 'tf.compat.as_text(line.strip())', 'if', 'tokenizer:', 'tokens', '=', 'tokenizer.tokenize(line)', 'else:', 'tokens', '=', 'line.split()', 'for', 'to... | 407,897 |
cheind/gcsl | robot_env.py | RobotEnv.get_done | get_done | Returns whether the episode should terminate. | [
"Returns",
"whether",
"the",
"episode",
"should",
"terminate."
] | def get_done(self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray]) -> np.ndarray:
del obs_dict
return np.zeros_like(next(iter(reward_dict.values())), dtype=bool) | ['def', 'get_done(self,', 'obs_dict:', 'Dict[str,', 'np.ndarray],', 'reward_dict:', 'Dict[str,', 'np.ndarray])', '->', 'np.ndarray:', 'del', 'obs_dict', 'return', 'np.zeros_like(next(iter(reward_dict.values())),', 'dtype=bool)'] | 201,616 |
lightonai/dfa-scales-to-modern-deep-learning | tiny_nerf.py | render_volume_density | render_volume_density | Differentiably renders a radiance field, given the origin of each ray in the "bundle", and the sampled depth values along them. | [
"Differentiably",
"renders",
"a",
"radiance",
"field,",
"given",
"the",
"origin",
"of",
"each",
"ray",
"in",
"the",
"\"bundle\",",
"and",
"the",
"sampled",
"depth",
"values",
"along",
"them."
] | def render_volume_density(radiance_field: torch.Tensor, ray_origins: torch.Tensor, depth_values: torch.Tensor) -> (torch.Tensor, torch.Tensor, torch.Tensor):
sigma_a = torch.nn.functional.relu(radiance_field[..., 3])
rgb = torch.sigmoid(radiance_field[..., :3])
one_e_10 = torch.tensor([10000000000.0], dtype... | ['def', 'render_volume_density(radiance_field:', 'torch.Tensor,', 'ray_origins:', 'torch.Tensor,', 'depth_values:', 'torch.Tensor)', '->', '(torch.Tensor,', 'torch.Tensor,', 'torch.Tensor):', 'sigma_a', '=', 'torch.nn.functional.relu(radiance_field[...,', '3])', 'rgb', '=', 'torch.sigmoid(radiance_field[...,', ':3])', ... | 550,017 |
tobegit3hub/deep_image_model | dataframe.py | DataFrame.exclude_columns | exclude_columns | Returns a new DataFrame with all columns not excluded via exclude_keys. | [
"Returns",
"a",
"new",
"DataFrame",
"with",
"all",
"columns",
"not",
"excluded",
"via",
"exclude_keys."
] | def exclude_columns(self, exclude_keys):
result = type(self)()
for (key, value) in self._columns.items():
if key not in exclude_keys:
result[key] = value
return result | ['def', 'exclude_columns(self,', 'exclude_keys):', 'result', '=', 'type(self)()', 'for', '(key,', 'value)', 'in', 'self._columns.items():', 'if', 'key', 'not', 'in', 'exclude_keys:', 'result[key]', '=', 'value', 'return', 'result'] | 181,592 |
srai-lab/srai | test_contextual_count_embedder.py | test_incorrect_indexes | test_incorrect_indexes | Test if cannot embed with incorrect dataframe indexes. | [
"Test",
"if",
"cannot",
"embed",
"with",
"incorrect",
"dataframe",
"indexes."
] | def test_incorrect_indexes(regions_fixture: str, features_fixture: str, joint_fixture: str, concatenate_features: bool, count_subcategories: bool, neighbourhood_distance: int, expectation: Any, request: Any) -> None:
regions_gdf = request.getfixturevalue(regions_fixture)
features_gdf = request.getfixturevalue(f... | ['def', 'test_incorrect_indexes(regions_fixture:', 'str,', 'features_fixture:', 'str,', 'joint_fixture:', 'str,', 'concatenate_features:', 'bool,', 'count_subcategories:', 'bool,', 'neighbourhood_distance:', 'int,', 'expectation:', 'Any,', 'request:', 'Any)', '->', 'None:', 'regions_gdf', '=', 'request.getfixturevalue(... | 371,954 |
chribsen/simple-machine-learning-examples | var.py | VAR.bic | bic | Returns the Bayesian information criterion. | [
"Returns",
"the",
"Bayesian",
"information",
"criterion."
] | def bic(self):
return self._ic['bic'] | ['def', 'bic(self):', 'return', "self._ic['bic']"] | 936,602 |
PaddlePaddle/PARL | cluster_monitor.py | ClusterMonitor.drop_worker_status | drop_worker_status | Drop worker status when it exits. | [
"Drop",
"worker",
"status",
"when",
"it",
"exits."
] | def drop_worker_status(self, worker_address):
self.lock.acquire()
self.status['workers'].pop(worker_address)
self.lock.release() | ['def', 'drop_worker_status(self,', 'worker_address):', 'self.lock.acquire()', "self.status['workers'].pop(worker_address)", 'self.lock.release()'] | 278,084 |
triaquae/triaquae | query.py | QuerySet.latest | latest | Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name. | [
"Returns",
"the",
"latest",
"object,",
"according",
"to",
"the",
"model's",
"'get_latest_by'",
"option",
"or",
"optional",
"given",
"field_name."
] | def latest(self, field_name=None):
latest_by = field_name or self.model._meta.get_latest_by
assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model"
assert self.query.can_filter(), 'Cannot change a query once a slice has been taken.'
obj = self._clone()
... | ['def', 'latest(self,', 'field_name=None):', 'latest_by', '=', 'field_name', 'or', 'self.model._meta.get_latest_by', 'assert', 'bool(latest_by),', '"latest()', 'requires', 'either', 'a', 'field_name', 'parameter', 'or', "'get_latest_by'", 'in', 'the', 'model"', 'assert', 'self.query.can_filter(),', "'Cannot", 'change',... | 423,475 |
Ruturaj123/Flowchart-Detection | losses.py | per_example_squared_loss | per_example_squared_loss | Squared loss given labels, example weights and predictions. | [
"Squared",
"loss",
"given",
"labels,",
"example",
"weights",
"and",
"predictions."
] | def per_example_squared_loss(labels, weights, predictions):
unweighted_loss = math_ops.reduce_sum(math_ops.square(predictions - labels), 1, keep_dims=True)
return (unweighted_loss * weights, control_flow_ops.no_op()) | ['def', 'per_example_squared_loss(labels,', 'weights,', 'predictions):', 'unweighted_loss', '=', 'math_ops.reduce_sum(math_ops.square(predictions', '-', 'labels),', '1,', 'keep_dims=True)', 'return', '(unweighted_loss', '*', 'weights,', 'control_flow_ops.no_op())'] | 586,909 |
kubeflow/pipelines | dataproc_util.py | DataprocBatchRemoteRunner.create_batch | create_batch | Common function for creating a batch workload. | [
"Common",
"function",
"for",
"creating",
"a",
"batch",
"workload."
] | def create_batch(self, batch_id: str, batch_request: Dict[str, Any]) -> Dict[str, Any]:
create_batch_url = f'https://dataproc.googleapis.com/v1/projects/{self._project}/locations/{self._location}/batches/?batchId={batch_id}'
lro = self._post_resource(create_batch_url, json.dumps(batch_request))
try:
... | ['def', 'create_batch(self,', 'batch_id:', 'str,', 'batch_request:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', 'create_batch_url', '=', "f'https://dataproc.googleapis.com/v1/projects/{self._project}/locations/{self._location}/batches/?batchId={batch_id}'", 'lro', '=', 'self._post_resource(create_batch_url,', 'j... | 770,796 |
zihuitang/medical_AI_platform | clinic.py | DSLParser.state_terminal | state_terminal | Called when processing the block is done. | [
"Called",
"when",
"processing",
"the",
"block",
"is",
"done."
] | def state_terminal(self, line):
assert not line
if not self.function:
return
if self.keyword_only:
values = self.function.parameters.values()
if not values:
no_parameter_after_star = True
else:
last_parameter = next(reversed(list(values)))
... | ['def', 'state_terminal(self,', 'line):', 'assert', 'not', 'line', 'if', 'not', 'self.function:', 'return', 'if', 'self.keyword_only:', 'values', '=', 'self.function.parameters.values()', 'if', 'not', 'values:', 'no_parameter_after_star', '=', 'True', 'else:', 'last_parameter', '=', 'next(reversed(list(values)))', 'no_... | 284,722 |
fudan-zvg/SETR | transforms.py | roi2bbox | roi2bbox | Convert rois to bounding box format. | [
"Convert",
"rois",
"to",
"bounding",
"box",
"format."
] | def roi2bbox(rois):
bbox_list = []
img_ids = torch.unique(rois[:, 0].cpu(), sorted=True)
for img_id in img_ids:
inds = rois[:, 0] == img_id.item()
bbox = rois[inds, 1:]
bbox_list.append(bbox)
return bbox_list | ['def', 'roi2bbox(rois):', 'bbox_list', '=', '[]', 'img_ids', '=', 'torch.unique(rois[:,', '0].cpu(),', 'sorted=True)', 'for', 'img_id', 'in', 'img_ids:', 'inds', '=', 'rois[:,', '0]', '==', 'img_id.item()', 'bbox', '=', 'rois[inds,', '1:]', 'bbox_list.append(bbox)', 'return', 'bbox_list'] | 897,762 |
open-mmlab/mmcv | transformer.py | build_transformer_layer | build_transformer_layer | Builder for transformer layer. | [
"Builder",
"for",
"transformer",
"layer."
] | def build_transformer_layer(cfg, default_args=None):
return MODELS.build(cfg, default_args=default_args) | ['def', 'build_transformer_layer(cfg,', 'default_args=None):', 'return', 'MODELS.build(cfg,', 'default_args=default_args)'] | 631,438 |
AndrewYinLi/lstm-neural-network-spam-filter | dependencygraph.py | DependencyGraph.left_children | left_children | Returns the number of left children under the node specified by the given address. | [
"Returns",
"the",
"number",
"of",
"left",
"children",
"under",
"the",
"node",
"specified",
"by",
"the",
"given",
"address."
] | def left_children(self, node_index):
children = chain.from_iterable(self.nodes[node_index]['deps'].values())
index = self.nodes[node_index]['address']
return sum((1 for c in children if c < index)) | ['def', 'left_children(self,', 'node_index):', 'children', '=', "chain.from_iterable(self.nodes[node_index]['deps'].values())", 'index', '=', "self.nodes[node_index]['address']", 'return', 'sum((1', 'for', 'c', 'in', 'children', 'if', 'c', '<', 'index))'] | 218,114 |
brain-research/realistic-ssl-evaluation | tf_utils.py | hash_float | hash_float | Hash a tensor 'x' into a floating point number in the range [0, 1). | [
"Hash",
"a",
"tensor",
"'x'",
"into",
"a",
"floating",
"point",
"number",
"in",
"the",
"range",
"[0,",
"1)."
] | def hash_float(x, big_num=1000 * 1000):
return tf.cast(tf.string_to_hash_bucket_fast(x, big_num), tf.float32) / tf.constant(float(big_num)) | ['def', 'hash_float(x,', 'big_num=1000', '*', '1000):', 'return', 'tf.cast(tf.string_to_hash_bucket_fast(x,', 'big_num),', 'tf.float32)', '/', 'tf.constant(float(big_num))'] | 309,007 |
weimin17/Object-Detection_HelmetDetection | plot_partition.py | plot_comparison | plot_comparison | Plots variants of GNMax algorithm and their analyses. | [
"Plots",
"variants",
"of",
"GNMax",
"algorithm",
"and",
"their",
"analyses."
] | def plot_comparison(figures_dir, simple_ind, conf_ind, simple_dep, conf_dep):
def pivot(x_axis, eps, answered):
y = np.full(len(x_axis), None, dtype=float)
for (i, x) in enumerate(x_axis):
idx = np.searchsorted(answered, x)
if idx < len(eps):
y[i] = eps[idx]
... | ['def', 'plot_comparison(figures_dir,', 'simple_ind,', 'conf_ind,', 'simple_dep,', 'conf_dep):', 'def', 'pivot(x_axis,', 'eps,', 'answered):', 'y', '=', 'np.full(len(x_axis),', 'None,', 'dtype=float)', 'for', '(i,', 'x)', 'in', 'enumerate(x_axis):', 'idx', '=', 'np.searchsorted(answered,', 'x)', 'if', 'idx', '<', 'len(... | 749,802 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | conftest.py | frame | frame | Returns the first ten items in fixture "float_frame". | [
"Returns",
"the",
"first",
"ten",
"items",
"in",
"fixture",
"\"float_frame\"."
] | def frame(float_frame):
return float_frame[:10] | ['def', 'frame(float_frame):', 'return', 'float_frame[:10]'] | 453,809 |
rudranil723/mini-main | test_mlab.py | TestGaussianKDECustom.test_callable_singledim_dataset | test_callable_singledim_dataset | Test the callable's cov factor for a single-dimensional array. | [
"Test",
"the",
"callable's",
"cov",
"factor",
"for",
"a",
"single-dimensional",
"array."
] | def test_callable_singledim_dataset(self):
np.random.seed(8765678)
n_basesample = 50
multidim_data = np.random.randn(n_basesample)
kde = mlab.GaussianKDE(multidim_data, bw_method='silverman')
y_expected = 0.4843884136334891
assert_almost_equal(kde.covariance_factor(), y_expected, 7) | ['def', 'test_callable_singledim_dataset(self):', 'np.random.seed(8765678)', 'n_basesample', '=', '50', 'multidim_data', '=', 'np.random.randn(n_basesample)', 'kde', '=', 'mlab.GaussianKDE(multidim_data,', "bw_method='silverman')", 'y_expected', '=', '0.4843884136334891', 'assert_almost_equal(kde.covariance_factor(),',... | 320,307 |
0xangelo/raylab | sampling.py | ModelSamplingMixin.set_new_elite | set_new_elite | Update the elite models based on model losses. | [
"Update",
"the",
"elite",
"models",
"based",
"on",
"model",
"losses."
] | def set_new_elite(self, losses: List[float]):
models = self.module.models
self.elite_models = [models[i] for i in np.argsort(losses)] | ['def', 'set_new_elite(self,', 'losses:', 'List[float]):', 'models', '=', 'self.module.models', 'self.elite_models', '=', '[models[i]', 'for', 'i', 'in', 'np.argsort(losses)]'] | 848,363 |
PaccMann/fdsa | cnn.py | CNNSetMatching.compute_output_img_size | compute_output_img_size | Computes the size of the output from a CNN in one dimension. | [
"Computes",
"the",
"size",
"of",
"the",
"output",
"from",
"a",
"CNN",
"in",
"one",
"dimension."
] | def compute_output_img_size(self, input_size: int, filter_size: int, padding: int, stride: int) -> int:
return 1 + (input_size - filter_size + 2 * padding) / stride | ['def', 'compute_output_img_size(self,', 'input_size:', 'int,', 'filter_size:', 'int,', 'padding:', 'int,', 'stride:', 'int)', '->', 'int:', 'return', '1', '+', '(input_size', '-', 'filter_size', '+', '2', '*', 'padding)', '/', 'stride'] | 560,864 |
xmax1/dvae | util.py | binarize | binarize | This function binarizes the input numpy array assuming that values are representing the mean parameter in a Bernoulli distribution. | [
"This",
"function",
"binarizes",
"the",
"input",
"numpy",
"array",
"assuming",
"that",
"values",
"are",
"representing",
"the",
"mean",
"parameter",
"in",
"a",
"Bernoulli",
"distribution."
] | def binarize(data, seed=None):
if seed is not None:
np.random.seed(seed)
random = np.random.rand(*data.shape[:])
bin = np.asarray(random < data, np.float32)
return bin | ['def', 'binarize(data,', 'seed=None):', 'if', 'seed', 'is', 'not', 'None:', 'np.random.seed(seed)', 'random', '=', 'np.random.rand(*data.shape[:])', 'bin', '=', 'np.asarray(random', '<', 'data,', 'np.float32)', 'return', 'bin'] | 554,895 |
bytedance/ParaGen | huggingface_tokenizer.py | HuggingfaceTokenizer.learn | learn | HuggingfaceTokenizer are used for pretrained model, and is usually directly load from huggingface. | [
"HuggingfaceTokenizer",
"are",
"used",
"for",
"pretrained",
"model,",
"and",
"is",
"usually",
"directly",
"load",
"from",
"huggingface."
] | def learn(*args, **kwargs):
logger.info('learn vocab not supported for huggingface tokenizer')
raise NotImplementedError | ['def', 'learn(*args,', '**kwargs):', "logger.info('learn", 'vocab', 'not', 'supported', 'for', 'huggingface', "tokenizer')", 'raise', 'NotImplementedError'] | 764,111 |
ZauggGroup/DeePiCt | motl2sph_mask.py | generate_particle_mask_from_motl | generate_particle_mask_from_motl | Function to paste a sphere of a given radius at every voxel coordinate specified by a motif list. | [
"Function",
"to",
"paste",
"a",
"sphere",
"of",
"a",
"given",
"radius",
"at",
"every",
"voxel",
"coordinate",
"specified",
"by",
"a",
"motif",
"list."
] | def generate_particle_mask_from_motl(path_to_motl: str, output_shape: tuple, sphere_radius: int, value: int=1 or str, mask=None or np.array) -> np.array:
motl_extension = os.path.basename(path_to_motl).split('.')[-1]
assert motl_extension in ['csv', 'em', 'txt']
if motl_extension == 'csv':
motive_li... | ['def', 'generate_particle_mask_from_motl(path_to_motl:', 'str,', 'output_shape:', 'tuple,', 'sphere_radius:', 'int,', 'value:', 'int=1', 'or', 'str,', 'mask=None', 'or', 'np.array)', '->', 'np.array:', 'motl_extension', '=', "os.path.basename(path_to_motl).split('.')[-1]", 'assert', 'motl_extension', 'in', "['csv',", ... | 521,157 |
SamsungLabs/fcaf3d | centerpoint_head.py | DCNSeparateHead.forward | forward | Forward function for DCNSepHead. | [
"Forward",
"function",
"for",
"DCNSepHead."
] | def forward(self, x):
center_feat = self.feature_adapt_cls(x)
reg_feat = self.feature_adapt_reg(x)
cls_score = self.cls_head(center_feat)
ret = self.task_head(reg_feat)
ret['heatmap'] = cls_score
return ret | ['def', 'forward(self,', 'x):', 'center_feat', '=', 'self.feature_adapt_cls(x)', 'reg_feat', '=', 'self.feature_adapt_reg(x)', 'cls_score', '=', 'self.cls_head(center_feat)', 'ret', '=', 'self.task_head(reg_feat)', "ret['heatmap']", '=', 'cls_score', 'return', 'ret'] | 560,420 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pixelda_model.py | upsample | upsample | Performs spatial upsampling of the given features. | [
"Performs",
"spatial",
"upsampling",
"of",
"the",
"given",
"features."
] | def upsample(net, num_filters, scale=2, method='resize_conv', scope=None):
if scale < 2:
raise ValueError('scale must be greater or equal to two.')
with tf.variable_scope(scope, 'upsample', [net]):
if method == 'resize_conv':
net = tf.image.resize_nearest_neighbor(net, [net.shape.as_... | ['def', 'upsample(net,', 'num_filters,', 'scale=2,', "method='resize_conv',", 'scope=None):', 'if', 'scale', '<', '2:', 'raise', "ValueError('scale", 'must', 'be', 'greater', 'or', 'equal', 'to', "two.')", 'with', 'tf.variable_scope(scope,', "'upsample',", '[net]):', 'if', 'method', '==', "'resize_conv':", 'net', '=', ... | 48,139 |
matsu0228/nlp-jp | test_bundler_tools.py | TestBundlerTools.test_get_cell_reference_patterns_precode_mdcomment | test_get_cell_reference_patterns_precode_mdcomment | Should find two references and ignore a comment in a fenced code block. | [
"Should",
"find",
"two",
"references",
"and",
"ignore",
"a",
"comment",
"in",
"a",
"fenced",
"code",
"block."
] | def test_get_cell_reference_patterns_precode_mdcomment(self):
cell = {'cell_type': 'markdown', 'source': '```\na\nb/\n#comment\n```'}
references = tools.get_cell_reference_patterns(cell)
self.assertTrue('a' in references and 'b/' in references, str(references))
self.assertEqual(len(references), 2, str(r... | ['def', 'test_get_cell_reference_patterns_precode_mdcomment(self):', 'cell', '=', "{'cell_type':", "'markdown',", "'source':", "'```\\na\\nb/\\n#comment\\n```'}", 'references', '=', 'tools.get_cell_reference_patterns(cell)', "self.assertTrue('a'", 'in', 'references', 'and', "'b/'", 'in', 'references,', 'str(references)... | 790,609 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | backend_bases.py | FigureCanvasBase.is_saving | is_saving | Returns whether the renderer is in the process of saving to a file, rather than rendering for an on-screen buffer. | [
"Returns",
"whether",
"the",
"renderer",
"is",
"in",
"the",
"process",
"of",
"saving",
"to",
"a",
"file,",
"rather",
"than",
"rendering",
"for",
"an",
"on-screen",
"buffer."
] | def is_saving(self):
return self._is_saving | ['def', 'is_saving(self):', 'return', 'self._is_saving'] | 306,415 |
43Carrig/recurrent_neural_networks_practice | test_util.py | NHWCToNCHW | NHWCToNCHW | Converts the input from the NHWC format to NCHW. | [
"Converts",
"the",
"input",
"from",
"the",
"NHWC",
"format",
"to",
"NCHW."
] | def NHWCToNCHW(input_tensor):
new_axes = {4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]}
if isinstance(input_tensor, ops.Tensor):
ndims = input_tensor.shape.ndims
return array_ops.transpose(input_tensor, new_axes[ndims])
else:
ndims = len(input_tensor)
return [input_tensor[a] for a in ... | ['def', 'NHWCToNCHW(input_tensor):', 'new_axes', '=', '{4:', '[0,', '3,', '1,', '2],', '5:', '[0,', '4,', '1,', '2,', '3]}', 'if', 'isinstance(input_tensor,', 'ops.Tensor):', 'ndims', '=', 'input_tensor.shape.ndims', 'return', 'array_ops.transpose(input_tensor,', 'new_axes[ndims])', 'else:', 'ndims', '=', 'len(input_te... | 336,592 |
rudranil723/mini-main | formsets.py | BaseFormSet.total_error_count | total_error_count | Return the number of errors across all forms in the formset. | [
"Return",
"the",
"number",
"of",
"errors",
"across",
"all",
"forms",
"in",
"the",
"formset."
] | def total_error_count(self):
return len(self.non_form_errors()) + sum((len(form_errors) for form_errors in self.errors)) | ['def', 'total_error_count(self):', 'return', 'len(self.non_form_errors())', '+', 'sum((len(form_errors)', 'for', 'form_errors', 'in', 'self.errors))'] | 316,267 |
xvjiarui/VFS | recognizer2d.py | Recognizer2D.forward_train | forward_train | Defines the computation performed at every call when training. | [
"Defines",
"the",
"computation",
"performed",
"at",
"every",
"call",
"when",
"training."
] | def forward_train(self, imgs, labels):
batches = imgs.shape[0]
imgs = imgs.reshape((-1,) + imgs.shape[2:])
num_segs = imgs.shape[0] // batches
x = self.extract_feat(imgs)
cls_score = self.cls_head(x, num_segs)
gt_labels = labels.squeeze()
loss = self.cls_head.loss(cls_score, gt_labels)
r... | ['def', 'forward_train(self,', 'imgs,', 'labels):', 'batches', '=', 'imgs.shape[0]', 'imgs', '=', 'imgs.reshape((-1,)', '+', 'imgs.shape[2:])', 'num_segs', '=', 'imgs.shape[0]', '//', 'batches', 'x', '=', 'self.extract_feat(imgs)', 'cls_score', '=', 'self.cls_head(x,', 'num_segs)', 'gt_labels', '=', 'labels.squeeze()',... | 379,682 |
lektor/lektor-archive | context.py | Context.record_dependency | record_dependency | Records a dependency from processing. | [
"Records",
"a",
"dependency",
"from",
"processing."
] | def record_dependency(self, filename):
self.referenced_dependencies.add(filename)
for coll in self._dependency_collectors:
coll(filename) | ['def', 'record_dependency(self,', 'filename):', 'self.referenced_dependencies.add(filename)', 'for', 'coll', 'in', 'self._dependency_collectors:', 'coll(filename)'] | 216,356 |
kaka-lin/object-detection | keras_darknet19.py | bottleneck_x2_block | bottleneck_x2_block | Bottleneck block of 3x3, 1x1, 3x3, 1x1, 3x3 convolutions. | [
"Bottleneck",
"block",
"of",
"3x3,",
"1x1,",
"3x3,",
"1x1,",
"3x3",
"convolutions."
] | def bottleneck_x2_block(outer_filters, bottleneck_filters):
return compose(bottleneck_block(outer_filters, bottleneck_filters), DarknetConv2D_BN_Leaky(bottleneck_filters, (1, 1)), DarknetConv2D_BN_Leaky(outer_filters, (3, 3))) | ['def', 'bottleneck_x2_block(outer_filters,', 'bottleneck_filters):', 'return', 'compose(bottleneck_block(outer_filters,', 'bottleneck_filters),', 'DarknetConv2D_BN_Leaky(bottleneck_filters,', '(1,', '1)),', 'DarknetConv2D_BN_Leaky(outer_filters,', '(3,', '3)))'] | 747,651 |
rudranil723/mini-main | ast.py | SizeParameters.build | build | Calls the builder object's ``set_size_parameters`` callback. | [
"Calls",
"the",
"builder",
"object's",
"``set_size_parameters``",
"callback."
] | def build(self, builder):
builder.set_size_parameters(self.location, self.DesignSize, self.SubfamilyID, self.RangeStart, self.RangeEnd) | ['def', 'build(self,', 'builder):', 'builder.set_size_parameters(self.location,', 'self.DesignSize,', 'self.SubfamilyID,', 'self.RangeStart,', 'self.RangeEnd)'] | 317,108 |
eddylau328/fyp-artificial-intelligence-ac-control-device | __init__.py | Channel.unsubscribe | unsubscribe | Unsubscribes a subscribed callback from this Channel's connectivity. | [
"Unsubscribes",
"a",
"subscribed",
"callback",
"from",
"this",
"Channel's",
"connectivity."
] | def unsubscribe(self, callback):
raise NotImplementedError() | ['def', 'unsubscribe(self,', 'callback):', 'raise', 'NotImplementedError()'] | 215,590 |
QData/deepWordBug | mail.py | mail_validator | mail_validator | Validates a handler implementation against the IMail interface. | [
"Validates",
"a",
"handler",
"implementation",
"against",
"the",
"IMail",
"interface."
] | def mail_validator(klass, obj):
members = ['_setup', 'send']
interface.validate(IMail, obj, members) | ['def', 'mail_validator(klass,', 'obj):', 'members', '=', "['_setup',", "'send']", 'interface.validate(IMail,', 'obj,', 'members)'] | 541,673 |
open-mmlab/mmtracking | dff.py | DFF.extract_feats | extract_feats | Extract features for `img` during testing. | [
"Extract",
"features",
"for",
"`img`",
"during",
"testing."
] | def extract_feats(self, img, img_metas):
key_frame_interval = self.test_cfg.get('key_frame_interval', 10)
frame_id = img_metas[0].get('frame_id', -1)
assert frame_id >= 0
is_key_frame = False if frame_id % key_frame_interval else True
if is_key_frame:
self.memo = Dict()
self.memo.img... | ['def', 'extract_feats(self,', 'img,', 'img_metas):', 'key_frame_interval', '=', "self.test_cfg.get('key_frame_interval',", '10)', 'frame_id', '=', "img_metas[0].get('frame_id',", '-1)', 'assert', 'frame_id', '>=', '0', 'is_key_frame', '=', 'False', 'if', 'frame_id', '%', 'key_frame_interval', 'else', 'True', 'if', 'is... | 625,918 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MapToRanks | MapToRanks | Returns a list of ranks corresponding to the elements in t. | [
"Returns",
"a",
"list",
"of",
"ranks",
"corresponding",
"to",
"the",
"elements",
"in",
"t."
] | def MapToRanks(t):
pairs = enumerate(t)
sorted_pairs = sorted(pairs, key=itemgetter(1))
ranked = enumerate(sorted_pairs)
resorted = sorted(ranked, key=lambda trip: trip[1][0])
ranks = [trip[0] + 1 for trip in resorted]
return ranks | ['def', 'MapToRanks(t):', 'pairs', '=', 'enumerate(t)', 'sorted_pairs', '=', 'sorted(pairs,', 'key=itemgetter(1))', 'ranked', '=', 'enumerate(sorted_pairs)', 'resorted', '=', 'sorted(ranked,', 'key=lambda', 'trip:', 'trip[1][0])', 'ranks', '=', '[trip[0]', '+', '1', 'for', 'trip', 'in', 'resorted]', 'return', 'ranks'] | 19,356 |
caiiiac/Machine-Learning-with-Python | test_gradient_boosting.py | early_stopping_monitor | early_stopping_monitor | Returns True on the 10th iteration. | [
"Returns",
"True",
"on",
"the",
"10th",
"iteration."
] | def early_stopping_monitor(i, est, locals):
if i == 9:
return True
else:
return False | ['def', 'early_stopping_monitor(i,', 'est,', 'locals):', 'if', 'i', '==', '9:', 'return', 'True', 'else:', 'return', 'False'] | 720,639 |
intel/neural-compressor | onnx_model.py | ONNXModel.remove_initializer | remove_initializer | Remove an initializer from model. | [
"Remove",
"an",
"initializer",
"from",
"model."
] | def remove_initializer(self, tensor):
if tensor in self._model.graph.initializer:
self._model.graph.initializer.remove(tensor) | ['def', 'remove_initializer(self,', 'tensor):', 'if', 'tensor', 'in', 'self._model.graph.initializer:', 'self._model.graph.initializer.remove(tensor)'] | 738,883 |
tinazhouhui/computer_vision | program.py | load_config | load_config | Load config from yml/yaml file. | [
"Load",
"config",
"from",
"yml/yaml",
"file."
] | def load_config(file_path):
merge_config(default_config)
(_, ext) = os.path.splitext(file_path)
assert ext in ['.yml', '.yaml'], 'only support yaml files for now'
merge_config(yaml.load(open(file_path, 'rb'), Loader=yaml.Loader))
return global_config | ['def', 'load_config(file_path):', 'merge_config(default_config)', '(_,', 'ext)', '=', 'os.path.splitext(file_path)', 'assert', 'ext', 'in', "['.yml',", "'.yaml'],", "'only", 'support', 'yaml', 'files', 'for', "now'", 'merge_config(yaml.load(open(file_path,', "'rb'),", 'Loader=yaml.Loader))', 'return', 'global_config'] | 474,749 |
UAVs-at-Berkeley/flywave | vlc.py | MediaPlayer.previous_chapter | previous_chapter | Set previous chapter (if applicable). | [
"Set",
"previous",
"chapter",
"(if",
"applicable)."
] | def previous_chapter(self):
return libvlc_media_player_previous_chapter(self) | ['def', 'previous_chapter(self):', 'return', 'libvlc_media_player_previous_chapter(self)'] | 607,864 |
pyvideo/richard | models.py | NotificationManager.get_live_notifications | get_live_notifications | Returns notifications in the "now" range This is anything that starts before now and either ends after now or had a null end date. | [
"Returns",
"notifications",
"in",
"the",
"\"now\"",
"range",
"This",
"is",
"anything",
"that",
"starts",
"before",
"now",
"and",
"either",
"ends",
"after",
"now",
"or",
"had",
"a",
"null",
"end",
"date."
] | def get_live_notifications(self):
now = datetime.date.today()
return self.get_queryset().filter(start_date__lte=now).filter(models.Q(end_date__gt=now) | models.Q(end_date__isnull=True)) | ['def', 'get_live_notifications(self):', 'now', '=', 'datetime.date.today()', 'return', 'self.get_queryset().filter(start_date__lte=now).filter(models.Q(end_date__gt=now)', '|', 'models.Q(end_date__isnull=True))'] | 348,846 |
sek788432/Waymo-2D-Object-Detection | target_assigner_test.py | CenterNetCenterHeatmapTargetAssignerTest.test_center_location_by_keypoints | test_center_location_by_keypoints | Test that the centers are at the correct location. | [
"Test",
"that",
"the",
"centers",
"are",
"at",
"the",
"correct",
"location."
] | def test_center_location_by_keypoints(self, keypoint_weights_for_center):
kpts_y = [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.0, 0.0, 0.0, 0.0]]
kpts_x = [[0.5, 0.6, 0.7, 0.8], [0.1, 0.2, 0.3, 0.4], [0.0, 0.0, 0.0, 0.0]]
gt_keypoints_list = [tf.stack([tf.constant(kpts_y), tf.constant(kpts_x)], axis=2)]... | ['def', 'test_center_location_by_keypoints(self,', 'keypoint_weights_for_center):', 'kpts_y', '=', '[[0.1,', '0.2,', '0.3,', '0.4],', '[0.5,', '0.6,', '0.7,', '0.8],', '[0.0,', '0.0,', '0.0,', '0.0]]', 'kpts_x', '=', '[[0.5,', '0.6,', '0.7,', '0.8],', '[0.1,', '0.2,', '0.3,', '0.4],', '[0.0,', '0.0,', '0.0,', '0.0]]', ... | 974,920 |
google/deepvariant | run_deepvariant.py | postprocess_variants_command | postprocess_variants_command | Returns a postprocess_variants (command, logfile) for subprocess. | [
"Returns",
"a",
"postprocess_variants",
"(command,",
"logfile)",
"for",
"subprocess."
] | def postprocess_variants_command(ref, infile, outfile, extra_args, nonvariant_site_tfrecord_path=None, gvcf_outfile=None, vcf_stats_report=True, sample_name=None):
command = ['time', '/opt/deepvariant/bin/postprocess_variants']
command.extend(['--ref', '"{}"'.format(ref)])
command.extend(['--infile', '"{}"'... | ['def', 'postprocess_variants_command(ref,', 'infile,', 'outfile,', 'extra_args,', 'nonvariant_site_tfrecord_path=None,', 'gvcf_outfile=None,', 'vcf_stats_report=True,', 'sample_name=None):', 'command', '=', "['time',", "'/opt/deepvariant/bin/postprocess_variants']", "command.extend(['--ref',", '\'"{}"\'.format(ref)])'... | 540,529 |
aeon-toolkit/aeon | test_dask_pd.py | test_convert_pd_dask_inverse | test_convert_pd_dask_inverse | Tests conversions from pandas from/to dask are inverses. | [
"Tests",
"conversions",
"from",
"pandas",
"from/to",
"dask",
"are",
"inverses."
] | def test_convert_pd_dask_inverse(pd_fixture):
dask_result = convert_pandas_to_dask(pd_fixture)
back_result = convert_dask_to_pandas(dask_result)
assert pd_fixture.equals(back_result) | ['def', 'test_convert_pd_dask_inverse(pd_fixture):', 'dask_result', '=', 'convert_pandas_to_dask(pd_fixture)', 'back_result', '=', 'convert_dask_to_pandas(dask_result)', 'assert', 'pd_fixture.equals(back_result)'] | 399,465 |
Westlake-AI/openmixup | test_attention.py | get_relative_position_index | get_relative_position_index | Method from original code of Swin-Transformer. | [
"Method",
"from",
"original",
"code",
"of",
"Swin-Transformer."
] | def get_relative_position_index(window_size):
coords_h = torch.arange(window_size[0])
coords_w = torch.arange(window_size[1])
coords = torch.stack(torch.meshgrid([coords_h, coords_w]))
coords_flatten = torch.flatten(coords, 1)
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]... | ['def', 'get_relative_position_index(window_size):', 'coords_h', '=', 'torch.arange(window_size[0])', 'coords_w', '=', 'torch.arange(window_size[1])', 'coords', '=', 'torch.stack(torch.meshgrid([coords_h,', 'coords_w]))', 'coords_flatten', '=', 'torch.flatten(coords,', '1)', 'relative_coords', '=', 'coords_flatten[:,',... | 252,669 |
sunishsheth2009/ChatterBot | test_ubuntu_corpus_training.py | UbuntuCorpusTrainerTestCase.test_is_not_extracted | test_is_not_extracted | Test that a check can be done for if the corpus has aleady been extracted. | [
"Test",
"that",
"a",
"check",
"can",
"be",
"done",
"for",
"if",
"the",
"corpus",
"has",
"aleady",
"been",
"extracted."
] | def test_is_not_extracted(self):
self._remove_data()
extracted = self.trainer.is_extracted(self.trainer.extracted_data_directory)
self.assertFalse(extracted) | ['def', 'test_is_not_extracted(self):', 'self._remove_data()', 'extracted', '=', 'self.trainer.is_extracted(self.trainer.extracted_data_directory)', 'self.assertFalse(extracted)'] | 486,019 |
43Carrig/recurrent_neural_networks_practice | control_flow_ops.py | WhileContext.parallel_iterations | parallel_iterations | The number of iterations allowed to run in parallel. | [
"The",
"number",
"of",
"iterations",
"allowed",
"to",
"run",
"in",
"parallel."
] | def parallel_iterations(self):
return self._parallel_iterations | ['def', 'parallel_iterations(self):', 'return', 'self._parallel_iterations'] | 337,173 |
omarmhaimdat/twitter_nlp_native_swift | api.py | Api.SetUserAgent | SetUserAgent | Override the default user agent. | [
"Override",
"the",
"default",
"user",
"agent."
] | def SetUserAgent(self, user_agent):
self._request_headers['User-Agent'] = user_agent | ['def', 'SetUserAgent(self,', 'user_agent):', "self._request_headers['User-Agent']", '=', 'user_agent'] | 955,176 |
xiongfengyan/gcnn | models.py | gcnn.training | training | Adds to the loss model the Ops required to generate and apply gradients. | [
"Adds",
"to",
"the",
"loss",
"model",
"the",
"Ops",
"required",
"to",
"generate",
"and",
"apply",
"gradients."
] | def training(self, loss, learning_rate, decay_steps, decay_rate=0.95, momentum=0.9):
with tf.name_scope('training'):
global_step = tf.Variable(0, name='global_step', trainable=False)
if decay_rate != 1:
learning_rate = tf.train.exponential_decay(learning_rate, global_step, decay_steps, d... | ['def', 'training(self,', 'loss,', 'learning_rate,', 'decay_steps,', 'decay_rate=0.95,', 'momentum=0.9):', 'with', "tf.name_scope('training'):", 'global_step', '=', 'tf.Variable(0,', "name='global_step',", 'trainable=False)', 'if', 'decay_rate', '!=', '1:', 'learning_rate', '=', 'tf.train.exponential_decay(learning_rat... | 201,366 |
mkusner/grammarVAE | test_conv.py | TestConv2D.test_unroll_patch_true | test_unroll_patch_true | Test basic convs with True. | [
"Test",
"basic",
"convs",
"with",
"True."
] | def test_unroll_patch_true(self):
self.validate((3, 2, 7, 5), (5, 2, 2, 3), 'valid', unroll_patch=True)
self.validate((3, 2, 7, 5), (5, 2, 2, 3), 'full', unroll_patch=True)
self.validate((3, 2, 3, 3), (4, 2, 3, 3), 'valid', unroll_patch=True, verify_grad=False) | ['def', 'test_unroll_patch_true(self):', 'self.validate((3,', '2,', '7,', '5),', '(5,', '2,', '2,', '3),', "'valid',", 'unroll_patch=True)', 'self.validate((3,', '2,', '7,', '5),', '(5,', '2,', '2,', '3),', "'full',", 'unroll_patch=True)', 'self.validate((3,', '2,', '3,', '3),', '(4,', '2,', '3,', '3),', "'valid',", 'u... | 580,078 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | esoteric.py | BrainfuckLexer.analyse_text | analyse_text | It's safe to assume that a program which mostly consists of + - and < > is brainfuck. | [
"It's",
"safe",
"to",
"assume",
"that",
"a",
"program",
"which",
"mostly",
"consists",
"of",
"+",
"-",
"and",
"<",
">",
"is",
"brainfuck."
] | def analyse_text(text):
plus_minus_count = 0
greater_less_count = 0
range_to_check = max(256, len(text))
for c in text[:range_to_check]:
if c == '+' or c == '-':
plus_minus_count += 1
if c == '<' or c == '>':
greater_less_count += 1
if plus_minus_count > 0.25 ... | ['def', 'analyse_text(text):', 'plus_minus_count', '=', '0', 'greater_less_count', '=', '0', 'range_to_check', '=', 'max(256,', 'len(text))', 'for', 'c', 'in', 'text[:range_to_check]:', 'if', 'c', '==', "'+'", 'or', 'c', '==', "'-':", 'plus_minus_count', '+=', '1', 'if', 'c', '==', "'<'", 'or', 'c', '==', "'>':", 'grea... | 435,608 |
pranjaldatta/PyVision | SVMEyeDetector.py | _TestSVMEyeDetector.test_training | test_training | This trains the FaceFinder on the scraps database. | [
"This",
"trains",
"the",
"FaceFinder",
"on",
"the",
"scraps",
"database."
] | def test_training(self):
eyes_filename = join(pv.__path__[0], 'data', 'csuScrapShots', 'coords.txt')
eyes_file = EyesFile(eyes_filename)
cascade_file = join(pv.__path__[0], 'config', 'facedetector_celebdb2.xml')
face_detector = CascadeDetector(cascade_file)
image_dir = join(pv.__path__[0], 'data', '... | ['def', 'test_training(self):', 'eyes_filename', '=', 'join(pv.__path__[0],', "'data',", "'csuScrapShots',", "'coords.txt')", 'eyes_file', '=', 'EyesFile(eyes_filename)', 'cascade_file', '=', 'join(pv.__path__[0],', "'config',", "'facedetector_celebdb2.xml')", 'face_detector', '=', 'CascadeDetector(cascade_file)', 'ima... | 815,839 |
zihuitang/medical_AI_platform | build-installer.py | setIcon | setIcon | Set the custom icon for the specified file or directory. | [
"Set",
"the",
"custom",
"icon",
"for",
"the",
"specified",
"file",
"or",
"directory."
] | def setIcon(filePath, icnsPath):
dirPath = os.path.normpath(os.path.dirname(__file__))
toolPath = os.path.join(dirPath, 'seticon.app/Contents/MacOS/seticon')
if not os.path.exists(toolPath) or os.stat(toolPath).st_mtime < os.stat(dirPath + '/seticon.m').st_mtime:
appPath = os.path.join(dirPath, 'set... | ['def', 'setIcon(filePath,', 'icnsPath):', 'dirPath', '=', 'os.path.normpath(os.path.dirname(__file__))', 'toolPath', '=', 'os.path.join(dirPath,', "'seticon.app/Contents/MacOS/seticon')", 'if', 'not', 'os.path.exists(toolPath)', 'or', 'os.stat(toolPath).st_mtime', '<', 'os.stat(dirPath', '+', "'/seticon.m').st_mtime:"... | 284,655 |
TonyLianLong/VAI-ReinforcementLearning | task.py | Task.physics_timestep | physics_timestep | Returns the physics timestep for this task (in seconds). | [
"Returns",
"the",
"physics",
"timestep",
"for",
"this",
"task",
"(in",
"seconds)."
] | def physics_timestep(self):
self._check_root_entity('physics_timestep')
if self.root_entity.mjcf_model.option.timestep is None:
return 0.002
else:
return self.root_entity.mjcf_model.option.timestep | ['def', 'physics_timestep(self):', "self._check_root_entity('physics_timestep')", 'if', 'self.root_entity.mjcf_model.option.timestep', 'is', 'None:', 'return', '0.002', 'else:', 'return', 'self.root_entity.mjcf_model.option.timestep'] | 439,894 |
jbwang1997/CrossKD | dii_head.py | DIIHead.loss_and_target | loss_and_target | Calculate the loss based on the features extracted by the DIIHead. | [
"Calculate",
"the",
"loss",
"based",
"on",
"the",
"features",
"extracted",
"by",
"the",
"DIIHead."
] | def loss_and_target(self, cls_score: Tensor, bbox_pred: Tensor, sampling_results: List[SamplingResult], rcnn_train_cfg: ConfigType, imgs_whwh: Tensor, concat: bool=True, reduction_override: str=None) -> dict:
cls_reg_targets = self.get_targets(sampling_results=sampling_results, rcnn_train_cfg=rcnn_train_cfg, concat... | ['def', 'loss_and_target(self,', 'cls_score:', 'Tensor,', 'bbox_pred:', 'Tensor,', 'sampling_results:', 'List[SamplingResult],', 'rcnn_train_cfg:', 'ConfigType,', 'imgs_whwh:', 'Tensor,', 'concat:', 'bool=True,', 'reduction_override:', 'str=None)', '->', 'dict:', 'cls_reg_targets', '=', 'self.get_targets(sampling_resul... | 491,444 |
vt-vl-lab/iCAN | Object_Detector.py | demo | demo | Detect object classes in an image using pre-computed object proposals. | [
"Detect",
"object",
"classes",
"in",
"an",
"image",
"using",
"pre-computed",
"object",
"proposals."
] | def demo(sess, net, im_file, RCNN):
image_name = im_file.split('/')[-1]
tmp = []
im = cv2.imread(im_file)
im = im[:, :, (2, 1, 0)]
timer = Timer()
timer.tic()
(scores, boxes) = im_detect(sess, net, im)
timer.toc()
CONF_THRESH = 0.3
NMS_THRESH = 0.3
for (cls_ind, cls) in enume... | ['def', 'demo(sess,', 'net,', 'im_file,', 'RCNN):', 'image_name', '=', "im_file.split('/')[-1]", 'tmp', '=', '[]', 'im', '=', 'cv2.imread(im_file)', 'im', '=', 'im[:,', ':,', '(2,', '1,', '0)]', 'timer', '=', 'Timer()', 'timer.tic()', '(scores,', 'boxes)', '=', 'im_detect(sess,', 'net,', 'im)', 'timer.toc()', 'CONF_THR... | 596,855 |
fbascheper/kafka-tf-burglar-alerts-demo-model | burglar_transfer_learning.py | train_model_using_transfer_learning | train_model_using_transfer_learning | Train a model for burglar alerts using transfer learning. | [
"Train",
"a",
"model",
"for",
"burglar",
"alerts",
"using",
"transfer",
"learning."
] | def train_model_using_transfer_learning():
base_dir = 'input-images/classified-and-converted-using-kafka-storage-converters'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
train_burglars_dir = os.path.join(train_dir, 'burglar-alert')
train_no_burgla... | ['def', 'train_model_using_transfer_learning():', 'base_dir', '=', "'input-images/classified-and-converted-using-kafka-storage-converters'", 'train_dir', '=', 'os.path.join(base_dir,', "'train')", 'validation_dir', '=', 'os.path.join(base_dir,', "'validation')", 'train_burglars_dir', '=', 'os.path.join(train_dir,', "'b... | 594,669 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | operator.py | imatmul | imatmul | Same as a @= b. | [
"Same",
"as",
"a",
"@=",
"b."
] | def imatmul(a, b):
a @= b
return a | ['def', 'imatmul(a,', 'b):', 'a', '@=', 'b', 'return', 'a'] | 801,571 |
ldkong1205/LaserMix | cam_box3d.py | CameraInstance3DBoxes.gravity_center | gravity_center | Tensor: A tensor with center of each box in shape (N, 3). | [
"Tensor:",
"A",
"tensor",
"with",
"center",
"of",
"each",
"box",
"in",
"shape",
"(N,",
"3)."
] | def gravity_center(self) -> Tensor:
bottom_center = self.bottom_center
gravity_center = torch.zeros_like(bottom_center)
gravity_center[:, [0, 2]] = bottom_center[:, [0, 2]]
gravity_center[:, 1] = bottom_center[:, 1] - self.tensor[:, 4] * 0.5
return gravity_center | ['def', 'gravity_center(self)', '->', 'Tensor:', 'bottom_center', '=', 'self.bottom_center', 'gravity_center', '=', 'torch.zeros_like(bottom_center)', 'gravity_center[:,', '[0,', '2]]', '=', 'bottom_center[:,', '[0,', '2]]', 'gravity_center[:,', '1]', '=', 'bottom_center[:,', '1]', '-', 'self.tensor[:,', '4]', '*', '0.... | 624,364 |
rlworkgroup/garage | test_mlp_module.py | TestMLPModel.test_is_pickleable | test_is_pickleable | Check MLPModule is pickeable. | [
"Check",
"MLPModule",
"is",
"pickeable."
] | def test_is_pickleable(self, input_dim, output_dim, hidden_sizes):
input_val = torch.ones([1, input_dim], dtype=torch.float32)
module = MLPModule(input_dim=input_dim, output_dim=output_dim, hidden_nonlinearity=torch.relu, hidden_sizes=hidden_sizes, hidden_w_init=nn.init.ones_, output_w_init=nn.init.ones_, outpu... | ['def', 'test_is_pickleable(self,', 'input_dim,', 'output_dim,', 'hidden_sizes):', 'input_val', '=', 'torch.ones([1,', 'input_dim],', 'dtype=torch.float32)', 'module', '=', 'MLPModule(input_dim=input_dim,', 'output_dim=output_dim,', 'hidden_nonlinearity=torch.relu,', 'hidden_sizes=hidden_sizes,', 'hidden_w_init=nn.init... | 201,033 |
rudranil723/mini-main | interface.py | InterfaceClass.validateInvariants | validateInvariants | validate object to defined invariants. | [
"validate",
"object",
"to",
"defined",
"invariants."
] | def validateInvariants(self, obj, errors=None):
for iface in self.__iro__:
for invariant in iface.queryDirectTaggedValue('invariants', ()):
try:
invariant(obj)
except Invalid as error:
if errors is not None:
errors.append(error)
... | ['def', 'validateInvariants(self,', 'obj,', 'errors=None):', 'for', 'iface', 'in', 'self.__iro__:', 'for', 'invariant', 'in', "iface.queryDirectTaggedValue('invariants',", '()):', 'try:', 'invariant(obj)', 'except', 'Invalid', 'as', 'error:', 'if', 'errors', 'is', 'not', 'None:', 'errors.append(error)', 'else:', 'raise... | 271,333 |
myothida/Supervised-Machine-Learning | json.py | JSON.from_data | from_data | Encodes a JSON object from arbitrary data. | [
"Encodes",
"a",
"JSON",
"object",
"from",
"arbitrary",
"data."
] | def from_data(cls, data: Any, indent: Union[None, int, str]=2, highlight: bool=True, skip_keys: bool=False, ensure_ascii: bool=False, check_circular: bool=True, allow_nan: bool=True, default: Optional[Callable[[Any], Any]]=None, sort_keys: bool=False) -> 'JSON':
json_instance: 'JSON' = cls.__new__(cls)
json = d... | ['def', 'from_data(cls,', 'data:', 'Any,', 'indent:', 'Union[None,', 'int,', 'str]=2,', 'highlight:', 'bool=True,', 'skip_keys:', 'bool=False,', 'ensure_ascii:', 'bool=False,', 'check_circular:', 'bool=True,', 'allow_nan:', 'bool=True,', 'default:', 'Optional[Callable[[Any],', 'Any]]=None,', 'sort_keys:', 'bool=False)'... | 445,033 |
ahthie7u/cockpit | utils_transforms.py | sum_grad_squared_transform | sum_grad_squared_transform | Transform individual gradients into second non-centered moment. | [
"Transform",
"individual",
"gradients",
"into",
"second",
"non-centered",
"moment."
] | def sum_grad_squared_transform(batch_grad):
return (batch_grad ** 2).sum(0) | ['def', 'sum_grad_squared_transform(batch_grad):', 'return', '(batch_grad', '**', '2).sum(0)'] | 493,142 |
intel/neural-compressor | util.py | calibration | calibration | Calibration with dataloader or calib_func. | [
"Calibration",
"with",
"dataloader",
"or",
"calib_func."
] | def calibration(model, dataloader=None, n_samples=128, calib_func=None):
if calib_func is not None:
calib_func(model)
else:
import math
from .smooth_quant import model_forward
batch_size = dataloader.batch_size
iters = int(math.ceil(n_samples / batch_size))
if n_s... | ['def', 'calibration(model,', 'dataloader=None,', 'n_samples=128,', 'calib_func=None):', 'if', 'calib_func', 'is', 'not', 'None:', 'calib_func(model)', 'else:', 'import', 'math', 'from', '.smooth_quant', 'import', 'model_forward', 'batch_size', '=', 'dataloader.batch_size', 'iters', '=', 'int(math.ceil(n_samples', '/',... | 737,920 |
myothida/Supervised-Machine-Learning | properties.py | Property.get_mapping | get_mapping | Return a function that maps from data domain to property range. | [
"Return",
"a",
"function",
"that",
"maps",
"from",
"data",
"domain",
"to",
"property",
"range."
] | def get_mapping(self, scale: Scale, data: Series) -> Mapping:
def identity(x):
return x
return identity | ['def', 'get_mapping(self,', 'scale:', 'Scale,', 'data:', 'Series)', '->', 'Mapping:', 'def', 'identity(x):', 'return', 'x', 'return', 'identity'] | 446,782 |
astooke/accel_rl | update_methods_stats.py | rmsprop | rmsprop | Exact copy from Lasagne updates, except also return expressions for the update step of each param. | [
"Exact",
"copy",
"from",
"Lasagne",
"updates,",
"except",
"also",
"return",
"expressions",
"for",
"the",
"update",
"step",
"of",
"each",
"param."
] | def rmsprop(loss_or_grads, params, learning_rate=1.0, rho=0.9, epsilon=1e-06):
grads = LU.get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
steps = list()
one = T.constant(1)
for (param, grad) in zip(params, grads):
value = param.get_value(borrow=True)
accu = theano... | ['def', 'rmsprop(loss_or_grads,', 'params,', 'learning_rate=1.0,', 'rho=0.9,', 'epsilon=1e-06):', 'grads', '=', 'LU.get_or_compute_grads(loss_or_grads,', 'params)', 'updates', '=', 'OrderedDict()', 'steps', '=', 'list()', 'one', '=', 'T.constant(1)', 'for', '(param,', 'grad)', 'in', 'zip(params,', 'grads):', 'value', '... | 406,711 |
43Carrig/recurrent_neural_networks_practice | edit.py | detach_control_inputs | detach_control_inputs | Detach all the external control inputs of the subgraph sgv. | [
"Detach",
"all",
"the",
"external",
"control",
"inputs",
"of",
"the",
"subgraph",
"sgv."
] | def detach_control_inputs(sgv):
sgv = subgraph.make_view(sgv)
for op in sgv.ops:
cops = [cop for cop in op.control_inputs if cop not in sgv.ops]
reroute.remove_control_inputs(op, cops) | ['def', 'detach_control_inputs(sgv):', 'sgv', '=', 'subgraph.make_view(sgv)', 'for', 'op', 'in', 'sgv.ops:', 'cops', '=', '[cop', 'for', 'cop', 'in', 'op.control_inputs', 'if', 'cop', 'not', 'in', 'sgv.ops]', 'reroute.remove_control_inputs(op,', 'cops)'] | 313,207 |
drprojects/superpoint_transformer | data.py | Data.sub | sub | Cluster object indicating subpoint indices for each point. | [
"Cluster",
"object",
"indicating",
"subpoint",
"indices",
"for",
"each",
"point."
] | def sub(self):
return self['sub'] if 'sub' in self._store else None | ['def', 'sub(self):', 'return', "self['sub']", 'if', "'sub'", 'in', 'self._store', 'else', 'None'] | 880,760 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | __init__.py | register | register | Register the function *inputhook* as an event loop integration. | [
"Register",
"the",
"function",
"*inputhook*",
"as",
"an",
"event",
"loop",
"integration."
] | def register(name, inputhook):
registered[name] = inputhook | ['def', 'register(name,', 'inputhook):', 'registered[name]', '=', 'inputhook'] | 448,847 |
triaquae/triaquae | geometries.py | OGRGeometry.touches | touches | Returns True if this geometry touches the other. | [
"Returns",
"True",
"if",
"this",
"geometry",
"touches",
"the",
"other."
] | def touches(self, other):
return self._topology(capi.ogr_touches, other) | ['def', 'touches(self,', 'other):', 'return', 'self._topology(capi.ogr_touches,', 'other)'] | 357,590 |
duerrp/pyexperiment | plot.py | setup_figure | setup_figure | Setup a figure that can be closed by pressing 'q' and saved by pressing 's'. | [
"Setup",
"a",
"figure",
"that",
"can",
"be",
"closed",
"by",
"pressing",
"'q'",
"and",
"saved",
"by",
"pressing",
"'s'."
] | def setup_figure(name='pyexperiment', figsize=None):
setup_plotting(override_setup=False)
fig = plt.figure(figsize=figsize)
fig.canvas.set_window_title(name)
quit_figure_on_key('q', fig)
return fig | ['def', "setup_figure(name='pyexperiment',", 'figsize=None):', 'setup_plotting(override_setup=False)', 'fig', '=', 'plt.figure(figsize=figsize)', 'fig.canvas.set_window_title(name)', "quit_figure_on_key('q',", 'fig)', 'return', 'fig'] | 296,345 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | test.py | Client.resolve_redirect | resolve_redirect | Perform a new request to the location given by the redirect response to the previous request. | [
"Perform",
"a",
"new",
"request",
"to",
"the",
"location",
"given",
"by",
"the",
"redirect",
"response",
"to",
"the",
"previous",
"request."
] | def resolve_redirect(self, response, new_location, environ, buffered=False):
(scheme, netloc, path, qs, anchor) = url_parse(new_location)
builder = EnvironBuilder.from_environ(environ, query_string=qs)
to_name_parts = netloc.split(':', 1)[0].split('.')
from_name_parts = builder.server_name.split('.')
... | ['def', 'resolve_redirect(self,', 'response,', 'new_location,', 'environ,', 'buffered=False):', '(scheme,', 'netloc,', 'path,', 'qs,', 'anchor)', '=', 'url_parse(new_location)', 'builder', '=', 'EnvironBuilder.from_environ(environ,', 'query_string=qs)', 'to_name_parts', '=', "netloc.split(':',", "1)[0].split('.')", 'fr... | 84,955 |
rlgraph/rlgraph | agent_test.py | AgentTest.step | step | Performs n steps in the environment, picking up from where the Agent/Environment was before (no reset). | [
"Performs",
"n",
"steps",
"in",
"the",
"environment,",
"picking",
"up",
"from",
"where",
"the",
"Agent/Environment",
"was",
"before",
"(no",
"reset)."
] | def step(self, num_timesteps=1, use_exploration=False, frameskip=None, reset=False):
return self.worker.execute_timesteps(num_timesteps=num_timesteps, use_exploration=use_exploration, frameskip=frameskip, reset=reset) | ['def', 'step(self,', 'num_timesteps=1,', 'use_exploration=False,', 'frameskip=None,', 'reset=False):', 'return', 'self.worker.execute_timesteps(num_timesteps=num_timesteps,', 'use_exploration=use_exploration,', 'frameskip=frameskip,', 'reset=reset)'] | 862,651 |
paulorauber/rl | actors.py | ActorValueOperator.get_policy_operator | get_policy_operator | Returns a standalone policy operator that maps an observation to an action. | [
"Returns",
"a",
"standalone",
"policy",
"operator",
"that",
"maps",
"an",
"observation",
"to",
"an",
"action."
] | def get_policy_operator(self) -> SafeSequential:
if isinstance(self.module[1], SafeProbabilisticTensorDictSequential):
return SafeProbabilisticTensorDictSequential(self.module[0], *self.module[1].module)
return SafeSequential(self.module[0], self.module[1]) | ['def', 'get_policy_operator(self)', '->', 'SafeSequential:', 'if', 'isinstance(self.module[1],', 'SafeProbabilisticTensorDictSequential):', 'return', 'SafeProbabilisticTensorDictSequential(self.module[0],', '*self.module[1].module)', 'return', 'SafeSequential(self.module[0],', 'self.module[1])'] | 859,244 |
FederatedAI/FedVision | checkport.py | wait_server_ready | wait_server_ready | Wait until parameter servers are ready, use connext_ex to detect port readiness. | [
"Wait",
"until",
"parameter",
"servers",
"are",
"ready,",
"use",
"connext_ex",
"to",
"detect",
"port",
"readiness."
] | def wait_server_ready(endpoints):
assert not isinstance(endpoints, string_types)
while True:
all_ok = True
not_ready_endpoints = []
for ep in endpoints:
ip_port = ep.split(':')
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
... | ['def', 'wait_server_ready(endpoints):', 'assert', 'not', 'isinstance(endpoints,', 'string_types)', 'while', 'True:', 'all_ok', '=', 'True', 'not_ready_endpoints', '=', '[]', 'for', 'ep', 'in', 'endpoints:', 'ip_port', '=', "ep.split(':')", 'with', 'closing(socket.socket(socket.AF_INET,', 'socket.SOCK_STREAM))', 'as', ... | 581,831 |
aisingapore/PeekingDuck | zones.py | Node.run | run | Draws the boundaries of each specified zone onto the image. | [
"Draws",
"the",
"boundaries",
"of",
"each",
"specified",
"zone",
"onto",
"the",
"image."
] | def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
draw_zones(inputs['img'], inputs['zones'])
return {} | ['def', 'run(self,', 'inputs:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', "draw_zones(inputs['img'],", "inputs['zones'])", 'return', '{}'] | 766,855 |
pyelasticsearch/pyelasticsearch | json_tests.py | JsonTests.test_set_encoding | test_set_encoding | Make sure encountering a set doesn't raise a circular reference error. | [
"Make",
"sure",
"encountering",
"a",
"set",
"doesn't",
"raise",
"a",
"circular",
"reference",
"error."
] | def test_set_encoding(self):
self.assertEqual(self.conn._encode_json({'hi': set([1])}), '{"hi": [1]}') | ['def', 'test_set_encoding(self):', "self.assertEqual(self.conn._encode_json({'hi':", 'set([1])}),', '\'{"hi":', "[1]}')"] | 296,279 |
intra2net/guibot | test_calibrator.py | CalibratorTest.test_calibrate_scaling | test_calibrate_scaling | Check that minimal calibration with a scaled image improves over time. | [
"Check",
"that",
"minimal",
"calibration",
"with",
"a",
"scaled",
"image",
"improves",
"over",
"time."
] | def test_calibrate_scaling(self):
raw_similarity = self.calibration_setUp('n_ibs', 'h_ibs_scaled', [])
cal_similarity = self.calibration_setUp('n_ibs', 'h_ibs_scaled', ['find', 'feature', 'fdetect', 'fextract', 'fmatch'])
self.assertLessEqual(raw_similarity, cal_similarity, 'Match similarity before calibrat... | ['def', 'test_calibrate_scaling(self):', 'raw_similarity', '=', "self.calibration_setUp('n_ibs',", "'h_ibs_scaled',", '[])', 'cal_similarity', '=', "self.calibration_setUp('n_ibs',", "'h_ibs_scaled',", "['find',", "'feature',", "'fdetect',", "'fextract',", "'fmatch'])", 'self.assertLessEqual(raw_similarity,', 'cal_simi... | 572,599 |
ifwe/digsby | errorpanel.py | ErrorPanel.OnSize | OnSize | This changes the link position when the size of the error panel changes. | [
"This",
"changes",
"the",
"link",
"position",
"when",
"the",
"size",
"of",
"the",
"error",
"panel",
"changes."
] | def OnSize(self, event):
if self.link:
linksize = self.linkrect.Size
if self.link:
self.linkrect = wx.Rect(self.Size.width - linksize.width - self.padding.x, self.Size.height - linksize.height - self.padding.y, *linksize)
self.Refresh(False) | ['def', 'OnSize(self,', 'event):', 'if', 'self.link:', 'linksize', '=', 'self.linkrect.Size', 'if', 'self.link:', 'self.linkrect', '=', 'wx.Rect(self.Size.width', '-', 'linksize.width', '-', 'self.padding.x,', 'self.Size.height', '-', 'linksize.height', '-', 'self.padding.y,', '*linksize)', 'self.Refresh(False)'] | 185,460 |
suarez12138/AI-Reversi_IMP_TextDichotomy | lazy_wheel.py | LazyZipOverHTTP.mode | mode | Opening mode, which is always rb. | [
"Opening",
"mode,",
"which",
"is",
"always",
"rb."
] | def mode(self):
return 'rb' | ['def', 'mode(self):', 'return', "'rb'"] | 98,413 |
thaines/helit | viewer.py | Viewer.get_bg | get_bg | Returns None if no background colour is selected, or a tuple (r,g,b) if it is. | [
"Returns",
"None",
"if",
"no",
"background",
"colour",
"is",
"selected,",
"or",
"a",
"tuple",
"(r,g,b)",
"if",
"it",
"is."
] | def get_bg(self):
return self.bg_col | ['def', 'get_bg(self):', 'return', 'self.bg_col'] | 592,758 |
sunishsheth2009/ChatterBot | ttk.py | Style.element_create | element_create | Create a new element in the current theme of given etype. | [
"Create",
"a",
"new",
"element",
"in",
"the",
"current",
"theme",
"of",
"given",
"etype."
] | def element_create(self, elementname, etype, *args, **kw):
(spec, opts) = _format_elemcreate(etype, False, *args, **kw)
self.tk.call(self._name, 'element', 'create', elementname, etype, spec, *opts) | ['def', 'element_create(self,', 'elementname,', 'etype,', '*args,', '**kw):', '(spec,', 'opts)', '=', '_format_elemcreate(etype,', 'False,', '*args,', '**kw)', 'self.tk.call(self._name,', "'element',", "'create',", 'elementname,', 'etype,', 'spec,', '*opts)'] | 528,142 |
imoscovitz/wittgenstein | irep.py | IREP.predict | predict | Predict classes of data using a IREP-fit model. | [
"Predict",
"classes",
"of",
"data",
"using",
"a",
"IREP-fit",
"model."
] | def predict(self, X_df, give_reasons=False):
if not hasattr(self, 'ruleset_'):
raise AttributeError('You should fit an IREP object before making predictions with it.')
else:
return self.ruleset_.predict(X_df, give_reasons=give_reasons) | ['def', 'predict(self,', 'X_df,', 'give_reasons=False):', 'if', 'not', 'hasattr(self,', "'ruleset_'):", 'raise', "AttributeError('You", 'should', 'fit', 'an', 'IREP', 'object', 'before', 'making', 'predictions', 'with', "it.')", 'else:', 'return', 'self.ruleset_.predict(X_df,', 'give_reasons=give_reasons)'] | 959,834 |
Quantum-Cheese/DeepReinforcementLearning_Pytorch | ddpg_1.py | Agent.step | step | Save experience in replay memory, and use random sample from buffer to learn. | [
"Save",
"experience",
"in",
"replay",
"memory,",
"and",
"use",
"random",
"sample",
"from",
"buffer",
"to",
"learn."
] | def step(self, state, action, reward, next_state, done):
self.memory.add(state, action, reward, next_state, done)
if len(self.memory) > BATCH_SIZE:
experiences = self.memory.sample()
self.learn(experiences, GAMMA) | ['def', 'step(self,', 'state,', 'action,', 'reward,', 'next_state,', 'done):', 'self.memory.add(state,', 'action,', 'reward,', 'next_state,', 'done)', 'if', 'len(self.memory)', '>', 'BATCH_SIZE:', 'experiences', '=', 'self.memory.sample()', 'self.learn(experiences,', 'GAMMA)'] | 539,409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.