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
LLNL/merlin
utils.py
determine_protocol
determine_protocol
Determines a file protocol based on file name extension.
[ "Determines", "a", "file", "protocol", "based", "on", "file", "name", "extension." ]
def determine_protocol(fname): (_, ext) = os.path.splitext(fname) if ext.startswith('.'): protocol = ext.lower().strip('.') else: raise ValueError(f'{fname} needs an ext (eg .hdf5) to determine protocol!') if protocol == 'h5': protocol = 'hdf5' return protocol
['def', 'determine_protocol(fname):', '(_,', 'ext)', '=', 'os.path.splitext(fname)', 'if', "ext.startswith('.'):", 'protocol', '=', "ext.lower().strip('.')", 'else:', 'raise', "ValueError(f'{fname}", 'needs', 'an', 'ext', '(eg', '.hdf5)', 'to', 'determine', "protocol!')", 'if', 'protocol', '==', "'h5':", 'protocol', '=...
632,610
johnnyp2587/transfer-learning
retrain.py
run_final_eval
run_final_eval
Runs a final evaluation on an eval graph using the test data set.
[ "Runs", "a", "final", "evaluation", "on", "an", "eval", "graph", "using", "the", "test", "data", "set." ]
def run_final_eval(train_session, module_spec, class_count, image_lists, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor): (test_bottlenecks, test_ground_truth, test_filenames) = get_random_cached_bottlenecks(train_session, image_lists, FLAGS.test_batch_size, 'testing', FLAGS.bottlen...
['def', 'run_final_eval(train_session,', 'module_spec,', 'class_count,', 'image_lists,', 'jpeg_data_tensor,', 'decoded_image_tensor,', 'resized_image_tensor,', 'bottleneck_tensor):', '(test_bottlenecks,', 'test_ground_truth,', 'test_filenames)', '=', 'get_random_cached_bottlenecks(train_session,', 'image_lists,', 'FLAG...
928,956
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_main.py
input_fn
input_fn
Create input graph for model.
[ "Create", "input", "graph", "for", "model." ]
def input_fn(data_dir, subset, num_shards, batch_size, use_distortion_for_training=True): with tf.device('/cpu:0'): use_distortion = subset == 'train' and use_distortion_for_training dataset = cifar10.Cifar10DataSet(data_dir, subset, use_distortion) (image_batch, label_batch) = dataset.make_...
['def', 'input_fn(data_dir,', 'subset,', 'num_shards,', 'batch_size,', 'use_distortion_for_training=True):', 'with', "tf.device('/cpu:0'):", 'use_distortion', '=', 'subset', '==', "'train'", 'and', 'use_distortion_for_training', 'dataset', '=', 'cifar10.Cifar10DataSet(data_dir,', 'subset,', 'use_distortion)', '(image_b...
30,316
Megvii-BaseDetection/DynamicRouting
extend_transform.py
PadTransform.apply_coords
apply_coords
Apply pad transform on coordinates.
[ "Apply", "pad", "transform", "on", "coordinates." ]
def apply_coords(self, coords: np.ndarray) -> np.ndarray: coords[:, 0] += self.dw[0] coords[:, 1] += self.dh[0] return coords
['def', 'apply_coords(self,', 'coords:', 'np.ndarray)', '->', 'np.ndarray:', 'coords[:,', '0]', '+=', 'self.dw[0]', 'coords[:,', '1]', '+=', 'self.dh[0]', 'return', 'coords']
555,168
QData/deepWordBug
test_core.py
test_time_left
test_time_left
test '_time_left' routine returns correct positive delta difference.
[ "test", "'_time_left'", "routine", "returns", "correct", "positive", "delta", "difference." ]
def test_time_left(): from blessed.keyboard import _time_left stime = time.time() - 10 timeout = 15 result = _time_left(stime=stime, timeout=timeout) assert math.ceil(result) == 5.0
['def', 'test_time_left():', 'from', 'blessed.keyboard', 'import', '_time_left', 'stime', '=', 'time.time()', '-', '10', 'timeout', '=', '15', 'result', '=', '_time_left(stime=stime,', 'timeout=timeout)', 'assert', 'math.ceil(result)', '==', '5.0']
541,131
ChrisFugl/Intrusing-Detection-System-Attack
model.py
WGAN.predict
predict
Use discriminator to predict whether real or fake.
[ "Use", "discriminator", "to", "predict", "whether", "real", "or", "fake." ]
def predict(self, traffic): outputs = self.discriminator(traffic).squeeze() predictions = torch.empty((len(outputs),), dtype=torch.uint8) predictions[outputs < 0] = 0 predictions[outputs >= 0] = 1 return predictions.cpu().numpy()
['def', 'predict(self,', 'traffic):', 'outputs', '=', 'self.discriminator(traffic).squeeze()', 'predictions', '=', 'torch.empty((len(outputs),),', 'dtype=torch.uint8)', 'predictions[outputs', '<', '0]', '=', '0', 'predictions[outputs', '>=', '0]', '=', '1', 'return', 'predictions.cpu().numpy()']
576,444
brsynth/RetroPathRL
cli.py
worker_fire
worker_fire
Apply a reaction a rule on a chemical.
[ "Apply", "a", "reaction", "a", "rule", "on", "a", "chemical." ]
def worker_fire(kwargs): r = RuleBurnerCore(**kwargs) return r.fire()
['def', 'worker_fire(kwargs):', 'r', '=', 'RuleBurnerCore(**kwargs)', 'return', 'r.fire()']
841,037
ugr-sail/sinergym
gcloud.py
read_from_bucket
read_from_bucket
Read a file or a directory (recursively) from specified bucket to local file system.
[ "Read", "a", "file", "or", "a", "directory", "(recursively)", "from", "specified", "bucket", "to", "local", "file", "system." ]
def read_from_bucket(client, bucket_name, blob_prefix): bucket = client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=blob_prefix) for blob in blobs: if blob.name.endswith('/'): continue file_split = blob.name.split('/') directory = '/'.join(file_split[0:-1]) ...
['def', 'read_from_bucket(client,', 'bucket_name,', 'blob_prefix):', 'bucket', '=', 'client.get_bucket(bucket_name)', 'blobs', '=', 'bucket.list_blobs(prefix=blob_prefix)', 'for', 'blob', 'in', 'blobs:', 'if', "blob.name.endswith('/'):", 'continue', 'file_split', '=', "blob.name.split('/')", 'directory', '=', "'/'.join...
884,429
briannemsick/barrage
core.py
RecordAugmentor.augment
augment
Apply augmentation to a train data record.
[ "Apply", "augmentation", "to", "a", "train", "data", "record." ]
def augment(self, data_record: api.DataRecord) -> api.DataRecord: return self.augment_func(data_record)
['def', 'augment(self,', 'data_record:', 'api.DataRecord)', '->', 'api.DataRecord:', 'return', 'self.augment_func(data_record)']
94,303
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
distributions.py
gaussian_pos_log_likelihood
gaussian_pos_log_likelihood
Gaussian log-likelihood function for a posterior in VAE Note: This function is specialized for a posterior distribution, that has the form of z = mean + sigma * noise.
[ "Gaussian", "log-likelihood", "function", "for", "a", "posterior", "in", "VAE", "Note:", "This", "function", "is", "specialized", "for", "a", "posterior", "distribution,", "that", "has", "the", "form", "of", "z", "=", "mean", "+", "sigma", "*", "noise." ]
def gaussian_pos_log_likelihood(unused_mean, logvar, noise): return -0.5 * (logvar + np.log(2 * np.pi) + tf.square(noise))
['def', 'gaussian_pos_log_likelihood(unused_mean,', 'logvar,', 'noise):', 'return', '-0.5', '*', '(logvar', '+', 'np.log(2', '*', 'np.pi)', '+', 'tf.square(noise))']
49,639
jeromewang-github/computer_vision
config_util_test.py
ConfigUtilTest.testKeyValueOverrideBadKey
testKeyValueOverrideBadKey
Tests that overwriting with a bad key causes an exception.
[ "Tests", "that", "overwriting", "with", "a", "bad", "key", "causes", "an", "exception." ]
def testKeyValueOverrideBadKey(self): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() configs = self._create_and_load_test_configs(pipeline_config) hparams = tf.contrib.training.HParams(**{'train_config.no_such_field': 10}) with self.assertRaises(ValueError): config_util.merge_external_...
['def', 'testKeyValueOverrideBadKey(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'configs', '=', 'self._create_and_load_test_configs(pipeline_config)', 'hparams', '=', "tf.contrib.training.HParams(**{'train_config.no_such_field':", '10})', 'with', 'self.assertRaises(ValueError):', 'config_...
512,230
opendilab/DI-star
metrics.py
Metrics.measure_step_time
measure_step_time
Return a context manager to measure the time to perform N game steps.
[ "Return", "a", "context", "manager", "to", "measure", "the", "time", "to", "perform", "N", "game", "steps." ]
def measure_step_time(self, num_steps=1): del num_steps return _EventTimer()
['def', 'measure_step_time(self,', 'num_steps=1):', 'del', 'num_steps', 'return', '_EventTimer()']
184,701
rudranil723/mini-main
text.py
Text.append
append
Add text with an optional style.
[ "Add", "text", "with", "an", "optional", "style." ]
def append(self, text: Union['Text', str], style: Optional[Union[str, 'Style']]=None) -> 'Text': if not isinstance(text, (str, Text)): raise TypeError('Only str or Text can be appended to Text') if len(text): if isinstance(text, str): sanitized_text = strip_control_codes(text) ...
['def', 'append(self,', 'text:', "Union['Text',", 'str],', 'style:', 'Optional[Union[str,', "'Style']]=None)", '->', "'Text':", 'if', 'not', 'isinstance(text,', '(str,', 'Text)):', 'raise', "TypeError('Only", 'str', 'or', 'Text', 'can', 'be', 'appended', 'to', "Text')", 'if', 'len(text):', 'if', 'isinstance(text,', 'st...
268,993
google-research/scenic
loss.py
l2_normalize
l2_normalize
L2 normalize an input tensor.
[ "L2", "normalize", "an", "input", "tensor." ]
def l2_normalize(tensor: Array, axis: int=-1, epsilon: float=1e-06): return tensor / jnp.linalg.norm(tensor, axis=axis, keepdims=True + epsilon)
['def', 'l2_normalize(tensor:', 'Array,', 'axis:', 'int=-1,', 'epsilon:', 'float=1e-06):', 'return', 'tensor', '/', 'jnp.linalg.norm(tensor,', 'axis=axis,', 'keepdims=True', '+', 'epsilon)']
847,084
facebookresearch/detectron2
post_processing.py
get_instance_segmentation
get_instance_segmentation
Post-processing for instance segmentation, gets class agnostic instance id.
[ "Post-processing", "for", "instance", "segmentation,", "gets", "class", "agnostic", "instance", "id." ]
def get_instance_segmentation(sem_seg, center_heatmap, offsets, thing_seg, thing_ids, threshold=0.1, nms_kernel=3, top_k=None): center_points = find_instance_center(center_heatmap, threshold=threshold, nms_kernel=nms_kernel, top_k=top_k) if center_points.size(0) == 0: return (torch.zeros_like(sem_seg), ...
['def', 'get_instance_segmentation(sem_seg,', 'center_heatmap,', 'offsets,', 'thing_seg,', 'thing_ids,', 'threshold=0.1,', 'nms_kernel=3,', 'top_k=None):', 'center_points', '=', 'find_instance_center(center_heatmap,', 'threshold=threshold,', 'nms_kernel=nms_kernel,', 'top_k=top_k)', 'if', 'center_points.size(0)', '==',...
549,542
rudranil723/mini-main
maxent.py
GISEncoding.C
C
The non-negative constant that all encoded feature vectors will sum to.
[ "The", "non-negative", "constant", "that", "all", "encoded", "feature", "vectors", "will", "sum", "to." ]
def C(self): return self._C
['def', 'C(self):', 'return', 'self._C']
320,850
robustness-gym/robustness-gym
operation.py
Operation.output_names
output_names
Name of output columns created by the Operation.
[ "Name", "of", "output", "columns", "created", "by", "the", "Operation." ]
def output_names(self) -> Optional[List[str]]: return self._output_names
['def', 'output_names(self)', '->', 'Optional[List[str]]:', 'return', 'self._output_names']
826,271
flavioschneider/rl-transfer-
path_buffer.py
PathBuffer.sample_timesteps
sample_timesteps
Sample a batch of timesteps from the buffer.
[ "Sample", "a", "batch", "of", "timesteps", "from", "the", "buffer." ]
def sample_timesteps(self, batch_size): samples = self.sample_transitions(batch_size) step_types = np.array([StepType.TERMINAL if terminal else StepType.MID for terminal in samples['terminals'].reshape(-1)], dtype=StepType) return TimeStepBatch(env_spec=self._env_spec, episode_infos={}, observations=samples...
['def', 'sample_timesteps(self,', 'batch_size):', 'samples', '=', 'self.sample_transitions(batch_size)', 'step_types', '=', 'np.array([StepType.TERMINAL', 'if', 'terminal', 'else', 'StepType.MID', 'for', 'terminal', 'in', "samples['terminals'].reshape(-1)],", 'dtype=StepType)', 'return', 'TimeStepBatch(env_spec=self._e...
861,243
bfshi/TOAST
registry.py
Registry.register
register
Creates a function that registers its input.
[ "Creates", "a", "function", "that", "registers", "its", "input." ]
def register(name, item_type): if item_type not in ['function', 'class']: raise ValueError('Unknown item type: %s' % item_type) def _register(item): if name in Registry.global_registry(): raise KeyError('The name {!r} was already registered in with type {!r}'.format(name, item_type)...
['def', 'register(name,', 'item_type):', 'if', 'item_type', 'not', 'in', "['function',", "'class']:", 'raise', "ValueError('Unknown", 'item', 'type:', "%s'", '%', 'item_type)', 'def', '_register(item):', 'if', 'name', 'in', 'Registry.global_registry():', 'raise', "KeyError('The", 'name', '{!r}', 'was', 'already', 'regi...
901,663
Eric3911/OpenAGI
download.py
getfile_insensitive
getfile_insensitive
Get the actual file path when given insensitive filename.
[ "Get", "the", "actual", "file", "path", "when", "given", "insensitive", "filename." ]
def getfile_insensitive(path): (directory, filename) = os.path.split(path) (directory, filename) = (directory or '.', filename.lower()) for f in os.listdir(directory): newpath = os.path.join(directory, f) if os.path.isfile(newpath) and f.lower() == filename: return newpath
['def', 'getfile_insensitive(path):', '(directory,', 'filename)', '=', 'os.path.split(path)', '(directory,', 'filename)', '=', '(directory', 'or', "'.',", 'filename.lower())', 'for', 'f', 'in', 'os.listdir(directory):', 'newpath', '=', 'os.path.join(directory,', 'f)', 'if', 'os.path.isfile(newpath)', 'and', 'f.lower()'...
251,155
zihuitang/medical_AI_platform
paragraph.py
reformat_paragraph
reformat_paragraph
Return data reformatted to specified width (limit).
[ "Return", "data", "reformatted", "to", "specified", "width", "(limit)." ]
def reformat_paragraph(data, limit): lines = data.split('\n') i = 0 n = len(lines) while i < n and is_all_white(lines[i]): i = i + 1 if i >= n: return data indent1 = get_indent(lines[i]) if i + 1 < n and (not is_all_white(lines[i + 1])): indent2 = get_indent(lines[i +...
['def', 'reformat_paragraph(data,', 'limit):', 'lines', '=', "data.split('\\n')", 'i', '=', '0', 'n', '=', 'len(lines)', 'while', 'i', '<', 'n', 'and', 'is_all_white(lines[i]):', 'i', '=', 'i', '+', '1', 'if', 'i', '>=', 'n:', 'return', 'data', 'indent1', '=', 'get_indent(lines[i])', 'if', 'i', '+', '1', '<', 'n', 'and...
282,796
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
security.py
gen_salt
gen_salt
Generate a random string of SALT_CHARS with specified ``length``.
[ "Generate", "a", "random", "string", "of", "SALT_CHARS", "with", "specified", "``length``." ]
def gen_salt(length): if length <= 0: raise ValueError('Salt length must be positive') return ''.join((_sys_rng.choice(SALT_CHARS) for _ in range_type(length)))
['def', 'gen_salt(length):', 'if', 'length', '<=', '0:', 'raise', "ValueError('Salt", 'length', 'must', 'be', "positive')", 'return', "''.join((_sys_rng.choice(SALT_CHARS)", 'for', '_', 'in', 'range_type(length)))']
84,913
ryu-ed/SpaceInvaders_Ros
surface_test.py
SurfaceTypeTest.test_get_rect
test_get_rect
Ensure a surface's rect can be retrieved.
[ "Ensure", "a", "surface's", "rect", "can", "be", "retrieved." ]
def test_get_rect(self): size = (16, 16) surf = pygame.Surface(size) rect = surf.get_rect() self.assertEqual(rect.size, size)
['def', 'test_get_rect(self):', 'size', '=', '(16,', '16)', 'surf', '=', 'pygame.Surface(size)', 'rect', '=', 'surf.get_rect()', 'self.assertEqual(rect.size,', 'size)']
369,172
famura/SimuRLacra
step.py
StepLogger.pop_prefix
pop_prefix
Remove the last string from the key prefix stack.
[ "Remove", "the", "last", "string", "from", "the", "key", "prefix", "stack." ]
def pop_prefix(self): self._prefix_stack.pop() self._prefix_str = ''.join(self._prefix_stack)
['def', 'pop_prefix(self):', 'self._prefix_stack.pop()', 'self._prefix_str', '=', "''.join(self._prefix_stack)"]
883,794
pytorch/rl
dataset.py
create_infinite_iterator
create_infinite_iterator
Iterates indefinitely over an iterator.
[ "Iterates", "indefinitely", "over", "an", "iterator." ]
def create_infinite_iterator(iterator): while True: yield from iterator
['def', 'create_infinite_iterator(iterator):', 'while', 'True:', 'yield', 'from', 'iterator']
858,822
yinyunie/ScenePriors
transformer_builders.py
BaseTransformerBuilder.query_dimensions
query_dimensions
The dimensions of the queries and keys in each attention layer.
[ "The", "dimensions", "of", "the", "queries", "and", "keys", "in", "each", "attention", "layer." ]
def query_dimensions(self): return self._d_query
['def', 'query_dimensions(self):', 'return', 'self._d_query']
329,527
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
input.py
observation_input
observation_input
Create placeholder to feed observations into of the size appropriate to the observation space, and add input encoder of the appropriate type.
[ "Create", "placeholder", "to", "feed", "observations", "into", "of", "the", "size", "appropriate", "to", "the", "observation", "space,", "and", "add", "input", "encoder", "of", "the", "appropriate", "type." ]
def observation_input(ob_space, batch_size=None, name='Ob'): placeholder = observation_placeholder(ob_space, batch_size, name) return (placeholder, encode_observation(ob_space, placeholder))
['def', 'observation_input(ob_space,', 'batch_size=None,', "name='Ob'):", 'placeholder', '=', 'observation_placeholder(ob_space,', 'batch_size,', 'name)', 'return', '(placeholder,', 'encode_observation(ob_space,', 'placeholder))']
433,848
researchmm/WSOD2
fpn.py
FPN.init_weights
init_weights
Initialize the weights of FPN module.
[ "Initialize", "the", "weights", "of", "FPN", "module." ]
def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): xavier_init(m, distribution='uniform')
['def', 'init_weights(self):', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', 'nn.Conv2d):', 'xavier_init(m,', "distribution='uniform')"]
374,351
NVIDIA/object-detection-tensorrt-example
voc.py
is_voc_label
is_voc_label
Returns boolean which tells if given label is VOC label.
[ "Returns", "boolean", "which", "tells", "if", "given", "label", "is", "VOC", "label." ]
def is_voc_label(label): return label in VOC_CLASSES_SET
['def', 'is_voc_label(label):', 'return', 'label', 'in', 'VOC_CLASSES_SET']
748,437
PacktPublishing/Hands-On-Artificial--for-Banking
test_validate.py
test_validate_bool_args
test_validate_bool_args
Tests for error handling related to data types of method arguments.
[ "Tests", "for", "error", "handling", "related", "to", "data", "types", "of", "method", "arguments." ]
def test_validate_bool_args(string_series, func, inplace): msg = 'For argument "inplace" expected type bool' kwargs = dict(inplace=inplace) if func == '_set_name': kwargs['name'] = 'hello' with pytest.raises(ValueError, match=msg): getattr(string_series, func)(**kwargs)
['def', 'test_validate_bool_args(string_series,', 'func,', 'inplace):', 'msg', '=', "'For", 'argument', '"inplace"', 'expected', 'type', "bool'", 'kwargs', '=', 'dict(inplace=inplace)', 'if', 'func', '==', "'_set_name':", "kwargs['name']", '=', "'hello'", 'with', 'pytest.raises(ValueError,', 'match=msg):', 'getattr(str...
237,317
tryolabs/luminoth
vis.py
draw_rectangle
draw_rectangle
Draw a rectangle with an optional width.
[ "Draw", "a", "rectangle", "with", "an", "optional", "width." ]
def draw_rectangle(draw, coordinates, color, width=1, fill=30): fill = color + (fill,) outline = color + (255,) for i in range(width): coords = [coordinates[0] - i, coordinates[1] - i, coordinates[2] + i, coordinates[3] + i] if i == 0: draw.rectangle(coords, fill=fill, outline=ou...
['def', 'draw_rectangle(draw,', 'coordinates,', 'color,', 'width=1,', 'fill=30):', 'fill', '=', 'color', '+', '(fill,)', 'outline', '=', 'color', '+', '(255,)', 'for', 'i', 'in', 'range(width):', 'coords', '=', '[coordinates[0]', '-', 'i,', 'coordinates[1]', '-', 'i,', 'coordinates[2]', '+', 'i,', 'coordinates[3]', '+'...
617,457
intel/neural-compressor
util.py
get_depth
get_depth
Query the depth of the dict.
[ "Query", "the", "depth", "of", "the", "dict." ]
def get_depth(d) -> int: if isinstance(d, dict): return 1 + max((get_depth(v) for v in d.values())) return 0
['def', 'get_depth(d)', '->', 'int:', 'if', 'isinstance(d,', 'dict):', 'return', '1', '+', 'max((get_depth(v)', 'for', 'v', 'in', 'd.values()))', 'return', '0']
737,912
kaixin96/PANet
FPN.py
get_min_max_levels
get_min_max_levels
The min and max FPN levels required for supporting RPN and/or RoI transform operations on multiple FPN levels.
[ "The", "min", "and", "max", "FPN", "levels", "required", "for", "supporting", "RPN", "and/or", "RoI", "transform", "operations", "on", "multiple", "FPN", "levels." ]
def get_min_max_levels(): min_level = LOWEST_BACKBONE_LVL max_level = HIGHEST_BACKBONE_LVL if cfg.FPN.MULTILEVEL_RPN and (not cfg.FPN.MULTILEVEL_ROIS): max_level = cfg.FPN.RPN_MAX_LEVEL min_level = cfg.FPN.RPN_MIN_LEVEL if not cfg.FPN.MULTILEVEL_RPN and cfg.FPN.MULTILEVEL_ROIS: m...
['def', 'get_min_max_levels():', 'min_level', '=', 'LOWEST_BACKBONE_LVL', 'max_level', '=', 'HIGHEST_BACKBONE_LVL', 'if', 'cfg.FPN.MULTILEVEL_RPN', 'and', '(not', 'cfg.FPN.MULTILEVEL_ROIS):', 'max_level', '=', 'cfg.FPN.RPN_MAX_LEVEL', 'min_level', '=', 'cfg.FPN.RPN_MIN_LEVEL', 'if', 'not', 'cfg.FPN.MULTILEVEL_RPN', 'an...
778,736
shijie-wu/crosslingual-nlp
process_ace.py
mask_escape
mask_escape
Replaces escaped characters with rare sequences.
[ "Replaces", "escaped", "characters", "with", "rare", "sequences." ]
def mask_escape(text: str) -> str: return text.replace('&amp;', 'Ã\x92ªÃ\x92ªÃ\x92ªÃ\x92ªÃ\x92ª').replace('&lt;', 'Ã\x92Â\x9aÃ\x92Â\x9aÃ\x92Â\x9aÃ\x92Â\x9a').replace('&gt;', 'Ã\x92ºÃ\x92ºÃ\x92ºÃ\x92º')
['def', 'mask_escape(text:', 'str)', '->', 'str:', 'return', "text.replace('&amp;',", "'Ã\\x92ªÃ\\x92ªÃ\\x92ªÃ\\x92ªÃ\\x92ª').replace('&lt;',", "'Ã\\x92Â\\x9aÃ\\x92Â\\x9aÃ\\x92Â\\x9aÃ\\x92Â\\x9a').replace('&gt;',", "'Ã\\x92ºÃ\\x92ºÃ\\x92ºÃ\\x92º')"]
491,993
apeterswu/RL4NMT
transformer_vae.py
expand_batch
expand_batch
Expand on batch by mul times.
[ "Expand", "on", "batch", "by", "mul", "times." ]
def expand_batch(x, mul): cx = tf.expand_dims(x, axis=1) x_shape = x.get_shape().as_list() batch_mul = tf.to_int32(mul) cx += tf.zeros([1, batch_mul, 1, 1, 1]) mid_shape = [tf.shape(x)[2]] if len(x_shape) > 3 else [] end_shape = [x_shape[-1]] if x_shape[-1] else [tf.shape(x)[-1]] res_shape =...
['def', 'expand_batch(x,', 'mul):', 'cx', '=', 'tf.expand_dims(x,', 'axis=1)', 'x_shape', '=', 'x.get_shape().as_list()', 'batch_mul', '=', 'tf.to_int32(mul)', 'cx', '+=', 'tf.zeros([1,', 'batch_mul,', '1,', '1,', '1])', 'mid_shape', '=', '[tf.shape(x)[2]]', 'if', 'len(x_shape)', '>', '3', 'else', '[]', 'end_shape', '=...
331,704
RasaHQ/rasa
train.py
run_nlu_training
run_nlu_training
Trains an NLU model.
[ "Trains", "an", "NLU", "model." ]
def run_nlu_training(args: argparse.Namespace) -> Optional[Text]: from rasa.model_training import train_nlu config = rasa.cli.utils.get_validated_config(args.config, CONFIG_MANDATORY_KEYS_NLU) nlu_data = rasa.cli.utils.get_validated_path(args.nlu, 'nlu', DEFAULT_DATA_PATH, none_is_valid=True) if args.do...
['def', 'run_nlu_training(args:', 'argparse.Namespace)', '->', 'Optional[Text]:', 'from', 'rasa.model_training', 'import', 'train_nlu', 'config', '=', 'rasa.cli.utils.get_validated_config(args.config,', 'CONFIG_MANDATORY_KEYS_NLU)', 'nlu_data', '=', 'rasa.cli.utils.get_validated_path(args.nlu,', "'nlu',", 'DEFAULT_DATA...
836,623
halbielee/ACoL_pytorch
util.py
load_model
load_model
Loading pretrained / trained model.
[ "Loading", "pretrained", "/", "trained", "model." ]
def load_model(model, optimizer, args): if os.path.isfile(args.resume): if args.gpu == 0: print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) try: args.start_epoch = checkpoint['epoch'] except (TypeError, KeyError) as e...
['def', 'load_model(model,', 'optimizer,', 'args):', 'if', 'os.path.isfile(args.resume):', 'if', 'args.gpu', '==', '0:', 'print("=>', 'loading', 'checkpoint', '\'{}\'".format(args.resume))', 'checkpoint', '=', 'torch.load(args.resume)', 'try:', 'args.start_epoch', '=', "checkpoint['epoch']", 'except', '(TypeError,', 'K...
8,562
RasaHQ/rasa
extractor.py
EntityExtractorMixin.convert_predictions_into_entities
convert_predictions_into_entities
Convert predictions into entities.
[ "Convert", "predictions", "into", "entities." ]
def convert_predictions_into_entities(text: Text, tokens: List[Token], tags: Dict[Text, List[Text]], split_entities_config: Optional[Dict[Text, bool]]=None, confidences: Optional[Dict[Text, List[float]]]=None) -> List[Dict[Text, Any]]: import rasa.nlu.utils.bilou_utils as bilou_utils entities = [] last_enti...
['def', 'convert_predictions_into_entities(text:', 'Text,', 'tokens:', 'List[Token],', 'tags:', 'Dict[Text,', 'List[Text]],', 'split_entities_config:', 'Optional[Dict[Text,', 'bool]]=None,', 'confidences:', 'Optional[Dict[Text,', 'List[float]]]=None)', '->', 'List[Dict[Text,', 'Any]]:', 'import', 'rasa.nlu.utils.bilou_...
837,214
zihuitang/medical_AI_platform
ftplib.py
FTP.mkd
mkd
Make a directory, return its full pathname.
[ "Make", "a", "directory,", "return", "its", "full", "pathname." ]
def mkd(self, dirname): resp = self.voidcmd('MKD ' + dirname) if not resp.startswith('257'): return '' return parse257(resp)
['def', 'mkd(self,', 'dirname):', 'resp', '=', "self.voidcmd('MKD", "'", '+', 'dirname)', 'if', 'not', "resp.startswith('257'):", 'return', "''", 'return', 'parse257(resp)']
280,415
google-research/scenic
model_utils.py
nest_params
nest_params
Nest (un-flatten) a dictionary.
[ "Nest", "(un-flatten)", "a", "dictionary." ]
def nest_params(flat_dic, sep='/'): res = dict() for (key, value) in flat_dic.items(): parts = key.split(sep) d = res for part in parts[:-1]: if part not in d: d[part] = dict() d = d[part] d[parts[-1]] = value return res
['def', 'nest_params(flat_dic,', "sep='/'):", 'res', '=', 'dict()', 'for', '(key,', 'value)', 'in', 'flat_dic.items():', 'parts', '=', 'key.split(sep)', 'd', '=', 'res', 'for', 'part', 'in', 'parts[:-1]:', 'if', 'part', 'not', 'in', 'd:', 'd[part]', '=', 'dict()', 'd', '=', 'd[part]', 'd[parts[-1]]', '=', 'value', 'ret...
846,368
brsynth/RetroPathRL
Tree.py
Tree.find_full_scope
find_full_scope
Returns the scope of the compound: all pathways leading to the chassis.
[ "Returns", "the", "scope", "of", "the", "compound:", "all", "pathways", "leading", "to", "the", "chassis." ]
def find_full_scope(self, folder_to_save='pathways', name=None): pile_to_treat = [] pathways_to_print = [] pathway_iteration = 1 full_scope = Pathway(first_iteration=-1, target=None, compounds=[], moves=[], main_layer=self.main_layer_chassis, organism=self.organism, edges=[], nodes_compounds=[], nodes_t...
['def', 'find_full_scope(self,', "folder_to_save='pathways',", 'name=None):', 'pile_to_treat', '=', '[]', 'pathways_to_print', '=', '[]', 'pathway_iteration', '=', '1', 'full_scope', '=', 'Pathway(first_iteration=-1,', 'target=None,', 'compounds=[],', 'moves=[],', 'main_layer=self.main_layer_chassis,', 'organism=self.o...
841,020
electronicvisions/norse
lif_refrac_adjoint.py
lif_refrac_feed_forward_adjoint_step
lif_refrac_feed_forward_adjoint_step
Implementes a single euler forward and adjoint backward step of a leaky integrate and fire neuron with current based exponential synapses and a refractory period.
[ "Implementes", "a", "single", "euler", "forward", "and", "adjoint", "backward", "step", "of", "a", "leaky", "integrate", "and", "fire", "neuron", "with", "current", "based", "exponential", "synapses", "and", "a", "refractory", "period." ]
def lif_refrac_feed_forward_adjoint_step(input: torch.Tensor, s: LIFRefracFeedForwardState, p: LIFRefracParameters=LIFRefracParameters(), dt: float=0.001) -> Tuple[torch.Tensor, LIFRefracFeedForwardState]: (z, v, i, rho) = LIFAdjointRefracFeedForwardFunction.apply(input, s.lif.v, s.lif.i, s.rho, p, dt) return (...
['def', 'lif_refrac_feed_forward_adjoint_step(input:', 'torch.Tensor,', 's:', 'LIFRefracFeedForwardState,', 'p:', 'LIFRefracParameters=LIFRefracParameters(),', 'dt:', 'float=0.001)', '->', 'Tuple[torch.Tensor,', 'LIFRefracFeedForwardState]:', '(z,', 'v,', 'i,', 'rho)', '=', 'LIFAdjointRefracFeedForwardFunction.apply(in...
729,740
HareeshBahuleyan/probabilistic_nlg
utils.py
tokenize_sequence
tokenize_sequence
Tokenizes a given input sequence of words.
[ "Tokenizes", "a", "given", "input", "sequence", "of", "words." ]
def tokenize_sequence(sentences, filters, max_num_words, max_vocab_size): sentences = [' '.join(word_tokenize(s)[:max_num_words]) for s in sentences] tokenizer = Tokenizer(filters=filters) tokenizer.fit_on_texts(sentences) word_index = dict() word_index['PAD'] = 0 word_index['UNK'] = 1 word_...
['def', 'tokenize_sequence(sentences,', 'filters,', 'max_num_words,', 'max_vocab_size):', 'sentences', '=', "['", "'.join(word_tokenize(s)[:max_num_words])", 'for', 's', 'in', 'sentences]', 'tokenizer', '=', 'Tokenizer(filters=filters)', 'tokenizer.fit_on_texts(sentences)', 'word_index', '=', 'dict()', "word_index['PAD...
825,039
g2-bernotas/PS-Plant-Framework
visualize.py
display_weight_stats
display_weight_stats
Scans all the weights in the model and returns a list of tuples that contain stats about each weight.
[ "Scans", "all", "the", "weights", "in", "the", "model", "and", "returns", "a", "list", "of", "tuples", "that", "contain", "stats", "about", "each", "weight." ]
def display_weight_stats(model): layers = model.get_trainable_layers() table = [['WEIGHT NAME', 'SHAPE', 'MIN', 'MAX', 'STD']] for l in layers: weight_values = l.get_weights() weight_tensors = l.weights for (i, w) in enumerate(weight_values): weight_name = weight_tensors[...
['def', 'display_weight_stats(model):', 'layers', '=', 'model.get_trainable_layers()', 'table', '=', "[['WEIGHT", "NAME',", "'SHAPE',", "'MIN',", "'MAX',", "'STD']]", 'for', 'l', 'in', 'layers:', 'weight_values', '=', 'l.get_weights()', 'weight_tensors', '=', 'l.weights', 'for', '(i,', 'w)', 'in', 'enumerate(weight_val...
818,215
instadeepai/jumanji
conftest.py
mmst_split_gn_env
mmst_split_gn_env
Instantiates a default `MMST` environment.
[ "Instantiates", "a", "default", "`MMST`", "environment." ]
def mmst_split_gn_env() -> MMST: return MMST(generator=None, reward_fn=None)
['def', 'mmst_split_gn_env()', '->', 'MMST:', 'return', 'MMST(generator=None,', 'reward_fn=None)']
594,387
kubeflow/pipelines
_data_passing.py
get_canonical_type_name_for_type
get_canonical_type_name_for_type
Find the canonical type name for a given type.
[ "Find", "the", "canonical", "type", "name", "for", "a", "given", "type." ]
def get_canonical_type_name_for_type(typ: Type) -> str: try: return type_to_type_name.get(typ, None) except: return None
['def', 'get_canonical_type_name_for_type(typ:', 'Type)', '->', 'str:', 'try:', 'return', 'type_to_type_name.get(typ,', 'None)', 'except:', 'return', 'None']
780,042
mj-will/nessai
test_flowmodel_base.py
test_prep_data_dataloader
test_prep_data_dataloader
Test the data prep, make sure batch sizes and validation size produce the correct result.
[ "Test", "the", "data", "prep,", "make", "sure", "batch", "sizes", "and", "validation", "size", "produce", "the", "correct", "result." ]
def test_prep_data_dataloader(flow_model, data_dim, val_size, batch_size): n = 100 x = np.random.randn(n, data_dim) (train, val, batch_size_out) = flow_model.prep_data(x, val_size, batch_size, use_dataloader=True) train_batch = next(iter(train))[0] val_batch = next(iter(val))[0] if batch_size ==...
['def', 'test_prep_data_dataloader(flow_model,', 'data_dim,', 'val_size,', 'batch_size):', 'n', '=', '100', 'x', '=', 'np.random.randn(n,', 'data_dim)', '(train,', 'val,', 'batch_size_out)', '=', 'flow_model.prep_data(x,', 'val_size,', 'batch_size,', 'use_dataloader=True)', 'train_batch', '=', 'next(iter(train))[0]', '...
292,465
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
common_video.py
scheduled_sample_count
scheduled_sample_count
Sample batch with specified mix of groundtruth and generated data points.
[ "Sample", "batch", "with", "specified", "mix", "of", "groundtruth", "and", "generated", "data", "points." ]
def scheduled_sample_count(ground_truth_x, generated_x, batch_size, scheduled_sample_var): num_ground_truth = scheduled_sample_var idx = tf.random_shuffle(tf.range(batch_size)) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_s...
['def', 'scheduled_sample_count(ground_truth_x,', 'generated_x,', 'batch_size,', 'scheduled_sample_var):', 'num_ground_truth', '=', 'scheduled_sample_var', 'idx', '=', 'tf.random_shuffle(tf.range(batch_size))', 'ground_truth_idx', '=', 'tf.gather(idx,', 'tf.range(num_ground_truth))', 'generated_idx', '=', 'tf.gather(id...
965,368
for-ai/rl
coding_ddpg.py
get_env_stats
get_env_stats
Gets the stats of an environment.
[ "Gets", "the", "stats", "of", "an", "environment." ]
def get_env_stats(): proof_env = make_transformed_env(make_env()) t = proof_env.transform[2] t.init_stats(init_env_steps) transform_state_dict = t.state_dict() proof_env.close() return transform_state_dict
['def', 'get_env_stats():', 'proof_env', '=', 'make_transformed_env(make_env())', 't', '=', 'proof_env.transform[2]', 't.init_stats(init_env_steps)', 'transform_state_dict', '=', 't.state_dict()', 'proof_env.close()', 'return', 'transform_state_dict']
859,593
mfbx9da4/neuron-astrocyte-networks
test_subsampling_connection.py
buildSubsamplingNetwork
buildSubsamplingNetwork
Builds a network with subsampling connections.
[ "Builds", "a", "network", "with", "subsampling", "connections." ]
def buildSubsamplingNetwork(): n = FeedForwardNetwork() n.addInputModule(LinearLayer(6, 'in')) n.addOutputModule(LinearLayer(1, 'out')) n.addConnection(SubsamplingConnection(n['in'], n['out'], inSliceTo=4)) n.addConnection(SubsamplingConnection(n['in'], n['out'], inSliceFrom=4)) n.sortModules() ...
['def', 'buildSubsamplingNetwork():', 'n', '=', 'FeedForwardNetwork()', 'n.addInputModule(LinearLayer(6,', "'in'))", 'n.addOutputModule(LinearLayer(1,', "'out'))", "n.addConnection(SubsamplingConnection(n['in'],", "n['out'],", 'inSliceTo=4))', "n.addConnection(SubsamplingConnection(n['in'],", "n['out'],", 'inSliceFrom=...
722,737
paulorauber/rl
test_cost.py
TestBase.test_tensordict_keys
test_tensordict_keys
Test configurable tensordict key behavior with derived classes.
[ "Test", "configurable", "tensordict", "key", "behavior", "with", "derived", "classes." ]
def test_tensordict_keys(self): class MyLoss(LossModule): def __init__(self): super().__init__() loss_module = MyLoss() with pytest.raises(AttributeError): loss_module.set_keys() class MyLoss2(MyLoss): def _forward_value_estimator_keys(self, **kwargs) -> None: ...
['def', 'test_tensordict_keys(self):', 'class', 'MyLoss(LossModule):', 'def', '__init__(self):', 'super().__init__()', 'loss_module', '=', 'MyLoss()', 'with', 'pytest.raises(AttributeError):', 'loss_module.set_keys()', 'class', 'MyLoss2(MyLoss):', 'def', '_forward_value_estimator_keys(self,', '**kwargs)', '->', 'None:'...
858,355
pytorch/rl
mappings.py
mappings
mappings
Given an input string, returns a surjective function f(x): R -> R^+.
[ "Given", "an", "input", "string,", "returns", "a", "surjective", "function", "f(x):", "R", "->", "R^+." ]
def mappings(key: str) -> Callable: _mappings = {'softplus': torch.nn.functional.softplus, 'exp': torch.exp, 'relu': torch.relu, 'biased_softplus': biased_softplus(1.0), 'expln': expln} if key in _mappings: return _mappings[key] elif key.startswith('biased_softplus'): stripped_key = key.spli...
['def', 'mappings(key:', 'str)', '->', 'Callable:', '_mappings', '=', "{'softplus':", 'torch.nn.functional.softplus,', "'exp':", 'torch.exp,', "'relu':", 'torch.relu,', "'biased_softplus':", 'biased_softplus(1.0),', "'expln':", 'expln}', 'if', 'key', 'in', '_mappings:', 'return', '_mappings[key]', 'elif', "key.startswi...
859,303
alibaba/EasyCV
raw.py
DetDataset.evaluate
evaluate
Evaluates the detection boxes.
[ "Evaluates", "the", "detection", "boxes." ]
def evaluate(self, results, evaluators=None, logger=None): eval_result = dict() groundtruth_dict = {} groundtruth_dict['groundtruth_boxes'] = [self.data_source.get_ann_info(idx)['bboxes'] for idx in range(len(results['img_metas']))] groundtruth_dict['groundtruth_classes'] = [self.data_source.get_ann_inf...
['def', 'evaluate(self,', 'results,', 'evaluators=None,', 'logger=None):', 'eval_result', '=', 'dict()', 'groundtruth_dict', '=', '{}', "groundtruth_dict['groundtruth_boxes']", '=', "[self.data_source.get_ann_info(idx)['bboxes']", 'for', 'idx', 'in', "range(len(results['img_metas']))]", "groundtruth_dict['groundtruth_c...
546,418
funkelab/gunpowder
unet.py
crop_spatial
crop_spatial
Crop only the spacial dimensions to match shape.
[ "Crop", "only", "the", "spacial", "dimensions", "to", "match", "shape." ]
def crop_spatial(fmaps_in, shape): in_shape = fmaps_in.get_shape().as_list() offset = [0, 0] + [(in_shape[i] - shape[i]) // 2 for i in range(2, len(shape))] size = in_shape[0:2] + shape[2:] fmaps = tf.slice(fmaps_in, offset, size) return fmaps
['def', 'crop_spatial(fmaps_in,', 'shape):', 'in_shape', '=', 'fmaps_in.get_shape().as_list()', 'offset', '=', '[0,', '0]', '+', '[(in_shape[i]', '-', 'shape[i])', '//', '2', 'for', 'i', 'in', 'range(2,', 'len(shape))]', 'size', '=', 'in_shape[0:2]', '+', 'shape[2:]', 'fmaps', '=', 'tf.slice(fmaps_in,', 'offset,', 'siz...
572,793
devashish-patel/webcam-motion-detector
test_exceptions.py
TestBestMatch.test_if_the_most_relevant_error_is_allOf_it_is_traversed
test_if_the_most_relevant_error_is_allOf_it_is_traversed
Now, if the error is allOf, we traverse but select the *most* relevant error from the context, because all schemas here must match anyways.
[ "Now,", "if", "the", "error", "is", "allOf,", "we", "traverse", "but", "select", "the", "*most*", "relevant", "error", "from", "the", "context,", "because", "all", "schemas", "here", "must", "match", "anyways." ]
def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self): validator = Draft4Validator({'properties': {'foo': {'allOf': [{'type': 'string'}, {'properties': {'bar': {'type': 'array'}}}]}}}) best = self.best_match(validator.iter_errors({'foo': {'bar': 12}})) self.assertEqual(best.validator_value, 'st...
['def', 'test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):', 'validator', '=', "Draft4Validator({'properties':", "{'foo':", "{'allOf':", "[{'type':", "'string'},", "{'properties':", "{'bar':", "{'type':", "'array'}}}]}}})", 'best', '=', "self.best_match(validator.iter_errors({'foo':", "{'bar':", '12}}))',...
979,922
wandb/wandb
_templates.py
create_example_footer
create_example_footer
Create an example footer with image and text at bottom.
[ "Create", "an", "example", "footer", "with", "image", "and", "text", "at", "bottom." ]
def create_example_footer(): import wandb.apis.reports as wr return [wr.P(), wr.HorizontalRule(), wr.P(), wr.H1('Disclaimer'), wr.P('The views and opinions expressed in this report are those of the authors and do not necessarily reflect the official policy or position of Weights & Biases. blah blah blah blah bl...
['def', 'create_example_footer():', 'import', 'wandb.apis.reports', 'as', 'wr', 'return', '[wr.P(),', 'wr.HorizontalRule(),', 'wr.P(),', "wr.H1('Disclaimer'),", "wr.P('The", 'views', 'and', 'opinions', 'expressed', 'in', 'this', 'report', 'are', 'those', 'of', 'the', 'authors', 'and', 'do', 'not', 'necessarily', 'refle...
941,496
AbdelrahmanRadwan/object-detection
ops.py
dense_to_sparse_boxes
dense_to_sparse_boxes
Converts bounding boxes from dense to sparse form.
[ "Converts", "bounding", "boxes", "from", "dense", "to", "sparse", "form." ]
def dense_to_sparse_boxes(dense_locations, dense_num_boxes, num_classes): num_valid_boxes = tf.reduce_sum(dense_num_boxes) box_locations = tf.slice(dense_locations, tf.constant([0, 0]), tf.stack([num_valid_boxes, 4])) tiled_classes = [tf.tile([i], tf.expand_dims(dense_num_boxes[i], 0)) for i in range(num_cl...
['def', 'dense_to_sparse_boxes(dense_locations,', 'dense_num_boxes,', 'num_classes):', 'num_valid_boxes', '=', 'tf.reduce_sum(dense_num_boxes)', 'box_locations', '=', 'tf.slice(dense_locations,', 'tf.constant([0,', '0]),', 'tf.stack([num_valid_boxes,', '4]))', 'tiled_classes', '=', '[tf.tile([i],', 'tf.expand_dims(dens...
747,389
mindsdb/lightwood
ts_num_array.py
TsArrayNumericEncoder.prepare
prepare
This method prepares the underlying time series numerical encoder.
[ "This", "method", "prepares", "the", "underlying", "time", "series", "numerical", "encoder." ]
def prepare(self, priming_data): if self.is_prepared: raise Exception('You can only call "prepare" once for a given encoder.') self.sub_encoder.prepare(priming_data) self.is_prepared = True
['def', 'prepare(self,', 'priming_data):', 'if', 'self.is_prepared:', 'raise', "Exception('You", 'can', 'only', 'call', '"prepare"', 'once', 'for', 'a', 'given', "encoder.')", 'self.sub_encoder.prepare(priming_data)', 'self.is_prepared', '=', 'True']
602,375
westerberg-science/openscope-glo-stim
behavior.py
FlashStimulus.extend
extend
Adds extension time to the next pre-flash.
[ "Adds", "extension", "time", "to", "the", "next", "pre-flash." ]
def extend(self, ms=None): if ms is None: self._extension_time += self.extension_duration else: self._extension_time += ms logging.debug('Trial extended by {} ms'.format(ms))
['def', 'extend(self,', 'ms=None):', 'if', 'ms', 'is', 'None:', 'self._extension_time', '+=', 'self.extension_duration', 'else:', 'self._extension_time', '+=', 'ms', "logging.debug('Trial", 'extended', 'by', '{}', "ms'.format(ms))"]
757,599
noahshinn024/reflexion
generate_reflections.py
update_memory
update_memory
Updates the given env_config with the appropriate reflections.
[ "Updates", "the", "given", "env_config", "with", "the", "appropriate", "reflections." ]
def update_memory(trial_log_path: str, env_configs: List[Dict[str, Any]]) -> List[Dict[str, Any]]: with open(trial_log_path, 'r') as f: full_log: str = f.read() env_logs: List[str] = full_log.split('#####\n\n#####') assert len(env_logs) == len(env_configs), print(f'bad: {len(env_logs)}, {len(env_con...
['def', 'update_memory(trial_log_path:', 'str,', 'env_configs:', 'List[Dict[str,', 'Any]])', '->', 'List[Dict[str,', 'Any]]:', 'with', 'open(trial_log_path,', "'r')", 'as', 'f:', 'full_log:', 'str', '=', 'f.read()', 'env_logs:', 'List[str]', '=', "full_log.split('#####\\n\\n#####')", 'assert', 'len(env_logs)', '==', 'l...
340,428
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
real_nvp_multiscale_dataset.py
get_default_hparams
get_default_hparams
Get the default hyperparameters.
[ "Get", "the", "default", "hyperparameters." ]
def get_default_hparams(): return HParams(batch_size=64, residual_blocks=2, n_couplings=2, n_scale=4, learning_rate=0.001, momentum=0.1, decay=0.001, l2_coeff=5e-05, clip_gradient=100.0, optimizer='adam', dropout_mask=0, base_dim=32, bottleneck=0, use_batch_norm=1, alternate=1, use_aff=1, skip=1, data_constraint=0....
['def', 'get_default_hparams():', 'return', 'HParams(batch_size=64,', 'residual_blocks=2,', 'n_couplings=2,', 'n_scale=4,', 'learning_rate=0.001,', 'momentum=0.1,', 'decay=0.001,', 'l2_coeff=5e-05,', 'clip_gradient=100.0,', "optimizer='adam',", 'dropout_mask=0,', 'base_dim=32,', 'bottleneck=0,', 'use_batch_norm=1,', 'a...
26,547
weimin17/Object-Detection_HelmetDetection
wide_deep_run_loop.py
export_model
export_model
Export to SavedModel format.
[ "Export", "to", "SavedModel", "format." ]
def export_model(model, model_type, export_dir, model_column_fn): (wide_columns, deep_columns) = model_column_fn() if model_type == 'wide': columns = wide_columns elif model_type == 'deep': columns = deep_columns else: columns = wide_columns + deep_columns feature_spec = tf.f...
['def', 'export_model(model,', 'model_type,', 'export_dir,', 'model_column_fn):', '(wide_columns,', 'deep_columns)', '=', 'model_column_fn()', 'if', 'model_type', '==', "'wide':", 'columns', '=', 'wide_columns', 'elif', 'model_type', '==', "'deep':", 'columns', '=', 'deep_columns', 'else:', 'columns', '=', 'wide_column...
761,384
wkirgsn/mawk-thesis
datamining.py
get_profilemarks
get_profilemarks
Extract indices for vertical profile separators.
[ "Extract", "indices", "for", "vertical", "profile", "separators." ]
def get_profilemarks(_data, _pool): profilemarks = np.asanyarray([[p.shape[1] for p in _pool], _data.trainset], dtype=np.float32) profilemarks[0, :] = np.asanyarray([sum(profilemarks[0, :p]) for p in range(profilemarks.shape[1])]) return profilemarks
['def', 'get_profilemarks(_data,', '_pool):', 'profilemarks', '=', 'np.asanyarray([[p.shape[1]', 'for', 'p', 'in', '_pool],', '_data.trainset],', 'dtype=np.float32)', 'profilemarks[0,', ':]', '=', 'np.asanyarray([sum(profilemarks[0,', ':p])', 'for', 'p', 'in', 'range(profilemarks.shape[1])])', 'return', 'profilemarks']
209,937
Eric3911/OpenAGI
beam_search.py
BeamSearch.search
search
Search new tokens for running hypotheses and encoded speech x.
[ "Search", "new", "tokens", "for", "running", "hypotheses", "and", "encoded", "speech", "x." ]
def search(self, running_hyps: List[Hypothesis], x: paddle.Tensor) -> List[Hypothesis]: best_hyps = [] part_ids = paddle.arange(self.n_vocab) for hyp in running_hyps: weighted_scores = paddle.zeros([self.n_vocab], dtype=x.dtype) (scores, states) = self.score_full(hyp, x) for k in sel...
['def', 'search(self,', 'running_hyps:', 'List[Hypothesis],', 'x:', 'paddle.Tensor)', '->', 'List[Hypothesis]:', 'best_hyps', '=', '[]', 'part_ids', '=', 'paddle.arange(self.n_vocab)', 'for', 'hyp', 'in', 'running_hyps:', 'weighted_scores', '=', 'paddle.zeros([self.n_vocab],', 'dtype=x.dtype)', '(scores,', 'states)', '...
251,186
bnpy/bnpy
TestSummaryAlg.py
TestSummaryAlg_K4T2.test_all_possible_single_merges
test_all_possible_single_merges
Iterate over all possible pairs (kA, kB), verify merge Htable correct.
[ "Iterate", "over", "all", "possible", "pairs", "(kA,", "kB),", "verify", "merge", "Htable", "correct." ]
def test_all_possible_single_merges(self): print('') for kA in range(self.K): for kB in range(kA + 1, self.K): self.test_single_merge__python_equals_cpp(kA=kA, kB=kB)
['def', 'test_all_possible_single_merges(self):', "print('')", 'for', 'kA', 'in', 'range(self.K):', 'for', 'kB', 'in', 'range(kA', '+', '1,', 'self.K):', 'self.test_single_merge__python_equals_cpp(kA=kA,', 'kB=kB)']
465,335
QData/deepWordBug
math2html.py
Globable.globexcluding
globexcluding
Glob a bit of text up until (excluding) any excluded character.
[ "Glob", "a", "bit", "of", "text", "up", "until", "(excluding)", "any", "excluded", "character." ]
def globexcluding(self, excluded): return self.glob(lambda : self.current() not in excluded)
['def', 'globexcluding(self,', 'excluded):', 'return', 'self.glob(lambda', ':', 'self.current()', 'not', 'in', 'excluded)']
542,389
nicknochnack/RealTimeSignLanguageTFJS
densepose_ops.py
DensePoseHorizontalFlip.flip_parts_and_coords
flip_parts_and_coords
Flips part ids and coordinates.
[ "Flips", "part", "ids", "and", "coordinates." ]
def flip_parts_and_coords(self, part_ids, vu): (num_instances, num_points) = shape_utils.combined_static_and_dynamic_shape(part_ids) part_ids_flattened = tf.reshape(part_ids, [-1]) new_part_ids_flattened = tf.gather(self.part_symmetries, part_ids_flattened) new_part_ids = tf.reshape(new_part_ids_flatten...
['def', 'flip_parts_and_coords(self,', 'part_ids,', 'vu):', '(num_instances,', 'num_points)', '=', 'shape_utils.combined_static_and_dynamic_shape(part_ids)', 'part_ids_flattened', '=', 'tf.reshape(part_ids,', '[-1])', 'new_part_ids_flattened', '=', 'tf.gather(self.part_symmetries,', 'part_ids_flattened)', 'new_part_ids...
852,156
fudan-zvg/SETR
ddod_head.py
DDODHead.calc_reweight_factor
calc_reweight_factor
Compute reweight_factor for regression and classification loss.
[ "Compute", "reweight_factor", "for", "regression", "and", "classification", "loss." ]
def calc_reweight_factor(self, labels_list): bg_class_ind = self.num_classes for (ii, each_level_label) in enumerate(labels_list): pos_inds = ((each_level_label >= 0) & (each_level_label < bg_class_ind)).nonzero(as_tuple=False).squeeze(1) self.cls_num_pos_samples_per_level[ii] += len(pos_inds) ...
['def', 'calc_reweight_factor(self,', 'labels_list):', 'bg_class_ind', '=', 'self.num_classes', 'for', '(ii,', 'each_level_label)', 'in', 'enumerate(labels_list):', 'pos_inds', '=', '((each_level_label', '>=', '0)', '&', '(each_level_label', '<', 'bg_class_ind)).nonzero(as_tuple=False).squeeze(1)', 'self.cls_num_pos_sa...
898,111
aleju/self-driving-truck
train.py
generate_debug_image
generate_debug_image
Draw an image with current ground truth and predictions for debug purposes.
[ "Draw", "an", "image", "with", "current", "ground", "truth", "and", "predictions", "for", "debug", "purposes." ]
def generate_debug_image(inputs, outputs_gt, outputs_pred): current_image = inputs.data[0].cpu().numpy() current_image = np.clip(current_image * 255, 0, 255).astype(np.uint8).transpose((1, 2, 0)) current_image = ia.imresize_single_image(current_image, (32 * 4, 64 * 4)) (h, w) = current_image.shape[0:2] ...
['def', 'generate_debug_image(inputs,', 'outputs_gt,', 'outputs_pred):', 'current_image', '=', 'inputs.data[0].cpu().numpy()', 'current_image', '=', 'np.clip(current_image', '*', '255,', '0,', '255).astype(np.uint8).transpose((1,', '2,', '0))', 'current_image', '=', 'ia.imresize_single_image(current_image,', '(32', '*'...
843,262
bnpy/bnpy
BarsViz.py
show_square_images
show_square_images
Show provided vectors as square images Post Condition -------------- Provided axes have plots updated.
[ "Show", "provided", "vectors", "as", "square", "images", "Post", "Condition", "--------------", "Provided", "axes", "have", "plots", "updated." ]
def show_square_images(topics_KV=None, xlabels=[], max_n_images=50, ncols=5, ax_list=None, im_width=1, im_height=1, fontsize=10, **kwargs): global imshowArgs local_imshowArgs = dict(**imshowArgs) for key in local_imshowArgs: if key in kwargs: local_imshowArgs[key] = kwargs[key] (K, V...
['def', 'show_square_images(topics_KV=None,', 'xlabels=[],', 'max_n_images=50,', 'ncols=5,', 'ax_list=None,', 'im_width=1,', 'im_height=1,', 'fontsize=10,', '**kwargs):', 'global', 'imshowArgs', 'local_imshowArgs', '=', 'dict(**imshowArgs)', 'for', 'key', 'in', 'local_imshowArgs:', 'if', 'key', 'in', 'kwargs:', 'local_...
465,247
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
base.py
LocalTree.dumps
dumps
Dump this token to a string.
[ "Dump", "this", "token", "to", "a", "string." ]
def dumps(self, level=0): fd = StringIO() self.dump(fd, level) return fd.getvalue()
['def', 'dumps(self,', 'level=0):', 'fd', '=', 'StringIO()', 'self.dump(fd,', 'level)', 'return', 'fd.getvalue()']
11,344
ananthpn/nlp
dureader_eval.py
get_main_result
get_main_result
Prepare answers for task 'main'.
[ "Prepare", "answers", "for", "task", "'main'." ]
def get_main_result(qid, pred_result, ref_result): ref_ans = ref_result[qid]['answers'] if not ref_ans: ref_ans = [EMPTY] pred_ans = pred_result.get(qid, {}).get('answers', [])[:1] if not pred_ans: pred_ans = [EMPTY] return ([(qid, pred_ans)], [(qid, ref_ans)])
['def', 'get_main_result(qid,', 'pred_result,', 'ref_result):', 'ref_ans', '=', "ref_result[qid]['answers']", 'if', 'not', 'ref_ans:', 'ref_ans', '=', '[EMPTY]', 'pred_ans', '=', 'pred_result.get(qid,', "{}).get('answers',", '[])[:1]', 'if', 'not', 'pred_ans:', 'pred_ans', '=', '[EMPTY]', 'return', '([(qid,', 'pred_ans...
808,738
netket/netket
graph.py
Edgeless
Edgeless
Construct a set graph (collection of unconnected vertices).
[ "Construct", "a", "set", "graph", "(collection", "of", "unconnected", "vertices)." ]
def Edgeless(n_nodes: int) -> Graph: return Graph([], n_nodes)
['def', 'Edgeless(n_nodes:', 'int)', '->', 'Graph:', 'return', 'Graph([],', 'n_nodes)']
735,997
tusen-ai/SST
SO3.py
mat_to_quat
mat_to_quat
Convert rotation matrix to scalar first quaternion.
[ "Convert", "rotation", "matrix", "to", "scalar", "first", "quaternion." ]
def mat_to_quat(mat: Tensor) -> Tensor: return C.rotation_matrix_to_quaternion(mat, order=C.QuaternionCoeffOrder.WXYZ)
['def', 'mat_to_quat(mat:', 'Tensor)', '->', 'Tensor:', 'return', 'C.rotation_matrix_to_quaternion(mat,', 'order=C.QuaternionCoeffOrder.WXYZ)']
872,684
triaquae/triaquae
driver.py
Driver.driver_count
driver_count
Returns the number of OGR data source drivers registered.
[ "Returns", "the", "number", "of", "OGR", "data", "source", "drivers", "registered." ]
def driver_count(self): return capi.get_driver_count()
['def', 'driver_count(self):', 'return', 'capi.get_driver_count()']
357,530
TrellixVulnTeam/Unsupervised_Learning_HFI7
transforms.py
BboxBase.height
height
The (signed) height of the bounding box.
[ "The", "(signed)", "height", "of", "the", "bounding", "box." ]
def height(self): points = self.get_points() return points[1, 1] - points[0, 1]
['def', 'height(self):', 'points', '=', 'self.get_points()', 'return', 'points[1,', '1]', '-', 'points[0,', '1]']
450,844
devashish-patel/webcam-motion-detector
fix_imports.py
all_patterns
all_patterns
Accepts a string and returns a pattern of possible patterns involving that name Called by simple_mapping_to_pattern for each name in the mapping it receives.
[ "Accepts", "a", "string", "and", "returns", "a", "pattern", "of", "possible", "patterns", "involving", "that", "name", "Called", "by", "simple_mapping_to_pattern", "for", "each", "name", "in", "the", "mapping", "it", "receives." ]
def all_patterns(name): if u'.' in name: (name, attr) = name.split(u'.', 1) simple_name = simple_name_match % name simple_attr = subname_match % attr dotted_name = dotted_name_match % (simple_name, simple_attr) i_from = from_import_match % dotted_name i_from_submod = ...
['def', 'all_patterns(name):', 'if', "u'.'", 'in', 'name:', '(name,', 'attr)', '=', "name.split(u'.',", '1)', 'simple_name', '=', 'simple_name_match', '%', 'name', 'simple_attr', '=', 'subname_match', '%', 'attr', 'dotted_name', '=', 'dotted_name_match', '%', '(simple_name,', 'simple_attr)', 'i_from', '=', 'from_import...
980,135
EducationalTestingService/skll
test_classification.py
TestClassification.test_all_new_labels_in_test
test_all_new_labels_in_test
Test classification with all labels in test set unseen.
[ "Test", "classification", "with", "all", "labels", "in", "test", "set", "unseen." ]
def test_all_new_labels_in_test(self): (train_fs, test_fs) = make_classification_data(num_labels=3, train_test_ratio=0.8) test_fs.labels = test_fs.labels + 3 learner = Learner('SVC') learner.train(train_fs, grid_search=False) res = learner.evaluate(test_fs) yield (self.check_results_with_unseen_...
['def', 'test_all_new_labels_in_test(self):', '(train_fs,', 'test_fs)', '=', 'make_classification_data(num_labels=3,', 'train_test_ratio=0.8)', 'test_fs.labels', '=', 'test_fs.labels', '+', '3', 'learner', '=', "Learner('SVC')", 'learner.train(train_fs,', 'grid_search=False)', 'res', '=', 'learner.evaluate(test_fs)', '...
885,036
voxel51/fiftyone
sample.py
_SampleMixin.compute_metadata
compute_metadata
Populates the ``metadata`` field of the sample.
[ "Populates", "the", "``metadata``", "field", "of", "the", "sample." ]
def compute_metadata(self, overwrite=False, skip_failures=False): fom.compute_sample_metadata(self, overwrite=overwrite, skip_failures=skip_failures)
['def', 'compute_metadata(self,', 'overwrite=False,', 'skip_failures=False):', 'fom.compute_sample_metadata(self,', 'overwrite=overwrite,', 'skip_failures=skip_failures)']
583,259
gunthercox/ChatterBot
collections.py
CollectionAdapter.clear_without_event
clear_without_event
Empty the collection, firing no events.
[ "Empty", "the", "collection,", "firing", "no", "events." ]
def clear_without_event(self): remover = getattr(self._data(), '_sa_remover') for item in list(self): remover(item, _sa_initiator=False)
['def', 'clear_without_event(self):', 'remover', '=', 'getattr(self._data(),', "'_sa_remover')", 'for', 'item', 'in', 'list(self):', 'remover(item,', '_sa_initiator=False)']
534,485
QData/deepWordBug
plugin.py
plugin_validator
plugin_validator
Validates an handler implementation against the IPlugin interface.
[ "Validates", "an", "handler", "implementation", "against", "the", "IPlugin", "interface." ]
def plugin_validator(klass, obj): members = ['_setup', 'load_plugin', 'load_plugins', 'get_loaded_plugins', 'get_enabled_plugins', 'get_disabled_plugins'] interface.validate(IPlugin, obj, members)
['def', 'plugin_validator(klass,', 'obj):', 'members', '=', "['_setup',", "'load_plugin',", "'load_plugins',", "'get_loaded_plugins',", "'get_enabled_plugins',", "'get_disabled_plugins']", 'interface.validate(IPlugin,', 'obj,', 'members)']
541,678
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
predict_test1.py
full_batch_norm
full_batch_norm
Batch normalization on fully connected layers.
[ "Batch", "normalization", "on", "fully", "connected", "layers." ]
def full_batch_norm(x, n_out, phase_train, scope='bn'): with tf.variable_scope(scope): beta = tf.Variable(tf.constant(0.0, shape=[n_out]), name='beta', trainable=True) gamma = tf.Variable(tf.constant(1.0, shape=[n_out]), name='gamma', trainable=True) (batch_mean, batch_var) = tf.nn.moments(x...
['def', 'full_batch_norm(x,', 'n_out,', 'phase_train,', "scope='bn'):", 'with', 'tf.variable_scope(scope):', 'beta', '=', 'tf.Variable(tf.constant(0.0,', 'shape=[n_out]),', "name='beta',", 'trainable=True)', 'gamma', '=', 'tf.Variable(tf.constant(1.0,', 'shape=[n_out]),', "name='gamma',", 'trainable=True)', '(batch_mea...
433,736
suarez12138/AI-Reversi_IMP_TextDichotomy
backend_bases.py
RendererBase.draw_quad_mesh
draw_quad_mesh
Fallback implementation of :meth:`draw_quad_mesh` that generates paths and then calls :meth:`draw_path_collection`.
[ "Fallback", "implementation", "of", ":meth:`draw_quad_mesh`", "that", "generates", "paths", "and", "then", "calls", ":meth:`draw_path_collection`." ]
def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, edgecolors): from matplotlib.collections import QuadMesh paths = QuadMesh.convert_mesh_to_paths(meshWidth, meshHeight, coordinates) if edgecolors is None: edgecolors = fa...
['def', 'draw_quad_mesh(self,', 'gc,', 'master_transform,', 'meshWidth,', 'meshHeight,', 'coordinates,', 'offsets,', 'offsetTrans,', 'facecolors,', 'antialiased,', 'edgecolors):', 'from', 'matplotlib.collections', 'import', 'QuadMesh', 'paths', '=', 'QuadMesh.convert_mesh_to_paths(meshWidth,', 'meshHeight,', 'coordinat...
96,136
RasaHQ/rasa
server.py
create_app
create_app
Class representing a Rasa HTTP server.
[ "Class", "representing", "a", "Rasa", "HTTP", "server." ]
def create_app(agent: Optional['Agent']=None, cors_origins: Union[Text, List[Text], None]='*', auth_token: Optional[Text]=None, response_timeout: int=DEFAULT_RESPONSE_TIMEOUT, jwt_secret: Optional[Text]=None, jwt_private_key: Optional[Text]=None, jwt_method: Text='HS256', endpoints: Optional[AvailableEndpoints]=None) -...
['def', 'create_app(agent:', "Optional['Agent']=None,", 'cors_origins:', 'Union[Text,', 'List[Text],', "None]='*',", 'auth_token:', 'Optional[Text]=None,', 'response_timeout:', 'int=DEFAULT_RESPONSE_TIMEOUT,', 'jwt_secret:', 'Optional[Text]=None,', 'jwt_private_key:', 'Optional[Text]=None,', 'jwt_method:', "Text='HS256...
836,552
ivanmontero/autobot
optimization_tf.py
GradientAccumulator.gradients
gradients
The accumulated gradients on the current replica.
[ "The", "accumulated", "gradients", "on", "the", "current", "replica." ]
def gradients(self): if not self._gradients: raise ValueError('The accumulator should be called first to initialize the gradients') return list((gradient.value() if gradient is not None else gradient for gradient in self._gradients))
['def', 'gradients(self):', 'if', 'not', 'self._gradients:', 'raise', "ValueError('The", 'accumulator', 'should', 'be', 'called', 'first', 'to', 'initialize', 'the', "gradients')", 'return', 'list((gradient.value()', 'if', 'gradient', 'is', 'not', 'None', 'else', 'gradient', 'for', 'gradient', 'in', 'self._gradients))'...
418,211
hankcs/HanLP
dataset.py
SamplerBuilder.scale
scale
Scale down the ``batch_size`` and ``batch_max_tokens`` to :math:`\frac{1}{\text{gradient_accumulation}}` of them respectively.
[ "Scale", "down", "the", "``batch_size``", "and", "``batch_max_tokens``", "to", ":math:`\\frac{1}{\\text{gradient_accumulation}}`", "of", "them", "respectively." ]
def scale(self, gradient_accumulation): batch_size = self.batch_size batch_max_tokens = self.batch_max_tokens if gradient_accumulation: if batch_size: batch_size //= gradient_accumulation if batch_max_tokens: batch_max_tokens //= gradient_accumulation return (batc...
['def', 'scale(self,', 'gradient_accumulation):', 'batch_size', '=', 'self.batch_size', 'batch_max_tokens', '=', 'self.batch_max_tokens', 'if', 'gradient_accumulation:', 'if', 'batch_size:', 'batch_size', '//=', 'gradient_accumulation', 'if', 'batch_max_tokens:', 'batch_max_tokens', '//=', 'gradient_accumulation', 'ret...
575,682
greydanus/mr_london
datastructures.py
ContentRange.set
set
Simple method to update the ranges.
[ "Simple", "method", "to", "update", "the", "ranges." ]
def set(self, start, stop, length=None, units='bytes'): assert is_byte_range_valid(start, stop, length), 'Bad range provided' self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
['def', 'set(self,', 'start,', 'stop,', 'length=None,', "units='bytes'):", 'assert', 'is_byte_range_valid(start,', 'stop,', 'length),', "'Bad", 'range', "provided'", 'self._units', '=', 'units', 'self._start', '=', 'start', 'self._stop', '=', 'stop', 'self._length', '=', 'length', 'if', 'self.on_update', 'is', 'not', '...
264,051
zcablii/LSKNet
re_resnet.py
ReResNet.forward
forward
Forward function of ReResNet.
[ "Forward", "function", "of", "ReResNet." ]
def forward(self, x): if not self.deep_stem: x = enn.GeometricTensor(x, self.in_type) x = self.conv1(x) x = self.norm1(x) x = self.relu(x) x = self.maxpool(x) outs = [] for (i, layer_name) in enumerate(self.res_layers): res_layer = getattr(self, layer_name) ...
['def', 'forward(self,', 'x):', 'if', 'not', 'self.deep_stem:', 'x', '=', 'enn.GeometricTensor(x,', 'self.in_type)', 'x', '=', 'self.conv1(x)', 'x', '=', 'self.norm1(x)', 'x', '=', 'self.relu(x)', 'x', '=', 'self.maxpool(x)', 'outs', '=', '[]', 'for', '(i,', 'layer_name)', 'in', 'enumerate(self.res_layers):', 'res_laye...
616,107
enuguru/artificial_intelligence_and_machine_learning
sysconfig.py
get_scheme_names
get_scheme_names
Return a tuple containing the schemes names.
[ "Return", "a", "tuple", "containing", "the", "schemes", "names." ]
def get_scheme_names(): return tuple(sorted(_SCHEMES.sections()))
['def', 'get_scheme_names():', 'return', 'tuple(sorted(_SCHEMES.sections()))']
163,540
zihuitang/medical_AI_platform
pydoc.py
HTMLDoc.formatvalue
formatvalue
Format an argument default value as text.
[ "Format", "an", "argument", "default", "value", "as", "text." ]
def formatvalue(self, object): return self.grey('=' + self.repr(object))
['def', 'formatvalue(self,', 'object):', 'return', "self.grey('='", '+', 'self.repr(object))']
281,228
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
HypothesisTest.PlotCdf
PlotCdf
Draws a Cdf with vertical lines at the observed test stat.
[ "Draws", "a", "Cdf", "with", "vertical", "lines", "at", "the", "observed", "test", "stat." ]
def PlotCdf(self, label=None): def VertLine(x): thinkplot.Plot([x, x], [0, 1], color='0.8') VertLine(self.actual) thinkplot.Cdf(self.test_cdf, label=label)
['def', 'PlotCdf(self,', 'label=None):', 'def', 'VertLine(x):', 'thinkplot.Plot([x,', 'x],', '[0,', '1],', "color='0.8')", 'VertLine(self.actual)', 'thinkplot.Cdf(self.test_cdf,', 'label=label)']
19,475
yihengsun/TransBoost
core.py
ctypes2cupy
ctypes2cupy
Convert a ctypes pointer array to a cupy array.
[ "Convert", "a", "ctypes", "pointer", "array", "to", "a", "cupy", "array." ]
def ctypes2cupy(cptr, length, dtype): import cupy from cupy.cuda.memory import MemoryPointer from cupy.cuda.memory import UnownedMemory CUPY_TO_CTYPES_MAPPING = {cupy.float32: ctypes.c_float, cupy.uint32: ctypes.c_uint} if dtype not in CUPY_TO_CTYPES_MAPPING.keys(): raise RuntimeError('Suppo...
['def', 'ctypes2cupy(cptr,', 'length,', 'dtype):', 'import', 'cupy', 'from', 'cupy.cuda.memory', 'import', 'MemoryPointer', 'from', 'cupy.cuda.memory', 'import', 'UnownedMemory', 'CUPY_TO_CTYPES_MAPPING', '=', '{cupy.float32:', 'ctypes.c_float,', 'cupy.uint32:', 'ctypes.c_uint}', 'if', 'dtype', 'not', 'in', 'CUPY_TO_CT...
920,496
tobegit3hub/deep_image_model
tensor_shape.py
TensorShape.with_rank_at_most
with_rank_at_most
Returns a shape based on `self` with at most the given rank.
[ "Returns", "a", "shape", "based", "on", "`self`", "with", "at", "most", "the", "given", "rank." ]
def with_rank_at_most(self, rank): if self.ndims is not None and self.ndims > rank: raise ValueError('Shape %s must have rank at most %d' % (self, rank)) else: return self
['def', 'with_rank_at_most(self,', 'rank):', 'if', 'self.ndims', 'is', 'not', 'None', 'and', 'self.ndims', '>', 'rank:', 'raise', "ValueError('Shape", '%s', 'must', 'have', 'rank', 'at', 'most', "%d'", '%', '(self,', 'rank))', 'else:', 'return', 'self']
182,648
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
build_models
build_models
Build the combined feature extraction and delta model.
[ "Build", "the", "combined", "feature", "extraction", "and", "delta", "model." ]
def build_models(audio_len): num_samples = get_num_samples(audio_len) assert num_samples, num_samples return (FEAT_EXTRACTOR, build_delta(num_samples))
['def', 'build_models(audio_len):', 'num_samples', '=', 'get_num_samples(audio_len)', 'assert', 'num_samples,', 'num_samples', 'return', '(FEAT_EXTRACTOR,', 'build_delta(num_samples))']
921,450
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
_reloader.py
run_with_reloader
run_with_reloader
Run the given function in an independent python interpreter.
[ "Run", "the", "given", "function", "in", "an", "independent", "python", "interpreter." ]
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type='auto'): import signal reloader = reloader_loops[reloader_type](extra_files, interval) signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get('WERKZEUG_RUN_MAIN') == 'true': ensure_e...
['def', 'run_with_reloader(main_func,', 'extra_files=None,', 'interval=1,', "reloader_type='auto'):", 'import', 'signal', 'reloader', '=', 'reloader_loops[reloader_type](extra_files,', 'interval)', 'signal.signal(signal.SIGTERM,', 'lambda', '*args:', 'sys.exit(0))', 'try:', 'if', "os.environ.get('WERKZEUG_RUN_MAIN')", ...
85,028
crestonbunch/tbcnn
sampling.py
batch_samples
batch_samples
Batch samples and return batches in a generator.
[ "Batch", "samples", "and", "return", "batches", "in", "a", "generator." ]
def batch_samples(samples, batch_size): batch = ([], []) count = 0 index_of = lambda x: NODE_MAP[x] for sample in samples: if sample['parent'] is not None: batch[0].append(index_of(sample['node'])) batch[1].append(index_of(sample['parent'])) count += 1 ...
['def', 'batch_samples(samples,', 'batch_size):', 'batch', '=', '([],', '[])', 'count', '=', '0', 'index_of', '=', 'lambda', 'x:', 'NODE_MAP[x]', 'for', 'sample', 'in', 'samples:', 'if', "sample['parent']", 'is', 'not', 'None:', "batch[0].append(index_of(sample['node']))", "batch[1].append(index_of(sample['parent']))",...
365,589
clear-nus/MuMMI
dog.py
Physics.torso_com_velocity
torso_com_velocity
Returns the velocity of the center-of-mass in the torso frame.
[ "Returns", "the", "velocity", "of", "the", "center-of-mass", "in", "the", "torso", "frame." ]
def torso_com_velocity(self): torso_frame = self.named.data.xmat['torso'].reshape(3, 3).copy() return self.center_of_mass_velocity().dot(torso_frame)
['def', 'torso_com_velocity(self):', 'torso_frame', '=', "self.named.data.xmat['torso'].reshape(3,", '3).copy()', 'return', 'self.center_of_mass_velocity().dot(torso_frame)']
265,938
jeromewang-github/computer_vision
detection_inference.py
infer_detections_and_add_to_example
infer_detections_and_add_to_example
Runs the supplied tensors and adds the inferred detections to the example.
[ "Runs", "the", "supplied", "tensors", "and", "adds", "the", "inferred", "detections", "to", "the", "example." ]
def infer_detections_and_add_to_example(serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, discard_image_pixels): tf_example = tf.train.Example() (serialized_example, detected_boxes, detected_scores, detected_classes) = tf.get_default_session().run([serialized_exam...
['def', 'infer_detections_and_add_to_example(serialized_example_tensor,', 'detected_boxes_tensor,', 'detected_scores_tensor,', 'detected_labels_tensor,', 'discard_image_pixels):', 'tf_example', '=', 'tf.train.Example()', '(serialized_example,', 'detected_boxes,', 'detected_scores,', 'detected_classes)', '=', 'tf.get_de...
506,059
jhultman/vision3d
bev_drawer.py
make_bev_map
make_bev_map
Scatter points to create sparse occupancy image.
[ "Scatter", "points", "to", "create", "sparse", "occupancy", "image." ]
def make_bev_map(points, pixel_size, bounds): mask = ((points > bounds[:2]) & (points < bounds[2:])).all(1) shape = np.int32(np.ceil((bounds[2:] - bounds[:2]) / pixel_size))[::-1] pixels = np.int32(np.floor((points[mask] - bounds[:2]) / pixel_size)) (pixels, counts) = np.unique(pixels, return_counts=Tru...
['def', 'make_bev_map(points,', 'pixel_size,', 'bounds):', 'mask', '=', '((points', '>', 'bounds[:2])', '&', '(points', '<', 'bounds[2:])).all(1)', 'shape', '=', 'np.int32(np.ceil((bounds[2:]', '-', 'bounds[:2])', '/', 'pixel_size))[::-1]', 'pixels', '=', 'np.int32(np.floor((points[mask]', '-', 'bounds[:2])', '/', 'pix...
944,792
deepmind/dm_control
lqr.py
Physics.state_norm
state_norm
Returns the norm of the physics state.
[ "Returns", "the", "norm", "of", "the", "physics", "state." ]
def state_norm(self): return np.linalg.norm(self.state())
['def', 'state_norm(self):', 'return', 'np.linalg.norm(self.state())']
165,505