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
clips/pattern
metrics.py
specificity
specificity
Returns the percentage of negative cases correctly classified as negative.
[ "Returns", "the", "percentage", "of", "negative", "cases", "correctly", "classified", "as", "negative." ]
def specificity(classify=lambda document: False, documents=[]): (TP, TN, FP, FN) = confusion_matrix(classify, documents) return float(TN) / (TN + FP or 1)
['def', 'specificity(classify=lambda', 'document:', 'False,', 'documents=[]):', '(TP,', 'TN,', 'FP,', 'FN)', '=', 'confusion_matrix(classify,', 'documents)', 'return', 'float(TN)', '/', '(TN', '+', 'FP', 'or', '1)']
764,493
arshpreetsingh/quantopian-machinelearning
widget_output.py
Output.append_stderr
append_stderr
Append text to the stderr stream.
[ "Append", "text", "to", "the", "stderr", "stream." ]
def append_stderr(self, text): self._append_stream_output(text, stream_name='stderr')
['def', 'append_stderr(self,', 'text):', 'self._append_stream_output(text,', "stream_name='stderr')"]
887,264
boostcampaitech2/semantic-segmentation-level2-cv-05
class_names.py
ade_classes
ade_classes
ADE20K class names for external use.
[ "ADE20K", "class", "names", "for", "external", "use." ]
def ade_classes(): return ['wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchai...
['def', 'ade_classes():', 'return', "['wall',", "'building',", "'sky',", "'floor',", "'tree',", "'ceiling',", "'road',", "'bed", "',", "'windowpane',", "'grass',", "'cabinet',", "'sidewalk',", "'person',", "'earth',", "'door',", "'table',", "'mountain',", "'plant',", "'curtain',", "'chair',", "'car',", "'water',", "'pa...
844,620
tensorflow/quantum
random_clifford_circuit_test.py
RandomCliffordCircuitTest.test_random_clifford_circuit_inputs
test_random_clifford_circuit_inputs
Test for input validation.
[ "Test", "for", "input", "validation." ]
def test_random_clifford_circuit_inputs(self): qubits = cirq.GridQubit.rect(3, 2) n_moments = 10 op_density = 0.9 with self.assertRaisesRegex(TypeError, 'RandomState'): random_clifford_circuit(qubits, n_moments, op_density, random_state='string') with self.assertRaisesRegex(TypeError, 'Rando...
['def', 'test_random_clifford_circuit_inputs(self):', 'qubits', '=', 'cirq.GridQubit.rect(3,', '2)', 'n_moments', '=', '10', 'op_density', '=', '0.9', 'with', 'self.assertRaisesRegex(TypeError,', "'RandomState'):", 'random_clifford_circuit(qubits,', 'n_moments,', 'op_density,', "random_state='string')", 'with', 'self.a...
834,568
jshilong/DDQ
anchor_generator.py
AnchorGenerator.single_level_valid_flags
single_level_valid_flags
Generate the valid flags of anchor in a single feature map.
[ "Generate", "the", "valid", "flags", "of", "anchor", "in", "a", "single", "feature", "map." ]
def single_level_valid_flags(self, featmap_size, valid_size, num_base_anchors, device='cuda'): (feat_h, feat_w) = featmap_size (valid_h, valid_w) = valid_size assert valid_h <= feat_h and valid_w <= feat_w valid_x = torch.zeros(feat_w, dtype=torch.bool, device=device) valid_y = torch.zeros(feat_h, d...
['def', 'single_level_valid_flags(self,', 'featmap_size,', 'valid_size,', 'num_base_anchors,', "device='cuda'):", '(feat_h,', 'feat_w)', '=', 'featmap_size', '(valid_h,', 'valid_w)', '=', 'valid_size', 'assert', 'valid_h', '<=', 'feat_h', 'and', 'valid_w', '<=', 'feat_w', 'valid_x', '=', 'torch.zeros(feat_w,', 'dtype=t...
515,619
RasaHQ/rasa
layers.py
Ffnn.call
call
Apply feed-forward network layer.
[ "Apply", "feed-forward", "network", "layer." ]
def call(self, x: tf.Tensor, training: Optional[Union[tf.Tensor, bool]]=None) -> tf.Tensor: for layer in self._ffn_layers: x = layer(x, training=training) return x
['def', 'call(self,', 'x:', 'tf.Tensor,', 'training:', 'Optional[Union[tf.Tensor,', 'bool]]=None)', '->', 'tf.Tensor:', 'for', 'layer', 'in', 'self._ffn_layers:', 'x', '=', 'layer(x,', 'training=training)', 'return', 'x']
837,915
ArkoSharma/Artificial-Intelligence
search.py
Node.expand
expand
List the nodes reachable in one step from this node.
[ "List", "the", "nodes", "reachable", "in", "one", "step", "from", "this", "node." ]
def expand(self, problem): return [self.child_node(problem, action) for action in problem.actions(self.state)]
['def', 'expand(self,', 'problem):', 'return', '[self.child_node(problem,', 'action)', 'for', 'action', 'in', 'problem.actions(self.state)]']
117,840
43Carrig/recurrent_neural_networks_practice
summaries.py
add_scalar_summary
add_scalar_summary
Adds a scalar summary for the given tensor.
[ "Adds", "a", "scalar", "summary", "for", "the", "given", "tensor." ]
def add_scalar_summary(tensor, name=None, prefix=None, print_summary=False): collections = [] if print_summary else None summary_name = _get_summary_name(tensor, name, prefix) op = summary.scalar(name=summary_name, tensor=tensor, collections=collections) if print_summary: op = logging_ops.Print(...
['def', 'add_scalar_summary(tensor,', 'name=None,', 'prefix=None,', 'print_summary=False):', 'collections', '=', '[]', 'if', 'print_summary', 'else', 'None', 'summary_name', '=', '_get_summary_name(tensor,', 'name,', 'prefix)', 'op', '=', 'summary.scalar(name=summary_name,', 'tensor=tensor,', 'collections=collections)'...
335,203
pytorch/rl
transforms.py
VecNorm.to_observation_norm
to_observation_norm
Converts VecNorm into an ObservationNorm class that can be used at inference time.
[ "Converts", "VecNorm", "into", "an", "ObservationNorm", "class", "that", "can", "be", "used", "at", "inference", "time." ]
def to_observation_norm(self) -> Union[Compose, ObservationNorm]: out = [] for key in self.in_keys: _sum = self._td.get(key + '_sum') _ssq = self._td.get(key + '_ssq') _count = self._td.get(key + '_count') mean = _sum / _count std = (_ssq / _count - mean.pow(2)).clamp_min...
['def', 'to_observation_norm(self)', '->', 'Union[Compose,', 'ObservationNorm]:', 'out', '=', '[]', 'for', 'key', 'in', 'self.in_keys:', '_sum', '=', 'self._td.get(key', '+', "'_sum')", '_ssq', '=', 'self._td.get(key', '+', "'_ssq')", '_count', '=', 'self._td.get(key', '+', "'_count')", 'mean', '=', '_sum', '/', '_coun...
859,104
rahlk/Bellwether
hsic.py
CHSIC.UnBiasedHSIC
UnBiasedHSIC
Compute the UNbiased estimator of HSIC.
[ "Compute", "the", "UNbiased", "estimator", "of", "HSIC." ]
def UnBiasedHSIC(self, x, y, kernelx=vector.CLinearKernel(), kernely=vector.CLinearKernel()): nx = x.shape ny = y.shape assert nx[0] == ny[0], 'Argument 1 and 2 have different number of data points' kMat = kernelx.Dot(x, x) setdiag0(kMat) lMat = kernely.Dot(y, y) setdiag0(lMat) sK = kMat...
['def', 'UnBiasedHSIC(self,', 'x,', 'y,', 'kernelx=vector.CLinearKernel(),', 'kernely=vector.CLinearKernel()):', 'nx', '=', 'x.shape', 'ny', '=', 'y.shape', 'assert', 'nx[0]', '==', 'ny[0],', "'Argument", '1', 'and', '2', 'have', 'different', 'number', 'of', 'data', "points'", 'kMat', '=', 'kernelx.Dot(x,', 'x)', 'setd...
432,143
kumarkan/Food_Detection
visualization_utils_test.py
VisualizationUtilsTest.test_draw_bounding_boxes_on_image_tensors
test_draw_bounding_boxes_on_image_tensors
Tests that bounding box utility produces reasonable results.
[ "Tests", "that", "bounding", "box", "utility", "produces", "reasonable", "results." ]
def test_draw_bounding_boxes_on_image_tensors(self): category_index = {1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}} fname = os.path.join(_TESTDATA_PATH, 'image1.jpg') image_np = np.array(Image.open(fname)) images_np = np.stack((image_np, image_np), axis=0) with tf.Graph().as_default(): ...
['def', 'test_draw_bounding_boxes_on_image_tensors(self):', 'category_index', '=', '{1:', "{'id':", '1,', "'name':", "'dog'},", '2:', "{'id':", '2,', "'name':", "'cat'}}", 'fname', '=', 'os.path.join(_TESTDATA_PATH,', "'image1.jpg')", 'image_np', '=', 'np.array(Image.open(fname))', 'images_np', '=', 'np.stack((image_np...
609,096
chenbinghui1/DSL
centernet_head.py
CenterNetHead.get_targets
get_targets
Compute regression and classification targets in multiple images.
[ "Compute", "regression", "and", "classification", "targets", "in", "multiple", "images." ]
def get_targets(self, gt_bboxes, gt_labels, feat_shape, img_shape): (img_h, img_w) = img_shape[:2] (bs, _, feat_h, feat_w) = feat_shape width_ratio = float(feat_w / img_w) height_ratio = float(feat_h / img_h) center_heatmap_target = gt_bboxes[-1].new_zeros([bs, self.num_classes, feat_h, feat_w]) ...
['def', 'get_targets(self,', 'gt_bboxes,', 'gt_labels,', 'feat_shape,', 'img_shape):', '(img_h,', 'img_w)', '=', 'img_shape[:2]', '(bs,', '_,', 'feat_h,', 'feat_w)', '=', 'feat_shape', 'width_ratio', '=', 'float(feat_w', '/', 'img_w)', 'height_ratio', '=', 'float(feat_h', '/', 'img_h)', 'center_heatmap_target', '=', 'g...
167,686
BestJuly/Pretext-Contrastive-Learning
retrieve_clips.py
extract_feature
extract_feature
Extract and save features for train split, several clips per video.
[ "Extract", "and", "save", "features", "for", "train", "split,", "several", "clips", "per", "video." ]
def extract_feature(args): torch.backends.cudnn.benchmark = True device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') if args.model == 'r3d': model = R3DNet(layer_sizes=(1, 1, 1, 1), with_classifier=False, return_conv=True).to(device) elif args.model == 'r18': model = ...
['def', 'extract_feature(args):', 'torch.backends.cudnn.benchmark', '=', 'True', 'device', '=', "torch.device('cuda:0'", 'if', 'torch.cuda.is_available()', 'else', "'cpu')", 'if', 'args.model', '==', "'r3d':", 'model', '=', 'R3DNet(layer_sizes=(1,', '1,', '1,', '1),', 'with_classifier=False,', 'return_conv=True).to(dev...
305,966
cristiand391/cs50ai
logic.py
Sentence.parenthesize
parenthesize
Parenthesizes an expression if not already parenthesized.
[ "Parenthesizes", "an", "expression", "if", "not", "already", "parenthesized." ]
def parenthesize(cls, s): def balanced(s): count = 0 for c in s: if c == '(': count += 1 elif c == ')': if count <= 0: return False count -= 1 return count == 0 if not len(s) or s.isalpha() or (s...
['def', 'parenthesize(cls,', 's):', 'def', 'balanced(s):', 'count', '=', '0', 'for', 'c', 'in', 's:', 'if', 'c', '==', "'(':", 'count', '+=', '1', 'elif', 'c', '==', "')':", 'if', 'count', '<=', '0:', 'return', 'False', 'count', '-=', '1', 'return', 'count', '==', '0', 'if', 'not', 'len(s)', 'or', 's.isalpha()', 'or', ...
192,214
google/balloon-learning-environment
features.py
PerciatelliFeatureConstructor.observation_space
observation_space
Returns the observation space for this feature constructor.
[ "Returns", "the", "observation", "space", "for", "this", "feature", "constructor." ]
def observation_space(self) -> gym.spaces.Box: low = np.zeros(self.num_features, dtype=np.float32) high = np.ones(self.num_features, dtype=np.float32) trig_features = [3, 4, 5, 6] low[trig_features] = -1.0 low[15] = 1.0 high[15] = np.inf return gym.spaces.Box(low=low, high=high)
['def', 'observation_space(self)', '->', 'gym.spaces.Box:', 'low', '=', 'np.zeros(self.num_features,', 'dtype=np.float32)', 'high', '=', 'np.ones(self.num_features,', 'dtype=np.float32)', 'trig_features', '=', '[3,', '4,', '5,', '6]', 'low[trig_features]', '=', '-1.0', 'low[15]', '=', '1.0', 'high[15]', '=', 'np.inf', ...
422,367
KalleHallden/InstaAutomator
__init__.py
VendorImporter.load_module
load_module
Iterate over the search path to locate and load fullname.
[ "Iterate", "over", "the", "search", "path", "to", "locate", "and", "load", "fullname." ]
def load_module(self, fullname): (root, base, target) = fullname.partition(self.root_name + '.') for prefix in self.search_path: try: extant = prefix + target __import__(extant) mod = sys.modules[extant] sys.modules[fullname] = mod if prefix an...
['def', 'load_module(self,', 'fullname):', '(root,', 'base,', 'target)', '=', 'fullname.partition(self.root_name', '+', "'.')", 'for', 'prefix', 'in', 'self.search_path:', 'try:', 'extant', '=', 'prefix', '+', 'target', '__import__(extant)', 'mod', '=', 'sys.modules[extant]', 'sys.modules[fullname]', '=', 'mod', 'if', ...
244,476
SamsungLabs/fcaf3d
single_stage_sparse.py
SingleStageSparse3DDetector.simple_test
simple_test
Test function without augmentaiton.
[ "Test", "function", "without", "augmentaiton." ]
def simple_test(self, points, img_metas, imgs=None, rescale=False): x = self.extract_feat(points, img_metas) bbox_list = self.neck_with_head.get_bboxes(*x, img_metas, rescale=rescale) bbox_results = [bbox3d2result(bboxes, scores, labels) for (bboxes, scores, labels) in bbox_list] return bbox_results
['def', 'simple_test(self,', 'points,', 'img_metas,', 'imgs=None,', 'rescale=False):', 'x', '=', 'self.extract_feat(points,', 'img_metas)', 'bbox_list', '=', 'self.neck_with_head.get_bboxes(*x,', 'img_metas,', 'rescale=rescale)', 'bbox_results', '=', '[bbox3d2result(bboxes,', 'scores,', 'labels)', 'for', '(bboxes,', 's...
560,485
zihuitang/medical_AI_platform
ast.py
NodeVisitor.generic_visit
generic_visit
Called if no explicit visitor function exists for a node.
[ "Called", "if", "no", "explicit", "visitor", "function", "exists", "for", "a", "node." ]
def generic_visit(self, node): for (field, value) in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
['def', 'generic_visit(self,', 'node):', 'for', '(field,', 'value)', 'in', 'iter_fields(node):', 'if', 'isinstance(value,', 'list):', 'for', 'item', 'in', 'value:', 'if', 'isinstance(item,', 'AST):', 'self.visit(item)', 'elif', 'isinstance(value,', 'AST):', 'self.visit(value)']
280,063
MANGA-UOFA/NAUS
utils.py
to_pair
to_pair
Make a pair (of type tuple) of given value.
[ "Make", "a", "pair", "(of", "type", "tuple)", "of", "given", "value." ]
def to_pair(value, name): if isinstance(value, Iterable): if len(value) != 2: raise ValueError('Expected `{}` to have exactly 2 elements, got: ({})'.format(name, value)) return value return tuple(repeat(value, 2))
['def', 'to_pair(value,', 'name):', 'if', 'isinstance(value,', 'Iterable):', 'if', 'len(value)', '!=', '2:', 'raise', "ValueError('Expected", '`{}`', 'to', 'have', 'exactly', '2', 'elements,', 'got:', "({})'.format(name,", 'value))', 'return', 'value', 'return', 'tuple(repeat(value,', '2))']
291,629
PJLab-ADG/LoGoNet
utils.py
NumClassCheckHook.before_train_epoch
before_train_epoch
Check whether the training dataset is compatible with head.
[ "Check", "whether", "the", "training", "dataset", "is", "compatible", "with", "head." ]
def before_train_epoch(self, runner): self._check_head(runner)
['def', 'before_train_epoch(self,', 'runner):', 'self._check_head(runner)']
615,073
intel/neural-compressor
main.py
evaluate
evaluate
Custom evaluate function to estimate the accuracy of the model.
[ "Custom", "evaluate", "function", "to", "estimate", "the", "accuracy", "of", "the", "model." ]
def evaluate(model, eval_dataloader, metric, postprocess=None): from neural_compressor.model import Model model = Model(model) input_tensor = model.input_tensor output_tensor = model.output_tensor if len(model.output_tensor) > 1 else model.output_tensor[0] iteration = -1 if args.benchmark and ar...
['def', 'evaluate(model,', 'eval_dataloader,', 'metric,', 'postprocess=None):', 'from', 'neural_compressor.model', 'import', 'Model', 'model', '=', 'Model(model)', 'input_tensor', '=', 'model.input_tensor', 'output_tensor', '=', 'model.output_tensor', 'if', 'len(model.output_tensor)', '>', '1', 'else', 'model.output_te...
736,951
suzanasvm/ComputerVision
ar_cube.py
my_calibration
my_calibration
Calibration function for the camera (iPhone4) used in this example.
[ "Calibration", "function", "for", "the", "camera", "(iPhone4)", "used", "in", "this", "example." ]
def my_calibration(sz): (row, col) = sz fx = 2555 * col / 2592 fy = 2586 * row / 1936 K = diag([fx, fy, 1]) K[0, 2] = 0.5 * col K[1, 2] = 0.5 * row return K
['def', 'my_calibration(sz):', '(row,', 'col)', '=', 'sz', 'fx', '=', '2555', '*', 'col', '/', '2592', 'fy', '=', '2586', '*', 'row', '/', '1936', 'K', '=', 'diag([fx,', 'fy,', '1])', 'K[0,', '2]', '=', '0.5', '*', 'col', 'K[1,', '2]', '=', '0.5', '*', 'row', 'return', 'K']
471,113
SvenGronauer/phoenix-drone-simulation
trpo.py
TRPOAlgorithm.adjust_step_direction
adjust_step_direction
TRPO performs line-search until constraint satisfaction.
[ "TRPO", "performs", "line-search", "until", "constraint", "satisfaction." ]
def adjust_step_direction(self, step_dir, g_flat, p_dist, data, total_steps: int=15, decay: float=0.8) -> tuple: step_frac = 1.0 _theta_old = U.get_flat_params_from(self.ac.pi.net) expected_improve = g_flat.dot(step_dir) for j in range(total_steps): new_theta = _theta_old + step_frac * step_dir ...
['def', 'adjust_step_direction(self,', 'step_dir,', 'g_flat,', 'p_dist,', 'data,', 'total_steps:', 'int=15,', 'decay:', 'float=0.8)', '->', 'tuple:', 'step_frac', '=', '1.0', '_theta_old', '=', 'U.get_flat_params_from(self.ac.pi.net)', 'expected_improve', '=', 'g_flat.dot(step_dir)', 'for', 'j', 'in', 'range(total_step...
769,100
scikit-learn-contrib/imbalanced-learn
test_docstring.py
test_function_docstring
test_function_docstring
Check function docstrings using numpydoc.
[ "Check", "function", "docstrings", "using", "numpydoc." ]
def test_function_docstring(function_name, request): if function_name in FUNCTION_DOCSTRING_IGNORE_LIST: request.applymarker(pytest.mark.xfail(run=False, reason='TODO pass numpydoc validation')) res = numpydoc_validation.validate(function_name) res['errors'] = list(filter_errors(res['errors'], metho...
['def', 'test_function_docstring(function_name,', 'request):', 'if', 'function_name', 'in', 'FUNCTION_DOCSTRING_IGNORE_LIST:', 'request.applymarker(pytest.mark.xfail(run=False,', "reason='TODO", 'pass', 'numpydoc', "validation'))", 'res', '=', 'numpydoc_validation.validate(function_name)', "res['errors']", '=', "list(f...
610,739
devashish-patel/webcam-motion-detector
models.py
RequestEncodingMixin.path_url
path_url
Build the path URL to use.
[ "Build", "the", "path", "URL", "to", "use." ]
def path_url(self): url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url)
['def', 'path_url(self):', 'url', '=', '[]', 'p', '=', 'urlsplit(self.url)', 'path', '=', 'p.path', 'if', 'not', 'path:', 'path', '=', "'/'", 'url.append(path)', 'query', '=', 'p.query', 'if', 'query:', "url.append('?')", 'url.append(query)', 'return', "''.join(url)"]
983,394
deepmind/bsuite
analysis.py
plot_learning
plot_learning
Simple learning curves for cartpole.
[ "Simple", "learning", "curves", "for", "cartpole." ]
def plot_learning(df: pd.DataFrame, sweep_vars: Optional[Sequence[str]]=None) -> gg.ggplot: df = cartpole_preprocess(df) p = plotting.plot_regret_learning(df, sweep_vars=sweep_vars, max_episode=NUM_EPISODES) p += gg.geom_hline(gg.aes(yintercept=BASE_REGRET), linetype='dashed', alpha=0.4, size=1.75) retu...
['def', 'plot_learning(df:', 'pd.DataFrame,', 'sweep_vars:', 'Optional[Sequence[str]]=None)', '->', 'gg.ggplot:', 'df', '=', 'cartpole_preprocess(df)', 'p', '=', 'plotting.plot_regret_learning(df,', 'sweep_vars=sweep_vars,', 'max_episode=NUM_EPISODES)', 'p', '+=', 'gg.geom_hline(gg.aes(yintercept=BASE_REGRET),', "linet...
410,175
hendrycks/ss-ood
opencv_functional.py
to_grayscale
to_grayscale
Convert image to grayscale version of image.
[ "Convert", "image", "to", "grayscale", "version", "of", "image." ]
def to_grayscale(img, num_output_channels=1): if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if num_output_channels == 1: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] elif num_output_channels == 3: img = np.broad...
['def', 'to_grayscale(img,', 'num_output_channels=1):', 'if', 'not', '_is_numpy_image(img):', 'raise', "TypeError('img", 'should', 'be', 'numpy', 'ndarray.', 'Got', "{}'.format(type(img)))", 'if', 'num_output_channels', '==', '1:', 'img', '=', 'cv2.cvtColor(img,', 'cv2.COLOR_RGB2GRAY)[:,', ':,', 'np.newaxis]', 'elif', ...
372,366
TrellixVulnTeam/Unsupervised_Learning_HFI7
install.py
install.create_home_path
create_home_path
Create directories under ~.
[ "Create", "directories", "under", "~." ]
def create_home_path(self): if not self.user: return home = convert_path(os.path.expanduser('~')) for (name, path) in self.config_vars.items(): if path.startswith(home) and (not os.path.isdir(path)): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path...
['def', 'create_home_path(self):', 'if', 'not', 'self.user:', 'return', 'home', '=', "convert_path(os.path.expanduser('~'))", 'for', '(name,', 'path)', 'in', 'self.config_vars.items():', 'if', 'path.startswith(home)', 'and', '(not', 'os.path.isdir(path)):', 'self.debug_print("os.makedirs(\'%s\',', '0o700)"', '%', 'path...
436,438
mohamadi-sara20/NaturalLanguageProcessing
modeling.py
layer_norm_and_dropout
layer_norm_and_dropout
Runs layer normalization followed by dropout.
[ "Runs", "layer", "normalization", "followed", "by", "dropout." ]
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None): output_tensor = layer_norm(input_tensor, name) output_tensor = dropout(output_tensor, dropout_prob) return output_tensor
['def', 'layer_norm_and_dropout(input_tensor,', 'dropout_prob,', 'name=None):', 'output_tensor', '=', 'layer_norm(input_tensor,', 'name)', 'output_tensor', '=', 'dropout(output_tensor,', 'dropout_prob)', 'return', 'output_tensor']
712,610
jxhe/unify-parameter-efficient-tuning
tokenization_xlm_prophetnet.py
load_vocab
load_vocab
Loads a vocabulary file into a dictionary.
[ "Loads", "a", "vocabulary", "file", "into", "a", "dictionary." ]
def load_vocab(vocab_file): vocab = collections.OrderedDict() with open(vocab_file, 'r', encoding='utf-8') as reader: tokens = reader.readlines() for (index, token) in enumerate(tokens): token = token.rstrip('\n') vocab[token] = index return vocab
['def', 'load_vocab(vocab_file):', 'vocab', '=', 'collections.OrderedDict()', 'with', 'open(vocab_file,', "'r',", "encoding='utf-8')", 'as', 'reader:', 'tokens', '=', 'reader.readlines()', 'for', '(index,', 'token)', 'in', 'enumerate(tokens):', 'token', '=', "token.rstrip('\\n')", 'vocab[token]', '=', 'index', 'return'...
949,371
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
resize_image
resize_image
Function that resize the np image.
[ "Function", "that", "resize", "the", "np", "image." ]
def resize_image(inp_array, new_height, new_width): inp_array = np.clip(inp_array, 0, 255).astype(np.uint8) image = Image.fromarray(inp_array) image = image.resize((new_width, new_height)) return np.array(image)
['def', 'resize_image(inp_array,', 'new_height,', 'new_width):', 'inp_array', '=', 'np.clip(inp_array,', '0,', '255).astype(np.uint8)', 'image', '=', 'Image.fromarray(inp_array)', 'image', '=', 'image.resize((new_width,', 'new_height))', 'return', 'np.array(image)']
109,295
sunishsheth2009/ChatterBot
reading.py
IndexReader.field_terms
field_terms
Yields all term values (converted from on-disk bytes) in the given field.
[ "Yields", "all", "term", "values", "(converted", "from", "on-disk", "bytes)", "in", "the", "given", "field." ]
def field_terms(self, fieldname): from_bytes = self.schema[fieldname].from_bytes for btext in self.lexicon(fieldname): yield from_bytes(btext)
['def', 'field_terms(self,', 'fieldname):', 'from_bytes', '=', 'self.schema[fieldname].from_bytes', 'for', 'btext', 'in', 'self.lexicon(fieldname):', 'yield', 'from_bytes(btext)']
484,015
weimin17/Object-Detection_HelmetDetection
problem_generator.py
Problem.init_variables
init_variables
Returns a list of variables with the given shape.
[ "Returns", "a", "list", "of", "variables", "with", "the", "given", "shape." ]
def init_variables(self, seed=None): with tf.variable_scope(PARAMETER_SCOPE): params = [tf.Variable(param) for param in self.init_tensors(seed)] return params
['def', 'init_variables(self,', 'seed=None):', 'with', 'tf.variable_scope(PARAMETER_SCOPE):', 'params', '=', '[tf.Variable(param)', 'for', 'param', 'in', 'self.init_tensors(seed)]', 'return', 'params']
763,284
liqd/adhocracy
__init__.py
format_date
format_date
Format the date in a local aware format.
[ "Format", "the", "date", "in", "a", "local", "aware", "format." ]
def format_date(dt, set_timezone=True, format=None): from pylons import tmpl_context as c if format is None: format = u'long' if set_timezone: dt = local_datetime(dt) return babel.dates.format_date(dt, format=format, locale=c.locale or babel.Locale('en', 'US'))
['def', 'format_date(dt,', 'set_timezone=True,', 'format=None):', 'from', 'pylons', 'import', 'tmpl_context', 'as', 'c', 'if', 'format', 'is', 'None:', 'format', '=', "u'long'", 'if', 'set_timezone:', 'dt', '=', 'local_datetime(dt)', 'return', 'babel.dates.format_date(dt,', 'format=format,', 'locale=c.locale', 'or', "b...
39,936
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
Wald_Friedman_utils.py
WaldFriedman.bayes_update_k
bayes_update_k
This function takes a value for p, and a realization of the random variable and calculates the value for p tomorrow.
[ "This", "function", "takes", "a", "value", "for", "p,", "and", "a", "realization", "of", "the", "random", "variable", "and", "calculates", "the", "value", "for", "p", "tomorrow." ]
def bayes_update_k(self, p, k): f0_k = self.f0[k] f1_k = self.f1[k] p_tp1 = p * f0_k / (p * f0_k + (1 - p) * f1_k) return np.clip(p_tp1, 0, 1)
['def', 'bayes_update_k(self,', 'p,', 'k):', 'f0_k', '=', 'self.f0[k]', 'f1_k', '=', 'self.f1[k]', 'p_tp1', '=', 'p', '*', 'f0_k', '/', '(p', '*', 'f0_k', '+', '(1', '-', 'p)', '*', 'f1_k)', 'return', 'np.clip(p_tp1,', '0,', '1)']
18,374
awslabs/predictive-maintenance-using--
generic.py
NDFrame.iteritems
iteritems
Iterate over (label, values) on info axis This is index for Series, columns for DataFrame, major_axis for Panel, and so on.
[ "Iterate", "over", "(label,", "values)", "on", "info", "axis", "This", "is", "index", "for", "Series,", "columns", "for", "DataFrame,", "major_axis", "for", "Panel,", "and", "so", "on." ]
def iteritems(self): for h in self._info_axis: yield (h, self[h])
['def', 'iteritems(self):', 'for', 'h', 'in', 'self._info_axis:', 'yield', '(h,', 'self[h])']
823,097
weimin17/Object-Detection_HelmetDetection
evaluate.py
run
run
Runs evaluation in a loop, and logs summaries to TensorBoard.
[ "Runs", "evaluation", "in", "a", "loop,", "and", "logs", "summaries", "to", "TensorBoard." ]
def run(): eval_dir = FLAGS.eval_dir if not tf.gfile.IsDirectory(eval_dir): tf.logging.info('Creating eval directory: %s', eval_dir) tf.gfile.MakeDirs(eval_dir) g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.input_file_pattern ...
['def', 'run():', 'eval_dir', '=', 'FLAGS.eval_dir', 'if', 'not', 'tf.gfile.IsDirectory(eval_dir):', "tf.logging.info('Creating", 'eval', 'directory:', "%s',", 'eval_dir)', 'tf.gfile.MakeDirs(eval_dir)', 'g', '=', 'tf.Graph()', 'with', 'g.as_default():', 'model_config', '=', 'configuration.ModelConfig()', 'model_config...
763,056
apeterswu/RL4NMT
diet.py
DietAdamOptimizer.create_slots
create_slots
Create the factorized Adam accumulators for diet variables.
[ "Create", "the", "factorized", "Adam", "accumulators", "for", "diet", "variables." ]
def create_slots(self, var): params = self.params shape = var.get_shape().as_list() if not hasattr(params, 'slots'): params.slots = defaultdict(dict) name = var.op.name slots = params.slots[name] if params.factored_second_moment_accumulator and len(shape) == 2: slots['adam_vr'] =...
['def', 'create_slots(self,', 'var):', 'params', '=', 'self.params', 'shape', '=', 'var.get_shape().as_list()', 'if', 'not', 'hasattr(params,', "'slots'):", 'params.slots', '=', 'defaultdict(dict)', 'name', '=', 'var.op.name', 'slots', '=', 'params.slots[name]', 'if', 'params.factored_second_moment_accumulator', 'and',...
331,739
weimin17/Object-Detection_HelmetDetection
ops.py
retain_groundtruth
retain_groundtruth
Retains groundtruth by valid indices.
[ "Retains", "groundtruth", "by", "valid", "indices." ]
def retain_groundtruth(tensor_dict, valid_indices): input_shape = valid_indices.get_shape().as_list() if not (len(input_shape) == 1 or (len(input_shape) == 2 and input_shape[1] == 1)): raise ValueError('The shape of valid_indices is invalid.') valid_indices = tf.reshape(valid_indices, [-1]) vali...
['def', 'retain_groundtruth(tensor_dict,', 'valid_indices):', 'input_shape', '=', 'valid_indices.get_shape().as_list()', 'if', 'not', '(len(input_shape)', '==', '1', 'or', '(len(input_shape)', '==', '2', 'and', 'input_shape[1]', '==', '1)):', 'raise', "ValueError('The", 'shape', 'of', 'valid_indices', 'is', "invalid.')...
759,228
RasaHQ/rasa
extractor.py
EntityExtractorMixin.add_extractor_name
add_extractor_name
Adds this extractor's name to a list of entities.
[ "Adds", "this", "extractor's", "name", "to", "a", "list", "of", "entities." ]
def add_extractor_name(self, entities: List[Dict[Text, Any]]) -> List[Dict[Text, Any]]: for entity in entities: entity[EXTRACTOR] = self.name return entities
['def', 'add_extractor_name(self,', 'entities:', 'List[Dict[Text,', 'Any]])', '->', 'List[Dict[Text,', 'Any]]:', 'for', 'entity', 'in', 'entities:', 'entity[EXTRACTOR]', '=', 'self.name', 'return', 'entities']
837,210
voxel51/fiftyone
openlabel.py
OpenLABELStreams.parse_streams_dict
parse_streams_dict
Parses the OpenLABEL annotations corresponding to a specific dictionary of streams.
[ "Parses", "the", "OpenLABEL", "annotations", "corresponding", "to", "a", "specific", "dictionary", "of", "streams." ]
def parse_streams_dict(self, streams_dict, label_file_id, frame_number=None): for (key, element_dict) in streams_dict.items(): self._add_stream_dict(label_file_id, key, element_dict, frame_number=frame_number)
['def', 'parse_streams_dict(self,', 'streams_dict,', 'label_file_id,', 'frame_number=None):', 'for', '(key,', 'element_dict)', 'in', 'streams_dict.items():', 'self._add_stream_dict(label_file_id,', 'key,', 'element_dict,', 'frame_number=frame_number)']
584,140
BMW-InnovationLab/BMW-Semantic--Training-GUI
rcnn.py
MaskAccMetric.update
update
Updates the internal evaluation result.
[ "Updates", "the", "internal", "evaluation", "result." ]
def update(self, labels, preds): (rcnn_mask_target, rcnn_mask_weight) = labels rcnn_mask = preds[0] num_inst = mx.nd.sum(rcnn_mask_weight) pred_label = mx.nd.sigmoid(rcnn_mask) >= 0.5 label = rcnn_mask_target >= 0.5 num_acc = mx.nd.sum((pred_label == label) * rcnn_mask_weight) self.sum_metri...
['def', 'update(self,', 'labels,', 'preds):', '(rcnn_mask_target,', 'rcnn_mask_weight)', '=', 'labels', 'rcnn_mask', '=', 'preds[0]', 'num_inst', '=', 'mx.nd.sum(rcnn_mask_weight)', 'pred_label', '=', 'mx.nd.sigmoid(rcnn_mask)', '>=', '0.5', 'label', '=', 'rcnn_mask_target', '>=', '0.5', 'num_acc', '=', 'mx.nd.sum((pre...
463,767
ugr-sail/sinergym
eplus.py
EnergyPlus.stop
stop
It forces the simulation ends, cleans all communication queues, thread is deleted (joined) and simulator attributes are reset (except handlers, to not initialize again if there is a next thread execution).
[ "It", "forces", "the", "simulation", "ends,", "cleans", "all", "communication", "queues,", "thread", "is", "deleted", "(joined)", "and", "simulator", "attributes", "are", "reset", "(except", "handlers,", "to", "not", "initialize", "again", "if", "there", "is", "...
def stop(self) -> None: if self.is_running: self.simulation_complete = True self._flush_queues() self.energyplus_thread.join() self.energyplus_thread = None self.api.runtime.clear_callbacks() self.api.state_manager.delete_state(self.energyplus_state) self.sim_...
['def', 'stop(self)', '->', 'None:', 'if', 'self.is_running:', 'self.simulation_complete', '=', 'True', 'self._flush_queues()', 'self.energyplus_thread.join()', 'self.energyplus_thread', '=', 'None', 'self.api.runtime.clear_callbacks()', 'self.api.state_manager.delete_state(self.energyplus_state)', 'self.sim_results:',...
884,412
43Carrig/recurrent_neural_networks_practice
models.py
Response.next
next
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
[ "Returns", "a", "PreparedRequest", "for", "the", "next", "request", "in", "a", "redirect", "chain,", "if", "there", "is", "one." ]
def next(self): return self._next
['def', 'next(self):', 'return', 'self._next']
311,814
rdevon/BGAN
math.py
log_sum_exp
log_sum_exp
Numerically stable log( sum( exp(A) ) ).
[ "Numerically", "stable", "log(", "sum(", "exp(A)", ")", ")." ]
def log_sum_exp(x, axis=None, keepdims=False): x_max = T.max(x, axis=axis, keepdims=True) y = T.log(T.sum(T.exp(x - x_max), axis=axis, keepdims=True)) + x_max y = T.sum(y, axis=axis, keepdims=keepdims) return y
['def', 'log_sum_exp(x,', 'axis=None,', 'keepdims=False):', 'x_max', '=', 'T.max(x,', 'axis=axis,', 'keepdims=True)', 'y', '=', 'T.log(T.sum(T.exp(x', '-', 'x_max),', 'axis=axis,', 'keepdims=True))', '+', 'x_max', 'y', '=', 'T.sum(y,', 'axis=axis,', 'keepdims=keepdims)', 'return', 'y']
434,430
Ruturaj123/Flowchart-Detection
data_utils.py
build_reverse_sequence
build_reverse_sequence
Builds a sequence that is the reverse of the input sequence.
[ "Builds", "a", "sequence", "that", "is", "the", "reverse", "of", "the", "input", "sequence." ]
def build_reverse_sequence(seq): reverse_seq = SequenceWrapper() for timestep in reversed(seq[:-1]): reverse_seq.add_timestep().copy_from(timestep) reverse_seq.add_timestep().copy_from(seq[-1]) return reverse_seq
['def', 'build_reverse_sequence(seq):', 'reverse_seq', '=', 'SequenceWrapper()', 'for', 'timestep', 'in', 'reversed(seq[:-1]):', 'reverse_seq.add_timestep().copy_from(timestep)', 'reverse_seq.add_timestep().copy_from(seq[-1])', 'return', 'reverse_seq']
585,387
openai/baselines
tf_util.py
initialize
initialize
Initialize all the uninitialized variables in the global scope.
[ "Initialize", "all", "the", "uninitialized", "variables", "in", "the", "global", "scope." ]
def initialize(): new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED get_session().run(tf.variables_initializer(new_variables)) ALREADY_INITIALIZED.update(new_variables)
['def', 'initialize():', 'new_variables', '=', 'set(tf.global_variables())', '-', 'ALREADY_INITIALIZED', 'get_session().run(tf.variables_initializer(new_variables))', 'ALREADY_INITIALIZED.update(new_variables)']
94,463
mfbx9da4/neuron-astrocyte-networks
nodes.py
Node.get_value
get_value
This function returns the internal value of the node.
[ "This", "function", "returns", "the", "internal", "value", "of", "the", "node." ]
def get_value(self): return self._value
['def', 'get_value(self):', 'return', 'self._value']
722,971
Layman0527/Parallel-Swin-Transformer-for--
utils.py
get_class_weight
get_class_weight
Get class weight for loss function.
[ "Get", "class", "weight", "for", "loss", "function." ]
def get_class_weight(class_weight): if isinstance(class_weight, str): if class_weight.endswith('.npy'): class_weight = np.load(class_weight) else: class_weight = mmcv.load(class_weight) return class_weight
['def', 'get_class_weight(class_weight):', 'if', 'isinstance(class_weight,', 'str):', 'if', "class_weight.endswith('.npy'):", 'class_weight', '=', 'np.load(class_weight)', 'else:', 'class_weight', '=', 'mmcv.load(class_weight)', 'return', 'class_weight']
764,331
Ruturaj123/Flowchart-Detection
curses_ui_test.py
CursesTest.testDisplayTensorWithIndices
testDisplayTensorWithIndices
Test displaying tensor with indices.
[ "Test", "displaying", "tensor", "with", "indices." ]
def testDisplayTensorWithIndices(self): ui = MockCursesUI(9, 80, command_sequence=[string_to_codes('print_ones --size 5\n'), [curses.KEY_NPAGE], [curses.KEY_NPAGE], [curses.KEY_NPAGE], [curses.KEY_END], [curses.KEY_NPAGE], [curses.KEY_PPAGE], [curses.KEY_PPAGE], [curses.KEY_PPAGE], [curses.KEY_HOME], [curses.KEY_PP...
['def', 'testDisplayTensorWithIndices(self):', 'ui', '=', 'MockCursesUI(9,', '80,', "command_sequence=[string_to_codes('print_ones", '--size', "5\\n'),", '[curses.KEY_NPAGE],', '[curses.KEY_NPAGE],', '[curses.KEY_NPAGE],', '[curses.KEY_END],', '[curses.KEY_NPAGE],', '[curses.KEY_PPAGE],', '[curses.KEY_PPAGE],', '[curse...
605,045
klb3713/cw_word_embedding
movingaverage.py
MovingAverage.add
add
Add value v to the moving average.
[ "Add", "value", "v", "to", "the", "moving", "average." ]
def add(self, v): self.cnt += 1 self.mean = self.mean - 2.0 / self.cnt * (self.mean - v) this_variance = (v - self.mean) * (v - self.mean) self.variance = self.variance - 2.0 / self.cnt * (self.variance - this_variance)
['def', 'add(self,', 'v):', 'self.cnt', '+=', '1', 'self.mean', '=', 'self.mean', '-', '2.0', '/', 'self.cnt', '*', '(self.mean', '-', 'v)', 'this_variance', '=', '(v', '-', 'self.mean)', '*', '(v', '-', 'self.mean)', 'self.variance', '=', 'self.variance', '-', '2.0', '/', 'self.cnt', '*', '(self.variance', '-', 'this_...
524,402
googleapis/python-aiplatform
grpc.py
PipelineServiceGrpcTransport.create_channel
create_channel
Create and return a gRPC channel object.
[ "Create", "and", "return", "a", "gRPC", "channel", "object." ]
def create_channel(cls, host: str='aiplatform.googleapis.com', credentials: Optional[ga_credentials.Credentials]=None, credentials_file: Optional[str]=None, scopes: Optional[Sequence[str]]=None, quota_project_id: Optional[str]=None, **kwargs) -> grpc.Channel: return grpc_helpers.create_channel(host, credentials=cre...
['def', 'create_channel(cls,', 'host:', "str='aiplatform.googleapis.com',", 'credentials:', 'Optional[ga_credentials.Credentials]=None,', 'credentials_file:', 'Optional[str]=None,', 'scopes:', 'Optional[Sequence[str]]=None,', 'quota_project_id:', 'Optional[str]=None,', '**kwargs)', '->', 'grpc.Channel:', 'return', 'grp...
811,598
loyalzc/transfer_learning
retrain.py
add_evaluation_step
add_evaluation_step
Inserts the operations we need to evaluate the accuracy of our results.
[ "Inserts", "the", "operations", "we", "need", "to", "evaluate", "the", "accuracy", "of", "our", "results." ]
def add_evaluation_step(result_tensor, ground_truth_tensor): with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): prediction = tf.argmax(result_tensor, 1) correct_prediction = tf.equal(prediction, tf.argmax(ground_truth_tensor, 1)) with tf.name_scope('acc...
['def', 'add_evaluation_step(result_tensor,', 'ground_truth_tensor):', 'with', "tf.name_scope('accuracy'):", 'with', "tf.name_scope('correct_prediction'):", 'prediction', '=', 'tf.argmax(result_tensor,', '1)', 'correct_prediction', '=', 'tf.equal(prediction,', 'tf.argmax(ground_truth_tensor,', '1))', 'with', "tf.name_s...
905,336
boostcampaitech2/semantic-segmentation-level2-cv-07
inference.py
show_result_pyplot
show_result_pyplot
Visualize the detection results on the image.
[ "Visualize", "the", "detection", "results", "on", "the", "image." ]
def show_result_pyplot(model, img, result, score_thr=0.3, title='result', wait_time=0): if hasattr(model, 'module'): model = model.module model.show_result(img, result, score_thr=score_thr, show=True, wait_time=wait_time, win_name=title, bbox_color=(72, 101, 241), text_color=(72, 101, 241))
['def', 'show_result_pyplot(model,', 'img,', 'result,', 'score_thr=0.3,', "title='result',", 'wait_time=0):', 'if', 'hasattr(model,', "'module'):", 'model', '=', 'model.module', 'model.show_result(img,', 'result,', 'score_thr=score_thr,', 'show=True,', 'wait_time=wait_time,', 'win_name=title,', 'bbox_color=(72,', '101,...
856,744
zihuitang/medical_AI_platform
ftplib.py
FTP.transfercmd
transfercmd
Like ntransfercmd() but returns only the socket.
[ "Like", "ntransfercmd()", "but", "returns", "only", "the", "socket." ]
def transfercmd(self, cmd, rest=None): return self.ntransfercmd(cmd, rest)[0]
['def', 'transfercmd(self,', 'cmd,', 'rest=None):', 'return', 'self.ntransfercmd(cmd,', 'rest)[0]']
280,404
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
test_dtype.py
TestRecord.test_equivalent_record
test_equivalent_record
Test whether equivalent record dtypes hash the same.
[ "Test", "whether", "equivalent", "record", "dtypes", "hash", "the", "same." ]
def test_equivalent_record(self): a = np.dtype([('yo', int)]) b = np.dtype([('yo', int)]) assert_dtype_equal(a, b)
['def', 'test_equivalent_record(self):', 'a', '=', "np.dtype([('yo',", 'int)])', 'b', '=', "np.dtype([('yo',", 'int)])', 'assert_dtype_equal(a,', 'b)']
966,476
NVIDIA-Omniverse/IsaacGymEnvs
adr_vec_task.py
ADRVecTask.recycle_envs
recycle_envs
Recycle the workers that have finished their episodes or to be reassigned etc.
[ "Recycle", "the", "workers", "that", "have", "finished", "their", "episodes", "or", "to", "be", "reassigned", "etc." ]
def recycle_envs(self, recycle_envs): worker_types_rand = torch.rand(len(recycle_envs), device=self.device, dtype=torch.float) new_worker_types = torch.zeros(len(recycle_envs), device=self.device, dtype=torch.long) new_worker_types[worker_types_rand < self.worker_adr_boundary_fraction] = RolloutWorkerModes....
['def', 'recycle_envs(self,', 'recycle_envs):', 'worker_types_rand', '=', 'torch.rand(len(recycle_envs),', 'device=self.device,', 'dtype=torch.float)', 'new_worker_types', '=', 'torch.zeros(len(recycle_envs),', 'device=self.device,', 'dtype=torch.long)', 'new_worker_types[worker_types_rand', '<', 'self.worker_adr_bound...
246,633
gunthercox/ChatterBot
filters.py
do_last
do_last
Return the last item of a sequence.
[ "Return", "the", "last", "item", "of", "a", "sequence." ]
def do_last(environment, seq): try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined('No last item, sequence was empty.')
['def', 'do_last(environment,', 'seq):', 'try:', 'return', 'next(iter(reversed(seq)))', 'except', 'StopIteration:', 'return', "environment.undefined('No", 'last', 'item,', 'sequence', 'was', "empty.')"]
479,155
UWARG/computer-vision-python
queue_proxy_wrapper.py
QueueProxyWrapper.fill_and_drain_queue
fill_and_drain_queue
Fill with sentinel and then drain.
[ "Fill", "with", "sentinel", "and", "then", "drain." ]
def fill_and_drain_queue(self): self.fill_queue_with_sentinel() time.sleep(self.__QUEUE_DELAY) self.drain_queue()
['def', 'fill_and_drain_queue(self):', 'self.fill_queue_with_sentinel()', 'time.sleep(self.__QUEUE_DELAY)', 'self.drain_queue()']
470,526
google-research/scenic
nn_ops.py
patch_image
patch_image
Applies patching operation on the input.
[ "Applies", "patching", "operation", "on", "the", "input." ]
def patch_image(inputs, inputs_shape, patch_size, strides=None, padding='VALID', mode='i2p'): strides = strides or patch_size def i2p(x): return extract_image_patches(lhs=x.astype(jnp.float64), rhs_shape=(1,) + patch_size + (1,), strides=(1,) + strides + (1,), padding=padding, rhs_dilation=(1,) * input...
['def', 'patch_image(inputs,', 'inputs_shape,', 'patch_size,', 'strides=None,', "padding='VALID',", "mode='i2p'):", 'strides', '=', 'strides', 'or', 'patch_size', 'def', 'i2p(x):', 'return', 'extract_image_patches(lhs=x.astype(jnp.float64),', 'rhs_shape=(1,)', '+', 'patch_size', '+', '(1,),', 'strides=(1,)', '+', 'stri...
846,265
zomux/deepy
tutorial2.py
MyJointTrainingModel.prepare
prepare
All codes that create parameters should be put into 'setup' function.
[ "All", "codes", "that", "create", "parameters", "should", "be", "put", "into", "'setup'", "function." ]
def prepare(self): self.output_dim = 10 self.encoder = Chain(self.input_dim).stack(Dense(self.internal_layer_size, 'tanh')) self.decoder = Chain(self.internal_layer_size).stack(Dense(self.input_dim)) self.classifier = Chain(self.internal_layer_size).stack(Dense(50, 'tanh'), Dense(self.output_dim), Softm...
['def', 'prepare(self):', 'self.output_dim', '=', '10', 'self.encoder', '=', 'Chain(self.input_dim).stack(Dense(self.internal_layer_size,', "'tanh'))", 'self.decoder', '=', 'Chain(self.internal_layer_size).stack(Dense(self.input_dim))', 'self.classifier', '=', 'Chain(self.internal_layer_size).stack(Dense(50,', "'tanh')...
181,028
luisespino/artificial_intelligence
tarfile.py
_FileInFile.read
read
Read data from the file.
[ "Read", "data", "from", "the", "file." ]
def read(self, size=None): if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b'' while size > 0: while True: (data, start, stop, offset) = self.map[self.map_index] if start <= self.position < stop: ...
['def', 'read(self,', 'size=None):', 'if', 'size', 'is', 'None:', 'size', '=', 'self.size', '-', 'self.position', 'else:', 'size', '=', 'min(size,', 'self.size', '-', 'self.position)', 'buf', '=', "b''", 'while', 'size', '>', '0:', 'while', 'True:', '(data,', 'start,', 'stop,', 'offset)', '=', 'self.map[self.map_index]...
148,680
muhanzhang/D-VAE
test_conv.py
TestConv2D.test_shape_Constant_tensor
test_shape_Constant_tensor
Tests convolution where the {image,filter}_shape is a Constant tensor.
[ "Tests", "convolution", "where", "the", "{image,filter}_shape", "is", "a", "Constant", "tensor." ]
def test_shape_Constant_tensor(self): as_t = T.as_tensor_variable self.validate((as_t(3), as_t(2), as_t(7), as_t(5)), (5, 2, 2, 3), 'valid') self.validate(as_t([3, 2, 7, 5]), (5, 2, 2, 3), 'valid') self.validate(as_t((3, 2, 7, 5)), (5, 2, 2, 3), 'valid') self.validate((3, 2, 7, 5), (as_t(5), as_t(2)...
['def', 'test_shape_Constant_tensor(self):', 'as_t', '=', 'T.as_tensor_variable', 'self.validate((as_t(3),', 'as_t(2),', 'as_t(7),', 'as_t(5)),', '(5,', '2,', '2,', '3),', "'valid')", 'self.validate(as_t([3,', '2,', '7,', '5]),', '(5,', '2,', '2,', '3),', "'valid')", 'self.validate(as_t((3,', '2,', '7,', '5)),', '(5,',...
525,741
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
preprocessing.py
pad_200
pad_200
Returns an image padded width-padded with 200 pixels.
[ "Returns", "an", "image", "padded", "width-padded", "with", "200", "pixels." ]
def pad_200(image): shape = tf.shape(image) image = tf.image.pad_to_bounding_box(image, 0, 200, shape[0], shape[1] + 400) shape = tf.shape(image) new_shape = tf.minimum(shape[0], shape[1]) offset_y = tf.maximum(shape[0] - shape[1], 0) // 2 offset_x = tf.maximum(shape[1] - shape[0], 0) // 2 i...
['def', 'pad_200(image):', 'shape', '=', 'tf.shape(image)', 'image', '=', 'tf.image.pad_to_bounding_box(image,', '0,', '200,', 'shape[0],', 'shape[1]', '+', '400)', 'shape', '=', 'tf.shape(image)', 'new_shape', '=', 'tf.minimum(shape[0],', 'shape[1])', 'offset_y', '=', 'tf.maximum(shape[0]', '-', 'shape[1],', '0)', '//...
29,410
surafelml/adapt-mnmt
decoder.py
Decoder.decode_from_inputs
decode_from_inputs
Decodes from full inputs.
[ "Decodes", "from", "full", "inputs." ]
def decode_from_inputs(self, inputs, sequence_length, initial_state=None, mode=tf.estimator.ModeKeys.TRAIN, memory=None, memory_sequence_length=None): raise NotImplementedError()
['def', 'decode_from_inputs(self,', 'inputs,', 'sequence_length,', 'initial_state=None,', 'mode=tf.estimator.ModeKeys.TRAIN,', 'memory=None,', 'memory_sequence_length=None):', 'raise', 'NotImplementedError()']
407,765
ShuLiu1993/PANet
boxes.py
xywh_to_xyxy
xywh_to_xyxy
Convert [x1 y1 w h] box format to [x1 y1 x2 y2] format.
[ "Convert", "[x1", "y1", "w", "h]", "box", "format", "to", "[x1", "y1", "x2", "y2]", "format." ]
def xywh_to_xyxy(xywh): if isinstance(xywh, (list, tuple)): assert len(xywh) == 4 (x1, y1) = (xywh[0], xywh[1]) x2 = x1 + np.maximum(0.0, xywh[2] - 1.0) y2 = y1 + np.maximum(0.0, xywh[3] - 1.0) return (x1, y1, x2, y2) elif isinstance(xywh, np.ndarray): return np.h...
['def', 'xywh_to_xyxy(xywh):', 'if', 'isinstance(xywh,', '(list,', 'tuple)):', 'assert', 'len(xywh)', '==', '4', '(x1,', 'y1)', '=', '(xywh[0],', 'xywh[1])', 'x2', '=', 'x1', '+', 'np.maximum(0.0,', 'xywh[2]', '-', '1.0)', 'y2', '=', 'y1', '+', 'np.maximum(0.0,', 'xywh[3]', '-', '1.0)', 'return', '(x1,', 'y1,', 'x2,', ...
778,855
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
data_utils.py
build_lm_sequence
build_lm_sequence
Builds language model sequence from input sequence.
[ "Builds", "language", "model", "sequence", "from", "input", "sequence." ]
def build_lm_sequence(seq): lm_seq = SequenceWrapper() for (i, timestep) in enumerate(seq): if i == len(seq) - 1: lm_seq.add_timestep().set_token(timestep.token).set_label(seq[i].token).set_weight(0.0) else: lm_seq.add_timestep().set_token(timestep.token).set_label(seq[i ...
['def', 'build_lm_sequence(seq):', 'lm_seq', '=', 'SequenceWrapper()', 'for', '(i,', 'timestep)', 'in', 'enumerate(seq):', 'if', 'i', '==', 'len(seq)', '-', '1:', 'lm_seq.add_timestep().set_token(timestep.token).set_label(seq[i].token).set_weight(0.0)', 'else:', 'lm_seq.add_timestep().set_token(timestep.token).set_labe...
14,346
rlpy/rlpy
InfiniteTrackCartPole.py
InfCartPoleSwingUp.s0
s0
Returns the initial state: pendulum straight up and unmoving.
[ "Returns", "the", "initial", "state:", "pendulum", "straight", "up", "and", "unmoving." ]
def s0(self): self.state = np.array([np.pi, 0]) return (self.state.copy(), self.isTerminal(), self.possibleActions())
['def', 's0(self):', 'self.state', '=', 'np.array([np.pi,', '0])', 'return', '(self.state.copy(),', 'self.isTerminal(),', 'self.possibleActions())']
334,121
luisespino/artificial_intelligence
tarfile.py
TarInfo.frombuf
frombuf
Construct a TarInfo object from a 512 byte bytes object.
[ "Construct", "a", "TarInfo", "object", "from", "a", "512", "byte", "bytes", "object." ]
def frombuf(cls, buf, encoding, errors): if len(buf) == 0: raise EmptyHeaderError('empty header') if len(buf) != BLOCKSIZE: raise TruncatedHeaderError('truncated header') if buf.count(NUL) == BLOCKSIZE: raise EOFHeaderError('end of file header') chksum = nti(buf[148:156]) if ...
['def', 'frombuf(cls,', 'buf,', 'encoding,', 'errors):', 'if', 'len(buf)', '==', '0:', 'raise', "EmptyHeaderError('empty", "header')", 'if', 'len(buf)', '!=', 'BLOCKSIZE:', 'raise', "TruncatedHeaderError('truncated", "header')", 'if', 'buf.count(NUL)', '==', 'BLOCKSIZE:', 'raise', "EOFHeaderError('end", 'of', 'file', "...
154,557
sjtu-marl/malib
env.py
Environment.record_episode_info_step
record_episode_info_step
Analyze timestep and record it as episode information.
[ "Analyze", "timestep", "and", "record", "it", "as", "episode", "information." ]
def record_episode_info_step(self, state: Any, observations: Dict[AgentID, Any], rewards: Dict[AgentID, Any], dones: Dict[AgentID, bool], infos: Any): reward_ph = self.episode_metrics['agent_reward'] step_ph = self.episode_metrics['agent_step'] for (aid, r) in rewards.items(): if aid not in reward_p...
['def', 'record_episode_info_step(self,', 'state:', 'Any,', 'observations:', 'Dict[AgentID,', 'Any],', 'rewards:', 'Dict[AgentID,', 'Any],', 'dones:', 'Dict[AgentID,', 'bool],', 'infos:', 'Any):', 'reward_ph', '=', "self.episode_metrics['agent_reward']", 'step_ph', '=', "self.episode_metrics['agent_step']", 'for', '(ai...
627,562
enuguru/artificial_intelligence_and_machine_learning
download.py
url_to_path
url_to_path
Convert a file: URL to a path.
[ "Convert", "a", "file:", "URL", "to", "a", "path." ]
def url_to_path(url): assert url.startswith('file:'), 'You can only turn file: urls into filenames (not %r)' % url path = url[len('file:'):].lstrip('/') path = urllib.unquote(path) if _url_drive_re.match(path): path = path[0] + ':' + path[2:] else: path = '/' + path return path
['def', 'url_to_path(url):', 'assert', "url.startswith('file:'),", "'You", 'can', 'only', 'turn', 'file:', 'urls', 'into', 'filenames', '(not', "%r)'", '%', 'url', 'path', '=', "url[len('file:'):].lstrip('/')", 'path', '=', 'urllib.unquote(path)', 'if', '_url_drive_re.match(path):', 'path', '=', 'path[0]', '+', "':'", ...
134,103
enuguru/artificial_intelligence_and_machine_
text.py
prefix_encode
prefix_encode
Compresses bytestring b as a byte representing the prefix it shares with a, followed by the suffix bytes.
[ "Compresses", "bytestring", "b", "as", "a", "byte", "representing", "the", "prefix", "it", "shares", "with", "a,", "followed", "by", "the", "suffix", "bytes." ]
def prefix_encode(a, b): i = first_diff(a, b) return byte(i) + b[i:]
['def', 'prefix_encode(a,', 'b):', 'i', '=', 'first_diff(a,', 'b)', 'return', 'byte(i)', '+', 'b[i:]']
162,806
huawei-noah/xingtian
get_xt_config.py
get_xt_benchmark_config
get_xt_benchmark_config
Get xt benchmark information from config files.
[ "Get", "xt", "benchmark", "information", "from", "config", "files." ]
def get_xt_benchmark_config(yaml_obj, default_bm_id=bm_conf.default_id): benchmark_id = yaml_obj.get('benchmark', dict()).get('id', default_bm_id) alg_name = yaml_obj.get('alg_para', dict()).get('alg_name') if not alg_name: raise KeyError("config: {} invalid, can't get 'alg_name'! ".format(yaml_obj)...
['def', 'get_xt_benchmark_config(yaml_obj,', 'default_bm_id=bm_conf.default_id):', 'benchmark_id', '=', "yaml_obj.get('benchmark',", "dict()).get('id',", 'default_bm_id)', 'alg_name', '=', "yaml_obj.get('alg_para',", "dict()).get('alg_name')", 'if', 'not', 'alg_name:', 'raise', 'KeyError("config:', '{}', 'invalid,', "c...
962,416
tinazhouhui/computer_vision
sast_process.py
SASTProcessTrain.theta_line_cross_point
theta_line_cross_point
Calculate the line through given point and angle in ax + by + c =0 form.
[ "Calculate", "the", "line", "through", "given", "point", "and", "angle", "in", "ax", "+", "by", "+", "c", "=0", "form." ]
def theta_line_cross_point(self, theta, point): (x, y) = point cos = np.cos(theta) sin = np.sin(theta) return [sin, -cos, cos * y - sin * x]
['def', 'theta_line_cross_point(self,', 'theta,', 'point):', '(x,', 'y)', '=', 'point', 'cos', '=', 'np.cos(theta)', 'sin', '=', 'np.sin(theta)', 'return', '[sin,', '-cos,', 'cos', '*', 'y', '-', 'sin', '*', 'x]']
502,078
zihuitang/medical_AI_platform
msvccompiler.py
read_keys
read_keys
Return list of registry keys.
[ "Return", "list", "of", "registry", "keys." ]
def read_keys(base, key): try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while True: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i += 1 return L
['def', 'read_keys(base,', 'key):', 'try:', 'handle', '=', 'RegOpenKeyEx(base,', 'key)', 'except', 'RegError:', 'return', 'None', 'L', '=', '[]', 'i', '=', '0', 'while', 'True:', 'try:', 'k', '=', 'RegEnumKey(handle,', 'i)', 'except', 'RegError:', 'break', 'L.append(k)', 'i', '+=', '1', 'return', 'L']
282,263
datduong/NLPMethods2CompareGOterms
helper.py
batchify
batchify
Transform data into batches.
[ "Transform", "data", "into", "batches." ]
def batchify(data, bsz): batched_data = [] for i in range(len(data)): if i % bsz == 0: batched_data.append([data[i]]) else: batched_data[len(batched_data) - 1].append(data[i]) return batched_data
['def', 'batchify(data,', 'bsz):', 'batched_data', '=', '[]', 'for', 'i', 'in', 'range(len(data)):', 'if', 'i', '%', 'bsz', '==', '0:', 'batched_data.append([data[i]])', 'else:', 'batched_data[len(batched_data)', '-', '1].append(data[i])', 'return', 'batched_data']
731,575
weimin17/Object-Detection_HelmetDetection
attention_layer.py
Attention.call
call
Apply attention mechanism to x and y.
[ "Apply", "attention", "mechanism", "to", "x", "and", "y." ]
def call(self, x, y, bias, cache=None): q = self.q_dense_layer(x) k = self.k_dense_layer(y) v = self.v_dense_layer(y) if cache is not None: k = tf.concat([cache['k'], k], axis=1) v = tf.concat([cache['v'], v], axis=1) cache['k'] = k cache['v'] = v q = self.split_heads...
['def', 'call(self,', 'x,', 'y,', 'bias,', 'cache=None):', 'q', '=', 'self.q_dense_layer(x)', 'k', '=', 'self.k_dense_layer(y)', 'v', '=', 'self.v_dense_layer(y)', 'if', 'cache', 'is', 'not', 'None:', 'k', '=', "tf.concat([cache['k'],", 'k],', 'axis=1)', 'v', '=', "tf.concat([cache['v'],", 'v],', 'axis=1)', "cache['k']...
761,200
KangboLu/Natural-Language-Processing
topicrank.py
TopicRank.candidate_selection
candidate_selection
Selects longest sequences of nouns and adjectives as keyphrase candidates.
[ "Selects", "longest", "sequences", "of", "nouns", "and", "adjectives", "as", "keyphrase", "candidates." ]
def candidate_selection(self, pos=None, stoplist=None): if pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} self.longest_pos_sequence_selection(valid_pos=pos) if stoplist is None: stoplist = self.stoplist self.candidate_filtering(stoplist=list(string.punctuation) + ['-lrb-', '-rrb-', '-lcb-',...
['def', 'candidate_selection(self,', 'pos=None,', 'stoplist=None):', 'if', 'pos', 'is', 'None:', 'pos', '=', "{'NOUN',", "'PROPN',", "'ADJ'}", 'self.longest_pos_sequence_selection(valid_pos=pos)', 'if', 'stoplist', 'is', 'None:', 'stoplist', '=', 'self.stoplist', 'self.candidate_filtering(stoplist=list(string.punctuati...
661,229
greydanus/mr_london
pildriver.py
PILDriver.do_add
do_add
usage: add <image:pic1> <image:pic2> <int:offset> <float:scale> Pop the two top images, produce the scaled sum with offset.
[ "usage:", "add", "<image:pic1>", "<image:pic2>", "<int:offset>", "<float:scale>", "Pop", "the", "two", "top", "images,", "produce", "the", "scaled", "sum", "with", "offset." ]
def do_add(self): from PIL import ImageChops image1 = self.do_pop() image2 = self.do_pop() scale = float(self.do_pop()) offset = int(self.do_pop()) self.push(ImageChops.add(image1, image2, scale, offset))
['def', 'do_add(self):', 'from', 'PIL', 'import', 'ImageChops', 'image1', '=', 'self.do_pop()', 'image2', '=', 'self.do_pop()', 'scale', '=', 'float(self.do_pop())', 'offset', '=', 'int(self.do_pop())', 'self.push(ImageChops.add(image1,', 'image2,', 'scale,', 'offset))']
241,766
Qbanxiaoxu/NaturalLanguageProcessingExperiment
operator.py
is_
is_
Same as a is b.
[ "Same", "as", "a", "is", "b." ]
def is_(a, b): return a is b
['def', 'is_(a,', 'b):', 'return', 'a', 'is', 'b']
801,542
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_input.py
inputs
inputs
Construct input for CIFAR evaluation using the Reader ops.
[ "Construct", "input", "for", "CIFAR", "evaluation", "using", "the", "Reader", "ops." ]
def inputs(eval_data, data_dir, batch_size): if not eval_data: filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) for i in xrange(1, 6)] num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN else: filenames = [os.path.join(data_dir, 'test_batch.bin')] num_examples_p...
['def', 'inputs(eval_data,', 'data_dir,', 'batch_size):', 'if', 'not', 'eval_data:', 'filenames', '=', '[os.path.join(data_dir,', "'data_batch_%d.bin'", '%', 'i)', 'for', 'i', 'in', 'xrange(1,', '6)]', 'num_examples_per_epoch', '=', 'NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN', 'else:', 'filenames', '=', '[os.path.join(data_dir,...
30,269
tonybeltramelli/Graphics-And-Vision
OpenCV3D.py
OpenCV3D.Image
Image
Get the last processed image.
[ "Get", "the", "last", "processed", "image." ]
def Image(self): return self.__image
['def', 'Image(self):', 'return', 'self.__image']
580,650
Ruturaj123/Flowchart-Detection
tfexample_decoder.py
TFExampleDecoder.decode
decode
Decodes the given serialized TF-example.
[ "Decodes", "the", "given", "serialized", "TF-example." ]
def decode(self, serialized_example, items=None): example = parsing_ops.parse_single_example(serialized_example, self._keys_to_features) for k in sorted(self._keys_to_features): v = self._keys_to_features[k] if isinstance(v, parsing_ops.FixedLenFeature): example[k] = array_ops.reshap...
['def', 'decode(self,', 'serialized_example,', 'items=None):', 'example', '=', 'parsing_ops.parse_single_example(serialized_example,', 'self._keys_to_features)', 'for', 'k', 'in', 'sorted(self._keys_to_features):', 'v', '=', 'self._keys_to_features[k]', 'if', 'isinstance(v,', 'parsing_ops.FixedLenFeature):', 'example[k...
604,491
enuguru/artificial_intelligence_and_machine_learning
__init__.py
VersionControl.parse_vcs_bundle_file
parse_vcs_bundle_file
Takes the contents of the bundled text file that explains how to revert the stripped off version control data of the given package and returns the URL and revision of it.
[ "Takes", "the", "contents", "of", "the", "bundled", "text", "file", "that", "explains", "how", "to", "revert", "the", "stripped", "off", "version", "control", "data", "of", "the", "given", "package", "and", "returns", "the", "URL", "and", "revision", "of", ...
def parse_vcs_bundle_file(self, content): raise NotImplementedError
['def', 'parse_vcs_bundle_file(self,', 'content):', 'raise', 'NotImplementedError']
130,787
weimin17/Object-Detection_HelmetDetection
ops.py
fixed_padding
fixed_padding
Pads the input along the spatial dimensions independently of input size.
[ "Pads", "the", "input", "along", "the", "spatial", "dimensions", "independently", "of", "input", "size." ]
def fixed_padding(inputs, kernel_size, rate=1): kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1) pad_total = kernel_size_effective - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]) ...
['def', 'fixed_padding(inputs,', 'kernel_size,', 'rate=1):', 'kernel_size_effective', '=', 'kernel_size', '+', '(kernel_size', '-', '1)', '*', '(rate', '-', '1)', 'pad_total', '=', 'kernel_size_effective', '-', '1', 'pad_beg', '=', 'pad_total', '//', '2', 'pad_end', '=', 'pad_total', '-', 'pad_beg', 'padded_inputs', '=...
752,337
aleju/computer-vision-algorithms
harris.py
harris_ones
harris_ones
Calculate the harris score based on a window function of diagonal ones.
[ "Calculate", "the", "harris", "score", "based", "on", "a", "window", "function", "of", "diagonal", "ones." ]
def harris_ones(img, window_size, k=0.05): img = skiutil.img_as_float(img) (imgy, imgx) = np.gradient(img) imgxy = imgx * imgy imgxx = imgx ** 2 imgyy = imgy ** 2 window = np.ones((window_size, window_size)) a11 = signal.correlate(imgxx, window, mode='same') / window_size a12 = signal.co...
['def', 'harris_ones(img,', 'window_size,', 'k=0.05):', 'img', '=', 'skiutil.img_as_float(img)', '(imgy,', 'imgx)', '=', 'np.gradient(img)', 'imgxy', '=', 'imgx', '*', 'imgy', 'imgxx', '=', 'imgx', '**', '2', 'imgyy', '=', 'imgy', '**', '2', 'window', '=', 'np.ones((window_size,', 'window_size))', 'a11', '=', 'signal.c...
467,555
43Carrig/recurrent_neural_networks_practice
misc.py
dist_in_usersite
dist_in_usersite
Return True if given Distribution is installed in user site.
[ "Return", "True", "if", "given", "Distribution", "is", "installed", "in", "user", "site." ]
def dist_in_usersite(dist): norm_path = normalize_path(dist_location(dist)) return norm_path.startswith(normalize_path(user_site))
['def', 'dist_in_usersite(dist):', 'norm_path', '=', 'normalize_path(dist_location(dist))', 'return', 'norm_path.startswith(normalize_path(user_site))']
311,370
omarmhaimdat/twitter_nlp_native_swift
fix_annotations.py
FixAnnotations.transform
transform
This just strips annotations from the funcdef completely.
[ "This", "just", "strips", "annotations", "from", "the", "funcdef", "completely." ]
def transform(self, node, results): params = results.get(u'params') ret = results.get(u'ret') if ret is not None: assert ret.prev_sibling.type == token.RARROW, u'Invalid return annotation' self.warn_once(node, reason=warning_text) ret.prev_sibling.remove() ret.remove() if...
['def', 'transform(self,', 'node,', 'results):', 'params', '=', "results.get(u'params')", 'ret', '=', "results.get(u'ret')", 'if', 'ret', 'is', 'not', 'None:', 'assert', 'ret.prev_sibling.type', '==', 'token.RARROW,', "u'Invalid", 'return', "annotation'", 'self.warn_once(node,', 'reason=warning_text)', 'ret.prev_siblin...
954,104
zhuye98/ICL
config.py
get_config
get_config
Get a yacs CfgNode object with default values.
[ "Get", "a", "yacs", "CfgNode", "object", "with", "default", "values." ]
def get_config(args): config = _C.clone() update_config(config, args) return config
['def', 'get_config(args):', 'config', '=', '_C.clone()', 'update_config(config,', 'args)', 'return', 'config']
228,940
PaddlePaddle/Paddle3D
hungarian_assigner.py
nan_to_num
nan_to_num
Replaces NaN, positive infinity, and negative infinity values in input tensor.
[ "Replaces", "NaN,", "positive", "infinity,", "and", "negative", "infinity", "values", "in", "input", "tensor." ]
def nan_to_num(x, nan=0.0, posinf=None, neginf=None, name=None): posinf_value = paddle.full_like(x, float('+inf')) neginf_value = paddle.full_like(x, float('-inf')) nan = paddle.full_like(x, nan) assert x.dtype in [paddle.float16, paddle.float32, paddle.float64] if posinf is None: if x.dtype...
['def', 'nan_to_num(x,', 'nan=0.0,', 'posinf=None,', 'neginf=None,', 'name=None):', 'posinf_value', '=', 'paddle.full_like(x,', "float('+inf'))", 'neginf_value', '=', 'paddle.full_like(x,', "float('-inf'))", 'nan', '=', 'paddle.full_like(x,', 'nan)', 'assert', 'x.dtype', 'in', '[paddle.float16,', 'paddle.float32,', 'pa...
777,720
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
feature_extractor.py
DelfFeaturePostProcessing
DelfFeaturePostProcessing
Extract DELF features from input image.
[ "Extract", "DELF", "features", "from", "input", "image." ]
def DelfFeaturePostProcessing(boxes, descriptors, config): locations = CalculateKeypointCenters(boxes) with tf.variable_scope('postprocess'): final_descriptors = tf.nn.l2_normalize(descriptors, dim=1, name='l2_normalization') if config.delf_local_config.use_pca: pca_mean = tf.constan...
['def', 'DelfFeaturePostProcessing(boxes,', 'descriptors,', 'config):', 'locations', '=', 'CalculateKeypointCenters(boxes)', 'with', "tf.variable_scope('postprocess'):", 'final_descriptors', '=', 'tf.nn.l2_normalize(descriptors,', 'dim=1,', "name='l2_normalization')", 'if', 'config.delf_local_config.use_pca:', 'pca_mea...
47,485
guenthermi/table-embeddings
random_forest_classifier.py
RFClassifier.evaluate
evaluate
Applies the classifier on the test set and returns the predition and the accuracy value.
[ "Applies", "the", "classifier", "on", "the", "test", "set", "and", "returns", "the", "predition", "and", "the", "accuracy", "value." ]
def evaluate(self, test_ids, labels): pred = self.rf_classifier.predict_proba(self.features) results = pred[np.array(test_ids.asnumpy(), dtype=int)] indices = np.argmax(results, axis=1) labels = labels.asnumpy() print(Counter(indices)) correct = sum(indices == labels) acc = correct * 1.0 / l...
['def', 'evaluate(self,', 'test_ids,', 'labels):', 'pred', '=', 'self.rf_classifier.predict_proba(self.features)', 'results', '=', 'pred[np.array(test_ids.asnumpy(),', 'dtype=int)]', 'indices', '=', 'np.argmax(results,', 'axis=1)', 'labels', '=', 'labels.asnumpy()', 'print(Counter(indices))', 'correct', '=', 'sum(indic...
365,129
arshpreetsingh/quantopian-machinelearning
pyparsing.py
ParseResults.copy
copy
Returns a new copy of a :class:`ParseResults` object.
[ "Returns", "a", "new", "copy", "of", "a", ":class:`ParseResults`", "object." ]
def copy(self): ret = ParseResults(self.__toklist) ret.__tokdict = dict(self.__tokdict.items()) ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name return ret
['def', 'copy(self):', 'ret', '=', 'ParseResults(self.__toklist)', 'ret.__tokdict', '=', 'dict(self.__tokdict.items())', 'ret.__parent', '=', 'self.__parent', 'ret.__accumNames.update(self.__accumNames)', 'ret.__name', '=', 'self.__name', 'return', 'ret']
891,400
tobegit3hub/deep_image_model
util.py
get_tensors
get_tensors
get all the tensors which are input or output of an op in the graph.
[ "get", "all", "the", "tensors", "which", "are", "input", "or", "output", "of", "an", "op", "in", "the", "graph." ]
def get_tensors(graph): if not isinstance(graph, tf_ops.Graph): raise TypeError('Expected a graph, got: {}'.format(type(graph))) ts = [] for op in graph.get_operations(): ts += op.outputs return ts
['def', 'get_tensors(graph):', 'if', 'not', 'isinstance(graph,', 'tf_ops.Graph):', 'raise', "TypeError('Expected", 'a', 'graph,', 'got:', "{}'.format(type(graph)))", 'ts', '=', '[]', 'for', 'op', 'in', 'graph.get_operations():', 'ts', '+=', 'op.outputs', 'return', 'ts']
181,405
kubeflow/pipelines
_pipeline.py
Pipeline.add_op
add_op
Add a new operator.
[ "Add", "a", "new", "operator." ]
def add_op(self, op: _container_op.BaseOp, define_only: bool): op_name = _naming._sanitize_python_function_name(op.human_name).replace('_', '-') op_name = _naming._make_name_unique_by_adding_index(op_name, list(self.ops.keys()), '-') if op_name == '': op_name = _naming._make_name_unique_by_adding_in...
['def', 'add_op(self,', 'op:', '_container_op.BaseOp,', 'define_only:', 'bool):', 'op_name', '=', "_naming._sanitize_python_function_name(op.human_name).replace('_',", "'-')", 'op_name', '=', '_naming._make_name_unique_by_adding_index(op_name,', 'list(self.ops.keys()),', "'-')", 'if', 'op_name', '==', "'':", 'op_name',...
780,172
bislara/Object-detection-GUI
preprocessor_test.py
PreprocessorTest.testScaleBoxesToPixelCoordinatesWithKeypoints
testScaleBoxesToPixelCoordinatesWithKeypoints
Tests box and keypoint scaling, checking scaled values.
[ "Tests", "box", "and", "keypoint", "scaling,", "checking", "scaled", "values." ]
def testScaleBoxesToPixelCoordinatesWithKeypoints(self): in_shape = [60, 40, 3] in_boxes = self.createTestBoxes() in_keypoints = self.createTestKeypoints() expected_boxes = [[0.0, 10.0, 45.0, 40.0], [15.0, 20.0, 45.0, 40.0]] expected_keypoints = [[[6.0, 4.0], [12.0, 8.0], [18.0, 12.0]], [[24.0, 16.0...
['def', 'testScaleBoxesToPixelCoordinatesWithKeypoints(self):', 'in_shape', '=', '[60,', '40,', '3]', 'in_boxes', '=', 'self.createTestBoxes()', 'in_keypoints', '=', 'self.createTestKeypoints()', 'expected_boxes', '=', '[[0.0,', '10.0,', '45.0,', '40.0],', '[15.0,', '20.0,', '45.0,', '40.0]]', 'expected_keypoints', '='...
726,563
danamyu/hedgehog_detector
real_nvp_utils.py
standard_normal_ll
standard_normal_ll
Log-likelihood of standard Gaussian distribution.
[ "Log-likelihood", "of", "standard", "Gaussian", "distribution." ]
def standard_normal_ll(input_): res = -0.5 * (tf.square(input_) + numpy.log(2.0 * numpy.pi)) return res
['def', 'standard_normal_ll(input_):', 'res', '=', '-0.5', '*', '(tf.square(input_)', '+', 'numpy.log(2.0', '*', 'numpy.pi))', 'return', 'res']
590,321
PaddlePaddle/PaddleSpeech
utility.py
rms_to_db
rms_to_db
Root Mean Square to dB.
[ "Root", "Mean", "Square", "to", "dB." ]
def rms_to_db(rms: float): return 20.0 * math.log10(max(1e-16, rms))
['def', 'rms_to_db(rms:', 'float):', 'return', '20.0', '*', 'math.log10(max(1e-16,', 'rms))']
276,496
jindongwang/transferlearning
ResNet.py
resnet50
resnet50
Constructs a ResNet-50 model.
[ "Constructs", "a", "ResNet-50", "model." ]
def resnet50(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
['def', 'resnet50(pretrained=False,', '**kwargs):', 'model', '=', 'ResNet(Bottleneck,', '[3,', '4,', '6,', '3],', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))", 'return', 'model']
904,531
xiongfengyan/gcnn
models.py
gcnn.logitsvalue
logitsvalue
Return the logits values.
[ "Return", "the", "logits", "values." ]
def logitsvalue(self, logits): with tf.name_scope('prediction'): probabilities = tf.nn.softmax(logits) prediction = tf.argmax(logits, axis=1) return (probabilities, prediction)
['def', 'logitsvalue(self,', 'logits):', 'with', "tf.name_scope('prediction'):", 'probabilities', '=', 'tf.nn.softmax(logits)', 'prediction', '=', 'tf.argmax(logits,', 'axis=1)', 'return', '(probabilities,', 'prediction)']
201,364