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
alibaba-mmai-research/HiCo
config.py
Config.get_args
get_args
Returns the read arguments.
[ "Returns", "the", "read", "arguments." ]
def get_args(self): return self.args
['def', 'get_args(self):', 'return', 'self.args']
206,178
sshleifer/object_detection_kitti
data_utils.py
build_seq_ae_sequence
build_seq_ae_sequence
Builds seq_ae sequence from input sequence.
[ "Builds", "seq_ae", "sequence", "from", "input", "sequence." ]
def build_seq_ae_sequence(seq): seq_ae_seq = SequenceWrapper() for i in range(len(seq) * 2 - 1): ts = seq_ae_seq.add_timestep() if i < len(seq) - 1: ts.set_token(seq[i].token) elif i == len(seq) - 1: ts.set_token(seq[i].token) ts.set_label(seq[0].token...
['def', 'build_seq_ae_sequence(seq):', 'seq_ae_seq', '=', 'SequenceWrapper()', 'for', 'i', 'in', 'range(len(seq)', '*', '2', '-', '1):', 'ts', '=', 'seq_ae_seq.add_timestep()', 'if', 'i', '<', 'len(seq)', '-', '1:', 'ts.set_token(seq[i].token)', 'elif', 'i', '==', 'len(seq)', '-', '1:', 'ts.set_token(seq[i].token)', 't...
794,537
sarnsdev/social-alignment-data-mining
pyparsing.py
line
line
Returns the line of text containing loc within a string, counting newlines as line separators.
[ "Returns", "the", "line", "of", "text", "containing", "loc", "within", "a", "string,", "counting", "newlines", "as", "line", "separators." ]
def line(loc, strg): lastCR = strg.rfind('\n', 0, loc) nextCR = strg.find('\n', loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[lastCR + 1:]
['def', 'line(loc,', 'strg):', 'lastCR', '=', "strg.rfind('\\n',", '0,', 'loc)', 'nextCR', '=', "strg.find('\\n',", 'loc)', 'if', 'nextCR', '>=', '0:', 'return', 'strg[lastCR', '+', '1:nextCR]', 'else:', 'return', 'strg[lastCR', '+', '1:]']
390,003
zcablii/LSKNet
odm_refine_head.py
ODMRefineHead.get_anchors
get_anchors
Get anchors according to feature map sizes.
[ "Get", "anchors", "according", "to", "feature", "map", "sizes." ]
def get_anchors(self, featmap_sizes, img_metas, device='cuda'): anchor_list = [[bboxes_img_lvl.clone().detach() for bboxes_img_lvl in bboxes_img] for bboxes_img in self.bboxes_as_anchors] valid_flag_list = [] for (img_id, img_meta) in enumerate(img_metas): multi_level_flags = self.anchor_generator.v...
['def', 'get_anchors(self,', 'featmap_sizes,', 'img_metas,', "device='cuda'):", 'anchor_list', '=', '[[bboxes_img_lvl.clone().detach()', 'for', 'bboxes_img_lvl', 'in', 'bboxes_img]', 'for', 'bboxes_img', 'in', 'self.bboxes_as_anchors]', 'valid_flag_list', '=', '[]', 'for', '(img_id,', 'img_meta)', 'in', 'enumerate(img_...
616,121
matsu0228/nlp-jp
storage_uri.py
BucketStorageUri.is_stream
is_stream
Returns True if this URI represents input/output stream.
[ "Returns", "True", "if", "this", "URI", "represents", "input/output", "stream." ]
def is_stream(self): return False
['def', 'is_stream(self):', 'return', 'False']
783,887
TrellixVulnTeam/Unsupervised_Learning_HFI7
conftest.py
read_ext
read_ext
Valid extensions for reading Excel files.
[ "Valid", "extensions", "for", "reading", "Excel", "files." ]
def read_ext(request): return request.param
['def', 'read_ext(request):', 'return', 'request.param']
453,811
Xianpeng919/MonoCon
test_fusion_coord_trans.py
test_coords_transformation
test_coords_transformation
Test the transformation of 3d coords.
[ "Test", "the", "transformation", "of", "3d", "coords." ]
def test_coords_transformation(): img_meta = {'pcd_scale_factor': 1.2311, 'pcd_rotation': [[0.8660254, 0.5, 0], [-0.5, 0.8660254, 0], [0, 0, 1.0]], 'pcd_trans': [0.01111, -0.00888, 0.0], 'pcd_horizontal_flip': True, 'transformation_3d_flow': ['HF', 'R', 'S', 'T']} pcd = torch.tensor([[-5.2422, -0.29757, 40.021]...
['def', 'test_coords_transformation():', 'img_meta', '=', "{'pcd_scale_factor':", '1.2311,', "'pcd_rotation':", '[[0.8660254,', '0.5,', '0],', '[-0.5,', '0.8660254,', '0],', '[0,', '0,', '1.0]],', "'pcd_trans':", '[0.01111,', '-0.00888,', '0.0],', "'pcd_horizontal_flip':", 'True,', "'transformation_3d_flow':", "['HF',"...
654,685
feidieufo/Carla-Reinforcement-Learning
sensor.py
Image.data
data
Lazy initialization for data property, stores converted data in its default format.
[ "Lazy", "initialization", "for", "data", "property,", "stores", "converted", "data", "in", "its", "default", "format." ]
def data(self): if self._converted_data is None: from . import image_converter if self.type == 'Depth': self._converted_data = image_converter.depth_to_array(self) elif self.type == 'SemanticSegmentation': self._converted_data = image_converter.labels_to_array(self) ...
['def', 'data(self):', 'if', 'self._converted_data', 'is', 'None:', 'from', '.', 'import', 'image_converter', 'if', 'self.type', '==', "'Depth':", 'self._converted_data', '=', 'image_converter.depth_to_array(self)', 'elif', 'self.type', '==', "'SemanticSegmentation':", 'self._converted_data', '=', 'image_converter.labe...
455,858
ashwin-phadke/cvplayground
keypoint_ops.py
scale
scale
Scales keypoint coordinates in x and y dimensions.
[ "Scales", "keypoint", "coordinates", "in", "x", "and", "y", "dimensions." ]
def scale(keypoints, y_scale, x_scale, scope=None): with tf.name_scope(scope, 'Scale'): y_scale = tf.cast(y_scale, tf.float32) x_scale = tf.cast(x_scale, tf.float32) new_keypoints = keypoints * [[[y_scale, x_scale]]] return new_keypoints
['def', 'scale(keypoints,', 'y_scale,', 'x_scale,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'Scale'):", 'y_scale', '=', 'tf.cast(y_scale,', 'tf.float32)', 'x_scale', '=', 'tf.cast(x_scale,', 'tf.float32)', 'new_keypoints', '=', 'keypoints', '*', '[[[y_scale,', 'x_scale]]]', 'return', 'new_keypoints']
509,870
tobegit3hub/deep_image_model
serialize_tensorboard.py
Clean
Clean
Clean a string so it can be used as a filepath.
[ "Clean", "a", "string", "so", "it", "can", "be", "used", "as", "a", "filepath." ]
def Clean(s): for c in BAD_CHARACTERS: s = s.replace(c, '_') return s
['def', 'Clean(s):', 'for', 'c', 'in', 'BAD_CHARACTERS:', 's', '=', 's.replace(c,', "'_')", 'return', 's']
183,497
tobegit3hub/deep_image_model
quantize_graph.py
GraphRewriter.quantize_node
quantize_node
Handles quantizing a single node.
[ "Handles", "quantizing", "a", "single", "node." ]
def quantize_node(self, input_node): input_name = input_node.name if input_name in self.already_quantized: return self.already_quantized[input_name] = True original_input_name = input_name + '_original' reshape_name = input_name + '_reshape' reshape_dims_name = input_name + '_reshape_dim...
['def', 'quantize_node(self,', 'input_node):', 'input_name', '=', 'input_node.name', 'if', 'input_name', 'in', 'self.already_quantized:', 'return', 'self.already_quantized[input_name]', '=', 'True', 'original_input_name', '=', 'input_name', '+', "'_original'", 'reshape_name', '=', 'input_name', '+', "'_reshape'", 'resh...
183,531
weimin17/Object-Detection_HelmetDetection
dsn_eval.py
provide_batch_fn
provide_batch_fn
The provide_batch function to use.
[ "The", "provide_batch", "function", "to", "use." ]
def provide_batch_fn(): return dataset_factory.provide_batch
['def', 'provide_batch_fn():', 'return', 'dataset_factory.provide_batch']
762,648
gencnis/NaturalLanguageProcessing
trigram_model.py
TrigramModel.raw_unigram_probability
raw_unigram_probability
COMPLETE THIS METHOD (PART 3) Returns the raw (unsmoothed) unigram probability.
[ "COMPLETE", "THIS", "METHOD", "(PART", "3)", "Returns", "the", "raw", "(unsmoothed)", "unigram", "probability." ]
def raw_unigram_probability(self, unigram): if unigram not in self.unigramcounts: num = 0 else: num = self.unigramcounts[unigram] denom = self.total_words if denom == 0: return 0 else: return num / denom
['def', 'raw_unigram_probability(self,', 'unigram):', 'if', 'unigram', 'not', 'in', 'self.unigramcounts:', 'num', '=', '0', 'else:', 'num', '=', 'self.unigramcounts[unigram]', 'denom', '=', 'self.total_words', 'if', 'denom', '==', '0:', 'return', '0', 'else:', 'return', 'num', '/', 'denom']
677,249
georgwiese/2048-rl
game.py
Game.available_actions
available_actions
Computes the set of actions that are available.
[ "Computes", "the", "set", "of", "actions", "that", "are", "available." ]
def available_actions(self): return [action for action in range(4) if self.is_action_available(action)]
['def', 'available_actions(self):', 'return', '[action', 'for', 'action', 'in', 'range(4)', 'if', 'self.is_action_available(action)]']
375,585
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
policy.py
Policy.core
core
Core neural network taking in inputs and outputting sampling distribution parameters.
[ "Core", "neural", "network", "taking", "in", "inputs", "and", "outputting", "sampling", "distribution", "parameters." ]
def core(self, obs, prev_internal_state, prev_actions): batch_size = tf.shape(obs[0])[0] if not self.recurrent: prev_internal_state = tf.zeros([batch_size, self.rnn_state_dim]) cell = self.get_cell() b = tf.get_variable('input_bias', [self.cell_input_dim], initializer=self.vector_init) cell_...
['def', 'core(self,', 'obs,', 'prev_internal_state,', 'prev_actions):', 'batch_size', '=', 'tf.shape(obs[0])[0]', 'if', 'not', 'self.recurrent:', 'prev_internal_state', '=', 'tf.zeros([batch_size,', 'self.rnn_state_dim])', 'cell', '=', 'self.get_cell()', 'b', '=', "tf.get_variable('input_bias',", '[self.cell_input_dim]...
26,187
Levantespot/UDA_for_RS
shape_convert.py
nchw_to_nlc
nchw_to_nlc
Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor.
[ "Flatten", "[N,", "C,", "H,", "W]", "shape", "tensor", "to", "[N,", "L,", "C]", "shape", "tensor." ]
def nchw_to_nlc(x): assert len(x.shape) == 4 return x.flatten(2).transpose(1, 2).contiguous()
['def', 'nchw_to_nlc(x):', 'assert', 'len(x.shape)', '==', '4', 'return', 'x.flatten(2).transpose(1,', '2).contiguous()']
947,420
ryu-ed/SpaceInvaders_Ros
classes.py
ClassChecker.leave_functiondef
leave_functiondef
on method node, check if this method couldn't be a function ignore class, static and abstract methods, initializer, methods overridden from a parent class.
[ "on", "method", "node,", "check", "if", "this", "method", "couldn't", "be", "a", "function", "ignore", "class,", "static", "and", "abstract", "methods,", "initializer,", "methods", "overridden", "from", "a", "parent", "class." ]
def leave_functiondef(self, node): if node.is_method(): if node.args.args is not None: self._first_attrs.pop() if not self.linter.is_message_enabled('no-self-use'): return class_node = node.parent.frame() if self._meth_could_be_func and node.type == 'method' a...
['def', 'leave_functiondef(self,', 'node):', 'if', 'node.is_method():', 'if', 'node.args.args', 'is', 'not', 'None:', 'self._first_attrs.pop()', 'if', 'not', "self.linter.is_message_enabled('no-self-use'):", 'return', 'class_node', '=', 'node.parent.frame()', 'if', 'self._meth_could_be_func', 'and', 'node.type', '==', ...
369,899
Eric3911/OpenAGI
numba_utils.py
skip_numba_cuda_test_if_unsupported
skip_numba_cuda_test_if_unsupported
Helper method to skip pytest test case if numba cuda is not supported.
[ "Helper", "method", "to", "skip", "pytest", "test", "case", "if", "numba", "cuda", "is", "not", "supported." ]
def skip_numba_cuda_test_if_unsupported(min_version: str): numba_cuda_support = numba_cuda_is_supported(min_version) if not numba_cuda_support: import pytest pytest.skip(f'Numba cuda test is being skipped. Minimum version required : {min_version}')
['def', 'skip_numba_cuda_test_if_unsupported(min_version:', 'str):', 'numba_cuda_support', '=', 'numba_cuda_is_supported(min_version)', 'if', 'not', 'numba_cuda_support:', 'import', 'pytest', "pytest.skip(f'Numba", 'cuda', 'test', 'is', 'being', 'skipped.', 'Minimum', 'version', 'required', ':', "{min_version}')"]
274,099
aws/sagemaker-python-sdk
lambda_step.py
LambdaStep.arguments
arguments
The arguments dict that is used to define the lambda step.
[ "The", "arguments", "dict", "that", "is", "used", "to", "define", "the", "lambda", "step." ]
def arguments(self) -> RequestType: return self.inputs
['def', 'arguments(self)', '->', 'RequestType:', 'return', 'self.inputs']
830,619
AgnostiqHQ/covalent
data_manager_test.py
get_mock_result
get_mock_result
Construct a mock result object corresponding to a lattice.
[ "Construct", "a", "mock", "result", "object", "corresponding", "to", "a", "lattice." ]
def get_mock_result() -> Result: import sys @ct.electron(executor='local') def task(x): print(f'stdout: {x}') print('Error!', file=sys.stderr) return x @ct.lattice def pipeline(x): res1 = task(x) res2 = task(res1) return res2 pipeline.build_graph...
['def', 'get_mock_result()', '->', 'Result:', 'import', 'sys', "@ct.electron(executor='local')", 'def', 'task(x):', "print(f'stdout:", "{x}')", "print('Error!',", 'file=sys.stderr)', 'return', 'x', '@ct.lattice', 'def', 'pipeline(x):', 'res1', '=', 'task(x)', 'res2', '=', 'task(res1)', 'return', 'res2', "pipeline.build...
489,693
openai/gym
test_env_checker.py
test_check_reset_options
test_check_reset_options
Tests the check_reset_options function.
[ "Tests", "the", "check_reset_options", "function." ]
def test_check_reset_options(): with pytest.raises(gym.error.Error, match=re.escape('The `reset` method does not provide an `options` or `**kwargs` keyword argument')): check_reset_options(GenericTestEnv(reset_fn=lambda self: (0, {})))
['def', 'test_check_reset_options():', 'with', 'pytest.raises(gym.error.Error,', "match=re.escape('The", '`reset`', 'method', 'does', 'not', 'provide', 'an', '`options`', 'or', '`**kwargs`', 'keyword', "argument')):", 'check_reset_options(GenericTestEnv(reset_fn=lambda', 'self:', '(0,', '{})))']
234,398
myothida/Supervised-Machine-Learning
test_mstats_basic.py
TestCompareWithStats.get_n
get_n
Returns list of sample sizes to be used for comparison.
[ "Returns", "list", "of", "sample", "sizes", "to", "be", "used", "for", "comparison." ]
def get_n(self): return [1000, 100, 10, 5]
['def', 'get_n(self):', 'return', '[1000,', '100,', '10,', '5]']
446,593
matsu0228/nlp-jp
alias.py
AliasManager.retrieve_alias
retrieve_alias
Retrieve the command to which an alias expands.
[ "Retrieve", "the", "command", "to", "which", "an", "alias", "expands." ]
def retrieve_alias(self, name): caller = self.get_alias(name) if caller: return caller.cmd else: raise ValueError('%s is not an alias' % name)
['def', 'retrieve_alias(self,', 'name):', 'caller', '=', 'self.get_alias(name)', 'if', 'caller:', 'return', 'caller.cmd', 'else:', 'raise', "ValueError('%s", 'is', 'not', 'an', "alias'", '%', 'name)']
786,499
chribsen/simple-machine-learning-examples
retry.py
Retry.from_int
from_int
Backwards-compatibility for the old retries format.
[ "Backwards-compatibility", "for", "the", "old", "retries", "format." ]
def from_int(cls, retries, redirect=True, default=None): if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug('Converted r...
['def', 'from_int(cls,', 'retries,', 'redirect=True,', 'default=None):', 'if', 'retries', 'is', 'None:', 'retries', '=', 'default', 'if', 'default', 'is', 'not', 'None', 'else', 'cls.DEFAULT', 'if', 'isinstance(retries,', 'Retry):', 'return', 'retries', 'redirect', '=', 'bool(redirect)', 'and', 'None', 'new_retries', '...
937,578
google-research/scenic
detr_base_model.py
BaseModelWithMatching.compute_cost_matrix
compute_cost_matrix
Implements the matching cost matrix computations.
[ "Implements", "the", "matching", "cost", "matrix", "computations." ]
def compute_cost_matrix(self, predictions: ArrayDict, targets: ArrayDict) -> jnp.ndarray: raise NotImplementedError('Subclasses must implement compute_cost_matrix.')
['def', 'compute_cost_matrix(self,', 'predictions:', 'ArrayDict,', 'targets:', 'ArrayDict)', '->', 'jnp.ndarray:', 'raise', "NotImplementedError('Subclasses", 'must', 'implement', "compute_cost_matrix.')"]
846,631
jason718/game-feature-learning
draw.py
get_edge_label
get_edge_label
Define edge label based on layer type.
[ "Define", "edge", "label", "based", "on", "layer", "type." ]
def get_edge_label(layer): if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif layer.type == 'InnerProduct': edge_label = str(lay...
['def', 'get_edge_label(layer):', 'if', 'layer.type', '==', "'Data':", 'edge_label', '=', "'Batch", "'", '+', 'str(layer.data_param.batch_size)', 'elif', 'layer.type', '==', "'Convolution'", 'or', 'layer.type', '==', "'Deconvolution':", 'edge_label', '=', 'str(layer.convolution_param.num_output)', 'elif', 'layer.type',...
199,460
clips/pattern
__init__.py
keywords
keywords
Returns a sorted list of keywords in the given string.
[ "Returns", "a", "sorted", "list", "of", "keywords", "in", "the", "given", "string." ]
def keywords(s, top=10, **kwargs): return parser.find_keywords(s, **dict({'frequency': parser.frequency, 'top': top, 'pos': ('NN',), 'ignore': ('rt',)}, **kwargs))
['def', 'keywords(s,', 'top=10,', '**kwargs):', 'return', 'parser.find_keywords(s,', "**dict({'frequency':", 'parser.frequency,', "'top':", 'top,', "'pos':", "('NN',),", "'ignore':", "('rt',)},", '**kwargs))']
764,868
apeterswu/fairseq_mix
trainer.py
Trainer.dummy_train_step
dummy_train_step
Dummy training step for warming caching allocator.
[ "Dummy", "training", "step", "for", "warming", "caching", "allocator." ]
def dummy_train_step(self, dummy_batch): self.train_step(dummy_batch, dummy_batch=True) self.zero_grad()
['def', 'dummy_train_step(self,', 'dummy_batch):', 'self.train_step(dummy_batch,', 'dummy_batch=True)', 'self.zero_grad()']
559,062
pantelis/artificial-intelligence
__init__.py
FCompiler.get_library_dirs
get_library_dirs
List of compiler library directories.
[ "List", "of", "compiler", "library", "directories." ]
def get_library_dirs(self): return self.library_dirs[:]
['def', 'get_library_dirs(self):', 'return', 'self.library_dirs[:]']
168,629
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
np_box_list.py
BoxList.get_extra_fields
get_extra_fields
Return all non-box fields.
[ "Return", "all", "non-box", "fields." ]
def get_extra_fields(self): return [k for k in self.data.keys() if k != 'boxes']
['def', 'get_extra_fields(self):', 'return', '[k', 'for', 'k', 'in', 'self.data.keys()', 'if', 'k', '!=', "'boxes']"]
58,224
arshpreetsingh/quantopian-machinelearning
conftest.py
wide_multi_index
wide_multi_index
Return a MultiIndex that is wider than the display (>80 characters).
[ "Return", "a", "MultiIndex", "that", "is", "wider", "than", "the", "display", "(>80", "characters)." ]
def wide_multi_index(): n = 1000 ci = pd.CategoricalIndex(list('a' * n) + ['abc'] * n) dti = pd.date_range('2000-01-01', freq='s', periods=n * 2) levels = [ci, ci.codes + 9, dti, dti, dti] names = ['a', 'b', 'dti_1', 'dti_2', 'dti_3'] return pd.MultiIndex.from_arrays(levels, names=names)
['def', 'wide_multi_index():', 'n', '=', '1000', 'ci', '=', "pd.CategoricalIndex(list('a'", '*', 'n)', '+', "['abc']", '*', 'n)', 'dti', '=', "pd.date_range('2000-01-01',", "freq='s',", 'periods=n', '*', '2)', 'levels', '=', '[ci,', 'ci.codes', '+', '9,', 'dti,', 'dti,', 'dti]', 'names', '=', "['a',", "'b',", "'dti_1',...
890,655
zhpmatrix/VisDrone2018
logger.py
Logger.histo_summary
histo_summary
Log a histogram of the tensor of values.
[ "Log", "a", "histogram", "of", "the", "tensor", "of", "values." ]
def histo_summary(self, tag, values, step, bins=1000): (counts, bin_edges) = np.histogram(values, bins=bins) hist = tf.HistogramProto() hist.min = float(np.min(values)) hist.max = float(np.max(values)) hist.num = int(np.prod(values.shape)) hist.sum = float(np.sum(values)) hist.sum_squares = ...
['def', 'histo_summary(self,', 'tag,', 'values,', 'step,', 'bins=1000):', '(counts,', 'bin_edges)', '=', 'np.histogram(values,', 'bins=bins)', 'hist', '=', 'tf.HistogramProto()', 'hist.min', '=', 'float(np.min(values))', 'hist.max', '=', 'float(np.max(values))', 'hist.num', '=', 'int(np.prod(values.shape))', 'hist.sum'...
955,687
apeterswu/RL4NMT
slicenet.py
similarity_cost
similarity_cost
Loss telling to be more similar to your own targets than to others.
[ "Loss", "telling", "to", "be", "more", "similar", "to", "your", "own", "targets", "than", "to", "others." ]
def similarity_cost(inputs_encoded, targets_encoded): (x, y) = common_layers.pad_to_same_length(inputs_encoded, targets_encoded) depth = tf.shape(inputs_encoded)[3] (x, y) = (tf.reshape(x, [-1, depth]), tf.reshape(y, [-1, depth])) return rank_loss(x, y)
['def', 'similarity_cost(inputs_encoded,', 'targets_encoded):', '(x,', 'y)', '=', 'common_layers.pad_to_same_length(inputs_encoded,', 'targets_encoded)', 'depth', '=', 'tf.shape(inputs_encoded)[3]', '(x,', 'y)', '=', '(tf.reshape(x,', '[-1,', 'depth]),', 'tf.reshape(y,', '[-1,', 'depth]))', 'return', 'rank_loss(x,', 'y...
331,165
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
tix.py
TixWidget.config_all
config_all
Set configuration options for all subwidgets (and self).
[ "Set", "configuration", "options", "for", "all", "subwidgets", "(and", "self)." ]
def config_all(self, option, value): if option == '': return elif not isinstance(option, str): option = repr(option) if not isinstance(value, str): value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, val...
['def', 'config_all(self,', 'option,', 'value):', 'if', 'option', '==', "'':", 'return', 'elif', 'not', 'isinstance(option,', 'str):', 'option', '=', 'repr(option)', 'if', 'not', 'isinstance(value,', 'str):', 'value', '=', 'repr(value)', 'names', '=', 'self._subwidget_names()', 'for', 'name', 'in', 'names:', 'self.tk.c...
376,637
minghangz/cpl
triangular_lr_scheduler.py
TriangularSchedule.add_args
add_args
Add arguments to the parser for this LR scheduler.
[ "Add", "arguments", "to", "the", "parser", "for", "this", "LR", "scheduler." ]
def add_args(parser): parser.add_argument('--max-lr', required=True, type=float, metavar='LR', help='max learning rate, must be more than args.lr') parser.add_argument('--lr-period-updates', default=5000, type=float, metavar='LR', help='initial number of updates per period (cycle length)') parser.add_argume...
['def', 'add_args(parser):', "parser.add_argument('--max-lr',", 'required=True,', 'type=float,', "metavar='LR',", "help='max", 'learning', 'rate,', 'must', 'be', 'more', 'than', "args.lr')", "parser.add_argument('--lr-period-updates',", 'default=5000,', 'type=float,', "metavar='LR',", "help='initial", 'number', 'of', '...
137,832
accel-brain/accel-brain-code
re_seq_2_seq.py
ReSeq2Seq.forward_propagation
forward_propagation
Hybrid forward with Gluon API.
[ "Hybrid", "forward", "with", "Gluon", "API." ]
def forward_propagation(self, F, x): observed_arr = x decoded_arr = self.__encoder_decoder_controller.forward_propagation(F, observed_arr) encoded_arr = self.__encoder_decoder_controller.feature_points_arr re_encoded_arr = self.__retrospective_encoder.forward_propagation(F, decoded_arr) return (obse...
['def', 'forward_propagation(self,', 'F,', 'x):', 'observed_arr', '=', 'x', 'decoded_arr', '=', 'self.__encoder_decoder_controller.forward_propagation(F,', 'observed_arr)', 'encoded_arr', '=', 'self.__encoder_decoder_controller.feature_points_arr', 're_encoded_arr', '=', 'self.__retrospective_encoder.forward_propagatio...
7,151
googleapis/python-aiplatform
client.py
FeaturestoreServiceClient.common_project_path
common_project_path
Returns a fully-qualified project string.
[ "Returns", "a", "fully-qualified", "project", "string." ]
def common_project_path(project: str) -> str: return 'projects/{project}'.format(project=project)
['def', 'common_project_path(project:', 'str)', '->', 'str:', 'return', "'projects/{project}'.format(project=project)"]
810,610
kornia/kornia
test_conversions.py
atol
atol
Lower tolerance for cuda-float16 only.
[ "Lower", "tolerance", "for", "cuda-float16", "only." ]
def atol(device, dtype): if 'cuda' in device.type and dtype == torch.float16: return 0.001 return 0.0001
['def', 'atol(device,', 'dtype):', 'if', "'cuda'", 'in', 'device.type', 'and', 'dtype', '==', 'torch.float16:', 'return', '0.001', 'return', '0.0001']
622,340
enuguru/artificial_intelligence_and_machine_
__init__.py
SQLAlchemy.make_connector
make_connector
Creates the connector for a given state and bind.
[ "Creates", "the", "connector", "for", "a", "given", "state", "and", "bind." ]
def make_connector(self, app, bind=None): return _EngineConnector(self, app, bind)
['def', 'make_connector(self,', 'app,', 'bind=None):', 'return', '_EngineConnector(self,', 'app,', 'bind)']
128,830
facebookresearch/CompilerGym
env_without_bazel_test.py
test_invalid_arguments
test_invalid_arguments
Test that running the binary with unrecognized arguments is an error.
[ "Test", "that", "running", "the", "binary", "with", "unrecognized", "arguments", "is", "an", "error." ]
def test_invalid_arguments(bin: Path): def run(cmd): with Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) as p: (stdout, stderr) = p.communicate(timeout=60) return (p.returncode, stdout, stderr) (returncode, _, stderr) = run([str(bin), 'foobar...
['def', 'test_invalid_arguments(bin:', 'Path):', 'def', 'run(cmd):', 'with', 'Popen(cmd,', 'stdout=subprocess.PIPE,', 'stderr=subprocess.PIPE,', 'universal_newlines=True)', 'as', 'p:', '(stdout,', 'stderr)', '=', 'p.communicate(timeout=60)', 'return', '(p.returncode,', 'stdout,', 'stderr)', '(returncode,', '_,', 'stder...
135,587
skylook/neural-networks-and-deep-learning
mnist.py
plot_top_left
plot_top_left
Plot the top left of ``image``.
[ "Plot", "the", "top", "left", "of", "``image``." ]
def plot_top_left(image): image[14:, :] = np.zeros((14, 28)) image[:, 14:] = np.zeros((28, 14)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.matshow(image, cmap=matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show()
['def', 'plot_top_left(image):', 'image[14:,', ':]', '=', 'np.zeros((14,', '28))', 'image[:,', '14:]', '=', 'np.zeros((28,', '14))', 'fig', '=', 'plt.figure()', 'ax', '=', 'fig.add_subplot(1,', '1,', '1)', 'ax.matshow(image,', 'cmap=matplotlib.cm.binary)', 'plt.xticks(np.array([]))', 'plt.yticks(np.array([]))', 'plt.sh...
722,071
gunthercox/ChatterBot
log.py
Log.good
good
If we log WARN messages, log this message as a 'nice' anti-warn message.
[ "If", "we", "log", "WARN", "messages,", "log", "this", "message", "as", "a", "'nice'", "anti-warn", "message." ]
def good(self, msg, *args): if WARN >= self.threshold: if args: print(green_text(msg % _fix_args(args))) else: print(green_text(msg)) sys.stdout.flush()
['def', 'good(self,', 'msg,', '*args):', 'if', 'WARN', '>=', 'self.threshold:', 'if', 'args:', 'print(green_text(msg', '%', '_fix_args(args)))', 'else:', 'print(green_text(msg))', 'sys.stdout.flush()']
531,036
coder-mano/Shi-Tomasi-Corner-Detector
__init__.py
VendorImporter.search_path
search_path
Search first the vendor package then as a natural package.
[ "Search", "first", "the", "vendor", "package", "then", "as", "a", "natural", "package." ]
def search_path(self): yield (self.vendor_pkg + '.') yield ''
['def', 'search_path(self):', 'yield', '(self.vendor_pkg', '+', "'.')", 'yield', "''"]
900,578
deepmind/acme
bc_utils.py
make_network
make_network
Creates networks used by the agent.
[ "Creates", "networks", "used", "by", "the", "agent." ]
def make_network(spec: specs.EnvironmentSpec) -> bc.BCNetworks: num_actions = spec.actions.num_values def actor_fn(obs, is_training=True, key=None): del is_training del key mlp = hk.Sequential([hk.Flatten(), hk.nets.MLP([64, 64, num_actions])]) return mlp(obs) policy = hk.wi...
['def', 'make_network(spec:', 'specs.EnvironmentSpec)', '->', 'bc.BCNetworks:', 'num_actions', '=', 'spec.actions.num_values', 'def', 'actor_fn(obs,', 'is_training=True,', 'key=None):', 'del', 'is_training', 'del', 'key', 'mlp', '=', 'hk.Sequential([hk.Flatten(),', 'hk.nets.MLP([64,', '64,', 'num_actions])])', 'return'...
7,991
dwf/convolupy
layers.py
MultiConvolutionalFeatureMapLayer.fprop
fprop
Forward propagate input through this module.
[ "Forward", "propagate", "input", "through", "this", "module." ]
def fprop(self, inputs): out = [] for (index, fmap) in enumerate(self.maps): theseinputs = [inputs[number] for number in self.connections[index]] out.append(fmap.fprop(theseinputs)) return out
['def', 'fprop(self,', 'inputs):', 'out', '=', '[]', 'for', '(index,', 'fmap)', 'in', 'enumerate(self.maps):', 'theseinputs', '=', '[inputs[number]', 'for', 'number', 'in', 'self.connections[index]]', 'out.append(fmap.fprop(theseinputs))', 'return', 'out']
137,004
open-mmlab/mmtracking
coco_video_parser.py
CocoVID.convert_img_to_vid
convert_img_to_vid
Convert image data to video data.
[ "Convert", "image", "data", "to", "video", "data." ]
def convert_img_to_vid(self, dataset): if 'images' in self.dataset: videos = [] for (i, img) in enumerate(self.dataset['images']): videos.append(dict(id=img['id'], name=img['file_name'])) img['video_id'] = img['id'] img['frame_id'] = 0 dataset['videos'] = ...
['def', 'convert_img_to_vid(self,', 'dataset):', 'if', "'images'", 'in', 'self.dataset:', 'videos', '=', '[]', 'for', '(i,', 'img)', 'in', "enumerate(self.dataset['images']):", "videos.append(dict(id=img['id'],", "name=img['file_name']))", "img['video_id']", '=', "img['id']", "img['frame_id']", '=', '0', "dataset['vide...
625,773
SamuelYute2/COM422-Assignment-1
pacman.py
GameState.generateSuccessor
generateSuccessor
Returns the successor state after the specified agent takes the action.
[ "Returns", "the", "successor", "state", "after", "the", "specified", "agent", "takes", "the", "action." ]
def generateSuccessor(self, agentIndex, action): if self.isWin() or self.isLose(): raise Exception("Can't generate a successor of a terminal state.") state = GameState(self) if agentIndex == 0: state.data._eaten = [False for i in range(state.getNumAgents())] PacmanRules.applyAction(s...
['def', 'generateSuccessor(self,', 'agentIndex,', 'action):', 'if', 'self.isWin()', 'or', 'self.isLose():', 'raise', 'Exception("Can\'t', 'generate', 'a', 'successor', 'of', 'a', 'terminal', 'state.")', 'state', '=', 'GameState(self)', 'if', 'agentIndex', '==', '0:', 'state.data._eaten', '=', '[False', 'for', 'i', 'in'...
125,119
Eric3911/OpenAGI
sgd_metrics.py
get_average_and_joint_goal_accuracy
get_average_and_joint_goal_accuracy
Get average and joint goal accuracies of a frame.
[ "Get", "average", "and", "joint", "goal", "accuracies", "of", "a", "frame." ]
def get_average_and_joint_goal_accuracy(frame_ref, frame_hyp, service, use_fuzzy_match): goal_acc = {} (list_acc, slot_active, slot_cat, list_status_acc, list_value_acc) = compare_slot_values(frame_ref['state']['slot_values'], frame_hyp['state']['slot_values'], service, use_fuzzy_match) active_acc = [acc fo...
['def', 'get_average_and_joint_goal_accuracy(frame_ref,', 'frame_hyp,', 'service,', 'use_fuzzy_match):', 'goal_acc', '=', '{}', '(list_acc,', 'slot_active,', 'slot_cat,', 'list_status_acc,', 'list_value_acc)', '=', "compare_slot_values(frame_ref['state']['slot_values'],", "frame_hyp['state']['slot_values'],", 'service,...
273,449
Trusted-AI/AIF360
adversarial_debiasing.py
AdversarialDebiasing.fit
fit
Train the classifier and adversary (if ``debias == True``) with the given training data.
[ "Train", "the", "classifier", "and", "adversary", "(if", "``debias", "==", "True``)", "with", "the", "given", "training", "data." ]
def fit(self, X, y): if tf.executing_eagerly(): raise RuntimeError('AdversarialDebiasing does not work in eager execution mode. To fix, add `tf.disable_eager_execution()` to the top of the calling script.') (X, y, _) = check_inputs(X, y) rng = check_random_state(self.random_state) ii32 = np.iinf...
['def', 'fit(self,', 'X,', 'y):', 'if', 'tf.executing_eagerly():', 'raise', "RuntimeError('AdversarialDebiasing", 'does', 'not', 'work', 'in', 'eager', 'execution', 'mode.', 'To', 'fix,', 'add', '`tf.disable_eager_execution()`', 'to', 'the', 'top', 'of', 'the', 'calling', "script.')", '(X,', 'y,', '_)', '=', 'check_inp...
412,393
aisingapore/PeekingDuck
model.py
YOLOXHead.forward
forward
Defines the computation performed at every call.
[ "Defines", "the", "computation", "performed", "at", "every", "call." ]
def forward(self, xin: Tuple[torch.Tensor, torch.Tensor, torch.Tensor]) -> torch.Tensor: outputs = [] for (k, (cls_conv, reg_conv, x)) in enumerate(zip(self.cls_convs, self.reg_convs, xin)): x = self.stems[k](x) cls_feat = cls_conv(x) cls_output = self.cls_preds[k](cls_feat) reg_...
['def', 'forward(self,', 'xin:', 'Tuple[torch.Tensor,', 'torch.Tensor,', 'torch.Tensor])', '->', 'torch.Tensor:', 'outputs', '=', '[]', 'for', '(k,', '(cls_conv,', 'reg_conv,', 'x))', 'in', 'enumerate(zip(self.cls_convs,', 'self.reg_convs,', 'xin)):', 'x', '=', 'self.stems[k](x)', 'cls_feat', '=', 'cls_conv(x)', 'cls_o...
767,096
openkinome/kinoml
test_proteins.py
test_protein_from_pdb
test_protein_from_pdb
Check instantation from PDB ID.
[ "Check", "instantation", "from", "PDB", "ID." ]
def test_protein_from_pdb(): from kinoml.core.proteins import Protein protein = Protein.from_pdb('4yne') assert isinstance(protein.molecule, oechem.OEGraphMol) protein = Protein.from_pdb('4yne', toolkit='MDAnalysis') assert isinstance(protein.molecule, Universe)
['def', 'test_protein_from_pdb():', 'from', 'kinoml.core.proteins', 'import', 'Protein', 'protein', '=', "Protein.from_pdb('4yne')", 'assert', 'isinstance(protein.molecule,', 'oechem.OEGraphMol)', 'protein', '=', "Protein.from_pdb('4yne',", "toolkit='MDAnalysis')", 'assert', 'isinstance(protein.molecule,', 'Universe)']
596,238
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
metrics.py
add_mask_pred_metrics
add_mask_pred_metrics
Computes the mask prediction metrics.
[ "Computes", "the", "mask", "prediction", "metrics." ]
def add_mask_pred_metrics(inputs, outputs, num_views, upscale_factor): names_to_values = dict() names_to_updates = dict() for k in xrange(num_views): (tmp_value, tmp_update) = tf.contrib.metrics.streaming_mean_squared_error(outputs['masks_%d' % (k + 1)], inputs['masks_%d' % (k + 1)]) name = ...
['def', 'add_mask_pred_metrics(inputs,', 'outputs,', 'num_views,', 'upscale_factor):', 'names_to_values', '=', 'dict()', 'names_to_updates', '=', 'dict()', 'for', 'k', 'in', 'xrange(num_views):', '(tmp_value,', 'tmp_update)', '=', "tf.contrib.metrics.streaming_mean_squared_error(outputs['masks_%d'", '%', '(k', '+', '1)...
109,153
LetheSec/PLG-MI-Attack
train_cgan.py
prepare_results_dir
prepare_results_dir
Makedir, init tensorboard if required, save args.
[ "Makedir,", "init", "tensorboard", "if", "required,", "save", "args." ]
def prepare_results_dir(args): root = os.path.join(args.results_root, args.data_name, args.target_model) os.makedirs(root, exist_ok=True) if not args.no_tensorboard: from tensorboardX import SummaryWriter writer = SummaryWriter(root) else: writer = None train_image_root = os....
['def', 'prepare_results_dir(args):', 'root', '=', 'os.path.join(args.results_root,', 'args.data_name,', 'args.target_model)', 'os.makedirs(root,', 'exist_ok=True)', 'if', 'not', 'args.no_tensorboard:', 'from', 'tensorboardX', 'import', 'SummaryWriter', 'writer', '=', 'SummaryWriter(root)', 'else:', 'writer', '=', 'Non...
780,523
pyRiemann/pyRiemann
test_simulated.py
test_make_masks
test_make_masks
Test function for make masks.
[ "Test", "function", "for", "make", "masks." ]
def test_make_masks(rndstate): (n_masks, n_dim0, n_dim1_min) = (5, 10, 3) M = make_masks(n_masks, n_dim0, n_dim1_min, rndstate) for m in M: (dim0, dim1) = m.shape assert dim0 == n_dim0 assert n_dim1_min <= dim1 <= n_dim0
['def', 'test_make_masks(rndstate):', '(n_masks,', 'n_dim0,', 'n_dim1_min)', '=', '(5,', '10,', '3)', 'M', '=', 'make_masks(n_masks,', 'n_dim0,', 'n_dim1_min,', 'rndstate)', 'for', 'm', 'in', 'M:', '(dim0,', 'dim1)', '=', 'm.shape', 'assert', 'dim0', '==', 'n_dim0', 'assert', 'n_dim1_min', '<=', 'dim1', '<=', 'n_dim0']
809,337
weimin17/Object-Detection_HelmetDetection
decoder_test.py
DecoderTest.testCodesFromCTC
testCodesFromCTC
Tests that the simple CTC decoder drops nulls and duplicates.
[ "Tests", "that", "the", "simple", "CTC", "decoder", "drops", "nulls", "and", "duplicates." ]
def testCodesFromCTC(self): ctc_labels = [9, 9, 9, 1, 9, 2, 2, 3, 9, 9, 0, 0, 1, 9, 1, 9, 9, 9] decode = decoder.Decoder(filename=None) non_null_labels = decode._CodesFromCTC(ctc_labels, merge_dups=False, null_label=9) self.assertEqual(non_null_labels, [1, 2, 2, 3, 0, 0, 1, 1]) idempotent_labels = d...
['def', 'testCodesFromCTC(self):', 'ctc_labels', '=', '[9,', '9,', '9,', '1,', '9,', '2,', '2,', '3,', '9,', '9,', '0,', '0,', '1,', '9,', '1,', '9,', '9,', '9]', 'decode', '=', 'decoder.Decoder(filename=None)', 'non_null_labels', '=', 'decode._CodesFromCTC(ctc_labels,', 'merge_dups=False,', 'null_label=9)', 'self.asse...
759,907
whatdhack/computer_vision
np_box_list.py
BoxList.get_field
get_field
Accesses data associated with the specified field in the box collection.
[ "Accesses", "data", "associated", "with", "the", "specified", "field", "in", "the", "box", "collection." ]
def get_field(self, field): if not self.has_field(field): raise ValueError('field {} does not exist'.format(field)) return self.data[field]
['def', 'get_field(self,', 'field):', 'if', 'not', 'self.has_field(field):', 'raise', "ValueError('field", '{}', 'does', 'not', "exist'.format(field))", 'return', 'self.data[field]']
512,769
melonwan/denseReg
losses.py
l1_l2_regularizer
l1_l2_regularizer
Define a L1L2 regularizer.
[ "Define", "a", "L1L2", "regularizer." ]
def l1_l2_regularizer(weight_l1=1.0, weight_l2=1.0, scope=None): def regularizer(tensor): with tf.name_scope(scope, 'L1L2Regularizer', [tensor]): weight_l1_t = tf.convert_to_tensor(weight_l1, dtype=tensor.dtype.base_dtype, name='weight_l1') weight_l2_t = tf.convert_to_tensor(weight_...
['def', 'l1_l2_regularizer(weight_l1=1.0,', 'weight_l2=1.0,', 'scope=None):', 'def', 'regularizer(tensor):', 'with', 'tf.name_scope(scope,', "'L1L2Regularizer',", '[tensor]):', 'weight_l1_t', '=', 'tf.convert_to_tensor(weight_l1,', 'dtype=tensor.dtype.base_dtype,', "name='weight_l1')", 'weight_l2_t', '=', 'tf.convert_t...
183,873
camilolaiton/Artificial_Intelligence
ghostAgents.py
GhostAgent.getDistribution
getDistribution
Returns a Counter encoding a distribution over actions from the provided state.
[ "Returns", "a", "Counter", "encoding", "a", "distribution", "over", "actions", "from", "the", "provided", "state." ]
def getDistribution(self, state): util.raiseNotDefined()
['def', 'getDistribution(self,', 'state):', 'util.raiseNotDefined()']
70,591
danamyu/hedgehog_detector
imagenet_test.py
BaseTest.resnet_model_fn_helper
resnet_model_fn_helper
Tests that the EstimatorSpec is given the appropriate arguments.
[ "Tests", "that", "the", "EstimatorSpec", "is", "given", "the", "appropriate", "arguments." ]
def resnet_model_fn_helper(self, mode): tf.train.create_global_step() (features, labels) = self.input_fn() spec = imagenet_main.resnet_model_fn(features, labels, mode, {'resnet_size': 50, 'data_format': 'channels_last', 'batch_size': _BATCH_SIZE}) predictions = spec.predictions self.assertAllEqual(p...
['def', 'resnet_model_fn_helper(self,', 'mode):', 'tf.train.create_global_step()', '(features,', 'labels)', '=', 'self.input_fn()', 'spec', '=', 'imagenet_main.resnet_model_fn(features,', 'labels,', 'mode,', "{'resnet_size':", '50,', "'data_format':", "'channels_last',", "'batch_size':", '_BATCH_SIZE})', 'predictions',...
589,157
yzy1996/Artificial-Intelligence
utils.py
weighted_sample_with_replacement
weighted_sample_with_replacement
Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.
[ "Pick", "n", "samples", "from", "seq", "at", "random,", "with", "replacement,", "with", "the", "probability", "of", "each", "element", "in", "proportion", "to", "its", "corresponding", "weight." ]
def weighted_sample_with_replacement(n, seq, weights): sample = weighted_sampler(seq, weights) return [sample() for _ in range(n)]
['def', 'weighted_sample_with_replacement(n,', 'seq,', 'weights):', 'sample', '=', 'weighted_sampler(seq,', 'weights)', 'return', '[sample()', 'for', '_', 'in', 'range(n)]']
119,608
raminmohammadi/Artificial-Intelligence
csp.py
first_unassigned_variable
first_unassigned_variable
The default variable order.
[ "The", "default", "variable", "order." ]
def first_unassigned_variable(assignment, csp): return first([var for var in csp.variables if var not in assignment])
['def', 'first_unassigned_variable(assignment,', 'csp):', 'return', 'first([var', 'for', 'var', 'in', 'csp.variables', 'if', 'var', 'not', 'in', 'assignment])']
115,878
ludwig-ai/ludwig
utils.py
FloatRange
FloatRange
Returns a dataclass field with marshmallow metadata enforcing numeric inputs must be in range set by relevant keyword args.
[ "Returns", "a", "dataclass", "field", "with", "marshmallow", "metadata", "enforcing", "numeric", "inputs", "must", "be", "in", "range", "set", "by", "relevant", "keyword", "args." ]
def FloatRange(default: Union[None, float], allow_none: bool=False, description: str='', parameter_metadata: ParameterMetadata=None, min: int=None, max: int=None, min_inclusive: bool=True, max_inclusive: bool=True): val = validate.Range(min=min, max=max, min_inclusive=min_inclusive, max_inclusive=max_inclusive) ...
['def', 'FloatRange(default:', 'Union[None,', 'float],', 'allow_none:', 'bool=False,', 'description:', "str='',", 'parameter_metadata:', 'ParameterMetadata=None,', 'min:', 'int=None,', 'max:', 'int=None,', 'min_inclusive:', 'bool=True,', 'max_inclusive:', 'bool=True):', 'val', '=', 'validate.Range(min=min,', 'max=max,'...
616,947
Levantespot/UDA_for_RS
decode_head.py
BaseDecodeHead.forward_test
forward_test
Forward function for testing.
[ "Forward", "function", "for", "testing." ]
def forward_test(self, inputs, img_metas, test_cfg): return self.forward(inputs)
['def', 'forward_test(self,', 'inputs,', 'img_metas,', 'test_cfg):', 'return', 'self.forward(inputs)']
947,371
LaoYang1994/PanopticSegmentation
nucleus.py
detect
detect
Run detection on images in the given directory.
[ "Run", "detection", "on", "images", "in", "the", "given", "directory." ]
def detect(model, dataset_dir, subset): print('Running on {}'.format(dataset_dir)) if not os.path.exists(RESULTS_DIR): os.makedirs(RESULTS_DIR) submit_dir = 'submit_{:%Y%m%dT%H%M%S}'.format(datetime.datetime.now()) submit_dir = os.path.join(RESULTS_DIR, submit_dir) os.makedirs(submit_dir) ...
['def', 'detect(model,', 'dataset_dir,', 'subset):', "print('Running", 'on', "{}'.format(dataset_dir))", 'if', 'not', 'os.path.exists(RESULTS_DIR):', 'os.makedirs(RESULTS_DIR)', 'submit_dir', '=', "'submit_{:%Y%m%dT%H%M%S}'.format(datetime.datetime.now())", 'submit_dir', '=', 'os.path.join(RESULTS_DIR,', 'submit_dir)',...
779,211
facebookresearch/deep_bisim4control
quadruped.py
Escape.get_observation
get_observation
Returns an observation to the agent.
[ "Returns", "an", "observation", "to", "the", "agent." ]
def get_observation(self, physics): obs = _common_observations(physics) obs['origin'] = physics.origin() obs['rangefinder'] = physics.rangefinder() return obs
['def', 'get_observation(self,', 'physics):', 'obs', '=', '_common_observations(physics)', "obs['origin']", '=', 'physics.origin()', "obs['rangefinder']", '=', 'physics.rangefinder()', 'return', 'obs']
536,451
eora-ai/torchok
detection.py
DetectionDataset.filter_bboxes
filter_bboxes
Filter empty bounding boxes.
[ "Filter", "empty", "bounding", "boxes." ]
def filter_bboxes(self, bboxes: Tensor, labels: Tensor, rows: int, cols: int) -> [Tensor, Tensor]: lbox = torch.hstack([bboxes, labels[..., None]]) alb_lbox = convert_bboxes_to_albumentations(lbox, self.bbox_format, rows, cols) alb_lbox_fixed = alb_filter_bboxes(alb_lbox, rows, cols) lbox_fixed = torch....
['def', 'filter_bboxes(self,', 'bboxes:', 'Tensor,', 'labels:', 'Tensor,', 'rows:', 'int,', 'cols:', 'int)', '->', '[Tensor,', 'Tensor]:', 'lbox', '=', 'torch.hstack([bboxes,', 'labels[...,', 'None]])', 'alb_lbox', '=', 'convert_bboxes_to_albumentations(lbox,', 'self.bbox_format,', 'rows,', 'cols)', 'alb_lbox_fixed', '...
903,029
google-research/batch-ppo
utility.py
initialize_variables
initialize_variables
Initialize or restore variables from a checkpoint if available.
[ "Initialize", "or", "restore", "variables", "from", "a", "checkpoint", "if", "available." ]
def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None): sess.run(tf.group(tf.local_variables_initializer(), tf.global_variables_initializer())) if resume and (not (logdir or checkpoint)): raise ValueError('Need to specify logdir to resume a checkpoint.') if logdir: state...
['def', 'initialize_variables(sess,', 'saver,', 'logdir,', 'checkpoint=None,', 'resume=None):', 'sess.run(tf.group(tf.local_variables_initializer(),', 'tf.global_variables_initializer()))', 'if', 'resume', 'and', '(not', '(logdir', 'or', 'checkpoint)):', 'raise', "ValueError('Need", 'to', 'specify', 'logdir', 'to', 're...
95,026
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
datasets.py
Dataset.batch_indices
batch_indices
Creates indices of shuffled minibatches.
[ "Creates", "indices", "of", "shuffled", "minibatches." ]
def batch_indices(self, num_batches, batch_size): if len(self.data) != len(self.labels): raise ValueError('Labels and data must have the same number of samples.') batch_indices = [] index_in_epoch = 0 dataset_size = len(self.data) dataset_indices = np.arange(dataset_size) np.random.shuff...
['def', 'batch_indices(self,', 'num_batches,', 'batch_size):', 'if', 'len(self.data)', '!=', 'len(self.labels):', 'raise', "ValueError('Labels", 'and', 'data', 'must', 'have', 'the', 'same', 'number', 'of', "samples.')", 'batch_indices', '=', '[]', 'index_in_epoch', '=', '0', 'dataset_size', '=', 'len(self.data)', 'dat...
55,581
albertonietos/artificial-intelligence
pep425tags.py
get_abi_tag
get_abi_tag
Return the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).
[ "Return", "the", "ABI", "tag", "based", "on", "SOABI", "(if", "available)", "or", "emulate", "SOABI", "(CPython", "2,", "PyPy)." ]
def get_abi_tag(): soabi = get_config_var('SOABI') impl = get_abbr_impl() if not soabi and impl in {'cp', 'pp'} and hasattr(sys, 'maxunicode'): d = '' m = '' u = '' if get_flag('Py_DEBUG', lambda : hasattr(sys, 'gettotalrefcount'), warn=impl == 'cp'): d = 'd' ...
['def', 'get_abi_tag():', 'soabi', '=', "get_config_var('SOABI')", 'impl', '=', 'get_abbr_impl()', 'if', 'not', 'soabi', 'and', 'impl', 'in', "{'cp',", "'pp'}", 'and', 'hasattr(sys,', "'maxunicode'):", 'd', '=', "''", 'm', '=', "''", 'u', '=', "''", 'if', "get_flag('Py_DEBUG',", 'lambda', ':', 'hasattr(sys,', "'gettota...
88,200
KalleHallden/InstaAutomator
cookies.py
MockRequest.add_header
add_header
cookielib has no legitimate use for this method; add it back if you find one.
[ "cookielib", "has", "no", "legitimate", "use", "for", "this", "method;", "add", "it", "back", "if", "you", "find", "one." ]
def add_header(self, key, val): raise NotImplementedError('Cookie headers should be added with add_unredirected_header()')
['def', 'add_header(self,', 'key,', 'val):', 'raise', "NotImplementedError('Cookie", 'headers', 'should', 'be', 'added', 'with', "add_unredirected_header()')"]
244,313
RasaHQ/rasa
trackers.py
DialogueStateTracker.get_last_event_for
get_last_event_for
Gets the last event of a given type which was actually applied.
[ "Gets", "the", "last", "event", "of", "a", "given", "type", "which", "was", "actually", "applied." ]
def get_last_event_for(self, event_type: Union[Type['EventTypeAlias'], Tuple[Type['EventTypeAlias'], ...]], action_names_to_exclude: Optional[List[Text]]=None, skip: int=0, event_verbosity: EventVerbosity=EventVerbosity.APPLIED) -> Optional['EventTypeAlias']: to_exclude = action_names_to_exclude or [] def filt...
['def', 'get_last_event_for(self,', 'event_type:', "Union[Type['EventTypeAlias'],", "Tuple[Type['EventTypeAlias'],", '...]],', 'action_names_to_exclude:', 'Optional[List[Text]]=None,', 'skip:', 'int=0,', 'event_verbosity:', 'EventVerbosity=EventVerbosity.APPLIED)', '->', "Optional['EventTypeAlias']:", 'to_exclude', '='...
837,553
matsu0228/nlp-jp
command_cursor.py
CommandCursor.close
close
Explicitly close / kill this cursor.
[ "Explicitly", "close", "/", "kill", "this", "cursor." ]
def close(self): self.__die(True)
['def', 'close(self):', 'self.__die(True)']
804,773
TonyLianLong/VAI-ReinforcementLearning
hooks_test_utils.py
HooksTracker.before_step
before_step
Implements `before_step` Composer callback.
[ "Implements", "`before_step`", "Composer", "callback." ]
def before_step(self, physics, *args): if self._has_super: super(HooksTracker, self).before_step(physics, *args) if not self.tracked: return self.assertHooksCalledOnce('initialize_episode_mjcf', 'after_compile', 'initialize_episode') self.assertEqual(self._call_count['after_step'], self....
['def', 'before_step(self,', 'physics,', '*args):', 'if', 'self._has_super:', 'super(HooksTracker,', 'self).before_step(physics,', '*args)', 'if', 'not', 'self.tracked:', 'return', "self.assertHooksCalledOnce('initialize_episode_mjcf',", "'after_compile',", "'initialize_episode')", "self.assertEqual(self._call_count['a...
439,882
binary-husky/hmp2g
base_vec_env.py
VecEnv.getattr_depth_check
getattr_depth_check
Check if an attribute reference is being hidden in a recursive call to __getattr__ :param name: name of attribute to check for :param already_found: whether this attribute has already been found in a wrapper :return: name of module whose attribute is being shadowed, if any.
[ "Check", "if", "an", "attribute", "reference", "is", "being", "hidden", "in", "a", "recursive", "call", "to", "__getattr__", ":param", "name:", "name", "of", "attribute", "to", "check", "for", ":param", "already_found:", "whether", "this", "attribute", "has", ...
def getattr_depth_check(self, name: str, already_found: bool) -> Optional[str]: if hasattr(self, name) and already_found: return f'{type(self).__module__}.{type(self).__name__}' else: return None
['def', 'getattr_depth_check(self,', 'name:', 'str,', 'already_found:', 'bool)', '->', 'Optional[str]:', 'if', 'hasattr(self,', 'name)', 'and', 'already_found:', 'return', "f'{type(self).__module__}.{type(self).__name__}'", 'else:', 'return', 'None']
569,023
mo-cv/pycv
rects.py
copyRect
copyRect
Copy part of the source to part of the destination.
[ "Copy", "part", "of", "the", "source", "to", "part", "of", "the", "destination." ]
def copyRect(src, dst, srcRect, dstRect, mask=None, interpolation=cv2.INTER_LINEAR): (x0, y0, w0, h0) = srcRect (x1, y1, w1, h1) = dstRect if mask is None: dst[y1:y1 + h1, x1:x1 + w1] = cv2.resize(src[y0:y0 + h0, x0:x0 + w0], (w1, h1), interpolation=interpolation) else: if not utils.isGr...
['def', 'copyRect(src,', 'dst,', 'srcRect,', 'dstRect,', 'mask=None,', 'interpolation=cv2.INTER_LINEAR):', '(x0,', 'y0,', 'w0,', 'h0)', '=', 'srcRect', '(x1,', 'y1,', 'w1,', 'h1)', '=', 'dstRect', 'if', 'mask', 'is', 'None:', 'dst[y1:y1', '+', 'h1,', 'x1:x1', '+', 'w1]', '=', 'cv2.resize(src[y0:y0', '+', 'h0,', 'x0:x0'...
819,494
sek788432/Waymo-2D-Object-Detection
box_list.py
BoxList.get_center_coordinates_and_sizes
get_center_coordinates_and_sizes
Computes the center coordinates, height and width of the boxes.
[ "Computes", "the", "center", "coordinates,", "height", "and", "width", "of", "the", "boxes." ]
def get_center_coordinates_and_sizes(self, scope=None): if not scope: scope = 'get_center_coordinates_and_sizes' with tf.name_scope(scope): box_corners = self.get() (ymin, xmin, ymax, xmax) = tf.unstack(tf.transpose(a=box_corners)) width = xmax - xmin height = ymax - ymin...
['def', 'get_center_coordinates_and_sizes(self,', 'scope=None):', 'if', 'not', 'scope:', 'scope', '=', "'get_center_coordinates_and_sizes'", 'with', 'tf.name_scope(scope):', 'box_corners', '=', 'self.get()', '(ymin,', 'xmin,', 'ymax,', 'xmax)', '=', 'tf.unstack(tf.transpose(a=box_corners))', 'width', '=', 'xmax', '-', ...
973,596
yinyunie/ScenePriors
tools.py
filter_cam_locs
filter_cam_locs
filter out the cam locs that are in nodes' bboxes :return: cam_loc ids that do not located in any bbox.
[ "filter", "out", "the", "cam", "locs", "that", "are", "in", "nodes'", "bboxes", ":return:", "cam_loc", "ids", "that", "do", "not", "located", "in", "any", "bbox." ]
def filter_cam_locs(cam_locs, bbox_3ds): inbox_vec = np.zeros(shape=cam_locs.shape[:-1], dtype=np.bool) for inst_bbox in bbox_3ds: centroid = inst_bbox[0:3] R_mat = R_from_pitch_yaw_roll(0, inst_bbox[6], 0)[0] size = inst_bbox[3:6] inbox_vec += check_in_box(cam_locs, {'centroid':...
['def', 'filter_cam_locs(cam_locs,', 'bbox_3ds):', 'inbox_vec', '=', 'np.zeros(shape=cam_locs.shape[:-1],', 'dtype=np.bool)', 'for', 'inst_bbox', 'in', 'bbox_3ds:', 'centroid', '=', 'inst_bbox[0:3]', 'R_mat', '=', 'R_from_pitch_yaw_roll(0,', 'inst_bbox[6],', '0)[0]', 'size', '=', 'inst_bbox[3:6]', 'inbox_vec', '+=', 'c...
330,302
abrarrhine/Artificial-Intelligence-PacmanGames
gridworld.py
Gridworld.getStates
getStates
Return list of all states.
[ "Return", "list", "of", "all", "states." ]
def getStates(self): states = [self.grid.terminalState] for x in range(self.grid.width): for y in range(self.grid.height): if self.grid[x][y] != '#': state = (x, y) states.append(state) return states
['def', 'getStates(self):', 'states', '=', '[self.grid.terminalState]', 'for', 'x', 'in', 'range(self.grid.width):', 'for', 'y', 'in', 'range(self.grid.height):', 'if', 'self.grid[x][y]', '!=', "'#':", 'state', '=', '(x,', 'y)', 'states.append(state)', 'return', 'states']
91,095
aeon-toolkit/aeon
test_base.py
test_equal_length_input
test_equal_length_input
Test with unequal length failures and passes.
[ "Test", "with", "unequal", "length", "failures", "and", "passes." ]
def test_equal_length_input(data): dummy = _TestClassifier() X = EQUAL_LENGTH_UNIVARIATE[data] y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) _assert_fit_predict(dummy, X, y) dummy = _TestHandlesAllInput() _assert_fit_predict(dummy, X, y)
['def', 'test_equal_length_input(data):', 'dummy', '=', '_TestClassifier()', 'X', '=', 'EQUAL_LENGTH_UNIVARIATE[data]', 'y', '=', 'np.array([0,', '0,', '0,', '0,', '0,', '1,', '1,', '1,', '1,', '1])', '_assert_fit_predict(dummy,', 'X,', 'y)', 'dummy', '=', '_TestHandlesAllInput()', '_assert_fit_predict(dummy,', 'X,', '...
399,310
ivanmontero/autobot
modeling_xlnet.py
XLNetRelativeAttention.rel_attn_core
rel_attn_core
Core relative positional attention operations.
[ "Core", "relative", "positional", "attention", "operations." ]
def rel_attn_core(self, q_head, k_head_h, v_head_h, k_head_r, seg_mat=None, attn_mask=None, head_mask=None, output_attentions=False): ac = torch.einsum('ibnd,jbnd->bnij', q_head + self.r_w_bias, k_head_h) bd = torch.einsum('ibnd,jbnd->bnij', q_head + self.r_r_bias, k_head_r) bd = self.rel_shift_bnij(bd, kle...
['def', 'rel_attn_core(self,', 'q_head,', 'k_head_h,', 'v_head_h,', 'k_head_r,', 'seg_mat=None,', 'attn_mask=None,', 'head_mask=None,', 'output_attentions=False):', 'ac', '=', "torch.einsum('ibnd,jbnd->bnij',", 'q_head', '+', 'self.r_w_bias,', 'k_head_h)', 'bd', '=', "torch.einsum('ibnd,jbnd->bnij',", 'q_head', '+', 's...
418,193
yanwenjie1/natural_language_processing
functions.py
get_span
get_span
Get span set from position start and end list.
[ "Get", "span", "set", "from", "position", "start", "and", "end", "list." ]
def get_span(start_ids, end_ids, with_prob=False): if with_prob: start_ids = sorted(start_ids, key=lambda x: x[0]) end_ids = sorted(end_ids, key=lambda x: x[0]) else: start_ids = sorted(start_ids) end_ids = sorted(end_ids) start_pointer = 0 end_pointer = 0 len_start =...
['def', 'get_span(start_ids,', 'end_ids,', 'with_prob=False):', 'if', 'with_prob:', 'start_ids', '=', 'sorted(start_ids,', 'key=lambda', 'x:', 'x[0])', 'end_ids', '=', 'sorted(end_ids,', 'key=lambda', 'x:', 'x[0])', 'else:', 'start_ids', '=', 'sorted(start_ids)', 'end_ids', '=', 'sorted(end_ids)', 'start_pointer', '=',...
734,546
PaddlePaddle/Paddle3D
bevf_transforms.py
ResizeImage.random_sample_ratio
random_sample_ratio
Randomly sample an img_scale when ``ratio_range`` is specified.
[ "Randomly", "sample", "an", "img_scale", "when", "``ratio_range``", "is", "specified." ]
def random_sample_ratio(img_scale, ratio_range): assert isinstance(img_scale, list) and len(img_scale) == 2 (min_ratio, max_ratio) = ratio_range assert min_ratio <= max_ratio ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio scale = (int(img_scale[0] * ratio), int(img_scale[1] ...
['def', 'random_sample_ratio(img_scale,', 'ratio_range):', 'assert', 'isinstance(img_scale,', 'list)', 'and', 'len(img_scale)', '==', '2', '(min_ratio,', 'max_ratio)', '=', 'ratio_range', 'assert', 'min_ratio', '<=', 'max_ratio', 'ratio', '=', 'np.random.random_sample()', '*', '(max_ratio', '-', 'min_ratio)', '+', 'min...
777,431
hamza-murad/AALU
compare_comply_v1.py
Value.to_dict
to_dict
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model." ]
def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: ...
['def', 'to_dict(self)', '->', 'Dict:', '_dict', '=', '{}', 'if', 'hasattr(self,', "'cell_id')", 'and', 'self.cell_id', 'is', 'not', 'None:', "_dict['cell_id']", '=', 'self.cell_id', 'if', 'hasattr(self,', "'location')", 'and', 'self.location', 'is', 'not', 'None:', "_dict['location']", '=', 'self.location._to_dict()',...
5,465
RasaHQ/rasa
utils.py
file_as_bytes
file_as_bytes
Read in a file as a byte array.
[ "Read", "in", "a", "file", "as", "a", "byte", "array." ]
def file_as_bytes(path: Text) -> bytes: with open(path, 'rb') as f: return f.read()
['def', 'file_as_bytes(path:', 'Text)', '->', 'bytes:', 'with', 'open(path,', "'rb')", 'as', 'f:', 'return', 'f.read()']
836,760
cangermueller/deepcpg
cpg.py
list_models
list_models
Return the name of models in the module.
[ "Return", "the", "name", "of", "models", "in", "the", "module." ]
def list_models(): models = dict() for (name, value) in globals().items(): if inspect.isclass(value) and name.lower().find('model') == -1: models[name] = value return models
['def', 'list_models():', 'models', '=', 'dict()', 'for', '(name,', 'value)', 'in', 'globals().items():', 'if', 'inspect.isclass(value)', 'and', "name.lower().find('model')", '==', '-1:', 'models[name]', '=', 'value', 'return', 'models']
520,272
tusen-ai/SST
custom_3d_seg.py
Custom3DSegDataset.load_annotations
load_annotations
Load annotations from ann_file.
[ "Load", "annotations", "from", "ann_file." ]
def load_annotations(self, ann_file): return mmcv.load(ann_file)
['def', 'load_annotations(self,', 'ann_file):', 'return', 'mmcv.load(ann_file)']
872,356
nicknochnack/RealTimeSignLanguageTFJS
dataset_loader.py
KittiRaw.is_valid_sample
is_valid_sample
Checks whether we can find a valid sequence around this frame.
[ "Checks", "whether", "we", "can", "find", "a", "valid", "sequence", "around", "this", "frame." ]
def is_valid_sample(self, frames, target_index): num_frames = len(frames) (target_drive, cam_id, _) = frames[target_index].split(' ') (start_index, end_index) = get_seq_start_end(target_index, self.seq_length) if start_index < 0 or end_index >= num_frames: return False (start_drive, start_ca...
['def', 'is_valid_sample(self,', 'frames,', 'target_index):', 'num_frames', '=', 'len(frames)', '(target_drive,', 'cam_id,', '_)', '=', "frames[target_index].split('", "')", '(start_index,', 'end_index)', '=', 'get_seq_start_end(target_index,', 'self.seq_length)', 'if', 'start_index', '<', '0', 'or', 'end_index', '>=',...
831,392
openvinotoolkit/training_extensions
supcon_classifier.py
SupConClassifier.forward_train
forward_train
Concatenate the different image views along the batch size.
[ "Concatenate", "the", "different", "image", "views", "along", "the", "batch", "size." ]
def forward_train(self, img, gt_label, **kwargs): if len(img.shape) == 5: img = torch.cat([img[:, d, :, :, :] for d in range(img.shape[1])], dim=0) x = self.extract_feat(img) losses = dict() if self.multilabel or self.hierarchical: loss = self.head.forward_train(x, gt_label, **kwargs) ...
['def', 'forward_train(self,', 'img,', 'gt_label,', '**kwargs):', 'if', 'len(img.shape)', '==', '5:', 'img', '=', 'torch.cat([img[:,', 'd,', ':,', ':,', ':]', 'for', 'd', 'in', 'range(img.shape[1])],', 'dim=0)', 'x', '=', 'self.extract_feat(img)', 'losses', '=', 'dict()', 'if', 'self.multilabel', 'or', 'self.hierarchic...
904,024
marcsto/rl
coding_ddpg.py
make_transformed_env
make_transformed_env
Apply transforms to the env (such as reward scaling and state normalization).
[ "Apply", "transforms", "to", "the", "env", "(such", "as", "reward", "scaling", "and", "state", "normalization)." ]
def make_transformed_env(env): env = TransformedEnv(env) env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) double_to_float_list = [] double_to_float_inv_list = [] if env_library is DMControlEnv: double_to_float_list += ['reward', 'action'] double_to_float_inv_list +=...
['def', 'make_transformed_env(env):', 'env', '=', 'TransformedEnv(env)', 'env.append_transform(RewardScaling(loc=0.0,', 'scale=reward_scaling))', 'double_to_float_list', '=', '[]', 'double_to_float_inv_list', '=', '[]', 'if', 'env_library', 'is', 'DMControlEnv:', 'double_to_float_list', '+=', "['reward',", "'action']",...
859,586
Eli-YiLi/WSSS_MMSeg
enc_head.py
EncHead.losses
losses
Compute segmentation and semantic encoding loss.
[ "Compute", "segmentation", "and", "semantic", "encoding", "loss." ]
def losses(self, seg_logit, seg_label): (seg_logit, se_seg_logit) = seg_logit loss = dict() loss.update(super(EncHead, self).losses(seg_logit, seg_label)) se_loss = self.loss_se_decode(se_seg_logit, self._convert_to_onehot_labels(seg_label, self.num_classes)) loss['loss_se'] = se_loss return los...
['def', 'losses(self,', 'seg_logit,', 'seg_label):', '(seg_logit,', 'se_seg_logit)', '=', 'seg_logit', 'loss', '=', 'dict()', 'loss.update(super(EncHead,', 'self).losses(seg_logit,', 'seg_label))', 'se_loss', '=', 'self.loss_se_decode(se_seg_logit,', 'self._convert_to_onehot_labels(seg_label,', 'self.num_classes))', "l...
961,169
anuragarnab/adversarial-attacks
dilated.py
PostprocessPrediction
PostprocessPrediction
Postprocess according to the original author's code.
[ "Postprocess", "according", "to", "the", "original", "author's", "code." ]
def PostprocessPrediction(x, image, dataset, zoom=8): if dataset.lower() == 'cityscapes': return x[:, 0:image.shape[0], 0:image.shape[1]] elif dataset.lower() == 'voc': return interp_map(x, zoom=zoom, width=image.shape[1], height=image.shape[0]) else: raise AssertionError('Unknown da...
['def', 'PostprocessPrediction(x,', 'image,', 'dataset,', 'zoom=8):', 'if', 'dataset.lower()', '==', "'cityscapes':", 'return', 'x[:,', '0:image.shape[0],', '0:image.shape[1]]', 'elif', 'dataset.lower()', '==', "'voc':", 'return', 'interp_map(x,', 'zoom=zoom,', 'width=image.shape[1],', 'height=image.shape[0])', 'else:'...
396,946
nicknochnack/RealTimeSignLanguageTFJS
inception_preprocessing.py
preprocess_image
preprocess_image
Pre-process one image for training or evaluation.
[ "Pre-process", "one", "image", "for", "training", "or", "evaluation." ]
def preprocess_image(image, height, width, is_training=False, bbox=None, fast_mode=True, add_image_summaries=True, crop_image=True, use_grayscale=False): if is_training: return preprocess_for_train(image, height, width, bbox, fast_mode, add_image_summaries=add_image_summaries, random_crop=crop_image, use_gr...
['def', 'preprocess_image(image,', 'height,', 'width,', 'is_training=False,', 'bbox=None,', 'fast_mode=True,', 'add_image_summaries=True,', 'crop_image=True,', 'use_grayscale=False):', 'if', 'is_training:', 'return', 'preprocess_for_train(image,', 'height,', 'width,', 'bbox,', 'fast_mode,', 'add_image_summaries=add_ima...
831,354
feast-dev/feast
test_online_retrieval.py
test_online
test_online
Test reading from the online store in local mode.
[ "Test", "reading", "from", "the", "online", "store", "in", "local", "mode." ]
def test_online() -> None: runner = CliRunner() with runner.local_repo(get_example_repo('example_feature_repo_1.py'), 'file') as store: driver_locations_fv = store.get_feature_view(name='driver_locations') customer_profile_fv = store.get_feature_view(name='customer_profile') customer_dri...
['def', 'test_online()', '->', 'None:', 'runner', '=', 'CliRunner()', 'with', "runner.local_repo(get_example_repo('example_feature_repo_1.py'),", "'file')", 'as', 'store:', 'driver_locations_fv', '=', "store.get_feature_view(name='driver_locations')", 'customer_profile_fv', '=', "store.get_feature_view(name='customer_p...
544,658
tusen-ai/SST
waymo_dataset.py
WaymoDataset.convert_valid_bboxes
convert_valid_bboxes
Convert the boxes into valid format.
[ "Convert", "the", "boxes", "into", "valid", "format." ]
def convert_valid_bboxes(self, box_dict, info): box_preds = box_dict['boxes_3d'] scores = box_dict['scores_3d'] labels = box_dict['labels_3d'] sample_idx = info['image']['image_idx'] box_preds.limit_yaw(offset=0.5, period=np.pi * 2) if len(box_preds) == 0: return dict(bbox=np.zeros([0, 4...
['def', 'convert_valid_bboxes(self,', 'box_dict,', 'info):', 'box_preds', '=', "box_dict['boxes_3d']", 'scores', '=', "box_dict['scores_3d']", 'labels', '=', "box_dict['labels_3d']", 'sample_idx', '=', "info['image']['image_idx']", 'box_preds.limit_yaw(offset=0.5,', 'period=np.pi', '*', '2)', 'if', 'len(box_preds)', '=...
872,432
awslabs/mxnet-lambda
config.py
config.check_inline
check_inline
Return the inline keyword recognized by the compiler, empty string otherwise.
[ "Return", "the", "inline", "keyword", "recognized", "by", "the", "compiler,", "empty", "string", "otherwise." ]
def check_inline(self): return check_inline(self)
['def', 'check_inline(self):', 'return', 'check_inline(self)']
288,573
SamsungLabs/imvoxelnet
lidar_box3d.py
LiDARInstance3DBoxes.rotate
rotate
Rotate boxes with points (optional) with the given angle.
[ "Rotate", "boxes", "with", "points", "(optional)", "with", "the", "given", "angle." ]
def rotate(self, angle, points=None): if not isinstance(angle, torch.Tensor): angle = self.tensor.new_tensor(angle) rot_sin = torch.sin(angle) rot_cos = torch.cos(angle) rot_mat_T = self.tensor.new_tensor([[rot_cos, -rot_sin, 0], [rot_sin, rot_cos, 0], [0, 0, 1]]) self.tensor[:, :3] = self.t...
['def', 'rotate(self,', 'angle,', 'points=None):', 'if', 'not', 'isinstance(angle,', 'torch.Tensor):', 'angle', '=', 'self.tensor.new_tensor(angle)', 'rot_sin', '=', 'torch.sin(angle)', 'rot_cos', '=', 'torch.cos(angle)', 'rot_mat_T', '=', 'self.tensor.new_tensor([[rot_cos,', '-rot_sin,', '0],', '[rot_sin,', 'rot_cos,'...
611,862
TrellixVulnTeam/Unsupervised_Learning_HFI7
__init__.py
safe_listdir
safe_listdir
Attempt to list contents of path, but suppress some exceptions.
[ "Attempt", "to", "list", "contents", "of", "path,", "but", "suppress", "some", "exceptions." ]
def safe_listdir(path): try: return os.listdir(path) except (PermissionError, NotADirectoryError): pass except OSError as e: if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT): raise return ()
['def', 'safe_listdir(path):', 'try:', 'return', 'os.listdir(path)', 'except', '(PermissionError,', 'NotADirectoryError):', 'pass', 'except', 'OSError', 'as', 'e:', 'if', 'e.errno', 'not', 'in', '(errno.ENOTDIR,', 'errno.EACCES,', 'errno.ENOENT):', 'raise', 'return', '()']
434,746
hamza-murad/AALU
discovery_v2.py
TableCellValues.from_dict
from_dict
Initialize a TableCellValues object from a json dictionary.
[ "Initialize", "a", "TableCellValues", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'TableCellValues': args = {} valid_keys = ['cell_id', 'location', 'text'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class TableCellValues: ' + ', '.join(bad_keys)) if 'cell_id'...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'TableCellValues':", 'args', '=', '{}', 'valid_keys', '=', "['cell_id',", "'location',", "'text']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'cl...
5,792
liujiboy/ComputerVision
homography.py
Haffine_from_points
Haffine_from_points
Find H, affine transformation, such that tp is affine transf of fp.
[ "Find", "H,", "affine", "transformation,", "such", "that", "tp", "is", "affine", "transf", "of", "fp." ]
def Haffine_from_points(fp, tp): if fp.shape != tp.shape: raise RuntimeError('number of points do not match') m = mean(fp[:2], axis=1) maxstd = max(std(fp[:2], axis=1)) + 1e-09 C1 = diag([1 / maxstd, 1 / maxstd, 1]) C1[0][2] = -m[0] / maxstd C1[1][2] = -m[1] / maxstd fp_cond = dot(C1...
['def', 'Haffine_from_points(fp,', 'tp):', 'if', 'fp.shape', '!=', 'tp.shape:', 'raise', "RuntimeError('number", 'of', 'points', 'do', 'not', "match')", 'm', '=', 'mean(fp[:2],', 'axis=1)', 'maxstd', '=', 'max(std(fp[:2],', 'axis=1))', '+', '1e-09', 'C1', '=', 'diag([1', '/', 'maxstd,', '1', '/', 'maxstd,', '1])', 'C1[...
471,533
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
resnet_model.py
building_block
building_block
Standard building block for residual networks with BN before convolutions.
[ "Standard", "building", "block", "for", "residual", "networks", "with", "BN", "before", "convolutions." ]
def building_block(inputs, filters, is_training, projection_shortcut, strides, data_format): shortcut = inputs inputs = batch_norm_relu(inputs, is_training, data_format) if projection_shortcut is not None: shortcut = projection_shortcut(inputs) inputs = conv2d_fixed_padding(inputs=inputs, filter...
['def', 'building_block(inputs,', 'filters,', 'is_training,', 'projection_shortcut,', 'strides,', 'data_format):', 'shortcut', '=', 'inputs', 'inputs', '=', 'batch_norm_relu(inputs,', 'is_training,', 'data_format)', 'if', 'projection_shortcut', 'is', 'not', 'None:', 'shortcut', '=', 'projection_shortcut(inputs)', 'inpu...
20,160