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 |
|---|---|---|---|---|---|---|---|---|
zehuichen123/AutoAlignV2 | dbsampler_backup.py | DataBaseSampler.filter_by_min_points | filter_by_min_points | Filter ground truths by number of points in the bbox. | [
"Filter",
"ground",
"truths",
"by",
"number",
"of",
"points",
"in",
"the",
"bbox."
] | def filter_by_min_points(db_infos, min_gt_points_dict):
for (name, min_num) in min_gt_points_dict.items():
min_num = int(min_num)
if min_num > 0:
filtered_infos = []
for info in db_infos[name]:
if info['num_points_in_gt'] >= min_num:
filter... | ['def', 'filter_by_min_points(db_infos,', 'min_gt_points_dict):', 'for', '(name,', 'min_num)', 'in', 'min_gt_points_dict.items():', 'min_num', '=', 'int(min_num)', 'if', 'min_num', '>', '0:', 'filtered_infos', '=', '[]', 'for', 'info', 'in', 'db_infos[name]:', 'if', "info['num_points_in_gt']", '>=', 'min_num:', 'filter... | 416,778 |
ahottung/CVAE-Opt | cvrp.py | update_dynamic | update_dynamic | Updates the (load, demand) dataset values. | [
"Updates",
"the",
"(load,",
"demand)",
"dataset",
"values."
] | def update_dynamic(instance, chosen_idx):
visit = chosen_idx.ne(0)
depot = ~visit
instance = instance.clone()
all_loads = instance[:, :, 2]
all_demands = instance[:, :, 3]
demand = torch.gather(all_demands, 1, chosen_idx.unsqueeze(1)).squeeze()
if visit.any():
new_load = torch.clamp(... | ['def', 'update_dynamic(instance,', 'chosen_idx):', 'visit', '=', 'chosen_idx.ne(0)', 'depot', '=', '~visit', 'instance', '=', 'instance.clone()', 'all_loads', '=', 'instance[:,', ':,', '2]', 'all_demands', '=', 'instance[:,', ':,', '3]', 'demand', '=', 'torch.gather(all_demands,', '1,', 'chosen_idx.unsqueeze(1)).squee... | 509,424 |
MycroftAI/mycroft-core | tts.py | TTS.begin_audio | begin_audio | Helper function for child classes to call in execute(). | [
"Helper",
"function",
"for",
"child",
"classes",
"to",
"call",
"in",
"execute()."
] | def begin_audio(self):
self.bus.emit(Message('recognizer_loop:audio_output_start')) | ['def', 'begin_audio(self):', "self.bus.emit(Message('recognizer_loop:audio_output_start'))"] | 290,704 |
rudranil723/mini-main | __init__.py | composite_call_credentials | composite_call_credentials | Compose multiple CallCredentials to make a new CallCredentials. | [
"Compose",
"multiple",
"CallCredentials",
"to",
"make",
"a",
"new",
"CallCredentials."
] | def composite_call_credentials(*call_credentials):
return CallCredentials(_cygrpc.CompositeCallCredentials(tuple((single_call_credentials._credentials for single_call_credentials in call_credentials)))) | ['def', 'composite_call_credentials(*call_credentials):', 'return', 'CallCredentials(_cygrpc.CompositeCallCredentials(tuple((single_call_credentials._credentials', 'for', 'single_call_credentials', 'in', 'call_credentials))))'] | 318,534 |
twke18/HSG | transformer_clusters.py | TransformerClustering.forward | forward | Feedforward for clustering with Transformer. | [
"Feedforward",
"for",
"clustering",
"with",
"Transformer."
] | def forward(self, src, mask, query_embed, pos_embed):
(bs, cs, sl) = src.shape
(centroids, node_features) = self._transformer(src, mask, query_embed, pos_embed)
tl = centroids.shape[-1]
flat_centroids = centroids.transpose(1, 2).flatten(0, 1)
centroids = self.centroid_fc(flat_centroids).view(bs, tl,... | ['def', 'forward(self,', 'src,', 'mask,', 'query_embed,', 'pos_embed):', '(bs,', 'cs,', 'sl)', '=', 'src.shape', '(centroids,', 'node_features)', '=', 'self._transformer(src,', 'mask,', 'query_embed,', 'pos_embed)', 'tl', '=', 'centroids.shape[-1]', 'flat_centroids', '=', 'centroids.transpose(1,', '2).flatten(0,', '1)'... | 570,681 |
Yagami360/MachineLearning_Exercises_Python_TensorFlow | BBoxMatcher.py | BBoxMatcher.extract_highest_indicies | extract_highest_indicies | extract specific indicies, that is, have most high loss_confs. | [
"extract",
"specific",
"indicies,",
"that",
"is,",
"have",
"most",
"high",
"loss_confs."
] | def extract_highest_indicies(self, pred_confs, max_length):
loss_confs = []
for pred_conf in pred_confs:
pred = np.exp(pred_conf) / (np.sum(np.exp(pred_conf)) + 1e-05)
loss_confs.append(np.amax(pred))
size = min(len(loss_confs), max_length)
indicies = np.argpartition(loss_confs, -size)[-... | ['def', 'extract_highest_indicies(self,', 'pred_confs,', 'max_length):', 'loss_confs', '=', '[]', 'for', 'pred_conf', 'in', 'pred_confs:', 'pred', '=', 'np.exp(pred_conf)', '/', '(np.sum(np.exp(pred_conf))', '+', '1e-05)', 'loss_confs.append(np.amax(pred))', 'size', '=', 'min(len(loss_confs),', 'max_length)', 'indicies... | 641,047 |
RasaHQ/rasa | io.py | read_model_configuration | read_model_configuration | Parses a model configuration file. | [
"Parses",
"a",
"model",
"configuration",
"file."
] | def read_model_configuration(filename: Union[Path, Text]) -> Dict[Text, Any]:
return read_validated_yaml(filename, MODEL_CONFIG_SCHEMA_FILE) | ['def', 'read_model_configuration(filename:', 'Union[Path,', 'Text])', '->', 'Dict[Text,', 'Any]:', 'return', 'read_validated_yaml(filename,', 'MODEL_CONFIG_SCHEMA_FILE)'] | 837,815 |
ZhAnGToNG1/transfer_learning_cspt | cross_entropy_loss.py | cross_entropy | cross_entropy | Calculate the CrossEntropy loss. | [
"Calculate",
"the",
"CrossEntropy",
"loss."
] | def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None, ignore_index=-100):
ignore_index = -100 if ignore_index is None else ignore_index
loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none', ignore_index=ignore_index)
if weight is not None:
... | ['def', 'cross_entropy(pred,', 'label,', 'weight=None,', "reduction='mean',", 'avg_factor=None,', 'class_weight=None,', 'ignore_index=-100):', 'ignore_index', '=', '-100', 'if', 'ignore_index', 'is', 'None', 'else', 'ignore_index', 'loss', '=', 'F.cross_entropy(pred,', 'label,', 'weight=class_weight,', "reduction='none... | 964,177 |
sunishsheth2009/ChatterBot | test_tree.py | TestElementObjects.test_len | test_len | The length of an element is its number of children. | [
"The",
"length",
"of",
"an",
"element",
"is",
"its",
"number",
"of",
"children."
] | def test_len(self):
soup = self.soup('<top>1<b>2</b>3</top>')
self.assertEqual(len(soup.contents), 1)
self.assertEqual(len(soup), 1)
self.assertEqual(len(soup.top), 3)
self.assertEqual(len(soup.top.contents), 3) | ['def', 'test_len(self):', 'soup', '=', "self.soup('<top>1<b>2</b>3</top>')", 'self.assertEqual(len(soup.contents),', '1)', 'self.assertEqual(len(soup),', '1)', 'self.assertEqual(len(soup.top),', '3)', 'self.assertEqual(len(soup.top.contents),', '3)'] | 528,832 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | widget.py | Widget.handle_comm_opened | handle_comm_opened | Static method, called when a widget is constructed. | [
"Static",
"method,",
"called",
"when",
"a",
"widget",
"is",
"constructed."
] | def handle_comm_opened(comm, msg):
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError('Incompatible widget protocol versions: received version %r, expected version %r' % (version, __protocol_version__))
data = msg['content']['dat... | ['def', 'handle_comm_opened(comm,', 'msg):', 'version', '=', "msg.get('metadata',", "{}).get('version',", "'')", 'if', "version.split('.')[0]", '!=', 'PROTOCOL_VERSION_MAJOR:', 'raise', "ValueError('Incompatible", 'widget', 'protocol', 'versions:', 'received', 'version', '%r,', 'expected', 'version', "%r'", '%', '(vers... | 449,134 |
tobegit3hub/deep_image_model | linear_test.py | LinearClassifierTest.testDisableCenteredBias | testDisableCenteredBias | Tests that we can disable centered bias. | [
"Tests",
"that",
"we",
"can",
"disable",
"centered",
"bias."
] | def testDisableCenteredBias(self):
def input_fn():
return ({'age': tf.constant([1]), 'language': tf.SparseTensor(values=['english'], indices=[[0, 0]], shape=[1, 1])}, tf.constant([[1]]))
language = tf.contrib.layers.sparse_column_with_hash_bucket('language', 100)
age = tf.contrib.layers.real_valued... | ['def', 'testDisableCenteredBias(self):', 'def', 'input_fn():', 'return', "({'age':", 'tf.constant([1]),', "'language':", "tf.SparseTensor(values=['english'],", 'indices=[[0,', '0]],', 'shape=[1,', '1])},', 'tf.constant([[1]]))', 'language', '=', "tf.contrib.layers.sparse_column_with_hash_bucket('language',", '100)', '... | 181,765 |
openml-labs/gama | primitive_node.py | find_terminal | find_terminal | Find the Terminal that matches `terminal_string` in `primitive_set`. | [
"Find",
"the",
"Terminal",
"that",
"matches",
"`terminal_string`",
"in",
"`primitive_set`."
] | def find_terminal(primitive_set: dict, terminal_string: str) -> Terminal:
(term_type, _) = terminal_string.split('=')
for terminal in primitive_set[term_type]:
if repr(terminal) == terminal_string:
return terminal
raise RuntimeError(f"Could not find Terminal of type '{terminal_string}'."... | ['def', 'find_terminal(primitive_set:', 'dict,', 'terminal_string:', 'str)', '->', 'Terminal:', '(term_type,', '_)', '=', "terminal_string.split('=')", 'for', 'terminal', 'in', 'primitive_set[term_type]:', 'if', 'repr(terminal)', '==', 'terminal_string:', 'return', 'terminal', 'raise', 'RuntimeError(f"Could', 'not', 'f... | 566,169 |
ViTAE-Transformer/ViTDet | gaussian_target.py | transpose_and_gather_feat | transpose_and_gather_feat | Transpose and gather feature according to index. | [
"Transpose",
"and",
"gather",
"feature",
"according",
"to",
"index."
] | def transpose_and_gather_feat(feat, ind):
feat = feat.permute(0, 2, 3, 1).contiguous()
feat = feat.view(feat.size(0), -1, feat.size(3))
feat = gather_feat(feat, ind)
return feat | ['def', 'transpose_and_gather_feat(feat,', 'ind):', 'feat', '=', 'feat.permute(0,', '2,', '3,', '1).contiguous()', 'feat', '=', 'feat.view(feat.size(0),', '-1,', 'feat.size(3))', 'feat', '=', 'gather_feat(feat,', 'ind)', 'return', 'feat'] | 945,804 |
sunishsheth2009/ChatterBot | test.py | Client.options | options | Like open but method is enforced to OPTIONS. | [
"Like",
"open",
"but",
"method",
"is",
"enforced",
"to",
"OPTIONS."
] | def options(self, *args, **kw):
kw['method'] = 'OPTIONS'
return self.open(*args, **kw) | ['def', 'options(self,', '*args,', '**kw):', "kw['method']", '=', "'OPTIONS'", 'return', 'self.open(*args,', '**kw)'] | 482,302 |
ThomasBrouwer/HMF | updates_Gibbs.py | beta_importance | beta_importance | Return the values for beta for the Gibbs sampler, for the importance learning of alpha. | [
"Return",
"the",
"values",
"for",
"beta",
"for",
"the",
"Gibbs",
"sampler,",
"for",
"the",
"importance",
"learning",
"of",
"alpha."
] | def beta_importance(betaA, tau, dataset, mask, F, G, S=None):
dataset_pred = numpy.dot(F, G.T) if S is None else triple_dot(F, S, G.T)
squared_error = (mask * (dataset - dataset_pred) ** 2).sum()
size_Omega = mask.sum()
return betaA + tau * squared_error / 2.0 - size_Omega / 2.0 * math.log(tau / (2.0 * ... | ['def', 'beta_importance(betaA,', 'tau,', 'dataset,', 'mask,', 'F,', 'G,', 'S=None):', 'dataset_pred', '=', 'numpy.dot(F,', 'G.T)', 'if', 'S', 'is', 'None', 'else', 'triple_dot(F,', 'S,', 'G.T)', 'squared_error', '=', '(mask', '*', '(dataset', '-', 'dataset_pred)', '**', '2).sum()', 'size_Omega', '=', 'mask.sum()', 're... | 206,688 |
Crepdo/CS188_Artificial-Intelligence | logic_utils.py | AIMAFile | AIMAFile | Open a file based at the AIMA root directory. | [
"Open",
"a",
"file",
"based",
"at",
"the",
"AIMA",
"root",
"directory."
] | def AIMAFile(components, mode='r'):
import logic_utils
dir = os.path.dirname(logic_utils.__file__)
return open(apply(os.path.join, [dir] + components), mode) | ['def', 'AIMAFile(components,', "mode='r'):", 'import', 'logic_utils', 'dir', '=', 'os.path.dirname(logic_utils.__file__)', 'return', 'open(apply(os.path.join,', '[dir]', '+', 'components),', 'mode)'] | 227,036 |
pfnet/pfrl | replay_buffer.py | AbstractEpisodicReplayBuffer.sample_episodes | sample_episodes | Sample n unique (sub)episodes from this replay buffer. | [
"Sample",
"n",
"unique",
"(sub)episodes",
"from",
"this",
"replay",
"buffer."
] | def sample_episodes(self, n_episodes, max_len=None):
raise NotImplementedError | ['def', 'sample_episodes(self,', 'n_episodes,', 'max_len=None):', 'raise', 'NotImplementedError'] | 304,638 |
eyounx/RetroCodes | sonic_util.py | make_env_local | make_env_local | Create an environment with some standard wrappers. | [
"Create",
"an",
"environment",
"with",
"some",
"standard",
"wrappers."
] | def make_env_local(stack=True, scale_rew=True, idx=6, frame_wrapper=WarpFrame, reward_type=None):
from retro_contest.local import make
all_level = train_level + test_level
print(str(idx) + ': start game=' + all_level[idx][0] + ', state=' + all_level[idx][1])
env = make(game=all_level[idx][0], state=all_... | ['def', 'make_env_local(stack=True,', 'scale_rew=True,', 'idx=6,', 'frame_wrapper=WarpFrame,', 'reward_type=None):', 'from', 'retro_contest.local', 'import', 'make', 'all_level', '=', 'train_level', '+', 'test_level', 'print(str(idx)', '+', "':", 'start', "game='", '+', 'all_level[idx][0]', '+', "',", "state='", '+', '... | 840,956 |
arnomoonens/yarll | network_ops.py | reset_accumulative_gradients_op | reset_accumulative_gradients_op | Make an operation to reset the accumulation to zero. | [
"Make",
"an",
"operation",
"to",
"reset",
"the",
"accumulation",
"to",
"zero."
] | def reset_accumulative_gradients_op(net_vars, accum_grads, identifier: int=0):
reset_grad_ops = []
with tf.name_scope(name='reset_grad_ops_{}'.format(identifier), values=net_vars):
for (var, accum_grad) in zip(net_vars, accum_grads):
zero = tf.zeros(var.get_shape().as_list(), dtype=var.dtype... | ['def', 'reset_accumulative_gradients_op(net_vars,', 'accum_grads,', 'identifier:', 'int=0):', 'reset_grad_ops', '=', '[]', 'with', "tf.name_scope(name='reset_grad_ops_{}'.format(identifier),", 'values=net_vars):', 'for', '(var,', 'accum_grad)', 'in', 'zip(net_vars,', 'accum_grads):', 'zero', '=', 'tf.zeros(var.get_sha... | 374,755 |
Alexander-Parker/youtube_nlp | results.py | BulkWriteResult.upserted_count | upserted_count | The number of documents upserted. | [
"The",
"number",
"of",
"documents",
"upserted."
] | def upserted_count(self):
self._raise_if_unacknowledged('upserted_count')
return self.__bulk_api_result.get('nUpserted') | ['def', 'upserted_count(self):', "self._raise_if_unacknowledged('upserted_count')", 'return', "self.__bulk_api_result.get('nUpserted')"] | 970,622 |
csuhan/s2anet | fsaf_head.py | FSAFHead.xcycwh2xyxy | xcycwh2xyxy | Convert [xc yc w y] box format to [x1 y1 x2 y2] format. | [
"Convert",
"[xc",
"yc",
"w",
"y]",
"box",
"format",
"to",
"[x1",
"y1",
"x2",
"y2]",
"format."
] | def xcycwh2xyxy(self, xywh):
return torch.cat((xywh[:, 0:2] - 0.5 * xywh[:, 2:4], xywh[:, 0:2] + 0.5 * xywh[:, 2:4]), dim=1) | ['def', 'xcycwh2xyxy(self,', 'xywh):', 'return', 'torch.cat((xywh[:,', '0:2]', '-', '0.5', '*', 'xywh[:,', '2:4],', 'xywh[:,', '0:2]', '+', '0.5', '*', 'xywh[:,', '2:4]),', 'dim=1)'] | 828,646 |
instadeepai/jumanji | env_test.py | test_game_2048__step_action_mask | test_game_2048__step_action_mask | Verify that the action mask returned from `step` is correct. | [
"Verify",
"that",
"the",
"action",
"mask",
"returned",
"from",
"`step`",
"is",
"correct."
] | def test_game_2048__step_action_mask(game_2048: Game2048) -> None:
state = State(board=jnp.array([[0, 1, 2, 3], [3, 1, 2, 3], [1, 2, 3, 4], [4, 3, 2, 1]]), step_count=jnp.array(0), action_mask=jnp.array([True, False, True, True]), score=jnp.array(0), key=jax.random.PRNGKey(0))
action = jnp.array(3)
step_fn ... | ['def', 'test_game_2048__step_action_mask(game_2048:', 'Game2048)', '->', 'None:', 'state', '=', 'State(board=jnp.array([[0,', '1,', '2,', '3],', '[3,', '1,', '2,', '3],', '[1,', '2,', '3,', '4],', '[4,', '3,', '2,', '1]]),', 'step_count=jnp.array(0),', 'action_mask=jnp.array([True,', 'False,', 'True,', 'True]),', 'sco... | 593,999 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | em.py | EM.save | save | Saves centroids and assignments. | [
"Saves",
"centroids",
"and",
"assignments."
] | def save(self, path, layer):
torch.save(self.centroids, os.path.join(path, '{}_centroids.pth'.format(layer)))
torch.save(self.assignments, os.path.join(path, '{}_assignments.pth'.format(layer)))
torch.save(self.objective, os.path.join(path, '{}_objective.pth'.format(layer))) | ['def', 'save(self,', 'path,', 'layer):', 'torch.save(self.centroids,', 'os.path.join(path,', "'{}_centroids.pth'.format(layer)))", 'torch.save(self.assignments,', 'os.path.join(path,', "'{}_assignments.pth'.format(layer)))", 'torch.save(self.objective,', 'os.path.join(path,', "'{}_objective.pth'.format(layer)))"] | 104,007 |
lium-lst/nmtpy | cleanup.py | register_tmp_file | register_tmp_file | Add new temp file to global set. | [
"Add",
"new",
"temp",
"file",
"to",
"global",
"set."
] | def register_tmp_file(f):
temp_files.add(f) | ['def', 'register_tmp_file(f):', 'temp_files.add(f)'] | 294,422 |
arshpreetsingh/quantopian-machinelearning | test_compat.py | pytables_hdf5_file | pytables_hdf5_file | Use PyTables to create a simple HDF5 file. | [
"Use",
"PyTables",
"to",
"create",
"a",
"simple",
"HDF5",
"file."
] | def pytables_hdf5_file():
table_schema = {'c0': tables.Time64Col(pos=0), 'c1': tables.StringCol(5, pos=1), 'c2': tables.Int64Col(pos=2)}
t0 = 1561105000.0
testsamples = [{'c0': t0, 'c1': 'aaaaa', 'c2': 1}, {'c0': t0 + 1, 'c1': 'bbbbb', 'c2': 2}, {'c0': t0 + 2, 'c1': 'ccccc', 'c2': 10 ** 5}, {'c0': t0 + 3, '... | ['def', 'pytables_hdf5_file():', 'table_schema', '=', "{'c0':", 'tables.Time64Col(pos=0),', "'c1':", 'tables.StringCol(5,', 'pos=1),', "'c2':", 'tables.Int64Col(pos=2)}', 't0', '=', '1561105000.0', 'testsamples', '=', "[{'c0':", 't0,', "'c1':", "'aaaaa',", "'c2':", '1},', "{'c0':", 't0', '+', '1,', "'c1':", "'bbbbb',",... | 890,694 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | dataset.py | read32 | read32 | Read 4 bytes from bytestream as an unsigned 32-bit integer. | [
"Read",
"4",
"bytes",
"from",
"bytestream",
"as",
"an",
"unsigned",
"32-bit",
"integer."
] | def read32(bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | ['def', 'read32(bytestream):', 'dt', '=', "np.dtype(np.uint32).newbyteorder('>')", 'return', 'np.frombuffer(bytestream.read(4),', 'dtype=dt)[0]'] | 13,902 |
cedkoffeto/artificial-intelligence | testutils.py | fail_if_equal | fail_if_equal | Raises an assertion error if two items are equal. | [
"Raises",
"an",
"assertion",
"error",
"if",
"two",
"items",
"are",
"equal."
] | def fail_if_equal(actual, desired, err_msg=''):
if isinstance(desired, dict):
if not isinstance(actual, dict):
raise AssertionError(repr(type(actual)))
fail_if_equal(len(actual), len(desired), err_msg)
for (k, i) in desired.items():
if k not in actual:
... | ['def', 'fail_if_equal(actual,', 'desired,', "err_msg=''):", 'if', 'isinstance(desired,', 'dict):', 'if', 'not', 'isinstance(actual,', 'dict):', 'raise', 'AssertionError(repr(type(actual)))', 'fail_if_equal(len(actual),', 'len(desired),', 'err_msg)', 'for', '(k,', 'i)', 'in', 'desired.items():', 'if', 'k', 'not', 'in',... | 172,483 |
TonyLianLong/VAI-ReinforcementLearning | cmu_humanoid.py | CMUHumanoidPositionControlled.cmu_pose_to_actuation | cmu_pose_to_actuation | Creates the control signal corresponding a CMU mocap joints pose. | [
"Creates",
"the",
"control",
"signal",
"corresponding",
"a",
"CMU",
"mocap",
"joints",
"pose."
] | def cmu_pose_to_actuation(self, target_pose):
return (2 * target_pose[self.actuator_order] - self._offset) / self._scale | ['def', 'cmu_pose_to_actuation(self,', 'target_pose):', 'return', '(2', '*', 'target_pose[self.actuator_order]', '-', 'self._offset)', '/', 'self._scale'] | 439,970 |
triaquae/triaquae | defaultfilters.py | linebreaks_filter | linebreaks_filter | Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br />``) and a new line followed by a blank line becomes a paragraph break (``</p>``). | [
"Replaces",
"line",
"breaks",
"in",
"plain",
"text",
"with",
"appropriate",
"HTML;",
"a",
"single",
"newline",
"becomes",
"an",
"HTML",
"line",
"break",
"(``<br",
"/>``)",
"and",
"a",
"new",
"line",
"followed",
"by",
"a",
"blank",
"line",
"becomes",
"a",
"... | def linebreaks_filter(value, autoescape=None):
autoescape = autoescape and (not isinstance(value, SafeData))
return mark_safe(linebreaks(value, autoescape)) | ['def', 'linebreaks_filter(value,', 'autoescape=None):', 'autoescape', '=', 'autoescape', 'and', '(not', 'isinstance(value,', 'SafeData))', 'return', 'mark_safe(linebreaks(value,', 'autoescape))'] | 423,828 |
yinyunie/ScenePriors | test_points_alignment.py | TestCorrespondingPointsAlignment.random_rotation | random_rotation | Generates a batch of random `dim`-dimensional rotation matrices. | [
"Generates",
"a",
"batch",
"of",
"random",
"`dim`-dimensional",
"rotation",
"matrices."
] | def random_rotation(batch_size, dim, device=None):
if dim == 3:
R = rotation_conversions.random_rotations(batch_size, device=device)
else:
H = torch.randn(batch_size, dim, dim, dtype=torch.float32, device=device)
(U, _, V) = torch.svd(H)
E = torch.eye(dim, dtype=torch.float32, de... | ['def', 'random_rotation(batch_size,', 'dim,', 'device=None):', 'if', 'dim', '==', '3:', 'R', '=', 'rotation_conversions.random_rotations(batch_size,', 'device=device)', 'else:', 'H', '=', 'torch.randn(batch_size,', 'dim,', 'dim,', 'dtype=torch.float32,', 'device=device)', '(U,', '_,', 'V)', '=', 'torch.svd(H)', 'E', '... | 330,064 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_lobpcg.py | test_maxit_None | test_maxit_None | Check lobpcg if maxit=None runs 20 iterations (the default) by checking the size of the iteration history output, which should be the number of iterations plus 2 (initial and final values). | [
"Check",
"lobpcg",
"if",
"maxit=None",
"runs",
"20",
"iterations",
"(the",
"default)",
"by",
"checking",
"the",
"size",
"of",
"the",
"iteration",
"history",
"output,",
"which",
"should",
"be",
"the",
"number",
"of",
"iterations",
"plus",
"2",
"(initial",
"and"... | def test_maxit_None():
np.random.seed(1566950023)
n = 50
m = 4
vals = -np.arange(1, n + 1)
A = diags([vals], [0], (n, n))
A = A.astype(np.float32)
X = np.random.randn(n, m)
X = X.astype(np.float32)
(_, _, l_h) = lobpcg(A, X, tol=1e-08, maxiter=20, retLambdaHistory=True)
assert_al... | ['def', 'test_maxit_None():', 'np.random.seed(1566950023)', 'n', '=', '50', 'm', '=', '4', 'vals', '=', '-np.arange(1,', 'n', '+', '1)', 'A', '=', 'diags([vals],', '[0],', '(n,', 'n))', 'A', '=', 'A.astype(np.float32)', 'X', '=', 'np.random.randn(n,', 'm)', 'X', '=', 'X.astype(np.float32)', '(_,', '_,', 'l_h)', '=', 'l... | 100,190 |
KalleHallden/InstaAutomator | _tifffile.py | read_numpy | read_numpy | Read tag data from file and return as numpy array. | [
"Read",
"tag",
"data",
"from",
"file",
"and",
"return",
"as",
"numpy",
"array."
] | def read_numpy(fh, byteorder, dtype, count):
dtype = 'b' if dtype[-1] == 's' else byteorder + dtype[-1]
return fh.read_array(dtype, count) | ['def', 'read_numpy(fh,', 'byteorder,', 'dtype,', 'count):', 'dtype', '=', "'b'", 'if', 'dtype[-1]', '==', "'s'", 'else', 'byteorder', '+', 'dtype[-1]', 'return', 'fh.read_array(dtype,', 'count)'] | 229,997 |
vanzytay/KDD2018_MPCN | utilities.py | exact_match_feats | exact_match_feats | builds exact match features Pass in tokens. | [
"builds",
"exact",
"match",
"features",
"Pass",
"in",
"tokens."
] | def exact_match_feats(q1, q2, stem=False, lower=False):
if lower:
q1 = [x.lower() for x in q1]
q2 = [x.lower() for x in q2]
if stem:
q1 = [porter_stemmer.stem(x) for x in q1]
q2 = [porter_stemmer.stem(x) for x in q2]
a_em = []
b_em = []
for a in q1:
check_b = ... | ['def', 'exact_match_feats(q1,', 'q2,', 'stem=False,', 'lower=False):', 'if', 'lower:', 'q1', '=', '[x.lower()', 'for', 'x', 'in', 'q1]', 'q2', '=', '[x.lower()', 'for', 'x', 'in', 'q2]', 'if', 'stem:', 'q1', '=', '[porter_stemmer.stem(x)', 'for', 'x', 'in', 'q1]', 'q2', '=', '[porter_stemmer.stem(x)', 'for', 'x', 'in'... | 247,634 |
brendanm12345/imageSequenceGeneration | scheduling_ddpm.py | DDPMScheduler.scale_model_input | scale_model_input | Ensures interchangeability with schedulers that need to scale the denoising model input depending on the current timestep. | [
"Ensures",
"interchangeability",
"with",
"schedulers",
"that",
"need",
"to",
"scale",
"the",
"denoising",
"model",
"input",
"depending",
"on",
"the",
"current",
"timestep."
] | def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int]=None) -> torch.FloatTensor:
return sample | ['def', 'scale_model_input(self,', 'sample:', 'torch.FloatTensor,', 'timestep:', 'Optional[int]=None)', '->', 'torch.FloatTensor:', 'return', 'sample'] | 599,775 |
neokarn/computer_vision | functional.py | pad | pad | Pad the given PIL Image on all sides with the given "pad" value. | [
"Pad",
"the",
"given",
"PIL",
"Image",
"on",
"all",
"sides",
"with",
"the",
"given",
"\"pad\"",
"value."
] | def pad(img, padding, fill=0):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
if not isinstance(padding, (numbers.Number, tuple)):
raise TypeError('Got inappropriate padding arg')
if not isinstance(fill, (numbers.Number, str, tuple)):
... | ['def', 'pad(img,', 'padding,', 'fill=0):', 'if', 'not', '_is_pil_image(img):', 'raise', "TypeError('img", 'should', 'be', 'PIL', 'Image.', 'Got', "{}'.format(type(img)))", 'if', 'not', 'isinstance(padding,', '(numbers.Number,', 'tuple)):', 'raise', "TypeError('Got", 'inappropriate', 'padding', "arg')", 'if', 'not', 'i... | 501,074 |
AndrewYinLi/lstm-neural-network-spam-filter | nkjp.py | NKJPCorpusReader.raw | raw | Returns words in specified fileids. | [
"Returns",
"words",
"in",
"specified",
"fileids."
] | def raw(self, fileids=None, **kwargs):
return concat([self._view(self.add_root(fileid), mode=NKJPCorpusReader.RAW_MODE, **kwargs).handle_query() for fileid in fileids]) | ['def', 'raw(self,', 'fileids=None,', '**kwargs):', 'return', 'concat([self._view(self.add_root(fileid),', 'mode=NKJPCorpusReader.RAW_MODE,', '**kwargs).handle_query()', 'for', 'fileid', 'in', 'fileids])'] | 217,709 |
omarabid59/TensorflowDeepSortTracking | track.py | Track.is_confirmed | is_confirmed | Returns True if this track is confirmed. | [
"Returns",
"True",
"if",
"this",
"track",
"is",
"confirmed."
] | def is_confirmed(self):
return self.state == TrackState.Confirmed | ['def', 'is_confirmed(self):', 'return', 'self.state', '==', 'TrackState.Confirmed'] | 922,465 |
sunishsheth2009/ChatterBot | lovins.py | stem | stem | Returns the stemmed version of the argument string. | [
"Returns",
"the",
"stemmed",
"version",
"of",
"the",
"argument",
"string."
] | def stem(word):
return fix_ending(remove_ending(word)) | ['def', 'stem(word):', 'return', 'fix_ending(remove_ending(word))'] | 526,777 |
tobegit3hub/deep_image_model | docs.py | write_libraries | write_libraries | Write a list of libraries to disk. | [
"Write",
"a",
"list",
"of",
"libraries",
"to",
"disk."
] | def write_libraries(output_dir, libraries):
files = [open(os.path.join(output_dir, k), 'w') for (k, _) in libraries]
indiv_dir = os.path.join(output_dir, _indiv_dir)
if not os.path.exists(indiv_dir):
os.makedirs(indiv_dir)
for i in range(0, _num_subdirs):
subdir = os.path.join(indiv_dir,... | ['def', 'write_libraries(output_dir,', 'libraries):', 'files', '=', '[open(os.path.join(output_dir,', 'k),', "'w')", 'for', '(k,', '_)', 'in', 'libraries]', 'indiv_dir', '=', 'os.path.join(output_dir,', '_indiv_dir)', 'if', 'not', 'os.path.exists(indiv_dir):', 'os.makedirs(indiv_dir)', 'for', 'i', 'in', 'range(0,', '_n... | 182,460 |
junjie18/CMT | cmt_transformer.py | CmtImageTransformer.forward | forward | Forward function for `Transformer`. | [
"Forward",
"function",
"for",
"`Transformer`."
] | def forward(self, x_img, query_embed, rv_pos_embed, attn_masks=None, reg_branch=None, bs=2):
memory = rearrange(x_img, '(bs v) c h w -> (v h w) bs c', bs=bs)
pos_embed = rearrange(rv_pos_embed, '(bs v) h w c -> (v h w) bs c', bs=bs)
query_embed = query_embed.transpose(0, 1)
mask = memory.new_zeros(bs, m... | ['def', 'forward(self,', 'x_img,', 'query_embed,', 'rv_pos_embed,', 'attn_masks=None,', 'reg_branch=None,', 'bs=2):', 'memory', '=', 'rearrange(x_img,', "'(bs", 'v)', 'c', 'h', 'w', '->', '(v', 'h', 'w)', 'bs', "c',", 'bs=bs)', 'pos_embed', '=', 'rearrange(rv_pos_embed,', "'(bs", 'v)', 'h', 'w', 'c', '->', '(v', 'h', '... | 492,136 |
eddylau328/fyp-artificial-intelligence-ac-control-device | sysconfig.py | get_makefile_filename | get_makefile_filename | Return the path of the Makefile. | [
"Return",
"the",
"path",
"of",
"the",
"Makefile."
] | def get_makefile_filename():
if _PYTHON_BUILD:
return os.path.join(_PROJECT_BASE, 'Makefile')
if hasattr(sys, 'abiflags'):
config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
else:
config_dir_name = 'config'
return os.path.join(get_path('stdlib'), config_dir_name,... | ['def', 'get_makefile_filename():', 'if', '_PYTHON_BUILD:', 'return', 'os.path.join(_PROJECT_BASE,', "'Makefile')", 'if', 'hasattr(sys,', "'abiflags'):", 'config_dir_name', '=', "'config-%s%s'", '%', '(_PY_VERSION_SHORT,', 'sys.abiflags)', 'else:', 'config_dir_name', '=', "'config'", 'return', "os.path.join(get_path('s... | 198,348 |
nasimrahaman/antipasti-tf | core.py | TFSession.reset | reset | Resets the internal Antipasti Tensorflow Session. | [
"Resets",
"the",
"internal",
"Antipasti",
"Tensorflow",
"Session."
] | def reset(self):
self._antipasti_session = None | ['def', 'reset(self):', 'self._antipasti_session', '=', 'None'] | 33,495 |
pykale/pykale | multiomics_datasets.py | SparseMultiomicsDataset.extend_data | extend_data | Extend data object by adding additional attributes. | [
"Extend",
"data",
"object",
"by",
"adding",
"additional",
"attributes."
] | def extend_data(self, data: Data) -> Data:
train_labels = torch.argmax(data.y[data.train_idx], dim=1)
train_sample_weight = self._get_sample_weight(train_labels)
data.train_sample_weight = train_sample_weight
(edge_index_train, edge_weight_train) = self._get_adjacency_info(data.x[data.train_idx], train=... | ['def', 'extend_data(self,', 'data:', 'Data)', '->', 'Data:', 'train_labels', '=', 'torch.argmax(data.y[data.train_idx],', 'dim=1)', 'train_sample_weight', '=', 'self._get_sample_weight(train_labels)', 'data.train_sample_weight', '=', 'train_sample_weight', '(edge_index_train,', 'edge_weight_train)', '=', 'self._get_ad... | 819,694 |
kubeflow/pipelines | component_compiler.py | SageMakerComponentCompiler.compile | compile | Compiles a defined component into its component YAML specification. | [
"Compiles",
"a",
"defined",
"component",
"into",
"its",
"component",
"YAML",
"specification."
] | def compile(component_def: Type[SageMakerComponent], component_file_path: str, output_path: str, component_image_uri: str, component_image_tag: str):
SageMakerComponentCompiler._create_and_write_component(component_def, component_file_path, output_path, component_image_uri, component_image_tag) | ['def', 'compile(component_def:', 'Type[SageMakerComponent],', 'component_file_path:', 'str,', 'output_path:', 'str,', 'component_image_uri:', 'str,', 'component_image_tag:', 'str):', 'SageMakerComponentCompiler._create_and_write_component(component_def,', 'component_file_path,', 'output_path,', 'component_image_uri,',... | 770,660 |
intel/neural-compressor | base_dataloader.py | BaseDataLoader.batch | batch | Set batch size for dataloader. | [
"Set",
"batch",
"size",
"for",
"dataloader."
] | def batch(self, batch_size, last_batch=None):
self._batch_size = batch_size
if last_batch is not None:
self.last_batch = last_batch
self.dataloader = self._generate_dataloader(self.dataset, batch_size, self.last_batch, self.collate_fn, self.sampler, self.batch_sampler, self.num_workers, self.pin_mem... | ['def', 'batch(self,', 'batch_size,', 'last_batch=None):', 'self._batch_size', '=', 'batch_size', 'if', 'last_batch', 'is', 'not', 'None:', 'self.last_batch', '=', 'last_batch', 'self.dataloader', '=', 'self._generate_dataloader(self.dataset,', 'batch_size,', 'self.last_batch,', 'self.collate_fn,', 'self.sampler,', 'se... | 738,246 |
tianyoul/AI-Robotics-ComputerVision | MultiCamShift.py | MultiCamShift.run | run | Will run the tracking program on the video from vid_src. | [
"Will",
"run",
"the",
"tracking",
"program",
"on",
"the",
"video",
"from",
"vid_src."
] | def run(self):
running = True
cv2.namedWindow('Drone Camera')
while running:
image = self.drone.image.copy()
(red, green, blue) = cv2.split(image)
image = cv2.merge((blue, green, red))
self.currFrame = image
x = cv2.waitKey(33)
if x != -1:
print('U... | ['def', 'run(self):', 'running', '=', 'True', "cv2.namedWindow('Drone", "Camera')", 'while', 'running:', 'image', '=', 'self.drone.image.copy()', '(red,', 'green,', 'blue)', '=', 'cv2.split(image)', 'image', '=', 'cv2.merge((blue,', 'green,', 'red))', 'self.currFrame', '=', 'image', 'x', '=', 'cv2.waitKey(33)', 'if', '... | 412,089 |
ChandlerBang/awesome-self-supervised-gnn | scholar.py | SearchScholarQuery.set_author | set_author | Sets names that must be on the result's author list. | [
"Sets",
"names",
"that",
"must",
"be",
"on",
"the",
"result's",
"author",
"list."
] | def set_author(self, author):
self.author = author | ['def', 'set_author(self,', 'author):', 'self.author', '=', 'author'] | 93,861 |
rifqind/Agent-Programs-3KS1 | buffer.py | Buffer.start_history_lines_completion | start_history_lines_completion | Start a completion based on all the other lines in the document and the history. | [
"Start",
"a",
"completion",
"based",
"on",
"all",
"the",
"other",
"lines",
"in",
"the",
"document",
"and",
"the",
"history."
] | def start_history_lines_completion(self):
found_completions = set()
completions = []
current_line = self.document.current_line_before_cursor.lstrip()
for (i, string) in enumerate(self._working_lines):
for (j, l) in enumerate(string.split('\n')):
l = l.strip()
if l and l.s... | ['def', 'start_history_lines_completion(self):', 'found_completions', '=', 'set()', 'completions', '=', '[]', 'current_line', '=', 'self.document.current_line_before_cursor.lstrip()', 'for', '(i,', 'string)', 'in', 'enumerate(self._working_lines):', 'for', '(j,', 'l)', 'in', "enumerate(string.split('\\n')):", 'l', '=',... | 44,916 |
enuguru/artificial_intelligence_and_machine_learning | reading.py | IndexReader.iter_docs | iter_docs | Yields a series of ``(docnum, stored_fields_dict)`` tuples for the undeleted documents in the reader. | [
"Yields",
"a",
"series",
"of",
"``(docnum,",
"stored_fields_dict)``",
"tuples",
"for",
"the",
"undeleted",
"documents",
"in",
"the",
"reader."
] | def iter_docs(self):
for docnum in self.all_doc_ids():
yield (docnum, self.stored_fields(docnum)) | ['def', 'iter_docs(self):', 'for', 'docnum', 'in', 'self.all_doc_ids():', 'yield', '(docnum,', 'self.stored_fields(docnum))'] | 162,111 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | iris_data.py | load_data | load_data | Returns the iris dataset as (train_x, train_y), (test_x, test_y). | [
"Returns",
"the",
"iris",
"dataset",
"as",
"(train_x,",
"train_y),",
"(test_x,",
"test_y)."
] | def load_data(y_name='Species'):
(train_path, test_path) = maybe_download()
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
(train_x, train_y) = (train, train.pop(y_name))
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
(test_x, test_y) = (test, test.pop(y_name))
... | ['def', "load_data(y_name='Species'):", '(train_path,', 'test_path)', '=', 'maybe_download()', 'train', '=', 'pd.read_csv(train_path,', 'names=CSV_COLUMN_NAMES,', 'header=0)', '(train_x,', 'train_y)', '=', '(train,', 'train.pop(y_name))', 'test', '=', 'pd.read_csv(test_path,', 'names=CSV_COLUMN_NAMES,', 'header=0)', '(... | 30,069 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | events.py | AbstractEventLoop.is_running | is_running | Return whether the event loop is currently running. | [
"Return",
"whether",
"the",
"event",
"loop",
"is",
"currently",
"running."
] | def is_running(self):
raise NotImplementedError | ['def', 'is_running(self):', 'raise', 'NotImplementedError'] | 430,143 |
annieyan/PreprocessSatelliteImagery- | rectangle.py | Rectangle.intersect_over_union | intersect_over_union | Returns the intersection over union ratio of this and other rectangle. | [
"Returns",
"the",
"intersection",
"over",
"union",
"ratio",
"of",
"this",
"and",
"other",
"rectangle."
] | def intersect_over_union(self, other):
if not self.intersects(other):
return 0.0
intersect_rect = self.intersect(other)
if intersect_rect.is_empty():
return 0.0
if self.area() == 0 or other.area() == 0:
return 0.0
return intersect_rect.area() / (self.area() + other.area() - i... | ['def', 'intersect_over_union(self,', 'other):', 'if', 'not', 'self.intersects(other):', 'return', '0.0', 'intersect_rect', '=', 'self.intersect(other)', 'if', 'intersect_rect.is_empty():', 'return', '0.0', 'if', 'self.area()', '==', '0', 'or', 'other.area()', '==', '0:', 'return', '0.0', 'return', 'intersect_rect.area... | 824,439 |
suarez12138/AI-Reversi_IMP_TextDichotomy | predictor.py | TreePredictor.get_n_leaf_nodes | get_n_leaf_nodes | Return number of leaves. | [
"Return",
"number",
"of",
"leaves."
] | def get_n_leaf_nodes(self):
return int(self.nodes['is_leaf'].sum()) | ['def', 'get_n_leaf_nodes(self):', 'return', "int(self.nodes['is_leaf'].sum())"] | 101,198 |
coderIlluminatus/Artificial-Intelligence | utils.py | multimap_items | multimap_items | Yield all (key, val) pairs stored in the multimap. | [
"Yield",
"all",
"(key,",
"val)",
"pairs",
"stored",
"in",
"the",
"multimap."
] | def multimap_items(mmap):
for (key, vals) in mmap.items():
for val in vals:
yield (key, val) | ['def', 'multimap_items(mmap):', 'for', '(key,', 'vals)', 'in', 'mmap.items():', 'for', 'val', 'in', 'vals:', 'yield', '(key,', 'val)'] | 119,444 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_list.py | data | data | Length-100 ListArray for semantics test. | [
"Length-100",
"ListArray",
"for",
"semantics",
"test."
] | def data():
data = make_data()
while len(data[0]) == len(data[1]):
data = make_data()
return ListArray(data) | ['def', 'data():', 'data', '=', 'make_data()', 'while', 'len(data[0])', '==', 'len(data[1]):', 'data', '=', 'make_data()', 'return', 'ListArray(data)'] | 453,713 |
netket/netket | cubic.py | T | T | Rotational symmetries of a tetrahedron with vertices (1,1,1), (1,-1,-1), (-1,1,-1), (-1,-1,1). | [
"Rotational",
"symmetries",
"of",
"a",
"tetrahedron",
"with",
"vertices",
"(1,1,1),",
"(1,-1,-1),",
"(-1,1,-1),",
"(-1,-1,1)."
] | def T() -> PointGroup:
return PointGroup([Identity(), _rotation(120, [1, 1, 1]), _rotation(120, [1, -1, -1]), _rotation(120, [-1, 1, -1]), _rotation(120, [-1, -1, 1]), _rotation(-120, [1, 1, 1]), _rotation(-120, [1, -1, -1]), _rotation(-120, [-1, 1, -1]), _rotation(-120, [-1, -1, 1]), _rotation(180, [0, 0, 1]), _ro... | ['def', 'T()', '->', 'PointGroup:', 'return', 'PointGroup([Identity(),', '_rotation(120,', '[1,', '1,', '1]),', '_rotation(120,', '[1,', '-1,', '-1]),', '_rotation(120,', '[-1,', '1,', '-1]),', '_rotation(120,', '[-1,', '-1,', '1]),', '_rotation(-120,', '[1,', '1,', '1]),', '_rotation(-120,', '[1,', '-1,', '-1]),', '_r... | 736,276 |
microsoft/maro | grass_executor.py | GrassExecutor.template | template | Export deployment template of grass mode. | [
"Export",
"deployment",
"template",
"of",
"grass",
"mode."
] | def template(export_path: str) -> None:
command = f'cp {GrassPaths.MARO_GRASS_LIB}/deployments/external/* {export_path}'
_ = Subprocess.run(command=command) | ['def', 'template(export_path:', 'str)', '->', 'None:', 'command', '=', "f'cp", '{GrassPaths.MARO_GRASS_LIB}/deployments/external/*', "{export_path}'", '_', '=', 'Subprocess.run(command=command)'] | 628,170 |
zihuitang/medical_AI_platform | ccompiler.py | CCompiler.add_runtime_library_dir | add_runtime_library_dir | Add 'dir' to the list of directories that will be searched for shared libraries at runtime. | [
"Add",
"'dir'",
"to",
"the",
"list",
"of",
"directories",
"that",
"will",
"be",
"searched",
"for",
"shared",
"libraries",
"at",
"runtime."
] | def add_runtime_library_dir(self, dir):
self.runtime_library_dirs.append(dir) | ['def', 'add_runtime_library_dir(self,', 'dir):', 'self.runtime_library_dirs.append(dir)'] | 282,181 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | inference_wrapper_base.py | InferenceWrapperBase.inference_step | inference_step | Runs one step of inference. | [
"Runs",
"one",
"step",
"of",
"inference."
] | def inference_step(self, sess, input_feed, state_feed):
tf.logging.fatal('Please implement inference_step in subclass') | ['def', 'inference_step(self,', 'sess,', 'input_feed,', 'state_feed):', "tf.logging.fatal('Please", 'implement', 'inference_step', 'in', "subclass')"] | 48,803 |
cpnota/autonomous-learning-library | state.py | State.as_input | as_input | Gets the value for a given key and reshapes it to a batch-style tensor suitable as input to a pytorch module. | [
"Gets",
"the",
"value",
"for",
"a",
"given",
"key",
"and",
"reshapes",
"it",
"to",
"a",
"batch-style",
"tensor",
"suitable",
"as",
"input",
"to",
"a",
"pytorch",
"module."
] | def as_input(self, key):
return self[key].unsqueeze(0) | ['def', 'as_input(self,', 'key):', 'return', 'self[key].unsqueeze(0)'] | 93,643 |
Ruturaj123/Flowchart-Detection | curses_ui_test.py | CursesTest.testRegexSearchFromCommandHistory | testRegexSearchFromCommandHistory | Test regex search commands are recorded in command history. | [
"Test",
"regex",
"search",
"commands",
"are",
"recorded",
"in",
"command",
"history."
] | def testRegexSearchFromCommandHistory(self):
ui = MockCursesUI(40, 80, command_sequence=[string_to_codes('babble -n 3\n'), string_to_codes('/(b|r)\n'), string_to_codes('babble -n 4\n'), [curses.KEY_UP], [curses.KEY_UP], string_to_codes('\n'), self._EXIT])
ui.register_command_handler('babble', self._babble, 'bab... | ['def', 'testRegexSearchFromCommandHistory(self):', 'ui', '=', 'MockCursesUI(40,', '80,', "command_sequence=[string_to_codes('babble", '-n', "3\\n'),", "string_to_codes('/(b|r)\\n'),", "string_to_codes('babble", '-n', "4\\n'),", '[curses.KEY_UP],', '[curses.KEY_UP],', "string_to_codes('\\n'),", 'self._EXIT])', "ui.regi... | 605,044 |
deepmind/dm_control | viewer.py | FreeCameraController.on_move | on_move | Translates mouse moves onto camera movements. | [
"Translates",
"mouse",
"moves",
"onto",
"camera",
"movements."
] | def on_move(self, position, translation):
del position
if self._action.in_progress:
viewport_offset = self._viewport.screen_to_viewport(translation)
self._camera.move(self._action.watermark, viewport_offset) | ['def', 'on_move(self,', 'position,', 'translation):', 'del', 'position', 'if', 'self._action.in_progress:', 'viewport_offset', '=', 'self._viewport.screen_to_viewport(translation)', 'self._camera.move(self._action.watermark,', 'viewport_offset)'] | 165,733 |
ToruOwO/marl-ae-comm | config.py | freeze | freeze | Freeze configuration and save to file (optional). | [
"Freeze",
"configuration",
"and",
"save",
"to",
"file",
"(optional)."
] | def freeze(config, save_file=False):
config.freeze()
if save_file:
if not os.path.isdir(config.run_dir):
os.makedirs(config.run_dir)
save_dir = os.path.join(config.run_dir, config.exp_name)
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
with open(os... | ['def', 'freeze(config,', 'save_file=False):', 'config.freeze()', 'if', 'save_file:', 'if', 'not', 'os.path.isdir(config.run_dir):', 'os.makedirs(config.run_dir)', 'save_dir', '=', 'os.path.join(config.run_dir,', 'config.exp_name)', 'if', 'not', 'os.path.isdir(save_dir):', 'os.makedirs(save_dir)', 'with', 'open(os.path... | 627,849 |
Megvii-BaseDetection/cvpods | functions.py | polyToBox | polyToBox | Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. | [
"Converts",
"a",
"polygon",
"in",
"COCO",
"lists",
"of",
"lists",
"format",
"to",
"a",
"bounding",
"box",
"in",
"[x,",
"y,",
"w,",
"h]."
] | def polyToBox(poly: list):
xmin = 10000000000.0
xmax = -10000000000.0
ymin = 10000000000.0
ymax = -10000000000.0
for poly_comp in poly:
for i in range(len(poly_comp) // 2):
x = poly_comp[2 * i + 0]
y = poly_comp[2 * i + 1]
xmin = min(x, xmin)
x... | ['def', 'polyToBox(poly:', 'list):', 'xmin', '=', '10000000000.0', 'xmax', '=', '-10000000000.0', 'ymin', '=', '10000000000.0', 'ymax', '=', '-10000000000.0', 'for', 'poly_comp', 'in', 'poly:', 'for', 'i', 'in', 'range(len(poly_comp)', '//', '2):', 'x', '=', 'poly_comp[2', '*', 'i', '+', '0]', 'y', '=', 'poly_comp[2', ... | 510,824 |
ldkong1205/LaserMix | box_np_ops.py | box2d_to_corner_jit | box2d_to_corner_jit | Convert box2d to corner. | [
"Convert",
"box2d",
"to",
"corner."
] | def box2d_to_corner_jit(boxes):
num_box = boxes.shape[0]
corners_norm = np.zeros((4, 2), dtype=boxes.dtype)
corners_norm[1, 1] = 1.0
corners_norm[2] = 1.0
corners_norm[3, 0] = 1.0
corners_norm -= np.array([0.5, 0.5], dtype=boxes.dtype)
corners = boxes.reshape(num_box, 1, 5)[:, :, 2:4] * corn... | ['def', 'box2d_to_corner_jit(boxes):', 'num_box', '=', 'boxes.shape[0]', 'corners_norm', '=', 'np.zeros((4,', '2),', 'dtype=boxes.dtype)', 'corners_norm[1,', '1]', '=', '1.0', 'corners_norm[2]', '=', '1.0', 'corners_norm[3,', '0]', '=', '1.0', 'corners_norm', '-=', 'np.array([0.5,', '0.5],', 'dtype=boxes.dtype)', 'corn... | 624,401 |
rudranil723/mini-main | mace.py | test_transform_output | test_transform_output | Transform the model into various Mace4 ``interpformat`` formats. | [
"Transform",
"the",
"model",
"into",
"various",
"Mace4",
"``interpformat``",
"formats."
] | def test_transform_output(argument_pair):
g = Expression.fromstring(argument_pair[0])
alist = [lp.parse(a) for a in argument_pair[1]]
m = MaceCommand(g, assumptions=alist)
m.build_model()
for a in alist:
print(' %s' % a)
print('|- %s: %s\n' % (g, m.build_model()))
for format in ['s... | ['def', 'test_transform_output(argument_pair):', 'g', '=', 'Expression.fromstring(argument_pair[0])', 'alist', '=', '[lp.parse(a)', 'for', 'a', 'in', 'argument_pair[1]]', 'm', '=', 'MaceCommand(g,', 'assumptions=alist)', 'm.build_model()', 'for', 'a', 'in', 'alist:', "print('", "%s'", '%', 'a)', "print('|-", '%s:', "%s... | 321,291 |
huaifeng1993/DFANet | scheduler.py | CosineWithRestarts.get_lr | get_lr | Get updated learning rate. | [
"Get",
"updated",
"learning",
"rate."
] | def get_lr(self):
if not self._initialized:
self._initialized = True
return self.base_lrs
step = self.last_epoch + 1
self._cycle_counter = step - self._last_restart
lrs = [self.eta_min + (lr - self.eta_min) / 2 * (np.cos(np.pi * (self._cycle_counter % self._updated_cycle_len) / self._upd... | ['def', 'get_lr(self):', 'if', 'not', 'self._initialized:', 'self._initialized', '=', 'True', 'return', 'self.base_lrs', 'step', '=', 'self.last_epoch', '+', '1', 'self._cycle_counter', '=', 'step', '-', 'self._last_restart', 'lrs', '=', '[self.eta_min', '+', '(lr', '-', 'self.eta_min)', '/', '2', '*', '(np.cos(np.pi',... | 550,048 |
greydanus/pythonic_ocr | core.py | Locale.get_script_name | get_script_name | Return the script name in the given locale. | [
"Return",
"the",
"script",
"name",
"in",
"the",
"given",
"locale."
] | def get_script_name(self, locale=None):
if locale is None:
locale = self
locale = Locale.parse(locale)
return locale.scripts.get(self.script) | ['def', 'get_script_name(self,', 'locale=None):', 'if', 'locale', 'is', 'None:', 'locale', '=', 'self', 'locale', '=', 'Locale.parse(locale)', 'return', 'locale.scripts.get(self.script)'] | 298,646 |
open-mmlab/mmsegmentation | class_names.py | cocostuff_palette | cocostuff_palette | CocoStuff palette for external use. | [
"CocoStuff",
"palette",
"for",
"external",
"use."
] | def cocostuff_palette():
return [[0, 192, 64], [0, 192, 64], [0, 64, 96], [128, 192, 192], [0, 64, 64], [0, 192, 224], [0, 192, 192], [128, 192, 64], [0, 192, 96], [128, 192, 64], [128, 32, 192], [0, 0, 224], [0, 0, 64], [0, 160, 192], [128, 0, 96], [128, 0, 192], [0, 32, 192], [128, 128, 224], [0, 0, 192], [128, 1... | ['def', 'cocostuff_palette():', 'return', '[[0,', '192,', '64],', '[0,', '192,', '64],', '[0,', '64,', '96],', '[128,', '192,', '192],', '[0,', '64,', '64],', '[0,', '192,', '224],', '[0,', '192,', '192],', '[128,', '192,', '64],', '[0,', '192,', '96],', '[128,', '192,', '64],', '[128,', '32,', '192],', '[0,', '0,', '2... | 625,508 |
imoscovitz/wittgenstein | base.py | Ruleset.covers | covers | Returns instances covered by the Ruleset. | [
"Returns",
"instances",
"covered",
"by",
"the",
"Ruleset."
] | def covers(self, df):
if not self.rules:
return df
else:
covered = self.rules[0].covers(df).copy()
for rule in self.rules[1:]:
covered = covered.append(rule.covers(df))
covered = covered.drop_duplicates()
return covered | ['def', 'covers(self,', 'df):', 'if', 'not', 'self.rules:', 'return', 'df', 'else:', 'covered', '=', 'self.rules[0].covers(df).copy()', 'for', 'rule', 'in', 'self.rules[1:]:', 'covered', '=', 'covered.append(rule.covers(df))', 'covered', '=', 'covered.drop_duplicates()', 'return', 'covered'] | 959,824 |
SajalGoel/Natural-Language-Processing | embedrank.py | EmbedRank.candidate_weighting | candidate_weighting | Candidate weighting function using distance to document. | [
"Candidate",
"weighting",
"function",
"using",
"distance",
"to",
"document."
] | def candidate_weighting(self, l=1, lower=False):
doc = ' '.join((w.lower() if lower else w for s in self.sentences for (i, w) in enumerate(s.words) if s.pos[i] in self._pos))
doc_embed = self._embedding_model.embed_sentence(doc)
cand_name = list(self.candidates.keys())
cand = (self.candidates[k] for k i... | ['def', 'candidate_weighting(self,', 'l=1,', 'lower=False):', 'doc', '=', "'", "'.join((w.lower()", 'if', 'lower', 'else', 'w', 'for', 's', 'in', 'self.sentences', 'for', '(i,', 'w)', 'in', 'enumerate(s.words)', 'if', 's.pos[i]', 'in', 'self._pos))', 'doc_embed', '=', 'self._embedding_model.embed_sentence(doc)', 'cand_... | 661,685 |
afandi354/ComputerVision | ar_teapot.py | draw_teapot | draw_teapot | Draw a red teapot at the origin. | [
"Draw",
"a",
"red",
"teapot",
"at",
"the",
"origin."
] | def draw_teapot(size):
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_DEPTH_TEST)
glClear(GL_DEPTH_BUFFER_BIT)
glMaterialfv(GL_FRONT, GL_AMBIENT, [0, 0, 0, 0])
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.5, 0.0, 0.0, 0.0])
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.7, 0.6, 0.6, 0.0])
glMate... | ['def', 'draw_teapot(size):', 'glEnable(GL_LIGHTING)', 'glEnable(GL_LIGHT0)', 'glEnable(GL_DEPTH_TEST)', 'glClear(GL_DEPTH_BUFFER_BIT)', 'glMaterialfv(GL_FRONT,', 'GL_AMBIENT,', '[0,', '0,', '0,', '0])', 'glMaterialfv(GL_FRONT,', 'GL_DIFFUSE,', '[0.5,', '0.0,', '0.0,', '0.0])', 'glMaterialfv(GL_FRONT,', 'GL_SPECULAR,',... | 471,167 |
rldotai/rl-algorithms | lstd.py | LSTD.theta | theta | Compute the weight vector via `A^{-1} b`. | [
"Compute",
"the",
"weight",
"vector",
"via",
"`A^{-1}",
"b`."
] | def theta(self):
_theta = np.dot(np.linalg.pinv(self.A), self.b)
return _theta | ['def', 'theta(self):', '_theta', '=', 'np.dot(np.linalg.pinv(self.A),', 'self.b)', 'return', '_theta'] | 841,692 |
tensortrade-org/tensortrade | base.py | Identifiable.id | id | Sets the identifier for the object Parameters ---------- identifier : str The identifier to set for the object. | [
"Sets",
"the",
"identifier",
"for",
"the",
"object",
"Parameters",
"----------",
"identifier",
":",
"str",
"The",
"identifier",
"to",
"set",
"for",
"the",
"object."
] | def id(self, identifier: str) -> None:
self._id = identifier | ['def', 'id(self,', 'identifier:', 'str)', '->', 'None:', 'self._id', '=', 'identifier'] | 366,663 |
gunthercox/ChatterBot | table.py | Table.bind | bind | Add a binding to this table's main frame that will call ``func`` in response to the event sequence. | [
"Add",
"a",
"binding",
"to",
"this",
"table's",
"main",
"frame",
"that",
"will",
"call",
"``func``",
"in",
"response",
"to",
"the",
"event",
"sequence."
] | def bind(self, sequence=None, func=None, add=None):
self._mlb.bind(sequence, func, add) | ['def', 'bind(self,', 'sequence=None,', 'func=None,', 'add=None):', 'self._mlb.bind(sequence,', 'func,', 'add)'] | 530,216 |
chinmayjog13/Computer-Vision | util_tf.py | resize_image | resize_image | Resize an image and bounding boxes. | [
"Resize",
"an",
"image",
"and",
"bounding",
"boxes."
] | def resize_image(image, size, method=tf.image.ResizeMethod.BILINEAR, align_corners=False):
with tf.name_scope('resize_image'):
(height, width, channels) = tensor_shape(image)
image = tf.expand_dims(image, 0)
image = tf.image.resize_images(image, size, method, align_corners)
image = t... | ['def', 'resize_image(image,', 'size,', 'method=tf.image.ResizeMethod.BILINEAR,', 'align_corners=False):', 'with', "tf.name_scope('resize_image'):", '(height,', 'width,', 'channels)', '=', 'tensor_shape(image)', 'image', '=', 'tf.expand_dims(image,', '0)', 'image', '=', 'tf.image.resize_images(image,', 'size,', 'method... | 469,268 |
rahulreddythummala/Natural-Language- | test_singletpr.py | test_topicalpagerank_candidate_weighting | test_topicalpagerank_candidate_weighting | Test Single Topical PageRank weighting method. | [
"Test",
"Single",
"Topical",
"PageRank",
"weighting",
"method."
] | def test_topicalpagerank_candidate_weighting():
extractor = pke.unsupervised.TopicalPageRank()
extractor.load_document(input=test_file)
extractor.candidate_selection(grammar=grammar)
extractor.candidate_weighting(window=10, pos=pos)
keyphrases = [k for (k, s) in extractor.get_n_best(n=3)]
assert... | ['def', 'test_topicalpagerank_candidate_weighting():', 'extractor', '=', 'pke.unsupervised.TopicalPageRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(grammar=grammar)', 'extractor.candidate_weighting(window=10,', 'pos=pos)', 'keyphrases', '=', '[k', 'for', '(k,', 's)', 'in', 'extract... | 663,420 |
tomcatmanager/tomcatmanager | interactive_tomcat_manager.py | InteractiveTomcatManager.help_version | help_version | Show help for the 'version' command. | [
"Show",
"help",
"for",
"the",
"'version'",
"command."
] | def help_version(self):
self.show_help_from(self.version_parser) | ['def', 'help_version(self):', 'self.show_help_from(self.version_parser)'] | 355,591 |
facebookresearch/Detectron | segms.py | flip_segms | flip_segms | Left/right flip each mask in a list of masks. | [
"Left/right",
"flip",
"each",
"mask",
"in",
"a",
"list",
"of",
"masks."
] | def flip_segms(segms, height, width):
def _flip_poly(poly, width):
flipped_poly = np.array(poly)
flipped_poly[0::2] = width - np.array(poly[0::2]) - 1
return flipped_poly.tolist()
def _flip_rle(rle, height, width):
if 'counts' in rle and type(rle['counts']) == list:
... | ['def', 'flip_segms(segms,', 'height,', 'width):', 'def', '_flip_poly(poly,', 'width):', 'flipped_poly', '=', 'np.array(poly)', 'flipped_poly[0::2]', '=', 'width', '-', 'np.array(poly[0::2])', '-', '1', 'return', 'flipped_poly.tolist()', 'def', '_flip_rle(rle,', 'height,', 'width):', 'if', "'counts'", 'in', 'rle', 'and... | 549,041 |
nicknochnack/RealTimeSignLanguageTFJS | resnet_ctl_imagenet_main.py | run | run | Run ResNet ImageNet training and eval loop using custom training loops. | [
"Run",
"ResNet",
"ImageNet",
"training",
"and",
"eval",
"loop",
"using",
"custom",
"training",
"loops."
] | def run(flags_obj):
keras_utils.set_session_config(enable_xla=flags_obj.enable_xla)
performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj), use_experimental_api=False)
if tf.config.list_physical_devices('GPU'):
if flags_obj.tf_gpu_thread_mode:
keras_utils.set_gpu_threa... | ['def', 'run(flags_obj):', 'keras_utils.set_session_config(enable_xla=flags_obj.enable_xla)', 'performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj),', 'use_experimental_api=False)', 'if', "tf.config.list_physical_devices('GPU'):", 'if', 'flags_obj.tf_gpu_thread_mode:', 'keras_utils.set_gpu_thread_m... | 851,237 |
Saran-nns/sorn | utils.py | Statistics.autocorr | autocorr | Score interpretation - scores near 1 imply a smoothly varying series - scores near 0 imply that there's no overall linear relationship between a data point and the following one (that is, plot(x[-length(x)],x[-1]) won't give a scatter plot with any apparent linearity) - scores near -1 suggest that the series is jagged ... | [
"Score",
"interpretation",
"-",
"scores",
"near",
"1",
"imply",
"a",
"smoothly",
"varying",
"series",
"-",
"scores",
"near",
"0",
"imply",
"that",
"there's",
"no",
"overall",
"linear",
"relationship",
"between",
"a",
"data",
"point",
"and",
"the",
"following",... | def autocorr(firing_rates: list, t: int=2):
return np.corrcoef(np.array([firing_rates[0:len(firing_rates) - t], firing_rates[t:len(firing_rates)]])) | ['def', 'autocorr(firing_rates:', 'list,', 't:', 'int=2):', 'return', 'np.corrcoef(np.array([firing_rates[0:len(firing_rates)', '-', 't],', 'firing_rates[t:len(firing_rates)]]))'] | 393,804 |
weimin17/Object-Detection_HelmetDetection | path_model.py | PathBasedModel.predict | predict | Predict the classification of the test set. | [
"Predict",
"the",
"classification",
"of",
"the",
"test",
"set."
] | def predict(self, session, inputs):
(predictions, _) = zip(*self.predict_with_score(session, inputs))
return np.array(predictions) | ['def', 'predict(self,', 'session,', 'inputs):', '(predictions,', '_)', '=', 'zip(*self.predict_with_score(session,', 'inputs))', 'return', 'np.array(predictions)'] | 763,459 |
zihuitang/medical_AI_platform | smtplib.py | SMTP.putcmd | putcmd | Send a command to the server. | [
"Send",
"a",
"command",
"to",
"the",
"server."
] | def putcmd(self, cmd, args=''):
if args == '':
str = '%s%s' % (cmd, CRLF)
else:
str = '%s %s%s' % (cmd, args, CRLF)
self.send(str) | ['def', 'putcmd(self,', 'cmd,', "args=''):", 'if', 'args', '==', "'':", 'str', '=', "'%s%s'", '%', '(cmd,', 'CRLF)', 'else:', 'str', '=', "'%s", "%s%s'", '%', '(cmd,', 'args,', 'CRLF)', 'self.send(str)'] | 281,366 |
43Carrig/recurrent_neural_networks_practice | variables.py | is_variable_initialized | is_variable_initialized | Tests if a variable has been initialized. | [
"Tests",
"if",
"a",
"variable",
"has",
"been",
"initialized."
] | def is_variable_initialized(variable):
return state_ops.is_variable_initialized(variable) | ['def', 'is_variable_initialized(variable):', 'return', 'state_ops.is_variable_initialized(variable)'] | 339,073 |
wandb/wandb | artifact.py | Artifact.updated_at | updated_at | The time at which the artifact was last updated. | [
"The",
"time",
"at",
"which",
"the",
"artifact",
"was",
"last",
"updated."
] | def updated_at(self) -> str:
self._ensure_logged('updated_at')
assert self._created_at is not None
return self._updated_at or self._created_at | ['def', 'updated_at(self)', '->', 'str:', "self._ensure_logged('updated_at')", 'assert', 'self._created_at', 'is', 'not', 'None', 'return', 'self._updated_at', 'or', 'self._created_at'] | 941,636 |
jxhe/unify-parameter-efficient-tuning | tokenization_speech_to_text.py | Speech2TextTokenizer.build_inputs_with_special_tokens | build_inputs_with_special_tokens | Build model inputs from a sequence by appending eos_token_id. | [
"Build",
"model",
"inputs",
"from",
"a",
"sequence",
"by",
"appending",
"eos_token_id."
] | def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]:
if token_ids_1 is None:
return self.prefix_tokens + token_ids_0 + [self.eos_token_id]
return self.prefix_tokens + token_ids_0 + token_ids_1 + [self.eos_token_id] | ['def', 'build_inputs_with_special_tokens(self,', 'token_ids_0,', 'token_ids_1=None)', '->', 'List[int]:', 'if', 'token_ids_1', 'is', 'None:', 'return', 'self.prefix_tokens', '+', 'token_ids_0', '+', '[self.eos_token_id]', 'return', 'self.prefix_tokens', '+', 'token_ids_0', '+', 'token_ids_1', '+', '[self.eos_token_id]... | 949,229 |
open-mmlab/mmselfsup | maskfeat_vit.py | MaskFeatViT.forward | forward | Generate features for masked images. | [
"Generate",
"features",
"for",
"masked",
"images."
] | def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
B = x.shape[0]
x = self.patch_embed(x)[0]
(B, L, _) = x.shape
mask_tokens = self.mask_token.expand(B, L, -1)
mask = mask.flatten(1).unsqueeze(-1)
x = x * (1 - mask.int()) + mask_tokens * mask
cls_tokens = self.cls_token.... | ['def', 'forward(self,', 'x:', 'torch.Tensor,', 'mask:', 'torch.Tensor)', '->', 'torch.Tensor:', 'B', '=', 'x.shape[0]', 'x', '=', 'self.patch_embed(x)[0]', '(B,', 'L,', '_)', '=', 'x.shape', 'mask_tokens', '=', 'self.mask_token.expand(B,', 'L,', '-1)', 'mask', '=', 'mask.flatten(1).unsqueeze(-1)', 'x', '=', 'x', '*', ... | 240,409 |
loliverhennigh/All-Convnet-Autoencoder-Example | input_data.py | dense_to_one_hot | dense_to_one_hot | Convert class labels from scalars to one-hot vectors. | [
"Convert",
"class",
"labels",
"from",
"scalars",
"to",
"one-hot",
"vectors."
] | def dense_to_one_hot(labels_dense, num_classes):
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot | ['def', 'dense_to_one_hot(labels_dense,', 'num_classes):', 'num_labels', '=', 'labels_dense.shape[0]', 'index_offset', '=', 'numpy.arange(num_labels)', '*', 'num_classes', 'labels_one_hot', '=', 'numpy.zeros((num_labels,', 'num_classes))', 'labels_one_hot.flat[index_offset', '+', 'labels_dense.ravel()]', '=', '1', 'ret... | 414,666 |
Katja-M/Python_NaturalLanguageProcessing | git.py | Git.resolve_revision | resolve_revision | Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. | [
"Resolve",
"a",
"revision",
"to",
"a",
"new",
"RevOptions",
"object",
"with",
"the",
"SHA1",
"of",
"the",
"branch,",
"tag,",
"or",
"ref",
"if",
"found."
] | def resolve_revision(cls, dest, url, rev_options):
rev = rev_options.arg_rev
assert rev is not None
(sha, is_branch) = cls.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_optio... | ['def', 'resolve_revision(cls,', 'dest,', 'url,', 'rev_options):', 'rev', '=', 'rev_options.arg_rev', 'assert', 'rev', 'is', 'not', 'None', '(sha,', 'is_branch)', '=', 'cls.get_revision_sha(dest,', 'rev)', 'if', 'sha', 'is', 'not', 'None:', 'rev_options', '=', 'rev_options.make_new(sha)', 'rev_options.branch_name', '='... | 868,291 |
Levantespot/UDA_for_RS | inference.py | inference_segmentor | inference_segmentor | Inference image(s) with the segmentor. | [
"Inference",
"image(s)",
"with",
"the",
"segmentor."
] | def inference_segmentor(model, img):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:]
test_pipeline = Compose(test_pipeline)
data = dict(img=img)
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if nex... | ['def', 'inference_segmentor(model,', 'img):', 'cfg', '=', 'model.cfg', 'device', '=', 'next(model.parameters()).device', 'test_pipeline', '=', '[LoadImage()]', '+', 'cfg.data.test.pipeline[1:]', 'test_pipeline', '=', 'Compose(test_pipeline)', 'data', '=', 'dict(img=img)', 'data', '=', 'test_pipeline(data)', 'data', '=... | 947,311 |
jshilong/DDQ | geometric.py | impad | impad | Pad the given image to a certain shape or pad on all sides with specified padding mode and padding value. | [
"Pad",
"the",
"given",
"image",
"to",
"a",
"certain",
"shape",
"or",
"pad",
"on",
"all",
"sides",
"with",
"specified",
"padding",
"mode",
"and",
"padding",
"value."
] | def impad(img, *, shape=None, padding=None, pad_val=0, padding_mode='constant'):
assert (shape is not None) ^ (padding is not None)
if shape is not None:
padding = (0, 0, shape[1] - img.shape[1], shape[0] - img.shape[0])
if isinstance(pad_val, tuple):
assert len(pad_val) == img.shape[-1]
... | ['def', 'impad(img,', '*,', 'shape=None,', 'padding=None,', 'pad_val=0,', "padding_mode='constant'):", 'assert', '(shape', 'is', 'not', 'None)', '^', '(padding', 'is', 'not', 'None)', 'if', 'shape', 'is', 'not', 'None:', 'padding', '=', '(0,', '0,', 'shape[1]', '-', 'img.shape[1],', 'shape[0]', '-', 'img.shape[0])', 'i... | 499,057 |
chribsen/simple-machine-learning-examples | generate_ufuncs.py | unique | unique | Return a list without repeated entries (first occurrence is kept), preserving order. | [
"Return",
"a",
"list",
"without",
"repeated",
"entries",
"(first",
"occurrence",
"is",
"kept),",
"preserving",
"order."
] | def unique(lst):
seen = set()
new_lst = []
for item in lst:
if item in seen:
continue
seen.add(item)
new_lst.append(item)
return new_lst | ['def', 'unique(lst):', 'seen', '=', 'set()', 'new_lst', '=', '[]', 'for', 'item', 'in', 'lst:', 'if', 'item', 'in', 'seen:', 'continue', 'seen.add(item)', 'new_lst.append(item)', 'return', 'new_lst'] | 938,513 |
PacktPublishing/Learning-OpenCV-5---with-Python-Fourth-Edition | utils.py | createFlatView | createFlatView | Return a 1D view of an array of any dimensionality. | [
"Return",
"a",
"1D",
"view",
"of",
"an",
"array",
"of",
"any",
"dimensionality."
] | def createFlatView(array):
flatView = array.view()
flatView.shape = array.size
return flatView | ['def', 'createFlatView(array):', 'flatView', '=', 'array.view()', 'flatView.shape', '=', 'array.size', 'return', 'flatView'] | 588,051 |
AgnostiqHQ/covalent | metrics_test.py | test_platform_metdata | test_platform_metdata | Test the platform metadata object. | [
"Test",
"the",
"platform",
"metadata",
"object."
] | def test_platform_metdata():
pmd = PlatformMetadata()
assert pmd.arch is not None
assert pmd.system is not None
assert pmd.machine is not None
assert pmd.os is not None
assert pmd.python_version is not None
print(pmd.arch)
print(pmd.system)
print(pmd.machine)
print(pmd.os)
pr... | ['def', 'test_platform_metdata():', 'pmd', '=', 'PlatformMetadata()', 'assert', 'pmd.arch', 'is', 'not', 'None', 'assert', 'pmd.system', 'is', 'not', 'None', 'assert', 'pmd.machine', 'is', 'not', 'None', 'assert', 'pmd.os', 'is', 'not', 'None', 'assert', 'pmd.python_version', 'is', 'not', 'None', 'print(pmd.arch)', 'pr... | 489,846 |
tensorflow/agents | common.py | check_matching_networks | check_matching_networks | Check that two networks have matching input specs and variables. | [
"Check",
"that",
"two",
"networks",
"have",
"matching",
"input",
"specs",
"and",
"variables."
] | def check_matching_networks(network_1, network_2):
if network_1.input_tensor_spec != network_2.input_tensor_spec:
raise ValueError('Input tensor specs of network and target network do not match: {} vs. {}.'.format(network_1.input_tensor_spec, network_2.input_tensor_spec))
if len(network_1.variables) != ... | ['def', 'check_matching_networks(network_1,', 'network_2):', 'if', 'network_1.input_tensor_spec', '!=', 'network_2.input_tensor_spec:', 'raise', "ValueError('Input", 'tensor', 'specs', 'of', 'network', 'and', 'target', 'network', 'do', 'not', 'match:', '{}', 'vs.', "{}.'.format(network_1.input_tensor_spec,", 'network_2... | 23,077 |
ifwe/digsby | simplemenu.py | SimpleMenu.RemoveItem | RemoveItem | Remove the item provided from the menu. | [
"Remove",
"the",
"item",
"provided",
"from",
"the",
"menu."
] | def RemoveItem(self, item):
sp = self.spine
if isinstance(item, int):
item = sp.items[item]
sp.Selection = -1
sp.items.remove(item)
sp.ItemCount = len(self.spine.items) | ['def', 'RemoveItem(self,', 'item):', 'sp', '=', 'self.spine', 'if', 'isinstance(item,', 'int):', 'item', '=', 'sp.items[item]', 'sp.Selection', '=', '-1', 'sp.items.remove(item)', 'sp.ItemCount', '=', 'len(self.spine.items)'] | 185,600 |
ryu-ed/SpaceInvaders_Ros | draw_test.py | AntiAliasedLineMixin.test_anti_aliasing_float_coordinates | test_anti_aliasing_float_coordinates | Float coordinates should be blended smoothly. | [
"Float",
"coordinates",
"should",
"be",
"blended",
"smoothly."
] | def test_anti_aliasing_float_coordinates(self):
check_points = [(i, j) for i in range(5) for j in range(5)]
brown = (127, 127, 0)
expected = {(1, 2): FG_GREEN}
self._check_antialiasing((1.5, 2), (1.5, 2), expected, check_points, set_endpoints=False)
expected = {(2, 2): FG_GREEN}
self._check_anti... | ['def', 'test_anti_aliasing_float_coordinates(self):', 'check_points', '=', '[(i,', 'j)', 'for', 'i', 'in', 'range(5)', 'for', 'j', 'in', 'range(5)]', 'brown', '=', '(127,', '127,', '0)', 'expected', '=', '{(1,', '2):', 'FG_GREEN}', 'self._check_antialiasing((1.5,', '2),', '(1.5,', '2),', 'expected,', 'check_points,', ... | 368,932 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | trainable_optimizer.py | is_local_state_variable | is_local_state_variable | Returns if this op is a local state variable created for training. | [
"Returns",
"if",
"this",
"op",
"is",
"a",
"local",
"state",
"variable",
"created",
"for",
"training."
] | def is_local_state_variable(op):
return op.node_def.op in ['Variable', 'VariableV2'] and op.name.startswith(OPTIMIZER_SCOPE + '/' + _LOCAL_VARIABLE_PREFIX) | ['def', 'is_local_state_variable(op):', 'return', 'op.node_def.op', 'in', "['Variable',", "'VariableV2']", 'and', 'op.name.startswith(OPTIMIZER_SCOPE', '+', "'/'", '+', '_LOCAL_VARIABLE_PREFIX)'] | 55,465 |
deepmind/meltingpot | allelopathic_harvest.py | create_colored_avatar_overlay | create_colored_avatar_overlay | Create a colored avatar overlay object. | [
"Create",
"a",
"colored",
"avatar",
"overlay",
"object."
] | def create_colored_avatar_overlay(player_idx: int) -> Dict[str, Any]:
lua_idx = player_idx + 1
overlay_object = {'name': 'avatar_overlay', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'avatarOverlayWait', 'stateConfigs': [{'state': 'avatarOverlay', 'layer': 'overlay', 'sprite': 'Newbo... | ['def', 'create_colored_avatar_overlay(player_idx:', 'int)', '->', 'Dict[str,', 'Any]:', 'lua_idx', '=', 'player_idx', '+', '1', 'overlay_object', '=', "{'name':", "'avatar_overlay',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'avatarOverlayWait',", "'stateConfigs':", "[{'s... | 285,244 |
jshilong/DDQ | general_data.py | GeneralData.values | values | Returns: list: Contains all values in data_fields. | [
"Returns:",
"list:",
"Contains",
"all",
"values",
"in",
"data_fields."
] | def values(self):
return [getattr(self, k) for k in self.keys()] | ['def', 'values(self):', 'return', '[getattr(self,', 'k)', 'for', 'k', 'in', 'self.keys()]'] | 515,721 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.