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
keyonvafa/career-code
quantization_options.py
convert_yaml_to_tuple
convert_yaml_to_tuple
Converts a yaml dictionary with two keys: `key` and `value` into a two argument tuple of those values.
[ "Converts", "a", "yaml", "dictionary", "with", "two", "keys:", "`key`", "and", "`value`", "into", "a", "two", "argument", "tuple", "of", "those", "values." ]
def convert_yaml_to_tuple(yaml_dictionary): return (yaml_dictionary['key'], yaml_dictionary['value'])
['def', 'convert_yaml_to_tuple(yaml_dictionary):', 'return', "(yaml_dictionary['key'],", "yaml_dictionary['value'])"]
455,638
Ruturaj123/Flowchart-Detection
linalg_ops.py
self_adjoint_eigvals
self_adjoint_eigvals
Computes the eigenvalues of one or more self-adjoint matrices.
[ "Computes", "the", "eigenvalues", "of", "one", "or", "more", "self-adjoint", "matrices." ]
def self_adjoint_eigvals(tensor, name=None): (e, _) = gen_linalg_ops._self_adjoint_eig_v2(tensor, compute_v=False, name=name) return e
['def', 'self_adjoint_eigvals(tensor,', 'name=None):', '(e,', '_)', '=', 'gen_linalg_ops._self_adjoint_eig_v2(tensor,', 'compute_v=False,', 'name=name)', 'return', 'e']
605,929
thaines/helit
mask_stats.py
MaskStats.getPrecision
getPrecision
Given a frame number returns that framess precision.
[ "Given", "a", "frame", "number", "returns", "that", "framess", "precision." ]
def getPrecision(self, frame): con = self.confusion[frame] if con[0, 1] + con[1, 1] == 0: return 1.0 return float(con[1, 1]) / float(con[0, 1] + con[1, 1])
['def', 'getPrecision(self,', 'frame):', 'con', '=', 'self.confusion[frame]', 'if', 'con[0,', '1]', '+', 'con[1,', '1]', '==', '0:', 'return', '1.0', 'return', 'float(con[1,', '1])', '/', 'float(con[0,', '1]', '+', 'con[1,', '1])']
592,788
rudranil723/mini-main
__init__.py
posix
posix
Normalize paths using forward slash to work also on Windows.
[ "Normalize", "paths", "using", "forward", "slash", "to", "work", "also", "on", "Windows." ]
def posix(path): new_path = posixpath.join(*path.split(os.path.sep)) if path.startswith('/'): new_path = '/' + new_path elif path.startswith('\\\\'): new_path = '//' + new_path return new_path
['def', 'posix(path):', 'new_path', '=', 'posixpath.join(*path.split(os.path.sep))', 'if', "path.startswith('/'):", 'new_path', '=', "'/'", '+', 'new_path', 'elif', "path.startswith('\\\\\\\\'):", 'new_path', '=', "'//'", '+', 'new_path', 'return', 'new_path']
317,003
triaquae/triaquae
query.py
Query.change_aliases
change_aliases
Changes the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause.
[ "Changes", "the", "aliases", "in", "change_map", "(which", "maps", "old-alias", "->", "new-alias),", "relabelling", "any", "references", "to", "them", "in", "select", "columns", "and", "the", "where", "clause." ]
def change_aliases(self, change_map): assert set(change_map.keys()).intersection(set(change_map.values())) == set() self.where.relabel_aliases(change_map) self.having.relabel_aliases(change_map) for columns in [self.select, self.group_by or []]: for (pos, col) in enumerate(columns): ...
['def', 'change_aliases(self,', 'change_map):', 'assert', 'set(change_map.keys()).intersection(set(change_map.values()))', '==', 'set()', 'self.where.relabel_aliases(change_map)', 'self.having.relabel_aliases(change_map)', 'for', 'columns', 'in', '[self.select,', 'self.group_by', 'or', '[]]:', 'for', '(pos,', 'col)', '...
423,583
CosmiQ/solaris
geo.py
get_crs
get_crs
Get a coordinate reference system from any georegistered object.
[ "Get", "a", "coordinate", "reference", "system", "from", "any", "georegistered", "object." ]
def get_crs(obj): if isinstance(obj, gpd.GeoDataFrame): return _check_crs(obj.crs) elif isinstance(obj, rasterio.DatasetReader): return _check_crs(obj.crs) elif isinstance(obj, gdal.Dataset): return _check_crs(int(osr.SpatialReference(wkt=obj.GetProjection()).GetAttrValue('AUTHORITY'...
['def', 'get_crs(obj):', 'if', 'isinstance(obj,', 'gpd.GeoDataFrame):', 'return', '_check_crs(obj.crs)', 'elif', 'isinstance(obj,', 'rasterio.DatasetReader):', 'return', '_check_crs(obj.crs)', 'elif', 'isinstance(obj,', 'gdal.Dataset):', 'return', "_check_crs(int(osr.SpatialReference(wkt=obj.GetProjection()).GetAttrVal...
879,412
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
dragnn_model_saver_lib.py
clean_output_paths
clean_output_paths
Ensures that the output path is cleaned and ready to receive a model.
[ "Ensures", "that", "the", "output", "path", "is", "cleaned", "and", "ready", "to", "receive", "a", "model." ]
def clean_output_paths(stripped_path): export_directory = os.path.dirname(stripped_path) if not tf.gfile.Exists(export_directory): tf.logging.info('%s does not exist; creating it.' % export_directory) tf.gfile.MakeDirs(export_directory) if tf.gfile.Exists(stripped_path): tf.logging.i...
['def', 'clean_output_paths(stripped_path):', 'export_directory', '=', 'os.path.dirname(stripped_path)', 'if', 'not', 'tf.gfile.Exists(export_directory):', "tf.logging.info('%s", 'does', 'not', 'exist;', 'creating', "it.'", '%', 'export_directory)', 'tf.gfile.MakeDirs(export_directory)', 'if', 'tf.gfile.Exists(stripped...
111,021
rudranil723/mini-main
conftest.py
month_classes
month_classes
Fixture for month based datetime offsets available for a time series.
[ "Fixture", "for", "month", "based", "datetime", "offsets", "available", "for", "a", "time", "series." ]
def month_classes(request): return request.param
['def', 'month_classes(request):', 'return', 'request.param']
267,708
chainer/chainerrl
iqn.py
cosine_basis_functions
cosine_basis_functions
Cosine basis functions used to embed quantile thresholds.
[ "Cosine", "basis", "functions", "used", "to", "embed", "quantile", "thresholds." ]
def cosine_basis_functions(x, n_basis_functions=64): xp = chainer.cuda.get_array_module(x) i_pi = xp.arange(1, n_basis_functions + 1, dtype=xp.float32) * xp.pi embedding = xp.cos(x[..., None] * i_pi) assert embedding.shape == x.shape + (n_basis_functions,) return embedding
['def', 'cosine_basis_functions(x,', 'n_basis_functions=64):', 'xp', '=', 'chainer.cuda.get_array_module(x)', 'i_pi', '=', 'xp.arange(1,', 'n_basis_functions', '+', '1,', 'dtype=xp.float32)', '*', 'xp.pi', 'embedding', '=', 'xp.cos(x[...,', 'None]', '*', 'i_pi)', 'assert', 'embedding.shape', '==', 'x.shape', '+', '(n_b...
104,566
Qbanxiaoxu/NaturalLanguageProcessingExperiment
operator.py
rshift
rshift
Same as a >> b.
[ "Same", "as", "a", ">>", "b." ]
def rshift(a, b): return a >> b
['def', 'rshift(a,', 'b):', 'return', 'a', '>>', 'b']
801,553
thaines/helit
model.py
Sample.nllAllDocs
nllAllDocs
Returns the negative log likelihood of all the documents in the sample - a reasonable value to compare various samples with.
[ "Returns", "the", "negative", "log", "likelihood", "of", "all", "the", "documents", "in", "the", "sample", "-", "a", "reasonable", "value", "to", "compare", "various", "samples", "with." ]
def nllAllDocs(self): return sum(map(lambda d: d.getNLL(), self.doc))
['def', 'nllAllDocs(self):', 'return', 'sum(map(lambda', 'd:', 'd.getNLL(),', 'self.doc))']
591,456
GeekLiB/keras
tensorflow_backend.py
temporal_padding
temporal_padding
Pads the middle dimension of a 3D tensor with "padding" zeros left and right.
[ "Pads", "the", "middle", "dimension", "of", "a", "3D", "tensor", "with", "\"padding\"", "zeros", "left", "and", "right." ]
def temporal_padding(x, padding=1): pattern = [[0, 0], [padding, padding], [0, 0]] return tf.pad(x, pattern)
['def', 'temporal_padding(x,', 'padding=1):', 'pattern', '=', '[[0,', '0],', '[padding,', 'padding],', '[0,', '0]]', 'return', 'tf.pad(x,', 'pattern)']
247,792
google-research/scenic
nn_ops.py
space_to_depth
space_to_depth
Applies space to depth.
[ "Applies", "space", "to", "depth." ]
def space_to_depth(inputs, window_shape, strides=None, padding='VALID'): strides = strides or window_shape patched = extract_image_patches(lhs=inputs.astype(jnp.float64), rhs_shape=(1,) + window_shape + (1,), strides=(1,) + strides + (1,), padding=padding, rhs_dilation=(1,) * inputs.ndim, data_format='NHWC') ...
['def', 'space_to_depth(inputs,', 'window_shape,', 'strides=None,', "padding='VALID'):", 'strides', '=', 'strides', 'or', 'window_shape', 'patched', '=', 'extract_image_patches(lhs=inputs.astype(jnp.float64),', 'rhs_shape=(1,)', '+', 'window_shape', '+', '(1,),', 'strides=(1,)', '+', 'strides', '+', '(1,),', 'padding=p...
846,266
yoonc5536/computer_vision
canvas.py
Canvas.selectShapePoint
selectShapePoint
Select the first shape created which contains this point.
[ "Select", "the", "first", "shape", "created", "which", "contains", "this", "point." ]
def selectShapePoint(self, point): self.deSelectShape() if self.selectedVertex(): (index, shape) = (self.hVertex, self.hShape) shape.highlightVertex(index, shape.MOVE_VERTEX) self.selectShape(shape) return self.hVertex for shape in reversed(self.shapes): if self.isVis...
['def', 'selectShapePoint(self,', 'point):', 'self.deSelectShape()', 'if', 'self.selectedVertex():', '(index,', 'shape)', '=', '(self.hVertex,', 'self.hShape)', 'shape.highlightVertex(index,', 'shape.MOVE_VERTEX)', 'self.selectShape(shape)', 'return', 'self.hVertex', 'for', 'shape', 'in', 'reversed(self.shapes):', 'if'...
474,644
scottemmons/rvs
analyze_d4rl.py
compare_commands_to_demonstrator
compare_commands_to_demonstrator
Evaluate the policies and compare their performance to the demonstrations.
[ "Evaluate", "the", "policies", "and", "compare", "their", "performance", "to", "the", "demonstrations." ]
def compare_commands_to_demonstrator(out_directory: str, parameters: Dict[str, Union[int, float, str, bool]], loaded_policies: Iterable[policies.RvS], attribute_dicts: List[Dict[str, Union[int, float, str]]], env: offline_env.OfflineEnv, goals: Union[np.ndarray, List[np.ndarray]], goal_names: List[Union[str, int, float...
['def', 'compare_commands_to_demonstrator(out_directory:', 'str,', 'parameters:', 'Dict[str,', 'Union[int,', 'float,', 'str,', 'bool]],', 'loaded_policies:', 'Iterable[policies.RvS],', 'attribute_dicts:', 'List[Dict[str,', 'Union[int,', 'float,', 'str]]],', 'env:', 'offline_env.OfflineEnv,', 'goals:', 'Union[np.ndarray...
326,961
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
base_vae.py
NextFrameBaseVae.get_extra_loss
get_extra_loss
Losses in addition to the default modality losses.
[ "Losses", "in", "addition", "to", "the", "default", "modality", "losses." ]
def get_extra_loss(self, mean, std): beta = self.get_beta() kl_loss = common_layers.kl_divergence(mean, std) tf.summary.histogram('posterior_mean', mean) tf.summary.histogram('posterior_std', std) tf.summary.scalar('kl_raw', tf.reduce_mean(kl_loss)) if self.hparams.information_capacity > 0.0: ...
['def', 'get_extra_loss(self,', 'mean,', 'std):', 'beta', '=', 'self.get_beta()', 'kl_loss', '=', 'common_layers.kl_divergence(mean,', 'std)', "tf.summary.histogram('posterior_mean',", 'mean)', "tf.summary.histogram('posterior_std',", 'std)', "tf.summary.scalar('kl_raw',", 'tf.reduce_mean(kl_loss))', 'if', 'self.hparam...
965,936
twangnh/SimCal
eval.py
LVISEval.evaluate_img
evaluate_img
Perform evaluation for single category and image.
[ "Perform", "evaluation", "for", "single", "category", "and", "image." ]
def evaluate_img(self, img_id, cat_id, area_rng): (gt, dt) = self._get_gt_dt(img_id, cat_id) if len(gt) == 0 and len(dt) == 0: return None for g in gt: if g['ignore'] or (g['area'] < area_rng[0] or g['area'] > area_rng[1]): g['_ignore'] = 1 else: g['_ignore'] ...
['def', 'evaluate_img(self,', 'img_id,', 'cat_id,', 'area_rng):', '(gt,', 'dt)', '=', 'self._get_gt_dt(img_id,', 'cat_id)', 'if', 'len(gt)', '==', '0', 'and', 'len(dt)', '==', '0:', 'return', 'None', 'for', 'g', 'in', 'gt:', 'if', "g['ignore']", 'or', "(g['area']", '<', 'area_rng[0]', 'or', "g['area']", '>', 'area_rng[...
934,749
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
poplib.py
POP3.rset
rset
Unmark all messages marked for deletion.
[ "Unmark", "all", "messages", "marked", "for", "deletion." ]
def rset(self): return self._shortcmd('RSET')
['def', 'rset(self):', 'return', "self._shortcmd('RSET')"]
429,226
deepmind/bsuite
summary_analysis.py
plot_single_experiment
plot_single_experiment
Compare score for just one experiment.
[ "Compare", "score", "for", "just", "one", "experiment." ]
def plot_single_experiment(summary_df: pd.DataFrame, bsuite_env: str, sweep_vars: Optional[Sequence[str]]=None) -> Union[gg.ggplot, None]: if len(summary_df) == 0: print('WARNING: you have no bsuite summary data, please reload.') return env_df = summary_df[summary_df.bsuite_env == bsuite_env] ...
['def', 'plot_single_experiment(summary_df:', 'pd.DataFrame,', 'bsuite_env:', 'str,', 'sweep_vars:', 'Optional[Sequence[str]]=None)', '->', 'Union[gg.ggplot,', 'None]:', 'if', 'len(summary_df)', '==', '0:', "print('WARNING:", 'you', 'have', 'no', 'bsuite', 'summary', 'data,', 'please', "reload.')", 'return', 'env_df', ...
410,160
kubeflow/pipelines
test_trainer.py
test_training_success_with_custom_model_name
test_training_success_with_custom_model_name
Test for successful training with custom model name.
[ "Test", "for", "successful", "training", "with", "custom", "model", "name." ]
def test_training_success_with_custom_model_name(trainer_params): tmp_dir = tempfile.mkdtemp() trainer_params['module_file_args']['checkpoint_dir'] = tmp_dir trainer_params['module_file_args']['model_name'] = 'iris.pth' invoke_training(trainer_params=trainer_params) assert 'iris.pth' in os.listdir(t...
['def', 'test_training_success_with_custom_model_name(trainer_params):', 'tmp_dir', '=', 'tempfile.mkdtemp()', "trainer_params['module_file_args']['checkpoint_dir']", '=', 'tmp_dir', "trainer_params['module_file_args']['model_name']", '=', "'iris.pth'", 'invoke_training(trainer_params=trainer_params)', 'assert', "'iris...
779,667
ericyuegu/CS-3600-Intro-to-AI
DataInterface.py
getConnect4Dataset
getConnect4Dataset
Reads in and parses through the Connect4 dataset.
[ "Reads", "in", "and", "parses", "through", "the", "Connect4", "dataset." ]
def getConnect4Dataset(start=None, end=None): examples = [] attrValues = {} data = open('datasets/connect4-data.txt') cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] rows = ['1', '2', '3', '4', '5', '6'] labelValues = ['win', 'loss', 'draw'] for col in cols: for row in rows: a...
['def', 'getConnect4Dataset(start=None,', 'end=None):', 'examples', '=', '[]', 'attrValues', '=', '{}', 'data', '=', "open('datasets/connect4-data.txt')", 'cols', '=', "['a',", "'b',", "'c',", "'d',", "'e',", "'f',", "'g']", 'rows', '=', "['1',", "'2',", "'3',", "'4',", "'5',", "'6']", 'labelValues', '=', "['win',", "'...
139,693
xinge008/Cylinder3D
pc_dataset.py
SemKITTI_sk_multiscan.load_calib_poses
load_calib_poses
load calib poses and times.
[ "load", "calib", "poses", "and", "times." ]
def load_calib_poses(self): self.calibrations = [] self.times = [] self.poses = [] for seq in range(0, 22): seq_folder = join(self.data_path, str(seq).zfill(2)) self.calibrations.append(self.parse_calibration(join(seq_folder, 'calib.txt'))) self.times.append(np.loadtxt(join(seq_f...
['def', 'load_calib_poses(self):', 'self.calibrations', '=', '[]', 'self.times', '=', '[]', 'self.poses', '=', '[]', 'for', 'seq', 'in', 'range(0,', '22):', 'seq_folder', '=', 'join(self.data_path,', 'str(seq).zfill(2))', 'self.calibrations.append(self.parse_calibration(join(seq_folder,', "'calib.txt')))", 'self.times....
524,534
caiiiac/Machine-Learning-with-Python
backend_pdf.py
GraphicsContextPdf.paint
paint
Return the appropriate pdf operator to cause the path to be stroked, filled, or both.
[ "Return", "the", "appropriate", "pdf", "operator", "to", "cause", "the", "path", "to", "be", "stroked,", "filled,", "or", "both." ]
def paint(self): return Op.paint_path(self.fill(), self.stroke())
['def', 'paint(self):', 'return', 'Op.paint_path(self.fill(),', 'self.stroke())']
716,431
Farama-Foundation/Gymnasium
dict_info_to_list.py
DictInfoToListV0.reset
reset
Resets the environment using kwargs.
[ "Resets", "the", "environment", "using", "kwargs." ]
def reset(self, *, seed: int | list[int] | None=None, options: dict[str, Any] | None=None) -> tuple[ObsType, list[dict[str, Any]]]: (obs, infos) = self.env.reset(seed=seed, options=options) list_info = self._convert_info_to_list(infos) return (obs, list_info)
['def', 'reset(self,', '*,', 'seed:', 'int', '|', 'list[int]', '|', 'None=None,', 'options:', 'dict[str,', 'Any]', '|', 'None=None)', '->', 'tuple[ObsType,', 'list[dict[str,', 'Any]]]:', '(obs,', 'infos)', '=', 'self.env.reset(seed=seed,', 'options=options)', 'list_info', '=', 'self._convert_info_to_list(infos)', 'retu...
573,212
ldkong1205/LaserMix
single_stage.py
SingleStage3DDetector.predict
predict
Predict results from a batch of inputs and data samples with post- processing.
[ "Predict", "results", "from", "a", "batch", "of", "inputs", "and", "data", "samples", "with", "post-", "processing." ]
def predict(self, batch_inputs_dict: dict, batch_data_samples: SampleList, **kwargs) -> SampleList: x = self.extract_feat(batch_inputs_dict) results_list = self.bbox_head.predict(x, batch_data_samples, **kwargs) predictions = self.add_pred_to_datasample(batch_data_samples, results_list) return predictio...
['def', 'predict(self,', 'batch_inputs_dict:', 'dict,', 'batch_data_samples:', 'SampleList,', '**kwargs)', '->', 'SampleList:', 'x', '=', 'self.extract_feat(batch_inputs_dict)', 'results_list', '=', 'self.bbox_head.predict(x,', 'batch_data_samples,', '**kwargs)', 'predictions', '=', 'self.add_pred_to_datasample(batch_d...
624,117
TencentYoutuResearch/PedestrianDetection-NohNMS
logger.py
log_every_n
log_every_n
Log once per n times.
[ "Log", "once", "per", "n", "times." ]
def log_every_n(lvl, msg, n=1, *, name=None): (caller_module, key) = _find_caller() _LOG_COUNTER[key] += 1 if n == 1 or _LOG_COUNTER[key] % n == 1: logging.getLogger(name or caller_module).log(lvl, msg)
['def', 'log_every_n(lvl,', 'msg,', 'n=1,', '*,', 'name=None):', '(caller_module,', 'key)', '=', '_find_caller()', '_LOG_COUNTER[key]', '+=', '1', 'if', 'n', '==', '1', 'or', '_LOG_COUNTER[key]', '%', 'n', '==', '1:', 'logging.getLogger(name', 'or', 'caller_module).log(lvl,', 'msg)']
766,765
TrellixVulnTeam/Unsupervised_Learning_HFI7
util.py
Configurable.configured_class
configured_class
Returns the currently configured class.
[ "Returns", "the", "currently", "configured", "class." ]
def configured_class(cls): base = cls.configurable_base() if base.__dict__.get('_Configurable__impl_class') is None: base.__impl_class = cls.configurable_default() if base.__impl_class is not None: return base.__impl_class else: raise ValueError('configured class not found')
['def', 'configured_class(cls):', 'base', '=', 'cls.configurable_base()', 'if', "base.__dict__.get('_Configurable__impl_class')", 'is', 'None:', 'base.__impl_class', '=', 'cls.configurable_default()', 'if', 'base.__impl_class', 'is', 'not', 'None:', 'return', 'base.__impl_class', 'else:', 'raise', "ValueError('configur...
437,677
alinlab/ifseg
fairseq_dataset.py
FairseqDataset.supports_fetch_outside_dataloader
supports_fetch_outside_dataloader
Whether this dataset supports fetching outside the workers of the dataloader.
[ "Whether", "this", "dataset", "supports", "fetching", "outside", "the", "workers", "of", "the", "dataloader." ]
def supports_fetch_outside_dataloader(self): return True
['def', 'supports_fetch_outside_dataloader(self):', 'return', 'True']
598,005
bm777/object_detection
segms.py
mask_to_bbox
mask_to_bbox
Compute the tight bounding box of a binary mask.
[ "Compute", "the", "tight", "bounding", "box", "of", "a", "binary", "mask." ]
def mask_to_bbox(mask): xs = np.where(np.sum(mask, axis=0) > 0)[0] ys = np.where(np.sum(mask, axis=1) > 0)[0] if len(xs) == 0 or len(ys) == 0: return None x0 = xs[0] x1 = xs[-1] y0 = ys[0] y1 = ys[-1] return np.array((x0, y0, x1, y1), dtype=np.float32)
['def', 'mask_to_bbox(mask):', 'xs', '=', 'np.where(np.sum(mask,', 'axis=0)', '>', '0)[0]', 'ys', '=', 'np.where(np.sum(mask,', 'axis=1)', '>', '0)[0]', 'if', 'len(xs)', '==', '0', 'or', 'len(ys)', '==', '0:', 'return', 'None', 'x0', '=', 'xs[0]', 'x1', '=', 'xs[-1]', 'y0', '=', 'ys[0]', 'y1', '=', 'ys[-1]', 'return', ...
773,615
matsu0228/nlp-jp
screen.py
screen.scroll_screen_rows
scroll_screen_rows
Enable scrolling from row {start} to row {end}.
[ "Enable", "scrolling", "from", "row", "{start}", "to", "row", "{end}." ]
def scroll_screen_rows(self, rs, re): self.scroll_row_start = rs self.scroll_row_end = re self.scroll_constrain()
['def', 'scroll_screen_rows(self,', 'rs,', 're):', 'self.scroll_row_start', '=', 'rs', 'self.scroll_row_end', '=', 're', 'self.scroll_constrain()']
803,247
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
code_tasks.py
make_task
make_task
Make tasks with setting from paper.
[ "Make", "tasks", "with", "setting", "from", "paper." ]
def make_task(task_name, override_kwargs=None, max_code_length=100, require_correct_syntax=False, do_code_simplification=False, correct_bonus=2.0, code_length_bonus=1.0): logging.info('Making paper-config task.') n = 16 task_mapping = {'print-hello': (PrintTask, dict(base=27, fixed_string=[8, 5, 12, 12, 15]...
['def', 'make_task(task_name,', 'override_kwargs=None,', 'max_code_length=100,', 'require_correct_syntax=False,', 'do_code_simplification=False,', 'correct_bonus=2.0,', 'code_length_bonus=1.0):', "logging.info('Making", 'paper-config', "task.')", 'n', '=', '16', 'task_mapping', '=', "{'print-hello':", '(PrintTask,', 'd...
52,679
deepmind/dm_control
fruitfly_v2.py
mul_jac_t_vec
mul_jac_t_vec
Maps forces from constraint space to joint space.
[ "Maps", "forces", "from", "constraint", "space", "to", "joint", "space." ]
def mul_jac_t_vec(physics, efc): qfrc = np.zeros(physics.model.nv) mjlib.mj_mulJacTVec(physics.model.ptr, physics.data.ptr, qfrc, efc) return qfrc
['def', 'mul_jac_t_vec(physics,', 'efc):', 'qfrc', '=', 'np.zeros(physics.model.nv)', 'mjlib.mj_mulJacTVec(physics.model.ptr,', 'physics.data.ptr,', 'qfrc,', 'efc)', 'return', 'qfrc']
166,001
weimin17/Object-Detection_HelmetDetection
generate_samples.py
write_unmasked_log
write_unmasked_log
Helper function for logging evaluated sequences without mask.
[ "Helper", "function", "for", "logging", "evaluated", "sequences", "without", "mask." ]
def write_unmasked_log(log, id_to_word, sequence_eval): indices_arr = np.asarray(sequence_eval) samples = helper.convert_to_human_readable(id_to_word, indices_arr, FLAGS.batch_size) for sample in samples: log.write(sample + '\n') log.flush() return samples
['def', 'write_unmasked_log(log,', 'id_to_word,', 'sequence_eval):', 'indices_arr', '=', 'np.asarray(sequence_eval)', 'samples', '=', 'helper.convert_to_human_readable(id_to_word,', 'indices_arr,', 'FLAGS.batch_size)', 'for', 'sample', 'in', 'samples:', 'log.write(sample', '+', "'\\n')", 'log.flush()', 'return', 'sampl...
757,881
deepmind/bsuite
analysis.py
score
score
Output a single score for bandit experiment.
[ "Output", "a", "single", "score", "for", "bandit", "experiment." ]
def score(df: pd.DataFrame) -> float: return plotting.ave_regret_score(df, baseline_regret=BASE_REGRET, episode=sweep.NUM_EPISODES)
['def', 'score(df:', 'pd.DataFrame)', '->', 'float:', 'return', 'plotting.ave_regret_score(df,', 'baseline_regret=BASE_REGRET,', 'episode=sweep.NUM_EPISODES)']
410,162
Juniper/OpenClos
devicePlugin.py
L2DataCollector.persistAdditionalLinks
persistAdditionalLinks
lldp has this port but cabling plan does not have this port.
[ "lldp", "has", "this", "port", "but", "cabling", "plan", "does", "not", "have", "this", "port." ]
def persistAdditionalLinks(self, links): self._session.query(AdditionalLink).filter(AdditionalLink.device1 == self.device.name).delete() additionalLinks = [] for link in links: additionalLinks.append(AdditionalLink(self.device.name, link['port1'], link['device2'], link['port2'], 'error')) self._...
['def', 'persistAdditionalLinks(self,', 'links):', 'self._session.query(AdditionalLink).filter(AdditionalLink.device1', '==', 'self.device.name).delete()', 'additionalLinks', '=', '[]', 'for', 'link', 'in', 'links:', 'additionalLinks.append(AdditionalLink(self.device.name,', "link['port1'],", "link['device2'],", "link[...
274,970
rwth-i6/returnn
compile_tf_graph.py
RecStepByStepLayer.set_construction_state_in_loop
set_construction_state_in_loop
Set that we entered the body.
[ "Set", "that", "we", "entered", "the", "body." ]
def set_construction_state_in_loop(self): self.construction_state = self.ConstructionState.InLoop self._set_global_batch_dim(self.get_batch_dim_from_loop_state_var())
['def', 'set_construction_state_in_loop(self):', 'self.construction_state', '=', 'self.ConstructionState.InLoop', 'self._set_global_batch_dim(self.get_batch_dim_from_loop_state_var())']
348,470
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
datum_io.py
ArrayToDatum
ArrayToDatum
Converts numpy array to DatumProto.
[ "Converts", "numpy", "array", "to", "DatumProto." ]
def ArrayToDatum(arr): datum = datum_pb2.DatumProto() datum.float_list.value.extend(arr.astype(float).flat) datum.shape.dim.extend(arr.shape) return datum
['def', 'ArrayToDatum(arr):', 'datum', '=', 'datum_pb2.DatumProto()', 'datum.float_list.value.extend(arr.astype(float).flat)', 'datum.shape.dim.extend(arr.shape)', 'return', 'datum']
47,423
google-research/ssl_detection
gradproc.py
GradientProcessor.process
process
Process the symbolic gradients.
[ "Process", "the", "symbolic", "gradients." ]
def process(self, grads): if self._name_scope is None: with tfv1.name_scope(type(self).__name__) as scope: self._name_scope = scope return self._process(grads) else: with tfv1.name_scope(self._name_scope): return self._process(grads)
['def', 'process(self,', 'grads):', 'if', 'self._name_scope', 'is', 'None:', 'with', 'tfv1.name_scope(type(self).__name__)', 'as', 'scope:', 'self._name_scope', '=', 'scope', 'return', 'self._process(grads)', 'else:', 'with', 'tfv1.name_scope(self._name_scope):', 'return', 'self._process(grads)']
382,276
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.body_jntadr
body_jntadr
start addr of joints; -1: no joints (nbody x 1).
[ "start", "addr", "of", "joints;", "-1:", "no", "joints", "(nbody", "x", "1)." ]
def body_jntadr(self): return util.buf_to_npy(self._ptr.contents.body_jntadr, (self.nbody,))
['def', 'body_jntadr(self):', 'return', 'util.buf_to_npy(self._ptr.contents.body_jntadr,', '(self.nbody,))']
440,240
salesforce/CodeRL
modeling_swin.py
window_reverse
window_reverse
Merges windows to produce higher resolution features.
[ "Merges", "windows", "to", "produce", "higher", "resolution", "features." ]
def window_reverse(windows, window_size, height, width): batch_size = int(windows.shape[0] / (height * width / window_size / window_size)) windows = windows.view(batch_size, height // window_size, width // window_size, window_size, window_size, -1) windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().vi...
['def', 'window_reverse(windows,', 'window_size,', 'height,', 'width):', 'batch_size', '=', 'int(windows.shape[0]', '/', '(height', '*', 'width', '/', 'window_size', '/', 'window_size))', 'windows', '=', 'windows.view(batch_size,', 'height', '//', 'window_size,', 'width', '//', 'window_size,', 'window_size,', 'window_s...
495,203
sktime/sktime
base.py
HDDBaseResults.save
save
Save results object as master file.
[ "Save", "results", "object", "as", "master", "file." ]
def save(self): file = os.path.join(self.path, 'results.pickle') if not os.path.isfile(file): dump(self, file) else: results = load(file) self.strategy_names = list(set(self.strategy_names + results.strategy_names)) self.dataset_names = list(set(self.dataset_names + results.d...
['def', 'save(self):', 'file', '=', 'os.path.join(self.path,', "'results.pickle')", 'if', 'not', 'os.path.isfile(file):', 'dump(self,', 'file)', 'else:', 'results', '=', 'load(file)', 'self.strategy_names', '=', 'list(set(self.strategy_names', '+', 'results.strategy_names))', 'self.dataset_names', '=', 'list(set(self.d...
885,817
TrellixVulnTeam/Unsupervised_Learning_HFI7
conftest.py
reduction_func
reduction_func
yields the string names of all groupby reduction functions, one at a time.
[ "yields", "the", "string", "names", "of", "all", "groupby", "reduction", "functions,", "one", "at", "a", "time." ]
def reduction_func(request): return request.param
['def', 'reduction_func(request):', 'return', 'request.param']
453,741
triaquae/triaquae
tests.py
GeographyTest.test04_invalid_operators_functions
test04_invalid_operators_functions
Ensuring exceptions are raised for operators & functions invalid on geography fields.
[ "Ensuring", "exceptions", "are", "raised", "for", "operators", "&", "functions", "invalid", "on", "geography", "fields." ]
def test04_invalid_operators_functions(self): z = Zipcode.objects.get(code='77002') self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count) self.assertRaises(ValueError, City.objects.filter(point__contained=z.poly).count) htown = City.objects.get(name='Houston') self.assertRai...
['def', 'test04_invalid_operators_functions(self):', 'z', '=', "Zipcode.objects.get(code='77002')", 'self.assertRaises(ValueError,', 'City.objects.filter(point__within=z.poly).count)', 'self.assertRaises(ValueError,', 'City.objects.filter(point__contained=z.poly).count)', 'htown', '=', "City.objects.get(name='Houston')...
358,027
jbwang1997/CrossKD
normed_predictor.py
NormedLinear.forward
forward
Forward function for `NormedLinear`.
[ "Forward", "function", "for", "`NormedLinear`." ]
def forward(self, x: Tensor) -> Tensor: weight_ = self.weight / (self.weight.norm(dim=1, keepdim=True).pow(self.power) + self.eps) x_ = x / (x.norm(dim=1, keepdim=True).pow(self.power) + self.eps) x_ = x_ * self.tempearture return F.linear(x_, weight_, self.bias)
['def', 'forward(self,', 'x:', 'Tensor)', '->', 'Tensor:', 'weight_', '=', 'self.weight', '/', '(self.weight.norm(dim=1,', 'keepdim=True).pow(self.power)', '+', 'self.eps)', 'x_', '=', 'x', '/', '(x.norm(dim=1,', 'keepdim=True).pow(self.power)', '+', 'self.eps)', 'x_', '=', 'x_', '*', 'self.tempearture', 'return', 'F.l...
491,290
pramodiperera/virtual-keyboard
egg_info.py
FileList.include
include
Include files that match 'pattern'.
[ "Include", "files", "that", "match", "'pattern'." ]
def include(self, pattern): found = [f for f in glob(pattern) if not os.path.isdir(f)] self.extend(found) return bool(found)
['def', 'include(self,', 'pattern):', 'found', '=', '[f', 'for', 'f', 'in', 'glob(pattern)', 'if', 'not', 'os.path.isdir(f)]', 'self.extend(found)', 'return', 'bool(found)']
933,083
myothida/Supervised-Machine-Learning
ticker.py
LogLocator.subs
subs
Set the minor ticks for the log scaling every ``base**i*subs[j]``.
[ "Set", "the", "minor", "ticks", "for", "the", "log", "scaling", "every", "``base**i*subs[j]``." ]
def subs(self, subs): self._set_subs(subs)
['def', 'subs(self,', 'subs):', 'self._set_subs(subs)']
362,326
JiawangBian/SC-SfMLearner-Release
inverse_warp.py
pose_vec2mat
pose_vec2mat
Convert 6DoF parameters to transformation matrix.
[ "Convert", "6DoF", "parameters", "to", "transformation", "matrix." ]
def pose_vec2mat(vec, rotation_mode='euler'): translation = vec[:, :3].unsqueeze(-1) rot = vec[:, 3:] if rotation_mode == 'euler': rot_mat = euler2mat(rot) elif rotation_mode == 'quat': rot_mat = quat2mat(rot) transform_mat = torch.cat([rot_mat, translation], dim=2) return transf...
['def', 'pose_vec2mat(vec,', "rotation_mode='euler'):", 'translation', '=', 'vec[:,', ':3].unsqueeze(-1)', 'rot', '=', 'vec[:,', '3:]', 'if', 'rotation_mode', '==', "'euler':", 'rot_mat', '=', 'euler2mat(rot)', 'elif', 'rotation_mode', '==', "'quat':", 'rot_mat', '=', 'quat2mat(rot)', 'transform_mat', '=', 'torch.cat([...
329,299
43Carrig/recurrent_neural_networks_practice
train.py
gan_model
gan_model
Returns GAN model outputs and variables.
[ "Returns", "GAN", "model", "outputs", "and", "variables." ]
def gan_model(generator_fn, discriminator_fn, real_data, generator_inputs, generator_scope='Generator', discriminator_scope='Discriminator', check_shapes=True): with variable_scope.variable_scope(generator_scope) as gen_scope: generator_inputs = _convert_tensor_or_l_or_d(generator_inputs) generated_...
['def', 'gan_model(generator_fn,', 'discriminator_fn,', 'real_data,', 'generator_inputs,', "generator_scope='Generator',", "discriminator_scope='Discriminator',", 'check_shapes=True):', 'with', 'variable_scope.variable_scope(generator_scope)', 'as', 'gen_scope:', 'generator_inputs', '=', '_convert_tensor_or_l_or_d(gene...
313,150
deepmind/meltingpot
fruit_market.py
create_scene
create_scene
Create the scene object, a non-physical object to hold global logic.
[ "Create", "the", "scene", "object,", "a", "non-physical", "object", "to", "hold", "global", "logic." ]
def create_scene(): scene = {'name': 'scene', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'scene', 'stateConfigs': [{'state': 'scene'}]}}, {'component': 'Transform'}, {'component': 'TradeManager'}]} return scene
['def', 'create_scene():', 'scene', '=', "{'name':", "'scene',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'scene',", "'stateConfigs':", "[{'state':", "'scene'}]}},", "{'component':", "'Transform'},", "{'component':", "'TradeManager'}]}", 'return', 'scene']
285,370
deepmind/dm_control
attribute.py
BaseAsset.get_vfs_filename
get_vfs_filename
Returns the name of the asset file as registered in MuJoCo's VFS.
[ "Returns", "the", "name", "of", "the", "asset", "file", "as", "registered", "in", "MuJoCo's", "VFS." ]
def get_vfs_filename(self): hash_string = hashlib.sha1(util.to_binary_string(self.contents)).hexdigest() if self.prefix: prefix = self.prefix raw_length = len(prefix) + len(hash_string) + len(self.extension) + 1 if raw_length > constants.MAX_VFS_FILENAME_LENGTH: trim_amount =...
['def', 'get_vfs_filename(self):', 'hash_string', '=', 'hashlib.sha1(util.to_binary_string(self.contents)).hexdigest()', 'if', 'self.prefix:', 'prefix', '=', 'self.prefix', 'raw_length', '=', 'len(prefix)', '+', 'len(hash_string)', '+', 'len(self.extension)', '+', '1', 'if', 'raw_length', '>', 'constants.MAX_VFS_FILENA...
166,078
RasaHQ/rasa_core
utils.py
read_endpoint_config
read_endpoint_config
Read an endpoint configuration file from disk and extract one config.
[ "Read", "an", "endpoint", "configuration", "file", "from", "disk", "and", "extract", "one", "config." ]
def read_endpoint_config(filename: Text, endpoint_type: Text) -> Optional['EndpointConfig']: if not filename: return None content = read_yaml_file(filename) if endpoint_type in content: return EndpointConfig.from_dict(content[endpoint_type]) else: return None
['def', 'read_endpoint_config(filename:', 'Text,', 'endpoint_type:', 'Text)', '->', "Optional['EndpointConfig']:", 'if', 'not', 'filename:', 'return', 'None', 'content', '=', 'read_yaml_file(filename)', 'if', 'endpoint_type', 'in', 'content:', 'return', 'EndpointConfig.from_dict(content[endpoint_type])', 'else:', 'retu...
838,281
irdanish11/Seq2Seq-UrduChatBot
chatbot_model.py
ChatbotModel.predict_batch
predict_batch
Predict a batch of output sequences given a batch of input sequences.
[ "Predict", "a", "batch", "of", "output", "sequences", "given", "a", "batch", "of", "input", "sequences." ]
def predict_batch(self, inputs, input_sequence_length, max_output_sequence_length, beam_length_penalty_weight, sampling_temperature, log_summary=True): if self.mode != tf.contrib.learn.ModeKeys.INFER: raise ValueError('predict_batch can only be called when the model is initialized in infer mode.') fetch...
['def', 'predict_batch(self,', 'inputs,', 'input_sequence_length,', 'max_output_sequence_length,', 'beam_length_penalty_weight,', 'sampling_temperature,', 'log_summary=True):', 'if', 'self.mode', '!=', 'tf.contrib.learn.ModeKeys.INFER:', 'raise', "ValueError('predict_batch", 'can', 'only', 'be', 'called', 'when', 'the'...
876,458
Yuting-Gao/DisCo-pytorch
gluon_resnet.py
gluon_seresnext101_64x4d
gluon_seresnext101_64x4d
Constructs a SEResNeXt-101-64x4d model.
[ "Constructs", "a", "SEResNeXt-101-64x4d", "model." ]
def gluon_seresnext101_64x4d(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=64, base_width=4, block_args=dict(attn_layer=SEModule), **kwargs) return _create_resnet('gluon_seresnext101_64x4d', pretrained, **model_args)
['def', 'gluon_seresnext101_64x4d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', 'cardinality=64,', 'base_width=4,', 'block_args=dict(attn_layer=SEModule),', '**kwargs)', 'return', "_create_resnet('gluon_seresnext101_64x4d',", 'pretrained,', '**model_arg...
186,780
georghess/voxel-mae
kitti_dataset.py
KittiDataset.keep_arrays_by_name
keep_arrays_by_name
Keep useful ground truths by name.
[ "Keep", "useful", "ground", "truths", "by", "name." ]
def keep_arrays_by_name(self, gt_names, used_classes): inds = [i for (i, x) in enumerate(gt_names) if x in used_classes] inds = np.array(inds, dtype=np.int64) return inds
['def', 'keep_arrays_by_name(self,', 'gt_names,', 'used_classes):', 'inds', '=', '[i', 'for', '(i,', 'x)', 'in', 'enumerate(gt_names)', 'if', 'x', 'in', 'used_classes]', 'inds', '=', 'np.array(inds,', 'dtype=np.int64)', 'return', 'inds']
380,535
RasaHQ/rasa
test.py
EvaluationStore.merge_store
merge_store
Add the contents of other to self.
[ "Add", "the", "contents", "of", "other", "to", "self." ]
def merge_store(self, other: 'EvaluationStore') -> None: self.add_to_store(action_predictions=other.action_predictions, action_targets=other.action_targets, intent_predictions=other.intent_predictions, intent_targets=other.intent_targets, entity_predictions=other.entity_predictions, entity_targets=other.entity_targ...
['def', 'merge_store(self,', 'other:', "'EvaluationStore')", '->', 'None:', 'self.add_to_store(action_predictions=other.action_predictions,', 'action_targets=other.action_targets,', 'intent_predictions=other.intent_predictions,', 'intent_targets=other.intent_targets,', 'entity_predictions=other.entity_predictions,', 'e...
836,720
facebookresearch/CompilerGym
client_service_compiler_env.py
ClientServiceCompilerEnv.versions
versions
Get the version numbers from the compiler service.
[ "Get", "the", "version", "numbers", "from", "the", "compiler", "service." ]
def versions(self) -> GetVersionReply: return self.service(self.service.stub.GetVersion, GetVersionRequest())
['def', 'versions(self)', '->', 'GetVersionReply:', 'return', 'self.service(self.service.stub.GetVersion,', 'GetVersionRequest())']
125,505
ozamanan/Progressive-MuseGAN
metrics.py
get_drum_pattern
get_drum_pattern
Return the drum_pattern metric value.
[ "Return", "the", "drum_pattern", "metric", "value." ]
def get_drum_pattern(measure, drum_filter): padded = np.pad(measure, ((1, 0), (0, 0)), 'constant') measure = np.diff(padded, axis=0) measure[measure < 0] = 0 max_score = 0 for i in range(6): cdf = np.roll(drum_filter, i) score = np.sum(np.multiply(cdf, np.sum(measure, 1))) if...
['def', 'get_drum_pattern(measure,', 'drum_filter):', 'padded', '=', 'np.pad(measure,', '((1,', '0),', '(0,', '0)),', "'constant')", 'measure', '=', 'np.diff(padded,', 'axis=0)', 'measure[measure', '<', '0]', '=', '0', 'max_score', '=', '0', 'for', 'i', 'in', 'range(6):', 'cdf', '=', 'np.roll(drum_filter,', 'i)', 'scor...
817,526
UWARG/computer-vision-python
object_in_world.py
ObjectInWorld.create
create
Position in local coordinates.
[ "Position", "in", "local", "coordinates." ]
def create(cls, position_x: float, position_y: float, spherical_variance: float) -> 'tuple[bool, ObjectInWorld | None]': if spherical_variance < 0.0: return (False, None) return (True, ObjectInWorld(cls.__create_key, position_x, position_y, spherical_variance))
['def', 'create(cls,', 'position_x:', 'float,', 'position_y:', 'float,', 'spherical_variance:', 'float)', '->', "'tuple[bool,", 'ObjectInWorld', '|', "None]':", 'if', 'spherical_variance', '<', '0.0:', 'return', '(False,', 'None)', 'return', '(True,', 'ObjectInWorld(cls.__create_key,', 'position_x,', 'position_y,', 'sp...
470,452
myothida/Supervised-Machine-Learning
otConverters.py
BaseConverter.xmlRead
xmlRead
Read a value from XML.
[ "Read", "a", "value", "from", "XML." ]
def xmlRead(self, attrs, content, font): raise NotImplementedError(self)
['def', 'xmlRead(self,', 'attrs,', 'content,', 'font):', 'raise', 'NotImplementedError(self)']
361,237
thaines/helit
corpus.py
Corpus.getSeperateClusterConc
getSeperateClusterConc
True if each cluster has its own seperate concentration parameter, false if they are shared.
[ "True", "if", "each", "cluster", "has", "its", "own", "seperate", "concentration", "parameter,", "false", "if", "they", "are", "shared." ]
def getSeperateClusterConc(self): return self.seperateClusterConc
['def', 'getSeperateClusterConc(self):', 'return', 'self.seperateClusterConc']
591,357
deepmind/meltingpot
play_fruit_market.py
get_push_pull
get_push_pull
Sets shove to either -1, 0, or 1.
[ "Sets", "shove", "to", "either", "-1,", "0,", "or", "1." ]
def get_push_pull() -> int: if level_playing_utils.get_right_shift_pressed(): return 1 if level_playing_utils.get_left_control_pressed(): return -1 return 0
['def', 'get_push_pull()', '->', 'int:', 'if', 'level_playing_utils.get_right_shift_pressed():', 'return', '1', 'if', 'level_playing_utils.get_left_control_pressed():', 'return', '-1', 'return', '0']
285,884
intel/neural-compressor
logger.py
log
log
Output log with the level as a parameter.
[ "Output", "log", "with", "the", "level", "as", "a", "parameter." ]
def log(level, msg, *args, **kwargs): if isinstance(msg, dict): for (_, line) in enumerate(_pretty_dict(msg).split('\n')): Logger().get_logger().log(level, line, *args, **kwargs) else: Logger().get_logger().log(level, msg, *args, **kwargs)
['def', 'log(level,', 'msg,', '*args,', '**kwargs):', 'if', 'isinstance(msg,', 'dict):', 'for', '(_,', 'line)', 'in', "enumerate(_pretty_dict(msg).split('\\n')):", 'Logger().get_logger().log(level,', 'line,', '*args,', '**kwargs)', 'else:', 'Logger().get_logger().log(level,', 'msg,', '*args,', '**kwargs)']
721,852
tobegit3hub/deep_image_model
monitors.py
ValidationMonitor.best_step
best_step
Returns the step at which the best early stopping metric was found.
[ "Returns", "the", "step", "at", "which", "the", "best", "early", "stopping", "metric", "was", "found." ]
def best_step(self): return self._best_value_step
['def', 'best_step(self):', 'return', 'self._best_value_step']
181,583
ryu-ed/SpaceInvaders_Ros
transform_test.py
TransformModuleTest.test_average_surfaces__subclassed_destination_surface
test_average_surfaces__subclassed_destination_surface
Ensure average_surfaces accepts a destination subclassed surface.
[ "Ensure", "average_surfaces", "accepts", "a", "destination", "subclassed", "surface." ]
def test_average_surfaces__subclassed_destination_surface(self): expected_size = (13, 27) expected_flags = 0 expected_depth = 32 expected_color = (15, 15, 15, 255) surfaces = [] for color in ((10, 10, 20), (20, 20, 10), (30, 30, 30)): s = test_utils.SurfaceSubclass(expected_size, expecte...
['def', 'test_average_surfaces__subclassed_destination_surface(self):', 'expected_size', '=', '(13,', '27)', 'expected_flags', '=', '0', 'expected_depth', '=', '32', 'expected_color', '=', '(15,', '15,', '15,', '255)', 'surfaces', '=', '[]', 'for', 'color', 'in', '((10,', '10,', '20),', '(20,', '20,', '10),', '(30,', '...
369,207
betarixm/CSED342
graderUtil.py
Grader.addManualPart
addManualPart
Add stub for a part to be manually graded.
[ "Add", "stub", "for", "a", "part", "to", "be", "manually", "graded." ]
def addManualPart(self, name, maxPoints, extraCredit=False, description=''): if not self.isSelected(name): return part = Part(name, None, maxPoints, None, extraCredit, description) self.manualParts.append(part)
['def', 'addManualPart(self,', 'name,', 'maxPoints,', 'extraCredit=False,', "description=''):", 'if', 'not', 'self.isSelected(name):', 'return', 'part', '=', 'Part(name,', 'None,', 'maxPoints,', 'None,', 'extraCredit,', 'description)', 'self.manualParts.append(part)']
193,691
AI-ON/Few-Shot-Music-Generation
base_model.py
BaseModel.sample
sample
Sample a sequence of size num conditioned on support_set.
[ "Sample", "a", "sequence", "of", "size", "num", "conditioned", "on", "support_set." ]
def sample(self, support_set, num): raise NotImplementedError()
['def', 'sample(self,', 'support_set,', 'num):', 'raise', 'NotImplementedError()']
179,927
tensorflow/quantum
cirq_ops_test.py
CirqSimulateStateTest.test_get_cirq_state_op
test_get_cirq_state_op
Input check the wrapper for the cirq state op.
[ "Input", "check", "the", "wrapper", "for", "the", "cirq", "state", "op." ]
def test_get_cirq_state_op(self): with self.assertRaisesRegex(TypeError, 'simulator must inherit cirq.SimulatesFinalState.'): cirq_ops._get_cirq_simulate_state('junk') cirq_ops._get_cirq_simulate_state() cirq_ops._get_cirq_simulate_state(cirq.Simulator()) cirq_ops._get_cirq_simulate_state(cirq.D...
['def', 'test_get_cirq_state_op(self):', 'with', 'self.assertRaisesRegex(TypeError,', "'simulator", 'must', 'inherit', "cirq.SimulatesFinalState.'):", "cirq_ops._get_cirq_simulate_state('junk')", 'cirq_ops._get_cirq_simulate_state()', 'cirq_ops._get_cirq_simulate_state(cirq.Simulator())', 'cirq_ops._get_cirq_simulate_s...
834,657
sek788432/Waymo-2D-Object-Detection
video_classification.py
video_classification_kinetics700
video_classification_kinetics700
Video classification on Kinectics 700 with resnet.
[ "Video", "classification", "on", "Kinectics", "700", "with", "resnet." ]
def video_classification_kinetics700() -> cfg.ExperimentConfig: train_dataset = kinetics700(is_training=True) validation_dataset = kinetics700(is_training=False) task = VideoClassificationTask(model=VideoClassificationModel(backbone=backbones_3d.Backbone3D(type='resnet_3d', resnet_3d=backbones_3d.ResNet3D50...
['def', 'video_classification_kinetics700()', '->', 'cfg.ExperimentConfig:', 'train_dataset', '=', 'kinetics700(is_training=True)', 'validation_dataset', '=', 'kinetics700(is_training=False)', 'task', '=', "VideoClassificationTask(model=VideoClassificationModel(backbone=backbones_3d.Backbone3D(type='resnet_3d',", 'resn...
973,040
farazBhatti/Human-Body-Measurements-using--
smpl_to_tfrecords.py
convert_to_example
convert_to_example
Build an Example proto for an image example.
[ "Build", "an", "Example", "proto", "for", "an", "image", "example." ]
def convert_to_example(pose, shape=None): if shape is None: example = tf.train.Example(features=tf.train.Features(feature={'pose': float_feature(pose.astype(np.float))})) else: example = tf.train.Example(features=tf.train.Features(feature={'pose': float_feature(pose.astype(np.float)), 'shape': f...
['def', 'convert_to_example(pose,', 'shape=None):', 'if', 'shape', 'is', 'None:', 'example', '=', "tf.train.Example(features=tf.train.Features(feature={'pose':", 'float_feature(pose.astype(np.float))}))', 'else:', 'example', '=', "tf.train.Example(features=tf.train.Features(feature={'pose':", 'float_feature(pose.astype...
571,106
jay-johnson/network-pipeline
icmp_send_msg.py
send_one_ping
send_one_ping
Send one ping to the given >destIP<.
[ "Send", "one", "ping", "to", "the", "given", ">destIP<." ]
def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size): myChecksum = 0 header = struct.pack('!BBHHH', ICMP_ECHO, 0, myChecksum, myID, mySeqNumber) padBytes = [] startVal = 66 if sys.version[:1] == '2': bytes = struct.calcsize('d') data = (packet_size - 8 - bytes) * 'Q' ...
['def', 'send_one_ping(mySocket,', 'destIP,', 'myID,', 'mySeqNumber,', 'packet_size):', 'myChecksum', '=', '0', 'header', '=', "struct.pack('!BBHHH',", 'ICMP_ECHO,', '0,', 'myChecksum,', 'myID,', 'mySeqNumber)', 'padBytes', '=', '[]', 'startVal', '=', '66', 'if', 'sys.version[:1]', '==', "'2':", 'bytes', '=', "struct.c...
736,385
eric-haibin-lin/nlp-notebooks
create_pretraining_data.py
write_to_files_np
write_to_files_np
Write to numpy files from `TrainingInstance`s.
[ "Write", "to", "numpy", "files", "from", "`TrainingInstance`s." ]
def write_to_files_np(features, tokenizer, max_seq_length, max_predictions_per_seq, output_files): next_sentence_labels = [] valid_lengths = [] assert len(output_files) == 1, 'numpy format only support single output file' output_file = output_files[0] (input_ids, segment_ids, masked_lm_positions, ma...
['def', 'write_to_files_np(features,', 'tokenizer,', 'max_seq_length,', 'max_predictions_per_seq,', 'output_files):', 'next_sentence_labels', '=', '[]', 'valid_lengths', '=', '[]', 'assert', 'len(output_files)', '==', '1,', "'numpy", 'format', 'only', 'support', 'single', 'output', "file'", 'output_file', '=', 'output_...
730,850
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vgsl_model.py
InitNetwork
InitNetwork
Constructs a python tensor flow model defined by model_spec.
[ "Constructs", "a", "python", "tensor", "flow", "model", "defined", "by", "model_spec." ]
def InitNetwork(input_pattern, model_spec, mode='eval', initial_learning_rate=5e-05, final_learning_rate=5e-05, halflife=1600000, optimizer_type='Adam', num_preprocess_threads=1, reader=None): model = VGSLImageModel(mode, model_spec, initial_learning_rate, final_learning_rate, halflife) left_bracket = model_spe...
['def', 'InitNetwork(input_pattern,', 'model_spec,', "mode='eval',", 'initial_learning_rate=5e-05,', 'final_learning_rate=5e-05,', 'halflife=1600000,', "optimizer_type='Adam',", 'num_preprocess_threads=1,', 'reader=None):', 'model', '=', 'VGSLImageModel(mode,', 'model_spec,', 'initial_learning_rate,', 'final_learning_r...
27,840
rouge8/20questions
http.py
profiler
profiler
Outputs basic profiling information at the bottom of each response.
[ "Outputs", "basic", "profiling", "information", "at", "the", "bottom", "of", "each", "response." ]
def profiler(app): from utils import profile def profile_internal(e, o): (out, result) = profile(app)(e, o) return list(out) + ['<pre>' + net.websafe(result) + '</pre>'] return profile_internal
['def', 'profiler(app):', 'from', 'utils', 'import', 'profile', 'def', 'profile_internal(e,', 'o):', '(out,', 'result)', '=', 'profile(app)(e,', 'o)', 'return', 'list(out)', '+', "['<pre>'", '+', 'net.websafe(result)', '+', "'</pre>']", 'return', 'profile_internal']
4,410
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
binary_log_likelihood
binary_log_likelihood
Computes binary log likelihood.
[ "Computes", "binary", "log", "likelihood." ]
def binary_log_likelihood(y, log_y_hat): return tf.reduce_sum(y * -softplus(-log_y_hat) + (1 - y) * (-log_y_hat - softplus(-log_y_hat)), 1)
['def', 'binary_log_likelihood(y,', 'log_y_hat):', 'return', 'tf.reduce_sum(y', '*', '-softplus(-log_y_hat)', '+', '(1', '-', 'y)', '*', '(-log_y_hat', '-', 'softplus(-log_y_hat)),', '1)']
26,709
OliverKillane/NuNet-Designer
NuNetLibrary.py
ActivationFunctions.expolinearunit
expolinearunit
Expolinearunit (exponential linear unit) activation function.
[ "Expolinearunit", "(exponential", "linear", "unit)", "activation", "function." ]
def expolinearunit(value: float, constant: float=0) -> FuncReturn: if value > 0: return FuncReturn(result=value, derivative=1) else: return FuncReturn(result=constant * (e ** value - 1), derivative=constant * e ** value)
['def', 'expolinearunit(value:', 'float,', 'constant:', 'float=0)', '->', 'FuncReturn:', 'if', 'value', '>', '0:', 'return', 'FuncReturn(result=value,', 'derivative=1)', 'else:', 'return', 'FuncReturn(result=constant', '*', '(e', '**', 'value', '-', '1),', 'derivative=constant', '*', 'e', '**', 'value)']
730,491
fajarzuhrihadiyanto/artificial-intelligence
testutils.py
assert_mask_equal
assert_mask_equal
Asserts the equality of two masks.
[ "Asserts", "the", "equality", "of", "two", "masks." ]
def assert_mask_equal(m1, m2, err_msg=''): if m1 is nomask: assert_(m2 is nomask) if m2 is nomask: assert_(m1 is nomask) assert_array_equal(m1, m2, err_msg=err_msg)
['def', 'assert_mask_equal(m1,', 'm2,', "err_msg=''):", 'if', 'm1', 'is', 'nomask:', 'assert_(m2', 'is', 'nomask)', 'if', 'm2', 'is', 'nomask:', 'assert_(m1', 'is', 'nomask)', 'assert_array_equal(m1,', 'm2,', 'err_msg=err_msg)']
172,478
microsoft/maro
abs_core.py
AbsEnv.summary
summary
dict: Summary about current simulator, may include node details, and mappings.
[ "dict:", "Summary", "about", "current", "simulator,", "may", "include", "node", "details,", "and", "mappings." ]
def summary(self) -> dict: raise NotImplementedError
['def', 'summary(self)', '->', 'dict:', 'raise', 'NotImplementedError']
628,583
yahoo/Prototrain
eval.py
compute_features
compute_features
Calculate all features for the index set (or for query set if query_set).
[ "Calculate", "all", "features", "for", "the", "index", "set", "(or", "for", "query", "set", "if", "query_set)." ]
def compute_features(model, datasets, checkpoint_dir, weights_load_path, feature_key, dataset_key='retrieval_index'): iterator = datasets[dataset_key].make_one_shot_iterator() inputs = iterator.get_next(name='index_set_iterator') mdict = model.build(inputs) init_op = tf.global_variables_initializer() ...
['def', 'compute_features(model,', 'datasets,', 'checkpoint_dir,', 'weights_load_path,', 'feature_key,', "dataset_key='retrieval_index'):", 'iterator', '=', 'datasets[dataset_key].make_one_shot_iterator()', 'inputs', '=', "iterator.get_next(name='index_set_iterator')", 'mdict', '=', 'model.build(inputs)', 'init_op', '=...
818,089
Ruturaj123/Flowchart-Detection
decode_jpeg_op_test.py
DecodeJpegBenchmark.benchmarkDecodeJpegMedium
benchmarkDecodeJpegMedium
Evaluate single DecodeImageOp for medium size image.
[ "Evaluate", "single", "DecodeImageOp", "for", "medium", "size", "image." ]
def benchmarkDecodeJpegMedium(self): parallelism = 1 num_iters = 10 for parallelism in [1, 10, 100]: duration = self._evalDecodeJpeg('medium.jpg', parallelism, num_iters) self.report_benchmark(name='decode_jpeg_medium_p%d' % parallelism, iters=num_iters, wall_time=duration)
['def', 'benchmarkDecodeJpegMedium(self):', 'parallelism', '=', '1', 'num_iters', '=', '10', 'for', 'parallelism', 'in', '[1,', '10,', '100]:', 'duration', '=', "self._evalDecodeJpeg('medium.jpg',", 'parallelism,', 'num_iters)', "self.report_benchmark(name='decode_jpeg_medium_p%d'", '%', 'parallelism,', 'iters=num_iter...
605,602
sshleifer/object_detection_kitti
prediction_model.py
scheduled_sample
scheduled_sample
Sample batch with specified mix of ground truth and generated data points.
[ "Sample", "batch", "with", "specified", "mix", "of", "ground", "truth", "and", "generated", "data", "points." ]
def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(gr...
['def', 'scheduled_sample(ground_truth_x,', 'generated_x,', 'batch_size,', 'num_ground_truth):', 'idx', '=', 'tf.random_shuffle(tf.range(int(batch_size)))', 'ground_truth_idx', '=', 'tf.gather(idx,', 'tf.range(num_ground_truth))', 'generated_idx', '=', 'tf.gather(idx,', 'tf.range(num_ground_truth,', 'int(batch_size)))'...
795,874
rudranil723/mini-main
text.py
Text.blank_copy
blank_copy
Return a new Text instance with copied meta data (but not the string or spans).
[ "Return", "a", "new", "Text", "instance", "with", "copied", "meta", "data", "(but", "not", "the", "string", "or", "spans)." ]
def blank_copy(self, plain: str='') -> 'Text': copy_self = Text(plain, style=self.style, justify=self.justify, overflow=self.overflow, no_wrap=self.no_wrap, end=self.end, tab_size=self.tab_size) return copy_self
['def', 'blank_copy(self,', 'plain:', "str='')", '->', "'Text':", 'copy_self', '=', 'Text(plain,', 'style=self.style,', 'justify=self.justify,', 'overflow=self.overflow,', 'no_wrap=self.no_wrap,', 'end=self.end,', 'tab_size=self.tab_size)', 'return', 'copy_self']
268,972
matsu0228/nlp-jp
layer2.py
TableGenerator.consumed_units
consumed_units
Returns a float representing the ConsumedCapacityUnits accumulated.
[ "Returns", "a", "float", "representing", "the", "ConsumedCapacityUnits", "accumulated." ]
def consumed_units(self): self.response return self._consumed_units
['def', 'consumed_units(self):', 'self.response', 'return', 'self._consumed_units']
784,259
dornik/reagent
buffer.py
discounted
discounted
Computes the discounted sum as used for the return in RL.
[ "Computes", "the", "discounted", "sum", "as", "used", "for", "the", "return", "in", "RL." ]
def discounted(vals, gamma=0.99): G = 0 discounted = torch.zeros_like(vals) for i in np.arange(vals.shape[-1] - 1, -1, -1): G = vals[..., i] + gamma * G discounted[..., i] = G return discounted
['def', 'discounted(vals,', 'gamma=0.99):', 'G', '=', '0', 'discounted', '=', 'torch.zeros_like(vals)', 'for', 'i', 'in', 'np.arange(vals.shape[-1]', '-', '1,', '-1,', '-1):', 'G', '=', 'vals[...,', 'i]', '+', 'gamma', '*', 'G', 'discounted[...,', 'i]', '=', 'G', 'return', 'discounted']
849,255
tonybeltramelli/Graphics-And-Vision
CamerasParameters.py
CamerasParameters.F
F
Get the fundamental matrix.
[ "Get", "the", "fundamental", "matrix." ]
def F(self): return self.__f
['def', 'F(self):', 'return', 'self.__f']
580,606
keras-team/keras-nlp
basic_usage_test.py
BasicUsageTest.test_quick_start
test_quick_start
This matches the quick start example in our base README.
[ "This", "matches", "the", "quick", "start", "example", "in", "our", "base", "README." ]
def test_quick_start(self, jit_compile): vocab = ['[UNK]', 'the', 'qu', '##ick', 'br', '##own', 'fox', '.'] sentences = ['The quick brown fox jumped.', 'The fox slept.'] tokenizer = keras_nlp.tokenizers.WordPieceTokenizer(vocabulary=vocab, sequence_length=10) (x, y) = (tokenizer(sentences), tf.constant(...
['def', 'test_quick_start(self,', 'jit_compile):', 'vocab', '=', "['[UNK]',", "'the',", "'qu',", "'##ick',", "'br',", "'##own',", "'fox',", "'.']", 'sentences', '=', "['The", 'quick', 'brown', 'fox', "jumped.',", "'The", 'fox', "slept.']", 'tokenizer', '=', 'keras_nlp.tokenizers.WordPieceTokenizer(vocabulary=vocab,', '...
595,605
TrellixVulnTeam/Unsupervised_Learning_HFI7
style_transformation.py
merge_style_transformations
merge_style_transformations
Merge multiple transformations together.
[ "Merge", "multiple", "transformations", "together." ]
def merge_style_transformations(style_transformations: Sequence[StyleTransformation]) -> StyleTransformation: return _MergedStyleTransformation(style_transformations)
['def', 'merge_style_transformations(style_transformations:', 'Sequence[StyleTransformation])', '->', 'StyleTransformation:', 'return', '_MergedStyleTransformation(style_transformations)']
435,490
TrellixVulnTeam/Unsupervised_Learning_HFI7
conftest.py
all_numeric_reductions
all_numeric_reductions
Fixture for numeric reduction names.
[ "Fixture", "for", "numeric", "reduction", "names." ]
def all_numeric_reductions(request): return request.param
['def', 'all_numeric_reductions(request):', 'return', 'request.param']
452,431
Eric3911/OpenAGI
load.py
get_audios
get_audios
List all wav and aif files recursively under the path folder.
[ "List", "all", "wav", "and", "aif", "files", "recursively", "under", "the", "path", "folder." ]
def get_audios(path): supported_formats = ['.wav', '.mp3', '.ogg', '.flac', '.m4a'] return [item for sublist in [[os.path.join(dir, file) for file in files] for (dir, _, files) in list(os.walk(path))] for item in sublist if os.path.splitext(item)[1] in supported_formats]
['def', 'get_audios(path):', 'supported_formats', '=', "['.wav',", "'.mp3',", "'.ogg',", "'.flac',", "'.m4a']", 'return', '[item', 'for', 'sublist', 'in', '[[os.path.join(dir,', 'file)', 'for', 'file', 'in', 'files]', 'for', '(dir,', '_,', 'files)', 'in', 'list(os.walk(path))]', 'for', 'item', 'in', 'sublist', 'if', 'o...
250,992
ryu-ed/SpaceInvaders_Ros
math2html.py
MacroFunction.addfilter
addfilter
Add a filter for the given parameter number and parameter value.
[ "Add", "a", "filter", "for", "the", "given", "parameter", "number", "and", "parameter", "value." ]
def addfilter(self, index, value): original = '#' + unicode(index + 1) value = ''.join(self.values[0].gethtml()) self.output.addfilter(original, value)
['def', 'addfilter(self,', 'index,', 'value):', 'original', '=', "'#'", '+', 'unicode(index', '+', '1)', 'value', '=', "''.join(self.values[0].gethtml())", 'self.output.addfilter(original,', 'value)']
395,389
deepmind/bsuite
analysis.py
plot_seeds
plot_seeds
Plot the returns through time individually by run.
[ "Plot", "the", "returns", "through", "time", "individually", "by", "run." ]
def plot_seeds(df_in: pd.DataFrame, sweep_vars: Optional[Sequence[str]]=None, colour_var: Optional[str]=None) -> gg.ggplot: df = df_in.copy() df['average_return'] = df.raw_return.diff() / df.episode.diff() p = plotting.plot_individual_returns(df_in=df, max_episode=NUM_EPISODES, return_column='average_return...
['def', 'plot_seeds(df_in:', 'pd.DataFrame,', 'sweep_vars:', 'Optional[Sequence[str]]=None,', 'colour_var:', 'Optional[str]=None)', '->', 'gg.ggplot:', 'df', '=', 'df_in.copy()', "df['average_return']", '=', 'df.raw_return.diff()', '/', 'df.episode.diff()', 'p', '=', 'plotting.plot_individual_returns(df_in=df,', 'max_e...
410,176
EducationalTestingService/skll
test_classification.py
TestClassification.test_xval_float_classes_as_strings
test_xval_float_classes_as_strings
Test that classification with float labels encoded as strings works.
[ "Test", "that", "classification", "with", "float", "labels", "encoded", "as", "strings", "works." ]
def test_xval_float_classes_as_strings(self): float_class_fs = self.make_float_class_data(labels_as_strings=True) prediction_prefix = output_dir / 'float_class' learner = Learner('LogisticRegression') learner.cross_validate(float_class_fs, grid_search=True, grid_objective='accuracy', prediction_prefix=p...
['def', 'test_xval_float_classes_as_strings(self):', 'float_class_fs', '=', 'self.make_float_class_data(labels_as_strings=True)', 'prediction_prefix', '=', 'output_dir', '/', "'float_class'", 'learner', '=', "Learner('LogisticRegression')", 'learner.cross_validate(float_class_fs,', 'grid_search=True,', "grid_objective=...
885,038
AranGarcia/ArtificialQuest
world1renderer.py
GameMap.getselected
getselected
Returns the tile that was clicked and now has the cursor tile upon it.
[ "Returns", "the", "tile", "that", "was", "clicked", "and", "now", "has", "the", "cursor", "tile", "upon", "it." ]
def getselected(self): if self.selectedtile: x = self.selectedtile[0] y = self.selectedtile[1] return self.gamemap.matrix[y][x]
['def', 'getselected(self):', 'if', 'self.selectedtile:', 'x', '=', 'self.selectedtile[0]', 'y', '=', 'self.selectedtile[1]', 'return', 'self.gamemap.matrix[y][x]']
70,460
matsu0228/nlp-jp
parser.py
Parser.fail_eof
fail_eof
Like fail_unknown_tag but for end of template situations.
[ "Like", "fail_unknown_tag", "but", "for", "end", "of", "template", "situations." ]
def fail_eof(self, end_tokens=None, lineno=None): stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
['def', 'fail_eof(self,', 'end_tokens=None,', 'lineno=None):', 'stack', '=', 'list(self._end_token_stack)', 'if', 'end_tokens', 'is', 'not', 'None:', 'stack.append(end_tokens)', 'return', 'self._fail_ut_eof(None,', 'stack,', 'lineno)']
787,928
famura/SimuRLacra
base.py
Env.dt
dt
Get the time step size.
[ "Get", "the", "time", "step", "size." ]
def dt(self) -> float: return self._dt
['def', 'dt(self)', '->', 'float:', 'return', 'self._dt']
883,637
Jun-CEN/Open-World-Semantic-Segmentation
modeling.py
deeplabv3plus_embedding_self_distillation_resnet101
deeplabv3plus_embedding_self_distillation_resnet101
Constructs a DeepLabV3+ model with a ResNet-101 backbone.
[ "Constructs", "a", "DeepLabV3+", "model", "with", "a", "ResNet-101", "backbone." ]
def deeplabv3plus_embedding_self_distillation_resnet101(num_classes=21, output_stride=8, pretrained_backbone=True): return _load_model('deeplabv3plus_embedding_self_distillation', 'resnet101', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
['def', 'deeplabv3plus_embedding_self_distillation_resnet101(num_classes=21,', 'output_stride=8,', 'pretrained_backbone=True):', 'return', "_load_model('deeplabv3plus_embedding_self_distillation',", "'resnet101',", 'num_classes,', 'output_stride=output_stride,', 'pretrained_backbone=pretrained_backbone)']
756,865
open-mmlab/mmdetection3d
dataset_wrappers.py
CBGSDataset.full_init
full_init
Loop to ``full_init`` each dataset.
[ "Loop", "to", "``full_init``", "each", "dataset." ]
def full_init(self) -> None: if self._fully_initialized: return self.dataset.full_init() self.sample_indices = self._get_sample_indices(self.dataset) self._fully_initialized = True
['def', 'full_init(self)', '->', 'None:', 'if', 'self._fully_initialized:', 'return', 'self.dataset.full_init()', 'self.sample_indices', '=', 'self._get_sample_indices(self.dataset)', 'self._fully_initialized', '=', 'True']
631,656
f-dangel/cockpit
optimized.py
get_out_files
get_out_files
Return all available output files for a test problem.
[ "Return", "all", "available", "output", "files", "for", "a", "test", "problem." ]
def get_out_files(testproblem): pattern = os.path.join(DIR, f'{testproblem}_optimized_*.csv') return glob.glob(pattern)
['def', 'get_out_files(testproblem):', 'pattern', '=', 'os.path.join(DIR,', "f'{testproblem}_optimized_*.csv')", 'return', 'glob.glob(pattern)']
493,201
nicknochnack/RealTimeSignLanguageTFJS
image_resizer_builder_test.py
ImageResizerBuilderTest.test_build_pad_to_multiple_resizer
test_build_pad_to_multiple_resizer
Test building a pad_to_multiple_resizer from proto.
[ "Test", "building", "a", "pad_to_multiple_resizer", "from", "proto." ]
def test_build_pad_to_multiple_resizer(self): image_resizer_text_proto = '\n pad_to_multiple_resizer {\n multiple: 32\n }\n ' input_shape = (60, 30, 3) expected_output_shape = (64, 32, 3) output_shape = self._shape_of_resized_random_image_given_text_proto(input_shape, image_resizer_t...
['def', 'test_build_pad_to_multiple_resizer(self):', 'image_resizer_text_proto', '=', "'\\n", 'pad_to_multiple_resizer', '{\\n', 'multiple:', '32\\n', '}\\n', "'", 'input_shape', '=', '(60,', '30,', '3)', 'expected_output_shape', '=', '(64,', '32,', '3)', 'output_shape', '=', 'self._shape_of_resized_random_image_given_...
852,062
airbus/scikit-decide
core.py
ExtendedDataclass.astuple
astuple
Return the fields of the instance as a new tuple of field values.
[ "Return", "the", "fields", "of", "the", "instance", "as", "a", "new", "tuple", "of", "field", "values." ]
def astuple(self): return astuple(self)
['def', 'astuple(self):', 'return', 'astuple(self)']
847,784
rifqind/Agent-Programs-3KS1
classes.py
BaseDefinition.in_builtin_module
in_builtin_module
Whether this is a builtin module.
[ "Whether", "this", "is", "a", "builtin", "module." ]
def in_builtin_module(self): return isinstance(self._module, compiled.CompiledObject)
['def', 'in_builtin_module(self):', 'return', 'isinstance(self._module,', 'compiled.CompiledObject)']
42,052