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
Eric3911/OpenAGI
msdd_models.py
NeuralDiarizer.get_integrated_preds_list
get_integrated_preds_list
Merge multiple sequence inference outputs into a session level result.
[ "Merge", "multiple", "sequence", "inference", "outputs", "into", "a", "session", "level", "result." ]
def get_integrated_preds_list(self, uniq_id_list: List[str], test_data_collection: List[Any], preds_list: List[torch.Tensor]) -> List[torch.Tensor]: session_dict = get_id_tup_dict(uniq_id_list, test_data_collection, preds_list) output_dict = {uniq_id: [] for uniq_id in uniq_id_list} for (uniq_id, data_list)...
['def', 'get_integrated_preds_list(self,', 'uniq_id_list:', 'List[str],', 'test_data_collection:', 'List[Any],', 'preds_list:', 'List[torch.Tensor])', '->', 'List[torch.Tensor]:', 'session_dict', '=', 'get_id_tup_dict(uniq_id_list,', 'test_data_collection,', 'preds_list)', 'output_dict', '=', '{uniq_id:', '[]', 'for', ...
272,479
unixpickle/anyrl-py
test_env.py
test_env_exit
test_env_exit
Test an environment that straightup exits.
[ "Test", "an", "environment", "that", "straightup", "exits." ]
def test_env_exit(): try: AsyncGymEnv(lambda : sys.exit(1), None) except RuntimeError: return pytest.fail('should have gotten exception')
['def', 'test_env_exit():', 'try:', 'AsyncGymEnv(lambda', ':', 'sys.exit(1),', 'None)', 'except', 'RuntimeError:', 'return', "pytest.fail('should", 'have', 'gotten', "exception')"]
33,929
rudranil723/mini-main
srs.py
SpatialReference.xml
xml
Return the XML representation of this Spatial Reference.
[ "Return", "the", "XML", "representation", "of", "this", "Spatial", "Reference." ]
def xml(self, dialect=''): return capi.to_xml(self.ptr, byref(c_char_p()), force_bytes(dialect))
['def', 'xml(self,', "dialect=''):", 'return', 'capi.to_xml(self.ptr,', 'byref(c_char_p()),', 'force_bytes(dialect))']
315,193
lvwerra/trl
modeling_sd_base.py
DDPOStableDiffusionPipeline.unet
unet
Returns the 2d U-Net model used for diffusion.
[ "Returns", "the", "2d", "U-Net", "model", "used", "for", "diffusion." ]
def unet(self): raise NotImplementedError
['def', 'unet(self):', 'raise', 'NotImplementedError']
425,874
trenton3983/Programming_Computer__with_Python
vocabulary.py
Vocabulary.get_words
get_words
Convert descriptors to words.
[ "Convert", "descriptors", "to", "words." ]
def get_words(self, descriptors): return vq(descriptors, self.voc)[0]
['def', 'get_words(self,', 'descriptors):', 'return', 'vq(descriptors,', 'self.voc)[0]']
817,409
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
train_agent
train_agent
Train the PPO agent in the simulated environment.
[ "Train", "the", "PPO", "agent", "in", "the", "simulated", "environment." ]
def train_agent(problem_name, agent_model_dir, event_dir, world_model_dir, epoch_data_dir, hparams, epoch=0, is_final_epoch=False): gym_problem = registry.problem(problem_name) ppo_hparams = trainer_lib.create_hparams(hparams.ppo_params) ppo_params_names = ['epochs_num', 'epoch_length', 'learning_rate', 'nu...
['def', 'train_agent(problem_name,', 'agent_model_dir,', 'event_dir,', 'world_model_dir,', 'epoch_data_dir,', 'hparams,', 'epoch=0,', 'is_final_epoch=False):', 'gym_problem', '=', 'registry.problem(problem_name)', 'ppo_hparams', '=', 'trainer_lib.create_hparams(hparams.ppo_params)', 'ppo_params_names', '=', "['epochs_n...
965,976
VieVaWaldi/ReinforcementLearning
replaybuffer.py
ReplayBuffer.sample
sample
Randomly sample a batch of experiences from memory.
[ "Randomly", "sample", "a", "batch", "of", "experiences", "from", "memory." ]
def sample(self): experiences = random.sample(self.memory, k=self.batch_size) states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device) actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device) rewards = torc...
['def', 'sample(self):', 'experiences', '=', 'random.sample(self.memory,', 'k=self.batch_size)', 'states', '=', 'torch.from_numpy(np.vstack([e.state', 'for', 'e', 'in', 'experiences', 'if', 'e', 'is', 'not', 'None])).float().to(device)', 'actions', '=', 'torch.from_numpy(np.vstack([e.action', 'for', 'e', 'in', 'experie...
287,784
xuwei95/transfer-learning
test_platform_util.py
test_platform_util_wmic_parsing
test_platform_util_wmic_parsing
Verifies that platform_utils gives us the proper values that we expect based on the wmic_output string provided.
[ "Verifies", "that", "platform_utils", "gives", "us", "the", "proper", "values", "that", "we", "expect", "based", "on", "the", "wmic_output", "string", "provided." ]
def test_platform_util_wmic_parsing(platform_mock, subprocess_mock, os_mock): platform_mock.return_value = 'Windows' os_mock.return_value = True subprocess_mock.return_value = platform_config.WMIC_OUTPUT platform_util = PlatformUtil(verbose=True) platform_util.windows_init() assert platform_util...
['def', 'test_platform_util_wmic_parsing(platform_mock,', 'subprocess_mock,', 'os_mock):', 'platform_mock.return_value', '=', "'Windows'", 'os_mock.return_value', '=', 'True', 'subprocess_mock.return_value', '=', 'platform_config.WMIC_OUTPUT', 'platform_util', '=', 'PlatformUtil(verbose=True)', 'platform_util.windows_i...
927,497
Caojunxu/AC-FPN
loader.py
RoIDataLoader.minibatch_loader_thread
minibatch_loader_thread
Load mini-batches and put them onto the mini-batch queue.
[ "Load", "mini-batches", "and", "put", "them", "onto", "the", "mini-batch", "queue." ]
def minibatch_loader_thread(self): with self.coordinator.stop_on_exception(): while not self.coordinator.should_stop(): blobs = self.get_next_minibatch() ordered_blobs = OrderedDict() for key in self.get_output_names(): assert blobs[key].dtype in (np.int32...
['def', 'minibatch_loader_thread(self):', 'with', 'self.coordinator.stop_on_exception():', 'while', 'not', 'self.coordinator.should_stop():', 'blobs', '=', 'self.get_next_minibatch()', 'ordered_blobs', '=', 'OrderedDict()', 'for', 'key', 'in', 'self.get_output_names():', 'assert', 'blobs[key].dtype', 'in', '(np.int32,'...
406,506
google-research/rigl
utils.py
param_as_array
param_as_array
Returns a Flax parameter pytree as a single numpy weight vector.
[ "Returns", "a", "Flax", "parameter", "pytree", "as", "a", "single", "numpy", "weight", "vector." ]
def param_as_array(params): params_flat = jax.tree_util.tree_leaves(params) return jnp.concatenate([param.flatten() for param in params_flat])
['def', 'param_as_array(params):', 'params_flat', '=', 'jax.tree_util.tree_leaves(params)', 'return', 'jnp.concatenate([param.flatten()', 'for', 'param', 'in', 'params_flat])']
841,556
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
networks.py
conditional_generator
conditional_generator
Generator to produce MNIST images conditioned on class.
[ "Generator", "to", "produce", "MNIST", "images", "conditioned", "on", "class." ]
def conditional_generator(inputs, weight_decay=2.5e-05): (noise, one_hot_labels) = inputs return _generator_helper(noise, True, one_hot_labels, weight_decay)
['def', 'conditional_generator(inputs,', 'weight_decay=2.5e-05):', '(noise,', 'one_hot_labels)', '=', 'inputs', 'return', '_generator_helper(noise,', 'True,', 'one_hot_labels,', 'weight_decay)']
54,840
bislara/Object-detection-GUI
inputs_test.py
InputsTest.test_error_with_bad_eval_input_config
test_error_with_bad_eval_input_config
Tests that a TypeError is raised with improper eval input config.
[ "Tests", "that", "a", "TypeError", "is", "raised", "with", "improper", "eval", "input", "config." ]
def test_error_with_bad_eval_input_config(self): configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 eval_input_fn = inputs.create_eval_input_fn(eval_config=configs['eval_config'], eval_input_config=configs['model'], model_config=configs['model']) with self.as...
['def', 'test_error_with_bad_eval_input_config(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['model'].ssd.num_classes", '=', '37', 'eval_input_fn', '=', "inputs.create_eval_input_fn(eval_config=configs['eval_config'],", "eval_input_config=configs['model'],", "model_config=configs[...
726,319
noambassat/SpeechTrainer
direct_url_helpers.py
direct_url_as_pep440_direct_reference
direct_url_as_pep440_direct_reference
Convert a DirectUrl to a pip requirement string.
[ "Convert", "a", "DirectUrl", "to", "a", "pip", "requirement", "string." ]
def direct_url_as_pep440_direct_reference(direct_url, name): direct_url.validate() requirement = name + ' @ ' fragments = [] if isinstance(direct_url.info, VcsInfo): requirement += '{}+{}@{}'.format(direct_url.info.vcs, direct_url.url, direct_url.info.commit_id) elif isinstance(direct_url.in...
['def', 'direct_url_as_pep440_direct_reference(direct_url,', 'name):', 'direct_url.validate()', 'requirement', '=', 'name', '+', "'", '@', "'", 'fragments', '=', '[]', 'if', 'isinstance(direct_url.info,', 'VcsInfo):', 'requirement', '+=', "'{}+{}@{}'.format(direct_url.info.vcs,", 'direct_url.url,', 'direct_url.info.com...
895,106
googleapis/python-aiplatform
client.py
MetadataServiceClient.metadata_schema_path
metadata_schema_path
Returns a fully-qualified metadata_schema string.
[ "Returns", "a", "fully-qualified", "metadata_schema", "string." ]
def metadata_schema_path(project: str, location: str, metadata_store: str, metadata_schema: str) -> str: return 'projects/{project}/locations/{location}/metadataStores/{metadata_store}/metadataSchemas/{metadata_schema}'.format(project=project, location=location, metadata_store=metadata_store, metadata_schema=metada...
['def', 'metadata_schema_path(project:', 'str,', 'location:', 'str,', 'metadata_store:', 'str,', 'metadata_schema:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/metadataStores/{metadata_store}/metadataSchemas/{metadata_schema}'.format(project=project,", 'location=location,', 'metadata_stor...
811,138
jmout123/ffnn-optimization-algos
FeedForwardNNCG.py
FeedForwardNNCG.show_err_vs_epoch
show_err_vs_epoch
Plot validation and training errors per epoch made during training.
[ "Plot", "validation", "and", "training", "errors", "per", "epoch", "made", "during", "training." ]
def show_err_vs_epoch(self): plt.plot(self.train_errors, c='teal') plt.plot(self.val_errors, c='r') plt.xlabel('Epoch') plt.ylabel('SSE') plt.legend(['Training', 'Validation']) plt.show()
['def', 'show_err_vs_epoch(self):', 'plt.plot(self.train_errors,', "c='teal')", 'plt.plot(self.val_errors,', "c='r')", "plt.xlabel('Epoch')", "plt.ylabel('SSE')", "plt.legend(['Training',", "'Validation'])", 'plt.show()']
582,667
ADLab3Ds/TiG-BEV
create_data.py
waymo_data_prep
waymo_data_prep
Prepare the info file for waymo dataset.
[ "Prepare", "the", "info", "file", "for", "waymo", "dataset." ]
def waymo_data_prep(root_path, info_prefix, version, out_dir, workers, max_sweeps=5): from tools.data_converter import waymo_converter as waymo splits = ['training', 'validation', 'testing'] for (i, split) in enumerate(splits): load_dir = osp.join(root_path, 'waymo_format', split) if split =...
['def', 'waymo_data_prep(root_path,', 'info_prefix,', 'version,', 'out_dir,', 'workers,', 'max_sweeps=5):', 'from', 'tools.data_converter', 'import', 'waymo_converter', 'as', 'waymo', 'splits', '=', "['training',", "'validation',", "'testing']", 'for', '(i,', 'split)', 'in', 'enumerate(splits):', 'load_dir', '=', 'osp....
917,168
sek788432/Waymo-2D-Object-Detection
base_model.py
Model.build_optimizer
build_optimizer
Returns train_op to optimize total loss.
[ "Returns", "train_op", "to", "optimize", "total", "loss." ]
def build_optimizer(self): return self._optimizer_fn(self._learning_rate)
['def', 'build_optimizer(self):', 'return', 'self._optimizer_fn(self._learning_rate)']
973,507
weiaicunzai/Bag_of_Tricks_for_Image_Classification_with___
utils.py
init_weights
init_weights
the weights of conv layer and fully connected layers are both initilized with Xavier algorithm, In particular, we set the parameters to random values uniformly drawn from [-a, a] where a = sqrt(6 * (din + dout)), for batch normalization layers, y=1, b=0, all bias initialized to 0.
[ "the", "weights", "of", "conv", "layer", "and", "fully", "connected", "layers", "are", "both", "initilized", "with", "Xavier", "algorithm,", "In", "particular,", "we", "set", "the", "parameters", "to", "random", "values", "uniformly", "drawn", "from", "[-a,", ...
def init_weights(net): for m in net.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init...
['def', 'init_weights(net):', 'for', 'm', 'in', 'net.modules():', 'if', 'isinstance(m,', 'nn.Conv2d):', 'nn.init.xavier_uniform_(m.weight)', 'if', 'm.bias', 'is', 'not', 'None:', 'nn.init.constant_(m.bias,', '0)', 'elif', 'isinstance(m,', 'nn.BatchNorm2d):', 'nn.init.constant_(m.weight,', '1)', 'nn.init.constant_(m.bia...
94,037
datamllab/rlcard
utils.py
encode_cards
encode_cards
Encode cards and represerve it into plane.
[ "Encode", "cards", "and", "represerve", "it", "into", "plane." ]
def encode_cards(plane, cards): if not cards: return None layer = 1 if len(cards) == 1: rank = CARD_RANK_STR.index(cards[0]) plane[layer][rank] = 1 plane[0][rank] = 0 else: for (index, card) in enumerate(cards): if index == 0: continue ...
['def', 'encode_cards(plane,', 'cards):', 'if', 'not', 'cards:', 'return', 'None', 'layer', '=', '1', 'if', 'len(cards)', '==', '1:', 'rank', '=', 'CARD_RANK_STR.index(cards[0])', 'plane[layer][rank]', '=', '1', 'plane[0][rank]', '=', '0', 'else:', 'for', '(index,', 'card)', 'in', 'enumerate(cards):', 'if', 'index', '=...
332,272
Yuting-Gao/DisCo-pytorch
resnet.py
resnet152d
resnet152d
Constructs a ResNet-152-D model.
[ "Constructs", "a", "ResNet-152-D", "model." ]
def resnet152d(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], stem_width=32, stem_type='deep', avg_down=True, **kwargs) return _create_resnet('resnet152d', pretrained, **model_args)
['def', 'resnet152d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '8,', '36,', '3],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', '**kwargs)', 'return', "_create_resnet('resnet152d',", 'pretrained,', '**model_args)']
186,546
rifqind/Agent-Programs-3KS1
latextools.py
kpsewhich
kpsewhich
Invoke kpsewhich command with an argument `filename`.
[ "Invoke", "kpsewhich", "command", "with", "an", "argument", "`filename`." ]
def kpsewhich(filename): try: find_cmd('kpsewhich') proc = subprocess.Popen(['kpsewhich', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = proc.communicate() return stdout.strip().decode('utf8', 'replace') except FindCmdError: pass
['def', 'kpsewhich(filename):', 'try:', "find_cmd('kpsewhich')", 'proc', '=', "subprocess.Popen(['kpsewhich',", 'filename],', 'stdout=subprocess.PIPE,', 'stderr=subprocess.PIPE)', '(stdout,', 'stderr)', '=', 'proc.communicate()', 'return', "stdout.strip().decode('utf8',", "'replace')", 'except', 'FindCmdError:', 'pass'...
41,640
akandykeller/NeuralWaveMachines
phase_space.py
PhaseSpace.momentum
momentum
The momentum element of the phase space.
[ "The", "momentum", "element", "of", "the", "phase", "space." ]
def momentum(self) -> jnp.ndarray: return self._momentum
['def', 'momentum(self)', '->', 'jnp.ndarray:', 'return', 'self._momentum']
293,579
danamyu/hedgehog_detector
real_nvp_utils.py
squeeze_2x2
squeeze_2x2
Squeezing operation: reshape to convert space to channels.
[ "Squeezing", "operation:", "reshape", "to", "convert", "space", "to", "channels." ]
def squeeze_2x2(input_): return squeeze_nxn(input_, n_factor=2)
['def', 'squeeze_2x2(input_):', 'return', 'squeeze_nxn(input_,', 'n_factor=2)']
590,316
eleurent/rl-agents
robust_epc.py
RobustEPCAgent.plan
plan
Perform OPD planning with make a pessimistic version of the environment, that propagates state intervals and computes pessimistic rewards.
[ "Perform", "OPD", "planning", "with", "make", "a", "pessimistic", "version", "of", "the", "environment,", "that", "propagates", "state", "intervals", "and", "computes", "pessimistic", "rewards." ]
def plan(self, observation): self.robust_env = self.robustify_env() self.sub_agent.env = self.robust_env return self.sub_agent.plan(observation)
['def', 'plan(self,', 'observation):', 'self.robust_env', '=', 'self.robustify_env()', 'self.sub_agent.env', '=', 'self.robust_env', 'return', 'self.sub_agent.plan(observation)']
349,394
haoyfan/HeteHG-VAE
layers.py
weight_variable_glorot
weight_variable_glorot
Create a weight variable with Glorot & Bengio (AISTATS 2010) initialization.
[ "Create", "a", "weight", "variable", "with", "Glorot", "&", "Bengio", "(AISTATS", "2010)", "initialization." ]
def weight_variable_glorot(input_dim, output_dim, name=''): init_range = np.sqrt(6.0 / (input_dim + output_dim)) initial = tf.random_uniform([input_dim, output_dim], minval=-init_range, maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
['def', 'weight_variable_glorot(input_dim,', 'output_dim,', "name=''):", 'init_range', '=', 'np.sqrt(6.0', '/', '(input_dim', '+', 'output_dim))', 'initial', '=', 'tf.random_uniform([input_dim,', 'output_dim],', 'minval=-init_range,', 'maxval=init_range,', 'dtype=tf.float32)', 'return', 'tf.Variable(initial,', 'name=na...
592,834
Ruturaj123/Flowchart-Detection
factorization_ops.py
WALSModel.col_factors
col_factors
Returns a list of tensors corresponding to column factor shards.
[ "Returns", "a", "list", "of", "tensors", "corresponding", "to", "column", "factor", "shards." ]
def col_factors(self): return self._col_factors
['def', 'col_factors(self):', 'return', 'self._col_factors']
602,985
jxhe/unify-parameter-efficient-tuning
training_args_tf.py
TFTrainingArguments.train_batch_size
train_batch_size
The actual batch size for training (may differ from :obj:`per_gpu_train_batch_size` in distributed training).
[ "The", "actual", "batch", "size", "for", "training", "(may", "differ", "from", ":obj:`per_gpu_train_batch_size`", "in", "distributed", "training)." ]
def train_batch_size(self) -> int: if self.per_gpu_train_batch_size: logger.warning('Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future version. Using `--per_device_train_batch_size` is preferred.') per_device_batch_size = self.per_gpu_train_batch_size or self.per_d...
['def', 'train_batch_size(self)', '->', 'int:', 'if', 'self.per_gpu_train_batch_size:', "logger.warning('Using", 'deprecated', '`--per_gpu_train_batch_size`', 'argument', 'which', 'will', 'be', 'removed', 'in', 'a', 'future', 'version.', 'Using', '`--per_device_train_batch_size`', 'is', "preferred.')", 'per_device_batc...
948,576
deepmind/acme
utils.py
batch_to_sequence
batch_to_sequence
Converts data between sequence-major and batch-major format.
[ "Converts", "data", "between", "sequence-major", "and", "batch-major", "format." ]
def batch_to_sequence(data: types.NestedTensor) -> types.NestedTensor: return tree.map_structure(lambda t: tf.transpose(t, [1, 0] + list(range(2, t.shape.rank))), data)
['def', 'batch_to_sequence(data:', 'types.NestedTensor)', '->', 'types.NestedTensor:', 'return', 'tree.map_structure(lambda', 't:', 'tf.transpose(t,', '[1,', '0]', '+', 'list(range(2,', 't.shape.rank))),', 'data)']
8,394
Megvii-BaseDetection/cvpods
checkpoint.py
Checkpointer.tag_last_checkpoint
tag_last_checkpoint
Tag the last checkpoint.
[ "Tag", "the", "last", "checkpoint." ]
def tag_last_checkpoint(self, last_filename_basename: str): save_file = os.path.join(self.save_dir, 'last_checkpoint') with megfile.smart_open(save_file, 'w') as f: f.write(last_filename_basename)
['def', 'tag_last_checkpoint(self,', 'last_filename_basename:', 'str):', 'save_file', '=', 'os.path.join(self.save_dir,', "'last_checkpoint')", 'with', 'megfile.smart_open(save_file,', "'w')", 'as', 'f:', 'f.write(last_filename_basename)']
510,834
tensorflow/quantum
util_test.py
ExponentialUtilFunctionsTest.test_exponential_simple
test_exponential_simple
Test exponential for a simple operator.
[ "Test", "exponential", "for", "a", "simple", "operator." ]
def test_exponential_simple(self): q = cirq.GridQubit(0, 0) for op in [cirq.X, cirq.Y, cirq.Z]: theta = np.random.random() circuit = util.exponential(operators=[theta * op(q)]) ground_truth_unitary = _exponential(theta, op(q)) self.assertAllClose(ground_truth_unitary, cirq.unitar...
['def', 'test_exponential_simple(self):', 'q', '=', 'cirq.GridQubit(0,', '0)', 'for', 'op', 'in', '[cirq.X,', 'cirq.Y,', 'cirq.Z]:', 'theta', '=', 'np.random.random()', 'circuit', '=', 'util.exponential(operators=[theta', '*', 'op(q)])', 'ground_truth_unitary', '=', '_exponential(theta,', 'op(q))', 'self.assertAllClose...
835,172
google-research/rigl
masked_test.py
MaskedTest.test_symmetric_mask_sparsity_empty
test_symmetric_mask_sparsity_empty
Tests symmetric mask generation, for 0% sparsity.
[ "Tests", "symmetric", "mask", "generation,", "for", "0%", "sparsity." ]
def test_symmetric_mask_sparsity_empty(self): mask = masked.symmetric_mask(self._masked_model, self._rng, 0.0) with self.subTest(name='shuffled_neuron_empty_mask'): self.assertIn('MaskedModule_0', mask) with self.subTest(name='symmetric_empty_mask_values'): self.assertTrue((mask['MaskedModul...
['def', 'test_symmetric_mask_sparsity_empty(self):', 'mask', '=', 'masked.symmetric_mask(self._masked_model,', 'self._rng,', '0.0)', 'with', "self.subTest(name='shuffled_neuron_empty_mask'):", "self.assertIn('MaskedModule_0',", 'mask)', 'with', "self.subTest(name='symmetric_empty_mask_values'):", "self.assertTrue((mask...
841,487
nicknochnack/RealTimeSignLanguageTFJS
seq_example_util.py
sequence_bytes_feature
sequence_bytes_feature
Converts a bytes float array to a sequence bytes feature.
[ "Converts", "a", "bytes", "float", "array", "to", "a", "sequence", "bytes", "feature." ]
def sequence_bytes_feature(ndarray): feature_list = tf.train.FeatureList() for row in ndarray: if isinstance(row, np.ndarray): row = row.tolist() feature = feature_list.feature.add() if row: row = [tf.compat.as_bytes(val) for val in row] feature.bytes_...
['def', 'sequence_bytes_feature(ndarray):', 'feature_list', '=', 'tf.train.FeatureList()', 'for', 'row', 'in', 'ndarray:', 'if', 'isinstance(row,', 'np.ndarray):', 'row', '=', 'row.tolist()', 'feature', '=', 'feature_list.feature.add()', 'if', 'row:', 'row', '=', '[tf.compat.as_bytes(val)', 'for', 'val', 'in', 'row]', ...
852,335
paulorauber/rl
tensor_specs.py
CompositeSpec.is_empty
is_empty
Whether the composite spec contains specs or not.
[ "Whether", "the", "composite", "spec", "contains", "specs", "or", "not." ]
def is_empty(self): return len(self._specs) == 0
['def', 'is_empty(self):', 'return', 'len(self._specs)', '==', '0']
858,722
jesolem/PCV
hcluster.py
hcluster
hcluster
Cluster the rows of features using hierarchical clustering.
[ "Cluster", "the", "rows", "of", "features", "using", "hierarchical", "clustering." ]
def hcluster(features, distfcn=L2dist): distances = {} node = [ClusterLeafNode(array(f), id=i) for (i, f) in enumerate(features)] while len(node) > 1: closest = float('Inf') for (ni, nj) in combinations(node, 2): if (ni, nj) not in distances: distances[ni, nj] = d...
['def', 'hcluster(features,', 'distfcn=L2dist):', 'distances', '=', '{}', 'node', '=', '[ClusterLeafNode(array(f),', 'id=i)', 'for', '(i,', 'f)', 'in', 'enumerate(features)]', 'while', 'len(node)', '>', '1:', 'closest', '=', "float('Inf')", 'for', '(ni,', 'nj)', 'in', 'combinations(node,', '2):', 'if', '(ni,', 'nj)', '...
765,668
joaquimcampos/DeepSplines
basemodel.py
BaseModel.initialization
initialization
Initializes the network weights with 'He', 'Xavier', or a custom gaussian initialization.
[ "Initializes", "the", "network", "weights", "with", "'He',", "'Xavier',", "or", "a", "custom", "gaussian", "initialization." ]
def initialization(self, init_type='He'): assert init_type in ['He', 'Xavier', 'custom_normal'] if init_type == 'He': if self.activation_type in ['leaky_relu', 'relu']: nonlinearity = self.activation_type slope_init = 0.01 if nonlinearity == 'leaky_relu' else 0.0 elif sel...
['def', 'initialization(self,', "init_type='He'):", 'assert', 'init_type', 'in', "['He',", "'Xavier',", "'custom_normal']", 'if', 'init_type', '==', "'He':", 'if', 'self.activation_type', 'in', "['leaky_relu',", "'relu']:", 'nonlinearity', '=', 'self.activation_type', 'slope_init', '=', '0.01', 'if', 'nonlinearity', '=...
540,094
tensorflow/quantum
flags_test.py
FlagsTest.test_test_flags
test_test_flags
Test that kwargs convert to attributes.
[ "Test", "that", "kwargs", "convert", "to", "attributes." ]
def test_test_flags(self): params = flags.TEST_FLAGS(garbage='garbage value', other_garbage=123) assert params.garbage == 'garbage value' assert params.other_garbate == 123
['def', 'test_test_flags(self):', 'params', '=', "flags.TEST_FLAGS(garbage='garbage", "value',", 'other_garbage=123)', 'assert', 'params.garbage', '==', "'garbage", "value'", 'assert', 'params.other_garbate', '==', '123']
834,561
sek788432/Waymo-2D-Object-Detection
model_builder_tf2_test.py
ModelBuilderTF2Test.test_create_center_net_model
test_create_center_net_model
Test building a CenterNet model from proto txt.
[ "Test", "building", "a", "CenterNet", "model", "from", "proto", "txt." ]
def test_create_center_net_model(self, customize_head_params): proto_txt = '\n center_net {\n num_classes: 10\n feature_extractor {\n type: "hourglass_52"\n channel_stds: [4, 5, 6]\n bgr_ordering: true\n }\n image_resizer {\n keep_aspect_ratio_res...
['def', 'test_create_center_net_model(self,', 'customize_head_params):', 'proto_txt', '=', "'\\n", 'center_net', '{\\n', 'num_classes:', '10\\n', 'feature_extractor', '{\\n', 'type:', '"hourglass_52"\\n', 'channel_stds:', '[4,', '5,', '6]\\n', 'bgr_ordering:', 'true\\n', '}\\n', 'image_resizer', '{\\n', 'keep_aspect_ra...
974,699
thaines/helit
line_feat.py
apply_tps
apply_tps
Given an image of average colours and a thin plate spline (tps) this returns a floating point map aligned with the image where the thin plate spline has been applied to every pixel that is in the thin_mask variable.
[ "Given", "an", "image", "of", "average", "colours", "and", "a", "thin", "plate", "spline", "(tps)", "this", "returns", "a", "floating", "point", "map", "aligned", "with", "the", "image", "where", "the", "thin", "plate", "spline", "has", "been", "applied", ...
def apply_tps(average_image, thin_mask, tps): index = thin_mask == True dm = average_image[index, :] values = tps(dm) ret = numpy.zeros(average_image.shape[:2], dtype=numpy.float32) ret[index] = values return ret
['def', 'apply_tps(average_image,', 'thin_mask,', 'tps):', 'index', '=', 'thin_mask', '==', 'True', 'dm', '=', 'average_image[index,', ':]', 'values', '=', 'tps(dm)', 'ret', '=', 'numpy.zeros(average_image.shape[:2],', 'dtype=numpy.float32)', 'ret[index]', '=', 'values', 'return', 'ret']
591,941
TrellixVulnTeam/Unsupervised_Learning_HFI7
tree.py
Function.get_params
get_params
Returns a list of `Param()`.
[ "Returns", "a", "list", "of", "`Param()`." ]
def get_params(self): return [p for p in self._get_param_nodes() if p.type == 'param']
['def', 'get_params(self):', 'return', '[p', 'for', 'p', 'in', 'self._get_param_nodes()', 'if', 'p.type', '==', "'param']"]
454,016
TonghanWang/ROMA
starcraft2.py
StarCraft2Env.get_surrounding_pathing
get_surrounding_pathing
Returns pathing values of the grid surrounding the given unit.
[ "Returns", "pathing", "values", "of", "the", "grid", "surrounding", "the", "given", "unit." ]
def get_surrounding_pathing(self, unit): points = self.get_surrounding_points(unit, include_self=False) vals = [self.pathing_grid[x, y] if self.check_bounds(x, y) else 1 for (x, y) in points] return vals
['def', 'get_surrounding_pathing(self,', 'unit):', 'points', '=', 'self.get_surrounding_points(unit,', 'include_self=False)', 'vals', '=', '[self.pathing_grid[x,', 'y]', 'if', 'self.check_bounds(x,', 'y)', 'else', '1', 'for', '(x,', 'y)', 'in', 'points]', 'return', 'vals']
827,232
rll/rllab
box2d_viewer.py
PygameDraw.DrawSolidPolygon
DrawSolidPolygon
Draw a filled polygon given the screen vertices with the specified color.
[ "Draw", "a", "filled", "polygon", "given", "the", "screen", "vertices", "with", "the", "specified", "color." ]
def DrawSolidPolygon(self, vertices, color): if not vertices: return if len(vertices) == 2: pygame.draw.aaline(self.surface, color.bytes, vertices[0], vertices[1]) else: pygame.draw.polygon(self.surface, (color / 2).bytes + [127], vertices, 0) pygame.draw.polygon(self.surface...
['def', 'DrawSolidPolygon(self,', 'vertices,', 'color):', 'if', 'not', 'vertices:', 'return', 'if', 'len(vertices)', '==', '2:', 'pygame.draw.aaline(self.surface,', 'color.bytes,', 'vertices[0],', 'vertices[1])', 'else:', 'pygame.draw.polygon(self.surface,', '(color', '/', '2).bytes', '+', '[127],', 'vertices,', '0)', ...
333,041
drivendataorg/concept-to-clinic
training.py
train
train
Load the training masks from the asset folder and train a keras model.
[ "Load", "the", "training", "masks", "from", "the", "asset", "folder", "and", "train", "a", "keras", "model." ]
def train(): CUBOID_IMAGE_SHAPE = DATA_SHAPE CUBOID_BATCH = 4 assets_dir = Config.SEGMENT_ASSETS_DIR dicom_paths = get_full_dicom_paths() if not dicom_paths: raise ValueError('No LIDC dicom images found') labels = glob.glob(os.path.join(assets_dir, 'segmented_lung_patient_*.npy')) if...
['def', 'train():', 'CUBOID_IMAGE_SHAPE', '=', 'DATA_SHAPE', 'CUBOID_BATCH', '=', '4', 'assets_dir', '=', 'Config.SEGMENT_ASSETS_DIR', 'dicom_paths', '=', 'get_full_dicom_paths()', 'if', 'not', 'dicom_paths:', 'raise', "ValueError('No", 'LIDC', 'dicom', 'images', "found')", 'labels', '=', 'glob.glob(os.path.join(assets...
136,201
wvangansbeke/Revisiting-Contrastive-SSL
functional.py
convert_image_dtype
convert_image_dtype
Convert a tensor image to the given ``dtype`` and scale the values accordingly This function does not support PIL Image.
[ "Convert", "a", "tensor", "image", "to", "the", "given", "``dtype``", "and", "scale", "the", "values", "accordingly", "This", "function", "does", "not", "support", "PIL", "Image." ]
def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype=torch.float) -> torch.Tensor: if not isinstance(image, torch.Tensor): raise TypeError('Input img should be Tensor Image') return F_t.convert_image_dtype(image, dtype)
['def', 'convert_image_dtype(image:', 'torch.Tensor,', 'dtype:', 'torch.dtype=torch.float)', '->', 'torch.Tensor:', 'if', 'not', 'isinstance(image,', 'torch.Tensor):', 'raise', "TypeError('Input", 'img', 'should', 'be', 'Tensor', "Image')", 'return', 'F_t.convert_image_dtype(image,', 'dtype)']
348,672
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
trainer_lib.py
run_training_step
run_training_step
Runs a single iteration of train_op on a randomly sampled batch.
[ "Runs", "a", "single", "iteration", "of", "train_op", "on", "a", "randomly", "sampled", "batch." ]
def run_training_step(sess, trainer, train_corpus, batch_size): batch = random.sample(train_corpus, batch_size) sess.run(trainer['run'], feed_dict={trainer['input_batch']: batch})
['def', 'run_training_step(sess,', 'trainer,', 'train_corpus,', 'batch_size):', 'batch', '=', 'random.sample(train_corpus,', 'batch_size)', "sess.run(trainer['run'],", "feed_dict={trainer['input_batch']:", 'batch})']
111,524
f-dangel/cockpit
quantity.py
SingleStepQuantity.should_compute
should_compute
Return if computations need to be performed at a specific iteration.
[ "Return", "if", "computations", "need", "to", "be", "performed", "at", "a", "specific", "iteration." ]
def should_compute(self, global_step): return self._track_schedule(global_step)
['def', 'should_compute(self,', 'global_step):', 'return', 'self._track_schedule(global_step)']
492,643
sunishsheth2009/ChatterBot
ma.py
trace
trace
trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array.
[ "trace(a,offset=0,", "axis1=0,", "axis2=1)", "returns", "the", "sum", "along", "diagonals", "(defined", "by", "the", "last", "two", "dimenions)", "of", "the", "array." ]
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): return diagonal(a, offset, axis1, axis2).sum(dtype=dtype)
['def', 'trace(a,', 'offset=0,', 'axis1=0,', 'axis2=1,', 'dtype=None,', 'out=None):', 'return', 'diagonal(a,', 'offset,', 'axis1,', 'axis2).sum(dtype=dtype)']
532,331
deepmind/meltingpot
scenario.py
Scenario.observables
observables
Returns the observables for the scenario.
[ "Returns", "the", "observables", "for", "the", "scenario." ]
def observables(self) -> ScenarioObservables: return self._observables
['def', 'observables(self)', '->', 'ScenarioObservables:', 'return', 'self._observables']
285,932
AbdelrahmanRadwan/object-detection
config_util.py
get_learning_rate_type
get_learning_rate_type
Returns the learning rate type for training.
[ "Returns", "the", "learning", "rate", "type", "for", "training." ]
def get_learning_rate_type(optimizer_config): return optimizer_config.learning_rate.WhichOneof('learning_rate')
['def', 'get_learning_rate_type(optimizer_config):', 'return', "optimizer_config.learning_rate.WhichOneof('learning_rate')"]
746,918
muyuuuu/Remote-Sensing-Semantic-
datamodule.py
DFC2022.plot
plot
Plot a sample from the dataset.
[ "Plot", "a", "sample", "from", "the", "dataset." ]
def plot(self, sample: Dict[str, Tensor], show_titles: bool=True, suptitle: Optional[str]=None) -> plt.Figure: ncols = 2 image = sample['image'][:3] image = image.to(torch.uint8) image = image.permute(1, 2, 0).numpy() dem = sample['image'][-1].numpy() dem = percentile_normalization(dem, lower=0,...
['def', 'plot(self,', 'sample:', 'Dict[str,', 'Tensor],', 'show_titles:', 'bool=True,', 'suptitle:', 'Optional[str]=None)', '->', 'plt.Figure:', 'ncols', '=', '2', 'image', '=', "sample['image'][:3]", 'image', '=', 'image.to(torch.uint8)', 'image', '=', 'image.permute(1,', '2,', '0).numpy()', 'dem', '=', "sample['image...
840,029
shanest/quantifier-rnn-learning
quantifiers.py
all_but_n
all_but_n
Generates a Quantifier corresponding to all but n.
[ "Generates", "a", "Quantifier", "corresponding", "to", "all", "but", "n." ]
def all_but_n(n): return Quantifier('all_but_{}'.format(n), isom=True, cons=True, lcons=False, rmon=None, lmon=None, fn=lambda seq: all_but_n_ver(seq, n))
['def', 'all_but_n(n):', 'return', "Quantifier('all_but_{}'.format(n),", 'isom=True,', 'cons=True,', 'lcons=False,', 'rmon=None,', 'lmon=None,', 'fn=lambda', 'seq:', 'all_but_n_ver(seq,', 'n))']
304,021
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_preprocess.py
resize_image
resize_image
Resize image to target size.
[ "Resize", "image", "to", "target", "size." ]
def resize_image(image, size=None): if size is None: raise ValueError('Must specify size') if image.shape_as_list()[:2] == size: return image image = tf.expand_dims(image, 0) image = tf.image.resize_images(image, size) image = tf.squeeze(image, 0) return image
['def', 'resize_image(image,', 'size=None):', 'if', 'size', 'is', 'None:', 'raise', "ValueError('Must", 'specify', "size')", 'if', 'image.shape_as_list()[:2]', '==', 'size:', 'return', 'image', 'image', '=', 'tf.expand_dims(image,', '0)', 'image', '=', 'tf.image.resize_images(image,', 'size)', 'image', '=', 'tf.squeeze...
54,470
rifqind/Agent-Programs-3KS1
prefilter.py
PrefilterManager.unregister_transformer
unregister_transformer
Unregister a transformer instance.
[ "Unregister", "a", "transformer", "instance." ]
def unregister_transformer(self, transformer): if transformer in self._transformers: self._transformers.remove(transformer)
['def', 'unregister_transformer(self,', 'transformer):', 'if', 'transformer', 'in', 'self._transformers:', 'self._transformers.remove(transformer)']
41,215
myothida/Supervised-Machine-Learning
properties.py
LineWidth.default_range
default_range
Min and max values used by default for semantic mapping.
[ "Min", "and", "max", "values", "used", "by", "default", "for", "semantic", "mapping." ]
def default_range(self) -> tuple[float, float]: base = mpl.rcParams['lines.linewidth'] return (base * 0.5, base * 2)
['def', 'default_range(self)', '->', 'tuple[float,', 'float]:', 'base', '=', "mpl.rcParams['lines.linewidth']", 'return', '(base', '*', '0.5,', 'base', '*', '2)']
446,787
triaquae/triaquae
sql.py
sql_indexes
sql_indexes
Returns a list of the CREATE INDEX SQL statements for all models in the given app.
[ "Returns", "a", "list", "of", "the", "CREATE", "INDEX", "SQL", "statements", "for", "all", "models", "in", "the", "given", "app." ]
def sql_indexes(app, style, connection): output = [] for model in models.get_models(app): output.extend(connection.creation.sql_indexes_for_model(model, style)) return output
['def', 'sql_indexes(app,', 'style,', 'connection):', 'output', '=', '[]', 'for', 'model', 'in', 'models.get_models(app):', 'output.extend(connection.creation.sql_indexes_for_model(model,', 'style))', 'return', 'output']
358,351
rudranil723/mini-main
__init__.py
BaseDocReader.readInfoElement
readInfoElement
Read the info element.
[ "Read", "the", "info", "element." ]
def readInfoElement(self, infoElement, instanceObject): instanceObject.info = True
['def', 'readInfoElement(self,', 'infoElement,', 'instanceObject):', 'instanceObject.info', '=', 'True']
317,028
Mhttx2016/Multi-Camera-Object-Tracking-via-Transferring-Representation-to-Top-View
resnet.py
Resnet.features_v2_generator
features_v2_generator
Generator for ResNet v2 models.
[ "Generator", "for", "ResNet", "v2", "models." ]
def features_v2_generator(self, block_fn, layers, is_training=True, feature_map_layer='block_layer4', data_format=None): print('Get feature map:', feature_map_layer, 'with is_training=', is_training, 'reuse:', self.reuse_resnet) if data_format is None: data_format = 'channels_first' if tf.test.is_built_...
['def', 'features_v2_generator(self,', 'block_fn,', 'layers,', 'is_training=True,', "feature_map_layer='block_layer4',", 'data_format=None):', "print('Get", 'feature', "map:',", 'feature_map_layer,', "'with", "is_training=',", 'is_training,', "'reuse:',", 'self.reuse_resnet)', 'if', 'data_format', 'is', 'None:', 'data_...
643,378
asyml/texar-pytorch
vocabulary.py
Vocab.special_tokens
special_tokens
The list of special tokens [:attr:`pad_token`, :attr:`bos_token`, :attr:`eos_token`, :attr:`unk_token`].
[ "The", "list", "of", "special", "tokens", "[:attr:`pad_token`,", ":attr:`bos_token`,", ":attr:`eos_token`,", ":attr:`unk_token`]." ]
def special_tokens(self) -> List[str]: return [self._pad_token, self._bos_token, self._eos_token, self._unk_token]
['def', 'special_tokens(self)', '->', 'List[str]:', 'return', '[self._pad_token,', 'self._bos_token,', 'self._eos_token,', 'self._unk_token]']
925,031
Speedwagon13/CS-3600-Introduction-to--
_abcoll.py
Set.isdisjoint
isdisjoint
Return True if two sets have a null intersection.
[ "Return", "True", "if", "two", "sets", "have", "a", "null", "intersection." ]
def isdisjoint(self, other): for value in other: if value in self: return False return True
['def', 'isdisjoint(self,', 'other):', 'for', 'value', 'in', 'other:', 'if', 'value', 'in', 'self:', 'return', 'False', 'return', 'True']
139,989
zihuitang/medical_AI_platform
mailbox.py
_mboxMMDF.get_message
get_message
Return a Message representation or raise a KeyError.
[ "Return", "a", "Message", "representation", "or", "raise", "a", "KeyError." ]
def get_message(self, key): (start, stop) = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(linesep, b'') string = self._file.read(stop - self._file.tell()) msg = self._message_factory(string.replace(linesep, b'\n')) msg.set_from(from_line[5:].decode('ascii')) ...
['def', 'get_message(self,', 'key):', '(start,', 'stop)', '=', 'self._lookup(key)', 'self._file.seek(start)', 'from_line', '=', 'self._file.readline().replace(linesep,', "b'')", 'string', '=', 'self._file.read(stop', '-', 'self._file.tell())', 'msg', '=', 'self._message_factory(string.replace(linesep,', "b'\\n'))", "ms...
280,745
zihuitang/medical_AI_platform
__init__.py
wstring_at
wstring_at
wstring_at(addr[, size]) -> string Return the string at addr.
[ "wstring_at(addr[,", "size])", "->", "string", "Return", "the", "string", "at", "addr." ]
def wstring_at(ptr, size=-1): return _wstring_at(ptr, size)
['def', 'wstring_at(ptr,', 'size=-1):', 'return', '_wstring_at(ptr,', 'size)']
282,148
Honkl/general-ai
dqn.py
DQN.convert_to_sequence
convert_to_sequence
From specified action, creates a list of n outputs, onehot encoding.
[ "From", "specified", "action,", "creates", "a", "list", "of", "n", "outputs,", "onehot", "encoding." ]
def convert_to_sequence(self, action): result = np.zeros(self.num_actions) result[action] = 1 return result
['def', 'convert_to_sequence(self,', 'action):', 'result', '=', 'np.zeros(self.num_actions)', 'result[action]', '=', '1', 'return', 'result']
202,297
google-research/rigl
sac_train_eval.py
create_sequential_critic_network
create_sequential_critic_network
Create a sequential critic network.
[ "Create", "a", "sequential", "critic", "network." ]
def create_sequential_critic_network(obs_fc_layer_units, action_fc_layer_units, joint_fc_layer_units, input_dim, is_sparse=False, width=1.0, weight_decay=0.0, sparse_output_layer=True): def split_inputs(inputs): return {'observation': inputs[0], 'action': inputs[1]} obs_network_layers = create_fc_layer...
['def', 'create_sequential_critic_network(obs_fc_layer_units,', 'action_fc_layer_units,', 'joint_fc_layer_units,', 'input_dim,', 'is_sparse=False,', 'width=1.0,', 'weight_decay=0.0,', 'sparse_output_layer=True):', 'def', 'split_inputs(inputs):', 'return', "{'observation':", 'inputs[0],', "'action':", 'inputs[1]}', 'obs...
841,648
Ikomia-dev/IkomiaApi
workflow.py
Workflow.find_task
find_task
Get identifiers and instance of tasks with the given name in the workflow.
[ "Get", "identifiers", "and", "instance", "of", "tasks", "with", "the", "given", "name", "in", "the", "workflow." ]
def find_task(self, name: str, index=-1): tasks = [] ids = self.get_task_ids() for task_id in ids: task = self.get_task(task_id) if task.name == name: tasks.append(task) if 0 <= index < len(tasks): return tasks[index] else: return tasks
['def', 'find_task(self,', 'name:', 'str,', 'index=-1):', 'tasks', '=', '[]', 'ids', '=', 'self.get_task_ids()', 'for', 'task_id', 'in', 'ids:', 'task', '=', 'self.get_task(task_id)', 'if', 'task.name', '==', 'name:', 'tasks.append(task)', 'if', '0', '<=', 'index', '<', 'len(tasks):', 'return', 'tasks[index]', 'else:',...
598,692
apeterswu/RL4NMT
bytenet.py
bytenet_internal
bytenet_internal
ByteNet, main step used for training.
[ "ByteNet,", "main", "step", "used", "for", "training." ]
def bytenet_internal(inputs, targets, hparams): with tf.variable_scope('bytenet'): inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2) extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1])) inputs_shape = inputs.shape.as_list() inputs = tf.pad(inputs, [[0,...
['def', 'bytenet_internal(inputs,', 'targets,', 'hparams):', 'with', "tf.variable_scope('bytenet'):", 'inputs', '=', 'tf.expand_dims(common_layers.flatten4d3d(inputs),', 'axis=2)', 'extend_length', '=', 'tf.to_int32(0.5', '*', 'tf.to_float(tf.shape(inputs)[1]))', 'inputs_shape', '=', 'inputs.shape.as_list()', 'inputs',...
331,634
deepmind/dm_control
engine.py
Physics.render
render
Returns a camera view as a NumPy array of pixel values.
[ "Returns", "a", "camera", "view", "as", "a", "NumPy", "array", "of", "pixel", "values." ]
def render(self, height=240, width=320, camera_id=-1, overlays=(), depth=False, segmentation=False, scene_option=None, render_flag_overrides=None, scene_callback: Optional[Callable[['Physics', mujoco.MjvScene], None]]=None): camera = Camera(physics=self, height=height, width=width, camera_id=camera_id, scene_callba...
['def', 'render(self,', 'height=240,', 'width=320,', 'camera_id=-1,', 'overlays=(),', 'depth=False,', 'segmentation=False,', 'scene_option=None,', 'render_flag_overrides=None,', 'scene_callback:', "Optional[Callable[['Physics',", 'mujoco.MjvScene],', 'None]]=None):', 'camera', '=', 'Camera(physics=self,', 'height=heigh...
165,256
RasaHQ/rasa
telemetry.py
track_validate_files
track_validate_files
Track when a user validates data files.
[ "Track", "when", "a", "user", "validates", "data", "files." ]
def track_validate_files(validation_success: bool) -> None: _track(TELEMETRY_DATA_VALIDATED_EVENT, {'validation_success': validation_success})
['def', 'track_validate_files(validation_success:', 'bool)', '->', 'None:', '_track(TELEMETRY_DATA_VALIDATED_EVENT,', "{'validation_success':", 'validation_success})']
836,572
pulp-platform/quantlib
inq_ops.py
INQController.step_pre_training_epoch
step_pre_training_epoch
Call this each epoch before training loop.
[ "Call", "this", "each", "epoch", "before", "training", "loop." ]
def step_pre_training_epoch(self, epoch, optimizer=None, tb_writer=None): if epoch in self.schedule.keys(): self.fraction = self.schedule[epoch] else: return for m in self.modules: m.step(self.fraction) if optimizer is not None and self.clear_optim_state_on_step: optimize...
['def', 'step_pre_training_epoch(self,', 'epoch,', 'optimizer=None,', 'tb_writer=None):', 'if', 'epoch', 'in', 'self.schedule.keys():', 'self.fraction', '=', 'self.schedule[epoch]', 'else:', 'return', 'for', 'm', 'in', 'self.modules:', 'm.step(self.fraction)', 'if', 'optimizer', 'is', 'not', 'None', 'and', 'self.clear_...
816,261
rudranil723/mini-main
geometry.py
GEOSGeometryBase.area
area
Return the area of the Geometry.
[ "Return", "the", "area", "of", "the", "Geometry." ]
def area(self): return capi.geos_area(self.ptr, byref(c_double()))
['def', 'area(self):', 'return', 'capi.geos_area(self.ptr,', 'byref(c_double()))']
315,330
gunthercox/ChatterBot
expression.py
Select.union_all
union_all
return a SQL UNION ALL of this select() construct against the given selectable.
[ "return", "a", "SQL", "UNION", "ALL", "of", "this", "select()", "construct", "against", "the", "given", "selectable." ]
def union_all(self, other, **kwargs): return union_all(self, other, **kwargs)
['def', 'union_all(self,', 'other,', '**kwargs):', 'return', 'union_all(self,', 'other,', '**kwargs)']
535,062
worldbank/wb-nlp-tools
cache_utils.py
get_func_fullname
get_func_fullname
Compute the part of part associated with a function.
[ "Compute", "the", "part", "of", "part", "associated", "with", "a", "function." ]
def get_func_fullname(func): (modules, funcname) = joblib.func_inspect.get_func_name(func) modules.append(funcname) return os.path.join(*modules)
['def', 'get_func_fullname(func):', '(modules,', 'funcname)', '=', 'joblib.func_inspect.get_func_name(func)', 'modules.append(funcname)', 'return', 'os.path.join(*modules)']
975,957
Eric3911/OpenAGI
vocab.py
Vocab.unk_index
unk_index
The index of unknow symbol.
[ "The", "index", "of", "unknow", "symbol." ]
def unk_index(self): return self.stoi.get(self.unk_symbol, -1)
['def', 'unk_index(self):', 'return', 'self.stoi.get(self.unk_symbol,', '-1)']
251,706
openvinotoolkit/training_extensions
custom_image_classifier.py
sam_image_classifier__extract_feat
sam_image_classifier__extract_feat
Feature extraction function for SAMClassifier with mmdeploy.
[ "Feature", "extraction", "function", "for", "SAMClassifier", "with", "mmdeploy." ]
def sam_image_classifier__extract_feat(ctx, self, img): feat = self.backbone(img) if isinstance(feat, (tuple, list)): feat = feat[-1] backbone_feat = feat if self.with_neck: feat = self.neck(feat) return (feat, backbone_feat)
['def', 'sam_image_classifier__extract_feat(ctx,', 'self,', 'img):', 'feat', '=', 'self.backbone(img)', 'if', 'isinstance(feat,', '(tuple,', 'list)):', 'feat', '=', 'feat[-1]', 'backbone_feat', '=', 'feat', 'if', 'self.with_neck:', 'feat', '=', 'self.neck(feat)', 'return', '(feat,', 'backbone_feat)']
904,011
Ruturaj123/Flowchart-Detection
stepper_cli.py
NodeStepperCLI.print_tensor
print_tensor
Print the value of a tensor that the stepper has access to.
[ "Print", "the", "value", "of", "a", "tensor", "that", "the", "stepper", "has", "access", "to." ]
def print_tensor(self, args, screen_info=None): parsed = self.arg_parsers['print_tensor'].parse_args(args) if screen_info and 'cols' in screen_info: np_printoptions = {'linewidth': screen_info['cols']} else: np_printoptions = {} highlight_options = cli_shared.parse_ranges_highlight(parse...
['def', 'print_tensor(self,', 'args,', 'screen_info=None):', 'parsed', '=', "self.arg_parsers['print_tensor'].parse_args(args)", 'if', 'screen_info', 'and', "'cols'", 'in', 'screen_info:', 'np_printoptions', '=', "{'linewidth':", "screen_info['cols']}", 'else:', 'np_printoptions', '=', '{}', 'highlight_options', '=', '...
605,092
voxel51/fiftyone
__init__.py
ZooDataset.supported_splits
supported_splits
A tuple of supported splits for the dataset, or None if the dataset does not have splits.
[ "A", "tuple", "of", "supported", "splits", "for", "the", "dataset,", "or", "None", "if", "the", "dataset", "does", "not", "have", "splits." ]
def supported_splits(self): raise NotImplementedError('subclasses must implement supported_splits')
['def', 'supported_splits(self):', 'raise', "NotImplementedError('subclasses", 'must', 'implement', "supported_splits')"]
584,394
Erfanafshar/Principles-and-Applications-of---graph-coloring
bezier.py
split_de_casteljau
split_de_casteljau
Split a bezier segment defined by its control points *beta* into two separate segments divided at *t* and return their control points.
[ "Split", "a", "bezier", "segment", "defined", "by", "its", "control", "points", "*beta*", "into", "two", "separate", "segments", "divided", "at", "*t*", "and", "return", "their", "control", "points." ]
def split_de_casteljau(beta, t): beta = np.asarray(beta) beta_list = [beta] while True: beta = _de_casteljau1(beta, t) beta_list.append(beta) if len(beta) == 1: break left_beta = [beta[0] for beta in beta_list] right_beta = [beta[-1] for beta in reversed(beta_list...
['def', 'split_de_casteljau(beta,', 't):', 'beta', '=', 'np.asarray(beta)', 'beta_list', '=', '[beta]', 'while', 'True:', 'beta', '=', '_de_casteljau1(beta,', 't)', 'beta_list.append(beta)', 'if', 'len(beta)', '==', '1:', 'break', 'left_beta', '=', '[beta[0]', 'for', 'beta', 'in', 'beta_list]', 'right_beta', '=', '[bet...
306,515
replit-archive/empythoned
_parseaddr.py
AddrlistClass.gotonext
gotonext
Parse up to the start of the next address.
[ "Parse", "up", "to", "the", "start", "of", "the", "next", "address." ]
def gotonext(self): while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break
['def', 'gotonext(self):', 'while', 'self.pos', '<', 'len(self.field):', 'if', 'self.field[self.pos]', 'in', 'self.LWS', '+', "'\\n\\r':", 'self.pos', '+=', '1', 'elif', 'self.field[self.pos]', '==', "'(':", 'self.commentlist.append(self.getcomment())', 'else:', 'break']
176,649
mrahtz/learning-from-human-preferences
reward_predictor_test.py
TestRewardPredictor.test_batches
test_batches
Present a batch of two trajectories and check that we get the same results as if we'd presented the trajectories individually.
[ "Present", "a", "batch", "of", "two", "trajectories", "and", "check", "that", "we", "get", "the", "same", "results", "as", "if", "we'd", "presented", "the", "trajectories", "individually." ]
def test_batches(self): n_segs = 2 n_frames = 20 prefs = [[0.0, 1.0], [1.0, 0.0]] s1s = [] s2s = [] for _ in range(n_segs): s1 = 255 * np.random.normal(loc=1.0, size=(n_frames, 84, 84, 4)) s2 = 255 * np.random.normal(loc=-1.0, size=(n_frames, 84, 84, 4)) s1s.append(s1) ...
['def', 'test_batches(self):', 'n_segs', '=', '2', 'n_frames', '=', '20', 'prefs', '=', '[[0.0,', '1.0],', '[1.0,', '0.0]]', 's1s', '=', '[]', 's2s', '=', '[]', 'for', '_', 'in', 'range(n_segs):', 's1', '=', '255', '*', 'np.random.normal(loc=1.0,', 'size=(n_frames,', '84,', '84,', '4))', 's2', '=', '255', '*', 'np.rand...
262,139
sbjelogr/TransferBoost
loss_functions.py
logloss
logloss
Return the gradient and hessian of the log loss.
[ "Return", "the", "gradient", "and", "hessian", "of", "the", "log", "loss." ]
def logloss(y_pred, y_true): if isinstance(y_pred, pd.Series): y_pred = y_pred.values if isinstance(y_true, pd.Series): y_true = y_true.values grad = y_true - y_pred hess = y_pred * (1.0 - y_pred) return (grad, hess)
['def', 'logloss(y_pred,', 'y_true):', 'if', 'isinstance(y_pred,', 'pd.Series):', 'y_pred', '=', 'y_pred.values', 'if', 'isinstance(y_true,', 'pd.Series):', 'y_true', '=', 'y_true.values', 'grad', '=', 'y_true', '-', 'y_pred', 'hess', '=', 'y_pred', '*', '(1.0', '-', 'y_pred)', 'return', '(grad,', 'hess)']
930,179
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
experiment.py
find_checkpoint
find_checkpoint
Finds the global step for the latest written checkpoint to the load_dir.
[ "Finds", "the", "global", "step", "for", "the", "latest", "written", "checkpoint", "to", "the", "load_dir." ]
def find_checkpoint(load_dir, seen_step): ckpt = tf.train.get_checkpoint_state(load_dir) if ckpt and ckpt.model_checkpoint_path: global_step = extract_step(ckpt.model_checkpoint_path) if int(global_step) != seen_step: return (int(global_step), ckpt.model_checkpoint_path) return (...
['def', 'find_checkpoint(load_dir,', 'seen_step):', 'ckpt', '=', 'tf.train.get_checkpoint_state(load_dir)', 'if', 'ckpt', 'and', 'ckpt.model_checkpoint_path:', 'global_step', '=', 'extract_step(ckpt.model_checkpoint_path)', 'if', 'int(global_step)', '!=', 'seen_step:', 'return', '(int(global_step),', 'ckpt.model_checkp...
46,803
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Canvas.focus
focus
Set focus to the first item specified in ARGS.
[ "Set", "focus", "to", "the", "first", "item", "specified", "in", "ARGS." ]
def focus(self, *args): return self.tk.call((self._w, 'focus') + args)
['def', 'focus(self,', '*args):', 'return', 'self.tk.call((self._w,', "'focus')", '+', 'args)']
376,957
open-mmlab/mmtracking
roi_embed_head.py
RoIEmbedHead.get_targets
get_targets
Calculate the ground truth for all samples in a batch according to the sampling_results.
[ "Calculate", "the", "ground", "truth", "for", "all", "samples", "in", "a", "batch", "according", "to", "the", "sampling_results." ]
def get_targets(self, sampling_results, gt_instance_ids, ref_gt_instance_ids): track_id_targets = [] track_id_weights = [] for (res, gt_instance_id, ref_gt_instance_id) in zip(sampling_results, gt_instance_ids, ref_gt_instance_ids): pos_instance_ids = gt_instance_id[res.pos_assigned_gt_inds] ...
['def', 'get_targets(self,', 'sampling_results,', 'gt_instance_ids,', 'ref_gt_instance_ids):', 'track_id_targets', '=', '[]', 'track_id_weights', '=', '[]', 'for', '(res,', 'gt_instance_id,', 'ref_gt_instance_id)', 'in', 'zip(sampling_results,', 'gt_instance_ids,', 'ref_gt_instance_ids):', 'pos_instance_ids', '=', 'gt_...
625,898
thaines/helit
gaussian.py
Gaussian.setMean
setMean
Sets the mean - you can use anything numpy will interprete as a 1D array of the correct length.
[ "Sets", "the", "mean", "-", "you", "can", "use", "anything", "numpy", "will", "interprete", "as", "a", "1D", "array", "of", "the", "correct", "length." ]
def setMean(self, mean): nm = numpy.array(mean, dtype=numpy.float32) assert nm.shape == self.mean.shape self.mean = nm
['def', 'setMean(self,', 'mean):', 'nm', '=', 'numpy.array(mean,', 'dtype=numpy.float32)', 'assert', 'nm.shape', '==', 'self.mean.shape', 'self.mean', '=', 'nm']
591,632
bnpy/bnpy
NumericUtil.py
inplaceExp_numexpr
inplaceExp_numexpr
Calculate exp of each entry of input matrix, done in-place.
[ "Calculate", "exp", "of", "each", "entry", "of", "input", "matrix,", "done", "in-place." ]
def inplaceExp_numexpr(R): ne.evaluate('exp(R)', out=R)
['def', 'inplaceExp_numexpr(R):', "ne.evaluate('exp(R)',", 'out=R)']
465,182
LLNL/Abmarl
wrapper.py
RavelActionWrapper.check_space
check_space
Ensure that the space is of type that can be ravelled to discrete value.
[ "Ensure", "that", "the", "space", "is", "of", "type", "that", "can", "be", "ravelled", "to", "discrete", "value." ]
def check_space(self, space): return rdw.check_space(space)
['def', 'check_space(self,', 'space):', 'return', 'rdw.check_space(space)']
405,820
intel/neural-compressor
keras.py
KerasAdaptor.inspect_tensor
inspect_tensor
The function is used by tune strategy class for dumping tensor info.
[ "The", "function", "is", "used", "by", "tune", "strategy", "class", "for", "dumping", "tensor", "info." ]
def inspect_tensor(self, model, dataloader, op_list=[], iteration_list=[], inspect_type='activation', save_to_disk=False): assert inspect_type in ['weight', 'activation', 'all'], 'Inspect type only support weight, activation or all' from keras import backend as K tensor_out = {} inp = model.input ou...
['def', 'inspect_tensor(self,', 'model,', 'dataloader,', 'op_list=[],', 'iteration_list=[],', "inspect_type='activation',", 'save_to_disk=False):', 'assert', 'inspect_type', 'in', "['weight',", "'activation',", "'all'],", "'Inspect", 'type', 'only', 'support', 'weight,', 'activation', 'or', "all'", 'from', 'keras', 'im...
737,314
43Carrig/recurrent_neural_networks_practice
datastructures.py
MIMEAccept.accept_xhtml
accept_xhtml
True if this object accepts XHTML.
[ "True", "if", "this", "object", "accepts", "XHTML." ]
def accept_xhtml(self): return 'application/xhtml+xml' in self or 'application/xml' in self
['def', 'accept_xhtml(self):', 'return', "'application/xhtml+xml'", 'in', 'self', 'or', "'application/xml'", 'in', 'self']
339,953
DLR-RM/stable-baselines3
dummy_vec_env.py
DummyVecEnv.set_attr
set_attr
Set attribute inside vectorized environments (see base class).
[ "Set", "attribute", "inside", "vectorized", "environments", "(see", "base", "class)." ]
def set_attr(self, attr_name: str, value: Any, indices: VecEnvIndices=None) -> None: target_envs = self._get_target_envs(indices) for env_i in target_envs: setattr(env_i, attr_name, value)
['def', 'set_attr(self,', 'attr_name:', 'str,', 'value:', 'Any,', 'indices:', 'VecEnvIndices=None)', '->', 'None:', 'target_envs', '=', 'self._get_target_envs(indices)', 'for', 'env_i', 'in', 'target_envs:', 'setattr(env_i,', 'attr_name,', 'value)']
383,503
microsoft/maro
request_decision.py
get_acc_decision_data
get_acc_decision_data
Get the decision data within a range.
[ "Get", "the", "decision", "data", "within", "a", "range." ]
def get_acc_decision_data(experiment_name: str, episode: str, start_tick: str, end_tick: str) -> json: input_range = get_input_range(start_tick, end_tick) query = f"select {request_column.decision_header.value} from {experiment_name}.full_on_vessels where episode='{episode}'" if input_range != '()': ...
['def', 'get_acc_decision_data(experiment_name:', 'str,', 'episode:', 'str,', 'start_tick:', 'str,', 'end_tick:', 'str)', '->', 'json:', 'input_range', '=', 'get_input_range(start_tick,', 'end_tick)', 'query', '=', 'f"select', '{request_column.decision_header.value}', 'from', '{experiment_name}.full_on_vessels', 'where...
628,307
dbash/zerowaste
logger.py
log_every_n_seconds
log_every_n_seconds
Log no more than once per n seconds.
[ "Log", "no", "more", "than", "once", "per", "n", "seconds." ]
def log_every_n_seconds(lvl, msg, n=1, *, name=None): (caller_module, key) = _find_caller() last_logged = _LOG_TIMER.get(key, None) current_time = time.time() if last_logged is None or current_time - last_logged >= n: logging.getLogger(name or caller_module).log(lvl, msg) _LOG_TIMER[key]...
['def', 'log_every_n_seconds(lvl,', 'msg,', 'n=1,', '*,', 'name=None):', '(caller_module,', 'key)', '=', '_find_caller()', 'last_logged', '=', '_LOG_TIMER.get(key,', 'None)', 'current_time', '=', 'time.time()', 'if', 'last_logged', 'is', 'None', 'or', 'current_time', '-', 'last_logged', '>=', 'n:', 'logging.getLogger(n...
971,583
googleapis/python-aiplatform
uploader_utils.py
request_logger
request_logger
Context manager to log request size and duration.
[ "Context", "manager", "to", "log", "request", "size", "and", "duration." ]
def request_logger(request: tensorboard_service.WriteTensorboardRunDataRequest) -> Generator[None, None, None]: upload_start_time = time.time() request_bytes = request._pb.ByteSize() logger.info('Trying request of %d bytes', request_bytes) yield upload_duration_secs = time.time() - upload_start_time...
['def', 'request_logger(request:', 'tensorboard_service.WriteTensorboardRunDataRequest)', '->', 'Generator[None,', 'None,', 'None]:', 'upload_start_time', '=', 'time.time()', 'request_bytes', '=', 'request._pb.ByteSize()', "logger.info('Trying", 'request', 'of', '%d', "bytes',", 'request_bytes)', 'yield', 'upload_durat...
810,186
asyml/texar
data_iterators.py
FeedableDataIterator.handle
handle
The handle placeholder that can be fed with a dataset handle to fetch data from the dataset.
[ "The", "handle", "placeholder", "that", "can", "be", "fed", "with", "a", "dataset", "handle", "to", "fetch", "data", "from", "the", "dataset." ]
def handle(self): return self._handle
['def', 'handle(self):', 'return', 'self._handle']
924,526
aws/sagemaker-python-sdk
artifact.py
Artifact.delete
delete
Delete the artifact object.
[ "Delete", "the", "artifact", "object." ]
def delete(self, disassociate: bool=False): if disassociate: _disassociate(source_arn=self.artifact_arn, sagemaker_session=self.sagemaker_session) _disassociate(destination_arn=self.artifact_arn, sagemaker_session=self.sagemaker_session) self._invoke_api(self._boto_delete_method, self._boto_dele...
['def', 'delete(self,', 'disassociate:', 'bool=False):', 'if', 'disassociate:', '_disassociate(source_arn=self.artifact_arn,', 'sagemaker_session=self.sagemaker_session)', '_disassociate(destination_arn=self.artifact_arn,', 'sagemaker_session=self.sagemaker_session)', 'self._invoke_api(self._boto_delete_method,', 'self...
830,238
myothida/Supervised-Machine-Learning
test_kdtree.py
KDTreeTest
KDTreeTest
Class decorator to create test cases for KDTree and cKDTree Tests use the class variable ``kdtree_type`` as the tree constructor.
[ "Class", "decorator", "to", "create", "test", "cases", "for", "KDTree", "and", "cKDTree", "Tests", "use", "the", "class", "variable", "``kdtree_type``", "as", "the", "tree", "constructor." ]
def KDTreeTest(kls): if not kls.__name__.startswith('_Test'): raise RuntimeError('Expected a class name starting with _Test') for tree in (KDTree, cKDTree): test_name = kls.__name__[1:] + '_' + tree.__name__ if test_name in globals(): raise RuntimeError('Duplicated test name:...
['def', 'KDTreeTest(kls):', 'if', 'not', "kls.__name__.startswith('_Test'):", 'raise', "RuntimeError('Expected", 'a', 'class', 'name', 'starting', 'with', "_Test')", 'for', 'tree', 'in', '(KDTree,', 'cKDTree):', 'test_name', '=', 'kls.__name__[1:]', '+', "'_'", '+', 'tree.__name__', 'if', 'test_name', 'in', 'globals():...
446,423
cheind/gcsl
utils.py
parse_env_params
parse_env_params
Parses a list of `key=value` strings as a dictionary.
[ "Parses", "a", "list", "of", "`key=value`", "strings", "as", "a", "dictionary." ]
def parse_env_params(user_entries: Sequence[str]) -> Dict[str, Any]: def is_value_convertable(v, convert_type) -> bool: try: convert_type(v) except ValueError: return False return True env_params = {} for user_text in user_entries: components = user_t...
['def', 'parse_env_params(user_entries:', 'Sequence[str])', '->', 'Dict[str,', 'Any]:', 'def', 'is_value_convertable(v,', 'convert_type)', '->', 'bool:', 'try:', 'convert_type(v)', 'except', 'ValueError:', 'return', 'False', 'return', 'True', 'env_params', '=', '{}', 'for', 'user_text', 'in', 'user_entries:', 'componen...
201,993
WHU-ZQH/E2S2
fairseq_lr_scheduler.py
FairseqLRScheduler.state_dict
state_dict
Return the LR scheduler state dict.
[ "Return", "the", "LR", "scheduler", "state", "dict." ]
def state_dict(self): return {'best': self.best}
['def', 'state_dict(self):', 'return', "{'best':", 'self.best}']
556,124
edshkim98/GAGCN
module.py
Mish.forward
forward
Forward pass of the function.
[ "Forward", "pass", "of", "the", "function." ]
def forward(self, input): return mish(input)
['def', 'forward(self,', 'input):', 'return', 'mish(input)']
566,074
datature/portal
folder.py
Folder.get_tree
get_tree
Create a list of filepaths within this folder.
[ "Create", "a", "list", "of", "filepaths", "within", "this", "folder." ]
def get_tree(self): return self._create_tree_(self._name_, self._path_, self._files_, self._folders_)
['def', 'get_tree(self):', 'return', 'self._create_tree_(self._name_,', 'self._path_,', 'self._files_,', 'self._folders_)']
821,001
enlite-ai/maze
parallel_rollout_runner.py
EpisodeRecorder.receive
receive
Receive the statistics from the env and store them.
[ "Receive", "the", "statistics", "from", "the", "env", "and", "store", "them." ]
def receive(self, stat: LogStats) -> None: self.last_stats = stat
['def', 'receive(self,', 'stat:', 'LogStats)', '->', 'None:', 'self.last_stats', '=', 'stat']
646,740
matsu0228/nlp-jp
vi.py
TextObject.sorted
sorted
Return a (start, end) tuple where start <= end.
[ "Return", "a", "(start,", "end)", "tuple", "where", "start", "<=", "end." ]
def sorted(self): if self.start < self.end: return (self.start, self.end) else: return (self.end, self.start)
['def', 'sorted(self):', 'if', 'self.start', '<', 'self.end:', 'return', '(self.start,', 'self.end)', 'else:', 'return', '(self.end,', 'self.start)']
804,500
neardws/Game-Theoretic-Deep-Reinforcement-Learning
environment_local_processing.py
vehicularNetworkEnv.observation_spec
observation_spec
Define and return the observation space.
[ "Define", "and", "return", "the", "observation", "space." ]
def observation_spec(self) -> specs.BoundedArray: if self._occuiped: observation_size = self._config.observation_size if not self._for_mad5pg: observation_size -= 2 observation_shape = (self._config.edge_number, observation_size) if self._flatten_space: observ...
['def', 'observation_spec(self)', '->', 'specs.BoundedArray:', 'if', 'self._occuiped:', 'observation_size', '=', 'self._config.observation_size', 'if', 'not', 'self._for_mad5pg:', 'observation_size', '-=', '2', 'observation_shape', '=', '(self._config.edge_number,', 'observation_size)', 'if', 'self._flatten_space:', 'o...
199,983