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 |
|---|---|---|---|---|---|---|---|---|
asyml/texar | tf_helpers.py | SampleEmbeddingHelper.sample | sample | Gets a sample for one step. | [
"Gets",
"a",
"sample",
"for",
"one",
"step."
] | def sample(self, time, outputs, state, name=None):
del time, state
if not isinstance(outputs, ops.Tensor):
raise TypeError('Expected outputs to be a single Tensor, got: %s' % type(outputs))
if self._softmax_temperature is None:
logits = outputs
else:
logits = outputs / self._soft... | ['def', 'sample(self,', 'time,', 'outputs,', 'state,', 'name=None):', 'del', 'time,', 'state', 'if', 'not', 'isinstance(outputs,', 'ops.Tensor):', 'raise', "TypeError('Expected", 'outputs', 'to', 'be', 'a', 'single', 'Tensor,', 'got:', "%s'", '%', 'type(outputs))', 'if', 'self._softmax_temperature', 'is', 'None:', 'log... | 924,695 |
intel/neural-compressor | tuning_space.py | TuningSpace.get_op_default_path_by_pattern | get_op_default_path_by_pattern | Get the default path by quant mode. | [
"Get",
"the",
"default",
"path",
"by",
"quant",
"mode."
] | def get_op_default_path_by_pattern(self, op_name_type, pattern):
internal_pattern = pattern_to_internal(pattern)
full_path = {'activation': None, 'weight': None}
(full_path['activation'], full_path['weight']) = pattern_to_path(internal_pattern)
result = {}
has_weight = op_name_type in self.ops_attr[... | ['def', 'get_op_default_path_by_pattern(self,', 'op_name_type,', 'pattern):', 'internal_pattern', '=', 'pattern_to_internal(pattern)', 'full_path', '=', "{'activation':", 'None,', "'weight':", 'None}', "(full_path['activation'],", "full_path['weight'])", '=', 'pattern_to_path(internal_pattern)', 'result', '=', '{}', 'h... | 738,775 |
sek788432/Waymo-2D-Object-Detection | xlnet_config.py | XLNetConfig.to_json | to_json | Save XLNetConfig to a json file. | [
"Save",
"XLNetConfig",
"to",
"a",
"json",
"file."
] | def to_json(self, json_path):
json_data = {}
for key in self.keys:
json_data[key] = getattr(self, key)
json_dir = os.path.dirname(json_path)
if not tf.io.gfile.exists(json_dir):
tf.io.gfile.makedirs(json_dir)
with tf.io.gfile.GFile(json_path, 'w') as f:
json.dump(json_data, f... | ['def', 'to_json(self,', 'json_path):', 'json_data', '=', '{}', 'for', 'key', 'in', 'self.keys:', 'json_data[key]', '=', 'getattr(self,', 'key)', 'json_dir', '=', 'os.path.dirname(json_path)', 'if', 'not', 'tf.io.gfile.exists(json_dir):', 'tf.io.gfile.makedirs(json_dir)', 'with', 'tf.io.gfile.GFile(json_path,', "'w')",... | 972,921 |
voxel51/fiftyone | sample.py | _SampleMixin.to_dict | to_dict | Serializes the sample to a JSON dictionary. | [
"Serializes",
"the",
"sample",
"to",
"a",
"JSON",
"dictionary."
] | def to_dict(self, include_frames=False, include_private=False):
d = super().to_dict(include_private=include_private)
if self.media_type == fomm.VIDEO:
if include_frames:
d['frames'] = self.frames._to_frames_dict(include_private=include_private)
else:
d.pop('frames', None)... | ['def', 'to_dict(self,', 'include_frames=False,', 'include_private=False):', 'd', '=', 'super().to_dict(include_private=include_private)', 'if', 'self.media_type', '==', 'fomm.VIDEO:', 'if', 'include_frames:', "d['frames']", '=', 'self.frames._to_frames_dict(include_private=include_private)', 'else:', "d.pop('frames',"... | 583,261 |
Cihsaing/RVSL-rvsl-robust-vehicle-similarity-learning--ECCV22 | usage.py | parseArgs | parseArgs | Print usage and parse arguments. | [
"Print",
"usage",
"and",
"parse",
"arguments."
] | def parseArgs():
def check_cols(value):
valid = ['idx', 'seq', 'altseq', 'tid', 'layer', 'trace', 'dir', 'sub', 'mod', 'op', 'kernel', 'params', 'sil', 'tc', 'device', 'stream', 'grid', 'block', 'flops', 'bytes']
cols = value.split(',')
for col in cols:
if col not in valid:
... | ['def', 'parseArgs():', 'def', 'check_cols(value):', 'valid', '=', "['idx',", "'seq',", "'altseq',", "'tid',", "'layer',", "'trace',", "'dir',", "'sub',", "'mod',", "'op',", "'kernel',", "'params',", "'sil',", "'tc',", "'device',", "'stream',", "'grid',", "'block',", "'flops',", "'bytes']", 'cols', '=', "value.split(',... | 327,126 |
ADLab3Ds/TiG-BEV | lyft_dataset.py | LyftDataset.json2csv | json2csv | Convert the json file to csv format for submission. | [
"Convert",
"the",
"json",
"file",
"to",
"csv",
"format",
"for",
"submission."
] | def json2csv(self, json_path, csv_savepath):
results = mmcv.load(json_path)['results']
sample_list_path = osp.join(self.data_root, 'sample_submission.csv')
data = pd.read_csv(sample_list_path)
Id_list = list(data['Id'])
pred_list = list(data['PredictionString'])
cnt = 0
print('Converting the... | ['def', 'json2csv(self,', 'json_path,', 'csv_savepath):', 'results', '=', "mmcv.load(json_path)['results']", 'sample_list_path', '=', 'osp.join(self.data_root,', "'sample_submission.csv')", 'data', '=', 'pd.read_csv(sample_list_path)', 'Id_list', '=', "list(data['Id'])", 'pred_list', '=', "list(data['PredictionString']... | 916,923 |
ecobost/cnn4brca | train.py | train | train | Creates and trains a convolutional network for image segmentation. | [
"Creates",
"and",
"trains",
"a",
"convolutional",
"network",
"for",
"image",
"segmentation."
] | def train(training_steps=TRAINING_STEPS, learning_rate=LEARNING_RATE, lambda_=LAMBDA, resume_training=RESUME_TRAINING, data_dir=DATA_DIR, model_dir=MODEL_DIR, csv_path=CSV_PATH):
if not os.path.exists(model_dir):
os.makedirs(model_dir)
(image_filenames, label_filenames) = read_csv_info(csv_path)
(im... | ['def', 'train(training_steps=TRAINING_STEPS,', 'learning_rate=LEARNING_RATE,', 'lambda_=LAMBDA,', 'resume_training=RESUME_TRAINING,', 'data_dir=DATA_DIR,', 'model_dir=MODEL_DIR,', 'csv_path=CSV_PATH):', 'if', 'not', 'os.path.exists(model_dir):', 'os.makedirs(model_dir)', '(image_filenames,', 'label_filenames)', '=', '... | 123,891 |
open-mmlab/mmdetection3d | mvx_two_stage.py | MVXTwoStageDetector.with_pts_backbone | with_pts_backbone | bool: Whether the detector has a 3D backbone. | [
"bool:",
"Whether",
"the",
"detector",
"has",
"a",
"3D",
"backbone."
] | def with_pts_backbone(self):
return hasattr(self, 'pts_backbone') and self.pts_backbone is not None | ['def', 'with_pts_backbone(self):', 'return', 'hasattr(self,', "'pts_backbone')", 'and', 'self.pts_backbone', 'is', 'not', 'None'] | 632,003 |
cristiand391/cs50ai | minesweeper.py | Minesweeper.print | print | Prints a text-based representation of where mines are located. | [
"Prints",
"a",
"text-based",
"representation",
"of",
"where",
"mines",
"are",
"located."
] | def print(self):
for i in range(self.height):
print('--' * self.width + '-')
for j in range(self.width):
if self.board[i][j]:
print('|X', end='')
else:
print('| ', end='')
print('|')
print('--' * self.width + '-') | ['def', 'print(self):', 'for', 'i', 'in', 'range(self.height):', "print('--'", '*', 'self.width', '+', "'-')", 'for', 'j', 'in', 'range(self.width):', 'if', 'self.board[i][j]:', "print('|X',", "end='')", 'else:', "print('|", "',", "end='')", "print('|')", "print('--'", '*', 'self.width', '+', "'-')"] | 192,188 |
ldkong1205/LaserMix | dsvt.py | DSVT.with_middle_encoder | with_middle_encoder | bool: Whether the detector has a middle encoder. | [
"bool:",
"Whether",
"the",
"detector",
"has",
"a",
"middle",
"encoder."
] | def with_middle_encoder(self):
return hasattr(self, 'middle_encoder') and self.middle_encoder is not None | ['def', 'with_middle_encoder(self):', 'return', 'hasattr(self,', "'middle_encoder')", 'and', 'self.middle_encoder', 'is', 'not', 'None'] | 624,537 |
43Carrig/recurrent_neural_networks_practice | db.py | Schema.create_event_logs_table_path_index | create_event_logs_table_path_index | Uniquely indexes the (name, path) fields on the event_logs table. | [
"Uniquely",
"indexes",
"the",
"(name,",
"path)",
"fields",
"on",
"the",
"event_logs",
"table."
] | def create_event_logs_table_path_index(self):
with self._cursor() as c:
c.execute(' CREATE UNIQUE INDEX IF NOT EXISTS EventLogsPathIndex\n ON EventLogs (run_id, path)\n ') | ['def', 'create_event_logs_table_path_index(self):', 'with', 'self._cursor()', 'as', 'c:', "c.execute('", 'CREATE', 'UNIQUE', 'INDEX', 'IF', 'NOT', 'EXISTS', 'EventLogsPathIndex\\n', 'ON', 'EventLogs', '(run_id,', 'path)\\n', "')"] | 311,978 |
deepmind/dm_alchemy | bot_running_tracker.py | BotRunningTracker.episode_returns | episode_returns | Gets returns from trackers on environment copies. | [
"Gets",
"returns",
"from",
"trackers",
"on",
"environment",
"copies."
] | def episode_returns(self) -> Any:
return tree.map_structure(lambda *args: np.mean(args, axis=0), *tuple((env.episode_returns() for env in self.envs))) | ['def', 'episode_returns(self)', '->', 'Any:', 'return', 'tree.map_structure(lambda', '*args:', 'np.mean(args,', 'axis=0),', '*tuple((env.episode_returns()', 'for', 'env', 'in', 'self.envs)))'] | 522,142 |
sail-sg/mugs | vision_transformer.py | drop_path | drop_path | Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). | [
"Drop",
"paths",
"(Stochastic",
"Depth)",
"per",
"sample",
"(when",
"applied",
"in",
"main",
"path",
"of",
"residual",
"blocks)."
] | def drop_path(x, drop_prob: float=0.0, training: bool=False):
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
random_tensor.floor_()
output = ... | ['def', 'drop_path(x,', 'drop_prob:', 'float=0.0,', 'training:', 'bool=False):', 'if', 'drop_prob', '==', '0.0', 'or', 'not', 'training:', 'return', 'x', 'keep_prob', '=', '1', '-', 'drop_prob', 'shape', '=', '(x.shape[0],)', '+', '(1,)', '*', '(x.ndim', '-', '1)', 'random_tensor', '=', 'keep_prob', '+', 'torch.rand(sh... | 265,639 |
jonathanking/sidechainnet | manual_adjustment.py | manually_correct_mask | manually_correct_mask | Corrects a protein sequence mask for a given ProteinNet ID. | [
"Corrects",
"a",
"protein",
"sequence",
"mask",
"for",
"a",
"given",
"ProteinNet",
"ID."
] | def manually_correct_mask(pnid, pn_entry, mask):
if pnid == '3TDN_1_A':
mask = binary_mask_to_str(pn_entry['mask'])
return mask | ['def', 'manually_correct_mask(pnid,', 'pn_entry,', 'mask):', 'if', 'pnid', '==', "'3TDN_1_A':", 'mask', '=', "binary_mask_to_str(pn_entry['mask'])", 'return', 'mask'] | 934,115 |
googleapis/python-aiplatform | client.py | EndpointServiceClient.parse_model_deployment_monitoring_job_path | parse_model_deployment_monitoring_job_path | Parses a model_deployment_monitoring_job path into its component segments. | [
"Parses",
"a",
"model_deployment_monitoring_job",
"path",
"into",
"its",
"component",
"segments."
] | def parse_model_deployment_monitoring_job_path(path: str) -> Dict[str, str]:
m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/modelDeploymentMonitoringJobs/(?P<model_deployment_monitoring_job>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_model_deployment_monitoring_job_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/modelDeploymentMonitoringJobs/(?P<model_deployment_monitoring_job>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 810,452 |
SamsungLabs/imvoxelnet | coord_3d_mode.py | Coord3DMode.convert_point | convert_point | Convert points from `src` mode to `dst` mode. | [
"Convert",
"points",
"from",
"`src`",
"mode",
"to",
"`dst`",
"mode."
] | def convert_point(point, src, dst, rt_mat=None):
if src == dst:
return point
is_numpy = isinstance(point, np.ndarray)
is_InstancePoints = isinstance(point, BasePoints)
single_point = isinstance(point, (list, tuple))
if single_point:
assert len(point) >= 3, 'CoordMode.convert takes ei... | ['def', 'convert_point(point,', 'src,', 'dst,', 'rt_mat=None):', 'if', 'src', '==', 'dst:', 'return', 'point', 'is_numpy', '=', 'isinstance(point,', 'np.ndarray)', 'is_InstancePoints', '=', 'isinstance(point,', 'BasePoints)', 'single_point', '=', 'isinstance(point,', '(list,', 'tuple))', 'if', 'single_point:', 'assert'... | 611,848 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | template.py | Base.isVoid | isVoid | True if this item is void. | [
"True",
"if",
"this",
"item",
"is",
"void."
] | def isVoid(self):
return 'void' == self.type | ['def', 'isVoid(self):', 'return', "'void'", '==', 'self.type'] | 10,920 |
Ruturaj123/Flowchart-Detection | command_parser.py | parse_tensor_name_with_slicing | parse_tensor_name_with_slicing | Parse tensor name, potentially suffixed by slicing string. | [
"Parse",
"tensor",
"name,",
"potentially",
"suffixed",
"by",
"slicing",
"string."
] | def parse_tensor_name_with_slicing(in_str):
if in_str.count('[') == 1 and in_str.endswith(']'):
tensor_name = in_str[:in_str.index('[')]
tensor_slicing = in_str[in_str.index('['):]
else:
tensor_name = in_str
tensor_slicing = ''
return (tensor_name, tensor_slicing) | ['def', 'parse_tensor_name_with_slicing(in_str):', 'if', "in_str.count('[')", '==', '1', 'and', "in_str.endswith(']'):", 'tensor_name', '=', "in_str[:in_str.index('[')]", 'tensor_slicing', '=', "in_str[in_str.index('['):]", 'else:', 'tensor_name', '=', 'in_str', 'tensor_slicing', '=', "''", 'return', '(tensor_name,', '... | 605,021 |
PacktPublishing/Hands-On-Artificial--for-Banking | base.py | trim_front | trim_front | Trims zeros and decimal points. | [
"Trims",
"zeros",
"and",
"decimal",
"points."
] | def trim_front(strings: List[str]) -> List[str]:
trimmed = strings
while len(strings) > 0 and all((x[0] == ' ' for x in trimmed)):
trimmed = [x[1:] for x in trimmed]
return trimmed | ['def', 'trim_front(strings:', 'List[str])', '->', 'List[str]:', 'trimmed', '=', 'strings', 'while', 'len(strings)', '>', '0', 'and', 'all((x[0]', '==', "'", "'", 'for', 'x', 'in', 'trimmed)):', 'trimmed', '=', '[x[1:]', 'for', 'x', 'in', 'trimmed]', 'return', 'trimmed'] | 236,595 |
matsu0228/nlp-jp | bsplines.py | gauss_spline | gauss_spline | Gaussian approximation to B-spline basis function of order n. | [
"Gaussian",
"approximation",
"to",
"B-spline",
"basis",
"function",
"of",
"order",
"n."
] | def gauss_spline(x, n):
signsq = (n + 1) / 12.0
return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq) | ['def', 'gauss_spline(x,', 'n):', 'signsq', '=', '(n', '+', '1)', '/', '12.0', 'return', '1', '/', 'sqrt(2', '*', 'pi', '*', 'signsq)', '*', 'exp(-x', '**', '2', '/', '2', '/', 'signsq)'] | 805,726 |
triaquae/triaquae | runserver.py | Command.get_handler | get_handler | Returns the default WSGI handler for the runner. | [
"Returns",
"the",
"default",
"WSGI",
"handler",
"for",
"the",
"runner."
] | def get_handler(self, *args, **options):
return get_internal_wsgi_application() | ['def', 'get_handler(self,', '*args,', '**options):', 'return', 'get_internal_wsgi_application()'] | 358,386 |
Farama-Foundation/D4RL | sim_robot.py | MujocoSimRobot.get_mjlib | get_mjlib | Returns an object that exposes the low-level MuJoCo API. | [
"Returns",
"an",
"object",
"that",
"exposes",
"the",
"low-level",
"MuJoCo",
"API."
] | def get_mjlib(self):
if self._use_dm_backend:
return module.get_dm_mujoco().wrapper.mjbindings.mjlib
else:
return module.get_mujoco_py_mjlib() | ['def', 'get_mjlib(self):', 'if', 'self._use_dm_backend:', 'return', 'module.get_dm_mujoco().wrapper.mjbindings.mjlib', 'else:', 'return', 'module.get_mujoco_py_mjlib()'] | 126,468 |
nosmokingbandit/watcher | event_handler.py | EventHandler.raiseEvent | raiseEvent | Raiser an event: call each handler for this event_name. | [
"Raiser",
"an",
"event:",
"call",
"each",
"handler",
"for",
"this",
"event_name."
] | def raiseEvent(self, event_name, *args):
if event_name not in self.handlers:
return
for handler in self.handlers[event_name]:
handler(*args) | ['def', 'raiseEvent(self,', 'event_name,', '*args):', 'if', 'event_name', 'not', 'in', 'self.handlers:', 'return', 'for', 'handler', 'in', 'self.handlers[event_name]:', 'handler(*args)'] | 381,658 |
Trusted-AI/AIF360 | sample_distortion_metric.py | SampleDistortionMetric.mean_euclidean_distance_difference | mean_euclidean_distance_difference | Difference of the averages. | [
"Difference",
"of",
"the",
"averages."
] | def mean_euclidean_distance_difference(self, privileged=None):
return self.difference(self.average(self.euclidean_distance, privileged=privileged)) | ['def', 'mean_euclidean_distance_difference(self,', 'privileged=None):', 'return', 'self.difference(self.average(self.euclidean_distance,', 'privileged=privileged))'] | 412,371 |
voxel51/fiftyone | cvat.py | CVATAnnotationAPI.post | post | Sends a POST request to the given CVAT API URL. | [
"Sends",
"a",
"POST",
"request",
"to",
"the",
"given",
"CVAT",
"API",
"URL."
] | def post(self, url, **kwargs):
return self._make_request(self._session.post, url, **kwargs) | ['def', 'post(self,', 'url,', '**kwargs):', 'return', 'self._make_request(self._session.post,', 'url,', '**kwargs)'] | 583,993 |
deepmind/dm_control | application.py | Application.launch | launch | Starts the viewer with the specified policy and environment. | [
"Starts",
"the",
"viewer",
"with",
"the",
"specified",
"policy",
"and",
"environment."
] | def launch(self, environment_loader, policy=None):
if environment_loader is None:
raise ValueError('"environment_loader" argument is required.')
if callable(environment_loader):
self._environment_loader = environment_loader
else:
self._environment_loader = lambda : environment_loader... | ['def', 'launch(self,', 'environment_loader,', 'policy=None):', 'if', 'environment_loader', 'is', 'None:', 'raise', 'ValueError(\'"environment_loader"', 'argument', 'is', "required.')", 'if', 'callable(environment_loader):', 'self._environment_loader', '=', 'environment_loader', 'else:', 'self._environment_loader', '='... | 165,643 |
Kvatsx/Artificial-Intelligence-Assignments | ansi_code_processor.py | QtAnsiCodeProcessor.get_color | get_color | Returns a QColor for a given color code or rgb list, or None if one cannot be constructed. | [
"Returns",
"a",
"QColor",
"for",
"a",
"given",
"color",
"code",
"or",
"rgb",
"list,",
"or",
"None",
"if",
"one",
"cannot",
"be",
"constructed."
] | def get_color(self, color, intensity=0):
if isinstance(color, int):
if color < 8 and intensity > 0:
color += 8
constructor = self.color_map.get(color, None)
elif isinstance(color, (tuple, list)):
constructor = color
else:
return None
if isinstance(constructor,... | ['def', 'get_color(self,', 'color,', 'intensity=0):', 'if', 'isinstance(color,', 'int):', 'if', 'color', '<', '8', 'and', 'intensity', '>', '0:', 'color', '+=', '8', 'constructor', '=', 'self.color_map.get(color,', 'None)', 'elif', 'isinstance(color,', '(tuple,', 'list)):', 'constructor', '=', 'color', 'else:', 'return... | 77,199 |
calico/basenji | basenji_sad.py | targets_prep_strand | targets_prep_strand | Adjust targets table for merged stranded datasets. | [
"Adjust",
"targets",
"table",
"for",
"merged",
"stranded",
"datasets."
] | def targets_prep_strand(targets_df):
targets_strand = []
for (_, target) in targets_df.iterrows():
if target.strand_pair == target.name:
targets_strand.append('.')
else:
targets_strand.append(target.identifier[-1])
targets_df['strand'] = targets_strand
strand_mask... | ['def', 'targets_prep_strand(targets_df):', 'targets_strand', '=', '[]', 'for', '(_,', 'target)', 'in', 'targets_df.iterrows():', 'if', 'target.strand_pair', '==', 'target.name:', "targets_strand.append('.')", 'else:', 'targets_strand.append(target.identifier[-1])', "targets_df['strand']", '=', 'targets_strand', 'stran... | 94,788 |
david-abel/simple_rl | ExperimentClass.py | Experiment.write_exp_info_to_file | write_exp_info_to_file | Summary: Writes relevant experiment information to a file for reproducibility. | [
"Summary:",
"Writes",
"relevant",
"experiment",
"information",
"to",
"a",
"file",
"for",
"reproducibility."
] | def write_exp_info_to_file(self):
out_file = open(os.path.join(self.exp_directory, Experiment.EXP_PARAM_FILE_NAME), 'w+')
to_write_to_file = self._get_exp_file_string()
out_file.write(to_write_to_file)
out_file.close() | ['def', 'write_exp_info_to_file(self):', 'out_file', '=', 'open(os.path.join(self.exp_directory,', 'Experiment.EXP_PARAM_FILE_NAME),', "'w+')", 'to_write_to_file', '=', 'self._get_exp_file_string()', 'out_file.write(to_write_to_file)', 'out_file.close()'] | 350,725 |
cjerry1243/TransferLearning-CLVC | kaldi_io.py | read_vec_flt_scp | read_vec_flt_scp | Create generator of (key,vector<float32/float64>) tuples, read according to Kaldi scp. | [
"Create",
"generator",
"of",
"(key,vector<float32/float64>)",
"tuples,",
"read",
"according",
"to",
"Kaldi",
"scp."
] | def read_vec_flt_scp(file_or_fd):
return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_flt_scp) | ['def', 'read_vec_flt_scp(file_or_fd):', 'return', '_convert_method_output_to_tensor(file_or_fd,', 'kaldi_io.read_vec_flt_scp)'] | 930,279 |
triaquae/triaquae | overlays.py | GOverlayBase.add_event | add_event | Attaches a GEvent to the overlay object. | [
"Attaches",
"a",
"GEvent",
"to",
"the",
"overlay",
"object."
] | def add_event(self, event):
self.events.append(event) | ['def', 'add_event(self,', 'event):', 'self.events.append(event)'] | 357,918 |
rakeshvar/rnn_ctc | updates.py | total_norm_constraint | total_norm_constraint | Rescales a list of tensors based on their combined norm If the combined norm of the input tensors exceeds the threshold then all tensors are rescaled such that the combined norm is equal to the threshold. | [
"Rescales",
"a",
"list",
"of",
"tensors",
"based",
"on",
"their",
"combined",
"norm",
"If",
"the",
"combined",
"norm",
"of",
"the",
"input",
"tensors",
"exceeds",
"the",
"threshold",
"then",
"all",
"tensors",
"are",
"rescaled",
"such",
"that",
"the",
"combin... | def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = T.sqrt(sum((T.sum(tensor ** 2) for tensor in tensor_vars)))
dtype = np.dtype(theano.config.floatX).type
target_norm = T.clip(norm, 0, dtype(max_norm))
multiplier = target_norm / (dtype(epsilon) + norm)
tensor_... | ['def', 'total_norm_constraint(tensor_vars,', 'max_norm,', 'epsilon=1e-07,', 'return_norm=False):', 'norm', '=', 'T.sqrt(sum((T.sum(tensor', '**', '2)', 'for', 'tensor', 'in', 'tensor_vars)))', 'dtype', '=', 'np.dtype(theano.config.floatX).type', 'target_norm', '=', 'T.clip(norm,', '0,', 'dtype(max_norm))', 'multiplier... | 325,553 |
43Carrig/recurrent_neural_networks_practice | cfg.py | GraphBuilder.end_statement | end_statement | Marks the end of a statement. | [
"Marks",
"the",
"end",
"of",
"a",
"statement."
] | def end_statement(self, stmt):
self.active_stmts.remove(stmt) | ['def', 'end_statement(self,', 'stmt):', 'self.active_stmts.remove(stmt)'] | 312,386 |
myothida/Supervised-Machine-Learning | _pylab_helpers.py | Gcf.get_fig_manager | get_fig_manager | If manager number *num* exists, make it the active one and return it; otherwise return *None*. | [
"If",
"manager",
"number",
"*num*",
"exists,",
"make",
"it",
"the",
"active",
"one",
"and",
"return",
"it;",
"otherwise",
"return",
"*None*."
] | def get_fig_manager(cls, num):
manager = cls.figs.get(num, None)
if manager is not None:
cls.set_active(manager)
return manager | ['def', 'get_fig_manager(cls,', 'num):', 'manager', '=', 'cls.figs.get(num,', 'None)', 'if', 'manager', 'is', 'not', 'None:', 'cls.set_active(manager)', 'return', 'manager'] | 362,496 |
rudranil723/mini-main | layer.py | Layer.get_geoms | get_geoms | Return a list containing the OGRGeometry for every Feature in the Layer. | [
"Return",
"a",
"list",
"containing",
"the",
"OGRGeometry",
"for",
"every",
"Feature",
"in",
"the",
"Layer."
] | def get_geoms(self, geos=False):
if geos:
from django.contrib.gis.geos import GEOSGeometry
return [GEOSGeometry(feat.geom.wkb) for feat in self]
else:
return [feat.geom for feat in self] | ['def', 'get_geoms(self,', 'geos=False):', 'if', 'geos:', 'from', 'django.contrib.gis.geos', 'import', 'GEOSGeometry', 'return', '[GEOSGeometry(feat.geom.wkb)', 'for', 'feat', 'in', 'self]', 'else:', 'return', '[feat.geom', 'for', 'feat', 'in', 'self]'] | 315,158 |
netket/netket | cubic.py | O | O | Rotational symmetries of a cube/octahedron aligned with the Cartesian axes. | [
"Rotational",
"symmetries",
"of",
"a",
"cube/octahedron",
"aligned",
"with",
"the",
"Cartesian",
"axes."
] | def O() -> PointGroup:
return PointGroup([Identity(), _rotation(90, [0, 0, 1])], ndim=3) @ T() | ['def', 'O()', '->', 'PointGroup:', 'return', 'PointGroup([Identity(),', '_rotation(90,', '[0,', '0,', '1])],', 'ndim=3)', '@', 'T()'] | 736,279 |
nicknochnack/RealTimeSignLanguageTFJS | mobilenet_test.py | MobileNetTest.test_mobilenet_v3_large_creation | test_mobilenet_v3_large_creation | Test creation of EfficientNet family models. | [
"Test",
"creation",
"of",
"EfficientNet",
"family",
"models."
] | def test_mobilenet_v3_large_creation(self, input_size):
tf.keras.backend.set_image_data_format('channels_last')
network = mobilenet.MobileNet(model_id='MobileNetV3Large', filter_size_scale=0.75)
inputs = tf.keras.Input(shape=(input_size, input_size, 3), batch_size=1)
endpoints = network(inputs)
self... | ['def', 'test_mobilenet_v3_large_creation(self,', 'input_size):', "tf.keras.backend.set_image_data_format('channels_last')", 'network', '=', "mobilenet.MobileNet(model_id='MobileNetV3Large',", 'filter_size_scale=0.75)', 'inputs', '=', 'tf.keras.Input(shape=(input_size,', 'input_size,', '3),', 'batch_size=1)', 'endpoint... | 850,813 |
Farama-Foundation/Shimmy | test_gym.py | EnvWithData.get_env_data | get_env_data | Gets the environment data. | [
"Gets",
"the",
"environment",
"data."
] | def get_env_data(self):
return self.data | ['def', 'get_env_data(self):', 'return', 'self.data'] | 901,069 |
s3prl/s3prl | model.py | GE2E.cosine_similarity | cosine_similarity | Calculate cosine similarity matrix of shape (N, M, N). | [
"Calculate",
"cosine",
"similarity",
"matrix",
"of",
"shape",
"(N,",
"M,",
"N)."
] | def cosine_similarity(self, dvecs):
(n_spkr, n_uttr, d_embd) = dvecs.size()
dvec_expns = dvecs.unsqueeze(-1).expand(n_spkr, n_uttr, d_embd, n_spkr)
dvec_expns = dvec_expns.transpose(2, 3)
ctrds = dvecs.mean(dim=1).to(dvecs.device)
ctrd_expns = ctrds.unsqueeze(0).expand(n_spkr * n_uttr, n_spkr, d_emb... | ['def', 'cosine_similarity(self,', 'dvecs):', '(n_spkr,', 'n_uttr,', 'd_embd)', '=', 'dvecs.size()', 'dvec_expns', '=', 'dvecs.unsqueeze(-1).expand(n_spkr,', 'n_uttr,', 'd_embd,', 'n_spkr)', 'dvec_expns', '=', 'dvec_expns.transpose(2,', '3)', 'ctrds', '=', 'dvecs.mean(dim=1).to(dvecs.device)', 'ctrd_expns', '=', 'ctrds... | 327,509 |
soumyaiitkgp/Custom_MaskRCNN | model.py | batch_pack_graph | batch_pack_graph | Picks different number of values from each row in x depending on the values in counts. | [
"Picks",
"different",
"number",
"of",
"values",
"from",
"each",
"row",
"in",
"x",
"depending",
"on",
"the",
"values",
"in",
"counts."
] | def batch_pack_graph(x, counts, num_rows):
outputs = []
for i in range(num_rows):
outputs.append(x[i, :counts[i]])
return tf.concat(outputs, axis=0) | ['def', 'batch_pack_graph(x,', 'counts,', 'num_rows):', 'outputs', '=', '[]', 'for', 'i', 'in', 'range(num_rows):', 'outputs.append(x[i,', ':counts[i]])', 'return', 'tf.concat(outputs,', 'axis=0)'] | 509,041 |
myothida/Supervised-Machine-Learning | _expm_multiply.py | LazyOperatorNormInfo.set_scale | set_scale | Set the scale parameter. | [
"Set",
"the",
"scale",
"parameter."
] | def set_scale(self, scale):
self._scale = scale | ['def', 'set_scale(self,', 'scale):', 'self._scale', '=', 'scale'] | 446,352 |
YBYBZhang/DiFa | ZSSGAN.py | SG2Generator.style | style | Convert z codes to w codes. | [
"Convert",
"z",
"codes",
"to",
"w",
"codes."
] | def style(self, styles):
styles = [self.generator.style(s) for s in styles]
return styles | ['def', 'style(self,', 'styles):', 'styles', '=', '[self.generator.style(s)', 'for', 's', 'in', 'styles]', 'return', 'styles'] | 550,414 |
yizheh/Chinese_Font_Transfer | dist.py | Distribution.parse_config_files | parse_config_files | Parses configuration files from various levels and loads configuration. | [
"Parses",
"configuration",
"files",
"from",
"various",
"levels",
"and",
"loads",
"configuration."
] | def parse_config_files(self, filenames=None, ignore_option_errors=False):
_Distribution.parse_config_files(self, filenames=filenames)
parse_configuration(self, self.command_options, ignore_option_errors=ignore_option_errors)
self._finalize_requires() | ['def', 'parse_config_files(self,', 'filenames=None,', 'ignore_option_errors=False):', '_Distribution.parse_config_files(self,', 'filenames=filenames)', 'parse_configuration(self,', 'self.command_options,', 'ignore_option_errors=ignore_option_errors)', 'self._finalize_requires()'] | 487,303 |
RasaHQ/rasa | kafka.py | KafkaEventBroker.rasa_environment | rasa_environment | Get value of the `RASA_ENVIRONMENT` environment variable. | [
"Get",
"value",
"of",
"the",
"`RASA_ENVIRONMENT`",
"environment",
"variable."
] | def rasa_environment(self) -> Optional[Text]:
return os.environ.get('RASA_ENVIRONMENT', 'RASA_ENVIRONMENT_NOT_SET') | ['def', 'rasa_environment(self)', '->', 'Optional[Text]:', 'return', "os.environ.get('RASA_ENVIRONMENT',", "'RASA_ENVIRONMENT_NOT_SET')"] | 836,799 |
boostcampaitech2/semantic-segmentation-level2-cv-05 | metrics.py | pre_eval_to_metrics | pre_eval_to_metrics | Convert pre-eval results to metrics. | [
"Convert",
"pre-eval",
"results",
"to",
"metrics."
] | def pre_eval_to_metrics(pre_eval_results, metrics=['mIoU'], nan_to_num=None, beta=1):
pre_eval_results = tuple(zip(*pre_eval_results))
assert len(pre_eval_results) == 4
total_area_intersect = sum(pre_eval_results[0])
total_area_union = sum(pre_eval_results[1])
total_area_pred_label = sum(pre_eval_re... | ['def', 'pre_eval_to_metrics(pre_eval_results,', "metrics=['mIoU'],", 'nan_to_num=None,', 'beta=1):', 'pre_eval_results', '=', 'tuple(zip(*pre_eval_results))', 'assert', 'len(pre_eval_results)', '==', '4', 'total_area_intersect', '=', 'sum(pre_eval_results[0])', 'total_area_union', '=', 'sum(pre_eval_results[1])', 'tot... | 844,633 |
whut2962575697/image_seg | seresnet_ibn.py | se_resnet50_ibn_a | se_resnet50_ibn_a | Constructs a SE-ResNet-50-IBN-a model. | [
"Constructs",
"a",
"SE-ResNet-50-IBN-a",
"model."
] | def se_resnet50_ibn_a(pretrained=False):
model = ResNet_IBN(SEBottleneck_IBN, [3, 4, 6, 3], ibn_cfg=('a', 'a', 'a', None))
if pretrained:
warnings.warn('Pretrained model not available for SE-ResNet-50-IBN-a!')
return model | ['def', 'se_resnet50_ibn_a(pretrained=False):', 'model', '=', 'ResNet_IBN(SEBottleneck_IBN,', '[3,', '4,', '6,', '3],', "ibn_cfg=('a',", "'a',", "'a',", 'None))', 'if', 'pretrained:', "warnings.warn('Pretrained", 'model', 'not', 'available', 'for', "SE-ResNet-50-IBN-a!')", 'return', 'model'] | 610,575 |
sktime/sktime | test_distr_metrics.py | test_distr_evaluate | test_distr_evaluate | Test expected output of evaluate functions. | [
"Test",
"expected",
"output",
"of",
"evaluate",
"functions."
] | def test_distr_evaluate(normal, metric, multivariate):
y_pred = normal.create_test_instance()
y_true = y_pred.sample()
m = metric(multivariate=multivariate)
if not multivariate:
expected_cols = y_true.columns
else:
expected_cols = ['score']
res = m.evaluate_by_index(y_true, y_pre... | ['def', 'test_distr_evaluate(normal,', 'metric,', 'multivariate):', 'y_pred', '=', 'normal.create_test_instance()', 'y_true', '=', 'y_pred.sample()', 'm', '=', 'metric(multivariate=multivariate)', 'if', 'not', 'multivariate:', 'expected_cols', '=', 'y_true.columns', 'else:', 'expected_cols', '=', "['score']", 'res', '=... | 877,420 |
triaquae/triaquae | options.py | BaseModelAdmin.get_readonly_fields | get_readonly_fields | Hook for specifying custom readonly fields. | [
"Hook",
"for",
"specifying",
"custom",
"readonly",
"fields."
] | def get_readonly_fields(self, request, obj=None):
return self.readonly_fields | ['def', 'get_readonly_fields(self,', 'request,', 'obj=None):', 'return', 'self.readonly_fields'] | 356,948 |
ryu-ed/SpaceInvaders_Ros | ast3.py | copy_location | copy_location | Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. | [
"Copy",
"source",
"location",
"(`lineno`",
"and",
"`col_offset`",
"attributes)",
"from",
"*old_node*",
"to",
"*new_node*",
"if",
"possible,",
"and",
"return",
"*new_node*."
] | def copy_location(new_node, old_node):
for attr in ('lineno', 'col_offset'):
if attr in old_node._attributes and attr in new_node._attributes and hasattr(old_node, attr):
setattr(new_node, attr, getattr(old_node, attr))
return new_node | ['def', 'copy_location(new_node,', 'old_node):', 'for', 'attr', 'in', "('lineno',", "'col_offset'):", 'if', 'attr', 'in', 'old_node._attributes', 'and', 'attr', 'in', 'new_node._attributes', 'and', 'hasattr(old_node,', 'attr):', 'setattr(new_node,', 'attr,', 'getattr(old_node,', 'attr))', 'return', 'new_node'] | 371,580 |
DeepGraphLearning/torchdrug | graph.py | Graph.node2graph | node2graph | Node id to graph id mapping. | [
"Node",
"id",
"to",
"graph",
"id",
"mapping."
] | def node2graph(self):
return torch.zeros(self.num_node, dtype=torch.long, device=self.device) | ['def', 'node2graph(self):', 'return', 'torch.zeros(self.num_node,', 'dtype=torch.long,', 'device=self.device)'] | 902,711 |
43Carrig/recurrent_neural_networks_practice | _argument_parser.py | FloatParser.convert | convert | Returns the float value of argument. | [
"Returns",
"the",
"float",
"value",
"of",
"argument."
] | def convert(self, argument):
if _is_integer_type(argument) or isinstance(argument, float) or isinstance(argument, six.string_types):
return float(argument)
else:
raise TypeError('Expect argument to be a string, int, or float, found {}'.format(type(argument))) | ['def', 'convert(self,', 'argument):', 'if', '_is_integer_type(argument)', 'or', 'isinstance(argument,', 'float)', 'or', 'isinstance(argument,', 'six.string_types):', 'return', 'float(argument)', 'else:', 'raise', "TypeError('Expect", 'argument', 'to', 'be', 'a', 'string,', 'int,', 'or', 'float,', 'found', "{}'.format(... | 309,592 |
instadeepai/jumanji | parametric_distribution.py | ParametricDistribution.mode_no_postprocessing | mode_no_postprocessing | Returns the mode of the distribution before postprocessing it. | [
"Returns",
"the",
"mode",
"of",
"the",
"distribution",
"before",
"postprocessing",
"it."
] | def mode_no_postprocessing(self, parameters: chex.Array) -> chex.Array:
return self.create_dist(parameters).mode() | ['def', 'mode_no_postprocessing(self,', 'parameters:', 'chex.Array)', '->', 'chex.Array:', 'return', 'self.create_dist(parameters).mode()'] | 594,596 |
albertomontesg/probabilistic-ai-exercises | bprop.py | FactorGraph.draw | draw | Draw the factor graph. | [
"Draw",
"the",
"factor",
"graph."
] | def draw(self):
g = self.to_networkx()
pos = nx.spring_layout(g)
nx.draw_networkx_edges(g, pos, edge_color=EDGE_COLOR, width=EDGE_WIDTH)
obj = nx.draw_networkx_nodes(g, pos, nodelist=self.vs.values(), node_size=NODE_SIZE, node_color=NODE_COLOR_NORMAL)
obj.set_linewidth(NODE_BORDER_WIDTH)
obj.set... | ['def', 'draw(self):', 'g', '=', 'self.to_networkx()', 'pos', '=', 'nx.spring_layout(g)', 'nx.draw_networkx_edges(g,', 'pos,', 'edge_color=EDGE_COLOR,', 'width=EDGE_WIDTH)', 'obj', '=', 'nx.draw_networkx_nodes(g,', 'pos,', 'nodelist=self.vs.values(),', 'node_size=NODE_SIZE,', 'node_color=NODE_COLOR_NORMAL)', 'obj.set_l... | 295,451 |
Floobits/floobits-sublime | diff_match_patch.py | diff_match_patch.diff_halfMatch | diff_halfMatch | Do the two texts share a substring which is at least half the length of the longer text? This speedup can produce non-minimal diffs. | [
"Do",
"the",
"two",
"texts",
"share",
"a",
"substring",
"which",
"is",
"at",
"least",
"half",
"the",
"length",
"of",
"the",
"longer",
"text?",
"This",
"speedup",
"can",
"produce",
"non-minimal",
"diffs."
] | def diff_halfMatch(self, text1, text2):
if self.Diff_Timeout <= 0:
return None
if len(text1) > len(text2):
(longtext, shorttext) = (text1, text2)
else:
(shorttext, longtext) = (text1, text2)
if len(longtext) < 4 or len(shorttext) * 2 < len(longtext):
return None
def ... | ['def', 'diff_halfMatch(self,', 'text1,', 'text2):', 'if', 'self.Diff_Timeout', '<=', '0:', 'return', 'None', 'if', 'len(text1)', '>', 'len(text2):', '(longtext,', 'shorttext)', '=', '(text1,', 'text2)', 'else:', '(shorttext,', 'longtext)', '=', '(text1,', 'text2)', 'if', 'len(longtext)', '<', '4', 'or', 'len(shorttext... | 211,418 |
megvii-research/MSCL | flow_extraction_megv2.py | generate_flow | generate_flow | Estimate flow with given frames. | [
"Estimate",
"flow",
"with",
"given",
"frames."
] | def generate_flow(frames, method='tvl1'):
assert method in ['tvl1', 'farneback']
gray_frames = [cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for frame in frames]
if method == 'tvl1':
tvl1 = cv2.optflow.DualTVL1OpticalFlow_create()
def op(x, y):
return tvl1.calc(x, y, None)
elif m... | ['def', 'generate_flow(frames,', "method='tvl1'):", 'assert', 'method', 'in', "['tvl1',", "'farneback']", 'gray_frames', '=', '[cv2.cvtColor(frame,', 'cv2.COLOR_BGR2GRAY)', 'for', 'frame', 'in', 'frames]', 'if', 'method', '==', "'tvl1':", 'tvl1', '=', 'cv2.optflow.DualTVL1OpticalFlow_create()', 'def', 'op(x,', 'y):', '... | 265,069 |
google-research/scenic | sinkhorn.py | idx2permutation | idx2permutation | Constructs a permutation matrix from the column and row indices of ones. | [
"Constructs",
"a",
"permutation",
"matrix",
"from",
"the",
"column",
"and",
"row",
"indices",
"of",
"ones."
] | def idx2permutation(row_ind, col_ind):
(bs, dim) = row_ind.shape[:2]
perm = jnp.zeros(shape=(bs, dim, dim), dtype='float32')
perm = jax.vmap(lambda x, idx, y: x.at[idx].set(y), (0, 0, None))(perm, (row_ind, col_ind), 1.0)
return perm | ['def', 'idx2permutation(row_ind,', 'col_ind):', '(bs,', 'dim)', '=', 'row_ind.shape[:2]', 'perm', '=', 'jnp.zeros(shape=(bs,', 'dim,', 'dim),', "dtype='float32')", 'perm', '=', 'jax.vmap(lambda', 'x,', 'idx,', 'y:', 'x.at[idx].set(y),', '(0,', '0,', 'None))(perm,', '(row_ind,', 'col_ind),', '1.0)', 'return', 'perm'] | 846,290 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | trainer_lib.py | write_summary | write_summary | Write a summary for a certain evaluation. | [
"Write",
"a",
"summary",
"for",
"a",
"certain",
"evaluation."
] | def write_summary(summary_writer, label, value, step):
summary = Summary(value=[Summary.Value(tag=label, simple_value=float(value))])
summary_writer.add_summary(summary, step)
summary_writer.flush() | ['def', 'write_summary(summary_writer,', 'label,', 'value,', 'step):', 'summary', '=', 'Summary(value=[Summary.Value(tag=label,', 'simple_value=float(value))])', 'summary_writer.add_summary(summary,', 'step)', 'summary_writer.flush()'] | 111,506 |
nicknochnack/RealTimeSignLanguageTFJS | revnet.py | build_revnet | build_revnet | Builds ResNet 3d backbone from a config. | [
"Builds",
"ResNet",
"3d",
"backbone",
"from",
"a",
"config."
] | def build_revnet(input_specs: tf.keras.layers.InputSpec, model_config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model:
backbone_type = model_config.backbone.type
backbone_cfg = model_config.backbone.get()
norm_activation_config = model_config.norm_activation
assert backbone_ty... | ['def', 'build_revnet(input_specs:', 'tf.keras.layers.InputSpec,', 'model_config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'model_config.backbone.type', 'backbone_cfg', '=', 'model_config.backbone.get()', 'norm_activation_config', '=', 'model_config.... | 850,828 |
enuguru/artificial_intelligence_and_machine_ | sql.py | TokenList.has_alias | has_alias | Returns ``True`` if an alias is present. | [
"Returns",
"``True``",
"if",
"an",
"alias",
"is",
"present."
] | def has_alias(self):
return self.get_alias() is not None | ['def', 'has_alias(self):', 'return', 'self.get_alias()', 'is', 'not', 'None'] | 131,945 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | _DictWrapper.Mult | Mult | Scales the freq/prob associated with the value x. | [
"Scales",
"the",
"freq/prob",
"associated",
"with",
"the",
"value",
"x."
] | def Mult(self, x, factor):
self.d[x] = self.d.get(x, 0) * factor | ['def', 'Mult(self,', 'x,', 'factor):', 'self.d[x]', '=', 'self.d.get(x,', '0)', '*', 'factor'] | 12,902 |
deepmind/dm_control | rodent.py | Rat.mjcf_model | mjcf_model | Return the model root. | [
"Return",
"the",
"model",
"root."
] | def mjcf_model(self):
return self._mjcf_root | ['def', 'mjcf_model(self):', 'return', 'self._mjcf_root'] | 165,142 |
jxhe/unify-parameter-efficient-tuning | optimization_tf.py | GradientAccumulator.step | step | Number of accumulated steps. | [
"Number",
"of",
"accumulated",
"steps."
] | def step(self):
if self._accum_steps is None:
self._accum_steps = tf.Variable(tf.constant(0, dtype=tf.int64), trainable=False, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA)
return self._accum_steps.value() | ['def', 'step(self):', 'if', 'self._accum_steps', 'is', 'None:', 'self._accum_steps', '=', 'tf.Variable(tf.constant(0,', 'dtype=tf.int64),', 'trainable=False,', 'synchronization=tf.VariableSynchronization.ON_READ,', 'aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA)', 'return', 'self._accum_steps.value()'] | 948,377 |
SvenGronauer/phoenix-drone-simulation | utils.py | rad2deg | rad2deg | Converts radians to degrees. | [
"Converts",
"radians",
"to",
"degrees."
] | def rad2deg(x):
return 180 * x / np.pi | ['def', 'rad2deg(x):', 'return', '180', '*', 'x', '/', 'np.pi'] | 769,153 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Text.tag_unbind | tag_unbind | Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID. | [
"Unbind",
"for",
"all",
"characters",
"with",
"TAGNAME",
"for",
"event",
"SEQUENCE",
"the",
"function",
"identified",
"with",
"FUNCID."
] | def tag_unbind(self, tagName, sequence, funcid=None):
self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
if funcid:
self.deletecommand(funcid) | ['def', 'tag_unbind(self,', 'tagName,', 'sequence,', 'funcid=None):', 'self.tk.call(self._w,', "'tag',", "'bind',", 'tagName,', 'sequence,', "'')", 'if', 'funcid:', 'self.deletecommand(funcid)'] | 377,077 |
scottemmons/rvs | util.py | extract_done_markers | extract_done_markers | Given a per-timestep dones vector, return starts, ends, and lengths of trajs. | [
"Given",
"a",
"per-timestep",
"dones",
"vector,",
"return",
"starts,",
"ends,",
"and",
"lengths",
"of",
"trajs."
] | def extract_done_markers(dones: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
(ends,) = np.where(dones)
starts = np.concatenate(([0], ends[:-1] + 1))
lengths = ends - starts + 1
return (starts, ends, lengths) | ['def', 'extract_done_markers(dones:', 'np.ndarray)', '->', 'Tuple[np.ndarray,', 'np.ndarray,', 'np.ndarray]:', '(ends,)', '=', 'np.where(dones)', 'starts', '=', 'np.concatenate(([0],', 'ends[:-1]', '+', '1))', 'lengths', '=', 'ends', '-', 'starts', '+', '1', 'return', '(starts,', 'ends,', 'lengths)'] | 327,025 |
GeekLiB/keras | common.py | image_dim_ordering | image_dim_ordering | Returns the image dimension ordering convention ('th' or 'tf'). | [
"Returns",
"the",
"image",
"dimension",
"ordering",
"convention",
"('th'",
"or",
"'tf')."
] | def image_dim_ordering():
return _IMAGE_DIM_ORDERING | ['def', 'image_dim_ordering():', 'return', '_IMAGE_DIM_ORDERING'] | 247,734 |
evhub/transfer-learning-live-song-id | transfer_learning_live_song_id.py | binary_threshold | binary_threshold | Cast the given array to binary. | [
"Cast",
"the",
"given",
"array",
"to",
"binary."
] | def binary_threshold(delta_arr, threshold=0):
return np.where(delta_arr >= threshold, 1, 0) | ['def', 'binary_threshold(delta_arr,', 'threshold=0):', 'return', 'np.where(delta_arr', '>=', 'threshold,', '1,', '0)'] | 921,448 |
NoGameNoLife00/mybolg | base.py | FBCompiler.limit_clause | limit_clause | Already taken care of in the `get_select_precolumns` method. | [
"Already",
"taken",
"care",
"of",
"in",
"the",
"`get_select_precolumns`",
"method."
] | def limit_clause(self, select):
return '' | ['def', 'limit_clause(self,', 'select):', 'return', "''"] | 289,671 |
devashish-patel/webcam-motion-detector | pefile.py | PE.get_overlay | get_overlay | Get the data appended to the file and not contained within the area described in the headers. | [
"Get",
"the",
"data",
"appended",
"to",
"the",
"file",
"and",
"not",
"contained",
"within",
"the",
"area",
"described",
"in",
"the",
"headers."
] | def get_overlay(self):
overlay_data_offset = self.get_overlay_data_start_offset()
if overlay_data_offset is not None:
return self.__data__[overlay_data_offset:]
return None | ['def', 'get_overlay(self):', 'overlay_data_offset', '=', 'self.get_overlay_data_start_offset()', 'if', 'overlay_data_offset', 'is', 'not', 'None:', 'return', 'self.__data__[overlay_data_offset:]', 'return', 'None'] | 976,809 |
rudranil723/mini-main | base.py | BaseDatabaseWrapper.clean_savepoints | clean_savepoints | Reset the counter used to generate unique savepoint ids in this thread. | [
"Reset",
"the",
"counter",
"used",
"to",
"generate",
"unique",
"savepoint",
"ids",
"in",
"this",
"thread."
] | def clean_savepoints(self):
self.savepoint_state = 0 | ['def', 'clean_savepoints(self):', 'self.savepoint_state', '=', '0'] | 315,720 |
akandykeller/NeuralWaveMachines | metrics.py | calculate_small_latents | calculate_small_latents | Calculates the number of active latents by thresholding the variance of their distribution. | [
"Calculates",
"the",
"number",
"of",
"active",
"latents",
"by",
"thresholding",
"the",
"variance",
"of",
"their",
"distribution."
] | def calculate_small_latents(dist, threshold=0.5):
if not isinstance(dist, distrax.Normal):
raise NotImplementedError()
latent_means = dist.mean()
latent_stddevs = dist.variance()
small_latents = jnp.sum((latent_stddevs < threshold) & (jnp.abs(latent_means) > 0.1), axis=1)
return jnp.mean(sma... | ['def', 'calculate_small_latents(dist,', 'threshold=0.5):', 'if', 'not', 'isinstance(dist,', 'distrax.Normal):', 'raise', 'NotImplementedError()', 'latent_means', '=', 'dist.mean()', 'latent_stddevs', '=', 'dist.variance()', 'small_latents', '=', 'jnp.sum((latent_stddevs', '<', 'threshold)', '&', '(jnp.abs(latent_means... | 293,536 |
chribsen/simple-machine-learning-examples | _trustregion.py | BaseQuadraticSubproblem.fun | fun | Value of objective function at current iteration. | [
"Value",
"of",
"objective",
"function",
"at",
"current",
"iteration."
] | def fun(self):
if self._f is None:
self._f = self._fun(self._x)
return self._f | ['def', 'fun(self):', 'if', 'self._f', 'is', 'None:', 'self._f', '=', 'self._fun(self._x)', 'return', 'self._f'] | 938,254 |
aws/sagemaker-python-sdk | cache.py | JumpStartModelsCache.get_manifest_file_s3_key | get_manifest_file_s3_key | Return manifest file s3 key for cache. | [
"Return",
"manifest",
"file",
"s3",
"key",
"for",
"cache."
] | def get_manifest_file_s3_key(self) -> str:
return self._manifest_file_s3_key | ['def', 'get_manifest_file_s3_key(self)', '->', 'str:', 'return', 'self._manifest_file_s3_key'] | 830,153 |
rudranil723/mini-main | _regex_core.py | parse_hex_escape | parse_hex_escape | Parses a hex escape sequence. | [
"Parses",
"a",
"hex",
"escape",
"sequence."
] | def parse_hex_escape(source, info, esc, expected_len, in_set, type):
saved_pos = source.pos
digits = []
for i in range(expected_len):
ch = source.get()
if ch not in HEX_DIGITS:
raise error('incomplete escape \\%s%s' % (type, ''.join(digits)), source.string, saved_pos)
dig... | ['def', 'parse_hex_escape(source,', 'info,', 'esc,', 'expected_len,', 'in_set,', 'type):', 'saved_pos', '=', 'source.pos', 'digits', '=', '[]', 'for', 'i', 'in', 'range(expected_len):', 'ch', '=', 'source.get()', 'if', 'ch', 'not', 'in', 'HEX_DIGITS:', 'raise', "error('incomplete", 'escape', "\\\\%s%s'", '%', '(type,',... | 269,811 |
AboudyKreidieh/h-baselines | humanoid_maze_env.py | HumanoidMazeEnv.get_ori | get_ori | Return the orientation of the humanoid. | [
"Return",
"the",
"orientation",
"of",
"the",
"humanoid."
] | def get_ori(self):
return self.wrapped_env.get_ori() | ['def', 'get_ori(self):', 'return', 'self.wrapped_env.get_ori()'] | 573,861 |
lebrice/Sequoia | get_metrics.py | to_optional_tensor | to_optional_tensor | Converts `x` into a Tensor if `x` is not None, else None. | [
"Converts",
"`x`",
"into",
"a",
"Tensor",
"if",
"`x`",
"is",
"not",
"None,",
"else",
"None."
] | def to_optional_tensor(x: Optional[Union[Tensor, np.ndarray, List]]) -> Optional[Tensor]:
return x if x is None else torch.as_tensor(x) | ['def', 'to_optional_tensor(x:', 'Optional[Union[Tensor,', 'np.ndarray,', 'List]])', '->', 'Optional[Tensor]:', 'return', 'x', 'if', 'x', 'is', 'None', 'else', 'torch.as_tensor(x)'] | 344,178 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | registry_test.py | RegistryTest.testCannotCreateNonClass | testCannotCreateNonClass | Tests that Create fails if the name does not identify a class. | [
"Tests",
"that",
"Create",
"fails",
"if",
"the",
"name",
"does",
"not",
"identify",
"a",
"class."
] | def testCannotCreateNonClass(self):
with self.assertRaisesRegexp(ValueError, 'Failed to create'):
registry_test_base.Base.Create(PATH + 'registry_test_impl.variable', 'hello world')
with self.assertRaisesRegexp(ValueError, 'Failed to create'):
registry_test_base.Base.Create(PATH + 'registry_test... | ['def', 'testCannotCreateNonClass(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", 'registry_test_base.Base.Create(PATH', '+', "'registry_test_impl.variable',", "'hello", "world')", 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", 'registry_test_base.Base... | 29,056 |
rifqind/Agent-Programs-3KS1 | base_context.py | Context.execute_evaluated | execute_evaluated | Execute a function with already executed arguments. | [
"Execute",
"a",
"function",
"with",
"already",
"executed",
"arguments."
] | def execute_evaluated(self, *value_list):
from jedi.evaluate.arguments import ValuesArguments
arguments = ValuesArguments([ContextSet(value) for value in value_list])
return self.execute(arguments) | ['def', 'execute_evaluated(self,', '*value_list):', 'from', 'jedi.evaluate.arguments', 'import', 'ValuesArguments', 'arguments', '=', 'ValuesArguments([ContextSet(value)', 'for', 'value', 'in', 'value_list])', 'return', 'self.execute(arguments)'] | 42,097 |
rudranil723/mini-main | _ast_gen.py | ASTCodeGenerator.parse_cfgfile | parse_cfgfile | Parse the configuration file and yield pairs of (name, contents) for each node. | [
"Parse",
"the",
"configuration",
"file",
"and",
"yield",
"pairs",
"of",
"(name,",
"contents)",
"for",
"each",
"node."
] | def parse_cfgfile(self, filename):
with open(filename, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
colon_i = line.find(':')
lbracket_i = line.find('[')
rbracket_i = line.find(']')
... | ['def', 'parse_cfgfile(self,', 'filename):', 'with', 'open(filename,', "'r')", 'as', 'f:', 'for', 'line', 'in', 'f:', 'line', '=', 'line.strip()', 'if', 'not', 'line', 'or', "line.startswith('#'):", 'continue', 'colon_i', '=', "line.find(':')", 'lbracket_i', '=', "line.find('[')", 'rbracket_i', '=', "line.find(']')", '... | 269,586 |
myothida/Supervised-Machine-Learning | text.py | Text.join | join | Join text together with this instance as the separator. | [
"Join",
"text",
"together",
"with",
"this",
"instance",
"as",
"the",
"separator."
] | def join(self, lines: Iterable['Text']) -> 'Text':
new_text = self.blank_copy()
def iter_text() -> Iterable['Text']:
if self.plain:
for (last, line) in loop_last(lines):
yield line
if not last:
yield self
else:
yield fr... | ['def', 'join(self,', 'lines:', "Iterable['Text'])", '->', "'Text':", 'new_text', '=', 'self.blank_copy()', 'def', 'iter_text()', '->', "Iterable['Text']:", 'if', 'self.plain:', 'for', '(last,', 'line)', 'in', 'loop_last(lines):', 'yield', 'line', 'if', 'not', 'last:', 'yield', 'self', 'else:', 'yield', 'from', 'lines'... | 445,123 |
PetrochukM/PyTorch-NLP | subword_text_tokenizer.py | SubwordTextTokenizer.decode | decode | Converts a sequence of subtoken to a native string. | [
"Converts",
"a",
"sequence",
"of",
"subtoken",
"to",
"a",
"native",
"string."
] | def decode(self, subtokens):
return unicode_to_native(decode(self._subtoken_to_tokens(subtokens))) | ['def', 'decode(self,', 'subtokens):', 'return', 'unicode_to_native(decode(self._subtoken_to_tokens(subtokens)))'] | 814,876 |
befelix/safe_learning | test_functions.py | TestQuadraticFunction.test_evaluate | test_evaluate | Setup testing environment for quadratic. | [
"Setup",
"testing",
"environment",
"for",
"quadratic."
] | def test_evaluate(self):
points = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float)
P = np.array([[1.0, 0.1], [0.2, 2.0]])
quad = QuadraticFunction(P)
true_fval = np.array([[0.0, 2.0, 1.0, 3.3]]).T
with tf.Session():
tf_res = quad(points)
res = tf_res.eval()
assert_allcl... | ['def', 'test_evaluate(self):', 'points', '=', 'np.array([[0,', '0],', '[0,', '1],', '[1,', '0],', '[1,', '1]],', 'dtype=np.float)', 'P', '=', 'np.array([[1.0,', '0.1],', '[0.2,', '2.0]])', 'quad', '=', 'QuadraticFunction(P)', 'true_fval', '=', 'np.array([[0.0,', '2.0,', '1.0,', '3.3]]).T', 'with', 'tf.Session():', 'tf... | 328,236 |
deepmind/dm_control | debugging.py | set_full_dump_dir | set_full_dump_dir | Sets the directory to dump full debug info files. | [
"Sets",
"the",
"directory",
"to",
"dump",
"full",
"debug",
"info",
"files."
] | def set_full_dump_dir(dump_path):
global _DEBUG_FULL_DUMP_DIR
_DEBUG_FULL_DUMP_DIR = dump_path | ['def', 'set_full_dump_dir(dump_path):', 'global', '_DEBUG_FULL_DUMP_DIR', '_DEBUG_FULL_DUMP_DIR', '=', 'dump_path'] | 165,199 |
loicmarie/hands-detection | check.py | Le | Le | Raises an error if |lhs| is not less than or equal to |rhs|. | [
"Raises",
"an",
"error",
"if",
"|lhs|",
"is",
"not",
"less",
"than",
"or",
"equal",
"to",
"|rhs|."
] | def Le(lhs, rhs, message='', error=ValueError):
if lhs > rhs:
raise error('Expected (%s) <= (%s): %s' % (lhs, rhs, message)) | ['def', 'Le(lhs,', 'rhs,', "message='',", 'error=ValueError):', 'if', 'lhs', '>', 'rhs:', 'raise', "error('Expected", '(%s)', '<=', '(%s):', "%s'", '%', '(lhs,', 'rhs,', 'message))'] | 575,494 |
Deci-AI/data-gradients | questions.py | FixedOptionsQuestion.ask | ask | Pose the question with options and capture the user's choice. | [
"Pose",
"the",
"question",
"with",
"options",
"and",
"capture",
"the",
"user's",
"choice."
] | def ask(self, hint: str='') -> Any:
if is_notebook():
return ask_option_via_jupyter(question=self, hint=hint)
else:
return ask_option_via_stdin(question=self, hint=hint) | ['def', 'ask(self,', 'hint:', "str='')", '->', 'Any:', 'if', 'is_notebook():', 'return', 'ask_option_via_jupyter(question=self,', 'hint=hint)', 'else:', 'return', 'ask_option_via_stdin(question=self,', 'hint=hint)'] | 497,359 |
nicknochnack/RealTimeSignLanguageTFJS | coco_evaluation_all_frames_test.py | CocoEvaluationAllFramesTest.testGroundtruthAndDetectionsDisagreeOnAllFrames | testGroundtruthAndDetectionsDisagreeOnAllFrames | Tests that mAP is calculated on several different frame results. | [
"Tests",
"that",
"mAP",
"is",
"calculated",
"on",
"several",
"different",
"frame",
"results."
] | def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]
video_evaluator = coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)
video_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict=[{standar... | ['def', 'testGroundtruthAndDetectionsDisagreeOnAllFrames(self):', 'category_list', '=', "[{'id':", '0,', "'name':", "'dog'},", "{'id':", '1,', "'name':", "'cat'}]", 'video_evaluator', '=', 'coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)', "video_evaluator.add_single_ground_truth_image_info(image_id='... | 851,906 |
asavinov/intelligent-trading-bot | model_store.py | load_model_pair | load_model_pair | Load a pair consisting of scaler model (possibly null) and prediction model from two files. | [
"Load",
"a",
"pair",
"consisting",
"of",
"scaler",
"model",
"(possibly",
"null)",
"and",
"prediction",
"model",
"from",
"two",
"files."
] | def load_model_pair(model_path, score_column_name: str):
if not isinstance(model_path, Path):
model_path = Path(model_path)
model_path = model_path.absolute()
scaler_file_name = (model_path / score_column_name).with_suffix('.scaler')
scaler = load(scaler_file_name)
if score_column_name.endsw... | ['def', 'load_model_pair(model_path,', 'score_column_name:', 'str):', 'if', 'not', 'isinstance(model_path,', 'Path):', 'model_path', '=', 'Path(model_path)', 'model_path', '=', 'model_path.absolute()', 'scaler_file_name', '=', '(model_path', '/', "score_column_name).with_suffix('.scaler')", 'scaler', '=', 'load(scaler_... | 614,096 |
greydanus/mr_london | runtime.py | Context.get_exported | get_exported | Get a new dict with the exported variables. | [
"Get",
"a",
"new",
"dict",
"with",
"the",
"exported",
"variables."
] | def get_exported(self):
return dict(((k, self.vars[k]) for k in self.exported_vars)) | ['def', 'get_exported(self):', 'return', 'dict(((k,', 'self.vars[k])', 'for', 'k', 'in', 'self.exported_vars))'] | 262,433 |
enuguru/artificial_intelligence_and_machine_ | base.py | FBDialect.has_table | has_table | Return ``True`` if the given table exists, ignoring the `schema`. | [
"Return",
"``True``",
"if",
"the",
"given",
"table",
"exists,",
"ignoring",
"the",
"`schema`."
] | def has_table(self, connection, table_name, schema=None):
tblqry = '\n SELECT 1 AS has_table FROM rdb$database\n WHERE EXISTS (SELECT rdb$relation_name\n FROM rdb$relations\n WHERE rdb$relation_name=?)\n '
c = connection.execute(tblqry, [self.denorm... | ['def', 'has_table(self,', 'connection,', 'table_name,', 'schema=None):', 'tblqry', '=', "'\\n", 'SELECT', '1', 'AS', 'has_table', 'FROM', 'rdb$database\\n', 'WHERE', 'EXISTS', '(SELECT', 'rdb$relation_name\\n', 'FROM', 'rdb$relations\\n', 'WHERE', 'rdb$relation_name=?)\\n', "'", 'c', '=', 'connection.execute(tblqry,',... | 160,923 |
scottemmons/rvs | step.py | render_env | render_env | Helper function that provides special case for rendering D4RL kitchen envs. | [
"Helper",
"function",
"that",
"provides",
"special",
"case",
"for",
"rendering",
"D4RL",
"kitchen",
"envs."
] | def render_env(env: gym.Env, mode='human') -> Union[np.ndarray, None]:
if is_kitchen_env(env):
return kitchen_multitask_v0.KitchenTaskRelaxV1.render(env, mode=mode)
else:
return env.render(mode=mode) | ['def', 'render_env(env:', 'gym.Env,', "mode='human')", '->', 'Union[np.ndarray,', 'None]:', 'if', 'is_kitchen_env(env):', 'return', 'kitchen_multitask_v0.KitchenTaskRelaxV1.render(env,', 'mode=mode)', 'else:', 'return', 'env.render(mode=mode)'] | 326,997 |
RasaHQ/rasa | domain.py | Domain.input_state_map | input_state_map | Provide a mapping from state names to indices. | [
"Provide",
"a",
"mapping",
"from",
"state",
"names",
"to",
"indices."
] | def input_state_map(self) -> Dict[Text, int]:
return {f: i for (i, f) in enumerate(self.input_states)} | ['def', 'input_state_map(self)', '->', 'Dict[Text,', 'int]:', 'return', '{f:', 'i', 'for', '(i,', 'f)', 'in', 'enumerate(self.input_states)}'] | 837,415 |
flavioschneider/rl-transfer- | test_ppo.py | TestPPO.test_ppo_with_regularized_entropy | test_ppo_with_regularized_entropy | Test PPO with regularized entropy method. | [
"Test",
"PPO",
"with",
"regularized",
"entropy",
"method."
] | def test_ppo_with_regularized_entropy(self):
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec, policy=self.policy, baseline=self.baseline, sampler=self.sampler, discount=0.99, lr_clip_range=0.01, optimizer_args=dict(batch_size=32, max_optimization_epochs=10), sto... | ['def', 'test_ppo_with_regularized_entropy(self):', 'with', 'TFTrainer(snapshot_config,', 'sess=self.sess)', 'as', 'trainer:', 'algo', '=', 'PPO(env_spec=self.env.spec,', 'policy=self.policy,', 'baseline=self.baseline,', 'sampler=self.sampler,', 'discount=0.99,', 'lr_clip_range=0.01,', 'optimizer_args=dict(batch_size=3... | 861,754 |
kwakuTM/SegNet | Preprocess.py | rotateImages | rotateImages | Rotates multiple images by the given angles. | [
"Rotates",
"multiple",
"images",
"by",
"the",
"given",
"angles."
] | def rotateImages(arr, angles):
arr = [rotateImage(img, angle) for (img, angle) in zip(arr, angles)]
return arr | ['def', 'rotateImages(arr,', 'angles):', 'arr', '=', '[rotateImage(img,', 'angle)', 'for', '(img,', 'angle)', 'in', 'zip(arr,', 'angles)]', 'return', 'arr'] | 842,916 |
zackmcnulty/CSE_446-Machine_Learning | backend_wx.py | MenuButtonWx.updateButtonText | updateButtonText | Update the list of selected axes in the menu button. | [
"Update",
"the",
"list",
"of",
"selected",
"axes",
"in",
"the",
"menu",
"button."
] | def updateButtonText(self, lst):
self.SetLabel('Axes: ' + ','.join(('%d' % (e + 1) for e in lst))) | ['def', 'updateButtonText(self,', 'lst):', "self.SetLabel('Axes:", "'", '+', "','.join(('%d'", '%', '(e', '+', '1)', 'for', 'e', 'in', 'lst)))'] | 195,086 |
bm777/object_detection | mask_rcnn_heads.py | add_ResNet_roi_conv5_head_for_masks | add_ResNet_roi_conv5_head_for_masks | Add a ResNet "conv5" / "stage5" head for predicting masks. | [
"Add",
"a",
"ResNet",
"\"conv5\"",
"/",
"\"stage5\"",
"head",
"for",
"predicting",
"masks."
] | def add_ResNet_roi_conv5_head_for_masks(model, blob_in, dim_in, spatial_scale):
model.RoIFeatureTransform(blob_in, blob_out='_[mask]_pool5', blob_rois='mask_rois', method=cfg.MRCNN.ROI_XFORM_METHOD, resolution=cfg.MRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.MRCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_s... | ['def', 'add_ResNet_roi_conv5_head_for_masks(model,', 'blob_in,', 'dim_in,', 'spatial_scale):', 'model.RoIFeatureTransform(blob_in,', "blob_out='_[mask]_pool5',", "blob_rois='mask_rois',", 'method=cfg.MRCNN.ROI_XFORM_METHOD,', 'resolution=cfg.MRCNN.ROI_XFORM_RESOLUTION,', 'sampling_ratio=cfg.MRCNN.ROI_XFORM_SAMPLING_RA... | 772,787 |
TobyPDE/FRRN | architectures.py | FRRNBuilderBase.add_split | add_split | Adds a split to the network for the block-wise backprop algorithm. | [
"Adds",
"a",
"split",
"to",
"the",
"network",
"for",
"the",
"block-wise",
"backprop",
"algorithm."
] | def add_split(self, layers, nnet):
nnet.splits.append(layers)
self.block_counter += 1
self.module_counter = 0 | ['def', 'add_split(self,', 'layers,', 'nnet):', 'nnet.splits.append(layers)', 'self.block_counter', '+=', '1', 'self.module_counter', '=', '0'] | 564,641 |
lebrice/Sequoia | model.py | Model.output_head_loss | output_head_loss | Gets the Loss of the output head. | [
"Gets",
"the",
"Loss",
"of",
"the",
"output",
"head."
] | def output_head_loss(self, forward_pass: ForwardPass, actions: Actions, rewards: Rewards) -> Loss:
assert actions.device == self.device
return self.output_head.get_loss(forward_pass, actions=actions, rewards=rewards) | ['def', 'output_head_loss(self,', 'forward_pass:', 'ForwardPass,', 'actions:', 'Actions,', 'rewards:', 'Rewards)', '->', 'Loss:', 'assert', 'actions.device', '==', 'self.device', 'return', 'self.output_head.get_loss(forward_pass,', 'actions=actions,', 'rewards=rewards)'] | 344,322 |
microsoft/maro | azure_controller.py | AzureController.get_connection_string | get_connection_string | Get the connection string for a storage account. | [
"Get",
"the",
"connection",
"string",
"for",
"a",
"storage",
"account."
] | def get_connection_string(storage_account_name: str) -> str:
command = f'az storage account show-connection-string --name {storage_account_name}'
return_str = Subprocess.run(command=command)
return json.loads(return_str)['connectionString'] | ['def', 'get_connection_string(storage_account_name:', 'str)', '->', 'str:', 'command', '=', "f'az", 'storage', 'account', 'show-connection-string', '--name', "{storage_account_name}'", 'return_str', '=', 'Subprocess.run(command=command)', 'return', "json.loads(return_str)['connectionString']"] | 628,334 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | interval.py | IntervalArray.closed | closed | Whether the intervals are closed on the left-side, right-side, both or neither. | [
"Whether",
"the",
"intervals",
"are",
"closed",
"on",
"the",
"left-side,",
"right-side,",
"both",
"or",
"neither."
] | def closed(self):
return self._closed | ['def', 'closed(self):', 'return', 'self._closed'] | 452,808 |
netket/netket | common_lattices.py | Grid | Grid | Constructs a hypercubic lattice given its extent in all dimensions. | [
"Constructs",
"a",
"hypercubic",
"lattice",
"given",
"its",
"extent",
"in",
"all",
"dimensions."
] | def Grid(extent: Sequence[int], *, pbc: Union[bool, Sequence[bool]]=True, color_edges: bool=False, **kwargs) -> Lattice:
extent = np.asarray(extent, dtype=int)
ndim = len(extent)
if isinstance(pbc, bool):
pbc = [pbc] * ndim
if color_edges:
kwargs['custom_edges'] = [(0, 0, vec) for vec in... | ['def', 'Grid(extent:', 'Sequence[int],', '*,', 'pbc:', 'Union[bool,', 'Sequence[bool]]=True,', 'color_edges:', 'bool=False,', '**kwargs)', '->', 'Lattice:', 'extent', '=', 'np.asarray(extent,', 'dtype=int)', 'ndim', '=', 'len(extent)', 'if', 'isinstance(pbc,', 'bool):', 'pbc', '=', '[pbc]', '*', 'ndim', 'if', 'color_e... | 735,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.