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 |
|---|---|---|---|---|---|---|---|---|
fangzhao2019/SSGNet-OIE | oieReader.py | OieReader.get_tabbed | get_tabbed | Get a tabbed format representation of this corpus (assumes that input was already read). | [
"Get",
"a",
"tabbed",
"format",
"representation",
"of",
"this",
"corpus",
"(assumes",
"that",
"input",
"was",
"already",
"read)."
] | def get_tabbed(self):
return '\n'.join(['\t'.join(map(str, [ex.sent, ex.confidence, ex.pred, '\t'.join(ex.args)])) for (sent, exs) in self.oie.iteritems() for ex in exs]) | ['def', 'get_tabbed(self):', 'return', "'\\n'.join(['\\t'.join(map(str,", '[ex.sent,', 'ex.confidence,', 'ex.pred,', "'\\t'.join(ex.args)]))", 'for', '(sent,', 'exs)', 'in', 'self.oie.iteritems()', 'for', 'ex', 'in', 'exs])'] | 872,065 |
Westlake-AI/openmixup | svm_classifier.py | svm_task | svm_task | The task function to train the model. | [
"The",
"task",
"function",
"to",
"train",
"the",
"model."
] | def svm_task(cls, cost, features, targets, model_path):
(out_file, ap_out_file) = SVMHelper.get_svm_train_output_files(cls, cost, model_path)
clf = LinearSVC(C=cost, class_weight={1: 2, -1: 1}, intercept_scaling=1.0, verbose=0, penalty='l2', loss='squared_hinge', tol=0.0001, dual=True, max_iter=2000)
cls_la... | ['def', 'svm_task(cls,', 'cost,', 'features,', 'targets,', 'model_path):', '(out_file,', 'ap_out_file)', '=', 'SVMHelper.get_svm_train_output_files(cls,', 'cost,', 'model_path)', 'clf', '=', 'LinearSVC(C=cost,', 'class_weight={1:', '2,', '-1:', '1},', 'intercept_scaling=1.0,', 'verbose=0,', "penalty='l2',", "loss='squa... | 252,557 |
thaines/helit | params.py | Kernel.toEquation | toEquation | Return a textural representation of the equation implimented by the kernel. | [
"Return",
"a",
"textural",
"representation",
"of",
"the",
"equation",
"implimented",
"by",
"the",
"kernel."
] | def toEquation(kernel):
data = {Kernel.linear: 'dot(x1,x2)', Kernel.homo_polynomial: 'dot(x1,x2)^p1', Kernel.polynomial: '(dot(x1,x2)+1)^p1', Kernel.rbf: 'exp(-p1||x1-x2||^2)', Kernel.gbf: 'exp(-||x1-x2||^2 / 2p1^2)', Kernel.sigmoid: 'tanh(p2*dot(x1,x2) + p1)'}
return data[kernel] | ['def', 'toEquation(kernel):', 'data', '=', '{Kernel.linear:', "'dot(x1,x2)',", 'Kernel.homo_polynomial:', "'dot(x1,x2)^p1',", 'Kernel.polynomial:', "'(dot(x1,x2)+1)^p1',", 'Kernel.rbf:', "'exp(-p1||x1-x2||^2)',", 'Kernel.gbf:', "'exp(-||x1-x2||^2", '/', "2p1^2)',", 'Kernel.sigmoid:', "'tanh(p2*dot(x1,x2)", '+', "p1)'}... | 592,536 |
eddylau328/fyp-artificial-intelligence-ac-control-device | iam.py | Policy.group | group | Factory method for a group member. | [
"Factory",
"method",
"for",
"a",
"group",
"member."
] | def group(email):
return 'group:%s' % (email,) | ['def', 'group(email):', 'return', "'group:%s'", '%', '(email,)'] | 214,475 |
aws/sagemaker-python-sdk | trial_component.py | _TrialComponent.list | list | Return a list of trial component summaries. | [
"Return",
"a",
"list",
"of",
"trial",
"component",
"summaries."
] | def list(cls, source_arn=None, created_before=None, created_after=None, sort_by=None, sort_order=None, sagemaker_session=None, trial_name=None, experiment_name=None, max_results=None, next_token=None):
return super(_TrialComponent, cls)._list('list_trial_components', _api_types.TrialComponentSummary.from_boto, 'Tri... | ['def', 'list(cls,', 'source_arn=None,', 'created_before=None,', 'created_after=None,', 'sort_by=None,', 'sort_order=None,', 'sagemaker_session=None,', 'trial_name=None,', 'experiment_name=None,', 'max_results=None,', 'next_token=None):', 'return', 'super(_TrialComponent,', "cls)._list('list_trial_components',", '_api_... | 829,970 |
muhanzhang/D-VAE | opt.py | local_mul_zero | local_mul_zero | As part of canonicalization, we replace multiplication by zero with zero. | [
"As",
"part",
"of",
"canonicalization,",
"we",
"replace",
"multiplication",
"by",
"zero",
"with",
"zero."
] | def local_mul_zero(node):
if node.op == T.mul:
otype = node.outputs[0].type
for i in node.inputs:
try:
value = get_scalar_constant_value(i)
except NotScalarConstantError:
continue
if value == 0:
return _fill_chain(th... | ['def', 'local_mul_zero(node):', 'if', 'node.op', '==', 'T.mul:', 'otype', '=', 'node.outputs[0].type', 'for', 'i', 'in', 'node.inputs:', 'try:', 'value', '=', 'get_scalar_constant_value(i)', 'except', 'NotScalarConstantError:', 'continue', 'if', 'value', '==', '0:', 'return', '_fill_chain(theano._asarray(0,', 'dtype=o... | 525,571 |
MCG-NJU/CGA-Net | basic_operators.py | ind_max_pool | ind_max_pool | This tensorflow operation compute a maxpooling according to the list of indices 'inds'. | [
"This",
"tensorflow",
"operation",
"compute",
"a",
"maxpooling",
"according",
"to",
"the",
"list",
"of",
"indices",
"'inds'."
] | def ind_max_pool(x, inds, scope):
with tf.variable_scope(scope) as sc:
x = tf.concat([x, tf.reduce_min(x, axis=0, keep_dims=True)], axis=0)
pool_features = tf.gather(x, inds, axis=0)
return tf.reduce_max(pool_features, axis=1) | ['def', 'ind_max_pool(x,', 'inds,', 'scope):', 'with', 'tf.variable_scope(scope)', 'as', 'sc:', 'x', '=', 'tf.concat([x,', 'tf.reduce_min(x,', 'axis=0,', 'keep_dims=True)],', 'axis=0)', 'pool_features', '=', 'tf.gather(x,', 'inds,', 'axis=0)', 'return', 'tf.reduce_max(pool_features,', 'axis=1)'] | 476,770 |
jialeli1/lidarseg3d | data_classes.py | DetectionMetricDataList.set | set | Sets the MetricData entry for a certain detection_name and match_distance. | [
"Sets",
"the",
"MetricData",
"entry",
"for",
"a",
"certain",
"detection_name",
"and",
"match_distance."
] | def set(self, detection_name: str, match_distance: float, data: DetectionMetricData):
self.md[detection_name, match_distance] = data | ['def', 'set(self,', 'detection_name:', 'str,', 'match_distance:', 'float,', 'data:', 'DetectionMetricData):', 'self.md[detection_name,', 'match_distance]', '=', 'data'] | 601,731 |
Katja-M/Python_NaturalLanguageProcessing | twitter_demo.py | expand_tweetids_demo | expand_tweetids_demo | Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available. | [
"Given",
"a",
"file",
"object",
"containing",
"a",
"list",
"of",
"Tweet",
"IDs,",
"fetch",
"the",
"corresponding",
"full",
"Tweets,",
"if",
"available."
] | def expand_tweetids_demo():
ids_f = StringIO(' 588665495492124672\n 588665495487909888\n 588665495508766721\n 588665495513006080\n 588665495517200384\n 588665495487811584\n 588665495525588992\n 588665495487844352\n 588665495492014081\n 5886654955... | ['def', 'expand_tweetids_demo():', 'ids_f', '=', "StringIO('", '588665495492124672\\n', '588665495487909888\\n', '588665495508766721\\n', '588665495513006080\\n', '588665495517200384\\n', '588665495487811584\\n', '588665495525588992\\n', '588665495487844352\\n', '588665495492014081\\n', "588665495512948737')", 'oauth',... | 867,295 |
YuYaoYang2333/SyntaLinker | inputter.py | build_vocab | build_vocab | Build the fields for all data sides. | [
"Build",
"the",
"fields",
"for",
"all",
"data",
"sides."
] | def build_vocab(train_dataset_files, fields, data_type, share_vocab, src_vocab_path, src_vocab_size, src_words_min_frequency, tgt_vocab_path, tgt_vocab_size, tgt_words_min_frequency, vocab_size_multiple=1):
counters = defaultdict(Counter)
if src_vocab_path:
try:
logger.info('Using existing v... | ['def', 'build_vocab(train_dataset_files,', 'fields,', 'data_type,', 'share_vocab,', 'src_vocab_path,', 'src_vocab_size,', 'src_words_min_frequency,', 'tgt_vocab_path,', 'tgt_vocab_size,', 'tgt_words_min_frequency,', 'vocab_size_multiple=1):', 'counters', '=', 'defaultdict(Counter)', 'if', 'src_vocab_path:', 'try:', "l... | 905,893 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | configHandler.py | IdleConf.SaveUserCfgFiles | SaveUserCfgFiles | Write all loaded user configuration files to disk. | [
"Write",
"all",
"loaded",
"user",
"configuration",
"files",
"to",
"disk."
] | def SaveUserCfgFiles(self):
for key in self.userCfg:
self.userCfg[key].Save() | ['def', 'SaveUserCfgFiles(self):', 'for', 'key', 'in', 'self.userCfg:', 'self.userCfg[key].Save()'] | 430,822 |
Eric3911/OpenAGI | export_utils.py | wrap_module | wrap_module | Generic function generator to replace BaseT module with DestT wrapper. | [
"Generic",
"function",
"generator",
"to",
"replace",
"BaseT",
"module",
"with",
"DestT",
"wrapper."
] | def wrap_module(BaseT: Type[nn.Module], DestT: Type[nn.Module]) -> Callable[[nn.Module], Optional[nn.Module]]:
def expansion_fn(mod: nn.Module) -> Optional[nn.Module]:
out = DestT(mod)
return out
return expansion_fn | ['def', 'wrap_module(BaseT:', 'Type[nn.Module],', 'DestT:', 'Type[nn.Module])', '->', 'Callable[[nn.Module],', 'Optional[nn.Module]]:', 'def', 'expansion_fn(mod:', 'nn.Module)', '->', 'Optional[nn.Module]:', 'out', '=', 'DestT(mod)', 'return', 'out', 'return', 'expansion_fn'] | 274,200 |
weimin17/Object-Detection_HelmetDetection | memory.py | LSHMemory.get_hash_slots | get_hash_slots | Gets hashed-to buckets for batch of queries. | [
"Gets",
"hashed-to",
"buckets",
"for",
"batch",
"of",
"queries."
] | def get_hash_slots(self, query):
binary_hash = [tf.less(tf.matmul(query, self.hash_vecs[i], transpose_b=True), 0) for i in xrange(self.num_libraries)]
hash_slot_idxs = [tf.reduce_sum(tf.to_int32(binary_hash[i]) * tf.constant([[2 ** i for i in xrange(self.num_hashes)]], dtype=tf.int32), 1) for i in xrange(self.n... | ['def', 'get_hash_slots(self,', 'query):', 'binary_hash', '=', '[tf.less(tf.matmul(query,', 'self.hash_vecs[i],', 'transpose_b=True),', '0)', 'for', 'i', 'in', 'xrange(self.num_libraries)]', 'hash_slot_idxs', '=', '[tf.reduce_sum(tf.to_int32(binary_hash[i])', '*', 'tf.constant([[2', '**', 'i', 'for', 'i', 'in', 'xrange... | 763,346 |
capjamesg/visionscript | lang.py | VisionScript.set_brightness | set_brightness | Set brightness of last image. | [
"Set",
"brightness",
"of",
"last",
"image."
] | def set_brightness(self, brightness):
image = self._get_item(-1, 'image_stack')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
(h, s, v) = cv2.split(hsv)
lim = 255 - brightness
v[v > lim] = 255
v[v <= lim] += brightness
final_hsv = cv2.merge((h, s, v))
image = cv2.cvtColor(final_hsv, cv2.C... | ['def', 'set_brightness(self,', 'brightness):', 'image', '=', 'self._get_item(-1,', "'image_stack')", 'hsv', '=', 'cv2.cvtColor(image,', 'cv2.COLOR_BGR2HSV)', '(h,', 's,', 'v)', '=', 'cv2.split(hsv)', 'lim', '=', '255', '-', 'brightness', 'v[v', '>', 'lim]', '=', '255', 'v[v', '<=', 'lim]', '+=', 'brightness', 'final_h... | 944,889 |
angeladai/ScanComplete | complete_scan.py | create_dfs_from_output | create_dfs_from_output | Rescales model output to distance fields (in voxel units). | [
"Rescales",
"model",
"output",
"to",
"distance",
"fields",
"(in",
"voxel",
"units)."
] | def create_dfs_from_output(input_sdf, output_df, target_scan):
input_sdf = (input_sdf[0, :, :, :, 0].astype(np.float32) + 1) * 0.5 * constants.TRUNCATION
if FLAGS.p_norm > 0:
factor = 0.5 if target_scan is not None else 1.0
output_df = factor * constants.TRUNCATION * (output_df[0, :, :, :, 0] + ... | ['def', 'create_dfs_from_output(input_sdf,', 'output_df,', 'target_scan):', 'input_sdf', '=', '(input_sdf[0,', ':,', ':,', ':,', '0].astype(np.float32)', '+', '1)', '*', '0.5', '*', 'constants.TRUNCATION', 'if', 'FLAGS.p_norm', '>', '0:', 'factor', '=', '0.5', 'if', 'target_scan', 'is', 'not', 'None', 'else', '1.0', 'o... | 845,839 |
ilya16/MultINN | data.py | prepare_sampling_inputs | prepare_sampling_inputs | Prepares inputs for the sampling based on the configurations. | [
"Prepares",
"inputs",
"for",
"the",
"sampling",
"based",
"on",
"the",
"configurations."
] | def prepare_sampling_inputs(X_train, X_valid, sampling_config, beat_size):
intro_beats = sampling_config['intro_beats']
intro_steps = int(intro_beats * beat_size)
intro_ids = sampling_config['intro_ids']
intro_train = X_train[intro_ids['train']['start']:intro_ids['train']['end'], :intro_steps, :]
in... | ['def', 'prepare_sampling_inputs(X_train,', 'X_valid,', 'sampling_config,', 'beat_size):', 'intro_beats', '=', "sampling_config['intro_beats']", 'intro_steps', '=', 'int(intro_beats', '*', 'beat_size)', 'intro_ids', '=', "sampling_config['intro_ids']", 'intro_train', '=', "X_train[intro_ids['train']['start']:intro_ids[... | 644,367 |
Sentdex/Carla-RL | transform.py | Transform.inverse | inverse | Return the inverse transform. | [
"Return",
"the",
"inverse",
"transform."
] | def inverse(self):
return Transform(matrix=numpy.linalg.inv(self.matrix)) | ['def', 'inverse(self):', 'return', 'Transform(matrix=numpy.linalg.inv(self.matrix))'] | 103,076 |
jxhe/self-training-text-generation | noise.py | NoiseLayer.word_dropout | word_dropout | Randomly drop input words. | [
"Randomly",
"drop",
"input",
"words."
] | def word_dropout(self, x, l):
if self.dropout_prob == 0:
return (x, l)
assert 0 < self.dropout_prob < 1
keep = np.random.rand(x.size(0) - 1, x.size(1)) >= self.dropout_prob
keep[0] = 1
sentences = []
lengths = []
for i in range(len(l)):
assert x[l[i] - 1, i] == self.eos_index... | ['def', 'word_dropout(self,', 'x,', 'l):', 'if', 'self.dropout_prob', '==', '0:', 'return', '(x,', 'l)', 'assert', '0', '<', 'self.dropout_prob', '<', '1', 'keep', '=', 'np.random.rand(x.size(0)', '-', '1,', 'x.size(1))', '>=', 'self.dropout_prob', 'keep[0]', '=', '1', 'sentences', '=', '[]', 'lengths', '=', '[]', 'for... | 843,857 |
tensortrade-org/tensortrade | observers.py | IntradayObserver.warmup | warmup | Warms up the data feed. | [
"Warms",
"up",
"the",
"data",
"feed."
] | def warmup(self) -> None:
if self.min_periods is not None:
for _ in range(self.min_periods):
if self.has_next():
obs_row = self.feed.next()['external']
obs_row.pop('timestamp', None)
self.history.push(obs_row) | ['def', 'warmup(self)', '->', 'None:', 'if', 'self.min_periods', 'is', 'not', 'None:', 'for', '_', 'in', 'range(self.min_periods):', 'if', 'self.has_next():', 'obs_row', '=', "self.feed.next()['external']", "obs_row.pop('timestamp',", 'None)', 'self.history.push(obs_row)'] | 366,415 |
triaquae/triaquae | forms.py | BoundField.value | value | Returns the value for this BoundField, using the initial value if the form is not bound or the data otherwise. | [
"Returns",
"the",
"value",
"for",
"this",
"BoundField,",
"using",
"the",
"initial",
"value",
"if",
"the",
"form",
"is",
"not",
"bound",
"or",
"the",
"data",
"otherwise."
] | def value(self):
if not self.form.is_bound:
data = self.form.initial.get(self.name, self.field.initial)
if callable(data):
data = data()
else:
data = self.field.bound_data(self.data, self.form.initial.get(self.name, self.field.initial))
return self.field.prepare_value(dat... | ['def', 'value(self):', 'if', 'not', 'self.form.is_bound:', 'data', '=', 'self.form.initial.get(self.name,', 'self.field.initial)', 'if', 'callable(data):', 'data', '=', 'data()', 'else:', 'data', '=', 'self.field.bound_data(self.data,', 'self.form.initial.get(self.name,', 'self.field.initial))', 'return', 'self.field.... | 423,678 |
spryor/Natural-Language-Processing | tfidf.py | TfIdf.candidate_weighting | candidate_weighting | Candidate weighting function using document frequencies. | [
"Candidate",
"weighting",
"function",
"using",
"document",
"frequencies."
] | def candidate_weighting(self, df=None):
if df is None:
logging.warning('LoadFile._df_counts is hard coded to {}'.format(self._df_counts))
df = load_document_frequency_file(self._df_counts, delimiter='\t')
N = 1 + df.get('--NB_DOC--', 0)
for (k, v) in self.candidates.items():
candidat... | ['def', 'candidate_weighting(self,', 'df=None):', 'if', 'df', 'is', 'None:', "logging.warning('LoadFile._df_counts", 'is', 'hard', 'coded', 'to', "{}'.format(self._df_counts))", 'df', '=', 'load_document_frequency_file(self._df_counts,', "delimiter='\\t')", 'N', '=', '1', '+', "df.get('--NB_DOC--',", '0)', 'for', '(k,'... | 662,179 |
rifqind/Agent-Programs-3KS1 | test_run.py | TestMagicRunSimple.test_run_formatting | test_run_formatting | Test that %run -t -N<N> does not raise a TypeError for N > 1. | [
"Test",
"that",
"%run",
"-t",
"-N<N>",
"does",
"not",
"raise",
"a",
"TypeError",
"for",
"N",
">",
"1."
] | def test_run_formatting(self):
src = 'pass'
self.mktmp(src)
_ip.magic('run -t -N 1 %s' % self.fname)
_ip.magic('run -t -N 10 %s' % self.fname) | ['def', 'test_run_formatting(self):', 'src', '=', "'pass'", 'self.mktmp(src)', "_ip.magic('run", '-t', '-N', '1', "%s'", '%', 'self.fname)', "_ip.magic('run", '-t', '-N', '10', "%s'", '%', 'self.fname)'] | 41,540 |
gradio-app/gradio | checkbox.py | Checkbox.get_interpretation_scores | get_interpretation_scores | Returns: The first value represents the interpretation score if the input is False, and the second if the input is True. | [
"Returns:",
"The",
"first",
"value",
"represents",
"the",
"interpretation",
"score",
"if",
"the",
"input",
"is",
"False,",
"and",
"the",
"second",
"if",
"the",
"input",
"is",
"True."
] | def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
if x:
return (scores[0], None)
else:
return (None, scores[0]) | ['def', 'get_interpretation_scores(self,', 'x,', 'neighbors,', 'scores,', '**kwargs):', 'if', 'x:', 'return', '(scores[0],', 'None)', 'else:', 'return', '(None,', 'scores[0])'] | 578,898 |
KaiyangZhou/Dassl.pytorch | ddaig_fcn.py | FCN.init_loc_layer | init_loc_layer | Initialize the weights/bias with identity transformation. | [
"Initialize",
"the",
"weights/bias",
"with",
"identity",
"transformation."
] | def init_loc_layer(self):
if self.locnet is not None:
self.locnet.fc_loc.weight.data.zero_()
self.locnet.fc_loc.bias.data.copy_(torch.tensor([1, 0, 0, 1], dtype=torch.float)) | ['def', 'init_loc_layer(self):', 'if', 'self.locnet', 'is', 'not', 'None:', 'self.locnet.fc_loc.weight.data.zero_()', 'self.locnet.fc_loc.bias.data.copy_(torch.tensor([1,', '0,', '0,', '1],', 'dtype=torch.float))'] | 126,748 |
deepmind/dm_control | mocap_playback.py | mocap_playback_env | mocap_playback_env | Constructs mocap playback environment. | [
"Constructs",
"mocap",
"playback",
"environment."
] | def mocap_playback_env(random_state=None):
walker_type = walkers.CMUHumanoidPositionControlledV2020
arena = arenas.Floor()
task = tracking.PlaybackTask(walker=walker_type, arena=arena, ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'), dataset='run_jump_tiny')
return composer.Environment(time_lim... | ['def', 'mocap_playback_env(random_state=None):', 'walker_type', '=', 'walkers.CMUHumanoidPositionControlledV2020', 'arena', '=', 'arenas.Floor()', 'task', '=', 'tracking.PlaybackTask(walker=walker_type,', 'arena=arena,', "ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'),", "dataset='run_jump_tiny')", 'return',... | 165,959 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | program_utils.py | ProgramGrower.grow_body | grow_body | Grow the program body. | [
"Grow",
"the",
"program",
"body."
] | def grow_body(self, new_var_name, dependencies, types_to_vars):
choices = []
for f in self.functions:
if all([a in types_to_vars.keys() for a in f.arg_types]):
choices.append(f)
f = random.choice(choices)
args = []
for t in f.arg_types:
possible_vars = random.choice(types... | ['def', 'grow_body(self,', 'new_var_name,', 'dependencies,', 'types_to_vars):', 'choices', '=', '[]', 'for', 'f', 'in', 'self.functions:', 'if', 'all([a', 'in', 'types_to_vars.keys()', 'for', 'a', 'in', 'f.arg_types]):', 'choices.append(f)', 'f', '=', 'random.choice(choices)', 'args', '=', '[]', 'for', 't', 'in', 'f.ar... | 50,226 |
ZhAnGToNG1/transfer_learning_cspt | test_fcos_head.py | test_fcos_head_loss | test_fcos_head_loss | Tests fcos head loss when truth is empty and non-empty. | [
"Tests",
"fcos",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_fcos_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
train_cfg = mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False))
self... | ['def', 'test_fcos_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'train_cfg', '=', "mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner',", 'pos_iou_thr=0.5,', 'neg_iou_thr=0.4,', 'min_pos_iou=0,', 'ignore_iof_thr=-1... | 964,336 |
RasaHQ/rasa | message.py | Message.find_overlapping_entities | find_overlapping_entities | Finds any overlapping entity annotations. | [
"Finds",
"any",
"overlapping",
"entity",
"annotations."
] | def find_overlapping_entities(self) -> List[Tuple[Dict[Text, Any], Dict[Text, Any]]]:
entities = self.get(ENTITIES, [])[:]
entities_with_location = [e for e in entities if ENTITY_ATTRIBUTE_START in e.keys() and ENTITY_ATTRIBUTE_END in e.keys()]
entities_with_location.sort(key=lambda e: e[ENTITY_ATTRIBUTE_ST... | ['def', 'find_overlapping_entities(self)', '->', 'List[Tuple[Dict[Text,', 'Any],', 'Dict[Text,', 'Any]]]:', 'entities', '=', 'self.get(ENTITIES,', '[])[:]', 'entities_with_location', '=', '[e', 'for', 'e', 'in', 'entities', 'if', 'ENTITY_ATTRIBUTE_START', 'in', 'e.keys()', 'and', 'ENTITY_ATTRIBUTE_END', 'in', 'e.keys()... | 837,696 |
rifqind/Agent-Programs-3KS1 | test_contents_api.py | uniq_stable | uniq_stable | uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, maintaining the order in which they first appear. | [
"uniq_stable(elems)",
"->",
"list",
"Return",
"from",
"an",
"iterable,",
"a",
"list",
"of",
"all",
"the",
"unique",
"elements",
"in",
"the",
"input,",
"maintaining",
"the",
"order",
"in",
"which",
"they",
"first",
"appear."
] | def uniq_stable(elems):
seen = set()
return [x for x in elems if x not in seen and (not seen.add(x))] | ['def', 'uniq_stable(elems):', 'seen', '=', 'set()', 'return', '[x', 'for', 'x', 'in', 'elems', 'if', 'x', 'not', 'in', 'seen', 'and', '(not', 'seen.add(x))]'] | 43,268 |
imoscovitz/wittgenstein | ripper.py | RIPPER.fit | fit | Fit a Ruleset model using a training DataFrame. | [
"Fit",
"a",
"Ruleset",
"model",
"using",
"a",
"training",
"DataFrame."
] | def fit(self, df, y=None, class_feat=None, pos_class=None, n_discretize_bins=None, random_state=None):
(df, self.class_feat, self.pos_class) = base.trainset_classfeat_posclass(df, y=y, class_feat=class_feat, pos_class=pos_class)
numeric_feats = base.find_numeric_feats(df, min_unique=n_discretize_bins, ignore_fe... | ['def', 'fit(self,', 'df,', 'y=None,', 'class_feat=None,', 'pos_class=None,', 'n_discretize_bins=None,', 'random_state=None):', '(df,', 'self.class_feat,', 'self.pos_class)', '=', 'base.trainset_classfeat_posclass(df,', 'y=y,', 'class_feat=class_feat,', 'pos_class=pos_class)', 'numeric_feats', '=', 'base.find_numeric_f... | 959,836 |
xvjiarui/VFS | davis_dataset.py | DavisDataset.prepare_test_frames | prepare_test_frames | Prepare the frames for testing given the index. | [
"Prepare",
"the",
"frames",
"for",
"testing",
"given",
"the",
"index."
] | def prepare_test_frames(self, idx):
results = copy.deepcopy(self.video_infos[idx])
results['filename_tmpl'] = self.filename_tmpl
results['modality'] = self.modality
results['start_index'] = self.start_index
ann_frame_dir = results['frame_dir'].replace(self.data_prefix, self.anno_prefix)
results[... | ['def', 'prepare_test_frames(self,', 'idx):', 'results', '=', 'copy.deepcopy(self.video_infos[idx])', "results['filename_tmpl']", '=', 'self.filename_tmpl', "results['modality']", '=', 'self.modality', "results['start_index']", '=', 'self.start_index', 'ann_frame_dir', '=', "results['frame_dir'].replace(self.data_prefi... | 379,570 |
goace/personal-file-sharing-center | wsgi.py | runfcgi | runfcgi | Runs a WSGI function as a FastCGI server. | [
"Runs",
"a",
"WSGI",
"function",
"as",
"a",
"FastCGI",
"server."
] | def runfcgi(func, addr=('localhost', 8000)):
import flup.server.fcgi as flups
return flups.WSGIServer(func, multiplexed=True, bindAddress=addr, debug=False).run() | ['def', 'runfcgi(func,', "addr=('localhost',", '8000)):', 'import', 'flup.server.fcgi', 'as', 'flups', 'return', 'flups.WSGIServer(func,', 'multiplexed=True,', 'bindAddress=addr,', 'debug=False).run()'] | 304,611 |
mj-will/nessai | test_base_proposal.py | test_initialised_setter | test_initialised_setter | Test the setter for initialised. | [
"Test",
"the",
"setter",
"for",
"initialised."
] | def test_initialised_setter(proposal, val):
Proposal.initialised.__set__(proposal, val)
assert proposal._initialised is val | ['def', 'test_initialised_setter(proposal,', 'val):', 'Proposal.initialised.__set__(proposal,', 'val)', 'assert', 'proposal._initialised', 'is', 'val'] | 292,658 |
matsu0228/nlp-jp | coherencemodel.py | CoherenceModel.for_topics | for_topics | Initialize a CoherenceModel with estimated probabilities for all of the given topics. | [
"Initialize",
"a",
"CoherenceModel",
"with",
"estimated",
"probabilities",
"for",
"all",
"of",
"the",
"given",
"topics."
] | def for_topics(cls, topics_as_topn_terms, **kwargs):
if not topics_as_topn_terms:
raise ValueError('len(topics) must be > 0.')
if any((len(topic_lists) == 0 for topic_lists in topics_as_topn_terms)):
raise ValueError('found empty topic listing in `topics`')
topn = 0
for topic_list in top... | ['def', 'for_topics(cls,', 'topics_as_topn_terms,', '**kwargs):', 'if', 'not', 'topics_as_topn_terms:', 'raise', "ValueError('len(topics)", 'must', 'be', '>', "0.')", 'if', 'any((len(topic_lists)', '==', '0', 'for', 'topic_lists', 'in', 'topics_as_topn_terms)):', 'raise', "ValueError('found", 'empty', 'topic', 'listing... | 785,765 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | gather_blocks_2d | gather_blocks_2d | Gathers flattened blocks from x. | [
"Gathers",
"flattened",
"blocks",
"from",
"x."
] | def gather_blocks_2d(x, indices):
x_shape = common_layers.shape_list(x)
x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])])
x_t = tf.transpose(x, [2, 0, 1, 3])
x_new = tf.gather(x_t, indices)
return tf.transpose(x_new, [2, 3, 0, 1, 4]) | ['def', 'gather_blocks_2d(x,', 'indices):', 'x_shape', '=', 'common_layers.shape_list(x)', 'x', '=', 'reshape_range(x,', '2,', '4,', '[tf.reduce_prod(x_shape[2:4])])', 'x_t', '=', 'tf.transpose(x,', '[2,', '0,', '1,', '3])', 'x_new', '=', 'tf.gather(x_t,', 'indices)', 'return', 'tf.transpose(x_new,', '[2,', '3,', '0,',... | 965,169 |
intel/neural-compressor | scheduler.py | Scheduler.train_func | train_func | Do not support get train_func. | [
"Do",
"not",
"support",
"get",
"train_func."
] | def train_func(self):
assert False, 'Should not try to get the value of `train_func` attribute.'
return None | ['def', 'train_func(self):', 'assert', 'False,', "'Should", 'not', 'try', 'to', 'get', 'the', 'value', 'of', '`train_func`', "attribute.'", 'return', 'None'] | 738,426 |
sarnsdev/social-alignment-data-mining | _in_process.py | get_requires_for_build_sdist | get_requires_for_build_sdist | Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined. | [
"Invoke",
"the",
"optional",
"get_requires_for_build_wheel",
"hook",
"Returns",
"[]",
"if",
"the",
"hook",
"is",
"not",
"defined."
] | def get_requires_for_build_sdist(config_settings):
backend = _build_backend()
try:
hook = backend.get_requires_for_build_sdist
except AttributeError:
return []
else:
return hook(config_settings) | ['def', 'get_requires_for_build_sdist(config_settings):', 'backend', '=', '_build_backend()', 'try:', 'hook', '=', 'backend.get_requires_for_build_sdist', 'except', 'AttributeError:', 'return', '[]', 'else:', 'return', 'hook(config_settings)'] | 390,272 |
tfzhou/ContrastiveSeg | base.py | _BaseEvaluator.prepare_validaton | prepare_validaton | Replicate models if using diverse size validation. | [
"Replicate",
"models",
"if",
"using",
"diverse",
"size",
"validation."
] | def prepare_validaton(self):
if is_distributed():
return
device_ids = list(range(len(self.configer.get('gpu'))))
if self.conditions.diverse_size:
cudnn.benchmark = False
assert self.configer.get('val', 'batch_size') <= len(device_ids)
replicas = nn.parallel.replicate(self.tra... | ['def', 'prepare_validaton(self):', 'if', 'is_distributed():', 'return', 'device_ids', '=', "list(range(len(self.configer.get('gpu'))))", 'if', 'self.conditions.diverse_size:', 'cudnn.benchmark', '=', 'False', 'assert', "self.configer.get('val',", "'batch_size')", '<=', 'len(device_ids)', 'replicas', '=', 'nn.parallel.... | 488,760 |
bfshi/TOAST | distributed.py | local_cat_all_gather | local_cat_all_gather | Performs the concatenated all_gather operation on the provided tensors. | [
"Performs",
"the",
"concatenated",
"all_gather",
"operation",
"on",
"the",
"provided",
"tensors."
] | def local_cat_all_gather(tensors):
tensors_gather = [torch.ones_like(tensors) for _ in range(get_local_size())]
torch.distributed.all_gather(tensors_gather, tensors, async_op=False, group=_LOCAL_PROCESS_GROUP)
output = torch.cat(tensors_gather, dim=0)
return output | ['def', 'local_cat_all_gather(tensors):', 'tensors_gather', '=', '[torch.ones_like(tensors)', 'for', '_', 'in', 'range(get_local_size())]', 'torch.distributed.all_gather(tensors_gather,', 'tensors,', 'async_op=False,', 'group=_LOCAL_PROCESS_GROUP)', 'output', '=', 'torch.cat(tensors_gather,', 'dim=0)', 'return', 'outpu... | 901,680 |
HyeonwooNoh/VQA-Transfer-ExternalData | WikiExtractor.py | Extractor.clean | clean | Removes irrelevant parts from :param: text. | [
"Removes",
"irrelevant",
"parts",
"from",
":param:",
"text."
] | def clean(self, text):
spans = []
for m in comment.finditer(text):
spans.append((m.start(), m.end()))
for pattern in selfClosing_tag_patterns:
for m in pattern.finditer(text):
spans.append((m.start(), m.end()))
for (left, right) in options.ignored_tag_patterns:
for m ... | ['def', 'clean(self,', 'text):', 'spans', '=', '[]', 'for', 'm', 'in', 'comment.finditer(text):', 'spans.append((m.start(),', 'm.end()))', 'for', 'pattern', 'in', 'selfClosing_tag_patterns:', 'for', 'm', 'in', 'pattern.finditer(text):', 'spans.append((m.start(),', 'm.end()))', 'for', '(left,', 'right)', 'in', 'options.... | 380,943 |
TengXiaoDai/DistributedCrawling | keys.py | WheelKeys.add_signer | add_signer | Remember verifying key vk as being valid for signing in scope. | [
"Remember",
"verifying",
"key",
"vk",
"as",
"being",
"valid",
"for",
"signing",
"in",
"scope."
] | def add_signer(self, scope, vk):
self.data['signers'].append({'scope': scope, 'vk': vk}) | ['def', 'add_signer(self,', 'scope,', 'vk):', "self.data['signers'].append({'scope':", 'scope,', "'vk':", 'vk})'] | 189,411 |
datamllab/rlcard | logger.py | Logger.log | log | Write the text to log file then print it. | [
"Write",
"the",
"text",
"to",
"log",
"file",
"then",
"print",
"it."
] | def log(self, text):
self.txt_file.write(text + '\n')
self.txt_file.flush()
print(text) | ['def', 'log(self,', 'text):', 'self.txt_file.write(text', '+', "'\\n')", 'self.txt_file.flush()', 'print(text)'] | 332,117 |
matsu0228/nlp-jp | screen.py | screen.cursor_constrain | cursor_constrain | This keeps the cursor within the screen area. | [
"This",
"keeps",
"the",
"cursor",
"within",
"the",
"screen",
"area."
] | def cursor_constrain(self):
self.cur_r = constrain(self.cur_r, 1, self.rows)
self.cur_c = constrain(self.cur_c, 1, self.cols) | ['def', 'cursor_constrain(self):', 'self.cur_r', '=', 'constrain(self.cur_r,', '1,', 'self.rows)', 'self.cur_c', '=', 'constrain(self.cur_c,', '1,', 'self.cols)'] | 803,239 |
cleanlab/cleanlab | label.py | LabelIssueManager.get_health_summary | get_health_summary | Returns a short summary of the health of this Lab. | [
"Returns",
"a",
"short",
"summary",
"of",
"the",
"health",
"of",
"this",
"Lab."
] | def get_health_summary(self, pred_probs) -> dict:
from cleanlab.dataset import health_summary
self._validate_pred_probs(pred_probs)
summary_kwargs = self._get_summary_parameters(pred_probs)
summary = health_summary(**summary_kwargs)
return summary | ['def', 'get_health_summary(self,', 'pred_probs)', '->', 'dict:', 'from', 'cleanlab.dataset', 'import', 'health_summary', 'self._validate_pred_probs(pred_probs)', 'summary_kwargs', '=', 'self._get_summary_parameters(pred_probs)', 'summary', '=', 'health_summary(**summary_kwargs)', 'return', 'summary'] | 487,980 |
ryu-ed/SpaceInvaders_Ros | test_filter_design.py | TestSos2Zpk.test_fewer_zeros | test_fewer_zeros | Test not the expected number of p/z (effectively at origin). | [
"Test",
"not",
"the",
"expected",
"number",
"of",
"p/z",
"(effectively",
"at",
"origin)."
] | def test_fewer_zeros(self):
sos = butter(3, 0.1, output='sos')
(z, p, k) = sos2zpk(sos)
assert len(z) == 4
assert len(p) == 4
sos = butter(12, [5.0, 30.0], 'bandpass', fs=1200.0, analog=False, output='sos')
with pytest.warns(BadCoefficients, match='Badly conditioned'):
(z, p, k) = sos2zp... | ['def', 'test_fewer_zeros(self):', 'sos', '=', 'butter(3,', '0.1,', "output='sos')", '(z,', 'p,', 'k)', '=', 'sos2zpk(sos)', 'assert', 'len(z)', '==', '4', 'assert', 'len(p)', '==', '4', 'sos', '=', 'butter(12,', '[5.0,', '30.0],', "'bandpass',", 'fs=1200.0,', 'analog=False,', "output='sos')", 'with', 'pytest.warns(Bad... | 370,916 |
microsoft/maro | port.py | Port.name | name | str: Name of this port. | [
"str:",
"Name",
"of",
"this",
"port."
] | def name(self) -> str:
return self._name | ['def', 'name(self)', '->', 'str:', 'return', 'self._name'] | 628,639 |
weimin17/Object-Detection_HelmetDetection | preprocessing.py | shapestring | shapestring | Returns a compact string describing shape of an array. | [
"Returns",
"a",
"compact",
"string",
"describing",
"shape",
"of",
"an",
"array."
] | def shapestring(array):
shape = array.shape
s = str(shape[0])
for i in range(1, len(shape)):
s += 'x' + str(shape[i])
return s | ['def', 'shapestring(array):', 'shape', '=', 'array.shape', 's', '=', 'str(shape[0])', 'for', 'i', 'in', 'range(1,', 'len(shape)):', 's', '+=', "'x'", '+', 'str(shape[i])', 'return', 's'] | 753,792 |
liruiw/Dec-SSL | utils.py | average_weights | average_weights | Returns the average of the weights. | [
"Returns",
"the",
"average",
"of",
"the",
"weights."
] | def average_weights(w, avg_weights=None):
w_avg = copy.deepcopy(w[0])
for key in w[0].keys():
for i in range(1, len(w)):
w_avg[key] = w_avg[key] + w[i][key]
w_avg[key] = torch.div(w_avg[key], len(w))
return w_avg | ['def', 'average_weights(w,', 'avg_weights=None):', 'w_avg', '=', 'copy.deepcopy(w[0])', 'for', 'key', 'in', 'w[0].keys():', 'for', 'i', 'in', 'range(1,', 'len(w)):', 'w_avg[key]', '=', 'w_avg[key]', '+', 'w[i][key]', 'w_avg[key]', '=', 'torch.div(w_avg[key],', 'len(w))', 'return', 'w_avg'] | 127,110 |
weimin17/Object-Detection_HelmetDetection | utils.py | print_op | print_op | Print a string and return an op wrapped in a control dependency to make sure it ran. | [
"Print",
"a",
"string",
"and",
"return",
"an",
"op",
"wrapped",
"in",
"a",
"control",
"dependency",
"to",
"make",
"sure",
"it",
"ran."
] | def print_op(op, msg):
print_op = tf.Print(tf.constant(0), [tf.constant(0)], msg)
return tf.group(op, print_op) | ['def', 'print_op(op,', 'msg):', 'print_op', '=', 'tf.Print(tf.constant(0),', '[tf.constant(0)],', 'msg)', 'return', 'tf.group(op,', 'print_op)'] | 750,453 |
43Carrig/recurrent_neural_networks_practice | metrics_impl.py | sparse_precision_at_k | sparse_precision_at_k | Renamed to `precision_at_k`, please use that method instead. | [
"Renamed",
"to",
"`precision_at_k`,",
"please",
"use",
"that",
"method",
"instead."
] | def sparse_precision_at_k(labels, predictions, k, class_id=None, weights=None, metrics_collections=None, updates_collections=None, name=None):
return precision_at_k(labels=labels, predictions=predictions, k=k, class_id=class_id, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_c... | ['def', 'sparse_precision_at_k(labels,', 'predictions,', 'k,', 'class_id=None,', 'weights=None,', 'metrics_collections=None,', 'updates_collections=None,', 'name=None):', 'return', 'precision_at_k(labels=labels,', 'predictions=predictions,', 'k=k,', 'class_id=class_id,', 'weights=weights,', 'metrics_collections=metrics... | 338,856 |
sek788432/Waymo-2D-Object-Detection | ffn_layer.py | FeedForwardNetwork.call | call | Return outputs of the feedforward network. | [
"Return",
"outputs",
"of",
"the",
"feedforward",
"network."
] | def call(self, x, training):
output = self.filter_dense_layer(x)
if training:
output = tf.nn.dropout(output, rate=self.relu_dropout)
output = self.output_dense_layer(output)
return output | ['def', 'call(self,', 'x,', 'training):', 'output', '=', 'self.filter_dense_layer(x)', 'if', 'training:', 'output', '=', 'tf.nn.dropout(output,', 'rate=self.relu_dropout)', 'output', '=', 'self.output_dense_layer(output)', 'return', 'output'] | 972,848 |
wuzheng-sjtu/FastFPN | roi.py | encode | encode | Matching and Encoding groundtruth boxes (gt_boxes) into learning targets to boxes Sampling Parameters --------- gt_boxes an array of shape (G x 5), [x1, y1, x2, y2, class] rois an array of shape (R x 4), [x1, y1, x2, y2] num_classes: scalar, number of classes Returns -------- labels: Nx1 array in [0, num_classes) bbox_... | [
"Matching",
"and",
"Encoding",
"groundtruth",
"boxes",
"(gt_boxes)",
"into",
"learning",
"targets",
"to",
"boxes",
"Sampling",
"Parameters",
"---------",
"gt_boxes",
"an",
"array",
"of",
"shape",
"(G",
"x",
"5),",
"[x1,",
"y1,",
"x2,",
"y2,",
"class]",
"rois",
... | def encode(gt_boxes, rois, num_classes):
all_rois = rois
num_rois = rois.shape[0]
if gt_boxes.size > 0:
overlaps = cython_bbox.bbox_overlaps(np.ascontiguousarray(all_rois[:, 0:4], dtype=np.float), np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))
gt_assignment = overlaps.argmax(axis=1)
... | ['def', 'encode(gt_boxes,', 'rois,', 'num_classes):', 'all_rois', '=', 'rois', 'num_rois', '=', 'rois.shape[0]', 'if', 'gt_boxes.size', '>', '0:', 'overlaps', '=', 'cython_bbox.bbox_overlaps(np.ascontiguousarray(all_rois[:,', '0:4],', 'dtype=np.float),', 'np.ascontiguousarray(gt_boxes[:,', ':4],', 'dtype=np.float))', '... | 559,760 |
weimin17/Object-Detection_HelmetDetection | lexnet_model.py | parse_tensorflow_examples | parse_tensorflow_examples | Reads TensorFlow examples from a RecordReader. | [
"Reads",
"TensorFlow",
"examples",
"from",
"a",
"RecordReader."
] | def parse_tensorflow_examples(record, batch_size, path_to_index):
features = tf.parse_example(record, {'x_embedding_id': tf.FixedLenFeature([1], dtype=tf.int64), 'y_embedding_id': tf.FixedLenFeature([1], dtype=tf.int64), 'nc_embedding_id': tf.FixedLenFeature([1], dtype=tf.int64), 'reprs': tf.FixedLenSequenceFeature... | ['def', 'parse_tensorflow_examples(record,', 'batch_size,', 'path_to_index):', 'features', '=', 'tf.parse_example(record,', "{'x_embedding_id':", 'tf.FixedLenFeature([1],', 'dtype=tf.int64),', "'y_embedding_id':", 'tf.FixedLenFeature([1],', 'dtype=tf.int64),', "'nc_embedding_id':", 'tf.FixedLenFeature([1],', 'dtype=tf.... | 757,733 |
hikvision-research/SSOD | semi_base.py | SemiBaseDetector.cuda | cuda | Since ema_model is registered as a plain object, it is necessary to put the ema model to cuda when calling cuda function. | [
"Since",
"ema_model",
"is",
"registered",
"as",
"a",
"plain",
"object,",
"it",
"is",
"necessary",
"to",
"put",
"the",
"ema",
"model",
"to",
"cuda",
"when",
"calling",
"cuda",
"function."
] | def cuda(self, device=None):
if self.ema_model:
self.ema_model.cuda(device=device)
return super().cuda(device=device) | ['def', 'cuda(self,', 'device=None):', 'if', 'self.ema_model:', 'self.ema_model.cuda(device=device)', 'return', 'super().cuda(device=device)'] | 872,101 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tiles.py | stitch_image | stitch_image | Stitches two images together in-place. | [
"Stitches",
"two",
"images",
"together",
"in-place."
] | def stitch_image(into, into_box, image, image_box):
into.paste(image.crop(box=image_box), box=into_box) | ['def', 'stitch_image(into,', 'into_box,', 'image,', 'image_box):', 'into.paste(image.crop(box=image_box),', 'box=into_box)'] | 18,104 |
kukuruza/shuffler | general.py | copyWithBackup | copyWithBackup | Copy in_path into out_path, which is backed up if already exists. | [
"Copy",
"in_path",
"into",
"out_path,",
"which",
"is",
"backed",
"up",
"if",
"already",
"exists."
] | def copyWithBackup(in_path, out_path):
if not op.exists(in_path):
raise FileNotFoundError('File does not exist: "%s"' % in_path)
if op.exists(out_path):
logging.warning('Will back up existing out_path "%s"', out_path)
ext = op.splitext(out_path)[1]
backup_path = op.splitext(out_p... | ['def', 'copyWithBackup(in_path,', 'out_path):', 'if', 'not', 'op.exists(in_path):', 'raise', "FileNotFoundError('File", 'does', 'not', 'exist:', '"%s"\'', '%', 'in_path)', 'if', 'op.exists(out_path):', "logging.warning('Will", 'back', 'up', 'existing', 'out_path', '"%s"\',', 'out_path)', 'ext', '=', 'op.splitext(out_p... | 933,900 |
KalleHallden/InstaAutomator | _tifffile.py | TiffFile.close | close | Close open file handle(s). | [
"Close",
"open",
"file",
"handle(s)."
] | def close(self):
for tif in self._files.values():
tif._fh.close()
self._files = {} | ['def', 'close(self):', 'for', 'tif', 'in', 'self._files.values():', 'tif._fh.close()', 'self._files', '=', '{}'] | 242,544 |
tensorflow/data-validation | schema_util.py | get_bytes_features | get_bytes_features | Get the list of features that should be treated as bytes. | [
"Get",
"the",
"list",
"of",
"features",
"that",
"should",
"be",
"treated",
"as",
"bytes."
] | def get_bytes_features(schema: schema_pb2.Schema) -> List[types.FeaturePath]:
bytes_features = []
for (feature_path, feature) in get_all_leaf_features(schema):
domain_info = feature.WhichOneof('domain_info')
if domain_info == 'image_domain':
bytes_features.append(feature_path)
re... | ['def', 'get_bytes_features(schema:', 'schema_pb2.Schema)', '->', 'List[types.FeaturePath]:', 'bytes_features', '=', '[]', 'for', '(feature_path,', 'feature)', 'in', 'get_all_leaf_features(schema):', 'domain_info', '=', "feature.WhichOneof('domain_info')", 'if', 'domain_info', '==', "'image_domain':", 'bytes_features.a... | 497,630 |
TidalPaladin/trader | model.py | Downsample.call | call | Runs the forward pass for this layer Arguments: input: input tensor(s) training: boolean, whether or not Keyword Arguments: Forwarded to call() of each component layer. | [
"Runs",
"the",
"forward",
"pass",
"for",
"this",
"layer",
"Arguments:",
"input:",
"input",
"tensor(s)",
"training:",
"boolean,",
"whether",
"or",
"not",
"Keyword",
"Arguments:",
"Forwarded",
"to",
"call()",
"of",
"each",
"component",
"layer."
] | def call(self, inputs, training=False, **kwargs):
_ = self.bn1(inputs, training=training)
_ = self.relu1(_)
_ = self.channel_conv_1(_)
_ = self.bn2(_, training=training)
_ = self.relu2(_)
_ = self.spatial_conv(_)
m = self.bn_main(inputs, training=training)
m = self.relu_main(m)
main ... | ['def', 'call(self,', 'inputs,', 'training=False,', '**kwargs):', '_', '=', 'self.bn1(inputs,', 'training=training)', '_', '=', 'self.relu1(_)', '_', '=', 'self.channel_conv_1(_)', '_', '=', 'self.bn2(_,', 'training=training)', '_', '=', 'self.relu2(_)', '_', '=', 'self.spatial_conv(_)', 'm', '=', 'self.bn_main(inputs,... | 903,673 |
srai-lab/srai | test_administrative_boundary_regionalizer.py | test_points_in_result | test_points_in_result | Test checks case when points are in a requested region. | [
"Test",
"checks",
"case",
"when",
"points",
"are",
"in",
"a",
"requested",
"region."
] | def test_points_in_result(toposimplify: Union[bool, float], request: Any) -> None:
request.getfixturevalue('mock_overpass_api')
request_gdf = gpd.GeoDataFrame({GEOMETRY_COLUMN: [Point(0.5, 0.5)]}, crs=WGS84_CRS)
abr = AdministrativeBoundaryRegionalizer(admin_level=2, return_empty_region=False, clip_regions=... | ['def', 'test_points_in_result(toposimplify:', 'Union[bool,', 'float],', 'request:', 'Any)', '->', 'None:', "request.getfixturevalue('mock_overpass_api')", 'request_gdf', '=', 'gpd.GeoDataFrame({GEOMETRY_COLUMN:', '[Point(0.5,', '0.5)]},', 'crs=WGS84_CRS)', 'abr', '=', 'AdministrativeBoundaryRegionalizer(admin_level=2,... | 372,113 |
michiyasunaga/BIFI | transformer_layer.py | TransformerDecoderLayer.reorder_incremental_state | reorder_incremental_state | Scriptable reorder incremental state in transformer layers. | [
"Scriptable",
"reorder",
"incremental",
"state",
"in",
"transformer",
"layers."
] | def reorder_incremental_state(self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order: Tensor):
self.self_attn.reorder_incremental_state(incremental_state, new_order)
if self.encoder_attn is not None:
self.encoder_attn.reorder_incremental_state(incremental_state, new_order) | ['def', 'reorder_incremental_state(self,', 'incremental_state:', 'Dict[str,', 'Dict[str,', 'Optional[Tensor]]],', 'new_order:', 'Tensor):', 'self.self_attn.reorder_incremental_state(incremental_state,', 'new_order)', 'if', 'self.encoder_attn', 'is', 'not', 'None:', 'self.encoder_attn.reorder_incremental_state(increment... | 107,544 |
Katja-M/Python_NaturalLanguageProcessing | twitter_demo.py | yesterday | yesterday | Get yesterday's datetime as a 5-tuple. | [
"Get",
"yesterday's",
"datetime",
"as",
"a",
"5-tuple."
] | def yesterday():
date = datetime.datetime.now()
date -= datetime.timedelta(days=1)
date_tuple = date.timetuple()[:6]
return date_tuple | ['def', 'yesterday():', 'date', '=', 'datetime.datetime.now()', 'date', '-=', 'datetime.timedelta(days=1)', 'date_tuple', '=', 'date.timetuple()[:6]', 'return', 'date_tuple'] | 867,283 |
enuguru/artificial_intelligence_and_machine_learning | tbtools.py | Traceback.exception | exception | String representation of the exception. | [
"String",
"representation",
"of",
"the",
"exception."
] | def exception(self):
buf = traceback.format_exception_only(self.exc_type, self.exc_value)
rv = ''.join(buf).strip()
return rv.decode('utf-8', 'replace') if PY2 else rv | ['def', 'exception(self):', 'buf', '=', 'traceback.format_exception_only(self.exc_type,', 'self.exc_value)', 'rv', '=', "''.join(buf).strip()", 'return', "rv.decode('utf-8',", "'replace')", 'if', 'PY2', 'else', 'rv'] | 161,868 |
devashish-patel/webcam-motion-detector | fix_absolute_import.py | FixAbsoluteImport.probably_a_local_import | probably_a_local_import | Like the corresponding method in the base class, but this also supports Cython modules. | [
"Like",
"the",
"corresponding",
"method",
"in",
"the",
"base",
"class,",
"but",
"this",
"also",
"supports",
"Cython",
"modules."
] | def probably_a_local_import(self, imp_name):
if imp_name.startswith(u'.'):
return False
imp_name = imp_name.split(u'.', 1)[0]
base_path = dirname(self.filename)
base_path = join(base_path, imp_name)
if not exists(join(dirname(base_path), '__init__.py')):
return False
for ext in [... | ['def', 'probably_a_local_import(self,', 'imp_name):', 'if', "imp_name.startswith(u'.'):", 'return', 'False', 'imp_name', '=', "imp_name.split(u'.',", '1)[0]', 'base_path', '=', 'dirname(self.filename)', 'base_path', '=', 'join(base_path,', 'imp_name)', 'if', 'not', 'exists(join(dirname(base_path),', "'__init__.py')):"... | 980,121 |
derek-schultz/audetect | utils.py | apply_filters_to_sample | apply_filters_to_sample | Given an image patch, applies gabor filters and builds a feature vector. | [
"Given",
"an",
"image",
"patch,",
"applies",
"gabor",
"filters",
"and",
"builds",
"a",
"feature",
"vector."
] | def apply_filters_to_sample(sample):
features = []
features = np.concatenate((features, sample.ravel()))
for kernel in build_gabor_kernels():
filtered = cv2.filter2D(sample, -1, kernel).ravel()
features = np.concatenate((features, filtered))
features = np.float32(features)
return fea... | ['def', 'apply_filters_to_sample(sample):', 'features', '=', '[]', 'features', '=', 'np.concatenate((features,', 'sample.ravel()))', 'for', 'kernel', 'in', 'build_gabor_kernels():', 'filtered', '=', 'cv2.filter2D(sample,', '-1,', 'kernel).ravel()', 'features', '=', 'np.concatenate((features,', 'filtered))', 'features',... | 403,201 |
makefile/objdet_web | app.py | embed_image_html | embed_image_html | Creates an image embedded in HTML base64 format. | [
"Creates",
"an",
"image",
"embedded",
"in",
"HTML",
"base64",
"format."
] | def embed_image_html(image_pil):
size = (512, 512)
resized = image_pil.resize(size)
string_buf = StringIO.StringIO()
resized.save(string_buf, format='png')
data = string_buf.getvalue().encode('base64').replace('\n', '')
return 'data:image/png;base64,' + data | ['def', 'embed_image_html(image_pil):', 'size', '=', '(512,', '512)', 'resized', '=', 'image_pil.resize(size)', 'string_buf', '=', 'StringIO.StringIO()', 'resized.save(string_buf,', "format='png')", 'data', '=', "string_buf.getvalue().encode('base64').replace('\\n',", "'')", 'return', "'data:image/png;base64,'", '+', '... | 725,699 |
devashish-patel/webcam-motion-detector | parse.py | splitvalue | splitvalue | splitvalue('attr=value') --> 'attr', 'value'. | [
"splitvalue('attr=value')",
"-->",
"'attr',",
"'value'."
] | def splitvalue(attr):
global _valueprog
if _valueprog is None:
import re
_valueprog = re.compile('^([^=]*)=(.*)$')
match = _valueprog.match(attr)
if match:
return match.group(1, 2)
return (attr, None) | ['def', 'splitvalue(attr):', 'global', '_valueprog', 'if', '_valueprog', 'is', 'None:', 'import', 're', '_valueprog', '=', "re.compile('^([^=]*)=(.*)$')", 'match', '=', '_valueprog.match(attr)', 'if', 'match:', 'return', 'match.group(1,', '2)', 'return', '(attr,', 'None)'] | 978,123 |
aalgirdas/Artificial-Intelligence-Course | csp.py | queen_constraint | queen_constraint | Constraint is satisfied (true) if A, B are really the same variable, or if they are not in the same row, down diagonal, or up diagonal. | [
"Constraint",
"is",
"satisfied",
"(true)",
"if",
"A,",
"B",
"are",
"really",
"the",
"same",
"variable,",
"or",
"if",
"they",
"are",
"not",
"in",
"the",
"same",
"row,",
"down",
"diagonal,",
"or",
"up",
"diagonal."
] | def queen_constraint(A, a, B, b):
return A == B or (a != b and A + a != B + b and (A - a != B - b)) | ['def', 'queen_constraint(A,', 'a,', 'B,', 'b):', 'return', 'A', '==', 'B', 'or', '(a', '!=', 'b', 'and', 'A', '+', 'a', '!=', 'B', '+', 'b', 'and', '(A', '-', 'a', '!=', 'B', '-', 'b))'] | 79,593 |
43Carrig/recurrent_neural_networks_practice | event_accumulator.py | EventAccumulator.PluginAssets | PluginAssets | Return a list of all plugin assets for the given plugin. | [
"Return",
"a",
"list",
"of",
"all",
"plugin",
"assets",
"for",
"the",
"given",
"plugin."
] | def PluginAssets(self, plugin_name):
return plugin_asset_util.ListAssets(self.path, plugin_name) | ['def', 'PluginAssets(self,', 'plugin_name):', 'return', 'plugin_asset_util.ListAssets(self.path,', 'plugin_name)'] | 312,037 |
rdipietro/miccai-2016-surgical-activity-rec | models.py | LSTM.outputs | outputs | A 3-D float32 Tensor with shape `[batch_size, duration, hidden_layer_size]`. | [
"A",
"3-D",
"float32",
"Tensor",
"with",
"shape",
"`[batch_size,",
"duration,",
"hidden_layer_size]`."
] | def outputs(self):
return self._outputs | ['def', 'outputs(self):', 'return', 'self._outputs'] | 286,339 |
VinF/deer | pendulum_env.py | MyEnv.act | act | Simulate one time step in the environment. | [
"Simulate",
"one",
"time",
"step",
"in",
"the",
"environment."
] | def act(self, action):
(self._last_observation, reward, self.is_terminal, info) = self.env.step(action)
if self.mode == 0:
self.env.render()
return reward | ['def', 'act(self,', 'action):', '(self._last_observation,', 'reward,', 'self.is_terminal,', 'info)', '=', 'self.env.step(action)', 'if', 'self.mode', '==', '0:', 'self.env.render()', 'return', 'reward'] | 183,673 |
voxel51/fiftyone | models.py | PromptMixin.embed_prompt | embed_prompt | Generates an embedding for the given prompt. | [
"Generates",
"an",
"embedding",
"for",
"the",
"given",
"prompt."
] | def embed_prompt(self, arg):
raise NotImplementedError('subclasses must implement embed_prompt') | ['def', 'embed_prompt(self,', 'arg):', 'raise', "NotImplementedError('subclasses", 'must', 'implement', "embed_prompt')"] | 583,207 |
ganyeshprasanna/AI | bustersAgents.py | GreedyBustersAgent.chooseAction | chooseAction | First computes the most likely position of each ghost that has not yet been captured, then chooses an action that brings Pacman closest to the closest ghost (according to mazeDistance!). | [
"First",
"computes",
"the",
"most",
"likely",
"position",
"of",
"each",
"ghost",
"that",
"has",
"not",
"yet",
"been",
"captured,",
"then",
"chooses",
"an",
"action",
"that",
"brings",
"Pacman",
"closest",
"to",
"the",
"closest",
"ghost",
"(according",
"to",
... | def chooseAction(self, gameState: busters.GameState):
pacmanPosition = gameState.getPacmanPosition()
legal = [a for a in gameState.getLegalPacmanActions()]
livingGhosts = gameState.getLivingGhosts()
livingGhostPositionDistributions = [beliefs for (i, beliefs) in enumerate(self.ghostBeliefs) if livingGho... | ['def', 'chooseAction(self,', 'gameState:', 'busters.GameState):', 'pacmanPosition', '=', 'gameState.getPacmanPosition()', 'legal', '=', '[a', 'for', 'a', 'in', 'gameState.getLegalPacmanActions()]', 'livingGhosts', '=', 'gameState.getLivingGhosts()', 'livingGhostPositionDistributions', '=', '[beliefs', 'for', '(i,', 'b... | 66,674 |
kumargaurav2722/udacity-artificial--projects-and-miniprojects | utils.py | Stack | Stack | Return an empty list, suitable as a Last-In-First-Out Queue. | [
"Return",
"an",
"empty",
"list,",
"suitable",
"as",
"a",
"Last-In-First-Out",
"Queue."
] | def Stack():
return [] | ['def', 'Stack():', 'return', '[]'] | 377,602 |
kemaloksuz/RankSortLoss | transformer.py | TransformerDecoderLayer.forward | forward | Forward function for `TransformerDecoderLayer`. | [
"Forward",
"function",
"for",
"`TransformerDecoderLayer`."
] | def forward(self, x, memory, memory_pos=None, query_pos=None, memory_attn_mask=None, target_attn_mask=None, memory_key_padding_mask=None, target_key_padding_mask=None):
norm_cnt = 0
inp_residual = x
for layer in self.order:
if layer == 'selfattn':
query = key = value = x
x = ... | ['def', 'forward(self,', 'x,', 'memory,', 'memory_pos=None,', 'query_pos=None,', 'memory_attn_mask=None,', 'target_attn_mask=None,', 'memory_key_padding_mask=None,', 'target_key_padding_mask=None):', 'norm_cnt', '=', '0', 'inp_residual', '=', 'x', 'for', 'layer', 'in', 'self.order:', 'if', 'layer', '==', "'selfattn':",... | 836,384 |
intra2net/guibot | test_finder.py | FinderTest.test_tempfeat_nomatch | test_tempfeat_nomatch | Test for unsuccessful match of different images for the template-feature CV backend. | [
"Test",
"for",
"unsuccessful",
"match",
"of",
"different",
"images",
"for",
"the",
"template-feature",
"CV",
"backend."
] | def test_tempfeat_nomatch(self):
finder = TemplateFeatureFinder()
finder.params['find']['similarity'].value = 0.25
i = 1
for tempfeat in finder.algorithms['tempfeat_matchers']:
finder.configure_backend(tempfeat, 'tempfeat')
matches = finder.find(Image('n_ibs'), Image('all_shapes'))
... | ['def', 'test_tempfeat_nomatch(self):', 'finder', '=', 'TemplateFeatureFinder()', "finder.params['find']['similarity'].value", '=', '0.25', 'i', '=', '1', 'for', 'tempfeat', 'in', "finder.algorithms['tempfeat_matchers']:", 'finder.configure_backend(tempfeat,', "'tempfeat')", 'matches', '=', "finder.find(Image('n_ibs'),... | 572,659 |
CQCL/lambeq | base.py | Rewriter.add_rules | add_rules | Add rules to this rewriter. | [
"Add",
"rules",
"to",
"this",
"rewriter."
] | def add_rules(self, *rules: RewriteRule | str) -> None:
for rule in rules:
if isinstance(rule, RewriteRule):
self.rules.append(rule)
else:
try:
self.rules.append(self._available_rules[rule])
except KeyError as e:
raise ValueError(f'... | ['def', 'add_rules(self,', '*rules:', 'RewriteRule', '|', 'str)', '->', 'None:', 'for', 'rule', 'in', 'rules:', 'if', 'isinstance(rule,', 'RewriteRule):', 'self.rules.append(rule)', 'else:', 'try:', 'self.rules.append(self._available_rules[rule])', 'except', 'KeyError', 'as', 'e:', 'raise', "ValueError(f'`{rule}`", 'is... | 623,210 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | ordered_set.py | OrderedSet.clear | clear | Remove all items from this OrderedSet. | [
"Remove",
"all",
"items",
"from",
"this",
"OrderedSet."
] | def clear(self):
del self.items[:]
self.map.clear() | ['def', 'clear(self):', 'del', 'self.items[:]', 'self.map.clear()'] | 436,473 |
Ruturaj123/Flowchart-Detection | saved_model_export_utils.py | get_input_alternatives | get_input_alternatives | Obtain all input alternatives using the input_fn output and heuristics. | [
"Obtain",
"all",
"input",
"alternatives",
"using",
"the",
"input_fn",
"output",
"and",
"heuristics."
] | def get_input_alternatives(input_ops):
input_alternatives = {}
if isinstance(input_ops, input_fn_utils.InputFnOps):
(features, unused_labels, default_inputs) = input_ops
input_alternatives[DEFAULT_INPUT_ALTERNATIVE_KEY] = default_inputs
else:
(features, unused_labels) = input_ops
... | ['def', 'get_input_alternatives(input_ops):', 'input_alternatives', '=', '{}', 'if', 'isinstance(input_ops,', 'input_fn_utils.InputFnOps):', '(features,', 'unused_labels,', 'default_inputs)', '=', 'input_ops', 'input_alternatives[DEFAULT_INPUT_ALTERNATIVE_KEY]', '=', 'default_inputs', 'else:', '(features,', 'unused_lab... | 604,162 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | sabl_head.py | SABLHead.reg_pred | reg_pred | Predict bucketing estimation (cls_pred) and fine regression (offset pred) with side-aware features. | [
"Predict",
"bucketing",
"estimation",
"(cls_pred)",
"and",
"fine",
"regression",
"(offset",
"pred)",
"with",
"side-aware",
"features."
] | def reg_pred(self, x, offset_fcs, cls_fcs):
x_offset = x.view(-1, self.reg_in_channels)
x_cls = x.view(-1, self.reg_in_channels)
for fc in offset_fcs:
x_offset = self.relu(fc(x_offset))
for fc in cls_fcs:
x_cls = self.relu(fc(x_cls))
offset_pred = self.fc_reg_offset(x_offset)
cls... | ['def', 'reg_pred(self,', 'x,', 'offset_fcs,', 'cls_fcs):', 'x_offset', '=', 'x.view(-1,', 'self.reg_in_channels)', 'x_cls', '=', 'x.view(-1,', 'self.reg_in_channels)', 'for', 'fc', 'in', 'offset_fcs:', 'x_offset', '=', 'self.relu(fc(x_offset))', 'for', 'fc', 'in', 'cls_fcs:', 'x_cls', '=', 'self.relu(fc(x_cls))', 'off... | 857,283 |
DLR-RM/stable-baselines3 | test_env_checker.py | test_check_env_detailed_error | test_check_env_detailed_error | Check that the env checker returns more detail error when the observation is not in the obs space. | [
"Check",
"that",
"the",
"env",
"checker",
"returns",
"more",
"detail",
"error",
"when",
"the",
"observation",
"is",
"not",
"in",
"the",
"obs",
"space."
] | def test_check_env_detailed_error(obs_tuple, method):
(observation_space, wrong_obs, error_message) = obs_tuple
good_obs = observation_space.sample()
class TestEnv(gym.Env):
action_space = spaces.Box(low=-1.0, high=1.0, shape=(3,), dtype=np.float32)
def reset(self, *, seed: Optional[int]=N... | ['def', 'test_check_env_detailed_error(obs_tuple,', 'method):', '(observation_space,', 'wrong_obs,', 'error_message)', '=', 'obs_tuple', 'good_obs', '=', 'observation_space.sample()', 'class', 'TestEnv(gym.Env):', 'action_space', '=', 'spaces.Box(low=-1.0,', 'high=1.0,', 'shape=(3,),', 'dtype=np.float32)', 'def', 'rese... | 383,246 |
qixuxiang/deeplabv3plus | get_dataset_colormap_test.py | VisualizationUtilTest.testPASCALLabelColorMapValue | testPASCALLabelColorMapValue | Test the getd color map value. | [
"Test",
"the",
"getd",
"color",
"map",
"value."
] | def testPASCALLabelColorMapValue(self):
colormap = get_dataset_colormap.create_pascal_label_colormap()
self.assertTrue(np.array_equal([128.0, 0.0, 128.0], colormap[5, :]))
self.assertTrue(np.array_equal([128.0, 192.0, 128.0], colormap[23, :]))
self.assertTrue(np.array_equal([128.0, 0.0, 192.0], colormap... | ['def', 'testPASCALLabelColorMapValue(self):', 'colormap', '=', 'get_dataset_colormap.create_pascal_label_colormap()', 'self.assertTrue(np.array_equal([128.0,', '0.0,', '128.0],', 'colormap[5,', ':]))', 'self.assertTrue(np.array_equal([128.0,', '192.0,', '128.0],', 'colormap[23,', ':]))', 'self.assertTrue(np.array_equa... | 521,424 |
PKU-Alignment/safe-rlhf | trainer.py | CostTrainer.loss | loss | Loss function for the cost model. | [
"Loss",
"function",
"for",
"the",
"cost",
"model."
] | def loss(self, safer_input_ids: torch.LongTensor, safer_attention_mask: torch.BoolTensor, safer_safety_sign: torch.LongTensor, unsafer_input_ids: torch.LongTensor, unsafer_attention_mask: torch.BoolTensor, unsafer_safety_sign: torch.LongTensor) -> dict[str, torch.Tensor]:
assert safer_input_ids.size(0) == unsafer_i... | ['def', 'loss(self,', 'safer_input_ids:', 'torch.LongTensor,', 'safer_attention_mask:', 'torch.BoolTensor,', 'safer_safety_sign:', 'torch.LongTensor,', 'unsafer_input_ids:', 'torch.LongTensor,', 'unsafer_attention_mask:', 'torch.BoolTensor,', 'unsafer_safety_sign:', 'torch.LongTensor)', '->', 'dict[str,', 'torch.Tensor... | 829,213 |
matsu0228/nlp-jp | iterable.py | unpack_tuple_to_dict | unpack_tuple_to_dict | Unpacking tuple assignments in for statements and expr_stmts. | [
"Unpacking",
"tuple",
"assignments",
"in",
"for",
"statements",
"and",
"expr_stmts."
] | def unpack_tuple_to_dict(context, types, exprlist):
if exprlist.type == 'name':
return {exprlist.value: types}
elif exprlist.type == 'atom' and exprlist.children[0] in '([':
return unpack_tuple_to_dict(context, types, exprlist.children[1])
elif exprlist.type in ('testlist', 'testlist_comp', ... | ['def', 'unpack_tuple_to_dict(context,', 'types,', 'exprlist):', 'if', 'exprlist.type', '==', "'name':", 'return', '{exprlist.value:', 'types}', 'elif', 'exprlist.type', '==', "'atom'", 'and', 'exprlist.children[0]', 'in', "'([':", 'return', 'unpack_tuple_to_dict(context,', 'types,', 'exprlist.children[1])', 'elif', 'e... | 787,710 |
flow-project/flow | base.py | BaseKernelNetwork.get_junction_list | get_junction_list | Return the names of all junctions in the network. | [
"Return",
"the",
"names",
"of",
"all",
"junctions",
"in",
"the",
"network."
] | def get_junction_list(self):
raise NotImplementedError | ['def', 'get_junction_list(self):', 'raise', 'NotImplementedError'] | 212,115 |
opendilab/DI-star | sc2_eval_env.py | SC2EVALEnv.game_info | game_info | A list of ResponseGameInfo, one per agent. | [
"A",
"list",
"of",
"ResponseGameInfo,",
"one",
"per",
"agent."
] | def game_info(self):
return self._game_info | ['def', 'game_info(self):', 'return', 'self._game_info'] | 184,643 |
Ruturaj123/Flowchart-Detection | feature_column_ops_test.py | WeightedSumTest.testSparseIntColumn | testSparseIntColumn | Tests a sparse column with int values. | [
"Tests",
"a",
"sparse",
"column",
"with",
"int",
"values."
] | def testSparseIntColumn(self):
hashed_sparse = feature_column.sparse_column_with_hash_bucket('wire', 10, dtype=dtypes.int64)
wire_tensor = sparse_tensor.SparseTensor(values=[101, 201, 301], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2])
features = {'wire': wire_tensor}
(logits, _, _) = feature_co... | ['def', 'testSparseIntColumn(self):', 'hashed_sparse', '=', "feature_column.sparse_column_with_hash_bucket('wire',", '10,', 'dtype=dtypes.int64)', 'wire_tensor', '=', 'sparse_tensor.SparseTensor(values=[101,', '201,', '301],', 'indices=[[0,', '0],', '[1,', '0],', '[1,', '1]],', 'dense_shape=[2,', '2])', 'features', '='... | 603,692 |
The-Compiler/pytest-vw | test_vw.py | test_normal | test_normal | Make sure failing tests fail when not running under CI. | [
"Make",
"sure",
"failing",
"tests",
"fail",
"when",
"not",
"running",
"under",
"CI."
] | def test_normal(testdir, monkeypatch):
for examinator in pytest_vw.EXAMINATORS:
monkeypatch.delenv(examinator, raising=False)
testdir.makepyfile('\n def test_environmental_impact_compliance():\n emissions = 12000\n legal_limit = 300\n assert emissions < legal_limi... | ['def', 'test_normal(testdir,', 'monkeypatch):', 'for', 'examinator', 'in', 'pytest_vw.EXAMINATORS:', 'monkeypatch.delenv(examinator,', 'raising=False)', "testdir.makepyfile('\\n", 'def', 'test_environmental_impact_compliance():\\n', 'emissions', '=', '12000\\n', 'legal_limit', '=', '300\\n', 'assert', 'emissions', '<'... | 297,418 |
open-mmlab/mmselfsup | inference.py | inference_model | inference_model | Inference an image with the mmselfsup model. | [
"Inference",
"an",
"image",
"with",
"the",
"mmselfsup",
"model."
] | def inference_model(model: nn.Module, img: Union[str, np.ndarray]) -> SelfSupDataSample:
cfg = model.cfg
test_pipeline_cfg = cfg.test_dataloader.dataset.pipeline
if isinstance(img, str):
if test_pipeline_cfg[0]['type'] != 'LoadImageFromFile':
test_pipeline_cfg.insert(0, dict(type='LoadIm... | ['def', 'inference_model(model:', 'nn.Module,', 'img:', 'Union[str,', 'np.ndarray])', '->', 'SelfSupDataSample:', 'cfg', '=', 'model.cfg', 'test_pipeline_cfg', '=', 'cfg.test_dataloader.dataset.pipeline', 'if', 'isinstance(img,', 'str):', 'if', "test_pipeline_cfg[0]['type']", '!=', "'LoadImageFromFile':", 'test_pipelin... | 240,294 |
weimin17/Object-Detection_HelmetDetection | preprocessing.py | resize_image | resize_image | Resizes an image to a target height and width. | [
"Resizes",
"an",
"image",
"to",
"a",
"target",
"height",
"and",
"width."
] | def resize_image(image, height, width):
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, [height, width], align_corners=False)
image = tf.squeeze(image, [0])
return image | ['def', 'resize_image(image,', 'height,', 'width):', 'image', '=', 'tf.expand_dims(image,', '0)', 'image', '=', 'tf.image.resize_bilinear(image,', '[height,', 'width],', 'align_corners=False)', 'image', '=', 'tf.squeeze(image,', '[0])', 'return', 'image'] | 760,589 |
enlite-ai/maze | core_env.py | Cutting2DCoreEnvironment.is_actor_done | is_actor_done | Returns True if the just stepped actor is done, which is different to the done flag of the environment. | [
"Returns",
"True",
"if",
"the",
"just",
"stepped",
"actor",
"is",
"done,",
"which",
"is",
"different",
"to",
"the",
"done",
"flag",
"of",
"the",
"environment."
] | def is_actor_done(self) -> bool:
return False | ['def', 'is_actor_done(self)', '->', 'bool:', 'return', 'False'] | 647,605 |
RasaHQ/rasa | whitespace_tokenizer.py | WhitespaceTokenizer.not_supported_languages | not_supported_languages | The languages that are not supported. | [
"The",
"languages",
"that",
"are",
"not",
"supported."
] | def not_supported_languages() -> Optional[List[Text]]:
return ['zh', 'ja', 'th'] | ['def', 'not_supported_languages()', '->', 'Optional[List[Text]]:', 'return', "['zh',", "'ja',", "'th']"] | 837,326 |
google-research/text-to-text-transfer-transformer | qa_utils.py | normalize_trivia_qa | normalize_trivia_qa | Normalization used in official TriviaQA evaluation script. | [
"Normalization",
"used",
"in",
"official",
"TriviaQA",
"evaluation",
"script."
] | def normalize_trivia_qa(answer):
return _normalize_answer(answer, punc_chars=string.punctuation + 'âÂ\x80Â\x98âÂ\x80Â\x99Ã\x82´`_', punc_repl=' ').strip() | ['def', 'normalize_trivia_qa(answer):', 'return', '_normalize_answer(answer,', 'punc_chars=string.punctuation', '+', "'âÂ\\x80Â\\x98âÂ\\x80Â\\x99Ã\\x82´`_',", "punc_repl='", "').strip()"] | 925,625 |
GregorKobsik/Octree-Transformer | shape_sampler.py | ShapeSampler.sample_random | sample_random | Sample a single unconditioned random array of elements from the model. | [
"Sample",
"a",
"single",
"unconditioned",
"random",
"array",
"of",
"elements",
"from",
"the",
"model."
] | def sample_random(self, target_resolution=32, temperature=1.0, cls=None):
array_size = self.spatial_dim * [self.trained_resolution]
random_element_array = torch.randint(low=0, high=2, size=array_size, dtype=torch.long).numpy()
return self.sampler(random_element_array, 2, target_resolution, temperature, cls) | ['def', 'sample_random(self,', 'target_resolution=32,', 'temperature=1.0,', 'cls=None):', 'array_size', '=', 'self.spatial_dim', '*', '[self.trained_resolution]', 'random_element_array', '=', 'torch.randint(low=0,', 'high=2,', 'size=array_size,', 'dtype=torch.long).numpy()', 'return', 'self.sampler(random_element_array... | 755,093 |
ryu-ed/SpaceInvaders_Ros | mask_test.py | MaskTypeTest.test_connected_component__one_set_bit | test_connected_component__one_set_bit | Ensure a mask's connected component is correctly calculated when the coordinate's bit is set with a connected component of 1 bit. | [
"Ensure",
"a",
"mask's",
"connected",
"component",
"is",
"correctly",
"calculated",
"when",
"the",
"coordinate's",
"bit",
"is",
"set",
"with",
"a",
"connected",
"component",
"of",
"1",
"bit."
] | def test_connected_component__one_set_bit(self):
(width, height) = (71, 67)
expected_size = (width, height)
original_mask = pygame.mask.Mask(expected_size, fill=True)
(xset, yset) = (width // 2, height // 2)
set_pos = (xset, yset)
expected_offset = (xset - 1, yset - 1)
expected_pattern = sel... | ['def', 'test_connected_component__one_set_bit(self):', '(width,', 'height)', '=', '(71,', '67)', 'expected_size', '=', '(width,', 'height)', 'original_mask', '=', 'pygame.mask.Mask(expected_size,', 'fill=True)', '(xset,', 'yset)', '=', '(width', '//', '2,', 'height', '//', '2)', 'set_pos', '=', '(xset,', 'yset)', 'exp... | 369,061 |
ryu-ed/SpaceInvaders_Ros | cdrom_test.py | CDROMModuleTest.test_get_count | test_get_count | Ensure the correct number of CD drives can be detected. | [
"Ensure",
"the",
"correct",
"number",
"of",
"CD",
"drives",
"can",
"be",
"detected."
] | def test_get_count(self):
count = pygame.cdrom.get_count()
response = question('Is the correct number of CD drives on this system [{}]?'.format(count))
self.assertTrue(response) | ['def', 'test_get_count(self):', 'count', '=', 'pygame.cdrom.get_count()', 'response', '=', "question('Is", 'the', 'correct', 'number', 'of', 'CD', 'drives', 'on', 'this', 'system', "[{}]?'.format(count))", 'self.assertTrue(response)'] | 368,896 |
FitSNAP/FitSNAP | snap-Ta.py | ridge | ridge | Least squares fit with ridge regularization. | [
"Least",
"squares",
"fit",
"with",
"ridge",
"regularization."
] | def ridge(c, d):
alval = 1e-06
reg = Ridge(alpha=alval, fit_intercept=False)
reg.fit(c, d)
return reg.coef_.T | ['def', 'ridge(c,', 'd):', 'alval', '=', '1e-06', 'reg', '=', 'Ridge(alpha=alval,', 'fit_intercept=False)', 'reg.fit(c,', 'd)', 'return', 'reg.coef_.T'] | 584,598 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | pointer_generator_word.py | TokenTextEncoderOov.decode_list_oov | decode_list_oov | decode ids back to tokens, considering OOVs temporary IDs. | [
"decode",
"ids",
"back",
"to",
"tokens,",
"considering",
"OOVs",
"temporary",
"IDs."
] | def decode_list_oov(self, ids, source_oov_id_to_token):
seq = reversed(ids) if self._reverse else ids
tokens = []
for cur_id in seq:
if cur_id in self._id_to_token:
tokens.append(self._id_to_token[cur_id])
else:
tokens.append(source_oov_id_to_token[cur_id - self.vocab... | ['def', 'decode_list_oov(self,', 'ids,', 'source_oov_id_to_token):', 'seq', '=', 'reversed(ids)', 'if', 'self._reverse', 'else', 'ids', 'tokens', '=', '[]', 'for', 'cur_id', 'in', 'seq:', 'if', 'cur_id', 'in', 'self._id_to_token:', 'tokens.append(self._id_to_token[cur_id])', 'else:', 'tokens.append(source_oov_id_to_tok... | 964,936 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | imagenet_main.py | resnet_model_fn | resnet_model_fn | Our model_fn for ResNet to be used with our Estimator. | [
"Our",
"model_fn",
"for",
"ResNet",
"to",
"be",
"used",
"with",
"our",
"Estimator."
] | def resnet_model_fn(features, labels, mode, params):
tf.summary.image('images', features, max_outputs=6)
network = resnet_model.imagenet_resnet_v2(params['resnet_size'], _LABEL_CLASSES, params['data_format'])
logits = network(inputs=features, is_training=mode == tf.estimator.ModeKeys.TRAIN)
predictions ... | ['def', 'resnet_model_fn(features,', 'labels,', 'mode,', 'params):', "tf.summary.image('images',", 'features,', 'max_outputs=6)', 'network', '=', "resnet_model.imagenet_resnet_v2(params['resnet_size'],", '_LABEL_CLASSES,', "params['data_format'])", 'logits', '=', 'network(inputs=features,', 'is_training=mode', '==', 't... | 20,121 |
voxel51/fiftyone | view.py | extend_view | extend_view | Adds the given extended stages to the view. | [
"Adds",
"the",
"given",
"extended",
"stages",
"to",
"the",
"view."
] | def extend_view(view, extended_stages):
for (_cls, d) in extended_stages.items():
kwargs = [[k, v] for (k, v) in d.items()]
stage = fosg.ViewStage._from_dict({'_cls': _cls, 'kwargs': kwargs})
view = view.add_stage(stage)
return view | ['def', 'extend_view(view,', 'extended_stages):', 'for', '(_cls,', 'd)', 'in', 'extended_stages.items():', 'kwargs', '=', '[[k,', 'v]', 'for', '(k,', 'v)', 'in', 'd.items()]', 'stage', '=', "fosg.ViewStage._from_dict({'_cls':", '_cls,', "'kwargs':", 'kwargs})', 'view', '=', 'view.add_stage(stage)', 'return', 'view'] | 583,860 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.