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 |
|---|---|---|---|---|---|---|---|---|
KalleHallden/InstaAutomator | tarfile.py | is_tarfile | is_tarfile | Return True if name points to a tar archive that we are able to handle, else return False. | [
"Return",
"True",
"if",
"name",
"points",
"to",
"a",
"tar",
"archive",
"that",
"we",
"are",
"able",
"to",
"handle,",
"else",
"return",
"False."
] | def is_tarfile(name):
try:
t = open(name)
t.close()
return True
except TarError:
return False | ['def', 'is_tarfile(name):', 'try:', 't', '=', 'open(name)', 't.close()', 'return', 'True', 'except', 'TarError:', 'return', 'False'] | 233,162 |
kianak2002/Sentiment-Emotion-Analysis-project | req_command.py | with_cleanup | with_cleanup | Decorator for common logic related to managing temporary directories. | [
"Decorator",
"for",
"common",
"logic",
"related",
"to",
"managing",
"temporary",
"directories."
] | def with_cleanup(func):
def configure_tempdir_registry(registry):
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)
def wrapper(self, options, args):
assert self.tempdir_registry is not None
if options.no_clean:
configure_tempdir_registry(self.tempd... | ['def', 'with_cleanup(func):', 'def', 'configure_tempdir_registry(registry):', 'for', 't', 'in', 'KEEPABLE_TEMPDIR_TYPES:', 'registry.set_delete(t,', 'False)', 'def', 'wrapper(self,', 'options,', 'args):', 'assert', 'self.tempdir_registry', 'is', 'not', 'None', 'if', 'options.no_clean:', 'configure_tempdir_registry(sel... | 874,533 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | cifar10_main.py | get_model_fn | get_model_fn | Returns a function that will build the resnet model. | [
"Returns",
"a",
"function",
"that",
"will",
"build",
"the",
"resnet",
"model."
] | def get_model_fn(num_gpus, variable_strategy, num_workers):
def _resnet_model_fn(features, labels, mode, params):
is_training = mode == tf.estimator.ModeKeys.TRAIN
weight_decay = params.weight_decay
momentum = params.momentum
tower_features = features
tower_labels = labels
... | ['def', 'get_model_fn(num_gpus,', 'variable_strategy,', 'num_workers):', 'def', '_resnet_model_fn(features,', 'labels,', 'mode,', 'params):', 'is_training', '=', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN', 'weight_decay', '=', 'params.weight_decay', 'momentum', '=', 'params.momentum', 'tower_features', '=', 'features'... | 30,321 |
eth-sri/debin | dynamic.py | Dynamic.get_table_offset | get_table_offset | Return the virtual address and file offset of a dynamic table. | [
"Return",
"the",
"virtual",
"address",
"and",
"file",
"offset",
"of",
"a",
"dynamic",
"table."
] | def get_table_offset(self, tag_name):
ptr = None
for tag in self._iter_tags(type=tag_name):
ptr = tag['d_ptr']
break
offset = None
if ptr:
offset = next(self.elffile.address_offsets(ptr), None)
return (ptr, offset) | ['def', 'get_table_offset(self,', 'tag_name):', 'ptr', '=', 'None', 'for', 'tag', 'in', 'self._iter_tags(type=tag_name):', 'ptr', '=', "tag['d_ptr']", 'break', 'offset', '=', 'None', 'if', 'ptr:', 'offset', '=', 'next(self.elffile.address_offsets(ptr),', 'None)', 'return', '(ptr,', 'offset)'] | 516,581 |
Ruturaj123/Flowchart-Detection | dnn_test.py | DNNClassifierIntegrationTest.test_numpy_input_fn | test_numpy_input_fn | Tests complete flow with numpy_input_fn. | [
"Tests",
"complete",
"flow",
"with",
"numpy_input_fn."
] | def test_numpy_input_fn(self):
n_classes = 3
input_dimension = 2
batch_size = 10
data = np.linspace(0.0, n_classes - 1.0, batch_size * input_dimension, dtype=np.float32)
x_data = data.reshape(batch_size, input_dimension)
y_data = np.reshape(self._as_label(data[:batch_size]), (batch_size, 1))
... | ['def', 'test_numpy_input_fn(self):', 'n_classes', '=', '3', 'input_dimension', '=', '2', 'batch_size', '=', '10', 'data', '=', 'np.linspace(0.0,', 'n_classes', '-', '1.0,', 'batch_size', '*', 'input_dimension,', 'dtype=np.float32)', 'x_data', '=', 'data.reshape(batch_size,', 'input_dimension)', 'y_data', '=', 'np.resh... | 605,205 |
amiralansary/rl-medical | medical.py | FrameStack.reset | reset | Clear buffer and re-fill by duplicating the first observation. | [
"Clear",
"buffer",
"and",
"re-fill",
"by",
"duplicating",
"the",
"first",
"observation."
] | def reset(self):
ob = self.env.reset()
for _ in range(self.k - 1):
self.frames.append(np.zeros_like(ob))
self.frames.append(ob)
return self._observation() | ['def', 'reset(self):', 'ob', '=', 'self.env.reset()', 'for', '_', 'in', 'range(self.k', '-', '1):', 'self.frames.append(np.zeros_like(ob))', 'self.frames.append(ob)', 'return', 'self._observation()'] | 860,801 |
zihuitang/medical_AI_platform | pdb.py | Pdb.user_exception | user_exception | This function is called if an exception occurs, but only if we are to stop at or just below this level. | [
"This",
"function",
"is",
"called",
"if",
"an",
"exception",
"occurs,",
"but",
"only",
"if",
"we",
"are",
"to",
"stop",
"at",
"or",
"just",
"below",
"this",
"level."
] | def user_exception(self, frame, exc_info):
if self._wait_for_mainpyfile:
return
(exc_type, exc_value, exc_traceback) = exc_info
frame.f_locals['__exception__'] = (exc_type, exc_value)
prefix = 'Internal ' if not exc_traceback and exc_type is StopIteration else ''
self.message('%s%s' % (prefi... | ['def', 'user_exception(self,', 'frame,', 'exc_info):', 'if', 'self._wait_for_mainpyfile:', 'return', '(exc_type,', 'exc_value,', 'exc_traceback)', '=', 'exc_info', "frame.f_locals['__exception__']", '=', '(exc_type,', 'exc_value)', 'prefix', '=', "'Internal", "'", 'if', 'not', 'exc_traceback', 'and', 'exc_type', 'is',... | 281,007 |
viko-3/DiffSeqMol | microbatch.py | Batch.get_device | get_device | Retrieves the device for this microbatch. | [
"Retrieves",
"the",
"device",
"for",
"this",
"microbatch."
] | def get_device(self):
if self.atomic:
return self._values.device
for value in self._values:
if torch.is_tensor(value):
return value.device | ['def', 'get_device(self):', 'if', 'self.atomic:', 'return', 'self._values.device', 'for', 'value', 'in', 'self._values:', 'if', 'torch.is_tensor(value):', 'return', 'value.device'] | 551,514 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | nb_007a.py | TextDataset.from_tokens | from_tokens | Creates a dataset from a token and label file. | [
"Creates",
"a",
"dataset",
"from",
"a",
"token",
"and",
"label",
"file."
] | def from_tokens(cls, folder: PathOrStr, name: str, tok_suff: str='_tok', lbl_suff: str='_lbl', **kwargs) -> 'TextDataset':
orig = [Path(folder / file) for file in [f'{name}{tok_suff}.npy', f'{name}{lbl_suff}.npy']]
dest = [Path(folder) / 'tmp' / file for file in [f'{name}_tok.npy', f'{name}_lbl.npy']]
maybe... | ['def', 'from_tokens(cls,', 'folder:', 'PathOrStr,', 'name:', 'str,', 'tok_suff:', "str='_tok',", 'lbl_suff:', "str='_lbl',", '**kwargs)', '->', "'TextDataset':", 'orig', '=', '[Path(folder', '/', 'file)', 'for', 'file', 'in', "[f'{name}{tok_suff}.npy',", "f'{name}{lbl_suff}.npy']]", 'dest', '=', '[Path(folder)', '/', ... | 32,446 |
akandykeller/NeuralWaveMachines | networks.py | make_flexible_net | make_flexible_net | Commonly used for creating a flexible network. | [
"Commonly",
"used",
"for",
"creating",
"a",
"flexible",
"network."
] | def make_flexible_net(net_type: str, output_dims: int, conv_channels: Union[Sequence[int], int], num_units: Union[Sequence[int], int], num_layers: Optional[int], activation: Activation, activate_final: bool=False, kernel_shapes: Union[Sequence[int], int]=3, strides: Union[Sequence[int], int]=1, padding: Union[Sequence[... | ['def', 'make_flexible_net(net_type:', 'str,', 'output_dims:', 'int,', 'conv_channels:', 'Union[Sequence[int],', 'int],', 'num_units:', 'Union[Sequence[int],', 'int],', 'num_layers:', 'Optional[int],', 'activation:', 'Activation,', 'activate_final:', 'bool=False,', 'kernel_shapes:', 'Union[Sequence[int],', 'int]=3,', '... | 293,694 |
shery322/Lunar-Lander-ANN | png.py | Test.testLtrns0 | testLtrns0 | Create greyscale image with tRNS chunk. | [
"Create",
"greyscale",
"image",
"with",
"tRNS",
"chunk."
] | def testLtrns0(self):
return self.helperLtrns(0) | ['def', 'testLtrns0(self):', 'return', 'self.helperLtrns(0)'] | 619,272 |
weimin17/Object-Detection_HelmetDetection | dataset.py | load | load | Returns training and evaluation input. | [
"Returns",
"training",
"and",
"evaluation",
"input."
] | def load(dataset, vocabulary_size, sentence_length):
if dataset == DATASET_IMDB:
return imdb.load(vocabulary_size, sentence_length)
else:
raise ValueError('unsupported dataset: ' + dataset) | ['def', 'load(dataset,', 'vocabulary_size,', 'sentence_length):', 'if', 'dataset', '==', 'DATASET_IMDB:', 'return', 'imdb.load(vocabulary_size,', 'sentence_length)', 'else:', 'raise', "ValueError('unsupported", 'dataset:', "'", '+', 'dataset)'] | 752,698 |
loicmarie/hands-detection | pixelda_preprocess.py | image_augmentation | image_augmentation | Performs data augmentation by randomly permuting the inputs. | [
"Performs",
"data",
"augmentation",
"by",
"randomly",
"permuting",
"the",
"inputs."
] | def image_augmentation(image):
num_channels = image.shape_as_list()[-1]
if num_channels == 4:
(image, depth) = (image[:, :, 0:3], image[:, :, 3:4])
elif num_channels == 1:
image = tf.image.grayscale_to_rgb(image)
image = tf.image.random_brightness(image, max_delta=0.1)
image = tf.ima... | ['def', 'image_augmentation(image):', 'num_channels', '=', 'image.shape_as_list()[-1]', 'if', 'num_channels', '==', '4:', '(image,', 'depth)', '=', '(image[:,', ':,', '0:3],', 'image[:,', ':,', '3:4])', 'elif', 'num_channels', '==', '1:', 'image', '=', 'tf.image.grayscale_to_rgb(image)', 'image', '=', 'tf.image.random_... | 574,612 |
ludwig-ai/ludwig | utils.py | is_all_close | is_all_close | Checks if two values are close to each other. | [
"Checks",
"if",
"two",
"values",
"are",
"close",
"to",
"each",
"other."
] | def is_all_close(val1: Union[np.ndarray, torch.Tensor, str, list], val2: Union[np.ndarray, torch.Tensor, str, list], tolerance=0.0001):
if isinstance(val1, list):
return all((is_all_close(v1, v2, tolerance) for (v1, v2) in zip(val1, val2)))
if isinstance(val1, str):
return val1 == val2
if is... | ['def', 'is_all_close(val1:', 'Union[np.ndarray,', 'torch.Tensor,', 'str,', 'list],', 'val2:', 'Union[np.ndarray,', 'torch.Tensor,', 'str,', 'list],', 'tolerance=0.0001):', 'if', 'isinstance(val1,', 'list):', 'return', 'all((is_all_close(v1,', 'v2,', 'tolerance)', 'for', '(v1,', 'v2)', 'in', 'zip(val1,', 'val2)))', 'if... | 617,363 |
huma-teknofest/Keras-RetinaNet-for-Teknofest-2019 | generator.py | Generator.compute_inputs | compute_inputs | Compute inputs for the network using an image_group. | [
"Compute",
"inputs",
"for",
"the",
"network",
"using",
"an",
"image_group."
] | def compute_inputs(self, image_group):
max_shape = tuple((max((image.shape[x] for image in image_group)) for x in range(3)))
image_batch = np.zeros((self.batch_size,) + max_shape, dtype=keras.backend.floatx())
for (image_index, image) in enumerate(image_group):
image_batch[image_index, :image.shape[... | ['def', 'compute_inputs(self,', 'image_group):', 'max_shape', '=', 'tuple((max((image.shape[x]', 'for', 'image', 'in', 'image_group))', 'for', 'x', 'in', 'range(3)))', 'image_batch', '=', 'np.zeros((self.batch_size,)', '+', 'max_shape,', 'dtype=keras.backend.floatx())', 'for', '(image_index,', 'image)', 'in', 'enumerat... | 248,008 |
zackmcnulty/CSE_446-Machine_Learning | glibc.py | glibc_version_string | glibc_version_string | Returns glibc version string, or None if not using glibc. | [
"Returns",
"glibc",
"version",
"string,",
"or",
"None",
"if",
"not",
"using",
"glibc."
] | def glibc_version_string():
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
return None
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
if not isinstance(version_st... | ['def', 'glibc_version_string():', 'process_namespace', '=', 'ctypes.CDLL(None)', 'try:', 'gnu_get_libc_version', '=', 'process_namespace.gnu_get_libc_version', 'except', 'AttributeError:', 'return', 'None', 'gnu_get_libc_version.restype', '=', 'ctypes.c_char_p', 'version_str', '=', 'gnu_get_libc_version()', 'if', 'not... | 197,050 |
user0407/CLUDA | collect_env.py | collect_env | collect_env | Collect the information of the running environments. | [
"Collect",
"the",
"information",
"of",
"the",
"running",
"environments."
] | def collect_env():
env_info = collect_base_env()
env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}'
return env_info | ['def', 'collect_env():', 'env_info', '=', 'collect_base_env()', "env_info['MMSegmentation']", '=', "f'{mmseg.__version__}+{get_git_hash()[:7]}'", 'return', 'env_info'] | 122,709 |
rudranil723/mini-main | transforms.py | BboxBase.ymax | ymax | The top edge of the bounding box. | [
"The",
"top",
"edge",
"of",
"the",
"bounding",
"box."
] | def ymax(self):
return np.max(self.get_points()[:, 1]) | ['def', 'ymax(self):', 'return', 'np.max(self.get_points()[:,', '1])'] | 319,750 |
microsoft/maro | proxy.py | Proxy.reply | reply | Reply a received message. | [
"Reply",
"a",
"received",
"message."
] | def reply(self, message: Union[SessionMessage, Message], tag: Union[str, Enum]=None, body=None, ack_reply: bool=False) -> List[str]:
message.reply(tag=tag, body=body)
if isinstance(message, SessionMessage):
if message.session_type == SessionType.TASK:
session_stage = TaskSessionStage.RECEIVE... | ['def', 'reply(self,', 'message:', 'Union[SessionMessage,', 'Message],', 'tag:', 'Union[str,', 'Enum]=None,', 'body=None,', 'ack_reply:', 'bool=False)', '->', 'List[str]:', 'message.reply(tag=tag,', 'body=body)', 'if', 'isinstance(message,', 'SessionMessage):', 'if', 'message.session_type', '==', 'SessionType.TASK:', '... | 628,362 |
jhultman/vision3d | proposal_targets.py | ProposalTargetAssigner.match_all_classes | match_all_classes | Match boxes to anchors based on IOU. | [
"Match",
"boxes",
"to",
"anchors",
"based",
"on",
"IOU."
] | def match_all_classes(self, boxes, class_idx, box_ignore):
full_idx = torch.arange(boxes.shape[0], device=boxes.device)
classes = range(self.cfg.NUM_CLASSES)
(matches, labels) = zip(*[self.match_class_i(boxes, class_idx, full_idx, i) for i in classes])
matches = torch.stack(matches).view(self.anchors.sh... | ['def', 'match_all_classes(self,', 'boxes,', 'class_idx,', 'box_ignore):', 'full_idx', '=', 'torch.arange(boxes.shape[0],', 'device=boxes.device)', 'classes', '=', 'range(self.cfg.NUM_CLASSES)', '(matches,', 'labels)', '=', 'zip(*[self.match_class_i(boxes,', 'class_idx,', 'full_idx,', 'i)', 'for', 'i', 'in', 'classes])... | 944,805 |
jbwang1997/CrossKD | htc_roi_head.py | HybridTaskCascadeRoIHead.predict | predict | Perform forward propagation of the roi head and predict detection results on the features of the upstream network. | [
"Perform",
"forward",
"propagation",
"of",
"the",
"roi",
"head",
"and",
"predict",
"detection",
"results",
"on",
"the",
"features",
"of",
"the",
"upstream",
"network."
] | def predict(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: SampleList, rescale: bool=False) -> InstanceList:
assert self.with_bbox, 'Bbox head must be implemented.'
batch_img_metas = [data_samples.metainfo for data_samples in batch_data_samples]
if self.with_semantic:
(_... | ['def', 'predict(self,', 'x:', 'Tuple[Tensor],', 'rpn_results_list:', 'InstanceList,', 'batch_data_samples:', 'SampleList,', 'rescale:', 'bool=False)', '->', 'InstanceList:', 'assert', 'self.with_bbox,', "'Bbox", 'head', 'must', 'be', "implemented.'", 'batch_img_metas', '=', '[data_samples.metainfo', 'for', 'data_sampl... | 491,389 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec_optimized.py | Word2Vec.save_vocab | save_vocab | Save the vocabulary to a file so the model can be reloaded. | [
"Save",
"the",
"vocabulary",
"to",
"a",
"file",
"so",
"the",
"model",
"can",
"be",
"reloaded."
] | def save_vocab(self):
opts = self._options
with open(os.path.join(opts.save_path, 'vocab.txt'), 'w') as f:
for i in xrange(opts.vocab_size):
vocab_word = tf.compat.as_text(opts.vocab_words[i]).encode('utf-8')
f.write('%s %d\n' % (vocab_word, opts.vocab_counts[i])) | ['def', 'save_vocab(self):', 'opts', '=', 'self._options', 'with', 'open(os.path.join(opts.save_path,', "'vocab.txt'),", "'w')", 'as', 'f:', 'for', 'i', 'in', 'xrange(opts.vocab_size):', 'vocab_word', '=', "tf.compat.as_text(opts.vocab_words[i]).encode('utf-8')", "f.write('%s", "%d\\n'", '%', '(vocab_word,', 'opts.voca... | 113,011 |
sunishsheth2009/ChatterBot | compat.py | BaseConfigurator.ext_convert | ext_convert | Default converter for the ext:// protocol. | [
"Default",
"converter",
"for",
"the",
"ext://",
"protocol."
] | def ext_convert(self, value):
return self.resolve(value) | ['def', 'ext_convert(self,', 'value):', 'return', 'self.resolve(value)'] | 480,259 |
jeromewang-github/computer_vision | config_util.py | get_spatial_image_size | get_spatial_image_size | Returns expected spatial size of the output image from a given config. | [
"Returns",
"expected",
"spatial",
"size",
"of",
"the",
"output",
"image",
"from",
"a",
"given",
"config."
] | def get_spatial_image_size(image_resizer_config):
if image_resizer_config.HasField('fixed_shape_resizer'):
return [image_resizer_config.fixed_shape_resizer.height, image_resizer_config.fixed_shape_resizer.width]
if image_resizer_config.HasField('keep_aspect_ratio_resizer'):
if image_resizer_conf... | ['def', 'get_spatial_image_size(image_resizer_config):', 'if', "image_resizer_config.HasField('fixed_shape_resizer'):", 'return', '[image_resizer_config.fixed_shape_resizer.height,', 'image_resizer_config.fixed_shape_resizer.width]', 'if', "image_resizer_config.HasField('keep_aspect_ratio_resizer'):", 'if', 'image_resi... | 512,061 |
nicknochnack/RealTimeSignLanguageTFJS | resnet_test.py | ResNetTest.test_network_creation | test_network_creation | Test creation of ResNet family models. | [
"Test",
"creation",
"of",
"ResNet",
"family",
"models."
] | def test_network_creation(self, input_size, model_id, endpoint_filter_scale):
resnet_params = {18: 11190464, 34: 21306048, 50: 23561152, 101: 42605504, 152: 58295232}
tf.keras.backend.set_image_data_format('channels_last')
network = resnet.ResNet(model_id=model_id)
self.assertEqual(network.count_params(... | ['def', 'test_network_creation(self,', 'input_size,', 'model_id,', 'endpoint_filter_scale):', 'resnet_params', '=', '{18:', '11190464,', '34:', '21306048,', '50:', '23561152,', '101:', '42605504,', '152:', '58295232}', "tf.keras.backend.set_image_data_format('channels_last')", 'network', '=', 'resnet.ResNet(model_id=mo... | 850,825 |
zihuitang/medical_AI_platform | build-installer.py | buildDMG | buildDMG | Create DMG containing the rootDir. | [
"Create",
"DMG",
"containing",
"the",
"rootDir."
] | def buildDMG():
outdir = os.path.join(WORKDIR, 'diskimage')
if os.path.exists(outdir):
shutil.rmtree(outdir)
imagepath = os.path.join(outdir, 'python-%s-macosx%s' % (getFullVersion(), DEPTARGET))
if INCLUDE_TIMESTAMP:
imagepath = imagepath + '-%04d-%02d-%02d' % time.localtime()[:3]
i... | ['def', 'buildDMG():', 'outdir', '=', 'os.path.join(WORKDIR,', "'diskimage')", 'if', 'os.path.exists(outdir):', 'shutil.rmtree(outdir)', 'imagepath', '=', 'os.path.join(outdir,', "'python-%s-macosx%s'", '%', '(getFullVersion(),', 'DEPTARGET))', 'if', 'INCLUDE_TIMESTAMP:', 'imagepath', '=', 'imagepath', '+', "'-%04d-%02... | 284,654 |
CAMeL-Lab/camel_tools | test_transliterate.py | TestTransliteratorTranslate.test_trans_single_ignore_strip | test_trans_single_ignore_strip | Test that a single word with markers gets transliterated with markers stripped when both strip_markers and ignore_markers are set to True. | [
"Test",
"that",
"a",
"single",
"word",
"with",
"markers",
"gets",
"transliterated",
"with",
"markers",
"stripped",
"when",
"both",
"strip_markers",
"and",
"ignore_markers",
"are",
"set",
"to",
"True."
] | def test_trans_single_ignore_strip(self):
trans = Transliterator(TEST_MAPPER, '@@')
assert trans.transliterate(u'@@Hello', True, True) == u'Xxxxx' | ['def', 'test_trans_single_ignore_strip(self):', 'trans', '=', 'Transliterator(TEST_MAPPER,', "'@@')", 'assert', "trans.transliterate(u'@@Hello',", 'True,', 'True)', '==', "u'Xxxxx'"] | 411,253 |
rifqind/Agent-Programs-3KS1 | sprite.py | LayeredUpdates.get_layer_of_sprite | get_layer_of_sprite | return the layer that sprite is currently in If the sprite is not found, then it will return the default layer. | [
"return",
"the",
"layer",
"that",
"sprite",
"is",
"currently",
"in",
"If",
"the",
"sprite",
"is",
"not",
"found,",
"then",
"it",
"will",
"return",
"the",
"default",
"layer."
] | def get_layer_of_sprite(self, sprite):
return self._spritelayers.get(sprite, self._default_layer) | ['def', 'get_layer_of_sprite(self,', 'sprite):', 'return', 'self._spritelayers.get(sprite,', 'self._default_layer)'] | 45,594 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | QualityWrapper.offsamples | offsamples | number of multisamples for offscreen rendering. | [
"number",
"of",
"multisamples",
"for",
"offscreen",
"rendering."
] | def offsamples(self):
return self._ptr.contents.offsamples | ['def', 'offsamples(self):', 'return', 'self._ptr.contents.offsamples'] | 440,169 |
gunthercox/ChatterBot | datastructures.py | MultiDict.popitemlist | popitemlist | Pop a ``(key, list)`` tuple from the dict. | [
"Pop",
"a",
"``(key,",
"list)``",
"tuple",
"from",
"the",
"dict."
] | def popitemlist(self):
try:
return dict.popitem(self)
except KeyError as e:
raise exceptions.BadRequestKeyError(str(e)) | ['def', 'popitemlist(self):', 'try:', 'return', 'dict.popitem(self)', 'except', 'KeyError', 'as', 'e:', 'raise', 'exceptions.BadRequestKeyError(str(e))'] | 482,024 |
guxm2021/ALT_SpeechBrain | TransformerLM.py | TransformerLM.forward | forward | Arguments --------- src : tensor The sequence to the encoder (required). | [
"Arguments",
"---------",
"src",
":",
"tensor",
"The",
"sequence",
"to",
"the",
"encoder",
"(required)."
] | def forward(self, src, hx=None):
(src_mask, src_key_padding_mask) = self.make_masks(src)
src = self.custom_src_module(src)
if self.embedding_proj is not None:
src = self.embedding_proj(src)
src = src + self.positional_encoding(src)
if self.num_encoder_layers > 0:
(encoder_out, _) = s... | ['def', 'forward(self,', 'src,', 'hx=None):', '(src_mask,', 'src_key_padding_mask)', '=', 'self.make_masks(src)', 'src', '=', 'self.custom_src_module(src)', 'if', 'self.embedding_proj', 'is', 'not', 'None:', 'src', '=', 'self.embedding_proj(src)', 'src', '=', 'src', '+', 'self.positional_encoding(src)', 'if', 'self.num... | 415,629 |
arshpreetsingh/quantopian-machinelearning | test_bundlerextension.py | TestBundlerExtensionCLI.setUp | setUp | Build an isolated config environment. | [
"Build",
"an",
"isolated",
"config",
"environment."
] | def setUp(self):
td = TemporaryDirectory()
self.test_dir = py3compat.cast_unicode(td.name)
self.data_dir = os.path.join(self.test_dir, 'data')
self.config_dir = os.path.join(self.test_dir, 'config')
self.system_data_dir = os.path.join(self.test_dir, 'system_data')
self.system_path = [self.system... | ['def', 'setUp(self):', 'td', '=', 'TemporaryDirectory()', 'self.test_dir', '=', 'py3compat.cast_unicode(td.name)', 'self.data_dir', '=', 'os.path.join(self.test_dir,', "'data')", 'self.config_dir', '=', 'os.path.join(self.test_dir,', "'config')", 'self.system_data_dir', '=', 'os.path.join(self.test_dir,', "'system_dat... | 888,501 |
rifqind/Agent-Programs-3KS1 | ipkernel.py | InProcessInteractiveShell.enable_matplotlib | enable_matplotlib | Enable matplotlib integration for the kernel. | [
"Enable",
"matplotlib",
"integration",
"for",
"the",
"kernel."
] | def enable_matplotlib(self, gui=None):
if not gui:
gui = self.kernel.gui
return super(InProcessInteractiveShell, self).enable_matplotlib(gui) | ['def', 'enable_matplotlib(self,', 'gui=None):', 'if', 'not', 'gui:', 'gui', '=', 'self.kernel.gui', 'return', 'super(InProcessInteractiveShell,', 'self).enable_matplotlib(gui)'] | 40,811 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | registry_test.py | RegistryTest.testCannotCreateMalformedType | testCannotCreateMalformedType | Tests that Create fails on malformed type names. | [
"Tests",
"that",
"Create",
"fails",
"on",
"malformed",
"type",
"names."
] | def testCannotCreateMalformedType(self):
with self.assertRaisesRegexp(ValueError, 'Failed to create'):
registry_test_base.Base.Create('oneword', 'hello world')
with self.assertRaisesRegexp(ValueError, 'Failed to create'):
registry_test_base.Base.Create('hyphen-ated', 'hello world')
with self... | ['def', 'testCannotCreateMalformedType(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", "registry_test_base.Base.Create('oneword',", "'hello", "world')", 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", "registry_test_base.Base.Create('hyphen-ated',", "'h... | 29,090 |
rudranil723/mini-main | test_generic_alias.py | TestGenericAlias.test_getattr | test_getattr | Test that `getattr` wraps around the underlying type, aka ``__origin__``. | [
"Test",
"that",
"`getattr`",
"wraps",
"around",
"the",
"underlying",
"type,",
"aka",
"``__origin__``."
] | def test_getattr(self, name: str) -> None:
value = getattr(NDArray, name)
value_ref1 = getattr(np.ndarray, name)
if sys.version_info >= (3, 9):
value_ref2 = getattr(NDArray_ref, name)
assert value == value_ref1 == value_ref2
else:
assert value == value_ref1 | ['def', 'test_getattr(self,', 'name:', 'str)', '->', 'None:', 'value', '=', 'getattr(NDArray,', 'name)', 'value_ref1', '=', 'getattr(np.ndarray,', 'name)', 'if', 'sys.version_info', '>=', '(3,', '9):', 'value_ref2', '=', 'getattr(NDArray_ref,', 'name)', 'assert', 'value', '==', 'value_ref1', '==', 'value_ref2', 'else:'... | 323,079 |
for-ai/rl | pendulum.py | gen_params | gen_params | Returns a tensordict containing the physical parameters such as gravitational force and torque or speed limits. | [
"Returns",
"a",
"tensordict",
"containing",
"the",
"physical",
"parameters",
"such",
"as",
"gravitational",
"force",
"and",
"torque",
"or",
"speed",
"limits."
] | def gen_params(g=10.0, batch_size=None) -> TensorDictBase:
if batch_size is None:
batch_size = []
td = TensorDict({'params': TensorDict({'max_speed': 8, 'max_torque': 2.0, 'dt': 0.05, 'g': g, 'm': 1.0, 'l': 1.0}, [])}, [])
if batch_size:
td = td.expand(batch_size).contiguous()
return td | ['def', 'gen_params(g=10.0,', 'batch_size=None)', '->', 'TensorDictBase:', 'if', 'batch_size', 'is', 'None:', 'batch_size', '=', '[]', 'td', '=', "TensorDict({'params':", "TensorDict({'max_speed':", '8,', "'max_torque':", '2.0,', "'dt':", '0.05,', "'g':", 'g,', "'m':", '1.0,', "'l':", '1.0},', '[])},', '[])', 'if', 'ba... | 859,601 |
unixpickle/anyrl-py | replay.py | FloatBuffer.set_value | set_value | Set the value at the given index. | [
"Set",
"the",
"value",
"at",
"the",
"given",
"index."
] | def set_value(self, idx, value):
idx = (idx + self._start) % self._capacity
self._set_idx(idx, value) | ['def', 'set_value(self,', 'idx,', 'value):', 'idx', '=', '(idx', '+', 'self._start)', '%', 'self._capacity', 'self._set_idx(idx,', 'value)'] | 33,863 |
palmettos/neat-autoencoders | test_distributed.py | run_primary | run_primary | Starts a DistributedEvaluator in primary mode. | [
"Starts",
"a",
"DistributedEvaluator",
"in",
"primary",
"mode."
] | def run_primary(addr, authkey, generations):
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'test_configuration')
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path)
p = neat.Population(config)
p... | ['def', 'run_primary(addr,', 'authkey,', 'generations):', 'local_dir', '=', 'os.path.dirname(__file__)', 'config_path', '=', 'os.path.join(local_dir,', "'test_configuration')", 'config', '=', 'neat.Config(neat.DefaultGenome,', 'neat.DefaultReproduction,', 'neat.DefaultSpeciesSet,', 'neat.DefaultStagnation,', 'config_pa... | 735,243 |
Kvatsx/Artificial-Intelligence-Assignments | test_mlab.py | TestGaussianKDECustom.test_no_data | test_no_data | Pass no data into the GaussianKDE class. | [
"Pass",
"no",
"data",
"into",
"the",
"GaussianKDE",
"class."
] | def test_no_data(self):
with pytest.raises(ValueError):
mlab.GaussianKDE([]) | ['def', 'test_no_data(self):', 'with', 'pytest.raises(ValueError):', 'mlab.GaussianKDE([])'] | 1,517 |
SamHusbands21/thesis | C4ht_array.py | rand | rand | Returns an C4htArray of shape size, with randomly chosen elements in int parameterization. | [
"Returns",
"an",
"C4htArray",
"of",
"shape",
"size,",
"with",
"randomly",
"chosen",
"elements",
"in",
"int",
"parameterization."
] | def rand(minu=0, maxu=5, minv=0, maxv=5, minw=0, maxw=5, size=()):
data = np.zeros(size + (5,), dtype=np.int64)
data[..., 0] = np.random.randint(0, 2, size)
data[..., 1] = np.random.randint(0, 4, size)
data[..., 2] = np.random.randint(minu, maxu, size)
data[..., 3] = np.random.randint(minv, maxv, si... | ['def', 'rand(minu=0,', 'maxu=5,', 'minv=0,', 'maxv=5,', 'minw=0,', 'maxw=5,', 'size=()):', 'data', '=', 'np.zeros(size', '+', '(5,),', 'dtype=np.int64)', 'data[...,', '0]', '=', 'np.random.randint(0,', '2,', 'size)', 'data[...,', '1]', '=', 'np.random.randint(0,', '4,', 'size)', 'data[...,', '2]', '=', 'np.random.rand... | 354,787 |
sunishsheth2009/ChatterBot | highlight.py | HtmlFormatter.clean | clean | Clears the dictionary mapping terms to HTML classnames. | [
"Clears",
"the",
"dictionary",
"mapping",
"terms",
"to",
"HTML",
"classnames."
] | def clean(self):
self.seen = {} | ['def', 'clean(self):', 'self.seen', '=', '{}'] | 483,931 |
Kvatsx/Artificial-Intelligence-Assignments | buffer.py | Buffer.delete | delete | Delete specified number of characters and Return the deleted text. | [
"Delete",
"specified",
"number",
"of",
"characters",
"and",
"Return",
"the",
"deleted",
"text."
] | def delete(self, count=1):
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + self.text[self.cursor_position + len(deleted):]
return deleted
else:
return '' | ['def', 'delete(self,', 'count=1):', 'if', 'self.cursor_position', '<', 'len(self.text):', 'deleted', '=', 'self.document.text_after_cursor[:count]', 'self.text', '=', 'self.text[:self.cursor_position]', '+', 'self.text[self.cursor_position', '+', 'len(deleted):]', 'return', 'deleted', 'else:', 'return', "''"] | 75,560 |
exiawsh/StreamPETR | repdetr3d.py | RepDetr3D.forward_pts_train | forward_pts_train | Forward function for point cloud branch. | [
"Forward",
"function",
"for",
"point",
"cloud",
"branch."
] | def forward_pts_train(self, gt_bboxes_3d, gt_labels_3d, gt_bboxes, gt_labels, img_metas, centers2d, depths, requires_grad=True, return_losses=False, **data):
if not requires_grad:
self.eval()
with torch.no_grad():
outs = self.pts_bbox_head(img_metas, **data)
self.train()
else... | ['def', 'forward_pts_train(self,', 'gt_bboxes_3d,', 'gt_labels_3d,', 'gt_bboxes,', 'gt_labels,', 'img_metas,', 'centers2d,', 'depths,', 'requires_grad=True,', 'return_losses=False,', '**data):', 'if', 'not', 'requires_grad:', 'self.eval()', 'with', 'torch.no_grad():', 'outs', '=', 'self.pts_bbox_head(img_metas,', '**da... | 910,075 |
santi-pdp/segan | utils.py | emphasis | emphasis | Pre-emphasis or De-emphasis of higher frequencies given a batch of signal. | [
"Pre-emphasis",
"or",
"De-emphasis",
"of",
"higher",
"frequencies",
"given",
"a",
"batch",
"of",
"signal."
] | def emphasis(signal_batch, emph_coeff=0.95, pre=True):
result = np.zeros(signal_batch.shape)
for (sample_idx, sample) in enumerate(signal_batch):
for (ch, channel_data) in enumerate(sample):
if pre:
result[sample_idx][ch] = np.append(channel_data[0], channel_data[1:] - emph_c... | ['def', 'emphasis(signal_batch,', 'emph_coeff=0.95,', 'pre=True):', 'result', '=', 'np.zeros(signal_batch.shape)', 'for', '(sample_idx,', 'sample)', 'in', 'enumerate(signal_batch):', 'for', '(ch,', 'channel_data)', 'in', 'enumerate(sample):', 'if', 'pre:', 'result[sample_idx][ch]', '=', 'np.append(channel_data[0],', 'c... | 842,021 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | ops.py | retain_groundtruth_with_positive_classes | retain_groundtruth_with_positive_classes | Retains only groundtruth with positive class ids. | [
"Retains",
"only",
"groundtruth",
"with",
"positive",
"class",
"ids."
] | def retain_groundtruth_with_positive_classes(tensor_dict):
if fields.InputDataFields.groundtruth_classes not in tensor_dict:
raise ValueError('`groundtruth classes` not in tensor_dict.')
keep_indices = tf.where(tf.greater(tensor_dict[fields.InputDataFields.groundtruth_classes], 0))
return retain_gro... | ['def', 'retain_groundtruth_with_positive_classes(tensor_dict):', 'if', 'fields.InputDataFields.groundtruth_classes', 'not', 'in', 'tensor_dict:', 'raise', "ValueError('`groundtruth", 'classes`', 'not', 'in', "tensor_dict.')", 'keep_indices', '=', 'tf.where(tf.greater(tensor_dict[fields.InputDataFields.groundtruth_clas... | 52,247 |
zzndream/ShipRSImageNet | anchor_head.py | AnchorHead.get_targets | get_targets | Compute regression and classification targets for anchors in multiple images. | [
"Compute",
"regression",
"and",
"classification",
"targets",
"for",
"anchors",
"in",
"multiple",
"images."
] | def get_targets(self, anchor_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list=None, gt_labels_list=None, label_channels=1, unmap_outputs=True, return_sampling_results=False):
num_imgs = len(img_metas)
assert len(anchor_list) == len(valid_flag_list) == num_imgs
num_level_anchors = [anc... | ['def', 'get_targets(self,', 'anchor_list,', 'valid_flag_list,', 'gt_bboxes_list,', 'img_metas,', 'gt_bboxes_ignore_list=None,', 'gt_labels_list=None,', 'label_channels=1,', 'unmap_outputs=True,', 'return_sampling_results=False):', 'num_imgs', '=', 'len(img_metas)', 'assert', 'len(anchor_list)', '==', 'len(valid_flag_l... | 901,377 |
dingmyu/D4LCN | core.py | adjust_lr | adjust_lr | Adjusts the learning rate of an optimizer according to iteration and configuration, primarily regarding regular SGD learning rate policies. | [
"Adjusts",
"the",
"learning",
"rate",
"of",
"an",
"optimizer",
"according",
"to",
"iteration",
"and",
"configuration,",
"primarily",
"regarding",
"regular",
"SGD",
"learning",
"rate",
"policies."
] | def adjust_lr(conf, optimizer, iter, scheduler):
if 'batch_skip' in conf and (iter + 1) % conf.batch_skip > 0:
return
if conf.solver_type.lower() == 'sgd':
lr = conf.lr
lr_steps = conf.lr_steps
max_iter = conf.max_iter
lr_policy = conf.lr_policy
lr_target = conf.l... | ['def', 'adjust_lr(conf,', 'optimizer,', 'iter,', 'scheduler):', 'if', "'batch_skip'", 'in', 'conf', 'and', '(iter', '+', '1)', '%', 'conf.batch_skip', '>', '0:', 'return', 'if', 'conf.solver_type.lower()', '==', "'sgd':", 'lr', '=', 'conf.lr', 'lr_steps', '=', 'conf.lr_steps', 'max_iter', '=', 'conf.max_iter', 'lr_pol... | 526,129 |
boostcampaitech2/semantic-segmentation-level2-cv-05 | transforms.py | Resize.random_select | random_select | Randomly select an img_scale from given candidates. | [
"Randomly",
"select",
"an",
"img_scale",
"from",
"given",
"candidates."
] | def random_select(img_scales):
assert mmcv.is_list_of(img_scales, tuple)
scale_idx = np.random.randint(len(img_scales))
img_scale = img_scales[scale_idx]
return (img_scale, scale_idx) | ['def', 'random_select(img_scales):', 'assert', 'mmcv.is_list_of(img_scales,', 'tuple)', 'scale_idx', '=', 'np.random.randint(len(img_scales))', 'img_scale', '=', 'img_scales[scale_idx]', 'return', '(img_scale,', 'scale_idx)'] | 844,665 |
openvinotoolkit/training_extensions | augments.py | CythonAugments.translate_x_rel | translate_x_rel | Apply translate_x_rel for an given image. | [
"Apply",
"translate_x_rel",
"for",
"an",
"given",
"image."
] | def translate_x_rel(img: ImgTypes, pct: float, *args, **kwargs) -> ImgTypes:
if Image.isImageType(img):
return pil_aug.translate_x_rel(img, pct)
raise NotImplementedError(f'Unknown type: {type(img)}') | ['def', 'translate_x_rel(img:', 'ImgTypes,', 'pct:', 'float,', '*args,', '**kwargs)', '->', 'ImgTypes:', 'if', 'Image.isImageType(img):', 'return', 'pil_aug.translate_x_rel(img,', 'pct)', 'raise', "NotImplementedError(f'Unknown", 'type:', "{type(img)}')"] | 917,913 |
thaines/helit | corpus.py | Corpus.getDocument | getDocument | Returns the Document associated with the given ident. | [
"Returns",
"the",
"Document",
"associated",
"with",
"the",
"given",
"ident."
] | def getDocument(self, ident):
return self.docs[ident] | ['def', 'getDocument(self,', 'ident):', 'return', 'self.docs[ident]'] | 591,031 |
rudranil723/mini-main | text.py | Text.wrap | wrap | Word wrap the text. | [
"Word",
"wrap",
"the",
"text."
] | def wrap(self, console: 'Console', width: int, *, justify: Optional['JustifyMethod']=None, overflow: Optional['OverflowMethod']=None, tab_size: int=8, no_wrap: Optional[bool]=None) -> Lines:
wrap_justify = justify or self.justify or DEFAULT_JUSTIFY
wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
... | ['def', 'wrap(self,', 'console:', "'Console',", 'width:', 'int,', '*,', 'justify:', "Optional['JustifyMethod']=None,", 'overflow:', "Optional['OverflowMethod']=None,", 'tab_size:', 'int=8,', 'no_wrap:', 'Optional[bool]=None)', '->', 'Lines:', 'wrap_justify', '=', 'justify', 'or', 'self.justify', 'or', 'DEFAULT_JUSTIFY'... | 269,000 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | image_processing.py | image_preprocessing | image_preprocessing | Decode and preprocess one image for evaluation or training. | [
"Decode",
"and",
"preprocess",
"one",
"image",
"for",
"evaluation",
"or",
"training."
] | def image_preprocessing(image_buffer, bbox, train, thread_id=0):
if bbox is None:
raise ValueError('Please supply a bounding box.')
image = decode_jpeg(image_buffer)
height = FLAGS.image_size
width = FLAGS.image_size
if train:
image = distort_image(image, height, width, bbox, thread_... | ['def', 'image_preprocessing(image_buffer,', 'bbox,', 'train,', 'thread_id=0):', 'if', 'bbox', 'is', 'None:', 'raise', "ValueError('Please", 'supply', 'a', 'bounding', "box.')", 'image', '=', 'decode_jpeg(image_buffer)', 'height', '=', 'FLAGS.image_size', 'width', '=', 'FLAGS.image_size', 'if', 'train:', 'image', '=', ... | 48,974 |
tencent-ailab/TriNet | fp16_optimizer.py | _MemoryEfficientFP16OptimizerMixin.multiply_grads | multiply_grads | Multiplies grads by a constant *c*. | [
"Multiplies",
"grads",
"by",
"a",
"constant",
"*c*."
] | def multiply_grads(self, c):
self._multiply_factor *= c | ['def', 'multiply_grads(self,', 'c):', 'self._multiply_factor', '*=', 'c'] | 425,624 |
43Carrig/recurrent_neural_networks_practice | message_test.py | MessageTest.testSortingRepeatedScalarFieldsCustomComparator | testSortingRepeatedScalarFieldsCustomComparator | Check some different types with custom comparator. | [
"Check",
"some",
"different",
"types",
"with",
"custom",
"comparator."
] | def testSortingRepeatedScalarFieldsCustomComparator(self, message_module):
message = message_module.TestAllTypes()
message.repeated_int32.append(-3)
message.repeated_int32.append(-2)
message.repeated_int32.append(-1)
message.repeated_int32.sort(key=abs)
self.assertEqual(message.repeated_int32[0]... | ['def', 'testSortingRepeatedScalarFieldsCustomComparator(self,', 'message_module):', 'message', '=', 'message_module.TestAllTypes()', 'message.repeated_int32.append(-3)', 'message.repeated_int32.append(-2)', 'message.repeated_int32.append(-1)', 'message.repeated_int32.sort(key=abs)', 'self.assertEqual(message.repeated_... | 309,945 |
sklearn-theano/sklearn-theano | decoder.py | MapDecoder | MapDecoder | Returns a decoder for a map field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"map",
"field."
] | def MapDecoder(field_descriptor, new_default, is_message_map):
key = field_descriptor
tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED)
tag_len = len(tag_bytes)
local_DecodeVarint = _DecodeVarint
message_type = field_descriptor.message_type
def DecodeM... | ['def', 'MapDecoder(field_descriptor,', 'new_default,', 'is_message_map):', 'key', '=', 'field_descriptor', 'tag_bytes', '=', 'encoder.TagBytes(field_descriptor.number,', 'wire_format.WIRETYPE_LENGTH_DELIMITED)', 'tag_len', '=', 'len(tag_bytes)', 'local_DecodeVarint', '=', '_DecodeVarint', 'message_type', '=', 'field_d... | 351,149 |
ChenhongyiYang/PGD | centernet_head.py | CenterNetHead.decode_heatmap | decode_heatmap | Transform outputs into detections raw bbox prediction. | [
"Transform",
"outputs",
"into",
"detections",
"raw",
"bbox",
"prediction."
] | def decode_heatmap(self, center_heatmap_pred, wh_pred, offset_pred, img_shape, k=100, kernel=3):
(height, width) = center_heatmap_pred.shape[2:]
(inp_h, inp_w) = img_shape
center_heatmap_pred = get_local_maximum(center_heatmap_pred, kernel=kernel)
(*batch_dets, topk_ys, topk_xs) = get_topk_from_heatmap(... | ['def', 'decode_heatmap(self,', 'center_heatmap_pred,', 'wh_pred,', 'offset_pred,', 'img_shape,', 'k=100,', 'kernel=3):', '(height,', 'width)', '=', 'center_heatmap_pred.shape[2:]', '(inp_h,', 'inp_w)', '=', 'img_shape', 'center_heatmap_pred', '=', 'get_local_maximum(center_heatmap_pred,', 'kernel=kernel)', '(*batch_de... | 767,983 |
deepmind/dm_control | autotune.py | tune_stud_radius | tune_stud_radius | Find a stud size that gives the desired separation force. | [
"Find",
"a",
"stud",
"size",
"that",
"gives",
"the",
"desired",
"separation",
"force."
] | def tune_stud_radius(desired_force, min_radius=0.0045, max_radius=0.005, desired_places=6, side='closest', **duplo_kwargs):
@_KeepBracketingSolutions
def func(radius):
radius = round(radius, desired_places)
return get_separation_force_for_radius(radius=radius, **duplo_kwargs) - desired_force
... | ['def', 'tune_stud_radius(desired_force,', 'min_radius=0.0045,', 'max_radius=0.005,', 'desired_places=6,', "side='closest',", '**duplo_kwargs):', '@_KeepBracketingSolutions', 'def', 'func(radius):', 'radius', '=', 'round(radius,', 'desired_places)', 'return', 'get_separation_force_for_radius(radius=radius,', '**duplo_k... | 165,899 |
zbwxp/NRD_decoder | unet.py | UNet.train | train | Convert the model into training mode while keep normalization layer freezed. | [
"Convert",
"the",
"model",
"into",
"training",
"mode",
"while",
"keep",
"normalization",
"layer",
"freezed."
] | def train(self, mode=True):
super(UNet, self).train(mode)
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval() | ['def', 'train(self,', 'mode=True):', 'super(UNet,', 'self).train(mode)', 'if', 'mode', 'and', 'self.norm_eval:', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', '_BatchNorm):', 'm.eval()'] | 729,883 |
sek788432/Waymo-2D-Object-Detection | base_model.py | Model.eval_metrics | eval_metrics | Returns tuple of metric function and its inputs for evaluation. | [
"Returns",
"tuple",
"of",
"metric",
"function",
"and",
"its",
"inputs",
"for",
"evaluation."
] | def eval_metrics(self):
raise NotImplementedError('Unimplemented eval_metrics') | ['def', 'eval_metrics(self):', 'raise', "NotImplementedError('Unimplemented", "eval_metrics')"] | 973,510 |
Brophy-E/ECG_GAN_MBD | train.py | permutation_test_mat | permutation_test_mat | Compute the p-value of the following statistic (rejects when high) \sum_{i,j} a_{\pi(i), \pi(j)} matrix[i, j]. | [
"Compute",
"the",
"p-value",
"of",
"the",
"following",
"statistic",
"(rejects",
"when",
"high)",
"\\sum_{i,j}",
"a_{\\pi(i),",
"\\pi(j)}",
"matrix[i,",
"j]."
] | def permutation_test_mat(matrix, n_1, n_2, n_permutations, a00=1, a11=1, a01=0):
n = n_1 + n_2
pi = np.zeros(n, dtype=np.int8)
pi[n_1:] = 1
larger = 0.0
count = 0
for sample_n in range(1 + n_permutations):
count = 0.0
for i in range(n):
for j in range(i, n):
... | ['def', 'permutation_test_mat(matrix,', 'n_1,', 'n_2,', 'n_permutations,', 'a00=1,', 'a11=1,', 'a01=0):', 'n', '=', 'n_1', '+', 'n_2', 'pi', '=', 'np.zeros(n,', 'dtype=np.int8)', 'pi[n_1:]', '=', '1', 'larger', '=', '0.0', 'count', '=', '0', 'for', 'sample_n', 'in', 'range(1', '+', 'n_permutations):', 'count', '=', '0.... | 547,869 |
awslabs/predictive-maintenance-using-- | test_html.py | TestReadHtml.test_empty_tables | test_empty_tables | Make sure that read_html ignores empty tables. | [
"Make",
"sure",
"that",
"read_html",
"ignores",
"empty",
"tables."
] | def test_empty_tables(self):
result = self.read_html('\n <table>\n <thead>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n ... | ['def', 'test_empty_tables(self):', 'result', '=', "self.read_html('\\n", '<table>\\n', '<thead>\\n', '<tr>\\n', '<th>A</th>\\n', '<th>B</th>\\n', '</tr>\\n', '</thead>\\n', '<tbody>\\n', '<tr>\\n', '<td>1</td>\\n', '<td>2</td>\\n', '</tr>\\n', '</tbody>\\n', '</table>\\n', '<table>\\n', '<tbody>\\n', '</tbody>\\n', '<... | 824,195 |
matsu0228/nlp-jp | gtk3embed.py | GTKEmbed.start | start | Starts the GTK main event loop and sets our kernel startup routine. | [
"Starts",
"the",
"GTK",
"main",
"event",
"loop",
"and",
"sets",
"our",
"kernel",
"startup",
"routine."
] | def start(self):
GObject.idle_add(self._wire_kernel)
Gtk.main() | ['def', 'start(self):', 'GObject.idle_add(self._wire_kernel)', 'Gtk.main()'] | 786,418 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | template.py | Base.typeName | typeName | Returns the name of this template type. | [
"Returns",
"the",
"name",
"of",
"this",
"template",
"type."
] | def typeName(self):
return self.className.lower() | ['def', 'typeName(self):', 'return', 'self.className.lower()'] | 17,055 |
aralab-unr/ReinforcementLearningWithGA | utils.py | TfInput.get | get | Return the tf variable(s) representing the possibly postprocessed value of placeholder(s). | [
"Return",
"the",
"tf",
"variable(s)",
"representing",
"the",
"possibly",
"postprocessed",
"value",
"of",
"placeholder(s)."
] | def get(self):
raise NotImplemented() | ['def', 'get(self):', 'raise', 'NotImplemented()'] | 833,908 |
aws/sagemaker-python-sdk | pipeline.py | Pipeline.update | update | Updates a Pipeline in the Workflow service. | [
"Updates",
"a",
"Pipeline",
"in",
"the",
"Workflow",
"service."
] | def update(self, role_arn: str=None, description: str=None, parallelism_config: ParallelismConfiguration=None) -> Dict[str, Any]:
role_arn = resolve_value_from_config(role_arn, PIPELINE_ROLE_ARN_PATH, sagemaker_session=self.sagemaker_session)
if not role_arn:
raise ValueError('An AWS IAM role is require... | ['def', 'update(self,', 'role_arn:', 'str=None,', 'description:', 'str=None,', 'parallelism_config:', 'ParallelismConfiguration=None)', '->', 'Dict[str,', 'Any]:', 'role_arn', '=', 'resolve_value_from_config(role_arn,', 'PIPELINE_ROLE_ARN_PATH,', 'sagemaker_session=self.sagemaker_session)', 'if', 'not', 'role_arn:', 'r... | 830,634 |
deepmind/bsuite | csv_logging.py | Logger.write | write | Adds a row to the internal list of data and saves to CSV. | [
"Adds",
"a",
"row",
"to",
"the",
"internal",
"list",
"of",
"data",
"and",
"saves",
"to",
"CSV."
] | def write(self, data: Mapping[str, Any]):
self._data.append(data)
df = pd.DataFrame(self._data)
df.to_csv(self._save_path, index=False) | ['def', 'write(self,', 'data:', 'Mapping[str,', 'Any]):', 'self._data.append(data)', 'df', '=', 'pd.DataFrame(self._data)', 'df.to_csv(self._save_path,', 'index=False)'] | 410,254 |
clvrai/spirl | general_utils.py | GetIntermediatesSequential.forward | forward | Computes forward pass through the network outputting all intermediate activations with final output. | [
"Computes",
"forward",
"pass",
"through",
"the",
"network",
"outputting",
"all",
"intermediate",
"activations",
"with",
"final",
"output."
] | def forward(self, input):
skips = []
for (i, module) in enumerate(self._modules.values()):
input = module(input)
if i % self.stride == 0:
skips.append(input)
else:
skips.append(None)
return (input, skips[:-1]) | ['def', 'forward(self,', 'input):', 'skips', '=', '[]', 'for', '(i,', 'module)', 'in', 'enumerate(self._modules.values()):', 'input', '=', 'module(input)', 'if', 'i', '%', 'self.stride', '==', '0:', 'skips.append(input)', 'else:', 'skips.append(None)', 'return', '(input,', 'skips[:-1])'] | 897,066 |
logang/neuroparser | synthetic_data.py | gen_correlated_instance | gen_correlated_instance | Generate a particular n imes p image instance with correlated noise. | [
"Generate",
"a",
"particular",
"n",
"imes",
"p",
"image",
"instance",
"with",
"correlated",
"noise."
] | def gen_correlated_instance(n, p, corr1, corr2=None, signal=None):
if signal is None:
return gen_correlated_matrix(n, p, corr1=corr1, corr2=corr2)
else:
return signal + gen_correlated_matrix(n, p, corr1=corr1, corr2=corr2) | ['def', 'gen_correlated_instance(n,', 'p,', 'corr1,', 'corr2=None,', 'signal=None):', 'if', 'signal', 'is', 'None:', 'return', 'gen_correlated_matrix(n,', 'p,', 'corr1=corr1,', 'corr2=corr2)', 'else:', 'return', 'signal', '+', 'gen_correlated_matrix(n,', 'p,', 'corr1=corr1,', 'corr2=corr2)'] | 293,743 |
MANGA-UOFA/NAUS | transformer_encoder.py | TransformerEncoderBase.reorder_encoder_out | reorder_encoder_out | Reorder encoder output according to *new_order*. | [
"Reorder",
"encoder",
"output",
"according",
"to",
"*new_order*."
] | def reorder_encoder_out(self, encoder_out: Dict[str, List[Tensor]], new_order):
if len(encoder_out['encoder_out']) == 0:
new_encoder_out = []
else:
new_encoder_out = [encoder_out['encoder_out'][0].index_select(1, new_order)]
if len(encoder_out['encoder_padding_mask']) == 0:
new_encod... | ['def', 'reorder_encoder_out(self,', 'encoder_out:', 'Dict[str,', 'List[Tensor]],', 'new_order):', 'if', "len(encoder_out['encoder_out'])", '==', '0:', 'new_encoder_out', '=', '[]', 'else:', 'new_encoder_out', '=', "[encoder_out['encoder_out'][0].index_select(1,", 'new_order)]', 'if', "len(encoder_out['encoder_padding_... | 291,658 |
ShiiVa03/Artificial-Intelligence | search.py | Graph.nodes | nodes | Return a list of nodes in the graph. | [
"Return",
"a",
"list",
"of",
"nodes",
"in",
"the",
"graph."
] | def nodes(self):
s1 = set([k for k in self.graph_dict.keys()])
s2 = set([k2 for v in self.graph_dict.values() for (k2, v2) in v.items()])
nodes = s1.union(s2)
return list(nodes) | ['def', 'nodes(self):', 's1', '=', 'set([k', 'for', 'k', 'in', 'self.graph_dict.keys()])', 's2', '=', 'set([k2', 'for', 'v', 'in', 'self.graph_dict.values()', 'for', '(k2,', 'v2)', 'in', 'v.items()])', 'nodes', '=', 's1.union(s2)', 'return', 'list(nodes)'] | 117,019 |
rudranil723/mini-main | arraylike.py | dispatch_ufunc_with_out | dispatch_ufunc_with_out | If we have an `out` keyword, then call the ufunc without `out` and then set the result into the given `out`. | [
"If",
"we",
"have",
"an",
"`out`",
"keyword,",
"then",
"call",
"the",
"ufunc",
"without",
"`out`",
"and",
"then",
"set",
"the",
"result",
"into",
"the",
"given",
"`out`."
] | def dispatch_ufunc_with_out(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
out = kwargs.pop('out')
where = kwargs.pop('where', None)
result = getattr(ufunc, method)(*inputs, **kwargs)
if result is NotImplemented:
return NotImplemented
if isinstance(result, tuple):
if not isi... | ['def', 'dispatch_ufunc_with_out(self,', 'ufunc:', 'np.ufunc,', 'method:', 'str,', '*inputs,', '**kwargs):', 'out', '=', "kwargs.pop('out')", 'where', '=', "kwargs.pop('where',", 'None)', 'result', '=', 'getattr(ufunc,', 'method)(*inputs,', '**kwargs)', 'if', 'result', 'is', 'NotImplemented:', 'return', 'NotImplemented... | 323,243 |
vbelz/audio_classification | egg_info.py | FileList.graft | graft | Include all files from 'dir/'. | [
"Include",
"all",
"files",
"from",
"'dir/'."
] | def graft(self, dir):
found = [item for match_dir in glob(dir) for item in distutils.filelist.findall(match_dir)]
self.extend(found)
return bool(found) | ['def', 'graft(self,', 'dir):', 'found', '=', '[item', 'for', 'match_dir', 'in', 'glob(dir)', 'for', 'item', 'in', 'distutils.filelist.findall(match_dir)]', 'self.extend(found)', 'return', 'bool(found)'] | 404,356 |
weimin17/Object-Detection_HelmetDetection | util.py | convert_and_cast | convert_and_cast | Convert input to tensor and cast to dtype. | [
"Convert",
"input",
"to",
"tensor",
"and",
"cast",
"to",
"dtype."
] | def convert_and_cast(value, name, dtype):
return tf.cast(tf.convert_to_tensor(value, name=name), dtype=dtype) | ['def', 'convert_and_cast(value,', 'name,', 'dtype):', 'return', 'tf.cast(tf.convert_to_tensor(value,', 'name=name),', 'dtype=dtype)'] | 763,029 |
sotudian/Natural-Language-Processing | vector_embeddings.py | IMDBMovieReviews.create_vocab | create_vocab | Creates a vocabulary with tokens that have frequency above unk_threshold and assigns each token a unique index, including the special tokens. | [
"Creates",
"a",
"vocabulary",
"with",
"tokens",
"that",
"have",
"frequency",
"above",
"unk_threshold",
"and",
"assigns",
"each",
"token",
"a",
"unique",
"index,",
"including",
"the",
"special",
"tokens."
] | def create_vocab(self, data, unk_threshold=UNK_THRESHOLD):
counter = Counter((token for review in data for token in review[L_TOKENS]))
self.vocab = {token for token in counter if counter[token] > unk_threshold}
token_to_idx = {PAD: 0, UNK: 1}
for token in self.vocab:
token_to_idx[token] = len(to... | ['def', 'create_vocab(self,', 'data,', 'unk_threshold=UNK_THRESHOLD):', 'counter', '=', 'Counter((token', 'for', 'review', 'in', 'data', 'for', 'token', 'in', 'review[L_TOKENS]))', 'self.vocab', '=', '{token', 'for', 'token', 'in', 'counter', 'if', 'counter[token]', '>', 'unk_threshold}', 'token_to_idx', '=', '{PAD:', ... | 658,069 |
keras-team/keras-cv | centernet_box_loss.py | l1 | l1 | Computes element-wise l1 loss. | [
"Computes",
"element-wise",
"l1",
"loss."
] | def l1(y_true, y_pred, sigma=9.0):
absolute_difference = ops.abs(y_pred - y_true)
loss = ops.where(absolute_difference < 1.0 / sigma, 0.5 * sigma * absolute_difference ** 2, absolute_difference - 0.5 / sigma)
return ops.sum(loss, axis=-1) | ['def', 'l1(y_true,', 'y_pred,', 'sigma=9.0):', 'absolute_difference', '=', 'ops.abs(y_pred', '-', 'y_true)', 'loss', '=', 'ops.where(absolute_difference', '<', '1.0', '/', 'sigma,', '0.5', '*', 'sigma', '*', 'absolute_difference', '**', '2,', 'absolute_difference', '-', '0.5', '/', 'sigma)', 'return', 'ops.sum(loss,',... | 595,115 |
dtemir/harvard-CS50AI | minesweeper.py | Minesweeper.nearby_mines | nearby_mines | Returns the number of mines that are within one row and column of a given cell, not including the cell itself. | [
"Returns",
"the",
"number",
"of",
"mines",
"that",
"are",
"within",
"one",
"row",
"and",
"column",
"of",
"a",
"given",
"cell,",
"not",
"including",
"the",
"cell",
"itself."
] | def nearby_mines(self, cell):
count = 0
for i in range(cell[0] - 1, cell[0] + 2):
for j in range(cell[1] - 1, cell[1] + 2):
if (i, j) == cell:
continue
if 0 <= i < self.height and 0 <= j < self.width:
if self.board[i][j]:
count ... | ['def', 'nearby_mines(self,', 'cell):', 'count', '=', '0', 'for', 'i', 'in', 'range(cell[0]', '-', '1,', 'cell[0]', '+', '2):', 'for', 'j', 'in', 'range(cell[1]', '-', '1,', 'cell[1]', '+', '2):', 'if', '(i,', 'j)', '==', 'cell:', 'continue', 'if', '0', '<=', 'i', '<', 'self.height', 'and', '0', '<=', 'j', '<', 'self.w... | 205,813 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | multi.py | MultiIndex.is_monotonic_decreasing | is_monotonic_decreasing | return if the index is monotonic decreasing (only equal or decreasing) values. | [
"return",
"if",
"the",
"index",
"is",
"monotonic",
"decreasing",
"(only",
"equal",
"or",
"decreasing)",
"values."
] | def is_monotonic_decreasing(self) -> bool:
return self[::-1].is_monotonic_increasing | ['def', 'is_monotonic_decreasing(self)', '->', 'bool:', 'return', 'self[::-1].is_monotonic_increasing'] | 453,182 |
BMIRDS/deepslide | utils_evaluation.py | get_xy_to_pred_class | get_xy_to_pred_class | Find the dictionary of predictions. | [
"Find",
"the",
"dictionary",
"of",
"predictions."
] | def get_xy_to_pred_class(window_prediction_folder: Path, img_name: str) -> Dict[Tuple[str, str], Tuple[str, float]]:
xy_to_pred_class = {}
with window_prediction_folder.joinpath(img_name).with_suffix('.csv').open(mode='r') as csv_lines_open:
csv_lines = csv_lines_open.readlines()[1:]
predictions... | ['def', 'get_xy_to_pred_class(window_prediction_folder:', 'Path,', 'img_name:', 'str)', '->', 'Dict[Tuple[str,', 'str],', 'Tuple[str,', 'float]]:', 'xy_to_pred_class', '=', '{}', 'with', "window_prediction_folder.joinpath(img_name).with_suffix('.csv').open(mode='r')", 'as', 'csv_lines_open:', 'csv_lines', '=', 'csv_lin... | 539,806 |
ashwanitanwar/nmt-transfer-learning-xlm-r | file_utils.py | s3_etag | s3_etag | Check ETag on S3 object. | [
"Check",
"ETag",
"on",
"S3",
"object."
] | def s3_etag(url):
s3_resource = boto3.resource('s3')
(bucket_name, s3_path) = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag | ['def', 's3_etag(url):', 's3_resource', '=', "boto3.resource('s3')", '(bucket_name,', 's3_path)', '=', 'split_s3_path(url)', 's3_object', '=', 's3_resource.Object(bucket_name,', 's3_path)', 'return', 's3_object.e_tag'] | 732,834 |
sek788432/Waymo-2D-Object-Detection | tfrecord_lib.py | write_tf_record_dataset | write_tf_record_dataset | Iterates over annotations, processes them and writes into TFRecords. | [
"Iterates",
"over",
"annotations,",
"processes",
"them",
"and",
"writes",
"into",
"TFRecords."
] | def write_tf_record_dataset(output_path, annotation_iterator, process_func, num_shards, use_multiprocessing=True, unpack_arguments=True):
writers = [tf.io.TFRecordWriter(output_path + '-%05d-of-%05d.tfrecord' % (i, num_shards)) for i in range(num_shards)]
total_num_annotations_skipped = 0
if use_multiproces... | ['def', 'write_tf_record_dataset(output_path,', 'annotation_iterator,', 'process_func,', 'num_shards,', 'use_multiprocessing=True,', 'unpack_arguments=True):', 'writers', '=', '[tf.io.TFRecordWriter(output_path', '+', "'-%05d-of-%05d.tfrecord'", '%', '(i,', 'num_shards))', 'for', 'i', 'in', 'range(num_shards)]', 'total... | 973,049 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | fairseq_optimizer.py | FairseqOptimizer.zero_grad | zero_grad | Clears the gradients of all optimized parameters. | [
"Clears",
"the",
"gradients",
"of",
"all",
"optimized",
"parameters."
] | def zero_grad(self):
for p in self.params:
p.grad = None
self.optimizer.zero_grad() | ['def', 'zero_grad(self):', 'for', 'p', 'in', 'self.params:', 'p.grad', '=', 'None', 'self.optimizer.zero_grad()'] | 104,049 |
open-mmlab/mmdetection3d | base_box3d.py | BaseInstance3DBoxes.top_height | top_height | Tensor: A vector with top height of each box in shape (N, ). | [
"Tensor:",
"A",
"vector",
"with",
"top",
"height",
"of",
"each",
"box",
"in",
"shape",
"(N,",
")."
] | def top_height(self) -> Tensor:
return self.bottom_height + self.height | ['def', 'top_height(self)', '->', 'Tensor:', 'return', 'self.bottom_height', '+', 'self.height'] | 632,230 |
RasaHQ/rasa | io.py | write_text_file | write_text_file | Writes text to a file. | [
"Writes",
"text",
"to",
"a",
"file."
] | def write_text_file(content: Text, file_path: Union[Text, Path], encoding: Text=DEFAULT_ENCODING, append: bool=False) -> None:
mode = 'a' if append else 'w'
with open(file_path, mode, encoding=encoding) as file:
file.write(content) | ['def', 'write_text_file(content:', 'Text,', 'file_path:', 'Union[Text,', 'Path],', 'encoding:', 'Text=DEFAULT_ENCODING,', 'append:', 'bool=False)', '->', 'None:', 'mode', '=', "'a'", 'if', 'append', 'else', "'w'", 'with', 'open(file_path,', 'mode,', 'encoding=encoding)', 'as', 'file:', 'file.write(content)'] | 837,789 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Text.tag_delete | tag_delete | Delete all tags in TAGNAMES. | [
"Delete",
"all",
"tags",
"in",
"TAGNAMES."
] | def tag_delete(self, *tagNames):
self.tk.call((self._w, 'tag', 'delete') + tagNames) | ['def', 'tag_delete(self,', '*tagNames):', 'self.tk.call((self._w,', "'tag',", "'delete')", '+', 'tagNames)'] | 377,081 |
Speedwagon13/CS-3600-Introduction-to-- | test_logging.py | SocketHandlerTest.tearDown | tearDown | Shutdown the TCP server. | [
"Shutdown",
"the",
"TCP",
"server."
] | def tearDown(self):
try:
self.tcpserver.abort = True
del self.tcpserver
self.root_logger.removeHandler(self.sock_hdlr)
self.sock_hdlr.close()
for thread in self.threads:
thread.join(2.0)
finally:
BaseTest.tearDown(self) | ['def', 'tearDown(self):', 'try:', 'self.tcpserver.abort', '=', 'True', 'del', 'self.tcpserver', 'self.root_logger.removeHandler(self.sock_hdlr)', 'self.sock_hdlr.close()', 'for', 'thread', 'in', 'self.threads:', 'thread.join(2.0)', 'finally:', 'BaseTest.tearDown(self)'] | 219,625 |
mj-will/nessai | test_flowproposal_configuration.py | test_config_poolsize_none | test_config_poolsize_none | Test the popluation configuration raises an error if poolsize is None. | [
"Test",
"the",
"popluation",
"configuration",
"raises",
"an",
"error",
"if",
"poolsize",
"is",
"None."
] | def test_config_poolsize_none(proposal):
with pytest.raises(RuntimeError) as excinfo:
FlowProposal.configure_population(proposal, None, None, True, 10, 1.0, 0.0, 'gaussian')
assert 'poolsize' in str(excinfo.value) | ['def', 'test_config_poolsize_none(proposal):', 'with', 'pytest.raises(RuntimeError)', 'as', 'excinfo:', 'FlowProposal.configure_population(proposal,', 'None,', 'None,', 'True,', '10,', '1.0,', '0.0,', "'gaussian')", 'assert', "'poolsize'", 'in', 'str(excinfo.value)'] | 292,682 |
anjanatiha/Generative-Open-Domain-Chatbot-Application-with--Learning | model_helper.py | create_train_model | create_train_model | Create train graph, model, and iterator. | [
"Create",
"train",
"graph,",
"model,",
"and",
"iterator."
] | def create_train_model(model_creator, hparams, scope=None, num_workers=1, jobid=0, extra_args=None):
src_file = '%s.%s' % (hparams.train_prefix, hparams.src)
tgt_file = '%s.%s' % (hparams.train_prefix, hparams.tgt)
src_vocab_file = hparams.src_vocab_file
tgt_vocab_file = hparams.tgt_vocab_file
graph... | ['def', 'create_train_model(model_creator,', 'hparams,', 'scope=None,', 'num_workers=1,', 'jobid=0,', 'extra_args=None):', 'src_file', '=', "'%s.%s'", '%', '(hparams.train_prefix,', 'hparams.src)', 'tgt_file', '=', "'%s.%s'", '%', '(hparams.train_prefix,', 'hparams.tgt)', 'src_vocab_file', '=', 'hparams.src_vocab_file'... | 556,438 |
Eric3911/OpenAGI | msdd_diarizer.py | MSDD_module.output_types | output_types | Return definitions of module output ports. | [
"Return",
"definitions",
"of",
"module",
"output",
"ports."
] | def output_types(self):
return OrderedDict({'probs': NeuralType(('B', 'T', 'C'), ProbsType()), 'scale_weights': NeuralType(('B', 'T', 'C', 'D'), ProbsType())}) | ['def', 'output_types(self):', 'return', "OrderedDict({'probs':", "NeuralType(('B',", "'T',", "'C'),", 'ProbsType()),', "'scale_weights':", "NeuralType(('B',", "'T',", "'C',", "'D'),", 'ProbsType())})'] | 272,583 |
rifqind/Agent-Programs-3KS1 | imports.py | get_modules_containing_name | get_modules_containing_name | Search a name in the directories of modules. | [
"Search",
"a",
"name",
"in",
"the",
"directories",
"of",
"modules."
] | def get_modules_containing_name(evaluator, modules, name):
def check_directories(paths):
for p in paths:
if p is not None:
d = os.path.dirname(os.path.abspath(p))
for file_name in os.listdir(d):
path = os.path.join(d, file_name)
... | ['def', 'get_modules_containing_name(evaluator,', 'modules,', 'name):', 'def', 'check_directories(paths):', 'for', 'p', 'in', 'paths:', 'if', 'p', 'is', 'not', 'None:', 'd', '=', 'os.path.dirname(os.path.abspath(p))', 'for', 'file_name', 'in', 'os.listdir(d):', 'path', '=', 'os.path.join(d,', 'file_name)', 'if', "file_... | 42,108 |
jxhe/unify-parameter-efficient-tuning | optimization_tf.py | GradientAccumulator.reset | reset | Resets the accumulated gradients on the current replica. | [
"Resets",
"the",
"accumulated",
"gradients",
"on",
"the",
"current",
"replica."
] | def reset(self):
if not self._gradients:
return
self._accum_steps.assign(0)
for gradient in self._gradients:
if gradient is not None:
gradient.assign(tf.zeros_like(gradient)) | ['def', 'reset(self):', 'if', 'not', 'self._gradients:', 'return', 'self._accum_steps.assign(0)', 'for', 'gradient', 'in', 'self._gradients:', 'if', 'gradient', 'is', 'not', 'None:', 'gradient.assign(tf.zeros_like(gradient))'] | 948,379 |
Gor-Ren/gym-jsbsim | test_environment.py | TestJsbSimEnv.assertValidObservation | assertValidObservation | Helper; checks shape and values of an observation. | [
"Helper;",
"checks",
"shape",
"and",
"values",
"of",
"an",
"observation."
] | def assertValidObservation(self, obs: np.array):
self.assertEqual(self.env.observation_space.shape, obs.shape, msg='observation has wrong size')
self.assert_in_box_space(obs, self.env.observation_space) | ['def', 'assertValidObservation(self,', 'obs:', 'np.array):', 'self.assertEqual(self.env.observation_space.shape,', 'obs.shape,', "msg='observation", 'has', 'wrong', "size')", 'self.assert_in_box_space(obs,', 'self.env.observation_space)'] | 572,924 |
SALT-NLP/Adaptive-Compositional-Modules | tokenization_tapas.py | TapasTokenizer.create_attention_mask_from_sequences | create_attention_mask_from_sequences | Creates the attention mask according to the query token IDs and a list of table values. | [
"Creates",
"the",
"attention",
"mask",
"according",
"to",
"the",
"query",
"token",
"IDs",
"and",
"a",
"list",
"of",
"table",
"values."
] | def create_attention_mask_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]:
return [1] * (1 + len(query_ids) + 1 + len(table_values)) | ['def', 'create_attention_mask_from_sequences(self,', 'query_ids:', 'List[int],', 'table_values:', 'List[TableValue])', '->', 'List[int]:', 'return', '[1]', '*', '(1', '+', 'len(query_ids)', '+', '1', '+', 'len(table_values))'] | 409,139 |
ArtificialIntelligenceToolkit/aitk.robots | robot.py | Robot.get_widget | get_widget | Get the robot widget. | [
"Get",
"the",
"robot",
"widget."
] | def get_widget(self, size=None, show_robot=None, attributes=None):
from .watchers import RobotWatcher
if self._watcher is None:
size = size if size is not None else 100
show_robot = show_robot if show_robot is not None else True
attributes = attributes if attributes is not None else 'all... | ['def', 'get_widget(self,', 'size=None,', 'show_robot=None,', 'attributes=None):', 'from', '.watchers', 'import', 'RobotWatcher', 'if', 'self._watcher', 'is', 'None:', 'size', '=', 'size', 'if', 'size', 'is', 'not', 'None', 'else', '100', 'show_robot', '=', 'show_robot', 'if', 'show_robot', 'is', 'not', 'None', 'else',... | 86,606 |
gunthercox/ChatterBot | abc.py | ABCMeta.register | register | Register a virtual subclass of an ABC. | [
"Register",
"a",
"virtual",
"subclass",
"of",
"an",
"ABC."
] | def register(cls, subclass):
if not isinstance(subclass, (type, types.ClassType)):
raise TypeError('Can only register classes')
if issubclass(subclass, cls):
return
if issubclass(cls, subclass):
raise RuntimeError('Refusing to create an inheritance cycle')
cls._abc_registry.add(s... | ['def', 'register(cls,', 'subclass):', 'if', 'not', 'isinstance(subclass,', '(type,', 'types.ClassType)):', 'raise', "TypeError('Can", 'only', 'register', "classes')", 'if', 'issubclass(subclass,', 'cls):', 'return', 'if', 'issubclass(cls,', 'subclass):', 'raise', "RuntimeError('Refusing", 'to', 'create', 'an', 'inheri... | 527,972 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | common.py | memory_used | memory_used | Compute memory usage when executing func. | [
"Compute",
"memory",
"usage",
"when",
"executing",
"func."
] | def memory_used(func, *args, **kwargs):
gc.collect()
mem_use = memory_usage((func, args, kwargs), interval=0.001)
return max(mem_use) - min(mem_use) | ['def', 'memory_used(func,', '*args,', '**kwargs):', 'gc.collect()', 'mem_use', '=', 'memory_usage((func,', 'args,', 'kwargs),', 'interval=0.001)', 'return', 'max(mem_use)', '-', 'min(mem_use)'] | 449,654 |
neurospin/pylearn-parsimony | grad.py | L1.grad | grad | Sub-gradient of the function f(x) = |x|_1, where |x|_1 is the L1-norm. | [
"Sub-gradient",
"of",
"the",
"function",
"f(x)",
"=",
"|x|_1,",
"where",
"|x|_1",
"is",
"the",
"L1-norm."
] | def grad(self, x):
grad = np.zeros((x.shape[0], 1))
grad[x >= TOLERANCE] = 1.0
grad[x <= -TOLERANCE] = -1.0
between = (x > -TOLERANCE) & (x < TOLERANCE)
grad[between] = self.rng(between.sum())
return self.l * grad | ['def', 'grad(self,', 'x):', 'grad', '=', 'np.zeros((x.shape[0],', '1))', 'grad[x', '>=', 'TOLERANCE]', '=', '1.0', 'grad[x', '<=', '-TOLERANCE]', '=', '-1.0', 'between', '=', '(x', '>', '-TOLERANCE)', '&', '(x', '<', 'TOLERANCE)', 'grad[between]', '=', 'self.rng(between.sum())', 'return', 'self.l', '*', 'grad'] | 820,009 |
google/deepvariant | variantcall_utils.py | get_med_dp | get_med_dp | Gets the 'MED_DP' field of the VariantCall. | [
"Gets",
"the",
"'MED_DP'",
"field",
"of",
"the",
"VariantCall."
] | def get_med_dp(variant_call):
return struct_utils.get_int_field(variant_call.info, 'MED_DP', is_single_field=True) | ['def', 'get_med_dp(variant_call):', 'return', 'struct_utils.get_int_field(variant_call.info,', "'MED_DP',", 'is_single_field=True)'] | 540,703 |
Media-Smart/volkscv | utils.py | draw_bbox | draw_bbox | Draw image for detection task. | [
"Draw",
"image",
"for",
"detection",
"task."
] | def draw_bbox(img, key, data, colors, categories, category_to_show=None, show_score=False, show_fpfn=False, show_fpfn_format='line', show_ignore=False, score_thr=0.3, base_thickness=1, base_fontscale=0.5, **kwargs):
img_ = img.copy()
anno = data[key]
if not anno:
return (img_, None)
bboxes = ann... | ['def', 'draw_bbox(img,', 'key,', 'data,', 'colors,', 'categories,', 'category_to_show=None,', 'show_score=False,', 'show_fpfn=False,', "show_fpfn_format='line',", 'show_ignore=False,', 'score_thr=0.3,', 'base_thickness=1,', 'base_fontscale=0.5,', '**kwargs):', 'img_', '=', 'img.copy()', 'anno', '=', 'data[key]', 'if',... | 946,438 |
omarmhaimdat/twitter_nlp_native_swift | sessions.py | SessionMixin.permanent | permanent | This reflects the ``'_permanent'`` key in the dict. | [
"This",
"reflects",
"the",
"``'_permanent'``",
"key",
"in",
"the",
"dict."
] | def permanent(self):
return self.get('_permanent', False) | ['def', 'permanent(self):', 'return', "self.get('_permanent',", 'False)'] | 953,103 |
tensorflow/agents | train_eval.py | train_eval | train_eval | A simple train and eval for DDPG. | [
"A",
"simple",
"train",
"and",
"eval",
"for",
"DDPG."
] | def train_eval(root_dir, env_name='HalfCheetah-v2', eval_env_name=None, env_load_fn=suite_mujoco.load, num_iterations=2000000, actor_fc_layers=(400, 300), critic_obs_fc_layers=(400,), critic_action_fc_layers=None, critic_joint_fc_layers=(300,), initial_collect_steps=1000, collect_steps_per_iteration=1, num_parallel_env... | ['def', 'train_eval(root_dir,', "env_name='HalfCheetah-v2',", 'eval_env_name=None,', 'env_load_fn=suite_mujoco.load,', 'num_iterations=2000000,', 'actor_fc_layers=(400,', '300),', 'critic_obs_fc_layers=(400,),', 'critic_action_fc_layers=None,', 'critic_joint_fc_layers=(300,),', 'initial_collect_steps=1000,', 'collect_s... | 23,201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.