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
google/deepvariant
variant_caller_test.py
VariantCallerTests.test_handles_large_reference_counts
test_handles_large_reference_counts
Tests that we don't blow up when the coverage gets really high.
[ "Tests", "that", "we", "don't", "blow", "up", "when", "the", "coverage", "gets", "really", "high." ]
def test_handles_large_reference_counts(self, n_ref, n_alt_fraction): caller = PlaceholderVariantCaller(0.01, 100) n_alt = int(n_alt_fraction * n_ref) (gq, likelihoods) = caller._calc_reference_confidence(n_ref, n_ref + n_alt) self.assertTrue(np.isfinite(likelihoods).all(), 'Non-finite likelihoods {}'.f...
['def', 'test_handles_large_reference_counts(self,', 'n_ref,', 'n_alt_fraction):', 'caller', '=', 'PlaceholderVariantCaller(0.01,', '100)', 'n_alt', '=', 'int(n_alt_fraction', '*', 'n_ref)', '(gq,', 'likelihoods)', '=', 'caller._calc_reference_confidence(n_ref,', 'n_ref', '+', 'n_alt)', 'self.assertTrue(np.isfinite(lik...
540,444
RLE-Foundation/rllte
utils.py
DistributedWrapper.step
step
Step function that returns a dict consists of the current and history observation and action.
[ "Step", "function", "that", "returns", "a", "dict", "consists", "of", "the", "current", "and", "history", "observation", "and", "action." ]
def step(self, action: th.Tensor) -> Dict[str, th.Tensor]: if self.action_type == 'Discrete': _action = action.item() elif self.action_type == 'Box': _action = action.squeeze(0).cpu().numpy() else: raise NotImplementedError('Unsupported action type!') (obs, reward, terminated, tr...
['def', 'step(self,', 'action:', 'th.Tensor)', '->', 'Dict[str,', 'th.Tensor]:', 'if', 'self.action_type', '==', "'Discrete':", '_action', '=', 'action.item()', 'elif', 'self.action_type', '==', "'Box':", '_action', '=', 'action.squeeze(0).cpu().numpy()', 'else:', 'raise', "NotImplementedError('Unsupported", 'action', ...
333,264
KalleHallden/InstaAutomator
decorators.py
requires_duration
requires_duration
Raise an error if the clip has no duration.
[ "Raise", "an", "error", "if", "the", "clip", "has", "no", "duration." ]
def requires_duration(f, clip, *a, **k): if clip.duration is None: raise ValueError("Attribute 'duration' not set") else: return f(clip, *a, **k)
['def', 'requires_duration(f,', 'clip,', '*a,', '**k):', 'if', 'clip.duration', 'is', 'None:', 'raise', 'ValueError("Attribute', "'duration'", 'not', 'set")', 'else:', 'return', 'f(clip,', '*a,', '**k)']
242,835
scikit-learn-contrib/imbalanced-learn
_forest.py
BalancedRandomForestClassifier.n_features_
n_features_
Number of features when ``fit`` is performed.
[ "Number", "of", "features", "when", "``fit``", "is", "performed." ]
def n_features_(self): warn('`n_features_` was deprecated in scikit-learn 1.0. This attribute will not be accessible when the minimum supported version of scikit-learn is 1.2.', FutureWarning) return self.n_features_in_
['def', 'n_features_(self):', "warn('`n_features_`", 'was', 'deprecated', 'in', 'scikit-learn', '1.0.', 'This', 'attribute', 'will', 'not', 'be', 'accessible', 'when', 'the', 'minimum', 'supported', 'version', 'of', 'scikit-learn', 'is', "1.2.',", 'FutureWarning)', 'return', 'self.n_features_in_']
610,640
bachiraoun/fullrmc
Engine.py
Engine.elements
elements
Sorted set of all existing atom elements.
[ "Sorted", "set", "of", "all", "existing", "atom", "elements." ]
def elements(self): return self.__elements
['def', 'elements(self):', 'return', 'self.__elements']
213,413
kubeflow/pipelines
_pipeline.py
PipelineConf.set_pod_disruption_budget
set_pod_disruption_budget
PodDisruptionBudget holds the number of concurrent disruptions that you allow for pipeline Pods.
[ "PodDisruptionBudget", "holds", "the", "number", "of", "concurrent", "disruptions", "that", "you", "allow", "for", "pipeline", "Pods." ]
def set_pod_disruption_budget(self, min_available: Union[int, str]): self._pod_disruption_budget_min_available = min_available return self
['def', 'set_pod_disruption_budget(self,', 'min_available:', 'Union[int,', 'str]):', 'self._pod_disruption_budget_min_available', '=', 'min_available', 'return', 'self']
780,165
pokaxpoka/sunrise
utils.py
posdef_eig_svd
posdef_eig_svd
Computes the singular values and left singular vectors of a matrix.
[ "Computes", "the", "singular", "values", "and", "left", "singular", "vectors", "of", "a", "matrix." ]
def posdef_eig_svd(mat): (evals, evecs, _) = linalg_ops.svd(mat) return (evals, evecs)
['def', 'posdef_eig_svd(mat):', '(evals,', 'evecs,', '_)', '=', 'linalg_ops.svd(mat)', 'return', '(evals,', 'evecs)']
911,852
cnr-isti-vclab/TagLab
TagLab.py
TagLab.createCrack
createCrack
Activate the tool "Create Crack".
[ "Activate", "the", "tool", "\"Create", "Crack\"." ]
def createCrack(self): self.setTool('CREATECRACK')
['def', 'createCrack(self):', "self.setTool('CREATECRACK')"]
906,617
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
create_timit_dataset.py
get_filenames
get_filenames
Get all wav filenames from the TIMIT archive.
[ "Get", "all", "wav", "filenames", "from", "the", "TIMIT", "archive." ]
def get_filenames(split): path = os.path.join(FLAGS.raw_timit_dir, 'TIMIT', split, '*', '*', '*.WAV') files = sorted(glob.glob(path)) return files
['def', 'get_filenames(split):', 'path', '=', 'os.path.join(FLAGS.raw_timit_dir,', "'TIMIT',", 'split,', "'*',", "'*',", "'*.WAV')", 'files', '=', 'sorted(glob.glob(path))', 'return', 'files']
54,659
facebookresearch/dinov2
__init__.py
FSDPCheckpointer.save
save
Dump model and checkpointables to a file.
[ "Dump", "model", "and", "checkpointables", "to", "a", "file." ]
def save(self, name: str, **kwargs: Any) -> None: if not self.save_dir or not self.save_to_disk: return data = {} with FSDP.state_dict_type(self.model, StateDictType.LOCAL_STATE_DICT): data['model'] = self.model.state_dict() for (key, obj) in self.checkpointables.items(): data[ke...
['def', 'save(self,', 'name:', 'str,', '**kwargs:', 'Any)', '->', 'None:', 'if', 'not', 'self.save_dir', 'or', 'not', 'self.save_to_disk:', 'return', 'data', '=', '{}', 'with', 'FSDP.state_dict_type(self.model,', 'StateDictType.LOCAL_STATE_DICT):', "data['model']", '=', 'self.model.state_dict()', 'for', '(key,', 'obj)'...
186,195
voxel51/fiftyone
dataset.py
list_datasets
list_datasets
Lists the available FiftyOne datasets.
[ "Lists", "the", "available", "FiftyOne", "datasets." ]
def list_datasets(glob_patt=None, tags=None, info=False): if info: return _list_datasets_info(glob_patt=glob_patt, tags=tags) return _list_datasets(glob_patt=glob_patt, tags=tags)
['def', 'list_datasets(glob_patt=None,', 'tags=None,', 'info=False):', 'if', 'info:', 'return', '_list_datasets_info(glob_patt=glob_patt,', 'tags=tags)', 'return', '_list_datasets(glob_patt=glob_patt,', 'tags=tags)']
582,848
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
traceback.py
format_exc
format_exc
Like print_exc() but return a string.
[ "Like", "print_exc()", "but", "return", "a", "string." ]
def format_exc(limit=None, chain=True): return ''.join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
['def', 'format_exc(limit=None,', 'chain=True):', 'return', "''.join(format_exception(*sys.exc_info(),", 'limit=limit,', 'chain=chain))']
429,742
weimin17/Object-Detection_HelmetDetection
tensorrt.py
get_serving_meta_graph_def
get_serving_meta_graph_def
Extract the SERVING MetaGraphDef from a SavedModel directory.
[ "Extract", "the", "SERVING", "MetaGraphDef", "from", "a", "SavedModel", "directory." ]
def get_serving_meta_graph_def(savedmodel_dir): tag_set = set([tf.saved_model.tag_constants.SERVING]) serving_graph_def = None saved_model = reader.read_saved_model(savedmodel_dir) for meta_graph_def in saved_model.meta_graphs: if set(meta_graph_def.meta_info_def.tags) == tag_set: se...
['def', 'get_serving_meta_graph_def(savedmodel_dir):', 'tag_set', '=', 'set([tf.saved_model.tag_constants.SERVING])', 'serving_graph_def', '=', 'None', 'saved_model', '=', 'reader.read_saved_model(savedmodel_dir)', 'for', 'meta_graph_def', 'in', 'saved_model.meta_graphs:', 'if', 'set(meta_graph_def.meta_info_def.tags)'...
760,760
aisingapore/PeekingDuck
core.py
init
init
Initializes a PeekingDuck project.
[ "Initializes", "a", "PeekingDuck", "project." ]
def init(custom_folder_name: str) -> None: print('Welcome to PeekingDuck!') _create_custom_folder(custom_folder_name) _create_pipeline_config_yml()
['def', 'init(custom_folder_name:', 'str)', '->', 'None:', "print('Welcome", 'to', "PeekingDuck!')", '_create_custom_folder(custom_folder_name)', '_create_pipeline_config_yml()']
766,790
Kvatsx/Artificial-Intelligence-Assignments
asyncio_win32.py
Win32AsyncioEventLoop.remove_reader
remove_reader
Stop watching the file descriptor for read availability.
[ "Stop", "watching", "the", "file", "descriptor", "for", "read", "availability." ]
def remove_reader(self, fd): self.loop.remove_reader(fd)
['def', 'remove_reader(self,', 'fd):', 'self.loop.remove_reader(fd)']
75,739
JinliangLu96/CL_UNMT
utils.py
concat_batches
concat_batches
Concat batches with different languages.
[ "Concat", "batches", "with", "different", "languages." ]
def concat_batches(x1, len1, lang1_id, x2, len2, lang2_id, pad_idx, eos_idx, reset_positions): assert reset_positions is False or lang1_id != lang2_id lengths = len1 + len2 if not reset_positions: lengths -= 1 (slen, bs) = (lengths.max().item(), lengths.size(0)) x = x1.new(slen, bs).fill_(pa...
['def', 'concat_batches(x1,', 'len1,', 'lang1_id,', 'x2,', 'len2,', 'lang2_id,', 'pad_idx,', 'eos_idx,', 'reset_positions):', 'assert', 'reset_positions', 'is', 'False', 'or', 'lang1_id', '!=', 'lang2_id', 'lengths', '=', 'len1', '+', 'len2', 'if', 'not', 'reset_positions:', 'lengths', '-=', '1', '(slen,', 'bs)', '=', ...
123,244
keyonvafa/career-code
fairseq_dataset.py
FairseqDataset.collater
collater
Merge a list of samples to form a mini-batch.
[ "Merge", "a", "list", "of", "samples", "to", "form", "a", "mini-batch." ]
def collater(self, samples): raise NotImplementedError
['def', 'collater(self,', 'samples):', 'raise', 'NotImplementedError']
455,259
jimtin/Stock_Comparison
converter.py
TimeSeries_DateLocator.autoscale
autoscale
Sets the view limits to the nearest multiples of base that contain the data.
[ "Sets", "the", "view", "limits", "to", "the", "nearest", "multiples", "of", "base", "that", "contain", "the", "data." ]
def autoscale(self): (vmin, vmax) = self.axis.get_data_interval() locs = self._get_default_locs(vmin, vmax) (vmin, vmax) = locs[[0, -1]] if vmin == vmax: vmin -= 1 vmax += 1 return nonsingular(vmin, vmax)
['def', 'autoscale(self):', '(vmin,', 'vmax)', '=', 'self.axis.get_data_interval()', 'locs', '=', 'self._get_default_locs(vmin,', 'vmax)', '(vmin,', 'vmax)', '=', 'locs[[0,', '-1]]', 'if', 'vmin', '==', 'vmax:', 'vmin', '-=', '1', 'vmax', '+=', '1', 'return', 'nonsingular(vmin,', 'vmax)']
388,221
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
frequencies.py
get_period_alias
get_period_alias
Alias to closest period strings BQ->Q etc.
[ "Alias", "to", "closest", "period", "strings", "BQ->Q", "etc." ]
def get_period_alias(offset_str: str) -> Optional[str]: return _offset_to_period_map.get(offset_str, None)
['def', 'get_period_alias(offset_str:', 'str)', '->', 'Optional[str]:', 'return', '_offset_to_period_map.get(offset_str,', 'None)']
83,572
0xangelo/raylab
stats.py
learner_stats
learner_stats
Wrap function to return stats under learner stats key.
[ "Wrap", "function", "to", "return", "stats", "under", "learner", "stats", "key." ]
def learner_stats(func: Callable[[Any], dict]) -> Callable[[Any], dict]: @functools.wraps(func) def wrapped(*args, **kwargs): stats = func(*args, **kwargs) nested = stats.get(LEARNER_STATS_KEY, {}) unnested = {k: v for (k, v) in stats.items() if k != LEARNER_STATS_KEY} return {L...
['def', 'learner_stats(func:', 'Callable[[Any],', 'dict])', '->', 'Callable[[Any],', 'dict]:', '@functools.wraps(func)', 'def', 'wrapped(*args,', '**kwargs):', 'stats', '=', 'func(*args,', '**kwargs)', 'nested', '=', 'stats.get(LEARNER_STATS_KEY,', '{})', 'unnested', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'stats.it...
848,316
PaddlePaddle/PaddleSpeech
decoder.py
Decoder.batch_score
batch_score
Score new token batch (required).
[ "Score", "new", "token", "batch", "(required)." ]
def batch_score(self, ys: paddle.Tensor, states: List[Any], xs: paddle.Tensor) -> Tuple[paddle.Tensor, List[Any]]: n_batch = len(ys) n_layers = len(self.decoders) if states[0] is None: batch_state = None else: batch_state = [paddle.stack([states[b][i] for b in range(n_batch)]) for i in r...
['def', 'batch_score(self,', 'ys:', 'paddle.Tensor,', 'states:', 'List[Any],', 'xs:', 'paddle.Tensor)', '->', 'Tuple[paddle.Tensor,', 'List[Any]]:', 'n_batch', '=', 'len(ys)', 'n_layers', '=', 'len(self.decoders)', 'if', 'states[0]', 'is', 'None:', 'batch_state', '=', 'None', 'else:', 'batch_state', '=', '[paddle.stack...
277,271
scotthuang1989/object_detection_with_tensorflow
feature_io.py
WriteToFile
WriteToFile
Helper function to write data to a file in DelfFeatures format.
[ "Helper", "function", "to", "write", "data", "to", "a", "file", "in", "DelfFeatures", "format." ]
def WriteToFile(file_path, locations, scales, descriptors, attention, orientations=None): serialized_data = SerializeToString(locations, scales, descriptors, attention, orientations) with tf.gfile.FastGFile(file_path, 'w') as f: f.write(serialized_data)
['def', 'WriteToFile(file_path,', 'locations,', 'scales,', 'descriptors,', 'attention,', 'orientations=None):', 'serialized_data', '=', 'SerializeToString(locations,', 'scales,', 'descriptors,', 'attention,', 'orientations)', 'with', 'tf.gfile.FastGFile(file_path,', "'w')", 'as', 'f:', 'f.write(serialized_data)']
796,957
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.winfo_rgb
winfo_rgb
Return tuple of decimal values for red, green, blue for COLOR in this widget.
[ "Return", "tuple", "of", "decimal", "values", "for", "red,", "green,", "blue", "for", "COLOR", "in", "this", "widget." ]
def winfo_rgb(self, color): return self._getints(self.tk.call('winfo', 'rgb', self._w, color))
['def', 'winfo_rgb(self,', 'color):', 'return', "self._getints(self.tk.call('winfo',", "'rgb',", 'self._w,', 'color))']
376,822
jbwang1997/CrossKD
ld_head.py
LDHead.loss_by_feat_single
loss_by_feat_single
Calculate the loss of a single scale level based on the features extracted by the detection head.
[ "Calculate", "the", "loss", "of", "a", "single", "scale", "level", "based", "on", "the", "features", "extracted", "by", "the", "detection", "head." ]
def loss_by_feat_single(self, anchors: Tensor, cls_score: Tensor, bbox_pred: Tensor, labels: Tensor, label_weights: Tensor, bbox_targets: Tensor, stride: Tuple[int], soft_targets: Tensor, avg_factor: int): assert stride[0] == stride[1], 'h stride is not equal to w stride!' anchors = anchors.reshape(-1, 4) c...
['def', 'loss_by_feat_single(self,', 'anchors:', 'Tensor,', 'cls_score:', 'Tensor,', 'bbox_pred:', 'Tensor,', 'labels:', 'Tensor,', 'label_weights:', 'Tensor,', 'bbox_targets:', 'Tensor,', 'stride:', 'Tuple[int],', 'soft_targets:', 'Tensor,', 'avg_factor:', 'int):', 'assert', 'stride[0]', '==', 'stride[1],', "'h", 'str...
491,098
dlshriver/dnnv
s_shaped.py
AbstractSShaped.split_point
split_point
Calculates the preferred split point for branching.
[ "Calculates", "the", "preferred", "split", "point", "for", "branching." ]
def split_point(self, xl: float, xu: float) -> float: raise NotImplementedError(f'split_point(...) not implemented in {self.__name__}')
['def', 'split_point(self,', 'xl:', 'float,', 'xu:', 'float)', '->', 'float:', 'raise', "NotImplementedError(f'split_point(...)", 'not', 'implemented', 'in', "{self.__name__}')"]
522,622
enuguru/artificial_intelligence_and_machine_
etxrd.py
getPriority
getPriority
Get the priority of this element Returns Max if no priority is specified or the priority value is invalid.
[ "Get", "the", "priority", "of", "this", "element", "Returns", "Max", "if", "no", "priority", "is", "specified", "or", "the", "priority", "value", "is", "invalid." ]
def getPriority(element): try: return getPriorityStrict(element) except ValueError: return Max
['def', 'getPriority(element):', 'try:', 'return', 'getPriorityStrict(element)', 'except', 'ValueError:', 'return', 'Max']
159,554
TrellixVulnTeam/Unsupervised_Learning_HFI7
__init__.py
_PluginManager.register
register
Makes it possible to register your plugin.
[ "Makes", "it", "possible", "to", "register", "your", "plugin." ]
def register(self, *plugins): self._registered_plugins.extend(plugins) self._build_functions()
['def', 'register(self,', '*plugins):', 'self._registered_plugins.extend(plugins)', 'self._build_functions()']
449,336
qcraftai/pillar-motion
_functions.py
scatter
scatter
Scatters tensor across multiple GPUs.
[ "Scatters", "tensor", "across", "multiple", "GPUs." ]
def scatter(input, devices, streams=None): if streams is None: streams = [None] * len(devices) if isinstance(input, list): chunk_size = (len(input) - 1) // len(devices) + 1 outputs = [scatter(input[i], [devices[i // chunk_size]], [streams[i // chunk_size]]) for i in range(len(input))] ...
['def', 'scatter(input,', 'devices,', 'streams=None):', 'if', 'streams', 'is', 'None:', 'streams', '=', '[None]', '*', 'len(devices)', 'if', 'isinstance(input,', 'list):', 'chunk_size', '=', '(len(input)', '-', '1)', '//', 'len(devices)', '+', '1', 'outputs', '=', '[scatter(input[i],', '[devices[i', '//', 'chunk_size]]...
305,015
KalleHallden/InstaAutomator
_tqdm_notebook.py
tqdm_notebook.status_printer
status_printer
Manage the printing of an IPython/Jupyter Notebook progress bar widget.
[ "Manage", "the", "printing", "of", "an", "IPython/Jupyter", "Notebook", "progress", "bar", "widget." ]
def status_printer(_, total=None, desc=None): if total: pbar = IntProgress(min=0, max=total) else: pbar = IntProgress(min=0, max=1) pbar.value = 1 pbar.bar_style = 'info' if desc: pbar.description = desc ptext = HTML() container = HBox(children=[pbar, ptext]) ...
['def', 'status_printer(_,', 'total=None,', 'desc=None):', 'if', 'total:', 'pbar', '=', 'IntProgress(min=0,', 'max=total)', 'else:', 'pbar', '=', 'IntProgress(min=0,', 'max=1)', 'pbar.value', '=', '1', 'pbar.bar_style', '=', "'info'", 'if', 'desc:', 'pbar.description', '=', 'desc', 'ptext', '=', 'HTML()', 'container', ...
244,958
caiiiac/Machine-Learning-with-Python
test_mldata.py
test_download
test_download
Test that fetch_mldata is able to download and cache a data set.
[ "Test", "that", "fetch_mldata", "is", "able", "to", "download", "and", "cache", "a", "data", "set." ]
def test_download(): _urlopen_ref = datasets.mldata.urlopen datasets.mldata.urlopen = mock_mldata_urlopen({'mock': {'label': sp.ones((150,)), 'data': sp.ones((150, 4))}}) try: mock = fetch_mldata('mock', data_home=tmpdir) for n in ['COL_NAMES', 'DESCR', 'target', 'data']: assert_...
['def', 'test_download():', '_urlopen_ref', '=', 'datasets.mldata.urlopen', 'datasets.mldata.urlopen', '=', "mock_mldata_urlopen({'mock':", "{'label':", 'sp.ones((150,)),', "'data':", 'sp.ones((150,', '4))}})', 'try:', 'mock', '=', "fetch_mldata('mock',", 'data_home=tmpdir)', 'for', 'n', 'in', "['COL_NAMES',", "'DESCR'...
720,520
LiWentomng/OrientedRepPoints
fcn_mask_head.py
FCNMaskHead.get_seg_masks
get_seg_masks
Get segmentation masks from mask_pred and bboxes.
[ "Get", "segmentation", "masks", "from", "mask_pred", "and", "bboxes." ]
def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid().cpu().numpy() assert isinstance(mask_pred, np.ndarray) mask_pred = mask_pred.astype(np.float32) cls_segms = [[] for...
['def', 'get_seg_masks(self,', 'mask_pred,', 'det_bboxes,', 'det_labels,', 'rcnn_test_cfg,', 'ori_shape,', 'scale_factor,', 'rescale):', 'if', 'isinstance(mask_pred,', 'torch.Tensor):', 'mask_pred', '=', 'mask_pred.sigmoid().cpu().numpy()', 'assert', 'isinstance(mask_pred,', 'np.ndarray)', 'mask_pred', '=', 'mask_pred....
776,596
salesforce/CodeRL
modeling_flax_blenderbot_small.py
shift_tokens_right
shift_tokens_right
Shift input ids one token to the right.
[ "Shift", "input", "ids", "one", "token", "to", "the", "right." ]
def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray: shifted_input_ids = np.zeros_like(input_ids) shifted_input_ids[:, 1:] = input_ids[:, :-1] shifted_input_ids[:, 0] = decoder_start_token_id shifted_input_ids = np.where(shifted_input_ids == -100...
['def', 'shift_tokens_right(input_ids:', 'jnp.ndarray,', 'pad_token_id:', 'int,', 'decoder_start_token_id:', 'int)', '->', 'jnp.ndarray:', 'shifted_input_ids', '=', 'np.zeros_like(input_ids)', 'shifted_input_ids[:,', '1:]', '=', 'input_ids[:,', ':-1]', 'shifted_input_ids[:,', '0]', '=', 'decoder_start_token_id', 'shift...
494,418
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_pretty.py
test_callability_checking
test_callability_checking
Test that the _repr_pretty_ method is tested for callability and skipped if not.
[ "Test", "that", "the", "_repr_pretty_", "method", "is", "tested", "for", "callability", "and", "skipped", "if", "not." ]
def test_callability_checking(): gotoutput = pretty.pretty(Dummy2()) expectedoutput = 'Dummy1(...)' nt.assert_equal(gotoutput, expectedoutput)
['def', 'test_callability_checking():', 'gotoutput', '=', 'pretty.pretty(Dummy2())', 'expectedoutput', '=', "'Dummy1(...)'", 'nt.assert_equal(gotoutput,', 'expectedoutput)']
448,787
microsoft/nni
bayesian.py
BayesianOptimizer.fit
fit
Fit the optimizer with new architectures and performances.
[ "Fit", "the", "optimizer", "with", "new", "architectures", "and", "performances." ]
def fit(self, x_queue, y_queue): self.gpr.fit(x_queue, y_queue)
['def', 'fit(self,', 'x_queue,', 'y_queue):', 'self.gpr.fit(x_queue,', 'y_queue)']
728,357
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
entropy_coder_model.py
EntropyCoderModel.GetConfigStringForUnitTest
GetConfigStringForUnitTest
Returns a default model configuration to be used for unit tests.
[ "Returns", "a", "default", "model", "configuration", "to", "be", "used", "for", "unit", "tests." ]
def GetConfigStringForUnitTest(self): return None
['def', 'GetConfigStringForUnitTest(self):', 'return', 'None']
53,638
ZhangAoCanada/RADDet
helper.py
GaussianModel
GaussianModel
Get the center and covariance from gaussian model.
[ "Get", "the", "center", "and", "covariance", "from", "gaussian", "model." ]
def GaussianModel(pcl): model = mixture.GaussianMixture(n_components=1, covariance_type='full') model.fit(pcl) return (model.means_[0], model.covariances_[0])
['def', 'GaussianModel(pcl):', 'model', '=', 'mixture.GaussianMixture(n_components=1,', "covariance_type='full')", 'model.fit(pcl)', 'return', '(model.means_[0],', 'model.covariances_[0])']
835,788
sek788432/Waymo-2D-Object-Detection
resnet_deeplab.py
build_dilated_resnet
build_dilated_resnet
Builds ResNet backbone from a config.
[ "Builds", "ResNet", "backbone", "from", "a", "config." ]
def build_dilated_resnet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model: backbone_type = backbone_config.type backbone_cfg = backbone_config.get() assert backbo...
['def', 'build_dilated_resnet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg', '='...
973,131
Caojunxu/AC-FPN
dataset_catalog.py
get_im_prefix
get_im_prefix
Retrieve the image prefix for the dataset.
[ "Retrieve", "the", "image", "prefix", "for", "the", "dataset." ]
def get_im_prefix(name): return _DATASETS[name][_IM_PREFIX] if _IM_PREFIX in _DATASETS[name] else ''
['def', 'get_im_prefix(name):', 'return', '_DATASETS[name][_IM_PREFIX]', 'if', '_IM_PREFIX', 'in', '_DATASETS[name]', 'else', "''"]
406,392
sek788432/Waymo-2D-Object-Detection
augment.py
translate
translate
Translates image(s) by provided vectors.
[ "Translates", "image(s)", "by", "provided", "vectors." ]
def translate(image: tf.Tensor, translations) -> tf.Tensor: transforms = _convert_translation_to_transform(translations) return transform(image, transforms=transforms)
['def', 'translate(image:', 'tf.Tensor,', 'translations)', '->', 'tf.Tensor:', 'transforms', '=', '_convert_translation_to_transform(translations)', 'return', 'transform(image,', 'transforms=transforms)']
973,682
tensorflow/agents
ppo_policy.py
PPOPolicy.get_initial_value_state
get_initial_value_state
Returns the initial state of the value network.
[ "Returns", "the", "initial", "state", "of", "the", "value", "network." ]
def get_initial_value_state(self, batch_size: types.Int) -> types.NestedTensor: return tensor_spec.zero_spec_nest(self._value_network.state_spec, outer_dims=None if batch_size is None else [batch_size])
['def', 'get_initial_value_state(self,', 'batch_size:', 'types.Int)', '->', 'types.NestedTensor:', 'return', 'tensor_spec.zero_spec_nest(self._value_network.state_spec,', 'outer_dims=None', 'if', 'batch_size', 'is', 'None', 'else', '[batch_size])']
22,493
MycroftAI/mycroft-core
test_setup.py
create_skills_manager
create_skills_manager
Create mycroft skills manager for the given url / branch.
[ "Create", "mycroft", "skills", "manager", "for", "the", "given", "url", "/", "branch." ]
def create_skills_manager(platform, skills_dir, url, branch): repo = SkillRepo(url=url, branch=branch) return MycroftSkillsManager(platform, skills_dir, repo)
['def', 'create_skills_manager(platform,', 'skills_dir,', 'url,', 'branch):', 'repo', '=', 'SkillRepo(url=url,', 'branch=branch)', 'return', 'MycroftSkillsManager(platform,', 'skills_dir,', 'repo)']
290,823
Kvatsx/Artificial-Intelligence-Assignments
parse.py
unquote_to_bytes
unquote_to_bytes
unquote_to_bytes('abc%20def') -> b'abc def'.
[ "unquote_to_bytes('abc%20def')", "->", "b'abc", "def'." ]
def unquote_to_bytes(string): if not string: string.split return bytes(b'') if isinstance(string, str): string = string.encode('utf-8') string = bytes(string) bits = string.split(b'%') if len(bits) == 1: return string res = [bits[0]] append = res.append fo...
['def', 'unquote_to_bytes(string):', 'if', 'not', 'string:', 'string.split', 'return', "bytes(b'')", 'if', 'isinstance(string,', 'str):', 'string', '=', "string.encode('utf-8')", 'string', '=', 'bytes(string)', 'bits', '=', "string.split(b'%')", 'if', 'len(bits)', '==', '1:', 'return', 'string', 'res', '=', '[bits[0]]'...
37,044
BMW-InnovationLab/BMW-Semantic--Training-GUI
utils.py
Track.is_mising
is_mising
Returns True if this track is tentative (unconfirmed).
[ "Returns", "True", "if", "this", "track", "is", "tentative", "(unconfirmed)." ]
def is_mising(self): return self.state == TrackState.Missing
['def', 'is_mising(self):', 'return', 'self.state', '==', 'TrackState.Missing']
462,871
weimin17/Object-Detection_HelmetDetection
compute_bleu.py
define_compute_bleu_flags
define_compute_bleu_flags
Add flags for computing BLEU score.
[ "Add", "flags", "for", "computing", "BLEU", "score." ]
def define_compute_bleu_flags(): flags.DEFINE_string(name='translation', default=None, help=flags_core.help_wrap('File containing translated text.')) flags.mark_flag_as_required('translation') flags.DEFINE_string(name='reference', default=None, help=flags_core.help_wrap('File containing reference translatio...
['def', 'define_compute_bleu_flags():', "flags.DEFINE_string(name='translation',", 'default=None,', "help=flags_core.help_wrap('File", 'containing', 'translated', "text.'))", "flags.mark_flag_as_required('translation')", "flags.DEFINE_string(name='reference',", 'default=None,', "help=flags_core.help_wrap('File", 'conta...
761,142
brandicted/scrapy-webdriver
selector.py
WebdriverXPathSelector.select_script
select_script
Return elements using JavaScript snippet execution.
[ "Return", "elements", "using", "JavaScript", "snippet", "execution." ]
def select_script(self, script, *args): result = self.webdriver.execute_script(script, *args) return XPathSelectorList(self._make_result(result))
['def', 'select_script(self,', 'script,', '*args):', 'result', '=', 'self.webdriver.execute_script(script,', '*args)', 'return', 'XPathSelectorList(self._make_result(result))']
341,502
feast-dev/feast
data_source.py
DataSource.get_table_query_string
get_table_query_string
Returns a string that can directly be used to reference this table in SQL.
[ "Returns", "a", "string", "that", "can", "directly", "be", "used", "to", "reference", "this", "table", "in", "SQL." ]
def get_table_query_string(self) -> str: raise NotImplementedError
['def', 'get_table_query_string(self)', '->', 'str:', 'raise', 'NotImplementedError']
544,211
kiretd/Unsupervised-MIseg
MRCNN.py
MRCNN.inference
inference
Runs model in inference mode.
[ "Runs", "model", "in", "inference", "mode." ]
def inference(self): config = InferenceConfig() model = self.model savedir = self.savedir model = modellib.MaskRCNN(mode='inference', config=config, model_dir=savedir) self.model = model self.inference_config = config
['def', 'inference(self):', 'config', '=', 'InferenceConfig()', 'model', '=', 'self.model', 'savedir', '=', 'self.savedir', 'model', '=', "modellib.MaskRCNN(mode='inference',", 'config=config,', 'model_dir=savedir)', 'self.model', '=', 'model', 'self.inference_config', '=', 'config']
353,674
Oneflow-Inc/vision
det_utils.py
retrieve_out_channels
retrieve_out_channels
This method retrieves the number of output channels of specific model.
[ "This", "method", "retrieves", "the", "number", "of", "output", "channels", "of", "specific", "model." ]
def retrieve_out_channels(model, size): in_training = model.training model.eval() with flow.no_grad(): device = next(model.parameters()).device tmp_img = flow.zeros((1, 3, size[1], size[0]), device=device) features = model(tmp_img) if isinstance(features, flow.Tensor): ...
['def', 'retrieve_out_channels(model,', 'size):', 'in_training', '=', 'model.training', 'model.eval()', 'with', 'flow.no_grad():', 'device', '=', 'next(model.parameters()).device', 'tmp_img', '=', 'flow.zeros((1,', '3,', 'size[1],', 'size[0]),', 'device=device)', 'features', '=', 'model(tmp_img)', 'if', 'isinstance(fea...
957,507
Anjok07/ultimatevocalremovergui
states.py
set_state
set_state
Set the state on a given model.
[ "Set", "the", "state", "on", "a", "given", "model." ]
def set_state(model, state, quantizer=None): if state.get('__quantized'): if quantizer is not None: quantizer.restore_quantized_state(model, state['quantized']) else: restore_quantized_state(model, state) else: model.load_state_dict(state) return state
['def', 'set_state(model,', 'state,', 'quantizer=None):', 'if', "state.get('__quantized'):", 'if', 'quantizer', 'is', 'not', 'None:', 'quantizer.restore_quantized_state(model,', "state['quantized'])", 'else:', 'restore_quantized_state(model,', 'state)', 'else:', 'model.load_state_dict(state)', 'return', 'state']
947,564
facebookresearch/minihack
reward_manager.py
RewardManager.add_wield_event
add_wield_event
Add event which is triggered when a specific weapon is wielded.
[ "Add", "event", "which", "is", "triggered", "when", "a", "specific", "weapon", "is", "wielded." ]
def add_wield_event(self, name: str, reward=1, repeatable=False, terminal_required=True, terminal_sufficient=False): msgs = [f'{name} wields itself to your hand!', f'{name} (weapon in hand)'] self._add_message_event(msgs, reward, repeatable, terminal_required, terminal_sufficient)
['def', 'add_wield_event(self,', 'name:', 'str,', 'reward=1,', 'repeatable=False,', 'terminal_required=True,', 'terminal_sufficient=False):', 'msgs', '=', "[f'{name}", 'wields', 'itself', 'to', 'your', "hand!',", "f'{name}", '(weapon', 'in', "hand)']", 'self._add_message_event(msgs,', 'reward,', 'repeatable,', 'termina...
670,726
FreshAirTonight/af2complex
rotation_matrix.py
Rot3Array.from_quaternion
from_quaternion
Construct Rot3Array from components of quaternion.
[ "Construct", "Rot3Array", "from", "components", "of", "quaternion." ]
def from_quaternion(cls, w: jnp.ndarray, x: jnp.ndarray, y: jnp.ndarray, z: jnp.ndarray, normalize: bool=True, epsilon: float=1e-06) -> Rot3Array: if normalize: inv_norm = jax.lax.rsqrt(jnp.maximum(epsilon, w ** 2 + x ** 2 + y ** 2 + z ** 2)) w *= inv_norm x *= inv_norm y *= inv_norm...
['def', 'from_quaternion(cls,', 'w:', 'jnp.ndarray,', 'x:', 'jnp.ndarray,', 'y:', 'jnp.ndarray,', 'z:', 'jnp.ndarray,', 'normalize:', 'bool=True,', 'epsilon:', 'float=1e-06)', '->', 'Rot3Array:', 'if', 'normalize:', 'inv_norm', '=', 'jax.lax.rsqrt(jnp.maximum(epsilon,', 'w', '**', '2', '+', 'x', '**', '2', '+', 'y', '*...
400,752
openvinotoolkit/training_extensions
dino_layers.py
coordinate_to_encoding
coordinate_to_encoding
Convert coordinate tensor to positional encoding.
[ "Convert", "coordinate", "tensor", "to", "positional", "encoding." ]
def coordinate_to_encoding(coord_tensor: Tensor, num_feats: int=128, temperature: int=10000, scale: float=2 * math.pi): dim_t = torch.arange(num_feats, dtype=torch.float32, device=coord_tensor.device) dim_t = temperature ** (2 * (dim_t // 2) / num_feats) x_embed = coord_tensor[..., 0] * scale y_embed = ...
['def', 'coordinate_to_encoding(coord_tensor:', 'Tensor,', 'num_feats:', 'int=128,', 'temperature:', 'int=10000,', 'scale:', 'float=2', '*', 'math.pi):', 'dim_t', '=', 'torch.arange(num_feats,', 'dtype=torch.float32,', 'device=coord_tensor.device)', 'dim_t', '=', 'temperature', '**', '(2', '*', '(dim_t', '//', '2)', '/...
918,181
caiiiac/Machine-Learning-with-Python
base.py
LinearRegression.residues_
residues_
Get the residues of the fitted model.
[ "Get", "the", "residues", "of", "the", "fitted", "model." ]
def residues_(self): return self._residues
['def', 'residues_(self):', 'return', 'self._residues']
720,871
jhultman/vision3d
refinement.py
RefinementLayer.build_mlp
build_mlp
TODO: Check if should use bias.
[ "TODO:", "Check", "if", "should", "use", "bias." ]
def build_mlp(self, cfg): channels = cfg.REFINEMENT.MLPS + [cfg.BOX_DOF + 1] mlp = MLP(channels, bias=True, bn=False, relu=[True, False]) return mlp
['def', 'build_mlp(self,', 'cfg):', 'channels', '=', 'cfg.REFINEMENT.MLPS', '+', '[cfg.BOX_DOF', '+', '1]', 'mlp', '=', 'MLP(channels,', 'bias=True,', 'bn=False,', 'relu=[True,', 'False])', 'return', 'mlp']
944,832
CosmiQ/solaris
evaluator_test.py
TestEvaluator.test_init_empty_geojson
test_init_empty_geojson
Test instantiation of Evaluator with an empty geojson file.
[ "Test", "instantiation", "of", "Evaluator", "with", "an", "empty", "geojson", "file." ]
def test_init_empty_geojson(self): base_instance = Evaluator(os.path.join(solaris.data.data_dir, 'empty.geojson')) expected_gdf = gpd.GeoDataFrame({'sindex': [], 'condition': [], 'geometry': []}) assert base_instance.ground_truth_GDF.equals(expected_gdf)
['def', 'test_init_empty_geojson(self):', 'base_instance', '=', 'Evaluator(os.path.join(solaris.data.data_dir,', "'empty.geojson'))", 'expected_gdf', '=', "gpd.GeoDataFrame({'sindex':", '[],', "'condition':", '[],', "'geometry':", '[]})', 'assert', 'base_instance.ground_truth_GDF.equals(expected_gdf)']
879,439
BMW-InnovationLab/BMW-Semantic--Training-GUI
base.py
KeyPointDataset.num_joints
num_joints
Dataset defined: number of joints provided.
[ "Dataset", "defined:", "number", "of", "joints", "provided." ]
def num_joints(self): return 0
['def', 'num_joints(self):', 'return', '0']
462,416
dibyaghosh/gcsl
hardware_tracker.py
HardwareTrackerComponent.set_state
set_state
Sets the tracker to the given initial state.
[ "Sets", "the", "tracker", "to", "the", "given", "initial", "state." ]
def set_state(self, state_groups: Dict[str, TrackerState]): origin_device_id = None device_positions = {} device_rotations = {} ignored_group_positions = [] for (group_name, state) in state_groups.items(): config = self.get_config(group_name) device_id = config.device_identifier ...
['def', 'set_state(self,', 'state_groups:', 'Dict[str,', 'TrackerState]):', 'origin_device_id', '=', 'None', 'device_positions', '=', '{}', 'device_rotations', '=', '{}', 'ignored_group_positions', '=', '[]', 'for', '(group_name,', 'state)', 'in', 'state_groups.items():', 'config', '=', 'self.get_config(group_name)', '...
201,802
IntelLabs/nlp-architect
tasks.py
WSCTask.get_summary_table
get_summary_table
Updates summary table with values associated with the saved click.
[ "Updates", "summary", "table", "with", "values", "associated", "with", "the", "saved", "click." ]
def get_summary_table(self, saved_click: pd.DataFrame) -> Dict[str, Union[str, int]]: selected_sentence = saved_click['sentence'] cols = ['span1', 'span2', 'acc', 'pred', 'target'] models_sentence_df = {} for (model_id, model_name) in zip(self.model_ids, self.model_names): sentence_df = self.map...
['def', 'get_summary_table(self,', 'saved_click:', 'pd.DataFrame)', '->', 'Dict[str,', 'Union[str,', 'int]]:', 'selected_sentence', '=', "saved_click['sentence']", 'cols', '=', "['span1',", "'span2',", "'acc',", "'pred',", "'target']", 'models_sentence_df', '=', '{}', 'for', '(model_id,', 'model_name)', 'in', 'zip(self...
783,547
JIA-HONG-CHU/Swin-Transformer-add-EncNet-DaNet-DraNet-for---on-Statelite-Dataset
da_head.py
DAHead.forward_test
forward_test
Forward function for testing, only ``pam_cam`` is used.
[ "Forward", "function", "for", "testing,", "only", "``pam_cam``", "is", "used." ]
def forward_test(self, inputs, img_metas, test_cfg): return self.forward(inputs)[0]
['def', 'forward_test(self,', 'inputs,', 'img_metas,', 'test_cfg):', 'return', 'self.forward(inputs)[0]']
905,587
google-research/scenic
k600_mtv_b2_cva.py
get_config
get_config
Returns the base experiment configuration.
[ "Returns", "the", "base", "experiment", "configuration." ]
def get_config(): config = ml_collections.ConfigDict() config.experiment_name = f'k600_mtv_{MODEL_VARIANT}' config.dataset_name = 'video_tfrecord_dataset' config.dataset_configs = ml_collections.ConfigDict() config.dataset_configs.base_dir = '/path/to/dataset' config.dataset_configs.tables = {'t...
['def', 'get_config():', 'config', '=', 'ml_collections.ConfigDict()', 'config.experiment_name', '=', "f'k600_mtv_{MODEL_VARIANT}'", 'config.dataset_name', '=', "'video_tfrecord_dataset'", 'config.dataset_configs', '=', 'ml_collections.ConfigDict()', 'config.dataset_configs.base_dir', '=', "'/path/to/dataset'", 'config...
847,071
PaddlePaddle/PaddleSpeech
util.py
ConfigCache.flush
flush
Flush the current configuration into the configuration file.
[ "Flush", "the", "current", "configuration", "into", "the", "configuration", "file." ]
def flush(self): with open(self.file, 'w') as file: cfg = json.loads(json.dumps(self._data)) yaml.dump(cfg, file)
['def', 'flush(self):', 'with', 'open(self.file,', "'w')", 'as', 'file:', 'cfg', '=', 'json.loads(json.dumps(self._data))', 'yaml.dump(cfg,', 'file)']
277,027
vturrisi/solo-learn
base.py
BaseMomentumMethod.on_train_batch_end
on_train_batch_end
Performs the momentum update of momentum pairs using exponential moving average at the end of the current training step if an optimizer step was performed.
[ "Performs", "the", "momentum", "update", "of", "momentum", "pairs", "using", "exponential", "moving", "average", "at", "the", "end", "of", "the", "current", "training", "step", "if", "an", "optimizer", "step", "was", "performed." ]
def on_train_batch_end(self, outputs: Dict[str, Any], batch: Sequence[Any], batch_idx: int): if self.trainer.global_step > self.last_step: momentum_pairs = self.momentum_pairs for mp in momentum_pairs: self.momentum_updater.update(*mp) self.log('tau', self.momentum_updater.cur_ta...
['def', 'on_train_batch_end(self,', 'outputs:', 'Dict[str,', 'Any],', 'batch:', 'Sequence[Any],', 'batch_idx:', 'int):', 'if', 'self.trainer.global_step', '>', 'self.last_step:', 'momentum_pairs', '=', 'self.momentum_pairs', 'for', 'mp', 'in', 'momentum_pairs:', 'self.momentum_updater.update(*mp)', "self.log('tau',", '...
393,599
dongliangcao/Self-Supervised-Multimodal-Shape-Matching
misc.py
sizeof_fmt
sizeof_fmt
Get human readable file size.
[ "Get", "human", "readable", "file", "size." ]
def sizeof_fmt(size, suffix='B'): for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(size) < 1024.0: return f'{size:3.1f} {unit}{suffix}' size /= 1024.0 return f'{size:3.1f} Y{suffix}'
['def', 'sizeof_fmt(size,', "suffix='B'):", 'for', 'unit', 'in', "['B',", "'K',", "'M',", "'G',", "'T',", "'P',", "'E',", "'Z']:", 'if', 'abs(size)', '<', '1024.0:', 'return', "f'{size:3.1f}", "{unit}{suffix}'", 'size', '/=', '1024.0', 'return', "f'{size:3.1f}", "Y{suffix}'"]
342,156
AEProgrammer/object_detection
image.py
aspect_ratio_rel
aspect_ratio_rel
Performs width-relative aspect ratio transformation.
[ "Performs", "width-relative", "aspect", "ratio", "transformation." ]
def aspect_ratio_rel(im, aspect_ratio): (im_h, im_w) = im.shape[:2] im_ar_w = int(round(aspect_ratio * im_w)) im_ar = cv2.resize(im, dsize=(im_ar_w, im_h)) return im_ar
['def', 'aspect_ratio_rel(im,', 'aspect_ratio):', '(im_h,', 'im_w)', '=', 'im.shape[:2]', 'im_ar_w', '=', 'int(round(aspect_ratio', '*', 'im_w))', 'im_ar', '=', 'cv2.resize(im,', 'dsize=(im_ar_w,', 'im_h))', 'return', 'im_ar']
773,337
paulorauber/rl
utils.py
make_composite_from_td
make_composite_from_td
Creates a CompositeSpec instance from a tensordict, assuming all values are unbounded.
[ "Creates", "a", "CompositeSpec", "instance", "from", "a", "tensordict,", "assuming", "all", "values", "are", "unbounded." ]
def make_composite_from_td(data): from torchrl.data import CompositeSpec, UnboundedContinuousTensorSpec composite = CompositeSpec({key: make_composite_from_td(tensor) if isinstance(tensor, TensorDictBase) else UnboundedContinuousTensorSpec(dtype=tensor.dtype, device=tensor.device, shape=tensor.shape if tensor.s...
['def', 'make_composite_from_td(data):', 'from', 'torchrl.data', 'import', 'CompositeSpec,', 'UnboundedContinuousTensorSpec', 'composite', '=', 'CompositeSpec({key:', 'make_composite_from_td(tensor)', 'if', 'isinstance(tensor,', 'TensorDictBase)', 'else', 'UnboundedContinuousTensorSpec(dtype=tensor.dtype,', 'device=ten...
859,031
bryanvriel/pgan
structures.py
train_test_indices
train_test_indices
Convenience function to get train/test splits.
[ "Convenience", "function", "to", "get", "train/test", "splits." ]
def train_test_indices(N, train_fraction=0.9, shuffle=True, rng=None): n_train = int(np.floor(train_fraction * N)) if shuffle: assert rng is not None, 'Must pass in a random number generator' ind = rng.permutation(N) else: ind = np.arange(N, dtype=int) ind_train = ind[:n_train] ...
['def', 'train_test_indices(N,', 'train_fraction=0.9,', 'shuffle=True,', 'rng=None):', 'n_train', '=', 'int(np.floor(train_fraction', '*', 'N))', 'if', 'shuffle:', 'assert', 'rng', 'is', 'not', 'None,', "'Must", 'pass', 'in', 'a', 'random', 'number', "generator'", 'ind', '=', 'rng.permutation(N)', 'else:', 'ind', '=', ...
767,636
JahJajaka/afternoon_cleaner
s3dg.py
s3dg_arg_scope
s3dg_arg_scope
Defines default arg_scope for S3D-G.
[ "Defines", "default", "arg_scope", "for", "S3D-G." ]
def s3dg_arg_scope(weight_decay=1e-07, batch_norm_decay=0.999, batch_norm_epsilon=0.001): batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'fused': False, 'variables_collections': {'beta': None, 'gamma': None, 'moving_mean': ['moving_vars'], 'moving_variance': ['moving_vars']}} wit...
['def', 's3dg_arg_scope(weight_decay=1e-07,', 'batch_norm_decay=0.999,', 'batch_norm_epsilon=0.001):', 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'fused':", 'False,', "'variables_collections':", "{'beta':", 'None,', "'gamma':", 'None,', "'moving_mean':", "['moving_...
411,305
salesforce/CodeRL
token_classification.py
TokenClassificationPipeline.group_entities
group_entities
Find and group together the adjacent tokens with the same entity predicted.
[ "Find", "and", "group", "together", "the", "adjacent", "tokens", "with", "the", "same", "entity", "predicted." ]
def group_entities(self, entities: List[dict]) -> List[dict]: entity_groups = [] entity_group_disagg = [] for entity in entities: if not entity_group_disagg: entity_group_disagg.append(entity) continue (bi, tag) = self.get_tag(entity['entity']) (last_bi, last_...
['def', 'group_entities(self,', 'entities:', 'List[dict])', '->', 'List[dict]:', 'entity_groups', '=', '[]', 'entity_group_disagg', '=', '[]', 'for', 'entity', 'in', 'entities:', 'if', 'not', 'entity_group_disagg:', 'entity_group_disagg.append(entity)', 'continue', '(bi,', 'tag)', '=', "self.get_tag(entity['entity'])",...
495,583
sunishsheth2009/ChatterBot
sourcedstring.py
SourcedStringStream.closed
closed
True if the underlying stream is closed.
[ "True", "if", "the", "underlying", "stream", "is", "closed." ]
def closed(self): return self.stream.closed
['def', 'closed(self):', 'return', 'self.stream.closed']
527,338
QData/deepWordBug
math2html.py
ContainerExtractor.safeclone
safeclone
Return a new container with contents only in a safe list, recursively.
[ "Return", "a", "new", "container", "with", "contents", "only", "in", "a", "safe", "list,", "recursively." ]
def safeclone(self, container): clone = Cloner.clone(container) clone.output = container.output clone.contents = self.extract(container) return clone
['def', 'safeclone(self,', 'container):', 'clone', '=', 'Cloner.clone(container)', 'clone.output', '=', 'container.output', 'clone.contents', '=', 'self.extract(container)', 'return', 'clone']
542,342
feast-dev/feast
test_dynamodb_online_store.py
test_dynamodb_online_store_config_default
test_dynamodb_online_store_config_default
Test DynamoDBOnlineStoreConfig default parameters.
[ "Test", "DynamoDBOnlineStoreConfig", "default", "parameters." ]
def test_dynamodb_online_store_config_default(): aws_region = 'us-west-2' dynamodb_store_config = DynamoDBOnlineStoreConfig(region=aws_region) assert dynamodb_store_config.type == 'dynamodb' assert dynamodb_store_config.batch_size == 40 assert dynamodb_store_config.endpoint_url is None assert dy...
['def', 'test_dynamodb_online_store_config_default():', 'aws_region', '=', "'us-west-2'", 'dynamodb_store_config', '=', 'DynamoDBOnlineStoreConfig(region=aws_region)', 'assert', 'dynamodb_store_config.type', '==', "'dynamodb'", 'assert', 'dynamodb_store_config.batch_size', '==', '40', 'assert', 'dynamodb_store_config.e...
544,626
Ruturaj123/Flowchart-Detection
problem_generator.py
SoftmaxClassifier.argmax
argmax
Samples the most likely class label given the logits.
[ "Samples", "the", "most", "likely", "class", "label", "given", "the", "logits." ]
def argmax(self, logits): return tf.cast(tf.argmax(tf.nn.softmax(logits), 1), tf.int32)
['def', 'argmax(self,', 'logits):', 'return', 'tf.cast(tf.argmax(tf.nn.softmax(logits),', '1),', 'tf.int32)']
585,787
enuguru/artificial_intelligence_and_machine_
tbtools.py
Traceback.render_summary
render_summary
Render the traceback for the interactive console.
[ "Render", "the", "traceback", "for", "the", "interactive", "console." ]
def render_summary(self, include_title=True): title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error: title = u'Syntax Error' else: title = u'Traceback <em>(most ...
['def', 'render_summary(self,', 'include_title=True):', 'title', '=', "''", 'frames', '=', '[]', 'classes', '=', "['traceback']", 'if', 'not', 'self.frames:', "classes.append('noframe-traceback')", 'if', 'include_title:', 'if', 'self.is_syntax_error:', 'title', '=', "u'Syntax", "Error'", 'else:', 'title', '=', "u'Trace...
132,771
weimin17/Object-Detection_HelmetDetection
seq2seq_vd.py
gen_encoder_cnn
gen_encoder_cnn
Define the CNN Encoder graph.
[ "Define", "the", "CNN", "Encoder", "graph." ]
def gen_encoder_cnn(hparams, inputs, targets_present, is_training, reuse=None): del reuse sequence = transform_input_with_is_missing_token(inputs, targets_present) dis_filter_sizes = [3, 4, 5, 6, 7, 8, 9, 10, 15, 20] with tf.variable_scope('encoder', reuse=True): with tf.variable_scope('rnn'): ...
['def', 'gen_encoder_cnn(hparams,', 'inputs,', 'targets_present,', 'is_training,', 'reuse=None):', 'del', 'reuse', 'sequence', '=', 'transform_input_with_is_missing_token(inputs,', 'targets_present)', 'dis_filter_sizes', '=', '[3,', '4,', '5,', '6,', '7,', '8,', '9,', '10,', '15,', '20]', 'with', "tf.variable_scope('en...
758,005
rishab-sharma/object_detection
model.py
ObjectDetector.build_basic_resnet101
build_basic_resnet101
Build the basic ResNet101 net.
[ "Build", "the", "basic", "ResNet101", "net." ]
def build_basic_resnet101(self): print('Building the basic ResNet101 net...') bn = self.batch_norm imgs = tf.placeholder(tf.float32, [self.batch_size] + self.img_shape) is_train = tf.placeholder(tf.bool) conv1_feats = convolution(imgs, 7, 7, 64, 2, 2, 'conv1') conv1_feats = batch_norm(conv1_feat...
['def', 'build_basic_resnet101(self):', "print('Building", 'the', 'basic', 'ResNet101', "net...')", 'bn', '=', 'self.batch_norm', 'imgs', '=', 'tf.placeholder(tf.float32,', '[self.batch_size]', '+', 'self.img_shape)', 'is_train', '=', 'tf.placeholder(tf.bool)', 'conv1_feats', '=', 'convolution(imgs,', '7,', '7,', '64,'...
745,092
Ruturaj123/Flowchart-Detection
lookup_ops.py
IdTableWithHashBuckets.init
init
The table initialization op.
[ "The", "table", "initialization", "op." ]
def init(self): if self._table: return self._table.init with ops.name_scope(None, 'init'): return control_flow_ops.no_op()
['def', 'init(self):', 'if', 'self._table:', 'return', 'self._table.init', 'with', 'ops.name_scope(None,', "'init'):", 'return', 'control_flow_ops.no_op()']
605,958
weimin17/Object-Detection_HelmetDetection
inputs.py
inputs
inputs
Inputs for text model.
[ "Inputs", "for", "text", "model." ]
def inputs(data_dir=None, phase='train', bidir=False, pretrain=False, use_seq2seq=False, state_name='lstm', state_size=None, num_layers=0, batch_size=32, unroll_steps=100, eos_id=None): with tf.name_scope('inputs'): filenames = _filenames_for_data_spec(phase, bidir, pretrain, use_seq2seq) if bidir a...
['def', 'inputs(data_dir=None,', "phase='train',", 'bidir=False,', 'pretrain=False,', 'use_seq2seq=False,', "state_name='lstm',", 'state_size=None,', 'num_layers=0,', 'batch_size=32,', 'unroll_steps=100,', 'eos_id=None):', 'with', "tf.name_scope('inputs'):", 'filenames', '=', '_filenames_for_data_spec(phase,', 'bidir,'...
761,475
NREL/sup3r
test_train_gan_exo.py
test_wind_hi_res_topo
test_wind_hi_res_topo
Test a special wind cc model with the custom Sup3rAdder or Sup3rConcat layer that adds/concatenates hi-res topography in the middle of the network.
[ "Test", "a", "special", "wind", "cc", "model", "with", "the", "custom", "Sup3rAdder", "or", "Sup3rConcat", "layer", "that", "adds/concatenates", "hi-res", "topography", "in", "the", "middle", "of", "the", "network." ]
def test_wind_hi_res_topo(custom_layer, log=False): handler = DataHandlerH5WindCC(INPUT_FILE_W, ('U_100m', 'V_100m', 'topography'), target=TARGET_W, shape=SHAPE, temporal_slice=slice(None, None, 2), time_roll=-7, val_split=0.1, sample_shape=(20, 20), worker_kwargs=dict(max_workers=1), train_only_features=()) ba...
['def', 'test_wind_hi_res_topo(custom_layer,', 'log=False):', 'handler', '=', 'DataHandlerH5WindCC(INPUT_FILE_W,', "('U_100m',", "'V_100m',", "'topography'),", 'target=TARGET_W,', 'shape=SHAPE,', 'temporal_slice=slice(None,', 'None,', '2),', 'time_roll=-7,', 'val_split=0.1,', 'sample_shape=(20,', '20),', 'worker_kwargs...
912,865
Trusted-AI/AIF360
gerryfair_classifier.py
GerryFairClassifier.fit
fit
Run Fictitious play to compute the approximately fair classifier.
[ "Run", "Fictitious", "play", "to", "compute", "the", "approximately", "fair", "classifier." ]
def fit(self, dataset, early_termination=True): (X, X_prime, y) = clean.extract_df_from_ds(dataset) learner = Learner(X, y, self.predictor) auditor = Auditor(dataset, self.fairness_def) history = ClassifierHistory() n = X.shape[0] (costs_0, costs_1, X_0) = auditor.initialize_costs(n) metric_...
['def', 'fit(self,', 'dataset,', 'early_termination=True):', '(X,', 'X_prime,', 'y)', '=', 'clean.extract_df_from_ds(dataset)', 'learner', '=', 'Learner(X,', 'y,', 'self.predictor)', 'auditor', '=', 'Auditor(dataset,', 'self.fairness_def)', 'history', '=', 'ClassifierHistory()', 'n', '=', 'X.shape[0]', '(costs_0,', 'co...
412,184
reevesAstronomy/Neural-Network
read_data.py
to_object
to_object
Converts hot coded array into an array of Samples, an encapsulation of training/testing data.
[ "Converts", "hot", "coded", "array", "into", "an", "array", "of", "Samples,", "an", "encapsulation", "of", "training/testing", "data." ]
def to_object(data): sample_arr = [] for i in range(len(data)): sample_arr.append(Sample(data[i][0], data[i][1])) return sample_arr
['def', 'to_object(data):', 'sample_arr', '=', '[]', 'for', 'i', 'in', 'range(len(data)):', 'sample_arr.append(Sample(data[i][0],', 'data[i][1]))', 'return', 'sample_arr']
721,987
greydanus/mr_london
itsdangerous.py
Signer.verify_signature
verify_signature
Verifies the signature for the given value.
[ "Verifies", "the", "signature", "for", "the", "given", "value." ]
def verify_signature(self, value, sig): key = self.derive_key() try: sig = base64_decode(sig) except Exception: return False return self.algorithm.verify_signature(key, value, sig)
['def', 'verify_signature(self,', 'value,', 'sig):', 'key', '=', 'self.derive_key()', 'try:', 'sig', '=', 'base64_decode(sig)', 'except', 'Exception:', 'return', 'False', 'return', 'self.algorithm.verify_signature(key,', 'value,', 'sig)']
241,796
facebookresearch/dmae_st
mixup.py
mixup_target
mixup_target
This function converts target class indices to one-hot vectors, given the number of classes.
[ "This", "function", "converts", "target", "class", "indices", "to", "one-hot", "vectors,", "given", "the", "number", "of", "classes." ]
def mixup_target(target, num_classes, lam=1.0, smoothing=0.0): off_value = smoothing / num_classes on_value = 1.0 - smoothing + off_value target1 = convert_to_one_hot(target, num_classes, on_value=on_value, off_value=off_value) target2 = convert_to_one_hot(target.flip(0), num_classes, on_value=on_value,...
['def', 'mixup_target(target,', 'num_classes,', 'lam=1.0,', 'smoothing=0.0):', 'off_value', '=', 'smoothing', '/', 'num_classes', 'on_value', '=', '1.0', '-', 'smoothing', '+', 'off_value', 'target1', '=', 'convert_to_one_hot(target,', 'num_classes,', 'on_value=on_value,', 'off_value=off_value)', 'target2', '=', 'conve...
522,016
PaddlePaddle/Paddle3D
transformer.py
PerceptionTransformer.init_weights
init_weights
Initialize the transformer weights.
[ "Initialize", "the", "transformer", "weights." ]
def init_weights(self): normal_init(self.level_embeds) normal_init(self.cams_embeds) xavier_uniform_init(self.reference_points.weight, reverse=True) constant_init(self.reference_points.bias, value=0) for layer in self.can_bus_mlp: if isinstance(layer, nn.Linear): reset_parameters...
['def', 'init_weights(self):', 'normal_init(self.level_embeds)', 'normal_init(self.cams_embeds)', 'xavier_uniform_init(self.reference_points.weight,', 'reverse=True)', 'constant_init(self.reference_points.bias,', 'value=0)', 'for', 'layer', 'in', 'self.can_bus_mlp:', 'if', 'isinstance(layer,', 'nn.Linear):', 'reset_par...
777,855
arshpreetsingh/quantopian-machinelearning
completion_html.py
CompletionHtml.eventFilter
eventFilter
Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus.
[ "Reimplemented", "to", "handle", "keyboard", "input", "and", "to", "auto-hide", "when", "the", "text", "edit", "loses", "focus." ]
def eventFilter(self, obj, event): if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if self._consecutive_tab == 0 and key in (QtCore.Qt.Key_Tab,): return False elif self._consecutive_tab == 1 and...
['def', 'eventFilter(self,', 'obj,', 'event):', 'if', 'obj', '==', 'self._text_edit:', 'etype', '=', 'event.type()', 'if', 'etype', '==', 'QtCore.QEvent.KeyPress:', 'key', '=', 'event.key()', 'if', 'self._consecutive_tab', '==', '0', 'and', 'key', 'in', '(QtCore.Qt.Key_Tab,):', 'return', 'False', 'elif', 'self._consecu...
892,838
openvinotoolkit/training_extensions
test_torchvision2mmdet.py
TestNDArrayToTensor.test_ndarray_to_tensor_with_single_channel_image
test_ndarray_to_tensor_with_single_channel_image
Test NDArrayToTensor with a single channel image.
[ "Test", "NDArrayToTensor", "with", "a", "single", "channel", "image." ]
def test_ndarray_to_tensor_with_single_channel_image(self, data: dict[str, np.ndarray]) -> None: pipeline = NDArrayToTensor(keys=['img']) output = pipeline(data) assert output['img'].shape == (3, 256, 256) assert isinstance(output['img'], torch.Tensor)
['def', 'test_ndarray_to_tensor_with_single_channel_image(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'pipeline', '=', "NDArrayToTensor(keys=['img'])", 'output', '=', 'pipeline(data)', 'assert', "output['img'].shape", '==', '(3,', '256,', '256)', 'assert', "isinstance(output['img'],", 'torch.Tensor)']
919,320
Liuyubao/transfer-learning
hf_dataset.py
HFDataset.preprocess
preprocess
Preprocess the textual dataset to apply padding, truncation and tokenize.
[ "Preprocess", "the", "textual", "dataset", "to", "apply", "padding,", "truncation", "and", "tokenize." ]
def preprocess(self, model_name: str, batch_size: int=32, padding: str='max_length', truncation: bool=True, max_length: int=64, **kwargs) -> None: if not isinstance(batch_size, int) or batch_size < 1: raise ValueError('batch_size should be an positive integer') if self._preprocessed: raise Value...
['def', 'preprocess(self,', 'model_name:', 'str,', 'batch_size:', 'int=32,', 'padding:', "str='max_length',", 'truncation:', 'bool=True,', 'max_length:', 'int=64,', '**kwargs)', '->', 'None:', 'if', 'not', 'isinstance(batch_size,', 'int)', 'or', 'batch_size', '<', '1:', 'raise', "ValueError('batch_size", 'should', 'be'...
927,589
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
neural_gpu_trainer.py
calculate_buckets_scale
calculate_buckets_scale
Calculate buckets scales for the given data set.
[ "Calculate", "buckets", "scales", "for", "the", "given", "data", "set." ]
def calculate_buckets_scale(data_set, buckets, problem): train_bucket_sizes = [len(data_set[b]) for b in xrange(len(buckets))] train_total_size = max(1, float(sum(train_bucket_sizes))) if problem not in train_buckets_scale: train_buckets_scale[problem] = [] train_buckets_scale[problem].append([s...
['def', 'calculate_buckets_scale(data_set,', 'buckets,', 'problem):', 'train_bucket_sizes', '=', '[len(data_set[b])', 'for', 'b', 'in', 'xrange(len(buckets))]', 'train_total_size', '=', 'max(1,', 'float(sum(train_bucket_sizes)))', 'if', 'problem', 'not', 'in', 'train_buckets_scale:', 'train_buckets_scale[problem]', '='...
56,405
openkinome/kinoml
test_oedocking.py
test_resids_to_box_molecule
test_resids_to_box_molecule
Compare results to expected minimal x_coordinate.
[ "Compare", "results", "to", "expected", "minimal", "x_coordinate." ]
def test_resids_to_box_molecule(package, resource, resids, expectation, min_x): from kinoml.modeling.OEModeling import read_molecules from kinoml.docking.OEDocking import resids_to_box_molecule with resources.path(package, resource) as path: with expectation: protein = read_molecules(str...
['def', 'test_resids_to_box_molecule(package,', 'resource,', 'resids,', 'expectation,', 'min_x):', 'from', 'kinoml.modeling.OEModeling', 'import', 'read_molecules', 'from', 'kinoml.docking.OEDocking', 'import', 'resids_to_box_molecule', 'with', 'resources.path(package,', 'resource)', 'as', 'path:', 'with', 'expectation...
596,254
43Carrig/recurrent_neural_networks_practice
debug.py
DebugRegressor.predict_scores
predict_scores
Returns predicted scores for given features.
[ "Returns", "predicted", "scores", "for", "given", "features." ]
def predict_scores(self, input_fn=None, batch_size=None): key = prediction_key.PredictionKey.SCORES preds = self.predict(input_fn=input_fn, batch_size=batch_size, outputs=[key]) return (pred[key] for pred in preds)
['def', 'predict_scores(self,', 'input_fn=None,', 'batch_size=None):', 'key', '=', 'prediction_key.PredictionKey.SCORES', 'preds', '=', 'self.predict(input_fn=input_fn,', 'batch_size=batch_size,', 'outputs=[key])', 'return', '(pred[key]', 'for', 'pred', 'in', 'preds)']
313,592
neokarn/computer_vision
utility.py
str_count
str_count
Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters.
[ "Count", "the", "number", "of", "Chinese", "characters,", "a", "single", "English", "character", "and", "a", "single", "number", "equal", "to", "half", "the", "length", "of", "Chinese", "characters." ]
def str_count(s): import string count_zh = count_pu = 0 s_len = len(s) en_dg_count = 0 for c in s: if c in string.ascii_letters or c.isdigit() or c.isspace(): en_dg_count += 1 elif c.isalpha(): count_zh += 1 else: count_pu += 1 return s...
['def', 'str_count(s):', 'import', 'string', 'count_zh', '=', 'count_pu', '=', '0', 's_len', '=', 'len(s)', 'en_dg_count', '=', '0', 'for', 'c', 'in', 's:', 'if', 'c', 'in', 'string.ascii_letters', 'or', 'c.isdigit()', 'or', 'c.isspace():', 'en_dg_count', '+=', '1', 'elif', 'c.isalpha():', 'count_zh', '+=', '1', 'else:...
474,811
devashish-patel/webcam-motion-detector
__init__.py
load_all
load_all
Parse all YAML documents in a stream and produce corresponding Python objects.
[ "Parse", "all", "YAML", "documents", "in", "a", "stream", "and", "produce", "corresponding", "Python", "objects." ]
def load_all(stream, Loader=Loader): loader = Loader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
['def', 'load_all(stream,', 'Loader=Loader):', 'loader', '=', 'Loader(stream)', 'try:', 'while', 'loader.check_data():', 'yield', 'loader.get_data()', 'finally:', 'loader.dispose()']
985,407
TrellixVulnTeam/Unsupervised_Learning_HFI7
axes_grid.py
Grid.get_aspect
get_aspect
Return the aspect of the SubplotDivider.
[ "Return", "the", "aspect", "of", "the", "SubplotDivider." ]
def get_aspect(self): return self._divider.get_aspect()
['def', 'get_aspect(self):', 'return', 'self._divider.get_aspect()']
451,526
bnpy/bnpy
DPMixtureModel.py
calcELBOGain_NonlinearTerms
calcELBOGain_NonlinearTerms
Compute gain in ELBO score by transition from before to after values.
[ "Compute", "gain", "in", "ELBO", "score", "by", "transition", "from", "before", "to", "after", "values." ]
def calcELBOGain_NonlinearTerms(beforeSS=None, afterSS=None): L_before = beforeSS.getELBOTerm('Hresp').sum() L_after = afterSS.getELBOTerm('Hresp').sum() return L_after - L_before
['def', 'calcELBOGain_NonlinearTerms(beforeSS=None,', 'afterSS=None):', 'L_before', '=', "beforeSS.getELBOTerm('Hresp').sum()", 'L_after', '=', "afterSS.getELBOTerm('Hresp').sum()", 'return', 'L_after', '-', 'L_before']
464,173
uber/causalml
synthetic.py
bar_plot_summary
bar_plot_summary
Generates a bar plot comparing learner performance.
[ "Generates", "a", "bar", "plot", "comparing", "learner", "performance." ]
def bar_plot_summary(synthetic_summary, k, drop_learners=[], drop_cols=[], sort_cols=['MSE', 'Abs % Error of ATE']): plot_data = synthetic_summary.sort_values(sort_cols, ascending=True) plot_data = plot_data.drop(drop_learners + [KEY_ACTUAL]).drop(drop_cols, axis=1) plot_data.plot(kind='bar', figsize=(12, 8...
['def', 'bar_plot_summary(synthetic_summary,', 'k,', 'drop_learners=[],', 'drop_cols=[],', "sort_cols=['MSE',", "'Abs", '%', 'Error', 'of', "ATE']):", 'plot_data', '=', 'synthetic_summary.sort_values(sort_cols,', 'ascending=True)', 'plot_data', '=', 'plot_data.drop(drop_learners', '+', '[KEY_ACTUAL]).drop(drop_cols,', ...
456,399
43Carrig/recurrent_neural_networks_practice
learning.py
train_step
train_step
Function that takes a gradient step and specifies whether to stop.
[ "Function", "that", "takes", "a", "gradient", "step", "and", "specifies", "whether", "to", "stop." ]
def train_step(sess, train_op, global_step, train_step_kwargs): start_time = time.time() trace_run_options = None run_metadata = None if 'should_trace' in train_step_kwargs: if 'logdir' not in train_step_kwargs: raise ValueError('logdir must be present in train_step_kwargs when shoul...
['def', 'train_step(sess,', 'train_op,', 'global_step,', 'train_step_kwargs):', 'start_time', '=', 'time.time()', 'trace_run_options', '=', 'None', 'run_metadata', '=', 'None', 'if', "'should_trace'", 'in', 'train_step_kwargs:', 'if', "'logdir'", 'not', 'in', 'train_step_kwargs:', 'raise', "ValueError('logdir", 'must',...
335,195
ylsung/VL_adapter
adapter_controller.py
MetaLayersAdapterController.apply_layer_norm
apply_layer_norm
Applies layer norm to the inputs.
[ "Applies", "layer", "norm", "to", "the", "inputs." ]
def apply_layer_norm(self, inputs, layer_norm_weights): return torch.nn.functional.layer_norm(inputs, (self.input_dim,), weight=layer_norm_weights.weight, bias=layer_norm_weights.bias)
['def', 'apply_layer_norm(self,', 'inputs,', 'layer_norm_weights):', 'return', 'torch.nn.functional.layer_norm(inputs,', '(self.input_dim,),', 'weight=layer_norm_weights.weight,', 'bias=layer_norm_weights.bias)']
946,053
triaquae/triaquae
test_geos.py
GEOSTest.test_emptyCollections
test_emptyCollections
Testing empty geometries and collections.
[ "Testing", "empty", "geometries", "and", "collections." ]
def test_emptyCollections(self): gc1 = GeometryCollection([]) gc2 = fromstr('GEOMETRYCOLLECTION EMPTY') pnt = fromstr('POINT EMPTY') ls = fromstr('LINESTRING EMPTY') poly = fromstr('POLYGON EMPTY') mls = fromstr('MULTILINESTRING EMPTY') mpoly1 = fromstr('MULTIPOLYGON EMPTY') mpoly2 = Mul...
['def', 'test_emptyCollections(self):', 'gc1', '=', 'GeometryCollection([])', 'gc2', '=', "fromstr('GEOMETRYCOLLECTION", "EMPTY')", 'pnt', '=', "fromstr('POINT", "EMPTY')", 'ls', '=', "fromstr('LINESTRING", "EMPTY')", 'poly', '=', "fromstr('POLYGON", "EMPTY')", 'mls', '=', "fromstr('MULTILINESTRING", "EMPTY')", 'mpoly1...
357,890
ForrestPi/ObjectDetectionTricks
cubic_spline_test.py
TestCubicSpline.testInterpolationPreservesDtype
testInterpolationPreservesDtype
Check that interpolating at a knot produces the value at that knot.
[ "Check", "that", "interpolating", "at", "a", "knot", "produces", "the", "value", "at", "that", "knot." ]
def testInterpolationPreservesDtype(self, float_dtype, device): n = 16 x = float_dtype(np.random.normal(size=n)) values = float_dtype(np.random.normal(size=n)) tangents = float_dtype(np.random.normal(size=n)) y = self._interpolate1d(x, values, tangents, float_dtype, device)[0] np.testing.assert_...
['def', 'testInterpolationPreservesDtype(self,', 'float_dtype,', 'device):', 'n', '=', '16', 'x', '=', 'float_dtype(np.random.normal(size=n))', 'values', '=', 'float_dtype(np.random.normal(size=n))', 'tangents', '=', 'float_dtype(np.random.normal(size=n))', 'y', '=', 'self._interpolate1d(x,', 'values,', 'tangents,', 'f...
744,681
weimin17/Object-Detection_HelmetDetection
registry_test.py
RegistryTest.testCanCreateImpl
testCanCreateImpl
Tests that Create can create the Impl subclass.
[ "Tests", "that", "Create", "can", "create", "the", "Impl", "subclass." ]
def testCanCreateImpl(self): try: impl = registry_test_base.Base.Create(PATH + 'registry_test_impl.Impl', 'hello world') except ValueError: self.fail('Create raised ValueError: %s' % traceback.format_exc()) self.assertEqual('hello world', impl.Get())
['def', 'testCanCreateImpl(self):', 'try:', 'impl', '=', 'registry_test_base.Base.Create(PATH', '+', "'registry_test_impl.Impl',", "'hello", "world')", 'except', 'ValueError:', "self.fail('Create", 'raised', 'ValueError:', "%s'", '%', 'traceback.format_exc())', "self.assertEqual('hello", "world',", 'impl.Get())']
760,477
enuguru/artificial_intelligence_and_machine_
html.py
HtmlStatus.write
write
Write the current status to `directory`.
[ "Write", "the", "current", "status", "to", "`directory`." ]
def write(self, directory): status_file = os.path.join(directory, self.STATUS_FILE) files = {} for (filename, fileinfo) in iitems(self.files): fileinfo['index']['nums'] = fileinfo['index']['nums'].init_args() files[filename] = fileinfo status = {'format': self.STATUS_FORMAT, 'version': c...
['def', 'write(self,', 'directory):', 'status_file', '=', 'os.path.join(directory,', 'self.STATUS_FILE)', 'files', '=', '{}', 'for', '(filename,', 'fileinfo)', 'in', 'iitems(self.files):', "fileinfo['index']['nums']", '=', "fileinfo['index']['nums'].init_args()", 'files[filename]', '=', 'fileinfo', 'status', '=', "{'fo...
157,458