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
RajanPatel97/Generating-Paintings-Using-Generative--
wikiart.py
get_split
get_split
Gets a dataset tuple with instructions for reading flowers.
[ "Gets", "a", "dataset", "tuple", "with", "instructions", "for", "reading", "flowers." ]
def get_split(split_name, dataset_dir, file_pattern=None, reader=None): if split_name not in SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_nam...
['def', 'get_split(split_name,', 'dataset_dir,', 'file_pattern=None,', 'reader=None):', 'if', 'split_name', 'not', 'in', 'SPLITS_TO_SIZES:', 'raise', "ValueError('split", 'name', '%s', 'was', 'not', "recognized.'", '%', 'split_name)', 'if', 'not', 'file_pattern:', 'file_pattern', '=', '_FILE_PATTERN', 'file_pattern', '...
567,853
TrellixVulnTeam/Unsupervised_Learning_HFI7
polar.py
PolarAxes.format_coord
format_coord
Return a format string formatting the coordinate using Unicode characters.
[ "Return", "a", "format", "string", "formatting", "the", "coordinate", "using", "Unicode", "characters." ]
def format_coord(self, theta, r): if theta < 0: theta += 2 * np.pi theta /= np.pi return 'θ=%0.3fπ (%0.3f°), r=%0.3f' % (theta, theta * 180.0, r)
['def', 'format_coord(self,', 'theta,', 'r):', 'if', 'theta', '<', '0:', 'theta', '+=', '2', '*', 'np.pi', 'theta', '/=', 'np.pi', 'return', "'θ=%0.3fπ", '(%0.3f°),', "r=%0.3f'", '%', '(theta,', 'theta', '*', '180.0,', 'r)']
451,226
cts198859/deeprl_network
cacc_env.py
OVMCarFollowing.get_accel
get_accel
Get target acceleration using OVM controller.
[ "Get", "target", "acceleration", "using", "OVM", "controller." ]
def get_accel(self, v, v_lead, h, alpha, beta, h_go=-1): vh = self.get_vh(h, h_go=h_go) return alpha * (vh - v) + beta * (v_lead - v)
['def', 'get_accel(self,', 'v,', 'v_lead,', 'h,', 'alpha,', 'beta,', 'h_go=-1):', 'vh', '=', 'self.get_vh(h,', 'h_go=h_go)', 'return', 'alpha', '*', '(vh', '-', 'v)', '+', 'beta', '*', '(v_lead', '-', 'v)']
180,774
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_main.py
parse_record
parse_record
Parse CIFAR-10 image and label from a raw record.
[ "Parse", "CIFAR-10", "image", "and", "label", "from", "a", "raw", "record." ]
def parse_record(raw_record): label_bytes = 1 image_bytes = _HEIGHT * _WIDTH * _DEPTH record_bytes = label_bytes + image_bytes record_vector = tf.decode_raw(raw_record, tf.uint8) label = tf.cast(record_vector[0], tf.int32) label = tf.one_hot(label, _NUM_CLASSES) depth_major = tf.reshape(reco...
['def', 'parse_record(raw_record):', 'label_bytes', '=', '1', 'image_bytes', '=', '_HEIGHT', '*', '_WIDTH', '*', '_DEPTH', 'record_bytes', '=', 'label_bytes', '+', 'image_bytes', 'record_vector', '=', 'tf.decode_raw(raw_record,', 'tf.uint8)', 'label', '=', 'tf.cast(record_vector[0],', 'tf.int32)', 'label', '=', 'tf.one...
20,090
janluke/cs188
multiagentTestClasses.py
PolyAgent.select
select
Return a sublist of elements given by indices in list.
[ "Return", "a", "sublist", "of", "elements", "given", "by", "indices", "in", "list." ]
def select(self, list, indices): return [list[i] for i in indices]
['def', 'select(self,', 'list,', 'indices):', 'return', '[list[i]', 'for', 'i', 'in', 'indices]']
223,183
43Carrig/recurrent_neural_networks_practice
well_known_types.py
Duration.ToMilliseconds
ToMilliseconds
Converts a Duration to milliseconds.
[ "Converts", "a", "Duration", "to", "milliseconds." ]
def ToMilliseconds(self): millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis
['def', 'ToMilliseconds(self):', 'millis', '=', '_RoundTowardZero(self.nanos,', '_NANOS_PER_MILLISECOND)', 'return', 'self.seconds', '*', '_MILLIS_PER_SECOND', '+', 'millis']
310,013
microsoft/UniSpeech
fairseq_decoder.py
FairseqDecoder.max_positions
max_positions
Maximum input length supported by the decoder.
[ "Maximum", "input", "length", "supported", "by", "the", "decoder." ]
def max_positions(self): return 1000000.0
['def', 'max_positions(self):', 'return', '1000000.0']
378,363
microsoft/InnerEye-DeepLearning
common_util.py
any_smaller_or_equal_than
any_smaller_or_equal_than
Returns True if any of the elements of the list is smaller than the given scalar number.
[ "Returns", "True", "if", "any", "of", "the", "elements", "of", "the", "list", "is", "smaller", "than", "the", "given", "scalar", "number." ]
def any_smaller_or_equal_than(items: Iterable[Any], scalar: float) -> bool: return any((item < scalar for item in items))
['def', 'any_smaller_or_equal_than(items:', 'Iterable[Any],', 'scalar:', 'float)', '->', 'bool:', 'return', 'any((item', '<', 'scalar', 'for', 'item', 'in', 'items))']
612,728
mindsdb/lightwood
tabtransformer.py
TabTransformerMixer.fit
fit
Skip the usual partial_fit call at the end.
[ "Skip", "the", "usual", "partial_fit", "call", "at", "the", "end." ]
def fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None: self._fit(train_data, dev_data)
['def', 'fit(self,', 'train_data:', 'EncodedDs,', 'dev_data:', 'EncodedDs)', '->', 'None:', 'self._fit(train_data,', 'dev_data)']
602,449
facebookresearch/fvcore
jit_handles.py
matmul_flop_jit
matmul_flop_jit
Count flops for matmul.
[ "Count", "flops", "for", "matmul." ]
def matmul_flop_jit(inputs: List[Any], outputs: List[Any]) -> Number: input_shapes = [get_shape(v) for v in inputs] assert len(input_shapes) == 2, input_shapes assert input_shapes[0][-1] == input_shapes[1][-2], input_shapes flop = prod(input_shapes[0]) * input_shapes[-1][-1] return flop
['def', 'matmul_flop_jit(inputs:', 'List[Any],', 'outputs:', 'List[Any])', '->', 'Number:', 'input_shapes', '=', '[get_shape(v)', 'for', 'v', 'in', 'inputs]', 'assert', 'len(input_shapes)', '==', '2,', 'input_shapes', 'assert', 'input_shapes[0][-1]', '==', 'input_shapes[1][-2],', 'input_shapes', 'flop', '=', 'prod(inpu...
565,918
udacity/artificial-intelligence
test_arrayprint.py
TestArray2String.test_format_function
test_format_function
Test custom format function for each element in array.
[ "Test", "custom", "format", "function", "for", "each", "element", "in", "array." ]
def test_format_function(self): def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3) if sys.version_info[0] >= 3: x_hex = '[0x0 0x1 0x2]' x_oct = '[0o0 0o1 0o2]' ...
['def', 'test_format_function(self):', 'def', '_format_function(x):', 'if', 'np.abs(x)', '<', '1:', 'return', "'.'", 'elif', 'np.abs(x)', '<', '2:', 'return', "'o'", 'else:', 'return', "'O'", 'x', '=', 'np.arange(3)', 'if', 'sys.version_info[0]', '>=', '3:', 'x_hex', '=', "'[0x0", '0x1', "0x2]'", 'x_oct', '=', "'[0o0",...
61,048
Feaxure-fresh/TL-Bearing-Fault-Diagnosis
PU.py
get_files
get_files
root: The location of the data set.
[ "root:", "The", "location", "of", "the", "data", "set." ]
def get_files(root): (data, lab) = ([], []) for i in sub_dir_nor: data_normal = os.path.join(root, datasetname[2], i) for item in os.listdir(data_normal): if item.endswith('.mat') and state in item: item_path = os.path.join(data_normal, item) data_load...
['def', 'get_files(root):', '(data,', 'lab)', '=', '([],', '[])', 'for', 'i', 'in', 'sub_dir_nor:', 'data_normal', '=', 'os.path.join(root,', 'datasetname[2],', 'i)', 'for', 'item', 'in', 'os.listdir(data_normal):', 'if', "item.endswith('.mat')", 'and', 'state', 'in', 'item:', 'item_path', '=', 'os.path.join(data_norma...
917,475
ArminMasoumian/GCNDepth
kitti_utils.py
transform_from_rot_trans
transform_from_rot_trans
Transforation matrix from rotation matrix and translation vector.
[ "Transforation", "matrix", "from", "rotation", "matrix", "and", "translation", "vector." ]
def transform_from_rot_trans(R, t): R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
['def', 'transform_from_rot_trans(R,', 't):', 'R', '=', 'R.reshape(3,', '3)', 't', '=', 't.reshape(3,', '1)', 'return', 'np.vstack((np.hstack([R,', 't]),', '[0,', '0,', '0,', '1]))']
567,559
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_to_latex.py
TestToLatexCaptionLabel.caption_longtable
caption_longtable
Caption for longtable LaTeX environment.
[ "Caption", "for", "longtable", "LaTeX", "environment." ]
def caption_longtable(self): return 'a table in a \\texttt{longtable} environment'
['def', 'caption_longtable(self):', 'return', "'a", 'table', 'in', 'a', '\\\\texttt{longtable}', "environment'"]
453,834
PaddlePaddle/PaddleSpeech
log.py
find_log_dir
find_log_dir
Returns the most suitable directory to put log files into.
[ "Returns", "the", "most", "suitable", "directory", "to", "put", "log", "files", "into." ]
def find_log_dir(log_dir=None): if log_dir: dirs = [log_dir] else: dirs = ['/tmp/', './'] for d in dirs: if os.path.isdir(d) and os.access(d, os.W_OK): return d raise FileNotFoundError("Can't find a writable directory for logs, tried %s" % dirs)
['def', 'find_log_dir(log_dir=None):', 'if', 'log_dir:', 'dirs', '=', '[log_dir]', 'else:', 'dirs', '=', "['/tmp/',", "'./']", 'for', 'd', 'in', 'dirs:', 'if', 'os.path.isdir(d)', 'and', 'os.access(d,', 'os.W_OK):', 'return', 'd', 'raise', 'FileNotFoundError("Can\'t', 'find', 'a', 'writable', 'directory', 'for', 'logs,...
277,015
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
image_lsun.py
ImageLsunBedrooms.read_and_convert_to_png
read_and_convert_to_png
Downloads the datasets, extracts from zip and yields in PNG format.
[ "Downloads", "the", "datasets,", "extracts", "from", "zip", "and", "yields", "in", "PNG", "format." ]
def read_and_convert_to_png(self, tmp_dir, split_name): category = 'bedroom' _get_lsun(tmp_dir, category, split_name) filename = _LSUN_DATA_FILENAME % (category, split_name) data_path = os.path.join(tmp_dir, filename) print('Extracting zip file.') zip_ref = zipfile.ZipFile(data_path, 'r') zi...
['def', 'read_and_convert_to_png(self,', 'tmp_dir,', 'split_name):', 'category', '=', "'bedroom'", '_get_lsun(tmp_dir,', 'category,', 'split_name)', 'filename', '=', '_LSUN_DATA_FILENAME', '%', '(category,', 'split_name)', 'data_path', '=', 'os.path.join(tmp_dir,', 'filename)', "print('Extracting", 'zip', "file.')", 'z...
964,895
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
mnist_shift.py
shift_2d
shift_2d
Shifts the image along each axis by introducing zero.
[ "Shifts", "the", "image", "along", "each", "axis", "by", "introducing", "zero." ]
def shift_2d(image, shift, max_shift): max_shift += 1 padded_image = np.pad(image, max_shift, 'constant') rolled_image = np.roll(padded_image, shift[0], axis=0) rolled_image = np.roll(rolled_image, shift[1], axis=1) shifted_image = rolled_image[max_shift:-max_shift, max_shift:-max_shift] return ...
['def', 'shift_2d(image,', 'shift,', 'max_shift):', 'max_shift', '+=', '1', 'padded_image', '=', 'np.pad(image,', 'max_shift,', "'constant')", 'rolled_image', '=', 'np.roll(padded_image,', 'shift[0],', 'axis=0)', 'rolled_image', '=', 'np.roll(rolled_image,', 'shift[1],', 'axis=1)', 'shifted_image', '=', 'rolled_image[m...
53,149
eddylau328/fyp-artificial-intelligence-ac-control-device
univ.py
Real.isMinusInf
isMinusInf
Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise.
[ "Indicate", "MINUS-INFINITY", "object", "value", "Returns", "-------", ":", ":class:`bool`", ":obj:`True`", "if", "calling", "object", "represents", "minus", "infinity", "or", ":obj:`False`", "otherwise." ]
def isMinusInf(self): return self._value == self._minusInf
['def', 'isMinusInf(self):', 'return', 'self._value', '==', 'self._minusInf']
198,773
weimin17/Object-Detection_HelmetDetection
vgsl_model_test.py
VgslModelTest.testPadLabels2d
testPadLabels2d
Must pad timesteps in labels to match logits.
[ "Must", "pad", "timesteps", "in", "labels", "to", "match", "logits." ]
def testPadLabels2d(self): with self.test_session() as sess: ph_logits = tf.placeholder(tf.float32, shape=(None, None, 42)) ph_labels = tf.placeholder(tf.int64, shape=(None, None)) padded_labels = vgsl_model._PadLabels2d(tf.shape(ph_logits)[1], ph_labels) real_logits = _rand(4, 97, 4...
['def', 'testPadLabels2d(self):', 'with', 'self.test_session()', 'as', 'sess:', 'ph_logits', '=', 'tf.placeholder(tf.float32,', 'shape=(None,', 'None,', '42))', 'ph_labels', '=', 'tf.placeholder(tf.int64,', 'shape=(None,', 'None))', 'padded_labels', '=', 'vgsl_model._PadLabels2d(tf.shape(ph_logits)[1],', 'ph_labels)', ...
753,168
microsoft/nlp-recipes
abstractive_summarization_bertsum.py
BertSumAbs.predict
predict
Predict the summarization for the input data iterator.
[ "Predict", "the", "summarization", "for", "the", "input", "data", "iterator." ]
def predict(self, test_dataset, num_gpus=None, gpu_ids=None, local_rank=-1, batch_size=16, alpha=0.6, beam_size=5, min_length=15, max_length=150, fp16=False, verbose=True): (device, num_gpus) = get_device(num_gpus=num_gpus, gpu_ids=gpu_ids, local_rank=local_rank) def this_model_move_callback(model, device): ...
['def', 'predict(self,', 'test_dataset,', 'num_gpus=None,', 'gpu_ids=None,', 'local_rank=-1,', 'batch_size=16,', 'alpha=0.6,', 'beam_size=5,', 'min_length=15,', 'max_length=150,', 'fp16=False,', 'verbose=True):', '(device,', 'num_gpus)', '=', 'get_device(num_gpus=num_gpus,', 'gpu_ids=gpu_ids,', 'local_rank=local_rank)'...
731,285
tobegit3hub/deep_image_model
graph_actions.py
get_summary_writer
get_summary_writer
Returns single SummaryWriter per logdir in current run.
[ "Returns", "single", "SummaryWriter", "per", "logdir", "in", "current", "run." ]
def get_summary_writer(logdir): return summary_io.SummaryWriterCache.get(logdir)
['def', 'get_summary_writer(logdir):', 'return', 'summary_io.SummaryWriterCache.get(logdir)']
181,555
QData/deepWordBug
nodes.py
Element.is_not_list_attribute
is_not_list_attribute
Returns True if and only if the given attribute is NOT one of the basic list attributes defined for all Elements.
[ "Returns", "True", "if", "and", "only", "if", "the", "given", "attribute", "is", "NOT", "one", "of", "the", "basic", "list", "attributes", "defined", "for", "all", "Elements." ]
def is_not_list_attribute(cls, attr): return attr not in cls.list_attributes
['def', 'is_not_list_attribute(cls,', 'attr):', 'return', 'attr', 'not', 'in', 'cls.list_attributes']
542,068
jimtin/Stock_Comparison
version.py
pyzmq_version_info
pyzmq_version_info
return the pyzmq version as a tuple of at least three numbers If pyzmq is a development version, `inf` will be appended after the third integer.
[ "return", "the", "pyzmq", "version", "as", "a", "tuple", "of", "at", "least", "three", "numbers", "If", "pyzmq", "is", "a", "development", "version,", "`inf`", "will", "be", "appended", "after", "the", "third", "integer." ]
def pyzmq_version_info(): return version_info
['def', 'pyzmq_version_info():', 'return', 'version_info']
359,579
yehengchen/Object-Detection-and-Tracking
model.py
yolo_eval
yolo_eval
Evaluate YOLO model on given input and return filtered boxes.
[ "Evaluate", "YOLO", "model", "on", "given", "input", "and", "return", "filtered", "boxes." ]
def yolo_eval(yolo_outputs, anchors, num_classes, image_shape, max_boxes=200, score_threshold=0.5, iou_threshold=0.5): num_layers = len(yolo_outputs) anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] input_shape = K.shape(yolo_outputs[0])[1:3] * 32 boxes = [] box_scores = [] for l in range(num_lay...
['def', 'yolo_eval(yolo_outputs,', 'anchors,', 'num_classes,', 'image_shape,', 'max_boxes=200,', 'score_threshold=0.5,', 'iou_threshold=0.5):', 'num_layers', '=', 'len(yolo_outputs)', 'anchor_mask', '=', '[[6,', '7,', '8],', '[3,', '4,', '5],', '[0,', '1,', '2]]', 'input_shape', '=', 'K.shape(yolo_outputs[0])[1:3]', '*...
726,034
JahJajaka/afternoon_cleaner
mobilenet_v1_train.py
get_checkpoint_init_fn
get_checkpoint_init_fn
Returns the checkpoint init_fn if the checkpoint is provided.
[ "Returns", "the", "checkpoint", "init_fn", "if", "the", "checkpoint", "is", "provided." ]
def get_checkpoint_init_fn(): if FLAGS.fine_tune_checkpoint: variables_to_restore = slim.get_variables_to_restore() global_step_reset = tf.assign(tf.train.get_or_create_global_step(), 0) slim_init_fn = slim.assign_from_checkpoint_fn(FLAGS.fine_tune_checkpoint, variables_to_restore, ignore_mi...
['def', 'get_checkpoint_init_fn():', 'if', 'FLAGS.fine_tune_checkpoint:', 'variables_to_restore', '=', 'slim.get_variables_to_restore()', 'global_step_reset', '=', 'tf.assign(tf.train.get_or_create_global_step(),', '0)', 'slim_init_fn', '=', 'slim.assign_from_checkpoint_fn(FLAGS.fine_tune_checkpoint,', 'variables_to_re...
411,853
cjiang2/video2command
model.py
Video2Command.evaluate
evaluate
Run the evaluation pipeline over the test dataset.
[ "Run", "the", "evaluation", "pipeline", "over", "the", "test", "dataset." ]
def evaluate(self, test_loader, vocab): assert self.config.MODE == 'test' (y_pred, y_true) = ([], []) for (i, (Xv, S_true, clip_names)) in enumerate(test_loader): (Xv, S_true) = (Xv.to(self.device), S_true.to(self.device)) S_pred = self.predict(Xv, vocab) y_pred.append(S_pred) ...
['def', 'evaluate(self,', 'test_loader,', 'vocab):', 'assert', 'self.config.MODE', '==', "'test'", '(y_pred,', 'y_true)', '=', '([],', '[])', 'for', '(i,', '(Xv,', 'S_true,', 'clip_names))', 'in', 'enumerate(test_loader):', '(Xv,', 'S_true)', '=', '(Xv.to(self.device),', 'S_true.to(self.device))', 'S_pred', '=', 'self....
379,877
RaySunWHUT/NeuralNetwork
NeuralNetwork.py
sigm
sigm
Description: -Calculates the output of a given value using the sigmoid function.
[ "Description:", "-Calculates", "the", "output", "of", "a", "given", "value", "using", "the", "sigmoid", "function." ]
def sigm(s): return 1.0 / (1.0 + np.e ** (-s))
['def', 'sigm(s):', 'return', '1.0', '/', '(1.0', '+', 'np.e', '**', '(-s))']
722,250
dheeraj141/Computer-Vision-Udacity-810-Problem-Sets
reference_KD_tree.py
KDNode.extreme_child
extreme_child
Returns a child of the subtree and its parent The child is selected by sel_func which is either min or max (or a different function with similar semantics).
[ "Returns", "a", "child", "of", "the", "subtree", "and", "its", "parent", "The", "child", "is", "selected", "by", "sel_func", "which", "is", "either", "min", "or", "max", "(or", "a", "different", "function", "with", "similar", "semantics)." ]
def extreme_child(self, sel_func, axis): max_key = lambda child_parent: child_parent[0].data[axis] me = [(self, None)] if self else [] child_max = [c.extreme_child(sel_func, axis) for (c, _) in self.children] child_max = [(c, p if p is not None else self) for (c, p) in child_max] candidates = me + c...
['def', 'extreme_child(self,', 'sel_func,', 'axis):', 'max_key', '=', 'lambda', 'child_parent:', 'child_parent[0].data[axis]', 'me', '=', '[(self,', 'None)]', 'if', 'self', 'else', '[]', 'child_max', '=', '[c.extreme_child(sel_func,', 'axis)', 'for', '(c,', '_)', 'in', 'self.children]', 'child_max', '=', '[(c,', 'p', '...
470,748
google/balloon-learning-environment
sampling.py
sample_time
sample_time
Samples a random time uniformly within the specified range.
[ "Samples", "a", "random", "time", "uniformly", "within", "the", "specified", "range." ]
def sample_time(key: jnp.ndarray, begin_range: dt.datetime=units.datetime(2011, 1, 1), end_range: dt.datetime=units.datetime(2014, 12, 31)) -> dt.datetime: time_range: dt.timedelta = end_range - begin_range time_offset = jax.random.choice(key, int(time_range.total_seconds()), ()).item() return begin_range +...
['def', 'sample_time(key:', 'jnp.ndarray,', 'begin_range:', 'dt.datetime=units.datetime(2011,', '1,', '1),', 'end_range:', 'dt.datetime=units.datetime(2014,', '12,', '31))', '->', 'dt.datetime:', 'time_range:', 'dt.timedelta', '=', 'end_range', '-', 'begin_range', 'time_offset', '=', 'jax.random.choice(key,', 'int(time...
422,456
devashish-patel/webcam-motion-detector
named_commands.py
clear_screen
clear_screen
Clear the screen and redraw everything at the top of the screen.
[ "Clear", "the", "screen", "and", "redraw", "everything", "at", "the", "top", "of", "the", "screen." ]
def clear_screen(event): event.cli.renderer.clear()
['def', 'clear_screen(event):', 'event.cli.renderer.clear()']
983,928
jshilong/DDQ
cross_entropy_loss.py
binary_cross_entropy
binary_cross_entropy
Calculate the binary CrossEntropy loss.
[ "Calculate", "the", "binary", "CrossEntropy", "loss." ]
def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None, ignore_index=-100): ignore_index = -100 if ignore_index is None else ignore_index if pred.dim() != label.dim(): (label, weight) = _expand_onehot_labels(label, weight, pred.size(-1), ignore_index) ...
['def', 'binary_cross_entropy(pred,', 'label,', 'weight=None,', "reduction='mean',", 'avg_factor=None,', 'class_weight=None,', 'ignore_index=-100):', 'ignore_index', '=', '-100', 'if', 'ignore_index', 'is', 'None', 'else', 'ignore_index', 'if', 'pred.dim()', '!=', 'label.dim():', '(label,', 'weight)', '=', '_expand_one...
516,170
Katja-M/Python_NaturalLanguageProcessing
transforms.py
BboxBase.fully_contains
fully_contains
Return whether ``x, y`` is in the bounding box, but not on its edge.
[ "Return", "whether", "``x,", "y``", "is", "in", "the", "bounding", "box,", "but", "not", "on", "its", "edge." ]
def fully_contains(self, x, y): return self.fully_containsx(x) and self.fully_containsy(y)
['def', 'fully_contains(self,', 'x,', 'y):', 'return', 'self.fully_containsx(x)', 'and', 'self.fully_containsy(y)']
864,968
brohrer/autoencoder_visualization
nn_viz_19.py
save_nn_viz
save_nn_viz
Generate a new filename for each step of the process.
[ "Generate", "a", "new", "filename", "for", "each", "step", "of", "the", "process." ]
def save_nn_viz(fig, postfix='0'): base_name = 'nn_viz_' filename = base_name + postfix + '.png' fig.savefig(filename, edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=DPI)
['def', 'save_nn_viz(fig,', "postfix='0'):", 'base_name', '=', "'nn_viz_'", 'filename', '=', 'base_name', '+', 'postfix', '+', "'.png'", 'fig.savefig(filename,', 'edgecolor=fig.get_edgecolor(),', 'facecolor=fig.get_facecolor(),', 'dpi=DPI)']
419,780
ajMIT95/MIT_Artificial_Intelligence_Labs
neural_net_api.py
NeuralNet.get_output_neuron
get_output_neuron
Returns the name of the output-layer neuron.
[ "Returns", "the", "name", "of", "the", "output-layer", "neuron." ]
def get_output_neuron(self): return self.get_incoming_neighbors(NeuralNet.OUT)[0]
['def', 'get_output_neuron(self):', 'return', 'self.get_incoming_neighbors(NeuralNet.OUT)[0]']
239,361
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vocabulary.py
Vocabulary.id_to_word
id_to_word
Returns the word string of an integer word id.
[ "Returns", "the", "word", "string", "of", "an", "integer", "word", "id." ]
def id_to_word(self, word_id): if word_id >= len(self.reverse_vocab): return self.reverse_vocab[self.unk_id] else: return self.reverse_vocab[word_id]
['def', 'id_to_word(self,', 'word_id):', 'if', 'word_id', '>=', 'len(self.reverse_vocab):', 'return', 'self.reverse_vocab[self.unk_id]', 'else:', 'return', 'self.reverse_vocab[word_id]']
55,058
flovera1/AI
bayesNet.py
normalize
normalize
Normalizes, assumes the operation is mathematically valid on the passed in factor.
[ "Normalizes,", "assumes", "the", "operation", "is", "mathematically", "valid", "on", "the", "passed", "in", "factor." ]
def normalize(factor): variableDomainsDict = factor.variableDomainsDict() for conditionedVariable in factor.conditionedVariables(): if len(variableDomainsDict[conditionedVariable]) > 1: print('Factor failed normalize typecheck: ', factor) raise ValueError('The factor to be normal...
['def', 'normalize(factor):', 'variableDomainsDict', '=', 'factor.variableDomainsDict()', 'for', 'conditionedVariable', 'in', 'factor.conditionedVariables():', 'if', 'len(variableDomainsDict[conditionedVariable])', '>', '1:', "print('Factor", 'failed', 'normalize', 'typecheck:', "',", 'factor)', 'raise', "ValueError('T...
66,177
Alexander-Parker/youtube_nlp
message.py
insert
insert
Get an **insert** message.
[ "Get", "an", "**insert**", "message." ]
def insert(collection_name, docs, check_keys, safe, last_error_args, continue_on_error, opts, ctx=None): if ctx: return _insert_compressed(collection_name, docs, check_keys, continue_on_error, opts, ctx) return _insert_uncompressed(collection_name, docs, check_keys, safe, last_error_args, continue_on_er...
['def', 'insert(collection_name,', 'docs,', 'check_keys,', 'safe,', 'last_error_args,', 'continue_on_error,', 'opts,', 'ctx=None):', 'if', 'ctx:', 'return', '_insert_compressed(collection_name,', 'docs,', 'check_keys,', 'continue_on_error,', 'opts,', 'ctx)', 'return', '_insert_uncompressed(collection_name,', 'docs,', '...
970,454
rudranil723/mini-main
smtp.py
EmailBackend.close
close
Close the connection to the email server.
[ "Close", "the", "connection", "to", "the", "email", "server." ]
def close(self): if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): self.connection.close() except smtplib.SMTPException: if self.fail_silently: return ...
['def', 'close(self):', 'if', 'self.connection', 'is', 'None:', 'return', 'try:', 'try:', 'self.connection.quit()', 'except', '(ssl.SSLError,', 'smtplib.SMTPServerDisconnected):', 'self.connection.close()', 'except', 'smtplib.SMTPException:', 'if', 'self.fail_silently:', 'return', 'raise', 'finally:', 'self.connection'...
315,587
wandb/wandb
inotify_c.py
Inotify.path
path
The path associated with the inotify instance.
[ "The", "path", "associated", "with", "the", "inotify", "instance." ]
def path(self): return self._path
['def', 'path(self):', 'return', 'self._path']
942,155
tencent-ailab/TriNet
utils.py
all_to_all
all_to_all
Perform an all-to-all operation on a 1D Tensor.
[ "Perform", "an", "all-to-all", "operation", "on", "a", "1D", "Tensor." ]
def all_to_all(tensor, group): assert tensor.dim() == 1 split_count = get_world_size(group=group) assert tensor.numel() % split_count == 0 if use_xla(): assert isinstance(group, tuple) and group[0] == 'tpu' return xm.all_to_all(tensor, split_dimension=0, concat_dimension=0, split_count=s...
['def', 'all_to_all(tensor,', 'group):', 'assert', 'tensor.dim()', '==', '1', 'split_count', '=', 'get_world_size(group=group)', 'assert', 'tensor.numel()', '%', 'split_count', '==', '0', 'if', 'use_xla():', 'assert', 'isinstance(group,', 'tuple)', 'and', 'group[0]', '==', "'tpu'", 'return', 'xm.all_to_all(tensor,', 's...
425,258
cristianpb/object-detection
preprocessor_test.py
PreprocessorTest.testSubtractChannelMean
testSubtractChannelMean
Tests whether channel means have been subtracted.
[ "Tests", "whether", "channel", "means", "have", "been", "subtracted." ]
def testSubtractChannelMean(self): with self.test_session(): image = tf.zeros((240, 320, 3)) means = [1, 2, 3] actual = preprocessor.subtract_channel_mean(image, means=means) actual = actual.eval() self.assertTrue((actual[:, :, 0] == -1).all()) self.assertTrue((actual...
['def', 'testSubtractChannelMean(self):', 'with', 'self.test_session():', 'image', '=', 'tf.zeros((240,', '320,', '3))', 'means', '=', '[1,', '2,', '3]', 'actual', '=', 'preprocessor.subtract_channel_mean(image,', 'means=means)', 'actual', '=', 'actual.eval()', 'self.assertTrue((actual[:,', ':,', '0]', '==', '-1).all()...
746,491
devashish-patel/webcam-motion-detector
compat.py
unsetenv
unsetenv
Delete the environment variable 'name'.
[ "Delete", "the", "environment", "variable", "'name'." ]
def unsetenv(name): os.environ[name] = '' del os.environ[name]
['def', 'unsetenv(name):', 'os.environ[name]', '=', "''", 'del', 'os.environ[name]']
984,194
deepmind/dm_control
renderer.py
RenderSettings.toggle_geom_group
toggle_geom_group
Toggles the specified geom group visible or not.
[ "Toggles", "the", "specified", "geom", "group", "visible", "or", "not." ]
def toggle_geom_group(self, group_index): self._visualization_options.geomgroup[group_index] = not self._visualization_options.geomgroup[group_index]
['def', 'toggle_geom_group(self,', 'group_index):', 'self._visualization_options.geomgroup[group_index]', '=', 'not', 'self._visualization_options.geomgroup[group_index]']
166,561
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds
structures.py
bitmap_to_polygon
bitmap_to_polygon
Convert masks from the form of bitmaps to polygons.
[ "Convert", "masks", "from", "the", "form", "of", "bitmaps", "to", "polygons." ]
def bitmap_to_polygon(bitmap): bitmap = np.ascontiguousarray(bitmap).astype(np.uint8) outs = cv2.findContours(bitmap, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) contours = outs[-2] hierarchy = outs[-1] if hierarchy is None: return ([], False) with_hole = (hierarchy.reshape(-1, 4)[:, 3] >= 0)...
['def', 'bitmap_to_polygon(bitmap):', 'bitmap', '=', 'np.ascontiguousarray(bitmap).astype(np.uint8)', 'outs', '=', 'cv2.findContours(bitmap,', 'cv2.RETR_CCOMP,', 'cv2.CHAIN_APPROX_NONE)', 'contours', '=', 'outs[-2]', 'hierarchy', '=', 'outs[-1]', 'if', 'hierarchy', 'is', 'None:', 'return', '([],', 'False)', 'with_hole'...
650,671
sshleifer/object_detection_kitti
resnet_v2_test.py
create_test_input
create_test_input
Create test input tensor.
[ "Create", "test", "input", "tensor." ]
def create_test_input(batch_size, height, width, channels): if None in [batch_size, height, width, channels]: return tf.placeholder(tf.float32, (batch_size, height, width, channels)) else: return tf.to_float(np.tile(np.reshape(np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(wid...
['def', 'create_test_input(batch_size,', 'height,', 'width,', 'channels):', 'if', 'None', 'in', '[batch_size,', 'height,', 'width,', 'channels]:', 'return', 'tf.placeholder(tf.float32,', '(batch_size,', 'height,', 'width,', 'channels))', 'else:', 'return', 'tf.to_float(np.tile(np.reshape(np.reshape(np.arange(height),',...
795,536
Deci-AI/super-gradients
test_deprecate.py
TestDeprecationDecorator.test_displays_removed_version
test_displays_removed_version
Ensure that the warning contains the version in which the function will be removed.
[ "Ensure", "that", "the", "warning", "contains", "the", "version", "in", "which", "the", "function", "will", "be", "removed." ]
def test_displays_removed_version(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') self.fully_configured_deprecated_func() self.assertTrue(any(('10.0.0' in str(warning.message) for warning in w)))
['def', 'test_displays_removed_version(self):', 'with', 'warnings.catch_warnings(record=True)', 'as', 'w:', "warnings.simplefilter('always')", 'self.fully_configured_deprecated_func()', "self.assertTrue(any(('10.0.0'", 'in', 'str(warning.message)', 'for', 'warning', 'in', 'w)))']
880,693
tobegit3hub/deep_image_model
debugger_cli_common.py
CommandHandlerRegistry.register_command_handler
register_command_handler
Register a callable as a command handler.
[ "Register", "a", "callable", "as", "a", "command", "handler." ]
def register_command_handler(self, prefix, handler, help_info, prefix_aliases=None): if not prefix: raise ValueError('Empty command prefix') if prefix in self._handlers: raise ValueError('A handler is already registered for command prefix "%s"' % prefix) if not callable(handler): rai...
['def', 'register_command_handler(self,', 'prefix,', 'handler,', 'help_info,', 'prefix_aliases=None):', 'if', 'not', 'prefix:', 'raise', "ValueError('Empty", 'command', "prefix')", 'if', 'prefix', 'in', 'self._handlers:', 'raise', "ValueError('A", 'handler', 'is', 'already', 'registered', 'for', 'command', 'prefix', '"...
182,405
enuguru/artificial_intelligence_and_machine_learning
sql.py
Token.has_ancestor
has_ancestor
Returns ``True`` if *other* is in this tokens ancestry.
[ "Returns", "``True``", "if", "*other*", "is", "in", "this", "tokens", "ancestry." ]
def has_ancestor(self, other): parent = self.parent while parent: if parent == other: return True parent = parent.parent return False
['def', 'has_ancestor(self,', 'other):', 'parent', '=', 'self.parent', 'while', 'parent:', 'if', 'parent', '==', 'other:', 'return', 'True', 'parent', '=', 'parent.parent', 'return', 'False']
131,898
Eric3911/OpenAGI
inference.py
audio_tagging
audio_tagging
Inference audio tagging result of an audio clip.
[ "Inference", "audio", "tagging", "result", "of", "an", "audio", "clip." ]
def audio_tagging(args): sample_rate = args.sample_rate window_size = args.window_size hop_size = args.hop_size mel_bins = args.mel_bins fmin = args.fmin fmax = args.fmax model_type = args.model_type checkpoint_path = args.checkpoint_path audio_path = args.audio_path device = tor...
['def', 'audio_tagging(args):', 'sample_rate', '=', 'args.sample_rate', 'window_size', '=', 'args.window_size', 'hop_size', '=', 'args.hop_size', 'mel_bins', '=', 'args.mel_bins', 'fmin', '=', 'args.fmin', 'fmax', '=', 'args.fmax', 'model_type', '=', 'args.model_type', 'checkpoint_path', '=', 'args.checkpoint_path', 'a...
250,464
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
mpi_util.py
gpu_count
gpu_count
Count the GPUs on this machine.
[ "Count", "the", "GPUs", "on", "this", "machine." ]
def gpu_count(): if shutil.which('nvidia-smi') is None: return 0 output = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv']) return max(0, len(output.split(b'\n')) - 2)
['def', 'gpu_count():', 'if', "shutil.which('nvidia-smi')", 'is', 'None:', 'return', '0', 'output', '=', "subprocess.check_output(['nvidia-smi',", "'--query-gpu=gpu_name',", "'--format=csv'])", 'return', 'max(0,', "len(output.split(b'\\n'))", '-', '2)']
432,940
intel/neural-compressor
sigopt.py
SigOptTuneStrategy.get_acc_target
get_acc_target
Get the tuning target of the accuracy ceiterion.
[ "Get", "the", "tuning", "target", "of", "the", "accuracy", "ceiterion." ]
def get_acc_target(self, base_acc): accuracy_criterion_conf = self.config.accuracy_criterion if accuracy_criterion_conf.criterion == 'relative': return base_acc * (1.0 - accuracy_criterion_conf.tolerable_loss) else: return base_acc - accuracy_criterion_conf.tolerable_loss
['def', 'get_acc_target(self,', 'base_acc):', 'accuracy_criterion_conf', '=', 'self.config.accuracy_criterion', 'if', 'accuracy_criterion_conf.criterion', '==', "'relative':", 'return', 'base_acc', '*', '(1.0', '-', 'accuracy_criterion_conf.tolerable_loss)', 'else:', 'return', 'base_acc', '-', 'accuracy_criterion_conf....
738,239
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mtf_layers.py
attention_mask_autoregressive
attention_mask_autoregressive
Bias for self-attention where attention to the right is disallowed.
[ "Bias", "for", "self-attention", "where", "attention", "to", "the", "right", "is", "disallowed." ]
def attention_mask_autoregressive(query_pos, dtype=tf.float32): memory_pos = rename_length_to_memory_length(query_pos) return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1000000000.0
['def', 'attention_mask_autoregressive(query_pos,', 'dtype=tf.float32):', 'memory_pos', '=', 'rename_length_to_memory_length(query_pos)', 'return', 'mtf.cast(mtf.less(query_pos,', 'memory_pos),', 'dtype)', '*', '-1000000000.0']
965,542
deepmind/dm_control
glfw_gui.py
GlfwWindow.position
position
Returns a tuple with top-left window corner's coordinates, (x, y).
[ "Returns", "a", "tuple", "with", "top-left", "window", "corner's", "coordinates,", "(x,", "y)." ]
def position(self): with self._context.make_current() as ctx: return ctx.call(glfw.get_window_pos, self._context.window)
['def', 'position(self):', 'with', 'self._context.make_current()', 'as', 'ctx:', 'return', 'ctx.call(glfw.get_window_pos,', 'self._context.window)']
165,757
f-dangel/cockpit
run_quadratic_deep.py
cosine_decay_restarts
cosine_decay_restarts
Cyclic LR schedule with restarts.
[ "Cyclic", "LR", "schedule", "with", "restarts." ]
def cosine_decay_restarts(steps_for_cycle, max_epochs, increase_restart_interval_factor=2, min_lr=0.0, restart_discount=0.0): lr_factors = [] step = 0 cycle = 0 for _ in range(0, max_epochs + 1): step += 1 completed_fraction = step / steps_for_cycle cosine_decayed = 0.5 * (1 + ma...
['def', 'cosine_decay_restarts(steps_for_cycle,', 'max_epochs,', 'increase_restart_interval_factor=2,', 'min_lr=0.0,', 'restart_discount=0.0):', 'lr_factors', '=', '[]', 'step', '=', '0', 'cycle', '=', '0', 'for', '_', 'in', 'range(0,', 'max_epochs', '+', '1):', 'step', '+=', '1', 'completed_fraction', '=', 'step', '/'...
493,243
lifuguan/ObjectDetection
transformsCV.py
RandomResizedCrop.get_params
get_params
Get parameters for ``crop`` for a random sized crop.
[ "Get", "parameters", "for", "``crop``", "for", "a", "random", "sized", "crop." ]
def get_params(img, scale, ratio): for attempt in range(10): area = img.shape[1] * img.shape[0] target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect...
['def', 'get_params(img,', 'scale,', 'ratio):', 'for', 'attempt', 'in', 'range(10):', 'area', '=', 'img.shape[1]', '*', 'img.shape[0]', 'target_area', '=', 'random.uniform(*scale)', '*', 'area', 'aspect_ratio', '=', 'random.uniform(*ratio)', 'w', '=', 'int(round(math.sqrt(target_area', '*', 'aspect_ratio)))', 'h', '=',...
743,499
bobwan1995/PMFNet
keypoint_rcnn.py
finalize_keypoint_minibatch
finalize_keypoint_minibatch
Finalize the minibatch after blobs for all minibatch images have been collated.
[ "Finalize", "the", "minibatch", "after", "blobs", "for", "all", "minibatch", "images", "have", "been", "collated." ]
def finalize_keypoint_minibatch(blobs, valid): min_count = cfg.KRCNN.MIN_KEYPOINT_COUNT_FOR_VALID_MINIBATCH num_visible_keypoints = np.sum(blobs['keypoint_weights']) valid = valid and len(blobs['keypoint_weights']) > 0 and (num_visible_keypoints > min_count) norm = num_visible_keypoints / (cfg.TRAIN.IMS...
['def', 'finalize_keypoint_minibatch(blobs,', 'valid):', 'min_count', '=', 'cfg.KRCNN.MIN_KEYPOINT_COUNT_FOR_VALID_MINIBATCH', 'num_visible_keypoints', '=', "np.sum(blobs['keypoint_weights'])", 'valid', '=', 'valid', 'and', "len(blobs['keypoint_weights'])", '>', '0', 'and', '(num_visible_keypoints', '>', 'min_count)', ...
780,697
sunishsheth2009/ChatterBot
api.py
ClusterI.cluster_names
cluster_names
Returns the names of the clusters.
[ "Returns", "the", "names", "of", "the", "clusters." ]
def cluster_names(self): return range(self.num_clusters())
['def', 'cluster_names(self):', 'return', 'range(self.num_clusters())']
485,200
Ruturaj123/Flowchart-Detection
tape.py
watch
watch
Marks this tensor to be watched by all tapes in the stack.
[ "Marks", "this", "tensor", "to", "be", "watched", "by", "all", "tapes", "in", "the", "stack." ]
def watch(tensor): for t in _tape_stack.stack: tensor = _watch_with_tape(t, tensor) return tensor
['def', 'watch(tensor):', 'for', 't', 'in', '_tape_stack.stack:', 'tensor', '=', '_watch_with_tape(t,', 'tensor)', 'return', 'tensor']
605,173
gunthercox/ChatterBot
fst.py
Values.skip
skip
Skips over a value in the given file.
[ "Skips", "over", "a", "value", "in", "the", "given", "file." ]
def skip(cls, dbfile): cls.read(dbfile)
['def', 'skip(cls,', 'dbfile):', 'cls.read(dbfile)']
526,616
nicknochnack/RealTimeSignLanguageTFJS
nasnet.py
nasnet_cifar_arg_scope
nasnet_cifar_arg_scope
Defines the default arg scope for the NASNet-A Cifar model.
[ "Defines", "the", "default", "arg", "scope", "for", "the", "NASNet-A", "Cifar", "model." ]
def nasnet_cifar_arg_scope(weight_decay=0.0005, batch_norm_decay=0.9, batch_norm_epsilon=1e-05): batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': True, 'fused': True} weights_regularizer = slim.l2_regularizer(weight_decay) weights_initializer = slim.variance_scaling_in...
['def', 'nasnet_cifar_arg_scope(weight_decay=0.0005,', 'batch_norm_decay=0.9,', 'batch_norm_epsilon=1e-05):', 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'scale':", 'True,', "'fused':", 'True}', 'weights_regularizer', '=', 'slim.l2_regularizer(weight_decay)', 'weigh...
831,328
omonimus1/super-computer-
mercurial.py
Mercurial.get_revision
get_revision
Return the repository-local changeset revision number, as an integer.
[ "Return", "the", "repository-local", "changeset", "revision", "number,", "as", "an", "integer." ]
def get_revision(cls, location): current_revision = cls.run_command(['parents', '--template={rev}'], show_stdout=False, cwd=location).strip() return current_revision
['def', 'get_revision(cls,', 'location):', 'current_revision', '=', "cls.run_command(['parents',", "'--template={rev}'],", 'show_stdout=False,', 'cwd=location).strip()', 'return', 'current_revision']
913,308
yadavpa1/Artificial-Intelligence
utils.py
distance
distance
The distance between two (x, y) points.
[ "The", "distance", "between", "two", "(x,", "y)", "points." ]
def distance(a, b): (xA, yA) = a (xB, yB) = b return np.hypot(xA - xB, yA - yB)
['def', 'distance(a,', 'b):', '(xA,', 'yA)', '=', 'a', '(xB,', 'yB)', '=', 'b', 'return', 'np.hypot(xA', '-', 'xB,', 'yA', '-', 'yB)']
120,402
deepmind/dm_alchemy
utils.py
ChemistrySeen.form_observation
form_observation
Forms an observation with the correct content type at each dimension.
[ "Forms", "an", "observation", "with", "the", "correct", "content", "type", "at", "each", "dimension." ]
def form_observation(self, contents: Sequence[ElementContent], get_obs: GetChemistryObsFns) -> List[float]: obs = [] for element_type in ElementType: dimensions = self.dimensions_for_content(contents, element_type) if contents else {} obs.extend(self.element(element_type).form_observation(dimens...
['def', 'form_observation(self,', 'contents:', 'Sequence[ElementContent],', 'get_obs:', 'GetChemistryObsFns)', '->', 'List[float]:', 'obs', '=', '[]', 'for', 'element_type', 'in', 'ElementType:', 'dimensions', '=', 'self.dimensions_for_content(contents,', 'element_type)', 'if', 'contents', 'else', '{}', 'obs.extend(sel...
522,304
Katja-M/Python_NaturalLanguageProcessing
arlstem.py
ARLSTem.plur2sing
plur2sing
transform the word from the plural form to the singular form.
[ "transform", "the", "word", "from", "the", "plural", "form", "to", "the", "singular", "form." ]
def plur2sing(self, token): if len(token) > 4: for ps2 in self.pl_si2: if token.endswith(ps2): return token[:-2] if len(token) > 5: for ps3 in self.pl_si3: if token.endswith(ps3): return token[:-3] if len(token) > 3 and token.endswith('...
['def', 'plur2sing(self,', 'token):', 'if', 'len(token)', '>', '4:', 'for', 'ps2', 'in', 'self.pl_si2:', 'if', 'token.endswith(ps2):', 'return', 'token[:-2]', 'if', 'len(token)', '>', '5:', 'for', 'ps3', 'in', 'self.pl_si3:', 'if', 'token.endswith(ps3):', 'return', 'token[:-3]', 'if', 'len(token)', '>', '3', 'and', "to...
866,943
openvinotoolkit/training_extensions
accuracy.py
Accuracy.get_performance
get_performance
Returns the performance with accuracy and confusion metrics.
[ "Returns", "the", "performance", "with", "accuracy", "and", "confusion", "metrics." ]
def get_performance(self) -> Performance: confusion_matrix_dashboard_metrics: List[MetricsGroup] = [] normalized_matrices: List[MatrixMetric] = copy.deepcopy(self._unnormalized_matrices) for unnormalized_matrix in normalized_matrices: unnormalized_matrix.normalize() confusion_matrix_info = Matri...
['def', 'get_performance(self)', '->', 'Performance:', 'confusion_matrix_dashboard_metrics:', 'List[MetricsGroup]', '=', '[]', 'normalized_matrices:', 'List[MatrixMetric]', '=', 'copy.deepcopy(self._unnormalized_matrices)', 'for', 'unnormalized_matrix', 'in', 'normalized_matrices:', 'unnormalized_matrix.normalize()', '...
918,735
Alexander-Parker/youtube_nlp
base.py
FromServiceAccountMixin.from_string
from_string
Construct an Signer instance from a private key string.
[ "Construct", "an", "Signer", "instance", "from", "a", "private", "key", "string." ]
def from_string(cls, key, key_id=None): raise NotImplementedError('from_string must be implemented')
['def', 'from_string(cls,', 'key,', 'key_id=None):', 'raise', "NotImplementedError('from_string", 'must', 'be', "implemented')"]
970,052
43Carrig/recurrent_neural_networks_practice
summaries.py
tf_parameter_summary
tf_parameter_summary
Summarize parameters by depth.
[ "Summarize", "parameters", "by", "depth." ]
def tf_parameter_summary(x, printer=print, combine=True): seq = tf_parameter_iter(x) if combine: seq = _combine_filter(seq) seq = reversed(list(seq)) for (name, total, shape) in seq: printer('%10d %-20s %s' % (total, name, shape))
['def', 'tf_parameter_summary(x,', 'printer=print,', 'combine=True):', 'seq', '=', 'tf_parameter_iter(x)', 'if', 'combine:', 'seq', '=', '_combine_filter(seq)', 'seq', '=', 'reversed(list(seq))', 'for', '(name,', 'total,', 'shape)', 'in', 'seq:', "printer('%10d", '%-20s', "%s'", '%', '(total,', 'name,', 'shape))']
335,288
Jamie725/Multimodal-Object-Detection-via-Probabilistic-Ensembling
compat.py
upgrade_config
upgrade_config
Upgrade a config from its current version to a newer version.
[ "Upgrade", "a", "config", "from", "its", "current", "version", "to", "a", "newer", "version." ]
def upgrade_config(cfg: CN, to_version: Optional[int]=None) -> CN: cfg = cfg.clone() if to_version is None: to_version = _C.VERSION assert cfg.VERSION <= to_version, 'Cannot upgrade from v{} to v{}!'.format(cfg.VERSION, to_version) for k in range(cfg.VERSION, to_version): converter = glo...
['def', 'upgrade_config(cfg:', 'CN,', 'to_version:', 'Optional[int]=None)', '->', 'CN:', 'cfg', '=', 'cfg.clone()', 'if', 'to_version', 'is', 'None:', 'to_version', '=', '_C.VERSION', 'assert', 'cfg.VERSION', '<=', 'to_version,', "'Cannot", 'upgrade', 'from', 'v{}', 'to', "v{}!'.format(cfg.VERSION,", 'to_version)', 'fo...
643,763
BLVLab/PiMAE
misc.py
seprate_point_cloud
seprate_point_cloud
seprate point cloud: usage : using to generate the incomplete point cloud with a setted number.
[ "seprate", "point", "cloud:", "usage", ":", "using", "to", "generate", "the", "incomplete", "point", "cloud", "with", "a", "setted", "number." ]
def seprate_point_cloud(xyz, num_points, crop, fixed_points=None, padding_zeros=False): (_, n, c) = xyz.shape assert n == num_points assert c == 3 if crop == num_points: return (xyz, None) INPUT = [] CROP = [] for points in xyz: if isinstance(crop, list): num_crop...
['def', 'seprate_point_cloud(xyz,', 'num_points,', 'crop,', 'fixed_points=None,', 'padding_zeros=False):', '(_,', 'n,', 'c)', '=', 'xyz.shape', 'assert', 'n', '==', 'num_points', 'assert', 'c', '==', '3', 'if', 'crop', '==', 'num_points:', 'return', '(xyz,', 'None)', 'INPUT', '=', '[]', 'CROP', '=', '[]', 'for', 'point...
769,651
Ruturaj123/Flowchart-Detection
losses_test.py
SparseMulticlassHingeLossTest.testInconsistentLabelsAndWeightsShapesDifferentRank
testInconsistentLabelsAndWeightsShapesDifferentRank
Error raised when weights and labels have different ranks and sizes.
[ "Error", "raised", "when", "weights", "and", "labels", "have", "different", "ranks", "and", "sizes." ]
def testInconsistentLabelsAndWeightsShapesDifferentRank(self): with self.test_session(): logits = constant_op.constant([-1.0, 2.1], shape=(2, 1)) labels = constant_op.constant([1, 0], shape=(2, 1)) weights = constant_op.constant([1.1, 2.0, 2.8], shape=(3,)) with self.assertRaises(Val...
['def', 'testInconsistentLabelsAndWeightsShapesDifferentRank(self):', 'with', 'self.test_session():', 'logits', '=', 'constant_op.constant([-1.0,', '2.1],', 'shape=(2,', '1))', 'labels', '=', 'constant_op.constant([1,', '0],', 'shape=(2,', '1))', 'weights', '=', 'constant_op.constant([1.1,', '2.0,', '2.8],', 'shape=(3,...
603,532
zzndream/ShipRSImageNet
transformer.py
TransformerEncoder.forward
forward
Forward function for `TransformerEncoder`.
[ "Forward", "function", "for", "`TransformerEncoder`." ]
def forward(self, x, pos=None, attn_mask=None, key_padding_mask=None): for layer in self.layers: x = layer(x, pos, attn_mask, key_padding_mask) if self.norm is not None: x = self.norm(x) return x
['def', 'forward(self,', 'x,', 'pos=None,', 'attn_mask=None,', 'key_padding_mask=None):', 'for', 'layer', 'in', 'self.layers:', 'x', '=', 'layer(x,', 'pos,', 'attn_mask,', 'key_padding_mask)', 'if', 'self.norm', 'is', 'not', 'None:', 'x', '=', 'self.norm(x)', 'return', 'x']
933,608
Xiangyu-Gao/Radar-multiple-perspective--
__init__.py
get_sec
get_sec
Get Seconds from time.
[ "Get", "Seconds", "from", "time." ]
def get_sec(time_str): (h, m, s) = time_str.split(':') return int(h) * 3600 + int(m) * 60 + float(s)
['def', 'get_sec(time_str):', '(h,', 'm,', 's)', '=', "time_str.split(':')", 'return', 'int(h)', '*', '3600', '+', 'int(m)', '*', '60', '+', 'float(s)']
835,724
Ruturaj123/Flowchart-Detection
model_analyzer.py
analyze_vars
analyze_vars
Prints the names and shapes of the variables.
[ "Prints", "the", "names", "and", "shapes", "of", "the", "variables." ]
def analyze_vars(variables, print_info=False): if print_info: print('---------') print('Variables: name (type shape) [size]') print('---------') total_size = 0 total_bytes = 0 for var in variables: var_size = var.get_shape().num_elements() or 0 var_bytes = var_siz...
['def', 'analyze_vars(variables,', 'print_info=False):', 'if', 'print_info:', "print('---------')", "print('Variables:", 'name', '(type', 'shape)', "[size]')", "print('---------')", 'total_size', '=', '0', 'total_bytes', '=', '0', 'for', 'var', 'in', 'variables:', 'var_size', '=', 'var.get_shape().num_elements()', 'or'...
604,464
ddbourgin/numpy-ml
layers.py
FullyConnected.hyperparameters
hyperparameters
Return a dictionary containing the layer hyperparameters.
[ "Return", "a", "dictionary", "containing", "the", "layer", "hyperparameters." ]
def hyperparameters(self): return {'layer': 'FullyConnected', 'init': self.init, 'n_in': self.n_in, 'n_out': self.n_out, 'act_fn': str(self.act_fn), 'optimizer': {'cache': self.optimizer.cache, 'hyperparameters': self.optimizer.hyperparameters}}
['def', 'hyperparameters(self):', 'return', "{'layer':", "'FullyConnected',", "'init':", 'self.init,', "'n_in':", 'self.n_in,', "'n_out':", 'self.n_out,', "'act_fn':", 'str(self.act_fn),', "'optimizer':", "{'cache':", 'self.optimizer.cache,', "'hyperparameters':", 'self.optimizer.hyperparameters}}']
730,161
fudan-zvg/SETR
xml_style.py
XMLDataset.get_ann_info
get_ann_info
Get annotation from XML file by index.
[ "Get", "annotation", "from", "XML", "file", "by", "index." ]
def get_ann_info(self, idx): img_id = self.data_infos[idx]['id'] xml_path = osp.join(self.img_prefix, self.ann_subdir, f'{img_id}.xml') tree = ET.parse(xml_path) root = tree.getroot() bboxes = [] labels = [] bboxes_ignore = [] labels_ignore = [] for obj in root.findall('object'): ...
['def', 'get_ann_info(self,', 'idx):', 'img_id', '=', "self.data_infos[idx]['id']", 'xml_path', '=', 'osp.join(self.img_prefix,', 'self.ann_subdir,', "f'{img_id}.xml')", 'tree', '=', 'ET.parse(xml_path)', 'root', '=', 'tree.getroot()', 'bboxes', '=', '[]', 'labels', '=', '[]', 'bboxes_ignore', '=', '[]', 'labels_ignore...
897,991
FahadTComsats/Natural-Language-Processing
test_textrank.py
test_textrank_with_candidate_selection
test_textrank_with_candidate_selection
Test TextRank with longest-POS-sequences candidate selection.
[ "Test", "TextRank", "with", "longest-POS-sequences", "candidate", "selection." ]
def test_textrank_with_candidate_selection(): extractor = pke.unsupervised.TextRank() extractor.load_document(input=test_file) extractor.candidate_selection(pos=pos) extractor.candidate_weighting(pos=pos) keyphrases = [k for (k, s) in extractor.get_n_best(n=3)] assert keyphrases == ['linear diop...
['def', 'test_textrank_with_candidate_selection():', 'extractor', '=', 'pke.unsupervised.TextRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(pos=pos)', 'extractor.candidate_weighting(pos=pos)', 'keyphrases', '=', '[k', 'for', '(k,', 's)', 'in', 'extractor.get_n_best(n=3)]', 'assert',...
663,538
hardmaru/resnet-cppn-gan-tensorflow
images2gif.py
GifWriter.convertImagesToPIL
convertImagesToPIL
convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF.
[ "convertImagesToPIL(images,", "nq=0)", "Convert", "images", "to", "Paletted", "PIL", "images,", "which", "can", "then", "be", "written", "to", "a", "single", "animaged", "GIF." ]
def convertImagesToPIL(self, images, dither, nq=0): images2 = [] for im in images: if isinstance(im, Image.Image): images2.append(im) elif np and isinstance(im, np.ndarray): if im.ndim == 3 and im.shape[2] == 3: im = Image.fromarray(im, 'RGB') ...
['def', 'convertImagesToPIL(self,', 'images,', 'dither,', 'nq=0):', 'images2', '=', '[]', 'for', 'im', 'in', 'images:', 'if', 'isinstance(im,', 'Image.Image):', 'images2.append(im)', 'elif', 'np', 'and', 'isinstance(im,', 'np.ndarray):', 'if', 'im.ndim', '==', '3', 'and', 'im.shape[2]', '==', '3:', 'im', '=', 'Image.fr...
840,518
myothida/Supervised-Machine-Learning
_triinterpolate.py
_Sparse_Matrix_coo.diag
diag
Return the (dense) vector of the diagonal elements.
[ "Return", "the", "(dense)", "vector", "of", "the", "diagonal", "elements." ]
def diag(self): in_diag = self.rows == self.cols diag = np.zeros(min(self.n, self.n), dtype=np.float64) diag[self.rows[in_diag]] = self.vals[in_diag] return diag
['def', 'diag(self):', 'in_diag', '=', 'self.rows', '==', 'self.cols', 'diag', '=', 'np.zeros(min(self.n,', 'self.n),', 'dtype=np.float64)', 'diag[self.rows[in_diag]]', '=', 'self.vals[in_diag]', 'return', 'diag']
363,004
arshpreetsingh/quantopian-machinelearning
mouse_handlers.py
MouseHandlers.set_mouse_handler_for_range
set_mouse_handler_for_range
Set mouse handler for a region.
[ "Set", "mouse", "handler", "for", "a", "region." ]
def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None): for (x, y) in product(range(x_min, x_max), range(y_min, y_max)): self.mouse_handlers[x, y] = handler
['def', 'set_mouse_handler_for_range(self,', 'x_min,', 'x_max,', 'y_min,', 'y_max,', 'handler=None):', 'for', '(x,', 'y)', 'in', 'product(range(x_min,', 'x_max),', 'range(y_min,', 'y_max)):', 'self.mouse_handlers[x,', 'y]', '=', 'handler']
892,475
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
test_vec_env.py
assert_envs_equal
assert_envs_equal
Compare two environments over num_steps steps and make sure that the observations produced by each are the same when given the same actions.
[ "Compare", "two", "environments", "over", "num_steps", "steps", "and", "make", "sure", "that", "the", "observations", "produced", "by", "each", "are", "the", "same", "when", "given", "the", "same", "actions." ]
def assert_envs_equal(env1, env2, num_steps): assert env1.num_envs == env2.num_envs assert env1.action_space.shape == env2.action_space.shape assert env1.action_space.dtype == env2.action_space.dtype joint_shape = (env1.num_envs,) + env1.action_space.shape try: (obs1, obs2) = (env1.reset(), ...
['def', 'assert_envs_equal(env1,', 'env2,', 'num_steps):', 'assert', 'env1.num_envs', '==', 'env2.num_envs', 'assert', 'env1.action_space.shape', '==', 'env2.action_space.shape', 'assert', 'env1.action_space.dtype', '==', 'env2.action_space.dtype', 'joint_shape', '=', '(env1.num_envs,)', '+', 'env1.action_space.shape',...
432,473
enuguru/artificial_intelligence_and_machine_learning
wrappers.py
WWWAuthenticateMixin.www_authenticate
www_authenticate
The `WWW-Authenticate` header in a parsed form.
[ "The", "`WWW-Authenticate`", "header", "in", "a", "parsed", "form." ]
def www_authenticate(self): def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') retu...
['def', 'www_authenticate(self):', 'def', 'on_update(www_auth):', 'if', 'not', 'www_auth', 'and', "'www-authenticate'", 'in', 'self.headers:', 'del', "self.headers['www-authenticate']", 'elif', 'www_auth:', "self.headers['WWW-Authenticate']", '=', 'www_auth.to_header()', 'header', '=', "self.headers.get('www-authentica...
161,642
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
get_estimator.py
get_mvtcn_estimator
get_mvtcn_estimator
Returns a configured MVTCN estimator.
[ "Returns", "a", "configured", "MVTCN", "estimator." ]
def get_mvtcn_estimator(loss_strategy, config, logdir): loss_to_trainer = {'triplet_semihard': mvtcn_estimators.MVTCNTripletEstimator, 'npairs': mvtcn_estimators.MVTCNNpairsEstimator} if loss_strategy not in loss_to_trainer: raise ValueError('Unknown loss for MVTCN: %s' % loss_strategy) estimator = ...
['def', 'get_mvtcn_estimator(loss_strategy,', 'config,', 'logdir):', 'loss_to_trainer', '=', "{'triplet_semihard':", 'mvtcn_estimators.MVTCNTripletEstimator,', "'npairs':", 'mvtcn_estimators.MVTCNNpairsEstimator}', 'if', 'loss_strategy', 'not', 'in', 'loss_to_trainer:', 'raise', "ValueError('Unknown", 'loss', 'for', 'M...
29,705
gugarosa/nalp
wgan.py
WGAN.penalty_lambda
penalty_lambda
Coefficient for the gradient penalty.
[ "Coefficient", "for", "the", "gradient", "penalty." ]
def penalty_lambda(self) -> int: return self._penalty_lambda
['def', 'penalty_lambda(self)', '->', 'int:', 'return', 'self._penalty_lambda']
651,741
LucasAlegre/morl-baselines
buffer.py
ReplayBuffer.sample
sample
Sample a batch of experiences from the buffer.
[ "Sample", "a", "batch", "of", "experiences", "from", "the", "buffer." ]
def sample(self, batch_size, replace=True, use_cer=False, to_tensor=False, device=None): inds = np.random.choice(self.size, batch_size, replace=replace) if use_cer: inds[0] = self.ptr - 1 experience_tuples = (self.obs[inds], self.actions[inds], self.rewards[inds], self.next_obs[inds], self.dones[ind...
['def', 'sample(self,', 'batch_size,', 'replace=True,', 'use_cer=False,', 'to_tensor=False,', 'device=None):', 'inds', '=', 'np.random.choice(self.size,', 'batch_size,', 'replace=replace)', 'if', 'use_cer:', 'inds[0]', '=', 'self.ptr', '-', '1', 'experience_tuples', '=', '(self.obs[inds],', 'self.actions[inds],', 'self...
655,770
Alexander-Parker/youtube_nlp
topology_description.py
TopologyDescription.has_known_servers
has_known_servers
Whether there are any Servers of types besides Unknown.
[ "Whether", "there", "are", "any", "Servers", "of", "types", "besides", "Unknown." ]
def has_known_servers(self): return any((s for s in self._server_descriptions.values() if s.is_server_type_known))
['def', 'has_known_servers(self):', 'return', 'any((s', 'for', 's', 'in', 'self._server_descriptions.values()', 'if', 's.is_server_type_known))']
970,695
tudelft3d/SUMS-Semantic-Urban-Mesh--public
subversion.py
Subversion.get_netloc_and_auth
get_netloc_and_auth
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
[ "This", "override", "allows", "the", "auth", "information", "to", "be", "passed", "to", "svn", "via", "the", "--username", "and", "--password", "options", "instead", "of", "via", "the", "URL." ]
def get_netloc_and_auth(self, netloc, scheme): if scheme == 'ssh': return super(Subversion, self).get_netloc_and_auth(netloc, scheme) return split_auth_from_netloc(netloc)
['def', 'get_netloc_and_auth(self,', 'netloc,', 'scheme):', 'if', 'scheme', '==', "'ssh':", 'return', 'super(Subversion,', 'self).get_netloc_and_auth(netloc,', 'scheme)', 'return', 'split_auth_from_netloc(netloc)']
911,068
rudranil723/mini-main
test_printing.py
test_nonnumeric_object_coefficients
test_nonnumeric_object_coefficients
Test coef fallback for object arrays of non-numeric coefficients.
[ "Test", "coef", "fallback", "for", "object", "arrays", "of", "non-numeric", "coefficients." ]
def test_nonnumeric_object_coefficients(coefs, tgt): p = poly.Polynomial(coefs) poly.set_default_printstyle('unicode') assert_equal(str(p), tgt)
['def', 'test_nonnumeric_object_coefficients(coefs,', 'tgt):', 'p', '=', 'poly.Polynomial(coefs)', "poly.set_default_printstyle('unicode')", 'assert_equal(str(p),', 'tgt)']
322,995
datamllab/rlcard
game.py
GinRummyGame.decode_action
decode_action
Action id -> the action_event in the game.
[ "Action", "id", "->", "the", "action_event", "in", "the", "game." ]
def decode_action(action_id) -> ActionEvent: return ActionEvent.decode_action(action_id=action_id)
['def', 'decode_action(action_id)', '->', 'ActionEvent:', 'return', 'ActionEvent.decode_action(action_id=action_id)']
332,282
ilya16/MultINN
model.py
Model.variables
variables
A dictionary of model's variables grouped by modules.
[ "A", "dictionary", "of", "model's", "variables", "grouped", "by", "modules." ]
def variables(self): return self._variables
['def', 'variables(self):', 'return', 'self._variables']
644,177
sek788432/Waymo-2D-Object-Detection
ddpg_agent.py
gen_debug_td_error_summaries
gen_debug_td_error_summaries
Generates debug summaries for critic given a set of batch samples.
[ "Generates", "debug", "summaries", "for", "critic", "given", "a", "set", "of", "batch", "samples." ]
def gen_debug_td_error_summaries(target_q_values, q_values, td_targets, td_errors): with tf.name_scope('td_errors'): tf.summary.histogram('td_targets', td_targets) tf.summary.histogram('q_values', q_values) tf.summary.histogram('target_q_values', target_q_values) tf.summary.histogram...
['def', 'gen_debug_td_error_summaries(target_q_values,', 'q_values,', 'td_targets,', 'td_errors):', 'with', "tf.name_scope('td_errors'):", "tf.summary.histogram('td_targets',", 'td_targets)', "tf.summary.histogram('q_values',", 'q_values)', "tf.summary.histogram('target_q_values',", 'target_q_values)', "tf.summary.hist...
974,347
greydanus/pythonic_ocr
setup_common.py
is_released
is_released
Return True if a released version of numpy is detected.
[ "Return", "True", "if", "a", "released", "version", "of", "numpy", "is", "detected." ]
def is_released(config): from distutils.version import LooseVersion v = config.get_version('../version.py') if v is None: raise ValueError('Could not get version') pv = LooseVersion(vstring=v).version if len(pv) > 3: return False return True
['def', 'is_released(config):', 'from', 'distutils.version', 'import', 'LooseVersion', 'v', '=', "config.get_version('../version.py')", 'if', 'v', 'is', 'None:', 'raise', "ValueError('Could", 'not', 'get', "version')", 'pv', '=', 'LooseVersion(vstring=v).version', 'if', 'len(pv)', '>', '3:', 'return', 'False', 'return'...
299,545
iver56/audiomentations
utils.py
calculate_rms
calculate_rms
Given a numpy array of audio samples, return its Root Mean Square (RMS).
[ "Given", "a", "numpy", "array", "of", "audio", "samples,", "return", "its", "Root", "Mean", "Square", "(RMS)." ]
def calculate_rms(samples): return np.sqrt(np.mean(np.square(samples)))
['def', 'calculate_rms(samples):', 'return', 'np.sqrt(np.mean(np.square(samples)))']
403,270
Kvatsx/Artificial-Intelligence-Assignments
test_polyint.py
TestCubicSpline.check_correctness
check_correctness
Check that spline coefficients satisfy the continuity and boundary conditions.
[ "Check", "that", "spline", "coefficients", "satisfy", "the", "continuity", "and", "boundary", "conditions." ]
def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot', tol=1e-14): x = S.x c = S.c dx = np.diff(x) dx = dx.reshape([dx.shape[0]] + [1] * (c.ndim - 2)) dxi = dx[:-1] assert_allclose(c[3, 1:], c[0, :-1] * dxi ** 3 + c[1, :-1] * dxi ** 2 + c[2, :-1] * dxi + c[3, :-1], rtol=tol, atol=t...
['def', 'check_correctness(S,', "bc_start='not-a-knot',", "bc_end='not-a-knot',", 'tol=1e-14):', 'x', '=', 'S.x', 'c', '=', 'S.c', 'dx', '=', 'np.diff(x)', 'dx', '=', 'dx.reshape([dx.shape[0]]', '+', '[1]', '*', '(c.ndim', '-', '2))', 'dxi', '=', 'dx[:-1]', 'assert_allclose(c[3,', '1:],', 'c[0,', ':-1]', '*', 'dxi', '*...
77,492
weimin17/Object-Detection_HelmetDetection
synthetic_data_utils.py
add_alignment_projections
add_alignment_projections
Create a matrix that aligns the datasets a bit, under the assumption that each dataset is observing the same underlying dynamical system.
[ "Create", "a", "matrix", "that", "aligns", "the", "datasets", "a", "bit,", "under", "the", "assumption", "that", "each", "dataset", "is", "observing", "the", "same", "underlying", "dynamical", "system." ]
def add_alignment_projections(datasets, npcs, ntime=None, nsamples=None): nchannels_all = 0 channel_idxs = {} conditions_all = {} nconditions_all = 0 for (name, dataset) in datasets.items(): cidxs = np.where(dataset['P_sxn'])[1] channel_idxs[name] = [cidxs[0], cidxs[-1] + 1] ...
['def', 'add_alignment_projections(datasets,', 'npcs,', 'ntime=None,', 'nsamples=None):', 'nchannels_all', '=', '0', 'channel_idxs', '=', '{}', 'conditions_all', '=', '{}', 'nconditions_all', '=', '0', 'for', '(name,', 'dataset)', 'in', 'datasets.items():', 'cidxs', '=', "np.where(dataset['P_sxn'])[1]", 'channel_idxs[n...
757,864
arshpreetsingh/quantopian-machinelearning
debugger.py
Pdb.do_debug
do_debug
debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).
[ "debug", "code", "Enter", "a", "recursive", "debugger", "that", "steps", "through", "the", "code", "argument", "(which", "is", "an", "arbitrary", "expression", "or", "statement", "to", "be", "executed", "in", "the", "current", "environment)." ]
def do_debug(self, arg): sys.settrace(None) globals = self.curframe.f_globals locals = self.curframe_locals p = self.__class__(completekey=self.completekey, stdin=self.stdin, stdout=self.stdout) p.use_rawinput = self.use_rawinput p.prompt = '(%s) ' % self.prompt.strip() self.message('ENTERIN...
['def', 'do_debug(self,', 'arg):', 'sys.settrace(None)', 'globals', '=', 'self.curframe.f_globals', 'locals', '=', 'self.curframe_locals', 'p', '=', 'self.__class__(completekey=self.completekey,', 'stdin=self.stdin,', 'stdout=self.stdout)', 'p.use_rawinput', '=', 'self.use_rawinput', 'p.prompt', '=', "'(%s)", "'", '%',...
817,040
enuguru/artificial_intelligence_and_machine_learning
data.py
CoverageDataFiles.read
read
Read the coverage data.
[ "Read", "the", "coverage", "data." ]
def read(self, data): if os.path.exists(self.filename): data.read_file(self.filename)
['def', 'read(self,', 'data):', 'if', 'os.path.exists(self.filename):', 'data.read_file(self.filename)']
157,330
google-research/scenic
svhn_dataset.py
get_dataset
get_dataset
Returns generators for the SVHN train, validation, and test set.
[ "Returns", "generators", "for", "the", "SVHN", "train,", "validation,", "and", "test", "set." ]
def get_dataset(*, batch_size, eval_batch_size, num_shards, dtype_str='float32', shuffle_seed=0, rng=None, dataset_configs=None, dataset_service_address: Optional[str]=None): del rng dataset_configs = dataset_configs or {} data_augmentations = dataset_configs.get('data_augmentations', []) for da in data...
['def', 'get_dataset(*,', 'batch_size,', 'eval_batch_size,', 'num_shards,', "dtype_str='float32',", 'shuffle_seed=0,', 'rng=None,', 'dataset_configs=None,', 'dataset_service_address:', 'Optional[str]=None):', 'del', 'rng', 'dataset_configs', '=', 'dataset_configs', 'or', '{}', 'data_augmentations', '=', "dataset_config...
846,053
sunary/nlp
dureader_eval.py
get_entity_result
get_entity_result
Prepare answers for task 'entity'.
[ "Prepare", "answers", "for", "task", "'entity'." ]
def get_entity_result(qid, pred_result, ref_result): if ref_result[qid]['question_type'] != 'ENTITY': return (None, None) return get_main_result(qid, pred_result, ref_result)
['def', 'get_entity_result(qid,', 'pred_result,', 'ref_result):', 'if', "ref_result[qid]['question_type']", '!=', "'ENTITY':", 'return', '(None,', 'None)', 'return', 'get_main_result(qid,', 'pred_result,', 'ref_result)']
808,769
MushroomRL/mushroom-rl
viewer.py
Viewer.circle
circle
Draw a circle on the screen.
[ "Draw", "a", "circle", "on", "the", "screen." ]
def circle(self, center, radius, color=(255, 255, 255), width=0): center = self._transform(center) radius = int(radius * self._ratio[0]) pygame.draw.circle(self.screen, color, center, radius, width)
['def', 'circle(self,', 'center,', 'radius,', 'color=(255,', '255,', '255),', 'width=0):', 'center', '=', 'self._transform(center)', 'radius', '=', 'int(radius', '*', 'self._ratio[0])', 'pygame.draw.circle(self.screen,', 'color,', 'center,', 'radius,', 'width)']
266,185
open-mmlab/mmdetection3d
box_np_ops.py
depth_to_points
depth_to_points
Convert depth map to points.
[ "Convert", "depth", "map", "to", "points." ]
def depth_to_points(depth, trunc_pixel): num_pts = np.sum(depth[trunc_pixel:,] > 0.1) points = np.zeros((num_pts, 3), dtype=depth.dtype) x = np.array([0, 0, 1], dtype=depth.dtype) k = 0 for i in range(trunc_pixel, depth.shape[0]): for j in range(depth.shape[1]): if depth[i, j] > ...
['def', 'depth_to_points(depth,', 'trunc_pixel):', 'num_pts', '=', 'np.sum(depth[trunc_pixel:,]', '>', '0.1)', 'points', '=', 'np.zeros((num_pts,', '3),', 'dtype=depth.dtype)', 'x', '=', 'np.array([0,', '0,', '1],', 'dtype=depth.dtype)', 'k', '=', '0', 'for', 'i', 'in', 'range(trunc_pixel,', 'depth.shape[0]):', 'for', ...
632,299