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 |
|---|---|---|---|---|---|---|---|---|
nicknochnack/RealTimeSignLanguageTFJS | keras_utils.py | TimeHistory.get_examples_per_sec | get_examples_per_sec | Calculates examples/sec through timestamp_log and skip warmup period. | [
"Calculates",
"examples/sec",
"through",
"timestamp_log",
"and",
"skip",
"warmup",
"period."
] | def get_examples_per_sec(self, warmup=1):
time_log = self.timestamp_log
seconds = time_log[-1].timestamp - time_log[warmup].timestamp
steps = time_log[-1].batch_index - time_log[warmup].batch_index
return self.batch_size * steps / seconds | ['def', 'get_examples_per_sec(self,', 'warmup=1):', 'time_log', '=', 'self.timestamp_log', 'seconds', '=', 'time_log[-1].timestamp', '-', 'time_log[warmup].timestamp', 'steps', '=', 'time_log[-1].batch_index', '-', 'time_log[warmup].batch_index', 'return', 'self.batch_size', '*', 'steps', '/', 'seconds'] | 850,729 |
enuguru/artificial_intelligence_and_machine_ | _compat.py | normalize_string_tuple | normalize_string_tuple | Ensures that all types in the tuple are either strings or bytes. | [
"Ensures",
"that",
"all",
"types",
"in",
"the",
"tuple",
"are",
"either",
"strings",
"or",
"bytes."
] | def normalize_string_tuple(tup):
tupiter = iter(tup)
is_text = isinstance(next(tupiter, None), text_type)
for arg in tupiter:
if isinstance(arg, text_type) != is_text:
raise TypeError('Cannot mix str and bytes arguments (got %s)' % repr(tup))
return tup | ['def', 'normalize_string_tuple(tup):', 'tupiter', '=', 'iter(tup)', 'is_text', '=', 'isinstance(next(tupiter,', 'None),', 'text_type)', 'for', 'arg', 'in', 'tupiter:', 'if', 'isinstance(arg,', 'text_type)', '!=', 'is_text:', 'raise', "TypeError('Cannot", 'mix', 'str', 'and', 'bytes', 'arguments', '(got', "%s)'", '%', ... | 161,752 |
hamza-murad/AALU | natural_language_understanding_v1.py | Feed.from_dict | from_dict | Initialize a Feed object from a json dictionary. | [
"Initialize",
"a",
"Feed",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'Feed':
args = {}
valid_keys = ['link']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class Feed: ' + ', '.join(bad_keys))
if 'link' in _dict:
args['link'] = _dict.get('lin... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'Feed':", 'args', '=', '{}', 'valid_keys', '=', "['link']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Feed:', "'", '+', "',", "'.join(b... | 5,937 |
weimin17/Object-Detection_HelmetDetection | cifar10_main.py | run_cifar | run_cifar | Run ResNet CIFAR-10 training and eval loop. | [
"Run",
"ResNet",
"CIFAR-10",
"training",
"and",
"eval",
"loop."
] | def run_cifar(flags_obj):
input_function = flags_obj.use_synthetic_data and get_synth_input_fn() or input_fn
resnet_run_loop.resnet_main(flags_obj, cifar10_model_fn, input_function, DATASET_NAME, shape=[_HEIGHT, _WIDTH, _NUM_CHANNELS]) | ['def', 'run_cifar(flags_obj):', 'input_function', '=', 'flags_obj.use_synthetic_data', 'and', 'get_synth_input_fn()', 'or', 'input_fn', 'resnet_run_loop.resnet_main(flags_obj,', 'cifar10_model_fn,', 'input_function,', 'DATASET_NAME,', 'shape=[_HEIGHT,', '_WIDTH,', '_NUM_CHANNELS])'] | 748,625 |
songyanho/Reinforcement-Learning-for-Self-Driving-Cars | road.py | AdvancedRoad.blit_mask | blit_mask | Blit an source image to the dest surface, at destpos, with a mask, using only the maskrect part of the mask. | [
"Blit",
"an",
"source",
"image",
"to",
"the",
"dest",
"surface,",
"at",
"destpos,",
"with",
"a",
"mask,",
"using",
"only",
"the",
"maskrect",
"part",
"of",
"the",
"mask."
] | def blit_mask(source, dest, destpos, mask, maskrect):
tmp = source.copy()
tmp.blit(mask, maskrect.topleft, maskrect, special_flags=pygame.BLEND_RGBA_MULT)
dest.blit(tmp, destpos, dest.get_rect().clip(maskrect)) | ['def', 'blit_mask(source,', 'dest,', 'destpos,', 'mask,', 'maskrect):', 'tmp', '=', 'source.copy()', 'tmp.blit(mask,', 'maskrect.topleft,', 'maskrect,', 'special_flags=pygame.BLEND_RGBA_MULT)', 'dest.blit(tmp,', 'destpos,', 'dest.get_rect().clip(maskrect))'] | 340,768 |
ryu-ed/SpaceInvaders_Ros | __init__.py | cache_py2_modules | cache_py2_modules | Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle. | [
"Currently",
"this",
"function",
"is",
"unneeded,",
"as",
"we",
"are",
"not",
"attempting",
"to",
"provide",
"import",
"hooks",
"for",
"modules",
"with",
"ambiguous",
"names:",
"email,",
"urllib,",
"pickle."
] | def cache_py2_modules():
if len(sys.py2_modules) != 0:
return
assert not detect_hooks()
import urllib
sys.py2_modules['urllib'] = urllib
import email
sys.py2_modules['email'] = email
import pickle
sys.py2_modules['pickle'] = pickle | ['def', 'cache_py2_modules():', 'if', 'len(sys.py2_modules)', '!=', '0:', 'return', 'assert', 'not', 'detect_hooks()', 'import', 'urllib', "sys.py2_modules['urllib']", '=', 'urllib', 'import', 'email', "sys.py2_modules['email']", '=', 'email', 'import', 'pickle', "sys.py2_modules['pickle']", '=', 'pickle'] | 395,997 |
zihuitang/medical_AI_platform | test_posix.py | PosixTester.test_path_error2 | test_path_error2 | Test functions that call path_error2(), providing two filenames in their exceptions. | [
"Test",
"functions",
"that",
"call",
"path_error2(),",
"providing",
"two",
"filenames",
"in",
"their",
"exceptions."
] | def test_path_error2(self):
for name in ('rename', 'replace', 'link'):
function = getattr(os, name, None)
if function is None:
continue
for dst in ('noodly2', support.TESTFN):
try:
function('doesnotexistfilename', dst)
except OSError as e:
... | ['def', 'test_path_error2(self):', 'for', 'name', 'in', "('rename',", "'replace',", "'link'):", 'function', '=', 'getattr(os,', 'name,', 'None)', 'if', 'function', 'is', 'None:', 'continue', 'for', 'dst', 'in', "('noodly2',", 'support.TESTFN):', 'try:', "function('doesnotexistfilename',", 'dst)', 'except', 'OSError', '... | 283,523 |
ThomasBrouwer/HMF | updates_Gibbs.py | row_precision_S | row_precision_S | Return the value for Precision for the Gibbs posterior, for row draws. | [
"Return",
"the",
"value",
"for",
"Precision",
"for",
"the",
"Gibbs",
"posterior,",
"for",
"row",
"draws."
] | def row_precision_S(dataset, mask, tau, alpha, F, S, G, lambdaSk, k, nonnegative):
(I, J) = mask.shape
precision_S = numpy.zeros((len(lambdaSk), len(lambdaSk))) if nonnegative else numpy.diag(lambdaSk)
G_outer_masked = numpy.array([numpy.dot(mask[i] * G.T, (mask[i] * G.T).T) for i in range(0, I)])
preci... | ['def', 'row_precision_S(dataset,', 'mask,', 'tau,', 'alpha,', 'F,', 'S,', 'G,', 'lambdaSk,', 'k,', 'nonnegative):', '(I,', 'J)', '=', 'mask.shape', 'precision_S', '=', 'numpy.zeros((len(lambdaSk),', 'len(lambdaSk)))', 'if', 'nonnegative', 'else', 'numpy.diag(lambdaSk)', 'G_outer_masked', '=', 'numpy.array([numpy.dot(m... | 206,707 |
vturrisi/solo-learn | vibcreg.py | vibcreg_loss_func | vibcreg_loss_func | Computes VIbCReg's loss given batch of projected features z1 from view 1 and projected features z2 from view 2. | [
"Computes",
"VIbCReg's",
"loss",
"given",
"batch",
"of",
"projected",
"features",
"z1",
"from",
"view",
"1",
"and",
"projected",
"features",
"z2",
"from",
"view",
"2."
] | def vibcreg_loss_func(z1: torch.Tensor, z2: torch.Tensor, sim_loss_weight: float=25.0, var_loss_weight: float=25.0, cov_loss_weight: float=200.0) -> torch.Tensor:
sim_loss = invariance_loss(z1, z2)
(z1, z2) = (gather(z1), gather(z2))
var_loss = variance_loss(z1, z2)
cov_loss = covariance_loss(z1, z2)
... | ['def', 'vibcreg_loss_func(z1:', 'torch.Tensor,', 'z2:', 'torch.Tensor,', 'sim_loss_weight:', 'float=25.0,', 'var_loss_weight:', 'float=25.0,', 'cov_loss_weight:', 'float=200.0)', '->', 'torch.Tensor:', 'sim_loss', '=', 'invariance_loss(z1,', 'z2)', '(z1,', 'z2)', '=', '(gather(z1),', 'gather(z2))', 'var_loss', '=', 'v... | 393,572 |
bradfitz/scanningcabinet | model.py | MigratingBlobReferenceProperty.make_value_from_datastore | make_value_from_datastore | Translate datastore value to BlobInfo. | [
"Translate",
"datastore",
"value",
"to",
"BlobInfo."
] | def make_value_from_datastore(self, value):
if value is None:
return None
if isinstance(value, basestring):
value = blobstore.BlobKey(value)
return blobstore.BlobInfo(value) | ['def', 'make_value_from_datastore(self,', 'value):', 'if', 'value', 'is', 'None:', 'return', 'None', 'if', 'isinstance(value,', 'basestring):', 'value', '=', 'blobstore.BlobKey(value)', 'return', 'blobstore.BlobInfo(value)'] | 329,429 |
gunthercox/ChatterBot | atom.py | AtomFeed.generate | generate | Return a generator that yields pieces of XML. | [
"Return",
"a",
"generator",
"that",
"yields",
"pieces",
"of",
"XML."
] | def generate(self):
if not self.author:
if False in map(lambda e: bool(e.author), self.entries):
self.author = ({'name': 'Unknown author'},)
if not self.updated:
dates = sorted([entry.updated for entry in self.entries])
self.updated = dates and dates[-1] or datetime.utcnow()
... | ['def', 'generate(self):', 'if', 'not', 'self.author:', 'if', 'False', 'in', 'map(lambda', 'e:', 'bool(e.author),', 'self.entries):', 'self.author', '=', "({'name':", "'Unknown", "author'},)", 'if', 'not', 'self.updated:', 'dates', '=', 'sorted([entry.updated', 'for', 'entry', 'in', 'self.entries])', 'self.updated', '=... | 483,672 |
AgileRL/AgileRL | evolvable_cnn.py | EvolvableCNN.reset_noise | reset_noise | Resets noise of value and advantage networks. | [
"Resets",
"noise",
"of",
"value",
"and",
"advantage",
"networks."
] | def reset_noise(self):
for layer in self.value_net:
if isinstance(layer, NoisyLinear):
layer.reset_noise()
if self.rainbow:
for layer in self.advantage_net:
if isinstance(layer, NoisyLinear):
layer.reset_noise() | ['def', 'reset_noise(self):', 'for', 'layer', 'in', 'self.value_net:', 'if', 'isinstance(layer,', 'NoisyLinear):', 'layer.reset_noise()', 'if', 'self.rainbow:', 'for', 'layer', 'in', 'self.advantage_net:', 'if', 'isinstance(layer,', 'NoisyLinear):', 'layer.reset_noise()'] | 24,148 |
yjn870/ESPCN-pytorch | imgproc.py | center_crop | center_crop | Crop small image patches from one image center area. | [
"Crop",
"small",
"image",
"patches",
"from",
"one",
"image",
"center",
"area."
] | def center_crop(image: np.ndarray, image_size: int) -> np.ndarray:
(image_height, image_width) = image.shape[:2]
top = (image_height - image_size) // 2
left = (image_width - image_size) // 2
patch_image = image[top:top + image_size, left:left + image_size, ...]
return patch_image | ['def', 'center_crop(image:', 'np.ndarray,', 'image_size:', 'int)', '->', 'np.ndarray:', '(image_height,', 'image_width)', '=', 'image.shape[:2]', 'top', '=', '(image_height', '-', 'image_size)', '//', '2', 'left', '=', '(image_width', '-', 'image_size)', '//', '2', 'patch_image', '=', 'image[top:top', '+', 'image_size... | 178,277 |
google/deepvariant | fasta.py | InMemoryFastaReader.contig | contig | Returns a ContigInfo proto for contig_name. | [
"Returns",
"a",
"ContigInfo",
"proto",
"for",
"contig_name."
] | def contig(self, contig_name):
return self._reader.contig(contig_name) | ['def', 'contig(self,', 'contig_name):', 'return', 'self._reader.contig(contig_name)'] | 540,563 |
Trusted-AI/AIF360 | binary_label_dataset_metric.py | BinaryLabelDatasetMetric.num_negatives | num_negatives | Compute the number of negatives, :math:`N = \sum_{i=1}^n \mathbb{1}[y_i = 0]`, optionally conditioned on protected attributes. | [
"Compute",
"the",
"number",
"of",
"negatives,",
":math:`N",
"=",
"\\sum_{i=1}^n",
"\\mathbb{1}[y_i",
"=",
"0]`,",
"optionally",
"conditioned",
"on",
"protected",
"attributes."
] | def num_negatives(self, privileged=None):
condition = self._to_condition(privileged)
return utils.compute_num_pos_neg(self.dataset.protected_attributes, self.dataset.labels, self.dataset.instance_weights, self.dataset.protected_attribute_names, self.dataset.unfavorable_label, condition=condition) | ['def', 'num_negatives(self,', 'privileged=None):', 'condition', '=', 'self._to_condition(privileged)', 'return', 'utils.compute_num_pos_neg(self.dataset.protected_attributes,', 'self.dataset.labels,', 'self.dataset.instance_weights,', 'self.dataset.protected_attribute_names,', 'self.dataset.unfavorable_label,', 'condi... | 412,307 |
pipermerriam/flex | utils.py | check_if_error_message_equal | check_if_error_message_equal | Helper assertion for testing that a formatted error message matches the expected unformatted version of that error. | [
"Helper",
"assertion",
"for",
"testing",
"that",
"a",
"formatted",
"error",
"message",
"matches",
"the",
"expected",
"unformatted",
"version",
"of",
"that",
"error."
] | def check_if_error_message_equal(formatted_msg, unformatted_msg):
if not isinstance(formatted_msg, six.string_types):
raise ValueError('formatted_msg must be a string: got `{0}`'.format(repr(formatted_msg)))
if not isinstance(unformatted_msg, six.string_types):
raise ValueError('unformatted_msg ... | ['def', 'check_if_error_message_equal(formatted_msg,', 'unformatted_msg):', 'if', 'not', 'isinstance(formatted_msg,', 'six.string_types):', 'raise', "ValueError('formatted_msg", 'must', 'be', 'a', 'string:', 'got', "`{0}`'.format(repr(formatted_msg)))", 'if', 'not', 'isinstance(unformatted_msg,', 'six.string_types):', ... | 211,328 |
openvinotoolkit/training_extensions | multi_gpu.py | MultiGPUManager.check_parent_processes_alive | check_parent_processes_alive | Check parent process is alive and if not, exit by itself. | [
"Check",
"parent",
"process",
"is",
"alive",
"and",
"if",
"not,",
"exit",
"by",
"itself."
] | def check_parent_processes_alive():
cur_process = psutil.Process()
parent = cur_process.parent()
while True:
time.sleep(1)
if not parent.is_running():
break
logger.warning('Parent process is terminated abnormally. Process exits.')
cur_process.kill() | ['def', 'check_parent_processes_alive():', 'cur_process', '=', 'psutil.Process()', 'parent', '=', 'cur_process.parent()', 'while', 'True:', 'time.sleep(1)', 'if', 'not', 'parent.is_running():', 'break', "logger.warning('Parent", 'process', 'is', 'terminated', 'abnormally.', 'Process', "exits.')", 'cur_process.kill()'] | 919,018 |
google-research/batch-ppo | in_graph_env.py | InGraphEnv.step | step | Access the variable containing total steps of this environment. | [
"Access",
"the",
"variable",
"containing",
"total",
"steps",
"of",
"this",
"environment."
] | def step(self):
return self._step | ['def', 'step(self):', 'return', 'self._step'] | 94,972 |
mkusner/grammarVAE | test_basic.py | test_grad.test_zero_gradient_shape | test_zero_gradient_shape | Ensure that a zero gradient has the proper shape. | [
"Ensure",
"that",
"a",
"zero",
"gradient",
"has",
"the",
"proper",
"shape."
] | def test_zero_gradient_shape(self):
x = dmatrix()
f = theano.function([x], grad(dscalar(), x, disconnected_inputs='ignore'))
a = numpy.ones((3, 7))
self.assertTrue((f(a) == 0).all())
self.assertTrue(a.shape == f(a).shape) | ['def', 'test_zero_gradient_shape(self):', 'x', '=', 'dmatrix()', 'f', '=', 'theano.function([x],', 'grad(dscalar(),', 'x,', "disconnected_inputs='ignore'))", 'a', '=', 'numpy.ones((3,', '7))', 'self.assertTrue((f(a)', '==', '0).all())', 'self.assertTrue(a.shape', '==', 'f(a).shape)'] | 580,155 |
brain-research/realistic-ssl-evaluation | evaluate_checkpoints.py | evaluate | evaluate | Evalute a set of checkpoints multiple times. | [
"Evalute",
"a",
"set",
"of",
"checkpoints",
"multiple",
"times."
] | def evaluate(hparams):
accuracies = {}
for explicit_checkpoint_path in FLAGS.checkpoints.split(','):
logging.info(explicit_checkpoint_path)
accuracies[explicit_checkpoint_path] = []
tf.reset_default_graph()
coord = tf.train.Coordinator()
with tf.device('/cpu:0'):
... | ['def', 'evaluate(hparams):', 'accuracies', '=', '{}', 'for', 'explicit_checkpoint_path', 'in', "FLAGS.checkpoints.split(','):", 'logging.info(explicit_checkpoint_path)', 'accuracies[explicit_checkpoint_path]', '=', '[]', 'tf.reset_default_graph()', 'coord', '=', 'tf.train.Coordinator()', 'with', "tf.device('/cpu:0'):"... | 308,974 |
ryu-ed/SpaceInvaders_Ros | support.py | sortdict | sortdict | Like repr(dict), but in sorted order. | [
"Like",
"repr(dict),",
"but",
"in",
"sorted",
"order."
] | def sortdict(dict):
items = sorted(dict.items())
reprpairs = ['%r: %r' % pair for pair in items]
withcommas = ', '.join(reprpairs)
return '{%s}' % withcommas | ['def', 'sortdict(dict):', 'items', '=', 'sorted(dict.items())', 'reprpairs', '=', "['%r:", "%r'", '%', 'pair', 'for', 'pair', 'in', 'items]', 'withcommas', '=', "',", "'.join(reprpairs)", 'return', "'{%s}'", '%', 'withcommas'] | 395,851 |
ifwe/digsby | promote.py | on_before_status_change | on_before_status_change | Invoked when the profile's status message changes. | [
"Invoked",
"when",
"the",
"profile's",
"status",
"message",
"changes."
] | def on_before_status_change(status):
log.info('on_status_change')
if isinstance(status, PromoteStatus):
s = status.status
if pref(PROMOTE_STATUS_PREF, type=str, default='available') != s:
profile.prefs.__setitem__(PROMOTE_STATUS_PREF, s.lower())
return status | ['def', 'on_before_status_change(status):', "log.info('on_status_change')", 'if', 'isinstance(status,', 'PromoteStatus):', 's', '=', 'status.status', 'if', 'pref(PROMOTE_STATUS_PREF,', 'type=str,', "default='available')", '!=', 's:', 'profile.prefs.__setitem__(PROMOTE_STATUS_PREF,', 's.lower())', 'return', 'status'] | 185,993 |
weimin17/Object-Detection_HelmetDetection | util.py | is_a_numpy_array | is_a_numpy_array | Returns true if obj is a numpy array. | [
"Returns",
"true",
"if",
"obj",
"is",
"a",
"numpy",
"array."
] | def is_a_numpy_array(obj):
return type(obj).__module__ == np.__name__ | ['def', 'is_a_numpy_array(obj):', 'return', 'type(obj).__module__', '==', 'np.__name__'] | 754,022 |
famura/SimuRLacra | eval_posterior_rollout_segments.py | mask_out | mask_out | Helper function to mask out states/observations and actions. | [
"Helper",
"function",
"to",
"mask",
"out",
"states/observations",
"and",
"actions."
] | def mask_out(segments_real_all: StepSequence, segments_ml_all: StepSequence, segments_nom: StepSequence, data_field: str, state_mask_labels: Iterable[str]=None, act_mask_labels: Iterable[str]=None):
if data_field == 'states' and state_mask_labels is not None:
state_mask = env_sim.state_space.create_mask(sta... | ['def', 'mask_out(segments_real_all:', 'StepSequence,', 'segments_ml_all:', 'StepSequence,', 'segments_nom:', 'StepSequence,', 'data_field:', 'str,', 'state_mask_labels:', 'Iterable[str]=None,', 'act_mask_labels:', 'Iterable[str]=None):', 'if', 'data_field', '==', "'states'", 'and', 'state_mask_labels', 'is', 'not', 'N... | 884,126 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_metrics.py | get_zipped_dataset_from_predictions | get_zipped_dataset_from_predictions | Creates dataset from in-memory predictions. | [
"Creates",
"dataset",
"from",
"in-memory",
"predictions."
] | def get_zipped_dataset_from_predictions(predictions):
targets = stack_data_given_key(predictions, 'targets')
outputs = stack_data_given_key(predictions, 'outputs')
num_videos = len(targets)
targets_placeholder = tf.placeholder(targets.dtype, targets.shape)
outputs_placeholder = tf.placeholder(output... | ['def', 'get_zipped_dataset_from_predictions(predictions):', 'targets', '=', 'stack_data_given_key(predictions,', "'targets')", 'outputs', '=', 'stack_data_given_key(predictions,', "'outputs')", 'num_videos', '=', 'len(targets)', 'targets_placeholder', '=', 'tf.placeholder(targets.dtype,', 'targets.shape)', 'outputs_pl... | 966,237 |
mariacer/cl_in_rnns | bi_rnn.py | BiRNN.num_rec_layers | num_rec_layers | Getter for read-only attribute :attr:`num_rec_layers`. | [
"Getter",
"for",
"read-only",
"attribute",
":attr:`num_rec_layers`."
] | def num_rec_layers(self):
num_rec_layers = 0
for net in self._forward_rnns + self._backward_rnns:
num_rec_layers += net.num_rec_layers
return num_rec_layers | ['def', 'num_rec_layers(self):', 'num_rec_layers', '=', '0', 'for', 'net', 'in', 'self._forward_rnns', '+', 'self._backward_rnns:', 'num_rec_layers', '+=', 'net.num_rec_layers', 'return', 'num_rec_layers'] | 122,845 |
ryu-ed/SpaceInvaders_Ros | mask_test.py | random_mask | random_mask | random_mask(size=(100,100)): return Mask Create a mask of the given size, with roughly half the bits set at random. | [
"random_mask(size=(100,100)):",
"return",
"Mask",
"Create",
"a",
"mask",
"of",
"the",
"given",
"size,",
"with",
"roughly",
"half",
"the",
"bits",
"set",
"at",
"random."
] | def random_mask(size=(100, 100)):
m = pygame.Mask(size)
for i in range(size[0] * size[1] // 2):
(x, y) = (random.randint(0, size[0] - 1), random.randint(0, size[1] - 1))
m.set_at((x, y))
return m | ['def', 'random_mask(size=(100,', '100)):', 'm', '=', 'pygame.Mask(size)', 'for', 'i', 'in', 'range(size[0]', '*', 'size[1]', '//', '2):', '(x,', 'y)', '=', '(random.randint(0,', 'size[0]', '-', '1),', 'random.randint(0,', 'size[1]', '-', '1))', 'm.set_at((x,', 'y))', 'return', 'm'] | 368,998 |
rudranil723/mini-main | control.py | Control.alt_screen | alt_screen | Enable or disable alt screen. | [
"Enable",
"or",
"disable",
"alt",
"screen."
] | def alt_screen(cls, enable: bool) -> 'Control':
if enable:
return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)
else:
return cls(ControlType.DISABLE_ALT_SCREEN) | ['def', 'alt_screen(cls,', 'enable:', 'bool)', '->', "'Control':", 'if', 'enable:', 'return', 'cls(ControlType.ENABLE_ALT_SCREEN,', 'ControlType.HOME)', 'else:', 'return', 'cls(ControlType.DISABLE_ALT_SCREEN)'] | 268,888 |
rwth-i6/returnn | pprint.py | pformat | pformat | Pretty-format a Python object. | [
"Pretty-format",
"a",
"Python",
"object."
] | def pformat(obj: Any) -> str:
import io
s = io.StringIO()
pprint(obj, file=s)
return s.getvalue() | ['def', 'pformat(obj:', 'Any)', '->', 'str:', 'import', 'io', 's', '=', 'io.StringIO()', 'pprint(obj,', 'file=s)', 'return', 's.getvalue()'] | 348,330 |
PyProphet/pyprophet | main.py | ipf | ipf | Infer peptidoforms after scoring of MS1, MS2 and transition-level data. | [
"Infer",
"peptidoforms",
"after",
"scoring",
"of",
"MS1,",
"MS2",
"and",
"transition-level",
"data."
] | def ipf(infile, outfile, ipf_ms1_scoring, ipf_ms2_scoring, ipf_h0, ipf_grouped_fdr, ipf_max_precursor_pep, ipf_max_peakgroup_pep, ipf_max_precursor_peakgroup_pep, ipf_max_transition_pep):
if outfile is None:
outfile = infile
else:
outfile = outfile
infer_peptidoforms(infile, outfile, ipf_ms1... | ['def', 'ipf(infile,', 'outfile,', 'ipf_ms1_scoring,', 'ipf_ms2_scoring,', 'ipf_h0,', 'ipf_grouped_fdr,', 'ipf_max_precursor_pep,', 'ipf_max_peakgroup_pep,', 'ipf_max_precursor_peakgroup_pep,', 'ipf_max_transition_pep):', 'if', 'outfile', 'is', 'None:', 'outfile', '=', 'infile', 'else:', 'outfile', '=', 'outfile', 'inf... | 296,870 |
gunthercox/ChatterBot | numlists.py | GInts.key_to_sizes | key_to_sizes | Returns a list of the sizes of the next four numbers given a key byte. | [
"Returns",
"a",
"list",
"of",
"the",
"sizes",
"of",
"the",
"next",
"four",
"numbers",
"given",
"a",
"key",
"byte."
] | def key_to_sizes(self, key):
return [(key >> i * 2 & 3) + 1 for i in xrange(4)] | ['def', 'key_to_sizes(self,', 'key):', 'return', '[(key', '>>', 'i', '*', '2', '&', '3)', '+', '1', 'for', 'i', 'in', 'xrange(4)]'] | 484,775 |
soanagno/wakenet | optimisation.py | florisOptimiser | florisOptimiser | Calls the Floris optimiser to calculate the optimal yaws of a turbine farm. | [
"Calls",
"the",
"Floris",
"optimiser",
"to",
"calculate",
"the",
"optimal",
"yaws",
"of",
"a",
"turbine",
"farm."
] | def florisOptimiser(ws, ti, layout_x, layout_y, min_yaw=-30, max_yaw=30, resx=dimx, resy=dimy, plots=False, mode='yaw', results=True):
print()
print()
print('In FLORIS Optimiser...')
file_dir = os.path.dirname(os.path.abspath(__file__))
fi = wfct.floris_interface.FlorisInterface(os.path.join(file_di... | ['def', 'florisOptimiser(ws,', 'ti,', 'layout_x,', 'layout_y,', 'min_yaw=-30,', 'max_yaw=30,', 'resx=dimx,', 'resy=dimy,', 'plots=False,', "mode='yaw',", 'results=True):', 'print()', 'print()', "print('In", 'FLORIS', "Optimiser...')", 'file_dir', '=', 'os.path.dirname(os.path.abspath(__file__))', 'fi', '=', 'wfct.flori... | 941,027 |
open-mmlab/mmdetection3d | dfm.py | DfM.with_depth_head_2d | with_depth_head_2d | Whether the detector has a image-based depth head. | [
"Whether",
"the",
"detector",
"has",
"a",
"image-based",
"depth",
"head."
] | def with_depth_head_2d(self):
return hasattr(self, 'depth_head_2d') and self.depth_head_2d is not None | ['def', 'with_depth_head_2d(self):', 'return', 'hasattr(self,', "'depth_head_2d')", 'and', 'self.depth_head_2d', 'is', 'not', 'None'] | 631,965 |
facebookresearch/fair_self_supervision_benchmark | config.py | cache_cfg_urls | cache_cfg_urls | If we have urls in the config file, cache them locally and point the cfg to use those cache file instead now. | [
"If",
"we",
"have",
"urls",
"in",
"the",
"config",
"file,",
"cache",
"them",
"locally",
"and",
"point",
"the",
"cfg",
"to",
"use",
"those",
"cache",
"file",
"instead",
"now."
] | def cache_cfg_urls():
__C.TRAIN.PARAMS_FILE = cache_url(__C.TRAIN.PARAMS_FILE, __C.DOWNLOAD_CACHE)
__C.TEST.PARAMS_FILE = cache_url(__C.TEST.PARAMS_FILE, __C.DOWNLOAD_CACHE) | ['def', 'cache_cfg_urls():', '__C.TRAIN.PARAMS_FILE', '=', 'cache_url(__C.TRAIN.PARAMS_FILE,', '__C.DOWNLOAD_CACHE)', '__C.TEST.PARAMS_FILE', '=', 'cache_url(__C.TEST.PARAMS_FILE,', '__C.DOWNLOAD_CACHE)'] | 178,951 |
benanne/morb | base.py | RBM.free_energy_affected_terms_from_activation | free_energy_affected_terms_from_activation | For each Units instance in the activation vmap, the corresponding free energy term is returned. | [
"For",
"each",
"Units",
"instance",
"in",
"the",
"activation",
"vmap,",
"the",
"corresponding",
"free",
"energy",
"term",
"is",
"returned."
] | def free_energy_affected_terms_from_activation(self, vmap):
return dict(((u, u.free_energy_term_from_activation(vmap)) for u in vmap)) | ['def', 'free_energy_affected_terms_from_activation(self,', 'vmap):', 'return', 'dict(((u,', 'u.free_energy_term_from_activation(vmap))', 'for', 'u', 'in', 'vmap))'] | 241,161 |
JanMarcelKezmann/Semi-Supervised-Learning-Image-Classification | data_augmentations.py | medium_augment | medium_augment | Function that applies weak augmentation on batch of given images. | [
"Function",
"that",
"applies",
"weak",
"augmentation",
"on",
"batch",
"of",
"given",
"images."
] | def medium_augment(x, height, width, pad=4, seed=[1, 2]):
x = tf.image.stateless_random_flip_left_right(x, seed=seed)
x = tf.image.stateless_random_brightness(x, max_delta=0.35, seed=seed)
x = tf.image.stateless_random_contrast(x, lower=0, upper=0.4, seed=seed)
x = tf.image.stateless_random_hue(x, max_d... | ['def', 'medium_augment(x,', 'height,', 'width,', 'pad=4,', 'seed=[1,', '2]):', 'x', '=', 'tf.image.stateless_random_flip_left_right(x,', 'seed=seed)', 'x', '=', 'tf.image.stateless_random_brightness(x,', 'max_delta=0.35,', 'seed=seed)', 'x', '=', 'tf.image.stateless_random_contrast(x,', 'lower=0,', 'upper=0.4,', 'seed... | 343,367 |
RasaHQ/rasa_core | embedding_policy.py | EmbeddingPolicy.continue_training | continue_training | Continue training an already trained policy. | [
"Continue",
"training",
"an",
"already",
"trained",
"policy."
] | def continue_training(self, training_trackers: List[DialogueStateTracker], domain: Domain, **kwargs: Any) -> None:
batch_size = kwargs.get('batch_size', 5)
epochs = kwargs.get('epochs', 50)
for _ in range(epochs):
training_data = self._training_data_for_continue_training(batch_size, training_tracker... | ['def', 'continue_training(self,', 'training_trackers:', 'List[DialogueStateTracker],', 'domain:', 'Domain,', '**kwargs:', 'Any)', '->', 'None:', 'batch_size', '=', "kwargs.get('batch_size',", '5)', 'epochs', '=', "kwargs.get('epochs',", '50)', 'for', '_', 'in', 'range(epochs):', 'training_data', '=', 'self._training_d... | 838,322 |
tobegit3hub/deep_image_model | ops.py | Operation.colocation_groups | colocation_groups | Returns the list of colocation groups of the op. | [
"Returns",
"the",
"list",
"of",
"colocation",
"groups",
"of",
"the",
"op."
] | def colocation_groups(self):
default_colocation_group = [compat.as_bytes('loc:@%s' % self._node_def.name)]
if '_class' not in self._node_def.attr:
return default_colocation_group
attr_groups = [class_name for class_name in self.get_attr('_class') if class_name.startswith(b'loc:@')]
return attr_g... | ['def', 'colocation_groups(self):', 'default_colocation_group', '=', "[compat.as_bytes('loc:@%s'", '%', 'self._node_def.name)]', 'if', "'_class'", 'not', 'in', 'self._node_def.attr:', 'return', 'default_colocation_group', 'attr_groups', '=', '[class_name', 'for', 'class_name', 'in', "self.get_attr('_class')", 'if', "cl... | 182,569 |
suarez12138/AI-Reversi_IMP_TextDichotomy | axis_artist.py | Ticks.set_tick_out | set_tick_out | Set whether ticks are drawn inside or outside the axes. | [
"Set",
"whether",
"ticks",
"are",
"drawn",
"inside",
"or",
"outside",
"the",
"axes."
] | def set_tick_out(self, b):
self._tick_out = b | ['def', 'set_tick_out(self,', 'b):', 'self._tick_out', '=', 'b'] | 97,510 |
sek788432/Waymo-2D-Object-Detection | lfads.py | GenGRU.output_from_state | output_from_state | Return the output portion of the state. | [
"Return",
"the",
"output",
"portion",
"of",
"the",
"state."
] | def output_from_state(self, state):
return state | ['def', 'output_from_state(self,', 'state):', 'return', 'state'] | 974,421 |
rifqind/Agent-Programs-3KS1 | menus.py | MultiColumnCompletionMenuControl.preferred_width | preferred_width | Preferred width: prefer to use at least min_rows, but otherwise as much as possible horizontally. | [
"Preferred",
"width:",
"prefer",
"to",
"use",
"at",
"least",
"min_rows,",
"but",
"otherwise",
"as",
"much",
"as",
"possible",
"horizontally."
] | def preferred_width(self, max_available_width):
complete_state = get_app().current_buffer.complete_state
column_width = self._get_column_width(complete_state)
result = int(column_width * math.ceil(len(complete_state.completions) / float(self.min_rows)))
while result > column_width and result > max_avail... | ['def', 'preferred_width(self,', 'max_available_width):', 'complete_state', '=', 'get_app().current_buffer.complete_state', 'column_width', '=', 'self._get_column_width(complete_state)', 'result', '=', 'int(column_width', '*', 'math.ceil(len(complete_state.completions)', '/', 'float(self.min_rows)))', 'while', 'result'... | 45,395 |
idsia-robotics/learning-long-range-perception | visualize_output.py | visualize_output | visualize_output | Visualize the content of the HDF5 file along with the prediction made by the model. | [
"Visualize",
"the",
"content",
"of",
"the",
"HDF5",
"file",
"along",
"with",
"the",
"prediction",
"made",
"by",
"the",
"model."
] | def visualize_output():
bag_index = 0
(x, y, _) = next(generator([bag_index], 32, is_testset=True, augment=False, do_flip=False))
l = x.shape[0]
y = y.reshape([l, -1, 5])[:, :31, :]
d = y.shape[1]
print('Generating predictions...')
cnn = model(old_version=False)
cnn.load_weights('model/m... | ['def', 'visualize_output():', 'bag_index', '=', '0', '(x,', 'y,', '_)', '=', 'next(generator([bag_index],', '32,', 'is_testset=True,', 'augment=False,', 'do_flip=False))', 'l', '=', 'x.shape[0]', 'y', '=', 'y.reshape([l,', '-1,', '5])[:,', ':31,', ':]', 'd', '=', 'y.shape[1]', "print('Generating", "predictions...')", ... | 216,037 |
rlworkgroup/garage | test_functions.py | TestOptimizerInterface.test_torch_make_optimizer_raise_value_error | test_torch_make_optimizer_raise_value_error | Test make_optimizer raises value error. | [
"Test",
"make_optimizer",
"raises",
"value",
"error."
] | def test_torch_make_optimizer_raise_value_error(self):
optimizer_type = (torch.optim.Adam, {'lr': 0.1})
module = torch.nn.Linear(2, 1)
with pytest.raises(ValueError):
_ = make_optimizer(optimizer_type, module=module, lr=0.123) | ['def', 'test_torch_make_optimizer_raise_value_error(self):', 'optimizer_type', '=', '(torch.optim.Adam,', "{'lr':", '0.1})', 'module', '=', 'torch.nn.Linear(2,', '1)', 'with', 'pytest.raises(ValueError):', '_', '=', 'make_optimizer(optimizer_type,', 'module=module,', 'lr=0.123)'] | 200,897 |
weimin17/Object-Detection_HelmetDetection | dataset.py | dataset | dataset | Download and parse MNIST dataset. | [
"Download",
"and",
"parse",
"MNIST",
"dataset."
] | def dataset(directory, images_file, labels_file):
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
image = tf.decode_raw(image, tf.uint8)
... | ['def', 'dataset(directory,', 'images_file,', 'labels_file):', 'images_file', '=', 'download(directory,', 'images_file)', 'labels_file', '=', 'download(directory,', 'labels_file)', 'check_image_file_header(images_file)', 'check_labels_file_header(labels_file)', 'def', 'decode_image(image):', 'image', '=', 'tf.decode_ra... | 748,563 |
tensorflow/data-validation | schema_util.py | is_categorical_feature | is_categorical_feature | Checks if the input feature is categorical. | [
"Checks",
"if",
"the",
"input",
"feature",
"is",
"categorical."
] | def is_categorical_feature(feature: schema_pb2.Feature):
if feature.type == schema_pb2.BYTES:
return True
elif feature.type == schema_pb2.INT:
return feature.HasField('int_domain') and feature.int_domain.is_categorical or feature.WhichOneof('domain_info') in ['bool_domain', 'natural_language_dom... | ['def', 'is_categorical_feature(feature:', 'schema_pb2.Feature):', 'if', 'feature.type', '==', 'schema_pb2.BYTES:', 'return', 'True', 'elif', 'feature.type', '==', 'schema_pb2.INT:', 'return', "feature.HasField('int_domain')", 'and', 'feature.int_domain.is_categorical', 'or', "feature.WhichOneof('domain_info')", 'in', ... | 497,631 |
sek788432/Waymo-2D-Object-Detection | preprocessing.py | load_eval_image | load_eval_image | Reads an image from the filesystem and applies image preprocessing. | [
"Reads",
"an",
"image",
"from",
"the",
"filesystem",
"and",
"applies",
"image",
"preprocessing."
] | def load_eval_image(filename: Text, image_size: int=IMAGE_SIZE) -> tf.Tensor:
image_bytes = tf.io.read_file(filename)
image = preprocess_for_eval(image_bytes, image_size)
return image | ['def', 'load_eval_image(filename:', 'Text,', 'image_size:', 'int=IMAGE_SIZE)', '->', 'tf.Tensor:', 'image_bytes', '=', 'tf.io.read_file(filename)', 'image', '=', 'preprocess_for_eval(image_bytes,', 'image_size)', 'return', 'image'] | 973,776 |
shengwenliang/lpcvc2020_water | efficientnet_builder.py | build_model_base | build_model_base | Create a base feature network and return the features before pooling. | [
"Create",
"a",
"base",
"feature",
"network",
"and",
"return",
"the",
"features",
"before",
"pooling."
] | def build_model_base(images, model_name, training, override_params=None):
assert isinstance(images, tf.Tensor)
if override_params and override_params.get('drop_connect_rate', None):
override_params['survival_prob'] = 1 - override_params['drop_connect_rate']
(blocks_args, global_params) = get_model_p... | ['def', 'build_model_base(images,', 'model_name,', 'training,', 'override_params=None):', 'assert', 'isinstance(images,', 'tf.Tensor)', 'if', 'override_params', 'and', "override_params.get('drop_connect_rate',", 'None):', "override_params['survival_prob']", '=', '1', '-', "override_params['drop_connect_rate']", '(block... | 615,848 |
sktime/sktime | test_reduce.py | test_linear_extrapolation_endogenous_only | test_linear_extrapolation_endogenous_only | Test linear extrapolation endogenous only. | [
"Test",
"linear",
"extrapolation",
"endogenous",
"only."
] | def test_linear_extrapolation_endogenous_only(fh, window_length, strategy, method, slope, regressor, scitype):
n_timepoints = 13
y = _make_y(0, n_timepoints, method=method, slope=slope)
y = pd.Series(y)
fh = check_fh(fh)
forecaster = make_reduction(regressor, scitype=scitype, window_length=window_le... | ['def', 'test_linear_extrapolation_endogenous_only(fh,', 'window_length,', 'strategy,', 'method,', 'slope,', 'regressor,', 'scitype):', 'n_timepoints', '=', '13', 'y', '=', '_make_y(0,', 'n_timepoints,', 'method=method,', 'slope=slope)', 'y', '=', 'pd.Series(y)', 'fh', '=', 'check_fh(fh)', 'forecaster', '=', 'make_redu... | 877,242 |
flatironinstitute/deepblast | nw.py | NeedlemanWunschDecoder.decode | decode | Shortcut for doing inference. | [
"Shortcut",
"for",
"doing",
"inference."
] | def decode(self, theta, A):
theta = theta.cpu()
A = A.cpu()
with torch.enable_grad():
nll = self.forward(theta, A)
v = torch.sum(nll)
(v_grad, _) = torch.autograd.grad(v, (theta, A), create_graph=True)
return v_grad | ['def', 'decode(self,', 'theta,', 'A):', 'theta', '=', 'theta.cpu()', 'A', '=', 'A.cpu()', 'with', 'torch.enable_grad():', 'nll', '=', 'self.forward(theta,', 'A)', 'v', '=', 'torch.sum(nll)', '(v_grad,', '_)', '=', 'torch.autograd.grad(v,', '(theta,', 'A),', 'create_graph=True)', 'return', 'v_grad'] | 520,006 |
voxel51/fiftyone | types.py | Object.str | str | Defines a property on the object that is a string. | [
"Defines",
"a",
"property",
"on",
"the",
"object",
"that",
"is",
"a",
"string."
] | def str(self, name, **kwargs):
return self.define_property(name, String(), **kwargs) | ['def', 'str(self,', 'name,', '**kwargs):', 'return', 'self.define_property(name,', 'String(),', '**kwargs)'] | 583,793 |
suarez12138/AI-Reversi_IMP_TextDichotomy | testing.py | warnings_to_stdout | warnings_to_stdout | Redirect all warnings to stdout. | [
"Redirect",
"all",
"warnings",
"to",
"stdout."
] | def warnings_to_stdout():
showwarning_orig = warnings.showwarning
def showwarning(msg, cat, fname, lno, file=None, line=0):
showwarning_orig(msg, cat, os.path.basename(fname), line, sys.stdout)
warnings.showwarning = showwarning | ['def', 'warnings_to_stdout():', 'showwarning_orig', '=', 'warnings.showwarning', 'def', 'showwarning(msg,', 'cat,', 'fname,', 'lno,', 'file=None,', 'line=0):', 'showwarning_orig(msg,', 'cat,', 'os.path.basename(fname),', 'line,', 'sys.stdout)', 'warnings.showwarning', '=', 'showwarning'] | 95,871 |
google-research/scenic | vtab_plainvit_config.py | task | task | Vision task with val and test splits. | [
"Vision",
"task",
"with",
"val",
"and",
"test",
"splits."
] | def task(hyper, name, train, test, n_cls, steps=None, warmup=None, lr=None, ch=3, base_pp='', label='label', crop=True, flip=True, h_res=256, l_res=224):
common = '|value_range(-1, 1)'
common += f'|onehot({n_cls},key="{label}",key_result="labels")'
common += '|keep("image", "labels")'
pp_train = f'decod... | ['def', 'task(hyper,', 'name,', 'train,', 'test,', 'n_cls,', 'steps=None,', 'warmup=None,', 'lr=None,', 'ch=3,', "base_pp='',", "label='label',", 'crop=True,', 'flip=True,', 'h_res=256,', 'l_res=224):', 'common', '=', "'|value_range(-1,", "1)'", 'common', '+=', 'f\'|onehot({n_cls},key="{label}",key_result="labels")\'',... | 846,715 |
weimin17/Object-Detection_HelmetDetection | metrics.py | get_eval_metrics | get_eval_metrics | Return dictionary of model evaluation metrics. | [
"Return",
"dictionary",
"of",
"model",
"evaluation",
"metrics."
] | def get_eval_metrics(logits, labels, params):
metrics = {'accuracy': _convert_to_eval_metric(padded_accuracy)(logits, labels), 'accuracy_top5': _convert_to_eval_metric(padded_accuracy_top5)(logits, labels), 'accuracy_per_sequence': _convert_to_eval_metric(padded_sequence_accuracy)(logits, labels), 'neg_log_perplexi... | ['def', 'get_eval_metrics(logits,', 'labels,', 'params):', 'metrics', '=', "{'accuracy':", '_convert_to_eval_metric(padded_accuracy)(logits,', 'labels),', "'accuracy_top5':", '_convert_to_eval_metric(padded_accuracy_top5)(logits,', 'labels),', "'accuracy_per_sequence':", '_convert_to_eval_metric(padded_sequence_accurac... | 748,759 |
rudranil723/mini-main | weka.py | ARFF_Formatter.labels | labels | Returns the list of classes. | [
"Returns",
"the",
"list",
"of",
"classes."
] | def labels(self):
return list(self._labels) | ['def', 'labels(self):', 'return', 'list(self._labels)'] | 320,877 |
vuptran/cardiac-segmentation | fcn_model.py | mvn | mvn | Performs per-channel spatial mean-variance normalization. | [
"Performs",
"per-channel",
"spatial",
"mean-variance",
"normalization."
] | def mvn(tensor):
epsilon = 1e-06
mean = K.mean(tensor, axis=(1, 2), keepdims=True)
std = K.std(tensor, axis=(1, 2), keepdims=True)
mvn = (tensor - mean) / (std + epsilon)
return mvn | ['def', 'mvn(tensor):', 'epsilon', '=', '1e-06', 'mean', '=', 'K.mean(tensor,', 'axis=(1,', '2),', 'keepdims=True)', 'std', '=', 'K.std(tensor,', 'axis=(1,', '2),', 'keepdims=True)', 'mvn', '=', '(tensor', '-', 'mean)', '/', '(std', '+', 'epsilon)', 'return', 'mvn'] | 102,973 |
thaines/helit | smp.py | SMP.reset | reset | Causes a reset, so you may add a new set of samples. | [
"Causes",
"a",
"reset,",
"so",
"you",
"may",
"add",
"a",
"new",
"set",
"of",
"samples."
] | def reset(self):
self.power[:] = 0 | ['def', 'reset(self):', 'self.power[:]', '=', '0'] | 592,461 |
myothida/Supervised-Machine-Learning | offsetbox.py | TextArea.set_text | set_text | Set the text of this area as a string. | [
"Set",
"the",
"text",
"of",
"this",
"area",
"as",
"a",
"string."
] | def set_text(self, s):
self._text.set_text(s)
self.stale = True | ['def', 'set_text(self,', 's):', 'self._text.set_text(s)', 'self.stale', '=', 'True'] | 362,156 |
vturrisi/solo-learn | classification_dataloader.py | prepare_data | prepare_data | Prepares transformations, creates dataset objects and wraps them in dataloaders. | [
"Prepares",
"transformations,",
"creates",
"dataset",
"objects",
"and",
"wraps",
"them",
"in",
"dataloaders."
] | def prepare_data(dataset: str, train_data_path: Optional[Union[str, Path]]=None, val_data_path: Optional[Union[str, Path]]=None, data_format: Optional[str]='image_folder', batch_size: int=64, num_workers: int=4, download: bool=True, data_fraction: float=-1.0, auto_augment: bool=False) -> Tuple[DataLoader, DataLoader]:
... | ['def', 'prepare_data(dataset:', 'str,', 'train_data_path:', 'Optional[Union[str,', 'Path]]=None,', 'val_data_path:', 'Optional[Union[str,', 'Path]]=None,', 'data_format:', "Optional[str]='image_folder',", 'batch_size:', 'int=64,', 'num_workers:', 'int=4,', 'download:', 'bool=True,', 'data_fraction:', 'float=-1.0,', 'a... | 393,545 |
nilearn/nilearn | test_hemodynamic_models.py | test_sample_condition_5 | test_sample_condition_5 | Test the experimental condition sampling -- negative onset. | [
"Test",
"the",
"experimental",
"condition",
"sampling",
"--",
"negative",
"onset."
] | def test_sample_condition_5():
condition = ([-10, 0, 36.5], [2, 2, 2], [1.0, -1.0, 5.0])
frame_times = np.linspace(0, 49, 50)
(reg, _) = _sample_condition(condition, frame_times, oversampling=1)
assert reg.sum() == 10
assert reg[14] == 1.0
assert reg[24] == -1.0
assert reg[61] == 5.0 | ['def', 'test_sample_condition_5():', 'condition', '=', '([-10,', '0,', '36.5],', '[2,', '2,', '2],', '[1.0,', '-1.0,', '5.0])', 'frame_times', '=', 'np.linspace(0,', '49,', '50)', '(reg,', '_)', '=', '_sample_condition(condition,', 'frame_times,', 'oversampling=1)', 'assert', 'reg.sum()', '==', '10', 'assert', 'reg[14... | 723,872 |
netket/netket | _discrete_operator.py | DiscreteOperator.max_conn_size | max_conn_size | The maximum number of non zero â¨x|O|x'â© for every x. | [
"The",
"maximum",
"number",
"of",
"non",
"zero",
"â¨x|O|x'â©",
"for",
"every",
"x."
] | def max_conn_size(self) -> int:
raise NotImplementedError | ['def', 'max_conn_size(self)', '->', 'int:', 'raise', 'NotImplementedError'] | 736,159 |
moodlehq/moodle-mlbackend-python | tensor.py | TF.predict | predict | Find the index of the most probable class. | [
"Find",
"the",
"index",
"of",
"the",
"most",
"probable",
"class."
] | def predict(self, x):
y = self.model.predict(x)
return tf.keras.backend.eval(tf.argmax(y, 1)) | ['def', 'predict(self,', 'x):', 'y', '=', 'self.model.predict(x)', 'return', 'tf.keras.backend.eval(tf.argmax(y,', '1))'] | 655,660 |
twke18/HSG | others.py | load_memory_banks | load_memory_banks | Return prototypes and labels save in the directory. | [
"Return",
"prototypes",
"and",
"labels",
"save",
"in",
"the",
"directory."
] | def load_memory_banks(memory_dir):
memory_paths = sorted(glob.glob(os.path.join(memory_dir, '*.npy')))
assert len(memory_paths) > 0, 'No memory stored in the directory'
(prototypes, prototype_labels) = ([], [])
for memory_path in memory_paths:
datas = np.load(memory_path, allow_pickle=True).item... | ['def', 'load_memory_banks(memory_dir):', 'memory_paths', '=', 'sorted(glob.glob(os.path.join(memory_dir,', "'*.npy')))", 'assert', 'len(memory_paths)', '>', '0,', "'No", 'memory', 'stored', 'in', 'the', "directory'", '(prototypes,', 'prototype_labels)', '=', '([],', '[])', 'for', 'memory_path', 'in', 'memory_paths:', ... | 570,727 |
arshpreetsingh/quantopian-machinelearning | _compatibility.py | u | u | Cast to unicode DAMMIT! Written because Python2 repr always implicitly casts to a string, so we have to cast back to a unicode (and we know that we always deal with valid unicode, because we check that in the beginning). | [
"Cast",
"to",
"unicode",
"DAMMIT!",
"Written",
"because",
"Python2",
"repr",
"always",
"implicitly",
"casts",
"to",
"a",
"string,",
"so",
"we",
"have",
"to",
"cast",
"back",
"to",
"a",
"unicode",
"(and",
"we",
"know",
"that",
"we",
"always",
"deal",
"with"... | def u(string):
if py_version >= 30:
return str(string)
if not isinstance(string, unicode):
return unicode(str(string), 'UTF-8')
return string | ['def', 'u(string):', 'if', 'py_version', '>=', '30:', 'return', 'str(string)', 'if', 'not', 'isinstance(string,', 'unicode):', 'return', 'unicode(str(string),', "'UTF-8')", 'return', 'string'] | 890,863 |
open-mmlab/mmcv | wrappers.py | RandomApply.random_apply | random_apply | Return a random bool value indicating whether apply the transform. | [
"Return",
"a",
"random",
"bool",
"value",
"indicating",
"whether",
"apply",
"the",
"transform."
] | def random_apply(self) -> bool:
return np.random.rand() < self.prob | ['def', 'random_apply(self)', '->', 'bool:', 'return', 'np.random.rand()', '<', 'self.prob'] | 631,598 |
chainer/chainer | onnx_helper.py | GraphBuilder.nodes | nodes | Returns all nodes created so far. | [
"Returns",
"all",
"nodes",
"created",
"so",
"far."
] | def nodes(self, output_names=None):
if output_names is not None:
assert len(self._nodes[-1].output) == len(output_names)
self._nodes[-1].output[:] = output_names
return tuple(self._nodes) | ['def', 'nodes(self,', 'output_names=None):', 'if', 'output_names', 'is', 'not', 'None:', 'assert', 'len(self._nodes[-1].output)', '==', 'len(output_names)', 'self._nodes[-1].output[:]', '=', 'output_names', 'return', 'tuple(self._nodes)'] | 477,704 |
cosmic-cortex/neural-networks-from-scratch | utils.py | zero_pad | zero_pad | Pads the given array X with zeroes at the both end of given dims. | [
"Pads",
"the",
"given",
"array",
"X",
"with",
"zeroes",
"at",
"the",
"both",
"end",
"of",
"given",
"dims."
] | def zero_pad(X, pad_width, dims):
dims = dims if isinstance(dims, int) else dims
pad = [(0, 0) if idx not in dims else (pad_width, pad_width) for idx in range(len(X.shape))]
X_padded = np.pad(X, pad, 'constant')
return X_padded | ['def', 'zero_pad(X,', 'pad_width,', 'dims):', 'dims', '=', 'dims', 'if', 'isinstance(dims,', 'int)', 'else', 'dims', 'pad', '=', '[(0,', '0)', 'if', 'idx', 'not', 'in', 'dims', 'else', '(pad_width,', 'pad_width)', 'for', 'idx', 'in', 'range(len(X.shape))]', 'X_padded', '=', 'np.pad(X,', 'pad,', "'constant')", 'return'... | 293,231 |
43Carrig/recurrent_neural_networks_practice | tensor_array_ops.py | TensorArray.scatter | scatter | Scatter the values of a `Tensor` in specific indices of a `TensorArray`. | [
"Scatter",
"the",
"values",
"of",
"a",
"`Tensor`",
"in",
"specific",
"indices",
"of",
"a",
"`TensorArray`."
] | def scatter(self, indices, value, name=None):
return self._implementation.scatter(indices, value, name=name) | ['def', 'scatter(self,', 'indices,', 'value,', 'name=None):', 'return', 'self._implementation.scatter(indices,', 'value,', 'name=name)'] | 339,061 |
onnx/onnx | numpy_helper.py | to_dict | to_dict | Converts a map def to a Python dictionary. | [
"Converts",
"a",
"map",
"def",
"to",
"a",
"Python",
"dictionary."
] | def to_dict(map_proto: MapProto) -> Dict[Any, Any]:
key_list: List[Any] = []
if map_proto.key_type == TensorProto.STRING:
key_list = list(map_proto.string_keys)
else:
key_list = list(map_proto.keys)
value_list = to_list(map_proto.values)
if len(key_list) != len(value_list):
r... | ['def', 'to_dict(map_proto:', 'MapProto)', '->', 'Dict[Any,', 'Any]:', 'key_list:', 'List[Any]', '=', '[]', 'if', 'map_proto.key_type', '==', 'TensorProto.STRING:', 'key_list', '=', 'list(map_proto.string_keys)', 'else:', 'key_list', '=', 'list(map_proto.keys)', 'value_list', '=', 'to_list(map_proto.values)', 'if', 'le... | 756,430 |
huawei-noah/xingtian | resnet_general.py | ResNetGeneral.resnet_cell | resnet_cell | Construct ResNet main cell. | [
"Construct",
"ResNet",
"main",
"cell."
] | def resnet_cell(self, ref_block):
items = {}
items['inchannel'] = self.inchannel_list
items['outchannel'] = self.outchannel_list
items['stride'] = self.stride_list
if hasattr(self, 'inner_channels'):
items['innerchannel'] = self.inner_channels
cell = Repeat(num_reps=len(self.stride_list)... | ['def', 'resnet_cell(self,', 'ref_block):', 'items', '=', '{}', "items['inchannel']", '=', 'self.inchannel_list', "items['outchannel']", '=', 'self.outchannel_list', "items['stride']", '=', 'self.stride_list', 'if', 'hasattr(self,', "'inner_channels'):", "items['innerchannel']", '=', 'self.inner_channels', 'cell', '=',... | 962,925 |
OpenMDAO/OpenMDAO-Framework | domain.py | DomainObj.demote | demote | Demote from N-dimensional to N-1 dimensional index space. | [
"Demote",
"from",
"N-dimensional",
"to",
"N-1",
"dimensional",
"index",
"space."
] | def demote(self):
for zone in self.zones:
zone.demote() | ['def', 'demote(self):', 'for', 'zone', 'in', 'self.zones:', 'zone.demote()'] | 275,472 |
enuguru/artificial_intelligence_and_machine_learning | config.py | CoverageConfig.from_args | from_args | Read config values from `kwargs`. | [
"Read",
"config",
"values",
"from",
"`kwargs`."
] | def from_args(self, **kwargs):
for (k, v) in iitems(kwargs):
if v is not None:
if k in self.MUST_BE_LIST and isinstance(v, string_class):
v = [v]
setattr(self, k, v) | ['def', 'from_args(self,', '**kwargs):', 'for', '(k,', 'v)', 'in', 'iitems(kwargs):', 'if', 'v', 'is', 'not', 'None:', 'if', 'k', 'in', 'self.MUST_BE_LIST', 'and', 'isinstance(v,', 'string_class):', 'v', '=', '[v]', 'setattr(self,', 'k,', 'v)'] | 157,252 |
sek788432/Waymo-2D-Object-Detection | input_pipeline.py | process_singledoc_dataset | process_singledoc_dataset | Parses and batches single-doc dataset. | [
"Parses",
"and",
"batches",
"single-doc",
"dataset."
] | def process_singledoc_dataset(dataset, batch_size, params):
name_to_features = {'input_ids_a': tf.io.FixedLenFeature([params.len_title], tf.int64), 'input_ids_b': tf.io.FixedLenFeature([params.len_passage], tf.int64), 'input_mask_b': tf.io.FixedLenFeature([params.len_passage], tf.int64), 'segment_ids_b': tf.io.Fixe... | ['def', 'process_singledoc_dataset(dataset,', 'batch_size,', 'params):', 'name_to_features', '=', "{'input_ids_a':", 'tf.io.FixedLenFeature([params.len_title],', 'tf.int64),', "'input_ids_b':", 'tf.io.FixedLenFeature([params.len_passage],', 'tf.int64),', "'input_mask_b':", 'tf.io.FixedLenFeature([params.len_passage],',... | 972,724 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | base.py | IndexOpsMixin.size | size | Return the number of elements in the underlying data. | [
"Return",
"the",
"number",
"of",
"elements",
"in",
"the",
"underlying",
"data."
] | def size(self):
return len(self._values) | ['def', 'size(self):', 'return', 'len(self._values)'] | 967,117 |
sunishsheth2009/ChatterBot | test_search.py | SearchTestCase.test_search_cast_to_list_no_results | test_search_cast_to_list_no_results | An empty list should be returned when the generator is cast to a list and there are no results to return. | [
"An",
"empty",
"list",
"should",
"be",
"returned",
"when",
"the",
"generator",
"is",
"cast",
"to",
"a",
"list",
"and",
"there",
"are",
"no",
"results",
"to",
"return."
] | def test_search_cast_to_list_no_results(self):
statement = Statement(text='What is your quest?')
results = list(self.search_algorithm.search(statement))
self.assertEqual(results, []) | ['def', 'test_search_cast_to_list_no_results(self):', 'statement', '=', "Statement(text='What", 'is', 'your', "quest?')", 'results', '=', 'list(self.search_algorithm.search(statement))', 'self.assertEqual(results,', '[])'] | 485,894 |
43Carrig/recurrent_neural_networks_practice | linear_operator.py | LinearOperator.dtype | dtype | The `DType` of `Tensor`s handled by this `LinearOperator`. | [
"The",
"`DType`",
"of",
"`Tensor`s",
"handled",
"by",
"this",
"`LinearOperator`."
] | def dtype(self):
return self._dtype | ['def', 'dtype(self):', 'return', 'self._dtype'] | 339,252 |
Trusted-AI/AIX360 | tsice.py | TSICEExplainer.explain_instance | explain_instance | Explain the forecast made by the forecaster at a certain point in time (**local explanation**). | [
"Explain",
"the",
"forecast",
"made",
"by",
"the",
"forecaster",
"at",
"a",
"certain",
"point",
"in",
"time",
"(**local",
"explanation**)."
] | def explain_instance(self, ts: tsFrame, ts_related: tsFrame=None, **explain_params):
return super(TSICEExplainer, self).explain_instance(ts=ts, ts_related=ts_related, **explain_params) | ['def', 'explain_instance(self,', 'ts:', 'tsFrame,', 'ts_related:', 'tsFrame=None,', '**explain_params):', 'return', 'super(TSICEExplainer,', 'self).explain_instance(ts=ts,', 'ts_related=ts_related,', '**explain_params)'] | 413,386 |
caiiiac/Machine-Learning-with-Python | __init__.py | FCompiler.get_flags_debug | get_flags_debug | List of compiler flags to compile with debugging information. | [
"List",
"of",
"compiler",
"flags",
"to",
"compile",
"with",
"debugging",
"information."
] | def get_flags_debug(self):
return [] | ['def', 'get_flags_debug(self):', 'return', '[]'] | 717,134 |
open-mmlab/mmdetection3d | coord_3d_mode.py | Coord3DMode.convert | convert | Convert boxes or points from ``src`` mode to ``dst`` mode. | [
"Convert",
"boxes",
"or",
"points",
"from",
"``src``",
"mode",
"to",
"``dst``",
"mode."
] | def convert(input: Union[Sequence[float], np.ndarray, Tensor, BaseInstance3DBoxes, BasePoints], src: Union[Box3DMode, 'Coord3DMode'], dst: Union[Box3DMode, 'Coord3DMode'], rt_mat: Optional[Union[np.ndarray, Tensor]]=None, with_yaw: bool=True, correct_yaw: bool=False, is_point: bool=True):
if isinstance(input, BaseI... | ['def', 'convert(input:', 'Union[Sequence[float],', 'np.ndarray,', 'Tensor,', 'BaseInstance3DBoxes,', 'BasePoints],', 'src:', 'Union[Box3DMode,', "'Coord3DMode'],", 'dst:', 'Union[Box3DMode,', "'Coord3DMode'],", 'rt_mat:', 'Optional[Union[np.ndarray,', 'Tensor]]=None,', 'with_yaw:', 'bool=True,', 'correct_yaw:', 'bool=... | 632,273 |
bborja/wasr_network | utils.py | prepare_label | prepare_label | Resize masks and perform one-hot encoding. | [
"Resize",
"masks",
"and",
"perform",
"one-hot",
"encoding."
] | def prepare_label(input_batch, new_size, num_classes, one_hot=True):
with tf.name_scope('label_encode'):
input_batch = tf.image.resize_nearest_neighbor(input_batch, new_size)
input_batch = tf.squeeze(input_batch, squeeze_dims=[3])
if one_hot:
input_batch = tf.one_hot(input_batch,... | ['def', 'prepare_label(input_batch,', 'new_size,', 'num_classes,', 'one_hot=True):', 'with', "tf.name_scope('label_encode'):", 'input_batch', '=', 'tf.image.resize_nearest_neighbor(input_batch,', 'new_size)', 'input_batch', '=', 'tf.squeeze(input_batch,', 'squeeze_dims=[3])', 'if', 'one_hot:', 'input_batch', '=', 'tf.o... | 942,366 |
scikit-learn/scikit-learn | test_polynomial.py | test_polynomial_features_input_validation | test_polynomial_features_input_validation | Test that we raise errors for invalid input in PolynomialFeatures. | [
"Test",
"that",
"we",
"raise",
"errors",
"for",
"invalid",
"input",
"in",
"PolynomialFeatures."
] | def test_polynomial_features_input_validation(params, err_msg):
X = [[1], [2]]
with pytest.raises(ValueError, match=err_msg):
PolynomialFeatures(**params).fit(X) | ['def', 'test_polynomial_features_input_validation(params,', 'err_msg):', 'X', '=', '[[1],', '[2]]', 'with', 'pytest.raises(ValueError,', 'match=err_msg):', 'PolynomialFeatures(**params).fit(X)'] | 854,066 |
AgileRL/AgileRL | evolvable_cnn.py | EvolvableCNN.create_cnn | create_cnn | Creates and returns convolutional neural network. | [
"Creates",
"and",
"returns",
"convolutional",
"neural",
"network."
] | def create_cnn(self, input_size, channel_size, kernal_size, stride_size, name):
net_dict = OrderedDict()
net_dict[f'{name}_conv_layer_0'] = nn.Conv2d(in_channels=input_size, out_channels=channel_size[0], kernel_size=kernal_size[0], stride=stride_size[0])
if self.layer_norm:
net_dict[f'{name}_layer_n... | ['def', 'create_cnn(self,', 'input_size,', 'channel_size,', 'kernal_size,', 'stride_size,', 'name):', 'net_dict', '=', 'OrderedDict()', "net_dict[f'{name}_conv_layer_0']", '=', 'nn.Conv2d(in_channels=input_size,', 'out_channels=channel_size[0],', 'kernel_size=kernal_size[0],', 'stride=stride_size[0])', 'if', 'self.laye... | 23,976 |
tusen-ai/SST | rotate_iou.py | rotate_iou_kernel_eval | rotate_iou_kernel_eval | Kernel of computing rotated iou. | [
"Kernel",
"of",
"computing",
"rotated",
"iou."
] | def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=-1):
threadsPerBlock = 8 * 8
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min(N - row_start * threadsPerBlock, threadsPerBlock)
col_size = min(K - col_start * threadsPerBlo... | ['def', 'rotate_iou_kernel_eval(N,', 'K,', 'dev_boxes,', 'dev_query_boxes,', 'dev_iou,', 'criterion=-1):', 'threadsPerBlock', '=', '8', '*', '8', 'row_start', '=', 'cuda.blockIdx.x', 'col_start', '=', 'cuda.blockIdx.y', 'tx', '=', 'cuda.threadIdx.x', 'row_size', '=', 'min(N', '-', 'row_start', '*', 'threadsPerBlock,', ... | 872,276 |
gunthercox/ChatterBot | ma.py | masked_outside | masked_outside | x with mask of all values of x that are outside [v1,v2] v1 and v2 can be given in either order. | [
"x",
"with",
"mask",
"of",
"all",
"values",
"of",
"x",
"that",
"are",
"outside",
"[v1,v2]",
"v1",
"and",
"v2",
"can",
"be",
"given",
"in",
"either",
"order."
] | def masked_outside(x, v1, v2, copy=1):
if v2 < v1:
t = v2
v2 = v1
v1 = t
d = filled(x, 0)
c = umath.logical_or(umath.less(d, v1), umath.greater(d, v2))
m = mask_or(c, getmask(x))
return array(d, mask=m, copy=copy) | ['def', 'masked_outside(x,', 'v1,', 'v2,', 'copy=1):', 'if', 'v2', '<', 'v1:', 't', '=', 'v2', 'v2', '=', 'v1', 'v1', '=', 't', 'd', '=', 'filled(x,', '0)', 'c', '=', 'umath.logical_or(umath.less(d,', 'v1),', 'umath.greater(d,', 'v2))', 'm', '=', 'mask_or(c,', 'getmask(x))', 'return', 'array(d,', 'mask=m,', 'copy=copy)... | 532,412 |
asyml/texar-pytorch | classification.py | ConfusionMatrix.class_id | class_id | Mapping of predicted values and labels to indices within the matrix. | [
"Mapping",
"of",
"predicted",
"values",
"and",
"labels",
"to",
"indices",
"within",
"the",
"matrix."
] | def class_id(self):
return self._class_id | ['def', 'class_id(self):', 'return', 'self._class_id'] | 925,290 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | PearsonMedianSkewness | PearsonMedianSkewness | Computes the Pearson median skewness. | [
"Computes",
"the",
"Pearson",
"median",
"skewness."
] | def PearsonMedianSkewness(xs):
median = Median(xs)
mean = RawMoment(xs, 1)
var = CentralMoment(xs, 2)
std = math.sqrt(var)
gp = 3 * (mean - median) / std
return gp | ['def', 'PearsonMedianSkewness(xs):', 'median', '=', 'Median(xs)', 'mean', '=', 'RawMoment(xs,', '1)', 'var', '=', 'CentralMoment(xs,', '2)', 'std', '=', 'math.sqrt(var)', 'gp', '=', '3', '*', '(mean', '-', 'median)', '/', 'std', 'return', 'gp'] | 19,368 |
PaddlePaddle/PaddleSpeech | tensor_utils.py | add_sos_eos | add_sos_eos | Add <sos> and <eos> labels. | [
"Add",
"<sos>",
"and",
"<eos>",
"labels."
] | def add_sos_eos(ys_pad: paddle.Tensor, sos: int, eos: int, ignore_id: int) -> Tuple[paddle.Tensor, paddle.Tensor]:
B = ys_pad.shape[0]
_sos = paddle.full([B, 1], sos, dtype=ys_pad.dtype)
_eos = paddle.full([B, 1], eos, dtype=ys_pad.dtype)
ys_in = paddle.cat([_sos, ys_pad], dim=1)
mask_pad = ys_in ==... | ['def', 'add_sos_eos(ys_pad:', 'paddle.Tensor,', 'sos:', 'int,', 'eos:', 'int,', 'ignore_id:', 'int)', '->', 'Tuple[paddle.Tensor,', 'paddle.Tensor]:', 'B', '=', 'ys_pad.shape[0]', '_sos', '=', 'paddle.full([B,', '1],', 'sos,', 'dtype=ys_pad.dtype)', '_eos', '=', 'paddle.full([B,', '1],', 'eos,', 'dtype=ys_pad.dtype)',... | 276,516 |
secretflow/secretflow | spu.py | SPU.psi_df | psi_df | Private set intersection with DataFrame. | [
"Private",
"set",
"intersection",
"with",
"DataFrame."
] | def psi_df(self, key: Union[str, List[str], Dict[Device, List[str]]], dfs: List[PYUObject], receiver: str, protocol='KKRT_PSI_2PC', precheck_input=True, sort=True, broadcast_result=True, bucket_size=1 << 20, curve_type='CURVE_25519', preprocess_path=None, ecdh_secret_key_path=None, dppsi_bob_sub_sampling=0.9, dppsi_eps... | ['def', 'psi_df(self,', 'key:', 'Union[str,', 'List[str],', 'Dict[Device,', 'List[str]]],', 'dfs:', 'List[PYUObject],', 'receiver:', 'str,', "protocol='KKRT_PSI_2PC',", 'precheck_input=True,', 'sort=True,', 'broadcast_result=True,', 'bucket_size=1', '<<', '20,', "curve_type='CURVE_25519',", 'preprocess_path=None,', 'ec... | 856,428 |
zhaocq-nlp/NJUNMT-tf | decoder.py | Decoder.merge_top_features | merge_top_features | Merges features of decoder top layers, as the input of softmax layer. | [
"Merges",
"features",
"of",
"decoder",
"top",
"layers,",
"as",
"the",
"input",
"of",
"softmax",
"layer."
] | def merge_top_features(self, decoder_output):
raise NotImplementedError | ['def', 'merge_top_features(self,', 'decoder_output):', 'raise', 'NotImplementedError'] | 782,818 |
sek788432/Waymo-2D-Object-Detection | box_utils.py | jitter_boxes | jitter_boxes | Jitter the box coordinates by some noise distribution. | [
"Jitter",
"the",
"box",
"coordinates",
"by",
"some",
"noise",
"distribution."
] | def jitter_boxes(boxes, noise_scale=0.025):
if boxes.shape[-1] != 4:
raise ValueError('boxes.shape[-1] is {:d}, but must be 4.'.format(boxes.shape[-1]))
with tf.name_scope('jitter_boxes'):
bbox_jitters = tf.random.normal(boxes.get_shape(), stddev=noise_scale)
ymin = boxes[..., 0:1]
... | ['def', 'jitter_boxes(boxes,', 'noise_scale=0.025):', 'if', 'boxes.shape[-1]', '!=', '4:', 'raise', "ValueError('boxes.shape[-1]", 'is', '{:d},', 'but', 'must', 'be', "4.'.format(boxes.shape[-1]))", 'with', "tf.name_scope('jitter_boxes'):", 'bbox_jitters', '=', 'tf.random.normal(boxes.get_shape(),', 'stddev=noise_scale... | 973,559 |
Westlake-AI/openmixup | inverted_residual.py | InvertedResidual.forward | forward | Forward inverted residual function. | [
"Forward",
"inverted",
"residual",
"function."
] | def forward(self, x):
def _inner_forward(x):
out = x
if self.with_expand_conv:
out = self.expand_conv(out)
out = self.depthwise_conv(out)
if self.with_se:
out = self.se(out)
out = self.linear_conv(out)
if self.with_res_shortcut:
re... | ['def', 'forward(self,', 'x):', 'def', '_inner_forward(x):', 'out', '=', 'x', 'if', 'self.with_expand_conv:', 'out', '=', 'self.expand_conv(out)', 'out', '=', 'self.depthwise_conv(out)', 'if', 'self.with_se:', 'out', '=', 'self.se(out)', 'out', '=', 'self.linear_conv(out)', 'if', 'self.with_res_shortcut:', 'return', 'x... | 252,521 |
tensorflow/agents | dm_control_wrapper.py | convert_time_step | convert_time_step | Convert to agents time_step type as the __hash__ method is different. | [
"Convert",
"to",
"agents",
"time_step",
"type",
"as",
"the",
"__hash__",
"method",
"is",
"different."
] | def convert_time_step(time_step):
reward = time_step.reward
if reward is None:
reward = 0.0
discount = time_step.discount
if discount is None:
discount = 1.0
observation = tf.nest.map_structure(_maybe_float32, time_step.observation)
return ts.TimeStep(ts.StepType(time_step.step_t... | ['def', 'convert_time_step(time_step):', 'reward', '=', 'time_step.reward', 'if', 'reward', 'is', 'None:', 'reward', '=', '0.0', 'discount', '=', 'time_step.discount', 'if', 'discount', 'is', 'None:', 'discount', '=', '1.0', 'observation', '=', 'tf.nest.map_structure(_maybe_float32,', 'time_step.observation)', 'return'... | 22,684 |
PRMorgan/State-of-the-Artificial-Intelligence | Player.py | Player.calc_grav | calc_grav | Calculate effect of gravity. | [
"Calculate",
"effect",
"of",
"gravity."
] | def calc_grav(self):
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += 0.45
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height | ['def', 'calc_grav(self):', 'if', 'self.change_y', '==', '0:', 'self.change_y', '=', '1', 'else:', 'self.change_y', '+=', '0.45', 'if', 'self.rect.y', '>=', 'SCREEN_HEIGHT', '-', 'self.rect.height', 'and', 'self.change_y', '>=', '0:', 'self.change_y', '=', '0', 'self.rect.y', '=', 'SCREEN_HEIGHT', '-', 'self.rect.heigh... | 383,897 |
google-research/fixmatch | resnet50_model.py | ResNet50.make_model | make_model | Instantiates the ResNet50 architecture. | [
"Instantiates",
"the",
"ResNet50",
"architecture."
] | def make_model(self, num_classes):
if backend.image_data_format() == 'channels_first':
input_shape = (3, 224, 224)
bn_axis = 1
else:
input_shape = (224, 224, 3)
bn_axis = 3
img_input = layers.Input(shape=input_shape)
x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pa... | ['def', 'make_model(self,', 'num_classes):', 'if', 'backend.image_data_format()', '==', "'channels_first':", 'input_shape', '=', '(3,', '224,', '224)', 'bn_axis', '=', '1', 'else:', 'input_shape', '=', '(224,', '224,', '3)', 'bn_axis', '=', '3', 'img_input', '=', 'layers.Input(shape=input_shape)', 'x', '=', 'layers.Zer... | 211,031 |
shery322/Lunar-Lander-ANN | event_test.py | EventModuleTest.test_post__and_poll | test_post__and_poll | Ensure events can be posted to the queue. | [
"Ensure",
"events",
"can",
"be",
"posted",
"to",
"the",
"queue."
] | def test_post__and_poll(self):
e1 = pygame.event.Event(pygame.USEREVENT, attr1='attr1')
pygame.event.post(e1)
posted_event = pygame.event.poll()
self.assertEqual(e1.attr1, posted_event.attr1, race_condition_notification)
for i in range(1, 11):
pygame.event.post(pygame.event.Event(events[i]))... | ['def', 'test_post__and_poll(self):', 'e1', '=', 'pygame.event.Event(pygame.USEREVENT,', "attr1='attr1')", 'pygame.event.post(e1)', 'posted_event', '=', 'pygame.event.poll()', 'self.assertEqual(e1.attr1,', 'posted_event.attr1,', 'race_condition_notification)', 'for', 'i', 'in', 'range(1,', '11):', 'pygame.event.post(py... | 618,934 |
triaquae/triaquae | test_ds.py | DataSourceTest.test02_invalid_shp | test02_invalid_shp | Testing invalid SHP files for the Data Source. | [
"Testing",
"invalid",
"SHP",
"files",
"for",
"the",
"Data",
"Source."
] | def test02_invalid_shp(self):
for source in bad_ds:
self.assertRaises(OGRException, DataSource, source.ds) | ['def', 'test02_invalid_shp(self):', 'for', 'source', 'in', 'bad_ds:', 'self.assertRaises(OGRException,', 'DataSource,', 'source.ds)'] | 357,690 |
RasaHQ/rasa | train_utils.py | update_evaluation_parameters | update_evaluation_parameters | If EVAL_NUM_EPOCHS is set to -1, evaluate at the end of the training. | [
"If",
"EVAL_NUM_EPOCHS",
"is",
"set",
"to",
"-1,",
"evaluate",
"at",
"the",
"end",
"of",
"the",
"training."
] | def update_evaluation_parameters(config: Dict[Text, Any]) -> Dict[Text, Any]:
if config[EVAL_NUM_EPOCHS] == -1:
config[EVAL_NUM_EPOCHS] = config[EPOCHS]
elif config[EVAL_NUM_EPOCHS] < 1:
raise InvalidConfigException(f"'{EVAL_NUM_EPOCHS}' is set to '{config[EVAL_NUM_EPOCHS]}'. Only values either ... | ['def', 'update_evaluation_parameters(config:', 'Dict[Text,', 'Any])', '->', 'Dict[Text,', 'Any]:', 'if', 'config[EVAL_NUM_EPOCHS]', '==', '-1:', 'config[EVAL_NUM_EPOCHS]', '=', 'config[EPOCHS]', 'elif', 'config[EVAL_NUM_EPOCHS]', '<', '1:', 'raise', 'InvalidConfigException(f"\'{EVAL_NUM_EPOCHS}\'', 'is', 'set', 'to', ... | 837,879 |
ashafahi/RobustTransferLWF | pgd_attack.py | LinfPGDAttack.perturb | perturb | Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm. | [
"Given",
"a",
"set",
"of",
"examples",
"(x_nat,",
"y),",
"returns",
"a",
"set",
"of",
"adversarial",
"examples",
"within",
"epsilon",
"of",
"x_nat",
"in",
"l_infinity",
"norm."
] | def perturb(self, x_nat, y, sess):
if self.rand:
x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
x = np.clip(x, 0, 255)
else:
x = np.copy(x_nat)
for i in range(self.num_steps):
grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_i... | ['def', 'perturb(self,', 'x_nat,', 'y,', 'sess):', 'if', 'self.rand:', 'x', '=', 'x_nat', '+', 'np.random.uniform(-self.epsilon,', 'self.epsilon,', 'x_nat.shape)', 'x', '=', 'np.clip(x,', '0,', '255)', 'else:', 'x', '=', 'np.copy(x_nat)', 'for', 'i', 'in', 'range(self.num_steps):', 'grad', '=', 'sess.run(self.grad,', '... | 826,383 |
weimin17/Object-Detection_HelmetDetection | tensorrt.py | get_trt_graph_from_calib | get_trt_graph_from_calib | Convert a TensorRT graph used for calibration to an inference graph. | [
"Convert",
"a",
"TensorRT",
"graph",
"used",
"for",
"calibration",
"to",
"an",
"inference",
"graph."
] | def get_trt_graph_from_calib(graph_name, calib_graph_def, output_dir):
trt_graph = trt.calib_graph_to_infer_graph(calib_graph_def)
write_graph_to_file(graph_name, trt_graph, output_dir)
return trt_graph | ['def', 'get_trt_graph_from_calib(graph_name,', 'calib_graph_def,', 'output_dir):', 'trt_graph', '=', 'trt.calib_graph_to_infer_graph(calib_graph_def)', 'write_graph_to_file(graph_name,', 'trt_graph,', 'output_dir)', 'return', 'trt_graph'] | 753,906 |
MycroftAI/mycroft-core | cache.py | PhonemeFile.load | load | Load phonemes from cache file. | [
"Load",
"phonemes",
"from",
"cache",
"file."
] | def load(self) -> List:
phonemes = None
if self.path.exists():
try:
with open(self.path) as phoneme_file:
phonemes = phoneme_file.read().strip()
except Exception:
LOG.exception('Failed to read phoneme from cache')
return json.loads(phonemes) | ['def', 'load(self)', '->', 'List:', 'phonemes', '=', 'None', 'if', 'self.path.exists():', 'try:', 'with', 'open(self.path)', 'as', 'phoneme_file:', 'phonemes', '=', 'phoneme_file.read().strip()', 'except', 'Exception:', "LOG.exception('Failed", 'to', 'read', 'phoneme', 'from', "cache')", 'return', 'json.loads(phonemes... | 290,663 |
kornia/kornia | crop3d.py | crop_by_transform_mat3d | crop_by_transform_mat3d | Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix. | [
"Perform",
"crop",
"transform",
"on",
"3D",
"volumes",
"(5D",
"tensor)",
"given",
"a",
"perspective",
"transformation",
"matrix."
] | def crop_by_transform_mat3d(tensor: torch.Tensor, transform: torch.Tensor, out_size: Tuple[int, int, int], mode: str='bilinear', padding_mode: str='zeros', align_corners: bool=True) -> torch.Tensor:
dst_trans_src = transform.expand(tensor.shape[0], -1, -1)
patches: torch.Tensor = warp_affine3d(tensor, dst_trans... | ['def', 'crop_by_transform_mat3d(tensor:', 'torch.Tensor,', 'transform:', 'torch.Tensor,', 'out_size:', 'Tuple[int,', 'int,', 'int],', 'mode:', "str='bilinear',", 'padding_mode:', "str='zeros',", 'align_corners:', 'bool=True)', '->', 'torch.Tensor:', 'dst_trans_src', '=', 'transform.expand(tensor.shape[0],', '-1,', '-1... | 622,143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.