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
aws/sagemaker-python-sdk
predictor.py
retrieve_default
retrieve_default
Retrieves the default predictor for the model matching the given arguments.
[ "Retrieves", "the", "default", "predictor", "for", "the", "model", "matching", "the", "given", "arguments." ]
def retrieve_default(endpoint_name: str, sagemaker_session: Session=DEFAULT_JUMPSTART_SAGEMAKER_SESSION, region: Optional[str]=None, model_id: Optional[str]=None, model_version: Optional[str]=None, tolerate_vulnerable_model: bool=False, tolerate_deprecated_model: bool=False) -> Predictor: if not is_jumpstart_model_...
['def', 'retrieve_default(endpoint_name:', 'str,', 'sagemaker_session:', 'Session=DEFAULT_JUMPSTART_SAGEMAKER_SESSION,', 'region:', 'Optional[str]=None,', 'model_id:', 'Optional[str]=None,', 'model_version:', 'Optional[str]=None,', 'tolerate_vulnerable_model:', 'bool=False,', 'tolerate_deprecated_model:', 'bool=False)'...
829,539
mschrader15/reinforcement-learning-sumo
utils.py
get_rllib_config
get_rllib_config
Return the data from the specified rllib configuration file.
[ "Return", "the", "data", "from", "the", "specified", "rllib", "configuration", "file." ]
def get_rllib_config(path): config_path = os.path.join(path, 'params.json') if not os.path.exists(config_path): config_path = os.path.join(path, '../params.json') if not os.path.exists(config_path): raise ValueError(f'Could not find params.json in either the checkpoint dir or its parent dire...
['def', 'get_rllib_config(path):', 'config_path', '=', 'os.path.join(path,', "'params.json')", 'if', 'not', 'os.path.exists(config_path):', 'config_path', '=', 'os.path.join(path,', "'../params.json')", 'if', 'not', 'os.path.exists(config_path):', 'raise', "ValueError(f'Could", 'not', 'find', 'params.json', 'in', 'eith...
833,593
deepmind/spriteworld
action_spaces.py
Embodied.get_non_body_sprites
get_non_body_sprites
Return all sprites except that representing the agent's body.
[ "Return", "all", "sprites", "except", "that", "representing", "the", "agent's", "body." ]
def get_non_body_sprites(self, sprites): return sprites[:-1]
['def', 'get_non_body_sprites(self,', 'sprites):', 'return', 'sprites[:-1]']
897,168
Trusted-AI/AIF360
test_datasets.py
test_fetch_meps
test_fetch_meps
Tests MEPS datasets shapes with various options.
[ "Tests", "MEPS", "datasets", "shapes", "with", "various", "options." ]
def test_fetch_meps(panel): meps = fetch_meps(panel, accept_terms=True, dropna=False) meps_dropna = fetch_meps(panel, dropna=True) assert meps_dropna.X.shape[0] < meps.X.shape[0] meps_numeric = fetch_meps(panel, accept_terms=True, numeric_only=True) assert meps_numeric.X.shape[1] == 5
['def', 'test_fetch_meps(panel):', 'meps', '=', 'fetch_meps(panel,', 'accept_terms=True,', 'dropna=False)', 'meps_dropna', '=', 'fetch_meps(panel,', 'dropna=True)', 'assert', 'meps_dropna.X.shape[0]', '<', 'meps.X.shape[0]', 'meps_numeric', '=', 'fetch_meps(panel,', 'accept_terms=True,', 'numeric_only=True)', 'assert',...
412,520
kornia/kornia
object_detection.py
results_from_detections
results_from_detections
Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.
[ "Convert", "a", "detection", "tensor", "to", "a", "list", "of", ":py:class:`ObjectDetectorResult`." ]
def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]: KORNIA_CHECK_SHAPE(detections, ['D', '6']) if isinstance(format, str): format = BoundingBoxDataFormat[format.upper()] results: list[ObjectDetectorResult] = [] for det in detections...
['def', 'results_from_detections(detections:', 'Tensor,', 'format:', 'str', '|', 'BoundingBoxDataFormat)', '->', 'list[ObjectDetectorResult]:', 'KORNIA_CHECK_SHAPE(detections,', "['D',", "'6'])", 'if', 'isinstance(format,', 'str):', 'format', '=', 'BoundingBoxDataFormat[format.upper()]', 'results:', 'list[ObjectDetecto...
621,607
apeterswu/RL4NMT
expert_utils.py
DistributedSparseDispatcher.combine
combine
Sum together the expert output, multiplied by the corresponding gates.
[ "Sum", "together", "the", "expert", "output,", "multiplied", "by", "the", "corresponding", "gates." ]
def combine(self, expert_out, multiply_by_gates=True): expert_part_sizes = tf.unstack(tf.stack([d.part_sizes for d in self._dispatchers]), num=self._ep.n, axis=1) expert_output_parts = self._ep(tf.split, expert_out, expert_part_sizes) expert_output_parts_t = transpose_list_of_lists(expert_output_parts) ...
['def', 'combine(self,', 'expert_out,', 'multiply_by_gates=True):', 'expert_part_sizes', '=', 'tf.unstack(tf.stack([d.part_sizes', 'for', 'd', 'in', 'self._dispatchers]),', 'num=self._ep.n,', 'axis=1)', 'expert_output_parts', '=', 'self._ep(tf.split,', 'expert_out,', 'expert_part_sizes)', 'expert_output_parts_t', '=', ...
331,266
nicknochnack/RealTimeSignLanguageTFJS
rewards_functions.py
plain_rewards
plain_rewards
Returns the given rewards.
[ "Returns", "the", "given", "rewards." ]
def plain_rewards(states, actions, rewards, next_states, contexts): del states, actions, next_states, contexts return (rewards, tf.ones_like(rewards))
['def', 'plain_rewards(states,', 'actions,', 'rewards,', 'next_states,', 'contexts):', 'del', 'states,', 'actions,', 'next_states,', 'contexts', 'return', '(rewards,', 'tf.ones_like(rewards))']
851,786
nemanja-rakicevic/informed_search
modelling.py
BaseModel.generate_sample
generate_sample
Generate the movement parameter vector to evaluate next, based on the calculated SIDF.
[ "Generate", "the", "movement", "parameter", "vector", "to", "evaluate", "next,", "based", "on", "the", "calculated", "SIDF." ]
def generate_sample(self, info_list=None, **kwargs): temp_good = np.array([]) cnt = 1 while len(temp_good) == 0: sample = np.array([self.sidf == c for c in nlargest(cnt * 1, self.sidf.ravel())]) sample = sample.reshape([-1] + list(self.param_dims)) sample_idx = np.argwhere(sample)[:,...
['def', 'generate_sample(self,', 'info_list=None,', '**kwargs):', 'temp_good', '=', 'np.array([])', 'cnt', '=', '1', 'while', 'len(temp_good)', '==', '0:', 'sample', '=', 'np.array([self.sidf', '==', 'c', 'for', 'c', 'in', 'nlargest(cnt', '*', '1,', 'self.sidf.ravel())])', 'sample', '=', 'sample.reshape([-1]', '+', 'li...
612,610
Rshcaroline/FDU-Artificial-Intelligence
AI-MCTS.py
isFree
isFree
Return a bool value indicating if (x, y) square is free.
[ "Return", "a", "bool", "value", "indicating", "if", "(x,", "y)", "square", "is", "free." ]
def isFree(x, y): return x >= 0 and y >= 0 and (x < pp.width) and (y < pp.height) and (board[x][y] == 0)
['def', 'isFree(x,', 'y):', 'return', 'x', '>=', '0', 'and', 'y', '>=', '0', 'and', '(x', '<', 'pp.width)', 'and', '(y', '<', 'pp.height)', 'and', '(board[x][y]', '==', '0)']
179,155
scikit-multiflow/scikit-multiflow
data_structures.py
SlidingWindow.targets_buffer
targets_buffer
Get the targets buffer The shape of the buffer is (window_size, n_targets).
[ "Get", "the", "targets", "buffer", "The", "shape", "of", "the", "buffer", "is", "(window_size,", "n_targets)." ]
def targets_buffer(self): return self._y_queue
['def', 'targets_buffer(self):', 'return', 'self._y_queue']
854,983
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
placement_mesh_impl.py
PlacementMeshImpl.slicewise
slicewise
Execute a function in parallel on all slices.
[ "Execute", "a", "function", "in", "parallel", "on", "all", "slices." ]
def slicewise(self, fn, *inputs): if fn == tf.add: assert len(inputs) == 2 if isinstance(inputs[0], mtf.LazyAllreduceSum): return inputs[0] + inputs[1] inputs = mtf.convert_args_to_laid_out_tensors(inputs) inputs = [x.tensor_list if isinstance(x, self.LaidOutTensor) else [x] * le...
['def', 'slicewise(self,', 'fn,', '*inputs):', 'if', 'fn', '==', 'tf.add:', 'assert', 'len(inputs)', '==', '2', 'if', 'isinstance(inputs[0],', 'mtf.LazyAllreduceSum):', 'return', 'inputs[0]', '+', 'inputs[1]', 'inputs', '=', 'mtf.convert_args_to_laid_out_tensors(inputs)', 'inputs', '=', '[x.tensor_list', 'if', 'isinsta...
965,561
PaddlePaddle/PaddleSpeech
embedding.py
ScaledRotaryRelPositionalEncoding.position_encoding
position_encoding
For getting encoding in a streaming fashion Attention!!!!! we apply dropout only once at the whole utterance level in a none streaming way, but will call this function several times with increasing input size in a streaming scenario, so the dropout will be applied several times.
[ "For", "getting", "encoding", "in", "a", "streaming", "fashion", "Attention!!!!!", "we", "apply", "dropout", "only", "once", "at", "the", "whole", "utterance", "level", "in", "a", "none", "streaming", "way,", "but", "will", "call", "this", "function", "several...
def position_encoding(self, offset: int, size: int) -> paddle.Tensor: start = offset end = (offset + size) * self.pscale assert end <= self.max_len position = paddle.arange(start, end, dtype=paddle.get_default_dtype()).unsqueeze(0) position *= 1.0 / self.pscale pe = self.sinusoidal_embeddings(po...
['def', 'position_encoding(self,', 'offset:', 'int,', 'size:', 'int)', '->', 'paddle.Tensor:', 'start', '=', 'offset', 'end', '=', '(offset', '+', 'size)', '*', 'self.pscale', 'assert', 'end', '<=', 'self.max_len', 'position', '=', 'paddle.arange(start,', 'end,', 'dtype=paddle.get_default_dtype()).unsqueeze(0)', 'posit...
276,933
IntelLabs/nlp-architect
tasks.py
WSCTask.get_val_to_label_map
get_val_to_label_map
Returns dict mapping t-SNE plot color option to a dictionary of (val, label) k/v pairs, for categorical plotting.
[ "Returns", "dict", "mapping", "t-SNE", "plot", "color", "option", "to", "a", "dictionary", "of", "(val,", "label)", "k/v", "pairs,", "for", "categorical", "plotting." ]
def get_val_to_label_map(self, dropdown_color_option: str) -> Dict[float, str]: return {0.0: 'False/No', 0.5: 'Ambiguous', 1.0: 'True/Yes'}
['def', 'get_val_to_label_map(self,', 'dropdown_color_option:', 'str)', '->', 'Dict[float,', 'str]:', 'return', '{0.0:', "'False/No',", '0.5:', "'Ambiguous',", '1.0:', "'True/Yes'}"]
783,543
guenthermi/table-embeddings
layout_classifier.py
LayoutClassifier.create_lstm_model
create_lstm_model
Create the LSTM network that uses only embedding features.
[ "Create", "the", "LSTM", "network", "that", "uses", "only", "embedding", "features." ]
def create_lstm_model(self, model_name, input_dim, global_features_input_dim, output_dim, label_index=None): print('input_dim', input_dim, 'output_dim', output_dim) last_activation = 'sigmoid' if label_index is not None else 'softmax' loss = 'binary_crossentropy' if label_index is not None else 'categorical...
['def', 'create_lstm_model(self,', 'model_name,', 'input_dim,', 'global_features_input_dim,', 'output_dim,', 'label_index=None):', "print('input_dim',", 'input_dim,', "'output_dim',", 'output_dim)', 'last_activation', '=', "'sigmoid'", 'if', 'label_index', 'is', 'not', 'None', 'else', "'softmax'", 'loss', '=', "'binary...
365,138
cjiang2/video2command
utils.py
texts_to_sequences
texts_to_sequences
Wrapper to convert batch of texts to sequences.
[ "Wrapper", "to", "convert", "batch", "of", "texts", "to", "sequences." ]
def texts_to_sequences(texts, vocab, filters='!"#$%&()*+.,-/:;=?@[\\]^_`{|}~ ', lower=True, split=' '): seqs = [] for text in texts: seqs.append(text_to_sequence(text, vocab, filters, lower, split)) return np.array(seqs)
['def', 'texts_to_sequences(texts,', 'vocab,', 'filters=\'!"#$%&()*+.,-/:;=?@[\\\\]^_`{|}~', "',", 'lower=True,', "split='", "'):", 'seqs', '=', '[]', 'for', 'text', 'in', 'texts:', 'seqs.append(text_to_sequence(text,', 'vocab,', 'filters,', 'lower,', 'split))', 'return', 'np.array(seqs)']
379,895
tinazhouhui/computer_vision
cpp_lint.py
_IncludeState.IsInAlphabeticalOrder
IsInAlphabeticalOrder
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): if self._last_header > header_path and (not Match('^\\s*$', clean_lines.elided[linenum - 1])): return False return True
['def', 'IsInAlphabeticalOrder(self,', 'clean_lines,', 'linenum,', 'header_path):', 'if', 'self._last_header', '>', 'header_path', 'and', '(not', "Match('^\\\\s*$',", 'clean_lines.elided[linenum', '-', '1])):', 'return', 'False', 'return', 'True']
473,084
kaize0409/Meta-PN
sparsegraph.py
SparseGraph.is_weighted
is_weighted
Check if the graph is weighted (edge weights other than 1).
[ "Check", "if", "the", "graph", "is", "weighted", "(edge", "weights", "other", "than", "1)." ]
def is_weighted(self) -> bool: return np.any(np.unique(self.adj_matrix[self.adj_matrix.nonzero()].A1) != 1)
['def', 'is_weighted(self)', '->', 'bool:', 'return', 'np.any(np.unique(self.adj_matrix[self.adj_matrix.nonzero()].A1)', '!=', '1)']
286,058
eddylau328/fyp-artificial-intelligence-ac-control-device
_user_import.py
UserImportHash.pbkdf2_sha256
pbkdf2_sha256
Creates a new PBKDF2 SHA256 algorithm instance.
[ "Creates", "a", "new", "PBKDF2", "SHA256", "algorithm", "instance." ]
def pbkdf2_sha256(cls, rounds): return UserImportHash('PBKDF2_SHA256', {'rounds': _auth_utils.validate_int(rounds, 'rounds', 0, 120000)})
['def', 'pbkdf2_sha256(cls,', 'rounds):', 'return', "UserImportHash('PBKDF2_SHA256',", "{'rounds':", '_auth_utils.validate_int(rounds,', "'rounds',", '0,', '120000)})']
214,378
edwardguil/MMTL
MMTL.py
EndToEndModule.add_tokens
add_tokens
Expands the language modules tokenizer to include passed tokens.
[ "Expands", "the", "language", "modules", "tokenizer", "to", "include", "passed", "tokens." ]
def add_tokens(self, tokens): self.language.add_tokens(tokens)
['def', 'add_tokens(self,', 'tokens):', 'self.language.add_tokens(tokens)']
625,640
wangck20/OPERA
helpers.py
set_pretrained_download_progress
set_pretrained_download_progress
Set download progress for pretrained weights on/off (globally).
[ "Set", "download", "progress", "for", "pretrained", "weights", "on/off", "(globally)." ]
def set_pretrained_download_progress(enable=True): global _DOWNLOAD_PROGRESS _DOWNLOAD_PROGRESS = enable
['def', 'set_pretrained_download_progress(enable=True):', 'global', '_DOWNLOAD_PROGRESS', '_DOWNLOAD_PROGRESS', '=', 'enable']
252,919
jbwang1997/CrossKD
reppoints_head.py
RepPointsHead.gen_grid_from_reg
gen_grid_from_reg
Base on the previous bboxes and regression values, we compute the regressed bboxes and generate the grids on the bboxes.
[ "Base", "on", "the", "previous", "bboxes", "and", "regression", "values,", "we", "compute", "the", "regressed", "bboxes", "and", "generate", "the", "grids", "on", "the", "bboxes." ]
def gen_grid_from_reg(self, reg: Tensor, previous_boxes: Tensor) -> Tuple[Tensor]: (b, _, h, w) = reg.shape bxy = (previous_boxes[:, :2, ...] + previous_boxes[:, 2:, ...]) / 2.0 bwh = (previous_boxes[:, 2:, ...] - previous_boxes[:, :2, ...]).clamp(min=1e-06) grid_topleft = bxy + bwh * reg[:, :2, ...] - ...
['def', 'gen_grid_from_reg(self,', 'reg:', 'Tensor,', 'previous_boxes:', 'Tensor)', '->', 'Tuple[Tensor]:', '(b,', '_,', 'h,', 'w)', '=', 'reg.shape', 'bxy', '=', '(previous_boxes[:,', ':2,', '...]', '+', 'previous_boxes[:,', '2:,', '...])', '/', '2.0', 'bwh', '=', '(previous_boxes[:,', '2:,', '...]', '-', 'previous_bo...
491,106
jimtin/Stock_Comparison
screen.py
screen.scroll_screen
scroll_screen
Enable scrolling for entire display.
[ "Enable", "scrolling", "for", "entire", "display." ]
def scroll_screen(self): self.scroll_row_start = 1 self.scroll_row_end = self.rows
['def', 'scroll_screen(self):', 'self.scroll_row_start', '=', '1', 'self.scroll_row_end', '=', 'self.rows']
388,447
gunthercox/ChatterBot
expression.py
Select.froms
froms
Return the displayed list of FromClause elements.
[ "Return", "the", "displayed", "list", "of", "FromClause", "elements." ]
def froms(self): return self._get_display_froms()
['def', 'froms(self):', 'return', 'self._get_display_froms()']
481,785
eth-sri/debin
py3compat.py
iteritems
iteritems
Return an iterator over the items of a dictionary.
[ "Return", "an", "iterator", "over", "the", "items", "of", "a", "dictionary." ]
def iteritems(d): return getattr(d, 'items' if PY3 else 'iteritems')()
['def', 'iteritems(d):', 'return', 'getattr(d,', "'items'", 'if', 'PY3', 'else', "'iteritems')()"]
516,461
noahshinn024/reflexion
evaluation.py
estimate_pass_at_k
estimate_pass_at_k
Estimates pass@k of each problem and returns them in an array.
[ "Estimates", "pass@k", "of", "each", "problem", "and", "returns", "them", "in", "an", "array." ]
def estimate_pass_at_k(num_samples: Union[int, List[int], np.ndarray], num_correct: Union[List[int], np.ndarray], k: int) -> np.ndarray: def estimator(n: int, c: int, k: int) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1)) if isinstance...
['def', 'estimate_pass_at_k(num_samples:', 'Union[int,', 'List[int],', 'np.ndarray],', 'num_correct:', 'Union[List[int],', 'np.ndarray],', 'k:', 'int)', '->', 'np.ndarray:', 'def', 'estimator(n:', 'int,', 'c:', 'int,', 'k:', 'int)', '->', 'float:', 'if', 'n', '-', 'c', '<', 'k:', 'return', '1.0', 'return', '1.0', '-', ...
340,459
QData/deepWordBug
test_gitwildmatch.py
GitWildMatchTest.test_07_match_bytes_and_bytes_complete
test_07_match_bytes_and_bytes_complete
Test byte string patterns matching byte string paths.
[ "Test", "byte", "string", "patterns", "matching", "byte", "string", "paths." ]
def test_07_match_bytes_and_bytes_complete(self): encoded = bytes(bytearray(range(0, 256))) escaped = b''.join((b'\\' + encoded[i:i + 1] for i in range(len(encoded)))) pattern = GitWildMatchPattern(escaped) results = set(pattern.match([encoded])) self.assertEqual(results, set([encoded]))
['def', 'test_07_match_bytes_and_bytes_complete(self):', 'encoded', '=', 'bytes(bytearray(range(0,', '256)))', 'escaped', '=', "b''.join((b'\\\\'", '+', 'encoded[i:i', '+', '1]', 'for', 'i', 'in', 'range(len(encoded))))', 'pattern', '=', 'GitWildMatchPattern(escaped)', 'results', '=', 'set(pattern.match([encoded]))', '...
543,735
mahossam/OptiGAN
utils_ace0.py
calc_los_angle
calc_los_angle
Calculates the los angle between two points.
[ "Calculates", "the", "los", "angle", "between", "two", "points." ]
def calc_los_angle(x1, y1, x2, y2): dy = y2 - y1 dx = x2 - x1 los = np.degrees(np.arctan2(dy, dx)) return los
['def', 'calc_los_angle(x1,', 'y1,', 'x2,', 'y2):', 'dy', '=', 'y2', '-', 'y1', 'dx', '=', 'x2', '-', 'x1', 'los', '=', 'np.degrees(np.arctan2(dy,', 'dx))', 'return', 'los']
776,319
thomasantony/runaway_robot
p2_noise.py
state_from_measurements
state_from_measurements
Estimates state of robot from the last three measurements Assumes each movement of robot is a "step" and a "turn" Three measurements constitute two moves, from which turn angle, heading and step size can be inferred.
[ "Estimates", "state", "of", "robot", "from", "the", "last", "three", "measurements", "Assumes", "each", "movement", "of", "robot", "is", "a", "\"step\"", "and", "a", "\"turn\"", "Three", "measurements", "constitute", "two", "moves,", "from", "which", "turn", "...
def state_from_measurements(three_measurements): (x1, y1) = three_measurements[-3] (x2, y2) = three_measurements[-2] (x3, y3) = three_measurements[-1] vec_1 = [x2 - x1, y2 - y1] vec_2 = [x3 - x2, y3 - y2] dot = sum((v1 * v2 for (v1, v2) in zip(vec_1, vec_2))) mag_v1 = sqrt(sum((v ** 2 for v ...
['def', 'state_from_measurements(three_measurements):', '(x1,', 'y1)', '=', 'three_measurements[-3]', '(x2,', 'y2)', '=', 'three_measurements[-2]', '(x3,', 'y3)', '=', 'three_measurements[-1]', 'vec_1', '=', '[x2', '-', 'x1,', 'y2', '-', 'y1]', 'vec_2', '=', '[x3', '-', 'x2,', 'y3', '-', 'y2]', 'dot', '=', 'sum((v1', '...
326,923
rudranil723/mini-main
padding.py
Padding.indent
indent
Make padding instance to render an indent.
[ "Make", "padding", "instance", "to", "render", "an", "indent." ]
def indent(cls, renderable: 'RenderableType', level: int) -> 'Padding': return Padding(renderable, pad=(0, 0, 0, level), expand=False)
['def', 'indent(cls,', 'renderable:', "'RenderableType',", 'level:', 'int)', '->', "'Padding':", 'return', 'Padding(renderable,', 'pad=(0,', '0,', '0,', 'level),', 'expand=False)']
268,914
zhangyp15/MonoFlex
instances.py
Instances.to
to
Returns: Instances: all fields are called with a `to(device)`, if the field has this method.
[ "Returns:", "Instances:", "all", "fields", "are", "called", "with", "a", "`to(device)`,", "if", "the", "field", "has", "this", "method." ]
def to(self, *args: Any, **kwargs: Any) -> 'Instances': ret = Instances(self._image_size) for (k, v) in self._fields.items(): if hasattr(v, 'to'): v = v.to(*args, **kwargs) ret.set(k, v) return ret
['def', 'to(self,', '*args:', 'Any,', '**kwargs:', 'Any)', '->', "'Instances':", 'ret', '=', 'Instances(self._image_size)', 'for', '(k,', 'v)', 'in', 'self._fields.items():', 'if', 'hasattr(v,', "'to'):", 'v', '=', 'v.to(*args,', '**kwargs)', 'ret.set(k,', 'v)', 'return', 'ret']
655,184
gunthercox/ChatterBot
bccache.py
Bucket.write_bytecode
write_bytecode
Dump the bytecode into the file or file like object passed.
[ "Dump", "the", "bytecode", "into", "the", "file", "or", "file", "like", "object", "passed." ]
def write_bytecode(self, f): if self.code is None: raise TypeError("can't write empty bucket") f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal_dump(self.code, f)
['def', 'write_bytecode(self,', 'f):', 'if', 'self.code', 'is', 'None:', 'raise', 'TypeError("can\'t', 'write', 'empty', 'bucket")', 'f.write(bc_magic)', 'pickle.dump(self.checksum,', 'f,', '2)', 'marshal_dump(self.code,', 'f)']
478,905
greydanus/mr_london
datastructures.py
MultiDict.lists
lists
Return a list of ``(key, values)`` pairs, where values is the list of all values associated with the key.
[ "Return", "a", "list", "of", "``(key,", "values)``", "pairs,", "where", "values", "is", "the", "list", "of", "all", "values", "associated", "with", "the", "key." ]
def lists(self): for (key, values) in iteritems(dict, self): yield (key, list(values))
['def', 'lists(self):', 'for', '(key,', 'values)', 'in', 'iteritems(dict,', 'self):', 'yield', '(key,', 'list(values))']
263,993
Vishal-V/StackGAN
model.py
StackGanStage2.train_stage2
train_stage2
Trains Stage 2 StackGAN.
[ "Trains", "Stage", "2", "StackGAN." ]
def train_stage2(self): (x_high_train, y_high_train, high_train_embeds) = load_data(filename_path=filename_path_train, class_id_path=class_id_path_train, dataset_path=dataset_path, embeddings_path=embeddings_path_train, size=(256, 256)) (x_high_test, y_high_test, high_test_embeds) = load_data(filename_path=file...
['def', 'train_stage2(self):', '(x_high_train,', 'y_high_train,', 'high_train_embeds)', '=', 'load_data(filename_path=filename_path_train,', 'class_id_path=class_id_path_train,', 'dataset_path=dataset_path,', 'embeddings_path=embeddings_path_train,', 'size=(256,', '256))', '(x_high_test,', 'y_high_test,', 'high_test_em...
873,367
devashish-patel/webcam-motion-detector
gen.py
WaitIterator.done
done
Returns True if this iterator has no more results.
[ "Returns", "True", "if", "this", "iterator", "has", "no", "more", "results." ]
def done(self): if self._finished or self._unfinished: return False self.current_index = self.current_future = None return True
['def', 'done(self):', 'if', 'self._finished', 'or', 'self._unfinished:', 'return', 'False', 'self.current_index', '=', 'self.current_future', '=', 'None', 'return', 'True']
984,929
instadeepai/jumanji
utils_test.py
TestObservationSpec.test_compute_time_penalties
test_compute_time_penalties
Test whether the compute_time_pentalties function works correctly.
[ "Test", "whether", "the", "compute_time_pentalties", "function", "works", "correctly." ]
def test_compute_time_penalties(self) -> None: local_times = np.array([1.0, 2.5, 4.0]) window_start = np.array([2.0, 2.0, 2.0]) window_end = np.array([3.0, 3.0, 3.0]) early_coefs = np.array([0.1, 0.15, 0.09]) late_coefs = np.array([0.5, 0.3, 0.7]) pentalties = compute_time_penalties(local_times,...
['def', 'test_compute_time_penalties(self)', '->', 'None:', 'local_times', '=', 'np.array([1.0,', '2.5,', '4.0])', 'window_start', '=', 'np.array([2.0,', '2.0,', '2.0])', 'window_end', '=', 'np.array([3.0,', '3.0,', '3.0])', 'early_coefs', '=', 'np.array([0.1,', '0.15,', '0.09])', 'late_coefs', '=', 'np.array([0.5,', '...
594,445
lixingjian/DELTA
text_nlu_joint_task.py
TextNLUJointTask.generate_data
generate_data
Generate data for offline training.
[ "Generate", "data", "for", "offline", "training." ]
def generate_data(self): if self.infer_without_label: column_num = 1 text_ds = load_textline_dataset(self.paths_after_pre_process, column_num) else: column_num = 3 (intent_label_ds, slots_label_ds, text_ds) = load_textline_dataset(self.paths_after_pre_process, column_num) log...
['def', 'generate_data(self):', 'if', 'self.infer_without_label:', 'column_num', '=', '1', 'text_ds', '=', 'load_textline_dataset(self.paths_after_pre_process,', 'column_num)', 'else:', 'column_num', '=', '3', '(intent_label_ds,', 'slots_label_ds,', 'text_ds)', '=', 'load_textline_dataset(self.paths_after_pre_process,'...
537,443
charlesq34/frustum-pointnets
test_drawline.py
test_plot3d
test_plot3d
Generates a pretty set of lines.
[ "Generates", "a", "pretty", "set", "of", "lines." ]
def test_plot3d(): (n_mer, n_long) = (6, 11) pi = numpy.pi dphi = pi / 1000.0 phi = numpy.arange(0.0, 2 * pi + 0.5 * dphi, dphi) mu = phi * n_mer x = numpy.cos(mu) * (1 + numpy.cos(n_long * mu / n_mer) * 0.5) y = numpy.sin(mu) * (1 + numpy.cos(n_long * mu / n_mer) * 0.5) z = numpy.sin(n_...
['def', 'test_plot3d():', '(n_mer,', 'n_long)', '=', '(6,', '11)', 'pi', '=', 'numpy.pi', 'dphi', '=', 'pi', '/', '1000.0', 'phi', '=', 'numpy.arange(0.0,', '2', '*', 'pi', '+', '0.5', '*', 'dphi,', 'dphi)', 'mu', '=', 'phi', '*', 'n_mer', 'x', '=', 'numpy.cos(mu)', '*', '(1', '+', 'numpy.cos(n_long', '*', 'mu', '/', '...
564,925
zcablii/LSKNet
split.py
get_multiscale_patch
get_multiscale_patch
Get multiscale patch sizes and steps.
[ "Get", "multiscale", "patch", "sizes", "and", "steps." ]
def get_multiscale_patch(sizes, steps, ratios): assert len(sizes) == len(steps), 'The length of `sizes` and `steps`should be the same.' (new_sizes, new_steps) = ([], []) size_steps = list(zip(sizes, steps)) for ((size, step), ratio) in product(size_steps, ratios): new_sizes.append(int(size / rat...
['def', 'get_multiscale_patch(sizes,', 'steps,', 'ratios):', 'assert', 'len(sizes)', '==', 'len(steps),', "'The", 'length', 'of', '`sizes`', 'and', '`steps`should', 'be', 'the', "same.'", '(new_sizes,', 'new_steps)', '=', '([],', '[])', 'size_steps', '=', 'list(zip(sizes,', 'steps))', 'for', '((size,', 'step),', 'ratio...
616,079
hamza-murad/AALU
tone_analyzer_v3.py
SentenceAnalysis.from_dict
from_dict
Initialize a SentenceAnalysis object from a json dictionary.
[ "Initialize", "a", "SentenceAnalysis", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': args = {} valid_keys = ['sentence_id', 'text', 'tones', 'tone_categories', 'input_from', 'input_to'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class SentenceAna...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'SentenceAnalysis':", 'args', '=', '{}', 'valid_keys', '=', "['sentence_id',", "'text',", "'tones',", "'tone_categories',", "'input_from',", "'input_to']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecogni...
6,114
RLE-Foundation/rllte
ddpg.py
DDPG.update_actor
update_actor
Update the actor network.
[ "Update", "the", "actor", "network." ]
def update_actor(self, obs: th.Tensor) -> Dict[str, float]: dist = self.policy.get_dist(obs, step=self.global_step) action = dist.sample(clip=True) (Q1, Q2) = self.policy.critic(obs, action) Q = th.min(Q1, Q2) actor_loss = -Q.mean() self.policy.optimizers['actor_opt'].zero_grad(set_to_none=True)...
['def', 'update_actor(self,', 'obs:', 'th.Tensor)', '->', 'Dict[str,', 'float]:', 'dist', '=', 'self.policy.get_dist(obs,', 'step=self.global_step)', 'action', '=', 'dist.sample(clip=True)', '(Q1,', 'Q2)', '=', 'self.policy.critic(obs,', 'action)', 'Q', '=', 'th.min(Q1,', 'Q2)', 'actor_loss', '=', '-Q.mean()', "self.po...
333,215
carlos-ferras/Sequence-ToolKit
WidgetGroup.py
WidgetGroup.checkForChildren
checkForChildren
Return true if we should automatically search the children of this object for more.
[ "Return", "true", "if", "we", "should", "automatically", "search", "the", "children", "of", "this", "object", "for", "more." ]
def checkForChildren(self, obj): iface = self.interface(obj) return len(iface) > 3 and iface[3]
['def', 'checkForChildren(self,', 'obj):', 'iface', '=', 'self.interface(obj)', 'return', 'len(iface)', '>', '3', 'and', 'iface[3]']
876,767
TonyLianLong/VAI-ReinforcementLearning
reacher.py
hard
hard
Returns reacher with sparse reward with 1e-2 tol and randomized target.
[ "Returns", "reacher", "with", "sparse", "reward", "with", "1e-2", "tol", "and", "randomized", "target." ]
def hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): physics = Physics.from_xml_string(*get_model_and_assets()) task = Reacher(target_size=_SMALL_TARGET, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limi...
['def', 'hard(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'Reacher(target_size=_SMALL_TARGET,', 'random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'return', 'control.Environmen...
440,969
googleinterns/ddsp-docker
ddsp_ai_platform.py
get_input
get_input
Gathers input from user.
[ "Gathers", "input", "from", "user." ]
def get_input(): msg = 'Path to training dataset directory' if FLAGS.data_path: data_path = check_bucket(FLAGS.data_path, msg) else: data_path = prompt_gs_path(msg, required=True) msg = 'Path for saving model, snapshots and summaries' if FLAGS.save_dir: save_dir = check_bucke...
['def', 'get_input():', 'msg', '=', "'Path", 'to', 'training', 'dataset', "directory'", 'if', 'FLAGS.data_path:', 'data_path', '=', 'check_bucket(FLAGS.data_path,', 'msg)', 'else:', 'data_path', '=', 'prompt_gs_path(msg,', 'required=True)', 'msg', '=', "'Path", 'for', 'saving', 'model,', 'snapshots', 'and', "summaries'...
516,401
matsu0228/nlp-jp
phrases.py
Phrases.learn_vocab
learn_vocab
Collect unigram/bigram counts from the `sentences` iterable.
[ "Collect", "unigram/bigram", "counts", "from", "the", "`sentences`", "iterable." ]
def learn_vocab(sentences, max_vocab_size, delimiter=b'_', progress_per=10000, common_terms=frozenset()): sentence_no = -1 total_words = 0 logger.info('collecting all words and their counts') vocab = defaultdict(int) min_reduce = 1 for (sentence_no, sentence) in enumerate(sentences): if ...
['def', 'learn_vocab(sentences,', 'max_vocab_size,', "delimiter=b'_',", 'progress_per=10000,', 'common_terms=frozenset()):', 'sentence_no', '=', '-1', 'total_words', '=', '0', "logger.info('collecting", 'all', 'words', 'and', 'their', "counts')", 'vocab', '=', 'defaultdict(int)', 'min_reduce', '=', '1', 'for', '(senten...
785,886
claws-lab/petgen
text_process.py
build_embedding_matrix
build_embedding_matrix
Load or build Glove embedding matrix.
[ "Load", "or", "build", "Glove", "embedding", "matrix." ]
def build_embedding_matrix(dataset): embed_filename = 'dataset/glove_embedding_300d_{}.pt'.format(dataset) if os.path.exists(embed_filename): print('Loading embedding:', embed_filename) embedding_matrix = torch.load(embed_filename) else: print('Loading Glove word vectors...') ...
['def', 'build_embedding_matrix(dataset):', 'embed_filename', '=', "'dataset/glove_embedding_300d_{}.pt'.format(dataset)", 'if', 'os.path.exists(embed_filename):', "print('Loading", "embedding:',", 'embed_filename)', 'embedding_matrix', '=', 'torch.load(embed_filename)', 'else:', "print('Loading", 'Glove', 'word', "vec...
767,399
myothida/Supervised-Machine-Learning
text.py
Text.remove_suffix
remove_suffix
Remove a suffix if it exists.
[ "Remove", "a", "suffix", "if", "it", "exists." ]
def remove_suffix(self, suffix: str) -> None: if self.plain.endswith(suffix): self.right_crop(len(suffix))
['def', 'remove_suffix(self,', 'suffix:', 'str)', '->', 'None:', 'if', 'self.plain.endswith(suffix):', 'self.right_crop(len(suffix))']
445,115
triaquae/triaquae
test_geos.py
GEOSTest.test_base
test_base
Tests out the GEOSBase class.
[ "Tests", "out", "the", "GEOSBase", "class." ]
def test_base(self): class FakeGeom1(GEOSBase): pass c_float_p = ctypes.POINTER(ctypes.c_float) class FakeGeom2(GEOSBase): ptr_type = c_float_p fg1 = FakeGeom1() fg2 = FakeGeom2() fg1.ptr = ctypes.c_void_p() fg1.ptr = None fg2.ptr = c_float_p(ctypes.c_float(5.23)) f...
['def', 'test_base(self):', 'class', 'FakeGeom1(GEOSBase):', 'pass', 'c_float_p', '=', 'ctypes.POINTER(ctypes.c_float)', 'class', 'FakeGeom2(GEOSBase):', 'ptr_type', '=', 'c_float_p', 'fg1', '=', 'FakeGeom1()', 'fg2', '=', 'FakeGeom2()', 'fg1.ptr', '=', 'ctypes.c_void_p()', 'fg1.ptr', '=', 'None', 'fg2.ptr', '=', 'c_fl...
357,875
msahasrabudhe/crosswise_sparse_autoencoder_pytorch
datasets.py
pil_loader
pil_loader
pil_loader ::: Uses PIL to read images.
[ "pil_loader", ":::", "Uses", "PIL", "to", "read", "images." ]
def pil_loader(path): img = Image.open(path) return img
['def', 'pil_loader(path):', 'img', '=', 'Image.open(path)', 'return', 'img']
492,047
commonsense/simplenlp
word.py
JaDeNai.lemma_form
lemma_form
Returns the lemma form of this verb Returns deAru for all cases, regardless of actual form.
[ "Returns", "the", "lemma", "form", "of", "this", "verb", "Returns", "deAru", "for", "all", "cases,", "regardless", "of", "actual", "form." ]
def lemma_form(self): return 'ãÂ\x81§ãÂ\x81Â\x82ãÂ\x82Â\x8b'
['def', 'lemma_form(self):', 'return', "'ãÂ\\x81§ãÂ\\x81Â\\x82ãÂ\\x82Â\\x8b'"]
883,360
tensorflow/agents
utils.py
TimeHistory.on_batch_end
on_batch_end
Records elapse time of the batch and calculates examples per second.
[ "Records", "elapse", "time", "of", "the", "batch", "and", "calculates", "examples", "per", "second." ]
def on_batch_end(self): if self.global_steps % self.log_steps == 0: timestamp = time.time() elapsed_time = timestamp - self.start_time steps_per_second = self.log_steps / elapsed_time examples_per_second = steps_per_second * self.batch_size step_time = elapsed_time / self.log...
['def', 'on_batch_end(self):', 'if', 'self.global_steps', '%', 'self.log_steps', '==', '0:', 'timestamp', '=', 'time.time()', 'elapsed_time', '=', 'timestamp', '-', 'self.start_time', 'steps_per_second', '=', 'self.log_steps', '/', 'elapsed_time', 'examples_per_second', '=', 'steps_per_second', '*', 'self.batch_size', ...
23,368
rfk/playitagainsam
util.py
set_terminal_size
set_terminal_size
Set the (width, height) size tuple for the given pty fd.
[ "Set", "the", "(width,", "height)", "size", "tuple", "for", "the", "given", "pty", "fd." ]
def set_terminal_size(fd, size): sizebuf = array.array('h', reversed(size)) fcntl.ioctl(fd, termios.TIOCSWINSZ, sizebuf)
['def', 'set_terminal_size(fd,', 'size):', 'sizebuf', '=', "array.array('h',", 'reversed(size))', 'fcntl.ioctl(fd,', 'termios.TIOCSWINSZ,', 'sizebuf)']
305,504
tobegit3hub/deep_image_model
saver.py
generate_checkpoint_state_proto
generate_checkpoint_state_proto
Generates a checkpoint state proto.
[ "Generates", "a", "checkpoint", "state", "proto." ]
def generate_checkpoint_state_proto(save_dir, model_checkpoint_path, all_model_checkpoint_paths=None): if all_model_checkpoint_paths is None: all_model_checkpoint_paths = [] if not all_model_checkpoint_paths or all_model_checkpoint_paths[-1] != model_checkpoint_path: logging.info('%s is not in a...
['def', 'generate_checkpoint_state_proto(save_dir,', 'model_checkpoint_path,', 'all_model_checkpoint_paths=None):', 'if', 'all_model_checkpoint_paths', 'is', 'None:', 'all_model_checkpoint_paths', '=', '[]', 'if', 'not', 'all_model_checkpoint_paths', 'or', 'all_model_checkpoint_paths[-1]', '!=', 'model_checkpoint_path:...
183,346
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
gaussian_moments.py
compute_log_moment
compute_log_moment
Compute the log moment of Gaussian mechanism for given parameters.
[ "Compute", "the", "log", "moment", "of", "Gaussian", "mechanism", "for", "given", "parameters." ]
def compute_log_moment(q, sigma, steps, lmbd, verify=False, verbose=False): moment = compute_a(sigma, q, lmbd, verbose=verbose) if verify: mp.dps = 50 moment_a_mp = compute_a_mp(sigma, q, lmbd, verbose=verbose) moment_b_mp = compute_b_mp(sigma, q, lmbd, verbose=verbose) np.testin...
['def', 'compute_log_moment(q,', 'sigma,', 'steps,', 'lmbd,', 'verify=False,', 'verbose=False):', 'moment', '=', 'compute_a(sigma,', 'q,', 'lmbd,', 'verbose=verbose)', 'if', 'verify:', 'mp.dps', '=', '50', 'moment_a_mp', '=', 'compute_a_mp(sigma,', 'q,', 'lmbd,', 'verbose=verbose)', 'moment_b_mp', '=', 'compute_b_mp(si...
54,085
pranjaldatta/PyVision
ImageBuffer.py
ImageBuffer.getCount
getCount
Note that getCount() differs from __len__() in that this method returns the number of image actually stored in the ImageBuffer, while __len__() returns the size of the buffer, defined as the number of images the buffer is allowed to store.
[ "Note", "that", "getCount()", "differs", "from", "__len__()", "in", "that", "this", "method", "returns", "the", "number", "of", "image", "actually", "stored", "in", "the", "ImageBuffer,", "while", "__len__()", "returns", "the", "size", "of", "the", "buffer,", ...
def getCount(self): return self._count
['def', 'getCount(self):', 'return', 'self._count']
815,910
RasaHQ/rasa
train.py
add_force_param
add_force_param
Specifies if the model should be trained from scratch.
[ "Specifies", "if", "the", "model", "should", "be", "trained", "from", "scratch." ]
def add_force_param(parser: Union[argparse.ArgumentParser, argparse._ActionsContainer]) -> None: parser.add_argument('--force', action='store_true', help='Force a model training even if the data has not changed.')
['def', 'add_force_param(parser:', 'Union[argparse.ArgumentParser,', 'argparse._ActionsContainer])', '->', 'None:', "parser.add_argument('--force',", "action='store_true',", "help='Force", 'a', 'model', 'training', 'even', 'if', 'the', 'data', 'has', 'not', "changed.')"]
836,661
mj-will/nessai
test_distance_converters.py
test_power_law_converter_missing_power
test_power_law_converter_missing_power
Assert an error is raised if the power is not specified.
[ "Assert", "an", "error", "is", "raised", "if", "the", "power", "is", "not", "specified." ]
def test_power_law_converter_missing_power(): with pytest.raises(RuntimeError) as excinfo: PowerLawConverter(power=None) assert 'Must specify the power' in str(excinfo.value)
['def', 'test_power_law_converter_missing_power():', 'with', 'pytest.raises(RuntimeError)', 'as', 'excinfo:', 'PowerLawConverter(power=None)', 'assert', "'Must", 'specify', 'the', "power'", 'in', 'str(excinfo.value)']
292,603
melfm/ibit
jaco_physics.py
JacoPhysics.step
step
Advances physics with up-to-date position and velocity dependent fields.
[ "Advances", "physics", "with", "up-to-date", "position", "and", "velocity", "dependent", "fields." ]
def step(self, control): self.handle_state(self.robot_client.step(command_type='ANGLE', relative=False, unit='rad', data=control)) return self.get_state()
['def', 'step(self,', 'control):', "self.handle_state(self.robot_client.step(command_type='ANGLE',", 'relative=False,', "unit='rad',", 'data=control))', 'return', 'self.get_state()']
596,846
Kvatsx/Artificial-Intelligence-Assignments
test_templateexporter.py
TestExporter.test_raw_template_assignment
test_raw_template_assignment
Test `raw_template` assigned after the fact on non-custom Exporter.
[ "Test", "`raw_template`", "assigned", "after", "the", "fact", "on", "non-custom", "Exporter." ]
def test_raw_template_assignment(self): nb = v4.new_notebook() nb.cells.append(v4.new_code_cell('some_text')) exporter_assign = TemplateExporter() exporter_assign.raw_template = raw_template (output_assign, _) = exporter_assign.from_notebook_node(nb) assert 'blah' in output_assign
['def', 'test_raw_template_assignment(self):', 'nb', '=', 'v4.new_notebook()', "nb.cells.append(v4.new_code_cell('some_text'))", 'exporter_assign', '=', 'TemplateExporter()', 'exporter_assign.raw_template', '=', 'raw_template', '(output_assign,', '_)', '=', 'exporter_assign.from_notebook_node(nb)', 'assert', "'blah'", ...
1,744
vghost2008/wml1
coco_evaluation_test.py
CocoKeypointEvaluationTest.testIgnoresCrowdAnnotations
testIgnoresCrowdAnnotations
Tests that the evaluator ignores GT marked as crowd.
[ "Tests", "that", "the", "evaluator", "ignores", "GT", "marked", "as", "crowd." ]
def testIgnoresCrowdAnnotations(self): category_keypoint_dict = _get_category_keypoints_dict() coco_evaluator = coco_evaluation.CocoKeypointEvaluator(category_id=1, category_keypoints=category_keypoint_dict['person'], class_text='person') coco_evaluator.add_single_ground_truth_image_info(image_id='image1', ...
['def', 'testIgnoresCrowdAnnotations(self):', 'category_keypoint_dict', '=', '_get_category_keypoints_dict()', 'coco_evaluator', '=', 'coco_evaluation.CocoKeypointEvaluator(category_id=1,', "category_keypoints=category_keypoint_dict['person'],", "class_text='person')", "coco_evaluator.add_single_ground_truth_image_info...
960,338
Ruturaj123/Flowchart-Detection
compat.py
as_str_any
as_str_any
Converts to `str` as `str(value)`, but use `as_str` for `bytes`.
[ "Converts", "to", "`str`", "as", "`str(value)`,", "but", "use", "`as_str`", "for", "`bytes`." ]
def as_str_any(value): if isinstance(value, bytes): return as_str(value) else: return str(value)
['def', 'as_str_any(value):', 'if', 'isinstance(value,', 'bytes):', 'return', 'as_str(value)', 'else:', 'return', 'str(value)']
606,638
matsu0228/nlp-jp
protocol.py
TelnetProtocolParser.do_received
do_received
Received telnet DO command.
[ "Received", "telnet", "DO", "command." ]
def do_received(self, data): logger.info('DO %r', data)
['def', 'do_received(self,', 'data):', "logger.info('DO", "%r',", 'data)']
804,375
huawei-noah/xingtian
metrics.py
MetricBase.objective
objective
Define reward mode, default is max.
[ "Define", "reward", "mode,", "default", "is", "max." ]
def objective(self): return 'MAX'
['def', 'objective(self):', 'return', "'MAX'"]
962,658
enuguru/artificial_intelligence_and_machine_
writing.py
SegmentWriter.has_deletions
has_deletions
Returns True if the current index has documents that are marked deleted but haven't been optimized out of the index yet.
[ "Returns", "True", "if", "the", "current", "index", "has", "documents", "that", "are", "marked", "deleted", "but", "haven't", "been", "optimized", "out", "of", "the", "index", "yet." ]
def has_deletions(self): return any((s.has_deletions() for s in self.segments))
['def', 'has_deletions(self):', 'return', 'any((s.has_deletions()', 'for', 's', 'in', 'self.segments))']
133,234
wandb/wandb
step_prepare.py
StepPrepare.prepare_async
prepare_async
Request the backend to prepare a file for upload.
[ "Request", "the", "backend", "to", "prepare", "a", "file", "for", "upload." ]
def prepare_async(self, file_spec: 'CreateArtifactFileSpecInput') -> 'asyncio.Future[ResponsePrepare]': response: asyncio.Future[ResponsePrepare] = asyncio.Future() self._request_queue.put(RequestPrepare(file_spec, (asyncio.get_event_loop(), response))) return response
['def', 'prepare_async(self,', 'file_spec:', "'CreateArtifactFileSpecInput')", '->', "'asyncio.Future[ResponsePrepare]':", 'response:', 'asyncio.Future[ResponsePrepare]', '=', 'asyncio.Future()', 'self._request_queue.put(RequestPrepare(file_spec,', '(asyncio.get_event_loop(),', 'response)))', 'return', 'response']
941,522
openvinotoolkit/training_extensions
io.py
save_saliency_output
save_saliency_output
Saves processed saliency map (with image overlay) or raw saliency map.
[ "Saves", "processed", "saliency", "map", "(with", "image", "overlay)", "or", "raw", "saliency", "map." ]
def save_saliency_output(process_saliency_maps: bool, img: np.array, saliency_map: np.array, save_dir: str, fname: str, weight: float=0.3) -> None: if process_saliency_maps: overlay = img * weight + saliency_map * (1 - weight) overlay[overlay > 255] = 255 overlay = overlay.astype(np.uint8) ...
['def', 'save_saliency_output(process_saliency_maps:', 'bool,', 'img:', 'np.array,', 'saliency_map:', 'np.array,', 'save_dir:', 'str,', 'fname:', 'str,', 'weight:', 'float=0.3)', '->', 'None:', 'if', 'process_saliency_maps:', 'overlay', '=', 'img', '*', 'weight', '+', 'saliency_map', '*', '(1', '-', 'weight)', 'overlay...
919,008
jshilong/DDQ
colorspace.py
rgb2gray
rgb2gray
Convert a RGB image to grayscale image.
[ "Convert", "a", "RGB", "image", "to", "grayscale", "image." ]
def rgb2gray(img, keepdim=False): out_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) if keepdim: out_img = out_img[..., None] return out_img
['def', 'rgb2gray(img,', 'keepdim=False):', 'out_img', '=', 'cv2.cvtColor(img,', 'cv2.COLOR_RGB2GRAY)', 'if', 'keepdim:', 'out_img', '=', 'out_img[...,', 'None]', 'return', 'out_img']
499,040
clear-nus/MuMMI
ball_in_cup.py
BallInCup.get_observation
get_observation
Returns an observation of the state.
[ "Returns", "an", "observation", "of", "the", "state." ]
def get_observation(self, physics): obs = collections.OrderedDict() obs['position'] = physics.position() obs['velocity'] = physics.velocity() obs['touch'] = physics.touchs() return obs
['def', 'get_observation(self,', 'physics):', 'obs', '=', 'collections.OrderedDict()', "obs['position']", '=', 'physics.position()', "obs['velocity']", '=', 'physics.velocity()', "obs['touch']", '=', 'physics.touchs()', 'return', 'obs']
265,894
YuYaoYang2333/SyntaLinker
inputter.py
load_old_vocab
load_old_vocab
Update a legacy vocab/field format.
[ "Update", "a", "legacy", "vocab/field", "format." ]
def load_old_vocab(vocab, data_type='text', dynamic_dict=False): if _old_style_vocab(vocab): vocab = dict(vocab) n_src_features = sum(('src_feat_' in k for k in vocab)) n_tgt_features = sum(('tgt_feat_' in k for k in vocab)) fields = get_fields(data_type, n_src_features, n_tgt_featur...
['def', 'load_old_vocab(vocab,', "data_type='text',", 'dynamic_dict=False):', 'if', '_old_style_vocab(vocab):', 'vocab', '=', 'dict(vocab)', 'n_src_features', '=', "sum(('src_feat_'", 'in', 'k', 'for', 'k', 'in', 'vocab))', 'n_tgt_features', '=', "sum(('tgt_feat_'", 'in', 'k', 'for', 'k', 'in', 'vocab))', 'fields', '='...
905,890
enuguru/artificial_intelligence_and_machine_learning
pkg_resources.py
safe_version
safe_version
Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash.
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string", "Spaces", "become", "dots,", "and", "all", "other", "non-alphanumeric", "characters", "become", "dashes,", "with", "runs", "of", "multiple", "dashes", "condensed", "to", "a", "si...
def safe_version(version): version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
['def', 'safe_version(version):', 'version', '=', "version.replace('", "',", "'.')", 'return', "re.sub('[^A-Za-z0-9.]+',", "'-',", 'version)']
156,671
ZumoLabs/zpy
cli.py
get_dataset
get_dataset
get dataset Download dataset of type DTYPE and name NAME to local PATH from backend.
[ "get", "dataset", "Download", "dataset", "of", "type", "DTYPE", "and", "name", "NAME", "to", "local", "PATH", "from", "backend." ]
def get_dataset(name, path, format): from cli.datasets import download_dataset from cli.utils import download_url try: output_path = download_dataset(name, path) click.echo(f"Downloaded dataset '{name}' to {output_path}") except requests.exceptions.HTTPError as e: click.secho(f'F...
['def', 'get_dataset(name,', 'path,', 'format):', 'from', 'cli.datasets', 'import', 'download_dataset', 'from', 'cli.utils', 'import', 'download_url', 'try:', 'output_path', '=', 'download_dataset(name,', 'path)', 'click.echo(f"Downloaded', 'dataset', "'{name}'", 'to', '{output_path}")', 'except', 'requests.exceptions....
971,902
tensorflow/hub
native_module_test.py
layers_module_fn
layers_module_fn
Module that exercises the use of layers.
[ "Module", "that", "exercises", "the", "use", "of", "layers." ]
def layers_module_fn(): x = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 2], name='x') def l2(weights): with tf.control_dependencies([weights]): return 2.0 * tf.compat.v1.nn.l2_loss(weights) h = tf.compat.v1.layers.dense(x, 2, activation=None, kernel_regularizer=l2, bias_regu...
['def', 'layers_module_fn():', 'x', '=', 'tf.compat.v1.placeholder(dtype=tf.float32,', 'shape=[None,', '2],', "name='x')", 'def', 'l2(weights):', 'with', 'tf.control_dependencies([weights]):', 'return', '2.0', '*', 'tf.compat.v1.nn.l2_loss(weights)', 'h', '=', 'tf.compat.v1.layers.dense(x,', '2,', 'activation=None,', '...
570,993
LittleWat/multichannel-semseg-with-uda
dann_solver.py
Solver.train
train
Train generator and discriminator.
[ "Train", "generator", "and", "discriminator." ]
def train(self): src_domain_lbl = Variable(torch.ones(args.batch_size).long()) tgt_domain_lbl = Variable(torch.zeros(args.batch_size).long()) for epoch in range(args.start_epoch, args.epochs): d_loss_per_epoch = 0 c_loss_per_epoch = 0 for (ind, (source, target)) in tqdm.tqdm(enumerat...
['def', 'train(self):', 'src_domain_lbl', '=', 'Variable(torch.ones(args.batch_size).long())', 'tgt_domain_lbl', '=', 'Variable(torch.zeros(args.batch_size).long())', 'for', 'epoch', 'in', 'range(args.start_epoch,', 'args.epochs):', 'd_loss_per_epoch', '=', '0', 'c_loss_per_epoch', '=', '0', 'for', '(ind,', '(source,',...
643,547
eric-haibin-lin/nlp-notebooks
pretraining_utils.py
save_states
save_states
Save the trainer states, marked by step_num.
[ "Save", "the", "trainer", "states,", "marked", "by", "step_num." ]
def save_states(step_num, trainer, ckpt_dir, local_rank=0): trainer_path = os.path.join(ckpt_dir, '%07d.states.%02d' % (step_num, local_rank)) logging.info('[step %d] Saving trainer states to %s.', step_num, trainer_path) nlp.utils.save_states(trainer, trainer_path)
['def', 'save_states(step_num,', 'trainer,', 'ckpt_dir,', 'local_rank=0):', 'trainer_path', '=', 'os.path.join(ckpt_dir,', "'%07d.states.%02d'", '%', '(step_num,', 'local_rank))', "logging.info('[step", '%d]', 'Saving', 'trainer', 'states', 'to', "%s.',", 'step_num,', 'trainer_path)', 'nlp.utils.save_states(trainer,', ...
730,880
ryu-ed/SpaceInvaders_Ros
brain_namedtuple_enum.py
infer_func_form
infer_func_form
Specific inference function for namedtuple or Python 3 enum.
[ "Specific", "inference", "function", "for", "namedtuple", "or", "Python", "3", "enum." ]
def infer_func_form(node, base_type, context=None, enum=False): try: (name, names) = _find_func_form_arguments(node, context) try: attributes = names.value.replace(',', ' ').split() except AttributeError: if not enum: attributes = [_infer_first(const, ...
['def', 'infer_func_form(node,', 'base_type,', 'context=None,', 'enum=False):', 'try:', '(name,', 'names)', '=', '_find_func_form_arguments(node,', 'context)', 'try:', 'attributes', '=', "names.value.replace(',',", "'", "').split()", 'except', 'AttributeError:', 'if', 'not', 'enum:', 'attributes', '=', '[_infer_first(c...
394,559
triaquae/triaquae
envelope.py
Envelope.max_x
max_x
Returns the value of the maximum X coordinate.
[ "Returns", "the", "value", "of", "the", "maximum", "X", "coordinate." ]
def max_x(self): return self._envelope.MaxX
['def', 'max_x(self):', 'return', 'self._envelope.MaxX']
357,534
alomax/ConvNetQuake_INGV
models.py
get
get
Returns a Model instance instance by model name.
[ "Returns", "a", "Model", "instance", "instance", "by", "model", "name." ]
def get(model_name, inputs, config, checkpoint_dir, is_training=False): return globals()[model_name](inputs, config, checkpoint_dir, is_training=is_training)
['def', 'get(model_name,', 'inputs,', 'config,', 'checkpoint_dir,', 'is_training=False):', 'return', 'globals()[model_name](inputs,', 'config,', 'checkpoint_dir,', 'is_training=is_training)']
136,907
cvjena/PartDetectorDisovery
deconvolution.py
DeconvolutionLayer.forward
forward
Runs the forward pass.
[ "Runs", "the", "forward", "pass." ]
def forward(self, bottom, top): bottom_data = bottom[0].data() if bottom_data.ndim != 4: raise ValueError('Bottom data should be a 4-dim tensor.') if not self._kernels.has_data(): self._kernels.init_data((bottom_data.shape[-1], self._ksize * self._ksize * self._num_channels), bottom_data.dty...
['def', 'forward(self,', 'bottom,', 'top):', 'bottom_data', '=', 'bottom[0].data()', 'if', 'bottom_data.ndim', '!=', '4:', 'raise', "ValueError('Bottom", 'data', 'should', 'be', 'a', '4-dim', "tensor.')", 'if', 'not', 'self._kernels.has_data():', 'self._kernels.init_data((bottom_data.shape[-1],', 'self._ksize', '*', 's...
278,345
hamza-murad/AALU
compare_comply_v1.py
Value.from_dict
from_dict
Initialize a Value object from a json dictionary.
[ "Initialize", "a", "Value", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'Value': args = {} valid_keys = ['cell_id', 'location', 'text'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class Value: ' + ', '.join(bad_keys)) if 'cell_id' in _dict: a...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'Value':", 'args', '=', '{}', 'valid_keys', '=', "['cell_id',", "'location',", "'text']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Val...
5,464
microsoft/InnerEye-DeepLearning
deep_learning_config.py
OutputParams.checkpoint_folder
checkpoint_folder
Gets the full path in which the model checkpoints should be stored during training.
[ "Gets", "the", "full", "path", "in", "which", "the", "model", "checkpoints", "should", "be", "stored", "during", "training." ]
def checkpoint_folder(self) -> Path: return self.outputs_folder / CHECKPOINT_FOLDER
['def', 'checkpoint_folder(self)', '->', 'Path:', 'return', 'self.outputs_folder', '/', 'CHECKPOINT_FOLDER']
612,861
SamsungLabs/fcaf3d
centerpoint_head.py
CenterHead.get_targets_single
get_targets_single
Generate training targets for a single sample.
[ "Generate", "training", "targets", "for", "a", "single", "sample." ]
def get_targets_single(self, gt_bboxes_3d, gt_labels_3d): device = gt_labels_3d.device gt_bboxes_3d = torch.cat((gt_bboxes_3d.gravity_center, gt_bboxes_3d.tensor[:, 3:]), dim=1).to(device) max_objs = self.train_cfg['max_objs'] * self.train_cfg['dense_reg'] grid_size = torch.tensor(self.train_cfg['grid_s...
['def', 'get_targets_single(self,', 'gt_bboxes_3d,', 'gt_labels_3d):', 'device', '=', 'gt_labels_3d.device', 'gt_bboxes_3d', '=', 'torch.cat((gt_bboxes_3d.gravity_center,', 'gt_bboxes_3d.tensor[:,', '3:]),', 'dim=1).to(device)', 'max_objs', '=', "self.train_cfg['max_objs']", '*', "self.train_cfg['dense_reg']", 'grid_si...
560,422
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
lstm.py
lstm
lstm
Adds a stack of LSTM layers on top of input.
[ "Adds", "a", "stack", "of", "LSTM", "layers", "on", "top", "of", "input." ]
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): layers = [_dropout_lstm_cell(hparams, train) for _ in range(hparams.num_hidden_layers)] with tf.variable_scope(name): return tf.nn.dynamic_rnn(tf.contrib.rnn.MultiRNNCell(layers), inputs, sequence_length, initial_state=initial_...
['def', 'lstm(inputs,', 'sequence_length,', 'hparams,', 'train,', 'name,', 'initial_state=None):', 'layers', '=', '[_dropout_lstm_cell(hparams,', 'train)', 'for', '_', 'in', 'range(hparams.num_hidden_layers)]', 'with', 'tf.variable_scope(name):', 'return', 'tf.nn.dynamic_rnn(tf.contrib.rnn.MultiRNNCell(layers),', 'inpu...
965,640
nhsx/SynthVAE
base.py
BaseTransformer.reverse_transform
reverse_transform
Revert the transformations to the original values.
[ "Revert", "the", "transformations", "to", "the", "original", "values." ]
def reverse_transform(self, data, drop=True): if any((column not in data.columns for column in self.output_columns)): return data data = data.copy() columns_data = self._get_columns_data(data, self.output_columns) reversed_data = self._reverse_transform(columns_data) self._set_columns_data(d...
['def', 'reverse_transform(self,', 'data,', 'drop=True):', 'if', 'any((column', 'not', 'in', 'data.columns', 'for', 'column', 'in', 'self.output_columns)):', 'return', 'data', 'data', '=', 'data.copy()', 'columns_data', '=', 'self._get_columns_data(data,', 'self.output_columns)', 'reversed_data', '=', 'self._reverse_tr...
906,370
lektor/lektor-archive
datamodel.py
PaginationConfig.count_pages
count_pages
Returns the total number of pages for the children of a record.
[ "Returns", "the", "total", "number", "of", "pages", "for", "the", "children", "of", "a", "record." ]
def count_pages(self, record): total = record.children.count() return int(math.ceil(total / float(self.per_page)))
['def', 'count_pages(self,', 'record):', 'total', '=', 'record.children.count()', 'return', 'int(math.ceil(total', '/', 'float(self.per_page)))']
216,361
kubeflow/pipelines
utils.py
get_temporal_fusion_transformer_forecasting_pipeline_and_parameters
get_temporal_fusion_transformer_forecasting_pipeline_and_parameters
Returns tft_forecasting pipeline and formatted parameters.
[ "Returns", "tft_forecasting", "pipeline", "and", "formatted", "parameters." ]
def get_temporal_fusion_transformer_forecasting_pipeline_and_parameters(*, project: str, location: str, root_dir: str, target_column: str, optimization_objective: str, transformations: Dict[str, List[str]], train_budget_milli_node_hours: float, time_column: str, time_series_identifier_columns: List[str], time_series_id...
['def', 'get_temporal_fusion_transformer_forecasting_pipeline_and_parameters(*,', 'project:', 'str,', 'location:', 'str,', 'root_dir:', 'str,', 'target_column:', 'str,', 'optimization_objective:', 'str,', 'transformations:', 'Dict[str,', 'List[str]],', 'train_budget_milli_node_hours:', 'float,', 'time_column:', 'str,',...
770,843
PacktPublishing/Hands-On-Artificial--for-Banking
user_agent.py
UserAgentMixin.user_agent
user_agent
The current user agent.
[ "The", "current", "user", "agent." ]
def user_agent(self): return UserAgent(self.environ)
['def', 'user_agent(self):', 'return', 'UserAgent(self.environ)']
205,116
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_007b.py
rnn_classifier_split
rnn_classifier_split
Splits a RNN model in groups.
[ "Splits", "a", "RNN", "model", "in", "groups." ]
def rnn_classifier_split(model: Model) -> List[Model]: groups = [nn.Sequential(model[0].encoder, model[0].encoder_dp)] groups += [nn.Sequential(rnn, dp) for (rnn, dp) in zip(model[0].rnns, model[0].hidden_dps)] groups.append(model[1]) return groups
['def', 'rnn_classifier_split(model:', 'Model)', '->', 'List[Model]:', 'groups', '=', '[nn.Sequential(model[0].encoder,', 'model[0].encoder_dp)]', 'groups', '+=', '[nn.Sequential(rnn,', 'dp)', 'for', '(rnn,', 'dp)', 'in', 'zip(model[0].rnns,', 'model[0].hidden_dps)]', 'groups.append(model[1])', 'return', 'groups']
32,455
43Carrig/recurrent_neural_networks_practice
input_pipeline.py
NumpyReader.read
read
Returns a large chunk of the Numpy arrays for later re-chunking.
[ "Returns", "a", "large", "chunk", "of", "the", "Numpy", "arrays", "for", "later", "re-chunking." ]
def read(self): features = {key: numpy.squeeze(value, axis=0) for (key, value) in self._features.items()} return estimator_lib.inputs.numpy_input_fn(x=features, batch_size=self._read_num_records_hint, num_epochs=None, shuffle=False)()
['def', 'read(self):', 'features', '=', '{key:', 'numpy.squeeze(value,', 'axis=0)', 'for', '(key,', 'value)', 'in', 'self._features.items()}', 'return', 'estimator_lib.inputs.numpy_input_fn(x=features,', 'batch_size=self._read_num_records_hint,', 'num_epochs=None,', 'shuffle=False)()']
335,408
bitprophet/ssh
test_client.py
SSHClientTest.test_5_cleanup
test_5_cleanup
verify that when an SSHClient is collected, its transport (and the transport's packetizer) is closed.
[ "verify", "that", "when", "an", "SSHClient", "is", "collected,", "its", "transport", "(and", "the", "transport's", "packetizer)", "is", "closed." ]
def test_5_cleanup(self): host_key = ssh.RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = ssh.RSAKey(data=str(host_key)) self.tc = ssh.SSHClient() self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy()) self.assertEquals(0, len(self.tc.get_host_keys())) self.tc.connect(self....
['def', 'test_5_cleanup(self):', 'host_key', '=', "ssh.RSAKey.from_private_key_file('tests/test_rsa.key')", 'public_host_key', '=', 'ssh.RSAKey(data=str(host_key))', 'self.tc', '=', 'ssh.SSHClient()', 'self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy())', 'self.assertEquals(0,', 'len(self.tc.get_host_keys()))', 's...
372,501
worldbank/wb-nlp-tools
respelling.py
get_suggestions
get_suggestions
Wrapper the caches the result of enchant's suggest method.
[ "Wrapper", "the", "caches", "the", "result", "of", "enchant's", "suggest", "method." ]
def get_suggestions(word: str, **kwargs) -> list: if en_lang.get_en_dict().check(word): suggest = [word] else: suggest = en_lang.get_en_dict().suggest(word) return suggest
['def', 'get_suggestions(word:', 'str,', '**kwargs)', '->', 'list:', 'if', 'en_lang.get_en_dict().check(word):', 'suggest', '=', '[word]', 'else:', 'suggest', '=', 'en_lang.get_en_dict().suggest(word)', 'return', 'suggest']
975,936
gunthercox/ChatterBot
ma.py
default_fill_value
default_fill_value
Function to calculate default fill value for an object.
[ "Function", "to", "calculate", "default", "fill", "value", "for", "an", "object." ]
def default_fill_value(obj): if isinstance(obj, float): return default_real_fill_value elif isinstance(obj, int) or isinstance(obj, long): return default_integer_fill_value elif isinstance(obj, bytes): return default_character_fill_value elif isinstance(obj, complex): ret...
['def', 'default_fill_value(obj):', 'if', 'isinstance(obj,', 'float):', 'return', 'default_real_fill_value', 'elif', 'isinstance(obj,', 'int)', 'or', 'isinstance(obj,', 'long):', 'return', 'default_integer_fill_value', 'elif', 'isinstance(obj,', 'bytes):', 'return', 'default_character_fill_value', 'elif', 'isinstance(o...
532,370
triaquae/triaquae
module_loading.py
module_has_submodule
module_has_submodule
See if 'module' is in 'package'.
[ "See", "if", "'module'", "is", "in", "'package'." ]
def module_has_submodule(package, module_name): name = '.'.join([package.__name__, module_name]) try: return sys.modules[name] is not None except KeyError: pass try: package_path = package.__path__ except AttributeError: return False for finder in sys.meta_path: ...
['def', 'module_has_submodule(package,', 'module_name):', 'name', '=', "'.'.join([package.__name__,", 'module_name])', 'try:', 'return', 'sys.modules[name]', 'is', 'not', 'None', 'except', 'KeyError:', 'pass', 'try:', 'package_path', '=', 'package.__path__', 'except', 'AttributeError:', 'return', 'False', 'for', 'finde...
424,157
triaquae/triaquae
srs.py
SpatialReference.import_epsg
import_epsg
Imports the Spatial Reference from the EPSG code (an integer).
[ "Imports", "the", "Spatial", "Reference", "from", "the", "EPSG", "code", "(an", "integer)." ]
def import_epsg(self, epsg): capi.from_epsg(self.ptr, epsg)
['def', 'import_epsg(self,', 'epsg):', 'capi.from_epsg(self.ptr,', 'epsg)']
357,656
cvjena/PartDetectorDisovery
im2col.py
Im2colLayer.backward
backward
Computes the backward pass.
[ "Computes", "the", "backward", "pass." ]
def backward(self, bottom, top, propagate_down): if not propagate_down: return 0.0 top_diff = top[0].diff() bottom_diff = bottom[0].init_diff(setzero=False) wrapper.im2col_backward(bottom_diff, top_diff, self._psize, self._stride) return 0.0
['def', 'backward(self,', 'bottom,', 'top,', 'propagate_down):', 'if', 'not', 'propagate_down:', 'return', '0.0', 'top_diff', '=', 'top[0].diff()', 'bottom_diff', '=', 'bottom[0].init_diff(setzero=False)', 'wrapper.im2col_backward(bottom_diff,', 'top_diff,', 'self._psize,', 'self._stride)', 'return', '0.0']
278,360
rlworkgroup/garage
default_worker.py
DefaultWorker.update_agent
update_agent
Update an agent, assuming it implements :class:`~Policy`.
[ "Update", "an", "agent,", "assuming", "it", "implements", ":class:`~Policy`." ]
def update_agent(self, agent_update): if isinstance(agent_update, (dict, tuple, np.ndarray)): self.agent.set_param_values(agent_update) elif agent_update is not None: self.agent = agent_update
['def', 'update_agent(self,', 'agent_update):', 'if', 'isinstance(agent_update,', '(dict,', 'tuple,', 'np.ndarray)):', 'self.agent.set_param_values(agent_update)', 'elif', 'agent_update', 'is', 'not', 'None:', 'self.agent', '=', 'agent_update']
200,440
poapper-inc/fights
base.py
BaseState.done
done
Whether the game is finished.
[ "Whether", "the", "game", "is", "finished." ]
def done(self) -> bool: ...
['def', 'done(self)', '->', 'bool:', '...']
180,063
Ruturaj123/Flowchart-Detection
tensor_array_ops.py
TensorArray.split
split
Split the values of a `Tensor` into the TensorArray.
[ "Split", "the", "values", "of", "a", "`Tensor`", "into", "the", "TensorArray." ]
def split(self, value, lengths, name=None): with ops.name_scope(name, 'TensorArraySplit', [self._handle, value, lengths]): value = ops.convert_to_tensor(value, name='value') with self._maybe_colocate_with(value): lengths_64 = math_ops.to_int64(lengths) flow_out = gen_data_flo...
['def', 'split(self,', 'value,', 'lengths,', 'name=None):', 'with', 'ops.name_scope(name,', "'TensorArraySplit',", '[self._handle,', 'value,', 'lengths]):', 'value', '=', 'ops.convert_to_tensor(value,', "name='value')", 'with', 'self._maybe_colocate_with(value):', 'lengths_64', '=', 'math_ops.to_int64(lengths)', 'flow_...
606,155
chainer/chainer
variable.py
Variable.xp
xp
Array module for the data array of this variable.
[ "Array", "module", "for", "the", "data", "array", "of", "this", "variable." ]
def xp(self) -> tp.Optional[types.Xp]: if self._has_chainerx_array: return chainerx else: device = self.device return None if device is None else device.xp
['def', 'xp(self)', '->', 'tp.Optional[types.Xp]:', 'if', 'self._has_chainerx_array:', 'return', 'chainerx', 'else:', 'device', '=', 'self.device', 'return', 'None', 'if', 'device', 'is', 'None', 'else', 'device.xp']
477,080
43Carrig/recurrent_neural_networks_practice
collective_ops.py
broadcast_send
broadcast_send
Broadcasts one tensor to a group of others, across devices.
[ "Broadcasts", "one", "tensor", "to", "a", "group", "of", "others,", "across", "devices." ]
def broadcast_send(t, shape, dtype, group_size, group_key, instance_key): if not device.canonical_name(t.device): raise ValueError('Device assignment required for collective ops') if group_size <= 1: raise ValueError('Parameter group_size to broadcast_send must be at least 2.') if t.shape !=...
['def', 'broadcast_send(t,', 'shape,', 'dtype,', 'group_size,', 'group_key,', 'instance_key):', 'if', 'not', 'device.canonical_name(t.device):', 'raise', "ValueError('Device", 'assignment', 'required', 'for', 'collective', "ops')", 'if', 'group_size', '<=', '1:', 'raise', "ValueError('Parameter", 'group_size', 'to', 'b...
337,118
matsu0228/nlp-jp
tests.py
test_upper
test_upper
Return true if the variable is uppercased.
[ "Return", "true", "if", "the", "variable", "is", "uppercased." ]
def test_upper(value): return text_type(value).isupper()
['def', 'test_upper(value):', 'return', 'text_type(value).isupper()']
787,974
dlshriver/dnnv
test_esip.py
TestNNBounds.test_valid_concrete_bounds
test_valid_concrete_bounds
Tests the output from the _valid_concrete_bounds() method against ground truth.
[ "Tests", "the", "output", "from", "the", "_valid_concrete_bounds()", "method", "against", "ground", "truth." ]
def test_valid_concrete_bounds(self): concrete_bounds_valid = np.array([[1, 2], [-1, 2], [3, 5]]) concrete_bounds_invalid = np.array([[1, -1], [-1, 2], [3, 5]]) self.assertTrue(self.bounds_relu._valid_concrete_bounds(concrete_bounds_valid)) self.assertFalse(self.bounds_relu._valid_concrete_bounds(concre...
['def', 'test_valid_concrete_bounds(self):', 'concrete_bounds_valid', '=', 'np.array([[1,', '2],', '[-1,', '2],', '[3,', '5]])', 'concrete_bounds_invalid', '=', 'np.array([[1,', '-1],', '[-1,', '2],', '[3,', '5]])', 'self.assertTrue(self.bounds_relu._valid_concrete_bounds(concrete_bounds_valid))', 'self.assertFalse(sel...
522,666