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 |
|---|---|---|---|---|---|---|---|---|
shery322/Lunar-Lander-ANN | mask_test.py | MaskTypeTest.test_overlap__invalid_mask_arg | test_overlap__invalid_mask_arg | Ensure overlap handles invalid mask arguments correctly. | [
"Ensure",
"overlap",
"handles",
"invalid",
"mask",
"arguments",
"correctly."
] | def test_overlap__invalid_mask_arg(self):
size = (5, 3)
offset = (0, 0)
mask = pygame.mask.Mask(size)
invalid_mask = pygame.Surface(size)
with self.assertRaises(TypeError):
overlap_pos = mask.overlap(invalid_mask, offset) | ['def', 'test_overlap__invalid_mask_arg(self):', 'size', '=', '(5,', '3)', 'offset', '=', '(0,', '0)', 'mask', '=', 'pygame.mask.Mask(size)', 'invalid_mask', '=', 'pygame.Surface(size)', 'with', 'self.assertRaises(TypeError):', 'overlap_pos', '=', 'mask.overlap(invalid_mask,', 'offset)'] | 619,012 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain_test.py | TestImageMock.test_image_mock_produces_expected_shape | test_image_mock_produces_expected_shape | Test that the image mocking utility produces expected shape output. | [
"Test",
"that",
"the",
"image",
"mocking",
"utility",
"produces",
"expected",
"shape",
"output."
] | def test_image_mock_produces_expected_shape(self):
with TemporaryDirectory() as tmp_dir:
cases = [{'x_dim': 8, 'y_dim': 8, 'num_channels': 3, 'output_path': '/foo', 'write_image': True}]
for (cid, case) in enumerate(cases):
output_path = os.path.join(tmp_dir, 'dummy%s.jpg' % cid)
... | ['def', 'test_image_mock_produces_expected_shape(self):', 'with', 'TemporaryDirectory()', 'as', 'tmp_dir:', 'cases', '=', "[{'x_dim':", '8,', "'y_dim':", '8,', "'num_channels':", '3,', "'output_path':", "'/foo',", "'write_image':", 'True}]', 'for', '(cid,', 'case)', 'in', 'enumerate(cases):', 'output_path', '=', 'os.pa... | 964,826 |
deepmind/dm_control | jaco_hand.py | JacoHand.tool_center_point | tool_center_point | Tool center point for the Jaco hand. | [
"Tool",
"center",
"point",
"for",
"the",
"Jaco",
"hand."
] | def tool_center_point(self):
return self._tool_center_point | ['def', 'tool_center_point(self):', 'return', 'self._tool_center_point'] | 165,013 |
saghul/evergreen | queue.py | Queue.qsize | qsize | Return the approximate size of the queue (not reliable!). | [
"Return",
"the",
"approximate",
"size",
"of",
"the",
"queue",
"(not",
"reliable!)."
] | def qsize(self):
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n | ['def', 'qsize(self):', 'self.mutex.acquire()', 'n', '=', 'self._qsize()', 'self.mutex.release()', 'return', 'n'] | 178,450 |
unixpickle/anyrl-py | test_dists.py | test_nat_softmax_batched | test_nat_softmax_batched | Test that batched gradients from NaturalSoftmax give the same results as single gradients. | [
"Test",
"that",
"batched",
"gradients",
"from",
"NaturalSoftmax",
"give",
"the",
"same",
"results",
"as",
"single",
"gradients."
] | def test_nat_softmax_batched():
with tf.Graph().as_default():
with tf.Session() as sess:
dist = NaturalSoftmax(7)
params = tf.constant(np.random.normal(size=(15, 7)), dtype=tf.float64)
sampled = tf.one_hot([random.randrange(7) for _ in range(15)], 7, dtype=tf.float64)
... | ['def', 'test_nat_softmax_batched():', 'with', 'tf.Graph().as_default():', 'with', 'tf.Session()', 'as', 'sess:', 'dist', '=', 'NaturalSoftmax(7)', 'params', '=', 'tf.constant(np.random.normal(size=(15,', '7)),', 'dtype=tf.float64)', 'sampled', '=', 'tf.one_hot([random.randrange(7)', 'for', '_', 'in', 'range(15)],', '7... | 33,694 |
tensorflow/quantum | pqc_test.py | PQCTest.test_pqc_simple_learn | test_pqc_simple_learn | Test a simple learning scenario using analytic and sample expectation on many backends. | [
"Test",
"a",
"simple",
"learning",
"scenario",
"using",
"analytic",
"and",
"sample",
"expectation",
"on",
"many",
"backends."
] | def test_pqc_simple_learn(self, backend, repetitions):
qubit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('bit'))
quantum_datum = tf.keras.Input(shape=(), dtype=tf.dtypes.string)
mpqc = pqc.PQC(circuit, cirq.Z(qubit), backend=backend, repetitions=repetitions, initializer=t... | ['def', 'test_pqc_simple_learn(self,', 'backend,', 'repetitions):', 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'circuit', '=', 'cirq.Circuit(cirq.X(qubit)', '**', "sympy.Symbol('bit'))", 'quantum_datum', '=', 'tf.keras.Input(shape=(),', 'dtype=tf.dtypes.string)', 'mpqc', '=', 'pqc.PQC(circuit,', 'cirq.Z(qubit),', 'backen... | 835,451 |
greydanus/mr_london | misc.py | Hasher.update | update | Add `v` to the hash, recursively if needed. | [
"Add",
"`v`",
"to",
"the",
"hash,",
"recursively",
"if",
"needed."
] | def update(self, v):
self.md5.update(to_bytes(str(type(v))))
if isinstance(v, string_class):
self.md5.update(to_bytes(v))
elif isinstance(v, bytes):
self.md5.update(v)
elif v is None:
pass
elif isinstance(v, (int, float)):
self.md5.update(to_bytes(str(v)))
elif is... | ['def', 'update(self,', 'v):', 'self.md5.update(to_bytes(str(type(v))))', 'if', 'isinstance(v,', 'string_class):', 'self.md5.update(to_bytes(v))', 'elif', 'isinstance(v,', 'bytes):', 'self.md5.update(v)', 'elif', 'v', 'is', 'None:', 'pass', 'elif', 'isinstance(v,', '(int,', 'float)):', 'self.md5.update(to_bytes(str(v))... | 242,199 |
RyanWangZf/PyTrial | ft_transformer.py | MultiheadAttention.forward | forward | Perform the forward pass. | [
"Perform",
"the",
"forward",
"pass."
] | def forward(self, x_q: Tensor, x_kv: Tensor, key_compression: Optional[nn.Linear], value_compression: Optional[nn.Linear]) -> Tuple[Tensor, Dict[str, Tensor]]:
assert _all_or_none([key_compression, value_compression]), 'If key_compression is (not) None, then value_compression must (not) be None'
(q, k, v) = (se... | ['def', 'forward(self,', 'x_q:', 'Tensor,', 'x_kv:', 'Tensor,', 'key_compression:', 'Optional[nn.Linear],', 'value_compression:', 'Optional[nn.Linear])', '->', 'Tuple[Tensor,', 'Dict[str,', 'Tensor]]:', 'assert', '_all_or_none([key_compression,', 'value_compression]),', "'If", 'key_compression', 'is', '(not)', 'None,',... | 302,363 |
AmirAbaskohi/PEACH | estimator_utils.py | add_scalars_to_summary | add_scalars_to_summary | Creates a host_call function that writes summaries on TPU. | [
"Creates",
"a",
"host_call",
"function",
"that",
"writes",
"summaries",
"on",
"TPU."
] | def add_scalars_to_summary(summary_dir, scalar_tensors_dict):
scalar_tensors_dict = {k: tf.reshape(v, [1]) for (k, v) in scalar_tensors_dict.items()}
def host_call_fn(**kwargs):
writer = contrib_summary.create_file_writer(summary_dir, max_queue=1000)
always_record = contrib_summary.always_recor... | ['def', 'add_scalars_to_summary(summary_dir,', 'scalar_tensors_dict):', 'scalar_tensors_dict', '=', '{k:', 'tf.reshape(v,', '[1])', 'for', '(k,', 'v)', 'in', 'scalar_tensors_dict.items()}', 'def', 'host_call_fn(**kwargs):', 'writer', '=', 'contrib_summary.create_file_writer(summary_dir,', 'max_queue=1000)', 'always_rec... | 765,997 |
LucasAlegre/morl-baselines | diverse_buffer.py | DiverseMemory.sec_distances | sec_distances | Give a set of traces, this method computes each trace's crowding distance. | [
"Give",
"a",
"set",
"of",
"traces,",
"this",
"method",
"computes",
"each",
"trace's",
"crowding",
"distance."
] | def sec_distances(self, traces):
values = [self.get_trace_value(tr) for tr in traces]
if self.crowding_diversity:
distances = crowd_dist(values)
else:
distances = values
return ([(i, d) for (i, d) in enumerate(distances)], values) | ['def', 'sec_distances(self,', 'traces):', 'values', '=', '[self.get_trace_value(tr)', 'for', 'tr', 'in', 'traces]', 'if', 'self.crowding_diversity:', 'distances', '=', 'crowd_dist(values)', 'else:', 'distances', '=', 'values', 'return', '([(i,', 'd)', 'for', '(i,', 'd)', 'in', 'enumerate(distances)],', 'values)'] | 655,788 |
sarnsdev/social-alignment-data-mining | _bvp.py | wrap_functions | wrap_functions | Wrap functions for unified usage in the solver. | [
"Wrap",
"functions",
"for",
"unified",
"usage",
"in",
"the",
"solver."
] | def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
if fun_jac is None:
fun_jac_wrapped = None
if bc_jac is None:
bc_jac_wrapped = None
if k == 0:
def fun_p(x, y, _):
return np.asarray(fun(x, y), dtype)
def bc_wrapped(ya, yb, _):
return ... | ['def', 'wrap_functions(fun,', 'bc,', 'fun_jac,', 'bc_jac,', 'k,', 'a,', 'S,', 'D,', 'dtype):', 'if', 'fun_jac', 'is', 'None:', 'fun_jac_wrapped', '=', 'None', 'if', 'bc_jac', 'is', 'None:', 'bc_jac_wrapped', '=', 'None', 'if', 'k', '==', '0:', 'def', 'fun_p(x,', 'y,', '_):', 'return', 'np.asarray(fun(x,', 'y),', 'dtyp... | 390,647 |
Kvatsx/Artificial-Intelligence-Assignments | backend_wx.py | RendererWx.get_gc | get_gc | Fetch the locally cached gc. | [
"Fetch",
"the",
"locally",
"cached",
"gc."
] | def get_gc(self):
assert self.gc is not None, 'gc must be defined'
return self.gc | ['def', 'get_gc(self):', 'assert', 'self.gc', 'is', 'not', 'None,', "'gc", 'must', 'be', "defined'", 'return', 'self.gc'] | 1,241 |
codekansas/gibberish-decoder | train.py | load_data | load_data | Loads the existing datasets. | [
"Loads",
"the",
"existing",
"datasets."
] | def load_data(efile='embeddings.npy', wfile='words.pkl', word_len=30):
if not os.path.exists(efile) or not os.path.exists(wfile):
raise IOError('You should generate embeddings before training the model using `create_embeddings.py`. Need both files: "%s" and "%s"' % (efile, wfile))
with open(wfile, 'rb')... | ['def', "load_data(efile='embeddings.npy',", "wfile='words.pkl',", 'word_len=30):', 'if', 'not', 'os.path.exists(efile)', 'or', 'not', 'os.path.exists(wfile):', 'raise', "IOError('You", 'should', 'generate', 'embeddings', 'before', 'training', 'the', 'model', 'using', '`create_embeddings.py`.', 'Need', 'both', 'files:'... | 202,418 |
feast-dev/feast | snowflake_source.py | SnowflakeSource.table | table | Returns the table of this snowflake source. | [
"Returns",
"the",
"table",
"of",
"this",
"snowflake",
"source."
] | def table(self):
return self.snowflake_options.table | ['def', 'table(self):', 'return', 'self.snowflake_options.table'] | 544,406 |
AiIsBetter/computer_vision | memory_module.py | SampleDistributeModule.forward_backward | forward_backward | A convenient function that calls both ``forward`` and ``backward``. | [
"A",
"convenient",
"function",
"that",
"calls",
"both",
"``forward``",
"and",
"``backward``."
] | def forward_backward(self, data_batch):
(total_feature, total_label) = self.forward(data_batch, is_train=True)
self.backward_all(total_feature, total_label) | ['def', 'forward_backward(self,', 'data_batch):', '(total_feature,', 'total_label)', '=', 'self.forward(data_batch,', 'is_train=True)', 'self.backward_all(total_feature,', 'total_label)'] | 500,448 |
muhanzhang/D-VAE | test_elemwise.py | T_prod_without_zeros_dtype.test_prod_without_zeros_custom_dtype | test_prod_without_zeros_custom_dtype | Test ability to provide your own output dtype for a ProdWithoutZeros(). | [
"Test",
"ability",
"to",
"provide",
"your",
"own",
"output",
"dtype",
"for",
"a",
"ProdWithoutZeros()."
] | def test_prod_without_zeros_custom_dtype(self):
axes = [None, 0, 1, [], [0], [1], [0, 1]]
idx = 0
for input_dtype in imap(str, theano.scalar.all_types):
x = tensor.matrix(dtype=input_dtype)
for output_dtype in imap(str, theano.scalar.all_types):
axis = axes[idx % len(axes)]
... | ['def', 'test_prod_without_zeros_custom_dtype(self):', 'axes', '=', '[None,', '0,', '1,', '[],', '[0],', '[1],', '[0,', '1]]', 'idx', '=', '0', 'for', 'input_dtype', 'in', 'imap(str,', 'theano.scalar.all_types):', 'x', '=', 'tensor.matrix(dtype=input_dtype)', 'for', 'output_dtype', 'in', 'imap(str,', 'theano.scalar.all... | 525,865 |
paulorauber/rl | transforms.py | TransformedEnv.set_seed | set_seed | Set the seeds of the environment. | [
"Set",
"the",
"seeds",
"of",
"the",
"environment."
] | def set_seed(self, seed: Optional[int]=None, static_seed: bool=False) -> Optional[int]:
return self.base_env.set_seed(seed, static_seed=static_seed) | ['def', 'set_seed(self,', 'seed:', 'Optional[int]=None,', 'static_seed:', 'bool=False)', '->', 'Optional[int]:', 'return', 'self.base_env.set_seed(seed,', 'static_seed=static_seed)'] | 859,140 |
enlite-ai/maze | custom_model_composer.py | CustomModelComposer.critic | critic | Return the critic networks. | [
"Return",
"the",
"critic",
"networks."
] | def critic(self) -> Optional[Union[TorchStateCritic, TorchStateActionCritic]]:
if self._critics_composer is None:
return None
return self._critics_composer.critic | ['def', 'critic(self)', '->', 'Optional[Union[TorchStateCritic,', 'TorchStateActionCritic]]:', 'if', 'self._critics_composer', 'is', 'None:', 'return', 'None', 'return', 'self._critics_composer.critic'] | 647,109 |
schulter/crbm | testcrbm.py | TestCRBM.controlTopDownActivity | controlTopDownActivity | Top down activity control implementation. | [
"Top",
"down",
"activity",
"control",
"implementation."
] | def controlTopDownActivity(self, w, c, data, datap=None):
seqlen = data.shape[3] + w.shape[3] - 1
nseq = data.shape[0]
nmot = w.shape[0]
mlen = w.shape[3]
output_control = np.zeros((nseq, 1, 4, seqlen))
output_control += c[np.newaxis, 0, :, np.newaxis]
for seq in range(nseq):
for pos... | ['def', 'controlTopDownActivity(self,', 'w,', 'c,', 'data,', 'datap=None):', 'seqlen', '=', 'data.shape[3]', '+', 'w.shape[3]', '-', '1', 'nseq', '=', 'data.shape[0]', 'nmot', '=', 'w.shape[0]', 'mlen', '=', 'w.shape[3]', 'output_control', '=', 'np.zeros((nseq,', '1,', '4,', 'seqlen))', 'output_control', '+=', 'c[np.ne... | 138,460 |
Kvatsx/Artificial-Intelligence-Assignments | exposition.py | instance_ip_grouping_key | instance_ip_grouping_key | Grouping key with instance set to the IP Address of this host. | [
"Grouping",
"key",
"with",
"instance",
"set",
"to",
"the",
"IP",
"Address",
"of",
"this",
"host."
] | def instance_ip_grouping_key():
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s:
s.connect(('localhost', 0))
return {'instance': s.getsockname()[0]} | ['def', 'instance_ip_grouping_key():', 'with', 'closing(socket.socket(socket.AF_INET,', 'socket.SOCK_DGRAM))', 'as', 's:', "s.connect(('localhost',", '0))', 'return', "{'instance':", 's.getsockname()[0]}'] | 75,534 |
myothida/Supervised-Machine-Learning | test_expm_multiply.py | test_expm_multiply_dtype | test_expm_multiply_dtype | Make sure `expm_multiply` handles all numerical dtypes correctly. | [
"Make",
"sure",
"`expm_multiply`",
"handles",
"all",
"numerical",
"dtypes",
"correctly."
] | def test_expm_multiply_dtype(dtype_a, dtype_b, b_is_matrix):
assert_allclose_ = partial(assert_allclose, rtol=0.0012, atol=1e-05) if {dtype_a, dtype_b} & IMPRECISE else assert_allclose
rng = np.random.default_rng(1234)
n = 7
b_shape = (n, 3) if b_is_matrix else (n,)
if dtype_a in REAL_DTYPES:
... | ['def', 'test_expm_multiply_dtype(dtype_a,', 'dtype_b,', 'b_is_matrix):', 'assert_allclose_', '=', 'partial(assert_allclose,', 'rtol=0.0012,', 'atol=1e-05)', 'if', '{dtype_a,', 'dtype_b}', '&', 'IMPRECISE', 'else', 'assert_allclose', 'rng', '=', 'np.random.default_rng(1234)', 'n', '=', '7', 'b_shape', '=', '(n,', '3)',... | 446,366 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | check.py | Gt | Gt | Raises an error if |lhs| is not greater than |rhs|. | [
"Raises",
"an",
"error",
"if",
"|lhs|",
"is",
"not",
"greater",
"than",
"|rhs|."
] | def Gt(lhs, rhs, message='', error=ValueError):
if lhs <= rhs:
raise error('Expected (%s) > (%s): %s' % (lhs, rhs, message)) | ['def', 'Gt(lhs,', 'rhs,', "message='',", 'error=ValueError):', 'if', 'lhs', '<=', 'rhs:', 'raise', "error('Expected", '(%s)', '>', '(%s):', "%s'", '%', '(lhs,', 'rhs,', 'message))'] | 111,831 |
chainer/chainer | timer.py | TimerHook.print_report | print_report | Prints a summary report of time profiling in functions. | [
"Prints",
"a",
"summary",
"report",
"of",
"time",
"profiling",
"in",
"functions."
] | def print_report(self, unit='auto', file=sys.stdout):
entries = [['FunctionName', 'ElapsedTime', 'Occurrence']]
auto_foreach = unit == 'auto_foreach'
if unit == 'auto':
max_time = max((record['elapsed_time'] for record in self.summary().values()))
(factor, unit) = self._choose_unit(max_time)... | ['def', 'print_report(self,', "unit='auto',", 'file=sys.stdout):', 'entries', '=', "[['FunctionName',", "'ElapsedTime',", "'Occurrence']]", 'auto_foreach', '=', 'unit', '==', "'auto_foreach'", 'if', 'unit', '==', "'auto':", 'max_time', '=', "max((record['elapsed_time']", 'for', 'record', 'in', 'self.summary().values())... | 477,399 |
myothida/Supervised-Machine-Learning | ast.py | LanguageStatement.build | build | Call the builder object's ``set_language`` callback. | [
"Call",
"the",
"builder",
"object's",
"``set_language``",
"callback."
] | def build(self, builder):
builder.set_language(location=self.location, language=self.language, include_default=self.include_default, required=self.required) | ['def', 'build(self,', 'builder):', 'builder.set_language(location=self.location,', 'language=self.language,', 'include_default=self.include_default,', 'required=self.required)'] | 360,862 |
ugr-sail/sinergym | wrappers.py | MultiObsWrapper.step | step | Performs the action in the new environment. | [
"Performs",
"the",
"action",
"in",
"the",
"new",
"environment."
] | def step(self, action: Union[int, np.ndarray]) -> Tuple[np.ndarray, float, bool, bool, Dict[str, Any]]:
(observation, reward, terminated, truncated, info) = self.env.step(action)
self.history.append(observation)
return (self._get_obs(), reward, terminated, truncated, info) | ['def', 'step(self,', 'action:', 'Union[int,', 'np.ndarray])', '->', 'Tuple[np.ndarray,', 'float,', 'bool,', 'bool,', 'Dict[str,', 'Any]]:', '(observation,', 'reward,', 'terminated,', 'truncated,', 'info)', '=', 'self.env.step(action)', 'self.history.append(observation)', 'return', '(self._get_obs(),', 'reward,', 'term... | 884,445 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model_test.py | ModelTest.testSingleTower_WithoutVariable | testSingleTower_WithoutVariable | Checks model will raise error when there is no trainable variable. | [
"Checks",
"model",
"will",
"raise",
"error",
"when",
"there",
"is",
"no",
"trainable",
"variable."
] | def testSingleTower_WithoutVariable(self):
with tf.Graph().as_default():
test_model = self.MockModel(self.hparams)
feature = {'labels': tf.one_hot([2], 3), 'num_targets': 1}
with self.assertRaises(ValueError):
test_model._single_tower(0, feature) | ['def', 'testSingleTower_WithoutVariable(self):', 'with', 'tf.Graph().as_default():', 'test_model', '=', 'self.MockModel(self.hparams)', 'feature', '=', "{'labels':", 'tf.one_hot([2],', '3),', "'num_targets':", '1}', 'with', 'self.assertRaises(ValueError):', 'test_model._single_tower(0,', 'feature)'] | 47,038 |
gregdurrett/nlp-qa-finalproj | main.py | train | train | Trains the model for a single epoch using the training dataset. | [
"Trains",
"the",
"model",
"for",
"a",
"single",
"epoch",
"using",
"the",
"training",
"dataset."
] | def train(args, epoch, model, dataset):
model.train()
train_loss = 0.0
train_steps = 0
optimizer = optim.Adam(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
train_dataloader = tqdm(dataset.get_batch(shuffle_examples=args.shuffle_examples), **_TQDM_OPTIONS)
for batch i... | ['def', 'train(args,', 'epoch,', 'model,', 'dataset):', 'model.train()', 'train_loss', '=', '0.0', 'train_steps', '=', '0', 'optimizer', '=', 'optim.Adam(model.parameters(),', 'lr=args.learning_rate,', 'weight_decay=args.weight_decay)', 'train_dataloader', '=', 'tqdm(dataset.get_batch(shuffle_examples=args.shuffle_exam... | 731,122 |
sarnsdev/social-alignment-data-mining | test_real_transforms.py | dct_2d_ref | dct_2d_ref | Calculate reference values for testing dct2. | [
"Calculate",
"reference",
"values",
"for",
"testing",
"dct2."
] | def dct_2d_ref(x, **kwargs):
x = np.array(x, copy=True)
for row in range(x.shape[0]):
x[row, :] = dct(x[row, :], **kwargs)
for col in range(x.shape[1]):
x[:, col] = dct(x[:, col], **kwargs)
return x | ['def', 'dct_2d_ref(x,', '**kwargs):', 'x', '=', 'np.array(x,', 'copy=True)', 'for', 'row', 'in', 'range(x.shape[0]):', 'x[row,', ':]', '=', 'dct(x[row,', ':],', '**kwargs)', 'for', 'col', 'in', 'range(x.shape[1]):', 'x[:,', 'col]', '=', 'dct(x[:,', 'col],', '**kwargs)', 'return', 'x'] | 390,631 |
devashish-patel/webcam-motion-detector | traitlets.py | HasTraits.has_trait | has_trait | Returns True if the object has a trait with the specified name. | [
"Returns",
"True",
"if",
"the",
"object",
"has",
"a",
"trait",
"with",
"the",
"specified",
"name."
] | def has_trait(self, name):
return isinstance(getattr(self.__class__, name, None), TraitType) | ['def', 'has_trait(self,', 'name):', 'return', 'isinstance(getattr(self.__class__,', 'name,', 'None),', 'TraitType)'] | 985,280 |
matsu0228/nlp-jp | spines.py | Spine.set_bounds | set_bounds | Set the bounds of the spine. | [
"Set",
"the",
"bounds",
"of",
"the",
"spine."
] | def set_bounds(self, low, high):
if self.spine_type == 'circle':
raise ValueError('set_bounds() method incompatible with circular spines')
self._bounds = (low, high)
self.stale = True | ['def', 'set_bounds(self,', 'low,', 'high):', 'if', 'self.spine_type', '==', "'circle':", 'raise', "ValueError('set_bounds()", 'method', 'incompatible', 'with', 'circular', "spines')", 'self._bounds', '=', '(low,', 'high)', 'self.stale', '=', 'True'] | 789,208 |
matsu0228/nlp-jp | containers.py | WindowRenderInfo.center_visible_line | center_visible_line | Like `first_visible_line`, but for the center visible line. | [
"Like",
"`first_visible_line`,",
"but",
"for",
"the",
"center",
"visible",
"line."
] | def center_visible_line(self, before_scroll_offset=False, after_scroll_offset=False):
return self.first_visible_line(after_scroll_offset) + (self.last_visible_line(before_scroll_offset) - self.first_visible_line(after_scroll_offset)) // 2 | ['def', 'center_visible_line(self,', 'before_scroll_offset=False,', 'after_scroll_offset=False):', 'return', 'self.first_visible_line(after_scroll_offset)', '+', '(self.last_visible_line(before_scroll_offset)', '-', 'self.first_visible_line(after_scroll_offset))', '//', '2'] | 804,518 |
intel/neural-compressor | patterns.py | Pattern.get_pattern_lock_masks | get_pattern_lock_masks | Obtain masks from original weight map, by masking where weights' are zero. | [
"Obtain",
"masks",
"from",
"original",
"weight",
"map,",
"by",
"masking",
"where",
"weights'",
"are",
"zero."
] | def get_pattern_lock_masks(self, modules):
pattern_lock_masks = {}
for key in modules.keys():
weight = modules[key].weight
shape = weight.shape
mask = torch.ones(shape)
mask[weight == 0] = 0.0
pattern_lock_masks[key] = mask.to(weight.device)
return pattern_lock_masks | ['def', 'get_pattern_lock_masks(self,', 'modules):', 'pattern_lock_masks', '=', '{}', 'for', 'key', 'in', 'modules.keys():', 'weight', '=', 'modules[key].weight', 'shape', '=', 'weight.shape', 'mask', '=', 'torch.ones(shape)', 'mask[weight', '==', '0]', '=', '0.0', 'pattern_lock_masks[key]', '=', 'mask.to(weight.device... | 738,665 |
EducationalTestingService/skll | test_regression.py | TestRegression.test_learner_api_rescaling_classifier | test_learner_api_rescaling_classifier | Check that rescaling fails for classifiers. | [
"Check",
"that",
"rescaling",
"fails",
"for",
"classifiers."
] | def test_learner_api_rescaling_classifier(self):
with self.assertRaises(ValueError):
_ = rescaled(LogisticRegression) | ['def', 'test_learner_api_rescaling_classifier(self):', 'with', 'self.assertRaises(ValueError):', '_', '=', 'rescaled(LogisticRegression)'] | 885,239 |
ryu-ed/SpaceInvaders_Ros | statemachine.py | StateMachine.abs_line_number | abs_line_number | Return line number of current line (counting from 1). | [
"Return",
"line",
"number",
"of",
"current",
"line",
"(counting",
"from",
"1)."
] | def abs_line_number(self):
return self.line_offset + self.input_offset + 1 | ['def', 'abs_line_number(self):', 'return', 'self.line_offset', '+', 'self.input_offset', '+', '1'] | 394,811 |
speedinghzl/DSRG | pylayers.py | AnnotationLayerCOCO.preprocess | preprocess | preprocess() emulate the pre-processing occuring in the vgg16 caffe prototxt. | [
"preprocess()",
"emulate",
"the",
"pre-processing",
"occuring",
"in",
"the",
"vgg16",
"caffe",
"prototxt."
] | def preprocess(self, image, label):
image = np.array(image)
image = zoom(image.astype('float32'), (self.new_h / float(image.shape[0]), self.new_w / float(image.shape[1]), 1.0), order=1)
image = image[:, :, [2, 1, 0]]
image = image - self.mean
image = image.transpose([2, 0, 1])
(h, w) = label.sha... | ['def', 'preprocess(self,', 'image,', 'label):', 'image', '=', 'np.array(image)', 'image', '=', "zoom(image.astype('float32'),", '(self.new_h', '/', 'float(image.shape[0]),', 'self.new_w', '/', 'float(image.shape[1]),', '1.0),', 'order=1)', 'image', '=', 'image[:,', ':,', '[2,', '1,', '0]]', 'image', '=', 'image', '-',... | 554,587 |
ifwe/digsby | simplemenu.py | SimpleMenuSpine.CalcSize | CalcSize | Calculates the size of the menu. | [
"Calculates",
"the",
"size",
"of",
"the",
"menu."
] | def CalcSize(self):
self.CalcItemHeight()
if self.Parent.staticwidth:
width = self.Parent.width
else:
self.CalcItemWidth()
width = self.calcedwidth
if not self.Parent.maxheight or self.ItemCount < self.Parent.maxheight:
height = self.itemheight * self.ItemCount
else:
... | ['def', 'CalcSize(self):', 'self.CalcItemHeight()', 'if', 'self.Parent.staticwidth:', 'width', '=', 'self.Parent.width', 'else:', 'self.CalcItemWidth()', 'width', '=', 'self.calcedwidth', 'if', 'not', 'self.Parent.maxheight', 'or', 'self.ItemCount', '<', 'self.Parent.maxheight:', 'height', '=', 'self.itemheight', '*', ... | 185,593 |
myothida/Supervised-Machine-Learning | test_colors.py | test_colormap_return_types | test_colormap_return_types | Make sure that tuples are returned for scalar input and that the proper shapes are returned for ndarrays. | [
"Make",
"sure",
"that",
"tuples",
"are",
"returned",
"for",
"scalar",
"input",
"and",
"that",
"the",
"proper",
"shapes",
"are",
"returned",
"for",
"ndarrays."
] | def test_colormap_return_types():
cmap = mpl.colormaps['plasma']
assert isinstance(cmap(0.5), tuple)
assert len(cmap(0.5)) == 4
x = np.ones(4)
assert cmap(x).shape == x.shape + (4,)
x2d = np.zeros((2, 2))
assert cmap(x2d).shape == x2d.shape + (4,) | ['def', 'test_colormap_return_types():', 'cmap', '=', "mpl.colormaps['plasma']", 'assert', 'isinstance(cmap(0.5),', 'tuple)', 'assert', 'len(cmap(0.5))', '==', '4', 'x', '=', 'np.ones(4)', 'assert', 'cmap(x).shape', '==', 'x.shape', '+', '(4,)', 'x2d', '=', 'np.zeros((2,', '2))', 'assert', 'cmap(x2d).shape', '==', 'x2d... | 362,821 |
SonyCSLParis/cae-invar | utils.py | chroma_to_tonnetz | chroma_to_tonnetz | Transforms chromagram to Tonnetz (Harte, Sandler, 2006). | [
"Transforms",
"chromagram",
"to",
"Tonnetz",
"(Harte,",
"Sandler,",
"2006)."
] | def chroma_to_tonnetz(C):
N = C.shape[0]
T = np.zeros((N, 6))
r1 = 1
r2 = 1
r3 = 0.5
phi = np.zeros((6, 12))
for i in range(6):
for j in range(12):
if i % 2 == 0:
fun = np.sin
else:
fun = np.cos
if i < 2:
... | ['def', 'chroma_to_tonnetz(C):', 'N', '=', 'C.shape[0]', 'T', '=', 'np.zeros((N,', '6))', 'r1', '=', '1', 'r2', '=', '1', 'r3', '=', '0.5', 'phi', '=', 'np.zeros((6,', '12))', 'for', 'i', 'in', 'range(6):', 'for', 'j', 'in', 'range(12):', 'if', 'i', '%', '2', '==', '0:', 'fun', '=', 'np.sin', 'else:', 'fun', '=', 'np.c... | 410,853 |
zhang614/MicroGrid | test_kdeoth.py | test_kde_integer_input | test_kde_integer_input | Regression test for #1181. | [
"Regression",
"test",
"for",
"#1181."
] | def test_kde_integer_input():
x1 = np.arange(5)
kde = stats.gaussian_kde(x1)
y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869, 0.13480721]
assert_array_almost_equal(kde(x1), y_expected, decimal=6) | ['def', 'test_kde_integer_input():', 'x1', '=', 'np.arange(5)', 'kde', '=', 'stats.gaussian_kde(x1)', 'y_expected', '=', '[0.13480721,', '0.18222869,', '0.19514935,', '0.18222869,', '0.13480721]', 'assert_array_almost_equal(kde(x1),', 'y_expected,', 'decimal=6)'] | 669,926 |
Farama-Foundation/Gymnasium | test_import_wrappers.py | test_import_wrappers | test_import_wrappers | Test that all wrappers can be imported. | [
"Test",
"that",
"all",
"wrappers",
"can",
"be",
"imported."
] | def test_import_wrappers():
with pytest.raises(wrappers.DeprecatedWrapper, match=re.escape("'NormalizeRewardV0' is now deprecated")):
getattr(wrappers, 'NormalizeRewardV0')
with pytest.raises(AttributeError, match=re.escape("module 'gymnasium.experimental.wrappers' has no attribute 'ClipRewardVT', did y... | ['def', 'test_import_wrappers():', 'with', 'pytest.raises(wrappers.DeprecatedWrapper,', 'match=re.escape("\'NormalizeRewardV0\'', 'is', 'now', 'deprecated")):', 'getattr(wrappers,', "'NormalizeRewardV0')", 'with', 'pytest.raises(AttributeError,', 'match=re.escape("module', "'gymnasium.experimental.wrappers'", 'has', 'n... | 573,575 |
StepNeverStop/RLs | torch_utils.py | gaussian_entropy | gaussian_entropy | Calculating the entropy of a Gaussian distribution. | [
"Calculating",
"the",
"entropy",
"of",
"a",
"Gaussian",
"distribution."
] | def gaussian_entropy(log_std):
return (0.5 * (1 + (2 * np.pi * log_std.exp() ** 2 + th.finfo().eps).log())).mean() | ['def', 'gaussian_entropy(log_std):', 'return', '(0.5', '*', '(1', '+', '(2', '*', 'np.pi', '*', 'log_std.exp()', '**', '2', '+', 'th.finfo().eps).log())).mean()'] | 334,875 |
yinyunie/ScenePriors | sample_points_from_meshes.py | sample_points_from_meshes | sample_points_from_meshes | Convert a batch of meshes to a batch of pointclouds by uniformly sampling points on the surface of the mesh with probability proportional to the face area. | [
"Convert",
"a",
"batch",
"of",
"meshes",
"to",
"a",
"batch",
"of",
"pointclouds",
"by",
"uniformly",
"sampling",
"points",
"on",
"the",
"surface",
"of",
"the",
"mesh",
"with",
"probability",
"proportional",
"to",
"the",
"face",
"area."
] | def sample_points_from_meshes(meshes, num_samples: int=10000, return_normals: bool=False, return_textures: bool=False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
if meshes.isempty():
raise ValueError('Meshes are empty.')
verts = meshes.ver... | ['def', 'sample_points_from_meshes(meshes,', 'num_samples:', 'int=10000,', 'return_normals:', 'bool=False,', 'return_textures:', 'bool=False)', '->', 'Union[torch.Tensor,', 'Tuple[torch.Tensor,', 'torch.Tensor],', 'Tuple[torch.Tensor,', 'torch.Tensor,', 'torch.Tensor]]:', 'if', 'meshes.isempty():', 'raise', "ValueError... | 329,790 |
OpenMDAO/OpenMDAO-Framework | test_query_hdf5.py | create_files | create_files | Create/update test data files. | [
"Create/update",
"test",
"data",
"files."
] | def create_files():
prob = set_as_top(SellarMDF())
prob.recorders = [HDF5CaseRecorder('sellar_hdf5.new')]
prob.run() | ['def', 'create_files():', 'prob', '=', 'set_as_top(SellarMDF())', 'prob.recorders', '=', "[HDF5CaseRecorder('sellar_hdf5.new')]", 'prob.run()'] | 275,436 |
tensorly/quantum | noisy_pqc_test.py | NoisyPQCTest.test_noisy_pqc_initializer | test_noisy_pqc_initializer | Test action of initializer. | [
"Test",
"action",
"of",
"initializer."
] | def test_noisy_pqc_initializer(self):
(a, b, c) = sympy.symbols('a b c')
qubit = cirq.GridQubit(0, 0)
three_parameters = cirq.Circuit([cirq.X(qubit) ** a, cirq.Y(qubit) ** b, cirq.Z(qubit) ** c])
mpqc_zeros = noisy_pqc.NoisyPQC(three_parameters, cirq.Z(qubit), repetitions=100, sample_based=False, initia... | ['def', 'test_noisy_pqc_initializer(self):', '(a,', 'b,', 'c)', '=', "sympy.symbols('a", 'b', "c')", 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'three_parameters', '=', 'cirq.Circuit([cirq.X(qubit)', '**', 'a,', 'cirq.Y(qubit)', '**', 'b,', 'cirq.Z(qubit)', '**', 'c])', 'mpqc_zeros', '=', 'noisy_pqc.NoisyPQC(three_parame... | 835,410 |
lebrice/Sequoia | ewc_method_test.py | TestEWCMethod.test_raises_warning_when_applied_to_non_cl_setting | test_raises_warning_when_applied_to_non_cl_setting | When applied onto a non-CL setting like IID or Multi-Task SL (or RL), the EWCMethod should raise a warning, and disable the auxiliary task. | [
"When",
"applied",
"onto",
"a",
"non-CL",
"setting",
"like",
"IID",
"or",
"Multi-Task",
"SL",
"(or",
"RL),",
"the",
"EWCMethod",
"should",
"raise",
"a",
"warning,",
"and",
"disable",
"the",
"auxiliary",
"task."
] | def test_raises_warning_when_applied_to_non_cl_setting(self, non_cl_setting_fn):
method = EwcMethod()
setting = non_cl_setting_fn()
with pytest.warns(RuntimeWarning):
method.configure(setting) | ['def', 'test_raises_warning_when_applied_to_non_cl_setting(self,', 'non_cl_setting_fn):', 'method', '=', 'EwcMethod()', 'setting', '=', 'non_cl_setting_fn()', 'with', 'pytest.warns(RuntimeWarning):', 'method.configure(setting)'] | 344,233 |
enuguru/artificial_intelligence_and_machine_ | reading.py | IndexReader.lexicon | lexicon | Yields all bytestrings in the given field. | [
"Yields",
"all",
"bytestrings",
"in",
"the",
"given",
"field."
] | def lexicon(self, fieldname):
for (fn, btext) in self.terms_from(fieldname, emptybytes):
if fn != fieldname:
return
yield btext | ['def', 'lexicon(self,', 'fieldname):', 'for', '(fn,', 'btext)', 'in', 'self.terms_from(fieldname,', 'emptybytes):', 'if', 'fn', '!=', 'fieldname:', 'return', 'yield', 'btext'] | 162,151 |
43Carrig/recurrent_neural_networks_practice | composable_model.py | _ComposableModel.build_model | build_model | Builds the model that can calculate the logits. | [
"Builds",
"the",
"model",
"that",
"can",
"calculate",
"the",
"logits."
] | def build_model(self, features, feature_columns, is_training):
raise NotImplementedError | ['def', 'build_model(self,', 'features,', 'feature_columns,', 'is_training):', 'raise', 'NotImplementedError'] | 313,583 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | polar.py | PolarAxes.get_thetamin | get_thetamin | Get the minimum theta limit in degrees. | [
"Get",
"the",
"minimum",
"theta",
"limit",
"in",
"degrees."
] | def get_thetamin(self):
return np.rad2deg(self.viewLim.xmin) | ['def', 'get_thetamin(self):', 'return', 'np.rad2deg(self.viewLim.xmin)'] | 257,762 |
lojzezust/WaSR-T | utils.py | bool_arg | bool_arg | Generalized bool argument for argparse. | [
"Generalized",
"bool",
"argument",
"for",
"argparse."
] | def bool_arg(v):
if isinstance(v, bool):
return v
if str(v).lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif str(v).lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.') | ['def', 'bool_arg(v):', 'if', 'isinstance(v,', 'bool):', 'return', 'v', 'if', 'str(v).lower()', 'in', "('yes',", "'true',", "'t',", "'y',", "'1'):", 'return', 'True', 'elif', 'str(v).lower()', 'in', "('no',", "'false',", "'f',", "'n',", "'0'):", 'return', 'False', 'else:', 'raise', "argparse.ArgumentTypeError('Boolean"... | 942,332 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | base.py | PreprocessorTestsBase.build_resources | build_resources | Build an empty resources dictionary. | [
"Build",
"an",
"empty",
"resources",
"dictionary."
] | def build_resources(self):
res = ResourcesDict()
res['metadata'] = ResourcesDict()
return res | ['def', 'build_resources(self):', 'res', '=', 'ResourcesDict()', "res['metadata']", '=', 'ResourcesDict()', 'return', 'res'] | 451,767 |
weimin17/Object-Detection_HelmetDetection | dataset_loader.py | Cityscapes.load_intrinsics | load_intrinsics | Read intrinsics data for frame. | [
"Read",
"intrinsics",
"data",
"for",
"frame."
] | def load_intrinsics(self, frame_id, split):
(city, seq, _, _) = frame_id.split('_')
camera_file = os.path.join(self.dataset_dir, 'camera', split, city, city + '_' + seq + '_*_camera.json')
camera_file = glob.glob(camera_file)[0]
with open(camera_file, 'r') as f:
camera = json.load(f)
fx = ca... | ['def', 'load_intrinsics(self,', 'frame_id,', 'split):', '(city,', 'seq,', '_,', '_)', '=', "frame_id.split('_')", 'camera_file', '=', 'os.path.join(self.dataset_dir,', "'camera',", 'split,', 'city,', 'city', '+', "'_'", '+', 'seq', '+', "'_*_camera.json')", 'camera_file', '=', 'glob.glob(camera_file)[0]', 'with', 'ope... | 754,048 |
TARGET-SIDE-DATA-AUG/TSDASG | fairseq_encoder.py | FairseqEncoder.set_num_updates | set_num_updates | State from trainer to pass along to model at every update. | [
"State",
"from",
"trainer",
"to",
"pass",
"along",
"to",
"model",
"at",
"every",
"update."
] | def set_num_updates(self, num_updates):
def _apply(m):
if hasattr(m, 'set_num_updates') and m != self:
m.set_num_updates(num_updates)
self.apply(_apply) | ['def', 'set_num_updates(self,', 'num_updates):', 'def', '_apply(m):', 'if', 'hasattr(m,', "'set_num_updates')", 'and', 'm', '!=', 'self:', 'm.set_num_updates(num_updates)', 'self.apply(_apply)'] | 952,084 |
lebrice/Sequoia | setting.py | IncrementalSLSetting.val_dataloader | val_dataloader | Returns a DataLoader for the validation dataset of the current task. | [
"Returns",
"a",
"DataLoader",
"for",
"the",
"validation",
"dataset",
"of",
"the",
"current",
"task."
] | def val_dataloader(self, batch_size: int=None, num_workers: int=None) -> PassiveEnvironment:
val_env = super().val_dataloader(batch_size=batch_size, num_workers=num_workers)
return self.val_env | ['def', 'val_dataloader(self,', 'batch_size:', 'int=None,', 'num_workers:', 'int=None)', '->', 'PassiveEnvironment:', 'val_env', '=', 'super().val_dataloader(batch_size=batch_size,', 'num_workers=num_workers)', 'return', 'self.val_env'] | 349,683 |
ancasag/ensembleObjectDetection | keras_version.py | assert_keras_version | assert_keras_version | Assert that the Keras version is up to date. | [
"Assert",
"that",
"the",
"Keras",
"version",
"is",
"up",
"to",
"date."
] | def assert_keras_version():
detected = keras.__version__
required = '.'.join(map(str, minimum_keras_version))
assert keras_version() >= minimum_keras_version, 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) | ['def', 'assert_keras_version():', 'detected', '=', 'keras.__version__', 'required', '=', "'.'.join(map(str,", 'minimum_keras_version))', 'assert', 'keras_version()', '>=', 'minimum_keras_version,', "'You", 'are', 'using', 'keras', 'version', '{}.', 'The', 'minimum', 'required', 'version', 'is', "{}.'.format(detected,"... | 562,048 |
open-mmlab/mmtracking | sot_train_dataset.py | SOTTrainDataset.prepare_results | prepare_results | Get training data and annotations. | [
"Get",
"training",
"data",
"and",
"annotations."
] | def prepare_results(self, img_id, instance_id, is_positive_pair):
img_info = self.coco.load_imgs([img_id])[0]
img_info['filename'] = img_info['file_name']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
ann_infos = self.coco.load_anns(ann_ids)
ann = self._parse_ann_info(instance_id, ann_infos)
... | ['def', 'prepare_results(self,', 'img_id,', 'instance_id,', 'is_positive_pair):', 'img_info', '=', 'self.coco.load_imgs([img_id])[0]', "img_info['filename']", '=', "img_info['file_name']", 'ann_ids', '=', 'self.coco.get_ann_ids(img_ids=[img_id])', 'ann_infos', '=', 'self.coco.load_anns(ann_ids)', 'ann', '=', 'self._par... | 625,760 |
zackmcnulty/CSE_446-Machine_Learning | _pylab_helpers.py | Gcf.get_num_fig_managers | get_num_fig_managers | Return the number of figures being managed. | [
"Return",
"the",
"number",
"of",
"figures",
"being",
"managed."
] | def get_num_fig_managers(cls):
return len(cls.figs) | ['def', 'get_num_fig_managers(cls):', 'return', 'len(cls.figs)'] | 194,817 |
unixpickle/anyrl-py | test_wrappers.py | test_logged_single_env | test_logged_single_env | Test LoggedEnv for a single environment. | [
"Test",
"LoggedEnv",
"for",
"a",
"single",
"environment."
] | def test_logged_single_env():
with tempfile.TemporaryDirectory() as dirpath:
log_file = os.path.join(dirpath, 'monitor.csv')
env = LoggedEnv(SimpleEnv(2, (3,), 'float32'), log_file)
for _ in range(4):
env.reset()
while not env.step(env.action_space.sample())[2]:
... | ['def', 'test_logged_single_env():', 'with', 'tempfile.TemporaryDirectory()', 'as', 'dirpath:', 'log_file', '=', 'os.path.join(dirpath,', "'monitor.csv')", 'env', '=', 'LoggedEnv(SimpleEnv(2,', '(3,),', "'float32'),", 'log_file)', 'for', '_', 'in', 'range(4):', 'env.reset()', 'while', 'not', 'env.step(env.action_space.... | 33,754 |
matsu0228/nlp-jp | settings.py | TopologySettings.get_server_descriptions | get_server_descriptions | Initial dict of (address, ServerDescription) for all seeds. | [
"Initial",
"dict",
"of",
"(address,",
"ServerDescription)",
"for",
"all",
"seeds."
] | def get_server_descriptions(self):
return dict([(address, ServerDescription(address)) for address in self.seeds]) | ['def', 'get_server_descriptions(self):', 'return', 'dict([(address,', 'ServerDescription(address))', 'for', 'address', 'in', 'self.seeds])'] | 805,050 |
saymedia/remoteobjects | fields.py | Dict.decode | decode | Decodes the dictionary value (a dictionary with dictionary values for values) into a `DataObject` attribute (a dictionary with `DataObject` attributes for values). | [
"Decodes",
"the",
"dictionary",
"value",
"(a",
"dictionary",
"with",
"dictionary",
"values",
"for",
"values)",
"into",
"a",
"`DataObject`",
"attribute",
"(a",
"dictionary",
"with",
"`DataObject`",
"attributes",
"for",
"values)."
] | def decode(self, value):
if value is None:
if callable(self.default):
return self.default()
return self.default or None
return dict(((k, self.fld.decode(v)) for (k, v) in value.iteritems())) | ['def', 'decode(self,', 'value):', 'if', 'value', 'is', 'None:', 'if', 'callable(self.default):', 'return', 'self.default()', 'return', 'self.default', 'or', 'None', 'return', 'dict(((k,', 'self.fld.decode(v))', 'for', '(k,', 'v)', 'in', 'value.iteritems()))'] | 346,025 |
clovaai/assembled-cnn | _device.py | define_device | define_device | Register device specific flags. | [
"Register",
"device",
"specific",
"flags."
] | def define_device(tpu=True):
key_flags = []
if tpu:
flags.DEFINE_string(name='tpu', default=None, help=help_wrap('The Cloud TPU to use for training. This should be either the name used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 url. Passing `local` will use theCPU of the local insta... | ['def', 'define_device(tpu=True):', 'key_flags', '=', '[]', 'if', 'tpu:', "flags.DEFINE_string(name='tpu',", 'default=None,', "help=help_wrap('The", 'Cloud', 'TPU', 'to', 'use', 'for', 'training.', 'This', 'should', 'be', 'either', 'the', 'name', 'used', 'when', 'creating', 'the', 'Cloud', 'TPU,', 'or', 'a', 'grpc://ip... | 92,439 |
Ruturaj123/Flowchart-Detection | option_builder.py | ProfileOptionBuilder.time_and_memory | time_and_memory | Show operation time and memory consumptions. | [
"Show",
"operation",
"time",
"and",
"memory",
"consumptions."
] | def time_and_memory(min_micros=1, min_bytes=1, min_accelerator_micros=0, min_cpu_micros=0, min_peak_bytes=0, min_residual_bytes=0, min_output_bytes=0):
return {'max_depth': 10000, 'min_bytes': min_bytes, 'min_peak_bytes': min_peak_bytes, 'min_residual_bytes': min_residual_bytes, 'min_output_bytes': min_output_bytes... | ['def', 'time_and_memory(min_micros=1,', 'min_bytes=1,', 'min_accelerator_micros=0,', 'min_cpu_micros=0,', 'min_peak_bytes=0,', 'min_residual_bytes=0,', 'min_output_bytes=0):', 'return', "{'max_depth':", '10000,', "'min_bytes':", 'min_bytes,', "'min_peak_bytes':", 'min_peak_bytes,', "'min_residual_bytes':", 'min_residu... | 606,360 |
hchasestevens/xpyth | __init__.py | query | query | Queries a DOM tree (lxml Element). | [
"Queries",
"a",
"DOM",
"tree",
"(lxml",
"Element)."
] | def query(g):
try:
dom = next(g.gi_frame.f_locals['.0']).getparent()
except StopIteration:
return []
g.gi_frame.f_locals['.0'] = DOM
ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(g.gi_frame), ctypes.c_int(0))
expression = '.' + xpath(g)
method_names = ('xpath', 'findall'... | ['def', 'query(g):', 'try:', 'dom', '=', "next(g.gi_frame.f_locals['.0']).getparent()", 'except', 'StopIteration:', 'return', '[]', "g.gi_frame.f_locals['.0']", '=', 'DOM', 'ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(g.gi_frame),', 'ctypes.c_int(0))', 'expression', '=', "'.'", '+', 'xpath(g)', 'method_names... | 374,499 |
yekeren/Cap2Det | trainer.py | predict | predict | Creates a callable to train and evaluate. | [
"Creates",
"a",
"callable",
"to",
"train",
"and",
"evaluate."
] | def predict(pipeline_proto, checkpoint_path=None, yield_single_examples=False):
if not isinstance(pipeline_proto, pipeline_pb2.Pipeline):
raise ValueError('pipeline_proto has to be an instance of Pipeline.')
predict_input_fn = reader.get_input_fn(pipeline_proto.eval_reader)
model_fn = _create_model_... | ['def', 'predict(pipeline_proto,', 'checkpoint_path=None,', 'yield_single_examples=False):', 'if', 'not', 'isinstance(pipeline_proto,', 'pipeline_pb2.Pipeline):', 'raise', "ValueError('pipeline_proto", 'has', 'to', 'be', 'an', 'instance', 'of', "Pipeline.')", 'predict_input_fn', '=', 'reader.get_input_fn(pipeline_proto... | 108,979 |
sek788432/Waymo-2D-Object-Detection | dual_encoder_test.py | DualEncoderTest.test_serialize_deserialize | test_serialize_deserialize | Validate that the dual encoder model can be serialized / deserialized. | [
"Validate",
"that",
"the",
"dual",
"encoder",
"model",
"can",
"be",
"serialized",
"/",
"deserialized."
] | def test_serialize_deserialize(self):
sequence_length = 32
test_network = networks.BertEncoder(vocab_size=100, num_layers=2, sequence_length=sequence_length)
dual_encoder_model = dual_encoder.DualEncoder(test_network, max_seq_length=sequence_length, output='predictions')
config = dual_encoder_model.get_... | ['def', 'test_serialize_deserialize(self):', 'sequence_length', '=', '32', 'test_network', '=', 'networks.BertEncoder(vocab_size=100,', 'num_layers=2,', 'sequence_length=sequence_length)', 'dual_encoder_model', '=', 'dual_encoder.DualEncoder(test_network,', 'max_seq_length=sequence_length,', "output='predictions')", 'c... | 972,644 |
rudranil723/mini-main | base.py | BaseDatabaseWrapper.rollback | rollback | Roll back a transaction and reset the dirty flag. | [
"Roll",
"back",
"a",
"transaction",
"and",
"reset",
"the",
"dirty",
"flag."
] | def rollback(self):
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._rollback()
self.errors_occurred = False
self.needs_rollback = False
self.run_on_commit = [] | ['def', 'rollback(self):', 'self.validate_thread_sharing()', 'self.validate_no_atomic_block()', 'self._rollback()', 'self.errors_occurred', '=', 'False', 'self.needs_rollback', '=', 'False', 'self.run_on_commit', '=', '[]'] | 315,715 |
thaines/helit | corpus.py | Corpus.getMu | getMu | Returns the PriorConcDP for the mu parameter. | [
"Returns",
"the",
"PriorConcDP",
"for",
"the",
"mu",
"parameter."
] | def getMu(self):
return self.mu | ['def', 'getMu(self):', 'return', 'self.mu'] | 591,026 |
sklearn-theano/sklearn-theano | message_test.py | MessageTest.testExtendShouldNotSwallowExceptions | testExtendShouldNotSwallowExceptions | This didn't use to work in the v2 C++ implementation. | [
"This",
"didn't",
"use",
"to",
"work",
"in",
"the",
"v2",
"C++",
"implementation."
] | def testExtendShouldNotSwallowExceptions(self, message_module):
m = message_module.TestAllTypes()
with self.assertRaises(NameError) as _:
m.repeated_int32.extend((a for i in range(10)))
with self.assertRaises(NameError) as _:
m.repeated_nested_enum.extend((a for i in range(10))) | ['def', 'testExtendShouldNotSwallowExceptions(self,', 'message_module):', 'm', '=', 'message_module.TestAllTypes()', 'with', 'self.assertRaises(NameError)', 'as', '_:', 'm.repeated_int32.extend((a', 'for', 'i', 'in', 'range(10)))', 'with', 'self.assertRaises(NameError)', 'as', '_:', 'm.repeated_nested_enum.extend((a', ... | 351,179 |
fpthink/3D-WSIS | misc.py | deprecated_api_warning | deprecated_api_warning | A decorator to check if some argments are deprecate and try to replace deprecate src_arg_name to dst_arg_name. | [
"A",
"decorator",
"to",
"check",
"if",
"some",
"argments",
"are",
"deprecate",
"and",
"try",
"to",
"replace",
"deprecate",
"src_arg_name",
"to",
"dst_arg_name."
] | def deprecated_api_warning(name_dict: Dict, cls_name: Optional[str]=None):
def api_warning_wrapper(old_func):
@functools.wraps(old_func)
def new_func(*args, **kwargs):
args_info = getfullargspec(old_func)
func_name = old_func.__name__
if cls_name is not None:
... | ['def', 'deprecated_api_warning(name_dict:', 'Dict,', 'cls_name:', 'Optional[str]=None):', 'def', 'api_warning_wrapper(old_func):', '@functools.wraps(old_func)', 'def', 'new_func(*args,', '**kwargs):', 'args_info', '=', 'getfullargspec(old_func)', 'func_name', '=', 'old_func.__name__', 'if', 'cls_name', 'is', 'not', 'N... | 4,673 |
tensorflow/data-validation | test_util.py | assert_feature_proto_equal | assert_feature_proto_equal | Ensures feature protos are equal. | [
"Ensures",
"feature",
"protos",
"are",
"equal."
] | def assert_feature_proto_equal(test: absltest.TestCase, actual: statistics_pb2.FeatureNameStatistics, expected: statistics_pb2.FeatureNameStatistics) -> None:
test.assertLen(actual.custom_stats, len(expected.custom_stats))
expected_custom_stats = {}
for expected_custom_stat in expected.custom_stats:
... | ['def', 'assert_feature_proto_equal(test:', 'absltest.TestCase,', 'actual:', 'statistics_pb2.FeatureNameStatistics,', 'expected:', 'statistics_pb2.FeatureNameStatistics)', '->', 'None:', 'test.assertLen(actual.custom_stats,', 'len(expected.custom_stats))', 'expected_custom_stats', '=', '{}', 'for', 'expected_custom_sta... | 497,674 |
OmidPoursaeed/Self_supervised_Learning_Point_Clouds | autoencoder.py | AutoEncoder.transform | transform | Transform data by mapping it into the latent space. | [
"Transform",
"data",
"by",
"mapping",
"it",
"into",
"the",
"latent",
"space."
] | def transform(self, X):
return self.sess.run(self.z, feed_dict={self.x: X}) | ['def', 'transform(self,', 'X):', 'return', 'self.sess.run(self.z,', 'feed_dict={self.x:', 'X})'] | 342,585 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | ticker.py | ScalarFormatter.get_offset | get_offset | Return scientific notation, plus offset. | [
"Return",
"scientific",
"notation,",
"plus",
"offset."
] | def get_offset(self):
if len(self.locs) == 0:
return ''
s = ''
if self.orderOfMagnitude or self.offset:
offsetStr = ''
sciNotStr = ''
if self.offset:
offsetStr = self.format_data(self.offset)
if self.offset > 0:
offsetStr = '+' + offset... | ['def', 'get_offset(self):', 'if', 'len(self.locs)', '==', '0:', 'return', "''", 's', '=', "''", 'if', 'self.orderOfMagnitude', 'or', 'self.offset:', 'offsetStr', '=', "''", 'sciNotStr', '=', "''", 'if', 'self.offset:', 'offsetStr', '=', 'self.format_data(self.offset)', 'if', 'self.offset', '>', '0:', 'offsetStr', '=',... | 257,322 |
devashish-patel/webcam-motion-detector | directory.py | DirectoryHandler.error_detail | error_detail | If the handler fails, may contain a traceback or other details. | [
"If",
"the",
"handler",
"fails,",
"may",
"contain",
"a",
"traceback",
"or",
"other",
"details."
] | def error_detail(self):
return self._main_handler.error_detail or self._lifecycle_handler.error_detail | ['def', 'error_detail(self):', 'return', 'self._main_handler.error_detail', 'or', 'self._lifecycle_handler.error_detail'] | 977,130 |
carbonati/variational-zoo | dataset.py | BaseDataset.num_latents | num_latents | Returns the number of latent variables. | [
"Returns",
"the",
"number",
"of",
"latent",
"variables."
] | def num_latents(self):
raise NotImplementedError | ['def', 'num_latents(self):', 'raise', 'NotImplementedError'] | 379,197 |
rudranil723/mini-main | segment.py | Segment.set_shape | set_shape | Set the shape of a list of lines (enclosing rectangle). | [
"Set",
"the",
"shape",
"of",
"a",
"list",
"of",
"lines",
"(enclosing",
"rectangle)."
] | def set_shape(cls, lines: List[List['Segment']], width: int, height: Optional[int]=None, style: Optional[Style]=None, new_lines: bool=False) -> List[List['Segment']]:
_height = height or len(lines)
blank = [cls(' ' * width + '\n', style)] if new_lines else [cls(' ' * width, style)]
adjust_line_length = cls.... | ['def', 'set_shape(cls,', 'lines:', "List[List['Segment']],", 'width:', 'int,', 'height:', 'Optional[int]=None,', 'style:', 'Optional[Style]=None,', 'new_lines:', 'bool=False)', '->', "List[List['Segment']]:", '_height', '=', 'height', 'or', 'len(lines)', 'blank', '=', "[cls('", "'", '*', 'width', '+', "'\\n',", 'style... | 268,936 |
google-research/tensor2robot | tpu_model_wrapper.py | TPUT2RModelWrapper.get_run_config | get_run_config | Get the RunConfig for Estimator model. | [
"Get",
"the",
"RunConfig",
"for",
"Estimator",
"model."
] | def get_run_config(self):
return self._t2r_model.get_run_config() | ['def', 'get_run_config(self):', 'return', 'self._t2r_model.get_run_config()'] | 908,245 |
LLNL/Abmarl | base.py | GridWorldSimulation.build_sim_from_grid | build_sim_from_grid | Build a GridSimluation from a Grid object. | [
"Build",
"a",
"GridSimluation",
"from",
"a",
"Grid",
"object."
] | def build_sim_from_grid(cls, grid, extra_agents=None, **kwargs):
assert type(grid) is Grid, 'Grid object required.'
if extra_agents is not None:
assert type(extra_agents) is dict, 'Extra agents must be a dictionary.'
agents = extra_agents
else:
agents = {}
for r in range(grid.row... | ['def', 'build_sim_from_grid(cls,', 'grid,', 'extra_agents=None,', '**kwargs):', 'assert', 'type(grid)', 'is', 'Grid,', "'Grid", 'object', "required.'", 'if', 'extra_agents', 'is', 'not', 'None:', 'assert', 'type(extra_agents)', 'is', 'dict,', "'Extra", 'agents', 'must', 'be', 'a', "dictionary.'", 'agents', '=', 'extra... | 405,748 |
thaines/helit | params.py | Kernel.toShortName | toShortName | Returns the short name of the kernel. | [
"Returns",
"the",
"short",
"name",
"of",
"the",
"kernel."
] | def toShortName(kernel):
data = {Kernel.linear: 'lin', Kernel.homo_polynomial: 'homo-poly', Kernel.polynomial: 'poly', Kernel.rbf: 'rbf', Kernel.gbf: 'gbf', Kernel.sigmoid: 'sig'}
return data[kernel] | ['def', 'toShortName(kernel):', 'data', '=', '{Kernel.linear:', "'lin',", 'Kernel.homo_polynomial:', "'homo-poly',", 'Kernel.polynomial:', "'poly',", 'Kernel.rbf:', "'rbf',", 'Kernel.gbf:', "'gbf',", 'Kernel.sigmoid:', "'sig'}", 'return', 'data[kernel]'] | 592,535 |
davidventuri/udacity-aind | logic.py | occur_check | occur_check | Return true if variable var occurs anywhere in x (or in subst(s, x), if s has a binding for x). | [
"Return",
"true",
"if",
"variable",
"var",
"occurs",
"anywhere",
"in",
"x",
"(or",
"in",
"subst(s,",
"x),",
"if",
"s",
"has",
"a",
"binding",
"for",
"x)."
] | def occur_check(var, x, s):
if var == x:
return True
elif is_variable(x) and x in s:
return occur_check(var, s[x], s)
elif isinstance(x, Expr):
return occur_check(var, x.op, s) or occur_check(var, x.args, s)
elif isinstance(x, (list, tuple)):
return first((e for e in x if... | ['def', 'occur_check(var,', 'x,', 's):', 'if', 'var', '==', 'x:', 'return', 'True', 'elif', 'is_variable(x)', 'and', 'x', 'in', 's:', 'return', 'occur_check(var,', 's[x],', 's)', 'elif', 'isinstance(x,', 'Expr):', 'return', 'occur_check(var,', 'x.op,', 's)', 'or', 'occur_check(var,', 'x.args,', 's)', 'elif', 'isinstanc... | 427,678 |
deepmind/xmanager | auth_test.py | GetServiceAccountTest.test_get_service_account_no_permissions | test_get_service_account_no_permissions | Tests if `get_service_account` creates permissions properly for an existing account with no permissions. | [
"Tests",
"if",
"`get_service_account`",
"creates",
"permissions",
"properly",
"for",
"an",
"existing",
"account",
"with",
"no",
"permissions."
] | def test_get_service_account_no_permissions(self, sys_argv, expected_account_name):
flags.FLAGS(sys_argv)
mock_service_accounts = mock.Mock()
mock_service_accounts.list.return_value.execute.return_value = {'accounts': [{'email': f'{expected_account_name}@test-project.iam.gserviceaccount.com'}]}
mock_ser... | ['def', 'test_get_service_account_no_permissions(self,', 'sys_argv,', 'expected_account_name):', 'flags.FLAGS(sys_argv)', 'mock_service_accounts', '=', 'mock.Mock()', 'mock_service_accounts.list.return_value.execute.return_value', '=', "{'accounts':", "[{'email':", "f'{expected_account_name}@test-project.iam.gserviceac... | 968,696 |
ahmedheakl/drone-vis | test_demo_drone.py | test_stop_video_thread | test_stop_video_thread | Drone video thread should stop and set to None when the method `stop` is called. | [
"Drone",
"video",
"thread",
"should",
"stop",
"and",
"set",
"to",
"None",
"when",
"the",
"method",
"`stop`",
"is",
"called."
] | def test_stop_video_thread(capsys):
init_logger('debug')
drone = DemoDrone()
drone.connect_video(print, print, 'Face')
assert drone.video_thread is not None
assert drone.video_thread.running
time.sleep(2)
drone.stop()
assert drone.video_thread is None
capture = capsys.readouterr()
... | ['def', 'test_stop_video_thread(capsys):', "init_logger('debug')", 'drone', '=', 'DemoDrone()', 'drone.connect_video(print,', 'print,', "'Face')", 'assert', 'drone.video_thread', 'is', 'not', 'None', 'assert', 'drone.video_thread.running', 'time.sleep(2)', 'drone.stop()', 'assert', 'drone.video_thread', 'is', 'None', '... | 553,365 |
google-research/scenic | test_vivit_trainer.py | ViViTClassificationTrainerTest.get_train_state | get_train_state | Generates the initial training state. | [
"Generates",
"the",
"initial",
"training",
"state."
] | def get_train_state(self, rng, fake_batch_logits):
config = ml_collections.ConfigDict({'lr_configs': {'base_learning_rate': 0.1}, 'optimizer': 'sgd'})
class FakeFlaxModel(nn.Module):
@nn.compact
def __call__(self, x, train=False, debug=False):
del x
del train
... | ['def', 'get_train_state(self,', 'rng,', 'fake_batch_logits):', 'config', '=', "ml_collections.ConfigDict({'lr_configs':", "{'base_learning_rate':", '0.1},', "'optimizer':", "'sgd'})", 'class', 'FakeFlaxModel(nn.Module):', '@nn.compact', 'def', '__call__(self,', 'x,', 'train=False,', 'debug=False):', 'del', 'x', 'del',... | 847,595 |
microsoft/nni | base_lightning.py | BaseOneShotLightningModule.set_model | set_model | Set the model space to be searched. | [
"Set",
"the",
"model",
"space",
"to",
"be",
"searched."
] | def set_model(self, model: nn.Module) -> None:
self.training_module.set_model(model) | ['def', 'set_model(self,', 'model:', 'nn.Module)', '->', 'None:', 'self.training_module.set_model(model)'] | 728,781 |
Eric3911/OpenAGI | transformer_generators.py | EnsembleBeamSearchSequenceGenerator.as_frozen | as_frozen | Context manager which temporarily freezes embedding, decoder, and log_softmax modules, yields control and finally unfreezes the modules. | [
"Context",
"manager",
"which",
"temporarily",
"freezes",
"embedding,",
"decoder,",
"and",
"log_softmax",
"modules,",
"yields",
"control",
"and",
"finally",
"unfreezes",
"the",
"modules."
] | def as_frozen(self):
self.freeze()
try:
yield
finally:
self.unfreeze() | ['def', 'as_frozen(self):', 'self.freeze()', 'try:', 'yield', 'finally:', 'self.unfreeze()'] | 273,839 |
thaines/helit | model.py | Sample.getTopicConc | getTopicConc | Returns the sampled concentration parameter for drawing topic instances from the global DP. | [
"Returns",
"the",
"sampled",
"concentration",
"parameter",
"for",
"drawing",
"topic",
"instances",
"from",
"the",
"global",
"DP."
] | def getTopicConc(self):
return self.topicConc | ['def', 'getTopicConc(self):', 'return', 'self.topicConc'] | 591,078 |
google-research/scenic | layers.py | get_q_kv_mask | get_q_kv_mask | Generates query, key/valye, input mask and logging input mask based on ac_config. | [
"Generates",
"query,",
"key/valye,",
"input",
"mask",
"and",
"logging",
"input",
"mask",
"based",
"on",
"ac_config."
] | def get_q_kv_mask(x: jnp.ndarray, input_mask: Optional[jnp.ndarray], layer: int, tape_added: int, ac_config: ml_collections.ConfigDict, bank: Optional[jnp.ndarray], train: bool) -> Tuple[jnp.ndarray, Optional[jnp.ndarray], Optional[jnp.ndarray], Optional[jnp.ndarray], Optional[jnp.ndarray], int]:
if layer in ac_con... | ['def', 'get_q_kv_mask(x:', 'jnp.ndarray,', 'input_mask:', 'Optional[jnp.ndarray],', 'layer:', 'int,', 'tape_added:', 'int,', 'ac_config:', 'ml_collections.ConfigDict,', 'bank:', 'Optional[jnp.ndarray],', 'train:', 'bool)', '->', 'Tuple[jnp.ndarray,', 'Optional[jnp.ndarray],', 'Optional[jnp.ndarray],', 'Optional[jnp.nd... | 846,311 |
wutong8023/CoLL | tokenization_tapas.py | parse_text | parse_text | Extracts longest number and date spans. | [
"Extracts",
"longest",
"number",
"and",
"date",
"spans."
] | def parse_text(text):
span_dict = collections.defaultdict(list)
for match in _NUMBER_PATTERN.finditer(text):
span_text = text[match.start():match.end()]
number = _parse_number(span_text)
if number is not None:
span_dict[match.span()].append(_get_numeric_value_from_float(numbe... | ['def', 'parse_text(text):', 'span_dict', '=', 'collections.defaultdict(list)', 'for', 'match', 'in', '_NUMBER_PATTERN.finditer(text):', 'span_text', '=', 'text[match.start():match.end()]', 'number', '=', '_parse_number(span_text)', 'if', 'number', 'is', 'not', 'None:', 'span_dict[match.span()].append(_get_numeric_valu... | 466,855 |
zihuitang/medical_AI_platform | __init__.py | Canvas.index | index | Return position of cursor as integer in item specified in ARGS. | [
"Return",
"position",
"of",
"cursor",
"as",
"integer",
"in",
"item",
"specified",
"in",
"ARGS."
] | def index(self, *args):
return self.tk.getint(self.tk.call((self._w, 'index') + args)) | ['def', 'index(self,', '*args):', 'return', 'self.tk.getint(self.tk.call((self._w,', "'index')", '+', 'args))'] | 284,235 |
deepmind/bsuite | run.py | run | run | Runs a DQN agent on a given bsuite environment, logging to CSV. | [
"Runs",
"a",
"DQN",
"agent",
"on",
"a",
"given",
"bsuite",
"environment,",
"logging",
"to",
"CSV."
] | def run(bsuite_id: str) -> str:
env = bsuite.load_and_record(bsuite_id=bsuite_id, save_path=FLAGS.save_path, logging_mode=FLAGS.logging_mode, overwrite=FLAGS.overwrite)
agent = dqn.default_agent(env.observation_spec(), env.action_spec())
num_episodes = FLAGS.num_episodes or getattr(env, 'bsuite_num_episodes... | ['def', 'run(bsuite_id:', 'str)', '->', 'str:', 'env', '=', 'bsuite.load_and_record(bsuite_id=bsuite_id,', 'save_path=FLAGS.save_path,', 'logging_mode=FLAGS.logging_mode,', 'overwrite=FLAGS.overwrite)', 'agent', '=', 'dqn.default_agent(env.observation_spec(),', 'env.action_spec())', 'num_episodes', '=', 'FLAGS.num_epis... | 410,121 |
jimtin/Stock_Comparison | console_widget.py | is_letter_or_number | is_letter_or_number | Returns whether the specified unicode character is a letter or a number. | [
"Returns",
"whether",
"the",
"specified",
"unicode",
"character",
"is",
"a",
"letter",
"or",
"a",
"number."
] | def is_letter_or_number(char):
cat = category(char)
return cat.startswith('L') or cat.startswith('N') | ['def', 'is_letter_or_number(char):', 'cat', '=', 'category(char)', 'return', "cat.startswith('L')", 'or', "cat.startswith('N')"] | 358,535 |
ldkong1205/LaserMix | mvx_two_stage.py | MVXTwoStageDetector.extract_pts_feat | extract_pts_feat | Extract features of points. | [
"Extract",
"features",
"of",
"points."
] | def extract_pts_feat(self, voxel_dict: Dict[str, Tensor], points: Optional[List[Tensor]]=None, img_feats: Optional[Sequence[Tensor]]=None, batch_input_metas: Optional[List[dict]]=None) -> Sequence[Tensor]:
if not self.with_pts_bbox:
return None
voxel_features = self.pts_voxel_encoder(voxel_dict['voxels'... | ['def', 'extract_pts_feat(self,', 'voxel_dict:', 'Dict[str,', 'Tensor],', 'points:', 'Optional[List[Tensor]]=None,', 'img_feats:', 'Optional[Sequence[Tensor]]=None,', 'batch_input_metas:', 'Optional[List[dict]]=None)', '->', 'Sequence[Tensor]:', 'if', 'not', 'self.with_pts_bbox:', 'return', 'None', 'voxel_features', '=... | 624,104 |
thaines/helit | tile_mask.py | TileMask.get_true | get_true | Returns the colour used for the True region of the mask, or None if it is transparent. | [
"Returns",
"the",
"colour",
"used",
"for",
"the",
"True",
"region",
"of",
"the",
"mask,",
"or",
"None",
"if",
"it",
"is",
"transparent."
] | def get_true(self):
return self.colTrue | ['def', 'get_true(self):', 'return', 'self.colTrue'] | 592,707 |
yasiemir/cs224n | model.py | Model.add_loss_op | add_loss_op | Adds Ops for the loss function to the computational graph. | [
"Adds",
"Ops",
"for",
"the",
"loss",
"function",
"to",
"the",
"computational",
"graph."
] | def add_loss_op(self, pred):
raise NotImplementedError('Each Model must re-implement this method.') | ['def', 'add_loss_op(self,', 'pred):', 'raise', "NotImplementedError('Each", 'Model', 'must', 're-implement', 'this', "method.')"] | 506,520 |
kianak2002/Sentiment-Emotion-Analysis-project | install.py | install.change_roots | change_roots | Change the install directories pointed by name using root. | [
"Change",
"the",
"install",
"directories",
"pointed",
"by",
"name",
"using",
"root."
] | def change_roots(self, *names):
for name in names:
attr = 'install_' + name
setattr(self, attr, change_root(self.root, getattr(self, attr))) | ['def', 'change_roots(self,', '*names):', 'for', 'name', 'in', 'names:', 'attr', '=', "'install_'", '+', 'name', 'setattr(self,', 'attr,', 'change_root(self.root,', 'getattr(self,', 'attr)))'] | 875,931 |
pfnet/pfrl | td3.py | TD3.update_policy | update_policy | Compute loss for actor. | [
"Compute",
"loss",
"for",
"actor."
] | def update_policy(self, batch):
batch_state = batch['state']
onpolicy_actions = self.policy(batch_state).rsample()
q = self.q_func1((batch_state, onpolicy_actions))
loss = -torch.mean(q)
self.policy_loss_record.append(float(loss))
self.policy_optimizer.zero_grad()
loss.backward()
if self... | ['def', 'update_policy(self,', 'batch):', 'batch_state', '=', "batch['state']", 'onpolicy_actions', '=', 'self.policy(batch_state).rsample()', 'q', '=', 'self.q_func1((batch_state,', 'onpolicy_actions))', 'loss', '=', '-torch.mean(q)', 'self.policy_loss_record.append(float(loss))', 'self.policy_optimizer.zero_grad()', ... | 304,669 |
asyml/texar | data_decoders.py | TextDataDecoder.text_id_tensor_name | text_id_tensor_name | The name of text index tensor. | [
"The",
"name",
"of",
"text",
"index",
"tensor."
] | def text_id_tensor_name(self):
return self._text_id_tensor_name | ['def', 'text_id_tensor_name(self):', 'return', 'self._text_id_tensor_name'] | 924,469 |
myothida/Supervised-Machine-Learning | ttFont.py | TTFont.getGlyphIDMany | getGlyphIDMany | Converts a list of glyph names into a list of glyph IDs. | [
"Converts",
"a",
"list",
"of",
"glyph",
"names",
"into",
"a",
"list",
"of",
"glyph",
"IDs."
] | def getGlyphIDMany(self, lst):
d = self.getReverseGlyphMap()
try:
return [d[glyphName] for glyphName in lst]
except KeyError:
getGlyphID = self.getGlyphID
return [getGlyphID(glyphName) for glyphName in lst] | ['def', 'getGlyphIDMany(self,', 'lst):', 'd', '=', 'self.getReverseGlyphMap()', 'try:', 'return', '[d[glyphName]', 'for', 'glyphName', 'in', 'lst]', 'except', 'KeyError:', 'getGlyphID', '=', 'self.getGlyphID', 'return', '[getGlyphID(glyphName)', 'for', 'glyphName', 'in', 'lst]'] | 361,199 |
alex-petrenko/sample-factory | envpool_atari_params.py | atari_override_defaults | atari_override_defaults | RL params specific to Atari envs. | [
"RL",
"params",
"specific",
"to",
"Atari",
"envs."
] | def atari_override_defaults(_env, parser):
parser.set_defaults(summaries_use_frameskip=True, use_record_episode_statistics=True, encoder_conv_architecture='convnet_atari', obs_scale=255.0, gamma=0.99, env_frameskip=4, env_framestack=4, exploration_loss_coeff=0.01, num_workers=4, num_envs_per_worker=1, worker_num_sp... | ['def', 'atari_override_defaults(_env,', 'parser):', 'parser.set_defaults(summaries_use_frameskip=True,', 'use_record_episode_statistics=True,', "encoder_conv_architecture='convnet_atari',", 'obs_scale=255.0,', 'gamma=0.99,', 'env_frameskip=4,', 'env_framestack=4,', 'exploration_loss_coeff=0.01,', 'num_workers=4,', 'nu... | 329,214 |
Trusted-AI/AIX360 | surrogate.py | linear_surrogate_weights | linear_surrogate_weights | Function to compute weights from a linear interpretable model using provided time series pertubations. | [
"Function",
"to",
"compute",
"weights",
"from",
"a",
"linear",
"interpretable",
"model",
"using",
"provided",
"time",
"series",
"pertubations."
] | def linear_surrogate_weights(x_perturbations: np.ndarray, y_perturbations: np.ndarray, surrogate: LinearSurrogateModel=None):
if surrogate is None:
surrogate = LinearRegressionSurrogate()
surrogate.fit(x_perturbations.reshape(x_perturbations.shape[0], -1), y_perturbations.reshape(y_perturbations.shape[0... | ['def', 'linear_surrogate_weights(x_perturbations:', 'np.ndarray,', 'y_perturbations:', 'np.ndarray,', 'surrogate:', 'LinearSurrogateModel=None):', 'if', 'surrogate', 'is', 'None:', 'surrogate', '=', 'LinearRegressionSurrogate()', 'surrogate.fit(x_perturbations.reshape(x_perturbations.shape[0],', '-1),', 'y_perturbatio... | 413,387 |
myuon/AI | cnf_transformation.py | distribute_or_over_and | distribute_or_over_and | Distributes the or operators over ands and returns the given formula transformed. | [
"Distributes",
"the",
"or",
"operators",
"over",
"ands",
"and",
"returns",
"the",
"given",
"formula",
"transformed."
] | def distribute_or_over_and(f):
left = f.lchild
right = f.rchild
left_is_atom = isinstance(left, Atom) or isinstance(left, Not)
right_is_atom = isinstance(right, Atom) or isinstance(right, Not)
if left_is_atom and right_is_atom:
return f
elif not left_is_atom and (not right_is_atom) and (... | ['def', 'distribute_or_over_and(f):', 'left', '=', 'f.lchild', 'right', '=', 'f.rchild', 'left_is_atom', '=', 'isinstance(left,', 'Atom)', 'or', 'isinstance(left,', 'Not)', 'right_is_atom', '=', 'isinstance(right,', 'Atom)', 'or', 'isinstance(right,', 'Not)', 'if', 'left_is_atom', 'and', 'right_is_atom:', 'return', 'f'... | 69,411 |
myothida/Supervised-Machine-Learning | test_openml.py | test_fetch_openml_iris_warn_multiple_version | test_fetch_openml_iris_warn_multiple_version | Check that a warning is raised when multiple versions exist and no version is requested. | [
"Check",
"that",
"a",
"warning",
"is",
"raised",
"when",
"multiple",
"versions",
"exist",
"and",
"no",
"version",
"is",
"requested."
] | def test_fetch_openml_iris_warn_multiple_version(monkeypatch, gzip_response):
data_id = 61
data_name = 'iris'
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
msg = 'Multiple active versions of the dataset matching the name iris exist. Versions may be fundamentally different, return... | ['def', 'test_fetch_openml_iris_warn_multiple_version(monkeypatch,', 'gzip_response):', 'data_id', '=', '61', 'data_name', '=', "'iris'", '_monkey_patch_webbased_functions(monkeypatch,', 'data_id,', 'gzip_response)', 'msg', '=', "'Multiple", 'active', 'versions', 'of', 'the', 'dataset', 'matching', 'the', 'name', 'iris... | 363,592 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.