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 |
|---|---|---|---|---|---|---|---|---|
scotthuang1989/object_detection_with_tensorflow | feature_extractor.py | ExtractKeypointDescriptor | ExtractKeypointDescriptor | Extract keypoint descriptor for input image. | [
"Extract",
"keypoint",
"descriptor",
"for",
"input",
"image."
] | def ExtractKeypointDescriptor(image, layer_name, image_scales, iou, max_feature_num, abs_thres, model_fn):
original_image_shape_float = tf.gather(tf.to_float(tf.shape(image)), [0, 1])
image_tensor = NormalizePixelValues(image)
image_tensor = tf.expand_dims(image_tensor, 0, name='image/expand_dims')
if l... | ['def', 'ExtractKeypointDescriptor(image,', 'layer_name,', 'image_scales,', 'iou,', 'max_feature_num,', 'abs_thres,', 'model_fn):', 'original_image_shape_float', '=', 'tf.gather(tf.to_float(tf.shape(image)),', '[0,', '1])', 'image_tensor', '=', 'NormalizePixelValues(image)', 'image_tensor', '=', 'tf.expand_dims(image_t... | 796,948 |
tensorflow/agents | utils.py | SquashToSpecNormal.input_distribution | input_distribution | The raw action distribution. | [
"The",
"raw",
"action",
"distribution."
] | def input_distribution(self):
return self._distribution | ['def', 'input_distribution(self):', 'return', 'self._distribution'] | 22,663 |
KalleHallden/InstaAutomator | compat.py | ChainMap.new_child | new_child | New ChainMap with a new dict followed by all previous maps. | [
"New",
"ChainMap",
"with",
"a",
"new",
"dict",
"followed",
"by",
"all",
"previous",
"maps."
] | def new_child(self):
return self.__class__({}, *self.maps) | ['def', 'new_child(self):', 'return', 'self.__class__({},', '*self.maps)'] | 231,636 |
rudranil723/mini-main | base.py | Signer.key_id | key_id | Optional[str]: The key ID used to identify this private key. | [
"Optional[str]:",
"The",
"key",
"ID",
"used",
"to",
"identify",
"this",
"private",
"key."
] | def key_id(self):
raise NotImplementedError('Key id must be implemented') | ['def', 'key_id(self):', 'raise', "NotImplementedError('Key", 'id', 'must', 'be', "implemented')"] | 317,844 |
BMW-InnovationLab/BMW-Semantic--Training-GUI | dataset.py | ObjectDetectionDataset.is_packed | is_packed | Check whether the current dataframe is providing packed representation of rois. | [
"Check",
"whether",
"the",
"current",
"dataframe",
"is",
"providing",
"packed",
"representation",
"of",
"rois."
] | def is_packed(self):
return 'rois' in self.columns and 'xmin' not in self.columns | ['def', 'is_packed(self):', 'return', "'rois'", 'in', 'self.columns', 'and', "'xmin'", 'not', 'in', 'self.columns'] | 462,385 |
sbhola/Feedforward-Neural-Network | feedforwardneuralnetwork.py | FeedforwardNeuralNetwork.train | train | Train the Neural Network. | [
"Train",
"the",
"Neural",
"Network."
] | def train(self, training_data, epochs, learning_ratio, plot_cost=False, plot_accuracy=False, discretize_accuracy=False):
total_costs = []
accuracy = []
for i in range(epochs):
for (input_data, output_data) in zip(training_data[0], training_data[1]):
self.feedforward(input_data)
... | ['def', 'train(self,', 'training_data,', 'epochs,', 'learning_ratio,', 'plot_cost=False,', 'plot_accuracy=False,', 'discretize_accuracy=False):', 'total_costs', '=', '[]', 'accuracy', '=', '[]', 'for', 'i', 'in', 'range(epochs):', 'for', '(input_data,', 'output_data)', 'in', 'zip(training_data[0],', 'training_data[1]):... | 582,200 |
fcjian/TOOD | yolact_head.py | YOLACTProtonet.get_targets | get_targets | Compute instance segmentation targets for each image. | [
"Compute",
"instance",
"segmentation",
"targets",
"for",
"each",
"image."
] | def get_targets(self, mask_pred, gt_masks, pos_assigned_gt_inds):
if gt_masks.size(0) == 0:
return None
(mask_h, mask_w) = mask_pred.shape[-2:]
gt_masks = F.interpolate(gt_masks.unsqueeze(0), (mask_h, mask_w), mode='bilinear', align_corners=False).squeeze(0)
gt_masks = gt_masks.gt(0.5).float()
... | ['def', 'get_targets(self,', 'mask_pred,', 'gt_masks,', 'pos_assigned_gt_inds):', 'if', 'gt_masks.size(0)', '==', '0:', 'return', 'None', '(mask_h,', 'mask_w)', '=', 'mask_pred.shape[-2:]', 'gt_masks', '=', 'F.interpolate(gt_masks.unsqueeze(0),', '(mask_h,', 'mask_w),', "mode='bilinear',", 'align_corners=False).squeeze... | 902,123 |
QData/deepWordBug | __init__.py | RTs.setup | setup | Call this before using the refactoring tools to create them on demand if needed. | [
"Call",
"this",
"before",
"using",
"the",
"refactoring",
"tools",
"to",
"create",
"them",
"on",
"demand",
"if",
"needed."
] | def setup():
if None in [RTs._rt, RTs._rtp]:
RTs._rt = RefactoringTool(myfixes)
RTs._rtp = RefactoringTool(myfixes, {'print_function': True}) | ['def', 'setup():', 'if', 'None', 'in', '[RTs._rt,', 'RTs._rtp]:', 'RTs._rt', '=', 'RefactoringTool(myfixes)', 'RTs._rtp', '=', 'RefactoringTool(myfixes,', "{'print_function':", 'True})'] | 543,690 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | datasets.py | create_pianoroll_dataset | create_pianoroll_dataset | Creates a pianoroll dataset. | [
"Creates",
"a",
"pianoroll",
"dataset."
] | def create_pianoroll_dataset(path, split, batch_size, num_parallel_calls=DEFAULT_PARALLELISM, shuffle=False, repeat=False, min_note=21, max_note=108):
num_notes = max_note - min_note + 1
with tf.gfile.Open(path, 'r') as f:
raw_data = pickle.load(f)
pianorolls = raw_data[split]
mean = raw_data['t... | ['def', 'create_pianoroll_dataset(path,', 'split,', 'batch_size,', 'num_parallel_calls=DEFAULT_PARALLELISM,', 'shuffle=False,', 'repeat=False,', 'min_note=21,', 'max_note=108):', 'num_notes', '=', 'max_note', '-', 'min_note', '+', '1', 'with', 'tf.gfile.Open(path,', "'r')", 'as', 'f:', 'raw_data', '=', 'pickle.load(f)'... | 48,447 |
chribsen/simple-machine-learning-examples | plm.py | MovingPanelOLS.y_predict | y_predict | Returns the predicted y values. | [
"Returns",
"the",
"predicted",
"y",
"values."
] | def y_predict(self):
return self._unstack_y(self._y_predict_raw) | ['def', 'y_predict(self):', 'return', 'self._unstack_y(self._y_predict_raw)'] | 936,597 |
iver56/audiomentations | mp3_compression.py | Mp3Compression.maybe_pre_gain | maybe_pre_gain | If the audio is too loud, gain it down to avoid distortion in the audio file to be encoded. | [
"If",
"the",
"audio",
"is",
"too",
"loud,",
"gain",
"it",
"down",
"to",
"avoid",
"distortion",
"in",
"the",
"audio",
"file",
"to",
"be",
"encoded."
] | def maybe_pre_gain(self, samples):
greatest_abs_sample = np.amax(np.abs(samples))
if greatest_abs_sample > 1.0:
self.post_gain_factor = greatest_abs_sample
samples = samples * (1.0 / greatest_abs_sample)
else:
self.post_gain_factor = None
return samples | ['def', 'maybe_pre_gain(self,', 'samples):', 'greatest_abs_sample', '=', 'np.amax(np.abs(samples))', 'if', 'greatest_abs_sample', '>', '1.0:', 'self.post_gain_factor', '=', 'greatest_abs_sample', 'samples', '=', 'samples', '*', '(1.0', '/', 'greatest_abs_sample)', 'else:', 'self.post_gain_factor', '=', 'None', 'return'... | 403,259 |
gugarosa/nalp | seqgan.py | SeqGAN.T | T | Temperature value to sample the token. | [
"Temperature",
"value",
"to",
"sample",
"the",
"token."
] | def T(self) -> float:
return self._T | ['def', 'T(self)', '->', 'float:', 'return', 'self._T'] | 651,734 |
Xianpeng919/MonoCon | inference.py | init_model | init_model | Initialize a model from config file, which could be a 3D detector or a 3D segmentor. | [
"Initialize",
"a",
"model",
"from",
"config",
"file,",
"which",
"could",
"be",
"a",
"3D",
"detector",
"or",
"a",
"3D",
"segmentor."
] | def init_model(config, checkpoint=None, device='cuda:0'):
if isinstance(config, str):
config = mmcv.Config.fromfile(config)
elif not isinstance(config, mmcv.Config):
raise TypeError(f'config must be a filename or Config object, but got {type(config)}')
config.model.pretrained = None
conv... | ['def', 'init_model(config,', 'checkpoint=None,', "device='cuda:0'):", 'if', 'isinstance(config,', 'str):', 'config', '=', 'mmcv.Config.fromfile(config)', 'elif', 'not', 'isinstance(config,', 'mmcv.Config):', 'raise', "TypeError(f'config", 'must', 'be', 'a', 'filename', 'or', 'Config', 'object,', 'but', 'got', "{type(c... | 654,204 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_logging.py | MemoryTest.setUp | setUp | Create a dict to remember potentially destroyed objects. | [
"Create",
"a",
"dict",
"to",
"remember",
"potentially",
"destroyed",
"objects."
] | def setUp(self):
BaseTest.setUp(self)
self._survivors = {} | ['def', 'setUp(self):', 'BaseTest.setUp(self)', 'self._survivors', '=', '{}'] | 376,223 |
43Carrig/recurrent_neural_networks_practice | gen_model_ops.py | create_tree_variable | create_tree_variable | Creates a tree model and returns a handle to it. | [
"Creates",
"a",
"tree",
"model",
"and",
"returns",
"a",
"handle",
"to",
"it."
] | def create_tree_variable(tree_handle, tree_config, params, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
params = _execute.make_str(params, 'params')
(_, _, _op) = _op_def_lib._apply_op_helper('CreateTreeVariable', tree_handle=tree_handle, tree_config=... | ['def', 'create_tree_variable(tree_handle,', 'tree_config,', 'params,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'params', '=', '_execute.make_str(params,', "'params')", '(_,', '_,', '_op)', '=', "_op_def_lib._apply_op_helper('CreateTreeV... | 335,335 |
eddylau328/fyp-artificial-intelligence-ac-control-device | _sseclient.py | SSEClient.close | close | Closes the SSEClient instance. | [
"Closes",
"the",
"SSEClient",
"instance."
] | def close(self):
self.should_connect = False
self.retry = 0
self.resp.close() | ['def', 'close(self):', 'self.should_connect', '=', 'False', 'self.retry', '=', '0', 'self.resp.close()'] | 214,362 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | validators.py | RefResolver.resolve_from_url | resolve_from_url | Resolve the given remote URL. | [
"Resolve",
"the",
"given",
"remote",
"URL."
] | def resolve_from_url(self, url):
(url, fragment) = urldefrag(url)
try:
document = self.store[url]
except KeyError:
try:
document = self.resolve_remote(url)
except Exception as exc:
raise exceptions.RefResolutionError(exc)
return self.resolve_fragment(docum... | ['def', 'resolve_from_url(self,', 'url):', '(url,', 'fragment)', '=', 'urldefrag(url)', 'try:', 'document', '=', 'self.store[url]', 'except', 'KeyError:', 'try:', 'document', '=', 'self.resolve_remote(url)', 'except', 'Exception', 'as', 'exc:', 'raise', 'exceptions.RefResolutionError(exc)', 'return', 'self.resolve_frag... | 449,725 |
researchmm/WSOD2 | reppoints_head.py | RepPointsHead.forward_single | forward_single | Forward feature map of a single FPN level. | [
"Forward",
"feature",
"map",
"of",
"a",
"single",
"FPN",
"level."
] | def forward_single(self, x):
dcn_base_offset = self.dcn_base_offset.type_as(x)
if self.use_grid_points or not self.center_init:
scale = self.point_base_scale / 2
points_init = dcn_base_offset / dcn_base_offset.max() * scale
bbox_init = x.new_tensor([-scale, -scale, scale, scale]).view(1,... | ['def', 'forward_single(self,', 'x):', 'dcn_base_offset', '=', 'self.dcn_base_offset.type_as(x)', 'if', 'self.use_grid_points', 'or', 'not', 'self.center_init:', 'scale', '=', 'self.point_base_scale', '/', '2', 'points_init', '=', 'dcn_base_offset', '/', 'dcn_base_offset.max()', '*', 'scale', 'bbox_init', '=', 'x.new_t... | 374,237 |
hitchtest/hitch | testing.py | CliRunner.isolated_filesystem | isolated_filesystem | A context manager that creates a temporary folder and changes the current working directory to it for isolated filesystem tests. | [
"A",
"context",
"manager",
"that",
"creates",
"a",
"temporary",
"folder",
"and",
"changes",
"the",
"current",
"working",
"directory",
"to",
"it",
"for",
"isolated",
"filesystem",
"tests."
] | def isolated_filesystem(self):
cwd = os.getcwd()
t = tempfile.mkdtemp()
os.chdir(t)
try:
yield t
finally:
os.chdir(cwd)
try:
shutil.rmtree(t)
except (OSError, IOError):
pass | ['def', 'isolated_filesystem(self):', 'cwd', '=', 'os.getcwd()', 't', '=', 'tempfile.mkdtemp()', 'os.chdir(t)', 'try:', 'yield', 't', 'finally:', 'os.chdir(cwd)', 'try:', 'shutil.rmtree(t)', 'except', '(OSError,', 'IOError):', 'pass'] | 206,638 |
sek788432/Waymo-2D-Object-Detection | standard_runner.py | StandardTrainer.train_dataset | train_dataset | The current training dataset. | [
"The",
"current",
"training",
"dataset."
] | def train_dataset(self):
return self._train_dataset | ['def', 'train_dataset(self):', 'return', 'self._train_dataset'] | 973,834 |
devashish-patel/webcam-motion-detector | code_runner.py | CodeRunner.source | source | The configured source code that will be executed when ``run`` is called. | [
"The",
"configured",
"source",
"code",
"that",
"will",
"be",
"executed",
"when",
"``run``",
"is",
"called."
] | def source(self):
return self._source | ['def', 'source(self):', 'return', 'self._source'] | 977,126 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | visitor.py | Class.acceptFunctionMethodDecl | acceptFunctionMethodDecl | Accept and process a typed method declaration. | [
"Accept",
"and",
"process",
"a",
"typed",
"method",
"declaration."
] | def acceptFunctionMethodDecl(self, node, memo):
ident = node.firstChildOfType(tokens.IDENT)
type = node.firstChildOfType(tokens.TYPE).children[0].text
mods = node.firstChildOfType(tokens.MODIFIER_LIST)
self.variables.append(ident.text)
return self.factory.method(name=ident.text, type=type, parent=se... | ['def', 'acceptFunctionMethodDecl(self,', 'node,', 'memo):', 'ident', '=', 'node.firstChildOfType(tokens.IDENT)', 'type', '=', 'node.firstChildOfType(tokens.TYPE).children[0].text', 'mods', '=', 'node.firstChildOfType(tokens.MODIFIER_LIST)', 'self.variables.append(ident.text)', 'return', 'self.factory.method(name=ident... | 11,253 |
instadeepai/jumanji | random.py | make_random_policy_cleaner | make_random_policy_cleaner | Make random policy for Cleaner. | [
"Make",
"random",
"policy",
"for",
"Cleaner."
] | def make_random_policy_cleaner() -> RandomPolicy:
return masked_categorical_random | ['def', 'make_random_policy_cleaner()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random'] | 594,607 |
jimtin/Stock_Comparison | pretty.py | for_type_by_name | for_type_by_name | Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. | [
"Add",
"a",
"pretty",
"printer",
"for",
"a",
"type",
"specified",
"by",
"the",
"module",
"and",
"name",
"of",
"a",
"type",
"rather",
"than",
"the",
"type",
"object",
"itself."
] | def for_type_by_name(type_module, type_name, func):
key = (type_module, type_name)
oldfunc = _deferred_type_pprinters.get(key, None)
if func is not None:
_deferred_type_pprinters[key] = func
return oldfunc | ['def', 'for_type_by_name(type_module,', 'type_name,', 'func):', 'key', '=', '(type_module,', 'type_name)', 'oldfunc', '=', '_deferred_type_pprinters.get(key,', 'None)', 'if', 'func', 'is', 'not', 'None:', '_deferred_type_pprinters[key]', '=', 'func', 'return', 'oldfunc'] | 385,273 |
tensorflow/agents | multi_objective_scalarizer.py | HyperVolumeScalarizer.set_parameters | set_parameters | Set the scalarization parameters for the HyperVolumeScalarizer. | [
"Set",
"the",
"scalarization",
"parameters",
"for",
"the",
"HyperVolumeScalarizer."
] | def set_parameters(self, direction: tf.Tensor, transform_params: Dict[str, tf.Tensor]):
self._validate_scalarization_parameters({self.DIRECTION_KEY: direction})
self._direction = direction
for (key, param) in transform_params.items():
if key == self.SLOPE_KEY:
self._validate_scalarizatio... | ['def', 'set_parameters(self,', 'direction:', 'tf.Tensor,', 'transform_params:', 'Dict[str,', 'tf.Tensor]):', 'self._validate_scalarization_parameters({self.DIRECTION_KEY:', 'direction})', 'self._direction', '=', 'direction', 'for', '(key,', 'param)', 'in', 'transform_params.items():', 'if', 'key', '==', 'self.SLOPE_KE... | 22,603 |
autonlab/weasel | optimization.py | get_scheduler | get_scheduler | This utility function is only needed if you do *not* use Hydra. | [
"This",
"utility",
"function",
"is",
"only",
"needed",
"if",
"you",
"do",
"*not*",
"use",
"Hydra."
] | def get_scheduler(optimizer, name, *args, **kwargs):
name = stem_word(name)
if name is None or name in ['no', 'none']:
return None
elif name in ['lron', 'reducelron', 'lronplateau', 'reducelronplateau']:
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, *args, **kwargs)
elif na... | ['def', 'get_scheduler(optimizer,', 'name,', '*args,', '**kwargs):', 'name', '=', 'stem_word(name)', 'if', 'name', 'is', 'None', 'or', 'name', 'in', "['no',", "'none']:", 'return', 'None', 'elif', 'name', 'in', "['lron',", "'reducelron',", "'lronplateau',", "'reducelronplateau']:", 'scheduler', '=', 'optim.lr_scheduler... | 373,377 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | conftest.py | groupby_func | groupby_func | yields both aggregation and transformation functions. | [
"yields",
"both",
"aggregation",
"and",
"transformation",
"functions."
] | def groupby_func(request):
return request.param | ['def', 'groupby_func(request):', 'return', 'request.param'] | 83,438 |
nicknochnack/RealTimeSignLanguageTFJS | decoder.py | TransformerDecoder.build | build | Implements build() for the layer. | [
"Implements",
"build()",
"for",
"the",
"layer."
] | def build(self, unused_input_shapes):
self.layers = []
for i in range(self.num_hidden_layers):
self.layers.append(layers.TransformerDecoderBlock(num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, intermediate_activation=self.intermediate_activation, dropout_rate=self... | ['def', 'build(self,', 'unused_input_shapes):', 'self.layers', '=', '[]', 'for', 'i', 'in', 'range(self.num_hidden_layers):', 'self.layers.append(layers.TransformerDecoderBlock(num_attention_heads=self.num_attention_heads,', 'intermediate_size=self.intermediate_size,', 'intermediate_activation=self.intermediate_activat... | 850,482 |
OPEN-AIR-SUN/Viewpoint-Bottleneck | __init__.py | get_models | get_models | Returns a tuple of sample models. | [
"Returns",
"a",
"tuple",
"of",
"sample",
"models."
] | def get_models():
return MODELS | ['def', 'get_models():', 'return', 'MODELS'] | 380,135 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | neural_gpu_trainer.py | m_step | m_step | Evaluation multi-step for program synthesis. | [
"Evaluation",
"multi-step",
"for",
"program",
"synthesis."
] | def m_step(model, beam_model, sess, batch_size, inp, target, bucket, nsteps, p):
(state, scores, hist) = (None, [[-11.0 for _ in xrange(batch_size)]], [])
for _ in xrange(nsteps):
(new_target, new_first, new_inp, new_scores) = get_best_beam(beam_model, sess, inp, target, batch_size, FLAGS.beam_size, buc... | ['def', 'm_step(model,', 'beam_model,', 'sess,', 'batch_size,', 'inp,', 'target,', 'bucket,', 'nsteps,', 'p):', '(state,', 'scores,', 'hist)', '=', '(None,', '[[-11.0', 'for', '_', 'in', 'xrange(batch_size)]],', '[])', 'for', '_', 'in', 'xrange(nsteps):', '(new_target,', 'new_first,', 'new_inp,', 'new_scores)', '=', 'g... | 56,450 |
cuiziteng/ICCV_MAET | mask_point_head.py | MaskPointHead.get_targets | get_targets | Get training targets of MaskPointHead for all images. | [
"Get",
"training",
"targets",
"of",
"MaskPointHead",
"for",
"all",
"images."
] | def get_targets(self, rois, rel_roi_points, sampling_results, gt_masks, cfg):
num_imgs = len(sampling_results)
rois_list = []
rel_roi_points_list = []
for batch_ind in range(num_imgs):
inds = rois[:, 0] == batch_ind
rois_list.append(rois[inds])
rel_roi_points_list.append(rel_roi_... | ['def', 'get_targets(self,', 'rois,', 'rel_roi_points,', 'sampling_results,', 'gt_masks,', 'cfg):', 'num_imgs', '=', 'len(sampling_results)', 'rois_list', '=', '[]', 'rel_roi_points_list', '=', '[]', 'for', 'batch_ind', 'in', 'range(num_imgs):', 'inds', '=', 'rois[:,', '0]', '==', 'batch_ind', 'rois_list.append(rois[in... | 228,809 |
eddylau328/fyp-artificial-intelligence-ac-control-device | install.py | create_env_error_message | create_env_error_message | Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. | [
"Format",
"an",
"error",
"message",
"for",
"an",
"EnvironmentError",
"It",
"may",
"occur",
"anytime",
"during",
"the",
"execution",
"of",
"the",
"install",
"command."
] | def create_env_error_message(error, show_traceback, using_user_site):
parts = []
parts.append('Could not install packages due to an EnvironmentError')
if not show_traceback:
parts.append(': ')
parts.append(str(error))
else:
parts.append('.')
parts[-1] += '\n'
if error.err... | ['def', 'create_env_error_message(error,', 'show_traceback,', 'using_user_site):', 'parts', '=', '[]', "parts.append('Could", 'not', 'install', 'packages', 'due', 'to', 'an', "EnvironmentError')", 'if', 'not', 'show_traceback:', "parts.append(':", "')", 'parts.append(str(error))', 'else:', "parts.append('.')", 'parts[-... | 215,846 |
SergiosKar/Deep-Learning-models | run_pretraining.py | mlm_loss_fn | mlm_loss_fn | label_weights is either 1 or 0, 0 meaning masked. | [
"label_weights",
"is",
"either",
"1",
"or",
"0,",
"0",
"meaning",
"masked."
] | def mlm_loss_fn(prediction_logits: '[batch, max_seq_len (512), vocab_size]', label_positions: '[batch, num_masks (20)]', label_ids: '[batch, num_masks (20)]', label_weights: '[batch, num_masks (20)]'):
logits_at_positions = gather_indexes(prediction_logits, label_positions)
preds_at_positions = tf.math.argmax(l... | ['def', 'mlm_loss_fn(prediction_logits:', "'[batch,", 'max_seq_len', '(512),', "vocab_size]',", 'label_positions:', "'[batch,", 'num_masks', "(20)]',", 'label_ids:', "'[batch,", 'num_masks', "(20)]',", 'label_weights:', "'[batch,", 'num_masks', "(20)]'):", 'logits_at_positions', '=', 'gather_indexes(prediction_logits,'... | 518,802 |
intra2net/guibot | guibot_simple.py | initialize | initialize | Initialize the simple API. | [
"Initialize",
"the",
"simple",
"API."
] | def initialize():
global guibot
guibot = GuiBot()
global last_match
last_match = guibot.last_match
global buttons
buttons.mouse = guibot.dc_backend.mousemap
buttons.key = guibot.dc_backend.keymap
buttons.mod = guibot.dc_backend.modmap | ['def', 'initialize():', 'global', 'guibot', 'guibot', '=', 'GuiBot()', 'global', 'last_match', 'last_match', '=', 'guibot.last_match', 'global', 'buttons', 'buttons.mouse', '=', 'guibot.dc_backend.mousemap', 'buttons.key', '=', 'guibot.dc_backend.keymap', 'buttons.mod', '=', 'guibot.dc_backend.modmap'] | 572,472 |
clips/pattern | __init__.py | verify_password | verify_password | Returns True if the given strings are identical, after hashing the first. | [
"Returns",
"True",
"if",
"the",
"given",
"strings",
"are",
"identical,",
"after",
"hashing",
"the",
"first."
] | def verify_password(s1, s2):
if isinstance(s1, str):
s1 = s1.encode('utf-8')
if isinstance(s2, str):
s2 = s2.encode('utf-8')
(m, f, n, x, s2) = s2.split(':')
return streql(pbkdf2(s1[:1024], x, int(n), len(s2) / 2, f), s2) | ['def', 'verify_password(s1,', 's2):', 'if', 'isinstance(s1,', 'str):', 's1', '=', "s1.encode('utf-8')", 'if', 'isinstance(s2,', 'str):', 's2', '=', "s2.encode('utf-8')", '(m,', 'f,', 'n,', 'x,', 's2)', '=', "s2.split(':')", 'return', 'streql(pbkdf2(s1[:1024],', 'x,', 'int(n),', 'len(s2)', '/', '2,', 'f),', 's2)'] | 764,692 |
jeromewang-github/computer_vision | mobilenet_v2.py | _LayersOverride.ZeroPadding2D | ZeroPadding2D | Replaces explicit padding in the Keras application with a no-op. | [
"Replaces",
"explicit",
"padding",
"in",
"the",
"Keras",
"application",
"with",
"a",
"no-op."
] | def ZeroPadding2D(self, **kwargs):
return lambda x: x | ['def', 'ZeroPadding2D(self,', '**kwargs):', 'return', 'lambda', 'x:', 'x'] | 511,917 |
aeon-toolkit/aeon | test_time_since.py | test_fit_transform_int_idx_output | test_fit_transform_int_idx_output | Tests that we get the expected outputs. | [
"Tests",
"that",
"we",
"get",
"the",
"expected",
"outputs."
] | def test_fit_transform_int_idx_output(df_int_idx):
transformer = TimeSince(start=None, to_numeric=True, keep_original_columns=False, positive_only=False)
Xt = transformer.fit_transform(df_int_idx)
expected = pd.DataFrame(data={'time_since_1': [0, 1, 2, 4, 8]}, index=df_int_idx.index)
assert_frame_equal(... | ['def', 'test_fit_transform_int_idx_output(df_int_idx):', 'transformer', '=', 'TimeSince(start=None,', 'to_numeric=True,', 'keep_original_columns=False,', 'positive_only=False)', 'Xt', '=', 'transformer.fit_transform(df_int_idx)', 'expected', '=', "pd.DataFrame(data={'time_since_1':", '[0,', '1,', '2,', '4,', '8]},', '... | 400,079 |
lxtGH/CAE | checkpoint.py | load_checkpoint | load_checkpoint | Load checkpoint from a file or URI. | [
"Load",
"checkpoint",
"from",
"a",
"file",
"or",
"URI."
] | def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None):
checkpoint = _load_checkpoint(filename, map_location)
if not isinstance(checkpoint, dict):
raise RuntimeError(f'No state_dict found in checkpoint file {filename}')
if 'state_dict' in checkpoint:
state_dict =... | ['def', 'load_checkpoint(model,', 'filename,', "map_location='cpu',", 'strict=False,', 'logger=None):', 'checkpoint', '=', '_load_checkpoint(filename,', 'map_location)', 'if', 'not', 'isinstance(checkpoint,', 'dict):', 'raise', "RuntimeError(f'No", 'state_dict', 'found', 'in', 'checkpoint', 'file', "{filename}')", 'if'... | 108,706 |
myothida/Supervised-Machine-Learning | ccompiler_opt.py | _CCompiler.cc_test_flags | cc_test_flags | Returns True if the compiler supports 'flags'. | [
"Returns",
"True",
"if",
"the",
"compiler",
"supports",
"'flags'."
] | def cc_test_flags(self, flags):
assert isinstance(flags, list)
self.dist_log('testing flags', flags)
test_path = os.path.join(self.conf_check_path, 'test_flags.c')
test = self.dist_test(test_path, flags)
if not test:
self.dist_log('testing failed', stderr=True)
return test | ['def', 'cc_test_flags(self,', 'flags):', 'assert', 'isinstance(flags,', 'list)', "self.dist_log('testing", "flags',", 'flags)', 'test_path', '=', 'os.path.join(self.conf_check_path,', "'test_flags.c')", 'test', '=', 'self.dist_test(test_path,', 'flags)', 'if', 'not', 'test:', "self.dist_log('testing", "failed',", 'std... | 441,541 |
YanZiQinKevin/object_detection | test_retinanet.py | im_detect_bbox | im_detect_bbox | Generate RetinaNet detections on a single image. | [
"Generate",
"RetinaNet",
"detections",
"on",
"a",
"single",
"image."
] | def im_detect_bbox(model, im, timers=None):
if timers is None:
timers = defaultdict(Timer)
anchors = _create_cell_anchors()
timers['im_detect_bbox'].tic()
(k_max, k_min) = (cfg.FPN.RPN_MAX_LEVEL, cfg.FPN.RPN_MIN_LEVEL)
A = cfg.RETINANET.SCALES_PER_OCTAVE * len(cfg.RETINANET.ASPECT_RATIOS)
... | ['def', 'im_detect_bbox(model,', 'im,', 'timers=None):', 'if', 'timers', 'is', 'None:', 'timers', '=', 'defaultdict(Timer)', 'anchors', '=', '_create_cell_anchors()', "timers['im_detect_bbox'].tic()", '(k_max,', 'k_min)', '=', '(cfg.FPN.RPN_MAX_LEVEL,', 'cfg.FPN.RPN_MIN_LEVEL)', 'A', '=', 'cfg.RETINANET.SCALES_PER_OCTA... | 772,405 |
enuguru/artificial_intelligence_and_machine_learning | test_resources.py | RequirementsTests.testSetuptoolsProjectName | testSetuptoolsProjectName | The setuptools project should implement the setuptools package. | [
"The",
"setuptools",
"project",
"should",
"implement",
"the",
"setuptools",
"package."
] | def testSetuptoolsProjectName(self):
self.assertEqual(Requirement.parse('setuptools').project_name, 'setuptools')
self.assertEqual(Requirement.parse('setuptools == 0.7').project_name, 'setuptools')
self.assertEqual(Requirement.parse('setuptools == 0.7a1').project_name, 'setuptools')
self.assertEqual(Req... | ['def', 'testSetuptoolsProjectName(self):', "self.assertEqual(Requirement.parse('setuptools').project_name,", "'setuptools')", "self.assertEqual(Requirement.parse('setuptools", '==', "0.7').project_name,", "'setuptools')", "self.assertEqual(Requirement.parse('setuptools", '==', "0.7a1').project_name,", "'setuptools')",... | 135,202 |
rlworkgroup/garage | bc_point.py | OptimalPolicy.get_actions | get_actions | Get actions given observations. | [
"Get",
"actions",
"given",
"observations."
] | def get_actions(self, observations):
return (self.goal[np.newaxis, :].repeat(len(observations), axis=0) - observations[:, :2], {}) | ['def', 'get_actions(self,', 'observations):', 'return', '(self.goal[np.newaxis,', ':].repeat(len(observations),', 'axis=0)', '-', 'observations[:,', ':2],', '{})'] | 200,305 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.acceptThis | acceptThis | Accept and process a 'this' expression. | [
"Accept",
"and",
"process",
"a",
"'this'",
"expression."
] | def acceptThis(self, node, memo):
self.pushRight('self') | ['def', 'acceptThis(self,', 'node,', 'memo):', "self.pushRight('self')"] | 17,183 |
abrarrhine/Artificial-Intelligence-PacmanGames | models.py | PerceptronModel.train | train | Train the perceptron until convergence. | [
"Train",
"the",
"perceptron",
"until",
"convergence."
] | def train(self, dataset):
incorrectNum = 1
while incorrectNum != 0:
incorrectNum = 0
for (x, y) in dataset.iterate_once(1):
if self.get_prediction(x) != nn.as_scalar(y):
incorrectNum += 1
self.w.update(x, nn.as_scalar(y)) | ['def', 'train(self,', 'dataset):', 'incorrectNum', '=', '1', 'while', 'incorrectNum', '!=', '0:', 'incorrectNum', '=', '0', 'for', '(x,', 'y)', 'in', 'dataset.iterate_once(1):', 'if', 'self.get_prediction(x)', '!=', 'nn.as_scalar(y):', 'incorrectNum', '+=', '1', 'self.w.update(x,', 'nn.as_scalar(y))'] | 90,818 |
matsu0228/nlp-jp | test_largefilemanager.py | TestLargeFileManager.make_dir | make_dir | make a subdirectory at api_path override in subclasses if contents are not on the filesystem. | [
"make",
"a",
"subdirectory",
"at",
"api_path",
"override",
"in",
"subclasses",
"if",
"contents",
"are",
"not",
"on",
"the",
"filesystem."
] | def make_dir(self, api_path):
_make_dir(self.contents_manager, api_path) | ['def', 'make_dir(self,', 'api_path):', '_make_dir(self.contents_manager,', 'api_path)'] | 790,705 |
shiwt03/SSformer | cgnet.py | CGNet.train | train | Convert the model into training mode will keeping the normalization layer freezed. | [
"Convert",
"the",
"model",
"into",
"training",
"mode",
"will",
"keeping",
"the",
"normalization",
"layer",
"freezed."
] | def train(self, mode=True):
super(CGNet, 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(CGNet,', 'self).train(mode)', 'if', 'mode', 'and', 'self.norm_eval:', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', '_BatchNorm):', 'm.eval()'] | 871,928 |
AlperHuseyn/artificial-intelligence-and-machine-learning-with-python | gallonomics.py | plot_epoch_mae_graph | plot_epoch_mae_graph | Plot the training and validation Mean Absolute Error (MAE) as a function of epochs. | [
"Plot",
"the",
"training",
"and",
"validation",
"Mean",
"Absolute",
"Error",
"(MAE)",
"as",
"a",
"function",
"of",
"epochs."
] | def plot_epoch_mae_graph(hist, title='Epoch-MAE Graph'):
x = hist.epoch
y = hist.history['mae']
z = hist.history['val_mae']
(fig, ax) = plt.subplots(figsize=(15, 5))
ax.plot(x, y, linewidth=2, color='blue', label='tarining mae')
ax.plot(x, z, linewidth=2, color='orange', label='validation mae')
... | ['def', 'plot_epoch_mae_graph(hist,', "title='Epoch-MAE", "Graph'):", 'x', '=', 'hist.epoch', 'y', '=', "hist.history['mae']", 'z', '=', "hist.history['val_mae']", '(fig,', 'ax)', '=', 'plt.subplots(figsize=(15,', '5))', 'ax.plot(x,', 'y,', 'linewidth=2,', "color='blue',", "label='tarining", "mae')", 'ax.plot(x,', 'z,'... | 36,124 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | experiment.py | default_hparams | default_hparams | Builds an HParam object with default hyperparameters. | [
"Builds",
"an",
"HParam",
"object",
"with",
"default",
"hyperparameters."
] | def default_hparams():
return tf.contrib.training.HParams(decay_rate=0.96, decay_steps=2000, leaky=False, learning_rate=0.001, loss_type='margin', num_prime_capsules=32, padding='VALID', remake=True, routing=3, verbose=False) | ['def', 'default_hparams():', 'return', 'tf.contrib.training.HParams(decay_rate=0.96,', 'decay_steps=2000,', 'leaky=False,', 'learning_rate=0.001,', "loss_type='margin',", 'num_prime_capsules=32,', "padding='VALID',", 'remake=True,', 'routing=3,', 'verbose=False)'] | 53,090 |
Westlake-AI/openmixup | precise_bn_hook.py | update_bn_stats | update_bn_stats | Computes precise BN stats on training data. | [
"Computes",
"precise",
"BN",
"stats",
"on",
"training",
"data."
] | def update_bn_stats(model: nn.Module, loader: DataLoader, num_samples: int=8192, update_all_stats: bool=False, logger: Optional[logging.Logger]=None) -> None:
(rank, world_size) = get_dist_info()
num_iter = num_samples // (loader.batch_size * world_size)
num_iter = min(num_iter, len(loader))
bn_layers =... | ['def', 'update_bn_stats(model:', 'nn.Module,', 'loader:', 'DataLoader,', 'num_samples:', 'int=8192,', 'update_all_stats:', 'bool=False,', 'logger:', 'Optional[logging.Logger]=None)', '->', 'None:', '(rank,', 'world_size)', '=', 'get_dist_info()', 'num_iter', '=', 'num_samples', '//', '(loader.batch_size', '*', 'world_... | 252,313 |
renmengye/few-shot-ssl-public | prototypical.py | prototypical_clustering_gmm_layer | prototypical_clustering_gmm_layer | Computes the prototypes, cluster centers, with additional clustering on the validation data. | [
"Computes",
"the",
"prototypes,",
"cluster",
"centers,",
"with",
"additional",
"clustering",
"on",
"the",
"validation",
"data."
] | def prototypical_clustering_gmm_layer(nclasses, x_train, y_train, x_test, phi, num_cluster_steps, lambd=0.1, alpha=0.0):
protos = [None] * nclasses
covar = [None] * nclasses
x_all = concat([x_train, x_test], 0)
(h, _) = phi(x_all, reuse=None, is_training=True)
num_x_train = tf.shape(x_train)[0]
... | ['def', 'prototypical_clustering_gmm_layer(nclasses,', 'x_train,', 'y_train,', 'x_test,', 'phi,', 'num_cluster_steps,', 'lambd=0.1,', 'alpha=0.0):', 'protos', '=', '[None]', '*', 'nclasses', 'covar', '=', '[None]', '*', 'nclasses', 'x_all', '=', 'concat([x_train,', 'x_test],', '0)', '(h,', '_)', '=', 'phi(x_all,', 'reu... | 179,999 |
prof-fabriciogmc/artificial_intelligence | url.py | Url.request_uri | request_uri | Absolute path including the query string. | [
"Absolute",
"path",
"including",
"the",
"query",
"string."
] | def request_uri(self):
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri | ['def', 'request_uri(self):', 'uri', '=', 'self.path', 'or', "'/'", 'if', 'self.query', 'is', 'not', 'None:', 'uri', '+=', "'?'", '+', 'self.query', 'return', 'uri'] | 146,559 |
zzndream/ShipRSImageNet | mask_target.py | mask_target_single | mask_target_single | Compute mask target for each positive proposal in the image. | [
"Compute",
"mask",
"target",
"for",
"each",
"positive",
"proposal",
"in",
"the",
"image."
] | def mask_target_single(pos_proposals, pos_assigned_gt_inds, gt_masks, cfg):
device = pos_proposals.device
mask_size = _pair(cfg.mask_size)
num_pos = pos_proposals.size(0)
if num_pos > 0:
proposals_np = pos_proposals.cpu().numpy()
(maxh, maxw) = (gt_masks.height, gt_masks.width)
p... | ['def', 'mask_target_single(pos_proposals,', 'pos_assigned_gt_inds,', 'gt_masks,', 'cfg):', 'device', '=', 'pos_proposals.device', 'mask_size', '=', '_pair(cfg.mask_size)', 'num_pos', '=', 'pos_proposals.size(0)', 'if', 'num_pos', '>', '0:', 'proposals_np', '=', 'pos_proposals.cpu().numpy()', '(maxh,', 'maxw)', '=', '(... | 901,191 |
triaquae/triaquae | envelope.py | Envelope.max_y | max_y | Returns the value of the maximum Y coordinate. | [
"Returns",
"the",
"value",
"of",
"the",
"maximum",
"Y",
"coordinate."
] | def max_y(self):
return self._envelope.MaxY | ['def', 'max_y(self):', 'return', 'self._envelope.MaxY'] | 357,535 |
MACderRu/HyperDomainNet | model_irse.py | IR_152 | IR_152 | Constructs a ir-152 model. | [
"Constructs",
"a",
"ir-152",
"model."
] | def IR_152(input_size):
model = Backbone(input_size, num_layers=152, mode='ir', drop_ratio=0.4, affine=False)
return model | ['def', 'IR_152(input_size):', 'model', '=', 'Backbone(input_size,', 'num_layers=152,', "mode='ir',", 'drop_ratio=0.4,', 'affine=False)', 'return', 'model'] | 571,392 |
tobegit3hub/deep_image_model | ctc_loss_op_test.py | CTCLossTest.testBasic | testBasic | Test two batch entries. | [
"Test",
"two",
"batch",
"entries."
] | def testBasic(self):
depth = 6
targets_0 = [0, 1, 2, 1, 0]
loss_log_prob_0 = -3.34211
input_prob_matrix_0 = np.asarray([[0.633766, 0.221185, 0.0917319, 0.0129757, 0.0142857, 0.0260553], [0.111121, 0.588392, 0.278779, 0.0055756, 0.00569609, 0.010436], [0.0357786, 0.633813, 0.321418, 0.00249248, 0.0027288... | ['def', 'testBasic(self):', 'depth', '=', '6', 'targets_0', '=', '[0,', '1,', '2,', '1,', '0]', 'loss_log_prob_0', '=', '-3.34211', 'input_prob_matrix_0', '=', 'np.asarray([[0.633766,', '0.221185,', '0.0917319,', '0.0129757,', '0.0142857,', '0.0260553],', '[0.111121,', '0.588392,', '0.278779,', '0.0055756,', '0.0056960... | 182,695 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | gen_test.py | GenBasicTest.delay | delay | Returns arg after a number of IOLoop iterations. | [
"Returns",
"arg",
"after",
"a",
"number",
"of",
"IOLoop",
"iterations."
] | def delay(self, iterations, arg):
for i in range(iterations):
yield gen.moment
raise gen.Return(arg) | ['def', 'delay(self,', 'iterations,', 'arg):', 'for', 'i', 'in', 'range(iterations):', 'yield', 'gen.moment', 'raise', 'gen.Return(arg)'] | 437,796 |
scotthuang1989/object_detection_with_tensorflow | pixelda_eval.py | create_metrics | create_metrics | Create metrics for the model. | [
"Create",
"metrics",
"for",
"the",
"model."
] | def create_metrics(end_points, source_labels, target_labels, hparams):
batch_size = hparams.batch_size
(names_to_values, names_to_updates) = slim.metrics.aggregate_metric_map({'eval/Domain_Accuracy-Transferred': tf.contrib.metrics.streaming_accuracy(tf.to_int32(tf.round(tf.sigmoid(end_points['transferred_domain... | ['def', 'create_metrics(end_points,', 'source_labels,', 'target_labels,', 'hparams):', 'batch_size', '=', 'hparams.batch_size', '(names_to_values,', 'names_to_updates)', '=', "slim.metrics.aggregate_metric_map({'eval/Domain_Accuracy-Transferred':", "tf.contrib.metrics.streaming_accuracy(tf.to_int32(tf.round(tf.sigmoid(... | 797,044 |
furkansenharputlu/Natural-Language- | multipartiterank.py | MultipartiteRank.weight_adjustment | weight_adjustment | Adjust edge weights for boosting some candidates. | [
"Adjust",
"edge",
"weights",
"for",
"boosting",
"some",
"candidates."
] | def weight_adjustment(self, alpha=1.1):
weighted_edges = {}
norm = sum([s.length for s in self.sentences])
for variants in self.topics:
if len(variants) == 1:
continue
offsets = [self.candidates[v].offsets[0] for v in variants]
first = variants[offsets.index(min(offsets))... | ['def', 'weight_adjustment(self,', 'alpha=1.1):', 'weighted_edges', '=', '{}', 'norm', '=', 'sum([s.length', 'for', 's', 'in', 'self.sentences])', 'for', 'variants', 'in', 'self.topics:', 'if', 'len(variants)', '==', '1:', 'continue', 'offsets', '=', '[self.candidates[v].offsets[0]', 'for', 'v', 'in', 'variants]', 'fir... | 660,113 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MakeMixture | MakeMixture | Make a mixture distribution. | [
"Make",
"a",
"mixture",
"distribution."
] | def MakeMixture(metapmf, label='mix'):
mix = Pmf(label=label)
for (pmf, p1) in metapmf.Items():
for (x, p2) in pmf.Items():
mix.Incr(x, p1 * p2)
return mix | ['def', 'MakeMixture(metapmf,', "label='mix'):", 'mix', '=', 'Pmf(label=label)', 'for', '(pmf,', 'p1)', 'in', 'metapmf.Items():', 'for', '(x,', 'p2)', 'in', 'pmf.Items():', 'mix.Incr(x,', 'p1', '*', 'p2)', 'return', 'mix'] | 13,545 |
Farama-Foundation/Gymnasium | step_api_compatibility.py | StepAPICompatibility.step | step | Steps through the environment, returning 5 or 4 items depending on `output_truncation_bool`. | [
"Steps",
"through",
"the",
"environment,",
"returning",
"5",
"or",
"4",
"items",
"depending",
"on",
"`output_truncation_bool`."
] | def step(self, action):
step_returns = self.env.step(action)
return step_api_compatibility(step_returns, self.output_truncation_bool, self.is_vector_env) | ['def', 'step(self,', 'action):', 'step_returns', '=', 'self.env.step(action)', 'return', 'step_api_compatibility(step_returns,', 'self.output_truncation_bool,', 'self.is_vector_env)'] | 573,412 |
Ruturaj123/Flowchart-Detection | control_flow_ops.py | GradLoopState.forward_index | forward_index | The loop index of forward loop. | [
"The",
"loop",
"index",
"of",
"forward",
"loop."
] | def forward_index(self):
return self._forward_index | ['def', 'forward_index(self):', 'return', 'self._forward_index'] | 605,773 |
Mandeepsahoo/natural_language_processing | functions.py | SpanEvaluator.update | update | This function takes (num_infer_spans, num_label_spans, num_correct_spans) as input, to accumulate and update the corresponding status of the SpanEvaluator object. | [
"This",
"function",
"takes",
"(num_infer_spans,",
"num_label_spans,",
"num_correct_spans)",
"as",
"input,",
"to",
"accumulate",
"and",
"update",
"the",
"corresponding",
"status",
"of",
"the",
"SpanEvaluator",
"object."
] | def update(self, num_correct_spans, num_infer_spans, num_label_spans):
self.num_infer_spans += num_infer_spans
self.num_label_spans += num_label_spans
self.num_correct_spans += num_correct_spans | ['def', 'update(self,', 'num_correct_spans,', 'num_infer_spans,', 'num_label_spans):', 'self.num_infer_spans', '+=', 'num_infer_spans', 'self.num_label_spans', '+=', 'num_label_spans', 'self.num_correct_spans', '+=', 'num_correct_spans'] | 734,624 |
deepmind/dm_control | traversal_utils.py | get_frame_joints | get_frame_joints | Retrieves all joints belonging to the attachment frame of an MJCF model. | [
"Retrieves",
"all",
"joints",
"belonging",
"to",
"the",
"attachment",
"frame",
"of",
"an",
"MJCF",
"model."
] | def get_frame_joints(mjcf_model):
frame = get_attachment_frame(mjcf_model)
if frame:
return frame.find_all('joint', immediate_children_only=True)
else:
return None | ['def', 'get_frame_joints(mjcf_model):', 'frame', '=', 'get_attachment_frame(mjcf_model)', 'if', 'frame:', 'return', "frame.find_all('joint',", 'immediate_children_only=True)', 'else:', 'return', 'None'] | 166,145 |
AastaNV/ObjectDetection | box_utils.py | refine_match_return_matches | refine_match_return_matches | Match each arm bbox with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. | [
"Match",
"each",
"arm",
"bbox",
"with",
"the",
"ground",
"truth",
"box",
"of",
"the",
"highest",
"jaccard",
"overlap,",
"encode",
"the",
"bounding",
"boxes,",
"then",
"return",
"the",
"matched",
"indices",
"corresponding",
"to",
"both",
"confidence",
"and",
"l... | def refine_match_return_matches(threshold, truths, priors, variances, labels, loc_t, conf_t, idx, arm_loc=None):
if arm_loc is None:
overlaps = jaccard(truths, point_form(priors))
else:
decode_arm = decode(arm_loc, priors=priors, variances=variances)
overlaps = jaccard(truths, decode_arm... | ['def', 'refine_match_return_matches(threshold,', 'truths,', 'priors,', 'variances,', 'labels,', 'loc_t,', 'conf_t,', 'idx,', 'arm_loc=None):', 'if', 'arm_loc', 'is', 'None:', 'overlaps', '=', 'jaccard(truths,', 'point_form(priors))', 'else:', 'decode_arm', '=', 'decode(arm_loc,', 'priors=priors,', 'variances=variances... | 742,797 |
ganyeshprasanna/AI | search.py | SearchProblem.isGoalState | isGoalState | state: Search state Returns True if and only if the state is a valid goal state. | [
"state:",
"Search",
"state",
"Returns",
"True",
"if",
"and",
"only",
"if",
"the",
"state",
"is",
"a",
"valid",
"goal",
"state."
] | def isGoalState(self, state):
util.raiseNotDefined() | ['def', 'isGoalState(self,', 'state):', 'util.raiseNotDefined()'] | 25,831 |
rifqind/Agent-Programs-3KS1 | list.py | format_for_columns | format_for_columns | Convert the package data into something usable by output_package_listing_columns. | [
"Convert",
"the",
"package",
"data",
"into",
"something",
"usable",
"by",
"output_package_listing_columns."
] | def format_for_columns(pkgs, options):
running_outdated = options.outdated
if running_outdated:
header = ['Package', 'Version', 'Latest', 'Type']
else:
header = ['Package', 'Version']
data = []
if options.verbose >= 1 or any((dist_is_editable(x) for x in pkgs)):
header.append... | ['def', 'format_for_columns(pkgs,', 'options):', 'running_outdated', '=', 'options.outdated', 'if', 'running_outdated:', 'header', '=', "['Package',", "'Version',", "'Latest',", "'Type']", 'else:', 'header', '=', "['Package',", "'Version']", 'data', '=', '[]', 'if', 'options.verbose', '>=', '1', 'or', 'any((dist_is_edi... | 44,185 |
ishwnews/MASS | loader.py | load_binarized | load_binarized | Load a binarized dataset. | [
"Load",
"a",
"binarized",
"dataset."
] | def load_binarized(path, params):
assert path.endswith('.pth')
if params.debug_train:
path = path.replace('train', 'valid')
if getattr(params, 'multi_gpu', False):
split_path = '%s.%i.pth' % (path[:-4], params.local_rank)
if os.path.isfile(split_path):
assert params.split... | ['def', 'load_binarized(path,', 'params):', 'assert', "path.endswith('.pth')", 'if', 'params.debug_train:', 'path', '=', "path.replace('train',", "'valid')", 'if', 'getattr(params,', "'multi_gpu',", 'False):', 'split_path', '=', "'%s.%i.pth'", '%', '(path[:-4],', 'params.local_rank)', 'if', 'os.path.isfile(split_path):... | 645,905 |
flavioschneider/rl-transfer- | gaussian_cnn_baseline.py | GaussianCNNBaseline.fit | fit | Fit regressor based on paths. | [
"Fit",
"regressor",
"based",
"on",
"paths."
] | def fit(self, paths):
xs = np.concatenate([p['observations'] for p in paths])
if isinstance(self._env_spec.observation_space, akro.Image) and len(xs[0].shape) < len(self._env_spec.observation_space.shape):
xs = self._env_spec.observation_space.unflatten_n(xs)
ys = np.concatenate([p['returns'] for p ... | ['def', 'fit(self,', 'paths):', 'xs', '=', "np.concatenate([p['observations']", 'for', 'p', 'in', 'paths])', 'if', 'isinstance(self._env_spec.observation_space,', 'akro.Image)', 'and', 'len(xs[0].shape)', '<', 'len(self._env_spec.observation_space.shape):', 'xs', '=', 'self._env_spec.observation_space.unflatten_n(xs)',... | 861,348 |
myothida/Supervised-Machine-Learning | backend_bases.py | FigureCanvasBase.close_event | close_event | Pass a `CloseEvent` to all functions connected to ``close_event``. | [
"Pass",
"a",
"`CloseEvent`",
"to",
"all",
"functions",
"connected",
"to",
"``close_event``."
] | def close_event(self, guiEvent=None):
s = 'close_event'
try:
event = CloseEvent(s, self, guiEvent=guiEvent)
self.callbacks.process(s, event)
except (TypeError, AttributeError):
pass | ['def', 'close_event(self,', 'guiEvent=None):', 's', '=', "'close_event'", 'try:', 'event', '=', 'CloseEvent(s,', 'self,', 'guiEvent=guiEvent)', 'self.callbacks.process(s,', 'event)', 'except', '(TypeError,', 'AttributeError):', 'pass'] | 361,747 |
IceClear/MW-GAN | degradations.py | random_mixed_kernels | random_mixed_kernels | Randomly generate mixed kernels. | [
"Randomly",
"generate",
"mixed",
"kernels."
] | def random_mixed_kernels(kernel_list, kernel_prob, kernel_size=21, sigma_x_range=(0.6, 5), sigma_y_range=(0.6, 5), rotation_range=(-math.pi, math.pi), betag_range=(0.5, 8), betap_range=(0.5, 8), noise_range=None):
kernel_type = random.choices(kernel_list, kernel_prob)[0]
if kernel_type == 'iso':
kernel ... | ['def', 'random_mixed_kernels(kernel_list,', 'kernel_prob,', 'kernel_size=21,', 'sigma_x_range=(0.6,', '5),', 'sigma_y_range=(0.6,', '5),', 'rotation_range=(-math.pi,', 'math.pi),', 'betag_range=(0.5,', '8),', 'betap_range=(0.5,', '8),', 'noise_range=None):', 'kernel_type', '=', 'random.choices(kernel_list,', 'kernel_p... | 651,463 |
goncalo120/3DRegNet | transformations.py | Arcball.down | down | Set initial cursor window coordinates and pick constrain-axis. | [
"Set",
"initial",
"cursor",
"window",
"coordinates",
"and",
"pick",
"constrain-axis."
] | def down(self, point):
self._vdown = arcball_map_to_sphere(point, self._center, self._radius)
self._qdown = self._qpre = self._qnow
if self._constrain and self._axes is not None:
self._axis = arcball_nearest_axis(self._vdown, self._axes)
self._vdown = arcball_constrain_to_axis(self._vdown, s... | ['def', 'down(self,', 'point):', 'self._vdown', '=', 'arcball_map_to_sphere(point,', 'self._center,', 'self._radius)', 'self._qdown', '=', 'self._qpre', '=', 'self._qnow', 'if', 'self._constrain', 'and', 'self._axes', 'is', 'not', 'None:', 'self._axis', '=', 'arcball_nearest_axis(self._vdown,', 'self._axes)', 'self._vd... | 405,181 |
Trusted-AI/AIF360 | test_infairness.py | test_target_encoding | test_target_encoding | Tests the automatic type casting for classification problems. | [
"Tests",
"the",
"automatic",
"type",
"casting",
"for",
"classification",
"problems."
] | def test_target_encoding(y, criterion, raises):
X = np.random.random((4, 2)).astype('float32')
y = np.array(y)
if criterion == nn.MSELoss:
y = np.array(y, dtype='float32')
classes = np.unique(y).tolist()
if criterion == nn.BCEWithLogitsLoss or criterion == nn.MSELoss:
ndim = 1 if y.n... | ['def', 'test_target_encoding(y,', 'criterion,', 'raises):', 'X', '=', 'np.random.random((4,', "2)).astype('float32')", 'y', '=', 'np.array(y)', 'if', 'criterion', '==', 'nn.MSELoss:', 'y', '=', 'np.array(y,', "dtype='float32')", 'classes', '=', 'np.unique(y).tolist()', 'if', 'criterion', '==', 'nn.BCEWithLogitsLoss', ... | 412,525 |
sktime/sktime | test_panel_converters.py | test_from_multi_index_to_nested | test_from_multi_index_to_nested | Test from_multi_index_to_nested for correctness. | [
"Test",
"from_multi_index_to_nested",
"for",
"correctness."
] | def test_from_multi_index_to_nested(n_instances, n_columns, n_timepoints):
mi_df = make_multi_index_dataframe(n_instances=n_instances, n_timepoints=n_timepoints, n_columns=n_columns)
nested_df = from_multi_index_to_nested(mi_df, instance_index='case_id', cells_as_numpy=False)
assert is_nested_dataframe(nest... | ['def', 'test_from_multi_index_to_nested(n_instances,', 'n_columns,', 'n_timepoints):', 'mi_df', '=', 'make_multi_index_dataframe(n_instances=n_instances,', 'n_timepoints=n_timepoints,', 'n_columns=n_columns)', 'nested_df', '=', 'from_multi_index_to_nested(mi_df,', "instance_index='case_id',", 'cells_as_numpy=False)', ... | 886,151 |
kianak2002/Sentiment-Emotion-Analysis-project | versioncontrol.py | VersionControl.is_repository_directory | is_repository_directory | Return whether a directory path is a repository directory. | [
"Return",
"whether",
"a",
"directory",
"path",
"is",
"a",
"repository",
"directory."
] | def is_repository_directory(cls, path):
logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name)
return os.path.exists(os.path.join(path, cls.dirname)) | ['def', 'is_repository_directory(cls,', 'path):', "logger.debug('Checking", 'in', '%s', 'for', '%s', "(%s)...',", 'path,', 'cls.dirname,', 'cls.name)', 'return', 'os.path.exists(os.path.join(path,', 'cls.dirname))'] | 874,835 |
intel/neural-compressor | quantization.py | Quantization.model | model | Override model setter method to handle quantization aware training case. | [
"Override",
"model",
"setter",
"method",
"to",
"handle",
"quantization",
"aware",
"training",
"case."
] | def model(self, user_model):
approach_cfg = deep_get(self.cfg, 'quantization.approach')
if not self.framework:
self.framework = get_model_fwk_name(user_model)
if self.framework == 'tensorflow' and approach_cfg == 'quant_aware_training':
if type(user_model) == str:
self._model = T... | ['def', 'model(self,', 'user_model):', 'approach_cfg', '=', 'deep_get(self.cfg,', "'quantization.approach')", 'if', 'not', 'self.framework:', 'self.framework', '=', 'get_model_fwk_name(user_model)', 'if', 'self.framework', '==', "'tensorflow'", 'and', 'approach_cfg', '==', "'quant_aware_training':", 'if', 'type(user_mo... | 738,421 |
Speedwagon13/CS-3600-Introduction-to-- | ttk.py | Notebook.identify | identify | Returns the name of the tab element at position x, y, or the empty string if none. | [
"Returns",
"the",
"name",
"of",
"the",
"tab",
"element",
"at",
"position",
"x,",
"y,",
"or",
"the",
"empty",
"string",
"if",
"none."
] | def identify(self, x, y):
return self.tk.call(self._w, 'identify', x, y) | ['def', 'identify(self,', 'x,', 'y):', 'return', 'self.tk.call(self._w,', "'identify',", 'x,', 'y)'] | 219,340 |
rchurchley/IMA-Deep-Learning | anomalies.py | add_line | add_line | Scribble over an image with a random white line, saving to another file. | [
"Scribble",
"over",
"an",
"image",
"with",
"a",
"random",
"white",
"line,",
"saving",
"to",
"another",
"file."
] | def add_line(args, path, output_path, output_format):
img = Image.open(path).convert('RGB')
draw = ImageDraw.Draw(img)
points = []
for _ in xrange(4):
points.append(numpy.random.randint(0, img.size[0]))
width = numpy.random.randint(args[0], args[1])
color = (255, 255, 255)
draw.line(... | ['def', 'add_line(args,', 'path,', 'output_path,', 'output_format):', 'img', '=', "Image.open(path).convert('RGB')", 'draw', '=', 'ImageDraw.Draw(img)', 'points', '=', '[]', 'for', '_', 'in', 'xrange(4):', 'points.append(numpy.random.randint(0,', 'img.size[0]))', 'width', '=', 'numpy.random.randint(args[0],', 'args[1])... | 598,833 |
vbelz/audio_classification | metadata.py | requires_to_requires_dist | requires_to_requires_dist | Return the version specifier for a requirement in PEP 345/566 fashion. | [
"Return",
"the",
"version",
"specifier",
"for",
"a",
"requirement",
"in",
"PEP",
"345/566",
"fashion."
] | def requires_to_requires_dist(requirement):
if getattr(requirement, 'url', None):
return ' @ ' + requirement.url
requires_dist = []
for (op, ver) in requirement.specs:
requires_dist.append(op + ver)
if not requires_dist:
return ''
return ' (%s)' % ','.join(sorted(requires_dis... | ['def', 'requires_to_requires_dist(requirement):', 'if', 'getattr(requirement,', "'url',", 'None):', 'return', "'", '@', "'", '+', 'requirement.url', 'requires_dist', '=', '[]', 'for', '(op,', 'ver)', 'in', 'requirement.specs:', 'requires_dist.append(op', '+', 'ver)', 'if', 'not', 'requires_dist:', 'return', "''", 'ret... | 404,452 |
implus/GFocalV2 | vfnet_head.py | VFNetHead.transform_bbox_targets | transform_bbox_targets | Transform bbox_targets (x1, y1, x2, y2) into (l, t, r, b) format. | [
"Transform",
"bbox_targets",
"(x1,",
"y1,",
"x2,",
"y2)",
"into",
"(l,",
"t,",
"r,",
"b)",
"format."
] | def transform_bbox_targets(self, decoded_bboxes, mlvl_points, num_imgs):
assert len(decoded_bboxes) == len(mlvl_points)
num_levels = len(decoded_bboxes)
mlvl_points = [points.repeat(num_imgs, 1) for points in mlvl_points]
bbox_targets = []
for i in range(num_levels):
bbox_target = bbox2dista... | ['def', 'transform_bbox_targets(self,', 'decoded_bboxes,', 'mlvl_points,', 'num_imgs):', 'assert', 'len(decoded_bboxes)', '==', 'len(mlvl_points)', 'num_levels', '=', 'len(decoded_bboxes)', 'mlvl_points', '=', '[points.repeat(num_imgs,', '1)', 'for', 'points', 'in', 'mlvl_points]', 'bbox_targets', '=', '[]', 'for', 'i'... | 557,627 |
secretflow/secretflow | boost.py | compute_obj | compute_obj | compute objective values of input buckets. | [
"compute",
"objective",
"values",
"of",
"input",
"buckets."
] | def compute_obj(G: np.ndarray, H: np.ndarray, reg_lambda: float) -> np.ndarray:
return G / (H + reg_lambda) * G | ['def', 'compute_obj(G:', 'np.ndarray,', 'H:', 'np.ndarray,', 'reg_lambda:', 'float)', '->', 'np.ndarray:', 'return', 'G', '/', '(H', '+', 'reg_lambda)', '*', 'G'] | 856,472 |
AEProgrammer/object_detection | train.py | dump_proto_files | dump_proto_files | Save prototxt descriptions of the training network and parameter initialization network. | [
"Save",
"prototxt",
"descriptions",
"of",
"the",
"training",
"network",
"and",
"parameter",
"initialization",
"network."
] | def dump_proto_files(model, output_dir):
with open(os.path.join(output_dir, 'net.pbtxt'), 'w') as fid:
fid.write(str(model.net.Proto()))
with open(os.path.join(output_dir, 'param_init_net.pbtxt'), 'w') as fid:
fid.write(str(model.param_init_net.Proto())) | ['def', 'dump_proto_files(model,', 'output_dir):', 'with', 'open(os.path.join(output_dir,', "'net.pbtxt'),", "'w')", 'as', 'fid:', 'fid.write(str(model.net.Proto()))', 'with', 'open(os.path.join(output_dir,', "'param_init_net.pbtxt'),", "'w')", 'as', 'fid:', 'fid.write(str(model.param_init_net.Proto()))'] | 773,664 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | tarfile.py | TarInfo.isdir | isdir | Return True if it is a directory. | [
"Return",
"True",
"if",
"it",
"is",
"a",
"directory."
] | def isdir(self):
return self.type == DIRTYPE | ['def', 'isdir(self):', 'return', 'self.type', '==', 'DIRTYPE'] | 801,733 |
devashish-patel/webcam-motion-detector | hook-_tkinter.py | hook | hook | Freeze all external Tcl/Tk data files if this is a supported platform *or* log a non-fatal error otherwise. | [
"Freeze",
"all",
"external",
"Tcl/Tk",
"data",
"files",
"if",
"this",
"is",
"a",
"supported",
"platform",
"*or*",
"log",
"a",
"non-fatal",
"error",
"otherwise."
] | def hook(hook_api):
if is_win or is_darwin or is_unix:
hook_api.add_datas(_collect_tcl_tk_files(hook_api))
else:
logger.error('... skipping Tcl/Tk handling on unsupported platform %s', sys.platform) | ['def', 'hook(hook_api):', 'if', 'is_win', 'or', 'is_darwin', 'or', 'is_unix:', 'hook_api.add_datas(_collect_tcl_tk_files(hook_api))', 'else:', "logger.error('...", 'skipping', 'Tcl/Tk', 'handling', 'on', 'unsupported', 'platform', "%s',", 'sys.platform)'] | 984,241 |
stan-hua/CytoImageNet | model_evaluation.py | CytoImageNetValidation.evaluate | evaluate | Predict on validation set. | [
"Predict",
"on",
"validation",
"set."
] | def evaluate(self):
model = load_model(weights='cytoimagenet', include_top=True, overwrite=False, dset_='full')
y_pred = model.predict(self.val_gen, batch_size=self.batch_size, steps=self.steps, verbose=1)
y_pred_label_prob = np.max(y_pred, axis=1)
y_pred_label = np.argmax(y_pred, axis=1)
y_pred_lab... | ['def', 'evaluate(self):', 'model', '=', "load_model(weights='cytoimagenet',", 'include_top=True,', 'overwrite=False,', "dset_='full')", 'y_pred', '=', 'model.predict(self.val_gen,', 'batch_size=self.batch_size,', 'steps=self.steps,', 'verbose=1)', 'y_pred_label_prob', '=', 'np.max(y_pred,', 'axis=1)', 'y_pred_label', ... | 524,618 |
qcraftai/pillar-motion | custom.py | PointCloudDataset.evaluation | evaluation | Dataset must provide a evaluation function to evaluate model. | [
"Dataset",
"must",
"provide",
"a",
"evaluation",
"function",
"to",
"evaluate",
"model."
] | def evaluation(self, dt_annos, output_dir):
raise NotImplementedError | ['def', 'evaluation(self,', 'dt_annos,', 'output_dir):', 'raise', 'NotImplementedError'] | 304,980 |
intel/neural-compressor | model.py | TensorflowModel.guard_requirements_installed | guard_requirements_installed | Ensure all requirements are installed. | [
"Ensure",
"all",
"requirements",
"are",
"installed."
] | def guard_requirements_installed(self) -> None:
check_module('tensorflow') | ['def', 'guard_requirements_installed(self)', '->', 'None:', "check_module('tensorflow')"] | 721,601 |
luc-leonard/pytorch-diffusion-autoencoder | nn.py | linear | linear | Create a linear module. | [
"Create",
"a",
"linear",
"module."
] | def linear(*args, **kwargs):
return nn.Linear(*args, **kwargs) | ['def', 'linear(*args,', '**kwargs):', 'return', 'nn.Linear(*args,', '**kwargs)'] | 814,468 |
AEProgrammer/object_detection | TEST.py | vis_mask | vis_mask | Visualizes a single binary mask. | [
"Visualizes",
"a",
"single",
"binary",
"mask."
] | def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], :] += alpha * col
if show_border:
(_, contours, _) = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAI... | ['def', 'vis_mask(img,', 'mask,', 'col,', 'alpha=0.4,', 'show_border=True,', 'border_thick=1):', 'img', '=', 'img.astype(np.float32)', 'idx', '=', 'np.nonzero(mask)', 'img[idx[0],', 'idx[1],', ':]', '*=', '1.0', '-', 'alpha', 'img[idx[0],', 'idx[1],', ':]', '+=', 'alpha', '*', 'col', 'if', 'show_border:', '(_,', 'conto... | 773,798 |
xuannianz/SAPD | pascal.py | PascalVocGenerator.has_label | has_label | Return True if label is a known label. | [
"Return",
"True",
"if",
"label",
"is",
"a",
"known",
"label."
] | def has_label(self, label):
return label in self.labels | ['def', 'has_label(self,', 'label):', 'return', 'label', 'in', 'self.labels'] | 845,460 |
SamRagusa/Checkers-Reinforcement-Learning | Board.py | Board.get_capture_moves | get_capture_moves | Recursively get all of the possible moves for a piece which involve capturing an opponent's piece. | [
"Recursively",
"get",
"all",
"of",
"the",
"possible",
"moves",
"for",
"a",
"piece",
"which",
"involve",
"capturing",
"an",
"opponent's",
"piece."
] | def get_capture_moves(self, start_loc, move_beginnings=None):
if move_beginnings is None:
move_beginnings = [start_loc]
answer = []
if self.spots[start_loc[0]][start_loc[1]] > 2:
next1 = self.forward_n_locations(start_loc, 1)
next2 = self.forward_n_locations(start_loc, 2)
nex... | ['def', 'get_capture_moves(self,', 'start_loc,', 'move_beginnings=None):', 'if', 'move_beginnings', 'is', 'None:', 'move_beginnings', '=', '[start_loc]', 'answer', '=', '[]', 'if', 'self.spots[start_loc[0]][start_loc[1]]', '>', '2:', 'next1', '=', 'self.forward_n_locations(start_loc,', '1)', 'next2', '=', 'self.forward... | 486,103 |
Sea1004/artificial_intelligence | ansitowin32.py | AnsiToWin32.write_and_convert | write_and_convert | Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. | [
"Write",
"the",
"given",
"text",
"to",
"our",
"wrapped",
"stream,",
"stripping",
"any",
"ANSI",
"sequences",
"from",
"the",
"text,",
"and",
"optionally",
"converting",
"them",
"into",
"win32",
"calls."
] | def write_and_convert(self, text):
cursor = 0
text = self.convert_osc(text)
for match in self.ANSI_CSI_RE.finditer(text):
(start, end) = match.span()
self.write_plain_text(text, cursor, start)
self.convert_ansi(*match.groups())
cursor = end
self.write_plain_text(text, cur... | ['def', 'write_and_convert(self,', 'text):', 'cursor', '=', '0', 'text', '=', 'self.convert_osc(text)', 'for', 'match', 'in', 'self.ANSI_CSI_RE.finditer(text):', '(start,', 'end)', '=', 'match.span()', 'self.write_plain_text(text,', 'cursor,', 'start)', 'self.convert_ansi(*match.groups())', 'cursor', '=', 'end', 'self.... | 154,122 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | baseline.py | Baseline.get_inputs | get_inputs | Get inputs to network as single tensor. | [
"Get",
"inputs",
"to",
"network",
"as",
"single",
"tensor."
] | def get_inputs(self, time_step, obs, prev_actions, internal_policy_states):
inputs = [tf.ones_like(time_step)]
input_dim = 1
if not self.input_policy_state:
for (i, (obs_dim, obs_type)) in enumerate(self.env_spec.obs_dims_and_types):
if self.env_spec.is_discrete(obs_type):
... | ['def', 'get_inputs(self,', 'time_step,', 'obs,', 'prev_actions,', 'internal_policy_states):', 'inputs', '=', '[tf.ones_like(time_step)]', 'input_dim', '=', '1', 'if', 'not', 'self.input_policy_state:', 'for', '(i,', '(obs_dim,', 'obs_type))', 'in', 'enumerate(self.env_spec.obs_dims_and_types):', 'if', 'self.env_spec.i... | 26,019 |
ml4a/ml4a | localimport.py | is_local | is_local | Returns True if *filename* is a subpath of any of the paths in *pathlist*. | [
"Returns",
"True",
"if",
"*filename*",
"is",
"a",
"subpath",
"of",
"any",
"of",
"the",
"paths",
"in",
"*pathlist*."
] | def is_local(filename, pathlist):
filename = os.path.abspath(filename)
for path_name in pathlist:
path_name = os.path.abspath(path_name)
if is_subpath(filename, path_name):
return True
return False | ['def', 'is_local(filename,', 'pathlist):', 'filename', '=', 'os.path.abspath(filename)', 'for', 'path_name', 'in', 'pathlist:', 'path_name', '=', 'os.path.abspath(path_name)', 'if', 'is_subpath(filename,', 'path_name):', 'return', 'True', 'return', 'False'] | 629,923 |
clear-nus/MuMMI | ball_in_cup.old.py | Physics.in_target | in_target | Returns 1 if the ball is in the target, 0 otherwise. | [
"Returns",
"1",
"if",
"the",
"ball",
"is",
"in",
"the",
"target,",
"0",
"otherwise."
] | def in_target(self):
ball_to_target = abs(self.ball_to_target())
target_size = self.named.model.site_size['target', [0, 2]]
ball_size = self.named.model.geom_size['ball', 0]
return float(all(ball_to_target < target_size - ball_size)) | ['def', 'in_target(self):', 'ball_to_target', '=', 'abs(self.ball_to_target())', 'target_size', '=', "self.named.model.site_size['target',", '[0,', '2]]', 'ball_size', '=', "self.named.model.geom_size['ball',", '0]', 'return', 'float(all(ball_to_target', '<', 'target_size', '-', 'ball_size))'] | 265,884 |
instadeepai/jumanji | utils.py | move_up | move_up | Move the board up. | [
"Move",
"the",
"board",
"up."
] | def move_up(board: Board) -> Tuple[Board, float]:
return move(board, 0) | ['def', 'move_up(board:', 'Board)', '->', 'Tuple[Board,', 'float]:', 'return', 'move(board,', '0)'] | 594,021 |
weimin17/Object-Detection_HelmetDetection | data_download.py | txt_line_iterator | txt_line_iterator | Iterate through lines of file. | [
"Iterate",
"through",
"lines",
"of",
"file."
] | def txt_line_iterator(path):
with tf.gfile.Open(path) as f:
for line in f:
yield line.strip() | ['def', 'txt_line_iterator(path):', 'with', 'tf.gfile.Open(path)', 'as', 'f:', 'for', 'line', 'in', 'f:', 'yield', 'line.strip()'] | 761,148 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Misc.event_info | event_info | Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL. | [
"Return",
"a",
"list",
"of",
"all",
"virtual",
"events",
"or",
"the",
"information",
"about",
"the",
"SEQUENCE",
"bound",
"to",
"the",
"virtual",
"event",
"VIRTUAL."
] | def event_info(self, virtual=None):
return self.tk.splitlist(self.tk.call('event', 'info', virtual)) | ['def', 'event_info(self,', 'virtual=None):', 'return', "self.tk.splitlist(self.tk.call('event',", "'info',", 'virtual))'] | 376,874 |
tomcatmanager/tomcatmanager | mock_server_ssl.py | MockRequestHandlerSSL.get_list | get_list | Send a list of applications. | [
"Send",
"a",
"list",
"of",
"applications."
] | def get_list(self):
self.send_text('OK - Listed applications for virtual host localhost\n/:running:0:ROOT\n/contacts:running:3:running##4.1\n/shiny:stopped:17:shiny##v2.0.6\n/contacts:running:8:running\n/shiny:stopped:0:shiny##v2.0.5\n/host-manager:stopped:0:/usr/share/tomcat8-admin/host-manager\n/shiny:running:12:... | ['def', 'get_list(self):', "self.send_text('OK", '-', 'Listed', 'applications', 'for', 'virtual', 'host', "localhost\\n/:running:0:ROOT\\n/contacts:running:3:running##4.1\\n/shiny:stopped:17:shiny##v2.0.6\\n/contacts:running:8:running\\n/shiny:stopped:0:shiny##v2.0.5\\n/host-manager:stopped:0:/usr/share/tomcat8-admin/h... | 355,660 |
JedMills/MTFL-For-Personalised-DNNs | fl_algs.py | init_stats_arrays | init_stats_arrays | Returns: (tupe) of 4 numpy 0-filled float32 arrays of length T. | [
"Returns:",
"(tupe)",
"of",
"4",
"numpy",
"0-filled",
"float32",
"arrays",
"of",
"length",
"T."
] | def init_stats_arrays(T):
return tuple((np.zeros(T, dtype=np.float32) for i in range(4))) | ['def', 'init_stats_arrays(T):', 'return', 'tuple((np.zeros(T,', 'dtype=np.float32)', 'for', 'i', 'in', 'range(4)))'] | 642,716 |
arshpreetsingh/quantopian-machinelearning | sanitize.py | SanitizeHTML.sanitize_html_tags | sanitize_html_tags | Sanitize a string containing raw HTML tags. | [
"Sanitize",
"a",
"string",
"containing",
"raw",
"HTML",
"tags."
] | def sanitize_html_tags(self, html_str):
return clean(html_str, tags=self.tags, attributes=self.attributes, styles=self.styles, strip=self.strip, strip_comments=self.strip_comments) | ['def', 'sanitize_html_tags(self,', 'html_str):', 'return', 'clean(html_str,', 'tags=self.tags,', 'attributes=self.attributes,', 'styles=self.styles,', 'strip=self.strip,', 'strip_comments=self.strip_comments)'] | 888,118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.