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
triaquae/triaquae
srs.py
SpatialReference.linear_name
linear_name
Returns the name of the linear units.
[ "Returns", "the", "name", "of", "the", "linear", "units." ]
def linear_name(self): (units, name) = capi.linear_units(self.ptr, byref(c_char_p())) return name
['def', 'linear_name(self):', '(units,', 'name)', '=', 'capi.linear_units(self.ptr,', 'byref(c_char_p()))', 'return', 'name']
357,644
BMW-InnovationLab/BMW-Semantic--Training-GUI
i3d_resnet.py
I3D_ResNetV1.inflate_weights
inflate_weights
Inflate I3D network with its 2D ImageNet pretrained weights.
[ "Inflate", "I3D", "network", "with", "its", "2D", "ImageNet", "pretrained", "weights." ]
def inflate_weights(self): if not self.pretrained_base: raise RuntimeError('I3D models need to be inflated. Please set PRETRAINED_BASE to True in config.') if self.pretrained_base and (not self.pretrained): import torchvision if self.depth == 50: R2D = torchvision.models.resn...
['def', 'inflate_weights(self):', 'if', 'not', 'self.pretrained_base:', 'raise', "RuntimeError('I3D", 'models', 'need', 'to', 'be', 'inflated.', 'Please', 'set', 'PRETRAINED_BASE', 'to', 'True', 'in', "config.')", 'if', 'self.pretrained_base', 'and', '(not', 'self.pretrained):', 'import', 'torchvision', 'if', 'self.dep...
463,688
43Carrig/recurrent_neural_networks_practice
profile_context.py
ProfileContext.trace_next_step
trace_next_step
Enables tracing and adds traces to profiler at next step.
[ "Enables", "tracing", "and", "adds", "traces", "to", "profiler", "at", "next", "step." ]
def trace_next_step(self): if not self._enabled: return self._trace_next_step = True self._slow_path_steps.add(self._step)
['def', 'trace_next_step(self):', 'if', 'not', 'self._enabled:', 'return', 'self._trace_next_step', '=', 'True', 'self._slow_path_steps.add(self._step)']
339,403
voxel51/fiftyone
exporters.py
GenericSampleDatasetExporter.export_sample
export_sample
Exports the given sample to the dataset.
[ "Exports", "the", "given", "sample", "to", "the", "dataset." ]
def export_sample(self, sample): raise NotImplementedError('subclass must implement export_sample()')
['def', 'export_sample(self,', 'sample):', 'raise', "NotImplementedError('subclass", 'must', 'implement', "export_sample()')"]
584,262
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjDataWrapper.cam_xmat
cam_xmat
Cartesian camera orientation (ncam x 9).
[ "Cartesian", "camera", "orientation", "(ncam", "x", "9)." ]
def cam_xmat(self): return util.buf_to_npy(self._ptr.contents.cam_xmat, (self._model.ncam, 9))
['def', 'cam_xmat(self):', 'return', 'util.buf_to_npy(self._ptr.contents.cam_xmat,', '(self._model.ncam,', '9))']
440,556
griffin-leonard/mit-6.034-artificial_intelligence
bayes_api.py
BayesNet.set_domain
set_domain
Establish the list of values that var can take on.
[ "Establish", "the", "list", "of", "values", "that", "var", "can", "take", "on." ]
def set_domain(self, var, values): self.domain[var] = values[:] return self
['def', 'set_domain(self,', 'var,', 'values):', 'self.domain[var]', '=', 'values[:]', 'return', 'self']
271,886
triaquae/triaquae
point.py
Point.set_coords
set_coords
Sets the coordinates of the point with the given tuple.
[ "Sets", "the", "coordinates", "of", "the", "point", "with", "the", "given", "tuple." ]
def set_coords(self, tup): self._cs[0] = tup
['def', 'set_coords(self,', 'tup):', 'self._cs[0]', '=', 'tup']
357,841
adzialocha/tomomibot
cli.py
Context.log
log
Logs a message to stderr.
[ "Logs", "a", "message", "to", "stderr." ]
def log(self, msg, *args): if args: msg %= args click.echo(msg)
['def', 'log(self,', 'msg,', '*args):', 'if', 'args:', 'msg', '%=', 'args', 'click.echo(msg)']
355,685
hamza-murad/AALU
discovery_v1.py
TrainingExampleList.from_dict
from_dict
Initialize a TrainingExampleList object from a json dictionary.
[ "Initialize", "a", "TrainingExampleList", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': args = {} valid_keys = ['examples'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class TrainingExampleList: ' + ', '.join(bad_keys)) if 'examples' in _dict:...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'TrainingExampleList':", 'args', '=', '{}', 'valid_keys', '=', "['examples']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'TrainingExampl...
5,692
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
model.py
CharsetMapper.get_text
get_text
Returns a string corresponding to a sequence of character ids.
[ "Returns", "a", "string", "corresponding", "to", "a", "sequence", "of", "character", "ids." ]
def get_text(self, ids): return tf.reduce_join(self.table.lookup(tf.to_int64(ids)), reduction_indices=1)
['def', 'get_text(self,', 'ids):', 'return', 'tf.reduce_join(self.table.lookup(tf.to_int64(ids)),', 'reduction_indices=1)']
20,729
tensorflow/quantum
state_test.py
StateTest.test_state_basic_inputs
test_state_basic_inputs
Test that state ingests inputs correctly in simple settings.
[ "Test", "that", "state", "ingests", "inputs", "correctly", "in", "simple", "settings." ]
def test_state_basic_inputs(self): state_calc = state.State() state_calc(cirq.Circuit()) state_calc([cirq.Circuit()]) state_calc(cirq.Circuit(), symbol_names=['name'], symbol_values=[[0.5]]) state_calc(cirq.Circuit(), symbol_names=[sympy.Symbol('name')], symbol_values=[[0.5]])
['def', 'test_state_basic_inputs(self):', 'state_calc', '=', 'state.State()', 'state_calc(cirq.Circuit())', 'state_calc([cirq.Circuit()])', 'state_calc(cirq.Circuit(),', "symbol_names=['name'],", 'symbol_values=[[0.5]])', 'state_calc(cirq.Circuit(),', "symbol_names=[sympy.Symbol('name')],", 'symbol_values=[[0.5]])']
835,352
TrellixVulnTeam/Unsupervised_Learning_HFI7
channels.py
HBChannel.is_beating
is_beating
Is the heartbeat running and responsive (and not paused).
[ "Is", "the", "heartbeat", "running", "and", "responsive", "(and", "not", "paused)." ]
def is_beating(self): if self.is_alive() and (not self._pause) and self._beating: return True else: return False
['def', 'is_beating(self):', 'if', 'self.is_alive()', 'and', '(not', 'self._pause)', 'and', 'self._beating:', 'return', 'True', 'else:', 'return', 'False']
449,767
sek788432/Waymo-2D-Object-Detection
preprocess_ops.py
build_batch_grided_gt
build_batch_grided_gt
Converts ground truth for use in loss functions.
[ "Converts", "ground", "truth", "for", "use", "in", "loss", "functions." ]
def build_batch_grided_gt(y_true, mask, size, dtype, use_tie_breaker): boxes = tf.cast(y_true['bbox'], dtype) classes = tf.expand_dims(tf.cast(y_true['classes'], dtype=dtype), axis=-1) anchors = tf.cast(y_true['best_anchors'], dtype) batches = tf.shape(boxes)[0] num_boxes = tf.shape(boxes)[1] le...
['def', 'build_batch_grided_gt(y_true,', 'mask,', 'size,', 'dtype,', 'use_tie_breaker):', 'boxes', '=', "tf.cast(y_true['bbox'],", 'dtype)', 'classes', '=', "tf.expand_dims(tf.cast(y_true['classes'],", 'dtype=dtype),', 'axis=-1)', 'anchors', '=', "tf.cast(y_true['best_anchors'],", 'dtype)', 'batches', '=', 'tf.shape(bo...
973,404
famura/SimuRLacra
playback.py
PlaybackPolicy.curr_rec
curr_rec
Get the pointer to the current recording.
[ "Get", "the", "pointer", "to", "the", "current", "recording." ]
def curr_rec(self) -> int: return self._curr_rec
['def', 'curr_rec(self)', '->', 'int:', 'return', 'self._curr_rec']
883,851
wangck20/OPERA
vision_transformer.py
vit_small_patch32_384
vit_small_patch32_384
ViT-Small (ViT-S/32) at 384x384.
[ "ViT-Small", "(ViT-S/32)", "at", "384x384." ]
def vit_small_patch32_384(pretrained=False, **kwargs): model_kwargs = dict(patch_size=32, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_vision_transformer('vit_small_patch32_384', pretrained=pretrained, **model_kwargs) return model
['def', 'vit_small_patch32_384(pretrained=False,', '**kwargs):', 'model_kwargs', '=', 'dict(patch_size=32,', 'embed_dim=384,', 'depth=12,', 'num_heads=6,', '**kwargs)', 'model', '=', "_create_vision_transformer('vit_small_patch32_384',", 'pretrained=pretrained,', '**model_kwargs)', 'return', 'model']
253,173
LucasAlegre/sumo-rl
epsilon_greedy.py
EpsilonGreedy.reset
reset
Reset epsilon to initial value.
[ "Reset", "epsilon", "to", "initial", "value." ]
def reset(self): self.epsilon = self.initial_epsilon
['def', 'reset(self):', 'self.epsilon', '=', 'self.initial_epsilon']
910,485
deepmind/bsuite
summary_analysis.py
ave_score_by_tag
ave_score_by_tag
Takes in a bsuite scored dataframe and summarizes by tags.
[ "Takes", "in", "a", "bsuite", "scored", "dataframe", "and", "summarizes", "by", "tags." ]
def ave_score_by_tag(score_df: pd.DataFrame, sweep_vars: Sequence[str]) -> pd.DataFrame: summary_fun = lambda x: _summarize_single_by_tag(x, list(ALL_TAGS), 'tags') if sweep_vars: summary_df = score_df.groupby(sweep_vars).apply(summary_fun).reset_index() else: summary_df = summary_fun(score_...
['def', 'ave_score_by_tag(score_df:', 'pd.DataFrame,', 'sweep_vars:', 'Sequence[str])', '->', 'pd.DataFrame:', 'summary_fun', '=', 'lambda', 'x:', '_summarize_single_by_tag(x,', 'list(ALL_TAGS),', "'tags')", 'if', 'sweep_vars:', 'summary_df', '=', 'score_df.groupby(sweep_vars).apply(summary_fun).reset_index()', 'else:'...
410,157
sarnsdev/social-alignment-data-mining
_memmapping_reducer.py
reduce_memmap
reduce_memmap
Pickle the descriptors of a memmap instance to reopen on same file.
[ "Pickle", "the", "descriptors", "of", "a", "memmap", "instance", "to", "reopen", "on", "same", "file." ]
def reduce_memmap(a): m = _get_backing_memmap(a) if m is not None: return _reduce_memmap_backed(a, m) else: return (loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL),))
['def', 'reduce_memmap(a):', 'm', '=', '_get_backing_memmap(a)', 'if', 'm', 'is', 'not', 'None:', 'return', '_reduce_memmap_backed(a,', 'm)', 'else:', 'return', '(loads,', '(dumps(np.asarray(a),', 'protocol=HIGHEST_PROTOCOL),))']
352,448
Kvatsx/Artificial-Intelligence-Assignments
sandbox.py
SandboxedEnvironment.getitem
getitem
Subscribe an object from sandboxed code.
[ "Subscribe", "an", "object", "from", "sandboxed", "code." ]
def getitem(self, obj, argument): try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, string_types): try: attr = str(argument) except Exception: pass else: try: ...
['def', 'getitem(self,', 'obj,', 'argument):', 'try:', 'return', 'obj[argument]', 'except', '(TypeError,', 'LookupError):', 'if', 'isinstance(argument,', 'string_types):', 'try:', 'attr', '=', 'str(argument)', 'except', 'Exception:', 'pass', 'else:', 'try:', 'value', '=', 'getattr(obj,', 'attr)', 'except', 'AttributeEr...
39,371
paarthneekhara/advoc
spectral.py
r9y9_melspec_to_waveform
r9y9_melspec_to_waveform
Approximately inverts unofficial mel spectrogram to waveform.
[ "Approximately", "inverts", "unofficial", "mel", "spectrogram", "to", "waveform." ]
def r9y9_melspec_to_waveform(X_mel_dbnorm, fs=22050, phase_estimation='lws', waveform_len=None): return melspec_to_waveform(X_mel_dbnorm, fs=fs, nfft=1024, nhop=256, phase_estimation=phase_estimation, waveform_len=waveform_len)
['def', 'r9y9_melspec_to_waveform(X_mel_dbnorm,', 'fs=22050,', "phase_estimation='lws',", 'waveform_len=None):', 'return', 'melspec_to_waveform(X_mel_dbnorm,', 'fs=fs,', 'nfft=1024,', 'nhop=256,', 'phase_estimation=phase_estimation,', 'waveform_len=waveform_len)']
398,713
suarez12138/AI-Reversi_IMP_TextDichotomy
contour.py
ContourLabeler.print_label
print_label
Return whether a contour is long enough to hold a label.
[ "Return", "whether", "a", "contour", "is", "long", "enough", "to", "hold", "a", "label." ]
def print_label(self, linecontour, labelwidth): return len(linecontour) > 10 * labelwidth or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()
['def', 'print_label(self,', 'linecontour,', 'labelwidth):', 'return', 'len(linecontour)', '>', '10', '*', 'labelwidth', 'or', '(np.ptp(linecontour,', 'axis=0)', '>', '1.2', '*', 'labelwidth).any()']
96,389
triaquae/triaquae
layermapping.py
LayerMapping.unique_kwargs
unique_kwargs
Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
[ "Given", "the", "feature", "keyword", "arguments", "(from", "`feature_kwargs`)", "this", "routine", "will", "construct", "and", "return", "the", "uniqueness", "keyword", "arguments", "--", "a", "subset", "of", "the", "feature", "kwargs." ]
def unique_kwargs(self, kwargs): if isinstance(self.unique, six.string_types): return {self.unique: kwargs[self.unique]} else: return dict(((fld, kwargs[fld]) for fld in self.unique))
['def', 'unique_kwargs(self,', 'kwargs):', 'if', 'isinstance(self.unique,', 'six.string_types):', 'return', '{self.unique:', 'kwargs[self.unique]}', 'else:', 'return', 'dict(((fld,', 'kwargs[fld])', 'for', 'fld', 'in', 'self.unique))']
358,062
facebookresearch/detectron2
develop.py
create_dummy_func
create_dummy_func
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
[ "When", "a", "dependency", "of", "a", "function", "is", "not", "available,", "create", "a", "dummy", "function", "which", "throws", "ImportError", "when", "used." ]
def create_dummy_func(func, dependency, message=''): err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func) if message: err = err + ' ' + message if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): ...
['def', 'create_dummy_func(func,', 'dependency,', "message=''):", 'err', '=', '"Cannot', 'import', "'{}',", 'therefore', "'{}'", 'is', 'not', 'available.".format(dependency,', 'func)', 'if', 'message:', 'err', '=', 'err', '+', "'", "'", '+', 'message', 'if', 'isinstance(dependency,', '(list,', 'tuple)):', 'dependency',...
549,359
weimin17/Object-Detection_HelmetDetection
network_units.py
lookup_named_tensor
lookup_named_tensor
Retrieves a NamedTensor by name, raising KeyError if it doesn't exist.
[ "Retrieves", "a", "NamedTensor", "by", "name,", "raising", "KeyError", "if", "it", "doesn't", "exist." ]
def lookup_named_tensor(name, named_tensors): result = lookup_named_tensor_or_none(name, named_tensors) if result is None: raise KeyError('Name "%s" not found in named tensors: %s' % (name, named_tensors)) return result
['def', 'lookup_named_tensor(name,', 'named_tensors):', 'result', '=', 'lookup_named_tensor_or_none(name,', 'named_tensors)', 'if', 'result', 'is', 'None:', 'raise', "KeyError('Name", '"%s"', 'not', 'found', 'in', 'named', 'tensors:', "%s'", '%', '(name,', 'named_tensors))', 'return', 'result']
753,417
tensorflow/agents
episodic_replay_buffer.py
EpisodicReplayBuffer.add_sequence
add_sequence
Adds a sequence of items to the replay buffer for the selected episode.
[ "Adds", "a", "sequence", "of", "items", "to", "the", "replay", "buffer", "for", "the", "selected", "episode." ]
def add_sequence(self, items, episode_id): episode_id.shape.assert_has_rank(0) with tf.device(self._device): with tf.name_scope('add_steps'): items = tf.nest.map_structure(lambda x, spec: tf.convert_to_tensor(value=x, dtype=spec.dtype), items, self._data_spec) item_0 = tf.nest.fl...
['def', 'add_sequence(self,', 'items,', 'episode_id):', 'episode_id.shape.assert_has_rank(0)', 'with', 'tf.device(self._device):', 'with', "tf.name_scope('add_steps'):", 'items', '=', 'tf.nest.map_structure(lambda', 'x,', 'spec:', 'tf.convert_to_tensor(value=x,', 'dtype=spec.dtype),', 'items,', 'self._data_spec)', 'ite...
22,892
rudranil723/mini-main
types.py
ParamType.fail
fail
Helper method to fail with an invalid value message.
[ "Helper", "method", "to", "fail", "with", "an", "invalid", "value", "message." ]
def fail(self, message: str, param: t.Optional['Parameter']=None, ctx: t.Optional['Context']=None) -> 't.NoReturn': raise BadParameter(message, ctx=ctx, param=param)
['def', 'fail(self,', 'message:', 'str,', 'param:', "t.Optional['Parameter']=None,", 'ctx:', "t.Optional['Context']=None)", '->', "'t.NoReturn':", 'raise', 'BadParameter(message,', 'ctx=ctx,', 'param=param)']
314,391
myothida/Supervised-Machine-Learning
text.py
Text.align
align
Align text to a given width.
[ "Align", "text", "to", "a", "given", "width." ]
def align(self, align: AlignMethod, width: int, character: str=' ') -> None: self.truncate(width) excess_space = width - cell_len(self.plain) if excess_space: if align == 'left': self.pad_right(excess_space, character) elif align == 'center': left = excess_space // 2 ...
['def', 'align(self,', 'align:', 'AlignMethod,', 'width:', 'int,', 'character:', "str='", "')", '->', 'None:', 'self.truncate(width)', 'excess_space', '=', 'width', '-', 'cell_len(self.plain)', 'if', 'excess_space:', 'if', 'align', '==', "'left':", 'self.pad_right(excess_space,', 'character)', 'elif', 'align', '==', "'...
445,129
ashwin-phadke/cvplayground
export_saved_model_tpu_lib.py
run_inference_from_saved_model
run_inference_from_saved_model
Loads saved model and run inference on TPU.
[ "Loads", "saved", "model", "and", "run", "inference", "on", "TPU." ]
def run_inference_from_saved_model(inputs, saved_model_dir, input_placeholder_name='placeholder_tensor', repeat=1): with tf.Graph().as_default(), tf.Session() as sess: meta_graph = loader.load(sess, [tag_constants.SERVING, tag_constants.TPU], saved_model_dir) sess.run(tf.contrib.tpu.initialize_syste...
['def', 'run_inference_from_saved_model(inputs,', 'saved_model_dir,', "input_placeholder_name='placeholder_tensor',", 'repeat=1):', 'with', 'tf.Graph().as_default(),', 'tf.Session()', 'as', 'sess:', 'meta_graph', '=', 'loader.load(sess,', '[tag_constants.SERVING,', 'tag_constants.TPU],', 'saved_model_dir)', 'sess.run(t...
510,179
tencent-ailab/TriNet
attention.py
MultiHeadedAttention.forward_qkv
forward_qkv
Transform query, key and value.
[ "Transform", "query,", "key", "and", "value." ]
def forward_qkv(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: n_batch = query.size(0) q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k) k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k) v = self.linear_v(value)....
['def', 'forward_qkv(self,', 'query:', 'torch.Tensor,', 'key:', 'torch.Tensor,', 'value:', 'torch.Tensor)', '->', 'Tuple[torch.Tensor,', 'torch.Tensor,', 'torch.Tensor]:', 'n_batch', '=', 'query.size(0)', 'q', '=', 'self.linear_q(query).view(n_batch,', '-1,', 'self.h,', 'self.d_k)', 'k', '=', 'self.linear_k(key).view(n...
425,480
tensorflow/quantum
serializable_gate_set_test.py
SerializableGateSetTest.test_gateset_with_added_gates_again
test_gateset_with_added_gates_again
Verify that adding a serializer twice doesn't mess anything up.
[ "Verify", "that", "adding", "a", "serializer", "twice", "doesn't", "mess", "anything", "up." ]
def test_gateset_with_added_gates_again(self): q = cirq.GridQubit(2, 2) x_gateset = serializable_gate_set.SerializableGateSet(gate_set_name='x', serializers=[X_SERIALIZER], deserializers=[X_DESERIALIZER]) xx_gateset = x_gateset.with_added_gates(gate_set_name='xx', serializers=[X_SERIALIZER], deserializers=[...
['def', 'test_gateset_with_added_gates_again(self):', 'q', '=', 'cirq.GridQubit(2,', '2)', 'x_gateset', '=', "serializable_gate_set.SerializableGateSet(gate_set_name='x',", 'serializers=[X_SERIALIZER],', 'deserializers=[X_DESERIALIZER])', 'xx_gateset', '=', "x_gateset.with_added_gates(gate_set_name='xx',", 'serializers...
834,973
deepmind/meltingpot
collaborative_cooking.py
create_counter
create_counter
Returns a prefab which can contain one of any item.
[ "Returns", "a", "prefab", "which", "can", "contain", "one", "of", "any", "item." ]
def create_counter(): base_prefab = create_base_prefab('counter') base_prefab['components'] += [{'component': 'Container', 'kwargs': {'reward': 0.0}}] return base_prefab
['def', 'create_counter():', 'base_prefab', '=', "create_base_prefab('counter')", "base_prefab['components']", '+=', "[{'component':", "'Container',", "'kwargs':", "{'reward':", '0.0}}]', 'return', 'base_prefab']
285,313
RasaHQ/rasa_core
utils.py
create_output_path
create_output_path
Creates an output path which includes the current timestamp.
[ "Creates", "an", "output", "path", "which", "includes", "the", "current", "timestamp." ]
def create_output_path(output_path: Text=DEFAULT_MODELS_PATH, prefix: Text='') -> Text: import time if output_path.endswith('tar.gz'): return output_path else: time_format = '%Y%m%d-%H%M%S' file_name = '{}{}.tar.gz'.format(prefix, time.strftime(time_format)) return os.path.jo...
['def', 'create_output_path(output_path:', 'Text=DEFAULT_MODELS_PATH,', 'prefix:', "Text='')", '->', 'Text:', 'import', 'time', 'if', "output_path.endswith('tar.gz'):", 'return', 'output_path', 'else:', 'time_format', '=', "'%Y%m%d-%H%M%S'", 'file_name', '=', "'{}{}.tar.gz'.format(prefix,", 'time.strftime(time_format))...
838,145
google-research/rigl
shuffled_mask_test.py
ShuffledMaskTest.test_run_fc
test_run_fc
Tests if the driver for shuffled training runs correctly with FC NN.
[ "Tests", "if", "the", "driver", "for", "shuffled", "training", "runs", "correctly", "with", "FC", "NN." ]
def test_run_fc(self): experiment_dir = tempfile.mkdtemp() eval_flags = dict(epochs=1, experiment_dir=experiment_dir, model='MNIST_FC') with flagsaver.flagsaver(**eval_flags): shuffled_mask.main([]) outfile = path.join(experiment_dir, '*', 'events.out.tfevents.*') files = glob.glob(outfile) ...
['def', 'test_run_fc(self):', 'experiment_dir', '=', 'tempfile.mkdtemp()', 'eval_flags', '=', 'dict(epochs=1,', 'experiment_dir=experiment_dir,', "model='MNIST_FC')", 'with', 'flagsaver.flagsaver(**eval_flags):', 'shuffled_mask.main([])', 'outfile', '=', 'path.join(experiment_dir,', "'*',", "'events.out.tfevents.*')", ...
841,399
deepmind/dm_control
control.py
flatten_observation
flatten_observation
Flattens multiple observation arrays into a single numpy array.
[ "Flattens", "multiple", "observation", "arrays", "into", "a", "single", "numpy", "array." ]
def flatten_observation(observation, output_key=FLAT_OBSERVATION_KEY): if not isinstance(observation, collections.abc.MutableMapping): raise ValueError('Can only flatten dict-like observations.') if isinstance(observation, collections.OrderedDict): keys = observation.keys() else: key...
['def', 'flatten_observation(observation,', 'output_key=FLAT_OBSERVATION_KEY):', 'if', 'not', 'isinstance(observation,', 'collections.abc.MutableMapping):', 'raise', "ValueError('Can", 'only', 'flatten', 'dict-like', "observations.')", 'if', 'isinstance(observation,', 'collections.OrderedDict):', 'keys', '=', 'observat...
165,343
RonMen10/Artificial-decision-making-of-autonomous-vehicles-AI
control.py
AgentVehicle.get_PO_solutions
get_PO_solutions
Identify the pareto optimal solutions for the agent out of all possible ones.
[ "Identify", "the", "pareto", "optimal", "solutions", "for", "the", "agent", "out", "of", "all", "possible", "ones." ]
def get_PO_solutions(self, time, risk): dominated_risk = [] dominated_time = [] for i in range(0, len(time)): for j in range(0, len(time)): if time[i] <= time[j] and risk[i] < risk[j] or (time[i] < time[j] and risk[i] <= risk[j]): if time[j] not in dominated_time: ...
['def', 'get_PO_solutions(self,', 'time,', 'risk):', 'dominated_risk', '=', '[]', 'dominated_time', '=', '[]', 'for', 'i', 'in', 'range(0,', 'len(time)):', 'for', 'j', 'in', 'range(0,', 'len(time)):', 'if', 'time[i]', '<=', 'time[j]', 'and', 'risk[i]', '<', 'risk[j]', 'or', '(time[i]', '<', 'time[j]', 'and', 'risk[i]',...
34,806
qianduoduolr/Spa-then-Temp
vanilla_tracker.py
BaseTracker.init_weights
init_weights
Initialize the model network weights.
[ "Initialize", "the", "model", "network", "weights." ]
def init_weights(self): self.backbone.init_weights()
['def', 'init_weights(self):', 'self.backbone.init_weights()']
393,961
TrellixVulnTeam/Unsupervised_Learning_HFI7
pretty.py
pprint
pprint
Like `pretty` but print to stdout.
[ "Like", "`pretty`", "but", "print", "to", "stdout." ]
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
['def', 'pprint(obj,', 'verbose=False,', 'max_width=79,', "newline='\\n',", 'max_seq_length=MAX_SEQ_LENGTH):', 'printer', '=', 'RepresentationPrinter(sys.stdout,', 'verbose,', 'max_width,', 'newline,', 'max_seq_length=max_seq_length)', 'printer.pretty(obj)', 'printer.flush()', 'sys.stdout.write(newline)', 'sys.stdout.f...
448,746
som-shahlab/femr
core.py
LabeledPatients.get_num_patients
get_num_patients
Return the total number of patients.
[ "Return", "the", "total", "number", "of", "patients." ]
def get_num_patients(self) -> int: return len(self)
['def', 'get_num_patients(self)', '->', 'int:', 'return', 'len(self)']
179,801
matsu0228/nlp-jp
internals.py
BlockManager.reindex_indexer
reindex_indexer
Parameters ---------- new_axis : Index indexer : ndarray of int64 or None axis : int fill_value : object allow_dups : bool pandas-indexer with -1's only.
[ "Parameters", "----------", "new_axis", ":", "Index", "indexer", ":", "ndarray", "of", "int64", "or", "None", "axis", ":", "int", "fill_value", ":", "object", "allow_dups", ":", "bool", "pandas-indexer", "with", "-1's", "only." ]
def reindex_indexer(self, new_axis, indexer, axis, fill_value=None, allow_dups=False, copy=True): if indexer is None: if new_axis is self.axes[axis] and (not copy): return self result = self.copy(deep=copy) result.axes = list(self.axes) result.axes[axis] = new_axis ...
['def', 'reindex_indexer(self,', 'new_axis,', 'indexer,', 'axis,', 'fill_value=None,', 'allow_dups=False,', 'copy=True):', 'if', 'indexer', 'is', 'None:', 'if', 'new_axis', 'is', 'self.axes[axis]', 'and', '(not', 'copy):', 'return', 'self', 'result', '=', 'self.copy(deep=copy)', 'result.axes', '=', 'list(self.axes)', '...
802,264
tobegit3hub/deep_image_model
text.py
ByteProcessor.transform
transform
Transforms input documents into sequence of ids.
[ "Transforms", "input", "documents", "into", "sequence", "of", "ids." ]
def transform(self, x): if six.PY3: buffer_or_memoryview = memoryview else: buffer_or_memoryview = buffer for document in x: if isinstance(document, six.text_type): document = document.encode('utf-8') document_mv = buffer_or_memoryview(document) buff = np....
['def', 'transform(self,', 'x):', 'if', 'six.PY3:', 'buffer_or_memoryview', '=', 'memoryview', 'else:', 'buffer_or_memoryview', '=', 'buffer', 'for', 'document', 'in', 'x:', 'if', 'isinstance(document,', 'six.text_type):', 'document', '=', "document.encode('utf-8')", 'document_mv', '=', 'buffer_or_memoryview(document)'...
181,861
QData/deepWordBug
math2html.py
CombiningFunction.parsesingleparameter
parsesingleparameter
Parse a parameter, or a single letter.
[ "Parse", "a", "parameter,", "or", "a", "single", "letter." ]
def parsesingleparameter(self, pos): self.factory.clearskipped(pos) if pos.finished(): Trace.error('Error while parsing single parameter at ' + pos.identifier()) return None if self.factory.detecttype(Bracket, pos) or self.factory.detecttype(FormulaCommand, pos): return self.parsepar...
['def', 'parsesingleparameter(self,', 'pos):', 'self.factory.clearskipped(pos)', 'if', 'pos.finished():', "Trace.error('Error", 'while', 'parsing', 'single', 'parameter', 'at', "'", '+', 'pos.identifier())', 'return', 'None', 'if', 'self.factory.detecttype(Bracket,', 'pos)', 'or', 'self.factory.detecttype(FormulaComman...
542,610
deepmind/acme
bc_utils.py
make_actor_evaluator
make_actor_evaluator
Makes an evaluator that runs the agent on the environment.
[ "Makes", "an", "evaluator", "that", "runs", "the", "agent", "on", "the", "environment." ]
def make_actor_evaluator(environment_factory: Callable[[bool], dm_env.Environment], evaluator_network: actor_core_lib.FeedForwardPolicy) -> offline_distributed_layout.EvaluatorFactory: def actor_evaluator(random_key: networks_lib.PRNGKey, variable_source: core.VariableSource, counter: counting.Counter): ac...
['def', 'make_actor_evaluator(environment_factory:', 'Callable[[bool],', 'dm_env.Environment],', 'evaluator_network:', 'actor_core_lib.FeedForwardPolicy)', '->', 'offline_distributed_layout.EvaluatorFactory:', 'def', 'actor_evaluator(random_key:', 'networks_lib.PRNGKey,', 'variable_source:', 'core.VariableSource,', 'co...
7,993
vanderschaarlab/mlforhealthlabpub
metrics.py
mean_confidence_interval
mean_confidence_interval
Generate the mean and a confindence interval over observed data.
[ "Generate", "the", "mean", "and", "a", "confindence", "interval", "over", "observed", "data." ]
def mean_confidence_interval(data: np.ndarray, confidence: float=0.95) -> Tuple[float, float]: a = 1.0 * np.array(data) n = len(a) (m, se) = (np.mean(a), stats.sem(a)) h = se * stats.t.ppf((1 + confidence) / 2.0, n - 1) return (m, h)
['def', 'mean_confidence_interval(data:', 'np.ndarray,', 'confidence:', 'float=0.95)', '->', 'Tuple[float,', 'float]:', 'a', '=', '1.0', '*', 'np.array(data)', 'n', '=', 'len(a)', '(m,', 'se)', '=', '(np.mean(a),', 'stats.sem(a))', 'h', '=', 'se', '*', 'stats.t.ppf((1', '+', 'confidence)', '/', '2.0,', 'n', '-', '1)', ...
240,093
RasaHQ/rasa_core
action.py
actions_from_names
actions_from_names
Converts the names of actions into class instances.
[ "Converts", "the", "names", "of", "actions", "into", "class", "instances." ]
def actions_from_names(action_names: List[Text], action_endpoint: Optional[EndpointConfig], user_actions: List[Text]) -> List['Action']: return [action_from_name(name, action_endpoint, user_actions) for name in action_names]
['def', 'actions_from_names(action_names:', 'List[Text],', 'action_endpoint:', 'Optional[EndpointConfig],', 'user_actions:', 'List[Text])', '->', "List['Action']:", 'return', '[action_from_name(name,', 'action_endpoint,', 'user_actions)', 'for', 'name', 'in', 'action_names]']
838,296
RLE-Foundation/rllte
bernoulli.py
Bernoulli.entropy
entropy
Returns the Shannon entropy of distribution.
[ "Returns", "the", "Shannon", "entropy", "of", "distribution." ]
def entropy(self) -> th.Tensor: return self.dist.entropy().sum(-1)
['def', 'entropy(self)', '->', 'th.Tensor:', 'return', 'self.dist.entropy().sum(-1)']
333,367
TrellixVulnTeam/Unsupervised_Learning_HFI7
classes.py
BaseName.in_builtin_module
in_builtin_module
Returns True, if this is a builtin module.
[ "Returns", "True,", "if", "this", "is", "a", "builtin", "module." ]
def in_builtin_module(self): value = self._get_module_context().get_value() if isinstance(value, StubModuleValue): return any((v.is_compiled() for v in value.non_stub_value_set)) return value.is_compiled()
['def', 'in_builtin_module(self):', 'value', '=', 'self._get_module_context().get_value()', 'if', 'isinstance(value,', 'StubModuleValue):', 'return', 'any((v.is_compiled()', 'for', 'v', 'in', 'value.non_stub_value_set))', 'return', 'value.is_compiled()']
449,198
ezliu/dream
config.py
Config.from_file
from_file
Loads from the provided file.
[ "Loads", "from", "the", "provided", "file." ]
def from_file(cls, f): return cls(json.load(f))
['def', 'from_file(cls,', 'f):', 'return', 'cls(json.load(f))']
552,559
Vignesh-95/cnn-semantic-segmentation-satellite-images
build_data.py
ImageReader.decode_image
decode_image
Decodes the image data string.
[ "Decodes", "the", "image", "data", "string." ]
def decode_image(self, image_data): image = self._session.run(self._decode, feed_dict={self._decode_data: image_data}) if len(image.shape) != 3 or image.shape[2] not in (1, 3): raise ValueError('The image channels not supported.') return image
['def', 'decode_image(self,', 'image_data):', 'image', '=', 'self._session.run(self._decode,', 'feed_dict={self._decode_data:', 'image_data})', 'if', 'len(image.shape)', '!=', '3', 'or', 'image.shape[2]', 'not', 'in', '(1,', '3):', 'raise', "ValueError('The", 'image', 'channels', 'not', "supported.')", 'return', 'image...
492,269
MarvinTeichmann/KittiSeg
seg_utils.py
setAxLinesBW
setAxLinesBW
Take each Line2D in the axes, ax, and convert the line style to be suitable for black and white viewing.
[ "Take", "each", "Line2D", "in", "the", "axes,", "ax,", "and", "convert", "the", "line", "style", "to", "be", "suitable", "for", "black", "and", "white", "viewing." ]
def setAxLinesBW(ax): MARKERSIZE = 3 COLORMAP = {'r': {'marker': 'None', 'dash': ('None', 'None')}, 'g': {'marker': 'None', 'dash': [5, 2]}, 'm': {'marker': 'None', 'dash': [11, 3]}, 'b': {'marker': 'None', 'dash': [6, 3, 2, 3]}, 'c': {'marker': 'None', 'dash': [1, 3]}, 'y': {'marker': 'None', 'dash': [5, 3, 1,...
['def', 'setAxLinesBW(ax):', 'MARKERSIZE', '=', '3', 'COLORMAP', '=', "{'r':", "{'marker':", "'None',", "'dash':", "('None',", "'None')},", "'g':", "{'marker':", "'None',", "'dash':", '[5,', '2]},', "'m':", "{'marker':", "'None',", "'dash':", '[11,', '3]},', "'b':", "{'marker':", "'None',", "'dash':", '[6,', '3,', '2,'...
596,353
011235813/hierarchical-marl
env_wrapper.py
Env.do_nothing_action
do_nothing_action
For dealing with STS2 delays.
[ "For", "dealing", "with", "STS2", "delays." ]
def do_nothing_action(self): actions = {} for idx_agent in range(self.N_home): actions['h_ai_%d' % (idx_agent + 1)] = {'action': self.actions_home[0], 'input': [0.0, 0.0]} return actions
['def', 'do_nothing_action(self):', 'actions', '=', '{}', 'for', 'idx_agent', 'in', 'range(self.N_home):', "actions['h_ai_%d'", '%', '(idx_agent', '+', '1)]', '=', "{'action':", 'self.actions_home[0],', "'input':", '[0.0,', '0.0]}', 'return', 'actions']
592,904
kubeflow/pipelines
type_utils.py
get_artifact_type_schema
get_artifact_type_schema
Gets the IR I/O artifact type msg for the given ComponentSpec I/O type.
[ "Gets", "the", "IR", "I/O", "artifact", "type", "msg", "for", "the", "given", "ComponentSpec", "I/O", "type." ]
def get_artifact_type_schema(artifact_class_or_type_name: Optional[Union[str, Type[artifact_types.Artifact]]]) -> pipeline_spec_pb2.ArtifactTypeSchema: artifact_class = artifact_types.Artifact if isinstance(artifact_class_or_type_name, str): if re.match(_GOOGLE_TYPES_PATTERN, artifact_class_or_type_name...
['def', 'get_artifact_type_schema(artifact_class_or_type_name:', 'Optional[Union[str,', 'Type[artifact_types.Artifact]]])', '->', 'pipeline_spec_pb2.ArtifactTypeSchema:', 'artifact_class', '=', 'artifact_types.Artifact', 'if', 'isinstance(artifact_class_or_type_name,', 'str):', 'if', 're.match(_GOOGLE_TYPES_PATTERN,', ...
780,101
val-iisc/deligan
params.py
read_model_data
read_model_data
Unpickles and loads parameters into a Lasagne model.
[ "Unpickles", "and", "loads", "parameters", "into", "a", "Lasagne", "model." ]
def read_model_data(model, filename): filename = os.path.join('./', '%s.%s' % (filename, PARAM_EXTENSION)) with open(filename, 'r') as f: data = pickle.load(f) nn.layers.set_all_param_values(model, data)
['def', 'read_model_data(model,', 'filename):', 'filename', '=', "os.path.join('./',", "'%s.%s'", '%', '(filename,', 'PARAM_EXTENSION))', 'with', 'open(filename,', "'r')", 'as', 'f:', 'data', '=', 'pickle.load(f)', 'nn.layers.set_all_param_values(model,', 'data)']
537,028
zihuitang/medical_AI_platform
tracemalloc.py
Snapshot.dump
dump
Write the snapshot into a file.
[ "Write", "the", "snapshot", "into", "a", "file." ]
def dump(self, filename): with open(filename, 'wb') as fp: pickle.dump(self, fp, pickle.HIGHEST_PROTOCOL)
['def', 'dump(self,', 'filename):', 'with', 'open(filename,', "'wb')", 'as', 'fp:', 'pickle.dump(self,', 'fp,', 'pickle.HIGHEST_PROTOCOL)']
281,674
tobegit3hub/deep_image_model
distribution.py
Distribution.prob
prob
Probability density/mass function (depending on `is_continuous`).
[ "Probability", "density/mass", "function", "(depending", "on", "`is_continuous`)." ]
def prob(self, value, name='prob', **condition_kwargs): with self._name_scope(name, values=[value]): value = ops.convert_to_tensor(value, name='value') try: return self._prob(value, **condition_kwargs) except NotImplementedError as original_exception: try: ...
['def', 'prob(self,', 'value,', "name='prob',", '**condition_kwargs):', 'with', 'self._name_scope(name,', 'values=[value]):', 'value', '=', 'ops.convert_to_tensor(value,', "name='value')", 'try:', 'return', 'self._prob(value,', '**condition_kwargs)', 'except', 'NotImplementedError', 'as', 'original_exception:', 'try:',...
181,159
mfbx9da4/neuron-astrocyte-networks
population.py
EvolinoPopulation.clearFitness
clearFitness
Clears all fitness values of all subpopulations.
[ "Clears", "all", "fitness", "values", "of", "all", "subpopulations." ]
def clearFitness(self): for sp in self._subPopulations: sp.clearFitness()
['def', 'clearFitness(self):', 'for', 'sp', 'in', 'self._subPopulations:', 'sp.clearFitness()']
722,721
lhotse-speech/lhotse
test_custom_attrs.py
test_cut_load_array
test_cut_load_array
Check that a custom Array attribute is successfully recognized.
[ "Check", "that", "a", "custom", "Array", "attribute", "is", "successfully", "recognized." ]
def test_cut_load_array(): ivector = np.arange(20).astype(np.float32) with TemporaryDirectory() as d, LilcomFilesWriter(d) as writer: manifest = writer.store_array(key='utt1', value=ivector) cut = MonoCut(id='x', start=0, duration=5, channel=0) cut.ivector = manifest restored_ive...
['def', 'test_cut_load_array():', 'ivector', '=', 'np.arange(20).astype(np.float32)', 'with', 'TemporaryDirectory()', 'as', 'd,', 'LilcomFilesWriter(d)', 'as', 'writer:', 'manifest', '=', "writer.store_array(key='utt1',", 'value=ivector)', 'cut', '=', "MonoCut(id='x',", 'start=0,', 'duration=5,', 'channel=0)', 'cut.ive...
601,049
liqd/adhocracy
treatment.py
Treatment.get_assigned_users
get_assigned_users
Return a list(with one element for each variant) of the lists of assigned users.
[ "Return", "a", "list(with", "one", "element", "for", "each", "variant)", "of", "the", "lists", "of", "assigned", "users." ]
def get_assigned_users(self): return [vb.users for vb in self._variant_badges]
['def', 'get_assigned_users(self):', 'return', '[vb.users', 'for', 'vb', 'in', 'self._variant_badges]']
40,039
juaml/julearn
target_confound_remover.py
TargetConfoundRemover.needed_types
needed_types
Get the needed column types.
[ "Get", "the", "needed", "column", "types." ]
def needed_types(self) -> ColumnTypesLike: return self.confounds
['def', 'needed_types(self)', '->', 'ColumnTypesLike:', 'return', 'self.confounds']
593,772
voxel51/fiftyone
matplotlib.py
plot_roc_curve
plot_roc_curve
Plots a receiver operating characteristic (ROC) curve.
[ "Plots", "a", "receiver", "operating", "characteristic", "(ROC)", "curve." ]
def plot_roc_curve(fpr, tpr, roc_auc=None, title=None, ax=None, figsize=None, style=None, **kwargs): if style is None: style = _DEFAULT_STYLE if 'color' not in kwargs: kwargs['color'] = _DEFAULT_LINE_COLOR with plt.style.context(style): display = skm.RocCurveDisplay(fpr=fpr, tpr=tpr,...
['def', 'plot_roc_curve(fpr,', 'tpr,', 'roc_auc=None,', 'title=None,', 'ax=None,', 'figsize=None,', 'style=None,', '**kwargs):', 'if', 'style', 'is', 'None:', 'style', '=', '_DEFAULT_STYLE', 'if', "'color'", 'not', 'in', 'kwargs:', "kwargs['color']", '=', '_DEFAULT_LINE_COLOR', 'with', 'plt.style.context(style):', 'dis...
583,639
mnot/thor
server.py
HttpServerConnection.input_body
input_body
Process a request body chunk from the wire.
[ "Process", "a", "request", "body", "chunk", "from", "the", "wire." ]
def input_body(self, chunk: bytes) -> None: self.ex_queue[-1].emit('request_body', chunk)
['def', 'input_body(self,', 'chunk:', 'bytes)', '->', 'None:', "self.ex_queue[-1].emit('request_body',", 'chunk)']
355,158
robinhenry/gym-anm
simple_env.py
SimpleEnvironment.next_vars
next_vars
Return a random load injection in [-10, 0] and a random aux variable in [0,10].
[ "Return", "a", "random", "load", "injection", "in", "[-10,", "0]", "and", "a", "random", "aux", "variable", "in", "[0,10]." ]
def next_vars(self, s_t): P_load = -10 * np.random.rand(1)[0] aux = np.random.randint(0, 10) return np.array([P_load, aux])
['def', 'next_vars(self,', 's_t):', 'P_load', '=', '-10', '*', 'np.random.rand(1)[0]', 'aux', '=', 'np.random.randint(0,', '10)', 'return', 'np.array([P_load,', 'aux])']
572,814
43Carrig/recurrent_neural_networks_practice
function.py
Function.graph
graph
Returns the graph from which this function was constructed.
[ "Returns", "the", "graph", "from", "which", "this", "function", "was", "constructed." ]
def graph(self): return self._func_graph
['def', 'graph(self):', 'return', 'self._func_graph']
336,149
nicknochnack/RealTimeSignLanguageTFJS
coco_evaluation_test.py
CocoKeypointEvaluationTest.testGetOneMAPWithMatchingKeypoints
testGetOneMAPWithMatchingKeypoints
Tests that correct mAP for keypoints is calculated.
[ "Tests", "that", "correct", "mAP", "for", "keypoints", "is", "calculated." ]
def testGetOneMAPWithMatchingKeypoints(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='im...
['def', 'testGetOneMAPWithMatchingKeypoints(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_ima...
852,493
google-research/scenic
uvit.py
UViTMultiLabelClassificationModel.loss_function
loss_function
Returns sigmoid cross entropy loss with an L2 penalty on the weights.
[ "Returns", "sigmoid", "cross", "entropy", "loss", "with", "an", "L2", "penalty", "on", "the", "weights." ]
def loss_function(self, logits: jnp.ndarray, auxiliary_outputs: Any, batch: base_model.Batch, model_params: Optional[jnp.ndarray]=None) -> float: weights = batch.get('batch_mask') if self.dataset_meta_data.get('target_is_onehot', False): multihot_target = batch['label'] else: multihot_target...
['def', 'loss_function(self,', 'logits:', 'jnp.ndarray,', 'auxiliary_outputs:', 'Any,', 'batch:', 'base_model.Batch,', 'model_params:', 'Optional[jnp.ndarray]=None)', '->', 'float:', 'weights', '=', "batch.get('batch_mask')", 'if', "self.dataset_meta_data.get('target_is_onehot',", 'False):', 'multihot_target', '=', "ba...
846,740
microsoft/nni
bayesian.py
IncrementalGaussianProcess.first_fit
first_fit
Fit the regressor for the first time.
[ "Fit", "the", "regressor", "for", "the", "first", "time." ]
def first_fit(self, train_x, train_y): (train_x, train_y) = (np.array(train_x), np.array(train_y)) self._x = np.copy(train_x) self._y = np.copy(train_y) self._distance_matrix = edit_distance_matrix(self._x) k_matrix = bourgain_embedding_matrix(self._distance_matrix) k_matrix[np.diag_indices_from...
['def', 'first_fit(self,', 'train_x,', 'train_y):', '(train_x,', 'train_y)', '=', '(np.array(train_x),', 'np.array(train_y))', 'self._x', '=', 'np.copy(train_x)', 'self._y', '=', 'np.copy(train_y)', 'self._distance_matrix', '=', 'edit_distance_matrix(self._x)', 'k_matrix', '=', 'bourgain_embedding_matrix(self._distance...
728,356
matsu0228/nlp-jp
locale.py
Locale.friendly_number
friendly_number
Returns a comma-separated number for the given integer.
[ "Returns", "a", "comma-separated", "number", "for", "the", "given", "integer." ]
def friendly_number(self, value): if self.code not in ('en', 'en_US'): return str(value) value = str(value) parts = [] while value: parts.append(value[-3:]) value = value[:-3] return ','.join(reversed(parts))
['def', 'friendly_number(self,', 'value):', 'if', 'self.code', 'not', 'in', "('en',", "'en_US'):", 'return', 'str(value)', 'value', '=', 'str(value)', 'parts', '=', '[]', 'while', 'value:', 'parts.append(value[-3:])', 'value', '=', 'value[:-3]', 'return', "','.join(reversed(parts))"]
807,292
GeekLiB/keras
tensorflow_backend.py
zeros_like
zeros_like
Instantiates an all-zeros tensor of the same shape as another tensor.
[ "Instantiates", "an", "all-zeros", "tensor", "of", "the", "same", "shape", "as", "another", "tensor." ]
def zeros_like(x, name=None): return tf.zeros_like(x, name=name)
['def', 'zeros_like(x,', 'name=None):', 'return', 'tf.zeros_like(x,', 'name=name)']
247,752
explosion/spaCy
test_noun_chunks.py
test_noun_chunks_is_parsed_ms
test_noun_chunks_is_parsed_ms
Test that noun_chunks raises Value Error for 'ms' language if Doc is not parsed.
[ "Test", "that", "noun_chunks", "raises", "Value", "Error", "for", "'ms'", "language", "if", "Doc", "is", "not", "parsed." ]
def test_noun_chunks_is_parsed_ms(ms_tokenizer): doc = ms_tokenizer('sebelas') with pytest.raises(ValueError): list(doc.noun_chunks)
['def', 'test_noun_chunks_is_parsed_ms(ms_tokenizer):', 'doc', '=', "ms_tokenizer('sebelas')", 'with', 'pytest.raises(ValueError):', 'list(doc.noun_chunks)']
894,186
alex-petrenko/sample-factory
encoder.py
default_make_encoder_func
default_make_encoder_func
Analyze the observation space and create either a convolutional or an MLP encoder depending on whether this is an image-based environment or environment with vector observations.
[ "Analyze", "the", "observation", "space", "and", "create", "either", "a", "convolutional", "or", "an", "MLP", "encoder", "depending", "on", "whether", "this", "is", "an", "image-based", "environment", "or", "environment", "with", "vector", "observations." ]
def default_make_encoder_func(cfg: Config, obs_space: ObsSpace) -> Encoder: return MultiInputEncoder(cfg, obs_space)
['def', 'default_make_encoder_func(cfg:', 'Config,', 'obs_space:', 'ObsSpace)', '->', 'Encoder:', 'return', 'MultiInputEncoder(cfg,', 'obs_space)']
329,039
marlbenchmark/off-policy
StarCraft2_Env.py
StarCraft2Env.get_unit_type_id
get_unit_type_id
Returns the ID of unit type in the given scenario.
[ "Returns", "the", "ID", "of", "unit", "type", "in", "the", "given", "scenario." ]
def get_unit_type_id(self, unit, ally): if ally: type_id = unit.unit_type - self._min_unit_type elif self.map_type == 'stalkers_and_zealots': type_id = unit.unit_type - 73 elif self.map_type == 'colossi_stalkers_zealots': if unit.unit_type == 4: type_id = 0 elif u...
['def', 'get_unit_type_id(self,', 'unit,', 'ally):', 'if', 'ally:', 'type_id', '=', 'unit.unit_type', '-', 'self._min_unit_type', 'elif', 'self.map_type', '==', "'stalkers_and_zealots':", 'type_id', '=', 'unit.unit_type', '-', '73', 'elif', 'self.map_type', '==', "'colossi_stalkers_zealots':", 'if', 'unit.unit_type', '...
755,493
NUAAXQ/MLCVNet
ap_helper.py
APCalculator.step
step
Accumulate one batch of prediction and groundtruth.
[ "Accumulate", "one", "batch", "of", "prediction", "and", "groundtruth." ]
def step(self, batch_pred_map_cls, batch_gt_map_cls): bsize = len(batch_pred_map_cls) assert bsize == len(batch_gt_map_cls) for i in range(bsize): self.gt_map_cls[self.scan_cnt] = batch_gt_map_cls[i] self.pred_map_cls[self.scan_cnt] = batch_pred_map_cls[i] self.scan_cnt += 1
['def', 'step(self,', 'batch_pred_map_cls,', 'batch_gt_map_cls):', 'bsize', '=', 'len(batch_pred_map_cls)', 'assert', 'bsize', '==', 'len(batch_gt_map_cls)', 'for', 'i', 'in', 'range(bsize):', 'self.gt_map_cls[self.scan_cnt]', '=', 'batch_gt_map_cls[i]', 'self.pred_map_cls[self.scan_cnt]', '=', 'batch_pred_map_cls[i]',...
630,108
Kvatsx/Artificial-Intelligence-Assignments
_tifffile.py
decode_jpeg
decode_jpeg
Decode JPEG encoded byte string (using _czifile extension module).
[ "Decode", "JPEG", "encoded", "byte", "string", "(using", "_czifile", "extension", "module)." ]
def decode_jpeg(encoded, tables=b'', photometric=None, ycbcrsubsampling=None, ycbcrpositioning=None): from czifile import _czifile image = _czifile.decode_jpeg(encoded, tables) if photometric == 2 and ycbcrsubsampling and ycbcrpositioning: pass return image.tostring()
['def', 'decode_jpeg(encoded,', "tables=b'',", 'photometric=None,', 'ycbcrsubsampling=None,', 'ycbcrpositioning=None):', 'from', 'czifile', 'import', '_czifile', 'image', '=', '_czifile.decode_jpeg(encoded,', 'tables)', 'if', 'photometric', '==', '2', 'and', 'ycbcrsubsampling', 'and', 'ycbcrpositioning:', 'pass', 'retu...
37,518
Erfanafshar/Principles-and-Applications-of---graph-coloring
dates.py
DateLocator.set_tzinfo
set_tzinfo
Set time zone info.
[ "Set", "time", "zone", "info." ]
def set_tzinfo(self, tz): self.tz = tz
['def', 'set_tzinfo(self,', 'tz):', 'self.tz', '=', 'tz']
306,646
Vill-Lab/2021-TIP-IGOAS
sampler.py
build_train_sampler
build_train_sampler
Builds a training sampler.
[ "Builds", "a", "training", "sampler." ]
def build_train_sampler(data_source, train_sampler, batch_size=32, num_instances=4, **kwargs): if train_sampler == 'RandomIdentitySampler': sampler = RandomIdentitySampler(data_source, batch_size, num_instances) else: sampler = RandomSampler(data_source) return sampler
['def', 'build_train_sampler(data_source,', 'train_sampler,', 'batch_size=32,', 'num_instances=4,', '**kwargs):', 'if', 'train_sampler', '==', "'RandomIdentitySampler':", 'sampler', '=', 'RandomIdentitySampler(data_source,', 'batch_size,', 'num_instances)', 'else:', 'sampler', '=', 'RandomSampler(data_source)', 'return...
375,433
DeepakSridhar/Deep-Learning-Coursera
misc.py
sigmoid
sigmoid
Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size.
[ "Compute", "the", "sigmoid", "of", "x", "Arguments:", "x", "--", "A", "scalar", "or", "numpy", "array", "of", "any", "size." ]
def sigmoid(x): s = 1 / (1 + np.exp(-x)) return s
['def', 'sigmoid(x):', 's', '=', '1', '/', '(1', '+', 'np.exp(-x))', 'return', 's']
517,340
thu-ml/ares
boundary.py
BoundaryAttack.get_init_noise
get_init_noise
The function to initialize noise.
[ "The", "function", "to", "initialize", "noise." ]
def get_init_noise(self, x_target, y, ytarget): while True: x_init = torch.rand(x_target.size()).to(self.device) x_init = torch.clamp(x_init, min=self.min_value, max=self.max_value) if self._is_adversarial(x_init, y, ytarget): return x_init
['def', 'get_init_noise(self,', 'x_target,', 'y,', 'ytarget):', 'while', 'True:', 'x_init', '=', 'torch.rand(x_target.size()).to(self.device)', 'x_init', '=', 'torch.clamp(x_init,', 'min=self.min_value,', 'max=self.max_value)', 'if', 'self._is_adversarial(x_init,', 'y,', 'ytarget):', 'return', 'x_init']
401,969
YuriyGuts/snake-ai-reinforcement
environment.py
Environment.record_timestep_stats
record_timestep_stats
Record environment statistics according to the verbosity level.
[ "Record", "environment", "statistics", "according", "to", "the", "verbosity", "level." ]
def record_timestep_stats(self, result): timestamp = time.strftime('%Y%m%d-%H%M%S') if self.verbose >= 1 and self.stats_file is None: self.stats_file = open(f'snake-env-{timestamp}.csv', 'w') stats_csv_header_line = self.stats.to_dataframe()[:0].to_csv(index=None) print(stats_csv_header_...
['def', 'record_timestep_stats(self,', 'result):', 'timestamp', '=', "time.strftime('%Y%m%d-%H%M%S')", 'if', 'self.verbose', '>=', '1', 'and', 'self.stats_file', 'is', 'None:', 'self.stats_file', '=', "open(f'snake-env-{timestamp}.csv',", "'w')", 'stats_csv_header_line', '=', 'self.stats.to_dataframe()[:0].to_csv(index...
352,171
angeladai/ScanComplete
util.py
quantize
quantize
Quantizes df in tensor to [0,num_quant_levels-1].
[ "Quantizes", "df", "in", "tensor", "to", "[0,num_quant_levels-1]." ]
def quantize(tensor, num_quant_levels, truncation): if num_quant_levels == 2: return np.less_equal(tensor, 1).astype(np.uint8) return np.round(tensor / truncation * (num_quant_levels - 1)).astype(np.uint8)
['def', 'quantize(tensor,', 'num_quant_levels,', 'truncation):', 'if', 'num_quant_levels', '==', '2:', 'return', 'np.less_equal(tensor,', '1).astype(np.uint8)', 'return', 'np.round(tensor', '/', 'truncation', '*', '(num_quant_levels', '-', '1)).astype(np.uint8)']
845,863
Ruturaj123/Flowchart-Detection
checkpoint_ops_test.py
LoadAndRemapMatrixWithMaxRowsTest.test_loading_partitions_equals_max_rows
test_loading_partitions_equals_max_rows
Tests loading partitioned var sliced on partition boundary.
[ "Tests", "loading", "partitioned", "var", "sliced", "on", "partition", "boundary." ]
def test_loading_partitions_equals_max_rows(self): self._test_loading_variable_with_max_rows(np_value=np.reshape(list(range(0, 36)), (9, 4)), partitioner=partitioned_variables.fixed_size_partitioner(3), max_rows_in_memory=3)
['def', 'test_loading_partitions_equals_max_rows(self):', 'self._test_loading_variable_with_max_rows(np_value=np.reshape(list(range(0,', '36)),', '(9,', '4)),', 'partitioner=partitioned_variables.fixed_size_partitioner(3),', 'max_rows_in_memory=3)']
603,060
thaines/helit
corpus.py
Corpus.setRho
setRho
Sets the concentration details used for each cluster instance.
[ "Sets", "the", "concentration", "details", "used", "for", "each", "cluster", "instance." ]
def setRho(self, alpha, beta, conc): self.rho.alpha = alpha self.rho.beta = beta self.rho.conc = conc
['def', 'setRho(self,', 'alpha,', 'beta,', 'conc):', 'self.rho.alpha', '=', 'alpha', 'self.rho.beta', '=', 'beta', 'self.rho.conc', '=', 'conc']
591,370
Kvatsx/Artificial-Intelligence-Assignments
named_commands.py
emacs_editing_mode
emacs_editing_mode
Switch to Emacs editing mode.
[ "Switch", "to", "Emacs", "editing", "mode." ]
def emacs_editing_mode(event): event.app.editing_mode = EditingMode.EMACS
['def', 'emacs_editing_mode(event):', 'event.app.editing_mode', '=', 'EditingMode.EMACS']
75,937
cjiang2/video2command
utils.py
build_vocab
build_vocab
Build vocabulary over texts/captions from training set.
[ "Build", "vocabulary", "over", "texts/captions", "from", "training", "set." ]
def build_vocab(texts, frequency=None, filters='!"#$%&()*+.,-/:;=?@[\\]^_`{|}~ ', lower=True, split=' ', start_word='<sos>', end_word='<eos>', unk_word=None): counter = Counter() for (i, text) in enumerate(texts): tokens = word_tokenize(text, filters, lower, split) counter.update(tokens) ...
['def', 'build_vocab(texts,', 'frequency=None,', 'filters=\'!"#$%&()*+.,-/:;=?@[\\\\]^_`{|}~', "',", 'lower=True,', "split='", "',", "start_word='<sos>',", "end_word='<eos>',", 'unk_word=None):', 'counter', '=', 'Counter()', 'for', '(i,', 'text)', 'in', 'enumerate(texts):', 'tokens', '=', 'word_tokenize(text,', 'filter...
379,890
tusen-ai/SST
seg_eval.py
per_class_iou
per_class_iou
Compute the per class iou.
[ "Compute", "the", "per", "class", "iou." ]
def per_class_iou(hist): return np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist))
['def', 'per_class_iou(hist):', 'return', 'np.diag(hist)', '/', '(hist.sum(1)', '+', 'hist.sum(0)', '-', 'np.diag(hist))']
872,261
43Carrig/recurrent_neural_networks_practice
containers.py
RepeatedCompositeFieldContainer.MergeFrom
MergeFrom
Appends the contents of another repeated field of the same type to this one, copying each individual message.
[ "Appends", "the", "contents", "of", "another", "repeated", "field", "of", "the", "same", "type", "to", "this", "one,", "copying", "each", "individual", "message." ]
def MergeFrom(self, other): self.extend(other._values)
['def', 'MergeFrom(self,', 'other):', 'self.extend(other._values)']
309,910
deepmind/acme
savers_test.py
SnapshotterTest.test_snapshot
test_snapshot
Test that snapshotter correctly calls saves/restores snapshots.
[ "Test", "that", "snapshotter", "correctly", "calls", "saves/restores", "snapshots." ]
def test_snapshot(self): net1 = networks.LayerNormMLP([10, 10]) spec = specs.Array([10], dtype=np.float32) tf2_utils.create_variables(net1, [spec]) directory = self.get_tempdir() objects_to_save = {'net': net1} snapshotter = tf2_savers.Snapshotter(objects_to_save, directory=directory) snapsh...
['def', 'test_snapshot(self):', 'net1', '=', 'networks.LayerNormMLP([10,', '10])', 'spec', '=', 'specs.Array([10],', 'dtype=np.float32)', 'tf2_utils.create_variables(net1,', '[spec])', 'directory', '=', 'self.get_tempdir()', 'objects_to_save', '=', "{'net':", 'net1}', 'snapshotter', '=', 'tf2_savers.Snapshotter(objects...
8,387
facebookresearch/deep_bisim4control
lqr.py
LQRLevel.get_evaluation
get_evaluation
Returns a sparse evaluation reward that is not used for learning.
[ "Returns", "a", "sparse", "evaluation", "reward", "that", "is", "not", "used", "for", "learning." ]
def get_evaluation(self, physics): return float(physics.state_norm() <= 0.01)
['def', 'get_evaluation(self,', 'physics):', 'return', 'float(physics.state_norm()', '<=', '0.01)']
536,401
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.winfo_parent
winfo_parent
Return the name of the parent of this widget.
[ "Return", "the", "name", "of", "the", "parent", "of", "this", "widget." ]
def winfo_parent(self): return self.tk.call('winfo', 'parent', self._w)
['def', 'winfo_parent(self):', 'return', "self.tk.call('winfo',", "'parent',", 'self._w)']
376,814
PartnershipOnAI/safelife
safelife_game.py
GameWithGoals.setup_initial_counts
setup_initial_counts
Record the counts of live cells and possible colors for new cells.
[ "Record", "the", "counts", "of", "live", "cells", "and", "possible", "colors", "for", "new", "cells." ]
def setup_initial_counts(self): self.initial_counts = self.alive_counts self.initial_colors = np.zeros(9, dtype=bool) generators = CellTypes.agent | CellTypes.alive | CellTypes.spawning colors = self.board[self.board & generators > 0] & CellTypes.rainbow_color colors = np.unique(colors) >> CellTypes...
['def', 'setup_initial_counts(self):', 'self.initial_counts', '=', 'self.alive_counts', 'self.initial_colors', '=', 'np.zeros(9,', 'dtype=bool)', 'generators', '=', 'CellTypes.agent', '|', 'CellTypes.alive', '|', 'CellTypes.spawning', 'colors', '=', 'self.board[self.board', '&', 'generators', '>', '0]', '&', 'CellTypes...
829,255
erichson/LipschitzRNN
tools.py
get_device
get_device
Get a gpu if available.
[ "Get", "a", "gpu", "if", "available." ]
def get_device(): if torch.cuda.device_count() > 0: device = torch.device('cuda') print('Connected to a GPU') else: print('Using the CPU') device = torch.device('cpu') return device
['def', 'get_device():', 'if', 'torch.cuda.device_count()', '>', '0:', 'device', '=', "torch.device('cuda')", "print('Connected", 'to', 'a', "GPU')", 'else:', "print('Using", 'the', "CPU')", 'device', '=', "torch.device('cpu')", 'return', 'device']
216,890
tobegit3hub/deep_image_model
random_forest.py
TensorForestEstimator.predict_proba
predict_proba
Returns prediction probabilities for given features (classification).
[ "Returns", "prediction", "probabilities", "for", "given", "features", "(classification)." ]
def predict_proba(self, x=None, input_fn=None, batch_size=None, outputs=None, as_iterable=True): results = self._estimator.predict(x=x, input_fn=input_fn, batch_size=batch_size, outputs=outputs, as_iterable=as_iterable) if as_iterable: return (x[eval_metrics.INFERENCE_PROB_NAME] for x in results) el...
['def', 'predict_proba(self,', 'x=None,', 'input_fn=None,', 'batch_size=None,', 'outputs=None,', 'as_iterable=True):', 'results', '=', 'self._estimator.predict(x=x,', 'input_fn=input_fn,', 'batch_size=batch_size,', 'outputs=outputs,', 'as_iterable=as_iterable)', 'if', 'as_iterable:', 'return', '(x[eval_metrics.INFERENC...
181,798
MycroftAI/mycroft-core
test_string_utils.py
TestStringFunctions.test_camel_case_split
test_camel_case_split
Check that camel case string is split properly.
[ "Check", "that", "camel", "case", "string", "is", "split", "properly." ]
def test_camel_case_split(self): self.assertEqual(camel_case_split('MyCoolSkill'), 'My Cool Skill') self.assertEqual(camel_case_split('MyCOOLSkill'), 'My COOL Skill')
['def', 'test_camel_case_split(self):', "self.assertEqual(camel_case_split('MyCoolSkill'),", "'My", 'Cool', "Skill')", "self.assertEqual(camel_case_split('MyCOOLSkill'),", "'My", 'COOL', "Skill')"]
291,030
akhilmathurs/orchestra
server.py
get_eval_fn
get_eval_fn
Return an evaluation function for server-side evaluation.
[ "Return", "an", "evaluation", "function", "for", "server-side", "evaluation." ]
def get_eval_fn(config_dict, net, device, global_acc_dict): (_, memloader, testloader) = utils.load_data(config_dict, client_id=-1, bsize=256) def evaluate(weights: fl.common.Weights) -> Optional[Tuple[float, Dict[str, fl.common.Scalar]]]: params_dict = zip(net.state_dict().keys(), weights) sta...
['def', 'get_eval_fn(config_dict,', 'net,', 'device,', 'global_acc_dict):', '(_,', 'memloader,', 'testloader)', '=', 'utils.load_data(config_dict,', 'client_id=-1,', 'bsize=256)', 'def', 'evaluate(weights:', 'fl.common.Weights)', '->', 'Optional[Tuple[float,', 'Dict[str,', 'fl.common.Scalar]]]:', 'params_dict', '=', 'z...
253,363
voxel51/fiftyone
database.py
drop_collection
drop_collection
Drops specified collection from the database.
[ "Drops", "specified", "collection", "from", "the", "database." ]
def drop_collection(collection_name): conn = get_db_conn() conn.drop_collection(collection_name)
['def', 'drop_collection(collection_name):', 'conn', '=', 'get_db_conn()', 'conn.drop_collection(collection_name)']
583,528
salesforce/CodeRL
trainer_pt_utils.py
nested_new_like
nested_new_like
Create the same nested structure as `arrays` with a first dimension always at `num_samples`.
[ "Create", "the", "same", "nested", "structure", "as", "`arrays`", "with", "a", "first", "dimension", "always", "at", "`num_samples`." ]
def nested_new_like(arrays, num_samples, padding_index=-100): if isinstance(arrays, (list, tuple)): return type(arrays)((nested_new_like(x, num_samples) for x in arrays)) return np.full_like(arrays, padding_index, shape=(num_samples, *arrays.shape[1:]))
['def', 'nested_new_like(arrays,', 'num_samples,', 'padding_index=-100):', 'if', 'isinstance(arrays,', '(list,', 'tuple)):', 'return', 'type(arrays)((nested_new_like(x,', 'num_samples)', 'for', 'x', 'in', 'arrays))', 'return', 'np.full_like(arrays,', 'padding_index,', 'shape=(num_samples,', '*arrays.shape[1:]))']
494,173
renfredxh/compilebot
reply.py
TestCreateReply.test_result_errors
test_result_errors
Test each error code and ensure the user will be alerted of errors via private message instead of in compiled replies.
[ "Test", "each", "error", "code", "and", "ensure", "the", "user", "will", "be", "alerted", "of", "errors", "via", "private", "message", "instead", "of", "in", "compiled", "replies." ]
def test_result_errors(self): with patch('{}.cb.compile'.format(__name__)) as mock_compile: for error_code in [13, 17, 19, 20, 12]: mock_compile.return_value = {'cmpinfo': '', 'input': '', 'langName': 'Python', 'output': 'Test', 'result': error_code, 'stderr': 'Error message', 'link': ''} ...
['def', 'test_result_errors(self):', 'with', "patch('{}.cb.compile'.format(__name__))", 'as', 'mock_compile:', 'for', 'error_code', 'in', '[13,', '17,', '19,', '20,', '12]:', 'mock_compile.return_value', '=', "{'cmpinfo':", "'',", "'input':", "'',", "'langName':", "'Python',", "'output':", "'Test',", "'result':", 'erro...
125,320
Ruturaj123/Flowchart-Detection
relaxed_bernoulli.py
RelaxedBernoulli.temperature
temperature
Distribution parameter for the location.
[ "Distribution", "parameter", "for", "the", "location." ]
def temperature(self): return self._temperature
['def', 'temperature(self):', 'return', 'self._temperature']
602,920
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
wikisum.py
extract_references_from_wets
extract_references_from_wets
Extract references from WET files into sharded output files.
[ "Extract", "references", "from", "WET", "files", "into", "sharded", "output", "files." ]
def extract_references_from_wets(wet_files, metadata_dir, out_dir, tmp_dir=None): shard_files = make_ref_shard_files(out_dir) num_refs = 0 for (i, wet_file) in enumerate(wet_files): num_refs_in_wet = 0 tf.logging.info('Processing file %d', i) metadata_fname = os.path.join(metadata_di...
['def', 'extract_references_from_wets(wet_files,', 'metadata_dir,', 'out_dir,', 'tmp_dir=None):', 'shard_files', '=', 'make_ref_shard_files(out_dir)', 'num_refs', '=', '0', 'for', '(i,', 'wet_file)', 'in', 'enumerate(wet_files):', 'num_refs_in_wet', '=', '0', "tf.logging.info('Processing", 'file', "%d',", 'i)', 'metada...
965,114
asyml/texar-pytorch
xlnet_utils.py
PositionWiseFF.output_size
output_size
The feature size of :meth:`forward` output.
[ "The", "feature", "size", "of", ":meth:`forward`", "output." ]
def output_size(self): return self._hparams.hidden_dim
['def', 'output_size(self):', 'return', 'self._hparams.hidden_dim']
925,264
flavioschneider/rl-transfer-
test_maml_ppo.py
TestMAMLPPO.setup_method
setup_method
Setup method which is called before every test.
[ "Setup", "method", "which", "is", "called", "before", "every", "test." ]
def setup_method(self): self.env = normalize(GymEnv(HalfCheetahDirEnv(), max_episode_length=100), expected_action_scale=10.0) self.task_sampler = SetTaskSampler(HalfCheetahDirEnv, wrapper=lambda env, _: normalize(GymEnv(env, max_episode_length=100), expected_action_scale=10.0)) self.policy = GaussianMLPPoli...
['def', 'setup_method(self):', 'self.env', '=', 'normalize(GymEnv(HalfCheetahDirEnv(),', 'max_episode_length=100),', 'expected_action_scale=10.0)', 'self.task_sampler', '=', 'SetTaskSampler(HalfCheetahDirEnv,', 'wrapper=lambda', 'env,', '_:', 'normalize(GymEnv(env,', 'max_episode_length=100),', 'expected_action_scale=1...
861,796
aeon-toolkit/aeon
test_reduce.py
test_sliding_window_transform_against_cv
test_sliding_window_transform_against_cv
Test sliding window transform against cv.
[ "Test", "sliding", "window", "transform", "against", "cv." ]
def test_sliding_window_transform_against_cv(n_timepoints, window_length, fh, scitype): fh = check_fh(fh) y = pd.Series(_make_y(0, n_timepoints)) cv = SlidingWindowSplitter(fh=fh, window_length=window_length) (xa, ya) = _get_windows(cv, y) (yb, xb) = _sliding_window_transform(y, window_length, fh, s...
['def', 'test_sliding_window_transform_against_cv(n_timepoints,', 'window_length,', 'fh,', 'scitype):', 'fh', '=', 'check_fh(fh)', 'y', '=', 'pd.Series(_make_y(0,', 'n_timepoints))', 'cv', '=', 'SlidingWindowSplitter(fh=fh,', 'window_length=window_length)', '(xa,', 'ya)', '=', '_get_windows(cv,', 'y)', '(yb,', 'xb)', '...
399,650