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
huggingface/datasets-server
queue.py
Queue.is_job_in_process
is_job_in_process
Check if a job is in process (waiting or started).
[ "Check", "if", "a", "job", "is", "in", "process", "(waiting", "or", "started)." ]
def is_job_in_process(self, job_type: str, dataset: str, revision: str, config: Optional[str]=None, split: Optional[str]=None) -> bool: return JobDocument.objects(type=job_type, dataset=dataset, revision=revision, config=config, split=split, status__in=[Status.WAITING, Status.STARTED]).count() > 0
['def', 'is_job_in_process(self,', 'job_type:', 'str,', 'dataset:', 'str,', 'revision:', 'str,', 'config:', 'Optional[str]=None,', 'split:', 'Optional[str]=None)', '->', 'bool:', 'return', 'JobDocument.objects(type=job_type,', 'dataset=dataset,', 'revision=revision,', 'config=config,', 'split=split,', 'status__in=[Stat...
497,885
enuguru/artificial_intelligence_and_machine_learning
compiler.py
CodeGenerator.write
write
Write a string into the output stream.
[ "Write", "a", "string", "into", "the", "output", "stream." ]
def write(self, x): if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) ...
['def', 'write(self,', 'x):', 'if', 'self._new_lines:', 'if', 'not', 'self._first_write:', "self.stream.write('\\n'", '*', 'self._new_lines)', 'self.code_lineno', '+=', 'self._new_lines', 'if', 'self._write_debug_info', 'is', 'not', 'None:', 'self.debug_info.append((self._write_debug_info,', 'self.code_lineno))', 'self...
129,043
FedML-AI/FedML
efficientnet.py
EfficientNet.extract_features
extract_features
use convolution layer to extract feature .
[ "use", "convolution", "layer", "to", "extract", "feature", "." ]
def extract_features(self, inputs): x = self._swish(self._bn0(self._conv_stem(inputs))) for (idx, block) in enumerate(self._blocks): drop_connect_rate = self._global_params.drop_connect_rate if drop_connect_rate: drop_connect_rate *= float(idx) / len(self._blocks) x = block(x...
['def', 'extract_features(self,', 'inputs):', 'x', '=', 'self._swish(self._bn0(self._conv_stem(inputs)))', 'for', '(idx,', 'block)', 'in', 'enumerate(self._blocks):', 'drop_connect_rate', '=', 'self._global_params.drop_connect_rate', 'if', 'drop_connect_rate:', 'drop_connect_rate', '*=', 'float(idx)', '/', 'len(self._b...
545,150
sktime/sktime
test_stray.py
test_2D_score_with_standardize
test_2D_score_with_standardize
Test score with 2D input array and median/IQR normalization.
[ "Test", "score", "with", "2D", "input", "array", "and", "median/IQR", "normalization." ]
def test_2D_score_with_standardize(): X = np.array([[-1.20706575, -0.57473996], [0.27742924, -0.54663186], [1.08444118, -0.564452], [-2.3456977, -0.89003783], [0.42912469, -0.4771927], [0.50605589, -0.99838644]]) y_scores_expected = np.array([1.1274565, 0.6139288, 0.5982989, 1.4866554, 0.5982989, 1.7245212]) ...
['def', 'test_2D_score_with_standardize():', 'X', '=', 'np.array([[-1.20706575,', '-0.57473996],', '[0.27742924,', '-0.54663186],', '[1.08444118,', '-0.564452],', '[-2.3456977,', '-0.89003783],', '[0.42912469,', '-0.4771927],', '[0.50605589,', '-0.99838644]])', 'y_scores_expected', '=', 'np.array([1.1274565,', '0.61392...
885,778
RasaHQ/rasa
finetuning_validator.py
FinetuningValidator.create
create
Creates a new `FineTuningValidator` (see parent class for full docstring).
[ "Creates", "a", "new", "`FineTuningValidator`", "(see", "parent", "class", "for", "full", "docstring)." ]
def create(cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> FinetuningValidator: return cls(config=config, model_storage=model_storage, resource=resource, execution_context=execution_context)
['def', 'create(cls,', 'config:', 'Dict[Text,', 'Any],', 'model_storage:', 'ModelStorage,', 'resource:', 'Resource,', 'execution_context:', 'ExecutionContext)', '->', 'FinetuningValidator:', 'return', 'cls(config=config,', 'model_storage=model_storage,', 'resource=resource,', 'execution_context=execution_context)']
837,093
enuguru/artificial_intelligence_and_machine_learning
test.py
encode_multipart
encode_multipart
Like `stream_encode_multipart` but returns a tuple in the form (``boundary``, ``data``) where data is a bytestring.
[ "Like", "`stream_encode_multipart`", "but", "returns", "a", "tuple", "in", "the", "form", "(``boundary``,", "``data``)", "where", "data", "is", "a", "bytestring." ]
def encode_multipart(values, boundary=None, charset='utf-8'): (stream, length, boundary) = stream_encode_multipart(values, use_tempfile=False, boundary=boundary, charset=charset) return (boundary, stream.read())
['def', 'encode_multipart(values,', 'boundary=None,', "charset='utf-8'):", '(stream,', 'length,', 'boundary)', '=', 'stream_encode_multipart(values,', 'use_tempfile=False,', 'boundary=boundary,', 'charset=charset)', 'return', '(boundary,', 'stream.read())']
132,343
calico/basenji
basenji_data_align.py
rejoin_large_contigs
rejoin_large_contigs
Rejoin large contigs that were broken up before alignment comparison.
[ "Rejoin", "large", "contigs", "that", "were", "broken", "up", "before", "alignment", "comparison." ]
def rejoin_large_contigs(contigs): gchr_contigs = {} for ctg in contigs: gchr = (ctg.genome, ctg.chr) gchr_contigs.setdefault(gchr, []).append(ctg) contigs = [] for gchr in gchr_contigs: gchr_contigs[gchr].sort(key=lambda x: x.start) ctg_ongoing = gchr_contigs[gchr][0] ...
['def', 'rejoin_large_contigs(contigs):', 'gchr_contigs', '=', '{}', 'for', 'ctg', 'in', 'contigs:', 'gchr', '=', '(ctg.genome,', 'ctg.chr)', 'gchr_contigs.setdefault(gchr,', '[]).append(ctg)', 'contigs', '=', '[]', 'for', 'gchr', 'in', 'gchr_contigs:', 'gchr_contigs[gchr].sort(key=lambda', 'x:', 'x.start)', 'ctg_ongoi...
94,745
llSourcell/AI_Artist
install.py
WheelFile.arity
arity
The number of compatibility tags the wheel declares.
[ "The", "number", "of", "compatibility", "tags", "the", "wheel", "declares." ]
def arity(self): return len(list(self.compatibility_tags))
['def', 'arity(self):', 'return', 'len(list(self.compatibility_tags))']
414,457
TonyLianLong/VAI-ReinforcementLearning
debugging.py
debug_mode
debug_mode
Returns a boolean that indicates whether PyMJCF debug mode is enabled.
[ "Returns", "a", "boolean", "that", "indicates", "whether", "PyMJCF", "debug", "mode", "is", "enabled." ]
def debug_mode(): global _DEBUG_MODE_ENABLED if _DEBUG_MODE_ENABLED is None: if FLAGS.is_parsed(): _DEBUG_MODE_ENABLED = FLAGS.pymjcf_debug else: _DEBUG_MODE_ENABLED = FLAGS['pymjcf_debug'].default return _DEBUG_MODE_ENABLED
['def', 'debug_mode():', 'global', '_DEBUG_MODE_ENABLED', 'if', '_DEBUG_MODE_ENABLED', 'is', 'None:', 'if', 'FLAGS.is_parsed():', '_DEBUG_MODE_ENABLED', '=', 'FLAGS.pymjcf_debug', 'else:', '_DEBUG_MODE_ENABLED', '=', "FLAGS['pymjcf_debug'].default", 'return', '_DEBUG_MODE_ENABLED']
439,999
kornia/kornia
elastic_transform.py
RandomElasticTransform.apply_transform_box
apply_transform_box
Process masks corresponding to the inputs that are transformed.
[ "Process", "masks", "corresponding", "to", "the", "inputs", "that", "are", "transformed." ]
def apply_transform_box(self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor]=None) -> Boxes: return input
['def', 'apply_transform_box(self,', 'input:', 'Boxes,', 'params:', 'Dict[str,', 'Tensor],', 'flags:', 'Dict[str,', 'Any],', 'transform:', 'Optional[Tensor]=None)', '->', 'Boxes:', 'return', 'input']
621,537
neardws/Game-Theoretic-Deep-Reinforcement-Learning
gradient.py
GradientTape.watched_variables
watched_variables
Returns variables watched by this tape in order of construction.
[ "Returns", "variables", "watched", "by", "this", "tape", "in", "order", "of", "construction." ]
def watched_variables(self): if self._tape is not None: self._watched_variables = self._tape.watched_variables() return self._watched_variables
['def', 'watched_variables(self):', 'if', 'self._tape', 'is', 'not', 'None:', 'self._watched_variables', '=', 'self._tape.watched_variables()', 'return', 'self._watched_variables']
199,914
thaines/helit
test_p2.py
TestPly2.equal
equal
Internal method that compares two ply files in the dictionary representation, to see if they are identical - will fail the test if not.
[ "Internal", "method", "that", "compares", "two", "ply", "files", "in", "the", "dictionary", "representation,", "to", "see", "if", "they", "are", "identical", "-", "will", "fail", "the", "test", "if", "not." ]
def equal(self, a, b): self.assertTrue((a['format'] if 'format' in a else 'ascii') == (b['format'] if 'format' in b else 'ascii')) self.assertTrue(set(a['type'] if 'type' in a else []) == set(b['type'] if 'type' in b else [])) a_meta = a['meta'] if 'meta' in a else dict() b_meta = b['meta'] if 'meta' in...
['def', 'equal(self,', 'a,', 'b):', "self.assertTrue((a['format']", 'if', "'format'", 'in', 'a', 'else', "'ascii')", '==', "(b['format']", 'if', "'format'", 'in', 'b', 'else', "'ascii'))", "self.assertTrue(set(a['type']", 'if', "'type'", 'in', 'a', 'else', '[])', '==', "set(b['type']", 'if', "'type'", 'in', 'b', 'else'...
592,275
YiSyuanChen/MTL-ABS
pyrouge.py
Rouge155.settings_file
settings_file
Path of the setttings file, which stores the ROUGE home dir.
[ "Path", "of", "the", "setttings", "file,", "which", "stores", "the", "ROUGE", "home", "dir." ]
def settings_file(self): return self._settings_file
['def', 'settings_file(self):', 'return', 'self._settings_file']
642,832
dguo98/DiffPruning
utils.py
set_seed
set_seed
Set the random seed.
[ "Set", "the", "random", "seed." ]
def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed)
['def', 'set_seed(args):', 'np.random.seed(args.seed)', 'torch.manual_seed(args.seed)', 'if', 'args.n_gpu', '>', '0:', 'torch.cuda.manual_seed_all(args.seed)']
550,460
openvinotoolkit/training_extensions
loss_dynamics_mixin.py
DetLossDynamicsTrackingMixin.train_step
train_step
The iteration step during training.
[ "The", "iteration", "step", "during", "training." ]
def train_step(self, data, optimizer): outputs = super().train_step(data, optimizer) if self.loss_dyns_tracker.initialized: gt_ann_ids = [item['gt_ann_ids'] for item in data['img_metas']] to_update = {} for (key, loss_dyns) in self.bbox_head.loss_dyns.items(): to_update[key] ...
['def', 'train_step(self,', 'data,', 'optimizer):', 'outputs', '=', 'super().train_step(data,', 'optimizer)', 'if', 'self.loss_dyns_tracker.initialized:', 'gt_ann_ids', '=', "[item['gt_ann_ids']", 'for', 'item', 'in', "data['img_metas']]", 'to_update', '=', '{}', 'for', '(key,', 'loss_dyns)', 'in', 'self.bbox_head.loss...
918,131
Farama-Foundation/Gymnasium
vector_env.py
VectorWrapper.unwrapped
unwrapped
Return the base non-wrapped environment.
[ "Return", "the", "base", "non-wrapped", "environment." ]
def unwrapped(self): return self.env.unwrapped
['def', 'unwrapped(self):', 'return', 'self.env.unwrapped']
573,119
simpleai-team/simpleai
models.py
SearchProblem.heuristic
heuristic
Returns an estimate of the cost remaining to reach the solution from `state`.
[ "Returns", "an", "estimate", "of", "the", "cost", "remaining", "to", "reach", "the", "solution", "from", "`state`." ]
def heuristic(self, state): return 0
['def', 'heuristic(self,', 'state):', 'return', '0']
350,644
danielpontello/cnn-captcha-solving
fies-generate.py
rndPointDisposition
rndPointDisposition
Return random disposition point.
[ "Return", "random", "disposition", "point." ]
def rndPointDisposition(dx, dy): x = int(random.uniform(-dx, dx)) y = int(random.uniform(-dy, dy)) return (x, y)
['def', 'rndPointDisposition(dx,', 'dy):', 'x', '=', 'int(random.uniform(-dx,', 'dx))', 'y', '=', 'int(random.uniform(-dy,', 'dy))', 'return', '(x,', 'y)']
123,563
liuzuxin/MPC_template-model_predictive_control_for__
dataset.py
DataLoader.sequential_next
sequential_next
Sequential version of the pre-processing.
[ "Sequential", "version", "of", "the", "pre-processing." ]
def sequential_next(self): if self.start_idx > len(self.indices): raise StopIteration if self.start_idx == 0: if self.shuffle: np.random.shuffle(self.indices) obs = self.observations[self._minibatch_indices] if self.load_images: obs = np.concatenate([self._make_batch_...
['def', 'sequential_next(self):', 'if', 'self.start_idx', '>', 'len(self.indices):', 'raise', 'StopIteration', 'if', 'self.start_idx', '==', '0:', 'if', 'self.shuffle:', 'np.random.shuffle(self.indices)', 'obs', '=', 'self.observations[self._minibatch_indices]', 'if', 'self.load_images:', 'obs', '=', 'np.concatenate([s...
656,804
matsu0228/nlp-jp
connection.py
IAMConnection.get_response
get_response
Utility method to handle calls to IAM and parsing of responses.
[ "Utility", "method", "to", "handle", "calls", "to", "IAM", "and", "parsing", "of", "responses." ]
def get_response(self, action, params, path='/', parent=None, verb='POST', list_marker='Set'): if not parent: parent = self response = self.make_request(action, params, path, verb) body = response.read() boto.log.debug(body) if response.status == 200: if body: e = boto.js...
['def', 'get_response(self,', 'action,', 'params,', "path='/',", 'parent=None,', "verb='POST',", "list_marker='Set'):", 'if', 'not', 'parent:', 'parent', '=', 'self', 'response', '=', 'self.make_request(action,', 'params,', 'path,', 'verb)', 'body', '=', 'response.read()', 'boto.log.debug(body)', 'if', 'response.status...
784,724
tensorflow/data-validation
count_missing_generator.py
CountMissingGenerator.add_input
add_input
Accumulates the number of missing rows from new batch.
[ "Accumulates", "the", "number", "of", "missing", "rows", "from", "new", "batch." ]
def add_input(self, accumulator, batch: input_batch.InputBatch) -> int: null_mask = batch.null_mask(self._path) if self._required_paths: required_null_mask = batch.all_null_mask(*self._required_paths) null_mask = null_mask & ~required_null_mask return accumulator + np.sum(null_mask)
['def', 'add_input(self,', 'accumulator,', 'batch:', 'input_batch.InputBatch)', '->', 'int:', 'null_mask', '=', 'batch.null_mask(self._path)', 'if', 'self._required_paths:', 'required_null_mask', '=', 'batch.all_null_mask(*self._required_paths)', 'null_mask', '=', 'null_mask', '&', '~required_null_mask', 'return', 'acc...
497,570
devashish-patel/webcam-motion-detector
libpython.py
PyObjectPtr.pyop_field
pyop_field
Get a PyObjectPtr for the given PyObject* field within this PyObject, coping with some python 2 versus python 3 differences.
[ "Get", "a", "PyObjectPtr", "for", "the", "given", "PyObject*", "field", "within", "this", "PyObject,", "coping", "with", "some", "python", "2", "versus", "python", "3", "differences." ]
def pyop_field(self, name): return PyObjectPtr.from_pyobject_ptr(self.field(name))
['def', 'pyop_field(self,', 'name):', 'return', 'PyObjectPtr.from_pyobject_ptr(self.field(name))']
977,579
thuml/Transfer-Learning-Library
data.py
send_to_device
send_to_device
Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device.
[ "Recursively", "sends", "the", "elements", "in", "a", "nested", "list/tuple/dictionary", "of", "tensors", "to", "a", "given", "device." ]
def send_to_device(tensor, device): if isinstance(tensor, (list, tuple)): return type(tensor)((send_to_device(t, device) for t in tensor)) elif isinstance(tensor, dict): return type(tensor)({k: send_to_device(v, device) for (k, v) in tensor.items()}) elif not hasattr(tensor, 'to'): r...
['def', 'send_to_device(tensor,', 'device):', 'if', 'isinstance(tensor,', '(list,', 'tuple)):', 'return', 'type(tensor)((send_to_device(t,', 'device)', 'for', 't', 'in', 'tensor))', 'elif', 'isinstance(tensor,', 'dict):', 'return', 'type(tensor)({k:', 'send_to_device(v,', 'device)', 'for', '(k,', 'v)', 'in', 'tensor.it...
921,259
43Carrig/recurrent_neural_networks_practice
tensor_shape.py
Dimension.value
value
The value of this dimension, or None if it is unknown.
[ "The", "value", "of", "this", "dimension,", "or", "None", "if", "it", "is", "unknown." ]
def value(self): return self._value
['def', 'value(self):', 'return', 'self._value']
336,465
instadeepai/jumanji
random.py
make_random_policy_tsp
make_random_policy_tsp
Make random policy for TSP.
[ "Make", "random", "policy", "for", "TSP." ]
def make_random_policy_tsp() -> RandomPolicy: return masked_categorical_random
['def', 'make_random_policy_tsp()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random']
594,646
0x5eba/Anime-Character-Generator
utils_.py
get_random_label
get_random_label
Sample a batch of random class labels given the class priors.
[ "Sample", "a", "batch", "of", "random", "class", "labels", "given", "the", "class", "priors." ]
def get_random_label(batch_size, hair_classes, eye_classes): hair_code = torch.zeros(batch_size, hair_classes) eye_code = torch.zeros(batch_size, eye_classes) hair_type = np.random.choice(hair_classes, batch_size) eye_type = np.random.choice(eye_classes, batch_size) for i in range(batch_size): ...
['def', 'get_random_label(batch_size,', 'hair_classes,', 'eye_classes):', 'hair_code', '=', 'torch.zeros(batch_size,', 'hair_classes)', 'eye_code', '=', 'torch.zeros(batch_size,', 'eye_classes)', 'hair_type', '=', 'np.random.choice(hair_classes,', 'batch_size)', 'eye_type', '=', 'np.random.choice(eye_classes,', 'batch_...
416,292
calico/basenji
test_data2.py
TestData.test_output
test_output
Test that the output is generated.
[ "Test", "that", "the", "output", "is", "generated." ]
def test_output(self): for gi in range(2): train_tfrs = len(glob.glob('%s/tfrecords/train-%d-*.tfr' % (self.out_dir, gi))) self.assertGreater(train_tfrs, 0) valid_tfrs = len(glob.glob('%s/tfrecords/valid-%d-*.tfr' % (self.out_dir, gi))) self.assertGreater(valid_tfrs, 0) test_...
['def', 'test_output(self):', 'for', 'gi', 'in', 'range(2):', 'train_tfrs', '=', "len(glob.glob('%s/tfrecords/train-%d-*.tfr'", '%', '(self.out_dir,', 'gi)))', 'self.assertGreater(train_tfrs,', '0)', 'valid_tfrs', '=', "len(glob.glob('%s/tfrecords/valid-%d-*.tfr'", '%', '(self.out_dir,', 'gi)))', 'self.assertGreater(va...
94,904
Ruturaj123/Flowchart-Detection
control_flow_ops.py
WhileContext.back_prop
back_prop
True iff backprop is enabled for this while loop.
[ "True", "iff", "backprop", "is", "enabled", "for", "this", "while", "loop." ]
def back_prop(self): return self._back_prop
['def', 'back_prop(self):', 'return', 'self._back_prop']
605,808
QData/deepWordBug
math2html.py
FormulaFactory.skipany
skipany
Skip any skipped types.
[ "Skip", "any", "skipped", "types." ]
def skipany(self, pos): for type in self.skippedtypes: if self.instance(type).detect(pos): return self.parsetype(type, pos) return None
['def', 'skipany(self,', 'pos):', 'for', 'type', 'in', 'self.skippedtypes:', 'if', 'self.instance(type).detect(pos):', 'return', 'self.parsetype(type,', 'pos)', 'return', 'None']
542,496
enuguru/artificial_intelligence_and_machine_learning
templite.py
CodeBuilder.get_globals
get_globals
Execute the code, and return a dict of globals it defines.
[ "Execute", "the", "code,", "and", "return", "a", "dict", "of", "globals", "it", "defines." ]
def get_globals(self): assert self.indent_level == 0 python_source = str(self) global_namespace = {} exec(python_source, global_namespace) return global_namespace
['def', 'get_globals(self):', 'assert', 'self.indent_level', '==', '0', 'python_source', '=', 'str(self)', 'global_namespace', '=', '{}', 'exec(python_source,', 'global_namespace)', 'return', 'global_namespace']
147,957
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Entry.selection_clear
selection_clear
Clear the selection if it is in this widget.
[ "Clear", "the", "selection", "if", "it", "is", "in", "this", "widget." ]
def selection_clear(self): self.tk.call(self._w, 'selection', 'clear')
['def', 'selection_clear(self):', 'self.tk.call(self._w,', "'selection',", "'clear')"]
376,987
nicknochnack/RealTimeSignLanguageTFJS
mnist_test.py
KerasMnistTest.test_end_to_end
test_end_to_end
Test Keras MNIST model with `strategy`.
[ "Test", "Keras", "MNIST", "model", "with", "`strategy`." ]
def test_end_to_end(self, distribution): extra_flags = ['-train_epochs', '1', '--data_dir='] dummy_data = (tf.ones(shape=(10, 28, 28, 1), dtype=tf.int32), tf.range(10)) datasets = (tf.data.Dataset.from_tensor_slices(dummy_data), tf.data.Dataset.from_tensor_slices(dummy_data)) run = functools.partial(mni...
['def', 'test_end_to_end(self,', 'distribution):', 'extra_flags', '=', "['-train_epochs',", "'1',", "'--data_dir=']", 'dummy_data', '=', '(tf.ones(shape=(10,', '28,', '28,', '1),', 'dtype=tf.int32),', 'tf.range(10))', 'datasets', '=', '(tf.data.Dataset.from_tensor_slices(dummy_data),', 'tf.data.Dataset.from_tensor_slic...
851,192
matsu0228/nlp-jp
response.py
Response.request_id
request_id
The request id of this operation.
[ "The", "request", "id", "of", "this", "operation." ]
def request_id(self): return self._request_id
['def', 'request_id(self):', 'return', 'self._request_id']
805,008
Eric3911/OpenAGI
whipser.py
hann_window
hann_window
hanning window n_fft: The number of frequency components of the discrete Fourier transform.
[ "hanning", "window", "n_fft:", "The", "number", "of", "frequency", "components", "of", "the", "discrete", "Fourier", "transform." ]
def hann_window(n_fft: int=N_FFT): return paddle.to_tensor([0.5 - 0.5 * np.cos(2 * np.pi * n / n_fft) for n in range(n_fft)], dtype=paddle.float32)
['def', 'hann_window(n_fft:', 'int=N_FFT):', 'return', 'paddle.to_tensor([0.5', '-', '0.5', '*', 'np.cos(2', '*', 'np.pi', '*', 'n', '/', 'n_fft)', 'for', 'n', 'in', 'range(n_fft)],', 'dtype=paddle.float32)']
251,454
proycon/foliapy
main.py
AbstractElement.checkdeclaration
checkdeclaration
Internal method (usually no need to call this) that checks whether the element's annotation type is properly declared, raises an exception if not so, or auto-declares the annotation type if need be.
[ "Internal", "method", "(usually", "no", "need", "to", "call", "this)", "that", "checks", "whether", "the", "element's", "annotation", "type", "is", "properly", "declared,", "raises", "an", "exception", "if", "not", "so,", "or", "auto-declares", "the", "annotatio...
def checkdeclaration(self): annotationtype = self.ANNOTATIONTYPE if self.doc and annotationtype is not None: FOLIA2 = self.doc.FOLIA2 if not isinstance(self, (Text, Speech, AbstractCorrectionChild)): if annotationtype in self.doc.alias_set and self.set in self.doc.alias_set[annotatio...
['def', 'checkdeclaration(self):', 'annotationtype', '=', 'self.ANNOTATIONTYPE', 'if', 'self.doc', 'and', 'annotationtype', 'is', 'not', 'None:', 'FOLIA2', '=', 'self.doc.FOLIA2', 'if', 'not', 'isinstance(self,', '(Text,', 'Speech,', 'AbstractCorrectionChild)):', 'if', 'annotationtype', 'in', 'self.doc.alias_set', 'and...
608,377
rifqind/Agent-Programs-3KS1
utils.py
Notebook.cells
cells
Gets all cells once they are visible.
[ "Gets", "all", "cells", "once", "they", "are", "visible." ]
def cells(self): return self.browser.find_elements_by_class_name('cell')
['def', 'cells(self):', 'return', "self.browser.find_elements_by_class_name('cell')"]
43,334
marlbenchmark/off-policy
StarCraft2_Env.py
StarCraft2Env.get_total_actions
get_total_actions
Returns the total number of actions an agent could ever take.
[ "Returns", "the", "total", "number", "of", "actions", "an", "agent", "could", "ever", "take." ]
def get_total_actions(self): return self.n_actions
['def', 'get_total_actions(self):', 'return', 'self.n_actions']
755,473
OliverKillane/NuNet-Designer
NuNetLibrary.py
Output.getname
getname
getname returns the name of the output neuron (name of the label associated with that neuron).
[ "getname", "returns", "the", "name", "of", "the", "output", "neuron", "(name", "of", "the", "label", "associated", "with", "that", "neuron)." ]
def getname(self) -> str: return self._name
['def', 'getname(self)', '->', 'str:', 'return', 'self._name']
730,524
google/deepvariant
test_utils.py
cc_iterable_len
cc_iterable_len
Count the number of elements in an Iterable object.
[ "Count", "the", "number", "of", "elements", "in", "an", "Iterable", "object." ]
def cc_iterable_len(cc_iterable): count = 0 while True: (not_done, _) = cc_iterable.Next() if not not_done: break count += 1 return count
['def', 'cc_iterable_len(cc_iterable):', 'count', '=', '0', 'while', 'True:', '(not_done,', '_)', '=', 'cc_iterable.Next()', 'if', 'not', 'not_done:', 'break', 'count', '+=', '1', 'return', 'count']
540,628
gunthercox/ChatterBot
__init__.py
fib
fib
Returns the nth value in the Fibonacci sequence.
[ "Returns", "the", "nth", "value", "in", "the", "Fibonacci", "sequence." ]
def fib(n): if n <= 2: return n if n in _fib_cache: return _fib_cache[n] result = fib(n - 1) + fib(n - 2) _fib_cache[n] = result return result
['def', 'fib(n):', 'if', 'n', '<=', '2:', 'return', 'n', 'if', 'n', 'in', '_fib_cache:', 'return', '_fib_cache[n]', 'result', '=', 'fib(n', '-', '1)', '+', 'fib(n', '-', '2)', '_fib_cache[n]', '=', 'result', 'return', 'result']
484,837
sek788432/Waymo-2D-Object-Detection
center_net_meta_arch.py
row_col_channel_indices_from_flattened_indices
row_col_channel_indices_from_flattened_indices
Computes row, column and channel indices from flattened indices.
[ "Computes", "row,", "column", "and", "channel", "indices", "from", "flattened", "indices." ]
def row_col_channel_indices_from_flattened_indices(indices, num_cols, num_channels): row_indices = indices // num_channels // num_cols col_indices = indices // num_channels - row_indices * num_cols channel_indices_temp = indices // num_channels channel_indices = indices - channel_indices_temp * num_chan...
['def', 'row_col_channel_indices_from_flattened_indices(indices,', 'num_cols,', 'num_channels):', 'row_indices', '=', 'indices', '//', 'num_channels', '//', 'num_cols', 'col_indices', '=', 'indices', '//', 'num_channels', '-', 'row_indices', '*', 'num_cols', 'channel_indices_temp', '=', 'indices', '//', 'num_channels',...
974,999
pseudotensor/temporal_autoencoder
clstm.py
CRNNCell.set_zero_state
set_zero_state
Return zero-filled state tensor(s).
[ "Return", "zero-filled", "state", "tensor(s)." ]
def set_zero_state(self, batch_size, dtype): shape = self.shape features = self.features zeros = tf.zeros([batch_size, shape[0], shape[1], features * 2]) return zeros
['def', 'set_zero_state(self,', 'batch_size,', 'dtype):', 'shape', '=', 'self.shape', 'features', '=', 'self.features', 'zeros', '=', 'tf.zeros([batch_size,', 'shape[0],', 'shape[1],', 'features', '*', '2])', 'return', 'zeros']
908,083
DeepGraphLearning/torchdrug
protein.py
Protein.connected_component_id
connected_component_id
Connected component id of each residue.
[ "Connected", "component", "id", "of", "each", "residue." ]
def connected_component_id(self): (node_in, node_out) = self.edge_list.t()[:2] (residue_in, residue_out) = (self.atom2residue[node_in], self.atom2residue[node_out]) mask = residue_in != residue_out (residue_in, residue_out) = (residue_in[mask], residue_out[mask]) range = torch.arange(self.num_residu...
['def', 'connected_component_id(self):', '(node_in,', 'node_out)', '=', 'self.edge_list.t()[:2]', '(residue_in,', 'residue_out)', '=', '(self.atom2residue[node_in],', 'self.atom2residue[node_out])', 'mask', '=', 'residue_in', '!=', 'residue_out', '(residue_in,', 'residue_out)', '=', '(residue_in[mask],', 'residue_out[m...
902,773
aleju/computer-vision-algorithms
binary_dilation_erosion.py
closing
closing
Perform Closing on an image.
[ "Perform", "Closing", "on", "an", "image." ]
def closing(img): return dilation(erosion(img))
['def', 'closing(img):', 'return', 'dilation(erosion(img))']
467,532
sek788432/Waymo-2D-Object-Detection
center_net_meta_arch_tf2_test.py
CenterNetMetaArchTest.test_non_max_suppression
test_non_max_suppression
Tests application of NMS on CenterNet detections.
[ "Tests", "application", "of", "NMS", "on", "CenterNet", "detections." ]
def test_non_max_suppression(self): target_class_id = 1 model = build_center_net_meta_arch(apply_non_max_suppression=True, detection_only=True) class_center = np.zeros((1, 32, 32, 10), dtype=np.float32) height_width = np.zeros((1, 32, 32, 2), dtype=np.float32) offset = np.zeros((1, 32, 32, 2), dtype...
['def', 'test_non_max_suppression(self):', 'target_class_id', '=', '1', 'model', '=', 'build_center_net_meta_arch(apply_non_max_suppression=True,', 'detection_only=True)', 'class_center', '=', 'np.zeros((1,', '32,', '32,', '10),', 'dtype=np.float32)', 'height_width', '=', 'np.zeros((1,', '32,', '32,', '2),', 'dtype=np....
975,035
sktime/sktime
test_trend.py
test_trendforecaster_with_datetimeindex
test_trendforecaster_with_datetimeindex
Test PolyonmialTrendForecaster with DatetimeIndex, see #4131.
[ "Test", "PolyonmialTrendForecaster", "with", "DatetimeIndex,", "see", "#4131." ]
def test_trendforecaster_with_datetimeindex(): df = load_airline() df.index = df.index.to_timestamp() f = PolynomialTrendForecaster() f.fit(df) f = TrendForecaster() f.fit(df)
['def', 'test_trendforecaster_with_datetimeindex():', 'df', '=', 'load_airline()', 'df.index', '=', 'df.index.to_timestamp()', 'f', '=', 'PolynomialTrendForecaster()', 'f.fit(df)', 'f', '=', 'TrendForecaster()', 'f.fit(df)']
877,365
feidieufo/Carla-Reinforcement-Learning
sensor.py
PointCloud.save_to_disk
save_to_disk
Save this point-cloud to disk as PLY format.
[ "Save", "this", "point-cloud", "to", "disk", "as", "PLY", "format." ]
def save_to_disk(self, filename): filename = _append_extension(filename, '.ply') def construct_ply_header(): points = len(self) header = ['ply', 'format ascii 1.0', 'element vertex {}', 'property float32 x', 'property float32 y', 'property float32 z', 'property uchar diffuse_red', 'property uch...
['def', 'save_to_disk(self,', 'filename):', 'filename', '=', '_append_extension(filename,', "'.ply')", 'def', 'construct_ply_header():', 'points', '=', 'len(self)', 'header', '=', "['ply',", "'format", 'ascii', "1.0',", "'element", 'vertex', "{}',", "'property", 'float32', "x',", "'property", 'float32', "y',", "'proper...
455,864
ryu-ed/SpaceInvaders_Ros
math2html.py
BigBracket.getcontents
getcontents
Get the bracket as an array or as a single bracket.
[ "Get", "the", "bracket", "as", "an", "array", "or", "as", "a", "single", "bracket." ]
def getcontents(self): if self.size == 1 or not self.pieces: return self.getsinglebracket() rows = [] for index in range(self.size): cell = self.getcell(index) rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) return [TaggedBit().complete(rows, 'span class="array...
['def', 'getcontents(self):', 'if', 'self.size', '==', '1', 'or', 'not', 'self.pieces:', 'return', 'self.getsinglebracket()', 'rows', '=', '[]', 'for', 'index', 'in', 'range(self.size):', 'cell', '=', 'self.getcell(index)', 'rows.append(TaggedBit().complete([cell],', "'span", 'class="arrayrow"\'))', 'return', '[TaggedB...
395,315
Eric3911/OpenAGI
generate_lexicon.py
generate_lexicon
generate_lexicon
Generate lexicon for Mandarin Chinese.
[ "Generate", "lexicon", "for", "Mandarin", "Chinese." ]
def generate_lexicon(with_tone=False, with_erhua=False): syllables = OrderedDict() for C in [''] + INITIALS: for V in FINALS: for R in [''] if not with_erhua else ['', 'r']: for T in [''] if not with_tone else ['1', '2', '3', '4', '5']: result = rule(C, V,...
['def', 'generate_lexicon(with_tone=False,', 'with_erhua=False):', 'syllables', '=', 'OrderedDict()', 'for', 'C', 'in', "['']", '+', 'INITIALS:', 'for', 'V', 'in', 'FINALS:', 'for', 'R', 'in', "['']", 'if', 'not', 'with_erhua', 'else', "['',", "'r']:", 'for', 'T', 'in', "['']", 'if', 'not', 'with_tone', 'else', "['1',"...
251,692
weimin17/Object-Detection_HelmetDetection
gamma_mapper_test.py
ConvGammaMapperByConnectivityResnetTest.assertConvsConnectedToGammas
assertConvsConnectedToGammas
Asserts that each convolution is connected to each gamma.
[ "Asserts", "that", "each", "convolution", "is", "connected", "to", "each", "gamma." ]
def assertConvsConnectedToGammas(self, conv_names, gamma_prefixes, mapper): def make_set(item): return item if isinstance(item, set) else set([item]) convs = [get_op(conv_name) for conv_name in conv_names] gamma_sets = [make_set(mapper.get_gamma(conv)) for conv in convs] if len(gamma_sets) > 1:...
['def', 'assertConvsConnectedToGammas(self,', 'conv_names,', 'gamma_prefixes,', 'mapper):', 'def', 'make_set(item):', 'return', 'item', 'if', 'isinstance(item,', 'set)', 'else', 'set([item])', 'convs', '=', '[get_op(conv_name)', 'for', 'conv_name', 'in', 'conv_names]', 'gamma_sets', '=', '[make_set(mapper.get_gamma(con...
751,323
triaquae/triaquae
debug.py
get_safe_settings
get_safe_settings
Returns a dictionary of the settings module, with sensitive settings blurred out.
[ "Returns", "a", "dictionary", "of", "the", "settings", "module,", "with", "sensitive", "settings", "blurred", "out." ]
def get_safe_settings(): settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict
['def', 'get_safe_settings():', 'settings_dict', '=', '{}', 'for', 'k', 'in', 'dir(settings):', 'if', 'k.isupper():', 'settings_dict[k]', '=', 'cleanse_setting(k,', 'getattr(settings,', 'k))', 'return', 'settings_dict']
424,300
matsu0228/nlp-jp
ldaseqmodel.py
LdaPost.init_lda_post
init_lda_post
Initialize variational posterior, does not return anything.
[ "Initialize", "variational", "posterior,", "does", "not", "return", "anything." ]
def init_lda_post(self): total = sum((count for (word_id, count) in self.doc)) self.gamma.fill(self.lda.alpha[0] + float(total) / self.lda.num_topics) self.phi[:len(self.doc), :] = 1.0 / self.lda.num_topics
['def', 'init_lda_post(self):', 'total', '=', 'sum((count', 'for', '(word_id,', 'count)', 'in', 'self.doc))', 'self.gamma.fill(self.lda.alpha[0]', '+', 'float(total)', '/', 'self.lda.num_topics)', 'self.phi[:len(self.doc),', ':]', '=', '1.0', '/', 'self.lda.num_topics']
785,853
open-mmlab/mmrotate
delta_midpointoffset_rbbox_coder.py
MidpointOffsetCoder.decode
decode
Apply transformation `pred_bboxes` to `bboxes`.
[ "Apply", "transformation", "`pred_bboxes`", "to", "`bboxes`." ]
def decode(self, bboxes, pred_bboxes, max_shape=None, wh_ratio_clip=16 / 1000): assert pred_bboxes.size(0) == bboxes.size(0) assert bboxes.size(-1) == 4 assert pred_bboxes.size(-1) == 6 decoded_bboxes = delta2bbox(bboxes, pred_bboxes, self.means, self.stds, wh_ratio_clip, self.version) return decode...
['def', 'decode(self,', 'bboxes,', 'pred_bboxes,', 'max_shape=None,', 'wh_ratio_clip=16', '/', '1000):', 'assert', 'pred_bboxes.size(0)', '==', 'bboxes.size(0)', 'assert', 'bboxes.size(-1)', '==', '4', 'assert', 'pred_bboxes.size(-1)', '==', '6', 'decoded_bboxes', '=', 'delta2bbox(bboxes,', 'pred_bboxes,', 'self.means,...
625,036
43Carrig/recurrent_neural_networks_practice
rev_block_lib.py
enable_with_args
enable_with_args
A decorator for decorators to enable their usage with or without args.
[ "A", "decorator", "for", "decorators", "to", "enable", "their", "usage", "with", "or", "without", "args." ]
def enable_with_args(dec): @_safe_wraps(dec) def new_dec(*args, **kwargs): if len(args) == 1 and (not kwargs) and callable(args[0]): fn = args[0] return dec(fn) else: return lambda fn: dec(fn, *args, **kwargs) return new_dec
['def', 'enable_with_args(dec):', '@_safe_wraps(dec)', 'def', 'new_dec(*args,', '**kwargs):', 'if', 'len(args)', '==', '1', 'and', '(not', 'kwargs)', 'and', 'callable(args[0]):', 'fn', '=', 'args[0]', 'return', 'dec(fn)', 'else:', 'return', 'lambda', 'fn:', 'dec(fn,', '*args,', '**kwargs)', 'return', 'new_dec']
313,488
apeterswu/RL4NMT
text_encoder.py
ImageEncoder.decode
decode
Transform a sequence of int ids into an image file.
[ "Transform", "a", "sequence", "of", "int", "ids", "into", "an", "image", "file." ]
def decode(self, ids): (_, tmp_file_path) = tempfile.mkstemp() length = self._height * self._width * self._channels if len(ids) != length: raise ValueError('Length of ids (%d) must be height (%d) x width (%d) x channels (%d); %d != %d.\n Ids: %s' % (len(ids), self._height, self._width, self._channel...
['def', 'decode(self,', 'ids):', '(_,', 'tmp_file_path)', '=', 'tempfile.mkstemp()', 'length', '=', 'self._height', '*', 'self._width', '*', 'self._channels', 'if', 'len(ids)', '!=', 'length:', 'raise', "ValueError('Length", 'of', 'ids', '(%d)', 'must', 'be', 'height', '(%d)', 'x', 'width', '(%d)', 'x', 'channels', '(%...
331,420
suarez12138/AI-Reversi_IMP_TextDichotomy
install.py
install.has_headers
has_headers
Returns true if the current distribution has any headers to install.
[ "Returns", "true", "if", "the", "current", "distribution", "has", "any", "headers", "to", "install." ]
def has_headers(self): return self.distribution.has_headers()
['def', 'has_headers(self):', 'return', 'self.distribution.has_headers()']
100,771
weimin17/Object-Detection_HelmetDetection
seq2seq.py
generator
generator
Define the Generator graph.
[ "Define", "the", "Generator", "graph." ]
def generator(hparams, inputs, targets, targets_present, is_training, is_validating, reuse=None): with tf.variable_scope('gen', reuse=reuse): (encoder_states, initial_state, final_state) = gen_encoder(hparams, inputs, targets_present, is_training=is_training, reuse=reuse) (stacked_sequence, stacked_...
['def', 'generator(hparams,', 'inputs,', 'targets,', 'targets_present,', 'is_training,', 'is_validating,', 'reuse=None):', 'with', "tf.variable_scope('gen',", 'reuse=reuse):', '(encoder_states,', 'initial_state,', 'final_state)', '=', 'gen_encoder(hparams,', 'inputs,', 'targets_present,', 'is_training=is_training,', 'r...
757,982
bluemoon/nlp
dureader_eval.py
compute_prf
compute_prf
Compute precision recall and f1-score.
[ "Compute", "precision", "recall", "and", "f1-score." ]
def compute_prf(pred_dict, ref_dict): pred_question_ids = set(pred_dict.keys()) ref_question_ids = set(ref_dict.keys()) (correct_preds, total_correct, total_preds) = (0, 0, 0) for question_id in ref_question_ids: pred_entity_list = pred_dict.get(question_id, [[]]) assert len(pred_entity_...
['def', 'compute_prf(pred_dict,', 'ref_dict):', 'pred_question_ids', '=', 'set(pred_dict.keys())', 'ref_question_ids', '=', 'set(ref_dict.keys())', '(correct_preds,', 'total_correct,', 'total_preds)', '=', '(0,', '0,', '0)', 'for', 'question_id', 'in', 'ref_question_ids:', 'pred_entity_list', '=', 'pred_dict.get(questi...
808,809
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Base.altIdent
altIdent
Returns an alternate identifier for the one given.
[ "Returns", "an", "alternate", "identifier", "for", "the", "one", "given." ]
def altIdent(self, name): for klass in self.parents(lambda v: v.isClass): if name in klass.variables: try: method = self.parents(lambda v: v.isMethod).next() except (StopIteration,): return name if name in [p['name'] for p in method.paramet...
['def', 'altIdent(self,', 'name):', 'for', 'klass', 'in', 'self.parents(lambda', 'v:', 'v.isClass):', 'if', 'name', 'in', 'klass.variables:', 'try:', 'method', '=', 'self.parents(lambda', 'v:', 'v.isMethod).next()', 'except', '(StopIteration,):', 'return', 'name', 'if', 'name', 'in', "[p['name']", 'for', 'p', 'in', 'me...
10,741
lancopku/Graph-to-seq-comment-generation
tfidf_utils.py
gen_tf
gen_tf
Given a segmented string, return a dict of tf.
[ "Given", "a", "segmented", "string,", "return", "a", "dict", "of", "tf." ]
def gen_tf(text): tokens = text.split() total = len(tokens) tf_dict = {} for w in tokens: tf_dict[w] = tf_dict.get(w, 0.0) + 1.0 for k in tf_dict: tf_dict[k] /= total return tf_dict
['def', 'gen_tf(text):', 'tokens', '=', 'text.split()', 'total', '=', 'len(tokens)', 'tf_dict', '=', '{}', 'for', 'w', 'in', 'tokens:', 'tf_dict[w]', '=', 'tf_dict.get(w,', '0.0)', '+', '1.0', 'for', 'k', 'in', 'tf_dict:', 'tf_dict[k]', '/=', 'total', 'return', 'tf_dict']
580,407
salesforce/CodeRL
modeling_sew_d.py
SEWDForSequenceClassification.freeze_feature_extractor
freeze_feature_extractor
Calling this function will disable the gradient computation for the feature encoder so that its parameters will not be updated during training.
[ "Calling", "this", "function", "will", "disable", "the", "gradient", "computation", "for", "the", "feature", "encoder", "so", "that", "its", "parameters", "will", "not", "be", "updated", "during", "training." ]
def freeze_feature_extractor(self): warnings.warn('The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.Please use the equivalent `freeze_feature_encoder` method instead.', FutureWarning) self.freeze_feature_encoder()
['def', 'freeze_feature_extractor(self):', "warnings.warn('The", 'method', '`freeze_feature_extractor`', 'is', 'deprecated', 'and', 'will', 'be', 'removed', 'in', 'Transformers', 'v5.Please', 'use', 'the', 'equivalent', '`freeze_feature_encoder`', 'method', "instead.',", 'FutureWarning)', 'self.freeze_feature_encoder()...
495,146
muhanzhang/D-VAE
test_elemwise.py
T_mean_dtype.test_mean_custom_dtype
test_mean_custom_dtype
Test the ability to provide your own output dtype for a mean.
[ "Test", "the", "ability", "to", "provide", "your", "own", "output", "dtype", "for", "a", "mean." ]
def test_mean_custom_dtype(self): axes = [None, 0, 1, [], [0], [1], [0, 1]] idx = 0 for input_dtype in imap(str, theano.scalar.all_types): x = tensor.matrix(dtype=input_dtype) for sum_dtype in imap(str, theano.scalar.all_types): axis = axes[idx % len(axes)] try: ...
['def', 'test_mean_custom_dtype(self):', 'axes', '=', '[None,', '0,', '1,', '[],', '[0],', '[1],', '[0,', '1]]', 'idx', '=', '0', 'for', 'input_dtype', 'in', 'imap(str,', 'theano.scalar.all_types):', 'x', '=', 'tensor.matrix(dtype=input_dtype)', 'for', 'sum_dtype', 'in', 'imap(str,', 'theano.scalar.all_types):', 'axis'...
525,862
RL-MLDM/alphagen
memory.py
save_batch
save_batch
Save Batch to file.
[ "Save", "Batch", "to", "file." ]
def save_batch(B, save_path): with open(save_path, 'wb') as f: np.savez(f, **dict(B._asdict()))
['def', 'save_batch(B,', 'save_path):', 'with', 'open(save_path,', "'wb')", 'as', 'f:', 'np.savez(f,', '**dict(B._asdict()))']
414,779
materialsvirtuallab/mlearn
models.py
LinearModel.evaluate_fit
evaluate_fit
Efficient method to obtain prediction on training inputs w/o calculating the features of inputs again.
[ "Efficient", "method", "to", "obtain", "prediction", "on", "training", "inputs", "w/o", "calculating", "the", "features", "of", "inputs", "again." ]
def evaluate_fit(self): self._xtest = self._xtrain return self.predict(inputs=None, override=False)
['def', 'evaluate_fit(self):', 'self._xtest', '=', 'self._xtrain', 'return', 'self.predict(inputs=None,', 'override=False)']
630,282
robustness-gym/robustness-gym
testbench.py
TestBench.available
available
Check the list of available testbenches in a directory.
[ "Check", "the", "list", "of", "available", "testbenches", "in", "a", "directory." ]
def available(cls, path: str) -> List[str]: savedir = pathlib.Path(path) testbench_identifiers = [] for maybe_testbench in savedir.glob('*'): if maybe_testbench.is_dir() and (maybe_testbench / 'metadata.dill').exists(): testbench_identifiers.append(maybe_testbench.name) return testbe...
['def', 'available(cls,', 'path:', 'str)', '->', 'List[str]:', 'savedir', '=', 'pathlib.Path(path)', 'testbench_identifiers', '=', '[]', 'for', 'maybe_testbench', 'in', "savedir.glob('*'):", 'if', 'maybe_testbench.is_dir()', 'and', '(maybe_testbench', '/', "'metadata.dill').exists():", 'testbench_identifiers.append(may...
826,294
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
Base.accept
accept
Accept a node, possibly creating a child visitor.
[ "Accept", "a", "node,", "possibly", "creating", "a", "child", "visitor." ]
def accept(self, node, memo): tokType = tokens.map.get(node.token.type) missing = lambda node, memo: self call = getattr(self, 'accept{0}'.format(tokens.title(tokType)), missing) if call is missing: debug('no visitor accept method for %s', tokType) return call(node, memo)
['def', 'accept(self,', 'node,', 'memo):', 'tokType', '=', 'tokens.map.get(node.token.type)', 'missing', '=', 'lambda', 'node,', 'memo:', 'self', 'call', '=', 'getattr(self,', "'accept{0}'.format(tokens.title(tokType)),", 'missing)', 'if', 'call', 'is', 'missing:', "debug('no", 'visitor', 'accept', 'method', 'for', "%s...
17,306
brohrer/autoencoder_visualization
nn_viz_31.py
add_layer_connections
add_layer_connections
Add in the connectors between all the layers Treat the input image as the first layer and the output layer as the last.
[ "Add", "in", "the", "connectors", "between", "all", "the", "layers", "Treat", "the", "input", "image", "as", "the", "first", "layer", "and", "the", "output", "layer", "as", "the", "last." ]
def add_layer_connections(ax_boss, image_axes): for i_start_layer in range(len(image_axes) - 1): n_start_nodes = len(image_axes[i_start_layer]) n_end_nodes = len(image_axes[i_start_layer + 1]) x_start = image_axes[i_start_layer][0].get_position().x1 x_end = image_axes[i_start_layer +...
['def', 'add_layer_connections(ax_boss,', 'image_axes):', 'for', 'i_start_layer', 'in', 'range(len(image_axes)', '-', '1):', 'n_start_nodes', '=', 'len(image_axes[i_start_layer])', 'n_end_nodes', '=', 'len(image_axes[i_start_layer', '+', '1])', 'x_start', '=', 'image_axes[i_start_layer][0].get_position().x1', 'x_end', ...
419,909
google-research/rigl
sparse_utils.py
get_wrap_fn
get_wrap_fn
Creates a function that wraps a given layer conditionally.
[ "Creates", "a", "function", "that", "wraps", "a", "given", "layer", "conditionally." ]
def get_wrap_fn(mode): if mode == 'dense': wrap_fn = lambda x: x else: wrap_fn = functools.partial(maybe_prune_layer, params=get_pruning_params(mode)) return wrap_fn
['def', 'get_wrap_fn(mode):', 'if', 'mode', '==', "'dense':", 'wrap_fn', '=', 'lambda', 'x:', 'x', 'else:', 'wrap_fn', '=', 'functools.partial(maybe_prune_layer,', 'params=get_pruning_params(mode))', 'return', 'wrap_fn']
841,633
tensortrade-org/tensortrade
base.py
Stream.reset
reset
Resets all inputs to and listeners of the stream and sets stream value to None.
[ "Resets", "all", "inputs", "to", "and", "listeners", "of", "the", "stream", "and", "sets", "stream", "value", "to", "None." ]
def reset(self) -> None: for listener in self.listeners: if hasattr(listener, 'reset'): listener.reset() for stream in self.inputs: stream.reset() self.value = None
['def', 'reset(self)', '->', 'None:', 'for', 'listener', 'in', 'self.listeners:', 'if', 'hasattr(listener,', "'reset'):", 'listener.reset()', 'for', 'stream', 'in', 'self.inputs:', 'stream.reset()', 'self.value', '=', 'None']
366,524
Eric3911/OpenAGI
download.py
check_md5sum
check_md5sum
check md5sum of file.
[ "check", "md5sum", "of", "file." ]
def check_md5sum(filepath: Text, md5sum: Text) -> bool: return md5file(filepath) == md5sum
['def', 'check_md5sum(filepath:', 'Text,', 'md5sum:', 'Text)', '->', 'bool:', 'return', 'md5file(filepath)', '==', 'md5sum']
251,158
matsu0228/nlp-jp
backend_ps.py
RendererPS.option_scale_image
option_scale_image
ps backend support arbitrary scaling of image.
[ "ps", "backend", "support", "arbitrary", "scaling", "of", "image." ]
def option_scale_image(self): return True
['def', 'option_scale_image(self):', 'return', 'True']
789,668
rudranil723/mini-main
testing.py
pyparsing_test.TestParseResultsAsserts.assertParseResultsEquals
assertParseResultsEquals
Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, and compare any defined results names with an optional ``expected_dict``.
[ "Unit", "test", "assertion", "to", "compare", "a", ":class:`ParseResults`", "object", "with", "an", "optional", "``expected_list``,", "and", "compare", "any", "defined", "results", "names", "with", "an", "optional", "``expected_dict``." ]
def assertParseResultsEquals(self, result, expected_list=None, expected_dict=None, msg=None): if expected_list is not None: self.assertEqual(expected_list, result.as_list(), msg=msg) if expected_dict is not None: self.assertEqual(expected_dict, result.as_dict(), msg=msg)
['def', 'assertParseResultsEquals(self,', 'result,', 'expected_list=None,', 'expected_dict=None,', 'msg=None):', 'if', 'expected_list', 'is', 'not', 'None:', 'self.assertEqual(expected_list,', 'result.as_list(),', 'msg=msg)', 'if', 'expected_dict', 'is', 'not', 'None:', 'self.assertEqual(expected_dict,', 'result.as_dic...
269,649
weimin17/Object-Detection_HelmetDetection
selfplay_mcts.py
play
play
Plays out a self-play match.
[ "Plays", "out", "a", "self-play", "match." ]
def play(board_size, network, readouts, resign_threshold, simultaneous_leaves, verbosity=0): player = MCTSPlayer(board_size, network, resign_threshold=resign_threshold, verbosity=verbosity, num_parallel=simultaneous_leaves) if random.random() < 0.05: player.resign_threshold = -1.0 player.initialize_...
['def', 'play(board_size,', 'network,', 'readouts,', 'resign_threshold,', 'simultaneous_leaves,', 'verbosity=0):', 'player', '=', 'MCTSPlayer(board_size,', 'network,', 'resign_threshold=resign_threshold,', 'verbosity=verbosity,', 'num_parallel=simultaneous_leaves)', 'if', 'random.random()', '<', '0.05:', 'player.resign...
758,190
yihui-he/KL-Loss
ResNet.py
bottleneck_transformation
bottleneck_transformation
Add a bottleneck transformation to the model.
[ "Add", "a", "bottleneck", "transformation", "to", "the", "model." ]
def bottleneck_transformation(model, blob_in, dim_in, dim_out, stride, prefix, dim_inner, dilation=1, group=1): (str1x1, str3x3) = (stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride) cur = model.ConvAffine(blob_in, prefix + '_branch2a', dim_in, dim_inner, kernel=1, stride=str1x1, pad=0, inplace=True) cur...
['def', 'bottleneck_transformation(model,', 'blob_in,', 'dim_in,', 'dim_out,', 'stride,', 'prefix,', 'dim_inner,', 'dilation=1,', 'group=1):', '(str1x1,', 'str3x3)', '=', '(stride,', '1)', 'if', 'cfg.RESNETS.STRIDE_1X1', 'else', '(1,', 'stride)', 'cur', '=', 'model.ConvAffine(blob_in,', 'prefix', '+', "'_branch2a',", '...
596,555
tobegit3hub/deep_image_model
transform.py
assign_renamed_collections_handler
assign_renamed_collections_handler
Add the transformed elem to the (renamed) collections of elem.
[ "Add", "the", "transformed", "elem", "to", "the", "(renamed)", "collections", "of", "elem." ]
def assign_renamed_collections_handler(info, elem, elem_): for (name, collection) in iteritems(elem.graph._collections): if elem not in collection: continue collection_name_ = info.transformer.new_name(name) info.graph_.add_to_collection(collection_name_, elem_)
['def', 'assign_renamed_collections_handler(info,', 'elem,', 'elem_):', 'for', '(name,', 'collection)', 'in', 'iteritems(elem.graph._collections):', 'if', 'elem', 'not', 'in', 'collection:', 'continue', 'collection_name_', '=', 'info.transformer.new_name(name)', 'info.graph_.add_to_collection(collection_name_,', 'elem_...
181,390
sunishsheth2009/ChatterBot
test_mongo_adapter.py
MongoAdapterFilterTestCase.test_filter_no_parameters
test_filter_no_parameters
If no parameters are passed to the filter, then all statements should be returned.
[ "If", "no", "parameters", "are", "passed", "to", "the", "filter,", "then", "all", "statements", "should", "be", "returned." ]
def test_filter_no_parameters(self): self.adapter.create(text='Testing...') self.adapter.create(text='Testing one, two, three.') results = list(self.adapter.filter()) self.assertEqual(len(results), 2)
['def', 'test_filter_no_parameters(self):', "self.adapter.create(text='Testing...')", "self.adapter.create(text='Testing", 'one,', 'two,', "three.')", 'results', '=', 'list(self.adapter.filter())', 'self.assertEqual(len(results),', '2)']
485,954
nilearn/nilearn
test_multi_pca.py
test_multi_pca_errors
test_multi_pca_errors
Fit and transform fail without the proper arguments.
[ "Fit", "and", "transform", "fail", "without", "the", "proper", "arguments." ]
def test_multi_pca_errors(multi_pca_data, mask_img): multi_pca = _MultiPCA(mask=mask_img) with pytest.raises(TypeError, match='missing 1 required positional'): multi_pca.fit() with pytest.raises(ValueError, match='Object has no components_ attribute. This is probably because fit has not been called'...
['def', 'test_multi_pca_errors(multi_pca_data,', 'mask_img):', 'multi_pca', '=', '_MultiPCA(mask=mask_img)', 'with', 'pytest.raises(TypeError,', "match='missing", '1', 'required', "positional'):", 'multi_pca.fit()', 'with', 'pytest.raises(ValueError,', "match='Object", 'has', 'no', 'components_', 'attribute.', 'This', ...
723,749
mfbx9da4/neuron-astrocyte-networks
twoplayergame.py
TwoPlayerGame.isLegal
isLegal
is this a legal move? By default, everything is allowed.
[ "is", "this", "a", "legal", "move?", "By", "default,", "everything", "is", "allowed." ]
def isLegal(self, player, action): return True
['def', 'isLegal(self,', 'player,', 'action):', 'return', 'True']
723,128
isl-org/vision-for-action
pyhookv_utils.py
get_ray_cast_hit
get_ray_cast_hit
Must use my shitty fork of PyhookV.
[ "Must", "use", "my", "shitty", "fork", "of", "PyhookV." ]
def get_ray_cast_hit(u, v): a = u.get_coords(1) b = v.get_coords(1) hit_entity = h.Entity(0) h.Worldprobe.get_raycast_result(h.Worldprobe.cast_ray_point_to_point(a.x, a.y, a.z, b.x, b.y, b.z, -1, u, 7), 0, h.Vector3(0, 0, 0), h.Vector3(0, 0, 0), hit_entity) return hit_entity
['def', 'get_ray_cast_hit(u,', 'v):', 'a', '=', 'u.get_coords(1)', 'b', '=', 'v.get_coords(1)', 'hit_entity', '=', 'h.Entity(0)', 'h.Worldprobe.get_raycast_result(h.Worldprobe.cast_ray_point_to_point(a.x,', 'a.y,', 'a.z,', 'b.x,', 'b.y,', 'b.z,', '-1,', 'u,', '7),', '0,', 'h.Vector3(0,', '0,', '0),', 'h.Vector3(0,', '0...
955,746
Luodian/MADAN
adda_net.py
AddaNet.load_src_net
load_src_net
Initialize source and target with source weights.
[ "Initialize", "source", "and", "target", "with", "source", "weights." ]
def load_src_net(self, init_path): self.src_net.load(init_path) self.tgt_net.load(init_path)
['def', 'load_src_net(self,', 'init_path):', 'self.src_net.load(init_path)', 'self.tgt_net.load(init_path)']
626,879
tensorflow/privacy
common_test_utils.py
reshape_and_sum
reshape_and_sum
Reshapes and sums along non-batch dims to get the shape [None, 1].
[ "Reshapes", "and", "sums", "along", "non-batch", "dims", "to", "get", "the", "shape", "[None,", "1]." ]
def reshape_and_sum(tensor: tf.Tensor) -> tf.Tensor: reshaped_2d = tf.reshape(tensor, [tf.shape(tensor)[0], -1]) return tf.reduce_sum(reshaped_2d, axis=-1, keepdims=True)
['def', 'reshape_and_sum(tensor:', 'tf.Tensor)', '->', 'tf.Tensor:', 'reshaped_2d', '=', 'tf.reshape(tensor,', '[tf.shape(tensor)[0],', '-1])', 'return', 'tf.reduce_sum(reshaped_2d,', 'axis=-1,', 'keepdims=True)']
824,773
jxhe/unify-parameter-efficient-tuning
tokenization_tapas.py
TapasTokenizer.create_segment_token_type_ids_from_sequences
create_segment_token_type_ids_from_sequences
Creates the segment token type IDs according to the query token IDs and a list of table values.
[ "Creates", "the", "segment", "token", "type", "IDs", "according", "to", "the", "query", "token", "IDs", "and", "a", "list", "of", "table", "values." ]
def create_segment_token_type_ids_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]: table_ids = list(zip(*table_values))[0] if table_values else [] return [0] * (1 + len(query_ids) + 1) + [1] * len(table_ids)
['def', 'create_segment_token_type_ids_from_sequences(self,', 'query_ids:', 'List[int],', 'table_values:', 'List[TableValue])', '->', 'List[int]:', 'table_ids', '=', 'list(zip(*table_values))[0]', 'if', 'table_values', 'else', '[]', 'return', '[0]', '*', '(1', '+', 'len(query_ids)', '+', '1)', '+', '[1]', '*', 'len(tab...
949,290
tomcatmanager/tomcatmanager
mock_server_ssl.py
MockRequestHandlerSSL.send_text
send_text
Send a status ok and content as text/html.
[ "Send", "a", "status", "ok", "and", "content", "as", "text/html." ]
def send_text(self, content): self.send_response(requests.codes.ok) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(content.encode('utf-8'))
['def', 'send_text(self,', 'content):', 'self.send_response(requests.codes.ok)', "self.send_header('Content-type',", "'text/html')", 'self.end_headers()', "self.wfile.write(content.encode('utf-8'))"]
355,659
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.hfield_ncol
hfield_ncol
number of columns in grid (nhfield x 1).
[ "number", "of", "columns", "in", "grid", "(nhfield", "x", "1)." ]
def hfield_ncol(self): return util.buf_to_npy(self._ptr.contents.hfield_ncol, (self.nhfield,))
['def', 'hfield_ncol(self):', 'return', 'util.buf_to_npy(self._ptr.contents.hfield_ncol,', '(self.nhfield,))']
440,375
tensorflow/agents
common.py
extract_shared_variables
extract_shared_variables
Separates shared variables from the given collections.
[ "Separates", "shared", "variables", "from", "the", "given", "collections." ]
def extract_shared_variables(variables_1, variables_2): var_refs1 = object_identity.ObjectIdentitySet(variables_1) var_refs2 = object_identity.ObjectIdentitySet(variables_2) shared_vars = var_refs1.intersection(var_refs2) return (var_refs1.difference(shared_vars), var_refs2.difference(shared_vars), shar...
['def', 'extract_shared_variables(variables_1,', 'variables_2):', 'var_refs1', '=', 'object_identity.ObjectIdentitySet(variables_1)', 'var_refs2', '=', 'object_identity.ObjectIdentitySet(variables_2)', 'shared_vars', '=', 'var_refs1.intersection(var_refs2)', 'return', '(var_refs1.difference(shared_vars),', 'var_refs2.d...
23,075
emadeldeen24/eval_ssl_ssc
algorithms.py
get_algorithm_class
get_algorithm_class
Return the algorithm class with the given name.
[ "Return", "the", "algorithm", "class", "with", "the", "given", "name." ]
def get_algorithm_class(algorithm_name): if algorithm_name not in globals(): raise NotImplementedError('Algorithm not found: {}'.format(algorithm_name)) return globals()[algorithm_name]
['def', 'get_algorithm_class(algorithm_name):', 'if', 'algorithm_name', 'not', 'in', 'globals():', 'raise', "NotImplementedError('Algorithm", 'not', 'found:', "{}'.format(algorithm_name))", 'return', 'globals()[algorithm_name]']
178,359
tobegit3hub/deep_image_model
debug_data.py
DebugDumpDir.node_inputs
node_inputs
Get the inputs of given node according to partition graphs.
[ "Get", "the", "inputs", "of", "given", "node", "according", "to", "partition", "graphs." ]
def node_inputs(self, node_name, is_control=False): if self._node_inputs is None or self._node_ctrl_inputs is None: raise RuntimeError('Node inputs are not loaded from partition graphs yet.') if node_name not in self._node_inputs: raise ValueError("Node '%s' does not exist in partition graphs." ...
['def', 'node_inputs(self,', 'node_name,', 'is_control=False):', 'if', 'self._node_inputs', 'is', 'None', 'or', 'self._node_ctrl_inputs', 'is', 'None:', 'raise', "RuntimeError('Node", 'inputs', 'are', 'not', 'loaded', 'from', 'partition', 'graphs', "yet.')", 'if', 'node_name', 'not', 'in', 'self._node_inputs:', 'raise'...
182,322
lebrice/Sequoia
episode_limit_test.py
test_episode_limit_with_vectorized_env
test_episode_limit_with_vectorized_env
Test that when adding the EpisodeLimit wrapper on top of a vectorized environment, the episode limit is with respect to each individual env rather than the batched env.
[ "Test", "that", "when", "adding", "the", "EpisodeLimit", "wrapper", "on", "top", "of", "a", "vectorized", "environment,", "the", "episode", "limit", "is", "with", "respect", "to", "each", "individual", "env", "rather", "than", "the", "batched", "env." ]
def test_episode_limit_with_vectorized_env(batch_size): starting_values = [0 for i in range(batch_size)] targets = [10 for i in range(batch_size)] env = SyncVectorEnv([partial(DummyEnvironment, start=start, target=target, max_value=10 * 2) for (start, target) in zip(starting_values, targets)]) env = Epi...
['def', 'test_episode_limit_with_vectorized_env(batch_size):', 'starting_values', '=', '[0', 'for', 'i', 'in', 'range(batch_size)]', 'targets', '=', '[10', 'for', 'i', 'in', 'range(batch_size)]', 'env', '=', 'SyncVectorEnv([partial(DummyEnvironment,', 'start=start,', 'target=target,', 'max_value=10', '*', '2)', 'for', ...
344,146
openvinotoolkit/training_extensions
movinet.py
OTXMoViNet.fill_se_config
fill_se_config
Set the values of a given Config object to SE module.
[ "Set", "the", "values", "of", "a", "given", "Config", "object", "to", "SE", "module." ]
def fill_se_config(conf, input_channels, out_channels, expanded_channels, kernel_size, stride, padding, padding_avg): conf.expanded_channels = expanded_channels conf.padding_avg = padding_avg OTXMoViNet.fill_conv(conf, input_channels, out_channels, kernel_size, stride, padding)
['def', 'fill_se_config(conf,', 'input_channels,', 'out_channels,', 'expanded_channels,', 'kernel_size,', 'stride,', 'padding,', 'padding_avg):', 'conf.expanded_channels', '=', 'expanded_channels', 'conf.padding_avg', '=', 'padding_avg', 'OTXMoViNet.fill_conv(conf,', 'input_channels,', 'out_channels,', 'kernel_size,', ...
903,864
tensorflow/agents
shifted_categorical_test.py
ShiftedCategoricalTest.testCopy
testCopy
Confirm we can copy the distribution.
[ "Confirm", "we", "can", "copy", "the", "distribution." ]
def testCopy(self): distribution = shifted_categorical.ShiftedCategorical(logits=[100.0, 100.0, 100.0], shift=2) copy = distribution.copy() with self.cached_session() as s: probs_np = s.run(copy.probs_parameter()) logits_np = s.run(copy.logits_parameter()) ref_probs_np = s.run(distri...
['def', 'testCopy(self):', 'distribution', '=', 'shifted_categorical.ShiftedCategorical(logits=[100.0,', '100.0,', '100.0],', 'shift=2)', 'copy', '=', 'distribution.copy()', 'with', 'self.cached_session()', 'as', 's:', 'probs_np', '=', 's.run(copy.probs_parameter())', 'logits_np', '=', 's.run(copy.logits_parameter())',...
23,382
rudranil723/mini-main
credentials.py
UserAccessTokenCredentials.with_account
with_account
Create a new instance with the given account.
[ "Create", "a", "new", "instance", "with", "the", "given", "account." ]
def with_account(self, account): return self.__class__(account=account, quota_project_id=self._quota_project_id)
['def', 'with_account(self,', 'account):', 'return', 'self.__class__(account=account,', 'quota_project_id=self._quota_project_id)']
318,202
sarnsdev/social-alignment-data-mining
test_decomp.py
eigenhproblem_standard
eigenhproblem_standard
Solve a standard eigenvalue problem.
[ "Solve", "a", "standard", "eigenvalue", "problem." ]
def eigenhproblem_standard(desc, dim, dtype, overwrite, lower, turbo, eigenvalues): if iscomplex(empty(1, dtype=dtype)): a = _complex_symrand(dim, dtype) else: a = symrand(dim).astype(dtype) if overwrite: a_c = a.copy() else: a_c = a (w, z) = eigh(a, overwrite_a=overw...
['def', 'eigenhproblem_standard(desc,', 'dim,', 'dtype,', 'overwrite,', 'lower,', 'turbo,', 'eigenvalues):', 'if', 'iscomplex(empty(1,', 'dtype=dtype)):', 'a', '=', '_complex_symrand(dim,', 'dtype)', 'else:', 'a', '=', 'symrand(dim).astype(dtype)', 'if', 'overwrite:', 'a_c', '=', 'a.copy()', 'else:', 'a_c', '=', 'a', '...
390,848
PacktPublishing/Hands-On-Artificial--for-Banking
datetimelike.py
DatetimeIndexOpsMixin.sort_values
sort_values
Return sorted copy of Index.
[ "Return", "sorted", "copy", "of", "Index." ]
def sort_values(self, return_indexer=False, ascending=True, key=None): idx = ensure_key_mapped(self, key) _as = idx.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) if return_indexer: return (sorted_index, _as) else: return sorted_index
['def', 'sort_values(self,', 'return_indexer=False,', 'ascending=True,', 'key=None):', 'idx', '=', 'ensure_key_mapped(self,', 'key)', '_as', '=', 'idx.argsort()', 'if', 'not', 'ascending:', '_as', '=', '_as[::-1]', 'sorted_index', '=', 'self.take(_as)', 'if', 'return_indexer:', 'return', '(sorted_index,', '_as)', 'else...
236,651
arpit196/Meta-Unsupervised-Representations-for-Prototypical-
omniglot.py
get_class_images_paths
get_class_images_paths
Return class names, paths to the corresponding images and rotations from the path of the classes' directories.
[ "Return", "class", "names,", "paths", "to", "the", "corresponding", "images", "and", "rotations", "from", "the", "path", "of", "the", "classes'", "directories." ]
def get_class_images_paths(dir_paths, rotates): (classes, img_paths, rotates_list) = ([], [], []) for (dir_path, rotate) in zip(dir_paths, rotates): class_images = sorted(glob.glob(os.path.join(dir_path, '*.png'))) classes.append(dir_path) img_paths.append(class_images) rotates_l...
['def', 'get_class_images_paths(dir_paths,', 'rotates):', '(classes,', 'img_paths,', 'rotates_list)', '=', '([],', '[],', '[])', 'for', '(dir_path,', 'rotate)', 'in', 'zip(dir_paths,', 'rotates):', 'class_images', '=', 'sorted(glob.glob(os.path.join(dir_path,', "'*.png')))", 'classes.append(dir_path)', 'img_paths.appen...
286,068
RasaHQ/rasa
mitie_featurizer.py
MitieFeaturizer.ndim
ndim
Returns the number of dimensions.
[ "Returns", "the", "number", "of", "dimensions." ]
def ndim(self, feature_extractor: 'mitie.total_word_feature_extractor') -> int: return feature_extractor.num_dimensions
['def', 'ndim(self,', 'feature_extractor:', "'mitie.total_word_feature_extractor')", '->', 'int:', 'return', 'feature_extractor.num_dimensions']
837,260
AEProgrammer/object_detection
dataset.py
prepare_train_coco_data
prepare_train_coco_data
Prepare relevant COCO data for training the model.
[ "Prepare", "relevant", "COCO", "data", "for", "training", "the", "model." ]
def prepare_train_coco_data(args): (image_dir, annotation_file, data_dir) = (args.train_coco_image_dir, args.train_coco_annotation_file, args.train_coco_data_dir) batch_size = args.batch_size basic_model = args.basic_model num_roi = args.num_roi coco = COCO(annotation_file) img_ids = list(coco.i...
['def', 'prepare_train_coco_data(args):', '(image_dir,', 'annotation_file,', 'data_dir)', '=', '(args.train_coco_image_dir,', 'args.train_coco_annotation_file,', 'args.train_coco_data_dir)', 'batch_size', '=', 'args.batch_size', 'basic_model', '=', 'args.basic_model', 'num_roi', '=', 'args.num_roi', 'coco', '=', 'COCO(...
745,000
google-research/scenic
model_utils.py
init_posemb
init_posemb
Initialize the positional embeddings.
[ "Initialize", "the", "positional", "embeddings." ]
def init_posemb(to_params, from_params, init_config, model_config, dataset_config, restored_model_cfg, name, prefix_path=None): if name not in to_params: logging.info('No %s in target model', name) elif init_config.restore_positional_embedding: if name == 'bottleneck': posemb = to_pa...
['def', 'init_posemb(to_params,', 'from_params,', 'init_config,', 'model_config,', 'dataset_config,', 'restored_model_cfg,', 'name,', 'prefix_path=None):', 'if', 'name', 'not', 'in', 'to_params:', "logging.info('No", '%s', 'in', 'target', "model',", 'name)', 'elif', 'init_config.restore_positional_embedding:', 'if', 'n...
847,033
enuguru/artificial_intelligence_and_machine_
mcore.py
Matcher.matching_terms
matching_terms
Returns an iterator of ``("fieldname", "termtext")`` tuples for the **currently matching** term matchers in this tree.
[ "Returns", "an", "iterator", "of", "``(\"fieldname\",", "\"termtext\")``", "tuples", "for", "the", "**currently", "matching**", "term", "matchers", "in", "this", "tree." ]
def matching_terms(self, id=None): if not self.is_active(): return if id is None: id = self.id() elif id != self.id(): return t = self.term() if t is None: for c in self.children(): for t in c.matching_terms(id): yield t else: y...
['def', 'matching_terms(self,', 'id=None):', 'if', 'not', 'self.is_active():', 'return', 'if', 'id', 'is', 'None:', 'id', '=', 'self.id()', 'elif', 'id', '!=', 'self.id():', 'return', 't', '=', 'self.term()', 'if', 't', 'is', 'None:', 'for', 'c', 'in', 'self.children():', 'for', 't', 'in', 'c.matching_terms(id):', 'yie...
162,594
galina0217/robustgraph
attack_steps.py
AttackerStep.to_image
to_image
Given an input (which may be in an alternative parameterization), convert it to a valid image (this is implemented as the identity function by default as most of the time we use the pixel parameterization, but for alternative parameterizations this functino must be overriden).
[ "Given", "an", "input", "(which", "may", "be", "in", "an", "alternative", "parameterization),", "convert", "it", "to", "a", "valid", "image", "(this", "is", "implemented", "as", "the", "identity", "function", "by", "default", "as", "most", "of", "the", "time...
def to_image(self, delta_A, show=False): delta_A = delta_A.detach().cpu().numpy() while 1: randm = np.random.uniform(size=(self.nb_nodes, self.nb_nodes)) ret = np.where(delta_A > randm, 1, 0) if show: b = np.triu(ret, 1).sum() print('b/eps: {}/{}'.format(b, self.e...
['def', 'to_image(self,', 'delta_A,', 'show=False):', 'delta_A', '=', 'delta_A.detach().cpu().numpy()', 'while', '1:', 'randm', '=', 'np.random.uniform(size=(self.nb_nodes,', 'self.nb_nodes))', 'ret', '=', 'np.where(delta_A', '>', 'randm,', '1,', '0)', 'if', 'show:', 'b', '=', 'np.triu(ret,', '1).sum()', "print('b/eps:...
326,089
sek788432/Waymo-2D-Object-Detection
preprocess_ops.py
random_blur
random_blur
Randomly blur an image.
[ "Randomly", "blur", "an", "image." ]
def random_blur(image, height, width, p=0.5): del width def _transform(image): sigma = tf.random.uniform([], 0.1, 2.0, dtype=tf.float32) return gaussian_blur(image, kernel_size=height // 10, sigma=sigma, padding='SAME') return random_apply(_transform, p=p, x=image)
['def', 'random_blur(image,', 'height,', 'width,', 'p=0.5):', 'del', 'width', 'def', '_transform(image):', 'sigma', '=', 'tf.random.uniform([],', '0.1,', '2.0,', 'dtype=tf.float32)', 'return', 'gaussian_blur(image,', 'kernel_size=height', '//', '10,', 'sigma=sigma,', "padding='SAME')", 'return', 'random_apply(_transfor...
973,374