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
WHU-ZQH/E2S2
trainer.py
Trainer.get_criterion
get_criterion
Get the (non-wrapped) criterion instance.
[ "Get", "the", "(non-wrapped)", "criterion", "instance." ]
def get_criterion(self): return self._criterion
['def', 'get_criterion(self):', 'return', 'self._criterion']
555,621
smaranjitghose/DeepPixel
gradcampp.py
GradCAMPP.heat_map
heat_map
to generate GradCAM++ heatmap for given :param:`input_` and :param:`class_index` with respect to :attr:`conv_layer`.
[ "to", "generate", "GradCAM++", "heatmap", "for", "given", ":param:`input_`", "and", ":param:`class_index`", "with", "respect", "to", ":attr:`conv_layer`." ]
def heat_map(self, input_, class_index=-1): conv_layer_model = keras.Model(self.model.inputs, self.conv_layer.output) classifier_input = keras.Input(shape=self.conv_layer.output.shape[1:]) x = classifier_input for layer in self.classifier_layers: x = layer(x) classifier_model = keras.Model(c...
['def', 'heat_map(self,', 'input_,', 'class_index=-1):', 'conv_layer_model', '=', 'keras.Model(self.model.inputs,', 'self.conv_layer.output)', 'classifier_input', '=', 'keras.Input(shape=self.conv_layer.output.shape[1:])', 'x', '=', 'classifier_input', 'for', 'layer', 'in', 'self.classifier_layers:', 'x', '=', 'layer(x...
539,261
boostcampaitech3/level2-semantic-segmentation-level2-cv-16
transforms.py
RandomMosaic.get_indexes
get_indexes
Call function to collect indexes.
[ "Call", "function", "to", "collect", "indexes." ]
def get_indexes(self, dataset): indexes = [random.randint(0, len(dataset)) for _ in range(3)] return indexes
['def', 'get_indexes(self,', 'dataset):', 'indexes', '=', '[random.randint(0,', 'len(dataset))', 'for', '_', 'in', 'range(3)]', 'return', 'indexes']
588,782
openvinotoolkit/training_extensions
model.py
ModelEntity.model_adapters
model_adapters
Returns the dictionary of model adapters for each data key.
[ "Returns", "the", "dictionary", "of", "model", "adapters", "for", "each", "data", "key." ]
def model_adapters(self) -> Dict[str, ModelAdapter]: return self.__model_adapters
['def', 'model_adapters(self)', '->', 'Dict[str,', 'ModelAdapter]:', 'return', 'self.__model_adapters']
918,638
weimin17/Object-Detection_HelmetDetection
utils.py
sample_n_per_class
sample_n_per_class
Create a new callable / dataset object that returns batches of each with samples_per_class per label.
[ "Create", "a", "new", "callable", "/", "dataset", "object", "that", "returns", "batches", "of", "each", "with", "samples_per_class", "per", "label." ]
def sample_n_per_class(dataset, samples_per_class): with tf.control_dependencies(None), tf.name_scope(None): with tf.name_scope('queue_runner/sample_n_per_class'): batch = dataset() num_classes = batch.label_onehot.shape.as_list()[1] batch_size = num_classes * samples_per...
['def', 'sample_n_per_class(dataset,', 'samples_per_class):', 'with', 'tf.control_dependencies(None),', 'tf.name_scope(None):', 'with', "tf.name_scope('queue_runner/sample_n_per_class'):", 'batch', '=', 'dataset()', 'num_classes', '=', 'batch.label_onehot.shape.as_list()[1]', 'batch_size', '=', 'num_classes', '*', 'sam...
763,389
open-mmlab/mmselfsup
utils.py
Formatter.get_offset
get_offset
Return the offset string.
[ "Return", "the", "offset", "string." ]
def get_offset(self) -> str: return ''
['def', 'get_offset(self)', '->', 'str:', 'return', "''"]
240,513
ArdaGunay99/Key_Detection_Unsupervised_Learning
transforms.py
Bbox.get_points
get_points
Get the points of the bounding box directly as a numpy array of the form: ``[[x0, y0], [x1, y1]]``.
[ "Get", "the", "points", "of", "the", "bounding", "box", "directly", "as", "a", "numpy", "array", "of", "the", "form:", "``[[x0,", "y0],", "[x1,", "y1]]``." ]
def get_points(self): self._invalid = 0 return self._points
['def', 'get_points(self):', 'self._invalid', '=', '0', 'return', 'self._points']
257,428
lambert-x/RVC_Segmentation
class_names.py
get_palette
get_palette
Get class palette (RGB) of a dataset.
[ "Get", "class", "palette", "(RGB)", "of", "a", "dataset." ]
def get_palette(dataset): alias2name = {} for (name, aliases) in dataset_aliases.items(): for alias in aliases: alias2name[alias] = name if mmcv.is_str(dataset): if dataset in alias2name: labels = eval(alias2name[dataset] + '_palette()') else: rais...
['def', 'get_palette(dataset):', 'alias2name', '=', '{}', 'for', '(name,', 'aliases)', 'in', 'dataset_aliases.items():', 'for', 'alias', 'in', 'aliases:', 'alias2name[alias]', '=', 'name', 'if', 'mmcv.is_str(dataset):', 'if', 'dataset', 'in', 'alias2name:', 'labels', '=', 'eval(alias2name[dataset]', '+', "'_palette()')...
828,341
mariacer/cl_in_rnns
torch_ckpts.py
make_ckpt_list
make_ckpt_list
Creates a file that lists all checkpoints together with there scores, such that one can easily find the checkpoint associated with the maximum score.
[ "Creates", "a", "file", "that", "lists", "all", "checkpoints", "together", "with", "there", "scores,", "such", "that", "one", "can", "easily", "find", "the", "checkpoint", "associated", "with", "the", "maximum", "score." ]
def make_ckpt_list(file_path): internal_key = _INTERNAL_KEY (dname, fname) = os.path.split(file_path) assert os.path.exists(dname) ckpt_fns = [(f, os.path.join(dname, f)) for f in os.listdir(dname) if os.path.isfile(os.path.join(dname, f)) and f.startswith(fname)] ckpts = [] for (fn, fpath) in c...
['def', 'make_ckpt_list(file_path):', 'internal_key', '=', '_INTERNAL_KEY', '(dname,', 'fname)', '=', 'os.path.split(file_path)', 'assert', 'os.path.exists(dname)', 'ckpt_fns', '=', '[(f,', 'os.path.join(dname,', 'f))', 'for', 'f', 'in', 'os.listdir(dname)', 'if', 'os.path.isfile(os.path.join(dname,', 'f))', 'and', 'f....
123,111
dibyaghosh/gcsl
dynamixel_utils.py
CalibrationMap.get_parameters
get_parameters
Returns a dictionary of calibration parameters.
[ "Returns", "a", "dictionary", "of", "calibration", "parameters." ]
def get_parameters(self, motor_ids: Iterable[int]) -> Dict[str, Any]: return {'calib_scale': [self.mapping[i][0] for i in motor_ids], 'calib_offset': [self.mapping[i][1] for i in motor_ids]}
['def', 'get_parameters(self,', 'motor_ids:', 'Iterable[int])', '->', 'Dict[str,', 'Any]:', 'return', "{'calib_scale':", '[self.mapping[i][0]', 'for', 'i', 'in', 'motor_ids],', "'calib_offset':", '[self.mapping[i][1]', 'for', 'i', 'in', 'motor_ids]}']
201,725
ShiiVa03/Artificial-Intelligence
search.py
compare_graph_searchers
compare_graph_searchers
Prints a table of search results.
[ "Prints", "a", "table", "of", "search", "results." ]
def compare_graph_searchers(): compare_searchers(problems=[GraphProblem('Arad', 'Bucharest', romania_map), GraphProblem('Oradea', 'Neamt', romania_map), GraphProblem('Q', 'WA', australia_map)], header=['Searcher', 'romania_map(Arad, Bucharest)', 'romania_map(Oradea, Neamt)', 'australia_map'])
['def', 'compare_graph_searchers():', "compare_searchers(problems=[GraphProblem('Arad',", "'Bucharest',", 'romania_map),', "GraphProblem('Oradea',", "'Neamt',", 'romania_map),', "GraphProblem('Q',", "'WA',", 'australia_map)],', "header=['Searcher',", "'romania_map(Arad,", "Bucharest)',", "'romania_map(Oradea,", "Neamt)...
116,989
matsu0228/nlp-jp
test_decomp.py
eigenhproblem_general
eigenhproblem_general
Solve a generalized eigenvalue problem.
[ "Solve", "a", "generalized", "eigenvalue", "problem." ]
def eigenhproblem_general(desc, dim, dtype, overwrite, lower, turbo, eigenvalues): if iscomplex(empty(1, dtype=dtype)): a = _complex_symrand(dim, dtype) b = _complex_symrand(dim, dtype) + diag([2.1] * dim).astype(dtype) else: a = symrand(dim).astype(dtype) b = symrand(dim).astype...
['def', 'eigenhproblem_general(desc,', 'dim,', 'dtype,', 'overwrite,', 'lower,', 'turbo,', 'eigenvalues):', 'if', 'iscomplex(empty(1,', 'dtype=dtype)):', 'a', '=', '_complex_symrand(dim,', 'dtype)', 'b', '=', '_complex_symrand(dim,', 'dtype)', '+', 'diag([2.1]', '*', 'dim).astype(dtype)', 'else:', 'a', '=', 'symrand(di...
805,599
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
problem_generator.py
matmul_problem_sequence
matmul_problem_sequence
Helper to generate a sequence of matrix multiplication problems.
[ "Helper", "to", "generate", "a", "sequence", "of", "matrix", "multiplication", "problems." ]
def matmul_problem_sequence(n, k_min, k_max): return [(_Spec(MatMulAlgorithm, (n, k), {}), None, None) for k in range(k_min, k_max + 1)]
['def', 'matmul_problem_sequence(n,', 'k_min,', 'k_max):', 'return', '[(_Spec(MatMulAlgorithm,', '(n,', 'k),', '{}),', 'None,', 'None)', 'for', 'k', 'in', 'range(k_min,', 'k_max', '+', '1)]']
55,700
JosephKJ/iOD
pascal_voc.py
load_voc_instances
load_voc_instances
Load Pascal VOC detection annotations to Detectron2 format.
[ "Load", "Pascal", "VOC", "detection", "annotations", "to", "Detectron2", "format." ]
def load_voc_instances(dirname: str, split: str): with PathManager.open(os.path.join(dirname, 'ImageSets', 'Main', split + '.txt')) as f: fileids = np.loadtxt(f, dtype=np.str) dicts = [] for fileid in fileids: anno_file = os.path.join(dirname, 'Annotations', fileid + '.xml') jpeg_fil...
['def', 'load_voc_instances(dirname:', 'str,', 'split:', 'str):', 'with', 'PathManager.open(os.path.join(dirname,', "'ImageSets',", "'Main',", 'split', '+', "'.txt'))", 'as', 'f:', 'fileids', '=', 'np.loadtxt(f,', 'dtype=np.str)', 'dicts', '=', '[]', 'for', 'fileid', 'in', 'fileids:', 'anno_file', '=', 'os.path.join(di...
576,796
Katja-M/Python_NaturalLanguageProcessing
test_ticker.py
TestMultipleLocator.test_view_limits
test_view_limits
Test basic behavior of view limits.
[ "Test", "basic", "behavior", "of", "view", "limits." ]
def test_view_limits(self): with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): loc = mticker.MultipleLocator(base=3.147) assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))
['def', 'test_view_limits(self):', 'with', "matplotlib.rc_context({'axes.autolimit_mode':", "'data'}):", 'loc', '=', 'mticker.MultipleLocator(base=3.147)', 'assert_almost_equal(loc.view_limits(-5,', '5),', '(-5,', '5))']
865,569
Kvatsx/Artificial-Intelligence-Assignments
utils.py
LRUCache.keys
keys
Return a list of all keys ordered by most recent usage.
[ "Return", "a", "list", "of", "all", "keys", "ordered", "by", "most", "recent", "usage." ]
def keys(self): return list(self)
['def', 'keys(self):', 'return', 'list(self)']
39,414
RomanoLab/comptox_ai
io.py
Neo4jData.add_edge
add_edge
Add an edge to the graph and synchronize it to the remote database.
[ "Add", "an", "edge", "to", "the", "graph", "and", "synchronize", "it", "to", "the", "remote", "database." ]
def add_edge(self, edge: tuple): (u, rel_type, v, props) = edge e = Relationship(u, rel_type, v, props) self._graph.create(e)
['def', 'add_edge(self,', 'edge:', 'tuple):', '(u,', 'rel_type,', 'v,', 'props)', '=', 'edge', 'e', '=', 'Relationship(u,', 'rel_type,', 'v,', 'props)', 'self._graph.create(e)']
136,141
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tiles.py
adjacent_tile
adjacent_tile
Retrieves an adjacent tile from a tile store.
[ "Retrieves", "an", "adjacent", "tile", "from", "a", "tile", "store." ]
def adjacent_tile(tile, dx, dy, tiles): (x, y, z) = map(int, [tile.x, tile.y, tile.z]) other = mercantile.Tile(x=x + dx, y=y + dy, z=z) try: path = tiles[other] return Image.open(path).convert('RGB') except KeyError: return None
['def', 'adjacent_tile(tile,', 'dx,', 'dy,', 'tiles):', '(x,', 'y,', 'z)', '=', 'map(int,', '[tile.x,', 'tile.y,', 'tile.z])', 'other', '=', 'mercantile.Tile(x=x', '+', 'dx,', 'y=y', '+', 'dy,', 'z=z)', 'try:', 'path', '=', 'tiles[other]', 'return', "Image.open(path).convert('RGB')", 'except', 'KeyError:', 'return', 'N...
18,091
arnomoonens/yarll
experiences_memory.py
ExperiencesMemory.terminal
terminal
Last experience is terminal.
[ "Last", "experience", "is", "terminal." ]
def terminal(self): return self.experiences[-1].terminal
['def', 'terminal(self):', 'return', 'self.experiences[-1].terminal']
374,751
google/deepvariant
protobuf_implementation_test.py
ProtobufImplementationTest.test_protobuf_uses_fast_cpp
test_protobuf_uses_fast_cpp
Checks that we are using the fast cpp version of python protobufs.
[ "Checks", "that", "we", "are", "using", "the", "fast", "cpp", "version", "of", "python", "protobufs." ]
def test_protobuf_uses_fast_cpp(self): self.assertEqual(api_implementation.Type(), 'cpp')
['def', 'test_protobuf_uses_fast_cpp(self):', 'self.assertEqual(api_implementation.Type(),', "'cpp')"]
540,619
pfnet/pfrl
acer.py
compute_loss_with_kl_constraint
compute_loss_with_kl_constraint
Compute loss considering a KL constraint.
[ "Compute", "loss", "considering", "a", "KL", "constraint." ]
def compute_loss_with_kl_constraint(distrib, another_distrib, original_loss, delta): distrib_params = get_params_of_distribution(distrib) for param in distrib_params: assert param.shape[0] == 1 assert param.requires_grad g = [grad[0] for grad in torch.autograd.grad([original_loss], distrib_p...
['def', 'compute_loss_with_kl_constraint(distrib,', 'another_distrib,', 'original_loss,', 'delta):', 'distrib_params', '=', 'get_params_of_distribution(distrib)', 'for', 'param', 'in', 'distrib_params:', 'assert', 'param.shape[0]', '==', '1', 'assert', 'param.requires_grad', 'g', '=', '[grad[0]', 'for', 'grad', 'in', '...
304,646
Technica-Corporation/TF-Movidius-Finetune
cyclegan_test.py
CycleganTest.test_generator_inference
test_generator_inference
Check one inference step.
[ "Check", "one", "inference", "step." ]
def test_generator_inference(self): img_batch = tf.zeros([2, 32, 32, 3]) (model_output, _) = cyclegan.cyclegan_generator_resnet(img_batch) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) sess.run(model_output)
['def', 'test_generator_inference(self):', 'img_batch', '=', 'tf.zeros([2,', '32,', '32,', '3])', '(model_output,', '_)', '=', 'cyclegan.cyclegan_generator_resnet(img_batch)', 'with', 'self.test_session()', 'as', 'sess:', 'sess.run(tf.global_variables_initializer())', 'sess.run(model_output)']
914,240
TensorSwarm/TensorSwarm
logger.py
logkv_mean
logkv_mean
The same as logkv(), but if called many times, values averaged.
[ "The", "same", "as", "logkv(),", "but", "if", "called", "many", "times,", "values", "averaged." ]
def logkv_mean(key, val): Logger.CURRENT.logkv_mean(key, val)
['def', 'logkv_mean(key,', 'val):', 'Logger.CURRENT.logkv_mean(key,', 'val)']
924,090
geekfarmer/Capsule-Networks-Towards--
layers.py
fully_connected
fully_connected
A capsule fully connected layer.
[ "A", "capsule", "fully", "connected", "layer." ]
def fully_connected(inputs, activation, num_outputs, out_caps_shape, routing_method='EMRouting', reuse=None): in_pose_shape = inputs.get_shape().as_list() num_inputs = in_pose_shape[1] batch_size = in_pose_shape[0] T_size = get_transformation_matrix_shape(in_pose_shape[-2:], out_caps_shape) T_shape ...
['def', 'fully_connected(inputs,', 'activation,', 'num_outputs,', 'out_caps_shape,', "routing_method='EMRouting',", 'reuse=None):', 'in_pose_shape', '=', 'inputs.get_shape().as_list()', 'num_inputs', '=', 'in_pose_shape[1]', 'batch_size', '=', 'in_pose_shape[0]', 'T_size', '=', 'get_transformation_matrix_shape(in_pose_...
454,829
google-research/text-to-text-transfer-transformer
utils.py
rate_unsupervised
rate_unsupervised
Gin-configurable mixing rate for the unsupervised co-training task.
[ "Gin-configurable", "mixing", "rate", "for", "the", "unsupervised", "co-training", "task." ]
def rate_unsupervised(task, value=1000000.0): del task return value
['def', 'rate_unsupervised(task,', 'value=1000000.0):', 'del', 'task', 'return', 'value']
925,599
flovera1/AI
inference.py
InferenceModule.getObservationProb
getObservationProb
Return the probability P(noisyDistance | pacmanPosition, ghostPosition).
[ "Return", "the", "probability", "P(noisyDistance", "|", "pacmanPosition,", "ghostPosition)." ]
def getObservationProb(self, noisyDistance: int, pacmanPosition: Tuple, ghostPosition: Tuple, jailPosition: Tuple): raiseNotDefined()
['def', 'getObservationProb(self,', 'noisyDistance:', 'int,', 'pacmanPosition:', 'Tuple,', 'ghostPosition:', 'Tuple,', 'jailPosition:', 'Tuple):', 'raiseNotDefined()']
67,251
jimtin/Stock_Comparison
easy_install.py
is_python_script
is_python_script
Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
[ "Is", "this", "text,", "as", "a", "whole,", "a", "Python", "script?", "(as", "opposed", "to", "shell/bat/etc." ]
def is_python_script(script_text, filename): if filename.endswith('.py') or filename.endswith('.pyw'): return True if is_python(script_text, filename): return True if script_text.startswith('#!'): return 'python' in script_text.splitlines()[0].lower() return False
['def', 'is_python_script(script_text,', 'filename):', 'if', "filename.endswith('.py')", 'or', "filename.endswith('.pyw'):", 'return', 'True', 'if', 'is_python(script_text,', 'filename):', 'return', 'True', 'if', "script_text.startswith('#!'):", 'return', "'python'", 'in', 'script_text.splitlines()[0].lower()', 'return...
358,918
moscow25/deep_draw
draw_poker.py
load_data
load_data
Get data with labels, split into training, validation and test set.
[ "Get", "data", "with", "labels,", "split", "into", "training,", "validation", "and", "test", "set." ]
def load_data(): data = _load_poker_csv() (X_all, y_all, z_all) = data X_split = np.split(X_all, [VALIDATION_SIZE, VALIDATION_SIZE + TEST_SIZE]) X_valid = X_split[0] X_test = X_split[1] X_train = X_split[2] print('X_valid %s %s' % (type(X_valid), X_valid.shape)) print('X_test %s %s' % (t...
['def', 'load_data():', 'data', '=', '_load_poker_csv()', '(X_all,', 'y_all,', 'z_all)', '=', 'data', 'X_split', '=', 'np.split(X_all,', '[VALIDATION_SIZE,', 'VALIDATION_SIZE', '+', 'TEST_SIZE])', 'X_valid', '=', 'X_split[0]', 'X_test', '=', 'X_split[1]', 'X_train', '=', 'X_split[2]', "print('X_valid", '%s', "%s'", '%'...
181,084
rudranil723/mini-main
ast.py
CVParametersNameStatement.build
build
Calls the builder object's ``add_cv_parameter`` callback.
[ "Calls", "the", "builder", "object's", "``add_cv_parameter``", "callback." ]
def build(self, builder): item = '' if self.block_name == 'ParamUILabelNameID': item = '_{}'.format(builder.cv_num_named_params_.get(self.nameID, 0)) builder.add_cv_parameter(self.nameID) self.nameID = (self.nameID, self.block_name + item) NameRecord.build(self, builder)
['def', 'build(self,', 'builder):', 'item', '=', "''", 'if', 'self.block_name', '==', "'ParamUILabelNameID':", 'item', '=', "'_{}'.format(builder.cv_num_named_params_.get(self.nameID,", '0))', 'builder.add_cv_parameter(self.nameID)', 'self.nameID', '=', '(self.nameID,', 'self.block_name', '+', 'item)', 'NameRecord.buil...
317,109
TrellixVulnTeam/Unsupervised_Learning_HFI7
sorting.py
get_indexer_dict
get_indexer_dict
Returns ------- dict: Labels mapped to indexers.
[ "Returns", "-------", "dict:", "Labels", "mapped", "to", "indexers." ]
def get_indexer_dict(label_list: List[np.ndarray], keys: List['Index']) -> Dict[Union[str, Tuple], np.ndarray]: shape = [len(x) for x in keys] group_index = get_group_index(label_list, shape, sort=True, xnull=True) if np.all(group_index == -1): return {} ngroups = (group_index.size and group_ind...
['def', 'get_indexer_dict(label_list:', 'List[np.ndarray],', 'keys:', "List['Index'])", '->', 'Dict[Union[str,', 'Tuple],', 'np.ndarray]:', 'shape', '=', '[len(x)', 'for', 'x', 'in', 'keys]', 'group_index', '=', 'get_group_index(label_list,', 'shape,', 'sort=True,', 'xnull=True)', 'if', 'np.all(group_index', '==', '-1)...
452,702
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.nnumericdata
nnumericdata
number of mjtNums in all numeric fields.
[ "number", "of", "mjtNums", "in", "all", "numeric", "fields." ]
def nnumericdata(self): return self._ptr.contents.nnumericdata
['def', 'nnumericdata(self):', 'return', 'self._ptr.contents.nnumericdata']
440,209
lancopku/Unpaired-Sentiment-Translation
data.py
outputids2words
outputids2words
Maps output ids to words, including mapping in-article OOVs from their temporary ids to the original OOV string (applicable in pointer-generator mode).
[ "Maps", "output", "ids", "to", "words,", "including", "mapping", "in-article", "OOVs", "from", "their", "temporary", "ids", "to", "the", "original", "OOV", "string", "(applicable", "in", "pointer-generator", "mode)." ]
def outputids2words(id_list, vocab, article_oovs): words = [] for i in id_list: try: w = vocab.id2word(i) except ValueError as e: assert article_oovs is not None, "Error: model produced a word ID that isn't in the vocabulary. This should not happen in baseline (no pointer...
['def', 'outputids2words(id_list,', 'vocab,', 'article_oovs):', 'words', '=', '[]', 'for', 'i', 'in', 'id_list:', 'try:', 'w', '=', 'vocab.id2word(i)', 'except', 'ValueError', 'as', 'e:', 'assert', 'article_oovs', 'is', 'not', 'None,', '"Error:', 'model', 'produced', 'a', 'word', 'ID', 'that', "isn't", 'in', 'the', 'vo...
949,647
arshpreetsingh/quantopian-machinelearning
containers.py
Container.is_modal
is_modal
When this container is modal, key bindings from parent containers are not taken into account if a user control in this container is focused.
[ "When", "this", "container", "is", "modal,", "key", "bindings", "from", "parent", "containers", "are", "not", "taken", "into", "account", "if", "a", "user", "control", "in", "this", "container", "is", "focused." ]
def is_modal(self): return False
['def', 'is_modal(self):', 'return', 'False']
892,396
ogunnoo/natural_language_processing
seq2seq.py
Seq2Seq.log_learning_curves
log_learning_curves
Logs the learning curve info to a csv.
[ "Logs", "the", "learning", "curve", "info", "to", "a", "csv." ]
def log_learning_curves(self, log_dir, graph=True): header = 'epoch,train_loss,valid_loss' num_epochs = len(self.train_losses) with open(os.path.join(log_dir, '{0}_learning_curves.csv'.format(self.name)), 'w') as fp: fp.write('{0}\n'.format(header)) for e in range(num_epochs): fp...
['def', 'log_learning_curves(self,', 'log_dir,', 'graph=True):', 'header', '=', "'epoch,train_loss,valid_loss'", 'num_epochs', '=', 'len(self.train_losses)', 'with', 'open(os.path.join(log_dir,', "'{0}_learning_curves.csv'.format(self.name)),", "'w')", 'as', 'fp:', "fp.write('{0}\\n'.format(header))", 'for', 'e', 'in',...
734,969
muhanzhang/D-VAE
opt.py
local_addsd_ccode
local_addsd_ccode
Convert AddSD to faster AddSD_ccode.
[ "Convert", "AddSD", "to", "faster", "AddSD_ccode." ]
def local_addsd_ccode(node): if isinstance(node.op, sparse.AddSD) and theano.config.cxx: new_node = AddSD_ccode(format=node.inputs[0].type.format)(*node.inputs) return [new_node] return False
['def', 'local_addsd_ccode(node):', 'if', 'isinstance(node.op,', 'sparse.AddSD)', 'and', 'theano.config.cxx:', 'new_node', '=', 'AddSD_ccode(format=node.inputs[0].type.format)(*node.inputs)', 'return', '[new_node]', 'return', 'False']
525,360
greydanus/pythonic_ocr
html.py
HtmlReporter.make_local_static_report_files
make_local_static_report_files
Make local instances of static files for HTML report.
[ "Make", "local", "instances", "of", "static", "files", "for", "HTML", "report." ]
def make_local_static_report_files(self): for (static, pkgdir) in self.STATIC_FILES: shutil.copyfile(data_filename(static, pkgdir), os.path.join(self.directory, static)) if self.extra_css: shutil.copyfile(self.config.extra_css, os.path.join(self.directory, self.extra_css))
['def', 'make_local_static_report_files(self):', 'for', '(static,', 'pkgdir)', 'in', 'self.STATIC_FILES:', 'shutil.copyfile(data_filename(static,', 'pkgdir),', 'os.path.join(self.directory,', 'static))', 'if', 'self.extra_css:', 'shutil.copyfile(self.config.extra_css,', 'os.path.join(self.directory,', 'self.extra_css))...
298,925
google-research/scenic
plainvit.py
PlainViT.loss_function
loss_function
Returns sigmoid or softmax cross entropy loss.
[ "Returns", "sigmoid", "or", "softmax", "cross", "entropy", "loss." ]
def loss_function(self, logits: jnp.ndarray, batch: base_model.Batch, model_params: Optional[jnp.ndarray]=None) -> float: weights = batch.get('batch_mask') loss_fn = self.config.get('loss', 'sigmoid_xent') if self.dataset_meta_data.get('target_is_onehot', False): one_hot_targets = batch['label'] ...
['def', 'loss_function(self,', 'logits:', 'jnp.ndarray,', 'batch:', 'base_model.Batch,', 'model_params:', 'Optional[jnp.ndarray]=None)', '->', 'float:', 'weights', '=', "batch.get('batch_mask')", 'loss_fn', '=', "self.config.get('loss',", "'sigmoid_xent')", 'if', "self.dataset_meta_data.get('target_is_onehot',", 'False...
846,701
Katja-M/Python_NaturalLanguageProcessing
backend_bases.py
NavigationToolbar2.press_pan
press_pan
Callback for mouse button press in pan/zoom mode.
[ "Callback", "for", "mouse", "button", "press", "in", "pan/zoom", "mode." ]
def press_pan(self, event): if event.button == 1: self._button_pressed = 1 elif event.button == 3: self._button_pressed = 3 else: self._button_pressed = None return if self._nav_stack() is None: self.push_current() (x, y) = (event.x, event.y) self._xypress...
['def', 'press_pan(self,', 'event):', 'if', 'event.button', '==', '1:', 'self._button_pressed', '=', '1', 'elif', 'event.button', '==', '3:', 'self._button_pressed', '=', '3', 'else:', 'self._button_pressed', '=', 'None', 'return', 'if', 'self._nav_stack()', 'is', 'None:', 'self.push_current()', '(x,', 'y)', '=', '(eve...
864,305
ADLab3Ds/TiG-BEV
voxel_generator.py
VoxelGenerator.voxel_size
voxel_size
list[float]: Size of a single voxel.
[ "list[float]:", "Size", "of", "a", "single", "voxel." ]
def voxel_size(self): return self._voxel_size
['def', 'voxel_size(self):', 'return', 'self._voxel_size']
916,875
tensorflow/hub
native_module_test.py
cond_module_fn
cond_module_fn
Computes relu(x) with a conditional.
[ "Computes", "relu(x)", "with", "a", "conditional." ]
def cond_module_fn(): x = tf.compat.v1.placeholder(dtype=tf.float32, name='x', shape=[]) result = tf.cond(0 < x, lambda : tf.identity(x), lambda : tf.constant(0.0)) hub.add_signature(inputs=x, outputs=result)
['def', 'cond_module_fn():', 'x', '=', 'tf.compat.v1.placeholder(dtype=tf.float32,', "name='x',", 'shape=[])', 'result', '=', 'tf.cond(0', '<', 'x,', 'lambda', ':', 'tf.identity(x),', 'lambda', ':', 'tf.constant(0.0))', 'hub.add_signature(inputs=x,', 'outputs=result)']
570,997
Jed-Z/artificial-intelligence-lab
main.py
ida_star
ida_star
Do IDA* algorithm from node `root`.
[ "Do", "IDA*", "algorithm", "from", "node", "`root`." ]
def ida_star(root): bound = h2(root) path = [root] while True: ret = search(path, 0, bound) if ret == True: return path if ret == float('inf'): return False else: bound = ret
['def', 'ida_star(root):', 'bound', '=', 'h2(root)', 'path', '=', '[root]', 'while', 'True:', 'ret', '=', 'search(path,', '0,', 'bound)', 'if', 'ret', '==', 'True:', 'return', 'path', 'if', 'ret', '==', "float('inf'):", 'return', 'False', 'else:', 'bound', '=', 'ret']
122,084
RasaHQ/rasa
entities_parser.py
find_entities_in_training_example
find_entities_in_training_example
Extracts entities from an annotated utterance.
[ "Extracts", "entities", "from", "an", "annotated", "utterance." ]
def find_entities_in_training_example(example: Text) -> List[Dict[Text, Any]]: entities = [] offset = 0 for match in re.finditer(ENTITY_REGEX, example): logger.debug(f'Entity annotation regex match: {match}') if match.groupdict()[GROUP_ENTITY_DICT] or match.groupdict()[GROUP_ENTITY_TYPE]: ...
['def', 'find_entities_in_training_example(example:', 'Text)', '->', 'List[Dict[Text,', 'Any]]:', 'entities', '=', '[]', 'offset', '=', '0', 'for', 'match', 'in', 're.finditer(ENTITY_REGEX,', 'example):', "logger.debug(f'Entity", 'annotation', 'regex', 'match:', "{match}')", 'if', 'match.groupdict()[GROUP_ENTITY_DICT]'...
837,663
VincentGranville/Machine-Learning
Smooth.py
LaplacianSmoother.prob_markov_chain
prob_markov_chain
Convenience method for computing probabilities for Markov-chains, such as P(A followed by B), which could be found using prob_markov_chain('AB').
[ "Convenience", "method", "for", "computing", "probabilities", "for", "Markov-chains,", "such", "as", "P(A", "followed", "by", "B),", "which", "could", "be", "found", "using", "prob_markov_chain('AB')." ]
def prob_markov_chain(self, query): size = len(query) assert size > 0 and size <= 2, 'query length must be between 1 and 2: ' + str(query) if size == 1: return self.prob_term_given_label(None, query[0]) else: return self.prob_term_given_label(query[0], query[1])
['def', 'prob_markov_chain(self,', 'query):', 'size', '=', 'len(query)', 'assert', 'size', '>', '0', 'and', 'size', '<=', '2,', "'query", 'length', 'must', 'be', 'between', '1', 'and', '2:', "'", '+', 'str(query)', 'if', 'size', '==', '1:', 'return', 'self.prob_term_given_label(None,', 'query[0])', 'else:', 'return', '...
190,523
sarnsdev/social-alignment-data-mining
mode.py
register_linker
register_linker
Add a `Linker` which can be referred to by `name` in `Mode`.
[ "Add", "a", "`Linker`", "which", "can", "be", "referred", "to", "by", "`name`", "in", "`Mode`." ]
def register_linker(name, linker): if name in predefined_linkers: raise ValueError('Linker name already taken: %s' % name) predefined_linkers[name] = linker
['def', 'register_linker(name,', 'linker):', 'if', 'name', 'in', 'predefined_linkers:', 'raise', "ValueError('Linker", 'name', 'already', 'taken:', "%s'", '%', 'name)', 'predefined_linkers[name]', '=', 'linker']
392,497
FahadTComsats/Natural-Language-Processing
batcher.py
Example.pad_article
pad_article
For selector, pad the article with pad_id up to max_art_len sentences and max_sent_len words for each sentence.
[ "For", "selector,", "pad", "the", "article", "with", "pad_id", "up", "to", "max_art_len", "sentences", "and", "max_sent_len", "words", "for", "each", "sentence." ]
def pad_article(self, max_art_len, max_sent_len, pad_id): while len(self.art_ids) < max_art_len: self.art_ids.append([pad_id] * max_sent_len) self.sent_lens.append(0) assert len(self.art_ids) == max_art_len assert len(self.sent_lens) == max_art_len for i in range(max_art_len): se...
['def', 'pad_article(self,', 'max_art_len,', 'max_sent_len,', 'pad_id):', 'while', 'len(self.art_ids)', '<', 'max_art_len:', 'self.art_ids.append([pad_id]', '*', 'max_sent_len)', 'self.sent_lens.append(0)', 'assert', 'len(self.art_ids)', '==', 'max_art_len', 'assert', 'len(self.sent_lens)', '==', 'max_art_len', 'for', ...
666,081
imoscovitz/wittgenstein
ripper.py
RIPPER.predict
predict
Predict classes of data using a RIPPER-fit model.
[ "Predict", "classes", "of", "data", "using", "a", "RIPPER-fit", "model." ]
def predict(self, X_df, give_reasons=False): if not hasattr(self, 'ruleset_'): raise AttributeError('You should fit a RIPPER object before making predictions with it.') else: return self.ruleset_.predict(X_df, give_reasons=give_reasons)
['def', 'predict(self,', 'X_df,', 'give_reasons=False):', 'if', 'not', 'hasattr(self,', "'ruleset_'):", 'raise', "AttributeError('You", 'should', 'fit', 'a', 'RIPPER', 'object', 'before', 'making', 'predictions', 'with', "it.')", 'else:', 'return', 'self.ruleset_.predict(X_df,', 'give_reasons=give_reasons)']
959,837
pedrojrv/nucml
ml_utilities.py
fill_ml_xs
fill_ml_xs
Fill in the head and tail of a set of cross section values using the hybrid approach.
[ "Fill", "in", "the", "head", "and", "tail", "of", "a", "set", "of", "cross", "section", "values", "using", "the", "hybrid", "approach." ]
def fill_ml_xs(MT, ml_xs, ace_xs, use_peaks=True): if use_peaks: fallback = False (peaks, properties) = find_peaks(ace_xs, prominence=1, width=5) if len(peaks) == 0: fallback = True else: (properties['prominences'], properties['widths']) to_append ...
['def', 'fill_ml_xs(MT,', 'ml_xs,', 'ace_xs,', 'use_peaks=True):', 'if', 'use_peaks:', 'fallback', '=', 'False', '(peaks,', 'properties)', '=', 'find_peaks(ace_xs,', 'prominence=1,', 'width=5)', 'if', 'len(peaks)', '==', '0:', 'fallback', '=', 'True', 'else:', "(properties['prominences'],", "properties['widths'])", 'to...
249,654
Fafa-DL/Image-Augmentation
opensimplex.py
OpenSimplex.noise4d
noise4d
Generate 4D OpenSimplex noise from X,Y,Z,W coordinates.
[ "Generate", "4D", "OpenSimplex", "noise", "from", "X,Y,Z,W", "coordinates." ]
def noise4d(self, x, y, z, w): stretch_offset = (x + y + z + w) * STRETCH_CONSTANT_4D xs = x + stretch_offset ys = y + stretch_offset zs = z + stretch_offset ws = w + stretch_offset xsb = floor(xs) ysb = floor(ys) zsb = floor(zs) wsb = floor(ws) squish_offset = (xsb + ysb + zsb +...
['def', 'noise4d(self,', 'x,', 'y,', 'z,', 'w):', 'stretch_offset', '=', '(x', '+', 'y', '+', 'z', '+', 'w)', '*', 'STRETCH_CONSTANT_4D', 'xs', '=', 'x', '+', 'stretch_offset', 'ys', '=', 'y', '+', 'stretch_offset', 'zs', '=', 'z', '+', 'stretch_offset', 'ws', '=', 'w', '+', 'stretch_offset', 'xsb', '=', 'floor(xs)', '...
598,974
Megvii-BaseDetection/DynamicRouting
jit_handles.py
generic_activation_jit
generic_activation_jit
This method return a handle that counts the number of activation from the output shape for the specified operation.
[ "This", "method", "return", "a", "handle", "that", "counts", "the", "number", "of", "activation", "from", "the", "output", "shape", "for", "the", "specified", "operation." ]
def generic_activation_jit(op_name: str) -> typing.Callable[[typing.List[object], typing.List[object]], typing.Counter[str]]: def _generic_activation_jit(outputs: typing.List[object]) -> int: out_shape = get_shape(outputs[0]) ac_count = prod(out_shape) return ac_count return lambda inpu...
['def', 'generic_activation_jit(op_name:', 'str)', '->', 'typing.Callable[[typing.List[object],', 'typing.List[object]],', 'typing.Counter[str]]:', 'def', '_generic_activation_jit(outputs:', 'typing.List[object])', '->', 'int:', 'out_shape', '=', 'get_shape(outputs[0])', 'ac_count', '=', 'prod(out_shape)', 'return', 'a...
555,222
YannDubs/Invariant-Self-Supervised-Learning
main.py
get_callbacks
get_callbacks
Return list of callbacks.
[ "Return", "list", "of", "callbacks." ]
def get_callbacks(cfg: NamespaceMap, is_representor: bool, dm: pl.LightningDataModule=None) -> list[pl.callbacks.Callback]: callbacks = [] if is_representor: if hasattr(cfg.decodability, 'is_ema') and cfg.decodability.is_ema: callbacks += [MAWeightUpdate()] callbacks += [pl.callbacks.Mod...
['def', 'get_callbacks(cfg:', 'NamespaceMap,', 'is_representor:', 'bool,', 'dm:', 'pl.LightningDataModule=None)', '->', 'list[pl.callbacks.Callback]:', 'callbacks', '=', '[]', 'if', 'is_representor:', 'if', 'hasattr(cfg.decodability,', "'is_ema')", 'and', 'cfg.decodability.is_ema:', 'callbacks', '+=', '[MAWeightUpdate(...
245,878
google-research/rigl
masked_test.py
MaskedTest.test_invalid_mask
test_invalid_mask
Tests using an invalid mask.
[ "Tests", "using", "an", "invalid", "mask." ]
def test_invalid_mask(self): invalid_mask = {'MaskedModule_0': {'not_kernel': jnp.ones(self._unmasked_model.params['Dense_0']['kernel'].shape)}} with self.assertRaisesRegex(ValueError, 'Mask is invalid for model.'): self._masked_model(self._input, mask=invalid_mask)
['def', 'test_invalid_mask(self):', 'invalid_mask', '=', "{'MaskedModule_0':", "{'not_kernel':", "jnp.ones(self._unmasked_model.params['Dense_0']['kernel'].shape)}}", 'with', 'self.assertRaisesRegex(ValueError,', "'Mask", 'is', 'invalid', 'for', "model.'):", 'self._masked_model(self._input,', 'mask=invalid_mask)']
841,470
scikit-learn/scikit-learn
test_from_model.py
test_prefit_get_feature_names_out
test_prefit_get_feature_names_out
Check the interaction between prefit and the feature names.
[ "Check", "the", "interaction", "between", "prefit", "and", "the", "feature", "names." ]
def test_prefit_get_feature_names_out(): clf = RandomForestClassifier(n_estimators=2, random_state=0) clf.fit(data, y) model = SelectFromModel(clf, prefit=True, max_features=1) name = type(model).__name__ err_msg = f"This {name} instance is not fitted yet. Call 'fit' with appropriate arguments befor...
['def', 'test_prefit_get_feature_names_out():', 'clf', '=', 'RandomForestClassifier(n_estimators=2,', 'random_state=0)', 'clf.fit(data,', 'y)', 'model', '=', 'SelectFromModel(clf,', 'prefit=True,', 'max_features=1)', 'name', '=', 'type(model).__name__', 'err_msg', '=', 'f"This', '{name}', 'instance', 'is', 'not', 'fitt...
853,334
ryu-ed/SpaceInvaders_Ros
nodes.py
Element.is_not_known_attribute
is_not_known_attribute
Returns True if and only if the given attribute is NOT recognized by this class.
[ "Returns", "True", "if", "and", "only", "if", "the", "given", "attribute", "is", "NOT", "recognized", "by", "this", "class." ]
def is_not_known_attribute(cls, attr): return attr not in cls.known_attributes
['def', 'is_not_known_attribute(cls,', 'attr):', 'return', 'attr', 'not', 'in', 'cls.known_attributes']
394,789
43Carrig/recurrent_neural_networks_practice
export.py
regression_signature_fn
regression_signature_fn
Creates regression signature from given examples and predictions.
[ "Creates", "regression", "signature", "from", "given", "examples", "and", "predictions." ]
def regression_signature_fn(examples, unused_features, predictions): if examples is None: raise ValueError('examples cannot be None when using this signature fn.') default_signature = exporter.regression_signature(input_tensor=examples, output_tensor=predictions) return (default_signature, {})
['def', 'regression_signature_fn(examples,', 'unused_features,', 'predictions):', 'if', 'examples', 'is', 'None:', 'raise', "ValueError('examples", 'cannot', 'be', 'None', 'when', 'using', 'this', 'signature', "fn.')", 'default_signature', '=', 'exporter.regression_signature(input_tensor=examples,', 'output_tensor=pred...
313,714
weimin17/Object-Detection_HelmetDetection
plot_partition.py
plot_partition
plot_partition
Plots an expert version of the privacy-per-answered-query graph.
[ "Plots", "an", "expert", "version", "of", "the", "privacy-per-answered-query", "graph." ]
def plot_partition(figures_dir, gnmax_conf, print_order): (eps_partitioned, answered, ss_std_opt, order_opt) = gnmax_conf xlim = 10000 x = range(0, int(xlim), 10) lenx = len(x) y0 = np.full(lenx, np.nan, dtype=float) y1 = np.full(lenx, np.nan, dtype=float) y2 = np.full(lenx, np.nan, dtype=fl...
['def', 'plot_partition(figures_dir,', 'gnmax_conf,', 'print_order):', '(eps_partitioned,', 'answered,', 'ss_std_opt,', 'order_opt)', '=', 'gnmax_conf', 'xlim', '=', '10000', 'x', '=', 'range(0,', 'int(xlim),', '10)', 'lenx', '=', 'len(x)', 'y0', '=', 'np.full(lenx,', 'np.nan,', 'dtype=float)', 'y1', '=', 'np.full(lenx...
749,803
JamesPiggott/Ancient-Language-Decipherer
image_processing.py
ImageProcessing.apply_canny_edge_detection
apply_canny_edge_detection
Apply Canny edge detection.
[ "Apply", "Canny", "edge", "detection." ]
def apply_canny_edge_detection(self): self.edges_img = cv2.Canny(self.blurred_img, self.lower_threshold, self.upper_threshold, apertureSize=3) cv2.imshow('Canny', self.edges_img) cv2.waitKey(0) cv2.destroyAllWindows()
['def', 'apply_canny_edge_detection(self):', 'self.edges_img', '=', 'cv2.Canny(self.blurred_img,', 'self.lower_threshold,', 'self.upper_threshold,', 'apertureSize=3)', "cv2.imshow('Canny',", 'self.edges_img)', 'cv2.waitKey(0)', 'cv2.destroyAllWindows()']
416,264
flavioschneider/rl-transfer-
dm_control_env.py
DMControlEnv.from_suite
from_suite
Create a DmControl task given the domain name and task name.
[ "Create", "a", "DmControl", "task", "given", "the", "domain", "name", "and", "task", "name." ]
def from_suite(cls, domain_name, task_name): return cls(env=suite.load(domain_name, task_name), name='{}.{}'.format(domain_name, task_name))
['def', 'from_suite(cls,', 'domain_name,', 'task_name):', 'return', 'cls(env=suite.load(domain_name,', 'task_name),', "name='{}.{}'.format(domain_name,", 'task_name))']
861,055
weimin17/Object-Detection_HelmetDetection
data_providers.py
parse_sequence_to_pairs_batch
parse_sequence_to_pairs_batch
Parses a serialized sequence example into a batch of preprocessed data.
[ "Parses", "a", "serialized", "sequence", "example", "into", "a", "batch", "of", "preprocessed", "data." ]
def parse_sequence_to_pairs_batch(serialized_example, preprocess_fn, is_training, num_views, batch_size, window): (_, views, seq_len) = parse_sequence_example(serialized_example, num_views) num_pairs = batch_size // 2 (ap_time_indices, a_view_indices, p_view_indices) = get_tcn_anchor_pos_indices(seq_len, nu...
['def', 'parse_sequence_to_pairs_batch(serialized_example,', 'preprocess_fn,', 'is_training,', 'num_views,', 'batch_size,', 'window):', '(_,', 'views,', 'seq_len)', '=', 'parse_sequence_example(serialized_example,', 'num_views)', 'num_pairs', '=', 'batch_size', '//', '2', '(ap_time_indices,', 'a_view_indices,', 'p_view...
760,530
43Carrig/recurrent_neural_networks_practice
feature_column.py
_CrossedColumn.id_tensor
id_tensor
Returns the id tensor from the given transformed input_tensor.
[ "Returns", "the", "id", "tensor", "from", "the", "given", "transformed", "input_tensor." ]
def id_tensor(self, input_tensor): return input_tensor
['def', 'id_tensor(self,', 'input_tensor):', 'return', 'input_tensor']
313,436
TrellixVulnTeam/Unsupervised_Learning_HFI7
_base.py
_AxesBase.get_yticklines
get_yticklines
Get the y tick lines as a list of `Line2D` instances.
[ "Get", "the", "y", "tick", "lines", "as", "a", "list", "of", "`Line2D`", "instances." ]
def get_yticklines(self): return self.yaxis.get_ticklines()
['def', 'get_yticklines(self):', 'return', 'self.yaxis.get_ticklines()']
451,003
jimtin/Stock_Comparison
displayhook.py
ZMQShellDisplayHook.finish_displayhook
finish_displayhook
Finish up all displayhook activities.
[ "Finish", "up", "all", "displayhook", "activities." ]
def finish_displayhook(self): sys.stdout.flush() sys.stderr.flush() if self.msg['content']['data']: self.session.send(self.pub_socket, self.msg, ident=self.topic) self.msg = None
['def', 'finish_displayhook(self):', 'sys.stdout.flush()', 'sys.stderr.flush()', 'if', "self.msg['content']['data']:", 'self.session.send(self.pub_socket,', 'self.msg,', 'ident=self.topic)', 'self.msg', '=', 'None']
384,415
aws/sagemaker-python-sdk
pipeline.py
LocalPipelineExecutor.execute
execute
Execute a local pipeline.
[ "Execute", "a", "local", "pipeline." ]
def execute(self): try: for step in self.pipeline_dag: if step.name not in self._blocked_steps: self._execute_step(step) except StepExecutionException as e: self.execution.update_execution_failure(e.step_name, e.message) else: self.execution.update_executi...
['def', 'execute(self):', 'try:', 'for', 'step', 'in', 'self.pipeline_dag:', 'if', 'step.name', 'not', 'in', 'self._blocked_steps:', 'self._execute_step(step)', 'except', 'StepExecutionException', 'as', 'e:', 'self.execution.update_execution_failure(e.step_name,', 'e.message)', 'else:', 'self.execution.update_execution...
830,344
rudranil723/mini-main
base.py
DataManager.reindex_axis
reindex_axis
Conform data manager to new index.
[ "Conform", "data", "manager", "to", "new", "index." ]
def reindex_axis(self: T, new_index: Index, axis: int, fill_value=None, only_slice: bool=False) -> T: (new_index, indexer) = self.axes[axis].reindex(new_index) return self.reindex_indexer(new_index, indexer, axis=axis, fill_value=fill_value, copy=False, only_slice=only_slice)
['def', 'reindex_axis(self:', 'T,', 'new_index:', 'Index,', 'axis:', 'int,', 'fill_value=None,', 'only_slice:', 'bool=False)', '->', 'T:', '(new_index,', 'indexer)', '=', 'self.axes[axis].reindex(new_index)', 'return', 'self.reindex_indexer(new_index,', 'indexer,', 'axis=axis,', 'fill_value=fill_value,', 'copy=False,',...
324,017
Kvatsx/Artificial-Intelligence-Assignments
test_magic.py
test_magic_parse_options
test_magic_parse_options
Test that we don't mangle paths when parsing magic options.
[ "Test", "that", "we", "don't", "mangle", "paths", "when", "parsing", "magic", "options." ]
def test_magic_parse_options(): ip = get_ipython() path = 'c:\\x' m = DummyMagics(ip) opts = m.parse_options('-f %s' % path, 'f:')[0] if os.name == 'posix': expected = 'c:x' else: expected = path nt.assert_equal(opts['f'], expected)
['def', 'test_magic_parse_options():', 'ip', '=', 'get_ipython()', 'path', '=', "'c:\\\\x'", 'm', '=', 'DummyMagics(ip)', 'opts', '=', "m.parse_options('-f", "%s'", '%', 'path,', "'f:')[0]", 'if', 'os.name', '==', "'posix':", 'expected', '=', "'c:x'", 'else:', 'expected', '=', 'path', "nt.assert_equal(opts['f'],", 'exp...
38,430
ADLab3Ds/TiG-BEV
primitive_head.py
PrimitiveHead.primitive_decode_scores
primitive_decode_scores
Decode predicted parts to primitive head.
[ "Decode", "predicted", "parts", "to", "primitive", "head." ]
def primitive_decode_scores(self, predictions, aggregated_points): ret_dict = {} pred_transposed = predictions.transpose(2, 1) center = aggregated_points + pred_transposed[:, :, 0:3] ret_dict['center_' + self.primitive_mode] = center if self.primitive_mode in ['z', 'xy']: ret_dict['size_resi...
['def', 'primitive_decode_scores(self,', 'predictions,', 'aggregated_points):', 'ret_dict', '=', '{}', 'pred_transposed', '=', 'predictions.transpose(2,', '1)', 'center', '=', 'aggregated_points', '+', 'pred_transposed[:,', ':,', '0:3]', "ret_dict['center_'", '+', 'self.primitive_mode]', '=', 'center', 'if', 'self.prim...
917,119
Ruturaj123/Flowchart-Detection
control_flow_ops.py
ControlFlowContext.ExitResult
ExitResult
Make a list of tensors available in the outer context.
[ "Make", "a", "list", "of", "tensors", "available", "in", "the", "outer", "context." ]
def ExitResult(self, result): if self._outer_context: nest.map_structure(lambda x: self._outer_context.AddName(x.name), result)
['def', 'ExitResult(self,', 'result):', 'if', 'self._outer_context:', 'nest.map_structure(lambda', 'x:', 'self._outer_context.AddName(x.name),', 'result)']
605,799
weimin17/Object-Detection_HelmetDetection
common.py
transformer_at_state
transformer_at_state
Get the base_model that has been transformed to use the variables in final_state.
[ "Get", "the", "base_model", "that", "has", "been", "transformed", "to", "use", "the", "variables", "in", "final_state." ]
def transformer_at_state(base_model, new_variables): assert not variable_replace.in_variable_replace_scope() def _feature_transformer(input_data): initial_variables = base_model.get_variables() replacement = collections.OrderedDict(utils.eqzip(initial_variables, new_variables)) with var...
['def', 'transformer_at_state(base_model,', 'new_variables):', 'assert', 'not', 'variable_replace.in_variable_replace_scope()', 'def', '_feature_transformer(input_data):', 'initial_variables', '=', 'base_model.get_variables()', 'replacement', '=', 'collections.OrderedDict(utils.eqzip(initial_variables,', 'new_variables...
763,400
rudranil723/mini-main
columns.py
Columns.add_renderable
add_renderable
Add a renderable to the columns.
[ "Add", "a", "renderable", "to", "the", "columns." ]
def add_renderable(self, renderable: RenderableType) -> None: self.renderables.append(renderable)
['def', 'add_renderable(self,', 'renderable:', 'RenderableType)', '->', 'None:', 'self.renderables.append(renderable)']
268,879
GregorKobsik/Octree-Transformer
kd_tree_utils.py
TrinaryRepresentation.decode_trinary_value
decode_trinary_value
Transforms given trinary value sequence into a basic sequence representation.
[ "Transforms", "given", "trinary", "value", "sequence", "into", "a", "basic", "sequence", "representation." ]
def decode_trinary_value(self, value): value_new = [] for val_token in value: value_new += self.dec_to_tri(val_token) value = np.array(value_new).reshape(-1) return value
['def', 'decode_trinary_value(self,', 'value):', 'value_new', '=', '[]', 'for', 'val_token', 'in', 'value:', 'value_new', '+=', 'self.dec_to_tri(val_token)', 'value', '=', 'np.array(value_new).reshape(-1)', 'return', 'value']
755,172
BurkhardtMicah/Artificial-Intelligence
search.py
BoggleFinder.score
score
The total score for the words found, according to the rules.
[ "The", "total", "score", "for", "the", "words", "found,", "according", "to", "the", "rules." ]
def score(self): return sum([self.scores[len(w)] for w in self.words()])
['def', 'score(self):', 'return', 'sum([self.scores[len(w)]', 'for', 'w', 'in', 'self.words()])']
119,048
KalleHallden/InstaAutomator
match.py
match
match
Matches the given input againts the available file type matchers.
[ "Matches", "the", "given", "input", "againts", "the", "available", "file", "type", "matchers." ]
def match(obj, matchers=TYPES): buf = get_bytes(obj) for matcher in matchers: if matcher.match(buf): return matcher return None
['def', 'match(obj,', 'matchers=TYPES):', 'buf', '=', 'get_bytes(obj)', 'for', 'matcher', 'in', 'matchers:', 'if', 'matcher.match(buf):', 'return', 'matcher', 'return', 'None']
242,409
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_lobpcg.py
test_tolerance_float32
test_tolerance_float32
Check lobpcg for attainable tolerance in float32.
[ "Check", "lobpcg", "for", "attainable", "tolerance", "in", "float32." ]
def test_tolerance_float32(): np.random.seed(1234) n = 50 m = 3 vals = -np.arange(1, n + 1) A = diags([vals], [0], (n, n)) A = A.astype(np.float32) X = np.random.randn(n, m) X = X.astype(np.float32) (eigvals, _) = lobpcg(A, X, tol=1e-09, maxiter=50, verbosityLevel=0) assert_allcl...
['def', 'test_tolerance_float32():', 'np.random.seed(1234)', 'n', '=', '50', 'm', '=', '3', 'vals', '=', '-np.arange(1,', 'n', '+', '1)', 'A', '=', 'diags([vals],', '[0],', '(n,', 'n))', 'A', '=', 'A.astype(np.float32)', 'X', '=', 'np.random.randn(n,', 'm)', 'X', '=', 'X.astype(np.float32)', '(eigvals,', '_)', '=', 'lo...
260,394
zhyhan/TransPar
keypoint_detection.py
center_crop
center_crop
Crop the given PIL Image and resize it to desired size.
[ "Crop", "the", "given", "PIL", "Image", "and", "resize", "it", "to", "desired", "size." ]
def center_crop(image, output_size, keypoint2d: np.ndarray): (width, height) = image.size (crop_height, crop_width) = output_size crop_top = int(round((height - crop_height) / 2.0)) crop_left = int(round((width - crop_width) / 2.0)) return crop(image, crop_top, crop_left, crop_height, crop_width, ke...
['def', 'center_crop(image,', 'output_size,', 'keypoint2d:', 'np.ndarray):', '(width,', 'height)', '=', 'image.size', '(crop_height,', 'crop_width)', '=', 'output_size', 'crop_top', '=', 'int(round((height', '-', 'crop_height)', '/', '2.0))', 'crop_left', '=', 'int(round((width', '-', 'crop_width)', '/', '2.0))', 'retu...
356,092
scikit-learn/scikit-learn
test_array_api.py
test_convert_to_numpy_cpu
test_convert_to_numpy_cpu
Check convert_to_numpy for PyTorch CPU arrays.
[ "Check", "convert_to_numpy", "for", "PyTorch", "CPU", "arrays." ]
def test_convert_to_numpy_cpu(): torch = pytest.importorskip('torch') X_torch = torch.asarray([1.0, 2.0, 3.0], device='cpu') X_cpu = _convert_to_numpy(X_torch, xp=torch) expected_output = numpy.asarray([1.0, 2.0, 3.0]) assert_allclose(X_cpu, expected_output)
['def', 'test_convert_to_numpy_cpu():', 'torch', '=', "pytest.importorskip('torch')", 'X_torch', '=', 'torch.asarray([1.0,', '2.0,', '3.0],', "device='cpu')", 'X_cpu', '=', '_convert_to_numpy(X_torch,', 'xp=torch)', 'expected_output', '=', 'numpy.asarray([1.0,', '2.0,', '3.0])', 'assert_allclose(X_cpu,', 'expected_outp...
854,288
muhanzhang/D-VAE
test_rng_mrg.py
test_consistency_GPU_serial
test_consistency_GPU_serial
Verify that the random numbers generated by GPU_mrg_uniform, serially, are the same as the reference (Java) implementation by L'Ecuyer et al.
[ "Verify", "that", "the", "random", "numbers", "generated", "by", "GPU_mrg_uniform,", "serially,", "are", "the", "same", "as", "the", "reference", "(Java)", "implementation", "by", "L'Ecuyer", "et", "al." ]
def test_consistency_GPU_serial(): if not cuda_available: raise SkipTest('Optional package cuda not available') if config.mode == 'FAST_COMPILE': mode = 'FAST_RUN' else: mode = config.mode seed = 12345 n_samples = 5 n_streams = 12 n_substreams = 7 samples = [] ...
['def', 'test_consistency_GPU_serial():', 'if', 'not', 'cuda_available:', 'raise', "SkipTest('Optional", 'package', 'cuda', 'not', "available')", 'if', 'config.mode', '==', "'FAST_COMPILE':", 'mode', '=', "'FAST_RUN'", 'else:', 'mode', '=', 'config.mode', 'seed', '=', '12345', 'n_samples', '=', '5', 'n_streams', '=', '...
525,249
Katja-M/Python_NaturalLanguageProcessing
ticker.py
LogLocator.base
base
Set the log base (major tick every ``base**i``, i integer).
[ "Set", "the", "log", "base", "(major", "tick", "every", "``base**i``,", "i", "integer)." ]
def base(self, base): self._base = float(base)
['def', 'base(self,', 'base):', 'self._base', '=', 'float(base)']
864,922
tudelft3d/SUMS-Semantic-Urban-Mesh--public
bn_schedulers.py
set_bn_momentum_default
set_bn_momentum_default
This function return a function which will assign `bn_momentum` to every module instance within `BATCH_NORM_MODULES`.
[ "This", "function", "return", "a", "function", "which", "will", "assign", "`bn_momentum`", "to", "every", "module", "instance", "within", "`BATCH_NORM_MODULES`." ]
def set_bn_momentum_default(bn_momentum): def fn(m): if isinstance(m, BATCH_NORM_MODULES): m.momentum = bn_momentum return fn
['def', 'set_bn_momentum_default(bn_momentum):', 'def', 'fn(m):', 'if', 'isinstance(m,', 'BATCH_NORM_MODULES):', 'm.momentum', '=', 'bn_momentum', 'return', 'fn']
910,653
danamyu/hedgehog_detector
problem_generator.py
SoftmaxClassifier.accuracy
accuracy
Computes the accuracy (fraction of correct classifications).
[ "Computes", "the", "accuracy", "(fraction", "of", "correct", "classifications)." ]
def accuracy(self, params, data, labels): predictions = self.argmax(self.inference(params, data)) return tf.contrib.metrics.accuracy(predictions, tf.cast(labels, tf.int32))
['def', 'accuracy(self,', 'params,', 'data,', 'labels):', 'predictions', '=', 'self.argmax(self.inference(params,', 'data))', 'return', 'tf.contrib.metrics.accuracy(predictions,', 'tf.cast(labels,', 'tf.int32))']
589,766
EricSteinberger/PokerRL
ChiefBase.py
ChiefBase.export_agent
export_agent
Wraps the current strategy of the agent in an EvalAgent instance and exports that.
[ "Wraps", "the", "current", "strategy", "of", "the", "agent", "in", "an", "EvalAgent", "instance", "and", "exports", "that." ]
def export_agent(self, step): raise NotImplementedError
['def', 'export_agent(self,', 'step):', 'raise', 'NotImplementedError']
305,675
rifqind/Agent-Programs-3KS1
test_pretty.py
test_pprint_nomod
test_pprint_nomod
Test that pprint works for classes with no __module__.
[ "Test", "that", "pprint", "works", "for", "classes", "with", "no", "__module__." ]
def test_pprint_nomod(): output = pretty.pretty(NoModule) nt.assert_equal(output, 'NoModule')
['def', 'test_pprint_nomod():', 'output', '=', 'pretty.pretty(NoModule)', 'nt.assert_equal(output,', "'NoModule')"]
41,689
Speedwagon13/CS-3600-Introduction-to--
headers.py
Headers.setdefault
setdefault
Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.
[ "Return", "first", "matching", "header", "value", "for", "'name',", "or", "'value'", "If", "there", "is", "no", "header", "named", "'name',", "add", "a", "new", "header", "with", "name", "'name'", "and", "value", "'value'." ]
def setdefault(self, name, value): result = self.get(name) if result is None: self._headers.append((name, value)) return value else: return result
['def', 'setdefault(self,', 'name,', 'value):', 'result', '=', 'self.get(name)', 'if', 'result', 'is', 'None:', 'self._headers.append((name,', 'value))', 'return', 'value', 'else:', 'return', 'result']
219,703
implus/GFocal
guided_anchor_head.py
GuidedAnchorHead.get_anchors
get_anchors
Get squares according to feature map sizes and guided anchors.
[ "Get", "squares", "according", "to", "feature", "map", "sizes", "and", "guided", "anchors." ]
def get_anchors(self, featmap_sizes, shape_preds, loc_preds, img_metas, use_loc_filter=False, device='cuda'): num_imgs = len(img_metas) num_levels = len(featmap_sizes) multi_level_squares = [] for i in range(num_levels): squares = self.square_generators[i].grid_anchors(featmap_sizes[i], self.anc...
['def', 'get_anchors(self,', 'featmap_sizes,', 'shape_preds,', 'loc_preds,', 'img_metas,', 'use_loc_filter=False,', "device='cuda'):", 'num_imgs', '=', 'len(img_metas)', 'num_levels', '=', 'len(featmap_sizes)', 'multi_level_squares', '=', '[]', 'for', 'i', 'in', 'range(num_levels):', 'squares', '=', 'self.square_genera...
557,250
sunishsheth2009/ChatterBot
conftest.py
model_form_all
model_form_all
Returns one of each possible model form classes with custom and the original metaclass.
[ "Returns", "one", "of", "each", "possible", "model", "form", "classes", "with", "custom", "and", "the", "original", "metaclass." ]
def model_form_all(request): ModelForm = model_form_factory(meta=request.param) return ModelForm
['def', 'model_form_all(request):', 'ModelForm', '=', 'model_form_factory(meta=request.param)', 'return', 'ModelForm']
485,757
Ruturaj123/Flowchart-Detection
factorization_ops.py
WALSModel.initialize_row_update_op
initialize_row_update_op
Op to initialize worker state before starting row updates.
[ "Op", "to", "initialize", "worker", "state", "before", "starting", "row", "updates." ]
def initialize_row_update_op(self): return self._row_updates_init
['def', 'initialize_row_update_op(self):', 'return', 'self._row_updates_init']
602,992
kukuruza/shuffler
backend_db.py
upgradeV4toV5
upgradeV4toV5
Upgrade the schema to V5, now object coordinates are floating-point.
[ "Upgrade", "the", "schema", "to", "V5,", "now", "object", "coordinates", "are", "floating-point." ]
def upgradeV4toV5(cursor): cursor.execute('SELECT name FROM sqlite_master WHERE type == "index" AND (name LIKE "objects%" OR name LIKE "polygons%")') for (index_name,) in cursor.fetchall(): logging.debug('Dropping index: %s', index_name) cursor.execute('DROP INDEX "%s"' % index_name) cursor....
['def', 'upgradeV4toV5(cursor):', "cursor.execute('SELECT", 'name', 'FROM', 'sqlite_master', 'WHERE', 'type', '==', '"index"', 'AND', '(name', 'LIKE', '"objects%"', 'OR', 'name', 'LIKE', '"polygons%")\')', 'for', '(index_name,)', 'in', 'cursor.fetchall():', "logging.debug('Dropping", 'index:', "%s',", 'index_name)', "c...
933,789
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_latextools.py
test_latex_to_png_color
test_latex_to_png_color
Test color settings for latex_to_png.
[ "Test", "color", "settings", "for", "latex_to_png." ]
def test_latex_to_png_color(): latex_string = '$x^2$' default_value = latextools.latex_to_png(latex_string, wrap=False) default_hexblack = latextools.latex_to_png(latex_string, wrap=False, color='#000000') dvipng_default = latextools.latex_to_png_dvipng(latex_string, False) dvipng_black = latextools...
['def', 'test_latex_to_png_color():', 'latex_string', '=', "'$x^2$'", 'default_value', '=', 'latextools.latex_to_png(latex_string,', 'wrap=False)', 'default_hexblack', '=', 'latextools.latex_to_png(latex_string,', 'wrap=False,', "color='#000000')", 'dvipng_default', '=', 'latextools.latex_to_png_dvipng(latex_string,', ...
448,783
enyac-group/NeuralPower
profiler.py
Profiler.save_conv_layers
save_conv_layers
Save convolution layers into separate files.
[ "Save", "convolution", "layers", "into", "separate", "files." ]
def save_conv_layers(self, save_dir): for layer_spec in self.graph.topology_order: if layer_spec['type'] != 'Convolution': continue layer = layer_spec.layer_op outfilename = os.path.join(save_dir, '%s.json' % layer_spec.name) save_layer.save_conv_layer(outfilename, layer)
['def', 'save_conv_layers(self,', 'save_dir):', 'for', 'layer_spec', 'in', 'self.graph.topology_order:', 'if', "layer_spec['type']", '!=', "'Convolution':", 'continue', 'layer', '=', 'layer_spec.layer_op', 'outfilename', '=', 'os.path.join(save_dir,', "'%s.json'", '%', 'layer_spec.name)', 'save_layer.save_conv_layer(ou...
293,445
ViTAE-Transformer/ViTDet
standard_roi_head.py
StandardRoIHead.mask_onnx_export
mask_onnx_export
Export mask branch to onnx which supports batch inference.
[ "Export", "mask", "branch", "to", "onnx", "which", "supports", "batch", "inference." ]
def mask_onnx_export(self, x, img_metas, det_bboxes, det_labels, **kwargs): if all((det_bbox.shape[0] == 0 for det_bbox in det_bboxes)): raise RuntimeError('[ONNX Error] Can not record MaskHead as it has not been executed this time') batch_size = det_bboxes.size(0) det_bboxes = det_bboxes[..., :4] ...
['def', 'mask_onnx_export(self,', 'x,', 'img_metas,', 'det_bboxes,', 'det_labels,', '**kwargs):', 'if', 'all((det_bbox.shape[0]', '==', '0', 'for', 'det_bbox', 'in', 'det_bboxes)):', 'raise', "RuntimeError('[ONNX", 'Error]', 'Can', 'not', 'record', 'MaskHead', 'as', 'it', 'has', 'not', 'been', 'executed', 'this', "time...
945,749
Ruturaj123/Flowchart-Detection
data_flow_ops.py
BaseStagingArea.dtypes
dtypes
The list of dtypes for each component of a staging area element.
[ "The", "list", "of", "dtypes", "for", "each", "component", "of", "a", "staging", "area", "element." ]
def dtypes(self): return self._dtypes
['def', 'dtypes(self):', 'return', 'self._dtypes']
605,857
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mnist.py
run_mnist
run_mnist
Run MNIST training and eval loop.
[ "Run", "MNIST", "training", "and", "eval", "loop." ]
def run_mnist(): mnist_classifier = tf.estimator.Estimator(model_fn=model_fn, model_dir=FLAGS.model_dir) def train_input_fn(): ds = dataset.train(FLAGS.data_dir) ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size) ds = ds_batched.repeat(FLAGS.epochs_between_evals)...
['def', 'run_mnist():', 'mnist_classifier', '=', 'tf.estimator.Estimator(model_fn=model_fn,', 'model_dir=FLAGS.model_dir)', 'def', 'train_input_fn():', 'ds', '=', 'dataset.train(FLAGS.data_dir)', 'ds_batched', '=', 'ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size)', 'ds', '=', 'ds_batched.repeat(FLAGS.epoc...
965,520
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
rollout.py
Rollout.extend
extend
Append another rollout to this rollout.
[ "Append", "another", "rollout", "to", "this", "rollout." ]
def extend(self, other): assert not self.terminated self.states.extend(other.states) self.actions.extend(other.actions) self.rewards.extend(other.rewards) self.values.extend(other.values) self.terminated = other.terminated self.total_reward += other.total_reward
['def', 'extend(self,', 'other):', 'assert', 'not', 'self.terminated', 'self.states.extend(other.states)', 'self.actions.extend(other.actions)', 'self.rewards.extend(other.rewards)', 'self.values.extend(other.values)', 'self.terminated', '=', 'other.terminated', 'self.total_reward', '+=', 'other.total_reward']
52,514
PaddlePaddle/PaddleSpeech
losses.py
KLDivergenceLoss.forward
forward
Calculate KL divergence loss.
[ "Calculate", "KL", "divergence", "loss." ]
def forward(self, z_p: paddle.Tensor, logs_q: paddle.Tensor, m_p: paddle.Tensor, logs_p: paddle.Tensor, z_mask: paddle.Tensor) -> paddle.Tensor: z_p = paddle.cast(z_p, 'float32') logs_q = paddle.cast(logs_q, 'float32') m_p = paddle.cast(m_p, 'float32') logs_p = paddle.cast(logs_p, 'float32') z_mask ...
['def', 'forward(self,', 'z_p:', 'paddle.Tensor,', 'logs_q:', 'paddle.Tensor,', 'm_p:', 'paddle.Tensor,', 'logs_p:', 'paddle.Tensor,', 'z_mask:', 'paddle.Tensor)', '->', 'paddle.Tensor:', 'z_p', '=', 'paddle.cast(z_p,', "'float32')", 'logs_q', '=', 'paddle.cast(logs_q,', "'float32')", 'm_p', '=', 'paddle.cast(m_p,', "'...
277,247
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
variables.py
get_unique_variable
get_unique_variable
Gets the variable uniquely identified by that name.
[ "Gets", "the", "variable", "uniquely", "identified", "by", "that", "name." ]
def get_unique_variable(name): candidates = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, name) if not candidates: raise ValueError('Couldnt find variable %s' % name) for candidate in candidates: if candidate.op.name == name: return candidate raise ValueError('Variable %s ...
['def', 'get_unique_variable(name):', 'candidates', '=', 'tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,', 'name)', 'if', 'not', 'candidates:', 'raise', "ValueError('Couldnt", 'find', 'variable', "%s'", '%', 'name)', 'for', 'candidate', 'in', 'candidates:', 'if', 'candidate.op.name', '==', 'name:', 'return', 'candida...
49,137
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
policy.py
Policy.sample_action
sample_action
Sample an action from a distribution.
[ "Sample", "an", "action", "from", "a", "distribution." ]
def sample_action(self, logits, sampling_dim, act_dim, act_type, greedy=False): if self.env_spec.is_discrete(act_type): if greedy: act = tf.argmax(logits, 1) else: act = tf.reshape(tf.multinomial(logits, 1), [-1]) elif self.env_spec.is_box(act_type): means = logit...
['def', 'sample_action(self,', 'logits,', 'sampling_dim,', 'act_dim,', 'act_type,', 'greedy=False):', 'if', 'self.env_spec.is_discrete(act_type):', 'if', 'greedy:', 'act', '=', 'tf.argmax(logits,', '1)', 'else:', 'act', '=', 'tf.reshape(tf.multinomial(logits,', '1),', '[-1])', 'elif', 'self.env_spec.is_box(act_type):',...
58,906
scikit-learn/scikit-learn
test_polynomial.py
test_polynomial_features_two_features
test_polynomial_features_two_features
Test PolynomialFeatures on 2 features up to degree 3.
[ "Test", "PolynomialFeatures", "on", "2", "features", "up", "to", "degree", "3." ]
def test_polynomial_features_two_features(two_features_degree3, degree, include_bias, interaction_only, indices, X_container): (X, P) = two_features_degree3 if X_container is not None: X = X_container(X) tf = PolynomialFeatures(degree=degree, include_bias=include_bias, interaction_only=interaction_o...
['def', 'test_polynomial_features_two_features(two_features_degree3,', 'degree,', 'include_bias,', 'interaction_only,', 'indices,', 'X_container):', '(X,', 'P)', '=', 'two_features_degree3', 'if', 'X_container', 'is', 'not', 'None:', 'X', '=', 'X_container(X)', 'tf', '=', 'PolynomialFeatures(degree=degree,', 'include_b...
854,068
enuguru/artificial_intelligence_and_machine_learning
html_parse.py
findLinksRel
findLinksRel
Filter the list of link attributes on whether it has target_rel as a relationship.
[ "Filter", "the", "list", "of", "link", "attributes", "on", "whether", "it", "has", "target_rel", "as", "a", "relationship." ]
def findLinksRel(link_attrs_list, target_rel): matchesTarget = lambda attrs: linkHasRel(attrs, target_rel) return list(filter(matchesTarget, link_attrs_list))
['def', 'findLinksRel(link_attrs_list,', 'target_rel):', 'matchesTarget', '=', 'lambda', 'attrs:', 'linkHasRel(attrs,', 'target_rel)', 'return', 'list(filter(matchesTarget,', 'link_attrs_list))']
130,148
ylsung/Ladder-Side-Tuning
adapter_controller.py
AdapterController.get_adapter
get_adapter
Given a task returns its corresponding adapter layer.
[ "Given", "a", "task", "returns", "its", "corresponding", "adapter", "layer." ]
def get_adapter(self, task): return self.adapters[task]
['def', 'get_adapter(self,', 'task):', 'return', 'self.adapters[task]']
622,948
googleapis/python-aiplatform
dataset.py
_Dataset.export_data
export_data
Exports data to output dir to GCS.
[ "Exports", "data", "to", "output", "dir", "to", "GCS." ]
def export_data(self, output_dir: str) -> Sequence[str]: self.wait() export_data_config = gca_dataset.ExportDataConfig(gcs_destination=gca_io.GcsDestination(output_uri_prefix=output_dir)) _LOGGER.log_action_start_against_resource('Exporting', 'data', self) export_lro = self.api_client.export_data(name=s...
['def', 'export_data(self,', 'output_dir:', 'str)', '->', 'Sequence[str]:', 'self.wait()', 'export_data_config', '=', 'gca_dataset.ExportDataConfig(gcs_destination=gca_io.GcsDestination(output_uri_prefix=output_dir))', "_LOGGER.log_action_start_against_resource('Exporting',", "'data',", 'self)', 'export_lro', '=', 'sel...
809,874
rudranil723/mini-main
autopep8.py
FixPEP8.fix_e125
fix_e125
Fix indentation undistinguish from the next logical line.
[ "Fix", "indentation", "undistinguish", "from", "the", "next", "logical", "line." ]
def fix_e125(self, result): num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) indent = len(_get_indentation(target)) modified_lines = [] while len(_get_indentat...
['def', 'fix_e125(self,', 'result):', 'num_indent_spaces', '=', "int(result['info'].split()[1])", 'line_index', '=', "result['line']", '-', '1', 'target', '=', 'self.source[line_index]', 'spaces_to_add', '=', 'num_indent_spaces', '-', 'len(_get_indentation(target))', 'indent', '=', 'len(_get_indentation(target))', 'mod...
313,904
matsu0228/nlp-jp
test_dtype.py
TestBuiltin.test_run
test_run
Only test hash runs at all.
[ "Only", "test", "hash", "runs", "at", "all." ]
def test_run(self): for t in [np.int, np.float, np.complex, np.int32, np.str, np.object, np.unicode]: dt = np.dtype(t) hash(dt)
['def', 'test_run(self):', 'for', 't', 'in', '[np.int,', 'np.float,', 'np.complex,', 'np.int32,', 'np.str,', 'np.object,', 'np.unicode]:', 'dt', '=', 'np.dtype(t)', 'hash(dt)']
790,886