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 |
|---|---|---|---|---|---|---|---|---|
supervisely/supervisely | annotation_transforms.py | drop_object_by_class | drop_object_by_class | Removes labels of specified classes from annotation. | [
"Removes",
"labels",
"of",
"specified",
"classes",
"from",
"annotation."
] | def drop_object_by_class(ann: Annotation, classes: List[str]) -> Annotation:
def _filter(label: Label):
if label.obj_class.name in classes:
return [label]
return []
return ann.transform_labels(_filter) | ['def', 'drop_object_by_class(ann:', 'Annotation,', 'classes:', 'List[str])', '->', 'Annotation:', 'def', '_filter(label:', 'Label):', 'if', 'label.obj_class.name', 'in', 'classes:', 'return', '[label]', 'return', '[]', 'return', 'ann.transform_labels(_filter)'] | 881,054 |
alibaba-mmai-research/Masked-Action-Recognition | params.py | update_av_conv_params | update_av_conv_params | Automatically decodes parameters for 3D convolution blocks according to the config and its index in the model. | [
"Automatically",
"decodes",
"parameters",
"for",
"3D",
"convolution",
"blocks",
"according",
"to",
"the",
"config",
"and",
"its",
"index",
"in",
"the",
"model."
] | def update_av_conv_params(cfg, conv, idx):
(stage_id, block_id) = idx
conv.stage_id = stage_id
conv.block_id = block_id
if block_id == 0:
conv.dim_in = cfg.VIDEO.BACKBONE.NUM_FILTERS[stage_id - 1]
if hasattr(cfg.VIDEO.BACKBONE, 'ADD_FUSION_CHANNEL') and cfg.VIDEO.BACKBONE.ADD_FUSION_CHAN... | ['def', 'update_av_conv_params(cfg,', 'conv,', 'idx):', '(stage_id,', 'block_id)', '=', 'idx', 'conv.stage_id', '=', 'stage_id', 'conv.block_id', '=', 'block_id', 'if', 'block_id', '==', '0:', 'conv.dim_in', '=', 'cfg.VIDEO.BACKBONE.NUM_FILTERS[stage_id', '-', '1]', 'if', 'hasattr(cfg.VIDEO.BACKBONE,', "'ADD_FUSION_CHA... | 628,985 |
NuttareeB/NaturalLanguageProcessing | trigram_model.py | TrigramModel.sentence_logprob | sentence_logprob | COMPLETE THIS METHOD (PART 5) Returns the log probability of an entire sequence. | [
"COMPLETE",
"THIS",
"METHOD",
"(PART",
"5)",
"Returns",
"the",
"log",
"probability",
"of",
"an",
"entire",
"sequence."
] | def sentence_logprob(self, sentence):
trigrams = get_ngrams(sentence, 3)
log_probs = []
summ = 0
for tri in trigrams:
log_probs.append(self.smoothed_trigram_probability(tri))
for prob in log_probs:
summ += math.log2(prob)
return summ | ['def', 'sentence_logprob(self,', 'sentence):', 'trigrams', '=', 'get_ngrams(sentence,', '3)', 'log_probs', '=', '[]', 'summ', '=', '0', 'for', 'tri', 'in', 'trigrams:', 'log_probs.append(self.smoothed_trigram_probability(tri))', 'for', 'prob', 'in', 'log_probs:', 'summ', '+=', 'math.log2(prob)', 'return', 'summ'] | 677,522 |
scotthuang1989/object_detection_with_tensorflow | policy.py | Policy.sample_actions | sample_actions | Sample all actions given output of core network. | [
"Sample",
"all",
"actions",
"given",
"output",
"of",
"core",
"network."
] | def sample_actions(self, output, actions=None, greedy=False):
sampled_actions = []
logits = []
log_probs = []
entropy = []
self_kl = []
start_idx = 0
for (i, (act_dim, act_type)) in enumerate(self.env_spec.act_dims_and_types):
sampling_dim = self.env_spec.sampling_dim(act_dim, act_ty... | ['def', 'sample_actions(self,', 'output,', 'actions=None,', 'greedy=False):', 'sampled_actions', '=', '[]', 'logits', '=', '[]', 'log_probs', '=', '[]', 'entropy', '=', '[]', 'self_kl', '=', '[]', 'start_idx', '=', '0', 'for', '(i,', '(act_dim,', 'act_type))', 'in', 'enumerate(self.env_spec.act_dims_and_types):', 'samp... | 739,484 |
FahadTComsats/Natural-Language-Processing | evaluate.py | make_html_safe | make_html_safe | Replace any angled brackets in string s to avoid interfering with HTML attention visualizer. | [
"Replace",
"any",
"angled",
"brackets",
"in",
"string",
"s",
"to",
"avoid",
"interfering",
"with",
"HTML",
"attention",
"visualizer."
] | def make_html_safe(s):
s.replace('<', '<')
s.replace('>', '>')
return s | ['def', 'make_html_safe(s):', "s.replace('<',", "'<')", "s.replace('>',", "'>')", 'return', 's'] | 701,067 |
OpenMDAO/OpenMDAO-Framework | hasstopcond.py | HasStopConditions.eval_stop_conditions | eval_stop_conditions | Returns a list of evaluated stop conditions. | [
"Returns",
"a",
"list",
"of",
"evaluated",
"stop",
"conditions."
] | def eval_stop_conditions(self):
return [c.evaluate() for c in self._stop_conditions.values()] | ['def', 'eval_stop_conditions(self):', 'return', '[c.evaluate()', 'for', 'c', 'in', 'self._stop_conditions.values()]'] | 275,862 |
deepmind/meltingpot | reaction_graph_utils.py | create_compound | create_compound | Convert node attributes to dictionary structure needed for a compound. | [
"Convert",
"node",
"attributes",
"to",
"dictionary",
"structure",
"needed",
"for",
"a",
"compound."
] | def create_compound(attributes):
data = {'color': attributes.get('color', (0, 0, 0, 0)), 'properties': {'structure': attributes.get('structure', (0, 0))}}
for (k, v) in attributes.items():
data[k] = v
return data | ['def', 'create_compound(attributes):', 'data', '=', "{'color':", "attributes.get('color',", '(0,', '0,', '0,', '0)),', "'properties':", "{'structure':", "attributes.get('structure',", '(0,', '0))}}', 'for', '(k,', 'v)', 'in', 'attributes.items():', 'data[k]', '=', 'v', 'return', 'data'] | 285,445 |
PBarde/NaturalLanguageProcessing | models.py | subsequent_mask | subsequent_mask | helper function for creating the masks. | [
"helper",
"function",
"for",
"creating",
"the",
"masks."
] | def subsequent_mask(size):
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0 | ['def', 'subsequent_mask(size):', 'attn_shape', '=', '(1,', 'size,', 'size)', 'subsequent_mask', '=', 'np.triu(np.ones(attn_shape),', "k=1).astype('uint8')", 'return', 'torch.from_numpy(subsequent_mask)', '==', '0'] | 672,707 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | _collections_abc.py | Coroutine.close | close | Raise GeneratorExit inside coroutine. | [
"Raise",
"GeneratorExit",
"inside",
"coroutine."
] | def close(self):
try:
self.throw(GeneratorExit)
except (GeneratorExit, StopIteration):
pass
else:
raise RuntimeError('coroutine ignored GeneratorExit') | ['def', 'close(self):', 'try:', 'self.throw(GeneratorExit)', 'except', '(GeneratorExit,', 'StopIteration):', 'pass', 'else:', 'raise', "RuntimeError('coroutine", 'ignored', "GeneratorExit')"] | 801,796 |
intel/neural-compressor | utility.py | get_op_list | get_op_list | Get OP list for model. | [
"Get",
"OP",
"list",
"for",
"model."
] | def get_op_list(minmax_file_path, input_model_tensors, optimized_model_tensors) -> List[OpEntry]:
with open(minmax_file_path, 'rb') as min_max_file:
min_max_data: dict = pickle.load(min_max_file)
op_list: List[OpEntry] = []
for (op_name, min_max) in min_max_data.items():
mse = calculate_mse(... | ['def', 'get_op_list(minmax_file_path,', 'input_model_tensors,', 'optimized_model_tensors)', '->', 'List[OpEntry]:', 'with', 'open(minmax_file_path,', "'rb')", 'as', 'min_max_file:', 'min_max_data:', 'dict', '=', 'pickle.load(min_max_file)', 'op_list:', 'List[OpEntry]', '=', '[]', 'for', '(op_name,', 'min_max)', 'in', ... | 721,516 |
rudranil723/mini-main | dates.py | DayMixin.get_day | get_day | Return the day for which this view should display data. | [
"Return",
"the",
"day",
"for",
"which",
"this",
"view",
"should",
"display",
"data."
] | def get_day(self):
day = self.day
if day is None:
try:
day = self.kwargs['day']
except KeyError:
try:
day = self.request.GET['day']
except KeyError:
raise Http404(_('No day specified'))
return day | ['def', 'get_day(self):', 'day', '=', 'self.day', 'if', 'day', 'is', 'None:', 'try:', 'day', '=', "self.kwargs['day']", 'except', 'KeyError:', 'try:', 'day', '=', "self.request.GET['day']", 'except', 'KeyError:', 'raise', "Http404(_('No", 'day', "specified'))", 'return', 'day'] | 316,882 |
chrisw2529/Natural-Language-Processing | utils.py | load_lda_model | load_lda_model | Load a gzip file containing lda model. | [
"Load",
"a",
"gzip",
"file",
"containing",
"lda",
"model."
] | def load_lda_model(input_file):
model = LatentDirichletAllocation()
with gzip.open(input_file, 'rb') as f:
(dictionary, model.components_, model.exp_dirichlet_component_, model.doc_topic_prior_) = pickle.load(f)
return (dictionary, model) | ['def', 'load_lda_model(input_file):', 'model', '=', 'LatentDirichletAllocation()', 'with', 'gzip.open(input_file,', "'rb')", 'as', 'f:', '(dictionary,', 'model.components_,', 'model.exp_dirichlet_component_,', 'model.doc_topic_prior_)', '=', 'pickle.load(f)', 'return', '(dictionary,', 'model)'] | 638,809 |
thaines/helit | solve_weave.py | gibbs_all | gibbs_all | Does all the runs requested by a states params object, collating all the samples into the State. | [
"Does",
"all",
"the",
"runs",
"requested",
"by",
"a",
"states",
"params",
"object,",
"collating",
"all",
"the",
"samples",
"into",
"the",
"State."
] | def gibbs_all(state, callback=None):
params = state.getParams()
reporter = ProgReporter(params, callback)
for r in xrange(params.runs):
tempState = State(state)
gibbs_run(tempState, reporter.next)
state.absorbClone(tempState) | ['def', 'gibbs_all(state,', 'callback=None):', 'params', '=', 'state.getParams()', 'reporter', '=', 'ProgReporter(params,', 'callback)', 'for', 'r', 'in', 'xrange(params.runs):', 'tempState', '=', 'State(state)', 'gibbs_run(tempState,', 'reporter.next)', 'state.absorbClone(tempState)'] | 591,230 |
cnr-isti-vclab/TagLab | QtHistogramWidget.py | QtHistogramWidget.saveas | saveas | Save the current histograms. | [
"Save",
"the",
"current",
"histograms."
] | def saveas(self):
filters = 'PNG (*.png)'
(filename, _) = QFileDialog.getSaveFileName(self, 'Save as', '', filters)
if filename:
pxmap = self.lblPreview.pixmap()
qimg = pxmap.toImage()
qimg.save(filename) | ['def', 'saveas(self):', 'filters', '=', "'PNG", "(*.png)'", '(filename,', '_)', '=', 'QFileDialog.getSaveFileName(self,', "'Save", "as',", "'',", 'filters)', 'if', 'filename:', 'pxmap', '=', 'self.lblPreview.pixmap()', 'qimg', '=', 'pxmap.toImage()', 'qimg.save(filename)'] | 906,811 |
43Carrig/recurrent_neural_networks_practice | stats_accumulator_ops.py | StatsAccumulator.schedule_add | schedule_add | Schedules an update to the stats accumulator. | [
"Schedules",
"an",
"update",
"to",
"the",
"stats",
"accumulator."
] | def schedule_add(self, partition_ids, feature_ids, gradients, hessians):
(partition_ids, feature_ids, gradients, hessians) = self._make_summary(partition_ids, feature_ids, gradients, hessians)
if self._is_scalar:
return batch_ops_utils.ScheduledStampedResourceOp(op=gen_stats_accumulator_ops.stats_accumu... | ['def', 'schedule_add(self,', 'partition_ids,', 'feature_ids,', 'gradients,', 'hessians):', '(partition_ids,', 'feature_ids,', 'gradients,', 'hessians)', '=', 'self._make_summary(partition_ids,', 'feature_ids,', 'gradients,', 'hessians)', 'if', 'self._is_scalar:', 'return', 'batch_ops_utils.ScheduledStampedResourceOp(o... | 312,586 |
ludwig-ai/ludwig | gbm_utils.py | logits_to_predictions | logits_to_predictions | Convert the logits of the model to Ludwig predictions. | [
"Convert",
"the",
"logits",
"of",
"the",
"model",
"to",
"Ludwig",
"predictions."
] | def logits_to_predictions(model: BaseModel, train_logits: torch.Tensor) -> Dict[str, Dict[str, torch.Tensor]]:
output_feature = get_single_output_feature(model)
train_logits = reshape_logits(output_feature, train_logits)
return model.outputs_to_predictions({f'{output_feature.feature_name}::logits': train_lo... | ['def', 'logits_to_predictions(model:', 'BaseModel,', 'train_logits:', 'torch.Tensor)', '->', 'Dict[str,', 'Dict[str,', 'torch.Tensor]]:', 'output_feature', '=', 'get_single_output_feature(model)', 'train_logits', '=', 'reshape_logits(output_feature,', 'train_logits)', 'return', "model.outputs_to_predictions({f'{output... | 617,084 |
megvii-research/CR-DA-DET | factory.py | list_imdbs | list_imdbs | List all registered imdbs. | [
"List",
"all",
"registered",
"imdbs."
] | def list_imdbs():
return list(__sets.keys()) | ['def', 'list_imdbs():', 'return', 'list(__sets.keys())'] | 490,374 |
simoncadman/CUPS-Cloud-Print | locked_file.py | _Win32Opener.open_and_lock | open_and_lock | Open the file and lock it. | [
"Open",
"the",
"file",
"and",
"lock",
"it."
] | def open_and_lock(self, timeout, delay):
if self._locked:
raise AlreadyLockedException('File %s is already locked' % self._filename)
start_time = time.time()
validate_file(self._filename)
try:
self._fh = open(self._filename, self._mode)
except IOError as e:
if e.errno == errn... | ['def', 'open_and_lock(self,', 'timeout,', 'delay):', 'if', 'self._locked:', 'raise', "AlreadyLockedException('File", '%s', 'is', 'already', "locked'", '%', 'self._filename)', 'start_time', '=', 'time.time()', 'validate_file(self._filename)', 'try:', 'self._fh', '=', 'open(self._filename,', 'self._mode)', 'except', 'IO... | 197,473 |
ldkong1205/LaserMix | shape_aware_head.py | BaseShapeHead.forward | forward | Forward function for SmallHead. | [
"Forward",
"function",
"for",
"SmallHead."
] | def forward(self, x: Tensor) -> Dict:
x = self.shared_conv(x)
cls_score = self.conv_cls(x)
bbox_pred = self.conv_reg(x)
featmap_size = bbox_pred.shape[-2:]
(H, W) = featmap_size
B = bbox_pred.shape[0]
cls_score = cls_score.view(-1, self.num_base_anchors, self.num_cls, H, W).permute(0, 1, 3, ... | ['def', 'forward(self,', 'x:', 'Tensor)', '->', 'Dict:', 'x', '=', 'self.shared_conv(x)', 'cls_score', '=', 'self.conv_cls(x)', 'bbox_pred', '=', 'self.conv_reg(x)', 'featmap_size', '=', 'bbox_pred.shape[-2:]', '(H,', 'W)', '=', 'featmap_size', 'B', '=', 'bbox_pred.shape[0]', 'cls_score', '=', 'cls_score.view(-1,', 'se... | 624,028 |
ashwanitanwar/nmt-transfer-learning-xlm-r | fairseq_task.py | FairseqTask.get_batch_iterator | get_batch_iterator | Get an iterator that yields batches of data from the given dataset. | [
"Get",
"an",
"iterator",
"that",
"yields",
"batches",
"of",
"data",
"from",
"the",
"given",
"dataset."
] | def get_batch_iterator(self, dataset, max_tokens=None, max_sentences=None, max_positions=None, ignore_invalid_inputs=False, required_batch_size_multiple=1, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0):
assert isinstance(dataset, FairseqDataset)
with data_utils.numpy_seed(seed):
indices = da... | ['def', 'get_batch_iterator(self,', 'dataset,', 'max_tokens=None,', 'max_sentences=None,', 'max_positions=None,', 'ignore_invalid_inputs=False,', 'required_batch_size_multiple=1,', 'seed=1,', 'num_shards=1,', 'shard_id=0,', 'num_workers=0,', 'epoch=0):', 'assert', 'isinstance(dataset,', 'FairseqDataset)', 'with', 'data... | 734,158 |
intel/neural-compressor | environment.py | Environment.ensure_workdir_exists_and_writeable | ensure_workdir_exists_and_writeable | Ensure that configured directory exists and can be used. | [
"Ensure",
"that",
"configured",
"directory",
"exists",
"and",
"can",
"be",
"used."
] | def ensure_workdir_exists_and_writeable() -> None:
from neural_insights.utils.logger import log
from neural_insights.web.configuration import Configuration
configuration = Configuration()
workdir = configuration.workdir
error_message_tail = 'Please ensure it is a directory that can be written to.\nE... | ['def', 'ensure_workdir_exists_and_writeable()', '->', 'None:', 'from', 'neural_insights.utils.logger', 'import', 'log', 'from', 'neural_insights.web.configuration', 'import', 'Configuration', 'configuration', '=', 'Configuration()', 'workdir', '=', 'configuration.workdir', 'error_message_tail', '=', "'Please", 'ensure... | 721,728 |
flavioschneider/rl-transfer- | test_sac.py | test_sac_inverted_double_pendulum | test_sac_inverted_double_pendulum | Test Sac performance on inverted pendulum. | [
"Test",
"Sac",
"performance",
"on",
"inverted",
"pendulum."
] | def test_sac_inverted_double_pendulum():
env = normalize(GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(env_spec=env.spec, hidden_sizes=[32, 32], hidden_nonlinearity=torch.nn.ReLU, output_nonlinearity=None, min_std=np.exp(-20.0), max_std... | ['def', 'test_sac_inverted_double_pendulum():', 'env', '=', "normalize(GymEnv('InvertedDoublePendulum-v2',", 'max_episode_length=100))', 'deterministic.set_seed(0)', 'policy', '=', 'TanhGaussianMLPPolicy(env_spec=env.spec,', 'hidden_sizes=[32,', '32],', 'hidden_nonlinearity=torch.nn.ReLU,', 'output_nonlinearity=None,',... | 861,817 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | util.py | rfc822_escape | rfc822_escape | Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. | [
"Return",
"a",
"version",
"of",
"the",
"string",
"escaped",
"for",
"inclusion",
"in",
"an",
"RFC-822",
"header,",
"by",
"ensuring",
"there",
"are",
"8",
"spaces",
"space",
"after",
"each",
"newline."
] | def rfc822_escape(header):
lines = header.split('\n')
sep = '\n' + 8 * ' '
return sep.join(lines) | ['def', 'rfc822_escape(header):', 'lines', '=', "header.split('\\n')", 'sep', '=', "'\\n'", '+', '8', '*', "'", "'", 'return', 'sep.join(lines)'] | 436,395 |
fudan-zvg/SETR | utils.py | encode_mask_results | encode_mask_results | Encode bitmap mask to RLE code. | [
"Encode",
"bitmap",
"mask",
"to",
"RLE",
"code."
] | def encode_mask_results(mask_results):
if isinstance(mask_results, tuple):
(cls_segms, cls_mask_scores) = mask_results
else:
cls_segms = mask_results
num_classes = len(cls_segms)
encoded_mask_results = [[] for _ in range(num_classes)]
for i in range(len(cls_segms)):
for cls_s... | ['def', 'encode_mask_results(mask_results):', 'if', 'isinstance(mask_results,', 'tuple):', '(cls_segms,', 'cls_mask_scores)', '=', 'mask_results', 'else:', 'cls_segms', '=', 'mask_results', 'num_classes', '=', 'len(cls_segms)', 'encoded_mask_results', '=', '[[]', 'for', '_', 'in', 'range(num_classes)]', 'for', 'i', 'in... | 897,894 |
priorfire4411/artificial_intelligence | models.py | Response.apparent_encoding | apparent_encoding | The apparent encoding, provided by the chardet library. | [
"The",
"apparent",
"encoding,",
"provided",
"by",
"the",
"chardet",
"library."
] | def apparent_encoding(self):
return chardet.detect(self.content)['encoding'] | ['def', 'apparent_encoding(self):', 'return', "chardet.detect(self.content)['encoding']"] | 149,878 |
chainer/chainer | convolution_nd.py | ConvolutionND.forward | forward | Applies N-dimensional convolution layer. | [
"Applies",
"N-dimensional",
"convolution",
"layer."
] | def forward(self, x):
if self.W.array is None:
self._initialize_params(x.shape[1])
return convolution_nd.convolution_nd(x, self.W, self.b, self.stride, self.pad, cover_all=self.cover_all, dilate=self.dilate, groups=self.groups) | ['def', 'forward(self,', 'x):', 'if', 'self.W.array', 'is', 'None:', 'self._initialize_params(x.shape[1])', 'return', 'convolution_nd.convolution_nd(x,', 'self.W,', 'self.b,', 'self.stride,', 'self.pad,', 'cover_all=self.cover_all,', 'dilate=self.dilate,', 'groups=self.groups)'] | 477,425 |
TKassis/OrgaQuant | kitti.py | KittiGenerator.name_to_label | name_to_label | Map name to label. | [
"Map",
"name",
"to",
"label."
] | def name_to_label(self, name):
raise NotImplementedError() | ['def', 'name_to_label(self,', 'name):', 'raise', 'NotImplementedError()'] | 253,437 |
prof-fabriciogmc/artificial_intelligence | cache.py | Cache.get | get | Returns a link to a cached item if it exists, otherwise returns the passed link. | [
"Returns",
"a",
"link",
"to",
"a",
"cached",
"item",
"if",
"it",
"exists,",
"otherwise",
"returns",
"the",
"passed",
"link."
] | def get(self, link, package_name):
raise NotImplementedError() | ['def', 'get(self,', 'link,', 'package_name):', 'raise', 'NotImplementedError()'] | 71,687 |
kuhnertdm/wow-addon-updater | _collections.py | HTTPHeaderDict.itermerged | itermerged | Iterate over all headers, merging duplicate ones together. | [
"Iterate",
"over",
"all",
"headers,",
"merging",
"duplicate",
"ones",
"together."
] | def itermerged(self):
for key in self:
val = self._container[key.lower()]
yield (val[0], ', '.join(val[1:])) | ['def', 'itermerged(self):', 'for', 'key', 'in', 'self:', 'val', '=', 'self._container[key.lower()]', 'yield', '(val[0],', "',", "'.join(val[1:]))"] | 373,827 |
AndrewYinLi/lstm-neural-network-spam-filter | collocations.py | AbstractCollocationFinder.apply_freq_filter | apply_freq_filter | Removes candidate ngrams which have frequency less than min_freq. | [
"Removes",
"candidate",
"ngrams",
"which",
"have",
"frequency",
"less",
"than",
"min_freq."
] | def apply_freq_filter(self, min_freq):
self._apply_filter(lambda ng, freq: freq < min_freq) | ['def', 'apply_freq_filter(self,', 'min_freq):', 'self._apply_filter(lambda', 'ng,', 'freq:', 'freq', '<', 'min_freq)'] | 217,182 |
intel/neural-compressor | ninm.py | PytorchPatternNInM.get_reduced_masks_from_data | get_reduced_masks_from_data | Obtain the unpruned weights and reshape according to the block_size. | [
"Obtain",
"the",
"unpruned",
"weights",
"and",
"reshape",
"according",
"to",
"the",
"block_size."
] | def get_reduced_masks_from_data(self, data, key):
data = self._reshape_orig_to_2dims(data)
shape = data.shape
M = self.M
N = self.N
new_shape = [shape[0], shape[1] // M, M]
data = data.reshape(new_shape)
nonzeros = torch.count_nonzero(data, dim=-1)
reduced_mask = nonzeros > N
return ... | ['def', 'get_reduced_masks_from_data(self,', 'data,', 'key):', 'data', '=', 'self._reshape_orig_to_2dims(data)', 'shape', '=', 'data.shape', 'M', '=', 'self.M', 'N', '=', 'self.N', 'new_shape', '=', '[shape[0],', 'shape[1]', '//', 'M,', 'M]', 'data', '=', 'data.reshape(new_shape)', 'nonzeros', '=', 'torch.count_nonzero... | 738,154 |
srai-lab/srai | test_osm_tile_data_collector.py | TestInMemoryDataCollector.test_should_return_stored | test_should_return_stored | Test values of collected images. | [
"Test",
"values",
"of",
"collected",
"images."
] | def test_should_return_stored(self, col: collectors.InMemoryDataCollector) -> None:
(x, y) = (1, 1)
img = PIL.Image.fromarray(rng.integers(0, 256, size=(3, 3), dtype='uint8'))
stored = col.store(create_id(x, y), img)
assert stored == img | ['def', 'test_should_return_stored(self,', 'col:', 'collectors.InMemoryDataCollector)', '->', 'None:', '(x,', 'y)', '=', '(1,', '1)', 'img', '=', 'PIL.Image.fromarray(rng.integers(0,', '256,', 'size=(3,', '3),', "dtype='uint8'))", 'stored', '=', 'col.store(create_id(x,', 'y),', 'img)', 'assert', 'stored', '==', 'img'] | 372,041 |
rudranil723/mini-main | ast.py | GlyphName.glyphSet | glyphSet | The glyphs in this class as a tuple of :class:`GlyphName` objects. | [
"The",
"glyphs",
"in",
"this",
"class",
"as",
"a",
"tuple",
"of",
":class:`GlyphName`",
"objects."
] | def glyphSet(self):
return (self.glyph,) | ['def', 'glyphSet(self):', 'return', '(self.glyph,)'] | 317,067 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | replay_buffer.py | PrioritizedReplayBuffer.update_last_batch | update_last_batch | Update last batch idxs with new priority. | [
"Update",
"last",
"batch",
"idxs",
"with",
"new",
"priority."
] | def update_last_batch(self, delta):
self.priorities[self.last_batch] = np.abs(delta)
self.priorities[0:self.init_length] = np.max(self.priorities[self.init_length:]) | ['def', 'update_last_batch(self,', 'delta):', 'self.priorities[self.last_batch]', '=', 'np.abs(delta)', 'self.priorities[0:self.init_length]', '=', 'np.max(self.priorities[self.init_length:])'] | 26,242 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | dates.py | AutoDateLocator.autoscale | autoscale | Try to choose the view limits intelligently. | [
"Try",
"to",
"choose",
"the",
"view",
"limits",
"intelligently."
] | def autoscale(self):
(dmin, dmax) = self.datalim_to_dt()
self._locator = self.get_locator(dmin, dmax)
return self._locator.autoscale() | ['def', 'autoscale(self):', '(dmin,', 'dmax)', '=', 'self.datalim_to_dt()', 'self._locator', '=', 'self.get_locator(dmin,', 'dmax)', 'return', 'self._locator.autoscale()'] | 450,380 |
Sea1004/artificial_intelligence | __init__.py | RevOptions.to_args | to_args | Return the VCS-specific command arguments. | [
"Return",
"the",
"VCS-specific",
"command",
"arguments."
] | def to_args(self):
args = []
rev = self.arg_rev
if rev is not None:
args += self.vcs.get_base_rev_args(rev)
args += self.extra_args
return args | ['def', 'to_args(self):', 'args', '=', '[]', 'rev', '=', 'self.arg_rev', 'if', 'rev', 'is', 'not', 'None:', 'args', '+=', 'self.vcs.get_base_rev_args(rev)', 'args', '+=', 'self.extra_args', 'return', 'args'] | 152,613 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | networks.py | unconditional_discriminator | unconditional_discriminator | Discriminator network on unconditional MNIST digits. | [
"Discriminator",
"network",
"on",
"unconditional",
"MNIST",
"digits."
] | def unconditional_discriminator(img, unused_conditioning, weight_decay=2.5e-05):
net = _discriminator_helper(img, False, None, weight_decay)
return layers.linear(net, 1) | ['def', 'unconditional_discriminator(img,', 'unused_conditioning,', 'weight_decay=2.5e-05):', 'net', '=', '_discriminator_helper(img,', 'False,', 'None,', 'weight_decay)', 'return', 'layers.linear(net,', '1)'] | 48,590 |
cheng052/BRNet | open3d_vis.py | project_pts_on_img | project_pts_on_img | Project the 3D points cloud on 2D image. | [
"Project",
"the",
"3D",
"points",
"cloud",
"on",
"2D",
"image."
] | def project_pts_on_img(points, raw_img, lidar2img_rt, max_distance=70, thickness=-1):
img = raw_img.copy()
num_points = points.shape[0]
pts_4d = np.concatenate([points[:, :3], np.ones((num_points, 1))], axis=-1)
pts_2d = pts_4d @ lidar2img_rt.T
pts_2d[:, 2] = np.clip(pts_2d[:, 2], a_min=1e-05, a_max... | ['def', 'project_pts_on_img(points,', 'raw_img,', 'lidar2img_rt,', 'max_distance=70,', 'thickness=-1):', 'img', '=', 'raw_img.copy()', 'num_points', '=', 'points.shape[0]', 'pts_4d', '=', 'np.concatenate([points[:,', ':3],', 'np.ones((num_points,', '1))],', 'axis=-1)', 'pts_2d', '=', 'pts_4d', '@', 'lidar2img_rt.T', 'p... | 409,782 |
ace19-dev/gvcnn-tf | eval_data.py | Dataset.augment | augment | Placeholder for data augmentation. | [
"Placeholder",
"for",
"data",
"augmentation."
] | def augment(self, images, label, filenames):
return (images, label, filenames) | ['def', 'augment(self,', 'images,', 'label,', 'filenames):', 'return', '(images,', 'label,', 'filenames)'] | 234,073 |
zackmcnulty/CSE_446-Machine_Learning | font_manager.py | FontProperties.get_size | get_size | Return the font size. | [
"Return",
"the",
"font",
"size."
] | def get_size(self):
return self._size | ['def', 'get_size(self):', 'return', 'self._size'] | 194,375 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | cmp_utils.py | deconv | deconv | Generates a up sampling network with residual connections. | [
"Generates",
"a",
"up",
"sampling",
"network",
"with",
"residual",
"connections."
] | def deconv(x, is_training, wt_decay, neurons, strides, layers_per_block, kernel_size, conv_fn, name, offset=0):
batch_norm_param = {'center': True, 'scale': True, 'activation_fn': tf.nn.relu, 'is_training': is_training}
outs = []
for (i, (neuron, stride)) in enumerate(zip(neurons, strides)):
for s i... | ['def', 'deconv(x,', 'is_training,', 'wt_decay,', 'neurons,', 'strides,', 'layers_per_block,', 'kernel_size,', 'conv_fn,', 'name,', 'offset=0):', 'batch_norm_param', '=', "{'center':", 'True,', "'scale':", 'True,', "'activation_fn':", 'tf.nn.relu,', "'is_training':", 'is_training}', 'outs', '=', '[]', 'for', '(i,', '(n... | 53,565 |
xiaoaleiBLUE/computer_vision | module.py | OCRCls.predict | predict | Get the text angle in the predicted images. | [
"Get",
"the",
"text",
"angle",
"in",
"the",
"predicted",
"images."
] | def predict(self, images=[], paths=[]):
if images != [] and isinstance(images, list) and (paths == []):
predicted_data = images
elif images == [] and isinstance(paths, list) and (paths != []):
predicted_data = self.read_images(paths)
else:
raise TypeError('The input data is inconsist... | ['def', 'predict(self,', 'images=[],', 'paths=[]):', 'if', 'images', '!=', '[]', 'and', 'isinstance(images,', 'list)', 'and', '(paths', '==', '[]):', 'predicted_data', '=', 'images', 'elif', 'images', '==', '[]', 'and', 'isinstance(paths,', 'list)', 'and', '(paths', '!=', '[]):', 'predicted_data', '=', 'self.read_image... | 501,865 |
danielajisafe/Real-Time-Object-detection-API | model.py | populate_experiment | populate_experiment | Populates an `Experiment` object. | [
"Populates",
"an",
"`Experiment`",
"object."
] | def populate_experiment(run_config, hparams, pipeline_config_path, train_steps=None, eval_steps=None, model_fn_creator=create_model_fn, **kwargs):
configs = config_util.get_configs_from_pipeline_file(pipeline_config_path)
configs = config_util.merge_external_params_with_configs(configs, hparams, train_steps=tra... | ['def', 'populate_experiment(run_config,', 'hparams,', 'pipeline_config_path,', 'train_steps=None,', 'eval_steps=None,', 'model_fn_creator=create_model_fn,', '**kwargs):', 'configs', '=', 'config_util.get_configs_from_pipeline_file(pipeline_config_path)', 'configs', '=', 'config_util.merge_external_params_with_configs(... | 849,305 |
TonyLianLong/VAI-ReinforcementLearning | codegen_util.py | try_coerce_to_num | try_coerce_to_num | Try to coerce string to Python numeric type, return None if empty. | [
"Try",
"to",
"coerce",
"string",
"to",
"Python",
"numeric",
"type,",
"return",
"None",
"if",
"empty."
] | def try_coerce_to_num(s, try_types=(int, float)):
if not s:
return None
for try_type in try_types:
try:
return try_type(s.rstrip('UuFf'))
except (ValueError, AttributeError):
continue
return s | ['def', 'try_coerce_to_num(s,', 'try_types=(int,', 'float)):', 'if', 'not', 's:', 'return', 'None', 'for', 'try_type', 'in', 'try_types:', 'try:', 'return', "try_type(s.rstrip('UuFf'))", 'except', '(ValueError,', 'AttributeError):', 'continue', 'return', 's'] | 439,804 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | cifar10_main.py | record_dataset | record_dataset | Returns an input pipeline Dataset from `filenames`. | [
"Returns",
"an",
"input",
"pipeline",
"Dataset",
"from",
"`filenames`."
] | def record_dataset(filenames):
record_bytes = _HEIGHT * _WIDTH * _DEPTH + 1
return tf.data.FixedLengthRecordDataset(filenames, record_bytes) | ['def', 'record_dataset(filenames):', 'record_bytes', '=', '_HEIGHT', '*', '_WIDTH', '*', '_DEPTH', '+', '1', 'return', 'tf.data.FixedLengthRecordDataset(filenames,', 'record_bytes)'] | 20,100 |
rudranil723/mini-main | ast.py | LigatureCaretByPosStatement.build | build | Calls the builder object's ``add_ligatureCaretByPos_`` callback. | [
"Calls",
"the",
"builder",
"object's",
"``add_ligatureCaretByPos_``",
"callback."
] | def build(self, builder):
glyphs = self.glyphs.glyphSet()
builder.add_ligatureCaretByPos_(self.location, glyphs, set(self.carets)) | ['def', 'build(self,', 'builder):', 'glyphs', '=', 'self.glyphs.glyphSet()', 'builder.add_ligatureCaretByPos_(self.location,', 'glyphs,', 'set(self.carets))'] | 317,094 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | ltisys.py | StateSpace.A | A | State matrix of the `StateSpace` system. | [
"State",
"matrix",
"of",
"the",
"`StateSpace`",
"system."
] | def A(self):
return self._A | ['def', 'A(self):', 'return', 'self._A'] | 260,213 |
open-mmlab/mmdetection3d | primitive_head.py | PrimitiveHead.compute_primitive_loss | compute_primitive_loss | Compute loss of primitive module. | [
"Compute",
"loss",
"of",
"primitive",
"module."
] | def compute_primitive_loss(self, primitive_center: torch.Tensor, primitive_semantic: torch.Tensor, semantic_scores: torch.Tensor, num_proposal: torch.Tensor, gt_primitive_center: torch.Tensor, gt_primitive_semantic: torch.Tensor, gt_sem_cls_label: torch.Tensor, gt_primitive_mask: torch.Tensor) -> Tuple:
batch_size ... | ['def', 'compute_primitive_loss(self,', 'primitive_center:', 'torch.Tensor,', 'primitive_semantic:', 'torch.Tensor,', 'semantic_scores:', 'torch.Tensor,', 'num_proposal:', 'torch.Tensor,', 'gt_primitive_center:', 'torch.Tensor,', 'gt_primitive_semantic:', 'torch.Tensor,', 'gt_sem_cls_label:', 'torch.Tensor,', 'gt_primi... | 632,131 |
weimin17/Object-Detection_HelmetDetection | synthetic_data_utils.py | get_train_n_valid_inds | get_train_n_valid_inds | Split the numbers between 0 and num_trials-1 into two portions for training and validation, based on the train fraction. | [
"Split",
"the",
"numbers",
"between",
"0",
"and",
"num_trials-1",
"into",
"two",
"portions",
"for",
"training",
"and",
"validation,",
"based",
"on",
"the",
"train",
"fraction."
] | def get_train_n_valid_inds(num_trials, train_fraction, nreplications):
train_inds = []
valid_inds = []
for i in range(num_trials):
if i % nreplications + 1 > train_fraction * nreplications:
valid_inds.append(i)
else:
train_inds.append(i)
return (train_inds, valid_... | ['def', 'get_train_n_valid_inds(num_trials,', 'train_fraction,', 'nreplications):', 'train_inds', '=', '[]', 'valid_inds', '=', '[]', 'for', 'i', 'in', 'range(num_trials):', 'if', 'i', '%', 'nreplications', '+', '1', '>', 'train_fraction', '*', 'nreplications:', 'valid_inds.append(i)', 'else:', 'train_inds.append(i)', ... | 757,861 |
treigerm/WaterNet | model.py | init_model | init_model | Initialise a new model with the given hyperparameters and save it for later use. | [
"Initialise",
"a",
"new",
"model",
"with",
"the",
"given",
"hyperparameters",
"and",
"save",
"it",
"for",
"later",
"use."
] | def init_model(tile_size, model_id, architecture='one_layer', nb_filters_1=64, filter_size_1=12, stride_1=(4, 4), pool_size_1=(3, 3), nb_filters_2=128, filter_size_2=4, stride_2=(1, 1), learning_rate=0.005, momentum=0.9, decay=0.002):
num_channels = 3
model = Sequential()
if architecture == 'one_layer':
... | ['def', 'init_model(tile_size,', 'model_id,', "architecture='one_layer',", 'nb_filters_1=64,', 'filter_size_1=12,', 'stride_1=(4,', '4),', 'pool_size_1=(3,', '3),', 'nb_filters_2=128,', 'filter_size_2=4,', 'stride_2=(1,', '1),', 'learning_rate=0.005,', 'momentum=0.9,', 'decay=0.002):', 'num_channels', '=', '3', 'model'... | 372,927 |
datamllab/rlcard | utils.py | rank2int | rank2int | Get the coresponding number of a rank. | [
"Get",
"the",
"coresponding",
"number",
"of",
"a",
"rank."
] | def rank2int(rank):
if rank == '':
return -1
elif rank.isdigit():
if int(rank) >= 2 and int(rank) <= 10:
return int(rank)
else:
return None
elif rank == 'A':
return 14
elif rank == 'T':
return 10
elif rank == 'J':
return 11
... | ['def', 'rank2int(rank):', 'if', 'rank', '==', "'':", 'return', '-1', 'elif', 'rank.isdigit():', 'if', 'int(rank)', '>=', '2', 'and', 'int(rank)', '<=', '10:', 'return', 'int(rank)', 'else:', 'return', 'None', 'elif', 'rank', '==', "'A':", 'return', '14', 'elif', 'rank', '==', "'T':", 'return', '10', 'elif', 'rank', '=... | 332,125 |
mkusner/grammarVAE | gh_api.py | post_gist | post_gist | Post some text to a Gist, and return the URL. | [
"Post",
"some",
"text",
"to",
"a",
"Gist,",
"and",
"return",
"the",
"URL."
] | def post_gist(content, description='', filename='file', auth=False):
post_data = json.dumps({'description': description, 'public': True, 'files': {filename: {'content': content}}}).encode('utf-8')
headers = make_auth_header() if auth else {}
response = requests.post('https://api.github.com/gists', data=post... | ['def', 'post_gist(content,', "description='',", "filename='file',", 'auth=False):', 'post_data', '=', "json.dumps({'description':", 'description,', "'public':", 'True,', "'files':", '{filename:', "{'content':", "content}}}).encode('utf-8')", 'headers', '=', 'make_auth_header()', 'if', 'auth', 'else', '{}', 'response',... | 579,401 |
scotthuang1989/object_detection_with_tensorflow | adversarial_losses.py | adversarial_loss | adversarial_loss | Adds gradient to embedding and recomputes classification loss. | [
"Adds",
"gradient",
"to",
"embedding",
"and",
"recomputes",
"classification",
"loss."
] | def adversarial_loss(embedded, loss, loss_fn):
(grad,) = tf.gradients(loss, embedded, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
grad = tf.stop_gradient(grad)
perturb = _scale_l2(grad, FLAGS.perturb_norm_length)
return loss_fn(embedded + perturb) | ['def', 'adversarial_loss(embedded,', 'loss,', 'loss_fn):', '(grad,)', '=', 'tf.gradients(loss,', 'embedded,', 'aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)', 'grad', '=', 'tf.stop_gradient(grad)', 'perturb', '=', '_scale_l2(grad,', 'FLAGS.perturb_norm_length)', 'return', 'loss_fn(embedded', '+', ... | 796,778 |
sek788432/Waymo-2D-Object-Detection | box_coder.py | BoxCoder.encode | encode | Encode a box list relative to an anchor collection. | [
"Encode",
"a",
"box",
"list",
"relative",
"to",
"an",
"anchor",
"collection."
] | def encode(self, boxes, anchors):
with tf.name_scope('Encode'):
return self._encode(boxes, anchors) | ['def', 'encode(self,', 'boxes,', 'anchors):', 'with', "tf.name_scope('Encode'):", 'return', 'self._encode(boxes,', 'anchors)'] | 973,586 |
chainer/chainer | minmax.py | max | max | Maximum of array elements over a given axis. | [
"Maximum",
"of",
"array",
"elements",
"over",
"a",
"given",
"axis."
] | def max(x, axis=None, keepdims=False):
return Max(axis, keepdims).apply((x,))[0] | ['def', 'max(x,', 'axis=None,', 'keepdims=False):', 'return', 'Max(axis,', 'keepdims).apply((x,))[0]'] | 477,340 |
googleapis/python-aiplatform | study_config.py | StudyConfig.trial_parameters | trial_parameters | Returns the trial values, cast to external types, if they exist. | [
"Returns",
"the",
"trial",
"values,",
"cast",
"to",
"external",
"types,",
"if",
"they",
"exist."
] | def trial_parameters(self, proto: study_pb2.Trial) -> Dict[str, ParameterValueSequence]:
pytrial = proto_converters.TrialConverter.from_proto(proto)
return self._pytrial_parameters(pytrial) | ['def', 'trial_parameters(self,', 'proto:', 'study_pb2.Trial)', '->', 'Dict[str,', 'ParameterValueSequence]:', 'pytrial', '=', 'proto_converters.TrialConverter.from_proto(proto)', 'return', 'self._pytrial_parameters(pytrial)'] | 810,304 |
interpretml/DiCE | model.py | Model.decide_implementation_type | decide_implementation_type | Decides the Model implementation type. | [
"Decides",
"the",
"Model",
"implementation",
"type."
] | def decide_implementation_type(self, model, model_path, backend, func, kw_args):
self.__class__ = decide(backend)
self.__init__(model, model_path, backend, func, kw_args) | ['def', 'decide_implementation_type(self,', 'model,', 'model_path,', 'backend,', 'func,', 'kw_args):', 'self.__class__', '=', 'decide(backend)', 'self.__init__(model,', 'model_path,', 'backend,', 'func,', 'kw_args)'] | 550,171 |
SamsungLabs/fcaf3d | base_points.py | BasePoints.cat | cat | Concatenate a list of Points into a single Points. | [
"Concatenate",
"a",
"list",
"of",
"Points",
"into",
"a",
"single",
"Points."
] | def cat(cls, points_list):
assert isinstance(points_list, (list, tuple))
if len(points_list) == 0:
return cls(torch.empty(0))
assert all((isinstance(points, cls) for points in points_list))
cat_points = cls(torch.cat([p.tensor for p in points_list], dim=0), points_dim=points_list[0].tensor.shape... | ['def', 'cat(cls,', 'points_list):', 'assert', 'isinstance(points_list,', '(list,', 'tuple))', 'if', 'len(points_list)', '==', '0:', 'return', 'cls(torch.empty(0))', 'assert', 'all((isinstance(points,', 'cls)', 'for', 'points', 'in', 'points_list))', 'cat_points', '=', 'cls(torch.cat([p.tensor', 'for', 'p', 'in', 'poin... | 560,258 |
intel/neural-compressor | component.py | Component.prepare | prepare | Register Quantization Aware Training hooks. | [
"Register",
"Quantization",
"Aware",
"Training",
"hooks."
] | def prepare(self):
if self.combination is not None and 'Quantization' in self.combination:
if self.adaptor is None:
framework_specific_info = {'device': self.cfg.device, 'approach': 'post_training_static_quant', 'random_seed': self.cfg.tuning.random_seed, 'workspace_path': self.cfg.tuning.worksp... | ['def', 'prepare(self):', 'if', 'self.combination', 'is', 'not', 'None', 'and', "'Quantization'", 'in', 'self.combination:', 'if', 'self.adaptor', 'is', 'None:', 'framework_specific_info', '=', "{'device':", 'self.cfg.device,', "'approach':", "'post_training_static_quant',", "'random_seed':", 'self.cfg.tuning.random_se... | 738,301 |
yanwenjie1/natural_language_processing | B.py | BerkeleyAligner.align | align | Returns the alignment result for one sentence pair. | [
"Returns",
"the",
"alignment",
"result",
"for",
"one",
"sentence",
"pair."
] | def align(self, align_sent):
if self.probabilities is None or self.alignments is None:
raise ValueError('The model does not train.')
alignment = []
l_e = align_sent.words.__len__()
l_f = align_sent.mots.__len__()
for (j, en_word) in enumerate(align_sent.words):
max_align_prob = (self... | ['def', 'align(self,', 'align_sent):', 'if', 'self.probabilities', 'is', 'None', 'or', 'self.alignments', 'is', 'None:', 'raise', "ValueError('The", 'model', 'does', 'not', "train.')", 'alignment', '=', '[]', 'l_e', '=', 'align_sent.words.__len__()', 'l_f', '=', 'align_sent.mots.__len__()', 'for', '(j,', 'en_word)', 'i... | 734,953 |
BurkhardtMicah/Artificial-Intelligence | utils.py | vector_add | vector_add | Component-wise addition of two vectors. | [
"Component-wise",
"addition",
"of",
"two",
"vectors."
] | def vector_add(a, b):
return tuple(map(operator.add, a, b)) | ['def', 'vector_add(a,', 'b):', 'return', 'tuple(map(operator.add,', 'a,', 'b))'] | 121,614 |
weimin17/Object-Detection_HelmetDetection | neural_gpu_trainer.py | single_test | single_test | Test model on test data of length l using the given session. | [
"Test",
"model",
"on",
"test",
"data",
"of",
"length",
"l",
"using",
"the",
"given",
"session."
] | def single_test(bin_id, model, sess, nprint, batch_size, dev, p, print_out=True, offset=None, beam_model=None):
if not dev[p][bin_id]:
data.print_out(' bin %d (%d)\t%s\tppl NA errors NA seq-errors NA' % (bin_id, data.bins[bin_id], p))
return (1.0, 1.0, 0.0)
(inpt, target) = data.get_batch(bin_i... | ['def', 'single_test(bin_id,', 'model,', 'sess,', 'nprint,', 'batch_size,', 'dev,', 'p,', 'print_out=True,', 'offset=None,', 'beam_model=None):', 'if', 'not', 'dev[p][bin_id]:', "data.print_out('", 'bin', '%d', '(%d)\\t%s\\tppl', 'NA', 'errors', 'NA', 'seq-errors', "NA'", '%', '(bin_id,', 'data.bins[bin_id],', 'p))', '... | 751,400 |
autonomousvision/differentiable_volumetric_rendering | fields.py | CategoryField.check_complete | check_complete | Check if field is complete. | [
"Check",
"if",
"field",
"is",
"complete."
] | def check_complete(self, files):
return True | ['def', 'check_complete(self,', 'files):', 'return', 'True'] | 185,015 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec.py | Word2Vec.optimize | optimize | Build the graph to optimize the loss function. | [
"Build",
"the",
"graph",
"to",
"optimize",
"the",
"loss",
"function."
] | def optimize(self, loss):
opts = self._options
words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)
lr = opts.learning_rate * tf.maximum(0.0001, 1.0 - tf.cast(self._words, tf.float32) / words_to_train)
self._lr = lr
optimizer = tf.train.GradientDescentOptimizer(lr)
train = optimiz... | ['def', 'optimize(self,', 'loss):', 'opts', '=', 'self._options', 'words_to_train', '=', 'float(opts.words_per_epoch', '*', 'opts.epochs_to_train)', 'lr', '=', 'opts.learning_rate', '*', 'tf.maximum(0.0001,', '1.0', '-', 'tf.cast(self._words,', 'tf.float32)', '/', 'words_to_train)', 'self._lr', '=', 'lr', 'optimizer', ... | 30,106 |
usmancheema89/computer_vision | cpp_lint.py | CheckComment | CheckComment | Checks for common mistakes in TODO comments. | [
"Checks",
"for",
"common",
"mistakes",
"in",
"TODO",
"comments."
] | def CheckComment(comment, filename, linenum, error):
match = _RE_PATTERN_TODO.match(comment)
if match:
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO')
username = match.group(2)
... | ['def', 'CheckComment(comment,', 'filename,', 'linenum,', 'error):', 'match', '=', '_RE_PATTERN_TODO.match(comment)', 'if', 'match:', 'leading_whitespace', '=', 'match.group(1)', 'if', 'len(leading_whitespace)', '>', '1:', 'error(filename,', 'linenum,', "'whitespace/todo',", '2,', "'Too", 'many', 'spaces', 'before', "T... | 473,239 |
keyonvafa/career-code | laser_lstm.py | LSTMEncoder.max_positions | max_positions | Maximum input length supported by the encoder. | [
"Maximum",
"input",
"length",
"supported",
"by",
"the",
"encoder."
] | def max_positions(self):
return int(100000.0) | ['def', 'max_positions(self):', 'return', 'int(100000.0)'] | 454,873 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | neural_gpu.py | place_at13 | place_at13 | Place selected at it-th coordinate of decided, dim=1 of 3. | [
"Place",
"selected",
"at",
"it-th",
"coordinate",
"of",
"decided,",
"dim=1",
"of",
"3."
] | def place_at13(decided, selected, it):
slice1 = decided[:, :it, :]
slice2 = decided[:, it + 1:, :]
return tf.concat(axis=1, values=[slice1, selected, slice2]) | ['def', 'place_at13(decided,', 'selected,', 'it):', 'slice1', '=', 'decided[:,', ':it,', ':]', 'slice2', '=', 'decided[:,', 'it', '+', '1:,', ':]', 'return', 'tf.concat(axis=1,', 'values=[slice1,', 'selected,', 'slice2])'] | 56,345 |
kamaleshkio/Natural-Language-Processing | Tagger.py | count_correct | count_correct | Return the total number of correctly predicted tags,the total number of correcttly predicted tags for oov words and the number of oov words in the given sentence. | [
"Return",
"the",
"total",
"number",
"of",
"correctly",
"predicted",
"tags,the",
"total",
"number",
"of",
"correcttly",
"predicted",
"tags",
"for",
"oov",
"words",
"and",
"the",
"number",
"of",
"oov",
"words",
"in",
"the",
"given",
"sentence."
] | def count_correct(gold_sentence, pred_sentence):
assert len(gold_sentence) == len(pred_sentence)
global START, END, UNK, allTagCounts, perWordTagCounts, transitionCounts, emissionCounts, A, B, num_of_sentences
(correct, correctOOV) = (0, 0)
for ((gold_word, gold_tag), (pred_word, pred_tag)) in zip(gold_... | ['def', 'count_correct(gold_sentence,', 'pred_sentence):', 'assert', 'len(gold_sentence)', '==', 'len(pred_sentence)', 'global', 'START,', 'END,', 'UNK,', 'allTagCounts,', 'perWordTagCounts,', 'transitionCounts,', 'emissionCounts,', 'A,', 'B,', 'num_of_sentences', '(correct,', 'correctOOV)', '=', '(0,', '0)', 'for', '(... | 708,695 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | datasets.py | is_image_file | is_image_file | Checks if a file is an image. | [
"Checks",
"if",
"a",
"file",
"is",
"an",
"image."
] | def is_image_file(filename):
filename_lower = filename.lower()
return any((filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)) | ['def', 'is_image_file(filename):', 'filename_lower', '=', 'filename.lower()', 'return', 'any((filename_lower.endswith(ext)', 'for', 'ext', 'in', 'IMG_EXTENSIONS))'] | 81,947 |
weimin17/Object-Detection_HelmetDetection | errorcounter.py | ComputeErrorRates | ComputeErrorRates | Returns an ErrorRates corresponding to the given counts. | [
"Returns",
"an",
"ErrorRates",
"corresponding",
"to",
"the",
"given",
"counts."
] | def ComputeErrorRates(label_counts, word_counts, seq_errors, num_seqs):
label_errors = label_counts.fn + label_counts.fp
num_labels = label_counts.truth_count + label_counts.test_count
return ErrorRates(ComputeErrorRate(label_errors, num_labels), ComputeErrorRate(word_counts.fn, word_counts.truth_count), Co... | ['def', 'ComputeErrorRates(label_counts,', 'word_counts,', 'seq_errors,', 'num_seqs):', 'label_errors', '=', 'label_counts.fn', '+', 'label_counts.fp', 'num_labels', '=', 'label_counts.truth_count', '+', 'label_counts.test_count', 'return', 'ErrorRates(ComputeErrorRate(label_errors,', 'num_labels),', 'ComputeErrorRate(... | 753,076 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | average_recorder.py | _SingleAverageRecorder.add | add | Appends a new record. | [
"Appends",
"a",
"new",
"record."
] | def add(self, record, weight=None):
w = weight if weight is not None else 1
self._w_sum += w
self._sum += record * w
if self._size is not None:
if len(self._q) == self._size:
w_pop = self._w.popleft()
self._sum -= self._q.popleft() * w_pop
self._w_sum -= w_pop... | ['def', 'add(self,', 'record,', 'weight=None):', 'w', '=', 'weight', 'if', 'weight', 'is', 'not', 'None', 'else', '1', 'self._w_sum', '+=', 'w', 'self._sum', '+=', 'record', '*', 'w', 'if', 'self._size', 'is', 'not', 'None:', 'if', 'len(self._q)', '==', 'self._size:', 'w_pop', '=', 'self._w.popleft()', 'self._sum', '-=... | 406,275 |
Kvatsx/Artificial-Intelligence-Assignments | test_bundler_tools.py | TestBundlerTools.test_get_cell_reference_patterns_precode_backticks | test_get_cell_reference_patterns_precode_backticks | Should find three references in a fenced code block. | [
"Should",
"find",
"three",
"references",
"in",
"a",
"fenced",
"code",
"block."
] | def test_get_cell_reference_patterns_precode_backticks(self):
cell = {'cell_type': 'markdown', 'source': '```c\na\nb/\n#comment\n```'}
references = tools.get_cell_reference_patterns(cell)
self.assertTrue('a' in references and 'b/' in references and ('c' in references), str(references))
self.assertEqual(... | ['def', 'test_get_cell_reference_patterns_precode_backticks(self):', 'cell', '=', "{'cell_type':", "'markdown',", "'source':", "'```c\\na\\nb/\\n#comment\\n```'}", 'references', '=', 'tools.get_cell_reference_patterns(cell)', "self.assertTrue('a'", 'in', 'references', 'and', "'b/'", 'in', 'references', 'and', "('c'", '... | 2,196 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | debugger.py | InterruptiblePdb.cmdloop | cmdloop | Wrap cmdloop() such that KeyboardInterrupt stops the debugger. | [
"Wrap",
"cmdloop()",
"such",
"that",
"KeyboardInterrupt",
"stops",
"the",
"debugger."
] | def cmdloop(self):
try:
return OldPdb.cmdloop(self)
except KeyboardInterrupt:
self.stop_here = lambda frame: False
self.do_quit('')
sys.settrace(None)
self.quitting = False
raise | ['def', 'cmdloop(self):', 'try:', 'return', 'OldPdb.cmdloop(self)', 'except', 'KeyboardInterrupt:', 'self.stop_here', '=', 'lambda', 'frame:', 'False', "self.do_quit('')", 'sys.settrace(None)', 'self.quitting', '=', 'False', 'raise'] | 448,058 |
voxel51/fiftyone | dataset.py | Dataset.clear_cache | clear_cache | Clears the dataset's in-memory cache. | [
"Clears",
"the",
"dataset's",
"in-memory",
"cache."
] | def clear_cache(self):
self._annotation_cache.clear()
self._brain_cache.clear()
self._evaluation_cache.clear() | ['def', 'clear_cache(self):', 'self._annotation_cache.clear()', 'self._brain_cache.clear()', 'self._evaluation_cache.clear()'] | 582,970 |
copenlu/X-MAML | modeling_t5.py | T5Attention.forward | forward | Self-attention (if kv is None) or attention over source sentence (provided by kv). | [
"Self-attention",
"(if",
"kv",
"is",
"None)",
"or",
"attention",
"over",
"source",
"sentence",
"(provided",
"by",
"kv)."
] | def forward(self, input, mask=None, kv=None, position_bias=None, cache=None, head_mask=None):
(bs, qlen, dim) = input.size()
if kv is None:
klen = qlen if cache is None else cache['slen'] + qlen
else:
klen = kv.size(1)
def shape(x):
return x.view(bs, -1, self.n_heads, self.d_kv)... | ['def', 'forward(self,', 'input,', 'mask=None,', 'kv=None,', 'position_bias=None,', 'cache=None,', 'head_mask=None):', '(bs,', 'qlen,', 'dim)', '=', 'input.size()', 'if', 'kv', 'is', 'None:', 'klen', '=', 'qlen', 'if', 'cache', 'is', 'None', 'else', "cache['slen']", '+', 'qlen', 'else:', 'klen', '=', 'kv.size(1)', 'def... | 961,561 |
asyml/texar | xlnet_tokenizer.py | XLNetTokenizer.map_token_to_text | map_token_to_text | Maps a sequence of tokens (string) in a single string. | [
"Maps",
"a",
"sequence",
"of",
"tokens",
"(string)",
"in",
"a",
"single",
"string."
] | def map_token_to_text(self, tokens: List[str]) -> str:
out_string = ''.join(tokens).replace(SPIECE_UNDERLINE, ' ').strip()
return out_string | ['def', 'map_token_to_text(self,', 'tokens:', 'List[str])', '->', 'str:', 'out_string', '=', "''.join(tokens).replace(SPIECE_UNDERLINE,", "'", "').strip()", 'return', 'out_string'] | 924,612 |
saysaysx/artificial-intelligence | test_dtype.py | TestStructuredObjectRefcounting.test_structured_object_indexing | test_structured_object_indexing | Structured object reference counting for advanced indexing. | [
"Structured",
"object",
"reference",
"counting",
"for",
"advanced",
"indexing."
] | def test_structured_object_indexing(self, shape, index, items_changed, dt, pat, count, singleton):
zero = 0
one = 1
arr = np.zeros(shape, dt)
gc.collect()
before_zero = sys.getrefcount(zero)
before_one = sys.getrefcount(one)
part = arr[index]
after_zero = sys.getrefcount(zero)
assert... | ['def', 'test_structured_object_indexing(self,', 'shape,', 'index,', 'items_changed,', 'dt,', 'pat,', 'count,', 'singleton):', 'zero', '=', '0', 'one', '=', '1', 'arr', '=', 'np.zeros(shape,', 'dt)', 'gc.collect()', 'before_zero', '=', 'sys.getrefcount(zero)', 'before_one', '=', 'sys.getrefcount(one)', 'part', '=', 'ar... | 61,246 |
Oneflow-Inc/vision | utils.py | flow_to_image | flow_to_image | Converts a flow to an RGB image. | [
"Converts",
"a",
"flow",
"to",
"an",
"RGB",
"image."
] | def flow_to_image(flow: torch.Tensor) -> torch.Tensor:
if flow.dtype != torch.float:
raise ValueError(f'Flow should be of dtype torch.float, got {flow.dtype}.')
orig_shape = flow.shape
if flow.ndim == 3:
flow = flow[None]
if flow.ndim != 4 or flow.shape[1] != 2:
raise ValueError(... | ['def', 'flow_to_image(flow:', 'torch.Tensor)', '->', 'torch.Tensor:', 'if', 'flow.dtype', '!=', 'torch.float:', 'raise', "ValueError(f'Flow", 'should', 'be', 'of', 'dtype', 'torch.float,', 'got', "{flow.dtype}.')", 'orig_shape', '=', 'flow.shape', 'if', 'flow.ndim', '==', '3:', 'flow', '=', 'flow[None]', 'if', 'flow.n... | 958,129 |
intelligent-environments-lab/CityLearn | energy_model.py | Battery.efficiency_history | efficiency_history | Time series of technical efficiency. | [
"Time",
"series",
"of",
"technical",
"efficiency."
] | def efficiency_history(self) -> List[float]:
return self._efficiency_history | ['def', 'efficiency_history(self)', '->', 'List[float]:', 'return', 'self._efficiency_history'] | 105,476 |
nicknochnack/RealTimeSignLanguageTFJS | talking_heads_attention_test.py | TalkingHeadsAttentionTest.test_non_masked_attention | test_non_masked_attention | Test that the attention layer can be created without a mask tensor. | [
"Test",
"that",
"the",
"attention",
"layer",
"can",
"be",
"created",
"without",
"a",
"mask",
"tensor."
] | def test_non_masked_attention(self, value_dim, output_shape, output_dims):
test_layer = talking_heads_attention.TalkingHeadsAttention(num_heads=12, key_dim=64, value_dim=value_dim, output_shape=output_shape)
query = tf.keras.Input(shape=(40, 80))
value = tf.keras.Input(shape=(20, 80))
output = test_laye... | ['def', 'test_non_masked_attention(self,', 'value_dim,', 'output_shape,', 'output_dims):', 'test_layer', '=', 'talking_heads_attention.TalkingHeadsAttention(num_heads=12,', 'key_dim=64,', 'value_dim=value_dim,', 'output_shape=output_shape)', 'query', '=', 'tf.keras.Input(shape=(40,', '80))', 'value', '=', 'tf.keras.Inp... | 850,384 |
yonatan-E/Unsupervised-Learning | utils.py | visualize_images | visualize_images | Visualize reconstructed images and generated images from randomly sampled values from the latent space. | [
"Visualize",
"reconstructed",
"images",
"and",
"generated",
"images",
"from",
"randomly",
"sampled",
"values",
"from",
"the",
"latent",
"space."
] | def visualize_images(test_images, epoch, label):
grid_size = 5
(fig, ax) = plt.subplots(grid_size, grid_size, figsize=(5, 5))
for (i, j) in itertools.product(range(grid_size), range(grid_size)):
ax[i, j].get_xaxis().set_visible(False)
ax[i, j].get_yaxis().set_visible(False)
for k in rang... | ['def', 'visualize_images(test_images,', 'epoch,', 'label):', 'grid_size', '=', '5', '(fig,', 'ax)', '=', 'plt.subplots(grid_size,', 'grid_size,', 'figsize=(5,', '5))', 'for', '(i,', 'j)', 'in', 'itertools.product(range(grid_size),', 'range(grid_size)):', 'ax[i,', 'j].get_xaxis().set_visible(False)', 'ax[i,', 'j].get_y... | 353,402 |
blakeblackshear/frigate | ws.py | WebSocketClient.start | start | Start the websocket client. | [
"Start",
"the",
"websocket",
"client."
] | def start(self) -> None:
class _WebSocketHandler(WebSocket):
receiver = self._dispatcher
def received_message(self, message: WebSocket.received_message) -> None:
try:
json_message = json.loads(message.data.decode('utf-8'))
json_message = {'topic': json_m... | ['def', 'start(self)', '->', 'None:', 'class', '_WebSocketHandler(WebSocket):', 'receiver', '=', 'self._dispatcher', 'def', 'received_message(self,', 'message:', 'WebSocket.received_message)', '->', 'None:', 'try:', 'json_message', '=', "json.loads(message.data.decode('utf-8'))", 'json_message', '=', "{'topic':", "json... | 564,476 |
TARGET-SIDE-DATA-AUG/TSDASG | trainer.py | Trainer.load_checkpoint | load_checkpoint | Load all training state from a checkpoint file. | [
"Load",
"all",
"training",
"state",
"from",
"a",
"checkpoint",
"file."
] | def load_checkpoint(self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None, reset_meters=False):
(extra_state, self._optim_history, last_optim_state) = (None, [], None)
bexists = PathManager.isfile(filename)
if bexists:
state = checkpoint_utils.load_checkpoint_to_c... | ['def', 'load_checkpoint(self,', 'filename,', 'reset_optimizer=False,', 'reset_lr_scheduler=False,', 'optimizer_overrides=None,', 'reset_meters=False):', '(extra_state,', 'self._optim_history,', 'last_optim_state)', '=', '(None,', '[],', 'None)', 'bexists', '=', 'PathManager.isfile(filename)', 'if', 'bexists:', 'state'... | 951,883 |
sek788432/Waymo-2D-Object-Detection | preprocessor_test.py | PreprocessorTest.testResizePadToMultipleWithMasks | testResizePadToMultipleWithMasks | Tests resizing when padding to multiple with masks. | [
"Tests",
"resizing",
"when",
"padding",
"to",
"multiple",
"with",
"masks."
] | def testResizePadToMultipleWithMasks(self):
def graph_fn():
image = tf.ones((200, 100, 3), dtype=tf.float32)
masks = tf.ones((10, 200, 100), dtype=tf.float32)
(_, out_masks, out_shape) = preprocessor.resize_pad_to_multiple(image, multiple=32, masks=masks)
return [out_masks, out_shap... | ['def', 'testResizePadToMultipleWithMasks(self):', 'def', 'graph_fn():', 'image', '=', 'tf.ones((200,', '100,', '3),', 'dtype=tf.float32)', 'masks', '=', 'tf.ones((10,', '200,', '100),', 'dtype=tf.float32)', '(_,', 'out_masks,', 'out_shape)', '=', 'preprocessor.resize_pad_to_multiple(image,', 'multiple=32,', 'masks=mas... | 974,888 |
HuiGuanLab/HiCo | checkpoint.py | get_last_checkpoint | get_last_checkpoint | Get the last checkpoint from the checkpointing folder. | [
"Get",
"the",
"last",
"checkpoint",
"from",
"the",
"checkpointing",
"folder."
] | def get_last_checkpoint(path_to_job):
d = get_checkpoint_dir(path_to_job)
names = os.listdir(d) if os.path.exists(d) else []
names = [f for f in names if 'checkpoint' in f]
assert len(names), "No checkpoints found in '{}'.".format(d)
name = sorted(names)[-1]
return os.path.join(d, name) | ['def', 'get_last_checkpoint(path_to_job):', 'd', '=', 'get_checkpoint_dir(path_to_job)', 'names', '=', 'os.listdir(d)', 'if', 'os.path.exists(d)', 'else', '[]', 'names', '=', '[f', 'for', 'f', 'in', 'names', 'if', "'checkpoint'", 'in', 'f]', 'assert', 'len(names),', '"No', 'checkpoints', 'found', 'in', '\'{}\'.".forma... | 206,167 |
google-research/scenic | metaphase_sexid_dataset.py | build_dataset | build_dataset | Dataset builder that takes care of strategy, batching and shuffling. | [
"Dataset",
"builder",
"that",
"takes",
"care",
"of",
"strategy,",
"batching",
"and",
"shuffling."
] | def build_dataset(dataset_fn, batch_size=None, shuffle_buffer_size=256, seed=None, strategy=None, **dataset_kwargs):
def _dataset_fn(input_context=None):
replica_batch_size = batch_size
if input_context:
replica_batch_size = input_context.get_per_replica_batch_size(batch_size)
d... | ['def', 'build_dataset(dataset_fn,', 'batch_size=None,', 'shuffle_buffer_size=256,', 'seed=None,', 'strategy=None,', '**dataset_kwargs):', 'def', '_dataset_fn(input_context=None):', 'replica_batch_size', '=', 'batch_size', 'if', 'input_context:', 'replica_batch_size', '=', 'input_context.get_per_replica_batch_size(batc... | 847,457 |
replit-archive/empythoned | ttk.py | OptionMenu.destroy | destroy | Destroy this widget and its associated variable. | [
"Destroy",
"this",
"widget",
"and",
"its",
"associated",
"variable."
] | def destroy(self):
del self._variable
Menubutton.destroy(self) | ['def', 'destroy(self):', 'del', 'self._variable', 'Menubutton.destroy(self)'] | 176,803 |
tensorflow/agents | array_spec.py | BoundedArraySpec.check_array | check_array | Return true if the given array conforms to the spec. | [
"Return",
"true",
"if",
"the",
"given",
"array",
"conforms",
"to",
"the",
"spec."
] | def check_array(self, array):
return super(BoundedArraySpec, self).check_array(array) and np.all(array >= self.minimum) and np.all(array <= self.maximum) | ['def', 'check_array(self,', 'array):', 'return', 'super(BoundedArraySpec,', 'self).check_array(array)', 'and', 'np.all(array', '>=', 'self.minimum)', 'and', 'np.all(array', '<=', 'self.maximum)'] | 23,683 |
jpmorganchase/Phantom | env.py | PhantomEnv.strategic_agent_ids | strategic_agent_ids | Return a list of the IDs of the agents that take actions. | [
"Return",
"a",
"list",
"of",
"the",
"IDs",
"of",
"the",
"agents",
"that",
"take",
"actions."
] | def strategic_agent_ids(self) -> List[AgentID]:
return [a.id for a in self.agents.values() if isinstance(a, StrategicAgent)] | ['def', 'strategic_agent_ids(self)', '->', 'List[AgentID]:', 'return', '[a.id', 'for', 'a', 'in', 'self.agents.values()', 'if', 'isinstance(a,', 'StrategicAgent)]'] | 768,678 |
michellesri/cs188 | bustersAgents.py | KeyboardInference.initializeUniformly | initializeUniformly | Begin with a uniform distribution over ghost positions. | [
"Begin",
"with",
"a",
"uniform",
"distribution",
"over",
"ghost",
"positions."
] | def initializeUniformly(self, gameState):
self.beliefs = util.Counter()
for p in self.legalPositions:
self.beliefs[p] = 1.0
self.beliefs.normalize() | ['def', 'initializeUniformly(self,', 'gameState):', 'self.beliefs', '=', 'util.Counter()', 'for', 'p', 'in', 'self.legalPositions:', 'self.beliefs[p]', '=', '1.0', 'self.beliefs.normalize()'] | 225,678 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | zipfile.py | ZipFile.getinfo | getinfo | Return the instance of ZipInfo given 'name'. | [
"Return",
"the",
"instance",
"of",
"ZipInfo",
"given",
"'name'."
] | def getinfo(self, name):
info = self.NameToInfo.get(name)
if info is None:
raise KeyError('There is no item named %r in the archive' % name)
return info | ['def', 'getinfo(self,', 'name):', 'info', '=', 'self.NameToInfo.get(name)', 'if', 'info', 'is', 'None:', 'raise', "KeyError('There", 'is', 'no', 'item', 'named', '%r', 'in', 'the', "archive'", '%', 'name)', 'return', 'info'] | 429,901 |
weimin17/Object-Detection_HelmetDetection | data_sampler.py | sample_covertype_data | sample_covertype_data | Returns bandit problem dataset based on the UCI Cover_Type data. | [
"Returns",
"bandit",
"problem",
"dataset",
"based",
"on",
"the",
"UCI",
"Cover_Type",
"data."
] | def sample_covertype_data(file_name, num_contexts, shuffle_rows=True, remove_underrepresented=False):
with tf.gfile.Open(file_name, 'r') as f:
df = pd.read_csv(f, header=0, na_values=['?']).dropna()
num_actions = 7
if shuffle_rows:
df = df.sample(frac=1)
df = df.iloc[:num_contexts, :]
... | ['def', 'sample_covertype_data(file_name,', 'num_contexts,', 'shuffle_rows=True,', 'remove_underrepresented=False):', 'with', 'tf.gfile.Open(file_name,', "'r')", 'as', 'f:', 'df', '=', 'pd.read_csv(f,', 'header=0,', "na_values=['?']).dropna()", 'num_actions', '=', '7', 'if', 'shuffle_rows:', 'df', '=', 'df.sample(frac=... | 762,367 |
zihuitang/medical_AI_platform | transports.py | BaseTransport.get_protocol | get_protocol | Return the current protocol. | [
"Return",
"the",
"current",
"protocol."
] | def get_protocol(self):
raise NotImplementedError | ['def', 'get_protocol(self):', 'raise', 'NotImplementedError'] | 282,089 |
weimin17/Object-Detection_HelmetDetection | policy.py | Policy.calculate_kl | calculate_kl | Calculate KL between one policy and another on batch of episodes. | [
"Calculate",
"KL",
"between",
"one",
"policy",
"and",
"another",
"on",
"batch",
"of",
"episodes."
] | def calculate_kl(self, my_logits, other_logits):
batch_size = tf.shape(my_logits[0])[1]
time_length = tf.shape(my_logits[0])[0]
reshaped_my_logits = [tf.reshape(my_logit, [batch_size * time_length, -1]) for my_logit in my_logits]
reshaped_other_logits = [tf.reshape(other_logit, [batch_size * time_length... | ['def', 'calculate_kl(self,', 'my_logits,', 'other_logits):', 'batch_size', '=', 'tf.shape(my_logits[0])[1]', 'time_length', '=', 'tf.shape(my_logits[0])[0]', 'reshaped_my_logits', '=', '[tf.reshape(my_logit,', '[batch_size', '*', 'time_length,', '-1])', 'for', 'my_logit', 'in', 'my_logits]', 'reshaped_other_logits', '... | 752,509 |
facebookresearch/CompilerGym | experiment.py | Experiment.results_paths | results_paths | Return an iterator over results files. | [
"Return",
"an",
"iterator",
"over",
"results",
"files."
] | def results_paths(self) -> Iterable[Path]:
for path in self.working_directory.iterdir():
if path.is_file() and path.name.startswith('results-'):
yield path | ['def', 'results_paths(self)', '->', 'Iterable[Path]:', 'for', 'path', 'in', 'self.working_directory.iterdir():', 'if', 'path.is_file()', 'and', "path.name.startswith('results-'):", 'yield', 'path'] | 135,660 |
IGNF/myria3d | finetuning_callbacks.py | FinetuningFreezeUnfreeze.freeze_before_training | freeze_before_training | Update in and out dimensions, and freeze everything at start. | [
"Update",
"in",
"and",
"out",
"dimensions,",
"and",
"freeze",
"everything",
"at",
"start."
] | def freeze_before_training(self, pl_module):
pl_module.model.change_num_class_for_finetuning(self._num_classes)
self.freeze(pl_module.model) | ['def', 'freeze_before_training(self,', 'pl_module):', 'pl_module.model.change_num_class_for_finetuning(self._num_classes)', 'self.freeze(pl_module.model)'] | 651,616 |
OliverKillane/NuNet-Designer | NuNetLibrary.py | Neuron.gettype | gettype | gettype returns the type of object (in this case 'Neuron'). | [
"gettype",
"returns",
"the",
"type",
"of",
"object",
"(in",
"this",
"case",
"'Neuron')."
] | def gettype(self) -> str:
return 'Neuron' | ['def', 'gettype(self)', '->', 'str:', 'return', "'Neuron'"] | 730,517 |
PacktPublishing/Learning-OpenCV-4---with-Python-Third-Edition | managers.py | CaptureManager.writeImage | writeImage | Write the next exited frame to an image file. | [
"Write",
"the",
"next",
"exited",
"frame",
"to",
"an",
"image",
"file."
] | def writeImage(self, filename):
self._imageFilename = filename | ['def', 'writeImage(self,', 'filename):', 'self._imageFilename', '=', 'filename'] | 588,030 |
am-shashank/artificial-intelligence | __init__.py | VersionControl.get_revision | get_revision | Return the current commit id of the files at the given location. | [
"Return",
"the",
"current",
"commit",
"id",
"of",
"the",
"files",
"at",
"the",
"given",
"location."
] | def get_revision(self, location):
raise NotImplementedError | ['def', 'get_revision(self,', 'location):', 'raise', 'NotImplementedError'] | 90,025 |
benanne/morb | utils.py | generate_data | generate_data | Creates a noisy dataset with some simple pattern in it. | [
"Creates",
"a",
"noisy",
"dataset",
"with",
"some",
"simple",
"pattern",
"in",
"it."
] | def generate_data(N):
T = N * 38
u = np.mat(np.zeros((T, 20)))
for i in range(1, T, 38):
if i % 76 == 1:
u[i - 1:i + 19, :] = np.eye(20)
u[i + 18:i + 38, :] = np.eye(20)[np.arange(19, -1, -1)]
u[i - 1:i + 19, :] += np.eye(20)[np.arange(19, -1, -1)]
else:
... | ['def', 'generate_data(N):', 'T', '=', 'N', '*', '38', 'u', '=', 'np.mat(np.zeros((T,', '20)))', 'for', 'i', 'in', 'range(1,', 'T,', '38):', 'if', 'i', '%', '76', '==', '1:', 'u[i', '-', '1:i', '+', '19,', ':]', '=', 'np.eye(20)', 'u[i', '+', '18:i', '+', '38,', ':]', '=', 'np.eye(20)[np.arange(19,', '-1,', '-1)]', 'u[... | 241,145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.