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
43Carrig/recurrent_neural_networks_practice
test_util.py
gpu_device_name
gpu_device_name
Returns the name of a GPU device if available or the empty string.
[ "Returns", "the", "name", "of", "a", "GPU", "device", "if", "available", "or", "the", "empty", "string." ]
def gpu_device_name(): for x in device_lib.list_local_devices(): if x.device_type == 'GPU' or x.device_type == 'SYCL': return compat.as_str(x.name) return ''
['def', 'gpu_device_name():', 'for', 'x', 'in', 'device_lib.list_local_devices():', 'if', 'x.device_type', '==', "'GPU'", 'or', 'x.device_type', '==', "'SYCL':", 'return', 'compat.as_str(x.name)', 'return', "''"]
336,588
awentzonline/keras-rtst
style_xfer.py
evaluation_input_generator
evaluation_input_generator
Generates batches of random samples paired with images.
[ "Generates", "batches", "of", "random", "samples", "paired", "with", "images." ]
def evaluation_input_generator(args): g_training_imgs = generate_img_batches(args.eval_data_path, args.batch_size, resize_shape=(args.max_height, args.max_width)) while True: data = {'content': np.array(next(g_training_imgs))} yield data
['def', 'evaluation_input_generator(args):', 'g_training_imgs', '=', 'generate_img_batches(args.eval_data_path,', 'args.batch_size,', 'resize_shape=(args.max_height,', 'args.max_width))', 'while', 'True:', 'data', '=', "{'content':", 'np.array(next(g_training_imgs))}', 'yield', 'data']
248,180
scotch/engineauth
model.py
BaseModel.deserialize
deserialize
Perform the actual deserialization from response string to Python object.
[ "Perform", "the", "actual", "deserialization", "from", "response", "string", "to", "Python", "object." ]
def deserialize(self, content): _abstract()
['def', 'deserialize(self,', 'content):', '_abstract()']
178,065
mlwithtf/mlwithtf
helper.py
std_spec
std_spec
Parameters commonly used by "post-AlexNet" architectures.
[ "Parameters", "commonly", "used", "by", "\"post-AlexNet\"", "architectures." ]
def std_spec(batch_size, isotropic=True): return DataSpec(batch_size=batch_size, scale_size=256, crop_size=224, isotropic=isotropic)
['def', 'std_spec(batch_size,', 'isotropic=True):', 'return', 'DataSpec(batch_size=batch_size,', 'scale_size=256,', 'crop_size=224,', 'isotropic=isotropic)']
631,180
tonybeltramelli/Graphics-And-Vision
Cameras.py
Cameras.Grab
Grab
Grabs the next frame from video file or capturing device.
[ "Grabs", "the", "next", "frame", "from", "video", "file", "or", "capturing", "device." ]
def Grab(self): for index in self.__camera: self.__camera[index].Grab()
['def', 'Grab(self):', 'for', 'index', 'in', 'self.__camera:', 'self.__camera[index].Grab()']
580,578
boostcampaitech2/semantic-segmentation-level2-cv-05
class_names.py
voc_classes
voc_classes
Pascal VOC class names for external use.
[ "Pascal", "VOC", "class", "names", "for", "external", "use." ]
def voc_classes(): return ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
['def', 'voc_classes():', 'return', "['background',", "'aeroplane',", "'bicycle',", "'bird',", "'boat',", "'bottle',", "'bus',", "'car',", "'cat',", "'chair',", "'cow',", "'diningtable',", "'dog',", "'horse',", "'motorbike',", "'person',", "'pottedplant',", "'sheep',", "'sofa',", "'train',", "'tvmonitor']"]
844,621
greydanus/mr_london
plugin_support.py
LabelledDebug.write
write
Write `message`, but with the labels prepended.
[ "Write", "`message`,", "but", "with", "the", "labels", "prepended." ]
def write(self, message): self.debug.write('%s%s' % (self.message_prefix(), message))
['def', 'write(self,', 'message):', "self.debug.write('%s%s'", '%', '(self.message_prefix(),', 'message))']
242,239
johschmidt42/PyTorch-Object-Detection-Faster-RCNN-Tutorial
object_detection_viewer.py
ObjectDetectionViewer.get_target
get_target
Get the target from the sample and transform it to be napari compatible.
[ "Get", "the", "target", "from", "the", "sample", "and", "transform", "it", "to", "be", "napari", "compatible." ]
def get_target(self, sample: Dict[str, Any]) -> Dict[str, Any]: logger.info(f"Target sample: {sample['y_name']}\n{sample['y']}") if self.rcnn_transform is not None: sample: Dict[str, Any] = self._rcnn_transformer(sample=sample, transform=self.rcnn_transform) logger.info(f"Transformed target samp...
['def', 'get_target(self,', 'sample:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', 'logger.info(f"Target', 'sample:', '{sample[\'y_name\']}\\n{sample[\'y\']}")', 'if', 'self.rcnn_transform', 'is', 'not', 'None:', 'sample:', 'Dict[str,', 'Any]', '=', 'self._rcnn_transformer(sample=sample,', 'transform=self.rcnn_tr...
814,935
iffiX/machin
prioritized_buffer.py
WeightTree.update_leaf
update_leaf
Update a single weight tree leaf.
[ "Update", "a", "single", "weight", "tree", "leaf." ]
def update_leaf(self, weight: float, index: int): if not 0 <= index <= self.size: raise ValueError('Index has elements out of boundary!') self.max_leaf = max(weight, self.max_leaf) self.weights[index] = weight value = weight comp_value = self.weights[index ^ 1] for i in range(1, self.dep...
['def', 'update_leaf(self,', 'weight:', 'float,', 'index:', 'int):', 'if', 'not', '0', '<=', 'index', '<=', 'self.size:', 'raise', "ValueError('Index", 'has', 'elements', 'out', 'of', "boundary!')", 'self.max_leaf', '=', 'max(weight,', 'self.max_leaf)', 'self.weights[index]', '=', 'weight', 'value', '=', 'weight', 'com...
620,314
StanfordVL/taskonomy
pairwise_siamese.py
PairWiseSiamese.get_losses
get_losses
Returns the loss for a Siamese Network.
[ "Returns", "the", "loss", "for", "a", "Siamese", "Network." ]
def get_losses(self, final_output, target, is_softmax=True): print('setting up losses...') self.target = target self.final_output = final_output with tf.variable_scope('losses'): if is_softmax: correct_prediction = tf.equal(tf.argmax(final_output, 1), target) self.accurac...
['def', 'get_losses(self,', 'final_output,', 'target,', 'is_softmax=True):', "print('setting", 'up', "losses...')", 'self.target', '=', 'target', 'self.final_output', '=', 'final_output', 'with', "tf.variable_scope('losses'):", 'if', 'is_softmax:', 'correct_prediction', '=', 'tf.equal(tf.argmax(final_output,', '1),', '...
907,797
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
imaplib.py
IMAP4.shutdown
shutdown
Close I/O established in "open".
[ "Close", "I/O", "established", "in", "\"open\"." ]
def shutdown(self): self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: if e.errno != errno.ENOTCONN: raise finally: self.sock.close()
['def', 'shutdown(self):', 'self.file.close()', 'try:', 'self.sock.shutdown(socket.SHUT_RDWR)', 'except', 'OSError', 'as', 'e:', 'if', 'e.errno', '!=', 'errno.ENOTCONN:', 'raise', 'finally:', 'self.sock.close()']
428,574
Eric3911/OpenAGI
text_generation_strategy.py
PromptLearningModelTextGenerationStrategy.init_batch
init_batch
initialize the batch data before the inference steps.
[ "initialize", "the", "batch", "data", "before", "the", "inference", "steps." ]
def init_batch(self, context_tokens: torch.Tensor, context_length: int): tokenizer = self.model.tokenizer tokens = context_tokens.contiguous().cuda() (self.attention_mask, _, self.position_ids) = get_ltor_masks_and_position_ids(tokens, tokenizer.eos_id, self.model.cfg.get('reset_position_ids', False), self....
['def', 'init_batch(self,', 'context_tokens:', 'torch.Tensor,', 'context_length:', 'int):', 'tokenizer', '=', 'self.model.tokenizer', 'tokens', '=', 'context_tokens.contiguous().cuda()', '(self.attention_mask,', '_,', 'self.position_ids)', '=', 'get_ltor_masks_and_position_ids(tokens,', 'tokenizer.eos_id,', "self.model...
273,729
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
operator.py
setitem
setitem
Same as a[b] = c.
[ "Same", "as", "a[b]", "=", "c." ]
def setitem(a, b, c): a[b] = c
['def', 'setitem(a,', 'b,', 'c):', 'a[b]', '=', 'c']
428,999
google-research/scenic
test_transforms.py
RandomHorizontalFlipTest.test_hflip_twice
test_hflip_twice
Tests hflip function by applying it twice and matching with original.
[ "Tests", "hflip", "function", "by", "applying", "it", "twice", "and", "matching", "with", "original." ]
def test_hflip_twice(self, n, h, w): features = fake_decoded_features(n, h, w) features_copy = copy.deepcopy(features) features_flip = transforms.hflip(features_copy) features_recon = transforms.hflip(features_flip) self._assert_features_equal(features, features_recon, msg='flip_twice mismatch at fe...
['def', 'test_hflip_twice(self,', 'n,', 'h,', 'w):', 'features', '=', 'fake_decoded_features(n,', 'h,', 'w)', 'features_copy', '=', 'copy.deepcopy(features)', 'features_flip', '=', 'transforms.hflip(features_copy)', 'features_recon', '=', 'transforms.hflip(features_flip)', 'self._assert_features_equal(features,', 'feat...
846,687
43Carrig/recurrent_neural_networks_practice
layer_utils.py
gather_non_trainable_weights
gather_non_trainable_weights
Lists the non-trainable weights for an object with sub-layers.
[ "Lists", "the", "non-trainable", "weights", "for", "an", "object", "with", "sub-layers." ]
def gather_non_trainable_weights(trainable, sub_layers, extra_variables): trainable_extra_variables = [] non_trainable_extra_variables = [] for v in extra_variables: if v.trainable: trainable_extra_variables.append(v) else: non_trainable_extra_variables.append(v) ...
['def', 'gather_non_trainable_weights(trainable,', 'sub_layers,', 'extra_variables):', 'trainable_extra_variables', '=', '[]', 'non_trainable_extra_variables', '=', '[]', 'for', 'v', 'in', 'extra_variables:', 'if', 'v.trainable:', 'trainable_extra_variables.append(v)', 'else:', 'non_trainable_extra_variables.append(v)'...
337,002
sauradip/night_image_semantic_segmentation
modeling.py
deeplabv3_mobilenet
deeplabv3_mobilenet
Constructs a DeepLabV3 model with a MobileNetv2 backbone.
[ "Constructs", "a", "DeepLabV3", "model", "with", "a", "MobileNetv2", "backbone." ]
def deeplabv3_mobilenet(num_classes=21, output_stride=8, pretrained_backbone=True, **kwargs): return _load_model('deeplabv3', 'mobilenetv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
['def', 'deeplabv3_mobilenet(num_classes=21,', 'output_stride=8,', 'pretrained_backbone=True,', '**kwargs):', 'return', "_load_model('deeplabv3',", "'mobilenetv2',", 'num_classes,', 'output_stride=output_stride,', 'pretrained_backbone=pretrained_backbone)']
723,551
dmpelt/msdnet
operations.py
ImageData.filtergradientfull
filtergradientfull
Compute gradients for filters.
[ "Compute", "gradients", "for", "filters." ]
def filtergradientfull(self, ims): gs = [] for i in range(len(self.dl)): d = self.dl[i] for j in range(self.nin + i): for q in [-1, 0, 1]: for r in [-1, 0, 1]: gs.append(filtergradient2d(ims.arr[j], self.arr[i], self.uxs[q * d], self.uys[r * d])) ...
['def', 'filtergradientfull(self,', 'ims):', 'gs', '=', '[]', 'for', 'i', 'in', 'range(len(self.dl)):', 'd', '=', 'self.dl[i]', 'for', 'j', 'in', 'range(self.nin', '+', 'i):', 'for', 'q', 'in', '[-1,', '0,', '1]:', 'for', 'r', 'in', '[-1,', '0,', '1]:', 'gs.append(filtergradient2d(ims.arr[j],', 'self.arr[i],', 'self.ux...
265,156
Kvatsx/Artificial-Intelligence-Assignments
gen_test.py
GenEngineTest.delay_callback
delay_callback
Runs callback(arg) after a number of IOLoop iterations.
[ "Runs", "callback(arg)", "after", "a", "number", "of", "IOLoop", "iterations." ]
def delay_callback(self, iterations, callback, arg): if iterations == 0: callback(arg) else: self.io_loop.add_callback(functools.partial(self.delay_callback, iterations - 1, callback, arg))
['def', 'delay_callback(self,', 'iterations,', 'callback,', 'arg):', 'if', 'iterations', '==', '0:', 'callback(arg)', 'else:', 'self.io_loop.add_callback(functools.partial(self.delay_callback,', 'iterations', '-', '1,', 'callback,', 'arg))']
78,880
Speedwagon13/CS-3600-Introduction-to--
datetime.py
datetime.replace
replace
Return a new datetime with new values for the specified fields.
[ "Return", "a", "new", "datetime", "with", "new", "values", "for", "the", "specified", "fields." ]
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=True): if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is...
['def', 'replace(self,', 'year=None,', 'month=None,', 'day=None,', 'hour=None,', 'minute=None,', 'second=None,', 'microsecond=None,', 'tzinfo=True):', 'if', 'year', 'is', 'None:', 'year', '=', 'self.year', 'if', 'month', 'is', 'None:', 'month', '=', 'self.month', 'if', 'day', 'is', 'None:', 'day', '=', 'self.day', 'if'...
219,755
deepmind/dm_control
swimmer.py
Physics.nose_to_target_dist
nose_to_target_dist
Returns the distance from the nose to the target.
[ "Returns", "the", "distance", "from", "the", "nose", "to", "the", "target." ]
def nose_to_target_dist(self): return np.linalg.norm(self.nose_to_target())
['def', 'nose_to_target_dist(self):', 'return', 'np.linalg.norm(self.nose_to_target())']
166,483
jmamath/ood-deep-learning
augmentations.py
float_parameter
float_parameter
Helper function to scale `val` between 0 and maxval.
[ "Helper", "function", "to", "scale", "`val`", "between", "0", "and", "maxval." ]
def float_parameter(level, maxval): return float(level) * maxval / 10.0
['def', 'float_parameter(level,', 'maxval):', 'return', 'float(level)', '*', 'maxval', '/', '10.0']
756,632
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vgslspecs.py
VGSLSpecs.BuildFromString
BuildFromString
Adds the layers defined by model_str[index:] to the model.
[ "Adds", "the", "layers", "defined", "by", "model_str[index:]", "to", "the", "model." ]
def BuildFromString(self, prev_layer, index): index = self._SkipWhitespace(index) for op in self.valid_ops: (output_layer, next_index) = op(prev_layer, index) if output_layer is not None: return (output_layer, next_index) if output_layer is not None: return (output_layer,...
['def', 'BuildFromString(self,', 'prev_layer,', 'index):', 'index', '=', 'self._SkipWhitespace(index)', 'for', 'op', 'in', 'self.valid_ops:', '(output_layer,', 'next_index)', '=', 'op(prev_layer,', 'index)', 'if', 'output_layer', 'is', 'not', 'None:', 'return', '(output_layer,', 'next_index)', 'if', 'output_layer', 'is...
27,701
suarez12138/AI-Reversi_IMP_TextDichotomy
__init__.py
open_file_cm
open_file_cm
Pass through file objects and context-manage path-likes.
[ "Pass", "through", "file", "objects", "and", "context-manage", "path-likes." ]
def open_file_cm(path_or_file, mode='r', encoding=None): (fh, opened) = to_filehandle(path_or_file, mode, True, encoding) if opened: with fh: yield fh else: yield fh
['def', 'open_file_cm(path_or_file,', "mode='r',", 'encoding=None):', '(fh,', 'opened)', '=', 'to_filehandle(path_or_file,', 'mode,', 'True,', 'encoding)', 'if', 'opened:', 'with', 'fh:', 'yield', 'fh', 'else:', 'yield', 'fh']
97,164
aeon-toolkit/aeon
test_mlflow_aeon_model_export.py
test_auto_arima_model_pyfunc_output
test_auto_arima_model_pyfunc_output
Test auto arima prediction of loaded pyfunc model.
[ "Test", "auto", "arima", "prediction", "of", "loaded", "pyfunc", "model." ]
def test_auto_arima_model_pyfunc_output(auto_arima_model, model_path, serialization_format): from aeon.utils import mlflow_aeon auto_arima_model.pyfunc_predict_conf = {'predict_method': ['predict', 'predict_interval', 'predict_quantiles', 'predict_var']} mlflow_aeon.save_model(estimator=auto_arima_model, pa...
['def', 'test_auto_arima_model_pyfunc_output(auto_arima_model,', 'model_path,', 'serialization_format):', 'from', 'aeon.utils', 'import', 'mlflow_aeon', 'auto_arima_model.pyfunc_predict_conf', '=', "{'predict_method':", "['predict',", "'predict_interval',", "'predict_quantiles',", "'predict_var']}", 'mlflow_aeon.save_m...
400,227
Kvatsx/Artificial-Intelligence-Assignments
osm.py
OSMagics.dirs
dirs
Return the current directory stack.
[ "Return", "the", "current", "directory", "stack." ]
def dirs(self, parameter_s=''): return self.shell.dir_stack
['def', 'dirs(self,', "parameter_s=''):", 'return', 'self.shell.dir_stack']
38,322
thaines/helit
model.py
DocModel.sampleList
sampleList
Returns a list of samples, for iterating.
[ "Returns", "a", "list", "of", "samples,", "for", "iterating." ]
def sampleList(self): return self.sample
['def', 'sampleList(self):', 'return', 'self.sample']
591,193
ivanmontero/autobot
registry.py
set_defaults
set_defaults
Helper to set default arguments based on *add_args*.
[ "Helper", "to", "set", "default", "arguments", "based", "on", "*add_args*." ]
def set_defaults(args, cls): if not hasattr(cls, 'add_args'): return parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, allow_abbrev=False) cls.add_args(parser) defaults = argparse.Namespace() for action in parser._actions: if action.dest is not argparse.SUPPRESS: ...
['def', 'set_defaults(args,', 'cls):', 'if', 'not', 'hasattr(cls,', "'add_args'):", 'return', 'parser', '=', 'argparse.ArgumentParser(argument_default=argparse.SUPPRESS,', 'allow_abbrev=False)', 'cls.add_args(parser)', 'defaults', '=', 'argparse.Namespace()', 'for', 'action', 'in', 'parser._actions:', 'if', 'action.des...
417,184
43Carrig/recurrent_neural_networks_practice
estimator.py
Estimator.export_savedmodel
export_savedmodel
Exports inference graph as a SavedModel into given dir.
[ "Exports", "inference", "graph", "as", "a", "SavedModel", "into", "given", "dir." ]
def export_savedmodel(self, export_dir_base, serving_input_fn, default_output_alternative_key=None, assets_extra=None, as_text=False, checkpoint_path=None, graph_rewrite_specs=(GraphRewriteSpec((tag_constants.SERVING,), ()),), strip_default_attrs=False): if serving_input_fn is None: raise ValueError('servin...
['def', 'export_savedmodel(self,', 'export_dir_base,', 'serving_input_fn,', 'default_output_alternative_key=None,', 'assets_extra=None,', 'as_text=False,', 'checkpoint_path=None,', 'graph_rewrite_specs=(GraphRewriteSpec((tag_constants.SERVING,),', '()),),', 'strip_default_attrs=False):', 'if', 'serving_input_fn', 'is',...
313,617
matsu0228/nlp-jp
backend_pdf.py
PdfFile.writeXref
writeXref
Write out the xref table.
[ "Write", "out", "the", "xref", "table." ]
def writeXref(self): self.startxref = self.fh.tell() - self.tell_base self.write(('xref\n0 %d\n' % self.nextObject).encode('ascii')) i = 0 borken = False for (offset, generation, name) in self.xrefTable: if offset is None: print('No offset for object %d (%s)' % (i, name), file=sy...
['def', 'writeXref(self):', 'self.startxref', '=', 'self.fh.tell()', '-', 'self.tell_base', "self.write(('xref\\n0", "%d\\n'", '%', "self.nextObject).encode('ascii'))", 'i', '=', '0', 'borken', '=', 'False', 'for', '(offset,', 'generation,', 'name)', 'in', 'self.xrefTable:', 'if', 'offset', 'is', 'None:', "print('No", ...
789,625
nosmokingbandit/watcher
_cpcompat.py
base64_decode
base64_decode
Return the native string base64-decoded (as a native string).
[ "Return", "the", "native", "string", "base64-decoded", "(as", "a", "native", "string)." ]
def base64_decode(n, encoding='ISO-8859-1'): if isinstance(n, six.text_type): b = n.encode(encoding) else: b = n b = _base64_decodebytes(b) if str is six.text_type: return b.decode(encoding) else: return b
['def', 'base64_decode(n,', "encoding='ISO-8859-1'):", 'if', 'isinstance(n,', 'six.text_type):', 'b', '=', 'n.encode(encoding)', 'else:', 'b', '=', 'n', 'b', '=', '_base64_decodebytes(b)', 'if', 'str', 'is', 'six.text_type:', 'return', 'b.decode(encoding)', 'else:', 'return', 'b']
381,290
suarez12138/AI-Reversi_IMP_TextDichotomy
test_image.py
test_image_interps
test_image_interps
Make the basic nearest, bilinear and bicubic interps.
[ "Make", "the", "basic", "nearest,", "bilinear", "and", "bicubic", "interps." ]
def test_image_interps(): plt.rcParams['text.kerning_factor'] = 6 X = np.arange(100) X = X.reshape(5, 20) fig = plt.figure() ax1 = fig.add_subplot(311) ax1.imshow(X, interpolation='nearest') ax1.set_title('three interpolations') ax1.set_ylabel('nearest') ax2 = fig.add_subplot(312) ...
['def', 'test_image_interps():', "plt.rcParams['text.kerning_factor']", '=', '6', 'X', '=', 'np.arange(100)', 'X', '=', 'X.reshape(5,', '20)', 'fig', '=', 'plt.figure()', 'ax1', '=', 'fig.add_subplot(311)', 'ax1.imshow(X,', "interpolation='nearest')", "ax1.set_title('three", "interpolations')", "ax1.set_ylabel('nearest...
97,349
Gradiant/pyodi
evaluation.py
plot_overlap_result
plot_overlap_result
Generates plot for train config evaluation based on overlap.
[ "Generates", "plot", "for", "train", "config", "evaluation", "based", "on", "overlap." ]
def plot_overlap_result(df: DataFrame, max_bins: int=30, show: bool=True, output: Optional[str]=None, output_size: Tuple[int, int]=(1600, 900)) -> None: fig = make_subplots(rows=2, cols=2, subplot_titles=('Cumulative overlap distribution', 'Bounding Box Distribution', 'Scale and mean overlap', 'Log Ratio and mean o...
['def', 'plot_overlap_result(df:', 'DataFrame,', 'max_bins:', 'int=30,', 'show:', 'bool=True,', 'output:', 'Optional[str]=None,', 'output_size:', 'Tuple[int,', 'int]=(1600,', '900))', '->', 'None:', 'fig', '=', 'make_subplots(rows=2,', 'cols=2,', "subplot_titles=('Cumulative", 'overlap', "distribution',", "'Bounding", ...
809,012
deepmind/acme
networks.py
make_network_from_module
make_network_from_module
Creates a network with dummy init arguments using the specified module.
[ "Creates", "a", "network", "with", "dummy", "init", "arguments", "using", "the", "specified", "module." ]
def make_network_from_module(module: hk.Transformed, spec: specs.EnvironmentSpec) -> networks.FeedForwardNetwork: dummy_obs = utils.add_batch_dim(utils.zeros_like(spec.observations)) dummy_action = utils.add_batch_dim(utils.zeros_like(spec.actions)) return networks.FeedForwardNetwork(lambda key: module.init...
['def', 'make_network_from_module(module:', 'hk.Transformed,', 'spec:', 'specs.EnvironmentSpec)', '->', 'networks.FeedForwardNetwork:', 'dummy_obs', '=', 'utils.add_batch_dim(utils.zeros_like(spec.observations))', 'dummy_action', '=', 'utils.add_batch_dim(utils.zeros_like(spec.actions))', 'return', 'networks.FeedForwar...
7,601
arshpreetsingh/quantopian-machinelearning
testing.py
assert_is_sorted
assert_is_sorted
Assert that the sequence is sorted.
[ "Assert", "that", "the", "sequence", "is", "sorted." ]
def assert_is_sorted(seq): if isinstance(seq, (Index, Series)): seq = seq.values assert_numpy_array_equal(seq, np.sort(np.array(seq)))
['def', 'assert_is_sorted(seq):', 'if', 'isinstance(seq,', '(Index,', 'Series)):', 'seq', '=', 'seq.values', 'assert_numpy_array_equal(seq,', 'np.sort(np.array(seq)))']
890,796
alinlab/ifseg
token_generation_constraints.py
ConstraintNode.next_tokens
next_tokens
The set of child labels.
[ "The", "set", "of", "child", "labels." ]
def next_tokens(self) -> Set[int]: return set(self.children.keys())
['def', 'next_tokens(self)', '->', 'Set[int]:', 'return', 'set(self.children.keys())']
597,875
deepmind/acme
rainbow.py
make_builder
make_builder
Returns a DQNBuilder with a pre-built loss function.
[ "Returns", "a", "DQNBuilder", "with", "a", "pre-built", "loss", "function." ]
def make_builder(config: RainbowConfig): loss_fn = losses.PrioritizedCategoricalDoubleQLearning(discount=config.discount, importance_sampling_exponent=config.importance_sampling_exponent, max_abs_reward=config.max_abs_reward) return builder.DQNBuilder(config, loss_fn=loss_fn)
['def', 'make_builder(config:', 'RainbowConfig):', 'loss_fn', '=', 'losses.PrioritizedCategoricalDoubleQLearning(discount=config.discount,', 'importance_sampling_exponent=config.importance_sampling_exponent,', 'max_abs_reward=config.max_abs_reward)', 'return', 'builder.DQNBuilder(config,', 'loss_fn=loss_fn)']
8,100
011235813/cm3
replay_buffer.py
Replay_Buffer.sample
sample
Randomly samples one episode, and samples a subsequence of <length> from episode.
[ "Randomly", "samples", "one", "episode,", "and", "samples", "a", "subsequence", "of", "<length>", "from", "episode." ]
def sample(self, length): episode = random.choice(self.memory) if len(episode) <= length: return episode else: start = np.random.randint(0, len(episode) + 1 - length) subsequence = episode[start:start + length] return subsequence
['def', 'sample(self,', 'length):', 'episode', '=', 'random.choice(self.memory)', 'if', 'len(episode)', '<=', 'length:', 'return', 'episode', 'else:', 'start', '=', 'np.random.randint(0,', 'len(episode)', '+', '1', '-', 'length)', 'subsequence', '=', 'episode[start:start', '+', 'length]', 'return', 'subsequence']
488,622
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_descr.py
MroTest.test_incomplete_extend
test_incomplete_extend
Extending an unitialized type with type->tp_mro == NULL must throw a reasonable TypeError exception, instead of failing with PyErr_BadInternalCall.
[ "Extending", "an", "unitialized", "type", "with", "type->tp_mro", "==", "NULL", "must", "throw", "a", "reasonable", "TypeError", "exception,", "instead", "of", "failing", "with", "PyErr_BadInternalCall." ]
def test_incomplete_extend(self): class M(DebugHelperMeta): def mro(cls): if cls.__mro__ is None and cls.__name__ != 'X': with self.assertRaises(TypeError): class X(cls): pass return type.mro(cls) class A(metaclass=M...
['def', 'test_incomplete_extend(self):', 'class', 'M(DebugHelperMeta):', 'def', 'mro(cls):', 'if', 'cls.__mro__', 'is', 'None', 'and', 'cls.__name__', '!=', "'X':", 'with', 'self.assertRaises(TypeError):', 'class', 'X(cls):', 'pass', 'return', 'type.mro(cls)', 'class', 'A(metaclass=M):', 'pass']
431,360
RasaHQ/rasa
telemetry.py
track_data_convert
track_data_convert
Track when a user converts data.
[ "Track", "when", "a", "user", "converts", "data." ]
def track_data_convert(output_format: Text, data_type: Text) -> None: _track(TELEMETRY_DATA_CONVERTED_EVENT, {'output_format': output_format, 'type': data_type})
['def', 'track_data_convert(output_format:', 'Text,', 'data_type:', 'Text)', '->', 'None:', '_track(TELEMETRY_DATA_CONVERTED_EVENT,', "{'output_format':", 'output_format,', "'type':", 'data_type})']
836,573
jimtin/Stock_Comparison
interactiveshell.py
get_pasted_lines
get_pasted_lines
Yield pasted lines until the user enters the given sentinel value.
[ "Yield", "pasted", "lines", "until", "the", "user", "enters", "the", "given", "sentinel", "value." ]
def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): if not quiet: print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." % sentinel) prompt = ':' else: prompt = '' while True: try: l = py3compat.str_to_unicode(l_input(prompt)) ...
['def', 'get_pasted_lines(sentinel,', 'l_input=py3compat.input,', 'quiet=False):', 'if', 'not', 'quiet:', 'print("Pasting', 'code;', 'enter', "'%s'", 'alone', 'on', 'the', 'line', 'to', 'stop', 'or', 'use', 'Ctrl-D."', '%', 'sentinel)', 'prompt', '=', "':'", 'else:', 'prompt', '=', "''", 'while', 'True:', 'try:', 'l', ...
385,334
TrellixVulnTeam/Unsupervised_Learning_HFI7
interval.py
IntervalArray.right
right
Return the right endpoints of each Interval in the IntervalArray as an Index.
[ "Return", "the", "right", "endpoints", "of", "each", "Interval", "in", "the", "IntervalArray", "as", "an", "Index." ]
def right(self): from pandas import Index return Index(self._right, copy=False)
['def', 'right(self):', 'from', 'pandas', 'import', 'Index', 'return', 'Index(self._right,', 'copy=False)']
452,805
googleapis/python-aiplatform
study_config.py
StudyConfig.from_proto
from_proto
Converts a StudyConfig proto to a StudyConfig object.
[ "Converts", "a", "StudyConfig", "proto", "to", "a", "StudyConfig", "object." ]
def from_proto(cls, proto: study_pb2.StudySpec) -> 'StudyConfig': metric_information = MetricsConfig(sorted([MetricInformationConverter.from_proto(m) for m in proto.metrics], key=lambda x: x.name)) oneof_name = proto._pb.WhichOneof('automated_stopping_spec') if not oneof_name: automated_stopping_con...
['def', 'from_proto(cls,', 'proto:', 'study_pb2.StudySpec)', '->', "'StudyConfig':", 'metric_information', '=', 'MetricsConfig(sorted([MetricInformationConverter.from_proto(m)', 'for', 'm', 'in', 'proto.metrics],', 'key=lambda', 'x:', 'x.name))', 'oneof_name', '=', "proto._pb.WhichOneof('automated_stopping_spec')", 'if...
810,300
Farama-Foundation/MO-Gymnasium
setup.py
get_version
get_version
Gets the mo-gymnasium version.
[ "Gets", "the", "mo-gymnasium", "version." ]
def get_version(): path = CWD / 'mo_gymnasium' / '__init__.py' content = path.read_text() for line in content.splitlines(): if line.startswith('__version__'): return line.strip().split()[-1].strip().strip('"') raise RuntimeError('bad version data in __init__.py')
['def', 'get_version():', 'path', '=', 'CWD', '/', "'mo_gymnasium'", '/', "'__init__.py'", 'content', '=', 'path.read_text()', 'for', 'line', 'in', 'content.splitlines():', 'if', "line.startswith('__version__'):", 'return', 'line.strip().split()[-1].strip().strip(\'"\')', 'raise', "RuntimeError('bad", 'version', 'data'...
626,078
instadeepai/jumanji
random.py
make_random_policy_snake
make_random_policy_snake
Make random policy for the `Snake` environment.
[ "Make", "random", "policy", "for", "the", "`Snake`", "environment." ]
def make_random_policy_snake() -> RandomPolicy: return masked_categorical_random
['def', 'make_random_policy_snake()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random']
594,636
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
baseball.py
summary
summary
Return summarized statistics for each of the ``sites`` in the traces corresponding to the approximate posterior.
[ "Return", "summarized", "statistics", "for", "each", "of", "the", "``sites``", "in", "the", "traces", "corresponding", "to", "the", "approximate", "posterior." ]
def summary(traces, sites, player_names, transforms={}): marginal = EmpiricalMarginal(traces, sites).get_samples_and_weights()[0].numpy() site_stats = {} for i in range(marginal.shape[1]): site_name = sites[i] marginal_site = marginal[:, i] if site_name in transforms: mar...
['def', 'summary(traces,', 'sites,', 'player_names,', 'transforms={}):', 'marginal', '=', 'EmpiricalMarginal(traces,', 'sites).get_samples_and_weights()[0].numpy()', 'site_stats', '=', '{}', 'for', 'i', 'in', 'range(marginal.shape[1]):', 'site_name', '=', 'sites[i]', 'marginal_site', '=', 'marginal[:,', 'i]', 'if', 'si...
9,122
adamshamsudeen/vision.ai
test.py
Client.head
head
Like open but method is enforced to HEAD.
[ "Like", "open", "but", "method", "is", "enforced", "to", "HEAD." ]
def head(self, *args, **kw): kw['method'] = 'HEAD' return self.open(*args, **kw)
['def', 'head(self,', '*args,', '**kw):', "kw['method']", '=', "'HEAD'", 'return', 'self.open(*args,', '**kw)']
944,558
chribsen/simple-machine-learning-examples
misc_util.py
mingw32
mingw32
Return true when using mingw32 environment.
[ "Return", "true", "when", "using", "mingw32", "environment." ]
def mingw32(): if sys.platform == 'win32': if os.environ.get('OSTYPE', '') == 'msys': return True if os.environ.get('MSYSTEM', '') == 'MINGW32': return True return False
['def', 'mingw32():', 'if', 'sys.platform', '==', "'win32':", 'if', "os.environ.get('OSTYPE',", "'')", '==', "'msys':", 'return', 'True', 'if', "os.environ.get('MSYSTEM',", "'')", '==', "'MINGW32':", 'return', 'True', 'return', 'False']
935,293
akshitsarin/Udacity-AI-Nanodegree
logic.py
KB.ask
ask
Return a substitution that makes the query true, or, failing that, return False.
[ "Return", "a", "substitution", "that", "makes", "the", "query", "true,", "or,", "failing", "that,", "return", "False." ]
def ask(self, query): return first(self.ask_generator(query), default=False)
['def', 'ask(self,', 'query):', 'return', 'first(self.ask_generator(query),', 'default=False)']
427,401
rudranil723/mini-main
test_collections.py
generate_EventCollection_plot
generate_EventCollection_plot
Generate the initial collection and plot it.
[ "Generate", "the", "initial", "collection", "and", "plot", "it." ]
def generate_EventCollection_plot(): positions = np.array([0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0]) extra_positions = np.array([34.0, 55.0, 89.0]) orientation = 'horizontal' lineoffset = 1 linelength = 0.5 linewidth = 2 color = [1, 0, 0, 1] linestyle = 'solid' antialiased = True ...
['def', 'generate_EventCollection_plot():', 'positions', '=', 'np.array([0.0,', '1.0,', '2.0,', '3.0,', '5.0,', '8.0,', '13.0,', '21.0])', 'extra_positions', '=', 'np.array([34.0,', '55.0,', '89.0])', 'orientation', '=', "'horizontal'", 'lineoffset', '=', '1', 'linelength', '=', '0.5', 'linewidth', '=', '2', 'color', '...
320,210
tensorflow/agents
nest_utils_test.py
NestedArraysTest.zeros_from_spec
zeros_from_spec
Return arrays matching spec with desired additional dimensions.
[ "Return", "arrays", "matching", "spec", "with", "desired", "additional", "dimensions." ]
def zeros_from_spec(self, specs, outer_dims=None): outer_dims = outer_dims or [] def _zeros(spec): return np.zeros(type(spec.shape)(outer_dims) + spec.shape, spec.dtype) return tf.nest.map_structure(_zeros, specs)
['def', 'zeros_from_spec(self,', 'specs,', 'outer_dims=None):', 'outer_dims', '=', 'outer_dims', 'or', '[]', 'def', '_zeros(spec):', 'return', 'np.zeros(type(spec.shape)(outer_dims)', '+', 'spec.shape,', 'spec.dtype)', 'return', 'tf.nest.map_structure(_zeros,', 'specs)']
23,868
mariacer/cl_in_rnns
module_wrappers.py
CLHyperNetInterface.has_theta
has_theta
Getter for read-only attribute has_theta.
[ "Getter", "for", "read-only", "attribute", "has_theta." ]
def has_theta(self): return self._theta is not None
['def', 'has_theta(self):', 'return', 'self._theta', 'is', 'not', 'None']
123,078
tobegit3hub/deep_image_model
dnn_linear_combined_test.py
DNNLinearCombinedClassifierTest.testExport
testExport
Tests export model for servo.
[ "Tests", "export", "model", "for", "servo." ]
def testExport(self): def input_fn(): return ({'age': tf.constant([1]), 'language': tf.SparseTensor(values=['english'], indices=[[0, 0]], shape=[1, 1])}, tf.constant([[1]])) language = tf.contrib.layers.sparse_column_with_hash_bucket('language', 100) classifier = tf.contrib.learn.DNNLinearCombinedC...
['def', 'testExport(self):', 'def', 'input_fn():', 'return', "({'age':", 'tf.constant([1]),', "'language':", "tf.SparseTensor(values=['english'],", 'indices=[[0,', '0]],', 'shape=[1,', '1])},', 'tf.constant([[1]]))', 'language', '=', "tf.contrib.layers.sparse_column_with_hash_bucket('language',", '100)', 'classifier', ...
181,672
openvinotoolkit/training_extensions
configurer.py
BaseConfigurer.configure_data_pipeline
configure_data_pipeline
Configuration data pipeline settings.
[ "Configuration", "data", "pipeline", "settings." ]
def configure_data_pipeline(self, cfg, input_size, model_ckpt_path, **kwargs): patch_color_conversion(cfg) self.configure_input_size(cfg, input_size, model_ckpt_path)
['def', 'configure_data_pipeline(self,', 'cfg,', 'input_size,', 'model_ckpt_path,', '**kwargs):', 'patch_color_conversion(cfg)', 'self.configure_input_size(cfg,', 'input_size,', 'model_ckpt_path)']
917,775
triaquae/triaquae
defaultfilters.py
default
default
If value is unavailable, use given default.
[ "If", "value", "is", "unavailable,", "use", "given", "default." ]
def default(value, arg): return value or arg
['def', 'default(value,', 'arg):', 'return', 'value', 'or', 'arg']
423,850
0xangelo/raylab
trainer.py
SVGInfTrainer.validate_config
validate_config
Assert configuration values are valid.
[ "Assert", "configuration", "values", "are", "valid." ]
def validate_config(self, config: dict): super().validate_config(config) assert config['num_workers'] == 0, 'No point in using additional workers.' assert config['rollout_fragment_length'] >= 1, 'At least one sample must be collected.' assert config['batch_mode'] == 'complete_episodes', 'SVG(inf) uses f...
['def', 'validate_config(self,', 'config:', 'dict):', 'super().validate_config(config)', 'assert', "config['num_workers']", '==', '0,', "'No", 'point', 'in', 'using', 'additional', "workers.'", 'assert', "config['rollout_fragment_length']", '>=', '1,', "'At", 'least', 'one', 'sample', 'must', 'be', "collected.'", 'asse...
848,258
aws/sagemaker-python-sdk
processing.py
ProcessingJob.from_processing_name
from_processing_name
Initializes a ``ProcessingJob`` from a processing job name.
[ "Initializes", "a", "``ProcessingJob``", "from", "a", "processing", "job", "name." ]
def from_processing_name(cls, sagemaker_session, processing_job_name): job_desc = sagemaker_session.describe_processing_job(job_name=processing_job_name) inputs = None if job_desc.get('ProcessingInputs'): inputs = [ProcessingInput(input_name=processing_input['InputName'], s3_input=S3Input.from_boto(...
['def', 'from_processing_name(cls,', 'sagemaker_session,', 'processing_job_name):', 'job_desc', '=', 'sagemaker_session.describe_processing_job(job_name=processing_job_name)', 'inputs', '=', 'None', 'if', "job_desc.get('ProcessingInputs'):", 'inputs', '=', "[ProcessingInput(input_name=processing_input['InputName'],", "...
829,554
zihuitang/medical_AI_platform
events.py
AbstractEventLoop.run_forever
run_forever
Run the event loop until stop() is called.
[ "Run", "the", "event", "loop", "until", "stop()", "is", "called." ]
def run_forever(self): raise NotImplementedError
['def', 'run_forever(self):', 'raise', 'NotImplementedError']
282,059
KalleHallden/InstaAutomator
_tifffile.py
TiffFile.is_bigtiff
is_bigtiff
File has BigTIFF format.
[ "File", "has", "BigTIFF", "format." ]
def is_bigtiff(self): return self.offset_size != 4
['def', 'is_bigtiff(self):', 'return', 'self.offset_size', '!=', '4']
242,547
hobson/aima
text.py
viterbi_segment
viterbi_segment
Find the best segmentation of the string of characters, given the UnigramTextModel P.
[ "Find", "the", "best", "segmentation", "of", "the", "string", "of", "characters,", "given", "the", "UnigramTextModel", "P." ]
def viterbi_segment(text, P): n = len(text) words = [''] + list(text) best = [1.0] + [0.0] * n for i in range(n + 1): for j in range(0, i): w = text[j:i] if P[w] * best[i - len(w)] >= best[i]: best[i] = P[w] * best[i - len(w)] words[i] = w ...
['def', 'viterbi_segment(text,', 'P):', 'n', '=', 'len(text)', 'words', '=', "['']", '+', 'list(text)', 'best', '=', '[1.0]', '+', '[0.0]', '*', 'n', 'for', 'i', 'in', 'range(n', '+', '1):', 'for', 'j', 'in', 'range(0,', 'i):', 'w', '=', 'text[j:i]', 'if', 'P[w]', '*', 'best[i', '-', 'len(w)]', '>=', 'best[i]:', 'best[...
86,227
amiralansary/rl-medical
detectPlanePlayerCardio.py
MedicalPlayer.step
step
The environment's step function returns exactly what we need.
[ "The", "environment's", "step", "function", "returns", "exactly", "what", "we", "need." ]
def step(self, act, qvalues): self.terminal = False self._qvalues = qvalues current_plane_params = np.copy(self._plane.params) next_plane_params = current_plane_params.copy() if act == 0: next_plane_params[0] += self.action_angle_step if act == 1: next_plane_params[1] += self.act...
['def', 'step(self,', 'act,', 'qvalues):', 'self.terminal', '=', 'False', 'self._qvalues', '=', 'qvalues', 'current_plane_params', '=', 'np.copy(self._plane.params)', 'next_plane_params', '=', 'current_plane_params.copy()', 'if', 'act', '==', '0:', 'next_plane_params[0]', '+=', 'self.action_angle_step', 'if', 'act', '=...
860,744
bigdata-ustc/EduNLP
base.py
PreProcessingPipeline.pipeline
pipeline
Get the processing pipeline consisting of (name, component) tuples.
[ "Get", "the", "processing", "pipeline", "consisting", "of", "(name,", "component)", "tuples." ]
def pipeline(self): return [(name, self._preproc_components[name]) for name in self.component_pipeline]
['def', 'pipeline(self):', 'return', '[(name,', 'self._preproc_components[name])', 'for', 'name', 'in', 'self.component_pipeline]']
548,323
llSourcell/AI_Artist
package_index.py
htmldecode
htmldecode
Decode HTML entities in the given text.
[ "Decode", "HTML", "entities", "in", "the", "given", "text." ]
def htmldecode(text): return entity_sub(decode_entity, text)
['def', 'htmldecode(text):', 'return', 'entity_sub(decode_entity,', 'text)']
414,355
Ruturaj123/Flowchart-Detection
student_t.py
StudentT.scale
scale
Scaling factors of these Student's t distribution(s).
[ "Scaling", "factors", "of", "these", "Student's", "t", "distribution(s)." ]
def scale(self): return self._scale
['def', 'scale(self):', 'return', 'self._scale']
606,285
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
conftest.py
dtype
dtype
A fixture providing the ExtensionDtype to validate.
[ "A", "fixture", "providing", "the", "ExtensionDtype", "to", "validate." ]
def dtype(): raise NotImplementedError
['def', 'dtype():', 'raise', 'NotImplementedError']
83,377
jimtin/Stock_Comparison
management.py
UniqueTermManager.client_disconnected
client_disconnected
Send terminal SIGHUP when client disconnects.
[ "Send", "terminal", "SIGHUP", "when", "client", "disconnects." ]
def client_disconnected(self, websocket): self.log.info('Websocket closed, sending SIGHUP to terminal.') if websocket.terminal: websocket.terminal.kill(signal.SIGHUP)
['def', 'client_disconnected(self,', 'websocket):', "self.log.info('Websocket", 'closed,', 'sending', 'SIGHUP', 'to', "terminal.')", 'if', 'websocket.terminal:', 'websocket.terminal.kill(signal.SIGHUP)']
358,967
flow-project/flow
traci.py
TraCIVehicle.set_lane_tailways
set_lane_tailways
Set the lane tailways of the specified vehicle.
[ "Set", "the", "lane", "tailways", "of", "the", "specified", "vehicle." ]
def set_lane_tailways(self, veh_id, lane_tailways): self.__vehicles[veh_id]['lane_tailways'] = lane_tailways
['def', 'set_lane_tailways(self,', 'veh_id,', 'lane_tailways):', "self.__vehicles[veh_id]['lane_tailways']", '=', 'lane_tailways']
212,230
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pathlib.py
PurePath.with_name
with_name
Return a new path with the file name changed.
[ "Return", "a", "new", "path", "with", "the", "file", "name", "changed." ]
def with_name(self, name): if not self.name: raise ValueError('%r has an empty name' % (self,)) (drv, root, parts) = self._flavour.parse_parts((name,)) if not name or name[-1] in [self._flavour.sep, self._flavour.altsep] or drv or root or (len(parts) != 1): raise ValueError('Invalid name %r'...
['def', 'with_name(self,', 'name):', 'if', 'not', 'self.name:', 'raise', "ValueError('%r", 'has', 'an', 'empty', "name'", '%', '(self,))', '(drv,', 'root,', 'parts)', '=', 'self._flavour.parse_parts((name,))', 'if', 'not', 'name', 'or', 'name[-1]', 'in', '[self._flavour.sep,', 'self._flavour.altsep]', 'or', 'drv', 'or'...
429,055
ucbdrive/few-shot-object-detection
model_zoo.py
get_config_file
get_config_file
Returns path to a builtin config file.
[ "Returns", "path", "to", "a", "builtin", "config", "file." ]
def get_config_file(config_path): cfg_file = pkg_resources.resource_filename('fsdet', os.path.join('..', 'configs', config_path)) if not os.path.exists(cfg_file): raise RuntimeError('{} not available in Model Zoo!'.format(config_path)) return cfg_file
['def', 'get_config_file(config_path):', 'cfg_file', '=', "pkg_resources.resource_filename('fsdet',", "os.path.join('..',", "'configs',", 'config_path))', 'if', 'not', 'os.path.exists(cfg_file):', 'raise', "RuntimeError('{}", 'not', 'available', 'in', 'Model', "Zoo!'.format(config_path))", 'return', 'cfg_file']
582,497
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_007b.py
MultiBatchRNNCore.concat
concat
Concatenates the arrays along the batch dimension.
[ "Concatenates", "the", "arrays", "along", "the", "batch", "dimension." ]
def concat(self, arrs: Collection[Tensor]) -> Tensor: return [torch.cat([l[si] for l in arrs]) for si in range(len(arrs[0]))]
['def', 'concat(self,', 'arrs:', 'Collection[Tensor])', '->', 'Tensor:', 'return', '[torch.cat([l[si]', 'for', 'l', 'in', 'arrs])', 'for', 'si', 'in', 'range(len(arrs[0]))]']
81,748
rwth-i6/returnn
util.py
check_graphs
check_graphs
Check that all the element in args belong to the same graph.
[ "Check", "that", "all", "the", "element", "in", "args", "belong", "to", "the", "same", "graph." ]
def check_graphs(*args): graph = None for (i, sgv) in enumerate(args): if graph is None and sgv.graph is not None: graph = sgv.graph elif sgv.graph is not None and sgv.graph is not graph: raise ValueError('Argument[{}]: Wrong graph!'.format(i))
['def', 'check_graphs(*args):', 'graph', '=', 'None', 'for', '(i,', 'sgv)', 'in', 'enumerate(args):', 'if', 'graph', 'is', 'None', 'and', 'sgv.graph', 'is', 'not', 'None:', 'graph', '=', 'sgv.graph', 'elif', 'sgv.graph', 'is', 'not', 'None', 'and', 'sgv.graph', 'is', 'not', 'graph:', 'raise', "ValueError('Argument[{}]:...
346,651
clovaai/assembled-cnn
data_util.py
float_feature
float_feature
Wrapper for inserting floats features into Example proto.
[ "Wrapper", "for", "inserting", "floats", "features", "into", "Example", "proto." ]
def float_feature(values): if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(float_list=tf.train.FloatList(value=values))
['def', 'float_feature(values):', 'if', 'not', 'isinstance(values,', '(tuple,', 'list)):', 'values', '=', '[values]', 'return', 'tf.train.Feature(float_list=tf.train.FloatList(value=values))']
92,511
facebookresearch/CompilerGym
loop_tool_sweep.py
run_one_sweep
run_one_sweep
Run a single sweep.
[ "Run", "a", "single", "sweep." ]
def run_one_sweep(device: str, k: int, vectorize: int=1, linear: bool=False, logdir: Optional[Path]=None): logdir = logdir or create_user_logs_dir('loop_tool_sweep') logfile = logdir / f"k{k}-v{vectorize}-{device}-{('linear' if linear else 'log')}.txt" print('Logging results to', logfile) print() pr...
['def', 'run_one_sweep(device:', 'str,', 'k:', 'int,', 'vectorize:', 'int=1,', 'linear:', 'bool=False,', 'logdir:', 'Optional[Path]=None):', 'logdir', '=', 'logdir', 'or', "create_user_logs_dir('loop_tool_sweep')", 'logfile', '=', 'logdir', '/', 'f"k{k}-v{vectorize}-{device}-{(\'linear\'', 'if', 'linear', 'else', '\'lo...
125,631
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
__init__.py
VersionControl.get_requirement_revision
get_requirement_revision
Return the revision string that should be used in a requirement.
[ "Return", "the", "revision", "string", "that", "should", "be", "used", "in", "a", "requirement." ]
def get_requirement_revision(cls, repo_dir): return cls.get_revision(repo_dir)
['def', 'get_requirement_revision(cls,', 'repo_dir):', 'return', 'cls.get_revision(repo_dir)']
950,186
43Carrig/recurrent_neural_networks_practice
util.py
get_generating_ops
get_generating_ops
Return all the generating ops of the tensors in `ts`.
[ "Return", "all", "the", "generating", "ops", "of", "the", "tensors", "in", "`ts`." ]
def get_generating_ops(ts): ts = make_list_of_t(ts, allow_graph=False) return [t.op for t in ts]
['def', 'get_generating_ops(ts):', 'ts', '=', 'make_list_of_t(ts,', 'allow_graph=False)', 'return', '[t.op', 'for', 't', 'in', 'ts]']
313,281
Trusted-AI/AIX360
nncontrastive.py
NearestNeighborContrastiveExplainer.set_exemplars
set_exemplars
Set user provided exemplars to guide contrastive exploration.
[ "Set", "user", "provided", "exemplars", "to", "guide", "contrastive", "exploration." ]
def set_exemplars(self, x: Union[pd.DataFrame, np.ndarray]): if not self.is_fitted: raise RuntimeError(f'Error: exemplar can only be set post model fitting!') x = np.asarray(x) if self.model is not None: classes = self.model(x) classes = np.array(classes, dtype=int).reshape(-1) ...
['def', 'set_exemplars(self,', 'x:', 'Union[pd.DataFrame,', 'np.ndarray]):', 'if', 'not', 'self.is_fitted:', 'raise', "RuntimeError(f'Error:", 'exemplar', 'can', 'only', 'be', 'set', 'post', 'model', "fitting!')", 'x', '=', 'np.asarray(x)', 'if', 'self.model', 'is', 'not', 'None:', 'classes', '=', 'self.model(x)', 'cla...
413,289
google-research/scenic
ssv2_B16_baseline.py
get_config
get_config
Return the config of baseline experiment on Something-Something v2.
[ "Return", "the", "config", "of", "baseline", "experiment", "on", "Something-Something", "v2." ]
def get_config(runlocal=''): runlocal = bool(runlocal) config = ml_collections.ConfigDict() config.experiment_name = 'ssv2_B16_baseline' config.dataset_name = 'objects_video_tfrecord_dataset' config.dataset_configs = ml_collections.ConfigDict() config.data_dtype_str = 'float32' config.datase...
['def', "get_config(runlocal=''):", 'runlocal', '=', 'bool(runlocal)', 'config', '=', 'ml_collections.ConfigDict()', 'config.experiment_name', '=', "'ssv2_B16_baseline'", 'config.dataset_name', '=', "'objects_video_tfrecord_dataset'", 'config.dataset_configs', '=', 'ml_collections.ConfigDict()', 'config.data_dtype_str'...
847,136
sconlyshootery/FeatDepth
transformations.py
Arcball.constrain
constrain
Set state of constrain to axis mode.
[ "Set", "state", "of", "constrain", "to", "axis", "mode." ]
def constrain(self, value): self._constrain = bool(value)
['def', 'constrain(self,', 'value):', 'self._constrain', '=', 'bool(value)']
179,566
rudranil723/mini-main
makepy.py
GetTypeLibsForSpec
GetTypeLibsForSpec
Given an argument on the command line (either a file name, library description, or ProgID of an object) return a list of actual typelibs to use.
[ "Given", "an", "argument", "on", "the", "command", "line", "(either", "a", "file", "name,", "library", "description,", "or", "ProgID", "of", "an", "object)", "return", "a", "list", "of", "actual", "typelibs", "to", "use." ]
def GetTypeLibsForSpec(arg): typelibs = [] try: try: tlb = pythoncom.LoadTypeLib(arg) spec = selecttlb.TypelibSpec(None, 0, 0, 0) spec.FromTypelib(tlb, arg) typelibs.append((tlb, spec)) except pythoncom.com_error: tlbs = selecttlb.FindT...
['def', 'GetTypeLibsForSpec(arg):', 'typelibs', '=', '[]', 'try:', 'try:', 'tlb', '=', 'pythoncom.LoadTypeLib(arg)', 'spec', '=', 'selecttlb.TypelibSpec(None,', '0,', '0,', '0)', 'spec.FromTypelib(tlb,', 'arg)', 'typelibs.append((tlb,', 'spec))', 'except', 'pythoncom.com_error:', 'tlbs', '=', 'selecttlb.FindTlbsWithDes...
271,176
ForrestPi/ObjectDetectionTricks
adaptive.py
AdaptiveImageLossFunction.df
df
Returns an image of degrees of freedom, for the Student's T model.
[ "Returns", "an", "image", "of", "degrees", "of", "freedom,", "for", "the", "Student's", "T", "model." ]
def df(self): assert self.use_students_t return torch.reshape(self.adaptive_lossfun.df(), self.image_size)
['def', 'df(self):', 'assert', 'self.use_students_t', 'return', 'torch.reshape(self.adaptive_lossfun.df(),', 'self.image_size)']
744,641
deepmind/dm_control
pendulum.py
swingup
swingup
Returns pendulum swingup task .
[ "Returns", "pendulum", "swingup", "task", "." ]
def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): physics = Physics.from_xml_string(*get_model_and_assets()) task = SwingUp(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, **environment_kwargs)
['def', 'swingup(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'SwingUp(random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'return', 'control.Environment(physics,', 'task,', 'time...
166,420
dustin/twitty-twister
test_streaming.py
LengthDelimitedStreamTest.test_receiveDatagram
test_receiveDatagram
A datagram is a length, CRLF and a sequence of bytes of given length.
[ "A", "datagram", "is", "a", "length,", "CRLF", "and", "a", "sequence", "of", "bytes", "of", "given", "length." ]
def test_receiveDatagram(self): self.protocol.dataReceived('4\r\ntest') self.assertEquals(['test'], self.protocol.datagrams) self.assertEquals(0, self.protocol.keepAlives)
['def', 'test_receiveDatagram(self):', "self.protocol.dataReceived('4\\r\\ntest')", "self.assertEquals(['test'],", 'self.protocol.datagrams)', 'self.assertEquals(0,', 'self.protocol.keepAlives)']
426,480
ryu-ed/SpaceInvaders_Ros
test_rotation_groups.py
test_tetrahedral
test_tetrahedral
Test that the tetrahedral group correctly fixes the rotations of a tetrahedron.
[ "Test", "that", "the", "tetrahedral", "group", "correctly", "fixes", "the", "rotations", "of", "a", "tetrahedron." ]
def test_tetrahedral(): P = _generate_tetrahedron() for g in Rotation.create_group('T'): assert _calculate_rmsd(P, g.apply(P)) < TOL
['def', 'test_tetrahedral():', 'P', '=', '_generate_tetrahedron()', 'for', 'g', 'in', "Rotation.create_group('T'):", 'assert', '_calculate_rmsd(P,', 'g.apply(P))', '<', 'TOL']
371,117
scottemmons/rvs
dataset.py
AbstractDataModule.val_dataloader
val_dataloader
Make the validation dataloader.
[ "Make", "the", "validation", "dataloader." ]
def val_dataloader(self) -> data.DataLoader: return data.DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers, generator=self.generator, worker_init_fn=seed_worker)
['def', 'val_dataloader(self)', '->', 'data.DataLoader:', 'return', 'data.DataLoader(self.data_val,', 'batch_size=self.batch_size,', 'num_workers=self.num_workers,', 'generator=self.generator,', 'worker_init_fn=seed_worker)']
326,977
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_input_test.py
CIFAR10InputTest.testRead
testRead
Tests if the records are read in the expected order and value.
[ "Tests", "if", "the", "records", "are", "read", "in", "the", "expected", "order", "and", "value." ]
def testRead(self): labels = [0, 1, 9] colors = [[0, 0, 0], [255, 255, 255], [1, 100, 253]] records = [] expecteds = [] for i in range(3): (record, expected) = self._record(labels[i], colors[i]) records.append(record) expecteds.append(expected) filename = os.path.join(sel...
['def', 'testRead(self):', 'labels', '=', '[0,', '1,', '9]', 'colors', '=', '[[0,', '0,', '0],', '[255,', '255,', '255],', '[1,', '100,', '253]]', 'records', '=', '[]', 'expecteds', '=', '[]', 'for', 'i', 'in', 'range(3):', '(record,', 'expected)', '=', 'self._record(labels[i],', 'colors[i])', 'records.append(record)',...
46,875
enuguru/artificial_intelligence_and_machine_learning
log.py
InstanceLogger.info
info
Delegate an info call to the underlying logger.
[ "Delegate", "an", "info", "call", "to", "the", "underlying", "logger." ]
def info(self, msg, *args, **kwargs): self.log(logging.INFO, msg, *args, **kwargs)
['def', 'info(self,', 'msg,', '*args,', '**kwargs):', 'self.log(logging.INFO,', 'msg,', '*args,', '**kwargs)']
131,780
RLE-Foundation/rllte
sac.py
SAC.update
update
Update the agent and return training metrics such as actor loss, critic_loss, etc.
[ "Update", "the", "agent", "and", "return", "training", "metrics", "such", "as", "actor", "loss,", "critic_loss,", "etc." ]
def update(self) -> Dict[str, float]: metrics = {} if self.global_step % self.update_every_steps != 0: return metrics batch = self.storage.sample() if self.irs is not None: intrinsic_rewards = self.irs.compute_irs(samples={'obs': batch.observations, 'actions': batch.actions, 'next_obs': ...
['def', 'update(self)', '->', 'Dict[str,', 'float]:', 'metrics', '=', '{}', 'if', 'self.global_step', '%', 'self.update_every_steps', '!=', '0:', 'return', 'metrics', 'batch', '=', 'self.storage.sample()', 'if', 'self.irs', 'is', 'not', 'None:', 'intrinsic_rewards', '=', "self.irs.compute_irs(samples={'obs':", 'batch.o...
333,219
arshpreetsingh/quantopian-machinelearning
buffer.py
Buffer.join_selected_lines
join_selected_lines
Join the selected lines.
[ "Join", "the", "selected", "lines." ]
def join_selected_lines(self, separator=' '): assert self.selection_state (from_, to) = sorted([self.cursor_position, self.selection_state.original_cursor_position]) before = self.text[:from_] lines = self.text[from_:to].splitlines() after = self.text[to:] lines = [l.lstrip(' ') + separator for ...
['def', 'join_selected_lines(self,', "separator='", "'):", 'assert', 'self.selection_state', '(from_,', 'to)', '=', 'sorted([self.cursor_position,', 'self.selection_state.original_cursor_position])', 'before', '=', 'self.text[:from_]', 'lines', '=', 'self.text[from_:to].splitlines()', 'after', '=', 'self.text[to:]', 'l...
891,984
43Carrig/recurrent_neural_networks_practice
descriptor_pool.py
DescriptorPool.FindFileByName
FindFileByName
Gets a FileDescriptor by file name.
[ "Gets", "a", "FileDescriptor", "by", "file", "name." ]
def FindFileByName(self, file_name): try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileBy...
['def', 'FindFileByName(self,', 'file_name):', 'try:', 'return', 'self._file_descriptors[file_name]', 'except', 'KeyError:', 'pass', 'try:', 'file_proto', '=', 'self._internal_db.FindFileByName(file_name)', 'except', 'KeyError', 'as', 'error:', 'if', 'self._descriptor_db:', 'file_proto', '=', 'self._descriptor_db.FindF...
309,813
voxel51/fiftyone
dataset.py
Dataset.deleted
deleted
Whether the dataset is deleted.
[ "Whether", "the", "dataset", "is", "deleted." ]
def deleted(self): return self._deleted
['def', 'deleted(self):', 'return', 'self._deleted']
582,877
myothida/Supervised-Machine-Learning
categorical.py
_ViolinPlotter.scale_width
scale_width
Scale each density curve to the same height.
[ "Scale", "each", "density", "curve", "to", "the", "same", "height." ]
def scale_width(self, density): if self.hue_names is None: for d in density: d /= d.max() else: for group in density: for d in group: d /= d.max()
['def', 'scale_width(self,', 'density):', 'if', 'self.hue_names', 'is', 'None:', 'for', 'd', 'in', 'density:', 'd', '/=', 'd.max()', 'else:', 'for', 'group', 'in', 'density:', 'for', 'd', 'in', 'group:', 'd', '/=', 'd.max()']
446,673
tonybeltramelli/Graphics-And-Vision
OpenCV3D.py
OpenCV3D.Clear
Clear
Empty all internal parameters used for this class.
[ "Empty", "all", "internal", "parameters", "used", "for", "this", "class." ]
def Clear(self): self.hasFundamentalMatrix = self.IsCalibrating = self.IsSaving = self.IsFrozen = False self.PointsQueue = deque(maxlen=16)
['def', 'Clear(self):', 'self.hasFundamentalMatrix', '=', 'self.IsCalibrating', '=', 'self.IsSaving', '=', 'self.IsFrozen', '=', 'False', 'self.PointsQueue', '=', 'deque(maxlen=16)']
580,662
ryu-ed/SpaceInvaders_Ros
mask_test.py
MaskTypeTest.test_invert__empty
test_invert__empty
Ensure an empty mask can be inverted.
[ "Ensure", "an", "empty", "mask", "can", "be", "inverted." ]
def test_invert__empty(self): (width, height) = (43, 97) expected_size = (width, height) expected_count = width * height mask = pygame.mask.Mask(expected_size) mask.invert() self.assertEqual(mask.count(), expected_count) self.assertEqual(mask.get_size(), expected_size)
['def', 'test_invert__empty(self):', '(width,', 'height)', '=', '(43,', '97)', 'expected_size', '=', '(width,', 'height)', 'expected_count', '=', 'width', '*', 'height', 'mask', '=', 'pygame.mask.Mask(expected_size)', 'mask.invert()', 'self.assertEqual(mask.count(),', 'expected_count)', 'self.assertEqual(mask.get_size(...
369,034
bnpy/bnpy
TestKMeans_Naive.py
Test.tearDown
tearDown
Shut down all the workers.
[ "Shut", "down", "all", "the", "workers." ]
def tearDown(self): self.shutdownWorkers() time.sleep(0.1)
['def', 'tearDown(self):', 'self.shutdownWorkers()', 'time.sleep(0.1)']
465,527
openkinome/kinoml
test_oemodeling.py
test_read_molecules
test_read_molecules
Compare results to expected number of read molecules as well as atoms of each interpreted molecule.
[ "Compare", "results", "to", "expected", "number", "of", "read", "molecules", "as", "well", "as", "atoms", "of", "each", "interpreted", "molecule." ]
def test_read_molecules(package, resource, add_hydrogens, expectation, n_atoms_list): with resources.path(package, resource) as path: with expectation: molecules = read_molecules(str(path), add_hydrogens) assert len(molecules) == len(n_atoms_list) for (molecule, n_atmos) ...
['def', 'test_read_molecules(package,', 'resource,', 'add_hydrogens,', 'expectation,', 'n_atoms_list):', 'with', 'resources.path(package,', 'resource)', 'as', 'path:', 'with', 'expectation:', 'molecules', '=', 'read_molecules(str(path),', 'add_hydrogens)', 'assert', 'len(molecules)', '==', 'len(n_atoms_list)', 'for', '...
596,282
STHSF/DeepNaturalLanguageProcessing
data_utils.py
get_processing_word
get_processing_word
Return lambda function that transform a word (string) into list, or tuple of (list, id) of int corresponding to the ids of the word and its corresponding characters.
[ "Return", "lambda", "function", "that", "transform", "a", "word", "(string)", "into", "list,", "or", "tuple", "of", "(list,", "id)", "of", "int", "corresponding", "to", "the", "ids", "of", "the", "word", "and", "its", "corresponding", "characters." ]
def get_processing_word(vocab_words=None, vocab_chars=None, lowercase=False, chars=False, allow_unk=True): def f(word): if vocab_chars is not None and chars == True: char_ids = [] for char in word: if char in vocab_chars: char_ids += [vocab_chars[...
['def', 'get_processing_word(vocab_words=None,', 'vocab_chars=None,', 'lowercase=False,', 'chars=False,', 'allow_unk=True):', 'def', 'f(word):', 'if', 'vocab_chars', 'is', 'not', 'None', 'and', 'chars', '==', 'True:', 'char_ids', '=', '[]', 'for', 'char', 'in', 'word:', 'if', 'char', 'in', 'vocab_chars:', 'char_ids', '...
538,949
Farama-Foundation/Gymnasium
test_core.py
test_gymnasium_wrapper
test_gymnasium_wrapper
Tests the gymnasium wrapper works as expected.
[ "Tests", "the", "gymnasium", "wrapper", "works", "as", "expected." ]
def test_gymnasium_wrapper(): env = ExampleEnv() wrapper_env = ExampleWrapper(env) assert env.metadata == wrapper_env.metadata wrapper_env.metadata = {'render_modes': ['rgb_array']} assert env.metadata != wrapper_env.metadata assert env.render_mode == wrapper_env.render_mode assert env.rewar...
['def', 'test_gymnasium_wrapper():', 'env', '=', 'ExampleEnv()', 'wrapper_env', '=', 'ExampleWrapper(env)', 'assert', 'env.metadata', '==', 'wrapper_env.metadata', 'wrapper_env.metadata', '=', "{'render_modes':", "['rgb_array']}", 'assert', 'env.metadata', '!=', 'wrapper_env.metadata', 'assert', 'env.render_mode', '=='...
573,437
matsu0228/nlp-jp
common.py
validate_ok_for_update
validate_ok_for_update
Validate an update document.
[ "Validate", "an", "update", "document." ]
def validate_ok_for_update(update): validate_is_mapping('update', update) if not update: raise ValueError('update only works with $ operators') first = next(iter(update)) if not first.startswith('$'): raise ValueError('update only works with $ operators')
['def', 'validate_ok_for_update(update):', "validate_is_mapping('update',", 'update)', 'if', 'not', 'update:', 'raise', "ValueError('update", 'only', 'works', 'with', '$', "operators')", 'first', '=', 'next(iter(update))', 'if', 'not', "first.startswith('$'):", 'raise', "ValueError('update", 'only', 'works', 'with', '$...
804,807
gopinath-balu/computer_vision
canvas.py
Canvas.transformPos
transformPos
Convert from widget-logical coordinates to painter-logical coordinates.
[ "Convert", "from", "widget-logical", "coordinates", "to", "painter-logical", "coordinates." ]
def transformPos(self, point): return point / self.scale - self.offsetToCenter()
['def', 'transformPos(self,', 'point):', 'return', 'point', '/', 'self.scale', '-', 'self.offsetToCenter()']
474,626
Eric3911/OpenAGI
asr_module_utils.py
change_conv_asr_se_context_window
change_conv_asr_se_context_window
Update the context window of the SqueezeExcitation module if the provided model contains an `encoder` which is an instance of `ConvASREncoder`.
[ "Update", "the", "context", "window", "of", "the", "SqueezeExcitation", "module", "if", "the", "provided", "model", "contains", "an", "`encoder`", "which", "is", "an", "instance", "of", "`ConvASREncoder`." ]
def change_conv_asr_se_context_window(model: 'ASRModel', context_window: int, update_config: bool=True): if update_config and (not hasattr(model.cfg, 'encoder')): logging.info('Could not change the context window in SqueezeExcite module since the model provided does not contain an `encoder` module in its co...
['def', 'change_conv_asr_se_context_window(model:', "'ASRModel',", 'context_window:', 'int,', 'update_config:', 'bool=True):', 'if', 'update_config', 'and', '(not', 'hasattr(model.cfg,', "'encoder')):", "logging.info('Could", 'not', 'change', 'the', 'context', 'window', 'in', 'SqueezeExcite', 'module', 'since', 'the', ...
272,812
JohannesVerherstraeten/semantic-video-segmentation
basemetric.py
BaseMetric.value
value
Returns the accumulated metric value of all previous input data.
[ "Returns", "the", "accumulated", "metric", "value", "of", "all", "previous", "input", "data." ]
def value(self) -> Tuple[Optional[float], Dict]: raise NotImplementedError
['def', 'value(self)', '->', 'Tuple[Optional[float],', 'Dict]:', 'raise', 'NotImplementedError']
342,843