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
arnomoonens/yarll
tile_coding.py
TileCoding.summed_thetas
summed_thetas
Theta values for features present for state and action.
[ "Theta", "values", "for", "features", "present", "for", "state", "and", "action." ]
def summed_thetas(self, state, action): summed = 0 for i in range(self.n_tilings): shifted = state - self.tile_starts[i] (x, y) = shifted if (x >= 0 and x <= self.tiling_width) and (y >= 0 and y <= self.tiling_height): summed += self.thetas[i][int(y // self.tile_height)][int(...
['def', 'summed_thetas(self,', 'state,', 'action):', 'summed', '=', '0', 'for', 'i', 'in', 'range(self.n_tilings):', 'shifted', '=', 'state', '-', 'self.tile_starts[i]', '(x,', 'y)', '=', 'shifted', 'if', '(x', '>=', '0', 'and', 'x', '<=', 'self.tiling_width)', 'and', '(y', '>=', '0', 'and', 'y', '<=', 'self.tiling_hei...
374,679
SonyCSLParis/cae-invar
utils.py
read_csv
read_csv
Reads a csv into a numpy array.
[ "Reads", "a", "csv", "into", "a", "numpy", "array." ]
def read_csv(csv_file): f = open(csv_file, 'r') csvscore = csv.reader(f, delimiter=',') score = [] for row in csvscore: score.append([float(row[CSV_ONTIME]), float(row[CSV_MIDI]), float(row[CSV_HEIGHT]), float(row[CSV_DUR]), float(row[CSV_STAFF])]) score = np.asarray(score) f.close() ...
['def', 'read_csv(csv_file):', 'f', '=', 'open(csv_file,', "'r')", 'csvscore', '=', 'csv.reader(f,', "delimiter=',')", 'score', '=', '[]', 'for', 'row', 'in', 'csvscore:', 'score.append([float(row[CSV_ONTIME]),', 'float(row[CSV_MIDI]),', 'float(row[CSV_HEIGHT]),', 'float(row[CSV_DUR]),', 'float(row[CSV_STAFF])])', 'sco...
410,869
muhanzhang/D-VAE
opt.py
ShapeFeature.shape_tuple
shape_tuple
Return a tuple of symbolic shape vars for tensor variable r.
[ "Return", "a", "tuple", "of", "symbolic", "shape", "vars", "for", "tensor", "variable", "r." ]
def shape_tuple(self, r): if not hasattr(r, 'ndim'): return None return tuple([self.shape_ir(i, r) for i in xrange(r.ndim)])
['def', 'shape_tuple(self,', 'r):', 'if', 'not', 'hasattr(r,', "'ndim'):", 'return', 'None', 'return', 'tuple([self.shape_ir(i,', 'r)', 'for', 'i', 'in', 'xrange(r.ndim)])']
525,587
befelix/safe_learning
utilities.py
constrained_batch_sampler
constrained_batch_sampler
Sample states that do not map outside a bounded state space or to saturated control inputs.
[ "Sample", "states", "that", "do", "not", "map", "outside", "a", "bounded", "state", "space", "or", "to", "saturated", "control", "inputs." ]
def constrained_batch_sampler(dynamics, policy, state_dim, batch_size, action_limit=None, zero_pad=0): batch = tf.random_uniform([int(batch_size), state_dim], -1, 1, dtype=TF_DTYPE, name='batch_sample') actions = policy(batch) future_batch = dynamics(batch, actions) maps_inside = tf.reduce_all(tf.logica...
['def', 'constrained_batch_sampler(dynamics,', 'policy,', 'state_dim,', 'batch_size,', 'action_limit=None,', 'zero_pad=0):', 'batch', '=', 'tf.random_uniform([int(batch_size),', 'state_dim],', '-1,', '1,', 'dtype=TF_DTYPE,', "name='batch_sample')", 'actions', '=', 'policy(batch)', 'future_batch', '=', 'dynamics(batch,'...
328,112
weimin17/Object-Detection_HelmetDetection
transformer_main.py
get_global_step
get_global_step
Return estimator's last checkpoint.
[ "Return", "estimator's", "last", "checkpoint." ]
def get_global_step(estimator): return int(estimator.latest_checkpoint().split('-')[-1])
['def', 'get_global_step(estimator):', 'return', "int(estimator.latest_checkpoint().split('-')[-1])"]
761,184
voxel51/fiftyone
models.py
SamplesMixin.needs_fields
needs_fields
A dict mapping model-specific keys to sample field names.
[ "A", "dict", "mapping", "model-specific", "keys", "to", "sample", "field", "names." ]
def needs_fields(self): return self._fields
['def', 'needs_fields(self):', 'return', 'self._fields']
583,209
huawei-noah/xingtian
sr_metric.py
SSIM.summary
summary
Summary all cached records, here is the last pfm record.
[ "Summary", "all", "cached", "records,", "here", "is", "the", "last", "pfm", "record." ]
def summary(self): return self.pfm
['def', 'summary(self):', 'return', 'self.pfm']
962,685
devashish-patel/webcam-motion-detector
buffer.py
Buffer.history_backward
history_backward
Move backwards through history.
[ "Move", "backwards", "through", "history." ]
def history_backward(self, count=1): self._set_history_search() found_something = False for i in range(self.working_index - 1, -1, -1): if self._history_matches(i): self.working_index = i count -= 1 found_something = True if count == 0: break ...
['def', 'history_backward(self,', 'count=1):', 'self._set_history_search()', 'found_something', '=', 'False', 'for', 'i', 'in', 'range(self.working_index', '-', '1,', '-1,', '-1):', 'if', 'self._history_matches(i):', 'self.working_index', '=', 'i', 'count', '-=', '1', 'found_something', '=', 'True', 'if', 'count', '=='...
983,674
LongPham7/Distributionally-Robust-Optimization
util_adversarial_attack.py
wrapModel
wrapModel
Wrap a PyTorch model using a wrapper provided by ART (Adversarial Robustness Toolbox) by IBM.
[ "Wrap", "a", "PyTorch", "model", "using", "a", "wrapper", "provided", "by", "ART", "(Adversarial", "Robustness", "Toolbox)", "by", "IBM." ]
def wrapModel(model, loss_criterion): optimizer = optim.Adam(model.parameters()) input_shape = (1, img_rows, img_cols) return PyTorchClassifier((0, 1), model, loss_criterion, optimizer, input_shape, nb_classes=10)
['def', 'wrapModel(model,', 'loss_criterion):', 'optimizer', '=', 'optim.Adam(model.parameters())', 'input_shape', '=', '(1,', 'img_rows,', 'img_cols)', 'return', 'PyTorchClassifier((0,', '1),', 'model,', 'loss_criterion,', 'optimizer,', 'input_shape,', 'nb_classes=10)']
552,149
43Carrig/recurrent_neural_networks_practice
images_plugin.py
ImagesPlugin.is_active
is_active
The images plugin is active iff any run has at least one relevant tag.
[ "The", "images", "plugin", "is", "active", "iff", "any", "run", "has", "at", "least", "one", "relevant", "tag." ]
def is_active(self): if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute('\n SELECT 1\n FROM Tags\n WHERE Tags.plugin_name = ?\n LIMIT 1\n ', (metadata.PLUGIN_NAME,)) return bool(list(cursor)) if not self._...
['def', 'is_active(self):', 'if', 'self._db_connection_provider:', 'db', '=', 'self._db_connection_provider()', 'cursor', '=', "db.execute('\\n", 'SELECT', '1\\n', 'FROM', 'Tags\\n', 'WHERE', 'Tags.plugin_name', '=', '?\\n', 'LIMIT', '1\\n', "',", '(metadata.PLUGIN_NAME,))', 'return', 'bool(list(cursor))', 'if', 'not',...
312,227
Ruturaj123/Flowchart-Detection
variable_scope.py
VariableScope.local_variables
local_variables
Get this scope's local variables.
[ "Get", "this", "scope's", "local", "variables." ]
def local_variables(self): return self.get_collection(ops.GraphKeys.LOCAL_VARIABLES)
['def', 'local_variables(self):', 'return', 'self.get_collection(ops.GraphKeys.LOCAL_VARIABLES)']
606,210
eth-ait/motion-infilling
flags_parser.py
get_data_path
get_data_path
Returns the default path where the data is stored.
[ "Returns", "the", "default", "path", "where", "the", "data", "is", "stored." ]
def get_data_path(): return '../data_preprocessed/'
['def', 'get_data_path():', 'return', "'../data_preprocessed/'"]
656,128
weimin17/Object-Detection_HelmetDetection
helper.py
convert_to_indices
convert_to_indices
Convert a list of size [batch_size, sequence_length, vocab_size] to a list of size [batch_size, sequence_length] where the vocab element is denoted by the index.
[ "Convert", "a", "list", "of", "size", "[batch_size,", "sequence_length,", "vocab_size]", "to", "a", "list", "of", "size", "[batch_size,", "sequence_length]", "where", "the", "vocab", "element", "is", "denoted", "by", "the", "index." ]
def convert_to_indices(sequences): batch_of_indices = [] for sequence in sequences: indices = [] for embedding in sequence: indices.append(np.argmax(embedding)) batch_of_indices.append(indices) return batch_of_indices
['def', 'convert_to_indices(sequences):', 'batch_of_indices', '=', '[]', 'for', 'sequence', 'in', 'sequences:', 'indices', '=', '[]', 'for', 'embedding', 'in', 'sequence:', 'indices.append(np.argmax(embedding))', 'batch_of_indices.append(indices)', 'return', 'batch_of_indices']
758,024
Erfanafshar/Principles-and-Applications-of---graph-coloring
transforms.py
LockableBbox.locked_y1
locked_y1
float or None: The value used for the locked y1.
[ "float", "or", "None:", "The", "value", "used", "for", "the", "locked", "y1." ]
def locked_y1(self): if self._locked_points.mask[1, 1]: return None else: return self._locked_points[1, 1]
['def', 'locked_y1(self):', 'if', 'self._locked_points.mask[1,', '1]:', 'return', 'None', 'else:', 'return', 'self._locked_points[1,', '1]']
307,164
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
rl.py
simple_gym_spec
simple_gym_spec
Parameters of environment specification.
[ "Parameters", "of", "environment", "specification." ]
def simple_gym_spec(env): standard_wrappers = None env_lambda = None if isinstance(env, str): env_lambda = lambda : gym.make(env) if callable(env): env_lambda = env assert env_lambda is not None, 'Unknown specification of environment' return tf.contrib.training.HParams(env_lambda...
['def', 'simple_gym_spec(env):', 'standard_wrappers', '=', 'None', 'env_lambda', '=', 'None', 'if', 'isinstance(env,', 'str):', 'env_lambda', '=', 'lambda', ':', 'gym.make(env)', 'if', 'callable(env):', 'env_lambda', '=', 'env', 'assert', 'env_lambda', 'is', 'not', 'None,', "'Unknown", 'specification', 'of', "environme...
965,845
43Carrig/recurrent_neural_networks_practice
pfor.py
WhileOp.op_is_inside_loop
op_is_inside_loop
True if op was created inside the pfor loop body.
[ "True", "if", "op", "was", "created", "inside", "the", "pfor", "loop", "body." ]
def op_is_inside_loop(self, op): assert isinstance(op, ops.Operation) return op._id in self._pfor_op_ids
['def', 'op_is_inside_loop(self,', 'op):', 'assert', 'isinstance(op,', 'ops.Operation)', 'return', 'op._id', 'in', 'self._pfor_op_ids']
339,331
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
autoencoders.py
autoencoder_residual_text
autoencoder_residual_text
Residual autoencoder model for text.
[ "Residual", "autoencoder", "model", "for", "text." ]
def autoencoder_residual_text(): hparams = autoencoder_residual() hparams.bottleneck_bits = 32 hparams.batch_size = 1024 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.target_modality = 'symbol:identity' hparams.input_modalities = 'symbol:id...
['def', 'autoencoder_residual_text():', 'hparams', '=', 'autoencoder_residual()', 'hparams.bottleneck_bits', '=', '32', 'hparams.batch_size', '=', '1024', 'hparams.hidden_size', '=', '64', 'hparams.max_hidden_size', '=', '512', 'hparams.bottleneck_noise', '=', '0.0', 'hparams.target_modality', '=', "'symbol:identity'",...
965,787
ELEKTRONN/elektronn3
unet.py
get_conv
get_conv
Chooses an implementation for a convolution layer.
[ "Chooses", "an", "implementation", "for", "a", "convolution", "layer." ]
def get_conv(dim=3): if dim == 3: return nn.Conv3d elif dim == 2: return nn.Conv2d else: raise ValueError('dim has to be 2 or 3')
['def', 'get_conv(dim=3):', 'if', 'dim', '==', '3:', 'return', 'nn.Conv3d', 'elif', 'dim', '==', '2:', 'return', 'nn.Conv2d', 'else:', 'raise', "ValueError('dim", 'has', 'to', 'be', '2', 'or', "3')"]
175,631
thu-ml/ares
vmi_fgsm.py
VMI_fgsm.attack_detection_forward
attack_detection_forward
This function is used to attack object detection models.
[ "This", "function", "is", "used", "to", "attack", "object", "detection", "models." ]
def attack_detection_forward(self, batch_data, excluded_losses, scale_factor=255.0, object_vanish_only=False): images = batch_data['inputs'] batchsize = len(images) advimages = images momentum = torch.zeros_like(images).detach() variance = torch.zeros_like(images).detach() for i in range(self.st...
['def', 'attack_detection_forward(self,', 'batch_data,', 'excluded_losses,', 'scale_factor=255.0,', 'object_vanish_only=False):', 'images', '=', "batch_data['inputs']", 'batchsize', '=', 'len(images)', 'advimages', '=', 'images', 'momentum', '=', 'torch.zeros_like(images).detach()', 'variance', '=', 'torch.zeros_like(i...
402,023
Katja-M/Python_NaturalLanguageProcessing
nkjp.py
NKJPCorpusReader.header
header
Returns header(s) of specified fileids.
[ "Returns", "header(s)", "of", "specified", "fileids." ]
def header(self, fileids=None, **kwargs): return concat([self._view(self.add_root(fileid), mode=NKJPCorpusReader.HEADER_MODE, **kwargs).handle_query() for fileid in fileids])
['def', 'header(self,', 'fileids=None,', '**kwargs):', 'return', 'concat([self._view(self.add_root(fileid),', 'mode=NKJPCorpusReader.HEADER_MODE,', '**kwargs).handle_query()', 'for', 'fileid', 'in', 'fileids])']
866,225
zjujdj/SuperAtomicCharge
MyUtils.py
EarlyStopping.load_checkpoint
load_checkpoint
Load model saved with early stopping.
[ "Load", "model", "saved", "with", "early", "stopping." ]
def load_checkpoint(self, model): model.load_state_dict(torch.load(self.filename)['model_state_dict'])
['def', 'load_checkpoint(self,', 'model):', "model.load_state_dict(torch.load(self.filename)['model_state_dict'])"]
880,744
SALT-NLP/Adaptive-Compositional-Modules
tokenization_blenderbot_small.py
BlenderbotSmallTokenizer.convert_tokens_to_string
convert_tokens_to_string
Converts a sequence of tokens in a single string.
[ "Converts", "a", "sequence", "of", "tokens", "in", "a", "single", "string." ]
def convert_tokens_to_string(self, tokens: List[str]) -> str: out_string = ' '.join(tokens).replace('@@ ', '').strip() return out_string
['def', 'convert_tokens_to_string(self,', 'tokens:', 'List[str])', '->', 'str:', 'out_string', '=', "'", "'.join(tokens).replace('@@", "',", "'').strip()", 'return', 'out_string']
408,666
Akash671/AI
analysis.py
question2c
question2c
Prefer the distant exit (+10), risking the cliff (-10).
[ "Prefer", "the", "distant", "exit", "(+10),", "risking", "the", "cliff", "(-10)." ]
def question2c(): answerDiscount = None answerNoise = None answerLivingReward = None return (answerDiscount, answerNoise, answerLivingReward)
['def', 'question2c():', 'answerDiscount', '=', 'None', 'answerNoise', '=', 'None', 'answerLivingReward', '=', 'None', 'return', '(answerDiscount,', 'answerNoise,', 'answerLivingReward)']
64,419
deepmind/dm_control
randomizers.py
random_limited_quaternion
random_limited_quaternion
Generates a random quaternion limited to the specified rotations.
[ "Generates", "a", "random", "quaternion", "limited", "to", "the", "specified", "rotations." ]
def random_limited_quaternion(random, limit): axis = random.randn(3) axis /= np.linalg.norm(axis) angle = random.rand() * limit quaternion = np.zeros(4) mjbindings.mjlib.mju_axisAngle2Quat(quaternion, axis, angle) return quaternion
['def', 'random_limited_quaternion(random,', 'limit):', 'axis', '=', 'random.randn(3)', 'axis', '/=', 'np.linalg.norm(axis)', 'angle', '=', 'random.rand()', '*', 'limit', 'quaternion', '=', 'np.zeros(4)', 'mjbindings.mjlib.mju_axisAngle2Quat(quaternion,', 'axis,', 'angle)', 'return', 'quaternion']
165,608
fundamentalvision/BEVFormer
nuscenes_converter.py
obtain_sensor2top
obtain_sensor2top
Obtain the info with RT matric from general sensor to Top LiDAR.
[ "Obtain", "the", "info", "with", "RT", "matric", "from", "general", "sensor", "to", "Top", "LiDAR." ]
def obtain_sensor2top(nusc, sensor_token, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, sensor_type='lidar'): sd_rec = nusc.get('sample_data', sensor_token) cs_record = nusc.get('calibrated_sensor', sd_rec['calibrated_sensor_token']) pose_record = nusc.get('ego_pose', sd_rec['ego_pose_token']) data_path = str(nus...
['def', 'obtain_sensor2top(nusc,', 'sensor_token,', 'l2e_t,', 'l2e_r_mat,', 'e2g_t,', 'e2g_r_mat,', "sensor_type='lidar'):", 'sd_rec', '=', "nusc.get('sample_data',", 'sensor_token)', 'cs_record', '=', "nusc.get('calibrated_sensor',", "sd_rec['calibrated_sensor_token'])", 'pose_record', '=', "nusc.get('ego_pose',", "sd...
434,392
navarmn/Elman_neural_network
testing.py
clean_warning_registry
clean_warning_registry
Safe way to reset warnings.
[ "Safe", "way", "to", "reset", "warnings." ]
def clean_warning_registry(): warnings.resetwarnings() reg = '__warningregistry__' for (mod_name, mod) in list(sys.modules.items()): if 'six.moves' in mod_name: continue if hasattr(mod, reg): getattr(mod, reg).clear()
['def', 'clean_warning_registry():', 'warnings.resetwarnings()', 'reg', '=', "'__warningregistry__'", 'for', '(mod_name,', 'mod)', 'in', 'list(sys.modules.items()):', 'if', "'six.moves'", 'in', 'mod_name:', 'continue', 'if', 'hasattr(mod,', 'reg):', 'getattr(mod,', 'reg).clear()']
176,010
Kvatsx/Artificial-Intelligence-Assignments
test_traitlets.py
TestDirectionalLink.test_connect_same
test_connect_same
Verify two traitlets of the same type can be linked together using directional_link.
[ "Verify", "two", "traitlets", "of", "the", "same", "type", "can", "be", "linked", "together", "using", "directional_link." ]
def test_connect_same(self): class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) c = directional_link((a, 'value'), (b, 'value')) self.assertEqual(a.value, b.value) a.value = 5 self.assertEqual(b.value, 5) b.value = 6 self.assertEqual(a.value, 5)
['def', 'test_connect_same(self):', 'class', 'A(HasTraits):', 'value', '=', 'Int()', 'a', '=', 'A(value=9)', 'b', '=', 'A(value=8)', 'c', '=', 'directional_link((a,', "'value'),", '(b,', "'value'))", 'self.assertEqual(a.value,', 'b.value)', 'a.value', '=', '5', 'self.assertEqual(b.value,', '5)', 'b.value', '=', '6', 's...
79,007
SforAiDl/genrl
neural_linpos.py
NeuralLinearPosteriorAgent.update_db
update_db
Updates transition database with given transition Updates latent context and predicted rewards seperately.
[ "Updates", "transition", "database", "with", "given", "transition", "Updates", "latent", "context", "and", "predicted", "rewards", "seperately." ]
def update_db(self, context: torch.Tensor, action: int, reward: int): self.db.add(context, action, reward) results = self.model(context) self.latent_db.add(results['x'].detach(), action, reward)
['def', 'update_db(self,', 'context:', 'torch.Tensor,', 'action:', 'int,', 'reward:', 'int):', 'self.db.add(context,', 'action,', 'reward)', 'results', '=', 'self.model(context)', "self.latent_db.add(results['x'].detach(),", 'action,', 'reward)']
556,808
tensorforce/tensorforce
conjugate_gradient.py
ConjugateGradient.solve
solve
Iteratively solves the system of linear equations $A x = b$.
[ "Iteratively", "solves", "the", "system", "of", "linear", "equations", "$A", "x", "=", "b$." ]
def solve(self, *, arguments, x_init, b, fn_x): return super().solve(arguments=arguments, x_init=x_init, b=b, fn_x=fn_x)
['def', 'solve(self,', '*,', 'arguments,', 'x_init,', 'b,', 'fn_x):', 'return', 'super().solve(arguments=arguments,', 'x_init=x_init,', 'b=b,', 'fn_x=fn_x)']
365,813
alinlab/ifseg
fairseq_lr_scheduler.py
FairseqLRScheduler.step
step
Update the learning rate at the end of the given epoch.
[ "Update", "the", "learning", "rate", "at", "the", "end", "of", "the", "given", "epoch." ]
def step(self, epoch, val_loss=None): if val_loss is not None: if self.best is None: self.best = val_loss else: self.best = min(self.best, val_loss)
['def', 'step(self,', 'epoch,', 'val_loss=None):', 'if', 'val_loss', 'is', 'not', 'None:', 'if', 'self.best', 'is', 'None:', 'self.best', '=', 'val_loss', 'else:', 'self.best', '=', 'min(self.best,', 'val_loss)']
598,429
shanest/quantifier-rnn-learning
analysis.py
experiment_analysis
experiment_analysis
Prints statistical tests and makes plots for experiment one.
[ "Prints", "statistical", "tests", "and", "makes", "plots", "for", "experiment", "one." ]
def experiment_analysis(path, quants, trials=list(range(30)), plots=True, threshold=0.95, filename=None, size=None): data = util.read_trials_from_csv(path, trials) remove_bad_trials(data, quants, threshold=threshold) convergence_points = get_convergence_points(data, quants, threshold) if plots: ...
['def', 'experiment_analysis(path,', 'quants,', 'trials=list(range(30)),', 'plots=True,', 'threshold=0.95,', 'filename=None,', 'size=None):', 'data', '=', 'util.read_trials_from_csv(path,', 'trials)', 'remove_bad_trials(data,', 'quants,', 'threshold=threshold)', 'convergence_points', '=', 'get_convergence_points(data,'...
303,992
jwwangchn/NWD
test_detr_head.py
test_detr_head_loss
test_detr_head_loss
Tests transformer head loss when truth is empty and non-empty.
[ "Tests", "transformer", "head", "loss", "when", "truth", "is", "empty", "and", "non-empty." ]
def test_detr_head_loss(): s = 256 img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3), 'batch_input_shape': (s, s)}] config = ConfigDict(dict(type='DETRHead', num_classes=80, in_channels=200, transformer=dict(type='Transformer', encoder=dict(type='DetrTransformerEncoder', num_la...
['def', 'test_detr_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3),', "'batch_input_shape':", '(s,', 's)}]', 'config', '=', "ConfigDict(dict(type='DETRHead',", 'num_classes=80,', 'in_channels=200,', "transformer=dict(type=...
725,079
TengXiaoDai/DistributedCrawling
easy_install.py
easy_install.select_scheme
select_scheme
Sets the install directories by applying the install schemes.
[ "Sets", "the", "install", "directories", "by", "applying", "the", "install", "schemes." ]
def select_scheme(self, name): scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key])
['def', 'select_scheme(self,', 'name):', 'scheme', '=', 'INSTALL_SCHEMES[name]', 'for', 'key', 'in', 'SCHEME_KEYS:', 'attrname', '=', "'install_'", '+', 'key', 'if', 'getattr(self,', 'attrname)', 'is', 'None:', 'setattr(self,', 'attrname,', 'scheme[key])']
189,327
facebookresearch/CompilerGym
env_without_bazel_test.py
test_versions
test_versions
Tests the GetVersion() RPC endpoint.
[ "Tests", "the", "GetVersion()", "RPC", "endpoint." ]
def test_versions(env: ClientServiceCompilerEnv): assert env.version == compiler_gym.__version__ assert env.compiler_version == '1.0.0'
['def', 'test_versions(env:', 'ClientServiceCompilerEnv):', 'assert', 'env.version', '==', 'compiler_gym.__version__', 'assert', 'env.compiler_version', '==', "'1.0.0'"]
125,798
bytedance/ParaGen
lightseq_transformer_encoder_layer.py
LSTransformerEncoderLayer.forward
forward
Pass the input through the encoder layer.
[ "Pass", "the", "input", "through", "the", "encoder", "layer." ]
def forward(self, src: Tensor, src_key_padding_mask: Optional[Tensor]=None) -> Tensor: return self._layer(src, src_key_padding_mask)
['def', 'forward(self,', 'src:', 'Tensor,', 'src_key_padding_mask:', 'Optional[Tensor]=None)', '->', 'Tensor:', 'return', 'self._layer(src,', 'src_key_padding_mask)']
779,330
galeone/dynamic-training-bench
VGG.py
VGG.loss
loss
Add L2Loss to all the trainable variables.
[ "Add", "L2Loss", "to", "all", "the", "trainable", "variables." ]
def loss(self, logits, labels): with tf.variable_scope('loss'): labels = tf.cast(labels, tf.int64) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='cross_entropy_per_example') cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_ent...
['def', 'loss(self,', 'logits,', 'labels):', 'with', "tf.variable_scope('loss'):", 'labels', '=', 'tf.cast(labels,', 'tf.int64)', 'cross_entropy', '=', 'tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,', 'labels=labels,', "name='cross_entropy_per_example')", 'cross_entropy_mean', '=', 'tf.reduce_mean(cross...
174,277
Speech-Lab-IITM/CCC-wav2vec-2.0
fairseq_task.py
FairseqTask.max_positions
max_positions
Return the max input length allowed by the task.
[ "Return", "the", "max", "input", "length", "allowed", "by", "the", "task." ]
def max_positions(self): return None
['def', 'max_positions(self):', 'return', 'None']
104,122
myothida/Supervised-Machine-Learning
test_score_objects.py
test_multimetric_scorer_exception_handling
test_multimetric_scorer_exception_handling
Check that the calling of the `_MultimetricScorer` returns exception messages in the result dict for the failing scorers in case of `raise_exc` is `False` and if `raise_exc` is `True`, then the proper exception is raised.
[ "Check", "that", "the", "calling", "of", "the", "`_MultimetricScorer`", "returns", "exception", "messages", "in", "the", "result", "dict", "for", "the", "failing", "scorers", "in", "case", "of", "`raise_exc`", "is", "`False`", "and", "if", "`raise_exc`", "is", ...
def test_multimetric_scorer_exception_handling(raise_exc): scorers = {'failing_1': 'neg_mean_squared_log_error', 'non_failing': 'neg_median_absolute_error', 'failing_2': 'neg_mean_squared_log_error'} (X, y) = make_classification(n_samples=50, n_features=2, n_redundant=0, random_state=0) y *= -1 clf = De...
['def', 'test_multimetric_scorer_exception_handling(raise_exc):', 'scorers', '=', "{'failing_1':", "'neg_mean_squared_log_error',", "'non_failing':", "'neg_median_absolute_error',", "'failing_2':", "'neg_mean_squared_log_error'}", '(X,', 'y)', '=', 'make_classification(n_samples=50,', 'n_features=2,', 'n_redundant=0,',...
364,280
ifwe/digsby
imwin_native.py
NativeNotebookPanel.OnNotebookPageChanged
OnNotebookPageChanged
Fire notifications so that the frame can handle changes to the active convo.
[ "Fire", "notifications", "so", "that", "the", "frame", "can", "handle", "changes", "to", "the", "active", "convo." ]
def OnNotebookPageChanged(self, event): page = self.notebook.GetPage(event.GetSelection()) icon = imwin_gui.icons.get(page.icontype, 'buddy')(page.Buddy) pubsub.Publisher().sendMessage(('tab', 'icon', 'updated'), (page, icon)) pubsub.Publisher().sendMessage(('tab', 'title', 'updated'), (page, page.Buddy...
['def', 'OnNotebookPageChanged(self,', 'event):', 'page', '=', 'self.notebook.GetPage(event.GetSelection())', 'icon', '=', 'imwin_gui.icons.get(page.icontype,', "'buddy')(page.Buddy)", "pubsub.Publisher().sendMessage(('tab',", "'icon',", "'updated'),", '(page,', 'icon))', "pubsub.Publisher().sendMessage(('tab',", "'tit...
185,426
calico/basenji
basenji_sad.py
write_snp_len
write_snp_len
Write SNP predictions to HDF, assuming the length dimension has been maintained.
[ "Write", "SNP", "predictions", "to", "HDF,", "assuming", "the", "length", "dimension", "has", "been", "maintained." ]
def write_snp_len(ref_preds, alt_preds, sad_out, si, sad_stats): (seq_length, num_targets) = ref_preds.shape ref_preds_log = np.log2(ref_preds + 1) alt_preds_log = np.log2(alt_preds + 1) ref_preds_sqrt = np.sqrt(ref_preds) alt_preds_sqrt = np.sqrt(alt_preds) ref_preds_sum = ref_preds.sum(axis=0)...
['def', 'write_snp_len(ref_preds,', 'alt_preds,', 'sad_out,', 'si,', 'sad_stats):', '(seq_length,', 'num_targets)', '=', 'ref_preds.shape', 'ref_preds_log', '=', 'np.log2(ref_preds', '+', '1)', 'alt_preds_log', '=', 'np.log2(alt_preds', '+', '1)', 'ref_preds_sqrt', '=', 'np.sqrt(ref_preds)', 'alt_preds_sqrt', '=', 'np....
94,793
tinazhouhui/computer_vision
inputs_test.py
InputsTest.test_faster_rcnn_resnet50_eval_input
test_faster_rcnn_resnet50_eval_input
Tests the eval input function for FasterRcnnResnet50.
[ "Tests", "the", "eval", "input", "function", "for", "FasterRcnnResnet50." ]
def test_faster_rcnn_resnet50_eval_input(self, eval_batch_size=1): configs = _get_configs_for_model('faster_rcnn_resnet50_pets') model_config = configs['model'] model_config.faster_rcnn.num_classes = 37 eval_config = configs['eval_config'] eval_config.batch_size = eval_batch_size eval_input_fn =...
['def', 'test_faster_rcnn_resnet50_eval_input(self,', 'eval_batch_size=1):', 'configs', '=', "_get_configs_for_model('faster_rcnn_resnet50_pets')", 'model_config', '=', "configs['model']", 'model_config.faster_rcnn.num_classes', '=', '37', 'eval_config', '=', "configs['eval_config']", 'eval_config.batch_size', '=', 'ev...
503,461
intel/neural-compressor
base.py
BasePattern.get_sparsity_ratio_each_layer
get_sparsity_ratio_each_layer
Calculate the sparsity ratio of each layer.
[ "Calculate", "the", "sparsity", "ratio", "of", "each", "layer." ]
def get_sparsity_ratio_each_layer(self, mask): raise NotImplementedError
['def', 'get_sparsity_ratio_each_layer(self,', 'mask):', 'raise', 'NotImplementedError']
738,141
weimin17/Object-Detection_HelmetDetection
word2vec.py
Word2Vec.eval
eval
Evaluate analogy questions and reports accuracy.
[ "Evaluate", "analogy", "questions", "and", "reports", "accuracy." ]
def eval(self): correct = 0 try: total = self._analogy_questions.shape[0] except AttributeError as e: raise AttributeError('Need to read analogy questions.') start = 0 while start < total: limit = start + 2500 sub = self._analogy_questions[start:limit, :] idx ...
['def', 'eval(self):', 'correct', '=', '0', 'try:', 'total', '=', 'self._analogy_questions.shape[0]', 'except', 'AttributeError', 'as', 'e:', 'raise', "AttributeError('Need", 'to', 'read', 'analogy', "questions.')", 'start', '=', '0', 'while', 'start', '<', 'total:', 'limit', '=', 'start', '+', '2500', 'sub', '=', 'sel...
760,880
lebrice/Sequoia
environment_test.py
TestPassiveEnvironment.test_observation_wrapper_applied_to_passive_environment
test_observation_wrapper_applied_to_passive_environment
Test that when we apply a gym wrapper to a PassiveEnvironment, it also affects the observations / actions / rewards produced when iterating on the env.
[ "Test", "that", "when", "we", "apply", "a", "gym", "wrapper", "to", "a", "PassiveEnvironment,", "it", "also", "affects", "the", "observations", "/", "actions", "/", "rewards", "produced", "when", "iterating", "on", "the", "env." ]
def test_observation_wrapper_applied_to_passive_environment(self): batch_size = 5 transforms = Compose([Transforms.to_tensor, Transforms.three_channels]) dataset = MNIST('data', transform=transforms) obs_space = Image(0, 255, (1, 28, 28), np.uint8) obs_space = transforms(obs_space) dataset.class...
['def', 'test_observation_wrapper_applied_to_passive_environment(self):', 'batch_size', '=', '5', 'transforms', '=', 'Compose([Transforms.to_tensor,', 'Transforms.three_channels])', 'dataset', '=', "MNIST('data',", 'transform=transforms)', 'obs_space', '=', 'Image(0,', '255,', '(1,', '28,', '28),', 'np.uint8)', 'obs_sp...
349,662
YanZiQinKevin/object_detection
c2.py
CudaDevice
CudaDevice
Create a Cuda device.
[ "Create", "a", "Cuda", "device." ]
def CudaDevice(gpu_id): return core.DeviceOption(caffe2_pb2.CUDA, gpu_id)
['def', 'CudaDevice(gpu_id):', 'return', 'core.DeviceOption(caffe2_pb2.CUDA,', 'gpu_id)']
773,238
weimin17/Object-Detection_HelmetDetection
dualnet.py
validate
validate
Perform model validation on the hold out data.
[ "Perform", "model", "validation", "on", "the", "hold", "out", "data." ]
def validate(working_dir, tf_records, params): estimator = tf.estimator.Estimator(dualnet_model.model_fn, model_dir=working_dir, params=params) def input_fn(): return preprocessing.get_input_tensors(params, params.batch_size, tf_records, filter_amount=0.05) estimator.evaluate(input_fn, steps=1000)
['def', 'validate(working_dir,', 'tf_records,', 'params):', 'estimator', '=', 'tf.estimator.Estimator(dualnet_model.model_fn,', 'model_dir=working_dir,', 'params=params)', 'def', 'input_fn():', 'return', 'preprocessing.get_input_tensors(params,', 'params.batch_size,', 'tf_records,', 'filter_amount=0.05)', 'estimator.ev...
758,128
YannDubs/Invariant-Self-Supervised-Learning
decorators.py
folder_split
folder_split
Split the dataset by the values in folder_col and call fn on each subfolder.
[ "Split", "the", "dataset", "by", "the", "values", "in", "folder_col", "and", "call", "fn", "on", "each", "subfolder." ]
def folder_split(fn): dflt_kwargs = get_default_args(fn) @functools.wraps(fn) def helper(self, *args, data=dflt_kwargs['data'], folder_col=dflt_kwargs['folder_col'], filename=dflt_kwargs['filename'], **kwargs): kws = ['folder_col'] for kw in kws: kwargs[kw] = eval(kw) if...
['def', 'folder_split(fn):', 'dflt_kwargs', '=', 'get_default_args(fn)', '@functools.wraps(fn)', 'def', 'helper(self,', '*args,', "data=dflt_kwargs['data'],", "folder_col=dflt_kwargs['folder_col'],", "filename=dflt_kwargs['filename'],", '**kwargs):', 'kws', '=', "['folder_col']", 'for', 'kw', 'in', 'kws:', 'kwargs[kw]'...
246,008
google-research/scenic
fashion_mnist_dataset.py
get_dataset
get_dataset
Returns generators for the fashion-MNIST train, validation, and test set.
[ "Returns", "generators", "for", "the", "fashion-MNIST", "train,", "validation,", "and", "test", "set." ]
def get_dataset(*, batch_size, eval_batch_size, num_shards, dtype_str='float32', shuffle_seed=0, rng=None, dataset_configs=None, dataset_service_address: Optional[str]=None): del rng del dataset_configs dtype = getattr(tf, dtype_str) preprocess_ex = functools.partial(preprocess_example, dtype=dtype) ...
['def', 'get_dataset(*,', 'batch_size,', 'eval_batch_size,', 'num_shards,', "dtype_str='float32',", 'shuffle_seed=0,', 'rng=None,', 'dataset_configs=None,', 'dataset_service_address:', 'Optional[str]=None):', 'del', 'rng', 'del', 'dataset_configs', 'dtype', '=', 'getattr(tf,', 'dtype_str)', 'preprocess_ex', '=', 'funct...
846,041
TrustAI/DeepConcolic
engine.py
Criterion.num_test_cases
num_test_cases
Returns the number of test cases.
[ "Returns", "the", "number", "of", "test", "cases." ]
def num_test_cases(self) -> int: return len(self.test_cases)
['def', 'num_test_cases(self)', '->', 'int:', 'return', 'len(self.test_cases)']
520,169
myothida/Supervised-Machine-Learning
transforms.py
BboxBase.max
max
The top-right corner of the bounding box.
[ "The", "top-right", "corner", "of", "the", "bounding", "box." ]
def max(self): return np.max(self.get_points(), axis=0)
['def', 'max(self):', 'return', 'np.max(self.get_points(),', 'axis=0)']
362,351
RasaHQ/rasa
mitie_tokenizer.py
MitieTokenizer.required_packages
required_packages
Any extra python dependencies required for this component to run.
[ "Any", "extra", "python", "dependencies", "required", "for", "this", "component", "to", "run." ]
def required_packages() -> List[Text]: return ['mitie']
['def', 'required_packages()', '->', 'List[Text]:', 'return', "['mitie']"]
837,314
open-mmlab/mmselfsup
swav_hook.py
SwAVHook.before_train_epoch
before_train_epoch
Check the queues' state.
[ "Check", "the", "queues'", "state." ]
def before_train_epoch(self, runner) -> None: if self.queue_length > 0 and runner.epoch >= self.epoch_queue_starts and (self.queue is None): self.queue = torch.zeros(len(self.crops_for_assign), self.queue_length // runner.world_size, self.feat_dim).cuda() get_model(runner.model).head.loss.queue = self.q...
['def', 'before_train_epoch(self,', 'runner)', '->', 'None:', 'if', 'self.queue_length', '>', '0', 'and', 'runner.epoch', '>=', 'self.epoch_queue_starts', 'and', '(self.queue', 'is', 'None):', 'self.queue', '=', 'torch.zeros(len(self.crops_for_assign),', 'self.queue_length', '//', 'runner.world_size,', 'self.feat_dim)....
240,334
DeepGraphLearning/torchdrug
molecule.py
Molecule.mol
mol
Context manager for molecule attributes.
[ "Context", "manager", "for", "molecule", "attributes." ]
def mol(self): return self.graph()
['def', 'mol(self):', 'return', 'self.graph()']
902,748
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
common_image_attention.py
dilated_attention_1d
dilated_attention_1d
Dilated 1d self attention.
[ "Dilated", "1d", "self", "attention." ]
def dilated_attention_1d(x, hparams, attention_type='masked_dilated_1d', q_padding='VALID', kv_padding='VALID', gap_size=2): (x, x_shape, is_4d) = maybe_reshape_4d_to_3d(x) with tf.variable_scope('masked_dilated_1d'): y = common_attention.multihead_attention(x, None, None, hparams.attention_key_channels...
['def', 'dilated_attention_1d(x,', 'hparams,', "attention_type='masked_dilated_1d',", "q_padding='VALID',", "kv_padding='VALID',", 'gap_size=2):', '(x,', 'x_shape,', 'is_4d)', '=', 'maybe_reshape_4d_to_3d(x)', 'with', "tf.variable_scope('masked_dilated_1d'):", 'y', '=', 'common_attention.multihead_attention(x,', 'None,...
965,213
FingerRec/Self-Supervised-Temporal-Discriminative-Representation--for-Video-Action-Recognition
clustering.py
make_graph
make_graph
Builds a graph of nearest neighbors.
[ "Builds", "a", "graph", "of", "nearest", "neighbors." ]
def make_graph(xb, nnn): (N, dim) = xb.shape res = faiss.StandardGpuResources() flat_config = faiss.GpuIndexFlatConfig() flat_config.device = int(torch.cuda.device_count()) - 1 index = faiss.GpuIndexFlatL2(res, dim, flat_config) index.add(xb) (D, I) = index.search(xb, nnn + 1) return (I,...
['def', 'make_graph(xb,', 'nnn):', '(N,', 'dim)', '=', 'xb.shape', 'res', '=', 'faiss.StandardGpuResources()', 'flat_config', '=', 'faiss.GpuIndexFlatConfig()', 'flat_config.device', '=', 'int(torch.cuda.device_count())', '-', '1', 'index', '=', 'faiss.GpuIndexFlatL2(res,', 'dim,', 'flat_config)', 'index.add(xb)', '(D,...
342,220
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.skin_bonenum
skin_bonenum
number of bones in skin (nskin x 1).
[ "number", "of", "bones", "in", "skin", "(nskin", "x", "1)." ]
def skin_bonenum(self): return util.buf_to_npy(self._ptr.contents.skin_bonenum, (self.nskin,))
['def', 'skin_bonenum(self):', 'return', 'util.buf_to_npy(self._ptr.contents.skin_bonenum,', '(self.nskin,))']
440,362
briannemsick/barrage
api.py
RecordTransformer.fit
fit
Fit transform to records.
[ "Fit", "transform", "to", "records." ]
def fit(self, records: Records): raise NotImplementedError()
['def', 'fit(self,', 'records:', 'Records):', 'raise', 'NotImplementedError()']
94,281
ylsung/Ladder-Side-Tuning
metrics.py
f1_score_with_invalid
f1_score_with_invalid
Computes F1 score, with any prediction != 0 or 1 is counted as incorrect.
[ "Computes", "F1", "score,", "with", "any", "prediction", "!=", "0", "or", "1", "is", "counted", "as", "incorrect." ]
def f1_score_with_invalid(predictions, targets) -> dict: def binary_reverse(labels): return ['0' if label == '1' else '1' for label in labels] (targets, predictions) = (np.asarray(targets), np.asarray(predictions)) invalid_idx_mask = np.logical_and(predictions != '0', predictions != '1') predic...
['def', 'f1_score_with_invalid(predictions,', 'targets)', '->', 'dict:', 'def', 'binary_reverse(labels):', 'return', "['0'", 'if', 'label', '==', "'1'", 'else', "'1'", 'for', 'label', 'in', 'labels]', '(targets,', 'predictions)', '=', '(np.asarray(targets),', 'np.asarray(predictions))', 'invalid_idx_mask', '=', 'np.log...
622,965
QData/deepWordBug
__init__.py
Component.supports
supports
Is `format` supported by this component? To be used by transforms to ask the dependent component if it supports a certain input context or output format.
[ "Is", "`format`", "supported", "by", "this", "component?", "To", "be", "used", "by", "transforms", "to", "ask", "the", "dependent", "component", "if", "it", "supports", "a", "certain", "input", "context", "or", "output", "format." ]
def supports(self, format): return format in self.supported
['def', 'supports(self,', 'format):', 'return', 'format', 'in', 'self.supported']
542,132
kengz/SLM-Lab
vec_env.py
dict_to_obs
dict_to_obs
Convert an observation dict into a raw array if the original observation space was not a Dict space.
[ "Convert", "an", "observation", "dict", "into", "a", "raw", "array", "if", "the", "original", "observation", "space", "was", "not", "a", "Dict", "space." ]
def dict_to_obs(obs_dict): if set(obs_dict.keys()) == {None}: return obs_dict[None] return obs_dict
['def', 'dict_to_obs(obs_dict):', 'if', 'set(obs_dict.keys())', '==', '{None}:', 'return', 'obs_dict[None]', 'return', 'obs_dict']
351,496
ryu-ed/SpaceInvaders_Ros
math2html.py
Bracket.innerliteral
innerliteral
Parse a literal inside the bracket, which does not generate HTML.
[ "Parse", "a", "literal", "inside", "the", "bracket,", "which", "does", "not", "generate", "HTML." ]
def innerliteral(self, pos): self.literal = '' while not pos.finished() and (not pos.current() == self.ending): if pos.current() == self.start: self.parseliteral(pos) else: self.literal += pos.skipcurrent() self.original += self.literal
['def', 'innerliteral(self,', 'pos):', 'self.literal', '=', "''", 'while', 'not', 'pos.finished()', 'and', '(not', 'pos.current()', '==', 'self.ending):', 'if', 'pos.current()', '==', 'self.start:', 'self.parseliteral(pos)', 'else:', 'self.literal', '+=', 'pos.skipcurrent()', 'self.original', '+=', 'self.literal']
395,188
open-mmlab/mmcv
wrappers.py
Compose.transform
transform
Call function to apply transforms sequentially.
[ "Call", "function", "to", "apply", "transforms", "sequentially." ]
def transform(self, results: Dict) -> Optional[Dict]: for t in self.transforms: results = t(results) if results is None: return None return results
['def', 'transform(self,', 'results:', 'Dict)', '->', 'Optional[Dict]:', 'for', 't', 'in', 'self.transforms:', 'results', '=', 't(results)', 'if', 'results', 'is', 'None:', 'return', 'None', 'return', 'results']
631,592
triaquae/triaquae
templates.py
TemplateCommand.extract
extract
Extracts the given file to a temporarily and returns the path of the directory with the extracted content.
[ "Extracts", "the", "given", "file", "to", "a", "temporarily", "and", "returns", "the", "path", "of", "the", "directory", "with", "the", "extracted", "content." ]
def extract(self, filename): prefix = 'django_%s_template_' % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract') self.paths_to_remove.append(tempdir) if self.verbosity >= 2: self.stdout.write('Extracting %s\n' % filename) try: archive.extract(filename, t...
['def', 'extract(self,', 'filename):', 'prefix', '=', "'django_%s_template_'", '%', 'self.app_or_project', 'tempdir', '=', 'tempfile.mkdtemp(prefix=prefix,', "suffix='_extract')", 'self.paths_to_remove.append(tempdir)', 'if', 'self.verbosity', '>=', '2:', "self.stdout.write('Extracting", "%s\\n'", '%', 'filename)', 'tr...
358,356
zhyhan/TransPar
mdd.py
GeneralModule.get_parameters
get_parameters
Return a parameters list which decides optimization hyper-parameters, such as the relative learning rate of each layer.
[ "Return", "a", "parameters", "list", "which", "decides", "optimization", "hyper-parameters,", "such", "as", "the", "relative", "learning", "rate", "of", "each", "layer." ]
def get_parameters(self, base_lr=1.0) -> List[Dict]: params = [{'params': self.backbone.parameters(), 'lr': 0.1 * base_lr if self.finetune else base_lr}, {'params': self.bottleneck.parameters(), 'lr': base_lr}, {'params': self.head.parameters(), 'lr': base_lr}, {'params': self.adv_head.parameters(), 'lr': base_lr}]...
['def', 'get_parameters(self,', 'base_lr=1.0)', '->', 'List[Dict]:', 'params', '=', "[{'params':", 'self.backbone.parameters(),', "'lr':", '0.1', '*', 'base_lr', 'if', 'self.finetune', 'else', 'base_lr},', "{'params':", 'self.bottleneck.parameters(),', "'lr':", 'base_lr},', "{'params':", 'self.head.parameters(),', "'lr...
356,101
huawei-noah/xingtian
tensorflow_fn.py
one_hot
one_hot
Take LongTensor with index values of shape.
[ "Take", "LongTensor", "with", "index", "values", "of", "shape." ]
def one_hot(inputs, num_classes): return tf.one_hot(inputs, num_classes)
['def', 'one_hot(inputs,', 'num_classes):', 'return', 'tf.one_hot(inputs,', 'num_classes)']
962,848
gunthercox/ChatterBot
mutable.py
Mutable.changed
changed
Subclasses should call this method whenever change events occur.
[ "Subclasses", "should", "call", "this", "method", "whenever", "change", "events", "occur." ]
def changed(self): for (parent, key) in self._parents.items(): flag_modified(parent, key)
['def', 'changed(self):', 'for', '(parent,', 'key)', 'in', 'self._parents.items():', 'flag_modified(parent,', 'key)']
481,101
kornia/kornia
so2.py
So2.random
random
Create a So2 group representing a random rotation.
[ "Create", "a", "So2", "group", "representing", "a", "random", "rotation." ]
def random(cls, batch_size: Optional[int]=None, device: Optional[Device]=None, dtype: Optional[Dtype]=None) -> So2: if batch_size is not None: KORNIA_CHECK(batch_size >= 1, msg='batch_size must be positive') real_data = rand((batch_size,), device=device, dtype=dtype) imag_data = rand((batch_...
['def', 'random(cls,', 'batch_size:', 'Optional[int]=None,', 'device:', 'Optional[Device]=None,', 'dtype:', 'Optional[Dtype]=None)', '->', 'So2:', 'if', 'batch_size', 'is', 'not', 'None:', 'KORNIA_CHECK(batch_size', '>=', '1,', "msg='batch_size", 'must', 'be', "positive')", 'real_data', '=', 'rand((batch_size,),', 'dev...
622,094
Ruturaj123/Flowchart-Detection
lstm2d.py
separable_lstm
separable_lstm
Run bidirectional LSTMs first horizontally then vertically.
[ "Run", "bidirectional", "LSTMs", "first", "horizontally", "then", "vertically." ]
def separable_lstm(images, num_filters_out, kernel_size=None, nhidden=None, scope=None): with variable_scope.variable_scope(scope, 'SeparableLstm', [images]): if nhidden is None: nhidden = num_filters_out if kernel_size is not None: images = get_blocks(images, kernel_size) ...
['def', 'separable_lstm(images,', 'num_filters_out,', 'kernel_size=None,', 'nhidden=None,', 'scope=None):', 'with', 'variable_scope.variable_scope(scope,', "'SeparableLstm',", '[images]):', 'if', 'nhidden', 'is', 'None:', 'nhidden', '=', 'num_filters_out', 'if', 'kernel_size', 'is', 'not', 'None:', 'images', '=', 'get_...
604,351
tobegit3hub/deep_image_model
event_multiplexer.py
EventMultiplexer.Scalars
Scalars
Retrieve the scalar events associated with a run and tag.
[ "Retrieve", "the", "scalar", "events", "associated", "with", "a", "run", "and", "tag." ]
def Scalars(self, run, tag): accumulator = self._GetAccumulator(run) return accumulator.Scalars(tag)
['def', 'Scalars(self,', 'run,', 'tag):', 'accumulator', '=', 'self._GetAccumulator(run)', 'return', 'accumulator.Scalars(tag)']
183,224
shery322/Lunar-Lander-ANN
cache.py
suppressed_cache_errors
suppressed_cache_errors
If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled.
[ "If", "we", "can't", "access", "the", "cache", "then", "we", "can", "just", "skip", "caching", "and", "process", "requests", "as", "if", "caching", "wasn't", "enabled." ]
def suppressed_cache_errors(): try: yield except (OSError, IOError): pass
['def', 'suppressed_cache_errors():', 'try:', 'yield', 'except', '(OSError,', 'IOError):', 'pass']
617,703
chrischoy/SpatioTemporalSegmentation
__init__.py
load_model
load_model
Creates and returns an instance of the model given its class name.
[ "Creates", "and", "returns", "an", "instance", "of", "the", "model", "given", "its", "class", "name." ]
def load_model(name): all_models = get_models() mdict = {model.__name__: model for model in all_models} if name not in mdict: print('Invalid model index. Options are:') for model in all_models: print('\t* {}'.format(model.__name__)) return None NetClass = mdict[name] ...
['def', 'load_model(name):', 'all_models', '=', 'get_models()', 'mdict', '=', '{model.__name__:', 'model', 'for', 'model', 'in', 'all_models}', 'if', 'name', 'not', 'in', 'mdict:', "print('Invalid", 'model', 'index.', 'Options', "are:')", 'for', 'model', 'in', 'all_models:', "print('\\t*", "{}'.format(model.__name__))"...
894,768
43Carrig/recurrent_neural_networks_practice
gen_dataset_ops.py
iterator_get_next_as_optional
iterator_get_next_as_optional
Gets the next output from the given iterator as an Optional variant.
[ "Gets", "the", "next", "output", "from", "the", "given", "iterator", "as", "an", "Optional", "variant." ]
def iterator_get_next_as_optional(iterator, output_types, output_shapes, name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(output_types, (list, tuple)): raise TypeError("Expected list for 'output_types' argument to 'iterator_get_next_...
['def', 'iterator_get_next_as_optional(iterator,', 'output_types,', 'output_shapes,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(output_types,', '(list,', 'tuple)):', 'raise', 'TypeError("Expected', 'list', 'for', "...
337,585
Shubham-786/Natural-Language-Processing
utils.py
train_supervised_model
train_supervised_model
Build a supervised keyphrase extraction model from a set of documents and a reference file.
[ "Build", "a", "supervised", "keyphrase", "extraction", "model", "from", "a", "set", "of", "documents", "and", "a", "reference", "file." ]
def train_supervised_model(input_dir, reference_file, model_file, extension='xml', language='en', normalization='stemming', df=None, model=None, sep_doc_id=':', sep_ref_keyphrases=',', normalize_reference=False, leave_one_out=False, encoding=None, ref_encoding=None): logging.info('building model {} from {}'.format(...
['def', 'train_supervised_model(input_dir,', 'reference_file,', 'model_file,', "extension='xml',", "language='en',", "normalization='stemming',", 'df=None,', 'model=None,', "sep_doc_id=':',", "sep_ref_keyphrases=',',", 'normalize_reference=False,', 'leave_one_out=False,', 'encoding=None,', 'ref_encoding=None):', "loggi...
638,870
tensorflow/agents
drifting_linear_environment_test.py
DriftingLinearEnvironmentTest.testObservationToRewardsVaries
testObservationToRewardsVaries
Ensure that `observation_to_reward` changes with non-zero drift.
[ "Ensure", "that", "`observation_to_reward`", "changes", "with", "non-zero", "drift." ]
def testObservationToRewardsVaries(self, observation_shape, action_shape, batch_size, seed): tf.compat.v1.set_random_seed(seed) env = get_deterministic_gaussian_non_stationary_environment(observation_shape, action_shape, batch_size, drift_mean=1.0, drift_scale=1.0) self.evaluate(tf.compat.v1.global_variable...
['def', 'testObservationToRewardsVaries(self,', 'observation_shape,', 'action_shape,', 'batch_size,', 'seed):', 'tf.compat.v1.set_random_seed(seed)', 'env', '=', 'get_deterministic_gaussian_non_stationary_environment(observation_shape,', 'action_shape,', 'batch_size,', 'drift_mean=1.0,', 'drift_scale=1.0)', 'self.evalu...
23,286
mj-love-life/Artificial-Intelligence
search.py
print_boggle
print_boggle
Print the board in a 2-d array.
[ "Print", "the", "board", "in", "a", "2-d", "array." ]
def print_boggle(board): n2 = len(board) n = exact_sqrt(n2) for i in range(n2): if i % n == 0 and i > 0: print() if board[i] == 'Q': print('Qu', end=' ') else: print(str(board[i]) + ' ', end=' ') print()
['def', 'print_boggle(board):', 'n2', '=', 'len(board)', 'n', '=', 'exact_sqrt(n2)', 'for', 'i', 'in', 'range(n2):', 'if', 'i', '%', 'n', '==', '0', 'and', 'i', '>', '0:', 'print()', 'if', 'board[i]', '==', "'Q':", "print('Qu',", "end='", "')", 'else:', 'print(str(board[i])', '+', "'", "',", "end='", "')", 'print()']
116,205
juaml/julearn
test_available_models.py
test_register_warning
test_register_warning
Test the register model function warnings.
[ "Test", "the", "register", "model", "function", "warnings." ]
def test_register_warning() -> None: with pytest.warns(RuntimeWarning, match='Model name'): register_model('rf', regression_cls=RandomForestRegressor) reset_model_register() with pytest.raises(ValueError, match='Model name'): register_model('rf', regression_cls=RandomForestRegressor, overwri...
['def', 'test_register_warning()', '->', 'None:', 'with', 'pytest.warns(RuntimeWarning,', "match='Model", "name'):", "register_model('rf',", 'regression_cls=RandomForestRegressor)', 'reset_model_register()', 'with', 'pytest.raises(ValueError,', "match='Model", "name'):", "register_model('rf',", 'regression_cls=RandomFo...
593,637
TrellixVulnTeam/Unsupervised_Learning_HFI7
managers.py
SingleBlockManager.from_blocks
from_blocks
Constructor for BlockManager and SingleBlockManager with same signature.
[ "Constructor", "for", "BlockManager", "and", "SingleBlockManager", "with", "same", "signature." ]
def from_blocks(cls, blocks: List[Block], axes: List[Index]) -> 'SingleBlockManager': assert len(blocks) == 1 assert len(axes) == 1 return cls(blocks[0], axes[0], do_integrity_check=False)
['def', 'from_blocks(cls,', 'blocks:', 'List[Block],', 'axes:', 'List[Index])', '->', "'SingleBlockManager':", 'assert', 'len(blocks)', '==', '1', 'assert', 'len(axes)', '==', '1', 'return', 'cls(blocks[0],', 'axes[0],', 'do_integrity_check=False)']
453,300
pramodiperera/virtual-keyboard
__init__.py
enabled
enabled
Allow selection of distutils by environment variable.
[ "Allow", "selection", "of", "distutils", "by", "environment", "variable." ]
def enabled(): which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') return which == 'local'
['def', 'enabled():', 'which', '=', "os.environ.get('SETUPTOOLS_USE_DISTUTILS',", "'stdlib')", 'return', 'which', '==', "'local'"]
933,483
wandb/wandb
wandb_watch.py
unwatch
unwatch
Remove pytorch model topology, gradient and parameter hooks.
[ "Remove", "pytorch", "model", "topology,", "gradient", "and", "parameter", "hooks." ]
def unwatch(models=None): if models: if not isinstance(models, (tuple, list)): models = (models,) for model in models: if not hasattr(model, '_wandb_hook_names'): wandb.termwarn('%s model has not been watched' % model) else: for nam...
['def', 'unwatch(models=None):', 'if', 'models:', 'if', 'not', 'isinstance(models,', '(tuple,', 'list)):', 'models', '=', '(models,)', 'for', 'model', 'in', 'models:', 'if', 'not', 'hasattr(model,', "'_wandb_hook_names'):", "wandb.termwarn('%s", 'model', 'has', 'not', 'been', "watched'", '%', 'model)', 'else:', 'for', ...
941,607
vinits5/pc_autoencoder
tf_util.py
batch_norm_for_conv1d
batch_norm_for_conv1d
Batch normalization on 1D convolutional maps.
[ "Batch", "normalization", "on", "1D", "convolutional", "maps." ]
def batch_norm_for_conv1d(inputs, is_training, bn_decay, scope): return batch_norm_template(inputs, is_training, scope, [0, 1], bn_decay)
['def', 'batch_norm_for_conv1d(inputs,', 'is_training,', 'bn_decay,', 'scope):', 'return', 'batch_norm_template(inputs,', 'is_training,', 'scope,', '[0,', '1],', 'bn_decay)']
765,815
taishi-i/nagisa
tagger.py
Tagger.extract
extract
Return the extracted words with POS-tags of the given sentence.
[ "Return", "the", "extracted", "words", "with", "POS-tags", "of", "the", "given", "sentence." ]
def extract(self, text, lower=False, extract_postags=None): if extract_postags is None: extract_postags = [] words = [] postags = [] tokens = self.tagging(text, lower) for (word, postag) in zip(tokens.words, tokens.postags): if postag in extract_postags: words.append(word...
['def', 'extract(self,', 'text,', 'lower=False,', 'extract_postags=None):', 'if', 'extract_postags', 'is', 'None:', 'extract_postags', '=', '[]', 'words', '=', '[]', 'postags', '=', '[]', 'tokens', '=', 'self.tagging(text,', 'lower)', 'for', '(word,', 'postag)', 'in', 'zip(tokens.words,', 'tokens.postags):', 'if', 'pos...
291,119
43Carrig/recurrent_neural_networks_practice
data.py
get_shift_reduce
get_shift_reduce
Obtain shift-reduce vector from a list of items from the SNLI data.
[ "Obtain", "shift-reduce", "vector", "from", "a", "list", "of", "items", "from", "the", "SNLI", "data." ]
def get_shift_reduce(items): trans = [] for item in items: if item == LEFT_PAREN: continue elif item == RIGHT_PAREN: trans.append(REDUCE_CODE) else: trans.append(SHIFT_CODE) return trans
['def', 'get_shift_reduce(items):', 'trans', '=', '[]', 'for', 'item', 'in', 'items:', 'if', 'item', '==', 'LEFT_PAREN:', 'continue', 'elif', 'item', '==', 'RIGHT_PAREN:', 'trans.append(REDUCE_CODE)', 'else:', 'trans.append(SHIFT_CODE)', 'return', 'trans']
313,009
fpaupier/tensorflow-serving_sidecar
coco_evaluation_test.py
CocoDetectionEvaluationTest.testRejectionOnDuplicateDetections
testRejectionOnDuplicateDetections
Tests that detections cannot be added more than once for an image.
[ "Tests", "that", "detections", "cannot", "be", "added", "more", "than", "once", "for", "an", "image." ]
def testRejectionOnDuplicateDetections(self): coco_evaluator = coco_evaluation.CocoDetectionEvaluator(_get_categories_list()) coco_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes: np.array([[99.0, 100.0, 200.0, 200.0]]), standar...
['def', 'testRejectionOnDuplicateDetections(self):', 'coco_evaluator', '=', 'coco_evaluation.CocoDetectionEvaluator(_get_categories_list())', "coco_evaluator.add_single_ground_truth_image_info(image_id='image1',", 'groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes:', 'np.array([[99.0,', '100.0,', '200...
922,068
matsu0228/nlp-jp
connection.py
FPSConnection.get_tokens
get_tokens
Returns a list of tokens installed on the given account.
[ "Returns", "a", "list", "of", "tokens", "installed", "on", "the", "given", "account." ]
def get_tokens(self, action, response, **kw): return self.get_object(action, kw, response)
['def', 'get_tokens(self,', 'action,', 'response,', '**kw):', 'return', 'self.get_object(action,', 'kw,', 'response)']
784,634
Ruturaj123/Flowchart-Detection
training_ops_test.py
GrowTreeEnsembleOpTest.testGrowExistingEnsembleTreeFinalizedWithDropout
testGrowExistingEnsembleTreeFinalizedWithDropout
Test growing an existing ensemble with the last tree finalized.
[ "Test", "growing", "an", "existing", "ensemble", "with", "the", "last", "tree", "finalized." ]
def testGrowExistingEnsembleTreeFinalizedWithDropout(self): with self.test_session() as session: tree_ensemble_config = tree_config_pb2.DecisionTreeEnsembleConfig() text_format.Merge('\n trees {\n nodes {\n leaf {\n vector {\n value: -0.32\n ...
['def', 'testGrowExistingEnsembleTreeFinalizedWithDropout(self):', 'with', 'self.test_session()', 'as', 'session:', 'tree_ensemble_config', '=', 'tree_config_pb2.DecisionTreeEnsembleConfig()', "text_format.Merge('\\n", 'trees', '{\\n', 'nodes', '{\\n', 'leaf', '{\\n', 'vector', '{\\n', 'value:', '-0.32\\n', 'value:', '...
586,875
googleapis/python-aiplatform
client.py
JobServiceClient.data_labeling_job_path
data_labeling_job_path
Returns a fully-qualified data_labeling_job string.
[ "Returns", "a", "fully-qualified", "data_labeling_job", "string." ]
def data_labeling_job_path(project: str, location: str, data_labeling_job: str) -> str: return 'projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}'.format(project=project, location=location, data_labeling_job=data_labeling_job)
['def', 'data_labeling_job_path(project:', 'str,', 'location:', 'str,', 'data_labeling_job:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}'.format(project=project,", 'location=location,', 'data_labeling_job=data_labeling_job)']
813,045
gunthercox/ChatterBot
fst.py
Values.add
add
Adds the given prefix (the result of a call to common()) to the given value.
[ "Adds", "the", "given", "prefix", "(the", "result", "of", "a", "call", "to", "common())", "to", "the", "given", "value." ]
def add(prefix, v): raise NotImplementedError
['def', 'add(prefix,', 'v):', 'raise', 'NotImplementedError']
526,612
RLE-Foundation/rllte
logger.py
Logger.train
train
Output msg with 'train' level.
[ "Output", "msg", "with", "'train'", "level." ]
def train(self, msg: Dict) -> None: print(self.time_stamp + TRAIN_PREFIX + self.parse_train_msg(msg)) self._dump_to_csv(self._train_file, msg, self._train_file_write_header) self._train_file_write_header = False
['def', 'train(self,', 'msg:', 'Dict)', '->', 'None:', 'print(self.time_stamp', '+', 'TRAIN_PREFIX', '+', 'self.parse_train_msg(msg))', 'self._dump_to_csv(self._train_file,', 'msg,', 'self._train_file_write_header)', 'self._train_file_write_header', '=', 'False']
333,480
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
transform_util.py
TransformUtil.remove_punctuation
remove_punctuation
Removes !, #, and ?.
[ "Removes", "!,", "#,", "and", "?." ]
def remove_punctuation(cls, value): return re.sub('[!#?]', '', value)
['def', 'remove_punctuation(cls,', 'value):', 'return', "re.sub('[!#?]',", "'',", 'value)']
18,302
43Carrig/recurrent_neural_networks_practice
control_flow_ops.py
from_control_flow_context_def
from_control_flow_context_def
Deserializes `context_def` into the appropriate ControlFlowContext.
[ "Deserializes", "`context_def`", "into", "the", "appropriate", "ControlFlowContext." ]
def from_control_flow_context_def(context_def, import_scope=None): if context_def.HasField('cond_ctxt'): return CondContext.from_proto(context_def.cond_ctxt, import_scope=import_scope) if context_def.HasField('while_ctxt'): return WhileContext.from_proto(context_def.while_ctxt, import_scope=impo...
['def', 'from_control_flow_context_def(context_def,', 'import_scope=None):', 'if', "context_def.HasField('cond_ctxt'):", 'return', 'CondContext.from_proto(context_def.cond_ctxt,', 'import_scope=import_scope)', 'if', "context_def.HasField('while_ctxt'):", 'return', 'WhileContext.from_proto(context_def.while_ctxt,', 'imp...
337,132
salesforce/CodeRL
squad.py
SquadProcessor.get_dev_examples
get_dev_examples
Returns the evaluation example from the data directory.
[ "Returns", "the", "evaluation", "example", "from", "the", "data", "directory." ]
def get_dev_examples(self, data_dir, filename=None): if data_dir is None: data_dir = '' if self.dev_file is None: raise ValueError('SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor') with open(os.path.join(data_dir, self.dev_file if filename is None else filenam...
['def', 'get_dev_examples(self,', 'data_dir,', 'filename=None):', 'if', 'data_dir', 'is', 'None:', 'data_dir', '=', "''", 'if', 'self.dev_file', 'is', 'None:', 'raise', "ValueError('SquadProcessor", 'should', 'be', 'instantiated', 'via', 'SquadV1Processor', 'or', "SquadV2Processor')", 'with', 'open(os.path.join(data_di...
494,260
GuoleiSun/VSS-CFFM
transforms.py
PhotoMetricDistortion_clips2.convert
convert
Multiple with alpha and add beat with clip.
[ "Multiple", "with", "alpha", "and", "add", "beat", "with", "clip." ]
def convert(self, img, alpha=1, beta=0): img = img.astype(np.float32) * alpha + beta img = np.clip(img, 0, 255) return img.astype(np.uint8)
['def', 'convert(self,', 'img,', 'alpha=1,', 'beta=0):', 'img', '=', 'img.astype(np.float32)', '*', 'alpha', '+', 'beta', 'img', '=', 'np.clip(img,', '0,', '255)', 'return', 'img.astype(np.uint8)']
940,313
jxhe/unify-parameter-efficient-tuning
modeling_funnel.py
FunnelAttentionStructure.token_type_ids_to_mat
token_type_ids_to_mat
Convert `token_type_ids` to `token_type_mat`.
[ "Convert", "`token_type_ids`", "to", "`token_type_mat`." ]
def token_type_ids_to_mat(self, token_type_ids): token_type_mat = token_type_ids[:, :, None] == token_type_ids[:, None] cls_ids = token_type_ids == self.cls_token_type_id cls_mat = cls_ids[:, :, None] | cls_ids[:, None] return cls_mat | token_type_mat
['def', 'token_type_ids_to_mat(self,', 'token_type_ids):', 'token_type_mat', '=', 'token_type_ids[:,', ':,', 'None]', '==', 'token_type_ids[:,', 'None]', 'cls_ids', '=', 'token_type_ids', '==', 'self.cls_token_type_id', 'cls_mat', '=', 'cls_ids[:,', ':,', 'None]', '|', 'cls_ids[:,', 'None]', 'return', 'cls_mat', '|', '...
948,882
microsoft/InnerEye-DeepLearning
image_util.py
apply_slice_exclusion_rules
apply_slice_exclusion_rules
Applies each slice exclusion rule to segmentation, modifying it in place.
[ "Applies", "each", "slice", "exclusion", "rule", "to", "segmentation,", "modifying", "it", "in", "place." ]
def apply_slice_exclusion_rules(model_config: SegmentationModelBase, segmentation: np.ndarray) -> np.ndarray: if model_config.slice_exclusion_rules is None: return segmentation for rule in model_config.slice_exclusion_rules: rule.validate(model_config.ground_truth_ids) higher_class_label...
['def', 'apply_slice_exclusion_rules(model_config:', 'SegmentationModelBase,', 'segmentation:', 'np.ndarray)', '->', 'np.ndarray:', 'if', 'model_config.slice_exclusion_rules', 'is', 'None:', 'return', 'segmentation', 'for', 'rule', 'in', 'model_config.slice_exclusion_rules:', 'rule.validate(model_config.ground_truth_id...
613,306
tinazhouhui/computer_vision
cpp_lint.py
_CppLintState.PrintErrorCounts
PrintErrorCounts
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category,", "and", "the", "total." ]
def PrintErrorCounts(self): for (category, count) in self.errors_by_category.iteritems(): sys.stderr.write("Category '%s' errors found: %d\n" % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
['def', 'PrintErrorCounts(self):', 'for', '(category,', 'count)', 'in', 'self.errors_by_category.iteritems():', 'sys.stderr.write("Category', "'%s'", 'errors', 'found:', '%d\\n"', '%', '(category,', 'count))', "sys.stderr.write('Total", 'errors', 'found:', "%d\\n'", '%', 'self.error_count)']
473,092
TrellixVulnTeam/Unsupervised_Learning_HFI7
backend_bases.py
GraphicsContextBase.get_alpha
get_alpha
Return the alpha value used for blending - not supported on all backends.
[ "Return", "the", "alpha", "value", "used", "for", "blending", "-", "not", "supported", "on", "all", "backends." ]
def get_alpha(self): return self._alpha
['def', 'get_alpha(self):', 'return', 'self._alpha']
450,115
intel/neural-compressor
onnxrt.py
ONNXRT_WeightOnlyAdaptor.quantize
quantize
The function is used to do calibration and quanitization in post-training quantization.
[ "The", "function", "is", "used", "to", "do", "calibration", "and", "quanitization", "in", "post-training", "quantization." ]
def quantize(self, tune_cfg, model, data_loader, q_func=None): assert q_func is None, 'quantization aware training has not been supported on ONNXRUNTIME' for precision in self.query_handler.get_precisions(): if precision == 'weight_only_integer': self.quantizable_op_types += self.query_handl...
['def', 'quantize(self,', 'tune_cfg,', 'model,', 'data_loader,', 'q_func=None):', 'assert', 'q_func', 'is', 'None,', "'quantization", 'aware', 'training', 'has', 'not', 'been', 'supported', 'on', "ONNXRUNTIME'", 'for', 'precision', 'in', 'self.query_handler.get_precisions():', 'if', 'precision', '==', "'weight_only_int...
737,344
thaines/helit
multiclass.py
MultiModel.classify
classify
Classifies a single feature vector - returns the most likelly label.
[ "Classifies", "a", "single", "feature", "vector", "-", "returns", "the", "most", "likelly", "label." ]
def classify(self, feature): if self.weightSVM: cost = numpy.zeros(len(self.labels), dtype=numpy.float_) for (lNeg, lPos) in self.models.keys(): m = self.models[lNeg, lPos] cg = -math.log(max((m[0], 0.001))) cb = -math.log(max((1.0 - m[0], 0.001))) val...
['def', 'classify(self,', 'feature):', 'if', 'self.weightSVM:', 'cost', '=', 'numpy.zeros(len(self.labels),', 'dtype=numpy.float_)', 'for', '(lNeg,', 'lPos)', 'in', 'self.models.keys():', 'm', '=', 'self.models[lNeg,', 'lPos]', 'cg', '=', '-math.log(max((m[0],', '0.001)))', 'cb', '=', '-math.log(max((1.0', '-', 'm[0],'...
592,504
yinyunie/ScenePriors
textures.py
TexturesAtlas.join_scene
join_scene
Return a new TexturesAtlas amalgamating the batch.
[ "Return", "a", "new", "TexturesAtlas", "amalgamating", "the", "batch." ]
def join_scene(self) -> 'TexturesAtlas': return self.__class__(atlas=[torch.cat(self.atlas_list())])
['def', 'join_scene(self)', '->', "'TexturesAtlas':", 'return', 'self.__class__(atlas=[torch.cat(self.atlas_list())])']
329,889
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
cloud_mlengine.py
validate_flags
validate_flags
Validates flags are set to acceptable values for CloudML Engine runs.
[ "Validates", "flags", "are", "set", "to", "acceptable", "values", "for", "CloudML", "Engine", "runs." ]
def validate_flags(): assert not FLAGS.cloud_tpu assert not job_dir() assert FLAGS.output_dir.startswith('gs://') assert FLAGS.data_dir.startswith('gs://') assert FLAGS.worker_replicas <= 1 assert FLAGS.ps_replicas <= 0 if FLAGS.hparams_range: assert FLAGS.autotune_objective if F...
['def', 'validate_flags():', 'assert', 'not', 'FLAGS.cloud_tpu', 'assert', 'not', 'job_dir()', 'assert', "FLAGS.output_dir.startswith('gs://')", 'assert', "FLAGS.data_dir.startswith('gs://')", 'assert', 'FLAGS.worker_replicas', '<=', '1', 'assert', 'FLAGS.ps_replicas', '<=', '0', 'if', 'FLAGS.hparams_range:', 'assert',...
966,064