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
AstraZeneca/SubTab
model.py
SubTab.load_models
load_models
Used to load weights saved at the end of the training.
[ "Used", "to", "load", "weights", "saved", "at", "the", "end", "of", "the", "training." ]
def load_models(self): for model_name in self.model_dict: model = th.load(self._model_path + '/' + model_name + '.pt', map_location=self.device) setattr(self, model_name, model.eval()) print(f'--{model_name} is loaded') print('Done with loading models.')
['def', 'load_models(self):', 'for', 'model_name', 'in', 'self.model_dict:', 'model', '=', 'th.load(self._model_path', '+', "'/'", '+', 'model_name', '+', "'.pt',", 'map_location=self.device)', 'setattr(self,', 'model_name,', 'model.eval())', "print(f'--{model_name}", 'is', "loaded')", "print('Done", 'with', 'loading',...
360,028
gopinath-balu/computer_vision
np_mask_ops.py
iou
iou
Computes pairwise intersection-over-union between mask collections.
[ "Computes", "pairwise", "intersection-over-union", "between", "mask", "collections." ]
def iou(masks1, masks2): if masks1.dtype != np.uint8 or masks2.dtype != np.uint8: raise ValueError('masks1 and masks2 should be of type np.uint8') intersect = intersection(masks1, masks2) area1 = area(masks1) area2 = area(masks2) union = np.expand_dims(area1, axis=1) + np.expand_dims(area2, ...
['def', 'iou(masks1,', 'masks2):', 'if', 'masks1.dtype', '!=', 'np.uint8', 'or', 'masks2.dtype', '!=', 'np.uint8:', 'raise', "ValueError('masks1", 'and', 'masks2', 'should', 'be', 'of', 'type', "np.uint8')", 'intersect', '=', 'intersection(masks1,', 'masks2)', 'area1', '=', 'area(masks1)', 'area2', '=', 'area(masks2)',...
513,161
clips/pattern
inflect.py
referenced
referenced
Returns a string with the article + the word.
[ "Returns", "a", "string", "with", "the", "article", "+", "the", "word." ]
def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT): return '%s %s' % (_article(word, article, gender, role), word)
['def', 'referenced(word,', 'article=INDEFINITE,', 'gender=MALE,', 'role=SUBJECT):', 'return', "'%s", "%s'", '%', '(_article(word,', 'article,', 'gender,', 'role),', 'word)']
764,850
NJU-LHRS/official-CMID
distribute.py
setup_print_for_distributed
setup_print_for_distributed
This function disables printing when not in master process.
[ "This", "function", "disables", "printing", "when", "not", "in", "master", "process." ]
def setup_print_for_distributed(is_master: bool) -> None: import builtins builtin_print = builtins.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) builtins.print = print
['def', 'setup_print_for_distributed(is_master:', 'bool)', '->', 'None:', 'import', 'builtins', 'builtin_print', '=', 'builtins.print', 'def', 'print(*args,', '**kwargs):', 'force', '=', "kwargs.pop('force',", 'False)', 'if', 'is_master', 'or', 'force:', 'builtin_print(*args,', '**kwargs)', 'builtins.print', '=', 'prin...
250,180
berlius/artificial-intelligence
test_ufunc.py
TestUfunc.test_cross1d
test_cross1d
Test with fixed-sized signature.
[ "Test", "with", "fixed-sized", "signature." ]
def test_cross1d(self): a = np.eye(3) assert_array_equal(umt.cross1d(a, a), np.zeros((3, 3))) out = np.zeros((3, 3)) result = umt.cross1d(a[0], a, out) assert_(result is out) assert_array_equal(result, np.vstack((np.zeros(3), a[2], -a[1]))) assert_raises(ValueError, umt.cross1d, np.eye(4), n...
['def', 'test_cross1d(self):', 'a', '=', 'np.eye(3)', 'assert_array_equal(umt.cross1d(a,', 'a),', 'np.zeros((3,', '3)))', 'out', '=', 'np.zeros((3,', '3))', 'result', '=', 'umt.cross1d(a[0],', 'a,', 'out)', 'assert_(result', 'is', 'out)', 'assert_array_equal(result,', 'np.vstack((np.zeros(3),', 'a[2],', '-a[1])))', 'as...
61,920
aeon-toolkit/aeon
test_fh.py
test_check_fh_absolute_values_input_conversion_to_pandas_index
test_check_fh_absolute_values_input_conversion_to_pandas_index
Test conversion of absolute horizons to pandas index.
[ "Test", "conversion", "of", "absolute", "horizons", "to", "pandas", "index." ]
def test_check_fh_absolute_values_input_conversion_to_pandas_index(arg): assert is_in_valid_index_types(ForecastingHorizon(arg, is_relative=False).to_pandas())
['def', 'test_check_fh_absolute_values_input_conversion_to_pandas_index(arg):', 'assert', 'is_in_valid_index_types(ForecastingHorizon(arg,', 'is_relative=False).to_pandas())']
399,574
QData/deepWordBug
math2html.py
Globable.globvalue
globvalue
Glob a value: any symbols but brackets.
[ "Glob", "a", "value:", "any", "symbols", "but", "brackets." ]
def globvalue(self): return self.glob(self.isvalue)
['def', 'globvalue(self):', 'return', 'self.glob(self.isvalue)']
542,386
yihengsun/TransBoost
sklearn.py
XGBModel.get_num_boosting_rounds
get_num_boosting_rounds
Gets the number of xgboost boosting rounds.
[ "Gets", "the", "number", "of", "xgboost", "boosting", "rounds." ]
def get_num_boosting_rounds(self): return self.n_estimators
['def', 'get_num_boosting_rounds(self):', 'return', 'self.n_estimators']
920,553
dguo98/DiffPruning
distiller.py
Distiller.iter
iter
Update global counts, write to tensorboard and save checkpoint.
[ "Update", "global", "counts,", "write", "to", "tensorboard", "and", "save", "checkpoint." ]
def iter(self): self.n_iter += 1 self.n_total_iter += 1 if self.n_total_iter % self.params.log_interval == 0: self.log_tensorboard() self.last_log = time.time() if self.n_total_iter % self.params.checkpoint_interval == 0: self.save_checkpoint()
['def', 'iter(self):', 'self.n_iter', '+=', '1', 'self.n_total_iter', '+=', '1', 'if', 'self.n_total_iter', '%', 'self.params.log_interval', '==', '0:', 'self.log_tensorboard()', 'self.last_log', '=', 'time.time()', 'if', 'self.n_total_iter', '%', 'self.params.checkpoint_interval', '==', '0:', 'self.save_checkpoint()']
550,874
sek788432/Waymo-2D-Object-Detection
datum_io.py
ParseFromString
ParseFromString
Converts serialized DatumProto string to NumPy array.
[ "Converts", "serialized", "DatumProto", "string", "to", "NumPy", "array." ]
def ParseFromString(string): datum = datum_pb2.DatumProto() datum.ParseFromString(string) return DatumToArray(datum)
['def', 'ParseFromString(string):', 'datum', '=', 'datum_pb2.DatumProto()', 'datum.ParseFromString(string)', 'return', 'DatumToArray(datum)']
974,227
paperswithcode/torchbench
utils.py
list_dir
list_dir
List all directories at a given root.
[ "List", "all", "directories", "at", "a", "given", "root." ]
def list_dir(root, prefix=False): root = os.path.expanduser(root) directories = list(filter(lambda p: os.path.isdir(os.path.join(root, p)), os.listdir(root))) if prefix is True: directories = [os.path.join(root, d) for d in directories] return directories
['def', 'list_dir(root,', 'prefix=False):', 'root', '=', 'os.path.expanduser(root)', 'directories', '=', 'list(filter(lambda', 'p:', 'os.path.isdir(os.path.join(root,', 'p)),', 'os.listdir(root)))', 'if', 'prefix', 'is', 'True:', 'directories', '=', '[os.path.join(root,', 'd)', 'for', 'd', 'in', 'directories]', 'return...
902,486
georghess/voxel-mae
kitti_dataset.py
KittiDataset.evaluate
evaluate
Evaluation in KITTI protocol.
[ "Evaluation", "in", "KITTI", "protocol." ]
def evaluate(self, results, metric=None, logger=None, pklfile_prefix=None, submission_prefix=None, show=False, out_dir=None, pipeline=None): (result_files, tmp_dir) = self.format_results(results, pklfile_prefix) from mmdet3d.core.evaluation import kitti_eval gt_annos = [info['annos'] for info in self.data_i...
['def', 'evaluate(self,', 'results,', 'metric=None,', 'logger=None,', 'pklfile_prefix=None,', 'submission_prefix=None,', 'show=False,', 'out_dir=None,', 'pipeline=None):', '(result_files,', 'tmp_dir)', '=', 'self.format_results(results,', 'pklfile_prefix)', 'from', 'mmdet3d.core.evaluation', 'import', 'kitti_eval', 'gt...
380,538
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
inception_model.py
inception_v3_parameters
inception_v3_parameters
Yields the scope with the default parameters for inception_v3.
[ "Yields", "the", "scope", "with", "the", "default", "parameters", "for", "inception_v3." ]
def inception_v3_parameters(weight_decay=4e-05, stddev=0.1, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with scopes.arg_scope([ops.conv2d, ops.fc], weight_decay=weight_decay): with scopes.arg_scope([ops.conv2d], stddev=stddev, activation=tf.nn.relu, batch_norm_params={'decay': batch_norm_decay, 'eps...
['def', 'inception_v3_parameters(weight_decay=4e-05,', 'stddev=0.1,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001):', 'with', 'scopes.arg_scope([ops.conv2d,', 'ops.fc],', 'weight_decay=weight_decay):', 'with', 'scopes.arg_scope([ops.conv2d],', 'stddev=stddev,', 'activation=tf.nn.relu,', "batch_norm_params={'d...
49,018
mandrakedrink/BraTS20_Unet3d_AutoEncoder
visualizer.py
ShowResult.image_preprocessing
image_preprocessing
Returns image flair as mask for overlaping gt and predictions.
[ "Returns", "image", "flair", "as", "mask", "for", "overlaping", "gt", "and", "predictions." ]
def image_preprocessing(self, image): image = image.squeeze().cpu().detach().numpy() image = np.moveaxis(image, (0, 1, 2, 3), (0, 3, 2, 1)) flair_img = np.rot90(montage(image[0])) return flair_img
['def', 'image_preprocessing(self,', 'image):', 'image', '=', 'image.squeeze().cpu().detach().numpy()', 'image', '=', 'np.moveaxis(image,', '(0,', '1,', '2,', '3),', '(0,', '3,', '2,', '1))', 'flair_img', '=', 'np.rot90(montage(image[0]))', 'return', 'flair_img']
409,560
ZhAnGToNG1/transfer_learning_cspt
anchor_free_head.py
AnchorFreeHead.get_targets
get_targets
Compute regression, classification and centerness targets for points in multiple images.
[ "Compute", "regression,", "classification", "and", "centerness", "targets", "for", "points", "in", "multiple", "images." ]
def get_targets(self, points, gt_bboxes_list, gt_labels_list): raise NotImplementedError
['def', 'get_targets(self,', 'points,', 'gt_bboxes_list,', 'gt_labels_list):', 'raise', 'NotImplementedError']
963,928
weimin17/Object-Detection_HelmetDetection
baseline.py
Baseline.get_values
get_values
Get value estimates given input.
[ "Get", "value", "estimates", "given", "input." ]
def get_values(self, all_obs, all_actions, internal_policy_states, policy_logits): batch_size = tf.shape(all_obs[0])[1] time_length = tf.shape(all_obs[0])[0] (time_step, reshaped_obs, reshaped_prev_act, reshaped_internal_policy_states, reshaped_policy_logits) = self.reshape_batched_inputs(all_obs, all_actio...
['def', 'get_values(self,', 'all_obs,', 'all_actions,', 'internal_policy_states,', 'policy_logits):', 'batch_size', '=', 'tf.shape(all_obs[0])[1]', 'time_length', '=', 'tf.shape(all_obs[0])[0]', '(time_step,', 'reshaped_obs,', 'reshaped_prev_act,', 'reshaped_internal_policy_states,', 'reshaped_policy_logits)', '=', 'se...
759,348
dibyaghosh/gcsl
configurable_test.py
TestConfigurable.test_set_config_inheritance
test_set_config_inheritance
Tests config values for a child class.
[ "Tests", "config", "values", "for", "a", "child", "class." ]
def test_set_config_inheritance(self): TEST_CONFIGS[ChildDummyWithConfig] = {'a': 4, 'c': 5} d1 = ChildDummyWithConfig() self.assertEqual(d1.a, 4) self.assertEqual(d1.b, 2) self.assertEqual(d1.c, 5) d2 = DummyWithConfig() self.assertEqual(d2.a, 1) self.assertEqual(d2.b, 2) self.asser...
['def', 'test_set_config_inheritance(self):', 'TEST_CONFIGS[ChildDummyWithConfig]', '=', "{'a':", '4,', "'c':", '5}', 'd1', '=', 'ChildDummyWithConfig()', 'self.assertEqual(d1.a,', '4)', 'self.assertEqual(d1.b,', '2)', 'self.assertEqual(d1.c,', '5)', 'd2', '=', 'DummyWithConfig()', 'self.assertEqual(d2.a,', '1)', 'self...
202,085
Stable-Baselines-Team/stable-baselines
dummy_vec_env.py
DummyVecEnv.env_method
env_method
Call instance methods of vectorized environments.
[ "Call", "instance", "methods", "of", "vectorized", "environments." ]
def env_method(self, method_name, *method_args, indices=None, **method_kwargs): target_envs = self._get_target_envs(indices) return [getattr(env_i, method_name)(*method_args, **method_kwargs) for env_i in target_envs]
['def', 'env_method(self,', 'method_name,', '*method_args,', 'indices=None,', '**method_kwargs):', 'target_envs', '=', 'self._get_target_envs(indices)', 'return', '[getattr(env_i,', 'method_name)(*method_args,', '**method_kwargs)', 'for', 'env_i', 'in', 'target_envs]']
873,144
kukuruza/shuffler
media_test.py
Test_cropObjects_carsDb.test_namehint_addObjectNameToFilename
test_namehint_addObjectNameToFilename
Test 'namehint' when add_object_name_to_filename is on.
[ "Test", "'namehint'", "when", "add_object_name_to_filename", "is", "on." ]
def test_namehint_addObjectNameToFilename(self, mock_imwriter): mock_imwriter.return_value.imwrite.side_effect = ['foo', 'bar', 'baz'] c = self.conn.cursor() args = argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR, media='pictures', image_path='mock_media', mask_path=None, where_object='...
['def', 'test_namehint_addObjectNameToFilename(self,', 'mock_imwriter):', 'mock_imwriter.return_value.imwrite.side_effect', '=', "['foo',", "'bar',", "'baz']", 'c', '=', 'self.conn.cursor()', 'args', '=', 'argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR,', "media='pictures',", "image_path='mock_med...
933,849
AndrewYinLi/lstm-neural-network-spam-filter
agreement.py
AnnotationTask.avg_Ao
avg_Ao
Average observed agreement across all coders and items.
[ "Average", "observed", "agreement", "across", "all", "coders", "and", "items." ]
def avg_Ao(self): ret = self._pairwise_average(self.Ao) log.debug('Average observed agreement: %f', ret) return ret
['def', 'avg_Ao(self):', 'ret', '=', 'self._pairwise_average(self.Ao)', "log.debug('Average", 'observed', 'agreement:', "%f',", 'ret)', 'return', 'ret']
218,008
LiangHann/Denoising-Hyperspectral-Images-by-Unsupervised-Deep-
common_utils.py
get_params
get_params
Returns parameters that we want to optimize over.
[ "Returns", "parameters", "that", "we", "want", "to", "optimize", "over." ]
def get_params(opt_over, net, net_input, downsampler=None): opt_over_list = opt_over.split(',') params = [] for opt in opt_over_list: if opt == 'net': params += [x for x in net.parameters()] elif opt == 'down': assert downsampler is not None params = [x fo...
['def', 'get_params(opt_over,', 'net,', 'net_input,', 'downsampler=None):', 'opt_over_list', '=', "opt_over.split(',')", 'params', '=', '[]', 'for', 'opt', 'in', 'opt_over_list:', 'if', 'opt', '==', "'net':", 'params', '+=', '[x', 'for', 'x', 'in', 'net.parameters()]', 'elif', 'opt', '==', "'down':", 'assert', 'downsam...
183,769
huawei-noah/xingtian
share_buffer.py
check_equal_dict
check_equal_dict
Check dict if equal.
[ "Check", "dict", "if", "equal." ]
def check_equal_dict(d1: dict, d2: dict): assert d1.keys() == d2.keys() for (_k, val) in d1.items(): if isinstance(val, np.ndarray): assert (val == d2[_k]).all(), '{} vs {}'.format(val, d2[_k]) else: assert val == d2[_k], '{} vs {}'.format(val, d2[_k])
['def', 'check_equal_dict(d1:', 'dict,', 'd2:', 'dict):', 'assert', 'd1.keys()', '==', 'd2.keys()', 'for', '(_k,', 'val)', 'in', 'd1.items():', 'if', 'isinstance(val,', 'np.ndarray):', 'assert', '(val', '==', 'd2[_k]).all(),', "'{}", 'vs', "{}'.format(val,", 'd2[_k])', 'else:', 'assert', 'val', '==', 'd2[_k],', "'{}", ...
962,360
thu-ml/tianshou
utils.py
test_episode
test_episode
A simple wrapper of testing policy in collector.
[ "A", "simple", "wrapper", "of", "testing", "policy", "in", "collector." ]
def test_episode(policy: BasePolicy, collector: Collector, test_fn: Optional[Callable[[int, Optional[int]], None]], epoch: int, n_episode: int, logger: Optional[BaseLogger]=None, global_step: Optional[int]=None, reward_metric: Optional[Callable[[np.ndarray], np.ndarray]]=None) -> dict[str, Any]: collector.reset_env...
['def', 'test_episode(policy:', 'BasePolicy,', 'collector:', 'Collector,', 'test_fn:', 'Optional[Callable[[int,', 'Optional[int]],', 'None]],', 'epoch:', 'int,', 'n_episode:', 'int,', 'logger:', 'Optional[BaseLogger]=None,', 'global_step:', 'Optional[int]=None,', 'reward_metric:', 'Optional[Callable[[np.ndarray],', 'np...
355,298
apeterswu/RL4NMT
bluenet.py
multi_subseparable_conv
multi_subseparable_conv
Simultaneously compute different kinds of convolutions on subsets of input.
[ "Simultaneously", "compute", "different", "kinds", "of", "convolutions", "on", "subsets", "of", "input." ]
def multi_subseparable_conv(inputs, filters, kernel_sizes, input_channels, separabilities, kernel_selection_weights=None, channel_selection_weights=None, separability_selection_weights=None, kernel_selection_weights_params=None, channel_selection_weights_params=None, separability_selection_weights_params=None, kernel_i...
['def', 'multi_subseparable_conv(inputs,', 'filters,', 'kernel_sizes,', 'input_channels,', 'separabilities,', 'kernel_selection_weights=None,', 'channel_selection_weights=None,', 'separability_selection_weights=None,', 'kernel_selection_weights_params=None,', 'channel_selection_weights_params=None,', 'separability_sele...
331,137
Sentdex/Carla-RL
tcp.py
TCPClient.write
write
Send message to the server.
[ "Send", "message", "to", "the", "server." ]
def write(self, message): if self._socket is None: raise TCPConnectionError(self._logprefix + 'not connected') header = struct.pack('<L', len(message)) try: self._socket.sendall(header + message) except socket.error as exception: self._reraise_exception_as_tcp_error('failed to wr...
['def', 'write(self,', 'message):', 'if', 'self._socket', 'is', 'None:', 'raise', 'TCPConnectionError(self._logprefix', '+', "'not", "connected')", 'header', '=', "struct.pack('<L',", 'len(message))', 'try:', 'self._socket.sendall(header', '+', 'message)', 'except', 'socket.error', 'as', 'exception:', "self._reraise_ex...
103,020
idptools/sparrow
versioneer.py
run_command
run_command
Call the given command(s).
[ "Call", "the", "given", "command(s)." ]
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIP...
['def', 'run_command(commands,', 'args,', 'cwd=None,', 'verbose=False,', 'hide_stderr=False,', 'env=None):', 'assert', 'isinstance(commands,', 'list)', 'p', '=', 'None', 'for', 'c', 'in', 'commands:', 'try:', 'dispcmd', '=', 'str([c]', '+', 'args)', 'p', '=', 'subprocess.Popen([c]', '+', 'args,', 'cwd=cwd,', 'env=env,'...
894,522
MycroftAI/mycroft-core
config.py
translate_list
translate_list
Translate list formated by mycroft server.
[ "Translate", "list", "formated", "by", "mycroft", "server." ]
def translate_list(config, values): for v in values: module = v['@type'] if v.get('active'): config['module'] = module config[module] = config.get(module, {}) translate_remote(config[module], v)
['def', 'translate_list(config,', 'values):', 'for', 'v', 'in', 'values:', 'module', '=', "v['@type']", 'if', "v.get('active'):", "config['module']", '=', 'module', 'config[module]', '=', 'config.get(module,', '{})', 'translate_remote(config[module],', 'v)']
290,330
devashish-patel/webcam-motion-detector
interface.py
CommandLineInterface.focus
focus
Focus the buffer with the given name on the focus stack.
[ "Focus", "the", "buffer", "with", "the", "given", "name", "on", "the", "focus", "stack." ]
def focus(self, buffer_name): self.buffers.focus(self, buffer_name)
['def', 'focus(self,', 'buffer_name):', 'self.buffers.focus(self,', 'buffer_name)']
983,764
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
MethodContent.acceptExpr
acceptExpr
Creates a new expression.
[ "Creates", "a", "new", "expression." ]
def acceptExpr(self, node, memo): if node.parentType in self.goodExprParents: return self.factory.expr(parent=self)
['def', 'acceptExpr(self,', 'node,', 'memo):', 'if', 'node.parentType', 'in', 'self.goodExprParents:', 'return', 'self.factory.expr(parent=self)']
17,095
hhkunming/State-Frequency-Memory---
MidiOutStream.py
MidiOutStream.update_time
update_time
Updates the time, if relative is true, new_time is relative, else it's absolute.
[ "Updates", "the", "time,", "if", "relative", "is", "true,", "new_time", "is", "relative,", "else", "it's", "absolute." ]
def update_time(self, new_time=0, relative=1): if relative: self._relative_time = new_time self._absolute_time += new_time else: self._relative_time = new_time - self._absolute_time self._absolute_time = new_time
['def', 'update_time(self,', 'new_time=0,', 'relative=1):', 'if', 'relative:', 'self._relative_time', '=', 'new_time', 'self._absolute_time', '+=', 'new_time', 'else:', 'self._relative_time', '=', 'new_time', '-', 'self._absolute_time', 'self._absolute_time', '=', 'new_time']
383,768
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
range.py
RangeIndex.step
step
The value of the `step` parameter (``1`` if this was not supplied).
[ "The", "value", "of", "the", "`step`", "parameter", "(``1``", "if", "this", "was", "not", "supplied)." ]
def step(self): return self._range.step
['def', 'step(self):', 'return', 'self._range.step']
82,981
mo-cv/pycv
filters.py
VConvolutionFilter.apply
apply
Apply the filter with a BGR or gray source/destination.
[ "Apply", "the", "filter", "with", "a", "BGR", "or", "gray", "source/destination." ]
def apply(self, src, dst): cv2.filter2D(src, -1, self._kernel, dst)
['def', 'apply(self,', 'src,', 'dst):', 'cv2.filter2D(src,', '-1,', 'self._kernel,', 'dst)']
819,488
scikit-learn/scikit-learn
test_boundary_decision_display.py
test_multilabel_classifier_error
test_multilabel_classifier_error
Check that multilabel classifier raises correct error.
[ "Check", "that", "multilabel", "classifier", "raises", "correct", "error." ]
def test_multilabel_classifier_error(pyplot, response_method): (X, y) = make_multilabel_classification(random_state=0) X = X[:, :2] tree = DecisionTreeClassifier().fit(X, y) msg = 'Multi-label and multi-output multi-class classifiers are not supported' with pytest.raises(ValueError, match=msg): ...
['def', 'test_multilabel_classifier_error(pyplot,', 'response_method):', '(X,', 'y)', '=', 'make_multilabel_classification(random_state=0)', 'X', '=', 'X[:,', ':2]', 'tree', '=', 'DecisionTreeClassifier().fit(X,', 'y)', 'msg', '=', "'Multi-label", 'and', 'multi-output', 'multi-class', 'classifiers', 'are', 'not', "supp...
853,458
43Carrig/recurrent_neural_networks_practice
model.py
ranking_model_builder
ranking_model_builder
Multi-machine batch gradient descent tree model for ranking.
[ "Multi-machine", "batch", "gradient", "descent", "tree", "model", "for", "ranking." ]
def ranking_model_builder(features, labels, mode, params, config, output_type=ModelBuilderOutputType.MODEL_FN_OPS): head = params['head'] learner_config = params['learner_config'] examples_per_layer = params['examples_per_layer'] feature_columns = params['feature_columns'] weight_column_name = param...
['def', 'ranking_model_builder(features,', 'labels,', 'mode,', 'params,', 'config,', 'output_type=ModelBuilderOutputType.MODEL_FN_OPS):', 'head', '=', "params['head']", 'learner_config', '=', "params['learner_config']", 'examples_per_layer', '=', "params['examples_per_layer']", 'feature_columns', '=', "params['feature_...
312,473
AndrewYinLi/lstm-neural-network-spam-filter
text.py
Text.count
count
Count the number of times this word appears in the text.
[ "Count", "the", "number", "of", "times", "this", "word", "appears", "in", "the", "text." ]
def count(self, word): return self.tokens.count(word)
['def', 'count(self,', 'word):', 'return', 'self.tokens.count(word)']
217,371
sktime/sktime
results.py
HDDResults.load_fitted_strategy
load_fitted_strategy
Load saved (fitted) strategy.
[ "Load", "saved", "(fitted)", "strategy." ]
def load_fitted_strategy(self, strategy_name, dataset_name, cv_fold): for (strategy_name, dataset_name) in self._iter(): key = self._generate_key(strategy_name, dataset_name, cv_fold, train_or_test='train') + '.pickle' return load(key)
['def', 'load_fitted_strategy(self,', 'strategy_name,', 'dataset_name,', 'cv_fold):', 'for', '(strategy_name,', 'dataset_name)', 'in', 'self._iter():', 'key', '=', 'self._generate_key(strategy_name,', 'dataset_name,', 'cv_fold,', "train_or_test='train')", '+', "'.pickle'", 'return', 'load(key)']
885,849
microsoft/nni
graph.py
Graph.extract_descriptor
extract_descriptor
Extract the the description of the Graph as an instance of NetworkDescriptor.
[ "Extract", "the", "the", "description", "of", "the", "Graph", "as", "an", "instance", "of", "NetworkDescriptor." ]
def extract_descriptor(self): main_chain = self.get_main_chain() index_in_main_chain = {} for (index, u) in enumerate(main_chain): index_in_main_chain[u] = index ret = NetworkDescriptor() for u in main_chain: for (v, layer_id) in self.adj_list[u]: if v not in index_in_mai...
['def', 'extract_descriptor(self):', 'main_chain', '=', 'self.get_main_chain()', 'index_in_main_chain', '=', '{}', 'for', '(index,', 'u)', 'in', 'enumerate(main_chain):', 'index_in_main_chain[u]', '=', 'index', 'ret', '=', 'NetworkDescriptor()', 'for', 'u', 'in', 'main_chain:', 'for', '(v,', 'layer_id)', 'in', 'self.ad...
728,372
unixpickle/anyrl-py
dqn_dist.py
DistQNetwork.step_feed_dict
step_feed_dict
Produce a feed_dict for taking a step.
[ "Produce", "a", "feed_dict", "for", "taking", "a", "step." ]
def step_feed_dict(self, observations, states): return {self.step_obs_ph: self.obs_vectorizer.to_vecs(observations)}
['def', 'step_feed_dict(self,', 'observations,', 'states):', 'return', '{self.step_obs_ph:', 'self.obs_vectorizer.to_vecs(observations)}']
33,821
csjunxu/Noisy-As-Clean-TIP2020
build.py
validate_system
validate_system
Ensure build system has the requisite fields.
[ "Ensure", "build", "system", "has", "the", "requisite", "fields." ]
def validate_system(system): required = {'requires', 'build-backend'} if not required <= set(system): message = 'Missing required fields: {missing}'.format(missing=required - set(system)) raise ValueError(message)
['def', 'validate_system(system):', 'required', '=', "{'requires',", "'build-backend'}", 'if', 'not', 'required', '<=', 'set(system):', 'message', '=', "'Missing", 'required', 'fields:', "{missing}'.format(missing=required", '-', 'set(system))', 'raise', 'ValueError(message)']
248,467
coldmanck/CS5242-Neural-Network-and--Learning-Assignments
net1-grad-check.py
LinearLayer.get_output
get_output
Perform the forward step linear transformation.
[ "Perform", "the", "forward", "step", "linear", "transformation." ]
def get_output(self, X): return X.dot(self.W) + self.b
['def', 'get_output(self,', 'X):', 'return', 'X.dot(self.W)', '+', 'self.b']
508,236
matsu0228/nlp-jp
client.py
InProcessKernelClient.comm_info
comm_info
Request a dictionary of valid comms and their targets.
[ "Request", "a", "dictionary", "of", "valid", "comms", "and", "their", "targets." ]
def comm_info(self, target_name=None): if target_name is None: content = {} else: content = dict(target_name=target_name) msg = self.session.msg('comm_info_request', content) self._dispatch_to_kernel(msg) return msg['header']['msg_id']
['def', 'comm_info(self,', 'target_name=None):', 'if', 'target_name', 'is', 'None:', 'content', '=', '{}', 'else:', 'content', '=', 'dict(target_name=target_name)', 'msg', '=', "self.session.msg('comm_info_request',", 'content)', 'self._dispatch_to_kernel(msg)', 'return', "msg['header']['msg_id']"]
786,429
georghess/voxel-mae
base_points.py
BasePoints.translate
translate
Translate points with the given translation vector.
[ "Translate", "points", "with", "the", "given", "translation", "vector." ]
def translate(self, trans_vector): if not isinstance(trans_vector, torch.Tensor): trans_vector = self.tensor.new_tensor(trans_vector) trans_vector = trans_vector.squeeze(0) if trans_vector.dim() == 1: assert trans_vector.shape[0] == 3 elif trans_vector.dim() == 2: assert trans_ve...
['def', 'translate(self,', 'trans_vector):', 'if', 'not', 'isinstance(trans_vector,', 'torch.Tensor):', 'trans_vector', '=', 'self.tensor.new_tensor(trans_vector)', 'trans_vector', '=', 'trans_vector.squeeze(0)', 'if', 'trans_vector.dim()', '==', '1:', 'assert', 'trans_vector.shape[0]', '==', '3', 'elif', 'trans_vector...
380,464
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
encoder_manager.py
EncoderManager.close
close
Closes the active TensorFlow Sessions.
[ "Closes", "the", "active", "TensorFlow", "Sessions." ]
def close(self): for sess in self.sessions: sess.close()
['def', 'close(self):', 'for', 'sess', 'in', 'self.sessions:', 'sess.close()']
26,756
cheng052/BRNet
voxel_generator.py
VoxelGenerator.max_num_points_per_voxel
max_num_points_per_voxel
int: Maximum number of points per voxel.
[ "int:", "Maximum", "number", "of", "points", "per", "voxel." ]
def max_num_points_per_voxel(self): return self._max_num_points
['def', 'max_num_points_per_voxel(self):', 'return', 'self._max_num_points']
409,790
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
parser_eval.py
Eval
Eval
Builds and evaluates a network.
[ "Builds", "and", "evaluates", "a", "network." ]
def Eval(sess): task_context = FLAGS.task_context if FLAGS.resource_dir: task_context = RewriteContext(task_context) (feature_sizes, domain_sizes, embedding_dims, num_actions) = sess.run(gen_parser_ops.feature_size(task_context=task_context, arg_prefix=FLAGS.arg_prefix)) t = time.time() hidd...
['def', 'Eval(sess):', 'task_context', '=', 'FLAGS.task_context', 'if', 'FLAGS.resource_dir:', 'task_context', '=', 'RewriteContext(task_context)', '(feature_sizes,', 'domain_sizes,', 'embedding_dims,', 'num_actions)', '=', 'sess.run(gen_parser_ops.feature_size(task_context=task_context,', 'arg_prefix=FLAGS.arg_prefix)...
111,755
pyRiemann/pyRiemann
distance.py
distance_kullback_right
distance_kullback_right
Wrapper for right Kullback-Leibler divergence.
[ "Wrapper", "for", "right", "Kullback-Leibler", "divergence." ]
def distance_kullback_right(A, B, squared=False): return distance_kullback(B, A, squared=squared)
['def', 'distance_kullback_right(A,', 'B,', 'squared=False):', 'return', 'distance_kullback(B,', 'A,', 'squared=squared)']
809,277
christina-winkler/cnfs-super-resolution
utils.py
mean
mean
Functionality to compute mean over desired dimensions.
[ "Functionality", "to", "compute", "mean", "over", "desired", "dimensions." ]
def mean(tensor, dims=None, keepdim=False): if dims is None: return torch.mean(tensor) else: if isinstance(dims, int): dims = [dims] dims = sorted(dims) for d in dims: tensor = tensor.mean(dim=d, keepdim=True) if not keepdim: for (i, d)...
['def', 'mean(tensor,', 'dims=None,', 'keepdim=False):', 'if', 'dims', 'is', 'None:', 'return', 'torch.mean(tensor)', 'else:', 'if', 'isinstance(dims,', 'int):', 'dims', '=', '[dims]', 'dims', '=', 'sorted(dims)', 'for', 'd', 'in', 'dims:', 'tensor', '=', 'tensor.mean(dim=d,', 'keepdim=True)', 'if', 'not', 'keepdim:', ...
123,495
rudranil723/mini-main
query.py
QuerySet.distinct
distinct
Return a new QuerySet instance that will select only distinct results.
[ "Return", "a", "new", "QuerySet", "instance", "that", "will", "select", "only", "distinct", "results." ]
def distinct(self, *field_names): assert self.query.can_filter(), 'Cannot create distinct fields once a slice has been taken.' obj = self._chain() obj.query.add_distinct_fields(*field_names) return obj
['def', 'distinct(self,', '*field_names):', 'assert', 'self.query.can_filter(),', "'Cannot", 'create', 'distinct', 'fields', 'once', 'a', 'slice', 'has', 'been', "taken.'", 'obj', '=', 'self._chain()', 'obj.query.add_distinct_fields(*field_names)', 'return', 'obj']
316,052
ldkong1205/LaserMix
pointwise_semantic_head.py
PointwiseSemanticHead.get_targets
get_targets
generate segmentation and part prediction targets.
[ "generate", "segmentation", "and", "part", "prediction", "targets." ]
def get_targets(self, voxel_dict: dict, batch_gt_instances_3d: InstanceList) -> dict: batch_size = len(batch_gt_instances_3d) voxel_center_list = [] gt_bboxes_3d = [] gt_labels_3d = [] for idx in range(batch_size): coords_idx = voxel_dict['coors'][:, 0] == idx voxel_center_list.appen...
['def', 'get_targets(self,', 'voxel_dict:', 'dict,', 'batch_gt_instances_3d:', 'InstanceList)', '->', 'dict:', 'batch_size', '=', 'len(batch_gt_instances_3d)', 'voxel_center_list', '=', '[]', 'gt_bboxes_3d', '=', '[]', 'gt_labels_3d', '=', '[]', 'for', 'idx', 'in', 'range(batch_size):', 'coords_idx', '=', "voxel_dict['...
624,213
tobegit3hub/deep_image_model
variables.py
get_model_variables
get_model_variables
Gets the list of model variables, filtered by scope and/or suffix.
[ "Gets", "the", "list", "of", "model", "variables,", "filtered", "by", "scope", "and/or", "suffix." ]
def get_model_variables(scope=None, suffix=None): return get_variables(scope, suffix, ops.GraphKeys.MODEL_VARIABLES)
['def', 'get_model_variables(scope=None,', 'suffix=None):', 'return', 'get_variables(scope,', 'suffix,', 'ops.GraphKeys.MODEL_VARIABLES)']
181,315
lhotse-speech/lhotse
chime6.py
Chime6ArraySynchronizer.synchronize_session
synchronize_session
Synchronize a single CHiME6 session.
[ "Synchronize", "a", "single", "CHiME6", "session." ]
def synchronize_session(self, session: str) -> None: temp_dir = Path(tempfile.mkdtemp(prefix=f'chime6_{session}_', dir=self.output_dir)) if session not in self.audio_edits: logging.warning(f'No audio edits found for session {session}') return session_audio_edits = self.audio_edits[session] ...
['def', 'synchronize_session(self,', 'session:', 'str)', '->', 'None:', 'temp_dir', '=', "Path(tempfile.mkdtemp(prefix=f'chime6_{session}_',", 'dir=self.output_dir))', 'if', 'session', 'not', 'in', 'self.audio_edits:', "logging.warning(f'No", 'audio', 'edits', 'found', 'for', 'session', "{session}')", 'return', 'sessio...
600,923
tensorflow/agents
common.py
clip_to_spec
clip_to_spec
Clips value to a given bounded tensor spec.
[ "Clips", "value", "to", "a", "given", "bounded", "tensor", "spec." ]
def clip_to_spec(value, spec): return tf.clip_by_value(value, spec.minimum, spec.maximum)
['def', 'clip_to_spec(value,', 'spec):', 'return', 'tf.clip_by_value(value,', 'spec.minimum,', 'spec.maximum)']
23,054
rifqind/Agent-Programs-3KS1
parser_utils.py
clean_scope_docstring
clean_scope_docstring
Returns a cleaned version of the docstring token.
[ "Returns", "a", "cleaned", "version", "of", "the", "docstring", "token." ]
def clean_scope_docstring(scope_node): node = scope_node.get_doc_node() if node is not None: cleaned = cleandoc(safe_literal_eval(node.value)) return force_unicode(cleaned) return ''
['def', 'clean_scope_docstring(scope_node):', 'node', '=', 'scope_node.get_doc_node()', 'if', 'node', 'is', 'not', 'None:', 'cleaned', '=', 'cleandoc(safe_literal_eval(node.value))', 'return', 'force_unicode(cleaned)', 'return', "''"]
42,033
divelab/AIRS
utils.py
plot_learning_curve
plot_learning_curve
Plot learning curves based on json history files.
[ "Plot", "learning", "curves", "based", "on", "json", "history", "files." ]
def plot_learning_curve(results_dir: Union[str, Path], key: str='mae', plot_train: bool=False): if isinstance(results_dir, str): results_dir = Path(results_dir) with open(results_dir / 'history_val.json', 'r') as f: val = json.load(f) p = plt.plot(val[key], label=results_dir.name) if plo...
['def', 'plot_learning_curve(results_dir:', 'Union[str,', 'Path],', 'key:', "str='mae',", 'plot_train:', 'bool=False):', 'if', 'isinstance(results_dir,', 'str):', 'results_dir', '=', 'Path(results_dir)', 'with', 'open(results_dir', '/', "'history_val.json',", "'r')", 'as', 'f:', 'val', '=', 'json.load(f)', 'p', '=', 'p...
86,535
terrible-ideas/butterdb
butterdb.py
Model.commit
commit
Commit all changed or new data to the database.
[ "Commit", "all", "changed", "or", "new", "data", "to", "the", "database." ]
def commit(self): cells = [] for field in filter(lambda x: x.has_changed, self.fields.values()): cell = self.database.get_cell(self.data, field.row, field.column) cell.value = field.value cells.append(cell) field.has_changed = False self.database.update_cells(self.data, cells...
['def', 'commit(self):', 'cells', '=', '[]', 'for', 'field', 'in', 'filter(lambda', 'x:', 'x.has_changed,', 'self.fields.values()):', 'cell', '=', 'self.database.get_cell(self.data,', 'field.row,', 'field.column)', 'cell.value', '=', 'field.value', 'cells.append(cell)', 'field.has_changed', '=', 'False', 'self.database...
108,569
apeterswu/RL4NMT
multimodel.py
conv_res_step
conv_res_step
One step of convolutions and mid-residual.
[ "One", "step", "of", "convolutions", "and", "mid-residual." ]
def conv_res_step(x, hparams, padding, mask): k = (hparams.kernel_height, hparams.kernel_width) k2 = (hparams.large_kernel_size, 1) dilations_and_kernels1 = [((1, 1), k), ((1, 1), k)] dilations_and_kernels2 = [((1, 1), k2), ((4, 4), k2)] with tf.variable_scope('conv_res_step'): y = common_la...
['def', 'conv_res_step(x,', 'hparams,', 'padding,', 'mask):', 'k', '=', '(hparams.kernel_height,', 'hparams.kernel_width)', 'k2', '=', '(hparams.large_kernel_size,', '1)', 'dilations_and_kernels1', '=', '[((1,', '1),', 'k),', '((1,', '1),', 'k)]', 'dilations_and_kernels2', '=', '[((1,', '1),', 'k2),', '((4,', '4),', 'k...
331,644
lishunyao97/Pun-GAN
NewBeamSearch_sample.py
BeamSearchDecoder.finalize
finalize
Finalize and return the predicted_ids.
[ "Finalize", "and", "return", "the", "predicted_ids." ]
def finalize(self, outputs, final_state, sequence_lengths): predicted_ids = beam_search_ops.gather_tree(outputs.predicted_ids, outputs.parent_ids, sequence_length=sequence_lengths) outputs = FinalBeamSearchDecoderOutput(beam_search_decoder_output=outputs, predicted_ids=predicted_ids) return (outputs, final_...
['def', 'finalize(self,', 'outputs,', 'final_state,', 'sequence_lengths):', 'predicted_ids', '=', 'beam_search_ops.gather_tree(outputs.predicted_ids,', 'outputs.parent_ids,', 'sequence_length=sequence_lengths)', 'outputs', '=', 'FinalBeamSearchDecoderOutput(beam_search_decoder_output=outputs,', 'predicted_ids=predicted...
818,746
googleapis/python-aiplatform
grpc.py
DatasetServiceGrpcTransport.cancel_operation
cancel_operation
Return a callable for the cancel_operation method over gRPC.
[ "Return", "a", "callable", "for", "the", "cancel_operation", "method", "over", "gRPC." ]
def cancel_operation(self) -> Callable[[operations_pb2.CancelOperationRequest], None]: if 'cancel_operation' not in self._stubs: self._stubs['cancel_operation'] = self.grpc_channel.unary_unary('/google.longrunning.Operations/CancelOperation', request_serializer=operations_pb2.CancelOperationRequest.Serializ...
['def', 'cancel_operation(self)', '->', 'Callable[[operations_pb2.CancelOperationRequest],', 'None]:', 'if', "'cancel_operation'", 'not', 'in', 'self._stubs:', "self._stubs['cancel_operation']", '=', "self.grpc_channel.unary_unary('/google.longrunning.Operations/CancelOperation',", 'request_serializer=operations_pb2.Ca...
812,219
asyml/texar
bert_classifier_test.py
BERTClassifierTest.test_trainable_variables
test_trainable_variables
Tests the functionality of automatically collecting trainable variables.
[ "Tests", "the", "functionality", "of", "automatically", "collecting", "trainable", "variables." ]
def test_trainable_variables(self): inputs = tf.placeholder(dtype=tf.int32, shape=[None, None]) hparams = {'pretrained_model_name': None} clas = BERTClassifier(hparams=hparams) (_, _) = clas(inputs) self.assertEqual(len(clas.trainable_variables), 199 + 2) hparams = {'pretrained_model_name': None...
['def', 'test_trainable_variables(self):', 'inputs', '=', 'tf.placeholder(dtype=tf.int32,', 'shape=[None,', 'None])', 'hparams', '=', "{'pretrained_model_name':", 'None}', 'clas', '=', 'BERTClassifier(hparams=hparams)', '(_,', '_)', '=', 'clas(inputs)', 'self.assertEqual(len(clas.trainable_variables),', '199', '+', '2)...
924,346
OpenMDAO/OpenMDAO-Framework
kriging_surrogate.py
KrigingSurrogate.predict
predict
Calculates a predicted value of the response based on the current trained model for the supplied list of inputs.
[ "Calculates", "a", "predicted", "value", "of", "the", "response", "based", "on", "the", "current", "trained", "model", "for", "the", "supplied", "list", "of", "inputs." ]
def predict(self, new_x): if self.m is None: raise RuntimeError('KrigingSurrogate has not been trained, so no prediction can be made') r = zeros(self.n) (X, Y) = (self.X, self.Y) thetas = 10.0 ** self.thetas XX = array(X) new_x = array(new_x) for i in range(self.n): r[i] = su...
['def', 'predict(self,', 'new_x):', 'if', 'self.m', 'is', 'None:', 'raise', "RuntimeError('KrigingSurrogate", 'has', 'not', 'been', 'trained,', 'so', 'no', 'prediction', 'can', 'be', "made')", 'r', '=', 'zeros(self.n)', '(X,', 'Y)', '=', '(self.X,', 'self.Y)', 'thetas', '=', '10.0', '**', 'self.thetas', 'XX', '=', 'arr...
275,601
openai/gym
record_video.py
RecordVideo.close_video_recorder
close_video_recorder
Closes the video recorder if currently recording.
[ "Closes", "the", "video", "recorder", "if", "currently", "recording." ]
def close_video_recorder(self): if self.recording: assert self.video_recorder is not None self.video_recorder.close() self.recording = False self.recorded_frames = 1
['def', 'close_video_recorder(self):', 'if', 'self.recording:', 'assert', 'self.video_recorder', 'is', 'not', 'None', 'self.video_recorder.close()', 'self.recording', '=', 'False', 'self.recorded_frames', '=', '1']
234,321
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
MakeHistFromDict
MakeHistFromDict
Makes a histogram from a map from values to frequencies.
[ "Makes", "a", "histogram", "from", "a", "map", "from", "values", "to", "frequencies." ]
def MakeHistFromDict(d, label=None): return Hist(d, label)
['def', 'MakeHistFromDict(d,', 'label=None):', 'return', 'Hist(d,', 'label)']
18,942
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
base64.py
encodebytes
encodebytes
Encode a bytestring into a bytes object containing multiple lines of base-64 data.
[ "Encode", "a", "bytestring", "into", "a", "bytes", "object", "containing", "multiple", "lines", "of", "base-64", "data." ]
def encodebytes(s): _input_type_check(s) pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i:i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return b''.join(pieces)
['def', 'encodebytes(s):', '_input_type_check(s)', 'pieces', '=', '[]', 'for', 'i', 'in', 'range(0,', 'len(s),', 'MAXBINSIZE):', 'chunk', '=', 's[i:i', '+', 'MAXBINSIZE]', 'pieces.append(binascii.b2a_base64(chunk))', 'return', "b''.join(pieces)"]
428,179
SamsungLabs/fcaf3d
single_stage.py
SingleStage3DDetector.extract_feat
extract_feat
Directly extract features from the backbone+neck.
[ "Directly", "extract", "features", "from", "the", "backbone+neck." ]
def extract_feat(self, points, img_metas=None): x = self.backbone(points) if self.with_neck: x = self.neck(x) return x
['def', 'extract_feat(self,', 'points,', 'img_metas=None):', 'x', '=', 'self.backbone(points)', 'if', 'self.with_neck:', 'x', '=', 'self.neck(x)', 'return', 'x']
560,479
arshpreetsingh/quantopian-machinelearning
test_tools.py
Test_ipexec_validate.test_exception_path
test_exception_path
Test exception path in exception_validate.
[ "Test", "exception", "path", "in", "exception_validate." ]
def test_exception_path(self): self.mktmp("import sys\nprint('A')\nprint('B')\nprint('C', file=sys.stderr)\nprint('D', file=sys.stderr)\n") out = 'A\nB' tt.ipexec_validate(self.fname, expected_out=out, expected_err='C\nD')
['def', 'test_exception_path(self):', 'self.mktmp("import', "sys\\nprint('A')\\nprint('B')\\nprint('C',", "file=sys.stderr)\\nprint('D',", 'file=sys.stderr)\\n")', 'out', '=', "'A\\nB'", 'tt.ipexec_validate(self.fname,', 'expected_out=out,', "expected_err='C\\nD')"]
887,026
greydanus/mr_london
routing.py
RuleFactory.get_rules
get_rules
Subclasses of `RuleFactory` have to override this method and return an iterable of rules.
[ "Subclasses", "of", "`RuleFactory`", "have", "to", "override", "this", "method", "and", "return", "an", "iterable", "of", "rules." ]
def get_rules(self, map): raise NotImplementedError()
['def', 'get_rules(self,', 'map):', 'raise', 'NotImplementedError()']
264,115
FishYuLi/BalancedGroupSoftmax
hooks.py
Fp16OptimizerHook.copy_params_to_fp16
copy_params_to_fp16
Copy updated params from fp32 weight copy to fp16 model.
[ "Copy", "updated", "params", "from", "fp32", "weight", "copy", "to", "fp16", "model." ]
def copy_params_to_fp16(self, fp16_net, fp32_weights): for (fp16_param, fp32_param) in zip(fp16_net.parameters(), fp32_weights): fp16_param.data.copy_(fp32_param.data)
['def', 'copy_params_to_fp16(self,', 'fp16_net,', 'fp32_weights):', 'for', '(fp16_param,', 'fp32_param)', 'in', 'zip(fp16_net.parameters(),', 'fp32_weights):', 'fp16_param.data.copy_(fp32_param.data)']
422,252
Ruturaj123/Flowchart-Detection
layers_test.py
PartialFlattenTest.testDenseFlattenRankAssertion
testDenseFlattenRankAssertion
Test `_inner_flatten` rank assertion for dense tensors.
[ "Test", "`_inner_flatten`", "rank", "assertion", "for", "dense", "tensors." ]
def testDenseFlattenRankAssertion(self): shape = [2, 3] new_rank = 3 inputs = array_ops.placeholder(dtypes.int32) inputs.set_shape(shape) with self.assertRaisesRegexp(ValueError, 'inputs has rank less than new_rank'): _layers._inner_flatten(inputs, new_rank)
['def', 'testDenseFlattenRankAssertion(self):', 'shape', '=', '[2,', '3]', 'new_rank', '=', '3', 'inputs', '=', 'array_ops.placeholder(dtypes.int32)', 'inputs.set_shape(shape)', 'with', 'self.assertRaisesRegexp(ValueError,', "'inputs", 'has', 'rank', 'less', 'than', "new_rank'):", '_layers._inner_flatten(inputs,', 'new...
603,730
ddbourgin/numpy-ml
wrappers.py
WrapperBase.X
X
The collection of layer inputs.
[ "The", "collection", "of", "layer", "inputs." ]
def X(self): return self._base_layer.X
['def', 'X(self):', 'return', 'self._base_layer.X']
730,297
flavioschneider/rl-transfer-
rl2.py
RL2Worker.start_episode
start_episode
Begin a new episode.
[ "Begin", "a", "new", "episode." ]
def start_episode(self): self._eps_length = 0 self._prev_obs = self.env.reset()[0]
['def', 'start_episode(self):', 'self._eps_length', '=', '0', 'self._prev_obs', '=', 'self.env.reset()[0]']
861,325
ArdaGunay99/Key_Detection_Unsupervised_Learning
disk.py
delete_folder
delete_folder
Utility function to cleanup a temporary folder if it still exists.
[ "Utility", "function", "to", "cleanup", "a", "temporary", "folder", "if", "it", "still", "exists." ]
def delete_folder(folder_path, onerror=None): if os.path.isdir(folder_path): if onerror is not None: shutil.rmtree(folder_path, False, onerror) else: err_count = 0 while True: try: shutil.rmtree(folder_path, False, None) ...
['def', 'delete_folder(folder_path,', 'onerror=None):', 'if', 'os.path.isdir(folder_path):', 'if', 'onerror', 'is', 'not', 'None:', 'shutil.rmtree(folder_path,', 'False,', 'onerror)', 'else:', 'err_count', '=', '0', 'while', 'True:', 'try:', 'shutil.rmtree(folder_path,', 'False,', 'None)', 'break', 'except', '(OSError,...
256,334
boris-kz/CogAlg
imaging.py
Ps_to_layers
Ps_to_layers
Return a nested list of layers, which is a nested list of rows, which in turn is a list of subsets.
[ "Return", "a", "nested", "list", "of", "layers,", "which", "is", "a", "nested", "list", "of", "rows,", "which", "in", "turn", "is", "a", "list", "of", "subsets." ]
def Ps_to_layers(P__): rows_of_layers = [] for P_ in P__: comb_layers = [] for P in P_: comb_layers = [comb_layer + layer for (comb_layer, layer) in zip_longest(comb_layers, P.sublayers, fillvalue=[])] comb_layers = [[(False, 1, 1, P_, [], [])]] + comb_layers rows_of_...
['def', 'Ps_to_layers(P__):', 'rows_of_layers', '=', '[]', 'for', 'P_', 'in', 'P__:', 'comb_layers', '=', '[]', 'for', 'P', 'in', 'P_:', 'comb_layers', '=', '[comb_layer', '+', 'layer', 'for', '(comb_layer,', 'layer)', 'in', 'zip_longest(comb_layers,', 'P.sublayers,', 'fillvalue=[])]', 'comb_layers', '=', '[[(False,', ...
496,053
sunishsheth2009/ChatterBot
ma.py
get_fill_value
get_fill_value
The fill value of a, if it has one; otherwise, the default fill value for that type.
[ "The", "fill", "value", "of", "a,", "if", "it", "has", "one;", "otherwise,", "the", "default", "fill", "value", "for", "that", "type." ]
def get_fill_value(a): if isMaskedArray(a): result = a.fill_value() else: result = default_fill_value(a) return result
['def', 'get_fill_value(a):', 'if', 'isMaskedArray(a):', 'result', '=', 'a.fill_value()', 'else:', 'result', '=', 'default_fill_value(a)', 'return', 'result']
532,286
jymChen/Diaformer
file_utils.py
split_s3_path
split_s3_path
Split a full s3 path into the bucket name and path.
[ "Split", "a", "full", "s3", "path", "into", "the", "bucket", "name", "and", "path." ]
def split_s3_path(url): parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError('bad s3 path {}'.format(url)) bucket_name = parsed.netloc s3_path = parsed.path if s3_path.startswith('/'): s3_path = s3_path[1:] return (bucket_name, s3_path)
['def', 'split_s3_path(url):', 'parsed', '=', 'urlparse(url)', 'if', 'not', 'parsed.netloc', 'or', 'not', 'parsed.path:', 'raise', "ValueError('bad", 's3', 'path', "{}'.format(url))", 'bucket_name', '=', 'parsed.netloc', 's3_path', '=', 'parsed.path', 'if', "s3_path.startswith('/'):", 's3_path', '=', 's3_path[1:]', 're...
550,101
YuriyGuts/snake-ai-reinforcement
entities.py
Field.create_level
create_level
Create a new field based on the level map.
[ "Create", "a", "new", "field", "based", "on", "the", "level", "map." ]
def create_level(self): try: self._cells = np.array([[self._level_map_to_cell_type[symbol] for symbol in line] for line in self.level_map]) self._empty_cells = {Point(x, y) for y in range(self.size) for x in range(self.size) if self[x, y] == CellType.EMPTY} except KeyError as err: raise ...
['def', 'create_level(self):', 'try:', 'self._cells', '=', 'np.array([[self._level_map_to_cell_type[symbol]', 'for', 'symbol', 'in', 'line]', 'for', 'line', 'in', 'self.level_map])', 'self._empty_cells', '=', '{Point(x,', 'y)', 'for', 'y', 'in', 'range(self.size)', 'for', 'x', 'in', 'range(self.size)', 'if', 'self[x,',...
352,162
tomcatmanager/tomcatmanager
interactive_tomcat_manager.py
InteractiveTomcatManager.do_sslconnectorciphers
do_sslconnectorciphers
Show SSL/TLS ciphers configured for each connector.
[ "Show", "SSL/TLS", "ciphers", "configured", "for", "each", "connector." ]
def do_sslconnectorciphers(self, cmdline: cmd2.Statement): self.parse_args(self.sslconnectorciphers_parser, cmdline.argv) r = self.docmd(self.tomcat.ssl_connector_ciphers) self.poutput(r.ssl_connector_ciphers)
['def', 'do_sslconnectorciphers(self,', 'cmdline:', 'cmd2.Statement):', 'self.parse_args(self.sslconnectorciphers_parser,', 'cmdline.argv)', 'r', '=', 'self.docmd(self.tomcat.ssl_connector_ciphers)', 'self.poutput(r.ssl_connector_ciphers)']
355,573
gunthercox/ChatterBot
test_core.py
TestMaskedArrayMathMethods.test_ptp
test_ptp
Tests ptp on MaskedArrays.
[ "Tests", "ptp", "on", "MaskedArrays." ]
def test_ptp(self): (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d (n, m) = X.shape assert_equal(mx.ptp(), mx.compressed().ptp()) rows = np.zeros(n, np.float) cols = np.zeros(m, np.float) for k in range(m): cols[k] = mX[:, k].compressed().ptp() for k in range(n): rows[k]...
['def', 'test_ptp(self):', '(x,', 'X,', 'XX,', 'm,', 'mx,', 'mX,', 'mXX,', 'm2x,', 'm2X,', 'm2XX)', '=', 'self.d', '(n,', 'm)', '=', 'X.shape', 'assert_equal(mx.ptp(),', 'mx.compressed().ptp())', 'rows', '=', 'np.zeros(n,', 'np.float)', 'cols', '=', 'np.zeros(m,', 'np.float)', 'for', 'k', 'in', 'range(m):', 'cols[k]', ...
532,060
PaddlePaddle/PaddleSpeech
zh_frontend.py
insert_after_character
insert_after_character
inset `item` after finals.
[ "inset", "`item`", "after", "finals." ]
def insert_after_character(lst, item): result = [item] for phone in lst: result.append(phone) if phone not in INITIALS: result.append(item) return result
['def', 'insert_after_character(lst,', 'item):', 'result', '=', '[item]', 'for', 'phone', 'in', 'lst:', 'result.append(phone)', 'if', 'phone', 'not', 'in', 'INITIALS:', 'result.append(item)', 'return', 'result']
277,162
karolmajek/object_detection_tensorflow
config_util_test.py
ConfigUtilTest.testOverwriteBatchSizeWithBadValueType
testOverwriteBatchSizeWithBadValueType
Tests that overwriting with a bad valuye type causes an exception.
[ "Tests", "that", "overwriting", "with", "a", "bad", "valuye", "type", "causes", "an", "exception." ]
def testOverwriteBatchSizeWithBadValueType(self): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.train_config.batch_size = 2 configs = self._create_and_load_test_configs(pipeline_config) hparams = tf.contrib.training.HParams(**{'train_config.batch_size': '10'}) with self.as...
['def', 'testOverwriteBatchSizeWithBadValueType(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.train_config.batch_size', '=', '2', 'configs', '=', 'self._create_and_load_test_configs(pipeline_config)', 'hparams', '=', "tf.contrib.training.HParams(**{'train_config.batch_size'...
795,951
hchasestevens/monkeys
aco.py
AntColony.evaporate
evaporate
Perform ACO-like end-of-iteration evaporation of pheromone.
[ "Perform", "ACO-like", "end-of-iteration", "evaporation", "of", "pheromone." ]
def evaporate(self): for (parent, edges) in iteritems(self._pheromone): for (child_combination, concentrations) in iteritems(edges): for pheromone_type in concentrations: concentrations[pheromone_type] *= 1 - self._evaporation_rate self._iteration += 1
['def', 'evaporate(self):', 'for', '(parent,', 'edges)', 'in', 'iteritems(self._pheromone):', 'for', '(child_combination,', 'concentrations)', 'in', 'iteritems(edges):', 'for', 'pheromone_type', 'in', 'concentrations:', 'concentrations[pheromone_type]', '*=', '1', '-', 'self._evaporation_rate', 'self._iteration', '+=',...
241,106
43Carrig/recurrent_neural_networks_practice
values.py
_TowerLocalSaveable.restore
restore
Restore the same value into all variables.
[ "Restore", "the", "same", "value", "into", "all", "variables." ]
def restore(self, restored_tensors, restored_shapes): (tensor,) = restored_tensors return self._tower_local_variable.assign(tensor)
['def', 'restore(self,', 'restored_tensors,', 'restored_shapes):', '(tensor,)', '=', 'restored_tensors', 'return', 'self._tower_local_variable.assign(tensor)']
312,794
asyml/texar
episodic_agent_base.py
EpisodicAgentBase.get_action
get_action
Gets action according to observation.
[ "Gets", "action", "according", "to", "observation." ]
def get_action(self, observ, feed_dict=None): return self._get_action_tmplt_fn(observ, feed_dict)
['def', 'get_action(self,', 'observ,', 'feed_dict=None):', 'return', 'self._get_action_tmplt_fn(observ,', 'feed_dict)']
924,421
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjDataWrapper.xaxis
xaxis
Cartesian joint axis (njnt x 3).
[ "Cartesian", "joint", "axis", "(njnt", "x", "3)." ]
def xaxis(self): return util.buf_to_npy(self._ptr.contents.xaxis, (self._model.njnt, 3))
['def', 'xaxis(self):', 'return', 'util.buf_to_npy(self._ptr.contents.xaxis,', '(self._model.njnt,', '3))']
440,550
voxel51/fiftyone
matplotlib.py
plot_regressions
plot_regressions
Plots the given regression results.
[ "Plots", "the", "given", "regression", "results." ]
def plot_regressions(ytrue, ypred, samples=None, ids=None, labels=None, sizes=None, classes=None, gt_field=None, pred_field=None, best_fit_label=None, marker_size=None, cmap=None, title=None, ax=None, figsize=None, style=None, **kwargs): if samples is not None and gt_field is not None and samples._is_frame_field(gt...
['def', 'plot_regressions(ytrue,', 'ypred,', 'samples=None,', 'ids=None,', 'labels=None,', 'sizes=None,', 'classes=None,', 'gt_field=None,', 'pred_field=None,', 'best_fit_label=None,', 'marker_size=None,', 'cmap=None,', 'title=None,', 'ax=None,', 'figsize=None,', 'style=None,', '**kwargs):', 'if', 'samples', 'is', 'not...
583,636
FreshAirTonight/af2complex
proteins_dataset.py
np_to_tensor_dict
np_to_tensor_dict
Creates dict of tensors from a dict of NumPy arrays.
[ "Creates", "dict", "of", "tensors", "from", "a", "dict", "of", "NumPy", "arrays." ]
def np_to_tensor_dict(np_example: Mapping[str, np.ndarray], features: Sequence[str]) -> TensorDict: features_metadata = _make_features_metadata(features) tensor_dict = {k: tf.constant(v) for (k, v) in np_example.items() if k in features_metadata} tensor_dict = parse_reshape_logic(tensor_dict, features_metad...
['def', 'np_to_tensor_dict(np_example:', 'Mapping[str,', 'np.ndarray],', 'features:', 'Sequence[str])', '->', 'TensorDict:', 'features_metadata', '=', '_make_features_metadata(features)', 'tensor_dict', '=', '{k:', 'tf.constant(v)', 'for', '(k,', 'v)', 'in', 'np_example.items()', 'if', 'k', 'in', 'features_metadata}', ...
400,794
dayorbyte/MongoAlchemy
ref.py
RefField.validate_unwrap
validate_unwrap
Validates that the DBRef is valid as well as can be done without retrieving it.
[ "Validates", "that", "the", "DBRef", "is", "valid", "as", "well", "as", "can", "be", "done", "without", "retrieving", "it." ]
def validate_unwrap(self, value, session=None): if not isinstance(value, DBRef): self._fail_validation_type(value, DBRef) if self.type: expected = self.type.type.get_collection_name() got = value.collection if expected != got: self._fail_validation(value, 'Wrong colle...
['def', 'validate_unwrap(self,', 'value,', 'session=None):', 'if', 'not', 'isinstance(value,', 'DBRef):', 'self._fail_validation_type(value,', 'DBRef)', 'if', 'self.type:', 'expected', '=', 'self.type.type.get_collection_name()', 'got', '=', 'value.collection', 'if', 'expected', '!=', 'got:', 'self._fail_validation(val...
241,088
juzb/DeeProtein
prettyplotter.py
PrettyPlotter.plot_ROC
plot_ROC
Plot the ROC of the model.
[ "Plot", "the", "ROC", "of", "the", "model." ]
def plot_ROC(self): (fig, ax) = plt.subplots() s = 'Model, GOs, AUC\n' ax.plot([0, 1.0], [0, 1.0], color=colors['lblue'], lw=2, linestyle='--') for (model, name, plt_color) in zip(self.overall_metrics, self.names, self.colors): x = model['fpr'] y = model['tpr'] c = colors[plt_col...
['def', 'plot_ROC(self):', '(fig,', 'ax)', '=', 'plt.subplots()', 's', '=', "'Model,", 'GOs,', "AUC\\n'", 'ax.plot([0,', '1.0],', '[0,', '1.0],', "color=colors['lblue'],", 'lw=2,', "linestyle='--')", 'for', '(model,', 'name,', 'plt_color)', 'in', 'zip(self.overall_metrics,', 'self.names,', 'self.colors):', 'x', '=', "m...
539,673
ljw-struggle/Bioinfor-DeepATT
utils.py
read_json
read_json
Read json to dict.
[ "Read", "json", "to", "dict." ]
def read_json(file_path): with open(file_path, 'rt') as f: return json.load(f, object_hook=OrderedDict)
['def', 'read_json(file_path):', 'with', 'open(file_path,', "'rt')", 'as', 'f:', 'return', 'json.load(f,', 'object_hook=OrderedDict)']
461,041
NVIDIA-Omniverse/OmniIsaacGymEnvs
factory_control.py
get_pose_error
get_pose_error
Compute task-space error between target Franka fingertip pose and current pose.
[ "Compute", "task-space", "error", "between", "target", "Franka", "fingertip", "pose", "and", "current", "pose." ]
def get_pose_error(fingertip_midpoint_pos, fingertip_midpoint_quat, ctrl_target_fingertip_midpoint_pos, ctrl_target_fingertip_midpoint_quat, jacobian_type, rot_error_type): pos_error = ctrl_target_fingertip_midpoint_pos - fingertip_midpoint_pos if jacobian_type == 'geometric': fingertip_midpoint_quat_no...
['def', 'get_pose_error(fingertip_midpoint_pos,', 'fingertip_midpoint_quat,', 'ctrl_target_fingertip_midpoint_pos,', 'ctrl_target_fingertip_midpoint_quat,', 'jacobian_type,', 'rot_error_type):', 'pos_error', '=', 'ctrl_target_fingertip_midpoint_pos', '-', 'fingertip_midpoint_pos', 'if', 'jacobian_type', '==', "'geometr...
250,382
tobegit3hub/deep_image_model
text.py
VocabularyProcessor.reverse
reverse
Reverses output of vocabulary mapping to words.
[ "Reverses", "output", "of", "vocabulary", "mapping", "to", "words." ]
def reverse(self, documents): for item in documents: output = [] for class_id in item: output.append(self.vocabulary_.reverse(class_id)) yield ' '.join(output)
['def', 'reverse(self,', 'documents):', 'for', 'item', 'in', 'documents:', 'output', '=', '[]', 'for', 'class_id', 'in', 'item:', 'output.append(self.vocabulary_.reverse(class_id))', 'yield', "'", "'.join(output)"]
181,865
QData/deepWordBug
test_core.py
test_control_c0_width_negative_1
test_control_c0_width_negative_1
CSI (Control sequence initiate) reports width -1.
[ "CSI", "(Control", "sequence", "initiate)", "reports", "width", "-1." ]
def test_control_c0_width_negative_1(): phrase = u'\x1b[0m' expect_length_each = (-1, 1, 1, 1) expect_length_phrase = -1 length_each = tuple(map(wcwidth.wcwidth, phrase)) length_phrase = wcwidth.wcswidth(phrase, len(phrase)) assert length_each == expect_length_each assert length_phrase == ex...
['def', 'test_control_c0_width_negative_1():', 'phrase', '=', "u'\\x1b[0m'", 'expect_length_each', '=', '(-1,', '1,', '1,', '1)', 'expect_length_phrase', '=', '-1', 'length_each', '=', 'tuple(map(wcwidth.wcwidth,', 'phrase))', 'length_phrase', '=', 'wcwidth.wcswidth(phrase,', 'len(phrase))', 'assert', 'length_each', '=...
536,101
Hadishh/cs188
trackingTestClasses.py
DoubleInferenceAgent.getAction
getAction
Updates beliefs, then chooses an action based on updated beliefs.
[ "Updates", "beliefs,", "then", "chooses", "an", "action", "based", "on", "updated", "beliefs." ]
def getAction(self, gameState): self.numMoves += 1 (moveNum, action, dists) = self.refSolution[self.numMoves] for (index, inf) in enumerate(self.inferenceModules): if self.elapse: if not self.firstMove: inf.elapseTime(gameState) self.firstMove = False if s...
['def', 'getAction(self,', 'gameState):', 'self.numMoves', '+=', '1', '(moveNum,', 'action,', 'dists)', '=', 'self.refSolution[self.numMoves]', 'for', '(index,', 'inf)', 'in', 'enumerate(self.inferenceModules):', 'if', 'self.elapse:', 'if', 'not', 'self.firstMove:', 'inf.elapseTime(gameState)', 'self.firstMove', '=', '...
225,901
SimingYan/IAE
checkpoints.py
CheckpointIO.load
load
Loads a module dictionary from local file or url.
[ "Loads", "a", "module", "dictionary", "from", "local", "file", "or", "url." ]
def load(self, filename): if is_url(filename): return self.load_url(filename) else: return self.load_file(filename)
['def', 'load(self,', 'filename):', 'if', 'is_url(filename):', 'return', 'self.load_url(filename)', 'else:', 'return', 'self.load_file(filename)']
228,226
rifqind/Agent-Programs-3KS1
test_inputtransformer2.py
null_cleanup_transformer
null_cleanup_transformer
A cleanup transform that returns an empty list.
[ "A", "cleanup", "transform", "that", "returns", "an", "empty", "list." ]
def null_cleanup_transformer(lines): return []
['def', 'null_cleanup_transformer(lines):', 'return', '[]']
41,417
flomock/EpiDope
versioneer.py
register_vcs_handler
register_vcs_handler
Decorator to mark a method as the handler for a particular VCS.
[ "Decorator", "to", "mark", "a", "method", "as", "the", "handler", "for", "a", "particular", "VCS." ]
def register_vcs_handler(vcs, method): def decorate(f): if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate
['def', 'register_vcs_handler(vcs,', 'method):', 'def', 'decorate(f):', 'if', 'vcs', 'not', 'in', 'HANDLERS:', 'HANDLERS[vcs]', '=', '{}', 'HANDLERS[vcs][method]', '=', 'f', 'return', 'f', 'return', 'decorate']
562,741
Eric3911/OpenAGI
punctuation_capitalization_tarred_dataset.py
remove_unexpected_files_and_dirs
remove_unexpected_files_and_dirs
This function removes all files with names which may be used in the dataset creation.
[ "This", "function", "removes", "all", "files", "with", "names", "which", "may", "be", "used", "in", "the", "dataset", "creation." ]
def remove_unexpected_files_and_dirs(output_dir: Path, output_file_tmpl: str, metadata_file_name: Path) -> None: if not output_dir.is_dir(): return tar_final_pattern = re.compile(output_file_tmpl.format(ctr=NUMBER_RE, num_batches=NUMBER_RE)) unexpected_tar_files = [path for path in output_dir.iterdi...
['def', 'remove_unexpected_files_and_dirs(output_dir:', 'Path,', 'output_file_tmpl:', 'str,', 'metadata_file_name:', 'Path)', '->', 'None:', 'if', 'not', 'output_dir.is_dir():', 'return', 'tar_final_pattern', '=', 're.compile(output_file_tmpl.format(ctr=NUMBER_RE,', 'num_batches=NUMBER_RE))', 'unexpected_tar_files', '=...
273,401
yizheh/Chinese_Font_Transfer
check.py
create_package_set_from_installed
create_package_set_from_installed
Converts a list of distributions into a PackageSet.
[ "Converts", "a", "list", "of", "distributions", "into", "a", "PackageSet." ]
def create_package_set_from_installed(**kwargs): if kwargs == {}: kwargs = {'local_only': False, 'skip': ()} package_set = {} for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) package_set[name] = PackageDetails(dist.version, dist.requires(...
['def', 'create_package_set_from_installed(**kwargs):', 'if', 'kwargs', '==', '{}:', 'kwargs', '=', "{'local_only':", 'False,', "'skip':", '()}', 'package_set', '=', '{}', 'for', 'dist', 'in', 'get_installed_distributions(**kwargs):', 'name', '=', 'canonicalize_name(dist.project_name)', 'package_set[name]', '=', 'Packa...
486,510
WhiteHerb/NaturalLanguageProcessing
run_classifier_with_tfhub.py
create_tokenizer_from_hub_module
create_tokenizer_from_hub_module
Get the vocab file and casing info from the Hub module.
[ "Get", "the", "vocab", "file", "and", "casing", "info", "from", "the", "Hub", "module." ]
def create_tokenizer_from_hub_module(bert_hub_module_handle): with tf.Graph().as_default(): bert_module = hub.Module(bert_hub_module_handle) tokenization_info = bert_module(signature='tokenization_info', as_dict=True) with tf.Session() as sess: (vocab_file, do_lower_case) = sess....
['def', 'create_tokenizer_from_hub_module(bert_hub_module_handle):', 'with', 'tf.Graph().as_default():', 'bert_module', '=', 'hub.Module(bert_hub_module_handle)', 'tokenization_info', '=', "bert_module(signature='tokenization_info',", 'as_dict=True)', 'with', 'tf.Session()', 'as', 'sess:', '(vocab_file,', 'do_lower_cas...
798,298
aws/sagemaker-python-sdk
estimator.py
EstimatorBase.get_app_url
get_app_url
Generate a URL to help access the specified app hosted in Amazon SageMaker Studio.
[ "Generate", "a", "URL", "to", "help", "access", "the", "specified", "app", "hosted", "in", "Amazon", "SageMaker", "Studio." ]
def get_app_url(self, app_type, open_in_default_web_browser=True, create_presigned_domain_url=False, domain_id=None, user_profile_name=None, optional_create_presigned_url_kwargs=None): url = None if isinstance(app_type, SupportedInteractiveAppTypes): app_type = app_type.name app_type = app_type.lowe...
['def', 'get_app_url(self,', 'app_type,', 'open_in_default_web_browser=True,', 'create_presigned_domain_url=False,', 'domain_id=None,', 'user_profile_name=None,', 'optional_create_presigned_url_kwargs=None):', 'url', '=', 'None', 'if', 'isinstance(app_type,', 'SupportedInteractiveAppTypes):', 'app_type', '=', 'app_type...
829,457
TencentYoutuResearch/PedestrianDetection-NohNMS
lvis.py
load_lvis_json
load_lvis_json
Load a json file in LVIS's annotation format.
[ "Load", "a", "json", "file", "in", "LVIS's", "annotation", "format." ]
def load_lvis_json(json_file, image_root, dataset_name=None): from lvis import LVIS json_file = PathManager.get_local_path(json_file) timer = Timer() lvis_api = LVIS(json_file) if timer.seconds() > 1: logger.info('Loading {} takes {:.2f} seconds.'.format(json_file, timer.seconds())) if d...
['def', 'load_lvis_json(json_file,', 'image_root,', 'dataset_name=None):', 'from', 'lvis', 'import', 'LVIS', 'json_file', '=', 'PathManager.get_local_path(json_file)', 'timer', '=', 'Timer()', 'lvis_api', '=', 'LVIS(json_file)', 'if', 'timer.seconds()', '>', '1:', "logger.info('Loading", '{}', 'takes', '{:.2f}', "secon...
766,545