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
myothida/Supervised-Machine-Learning
control.py
strip_control_codes
strip_control_codes
Remove control codes from text.
[ "Remove", "control", "codes", "from", "text." ]
def strip_control_codes(text: str, _translate_table: Dict[int, None]=_CONTROL_STRIP_TRANSLATE) -> str: return text.translate(_translate_table)
['def', 'strip_control_codes(text:', 'str,', '_translate_table:', 'Dict[int,', 'None]=_CONTROL_STRIP_TRANSLATE)', '->', 'str:', 'return', 'text.translate(_translate_table)']
445,018
ifwe/digsby
UberCombo.py
UberCombo.ChangeValue
ChangeValue
Changes the value of the textfield without firing an event.
[ "Changes", "the", "value", "of", "the", "textfield", "without", "firing", "an", "event." ]
def ChangeValue(self, value, default=None): self.display.ChangeValue(value, default)
['def', 'ChangeValue(self,', 'value,', 'default=None):', 'self.display.ChangeValue(value,', 'default)']
185,669
PaddlePaddle/PaddleSpeech
text_featurizer.py
TextFeaturizer.defeaturize
defeaturize
Convert a list of token indices to text string, ignore index after eos_id.
[ "Convert", "a", "list", "of", "token", "indices", "to", "text", "string,", "ignore", "index", "after", "eos_id." ]
def defeaturize(self, idxs): tokens = [] for idx in idxs: if idx == self.eos_id: break tokens.append(self._id2token[idx]) text = self.detokenize(tokens) return text
['def', 'defeaturize(self,', 'idxs):', 'tokens', '=', '[]', 'for', 'idx', 'in', 'idxs:', 'if', 'idx', '==', 'self.eos_id:', 'break', 'tokens.append(self._id2token[idx])', 'text', '=', 'self.detokenize(tokens)', 'return', 'text']
276,490
googleapis/python-aiplatform
_models.py
get_experiment_model_info
get_experiment_model_info
Get the model's info from an experiment model artifact.
[ "Get", "the", "model's", "info", "from", "an", "experiment", "model", "artifact." ]
def get_experiment_model_info(model: Union[str, google_artifact_schema.ExperimentModel]) -> Dict[str, Any]: if isinstance(model, str): model = aiplatform.get_experiment_model(model) model_info = {'model_class': model.model_class, 'framework_name': model.framework_name, 'framework_version': model.framewo...
['def', 'get_experiment_model_info(model:', 'Union[str,', 'google_artifact_schema.ExperimentModel])', '->', 'Dict[str,', 'Any]:', 'if', 'isinstance(model,', 'str):', 'model', '=', 'aiplatform.get_experiment_model(model)', 'model_info', '=', "{'model_class':", 'model.model_class,', "'framework_name':", 'model.framework_...
810,062
acrosson/nlp
preProcessed.py
candidates
candidates
Generate possible spelling corrections for word.
[ "Generate", "possible", "spelling", "corrections", "for", "word." ]
def candidates(word): return known([word]) or known(edits1(word)) or known(edits2(word)) or [word]
['def', 'candidates(word):', 'return', 'known([word])', 'or', 'known(edits1(word))', 'or', 'known(edits2(word))', 'or', '[word]']
808,050
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
losses.py
dann_loss
dann_loss
Adds the domain adversarial (DANN) loss.
[ "Adds", "the", "domain", "adversarial", "(DANN)", "loss." ]
def dann_loss(source_samples, target_samples, weight, scope=None): with tf.variable_scope('dann'): batch_size = tf.shape(source_samples)[0] samples = tf.concat(axis=0, values=[source_samples, target_samples]) samples = slim.flatten(samples) domain_selection_mask = tf.concat(axis=0, v...
['def', 'dann_loss(source_samples,', 'target_samples,', 'weight,', 'scope=None):', 'with', "tf.variable_scope('dann'):", 'batch_size', '=', 'tf.shape(source_samples)[0]', 'samples', '=', 'tf.concat(axis=0,', 'values=[source_samples,', 'target_samples])', 'samples', '=', 'slim.flatten(samples)', 'domain_selection_mask',...
54,194
Ruturaj123/Flowchart-Detection
gbdt_batch_test.py
GbdtTest.testTrainFnChiefWithBiasCentering
testTrainFnChiefWithBiasCentering
Tests the train function running on chief with bias centering.
[ "Tests", "the", "train", "function", "running", "on", "chief", "with", "bias", "centering." ]
def testTrainFnChiefWithBiasCentering(self): with self.test_session(): ensemble_handle = model_ops.tree_ensemble_variable(stamp_token=0, tree_ensemble_config='', name='tree_ensemble') learner_config = learner_pb2.LearnerConfig() learner_config.learning_rate_tuner.fixed.learning_rate = 0.1 ...
['def', 'testTrainFnChiefWithBiasCentering(self):', 'with', 'self.test_session():', 'ensemble_handle', '=', 'model_ops.tree_ensemble_variable(stamp_token=0,', "tree_ensemble_config='',", "name='tree_ensemble')", 'learner_config', '=', 'learner_pb2.LearnerConfig()', 'learner_config.learning_rate_tuner.fixed.learning_rat...
586,900
alex-petrenko/sample-factory
action_parameterization.py
ActionParameterizationDefault.forward
forward
Just forward the FC layer and generate the distribution object.
[ "Just", "forward", "the", "FC", "layer", "and", "generate", "the", "distribution", "object." ]
def forward(self, actor_core_output): action_distribution_params = self.distribution_linear(actor_core_output) action_distribution = get_action_distribution(self.action_space, raw_logits=action_distribution_params) return (action_distribution_params, action_distribution)
['def', 'forward(self,', 'actor_core_output):', 'action_distribution_params', '=', 'self.distribution_linear(actor_core_output)', 'action_distribution', '=', 'get_action_distribution(self.action_space,', 'raw_logits=action_distribution_params)', 'return', '(action_distribution_params,', 'action_distribution)']
329,037
openvinotoolkit/training_extensions
test_multi_gpu.py
test_set_arguments_to_argv_key_none_val
test_set_arguments_to_argv_key_none_val
Test a case where key to set doesn't exists in argv and order of key is before params and vlaue doesn't exist.
[ "Test", "a", "case", "where", "key", "to", "set", "doesn't", "exists", "in", "argv", "and", "order", "of", "key", "is", "before", "params", "and", "vlaue", "doesn't", "exist." ]
def test_set_arguments_to_argv_key_none_val(mock_argv_with_params): set_arguments_to_argv('--other_key') param_idx = mock_argv_with_params.index('params') new_key_idx = mock_argv_with_params.index('--other_key') assert new_key_idx < param_idx assert '--other_key' in mock_argv_with_params
['def', 'test_set_arguments_to_argv_key_none_val(mock_argv_with_params):', "set_arguments_to_argv('--other_key')", 'param_idx', '=', "mock_argv_with_params.index('params')", 'new_key_idx', '=', "mock_argv_with_params.index('--other_key')", 'assert', 'new_key_idx', '<', 'param_idx', 'assert', "'--other_key'", 'in', 'moc...
919,856
sunishsheth2009/ChatterBot
base.py
FBDDLCompiler.visit_drop_sequence
visit_drop_sequence
Generate a ``DROP GENERATOR`` statement for the sequence.
[ "Generate", "a", "``DROP", "GENERATOR``", "statement", "for", "the", "sequence." ]
def visit_drop_sequence(self, drop): if self.dialect._version_two: return 'DROP SEQUENCE %s' % self.preparer.format_sequence(drop.element) else: return 'DROP GENERATOR %s' % self.preparer.format_sequence(drop.element)
['def', 'visit_drop_sequence(self,', 'drop):', 'if', 'self.dialect._version_two:', 'return', "'DROP", 'SEQUENCE', "%s'", '%', 'self.preparer.format_sequence(drop.element)', 'else:', 'return', "'DROP", 'GENERATOR', "%s'", '%', 'self.preparer.format_sequence(drop.element)']
534,224
43Carrig/recurrent_neural_networks_practice
model_utils.py
canonicalize_times_or_steps_from_output
canonicalize_times_or_steps_from_output
Canonicalizes either relative or absolute times, with error checking.
[ "Canonicalizes", "either", "relative", "or", "absolute", "times,", "with", "error", "checking." ]
def canonicalize_times_or_steps_from_output(times, steps, previous_model_output): if steps is not None and times is not None: raise ValueError('Only one of `steps` and `times` may be specified.') if steps is None and times is None: raise ValueError('One of `steps` and `times` must be specified.'...
['def', 'canonicalize_times_or_steps_from_output(times,', 'steps,', 'previous_model_output):', 'if', 'steps', 'is', 'not', 'None', 'and', 'times', 'is', 'not', 'None:', 'raise', "ValueError('Only", 'one', 'of', '`steps`', 'and', '`times`', 'may', 'be', "specified.')", 'if', 'steps', 'is', 'None', 'and', 'times', 'is', ...
335,441
Ruturaj123/Flowchart-Detection
coordinator.py
Coordinator.wait_for_stop
wait_for_stop
Wait till the Coordinator is told to stop.
[ "Wait", "till", "the", "Coordinator", "is", "told", "to", "stop." ]
def wait_for_stop(self, timeout=None): return self._stop_event.wait(timeout)
['def', 'wait_for_stop(self,', 'timeout=None):', 'return', 'self._stop_event.wait(timeout)']
606,492
enuguru/artificial_intelligence_and_machine_
misc.py
output_encoding
output_encoding
Determine the encoding to use for output written to `outfile` or stdout.
[ "Determine", "the", "encoding", "to", "use", "for", "output", "written", "to", "`outfile`", "or", "stdout." ]
def output_encoding(outfile=None): if outfile is None: outfile = sys.stdout encoding = getattr(outfile, 'encoding', None) or getattr(sys.__stdout__, 'encoding', None) or locale.getpreferredencoding() return encoding
['def', 'output_encoding(outfile=None):', 'if', 'outfile', 'is', 'None:', 'outfile', '=', 'sys.stdout', 'encoding', '=', 'getattr(outfile,', "'encoding',", 'None)', 'or', 'getattr(sys.__stdout__,', "'encoding',", 'None)', 'or', 'locale.getpreferredencoding()', 'return', 'encoding']
157,484
sunishsheth2009/ChatterBot
environment.py
Environment.getitem
getitem
Get an item or attribute of an object but prefer the item.
[ "Get", "an", "item", "or", "attribute", "of", "an", "object", "but", "prefer", "the", "item." ]
def getitem(self, obj, argument): try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, string_types): try: attr = str(argument) except Exception: pass else: try: ...
['def', 'getitem(self,', 'obj,', 'argument):', 'try:', 'return', 'obj[argument]', 'except', '(TypeError,', 'LookupError):', 'if', 'isinstance(argument,', 'string_types):', 'try:', 'attr', '=', 'str(argument)', 'except', 'Exception:', 'pass', 'else:', 'try:', 'return', 'getattr(obj,', 'attr)', 'except', 'AttributeError:...
479,009
ryu-ed/SpaceInvaders_Ros
test_filter_design.py
TestFreqz.test_ticket1441
test_ticket1441
Regression test for ticket 1441.
[ "Regression", "test", "for", "ticket", "1441." ]
def test_ticket1441(self): N = 100000 (w, h) = freqz([1.0], worN=N) assert_equal(w.shape, (N,))
['def', 'test_ticket1441(self):', 'N', '=', '100000', '(w,', 'h)', '=', 'freqz([1.0],', 'worN=N)', 'assert_equal(w.shape,', '(N,))']
370,917
zomux/deepy
worker.py
MultiGPUTrainer.train
train
Train the model in multi-GPU environment.
[ "Train", "the", "model", "in", "multi-GPU", "environment." ]
def train(self, train_set, valid_set=None, test_set=None, train_size=None): from platoon.channel import Worker from platoon.param_sync import EASGD, ASGD server_port = self._port param_map = self.create_param_map() worker = Worker(control_port=server_port) if self.config.learning_rate: w...
['def', 'train(self,', 'train_set,', 'valid_set=None,', 'test_set=None,', 'train_size=None):', 'from', 'platoon.channel', 'import', 'Worker', 'from', 'platoon.param_sync', 'import', 'EASGD,', 'ASGD', 'server_port', '=', 'self._port', 'param_map', '=', 'self.create_param_map()', 'worker', '=', 'Worker(control_port=serve...
180,970
skyhehe123/SA-SSD
fastai_optim.py
model_g2master_g
model_g2master_g
Copy the `model_params` gradients to `master_params` for the optimizer step.
[ "Copy", "the", "`model_params`", "gradients", "to", "`master_params`", "for", "the", "optimizer", "step." ]
def model_g2master_g(model_params, master_params, flat_master: bool=False) -> None: if flat_master: for (model_group, master_group) in zip(model_params, master_params): if len(master_group) != 0: master_group[0].grad.data.copy_(parameters_to_vector([p.grad.data.float() for p in m...
['def', 'model_g2master_g(model_params,', 'master_params,', 'flat_master:', 'bool=False)', '->', 'None:', 'if', 'flat_master:', 'for', '(model_group,', 'master_group)', 'in', 'zip(model_params,', 'master_params):', 'if', 'len(master_group)', '!=', '0:', 'master_group[0].grad.data.copy_(parameters_to_vector([p.grad.data...
828,813
zackmcnulty/CSE_446-Machine_Learning
afm.py
AFM.string_width_height
string_width_height
Return the string width (including kerning) and string height as a (*w*, *h*) tuple.
[ "Return", "the", "string", "width", "(including", "kerning)", "and", "string", "height", "as", "a", "(*w*,", "*h*)", "tuple." ]
def string_width_height(self, s): if not len(s): return (0, 0) total_width = 0 namelast = None miny = 1000000000.0 maxy = 0 for c in s: if c == '\n': continue (wx, name, bbox) = self._metrics[ord(c)] total_width += wx + self._kern.get((namelast, name),...
['def', 'string_width_height(self,', 's):', 'if', 'not', 'len(s):', 'return', '(0,', '0)', 'total_width', '=', '0', 'namelast', '=', 'None', 'miny', '=', '1000000000.0', 'maxy', '=', '0', 'for', 'c', 'in', 's:', 'if', 'c', '==', "'\\n':", 'continue', '(wx,', 'name,', 'bbox)', '=', 'self._metrics[ord(c)]', 'total_width'...
193,849
weimin17/Object-Detection_HelmetDetection
multitask_gp.py
MultitaskGP.train
train
Trains the GP for num_steps, using the data in 'data'.
[ "Trains", "the", "GP", "for", "num_steps,", "using", "the", "data", "in", "'data'." ]
def train(self, data, num_steps): logging.info('Training %s for %d steps...', self.name, num_steps) for step in range(num_steps): numpts = min(data.num_points(None), self.max_num_points) if numpts >= self.max_num_points and self.keep_fixed_after_max_obs: x = data.contexts[:numpts, :]...
['def', 'train(self,', 'data,', 'num_steps):', "logging.info('Training", '%s', 'for', '%d', "steps...',", 'self.name,', 'num_steps)', 'for', 'step', 'in', 'range(num_steps):', 'numpts', '=', 'min(data.num_points(None),', 'self.max_num_points)', 'if', 'numpts', '>=', 'self.max_num_points', 'and', 'self.keep_fixed_after_...
762,270
sek788432/Waymo-2D-Object-Detection
pnasnet.py
pnasnet_large_arg_scope
pnasnet_large_arg_scope
Default arg scope for the PNASNet Large ImageNet model.
[ "Default", "arg", "scope", "for", "the", "PNASNet", "Large", "ImageNet", "model." ]
def pnasnet_large_arg_scope(weight_decay=4e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): return nasnet.nasnet_large_arg_scope(weight_decay, batch_norm_decay, batch_norm_epsilon)
['def', 'pnasnet_large_arg_scope(weight_decay=4e-05,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001):', 'return', 'nasnet.nasnet_large_arg_scope(weight_decay,', 'batch_norm_decay,', 'batch_norm_epsilon)']
975,859
neuroailab/VIE
transforms.py
video_OPN_transform_color
video_OPN_transform_color
Return prepared video transform.
[ "Return", "prepared", "video", "transform." ]
def video_OPN_transform_color(frame_size_min=256, frame_size_max=320, crop_size=80): return Compose([RandomGroupResize(frame_size_min, frame_size_max), GroupRandomCrop(crop_size + 20), SpatialJitter(crop_size), GroupColorJitter(), GroupRandomHorizontalFlip(), ByteStack()])
['def', 'video_OPN_transform_color(frame_size_min=256,', 'frame_size_max=320,', 'crop_size=80):', 'return', 'Compose([RandomGroupResize(frame_size_min,', 'frame_size_max),', 'GroupRandomCrop(crop_size', '+', '20),', 'SpatialJitter(crop_size),', 'GroupColorJitter(),', 'GroupRandomHorizontalFlip(),', 'ByteStack()])']
380,048
Farama-Foundation/Gymnasium
test_autoreset.py
unwrap_env
unwrap_env
Unwraps an environment yielding all wrappers around environment.
[ "Unwraps", "an", "environment", "yielding", "all", "wrappers", "around", "environment." ]
def unwrap_env(env) -> Generator[gym.Wrapper, None, None]: while isinstance(env, gym.Wrapper): yield type(env) env = env.env
['def', 'unwrap_env(env)', '->', 'Generator[gym.Wrapper,', 'None,', 'None]:', 'while', 'isinstance(env,', 'gym.Wrapper):', 'yield', 'type(env)', 'env', '=', 'env.env']
573,670
facebookresearch/CompilerGym
benchmarks.py
BenchmarksEntry.benchmark_uris_iterator
benchmark_uris_iterator
Return an iterator over the URIs of the benchmarks.
[ "Return", "an", "iterator", "over", "the", "URIs", "of", "the", "benchmarks." ]
def benchmark_uris_iterator(self, env: LlvmEnv) -> Iterable[str]: return self._benchmark_iterator(env, uris=True)
['def', 'benchmark_uris_iterator(self,', 'env:', 'LlvmEnv)', '->', 'Iterable[str]:', 'return', 'self._benchmark_iterator(env,', 'uris=True)']
135,656
LZDSJTU/pointnet_pytorch
indoor3d_util.py
room2blocks_plus
room2blocks_plus
room2block with input filename and RGB preprocessing.
[ "room2block", "with", "input", "filename", "and", "RGB", "preprocessing." ]
def room2blocks_plus(data_label, num_point, block_size, stride, random_sample, sample_num, sample_aug): data = data_label[:, 0:6] data[:, 3:6] /= 255.0 label = data_label[:, -1].astype(np.uint8) return room2blocks(data, label, num_point, block_size, stride, random_sample, sample_num, sample_aug)
['def', 'room2blocks_plus(data_label,', 'num_point,', 'block_size,', 'stride,', 'random_sample,', 'sample_num,', 'sample_aug):', 'data', '=', 'data_label[:,', '0:6]', 'data[:,', '3:6]', '/=', '255.0', 'label', '=', 'data_label[:,', '-1].astype(np.uint8)', 'return', 'room2blocks(data,', 'label,', 'num_point,', 'block_si...
781,139
TrellixVulnTeam/Unsupervised_Learning_HFI7
conftest.py
xsys
xsys
Replace the default system call with a capturing one for doctest.
[ "Replace", "the", "default", "system", "call", "with", "a", "capturing", "one", "for", "doctest." ]
def xsys(self, cmd): print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout) sys.stdout.flush()
['def', 'xsys(self,', 'cmd):', 'print(self.getoutput(cmd,', 'split=False,', 'depth=1).rstrip(),', "end='',", 'file=sys.stdout)', 'sys.stdout.flush()']
447,961
google/ml-compiler-opt
make_corpus_lib.py
copy_bitcode
copy_bitcode
Copies bitcode files from the base directory to the output directory.
[ "Copies", "bitcode", "files", "from", "the", "base", "directory", "to", "the", "output", "directory." ]
def copy_bitcode(relative_paths: List[str], bitcode_base_dir: str, output_dir: str) -> None: for relative_path in relative_paths: base_path = os.path.join(bitcode_base_dir, relative_path + BITCODE_EXTENSION) destination_path = os.path.join(output_dir, relative_path + BITCODE_EXTENSION) os.ma...
['def', 'copy_bitcode(relative_paths:', 'List[str],', 'bitcode_base_dir:', 'str,', 'output_dir:', 'str)', '->', 'None:', 'for', 'relative_path', 'in', 'relative_paths:', 'base_path', '=', 'os.path.join(bitcode_base_dir,', 'relative_path', '+', 'BITCODE_EXTENSION)', 'destination_path', '=', 'os.path.join(output_dir,', '...
671,243
Trusted-AI/adversarial-robustness-toolbox
test_cutout_pytorch.py
image_batch
image_batch
Image fixtures of shape NHWC and NCHW.
[ "Image", "fixtures", "of", "shape", "NHWC", "and", "NCHW." ]
def image_batch(request, channels_first): channels = request.param if channels_first: data_shape = (2, channels, 12, 8) else: data_shape = (2, 12, 8, channels) return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)
['def', 'image_batch(request,', 'channels_first):', 'channels', '=', 'request.param', 'if', 'channels_first:', 'data_shape', '=', '(2,', 'channels,', '12,', '8)', 'else:', 'data_shape', '=', '(2,', '12,', '8,', 'channels)', 'return', '(255', '*', 'np.ones(data_shape)).astype(ART_NUMPY_DTYPE)']
398,577
Kvatsx/Artificial-Intelligence-Assignments
application.py
Application.initialize_subcommand
initialize_subcommand
Initialize a subcommand with argv.
[ "Initialize", "a", "subcommand", "with", "argv." ]
def initialize_subcommand(self, subc, argv=None): (subapp, help) = self.subcommands.get(subc) if isinstance(subapp, six.string_types): subapp = import_item(subapp) self.__class__.clear_instance() self.subapp = subapp.instance(parent=self) self.subapp.initialize(argv)
['def', 'initialize_subcommand(self,', 'subc,', 'argv=None):', '(subapp,', 'help)', '=', 'self.subcommands.get(subc)', 'if', 'isinstance(subapp,', 'six.string_types):', 'subapp', '=', 'import_item(subapp)', 'self.__class__.clear_instance()', 'self.subapp', '=', 'subapp.instance(parent=self)', 'self.subapp.initialize(ar...
78,961
deepmind/trfl
action_value_ops_test.py
SarsaTest.testGradQtm1
testGradQtm1
Tests that the gradients of negative loss are equal to the td_error.
[ "Tests", "that", "the", "gradients", "of", "negative", "loss", "are", "equal", "to", "the", "td_error." ]
def testGradQtm1(self): with self.test_session() as sess: gradients = tf.gradients([-self.sarsa.loss], [self.q_tm1]) grad_q_tm1 = sess.run(gradients[0]) self.assertAllClose(grad_q_tm1, [[0, 0, 0], [0, 3, 0]])
['def', 'testGradQtm1(self):', 'with', 'self.test_session()', 'as', 'sess:', 'gradients', '=', 'tf.gradients([-self.sarsa.loss],', '[self.q_tm1])', 'grad_q_tm1', '=', 'sess.run(gradients[0])', 'self.assertAllClose(grad_q_tm1,', '[[0,', '0,', '0],', '[0,', '3,', '0]])']
356,178
triaquae/triaquae
_winapi.py
get_security_attributes_for_user
get_security_attributes_for_user
Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified).
[ "Return", "a", "SECURITY_ATTRIBUTES", "structure", "with", "the", "SID", "set", "to", "the", "specified", "user", "(uses", "current", "user", "if", "none", "is", "specified)." ]
def get_security_attributes_for_user(user=None): if user is None: user = get_current_user() assert isinstance(user, TOKEN_USER), 'user must be TOKEN_USER instance' SD = SECURITY_DESCRIPTOR() SA = SECURITY_ATTRIBUTES() SA.descriptor = SD SA.bInheritHandle = 1 ctypes.windll.advapi32.In...
['def', 'get_security_attributes_for_user(user=None):', 'if', 'user', 'is', 'None:', 'user', '=', 'get_current_user()', 'assert', 'isinstance(user,', 'TOKEN_USER),', "'user", 'must', 'be', 'TOKEN_USER', "instance'", 'SD', '=', 'SECURITY_DESCRIPTOR()', 'SA', '=', 'SECURITY_ATTRIBUTES()', 'SA.descriptor', '=', 'SD', 'SA....
356,808
benedekrozemberczki/karateclub
graph_embedding_test.py
test_ldp
test_ldp
Test the LDP embedding.
[ "Test", "the", "LDP", "embedding." ]
def test_ldp(): graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)] model = LDP(bins=8) model.fit(graphs) embedding = model.get_embedding() assert embedding.shape[0] == len(graphs) assert embedding.shape[1] == 5 * model.bins assert type(embedding) == np.ndarray grap...
['def', 'test_ldp():', 'graphs', '=', '[nx.newman_watts_strogatz_graph(50,', '5,', '0.3)', 'for', '_', 'in', 'range(100)]', 'model', '=', 'LDP(bins=8)', 'model.fit(graphs)', 'embedding', '=', 'model.get_embedding()', 'assert', 'embedding.shape[0]', '==', 'len(graphs)', 'assert', 'embedding.shape[1]', '==', '5', '*', 'm...
247,412
microsoft/InnerEye-DeepLearning
test_metrics_dict.py
test_metrics_dict_average_metrics_averaging
test_metrics_dict_average_metrics_averaging
Test if averaging metrics avoid NaN as expected.
[ "Test", "if", "averaging", "metrics", "avoid", "NaN", "as", "expected." ]
def test_metrics_dict_average_metrics_averaging() -> None: m = MetricsDict() metric1 = 'foo' v1 = 1.0 m.add_metric(metric1, v1) m.add_metric(metric1, np.nan, skip_nan_when_averaging=True) metric2 = 'bar' v2 = 2.0 m.add_metric(metric2, v2) m.add_metric(metric2, np.nan, skip_nan_when_a...
['def', 'test_metrics_dict_average_metrics_averaging()', '->', 'None:', 'm', '=', 'MetricsDict()', 'metric1', '=', "'foo'", 'v1', '=', '1.0', 'm.add_metric(metric1,', 'v1)', 'm.add_metric(metric1,', 'np.nan,', 'skip_nan_when_averaging=True)', 'metric2', '=', "'bar'", 'v2', '=', '2.0', 'm.add_metric(metric2,', 'v2)', 'm...
613,524
deepset-ai/FARM
test_prediction_head.py
test_prediction_head_load_save_class_weights
test_prediction_head_load_save_class_weights
This is a regression test for #428 and #422.
[ "This", "is", "a", "regression", "test", "for", "#428", "and", "#422." ]
def test_prediction_head_load_save_class_weights(tmp_path, caplog=None): if caplog: caplog.set_level(logging.CRITICAL) set_all_seeds(seed=42) (device, n_gpu) = initialize_device_settings(use_cuda=False) batch_size = 1 lang_model = 'bert-base-german-cased' data_dir_path = 'samples/doc_cla...
['def', 'test_prediction_head_load_save_class_weights(tmp_path,', 'caplog=None):', 'if', 'caplog:', 'caplog.set_level(logging.CRITICAL)', 'set_all_seeds(seed=42)', '(device,', 'n_gpu)', '=', 'initialize_device_settings(use_cuda=False)', 'batch_size', '=', '1', 'lang_model', '=', "'bert-base-german-cased'", 'data_dir_pa...
559,490
farcepest/moist
converters.py
Set_to_sql
Set_to_sql
Convert a Python set to an SQL literal.
[ "Convert", "a", "Python", "set", "to", "an", "SQL", "literal." ]
def Set_to_sql(connection, value): return connection.string_literal(','.join(value))
['def', 'Set_to_sql(connection,', 'value):', 'return', "connection.string_literal(','.join(value))"]
240,752
myothida/Supervised-Machine-Learning
ast.py
BaseAxis.build
build
Calls the builder object's ``set_base_axis`` callback.
[ "Calls", "the", "builder", "object's", "``set_base_axis``", "callback." ]
def build(self, builder): builder.set_base_axis(self.bases, self.scripts, self.vertical)
['def', 'build(self,', 'builder):', 'builder.set_base_axis(self.bases,', 'self.scripts,', 'self.vertical)']
360,882
tonybeltramelli/Graphics-And-Vision
Image.py
Image.StereoSGBM
StereoSGBM
Computing a stereo correspondence using the block matching algorithm.
[ "Computing", "a", "stereo", "correspondence", "using", "the", "block", "matching", "algorithm." ]
def StereoSGBM(self, minDisparity=0, blockSize=1): sgbm = cv2.StereoSGBM_create(minDisparity, minDisparity + 16, blockSize, P1=8 * 3 * blockSize ** 2, P2=32 * 3 * blockSize ** 2, disp12MaxDiff=1, preFilterCap=63, uniquenessRatio=10, speckleWindowSize=100, speckleRange=32, mode=cv2.STEREO_SGBM_MODE_HH) self.Disp...
['def', 'StereoSGBM(self,', 'minDisparity=0,', 'blockSize=1):', 'sgbm', '=', 'cv2.StereoSGBM_create(minDisparity,', 'minDisparity', '+', '16,', 'blockSize,', 'P1=8', '*', '3', '*', 'blockSize', '**', '2,', 'P2=32', '*', '3', '*', 'blockSize', '**', '2,', 'disp12MaxDiff=1,', 'preFilterCap=63,', 'uniquenessRatio=10,', 's...
580,634
Echo-Ji/ST-SSL
utils.py
load_graph
load_graph
Loading graph in form of edge index.
[ "Loading", "graph", "in", "form", "of", "edge", "index." ]
def load_graph(adj_file, device='cpu'): graph = np.load(adj_file)['adj_mx'] graph = torch.tensor(graph, device=device, dtype=torch.float) return graph
['def', 'load_graph(adj_file,', "device='cpu'):", 'graph', '=', "np.load(adj_file)['adj_mx']", 'graph', '=', 'torch.tensor(graph,', 'device=device,', 'dtype=torch.float)', 'return', 'graph']
382,973
xvjiarui/VFS
resnet3d.py
ResNet3d.init_weights
init_weights
Initiate the parameters either from existing checkpoint or from scratch.
[ "Initiate", "the", "parameters", "either", "from", "existing", "checkpoint", "or", "from", "scratch." ]
def init_weights(self): if isinstance(self.pretrained, str): logger = get_root_logger() logger.info(f'load model from: {self.pretrained}') if self.pretrained2d: self.inflate_weights(logger) else: load_checkpoint(self, self.pretrained, strict=False, logger=logg...
['def', 'init_weights(self):', 'if', 'isinstance(self.pretrained,', 'str):', 'logger', '=', 'get_root_logger()', "logger.info(f'load", 'model', 'from:', "{self.pretrained}')", 'if', 'self.pretrained2d:', 'self.inflate_weights(logger)', 'else:', 'load_checkpoint(self,', 'self.pretrained,', 'strict=False,', 'logger=logge...
379,609
PaddlePaddle/PARL
obs_filter.py
MeanStdFilter.copy
copy
Returns a copy of Filter.
[ "Returns", "a", "copy", "of", "Filter." ]
def copy(self): other = MeanStdFilter(self.shape) other.sync(self) return other
['def', 'copy(self):', 'other', '=', 'MeanStdFilter(self.shape)', 'other.sync(self)', 'return', 'other']
277,792
ddbourgin/numpy-ml
rf.py
RandomForest.fit
fit
Create `n_trees`-worth of bootstrapped samples from the training data and use each to fit a separate decision tree.
[ "Create", "`n_trees`-worth", "of", "bootstrapped", "samples", "from", "the", "training", "data", "and", "use", "each", "to", "fit", "a", "separate", "decision", "tree." ]
def fit(self, X, Y): self.trees = [] for _ in range(self.n_trees): (X_samp, Y_samp) = bootstrap_sample(X, Y) tree = DecisionTree(n_feats=self.n_feats, max_depth=self.max_depth, criterion=self.criterion, classifier=self.classifier) tree.fit(X_samp, Y_samp) self.trees.append(tree)
['def', 'fit(self,', 'X,', 'Y):', 'self.trees', '=', '[]', 'for', '_', 'in', 'range(self.n_trees):', '(X_samp,', 'Y_samp)', '=', 'bootstrap_sample(X,', 'Y)', 'tree', '=', 'DecisionTree(n_feats=self.n_feats,', 'max_depth=self.max_depth,', 'criterion=self.criterion,', 'classifier=self.classifier)', 'tree.fit(X_samp,', 'Y...
730,427
google/deepvariant
make_examples_options.py
shared_flags_to_options
shared_flags_to_options
Creates options from flags that are shared, along with given samples.
[ "Creates", "options", "from", "flags", "that", "are", "shared,", "along", "with", "given", "samples." ]
def shared_flags_to_options(add_flags, flags_obj, samples_in_order, sample_role_to_train, main_sample_index) -> deepvariant_pb2.MakeExamplesOptions: read_reqs = reads_pb2.ReadRequirements(keep_duplicates=flags_obj.keep_duplicates, keep_supplementary_alignments=flags_obj.keep_supplementary_alignments, keep_secondary...
['def', 'shared_flags_to_options(add_flags,', 'flags_obj,', 'samples_in_order,', 'sample_role_to_train,', 'main_sample_index)', '->', 'deepvariant_pb2.MakeExamplesOptions:', 'read_reqs', '=', 'reads_pb2.ReadRequirements(keep_duplicates=flags_obj.keep_duplicates,', 'keep_supplementary_alignments=flags_obj.keep_supplemen...
540,335
devashish-patel/webcam-motion-detector
test_dtype.py
TestSubarray.test_equivalent_record
test_equivalent_record
Test whether equivalent subarray dtypes hash the same.
[ "Test", "whether", "equivalent", "subarray", "dtypes", "hash", "the", "same." ]
def test_equivalent_record(self): a = np.dtype((int, (2, 3))) b = np.dtype((int, (2, 3))) assert_dtype_equal(a, b)
['def', 'test_equivalent_record(self):', 'a', '=', 'np.dtype((int,', '(2,', '3)))', 'b', '=', 'np.dtype((int,', '(2,', '3)))', 'assert_dtype_equal(a,', 'b)']
980,976
bnpy/bnpy
SeqOfBinBars9x9.py
makePi
makePi
Make phi matrix that defines probability of each pixel.
[ "Make", "phi", "matrix", "that", "defines", "probability", "of", "each", "pixel." ]
def makePi(stickyProb=0.95, extraStickyProb=0.9999, **kwargs): pi = np.zeros((K, K)) for k in range(9): pi[k, k] = stickyProb if k == 8: pi[k, bgStateID] = 1 - stickyProb else: pi[k, (k + 1) % 9] = 1 - stickyProb for k in range(9, 18): pi[k, k] = stick...
['def', 'makePi(stickyProb=0.95,', 'extraStickyProb=0.9999,', '**kwargs):', 'pi', '=', 'np.zeros((K,', 'K))', 'for', 'k', 'in', 'range(9):', 'pi[k,', 'k]', '=', 'stickyProb', 'if', 'k', '==', '8:', 'pi[k,', 'bgStateID]', '=', '1', '-', 'stickyProb', 'else:', 'pi[k,', '(k', '+', '1)', '%', '9]', '=', '1', '-', 'stickyPr...
464,631
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
imaplib.py
IMAP4.read
read
Read 'size' bytes from remote.
[ "Read", "'size'", "bytes", "from", "remote." ]
def read(self, size): return self.file.read(size)
['def', 'read(self,', 'size):', 'return', 'self.file.read(size)']
428,571
rifqind/Agent-Programs-3KS1
test_zmq_shell.py
ZMQDisplayPublisherTests.test_display_hook_return_calls_send
test_display_hook_return_calls_send
If a hook is installed and on calling the object it returns a new message, then we assume that this is just a message transformation, and the message should be sent in the usual manner.
[ "If", "a", "hook", "is", "installed", "and", "on", "calling", "the", "object", "it", "returns", "a", "new", "message,", "then", "we", "assume", "that", "this", "is", "just", "a", "message", "transformation,", "and", "the", "message", "should", "be", "sent"...
def test_display_hook_return_calls_send(self): data = dict(a=1) hook = ReturnDisplayHook() self.disp_pub.register_hook(hook) assert hook.call_count == 0 assert self.session.send_count == 0 self.disp_pub.publish(data) assert hook.call_count == 1 assert self.session.send_count == 1
['def', 'test_display_hook_return_calls_send(self):', 'data', '=', 'dict(a=1)', 'hook', '=', 'ReturnDisplayHook()', 'self.disp_pub.register_hook(hook)', 'assert', 'hook.call_count', '==', '0', 'assert', 'self.session.send_count', '==', '0', 'self.disp_pub.publish(data)', 'assert', 'hook.call_count', '==', '1', 'assert'...
40,854
arshpreetsingh/quantopian-machinelearning
console_widget.py
ConsoleWidget.copy
copy
Copy the currently selected text to the clipboard.
[ "Copy", "the", "currently", "selected", "text", "to", "the", "clipboard." ]
def copy(self): self.layout().currentWidget().copy()
['def', 'copy(self):', 'self.layout().currentWidget().copy()']
892,856
jimtin/Stock_Comparison
decorators.py
onlyif_any_cmd_exists
onlyif_any_cmd_exists
Decorator to skip test unless at least one of `commands` is found.
[ "Decorator", "to", "skip", "test", "unless", "at", "least", "one", "of", "`commands`", "is", "found." ]
def onlyif_any_cmd_exists(*commands): for cmd in commands: if which(cmd): return null_deco return skip('This test runs only if one of the commands {0} is installed'.format(commands))
['def', 'onlyif_any_cmd_exists(*commands):', 'for', 'cmd', 'in', 'commands:', 'if', 'which(cmd):', 'return', 'null_deco', 'return', "skip('This", 'test', 'runs', 'only', 'if', 'one', 'of', 'the', 'commands', '{0}', 'is', "installed'.format(commands))"]
385,633
zackmcnulty/CSE_446-Machine_Learning
pyplot.py
isinteractive
isinteractive
Return the status of interactive mode.
[ "Return", "the", "status", "of", "interactive", "mode." ]
def isinteractive(): return matplotlib.is_interactive()
['def', 'isinteractive():', 'return', 'matplotlib.is_interactive()']
194,600
rudranil723/mini-main
color.py
Color.from_rgb
from_rgb
Create a truecolor from three color components in the range(0->255).
[ "Create", "a", "truecolor", "from", "three", "color", "components", "in", "the", "range(0->255)." ]
def from_rgb(cls, red: float, green: float, blue: float) -> 'Color': return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue)))
['def', 'from_rgb(cls,', 'red:', 'float,', 'green:', 'float,', 'blue:', 'float)', '->', "'Color':", 'return', 'cls.from_triplet(ColorTriplet(int(red),', 'int(green),', 'int(blue)))']
268,871
bryanvriel/pgan
models.py
Model.save
save
Save model weights to file.
[ "Save", "model", "weights", "to", "file." ]
def save(self, outdir='checkpoints', model=None): if not os.path.isdir(outdir): os.mkdir(outdir) if model is None: for (name, saver) in self.savers.items(): saver.save(self.sess, os.path.join(outdir, '%s.ckpt' % name)) else: self.savers[model].save(self.sess, os.path.join...
['def', 'save(self,', "outdir='checkpoints',", 'model=None):', 'if', 'not', 'os.path.isdir(outdir):', 'os.mkdir(outdir)', 'if', 'model', 'is', 'None:', 'for', '(name,', 'saver)', 'in', 'self.savers.items():', 'saver.save(self.sess,', 'os.path.join(outdir,', "'%s.ckpt'", '%', 'name))', 'else:', 'self.savers[model].save(...
767,659
edwardlib/observations
free1.py
free1
free1
Freedom of Speech Data Selection of individual-level survey data for freedom of speech.
[ "Freedom", "of", "Speech", "Data", "Selection", "of", "individual-level", "survey", "data", "for", "freedom", "of", "speech." ]
def free1(path): import pandas as pd path = os.path.expanduser(path) filename = 'free1.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/Zelig/free1.csv' maybe_download_and_extract(path, url, save_file_name='free1.csv', resume=False) data =...
['def', 'free1(path):', 'import', 'pandas', 'as', 'pd', 'path', '=', 'os.path.expanduser(path)', 'filename', '=', "'free1.csv'", 'if', 'not', 'os.path.exists(os.path.join(path,', 'filename)):', 'url', '=', "'http://dustintran.com/data/r/Zelig/free1.csv'", 'maybe_download_and_extract(path,', 'url,', "save_file_name='fre...
740,290
flyteorg/flytelab
utils.py
load_train_data
load_train_data
Load jsonl train data as a list, ready to be ingested by spacy model.
[ "Load", "jsonl", "train", "data", "as", "a", "list,", "ready", "to", "be", "ingested", "by", "spacy", "model." ]
def load_train_data(train_data_files: str) -> List: train_data = [] for data_file in train_data_files: with open(data_file, 'r') as f: for json_str in list(f): train_data_dict = json.loads(json_str) train_text = train_data_dict['text'] train_en...
['def', 'load_train_data(train_data_files:', 'str)', '->', 'List:', 'train_data', '=', '[]', 'for', 'data_file', 'in', 'train_data_files:', 'with', 'open(data_file,', "'r')", 'as', 'f:', 'for', 'json_str', 'in', 'list(f):', 'train_data_dict', '=', 'json.loads(json_str)', 'train_text', '=', "train_data_dict['text']", 't...
607,006
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Base.dump
dump
Writes the Python source code for this template to the given file.
[ "Writes", "the", "Python", "source", "code", "for", "this", "template", "to", "the", "given", "file." ]
def dump(self, fd, level=0): (indent, isNotNone) = (level * self.indent, lambda x: x is not None) lineFormat = '{0}{1}\n'.format for line in ifilter(isNotNone, self.iterPrologue()): line = lineFormat(indent, line) fd.write(line if line.strip() else '\n') for item in ifilter(isNotNone, se...
['def', 'dump(self,', 'fd,', 'level=0):', '(indent,', 'isNotNone)', '=', '(level', '*', 'self.indent,', 'lambda', 'x:', 'x', 'is', 'not', 'None)', 'lineFormat', '=', "'{0}{1}\\n'.format", 'for', 'line', 'in', 'ifilter(isNotNone,', 'self.iterPrologue()):', 'line', '=', 'lineFormat(indent,', 'line)', 'fd.write(line', 'if...
16,938
srai-lab/srai
conftest.py
empty_result_gdf
empty_result_gdf
Get empty OSMOnlineLoader result gdf.
[ "Get", "empty", "OSMOnlineLoader", "result", "gdf." ]
def empty_result_gdf() -> gpd.GeoDataFrame: result_index = pd.Index(data=[], name=FEATURES_INDEX, dtype='object') return gpd.GeoDataFrame(index=result_index, crs=WGS84_CRS, geometry=[])
['def', 'empty_result_gdf()', '->', 'gpd.GeoDataFrame:', 'result_index', '=', 'pd.Index(data=[],', 'name=FEATURES_INDEX,', "dtype='object')", 'return', 'gpd.GeoDataFrame(index=result_index,', 'crs=WGS84_CRS,', 'geometry=[])']
372,024
flavioschneider/rl-transfer-
path_buffer.py
PathBuffer.add_path
add_path
Add a path to the buffer.
[ "Add", "a", "path", "to", "the", "buffer." ]
def add_path(self, path): for (key, buf_arr) in self._buffer.items(): path_array = path.get(key, None) if path_array is None: raise ValueError('Key {} missing from path.'.format(key)) if len(path_array.shape) != 2 or path_array.shape[1] != buf_arr.shape[1]: raise Valu...
['def', 'add_path(self,', 'path):', 'for', '(key,', 'buf_arr)', 'in', 'self._buffer.items():', 'path_array', '=', 'path.get(key,', 'None)', 'if', 'path_array', 'is', 'None:', 'raise', "ValueError('Key", '{}', 'missing', 'from', "path.'.format(key))", 'if', 'len(path_array.shape)', '!=', '2', 'or', 'path_array.shape[1]'...
861,240
AlperHuseyn/artificial-intelligence-and-machine-learning-with-python
iris_analysis.py
train_evaluate_save_model
train_evaluate_save_model
Train, evaluate, and save the iris prediction model.
[ "Train,", "evaluate,", "and", "save", "the", "iris", "prediction", "model." ]
def train_evaluate_save_model(X_train, y_train, X_test, y_test, X_to_predict, name='model', epochs=100): model = create_iris_model(input_dim=X_train.shape[1], name='iris') hist = model.fit(X_train, y_train, epochs=epochs, validation_split=0.1) (loss, categorical_accuracy) = model.evaluate(X_test, y_test, ve...
['def', 'train_evaluate_save_model(X_train,', 'y_train,', 'X_test,', 'y_test,', 'X_to_predict,', "name='model',", 'epochs=100):', 'model', '=', 'create_iris_model(input_dim=X_train.shape[1],', "name='iris')", 'hist', '=', 'model.fit(X_train,', 'y_train,', 'epochs=epochs,', 'validation_split=0.1)', '(loss,', 'categorica...
36,126
FitSNAP/FitSNAP
parallel_tools.py
ParallelTools.new_slice_dgrad
new_slice_dgrad
Create array to show which sub dgrad matrix indices belong to which proc.
[ "Create", "array", "to", "show", "which", "sub", "dgrad", "matrix", "indices", "belong", "to", "which", "proc." ]
def new_slice_dgrad(self): nof = len(self.shared_arrays['number_of_atoms'].array) if self._sub_rank != 0: self._bcast_fitsnap('sub_dgrad_size') self.fitsnap_dict['sub_dgrad_size'] = int(self.fitsnap_dict['sub_dgrad_size'][self._sub_rank]) self._bcast_fitsnap('sub_dgrad_indices') ...
['def', 'new_slice_dgrad(self):', 'nof', '=', "len(self.shared_arrays['number_of_atoms'].array)", 'if', 'self._sub_rank', '!=', '0:', "self._bcast_fitsnap('sub_dgrad_size')", "self.fitsnap_dict['sub_dgrad_size']", '=', "int(self.fitsnap_dict['sub_dgrad_size'][self._sub_rank])", "self._bcast_fitsnap('sub_dgrad_indices')...
584,630
LetheSec/PLG-MI-Attack
facenet.py
IR_SE_101
IR_SE_101
Constructs a ir_se-101 model.
[ "Constructs", "a", "ir_se-101", "model." ]
def IR_SE_101(input_size): model = Backbone(input_size, 100, 'ir_se') return model
['def', 'IR_SE_101(input_size):', 'model', '=', 'Backbone(input_size,', '100,', "'ir_se')", 'return', 'model']
780,545
lebrice/Sequoia
self_supervised_model.py
SelfSupervisedModel.add_auxiliary_task
add_auxiliary_task
Adds an auxiliary task to the self-supervised model.
[ "Adds", "an", "auxiliary", "task", "to", "the", "self-supervised", "model." ]
def add_auxiliary_task(self, aux_task: AuxiliaryTask, key: str=None, coefficient: float=None) -> None: key = aux_task.name if key is None else key if key in self.tasks: raise RuntimeError(f'There is already an auxiliary task with name {key} in the model!') self.tasks[key] = aux_task.to(self.device) ...
['def', 'add_auxiliary_task(self,', 'aux_task:', 'AuxiliaryTask,', 'key:', 'str=None,', 'coefficient:', 'float=None)', '->', 'None:', 'key', '=', 'aux_task.name', 'if', 'key', 'is', 'None', 'else', 'key', 'if', 'key', 'in', 'self.tasks:', 'raise', "RuntimeError(f'There", 'is', 'already', 'an', 'auxiliary', 'task', 'wit...
344,338
gunthercox/ChatterBot
qcore.py
Query.is_range
is_range
Returns True if this object searches for values within a range.
[ "Returns", "True", "if", "this", "object", "searches", "for", "values", "within", "a", "range." ]
def is_range(self): return False
['def', 'is_range(self):', 'return', 'False']
526,984
vivjay30/clearbuds
pit_criterion.py
cal_si_snr_with_pit
cal_si_snr_with_pit
Calculate SI-SNR with PIT training.
[ "Calculate", "SI-SNR", "with", "PIT", "training." ]
def cal_si_snr_with_pit(source, estimate_source, source_lengths): assert source.size() == estimate_source.size() (B, C, T) = source.size() mask = get_mask(source, source_lengths) estimate_source *= mask num_samples = source_lengths.view(-1, 1, 1).float() mean_target = torch.sum(source, dim=2, ke...
['def', 'cal_si_snr_with_pit(source,', 'estimate_source,', 'source_lengths):', 'assert', 'source.size()', '==', 'estimate_source.size()', '(B,', 'C,', 'T)', '=', 'source.size()', 'mask', '=', 'get_mask(source,', 'source_lengths)', 'estimate_source', '*=', 'mask', 'num_samples', '=', 'source_lengths.view(-1,', '1,', '1)...
488,212
facebookresearch/detectron2
coco_evaluation.py
instances_to_coco_json
instances_to_coco_json
Dump an "Instances" object to a COCO-format json that's used for evaluation.
[ "Dump", "an", "\"Instances\"", "object", "to", "a", "COCO-format", "json", "that's", "used", "for", "evaluation." ]
def instances_to_coco_json(instances, img_id): num_instance = len(instances) if num_instance == 0: return [] boxes = instances.pred_boxes.tensor.numpy() boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) boxes = boxes.tolist() scores = instances.scores.tolist() classe...
['def', 'instances_to_coco_json(instances,', 'img_id):', 'num_instance', '=', 'len(instances)', 'if', 'num_instance', '==', '0:', 'return', '[]', 'boxes', '=', 'instances.pred_boxes.tensor.numpy()', 'boxes', '=', 'BoxMode.convert(boxes,', 'BoxMode.XYXY_ABS,', 'BoxMode.XYWH_ABS)', 'boxes', '=', 'boxes.tolist()', 'scores...
549,136
sek788432/Waymo-2D-Object-Detection
video_classification.py
VideoClassificationTask.train_step
train_step
Does forward and backward.
[ "Does", "forward", "and", "backward." ]
def train_step(self, inputs: Tuple[Any, Any], model: tf.keras.Model, optimizer: tf.keras.optimizers.Optimizer, metrics: Optional[List[Any]]=None): (features, labels) = inputs num_replicas = tf.distribute.get_strategy().num_replicas_in_sync with tf.GradientTape() as tape: outputs = model(features, tr...
['def', 'train_step(self,', 'inputs:', 'Tuple[Any,', 'Any],', 'model:', 'tf.keras.Model,', 'optimizer:', 'tf.keras.optimizers.Optimizer,', 'metrics:', 'Optional[List[Any]]=None):', '(features,', 'labels)', '=', 'inputs', 'num_replicas', '=', 'tf.distribute.get_strategy().num_replicas_in_sync', 'with', 'tf.GradientTape(...
973,469
tensorflow/agents
wrappers_test.py
GoalReplayEnvWrapperTest.test_with_varying_observation_specs
test_with_varying_observation_specs
Vary the observation spec and step the environment.
[ "Vary", "the", "observation", "spec", "and", "step", "the", "environment." ]
def test_with_varying_observation_specs(self, observation_keys, observation_shapes, observation_dtypes): obs_spec = collections.OrderedDict() for (idx, key) in enumerate(observation_keys): obs_spec[key] = array_spec.ArraySpec(observation_shapes[idx], observation_dtypes) action_spec = array_spec.Boun...
['def', 'test_with_varying_observation_specs(self,', 'observation_keys,', 'observation_shapes,', 'observation_dtypes):', 'obs_spec', '=', 'collections.OrderedDict()', 'for', '(idx,', 'key)', 'in', 'enumerate(observation_keys):', 'obs_spec[key]', '=', 'array_spec.ArraySpec(observation_shapes[idx],', 'observation_dtypes)...
23,466
cheng052/BRNet
base_points.py
BasePoints.rotate
rotate
Rotate points with the given rotation matrix or angle.
[ "Rotate", "points", "with", "the", "given", "rotation", "matrix", "or", "angle." ]
def rotate(self, rotation, axis=None): if not isinstance(rotation, torch.Tensor): rotation = self.tensor.new_tensor(rotation) assert rotation.shape == torch.Size([3, 3]) or rotation.numel() == 1 if axis is None: axis = self.rotation_axis if rotation.numel() == 1: rot_sin = torch....
['def', 'rotate(self,', 'rotation,', 'axis=None):', 'if', 'not', 'isinstance(rotation,', 'torch.Tensor):', 'rotation', '=', 'self.tensor.new_tensor(rotation)', 'assert', 'rotation.shape', '==', 'torch.Size([3,', '3])', 'or', 'rotation.numel()', '==', '1', 'if', 'axis', 'is', 'None:', 'axis', '=', 'self.rotation_axis', ...
409,752
nilearn/nilearn
test_paradigm.py
test_check_events_warnings
test_check_events_warnings
Test the function which tests that the events data describes a valid experimental paradigm.
[ "Test", "the", "function", "which", "tests", "that", "the", "events", "data", "describes", "a", "valid", "experimental", "paradigm." ]
def test_check_events_warnings(): events = basic_paradigm() events = events.drop(columns=['trial_type']) with pytest.warns(UserWarning, match="'trial_type' column not found"): events_copy = check_events(events) assert len(np.unique(events_copy['trial_type'])) == 1 assert events_copy['trial_t...
['def', 'test_check_events_warnings():', 'events', '=', 'basic_paradigm()', 'events', '=', "events.drop(columns=['trial_type'])", 'with', 'pytest.warns(UserWarning,', 'match="\'trial_type\'', 'column', 'not', 'found"):', 'events_copy', '=', 'check_events(events)', 'assert', "len(np.unique(events_copy['trial_type']))", ...
723,884
scotthuang1989/object_detection_with_tensorflow
adversarial_losses.py
random_perturbation_loss_bidir
random_perturbation_loss_bidir
Adds noise to embeddings and recomputes classification loss.
[ "Adds", "noise", "to", "embeddings", "and", "recomputes", "classification", "loss." ]
def random_perturbation_loss_bidir(embedded, length, loss_fn): noise = [tf.random_normal(shape=tf.shape(emb)) for emb in embedded] masked = [_mask_by_length(n, length) for n in noise] scaled = [_scale_l2(m, FLAGS.perturb_norm_length) for m in masked] return loss_fn([e + s for (e, s) in zip(embedded, sca...
['def', 'random_perturbation_loss_bidir(embedded,', 'length,', 'loss_fn):', 'noise', '=', '[tf.random_normal(shape=tf.shape(emb))', 'for', 'emb', 'in', 'embedded]', 'masked', '=', '[_mask_by_length(n,', 'length)', 'for', 'n', 'in', 'noise]', 'scaled', '=', '[_scale_l2(m,', 'FLAGS.perturb_norm_length)', 'for', 'm', 'in'...
796,780
yinyunie/ScenePriors
test_raymarching.py
TestRaymarching.test_emission_absorption
test_emission_absorption
Test the EA raymarching algorithm.
[ "Test", "the", "EA", "raymarching", "algorithm." ]
def test_emission_absorption(self): (rays_z, rays_densities, rays_features, depths_gt, features_gt, opacities_gt) = TestRaymarching._init_random_rays(n_rays=1000, n_pts_per_ray=9, device=None, dtype=torch.float32) raymarcher_ea = EmissionAbsorptionRaymarcher() rays_densities.requires_grad = True rays_fe...
['def', 'test_emission_absorption(self):', '(rays_z,', 'rays_densities,', 'rays_features,', 'depths_gt,', 'features_gt,', 'opacities_gt)', '=', 'TestRaymarching._init_random_rays(n_rays=1000,', 'n_pts_per_ray=9,', 'device=None,', 'dtype=torch.float32)', 'raymarcher_ea', '=', 'EmissionAbsorptionRaymarcher()', 'rays_dens...
330,101
swisscom/cleanerversion
test_models.py
VersionNavigationTest.test_getting_next_version
test_getting_next_version
Get the first version of an object and navigate to the next version until we reach the last version.
[ "Get", "the", "first", "version", "of", "an", "object", "and", "navigate", "to", "the", "next", "version", "until", "we", "reach", "the", "last", "version." ]
def test_getting_next_version(self): self.assertEqual(B.objects.all().count(), 3) v1 = B.objects.as_of(self.t1).first() self.assertEqual('v1', v1.name) should_be_v2 = B.objects.next_version(v1) self.assertEqual('v2', should_be_v2.name) v2 = should_be_v2 should_be_v3 = B.objects.next_version(...
['def', 'test_getting_next_version(self):', 'self.assertEqual(B.objects.all().count(),', '3)', 'v1', '=', 'B.objects.as_of(self.t1).first()', "self.assertEqual('v1',", 'v1.name)', 'should_be_v2', '=', 'B.objects.next_version(v1)', "self.assertEqual('v2',", 'should_be_v2.name)', 'v2', '=', 'should_be_v2', 'should_be_v3'...
122,434
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
losses.py
add_rotator_image_loss
add_rotator_image_loss
Computes the image loss of deep rotator model.
[ "Computes", "the", "image", "loss", "of", "deep", "rotator", "model." ]
def add_rotator_image_loss(inputs, outputs, step_size, weight_scale): batch_size = tf.shape(inputs['images_0'])[0] image_loss = 0 for k in range(1, step_size + 1): image_loss += tf.nn.l2_loss(inputs['images_%d' % k] - outputs['images_%d' % k]) image_loss /= tf.to_float(step_size * batch_size) ...
['def', 'add_rotator_image_loss(inputs,', 'outputs,', 'step_size,', 'weight_scale):', 'batch_size', '=', "tf.shape(inputs['images_0'])[0]", 'image_loss', '=', '0', 'for', 'k', 'in', 'range(1,', 'step_size', '+', '1):', 'image_loss', '+=', "tf.nn.l2_loss(inputs['images_%d'", '%', 'k]', '-', "outputs['images_%d'", '%', '...
109,134
NUAAXQ/MLCVNet
metric_util.py
calc_iou
calc_iou
Computes IoU of two axis aligned bboxes.
[ "Computes", "IoU", "of", "two", "axis", "aligned", "bboxes." ]
def calc_iou(box_a, box_b): max_a = box_a[0:3] + box_a[3:6] / 2 max_b = box_b[0:3] + box_b[3:6] / 2 min_max = np.array([max_a, max_b]).min(0) min_a = box_a[0:3] - box_a[3:6] / 2 min_b = box_b[0:3] - box_b[3:6] / 2 max_min = np.array([min_a, min_b]).max(0) if not (min_max > max_min).all(): ...
['def', 'calc_iou(box_a,', 'box_b):', 'max_a', '=', 'box_a[0:3]', '+', 'box_a[3:6]', '/', '2', 'max_b', '=', 'box_b[0:3]', '+', 'box_b[3:6]', '/', '2', 'min_max', '=', 'np.array([max_a,', 'max_b]).min(0)', 'min_a', '=', 'box_a[0:3]', '-', 'box_a[3:6]', '/', '2', 'min_b', '=', 'box_b[0:3]', '-', 'box_b[3:6]', '/', '2', ...
630,161
kumargaurav2722/udacity-artificial--projects-and-miniprojects
logic.py
pl_resolve
pl_resolve
Return all clauses that can be obtained by resolving clauses ci and cj.
[ "Return", "all", "clauses", "that", "can", "be", "obtained", "by", "resolving", "clauses", "ci", "and", "cj." ]
def pl_resolve(ci, cj): clauses = [] for di in disjuncts(ci): for dj in disjuncts(cj): if di == ~dj or ~di == dj: dnew = unique(removeall(di, disjuncts(ci)) + removeall(dj, disjuncts(cj))) clauses.append(associate('|', dnew)) return clauses
['def', 'pl_resolve(ci,', 'cj):', 'clauses', '=', '[]', 'for', 'di', 'in', 'disjuncts(ci):', 'for', 'dj', 'in', 'disjuncts(cj):', 'if', 'di', '==', '~dj', 'or', '~di', '==', 'dj:', 'dnew', '=', 'unique(removeall(di,', 'disjuncts(ci))', '+', 'removeall(dj,', 'disjuncts(cj)))', "clauses.append(associate('|',", 'dnew))', ...
377,537
microsoft/nni
darts.py
DartsClassificationModule.configure_optimizers
configure_optimizers
Customized optimizer with momentum, as well as a scheduler.
[ "Customized", "optimizer", "with", "momentum,", "as", "well", "as", "a", "scheduler." ]
def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), momentum=0.9, lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay) return {'optimizer': optimizer, 'lr_scheduler': torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, self.max_epochs, eta_min=0.001)}
['def', 'configure_optimizers(self):', 'optimizer', '=', 'torch.optim.SGD(self.parameters(),', 'momentum=0.9,', 'lr=self.hparams.learning_rate,', 'weight_decay=self.hparams.weight_decay)', 'return', "{'optimizer':", 'optimizer,', "'lr_scheduler':", 'torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,', 'self.max_epoc...
727,989
ivanmontero/autobot
modeling_utils.py
find_pruneable_heads_and_indices
find_pruneable_heads_and_indices
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
[ "Finds", "the", "heads", "and", "their", "indices", "taking", ":obj:`already_pruned_heads`", "into", "account." ]
def find_pruneable_heads_and_indices(heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int]) -> Tuple[Set[int], torch.LongTensor]: mask = torch.ones(n_heads, head_size) heads = set(heads) - already_pruned_heads for head in heads: head = head - sum((1 if h < head else 0 for h ...
['def', 'find_pruneable_heads_and_indices(heads:', 'List[int],', 'n_heads:', 'int,', 'head_size:', 'int,', 'already_pruned_heads:', 'Set[int])', '->', 'Tuple[Set[int],', 'torch.LongTensor]:', 'mask', '=', 'torch.ones(n_heads,', 'head_size)', 'heads', '=', 'set(heads)', '-', 'already_pruned_heads', 'for', 'head', 'in', ...
418,156
open-mmlab/mmtracking
kalman_filter.py
KalmanFilter.update
update
Run Kalman filter correction step.
[ "Run", "Kalman", "filter", "correction", "step." ]
def update(self, mean, covariance, measurement): (projected_mean, projected_cov) = self.project(mean, covariance) (chol_factor, lower) = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False) kalman_gain = scipy.linalg.cho_solve((chol_factor, lower), np.dot(covariance, self._update_mat.T).T,...
['def', 'update(self,', 'mean,', 'covariance,', 'measurement):', '(projected_mean,', 'projected_cov)', '=', 'self.project(mean,', 'covariance)', '(chol_factor,', 'lower)', '=', 'scipy.linalg.cho_factor(projected_cov,', 'lower=True,', 'check_finite=False)', 'kalman_gain', '=', 'scipy.linalg.cho_solve((chol_factor,', 'lo...
625,830
google/balloon-learning-environment
balloon_env.py
BalloonEnv.step
step
Applies an action and steps the environment.
[ "Applies", "an", "action", "and", "steps", "the", "environment." ]
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Mapping[str, Any]]: command = control.AltitudeControlCommand(action) observation = self.arena.step(command) assert isinstance(observation, np.ndarray) simulator_state = self.arena.get_simulator_state() if self._renderer is not None: ...
['def', 'step(self,', 'action:', 'int)', '->', 'Tuple[np.ndarray,', 'float,', 'bool,', 'Mapping[str,', 'Any]]:', 'command', '=', 'control.AltitudeControlCommand(action)', 'observation', '=', 'self.arena.step(command)', 'assert', 'isinstance(observation,', 'np.ndarray)', 'simulator_state', '=', 'self.arena.get_simulator...
422,352
kakaobrain/pororo
__init__.py
lengths_to_mask
lengths_to_mask
Convert tensor of lengths into a boolean mask.
[ "Convert", "tensor", "of", "lengths", "into", "a", "boolean", "mask." ]
def lengths_to_mask(lengths, max_length=None): ml = torch.max(lengths) if max_length is None else max_length return torch.arange(ml, device=lengths.device)[None, :] < lengths[:, None]
['def', 'lengths_to_mask(lengths,', 'max_length=None):', 'ml', '=', 'torch.max(lengths)', 'if', 'max_length', 'is', 'None', 'else', 'max_length', 'return', 'torch.arange(ml,', 'device=lengths.device)[None,', ':]', '<', 'lengths[:,', 'None]']
782,497
Kvatsx/Artificial-Intelligence-Assignments
tree.py
Param.get_parent_function
get_parent_function
Returns the function/lambda of a parameter.
[ "Returns", "the", "function/lambda", "of", "a", "parameter." ]
def get_parent_function(self): return search_ancestor(self, 'funcdef', 'lambdef')
['def', 'get_parent_function(self):', 'return', 'search_ancestor(self,', "'funcdef',", "'lambdef')"]
74,511
CarperAI/trlx
logging.py
enable_default_handler
enable_default_handler
Enable the default handler of trlx's root logger.
[ "Enable", "the", "default", "handler", "of", "trlx's", "root", "logger." ]
def enable_default_handler() -> None: _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler)
['def', 'enable_default_handler()', '->', 'None:', '_configure_library_root_logger()', 'assert', '_default_handler', 'is', 'not', 'None', '_get_library_root_logger().addHandler(_default_handler)']
426,028
westerberg-science/openscope-glo-stim
behavior.py
Behavior.update
update
Update method for behavior.
[ "Update", "method", "for", "behavior." ]
def update(self, index=None): index = index or self.update_count super(Behavior, self).update(index) for stimulus in self.stimuli.values(): stimulus.update(index) if self.sync_sqr: self.sync_sqr.update(index) if self.auto_update: if self.window: if self.frame_puls...
['def', 'update(self,', 'index=None):', 'index', '=', 'index', 'or', 'self.update_count', 'super(Behavior,', 'self).update(index)', 'for', 'stimulus', 'in', 'self.stimuli.values():', 'stimulus.update(index)', 'if', 'self.sync_sqr:', 'self.sync_sqr.update(index)', 'if', 'self.auto_update:', 'if', 'self.window:', 'if', '...
757,579
tangyuhao/DAVIS-2016-Chanllege-Solution
xception.py
xception_arg_scope
xception_arg_scope
Defines the default Xception arg scope.
[ "Defines", "the", "default", "Xception", "arg", "scope." ]
def xception_arg_scope(weight_decay=1e-05, stddev=0.1): batch_norm_params = {'decay': 0.9997, 'epsilon': 0.001, 'updates_collections': tf.GraphKeys.UPDATE_OPS} with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.separable_convolution2d], weights_regularizer=slim.l2_regularizer(weight_decay)): w...
['def', 'xception_arg_scope(weight_decay=1e-05,', 'stddev=0.1):', 'batch_norm_params', '=', "{'decay':", '0.9997,', "'epsilon':", '0.001,', "'updates_collections':", 'tf.GraphKeys.UPDATE_OPS}', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.fully_connected,', 'slim.separable_convolution2d],', 'weights_regularizer=slim.l...
498,352
tencent-ailab/TriNet
espnet_multihead_attention.py
RelPositionMultiHeadedAttention.rel_shift
rel_shift
Compute relative positional encoding.
[ "Compute", "relative", "positional", "encoding." ]
def rel_shift(self, x): zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=-1) x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2)) x = x_padded[:, :, 1:].view_as(x)[:, :, :, :x.size(-1) // 2 + 1] if self.zero_triu: ...
['def', 'rel_shift(self,', 'x):', 'zero_pad', '=', 'torch.zeros((*x.size()[:3],', '1),', 'device=x.device,', 'dtype=x.dtype)', 'x_padded', '=', 'torch.cat([zero_pad,', 'x],', 'dim=-1)', 'x_padded', '=', 'x_padded.view(*x.size()[:2],', 'x.size(3)', '+', '1,', 'x.size(2))', 'x', '=', 'x_padded[:,', ':,', '1:].view_as(x)[...
425,545
myothida/Supervised-Machine-Learning
conftest.py
data_missing
data_missing
Fixture returning array with missing data according to parametrized float 'dtype'.
[ "Fixture", "returning", "array", "with", "missing", "data", "according", "to", "parametrized", "float", "'dtype'." ]
def data_missing(dtype): return pd.array([np.nan, 0.1], dtype=dtype)
['def', 'data_missing(dtype):', 'return', 'pd.array([np.nan,', '0.1],', 'dtype=dtype)']
443,539
matsu0228/nlp-jp
launchconfig.py
LaunchConfiguration.delete
delete
Delete this launch configuration.
[ "Delete", "this", "launch", "configuration." ]
def delete(self): return self.connection.delete_launch_configuration(self.name)
['def', 'delete(self):', 'return', 'self.connection.delete_launch_configuration(self.name)']
784,453
GatorEducator/GatorMiner
test_analyzer.py
test_dir_frequency
test_dir_frequency
Test if it return correct frequency result from a directory.
[ "Test", "if", "it", "return", "correct", "frequency", "result", "from", "a", "directory." ]
def test_dir_frequency(tmp_path): directory = tmp_path / 'sub' directory.mkdir() para_1 = directory / 'hello.md' para_2 = directory / 'world.md' text = '# header\n hello world hello world hello world' para_1.write_text(text) para_2.write_text(text) output = az.dir_frequency(directory) ...
['def', 'test_dir_frequency(tmp_path):', 'directory', '=', 'tmp_path', '/', "'sub'", 'directory.mkdir()', 'para_1', '=', 'directory', '/', "'hello.md'", 'para_2', '=', 'directory', '/', "'world.md'", 'text', '=', "'#", 'header\\n', 'hello', 'world', 'hello', 'world', 'hello', "world'", 'para_1.write_text(text)', 'para_...
567,455
Khan/guacamole
simple_engine.py
SimpleEngine.estimated_exercise_accuracies
estimated_exercise_accuracies
The simple model does not estimate exercise accuracies.
[ "The", "simple", "model", "does", "not", "estimate", "exercise", "accuracies." ]
def estimated_exercise_accuracies(self, history): return None
['def', 'estimated_exercise_accuracies(self,', 'history):', 'return', 'None']
572,197
opendilab/DI-star
lib.py
Map.data
data
Return the map data.
[ "Return", "the", "map", "data." ]
def data(self, run_config): try: return run_config.map_data(self.path, self.players) except (IOError, OSError) as e: if self.download and hasattr(e, 'filename'): logging.error("Error reading map '%s' from: %s", self.name, e.filename) logging.error('Download the map from: ...
['def', 'data(self,', 'run_config):', 'try:', 'return', 'run_config.map_data(self.path,', 'self.players)', 'except', '(IOError,', 'OSError)', 'as', 'e:', 'if', 'self.download', 'and', 'hasattr(e,', "'filename'):", 'logging.error("Error', 'reading', 'map', "'%s'", 'from:', '%s",', 'self.name,', 'e.filename)', "logging.e...
184,813
abakan-zz/ablog
blog.py
Post.prev
prev
Previous published post in chronological order.
[ "Previous", "published", "post", "in", "chronological", "order." ]
def prev(self): if self._prev == -1: link_posts(self._blog.posts) return self._prev
['def', 'prev(self):', 'if', 'self._prev', '==', '-1:', 'link_posts(self._blog.posts)', 'return', 'self._prev']
6,405
RLE-Foundation/rllte
re3.py
RE3.compute_irs
compute_irs
Compute the intrinsic rewards for current samples.
[ "Compute", "the", "intrinsic", "rewards", "for", "current", "samples." ]
def compute_irs(self, samples: Dict, step: int=0) -> th.Tensor: beta_t = self._beta * np.power(1.0 - self._kappa, step) num_steps = samples['obs'].size()[0] num_envs = samples['obs'].size()[1] obs_tensor = samples['obs'].to(self._device) intrinsic_rewards = th.zeros(size=(num_steps, num_envs)).to(se...
['def', 'compute_irs(self,', 'samples:', 'Dict,', 'step:', 'int=0)', '->', 'th.Tensor:', 'beta_t', '=', 'self._beta', '*', 'np.power(1.0', '-', 'self._kappa,', 'step)', 'num_steps', '=', "samples['obs'].size()[0]", 'num_envs', '=', "samples['obs'].size()[1]", 'obs_tensor', '=', "samples['obs'].to(self._device)", 'intri...
333,429
rifqind/Agent-Programs-3KS1
test_arraypad.py
TestAsPairs.test_as_index
test_as_index
Test results if `as_index=True`.
[ "Test", "results", "if", "`as_index=True`." ]
def test_as_index(self): assert_equal(_as_pairs([2.6, 3.3], 10, as_index=True), np.array([[3, 3]] * 10, dtype=np.intp)) assert_equal(_as_pairs([2.6, 4.49], 10, as_index=True), np.array([[3, 4]] * 10, dtype=np.intp)) for x in (-3, [-3], [[-3]], [-3, 4], [3, -4], [[-3, 4]], [[4, -3]], [[1, 2]] * 9 + [[1, -2]]...
['def', 'test_as_index(self):', 'assert_equal(_as_pairs([2.6,', '3.3],', '10,', 'as_index=True),', 'np.array([[3,', '3]]', '*', '10,', 'dtype=np.intp))', 'assert_equal(_as_pairs([2.6,', '4.49],', '10,', 'as_index=True),', 'np.array([[3,', '4]]', '*', '10,', 'dtype=np.intp))', 'for', 'x', 'in', '(-3,', '[-3],', '[[-3]],...
43,791
jsyoon0823/MRNN
mrnn.py
mrnn.fc_train
fc_train
Train Fully Connected Networks after RNN block.
[ "Train", "Fully", "Connected", "Networks", "after", "RNN", "block." ]
def fc_train(self, x, m, t): tf.compat.v1.reset_default_graph() rnn_imputed_x = self.rnn_predict(x, m, t) x = np.reshape(x, [self.no * self.seq_len, self.dim]) rnn_imputed_x = np.reshape(rnn_imputed_x, [self.no * self.seq_len, self.dim]) m = np.reshape(m, [self.no * self.seq_len, self.dim]) x_in...
['def', 'fc_train(self,', 'x,', 'm,', 't):', 'tf.compat.v1.reset_default_graph()', 'rnn_imputed_x', '=', 'self.rnn_predict(x,', 'm,', 't)', 'x', '=', 'np.reshape(x,', '[self.no', '*', 'self.seq_len,', 'self.dim])', 'rnn_imputed_x', '=', 'np.reshape(rnn_imputed_x,', '[self.no', '*', 'self.seq_len,', 'self.dim])', 'm', '...
241,704
treigerm/WaterNet
preprocessing.py
create_tiled_features_and_labels
create_tiled_features_and_labels
Create the features and labels for a given satellite image and its shapefiles.
[ "Create", "the", "features", "and", "labels", "for", "a", "given", "satellite", "image", "and", "its", "shapefiles." ]
def create_tiled_features_and_labels(geotiff_path, shapefile_paths, tile_size, only_cache=False): satellite_img_name = get_file_name(geotiff_path) cache_file_name = '{}_{}.pickle'.format(satellite_img_name, tile_size) cache_path = os.path.join(TILES_DIR, cache_file_name) try: print('Load tiles f...
['def', 'create_tiled_features_and_labels(geotiff_path,', 'shapefile_paths,', 'tile_size,', 'only_cache=False):', 'satellite_img_name', '=', 'get_file_name(geotiff_path)', 'cache_file_name', '=', "'{}_{}.pickle'.format(satellite_img_name,", 'tile_size)', 'cache_path', '=', 'os.path.join(TILES_DIR,', 'cache_file_name)',...
372,933
AndrewYinLi/lstm-neural-network-spam-filter
lancaster.py
LancasterStemmer.parseRules
parseRules
Validate the set of rules used in this stemmer.
[ "Validate", "the", "set", "of", "rules", "used", "in", "this", "stemmer." ]
def parseRules(self, rule_tuple): valid_rule = re.compile('^[a-z]+\\*?\\d[a-z]*[>\\.]?$') self.rule_dictionary = {} for rule in rule_tuple: if not valid_rule.match(rule): raise ValueError('The rule %s is invalid' % rule) first_letter = rule[0:1] if first_letter in self.ru...
['def', 'parseRules(self,', 'rule_tuple):', 'valid_rule', '=', "re.compile('^[a-z]+\\\\*?\\\\d[a-z]*[>\\\\.]?$')", 'self.rule_dictionary', '=', '{}', 'for', 'rule', 'in', 'rule_tuple:', 'if', 'not', 'valid_rule.match(rule):', 'raise', "ValueError('The", 'rule', '%s', 'is', "invalid'", '%', 'rule)', 'first_letter', '=',...
218,385
sunary/nlp
pointer_net.py
custom_dynamic_rnn
custom_dynamic_rnn
Implements a dynamic rnn that can store scores in the pointer network, the reason why we implements this is that the raw_rnn or dynamic_rnn function in Tensorflow seem to require the hidden unit and memory unit has the same dimension, and we cannot store the scores directly in the hidden unit.
[ "Implements", "a", "dynamic", "rnn", "that", "can", "store", "scores", "in", "the", "pointer", "network,", "the", "reason", "why", "we", "implements", "this", "is", "that", "the", "raw_rnn", "or", "dynamic_rnn", "function", "in", "Tensorflow", "seem", "to", ...
def custom_dynamic_rnn(cell, inputs, inputs_len, initial_state=None): batch_size = tf.shape(inputs)[0] max_time = tf.shape(inputs)[1] inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time) inputs_ta = inputs_ta.unstack(tf.transpose(inputs, [1, 0, 2])) emit_ta = tf.TensorArray(dtype=tf.float32, ...
['def', 'custom_dynamic_rnn(cell,', 'inputs,', 'inputs_len,', 'initial_state=None):', 'batch_size', '=', 'tf.shape(inputs)[0]', 'max_time', '=', 'tf.shape(inputs)[1]', 'inputs_ta', '=', 'tf.TensorArray(dtype=tf.float32,', 'size=max_time)', 'inputs_ta', '=', 'inputs_ta.unstack(tf.transpose(inputs,', '[1,', '0,', '2]))',...
808,713
jsn5/dancenet
mdn.py
split_mixture_params
split_mixture_params
Splits up an array of mixture parameters into mus, sigmas, and pis depending on the number of mixtures and output dimension.
[ "Splits", "up", "an", "array", "of", "mixture", "parameters", "into", "mus,", "sigmas,", "and", "pis", "depending", "on", "the", "number", "of", "mixtures", "and", "output", "dimension." ]
def split_mixture_params(params, output_dim, num_mixes): mus = params[:num_mixes * output_dim] sigs = params[num_mixes * output_dim:2 * num_mixes * output_dim] pi_logits = params[-num_mixes:] return (mus, sigs, pi_logits)
['def', 'split_mixture_params(params,', 'output_dim,', 'num_mixes):', 'mus', '=', 'params[:num_mixes', '*', 'output_dim]', 'sigs', '=', 'params[num_mixes', '*', 'output_dim:2', '*', 'num_mixes', '*', 'output_dim]', 'pi_logits', '=', 'params[-num_mixes:]', 'return', '(mus,', 'sigs,', 'pi_logits)']
497,028
43Carrig/recurrent_neural_networks_practice
base_ui.py
BaseUI.run_ui
run_ui
Run the UI until user- or command- triggered exit.
[ "Run", "the", "UI", "until", "user-", "or", "command-", "triggered", "exit." ]
def run_ui(self, init_command=None, title=None, title_color=None, enable_mouse_on_start=True): raise NotImplementedError('run_ui() is not implemented in BaseUI')
['def', 'run_ui(self,', 'init_command=None,', 'title=None,', 'title_color=None,', 'enable_mouse_on_start=True):', 'raise', "NotImplementedError('run_ui()", 'is', 'not', 'implemented', 'in', "BaseUI')"]
335,838
explosion/spaCy
test_pipe_methods.py
test_disable_pipes_context
test_disable_pipes_context
Test that an enabled component stays enabled after running the context manager.
[ "Test", "that", "an", "enabled", "component", "stays", "enabled", "after", "running", "the", "context", "manager." ]
def test_disable_pipes_context(nlp, name): nlp.add_pipe('new_pipe', name=name) assert nlp.has_pipe(name) with nlp.select_pipes(disable=name): assert not nlp.has_pipe(name) assert nlp.has_pipe(name)
['def', 'test_disable_pipes_context(nlp,', 'name):', "nlp.add_pipe('new_pipe',", 'name=name)', 'assert', 'nlp.has_pipe(name)', 'with', 'nlp.select_pipes(disable=name):', 'assert', 'not', 'nlp.has_pipe(name)', 'assert', 'nlp.has_pipe(name)']
894,304
lucylow/En_francais_si_vous_plait-
collaters.py
Seq2SeqCollater.collate
collate
utility function to collate samples into batch for speech recognition.
[ "utility", "function", "to", "collate", "samples", "into", "batch", "for", "speech", "recognition." ]
def collate(self, samples): if len(samples) == 0: return {} parsed_samples = [] for s in samples: if s['data'][self.feature_index] is None: continue source = s['data'][self.feature_index] if isinstance(source, (np.ndarray, np.generic)): source = torch....
['def', 'collate(self,', 'samples):', 'if', 'len(samples)', '==', '0:', 'return', '{}', 'parsed_samples', '=', '[]', 'for', 's', 'in', 'samples:', 'if', "s['data'][self.feature_index]", 'is', 'None:', 'continue', 'source', '=', "s['data'][self.feature_index]", 'if', 'isinstance(source,', '(np.ndarray,', 'np.generic)):'...
562,366
Kvatsx/Artificial-Intelligence-Assignments
glustruct.py
GLUStruct.noteObject
noteObject
Note object for later retrieval as a Python object pointer This is the registration point for "original object return", returns a void pointer to the Python object, though this is, effectively, an opaque value.
[ "Note", "object", "for", "later", "retrieval", "as", "a", "Python", "object", "pointer", "This", "is", "the", "registration", "point", "for", "\"original", "object", "return\",", "returns", "a", "void", "pointer", "to", "the", "Python", "object,", "though", "t...
def noteObject(self, object): identity = id(object) try: self.dataPointers[identity] = object except AttributeError as err: self.dataPointers = {identity: object} return identity
['def', 'noteObject(self,', 'object):', 'identity', '=', 'id(object)', 'try:', 'self.dataPointers[identity]', '=', 'object', 'except', 'AttributeError', 'as', 'err:', 'self.dataPointers', '=', '{identity:', 'object}', 'return', 'identity']
4,102
43Carrig/recurrent_neural_networks_practice
early_stopping.py
read_eval_metrics
read_eval_metrics
Helper to read eval metrics from eval summary files.
[ "Helper", "to", "read", "eval", "metrics", "from", "eval", "summary", "files." ]
def read_eval_metrics(eval_dir): eval_metrics_dict = {} for event in _summaries(eval_dir): if not event.HasField('summary'): continue metrics = {} for value in event.summary.value: if value.HasField('simple_value'): metrics[value.tag] = value.simpl...
['def', 'read_eval_metrics(eval_dir):', 'eval_metrics_dict', '=', '{}', 'for', 'event', 'in', '_summaries(eval_dir):', 'if', 'not', "event.HasField('summary'):", 'continue', 'metrics', '=', '{}', 'for', 'value', 'in', 'event.summary.value:', 'if', "value.HasField('simple_value'):", 'metrics[value.tag]', '=', 'value.sim...
313,025