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 |
|---|---|---|---|---|---|---|---|---|
sunishsheth2009/ChatterBot | compiler.py | CodeGenerator.end_write | end_write | End the writing process started by `start_write`. | [
"End",
"the",
"writing",
"process",
"started",
"by",
"`start_write`."
] | def end_write(self, frame):
if frame.buffer is not None:
self.write(')') | ['def', 'end_write(self,', 'frame):', 'if', 'frame.buffer', 'is', 'not', 'None:', "self.write(')')"] | 478,933 |
instadeepai/jumanji | space.py | Space.volume | volume | Returns the volume as a float to prevent from overflow with 32 bits. | [
"Returns",
"the",
"volume",
"as",
"a",
"float",
"to",
"prevent",
"from",
"overflow",
"with",
"32",
"bits."
] | def volume(self) -> chex.Numeric:
x_len = jnp.asarray(self.x2 - self.x1, float)
y_len = jnp.asarray(self.y2 - self.y1, float)
z_len = jnp.asarray(self.z2 - self.z1, float)
return x_len * y_len * z_len | ['def', 'volume(self)', '->', 'chex.Numeric:', 'x_len', '=', 'jnp.asarray(self.x2', '-', 'self.x1,', 'float)', 'y_len', '=', 'jnp.asarray(self.y2', '-', 'self.y1,', 'float)', 'z_len', '=', 'jnp.asarray(self.z2', '-', 'self.z1,', 'float)', 'return', 'x_len', '*', 'y_len', '*', 'z_len'] | 594,186 |
ronrest/kitti_semantic_segmentation | base.py | SegmentationModel.get_batch | get_batch | Get the ith batch from the data. | [
"Get",
"the",
"ith",
"batch",
"from",
"the",
"data."
] | def get_batch(self, i, batch_size, X, Y=None):
X_batch = X[batch_size * i:batch_size * (i + 1)]
if self.dynamic:
X_batch = load_batch_of_images(X_batch, img_shape=self.img_shape)
if Y is not None:
Y_batch = Y[batch_size * i:batch_size * (i + 1)]
return (X_batch, Y_batch)
else:
... | ['def', 'get_batch(self,', 'i,', 'batch_size,', 'X,', 'Y=None):', 'X_batch', '=', 'X[batch_size', '*', 'i:batch_size', '*', '(i', '+', '1)]', 'if', 'self.dynamic:', 'X_batch', '=', 'load_batch_of_images(X_batch,', 'img_shape=self.img_shape)', 'if', 'Y', 'is', 'not', 'None:', 'Y_batch', '=', 'Y[batch_size', '*', 'i:batc... | 596,371 |
yukitaka13-1110/NaturalLanguageProcessing | run_classifier_with_tfhub.py | model_fn_builder | model_fn_builder | Returns `model_fn` closure for TPUEstimator. | [
"Returns",
"`model_fn`",
"closure",
"for",
"TPUEstimator."
] | def model_fn_builder(num_labels, learning_rate, num_train_steps, num_warmup_steps, use_tpu, bert_hub_module_handle):
def model_fn(features, labels, mode, params):
tf.logging.info('*** Features ***')
for name in sorted(features.keys()):
tf.logging.info(' name = %s, shape = %s' % (name, ... | ['def', 'model_fn_builder(num_labels,', 'learning_rate,', 'num_train_steps,', 'num_warmup_steps,', 'use_tpu,', 'bert_hub_module_handle):', 'def', 'model_fn(features,', 'labels,', 'mode,', 'params):', "tf.logging.info('***", 'Features', "***')", 'for', 'name', 'in', 'sorted(features.keys()):', "tf.logging.info('", 'name... | 798,210 |
Eric3911/OpenAGI | schedule.py | PipeSchedule.num_stages | num_stages | The number of total pipeline stages used to configure this schedule. | [
"The",
"number",
"of",
"total",
"pipeline",
"stages",
"used",
"to",
"configure",
"this",
"schedule."
] | def num_stages(self):
return self.stages | ['def', 'num_stages(self):', 'return', 'self.stages'] | 252,175 |
Xianpeng919/MonoCon | test_utils.py | TestCase.assertAllEqual | assertAllEqual | Asserts that two numpy arrays have the same values. | [
"Asserts",
"that",
"two",
"numpy",
"arrays",
"have",
"the",
"same",
"values."
] | def assertAllEqual(self, a, b):
a = self._GetNdArray(a)
b = self._GetNdArray(b)
self.assertEqual(a.shape, b.shape, 'Shape mismatch: expected %s, got %s.' % (a.shape, b.shape))
same = a == b
if a.dtype == np.float32 or a.dtype == np.float64:
same = np.logical_or(same, np.logical_and(np.isnan(... | ['def', 'assertAllEqual(self,', 'a,', 'b):', 'a', '=', 'self._GetNdArray(a)', 'b', '=', 'self._GetNdArray(b)', 'self.assertEqual(a.shape,', 'b.shape,', "'Shape", 'mismatch:', 'expected', '%s,', 'got', "%s.'", '%', '(a.shape,', 'b.shape))', 'same', '=', 'a', '==', 'b', 'if', 'a.dtype', '==', 'np.float32', 'or', 'a.dtype... | 654,679 |
caiiiac/Machine-Learning-with-Python | _parallel_backends.py | ParallelBackendBase.get_exceptions | get_exceptions | List of exception types to be captured. | [
"List",
"of",
"exception",
"types",
"to",
"be",
"captured."
] | def get_exceptions(self):
return [] | ['def', 'get_exceptions(self):', 'return', '[]'] | 720,745 |
Katja-M/Python_NaturalLanguageProcessing | transforms.py | LockableBbox.locked_x1 | locked_x1 | float or None: The value used for the locked x1. | [
"float",
"or",
"None:",
"The",
"value",
"used",
"for",
"the",
"locked",
"x1."
] | def locked_x1(self):
if self._locked_points.mask[1, 0]:
return None
else:
return self._locked_points[1, 0] | ['def', 'locked_x1(self):', 'if', 'self._locked_points.mask[1,', '0]:', 'return', 'None', 'else:', 'return', 'self._locked_points[1,', '0]'] | 865,001 |
Shajiu/NaturalLanguageProcessing | tokenization.py | convert_to_unicode | convert_to_unicode | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | [
"Converts",
"`text`",
"to",
"Unicode",
"(if",
"it's",
"not",
"already),",
"assuming",
"utf-8",
"input."
] | def convert_to_unicode(text):
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError('Unsupported string type: %s' % type(text))
elif six.PY2:
if isinstance(t... | ['def', 'convert_to_unicode(text):', 'if', 'six.PY3:', 'if', 'isinstance(text,', 'str):', 'return', 'text', 'elif', 'isinstance(text,', 'bytes):', 'return', "text.decode('utf-8',", "'ignore')", 'else:', 'raise', "ValueError('Unsupported", 'string', 'type:', "%s'", '%', 'type(text))', 'elif', 'six.PY2:', 'if', 'isinstan... | 799,846 |
xingyizhou/CenterTrack | evaluate_tracking.py | trackingEvaluation.createEvalDir | createEvalDir | Creates directory to store evaluation results and data for visualization. | [
"Creates",
"directory",
"to",
"store",
"evaluation",
"results",
"and",
"data",
"for",
"visualization."
] | def createEvalDir(self):
self.eval_dir = os.path.join(self.t_sha, 'eval', self.cls)
if not os.path.exists(self.eval_dir):
print('create directory:', self.eval_dir)
os.makedirs(self.eval_dir)
print('done') | ['def', 'createEvalDir(self):', 'self.eval_dir', '=', 'os.path.join(self.t_sha,', "'eval',", 'self.cls)', 'if', 'not', 'os.path.exists(self.eval_dir):', "print('create", "directory:',", 'self.eval_dir)', 'os.makedirs(self.eval_dir)', "print('done')"] | 457,722 |
lancopku/Graph-to-seq-comment-generation | pd_utils.py | import_column | import_column | Merge a column from a file. | [
"Merge",
"a",
"column",
"from",
"a",
"file."
] | def import_column(fin, fcol, fout, col, sep_in, sep_out, contain_header=False):
fcol = open(fcol, 'r')
lines = fcol.read().splitlines()
df = pd.read_csv(fin, sep=sep_in, quoting=csv.QUOTE_NONE)
df[col] = lines
df.to_csv(fout, sep=sep_out, header=True, index=False) | ['def', 'import_column(fin,', 'fcol,', 'fout,', 'col,', 'sep_in,', 'sep_out,', 'contain_header=False):', 'fcol', '=', 'open(fcol,', "'r')", 'lines', '=', 'fcol.read().splitlines()', 'df', '=', 'pd.read_csv(fin,', 'sep=sep_in,', 'quoting=csv.QUOTE_NONE)', 'df[col]', '=', 'lines', 'df.to_csv(fout,', 'sep=sep_out,', 'head... | 580,404 |
fcjian/LOCE | gfl_head.py | GFLHead.anchor_center | anchor_center | Get anchor centers from anchors. | [
"Get",
"anchor",
"centers",
"from",
"anchors."
] | def anchor_center(self, anchors):
anchors_cx = (anchors[:, 2] + anchors[:, 0]) / 2
anchors_cy = (anchors[:, 3] + anchors[:, 1]) / 2
return torch.stack([anchors_cx, anchors_cy], dim=-1) | ['def', 'anchor_center(self,', 'anchors):', 'anchors_cx', '=', '(anchors[:,', '2]', '+', 'anchors[:,', '0])', '/', '2', 'anchors_cy', '=', '(anchors[:,', '3]', '+', 'anchors[:,', '1])', '/', '2', 'return', 'torch.stack([anchors_cx,', 'anchors_cy],', 'dim=-1)'] | 614,492 |
PacktPublishing/Hands-On-Artificial--for-Banking | base.py | ExtensionArray.ndim | ndim | Extension Arrays are only allowed to be 1-dimensional. | [
"Extension",
"Arrays",
"are",
"only",
"allowed",
"to",
"be",
"1-dimensional."
] | def ndim(self) -> int:
return 1 | ['def', 'ndim(self)', '->', 'int:', 'return', '1'] | 236,244 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | vgslspecs.py | VGSLSpecs.AddFCLayer | AddFCLayer | Parse expression and add Fully Connected Layer. | [
"Parse",
"expression",
"and",
"add",
"Fully",
"Connected",
"Layer."
] | def AddFCLayer(self, prev_layer, index):
pattern = re.compile('(F)(s|t|r|l|m)({\\w+})?(\\d+)')
m = pattern.match(self.model_str, index)
if m is None:
return (None, None)
fn = self._NonLinearity(m.group(2))
name = self._GetLayerName(m.group(0), index, m.group(3))
depth = int(m.group(4))
... | ['def', 'AddFCLayer(self,', 'prev_layer,', 'index):', 'pattern', '=', "re.compile('(F)(s|t|r|l|m)({\\\\w+})?(\\\\d+)')", 'm', '=', 'pattern.match(self.model_str,', 'index)', 'if', 'm', 'is', 'None:', 'return', '(None,', 'None)', 'fn', '=', 'self._NonLinearity(m.group(2))', 'name', '=', 'self._GetLayerName(m.group(0),',... | 27,741 |
gunthercox/ChatterBot | compiler.py | CodeGenerator.macro_def | macro_def | Dump the macro definition for the def created by macro_body. | [
"Dump",
"the",
"macro",
"definition",
"for",
"the",
"def",
"created",
"by",
"macro_body."
] | def macro_def(self, node, frame):
arg_tuple = ', '.join((repr(x.name) for x in node.args))
name = getattr(node, 'name', None)
if len(node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple))
for arg in node.defaults:
self.visit(arg, fra... | ['def', 'macro_def(self,', 'node,', 'frame):', 'arg_tuple', '=', "',", "'.join((repr(x.name)", 'for', 'x', 'in', 'node.args))', 'name', '=', 'getattr(node,', "'name',", 'None)', 'if', 'len(node.args)', '==', '1:', 'arg_tuple', '+=', "','", "self.write('Macro(environment,", 'macro,', '%r,', '(%s),', "('", '%', '(name,',... | 529,170 |
OpenMDAO/OpenMDAO-Framework | test_rbac.py | Object.single_role | single_role | Just a single role assigned. | [
"Just",
"a",
"single",
"role",
"assigned."
] | def single_role(self):
return None | ['def', 'single_role(self):', 'return', 'None'] | 276,216 |
jimtin/Stock_Comparison | kernelspec.py | KernelSpecManager.find_kernel_specs | find_kernel_specs | Returns a dict mapping kernel names to resource directories. | [
"Returns",
"a",
"dict",
"mapping",
"kernel",
"names",
"to",
"resource",
"directories."
] | def find_kernel_specs(self):
d = {}
for kernel_dir in self.kernel_dirs:
kernels = _list_kernels_in(kernel_dir)
for (kname, spec) in kernels.items():
if kname not in d:
self.log.debug('Found kernel %s in %s', kname, kernel_dir)
d[kname] = spec
if NA... | ['def', 'find_kernel_specs(self):', 'd', '=', '{}', 'for', 'kernel_dir', 'in', 'self.kernel_dirs:', 'kernels', '=', '_list_kernels_in(kernel_dir)', 'for', '(kname,', 'spec)', 'in', 'kernels.items():', 'if', 'kname', 'not', 'in', 'd:', "self.log.debug('Found", 'kernel', '%s', 'in', "%s',", 'kname,', 'kernel_dir)', 'd[kn... | 386,023 |
suarez12138/AI-Reversi_IMP_TextDichotomy | wavelets.py | qmf | qmf | Return high-pass qmf filter from low-pass Parameters ---------- hk : array_like Coefficients of high-pass filter. | [
"Return",
"high-pass",
"qmf",
"filter",
"from",
"low-pass",
"Parameters",
"----------",
"hk",
":",
"array_like",
"Coefficients",
"of",
"high-pass",
"filter."
] | def qmf(hk):
N = len(hk) - 1
asgn = [{0: 1, 1: -1}[k % 2] for k in range(N + 1)]
return hk[::-1] * np.array(asgn) | ['def', 'qmf(hk):', 'N', '=', 'len(hk)', '-', '1', 'asgn', '=', '[{0:', '1,', '1:', '-1}[k', '%', '2]', 'for', 'k', 'in', 'range(N', '+', '1)]', 'return', 'hk[::-1]', '*', 'np.array(asgn)'] | 100,017 |
TonyLianLong/VAI-ReinforcementLearning | codegen_util.py | mangle_varname | mangle_varname | Append underscores to ensure that `s` is not a reserved Python keyword. | [
"Append",
"underscores",
"to",
"ensure",
"that",
"`s`",
"is",
"not",
"a",
"reserved",
"Python",
"keyword."
] | def mangle_varname(s):
while s in _PYTHON_RESERVED_KEYWORDS:
s += '_'
return s | ['def', 'mangle_varname(s):', 'while', 's', 'in', '_PYTHON_RESERVED_KEYWORDS:', 's', '+=', "'_'", 'return', 's'] | 439,800 |
gunthercox/ChatterBot | cookies.py | RequestsCookieJar.get_dict | get_dict | Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. | [
"Takes",
"as",
"an",
"argument",
"an",
"optional",
"domain",
"and",
"path",
"and",
"returns",
"a",
"plain",
"old",
"Python",
"dict",
"of",
"name-value",
"pairs",
"of",
"cookies",
"that",
"meet",
"the",
"requirements."
] | def get_dict(self, domain=None, path=None):
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (path is None or cookie.path == path):
dictionary[cookie.name] = cookie.value
return dictionary | ['def', 'get_dict(self,', 'domain=None,', 'path=None):', 'dictionary', '=', '{}', 'for', 'cookie', 'in', 'iter(self):', 'if', '(domain', 'is', 'None', 'or', 'cookie.domain', '==', 'domain)', 'and', '(path', 'is', 'None', 'or', 'cookie.path', '==', 'path):', 'dictionary[cookie.name]', '=', 'cookie.value', 'return', 'dic... | 480,548 |
awslabs/mxnet-lambda | core.py | _convert2ma.getdoc | getdoc | Return the doc of the function (from the doc of the method). | [
"Return",
"the",
"doc",
"of",
"the",
"function",
"(from",
"the",
"doc",
"of",
"the",
"method)."
] | def getdoc(self):
doc = getattr(self._func, '__doc__', None)
sig = get_object_signature(self._func)
if doc:
if sig:
sig = '%s%s\n' % (self._func.__name__, sig)
doc = sig + doc
return doc | ['def', 'getdoc(self):', 'doc', '=', 'getattr(self._func,', "'__doc__',", 'None)', 'sig', '=', 'get_object_signature(self._func)', 'if', 'doc:', 'if', 'sig:', 'sig', '=', "'%s%s\\n'", '%', '(self._func.__name__,', 'sig)', 'doc', '=', 'sig', '+', 'doc', 'return', 'doc'] | 288,818 |
arshpreetsingh/quantopian-machinelearning | easy_install.py | ScriptWriter.best | best | Select the best ScriptWriter for this environment. | [
"Select",
"the",
"best",
"ScriptWriter",
"for",
"this",
"environment."
] | def best(cls):
if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
return WindowsScriptWriter.best()
else:
return cls | ['def', 'best(cls):', 'if', 'sys.platform', '==', "'win32'", 'or', '(os.name', '==', "'java'", 'and', 'os._name', '==', "'nt'):", 'return', 'WindowsScriptWriter.best()', 'else:', 'return', 'cls'] | 893,240 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | preprocessing.py | preprocess_training_image | preprocess_training_image | Preprocesses an image for training. | [
"Preprocesses",
"an",
"image",
"for",
"training."
] | def preprocess_training_image(image, height, width, min_scale, max_scale, p_scale_up, aug_color=True, fast_mode=True):
image = augment_image_scale(image, min_scale, max_scale, p_scale_up)
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, [height, width], align_corners=False)
image... | ['def', 'preprocess_training_image(image,', 'height,', 'width,', 'min_scale,', 'max_scale,', 'p_scale_up,', 'aug_color=True,', 'fast_mode=True):', 'image', '=', 'augment_image_scale(image,', 'min_scale,', 'max_scale,', 'p_scale_up)', 'image', '=', 'tf.expand_dims(image,', '0)', 'image', '=', 'tf.image.resize_bilinear(i... | 29,453 |
weimin17/Object-Detection_HelmetDetection | inference_demo.py | export | export | Exports inference outputs to an output directory. | [
"Exports",
"inference",
"outputs",
"to",
"an",
"output",
"directory."
] | def export(sess, input_pl, output_tensor, input_file_pattern, output_dir):
if output_dir:
_make_dir_if_not_exists(output_dir)
if input_file_pattern:
for file_path in tf.gfile.Glob(input_file_pattern):
input_np = np.asarray(PIL.Image.open(file_path))
output_np = sess.run(o... | ['def', 'export(sess,', 'input_pl,', 'output_tensor,', 'input_file_pattern,', 'output_dir):', 'if', 'output_dir:', '_make_dir_if_not_exists(output_dir)', 'if', 'input_file_pattern:', 'for', 'file_path', 'in', 'tf.gfile.Glob(input_file_pattern):', 'input_np', '=', 'np.asarray(PIL.Image.open(file_path))', 'output_np', '=... | 750,063 |
weimin17/Object-Detection_HelmetDetection | pnasnet.py | large_imagenet_config | large_imagenet_config | Large ImageNet configuration based on PNASNet-5. | [
"Large",
"ImageNet",
"configuration",
"based",
"on",
"PNASNet-5."
] | def large_imagenet_config():
return tf.contrib.training.HParams(stem_multiplier=3.0, dense_dropout_keep_prob=0.5, num_cells=12, filter_scaling_rate=2.0, num_conv_filters=216, drop_path_keep_prob=0.6, use_aux_head=1, num_reduction_layers=2, data_format='NHWC', total_training_steps=250000) | ['def', 'large_imagenet_config():', 'return', 'tf.contrib.training.HParams(stem_multiplier=3.0,', 'dense_dropout_keep_prob=0.5,', 'num_cells=12,', 'filter_scaling_rate=2.0,', 'num_conv_filters=216,', 'drop_path_keep_prob=0.6,', 'use_aux_head=1,', 'num_reduction_layers=2,', "data_format='NHWC',", 'total_training_steps=2... | 759,870 |
MycroftAI/mycroft-core | audioservice.py | AudioService.next | next | Change to next track. | [
"Change",
"to",
"next",
"track."
] | def next(self):
self.bus.emit(Message('mycroft.audio.service.next')) | ['def', 'next(self):', "self.bus.emit(Message('mycroft.audio.service.next'))"] | 290,424 |
mapbox/robosat | tiles.py | buffer_tile_image | buffer_tile_image | Buffers a tile image adding borders on all sides based on adjacent tiles. | [
"Buffers",
"a",
"tile",
"image",
"adding",
"borders",
"on",
"all",
"sides",
"based",
"on",
"adjacent",
"tiles."
] | def buffer_tile_image(tile, tiles, overlap, tile_size, nodata=0):
tiles = dict(tiles)
(x, y, z) = map(int, [tile.x, tile.y, tile.z])
composite_size = tile_size + 2 * overlap
composite = Image.new(mode='RGB', size=(composite_size, composite_size), color=nodata)
path = tiles[tile]
center = Image.o... | ['def', 'buffer_tile_image(tile,', 'tiles,', 'overlap,', 'tile_size,', 'nodata=0):', 'tiles', '=', 'dict(tiles)', '(x,', 'y,', 'z)', '=', 'map(int,', '[tile.x,', 'tile.y,', 'tile.z])', 'composite_size', '=', 'tile_size', '+', '2', '*', 'overlap', 'composite', '=', "Image.new(mode='RGB',", 'size=(composite_size,', 'comp... | 825,973 |
weimin17/Object-Detection_HelmetDetection | coords.py | to_flat | to_flat | Converts from a MiniGo coordinate to a flattened coordinate. | [
"Converts",
"from",
"a",
"MiniGo",
"coordinate",
"to",
"a",
"flattened",
"coordinate."
] | def to_flat(board_size, coord):
if coord is None:
return board_size * board_size
return board_size * coord[0] + coord[1] | ['def', 'to_flat(board_size,', 'coord):', 'if', 'coord', 'is', 'None:', 'return', 'board_size', '*', 'board_size', 'return', 'board_size', '*', 'coord[0]', '+', 'coord[1]'] | 763,814 |
xiaoaleiBLUE/computer_vision | preprocessor_test.py | PreprocessorTest.testResizeToRangeWithInstanceMasksTensorOfSizeZero | testResizeToRangeWithInstanceMasksTensorOfSizeZero | Tests image resizing, checking output sizes. | [
"Tests",
"image",
"resizing,",
"checking",
"output",
"sizes."
] | def testResizeToRangeWithInstanceMasksTensorOfSizeZero(self):
in_image_shape_list = [[60, 40, 3], [15, 30, 3]]
in_masks_shape_list = [[0, 60, 40], [0, 15, 30]]
min_dim = 50
max_dim = 100
expected_image_shape_list = [[75, 50, 3], [50, 100, 3]]
expected_masks_shape_list = [[0, 75, 50], [0, 50, 100... | ['def', 'testResizeToRangeWithInstanceMasksTensorOfSizeZero(self):', 'in_image_shape_list', '=', '[[60,', '40,', '3],', '[15,', '30,', '3]]', 'in_masks_shape_list', '=', '[[0,', '60,', '40],', '[0,', '15,', '30]]', 'min_dim', '=', '50', 'max_dim', '=', '100', 'expected_image_shape_list', '=', '[[75,', '50,', '3],', '[5... | 505,771 |
caiiiac/Machine-Learning-with-Python | base.py | Index.equals | equals | Determines if two Index objects contain the same elements. | [
"Determines",
"if",
"two",
"Index",
"objects",
"contain",
"the",
"same",
"elements."
] | def equals(self, other):
if self.is_(other):
return True
if not isinstance(other, Index):
return False
if is_object_dtype(self) and (not is_object_dtype(other)):
return other.equals(self)
try:
return array_equivalent(_values_from_object(self), _values_from_object(other))
... | ['def', 'equals(self,', 'other):', 'if', 'self.is_(other):', 'return', 'True', 'if', 'not', 'isinstance(other,', 'Index):', 'return', 'False', 'if', 'is_object_dtype(self)', 'and', '(not', 'is_object_dtype(other)):', 'return', 'other.equals(self)', 'try:', 'return', 'array_equivalent(_values_from_object(self),', '_valu... | 718,057 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | component.py | ComponentBuilderBase.advance_counters | advance_counters | Returns ops to advance the per-component step and total counters. | [
"Returns",
"ops",
"to",
"advance",
"the",
"per-component",
"step",
"and",
"total",
"counters."
] | def advance_counters(self, total):
update_total = tf.assign_add(self._total, total, use_locking=True)
update_step = tf.assign_add(self._step, 1, use_locking=True)
return tf.group(update_total, update_step) | ['def', 'advance_counters(self,', 'total):', 'update_total', '=', 'tf.assign_add(self._total,', 'total,', 'use_locking=True)', 'update_step', '=', 'tf.assign_add(self._step,', '1,', 'use_locking=True)', 'return', 'tf.group(update_total,', 'update_step)'] | 28,105 |
neardws/Game-Theoretic-Deep-Reinforcement-Learning | gradient.py | GradientTape.watch | watch | Ensures that `tensor` is being traced by this tape. | [
"Ensures",
"that",
"`tensor`",
"is",
"being",
"traced",
"by",
"this",
"tape."
] | def watch(self, tensor):
for t in nest.flatten(tensor, expand_composites=True):
if not (_pywrap_utils.IsTensor(t) or _pywrap_utils.IsVariable(t)):
raise ValueError('Passed in object of type {}, not tf.Tensor'.format(type(t)))
if not backprop_util.IsTrainable(t):
logging.log_f... | ['def', 'watch(self,', 'tensor):', 'for', 't', 'in', 'nest.flatten(tensor,', 'expand_composites=True):', 'if', 'not', '(_pywrap_utils.IsTensor(t)', 'or', '_pywrap_utils.IsVariable(t)):', 'raise', "ValueError('Passed", 'in', 'object', 'of', 'type', '{},', 'not', "tf.Tensor'.format(type(t)))", 'if', 'not', 'backprop_util... | 199,659 |
google-research/ssl_detection | param.py | GraphVarParam.setup_graph | setup_graph | Will setup the assign operator for that variable. | [
"Will",
"setup",
"the",
"assign",
"operator",
"for",
"that",
"variable."
] | def setup_graph(self):
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError('{} is not a variable in the graph!'.format(self.var_name)) | ['def', 'setup_graph(self):', 'all_vars', '=', 'tfv1.global_variables()', '+', 'tfv1.local_variables()', 'for', 'v', 'in', 'all_vars:', 'if', 'v.name', '==', 'self.var_name:', 'self.var', '=', 'v', 'break', 'else:', 'raise', "ValueError('{}", 'is', 'not', 'a', 'variable', 'in', 'the', "graph!'.format(self.var_name))"] | 382,173 |
gaurav0535/NaturalLanguageProcessing | trigram_model.py | TrigramModel.count_ngrams | count_ngrams | COMPLETE THIS METHOD (PART 2) Given a corpus iterator, populate dictionaries of unigram, bigram, and trigram counts. | [
"COMPLETE",
"THIS",
"METHOD",
"(PART",
"2)",
"Given",
"a",
"corpus",
"iterator,",
"populate",
"dictionaries",
"of",
"unigram,",
"bigram,",
"and",
"trigram",
"counts."
] | def count_ngrams(self, corpus):
self.unigramcounts = {}
self.bigramcounts = {}
self.trigramcounts = {}
self.total_words = 0
num_starts = 0
for sentence in corpus:
num_starts += 1
unigrams = get_ngrams(sentence, 1)
bigrams = get_ngrams(sentence, 2)
trigrams = get_n... | ['def', 'count_ngrams(self,', 'corpus):', 'self.unigramcounts', '=', '{}', 'self.bigramcounts', '=', '{}', 'self.trigramcounts', '=', '{}', 'self.total_words', '=', '0', 'num_starts', '=', '0', 'for', 'sentence', 'in', 'corpus:', 'num_starts', '+=', '1', 'unigrams', '=', 'get_ngrams(sentence,', '1)', 'bigrams', '=', 'g... | 677,597 |
deepmind/meltingpot | running_with_scissors_in_the_matrix__repeated.py | create_avatar_object | create_avatar_object | Create an avatar object given self vs other sprite data. | [
"Create",
"an",
"avatar",
"object",
"given",
"self",
"vs",
"other",
"sprite",
"data."
] | def create_avatar_object(player_idx: int, all_source_sprite_names: Sequence[str], target_sprite_self: Dict[str, Any], target_sprite_other: Dict[str, Any], turn_off_default_reward: bool=False) -> Dict[str, Any]:
lua_index = player_idx + 1
source_sprite_self = 'Avatar' + str(lua_index)
custom_sprite_map = {so... | ['def', 'create_avatar_object(player_idx:', 'int,', 'all_source_sprite_names:', 'Sequence[str],', 'target_sprite_self:', 'Dict[str,', 'Any],', 'target_sprite_other:', 'Dict[str,', 'Any],', 'turn_off_default_reward:', 'bool=False)', '->', 'Dict[str,', 'Any]:', 'lua_index', '=', 'player_idx', '+', '1', 'source_sprite_sel... | 285,843 |
Ruturaj123/Flowchart-Detection | tensor_shape.py | TensorShape.num_elements | num_elements | Returns the total number of elements, or none for incomplete shapes. | [
"Returns",
"the",
"total",
"number",
"of",
"elements,",
"or",
"none",
"for",
"incomplete",
"shapes."
] | def num_elements(self):
if self.is_fully_defined():
size = 1
for dim in self._dims:
size *= dim.value
return size
else:
return None | ['def', 'num_elements(self):', 'if', 'self.is_fully_defined():', 'size', '=', '1', 'for', 'dim', 'in', 'self._dims:', 'size', '*=', 'dim.value', 'return', 'size', 'else:', 'return', 'None'] | 605,518 |
victorchen96/ReNode | ppr.py | topk_ppr_matrix | topk_ppr_matrix | Create a sparse matrix where each node has up to the topk PPR neighbors and their weights. | [
"Create",
"a",
"sparse",
"matrix",
"where",
"each",
"node",
"has",
"up",
"to",
"the",
"topk",
"PPR",
"neighbors",
"and",
"their",
"weights."
] | def topk_ppr_matrix(adj_matrix, alpha, eps, idx, topk, normalization='sym'):
topk_matrix = ppr_topk(adj_matrix, alpha, eps, idx, topk).tocsr()
if normalization == 'sym':
deg = adj_matrix.sum(1).A1
deg_sqrt = np.sqrt(np.maximum(deg, 1e-12))
deg_inv_sqrt = 1.0 / deg_sqrt
(row, col)... | ['def', 'topk_ppr_matrix(adj_matrix,', 'alpha,', 'eps,', 'idx,', 'topk,', "normalization='sym'):", 'topk_matrix', '=', 'ppr_topk(adj_matrix,', 'alpha,', 'eps,', 'idx,', 'topk).tocsr()', 'if', 'normalization', '==', "'sym':", 'deg', '=', 'adj_matrix.sum(1).A1', 'deg_sqrt', '=', 'np.sqrt(np.maximum(deg,', '1e-12))', 'deg... | 346,057 |
weimin17/Object-Detection_HelmetDetection | prediction_train.py | mean_squared_error | mean_squared_error | L2 distance between tensors true and pred. | [
"L2",
"distance",
"between",
"tensors",
"true",
"and",
"pred."
] | def mean_squared_error(true, pred):
return tf.reduce_sum(tf.square(true - pred)) / tf.to_float(tf.size(pred)) | ['def', 'mean_squared_error(true,', 'pred):', 'return', 'tf.reduce_sum(tf.square(true', '-', 'pred))', '/', 'tf.to_float(tf.size(pred))'] | 754,101 |
techexpert1611/Natural-Language-Processing | a2_test.py | TestA2.test_hmm_fit_emission | test_hmm_fit_emission | Test supervised HMM learning emission probabilities. | [
"Test",
"supervised",
"HMM",
"learning",
"emission",
"probabilities."
] | def test_hmm_fit_emission(self):
model = HMM()
model.fit(test_sentences, test_tags)
self.assertEqual(0.2, round(model.emission_probas['N']['ball'], 1))
self.assertEqual(0.4, round(model.emission_probas['N']['boy'], 1))
self.assertEqual(0.4, round(model.emission_probas['N']['dog'], 1))
self.asser... | ['def', 'test_hmm_fit_emission(self):', 'model', '=', 'HMM()', 'model.fit(test_sentences,', 'test_tags)', 'self.assertEqual(0.2,', "round(model.emission_probas['N']['ball'],", '1))', 'self.assertEqual(0.4,', "round(model.emission_probas['N']['boy'],", '1))', 'self.assertEqual(0.4,', "round(model.emission_probas['N']['d... | 703,774 |
jbwang1997/OBBDetection | center_region_assigner.py | scale_boxes | scale_boxes | Expand an array of boxes by a given scale. | [
"Expand",
"an",
"array",
"of",
"boxes",
"by",
"a",
"given",
"scale."
] | def scale_boxes(bboxes, scale):
assert bboxes.size(1) == 4
w_half = (bboxes[:, 2] - bboxes[:, 0]) * 0.5
h_half = (bboxes[:, 3] - bboxes[:, 1]) * 0.5
x_c = (bboxes[:, 2] + bboxes[:, 0]) * 0.5
y_c = (bboxes[:, 3] + bboxes[:, 1]) * 0.5
w_half *= scale
h_half *= scale
boxes_scaled = torch.ze... | ['def', 'scale_boxes(bboxes,', 'scale):', 'assert', 'bboxes.size(1)', '==', '4', 'w_half', '=', '(bboxes[:,', '2]', '-', 'bboxes[:,', '0])', '*', '0.5', 'h_half', '=', '(bboxes[:,', '3]', '-', 'bboxes[:,', '1])', '*', '0.5', 'x_c', '=', '(bboxes[:,', '2]', '+', 'bboxes[:,', '0])', '*', '0.5', 'y_c', '=', '(bboxes[:,', ... | 725,194 |
fcjian/LOCE | utils.py | NumClassCheckHook.before_val_epoch | before_val_epoch | Check whether the dataset in val epoch is compatible with head. | [
"Check",
"whether",
"the",
"dataset",
"in",
"val",
"epoch",
"is",
"compatible",
"with",
"head."
] | def before_val_epoch(self, runner):
self._check_head(runner) | ['def', 'before_val_epoch(self,', 'runner):', 'self._check_head(runner)'] | 614,363 |
triaquae/triaquae | PKCS1_OAEP.py | PKCS1OAEP_Cipher.can_decrypt | can_decrypt | Return True/1 if this cipher object can be used for decryption. | [
"Return",
"True/1",
"if",
"this",
"cipher",
"object",
"can",
"be",
"used",
"for",
"decryption."
] | def can_decrypt(self):
return self._key.can_decrypt() | ['def', 'can_decrypt(self):', 'return', 'self._key.can_decrypt()'] | 356,282 |
sergiosaraiva/artificial-intelligence | misc_util.py | get_frame | get_frame | Return frame object from call stack with given level. | [
"Return",
"frame",
"object",
"from",
"call",
"stack",
"with",
"given",
"level."
] | def get_frame(level=0):
try:
return sys._getframe(level + 1)
except AttributeError:
frame = sys.exc_info()[2].tb_frame
for _ in range(level + 1):
frame = frame.f_back
return frame | ['def', 'get_frame(level=0):', 'try:', 'return', 'sys._getframe(level', '+', '1)', 'except', 'AttributeError:', 'frame', '=', 'sys.exc_info()[2].tb_frame', 'for', '_', 'in', 'range(level', '+', '1):', 'frame', '=', 'frame.f_back', 'return', 'frame'] | 62,742 |
gunthercox/ChatterBot | core.py | Locale.get_territory_name | get_territory_name | Return the territory name in the given locale. | [
"Return",
"the",
"territory",
"name",
"in",
"the",
"given",
"locale."
] | def get_territory_name(self, locale=None):
if locale is None:
locale = self
locale = Locale.parse(locale)
return locale.territories.get(self.territory) | ['def', 'get_territory_name(self,', 'locale=None):', 'if', 'locale', 'is', 'None:', 'locale', '=', 'self', 'locale', '=', 'Locale.parse(locale)', 'return', 'locale.territories.get(self.territory)'] | 478,431 |
devashish-patel/webcam-motion-detector | environment.py | copy_cache | copy_cache | Create an empty copy of the given cache. | [
"Create",
"an",
"empty",
"copy",
"of",
"the",
"given",
"cache."
] | def copy_cache(cache):
if cache is None:
return None
elif type(cache) is dict:
return {}
return LRUCache(cache.capacity) | ['def', 'copy_cache(cache):', 'if', 'cache', 'is', 'None:', 'return', 'None', 'elif', 'type(cache)', 'is', 'dict:', 'return', '{}', 'return', 'LRUCache(cache.capacity)'] | 979,678 |
mhubii/artificial_intelligence | selectors.py | BaseSelector.register | register | Register a file object for a set of events to monitor. | [
"Register",
"a",
"file",
"object",
"for",
"a",
"set",
"of",
"events",
"to",
"monitor."
] | def register(self, fileobj, events, data=None):
if not events or events & ~(EVENT_READ | EVENT_WRITE):
raise ValueError('Invalid events: {0!r}'.format(events))
key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
if key.fd in self._fd_to_key:
raise KeyError('{0!r} (FD {1})... | ['def', 'register(self,', 'fileobj,', 'events,', 'data=None):', 'if', 'not', 'events', 'or', 'events', '&', '~(EVENT_READ', '|', 'EVENT_WRITE):', 'raise', "ValueError('Invalid", 'events:', "{0!r}'.format(events))", 'key', '=', 'SelectorKey(fileobj,', 'self._fileobj_lookup(fileobj),', 'events,', 'data)', 'if', 'key.fd',... | 140,585 |
googleapis/python-aiplatform | client.py | ScheduleServiceClient.execution_path | execution_path | Returns a fully-qualified execution string. | [
"Returns",
"a",
"fully-qualified",
"execution",
"string."
] | def execution_path(project: str, location: str, metadata_store: str, execution: str) -> str:
return 'projects/{project}/locations/{location}/metadataStores/{metadata_store}/executions/{execution}'.format(project=project, location=location, metadata_store=metadata_store, execution=execution) | ['def', 'execution_path(project:', 'str,', 'location:', 'str,', 'metadata_store:', 'str,', 'execution:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/metadataStores/{metadata_store}/executions/{execution}'.format(project=project,", 'location=location,', 'metadata_store=metadata_store,', 'ex... | 813,965 |
myothida/Supervised-Machine-Learning | test_hashing.py | test_trivial_hash | test_trivial_hash | Smoke test hash on various types. | [
"Smoke",
"test",
"hash",
"on",
"various",
"types."
] | def test_trivial_hash(obj1, obj2):
are_hashes_equal = hash(obj1) == hash(obj2)
are_objs_identical = obj1 is obj2
assert are_hashes_equal == are_objs_identical | ['def', 'test_trivial_hash(obj1,', 'obj2):', 'are_hashes_equal', '=', 'hash(obj1)', '==', 'hash(obj2)', 'are_objs_identical', '=', 'obj1', 'is', 'obj2', 'assert', 'are_hashes_equal', '==', 'are_objs_identical'] | 361,535 |
facebookresearch/CompilerGym | validate_test.py | test_validate_state_without_state_reward | test_validate_state_without_state_reward | Validating state when state has no reward value. | [
"Validating",
"state",
"when",
"state",
"has",
"no",
"reward",
"value."
] | def test_validate_state_without_state_reward():
state = CompilerEnvState(benchmark='benchmark://cbench-v1/crc32', walltime=1, commandline='opt input.bc -o output.bc')
with gym.make('llvm-v0', reward_space='IrInstructionCount') as env:
result = env.validate(state)
assert result.okay()
assert not... | ['def', 'test_validate_state_without_state_reward():', 'state', '=', "CompilerEnvState(benchmark='benchmark://cbench-v1/crc32',", 'walltime=1,', "commandline='opt", 'input.bc', '-o', "output.bc')", 'with', "gym.make('llvm-v0',", "reward_space='IrInstructionCount')", 'as', 'env:', 'result', '=', 'env.validate(state)', '... | 125,950 |
bfortuner/labelml | target_assigner.py | create_target_assigner | create_target_assigner | Factory function for creating standard target assigners. | [
"Factory",
"function",
"for",
"creating",
"standard",
"target",
"assigners."
] | def create_target_assigner(reference, stage=None, positive_class_weight=1.0, negative_class_weight=1.0, unmatched_cls_target=None):
if reference == 'Multibox' and stage == 'proposal':
similarity_calc = sim_calc.NegSqDistSimilarity()
matcher = bipartite_matcher.GreedyBipartiteMatcher()
box_co... | ['def', 'create_target_assigner(reference,', 'stage=None,', 'positive_class_weight=1.0,', 'negative_class_weight=1.0,', 'unmatched_cls_target=None):', 'if', 'reference', '==', "'Multibox'", 'and', 'stage', '==', "'proposal':", 'similarity_calc', '=', 'sim_calc.NegSqDistSimilarity()', 'matcher', '=', 'bipartite_matcher.... | 622,734 |
Ruturaj123/Flowchart-Detection | tpu_function_test.py | FunctionArgCheckTest.testSimple | testSimple | Tests that arg checker works for functions with no varargs or defaults. | [
"Tests",
"that",
"arg",
"checker",
"works",
"for",
"functions",
"with",
"no",
"varargs",
"or",
"defaults."
] | def testSimple(self):
def func(x, y, z):
return x + y + z
self.assertEqual(None, tpu_function.check_function_argument_count(func, 3, None))
self.assertEqual('exactly 3 arguments', tpu_function.check_function_argument_count(func, 2, None))
queue = tpu_feed.InfeedQueue(2)
self.assertEqual(Non... | ['def', 'testSimple(self):', 'def', 'func(x,', 'y,', 'z):', 'return', 'x', '+', 'y', '+', 'z', 'self.assertEqual(None,', 'tpu_function.check_function_argument_count(func,', '3,', 'None))', "self.assertEqual('exactly", '3', "arguments',", 'tpu_function.check_function_argument_count(func,', '2,', 'None))', 'queue', '=', ... | 604,766 |
weimin17/Object-Detection_HelmetDetection | translate.py | translate_text | translate_text | Translate a single string. | [
"Translate",
"a",
"single",
"string."
] | def translate_text(estimator, subtokenizer, txt):
encoded_txt = _encode_and_add_eos(txt, subtokenizer)
def input_fn():
ds = tf.data.Dataset.from_tensors(encoded_txt)
ds = ds.batch(_DECODE_BATCH_SIZE)
return ds
predictions = estimator.predict(input_fn)
translation = next(predicti... | ['def', 'translate_text(estimator,', 'subtokenizer,', 'txt):', 'encoded_txt', '=', '_encode_and_add_eos(txt,', 'subtokenizer)', 'def', 'input_fn():', 'ds', '=', 'tf.data.Dataset.from_tensors(encoded_txt)', 'ds', '=', 'ds.batch(_DECODE_BATCH_SIZE)', 'return', 'ds', 'predictions', '=', 'estimator.predict(input_fn)', 'tra... | 748,717 |
SilenceDut/nbaplus-server | _html5lib.py | Element.reparentChildren | reparentChildren | Move all of this tag's children into another tag. | [
"Move",
"all",
"of",
"this",
"tag's",
"children",
"into",
"another",
"tag."
] | def reparentChildren(self, new_parent):
element = self.element
new_parent_element = new_parent.element
final_next_element = element.next_sibling
new_parents_last_descendant = new_parent_element._last_descendant(False, False)
if len(new_parent_element.contents) > 0:
new_parents_last_child = n... | ['def', 'reparentChildren(self,', 'new_parent):', 'element', '=', 'self.element', 'new_parent_element', '=', 'new_parent.element', 'final_next_element', '=', 'element.next_sibling', 'new_parents_last_descendant', '=', 'new_parent_element._last_descendant(False,', 'False)', 'if', 'len(new_parent_element.contents)', '>',... | 291,937 |
aasimkhan0207/computer_vision | common.py | polygons_to_mask | polygons_to_mask | Convert polygons to binary masks. | [
"Convert",
"polygons",
"to",
"binary",
"masks."
] | def polygons_to_mask(polys, height, width):
polys = [p.flatten().tolist() for p in polys]
assert len(polys) > 0, 'Polygons are empty!'
import pycocotools.mask as cocomask
rles = cocomask.frPyObjects(polys, height, width)
rle = cocomask.merge(rles)
return cocomask.decode(rle) | ['def', 'polygons_to_mask(polys,', 'height,', 'width):', 'polys', '=', '[p.flatten().tolist()', 'for', 'p', 'in', 'polys]', 'assert', 'len(polys)', '>', '0,', "'Polygons", 'are', "empty!'", 'import', 'pycocotools.mask', 'as', 'cocomask', 'rles', '=', 'cocomask.frPyObjects(polys,', 'height,', 'width)', 'rle', '=', 'coco... | 501,365 |
rifqind/Agent-Programs-3KS1 | environment.py | Template.get_corresponding_lineno | get_corresponding_lineno | Return the source line number of a line number in the generated bytecode as they are not in sync. | [
"Return",
"the",
"source",
"line",
"number",
"of",
"a",
"line",
"number",
"in",
"the",
"generated",
"bytecode",
"as",
"they",
"are",
"not",
"in",
"sync."
] | def get_corresponding_lineno(self, lineno):
for (template_line, code_line) in reversed(self.debug_info):
if code_line <= lineno:
return template_line
return 1 | ['def', 'get_corresponding_lineno(self,', 'lineno):', 'for', '(template_line,', 'code_line)', 'in', 'reversed(self.debug_info):', 'if', 'code_line', '<=', 'lineno:', 'return', 'template_line', 'return', '1'] | 42,226 |
nhsx/SynthVAE | numerical.py | AlmostConstantIntegerGenerator.generate | generate | Generate a ``num_rows`` number of rows. | [
"Generate",
"a",
"``num_rows``",
"number",
"of",
"rows."
] | def generate(num_rows):
ii32 = np.iinfo(np.int32)
values = np.random.randint(ii32.min, ii32.max, size=2)
additional_values = np.full(num_rows - 2, values[1])
array = np.concatenate([values, additional_values])
np.random.shuffle(array)
return array | ['def', 'generate(num_rows):', 'ii32', '=', 'np.iinfo(np.int32)', 'values', '=', 'np.random.randint(ii32.min,', 'ii32.max,', 'size=2)', 'additional_values', '=', 'np.full(num_rows', '-', '2,', 'values[1])', 'array', '=', 'np.concatenate([values,', 'additional_values])', 'np.random.shuffle(array)', 'return', 'array'] | 906,344 |
kubeflow/pipelines | test_mar_generation.py | test_mar_generation_optional_arguments | test_mar_generation_optional_arguments | Tests mar generation with optional arguments. | [
"Tests",
"mar",
"generation",
"with",
"optional",
"arguments."
] | def test_mar_generation_optional_arguments(mar_config, optional_arg):
(new_file, filename) = tempfile.mkstemp()
mar_config[optional_arg] = os.path.join(os.getcwd(), filename)
generate_mar_file(config=mar_config, save_path=EXPORT_PATH)
mar_config.pop(optional_arg) | ['def', 'test_mar_generation_optional_arguments(mar_config,', 'optional_arg):', '(new_file,', 'filename)', '=', 'tempfile.mkstemp()', 'mar_config[optional_arg]', '=', 'os.path.join(os.getcwd(),', 'filename)', 'generate_mar_file(config=mar_config,', 'save_path=EXPORT_PATH)', 'mar_config.pop(optional_arg)'] | 779,648 |
PaddlePaddle/Paddle3D | petr_head_seg.py | PETRHeadseg.init_weights | init_weights | Initialize weights of the transformer head. | [
"Initialize",
"weights",
"of",
"the",
"transformer",
"head."
] | def init_weights(self):
self.input_proj.apply(param_init.reset_parameters)
self.cls_branches.apply(param_init.reset_parameters)
self.reg_branches.apply(param_init.reset_parameters)
self.lane_branches.apply(param_init.reset_parameters)
self.adapt_pos3d.apply(param_init.reset_parameters)
if self.w... | ['def', 'init_weights(self):', 'self.input_proj.apply(param_init.reset_parameters)', 'self.cls_branches.apply(param_init.reset_parameters)', 'self.reg_branches.apply(param_init.reset_parameters)', 'self.lane_branches.apply(param_init.reset_parameters)', 'self.adapt_pos3d.apply(param_init.reset_parameters)', 'if', 'self... | 777,698 |
DevHunterYZ/Natural-Language-Processing | base.py | LoadFile.longest_sequence_selection | longest_sequence_selection | Select the longest sequences of given POS tags as candidates. | [
"Select",
"the",
"longest",
"sequences",
"of",
"given",
"POS",
"tags",
"as",
"candidates."
] | def longest_sequence_selection(self, key, valid_values):
for (i, sentence) in enumerate(self.sentences):
shift = sum([s.length for s in self.sentences[0:i]])
seq = []
for (j, value) in enumerate(key(self.sentences[i])):
if value in valid_values:
seq.append(j)
... | ['def', 'longest_sequence_selection(self,', 'key,', 'valid_values):', 'for', '(i,', 'sentence)', 'in', 'enumerate(self.sentences):', 'shift', '=', 'sum([s.length', 'for', 's', 'in', 'self.sentences[0:i]])', 'seq', '=', '[]', 'for', '(j,', 'value)', 'in', 'enumerate(key(self.sentences[i])):', 'if', 'value', 'in', 'valid... | 637,770 |
matsu0228/nlp-jp | spines.py | Spine.get_bounds | get_bounds | Get the bounds of the spine. | [
"Get",
"the",
"bounds",
"of",
"the",
"spine."
] | def get_bounds(self):
return self._bounds | ['def', 'get_bounds(self):', 'return', 'self._bounds'] | 789,209 |
greydanus/pythonic_ocr | index.py | Link.verifiable | verifiable | Returns True if this link can be verified after download, False if it cannot, and None if we cannot determine. | [
"Returns",
"True",
"if",
"this",
"link",
"can",
"be",
"verified",
"after",
"download,",
"False",
"if",
"it",
"cannot,",
"and",
"None",
"if",
"we",
"cannot",
"determine."
] | def verifiable(self):
trusted = self.trusted or getattr(self.comes_from, 'trusted', None)
if trusted is not None and trusted:
try:
api_version = getattr(self.comes_from, 'api_version', None)
api_version = int(api_version)
except (ValueError, TypeError):
api_ve... | ['def', 'verifiable(self):', 'trusted', '=', 'self.trusted', 'or', 'getattr(self.comes_from,', "'trusted',", 'None)', 'if', 'trusted', 'is', 'not', 'None', 'and', 'trusted:', 'try:', 'api_version', '=', 'getattr(self.comes_from,', "'api_version',", 'None)', 'api_version', '=', 'int(api_version)', 'except', '(ValueError... | 300,263 |
mj-will/nessai | test_model.py | test_vectorised_likelihood_setter | test_vectorised_likelihood_setter | Assert the setter sets the correct variable. | [
"Assert",
"the",
"setter",
"sets",
"the",
"correct",
"variable."
] | def test_vectorised_likelihood_setter(model):
Model.vectorised_likelihood.__set__(model, 'test')
assert model._vectorised_likelihood == 'test' | ['def', 'test_vectorised_likelihood_setter(model):', 'Model.vectorised_likelihood.__set__(model,', "'test')", 'assert', 'model._vectorised_likelihood', '==', "'test'"] | 292,293 |
jeffnyman/pacumen | environment.py | Environment.reset | reset | Returns the environment to its start state. | [
"Returns",
"the",
"environment",
"to",
"its",
"start",
"state."
] | def reset(self):
abstract() | ['def', 'reset(self):', 'abstract()'] | 255,933 |
ballaneypranav/cs50ai | generate.py | CrosswordCreator.print | print | Print crossword assignment to the terminal. | [
"Print",
"crossword",
"assignment",
"to",
"the",
"terminal."
] | def print(self, assignment):
letters = self.letter_grid(assignment)
for i in range(self.crossword.height):
for j in range(self.crossword.width):
if self.crossword.structure[i][j]:
print(letters[i][j] or ' ', end='')
else:
print('âÂ\x96Â\x88', end=... | ['def', 'print(self,', 'assignment):', 'letters', '=', 'self.letter_grid(assignment)', 'for', 'i', 'in', 'range(self.crossword.height):', 'for', 'j', 'in', 'range(self.crossword.width):', 'if', 'self.crossword.structure[i][j]:', 'print(letters[i][j]', 'or', "'", "',", "end='')", 'else:', "print('âÂ\\x96Â\\x88',", "end... | 192,534 |
rifqind/Agent-Programs-3KS1 | layout.py | Layout.focus_last | focus_last | Give the focus to the last focused control. | [
"Give",
"the",
"focus",
"to",
"the",
"last",
"focused",
"control."
] | def focus_last(self):
if len(self._stack) > 1:
self._stack = self._stack[:-1] | ['def', 'focus_last(self):', 'if', 'len(self._stack)', '>', '1:', 'self._stack', '=', 'self._stack[:-1]'] | 45,383 |
alugupta/ares | trainer.py | Trainer.before_epoch | before_epoch | Do something before each training epoch. | [
"Do",
"something",
"before",
"each",
"training",
"epoch."
] | def before_epoch(self):
epoch = self.runtime['epoch']
self.model.train() if not self.is_distributed else self.model.module.train()
if self.is_distributed:
self.train_dataloader.batch_sampler.sampler.set_epoch(epoch) | ['def', 'before_epoch(self):', 'epoch', '=', "self.runtime['epoch']", 'self.model.train()', 'if', 'not', 'self.is_distributed', 'else', 'self.model.module.train()', 'if', 'self.is_distributed:', 'self.train_dataloader.batch_sampler.sampler.set_epoch(epoch)'] | 402,069 |
chribsen/simple-machine-learning-examples | numpy_pickle_compat.py | hex_str | hex_str | Convert an int to an hexadecimal string. | [
"Convert",
"an",
"int",
"to",
"an",
"hexadecimal",
"string."
] | def hex_str(an_int):
return '{0:#x}'.format(an_int) | ['def', 'hex_str(an_int):', 'return', "'{0:#x}'.format(an_int)"] | 939,273 |
xuannianz/FSAF | util_graphs.py | xyxy2cxcywh | xyxy2cxcywh | Convert [x1 y1 x2 y2] box format to [cx cx w h] format. | [
"Convert",
"[x1",
"y1",
"x2",
"y2]",
"box",
"format",
"to",
"[cx",
"cx",
"w",
"h]",
"format."
] | def xyxy2cxcywh(xyxy):
return tf.concat((0.5 * (xyxy[:, 0:2] + xyxy[:, 2:4]), xyxy[:, 2:4] - xyxy[:, 0:2]), axis=-1) | ['def', 'xyxy2cxcywh(xyxy):', 'return', 'tf.concat((0.5', '*', '(xyxy[:,', '0:2]', '+', 'xyxy[:,', '2:4]),', 'xyxy[:,', '2:4]', '-', 'xyxy[:,', '0:2]),', 'axis=-1)'] | 565,036 |
greydanus/mr_london | urls.py | BaseURL.auth | auth | The authentication part in the URL if available, `None` otherwise. | [
"The",
"authentication",
"part",
"in",
"the",
"URL",
"if",
"available,",
"`None`",
"otherwise."
] | def auth(self):
return self._split_netloc()[0] | ['def', 'auth(self):', 'return', 'self._split_netloc()[0]'] | 264,199 |
jimtin/Stock_Comparison | template.py | BaseLoader.resolve_path | resolve_path | Converts a possibly-relative path to absolute (used internally). | [
"Converts",
"a",
"possibly-relative",
"path",
"to",
"absolute",
"(used",
"internally)."
] | def resolve_path(self, name, parent_path=None):
raise NotImplementedError() | ['def', 'resolve_path(self,', 'name,', 'parent_path=None):', 'raise', 'NotImplementedError()'] | 359,192 |
kianak2002/Sentiment-Emotion-Analysis-project | _in_process.py | contained_in | contained_in | Test if a file is located within the given directory. | [
"Test",
"if",
"a",
"file",
"is",
"located",
"within",
"the",
"given",
"directory."
] | def contained_in(filename, directory):
filename = os.path.normcase(os.path.abspath(filename))
directory = os.path.normcase(os.path.abspath(directory))
return os.path.commonprefix([filename, directory]) == directory | ['def', 'contained_in(filename,', 'directory):', 'filename', '=', 'os.path.normcase(os.path.abspath(filename))', 'directory', '=', 'os.path.normcase(os.path.abspath(directory))', 'return', 'os.path.commonprefix([filename,', 'directory])', '==', 'directory'] | 875,153 |
mit-han-lab/hardware-aware-transformers | evolution.py | validate_all | validate_all | Evaluate the model on the validation set(s) and return the losses. | [
"Evaluate",
"the",
"model",
"on",
"the",
"validation",
"set(s)",
"and",
"return",
"the",
"losses."
] | def validate_all(args, trainer, task, epoch_itr, configs):
valid_losses = []
def get_itr():
itr = task.get_batch_iterator(dataset=task.dataset('valid'), max_tokens=args.max_tokens_valid, max_sentences=args.max_sentences_valid, max_positions=utils.resolve_max_positions(task.max_positions(), trainer.get_... | ['def', 'validate_all(args,', 'trainer,', 'task,', 'epoch_itr,', 'configs):', 'valid_losses', '=', '[]', 'def', 'get_itr():', 'itr', '=', "task.get_batch_iterator(dataset=task.dataset('valid'),", 'max_tokens=args.max_tokens_valid,', 'max_sentences=args.max_sentences_valid,', 'max_positions=utils.resolve_max_positions(t... | 576,006 |
thenamangoyal/artificial-intelligence | __init__.py | VersionControl.make_rev_options | make_rev_options | Return a RevOptions object. | [
"Return",
"a",
"RevOptions",
"object."
] | def make_rev_options(self, rev=None, extra_args=None):
return RevOptions(self, rev, extra_args=extra_args) | ['def', 'make_rev_options(self,', 'rev=None,', 'extra_args=None):', 'return', 'RevOptions(self,', 'rev,', 'extra_args=extra_args)'] | 90,137 |
flow-project/flow | test_environments.py | TestWaveAttenuationEnv.test_observation_action_space | test_observation_action_space | Tests the observation and action spaces upon initialization. | [
"Tests",
"the",
"observation",
"and",
"action",
"spaces",
"upon",
"initialization."
] | def test_observation_action_space(self):
env = WaveAttenuationEnv(sim_params=self.sim_params, network=self.network, env_params=self.env_params)
self.assertTrue(test_space(env.observation_space, expected_size=2 * env.initial_vehicles.num_vehicles, expected_min=0, expected_max=1))
self.assertTrue(test_space(e... | ['def', 'test_observation_action_space(self):', 'env', '=', 'WaveAttenuationEnv(sim_params=self.sim_params,', 'network=self.network,', 'env_params=self.env_params)', 'self.assertTrue(test_space(env.observation_space,', 'expected_size=2', '*', 'env.initial_vehicles.num_vehicles,', 'expected_min=0,', 'expected_max=1))', ... | 211,905 |
myothida/Supervised-Machine-Learning | blocks.py | extract_pandas_array | extract_pandas_array | Ensure that we don't allow PandasArray / PandasDtype in internals. | [
"Ensure",
"that",
"we",
"don't",
"allow",
"PandasArray",
"/",
"PandasDtype",
"in",
"internals."
] | def extract_pandas_array(values: np.ndarray | ExtensionArray, dtype: DtypeObj | None, ndim: int) -> tuple[np.ndarray | ExtensionArray, DtypeObj | None]:
if isinstance(values, ABCPandasArray):
values = values.to_numpy()
if ndim and ndim > 1:
values = np.atleast_2d(values)
if isinstanc... | ['def', 'extract_pandas_array(values:', 'np.ndarray', '|', 'ExtensionArray,', 'dtype:', 'DtypeObj', '|', 'None,', 'ndim:', 'int)', '->', 'tuple[np.ndarray', '|', 'ExtensionArray,', 'DtypeObj', '|', 'None]:', 'if', 'isinstance(values,', 'ABCPandasArray):', 'values', '=', 'values.to_numpy()', 'if', 'ndim', 'and', 'ndim',... | 443,048 |
spite-triangle/artificial_intelligence | retry.py | Retry.get_retry_after | get_retry_after | Get the value of Retry-After in seconds. | [
"Get",
"the",
"value",
"of",
"Retry-After",
"in",
"seconds."
] | def get_retry_after(self, response):
retry_after = response.getheader('Retry-After')
if retry_after is None:
return None
return self.parse_retry_after(retry_after) | ['def', 'get_retry_after(self,', 'response):', 'retry_after', '=', "response.getheader('Retry-After')", 'if', 'retry_after', 'is', 'None:', 'return', 'None', 'return', 'self.parse_retry_after(retry_after)'] | 150,810 |
enuguru/artificial_intelligence_and_machine_ | nonlinear.py | dreclin | dreclin | Computes the derivative of a rectified linear function with respect to its input, given its output and the derivative on the output. | [
"Computes",
"the",
"derivative",
"of",
"a",
"rectified",
"linear",
"function",
"with",
"respect",
"to",
"its",
"input,",
"given",
"its",
"output",
"and",
"the",
"derivative",
"on",
"the",
"output."
] | def dreclin(output, doutput, dinput):
nonlinear_.dreclin_(output, doutput, dinput) | ['def', 'dreclin(output,', 'doutput,', 'dinput):', 'nonlinear_.dreclin_(output,', 'doutput,', 'dinput)'] | 164,422 |
tencent-ailab/TriNet | noisy_channel_translation.py | NoisyChannelTranslation.add_args | add_args | Add task-specific arguments to the parser. | [
"Add",
"task-specific",
"arguments",
"to",
"the",
"parser."
] | def add_args(parser):
TranslationTask.add_args(parser)
parser.add_argument('--channel-model', metavar='FILE', help='path to P(S|T) model. P(S|T) and P(T|S) must share source and target dictionaries.')
parser.add_argument('--combine-method', default='lm_only', choices=['lm_only', 'noisy_channel'], help='meth... | ['def', 'add_args(parser):', 'TranslationTask.add_args(parser)', "parser.add_argument('--channel-model',", "metavar='FILE',", "help='path", 'to', 'P(S|T)', 'model.', 'P(S|T)', 'and', 'P(T|S)', 'must', 'share', 'source', 'and', 'target', "dictionaries.')", "parser.add_argument('--combine-method',", "default='lm_only',",... | 424,859 |
Zengyi-Qin/TLNet | img_vgg_pyramid.py | ImgVggPyr.vgg_arg_scope | vgg_arg_scope | Defines the VGG arg scope. | [
"Defines",
"the",
"VGG",
"arg",
"scope."
] | def vgg_arg_scope(self, weight_decay=0.0005):
with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()):
with slim.arg_scope([slim.conv2d], padding='SAME') as arg_sc:
return... | ['def', 'vgg_arg_scope(self,', 'weight_decay=0.0005):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.fully_connected],', 'activation_fn=tf.nn.relu,', 'weights_regularizer=slim.l2_regularizer(weight_decay),', 'biases_initializer=tf.zeros_initializer()):', 'with', 'slim.arg_scope([slim.conv2d],', "padding='SAME')", 'as'... | 917,719 |
shiwt03/MUSTER | base.py | BaseSegmentor.show_result | show_result | Draw `result` over `img`. | [
"Draw",
"`result`",
"over",
"`img`."
] | def show_result(self, img, result, palette=None, win_name='', show=False, wait_time=0, out_file=None, opacity=0.5):
img = mmcv.imread(img)
img = img.copy()
seg = result[0]
if palette is None:
if self.PALETTE is None:
state = np.random.get_state()
np.random.seed(42)
... | ['def', 'show_result(self,', 'img,', 'result,', 'palette=None,', "win_name='',", 'show=False,', 'wait_time=0,', 'out_file=None,', 'opacity=0.5):', 'img', '=', 'mmcv.imread(img)', 'img', '=', 'img.copy()', 'seg', '=', 'result[0]', 'if', 'palette', 'is', 'None:', 'if', 'self.PALETTE', 'is', 'None:', 'state', '=', 'np.ran... | 644,919 |
triaquae/triaquae | numbertheory.py | factorization | factorization | Decompose n into a list of (prime,exponent) pairs. | [
"Decompose",
"n",
"into",
"a",
"list",
"of",
"(prime,exponent)",
"pairs."
] | def factorization(n):
assert isinstance(n, integer_types)
if n < 2:
return []
result = []
d = 2
for d in smallprimes:
if d > n:
break
(q, r) = divmod(n, d)
if r == 0:
count = 1
while d <= n:
n = q
(q,... | ['def', 'factorization(n):', 'assert', 'isinstance(n,', 'integer_types)', 'if', 'n', '<', '2:', 'return', '[]', 'result', '=', '[]', 'd', '=', '2', 'for', 'd', 'in', 'smallprimes:', 'if', 'd', '>', 'n:', 'break', '(q,', 'r)', '=', 'divmod(n,', 'd)', 'if', 'r', '==', '0:', 'count', '=', '1', 'while', 'd', '<=', 'n:', 'n... | 356,732 |
deepmind/meltingpot | __init__.py | saved_model | saved_model | Returns the config for a saved model bot. | [
"Returns",
"the",
"config",
"for",
"a",
"saved",
"model",
"bot."
] | def saved_model(*, substrate: str, roles: Iterable[str]=('default',), model: str, models_root: str=MODELS_ROOT) -> BotConfig:
model_path = os.path.join(models_root, substrate, model)
return BotConfig(substrate=substrate, roles=frozenset(roles), model_path=model_path, puppeteer_builder=None) | ['def', 'saved_model(*,', 'substrate:', 'str,', 'roles:', "Iterable[str]=('default',),", 'model:', 'str,', 'models_root:', 'str=MODELS_ROOT)', '->', 'BotConfig:', 'model_path', '=', 'os.path.join(models_root,', 'substrate,', 'model)', 'return', 'BotConfig(substrate=substrate,', 'roles=frozenset(roles),', 'model_path=mo... | 285,238 |
tensorflow/privacy | input.py | extract_mnist_labels | extract_mnist_labels | Extract the labels into a vector of int64 label IDs. | [
"Extract",
"the",
"labels",
"into",
"a",
"vector",
"of",
"int64",
"label",
"IDs."
] | def extract_mnist_labels(filename, num_images):
if not tf.gfile.Exists(filename + '.npy'):
with gzip.open(filename) as bytestream:
bytestream.read(8)
buf = bytestream.read(1 * num_images)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int32)
np.save(fil... | ['def', 'extract_mnist_labels(filename,', 'num_images):', 'if', 'not', 'tf.gfile.Exists(filename', '+', "'.npy'):", 'with', 'gzip.open(filename)', 'as', 'bytestream:', 'bytestream.read(8)', 'buf', '=', 'bytestream.read(1', '*', 'num_images)', 'labels', '=', 'np.frombuffer(buf,', 'dtype=np.uint8).astype(np.int32)', 'np.... | 824,558 |
whatdhack/computer_vision | cpp_lint.py | ProcessFile | ProcessFile | Does google-lint on a single file. | [
"Does",
"google-lint",
"on",
"a",
"single",
"file."
] | def ProcessFile(filename, vlevel, extra_check_functions=[]):
_SetVerboseLevel(vlevel)
try:
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n')
else:
lines = codecs.open(filename... | ['def', 'ProcessFile(filename,', 'vlevel,', 'extra_check_functions=[]):', '_SetVerboseLevel(vlevel)', 'try:', 'if', 'filename', '==', "'-':", 'lines', '=', 'codecs.StreamReaderWriter(sys.stdin,', "codecs.getreader('utf8'),", "codecs.getwriter('utf8'),", "'replace').read().split('\\n')", 'else:', 'lines', '=', 'codecs.o... | 473,443 |
prof-fabriciogmc/artificial_intelligence | pyparsing.py | ParseResults.copy | copy | Returns a new copy of a C{ParseResults} object. | [
"Returns",
"a",
"new",
"copy",
"of",
"a",
"C{ParseResults}",
"object."
] | def copy(self):
ret = ParseResults(self.__toklist)
ret.__tokdict = self.__tokdict.copy()
ret.__parent = self.__parent
ret.__accumNames.update(self.__accumNames)
ret.__name = self.__name
return ret | ['def', 'copy(self):', 'ret', '=', 'ParseResults(self.__toklist)', 'ret.__tokdict', '=', 'self.__tokdict.copy()', 'ret.__parent', '=', 'self.__parent', 'ret.__accumNames.update(self.__accumNames)', 'ret.__name', '=', 'self.__name', 'return', 'ret'] | 74,081 |
RLE-Foundation/rllte | utils.py | OnPolicyDiscreteActor.forward | forward | Only for model inference. | [
"Only",
"for",
"model",
"inference."
] | def forward(self, obs: th.Tensor) -> th.Tensor:
return self.actor(obs) | ['def', 'forward(self,', 'obs:', 'th.Tensor)', '->', 'th.Tensor:', 'return', 'self.actor(obs)'] | 333,598 |
scotthuang1989/object_detection_with_tensorflow | test_utils.py | create_random_boxes | create_random_boxes | Creates random bounding boxes of specific maximum height and width. | [
"Creates",
"random",
"bounding",
"boxes",
"of",
"specific",
"maximum",
"height",
"and",
"width."
] | def create_random_boxes(num_boxes, max_height, max_width):
y_1 = np.random.uniform(size=(1, num_boxes)) * max_height
y_2 = np.random.uniform(size=(1, num_boxes)) * max_height
x_1 = np.random.uniform(size=(1, num_boxes)) * max_width
x_2 = np.random.uniform(size=(1, num_boxes)) * max_width
boxes = np.... | ['def', 'create_random_boxes(num_boxes,', 'max_height,', 'max_width):', 'y_1', '=', 'np.random.uniform(size=(1,', 'num_boxes))', '*', 'max_height', 'y_2', '=', 'np.random.uniform(size=(1,', 'num_boxes))', '*', 'max_height', 'x_1', '=', 'np.random.uniform(size=(1,', 'num_boxes))', '*', 'max_width', 'x_2', '=', 'np.rando... | 739,438 |
TheCurryMan/MedicAI | req_file.py | ignore_comments | ignore_comments | Strips and filters empty or commented lines. | [
"Strips",
"and",
"filters",
"empty",
"or",
"commented",
"lines."
] | def ignore_comments(iterator):
for line in iterator:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line | ['def', 'ignore_comments(iterator):', 'for', 'line', 'in', 'iterator:', 'line', '=', "COMMENT_RE.sub('',", 'line)', 'line', '=', 'line.strip()', 'if', 'line:', 'yield', 'line'] | 648,617 |
juaml/julearn | test_available_target_transformers.py | test_register_target_transformer | test_register_target_transformer | Test registering target transformers. | [
"Test",
"registering",
"target",
"transformers."
] | def test_register_target_transformer() -> None:
with pytest.raises(ValueError, match='\\(useless\\) is not available'):
get_target_transformer('useless')
first = list_target_transformers()
class MyTransformer(JuTargetTransformer):
pass
register_target_transformer('useless', MyTransforme... | ['def', 'test_register_target_transformer()', '->', 'None:', 'with', 'pytest.raises(ValueError,', "match='\\\\(useless\\\\)", 'is', 'not', "available'):", "get_target_transformer('useless')", 'first', '=', 'list_target_transformers()', 'class', 'MyTransformer(JuTargetTransformer):', 'pass', "register_target_transformer... | 593,775 |
YangRui2015/AWGCSL | logger.py | logkv | logkv | Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration If called many times, last value will be used. | [
"Log",
"a",
"value",
"of",
"some",
"diagnostic",
"Call",
"this",
"once",
"for",
"each",
"diagnostic",
"quantity,",
"each",
"iteration",
"If",
"called",
"many",
"times,",
"last",
"value",
"will",
"be",
"used."
] | def logkv(key, val):
get_current().logkv(key, val) | ['def', 'logkv(key,', 'val):', 'get_current().logkv(key,', 'val)'] | 93,887 |
tejas-trivedi/Natural-Language-Processing | a2_test.py | TestA2.test_hmm_fit_start | test_hmm_fit_start | Test supervised HMM learning start_probas. | [
"Test",
"supervised",
"HMM",
"learning",
"start_probas."
] | def test_hmm_fit_start(self):
model = HMM()
model.fit(test_sentences, test_tags)
self.assertEqual(0.75, round(model.start_probas['D'], 2))
self.assertEqual(0.0, round(model.start_probas['N'], 1))
self.assertEqual(0.25, round(model.start_probas['V'], 2)) | ['def', 'test_hmm_fit_start(self):', 'model', '=', 'HMM()', 'model.fit(test_sentences,', 'test_tags)', 'self.assertEqual(0.75,', "round(model.start_probas['D'],", '2))', 'self.assertEqual(0.0,', "round(model.start_probas['N'],", '1))', 'self.assertEqual(0.25,', "round(model.start_probas['V'],", '2))'] | 690,761 |
5taku/tensorflow_object_detection_helper_tool | np_box_list_ops.py | intersection | intersection | Compute pairwise intersection areas between boxes. | [
"Compute",
"pairwise",
"intersection",
"areas",
"between",
"boxes."
] | def intersection(boxlist1, boxlist2):
return np_box_ops.intersection(boxlist1.get(), boxlist2.get()) | ['def', 'intersection(boxlist1,', 'boxlist2):', 'return', 'np_box_ops.intersection(boxlist1.get(),', 'boxlist2.get())'] | 923,228 |
cjiang2/video2command | utils.py | text_to_sequence | text_to_sequence | Convert a text to numerical sequence. | [
"Convert",
"a",
"text",
"to",
"numerical",
"sequence."
] | def text_to_sequence(text, vocab, filters='!"#$%&()*+.,-/:;=?@[\\]^_`{|}~ ', lower=True, split=' '):
tokens = word_tokenize(text, filters, lower, split)
seq = []
for token in tokens:
word_index = vocab(token)
if word_index is not None:
seq.extend([word_index])
return seq | ['def', 'text_to_sequence(text,', 'vocab,', 'filters=\'!"#$%&()*+.,-/:;=?@[\\\\]^_`{|}~', "',", 'lower=True,', "split='", "'):", 'tokens', '=', 'word_tokenize(text,', 'filters,', 'lower,', 'split)', 'seq', '=', '[]', 'for', 'token', 'in', 'tokens:', 'word_index', '=', 'vocab(token)', 'if', 'word_index', 'is', 'not', 'N... | 379,893 |
Kvatsx/Artificial-Intelligence-Assignments | egg_info.py | FileList.exclude | exclude | Exclude files that match 'pattern'. | [
"Exclude",
"files",
"that",
"match",
"'pattern'."
] | def exclude(self, pattern):
match = translate_pattern(pattern)
return self._remove_files(match.match) | ['def', 'exclude(self,', 'pattern):', 'match', '=', 'translate_pattern(pattern)', 'return', 'self._remove_files(match.match)'] | 78,367 |
rudranil723/mini-main | base.py | Index.shape | shape | Return a tuple of the shape of the underlying data. | [
"Return",
"a",
"tuple",
"of",
"the",
"shape",
"of",
"the",
"underlying",
"data."
] | def shape(self) -> Shape:
return (len(self),) | ['def', 'shape(self)', '->', 'Shape:', 'return', '(len(self),)'] | 323,879 |
coldmanck/CS5242-Neural-Network-and--Learning-Assignments | net1-grad-check.py | SoftmaxOutputLayer.get_input_grad | get_input_grad | Return the gradient at the inputs of this layer. | [
"Return",
"the",
"gradient",
"at",
"the",
"inputs",
"of",
"this",
"layer."
] | def get_input_grad(self, Y, T):
return (Y - T) / Y.shape[0] | ['def', 'get_input_grad(self,', 'Y,', 'T):', 'return', '(Y', '-', 'T)', '/', 'Y.shape[0]'] | 508,241 |
open-mmlab/mmcv | wrappers.py | RandomApply.transform | transform | Randomly apply the transform. | [
"Randomly",
"apply",
"the",
"transform."
] | def transform(self, results: Dict) -> Optional[Dict]:
if self.random_apply():
return self.transforms(results)
else:
return results | ['def', 'transform(self,', 'results:', 'Dict)', '->', 'Optional[Dict]:', 'if', 'self.random_apply():', 'return', 'self.transforms(results)', 'else:', 'return', 'results'] | 631,599 |
gopinath-balu/computer_vision | generate_anchor.py | generate_anchors | generate_anchors | Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. | [
"Generate",
"anchor",
"(reference)",
"windows",
"by",
"enumerating",
"aspect",
"ratios",
"X",
"scales",
"wrt",
"a",
"reference",
"(0,",
"0,",
"15,",
"15)",
"window."
] | def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6), stride=16, dense_anchor=False):
base_anchor = np.array([1, 1, base_size, base_size]) - 1
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anc... | ['def', 'generate_anchors(base_size=16,', 'ratios=[0.5,', '1,', '2],', 'scales=2', '**', 'np.arange(3,', '6),', 'stride=16,', 'dense_anchor=False):', 'base_anchor', '=', 'np.array([1,', '1,', 'base_size,', 'base_size])', '-', '1', 'ratio_anchors', '=', '_ratio_enum(base_anchor,', 'ratios)', 'anchors', '=', 'np.vstack([... | 499,327 |
Eric3911/OpenAGI | modules.py | init_bn | init_bn | Initialize a Batchnorm layer. | [
"Initialize",
"a",
"Batchnorm",
"layer."
] | def init_bn(bn):
bn.bias.data.fill_(0.0)
bn.weight.data.fill_(1.0) | ['def', 'init_bn(bn):', 'bn.bias.data.fill_(0.0)', 'bn.weight.data.fill_(1.0)'] | 250,669 |
yizheh/Chinese_Font_Transfer | logging.py | IndentingFormatter.format | format | Calls the standard formatter, but will indent all of the log messages by our current indentation level. | [
"Calls",
"the",
"standard",
"formatter,",
"but",
"will",
"indent",
"all",
"of",
"the",
"log",
"messages",
"by",
"our",
"current",
"indentation",
"level."
] | def format(self, record):
formatted = logging.Formatter.format(self, record)
formatted = ''.join([' ' * get_indentation() + line for line in formatted.splitlines(True)])
return formatted | ['def', 'format(self,', 'record):', 'formatted', '=', 'logging.Formatter.format(self,', 'record)', 'formatted', '=', "''.join(['", "'", '*', 'get_indentation()', '+', 'line', 'for', 'line', 'in', 'formatted.splitlines(True)])', 'return', 'formatted'] | 486,567 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.