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
tensorflow/quantum
cirq_ops_test.py
CirqSampledExpectationTest.test_sampled_expectation_no_circuit
test_sampled_expectation_no_circuit
Test empty tensors with no circuits at all.
[ "Test", "empty", "tensors", "with", "no", "circuits", "at", "all." ]
def test_sampled_expectation_no_circuit(self): test_op = cirq_ops._get_cirq_sampled_expectation(cirq.Simulator()) empty_programs = tf.raw_ops.Empty(shape=(0,), dtype=tf.string) empty_values = tf.raw_ops.Empty(shape=(0, 0), dtype=tf.float32) empty_paulis = tf.raw_ops.Empty(shape=(0, 0), dtype=tf.string) ...
['def', 'test_sampled_expectation_no_circuit(self):', 'test_op', '=', 'cirq_ops._get_cirq_sampled_expectation(cirq.Simulator())', 'empty_programs', '=', 'tf.raw_ops.Empty(shape=(0,),', 'dtype=tf.string)', 'empty_values', '=', 'tf.raw_ops.Empty(shape=(0,', '0),', 'dtype=tf.float32)', 'empty_paulis', '=', 'tf.raw_ops.Emp...
834,656
ArdaGunay99/Key_Detection_Unsupervised_Learning
textpath.py
TextToPath.get_glyphs_tex
get_glyphs_tex
Convert the string *s* to vertices and codes using usetex mode.
[ "Convert", "the", "string", "*s*", "to", "vertices", "and", "codes", "using", "usetex", "mode." ]
def get_glyphs_tex(self, prop, s, glyph_map=None, return_new_glyphs_only=False): dvifile = self.get_texmanager().make_dvi(s, self.FONT_SCALE) with dviread.Dvi(dvifile, self.DPI) as dvi: (page,) = dvi if glyph_map is None: glyph_map = OrderedDict() if return_new_glyphs_only: glyph...
['def', 'get_glyphs_tex(self,', 'prop,', 's,', 'glyph_map=None,', 'return_new_glyphs_only=False):', 'dvifile', '=', 'self.get_texmanager().make_dvi(s,', 'self.FONT_SCALE)', 'with', 'dviread.Dvi(dvifile,', 'self.DPI)', 'as', 'dvi:', '(page,)', '=', 'dvi', 'if', 'glyph_map', 'is', 'None:', 'glyph_map', '=', 'OrderedDict(...
257,304
ChenhongyiYang/PPAL
vfnet_head.py
VFNetHead.num_anchors
num_anchors
Returns: int: Number of anchors on each point of feature map.
[ "Returns:", "int:", "Number", "of", "anchors", "on", "each", "point", "of", "feature", "map." ]
def num_anchors(self): warnings.warn('DeprecationWarning: `num_anchors` is deprecated, please use "num_base_priors" instead') return self.num_base_priors
['def', 'num_anchors(self):', "warnings.warn('DeprecationWarning:", '`num_anchors`', 'is', 'deprecated,', 'please', 'use', '"num_base_priors"', "instead')", 'return', 'self.num_base_priors']
821,607
wutong8023/CoLL
optimization.py
get_linear_schedule_with_warmup
get_linear_schedule_with_warmup
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
[ "Create", "a", "schedule", "with", "a", "learning", "rate", "that", "decreases", "linearly", "from", "the", "initial", "lr", "set", "in", "the", "optimizer", "to", "0,", "after", "a", "warmup", "period", "during", "which", "it", "increases", "linearly", "fro...
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max(0.0, float(num_training_steps - current_step...
['def', 'get_linear_schedule_with_warmup(optimizer,', 'num_warmup_steps,', 'num_training_steps,', 'last_epoch=-1):', 'def', 'lr_lambda(current_step:', 'int):', 'if', 'current_step', '<', 'num_warmup_steps:', 'return', 'float(current_step)', '/', 'float(max(1,', 'num_warmup_steps))', 'return', 'max(0.0,', 'float(num_tra...
496,374
AboudyKreidieh/h-baselines
test_goal_conditioned.py
TestSACGoalConditionedPolicy.test_cooperative_gradients
test_cooperative_gradients
Check the functionality of the cooperative-gradients feature.
[ "Check", "the", "functionality", "of", "the", "cooperative-gradients", "feature." ]
def test_cooperative_gradients(self): policy = SACGoalConditionedPolicy(**self.policy_params) self.assertRaises(NotImplementedError, policy._cooperative_gradients_update, obs0=None, actions=None, rewards=None, obs1=None, terminals1=None, level_num=None)
['def', 'test_cooperative_gradients(self):', 'policy', '=', 'SACGoalConditionedPolicy(**self.policy_params)', 'self.assertRaises(NotImplementedError,', 'policy._cooperative_gradients_update,', 'obs0=None,', 'actions=None,', 'rewards=None,', 'obs1=None,', 'terminals1=None,', 'level_num=None)']
574,104
devashish-patel/webcam-motion-detector
test_figure.py
TestMarkers.test_mixed_inputs
test_mixed_inputs
Helper method to test mixed global and specific color args.
[ "Helper", "method", "to", "test", "mixed", "global", "and", "specific", "color", "args." ]
def test_mixed_inputs(self): p = plt.figure() rgb = (100, 0, 0) rgb_other = (0, 100, 0) alpha1 = 0.5 alpha2 = 0.75 p.circle([1, 2, 3], [1, 2, 3], color=rgb, line_color=rgb_other) self.assertTupleEqual(p.renderers[-1].glyph.fill_color, rgb) self.assertTupleEqual(p.renderers[-1].glyph.line...
['def', 'test_mixed_inputs(self):', 'p', '=', 'plt.figure()', 'rgb', '=', '(100,', '0,', '0)', 'rgb_other', '=', '(0,', '100,', '0)', 'alpha1', '=', '0.5', 'alpha2', '=', '0.75', 'p.circle([1,', '2,', '3],', '[1,', '2,', '3],', 'color=rgb,', 'line_color=rgb_other)', 'self.assertTupleEqual(p.renderers[-1].glyph.fill_col...
977,422
DPerrySvendsen/COS30002
path.py
Path.current_pt
current_pt
Return the way point of the path indicated by the current point index.
[ "Return", "the", "way", "point", "of", "the", "path", "indicated", "by", "the", "current", "point", "index." ]
def current_pt(self): return self._pts[self._cur_pt_idx]
['def', 'current_pt(self):', 'return', 'self._pts[self._cur_pt_idx]']
137,358
rudranil723/mini-main
test_seed_sequence.py
test_zero_padding
test_zero_padding
Ensure that the implicit zero-padding does not cause problems.
[ "Ensure", "that", "the", "implicit", "zero-padding", "does", "not", "cause", "problems." ]
def test_zero_padding(): ss0 = SeedSequence(42) ss1 = SeedSequence(42 << 32) assert_array_compare(np.not_equal, ss0.generate_state(4), ss1.generate_state(4)) expected42 = np.array([3444837047, 2669555309, 2046530742, 3581440988], dtype=np.uint32) assert_array_equal(SeedSequence(42).generate_state(4)...
['def', 'test_zero_padding():', 'ss0', '=', 'SeedSequence(42)', 'ss1', '=', 'SeedSequence(42', '<<', '32)', 'assert_array_compare(np.not_equal,', 'ss0.generate_state(4),', 'ss1.generate_state(4))', 'expected42', '=', 'np.array([3444837047,', '2669555309,', '2046530742,', '3581440988],', 'dtype=np.uint32)', 'assert_arra...
322,997
fcjian/TOOD
test_dense_heads_attr.py
test_dense_heads_test_attr
test_dense_heads_test_attr
Tests inference methods such as simple_test and aug_test.
[ "Tests", "inference", "methods", "such", "as", "simple_test", "and", "aug_test." ]
def test_dense_heads_test_attr(): exceptions = ['FeatureAdaption'] all_dense_heads = [m for m in dense_heads.__all__ if m not in exceptions] check_attributes = ['simple_test', 'aug_test', 'simple_test_bboxes', 'simple_test_rpn', 'aug_test_rpn'] table_header = ['head name'] + check_attributes table_d...
['def', 'test_dense_heads_test_attr():', 'exceptions', '=', "['FeatureAdaption']", 'all_dense_heads', '=', '[m', 'for', 'm', 'in', 'dense_heads.__all__', 'if', 'm', 'not', 'in', 'exceptions]', 'check_attributes', '=', "['simple_test',", "'aug_test',", "'simple_test_bboxes',", "'simple_test_rpn',", "'aug_test_rpn']", 't...
902,315
TrellixVulnTeam/Unsupervised_Learning_HFI7
tags.py
interpreter_name
interpreter_name
Returns the name of the running interpreter.
[ "Returns", "the", "name", "of", "the", "running", "interpreter." ]
def interpreter_name(): try: name = sys.implementation.name except AttributeError: name = platform.python_implementation().lower() return INTERPRETER_SHORT_NAMES.get(name) or name
['def', 'interpreter_name():', 'try:', 'name', '=', 'sys.implementation.name', 'except', 'AttributeError:', 'name', '=', 'platform.python_implementation().lower()', 'return', 'INTERPRETER_SHORT_NAMES.get(name)', 'or', 'name']
452,391
rlberry-py/rlberry
mdqn.py
default_q_net_fn
default_q_net_fn
Returns a default Q value network.
[ "Returns", "a", "default", "Q", "value", "network." ]
def default_q_net_fn(env, **kwargs): del kwargs model_config = {'type': 'MultiLayerPerceptron', 'layer_sizes': (64, 64), 'reshape': False} model_config = size_model_config(env, **model_config) return model_factory(**model_config)
['def', 'default_q_net_fn(env,', '**kwargs):', 'del', 'kwargs', 'model_config', '=', "{'type':", "'MultiLayerPerceptron',", "'layer_sizes':", '(64,', '64),', "'reshape':", 'False}', 'model_config', '=', 'size_model_config(env,', '**model_config)', 'return', 'model_factory(**model_config)']
862,081
mkusner/grammarVAE
test_basic.py
T_Join_and_Split.test_broadcastable_flag_assignment_mixed_otheraxes
test_broadcastable_flag_assignment_mixed_otheraxes
Test that the broadcastable flags for the output of a join operation on non-join axes are True if one or more inputs is broadcastable on that dimension.
[ "Test", "that", "the", "broadcastable", "flags", "for", "the", "output", "of", "a", "join", "operation", "on", "non-join", "axes", "are", "True", "if", "one", "or", "more", "inputs", "is", "broadcastable", "on", "that", "dimension." ]
def test_broadcastable_flag_assignment_mixed_otheraxes(self): rng = numpy.random.RandomState(seed=utt.fetch_seed()) a_val = rng.rand(1, 4, 1).astype(self.floatX) b_val = rng.rand(1, 3, 1).astype(self.floatX) a = self.shared(a_val, broadcastable=(False, False, True)) b = self.shared(b_val, broadcasta...
['def', 'test_broadcastable_flag_assignment_mixed_otheraxes(self):', 'rng', '=', 'numpy.random.RandomState(seed=utt.fetch_seed())', 'a_val', '=', 'rng.rand(1,', '4,', '1).astype(self.floatX)', 'b_val', '=', 'rng.rand(1,', '3,', '1).astype(self.floatX)', 'a', '=', 'self.shared(a_val,', 'broadcastable=(False,', 'False,',...
580,146
vturrisi/solo-learn
nnclr.py
nnclr_loss_func
nnclr_loss_func
Computes NNCLR's loss given batch of nearest-neighbors nn from view 1 and predicted features p from view 2.
[ "Computes", "NNCLR's", "loss", "given", "batch", "of", "nearest-neighbors", "nn", "from", "view", "1", "and", "predicted", "features", "p", "from", "view", "2." ]
def nnclr_loss_func(nn: torch.Tensor, p: torch.Tensor, temperature: float=0.1) -> torch.Tensor: nn = F.normalize(nn, dim=-1) p = F.normalize(p, dim=-1) p = gather(p) logits = nn @ p.T / temperature rank = get_rank() n = nn.size(0) labels = torch.arange(n * rank, n * (rank + 1), device=p.devi...
['def', 'nnclr_loss_func(nn:', 'torch.Tensor,', 'p:', 'torch.Tensor,', 'temperature:', 'float=0.1)', '->', 'torch.Tensor:', 'nn', '=', 'F.normalize(nn,', 'dim=-1)', 'p', '=', 'F.normalize(p,', 'dim=-1)', 'p', '=', 'gather(p)', 'logits', '=', 'nn', '@', 'p.T', '/', 'temperature', 'rank', '=', 'get_rank()', 'n', '=', 'nn...
393,566
FireFYF/SlimCAE
SlimCAE.py
load_image
load_image
Loads a PNG image file.
[ "Loads", "a", "PNG", "image", "file." ]
def load_image(filename): string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
['def', 'load_image(filename):', 'string', '=', 'tf.read_file(filename)', 'image', '=', 'tf.image.decode_image(string,', 'channels=3)', 'image', '=', 'tf.cast(image,', 'tf.float32)', 'image', '/=', '255', 'return', 'image']
878,224
triaquae/triaquae
legacy.py
FormWizard.render
render
Renders the given Form object, returning an HttpResponse.
[ "Renders", "the", "given", "Form", "object,", "returning", "an", "HttpResponse." ]
def render(self, form, request, step, context=None): old_data = request.POST prev_fields = [] if old_data: hidden = HiddenInput() for i in range(step): old_form = self.get_form(i, old_data) hash_name = 'hash_%s' % i prev_fields.extend([bf.as_hidden() for b...
['def', 'render(self,', 'form,', 'request,', 'step,', 'context=None):', 'old_data', '=', 'request.POST', 'prev_fields', '=', '[]', 'if', 'old_data:', 'hidden', '=', 'HiddenInput()', 'for', 'i', 'in', 'range(step):', 'old_form', '=', 'self.get_form(i,', 'old_data)', 'hash_name', '=', "'hash_%s'", '%', 'i', 'prev_fields....
357,343
open-mmlab/mmtracking
stark.py
Stark.extract_feat
extract_feat
Extract the features of the input image.
[ "Extract", "the", "features", "of", "the", "input", "image." ]
def extract_feat(self, img): feat = self.backbone(img) feat = self.neck(feat) return feat
['def', 'extract_feat(self,', 'img):', 'feat', '=', 'self.backbone(img)', 'feat', '=', 'self.neck(feat)', 'return', 'feat']
625,859
tensorflow/data-validation
stats_util.py
maybe_get_utf8
maybe_get_utf8
Returns the value decoded as utf-8, or None if it cannot be decoded.
[ "Returns", "the", "value", "decoded", "as", "utf-8,", "or", "None", "if", "it", "cannot", "be", "decoded." ]
def maybe_get_utf8(value: bytes) -> Optional[Text]: try: decoded_value = value.decode('utf-8') except UnicodeError: return None return decoded_value
['def', 'maybe_get_utf8(value:', 'bytes)', '->', 'Optional[Text]:', 'try:', 'decoded_value', '=', "value.decode('utf-8')", 'except', 'UnicodeError:', 'return', 'None', 'return', 'decoded_value']
497,647
LucasAlegre/morl-baselines
tabular_model.py
TabularModel.update
update
Update the model with the given transition.
[ "Update", "the", "model", "with", "the", "given", "transition." ]
def update(self, state, action, reward, next_state, terminal, priority=None): sa = (tuple(state), int(action)) srt = (tuple(next_state), tuple(reward) if isinstance(reward, np.ndarray) else reward, terminal) if sa not in self.model: self.state_actions_pairs.append(sa) if priority is not None...
['def', 'update(self,', 'state,', 'action,', 'reward,', 'next_state,', 'terminal,', 'priority=None):', 'sa', '=', '(tuple(state),', 'int(action))', 'srt', '=', '(tuple(next_state),', 'tuple(reward)', 'if', 'isinstance(reward,', 'np.ndarray)', 'else', 'reward,', 'terminal)', 'if', 'sa', 'not', 'in', 'self.model:', 'self...
655,851
matsu0228/nlp-jp
monitoring.py
TopologyEvent.topology_id
topology_id
A unique identifier for the topology this server is a part of.
[ "A", "unique", "identifier", "for", "the", "topology", "this", "server", "is", "a", "part", "of." ]
def topology_id(self): return self.__topology_id
['def', 'topology_id(self):', 'return', 'self.__topology_id']
804,942
hamza-murad/AALU
visual_recognition_v4.py
ErrorTarget.from_dict
from_dict
Initialize a ErrorTarget object from a json dictionary.
[ "Initialize", "a", "ErrorTarget", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'ErrorTarget': args = {} valid_keys = ['type', 'name'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class ErrorTarget: ' + ', '.join(bad_keys)) if 'type' in _dict: args['t...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ErrorTarget':", 'args', '=', '{}', 'valid_keys', '=', "['type',", "'name']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'ErrorTarget:', ...
6,180
farazBhatti/Human-Body-Measurements-using--
data_loader.py
DataLoader.get_smpl_loader_from_files
get_smpl_loader_from_files
files = list of tf records.
[ "files", "=", "list", "of", "tf", "records." ]
def get_smpl_loader_from_files(self, files): with tf.name_scope('input_smpl_loader'): filename_queue = tf.train.string_input_producer(files, shuffle=True) mosh_batch_size = self.batch_size * self.config.num_stage min_after_dequeue = 1000 capacity = min_after_dequeue + 3 * mosh_batch_...
['def', 'get_smpl_loader_from_files(self,', 'files):', 'with', "tf.name_scope('input_smpl_loader'):", 'filename_queue', '=', 'tf.train.string_input_producer(files,', 'shuffle=True)', 'mosh_batch_size', '=', 'self.batch_size', '*', 'self.config.num_stage', 'min_after_dequeue', '=', '1000', 'capacity', '=', 'min_after_de...
571,069
eora-ai/torchok
pairwise_task.py
PairwiseLearnTask.calc_relevance_matrix
calc_relevance_matrix
Calculates binary relevance matrix given multi-label matrix `y`.
[ "Calculates", "binary", "relevance", "matrix", "given", "multi-label", "matrix", "`y`." ]
def calc_relevance_matrix(self, y: Tensor) -> Tensor: if y.ndim == 1: bs = y.shape[0] input_label = torch.zeros(bs, self.num_classes, device=y.device) y = input_label.scatter_(1, y[:, None], 1) intersections = torch.matmul(y, y.transpose(1, 0)) rel_matrix = torch.where(intersections ...
['def', 'calc_relevance_matrix(self,', 'y:', 'Tensor)', '->', 'Tensor:', 'if', 'y.ndim', '==', '1:', 'bs', '=', 'y.shape[0]', 'input_label', '=', 'torch.zeros(bs,', 'self.num_classes,', 'device=y.device)', 'y', '=', 'input_label.scatter_(1,', 'y[:,', 'None],', '1)', 'intersections', '=', 'torch.matmul(y,', 'y.transpose...
903,324
AminaKeldibek/SeqGen
initialization.py
test_initialization_basic
test_initialization_basic
Some simple tests for the initialization.
[ "Some", "simple", "tests", "for", "the", "initialization." ]
def test_initialization_basic(): print('Running basic tests...') xavier_initializer = xavier_weight_init() shape = (1,) xavier_mat = xavier_initializer(shape) assert xavier_mat.get_shape() == shape shape = (1, 2, 3) xavier_mat = xavier_initializer(shape) assert xavier_mat.get_shape() == ...
['def', 'test_initialization_basic():', "print('Running", 'basic', "tests...')", 'xavier_initializer', '=', 'xavier_weight_init()', 'shape', '=', '(1,)', 'xavier_mat', '=', 'xavier_initializer(shape)', 'assert', 'xavier_mat.get_shape()', '==', 'shape', 'shape', '=', '(1,', '2,', '3)', 'xavier_mat', '=', 'xavier_initial...
876,553
rudranil723/mini-main
shortcuts.py
render_to_kml
render_to_kml
Render the response as KML (using the correct MIME type).
[ "Render", "the", "response", "as", "KML", "(using", "the", "correct", "MIME", "type)." ]
def render_to_kml(*args, **kwargs): return HttpResponse(loader.render_to_string(*args, **kwargs), content_type='application/vnd.google-earth.kml+xml')
['def', 'render_to_kml(*args,', '**kwargs):', 'return', 'HttpResponse(loader.render_to_string(*args,', '**kwargs),', "content_type='application/vnd.google-earth.kml+xml')"]
314,976
meganlsmith/phyloGAN
simulators.py
Simulator.countPinvIQTree
countPinvIQTree
Convert a simulated alignment into a proportion of invariant sites.
[ "Convert", "a", "simulated", "alignment", "into", "a", "proportion", "of", "invariant", "sites." ]
def countPinvIQTree(self, align): chunklength = align.get_alignment_length() countvarsites = 0 for i in range(0, chunklength): sequence = list(align[:, i]) if len(set(sequence)) > 1: countvarsites += 1 prop_inv = [1 - countvarsites / chunklength] return prop_inv
['def', 'countPinvIQTree(self,', 'align):', 'chunklength', '=', 'align.get_alignment_length()', 'countvarsites', '=', '0', 'for', 'i', 'in', 'range(0,', 'chunklength):', 'sequence', '=', 'list(align[:,', 'i])', 'if', 'len(set(sequence))', '>', '1:', 'countvarsites', '+=', '1', 'prop_inv', '=', '[1', '-', 'countvarsites...
769,281
secretflow/secretflow
spu.py
SPU.pir_setup
pir_setup
Private information retrival offline setup.
[ "Private", "information", "retrival", "offline", "setup." ]
def pir_setup(self, server: str, input_path: Union[str, Dict[Device, str]], key_columns: Union[str, List[str]], label_columns: Union[str, List[str]], oprf_key_path: str, setup_path: str, num_per_query: int, label_max_len: int, protocol='KEYWORD_PIR_LABELED_PSI'): return dispatch('pir_setup', self, server, input_pat...
['def', 'pir_setup(self,', 'server:', 'str,', 'input_path:', 'Union[str,', 'Dict[Device,', 'str]],', 'key_columns:', 'Union[str,', 'List[str]],', 'label_columns:', 'Union[str,', 'List[str]],', 'oprf_key_path:', 'str,', 'setup_path:', 'str,', 'num_per_query:', 'int,', 'label_max_len:', 'int,', "protocol='KEYWORD_PIR_LAB...
856,432
deepmind/dm_control
inverse_kinematics.py
nullspace_method
nullspace_method
Calculates the joint velocities to achieve a specified end effector delta.
[ "Calculates", "the", "joint", "velocities", "to", "achieve", "a", "specified", "end", "effector", "delta." ]
def nullspace_method(jac_joints, delta, regularization_strength=0.0): hess_approx = jac_joints.T.dot(jac_joints) joint_delta = jac_joints.T.dot(delta) if regularization_strength > 0: hess_approx += np.eye(hess_approx.shape[0]) * regularization_strength return np.linalg.solve(hess_approx, joi...
['def', 'nullspace_method(jac_joints,', 'delta,', 'regularization_strength=0.0):', 'hess_approx', '=', 'jac_joints.T.dot(jac_joints)', 'joint_delta', '=', 'jac_joints.T.dot(delta)', 'if', 'regularization_strength', '>', '0:', 'hess_approx', '+=', 'np.eye(hess_approx.shape[0])', '*', 'regularization_strength', 'return',...
165,614
BMW-InnovationLab/BMW-Semantic--Training-GUI
auto_data.py
Config.create_config
create_config
create new config with default paths and set `version` to 2.
[ "create", "new", "config", "with", "default", "paths", "and", "set", "`version`", "to", "2." ]
def create_config(self, cfg=None): config = {'data_path': str(self.config_path / 'datasets'), 'archive_path': str(self.config_path / 'archive'), 'storage_path': '/tmp', 'model_path': str(self.config_path / 'models'), 'version': 2} if cfg is not None: cfg['version'] = 2 config = merge(config, cfg...
['def', 'create_config(self,', 'cfg=None):', 'config', '=', "{'data_path':", 'str(self.config_path', '/', "'datasets'),", "'archive_path':", 'str(self.config_path', '/', "'archive'),", "'storage_path':", "'/tmp',", "'model_path':", 'str(self.config_path', '/', "'models'),", "'version':", '2}', 'if', 'cfg', 'is', 'not',...
463,094
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
registry_test.py
RegistryTest.testCanCreateWithRelativePath
testCanCreateWithRelativePath
Tests that Create can create the Impl subclass using a relative path.
[ "Tests", "that", "Create", "can", "create", "the", "Impl", "subclass", "using", "a", "relative", "path." ]
def testCanCreateWithRelativePath(self): for name in [PATH + 'registry_test_impl.Impl', 'syntaxnet.util.registry_test_impl.Impl', 'util.registry_test_impl.Impl', 'registry_test_impl.Impl']: value = 'created via %s' % name try: impl = registry_test_base.Base.Create(name, value) ex...
['def', 'testCanCreateWithRelativePath(self):', 'for', 'name', 'in', '[PATH', '+', "'registry_test_impl.Impl',", "'syntaxnet.util.registry_test_impl.Impl',", "'util.registry_test_impl.Impl',", "'registry_test_impl.Impl']:", 'value', '=', "'created", 'via', "%s'", '%', 'name', 'try:', 'impl', '=', 'registry_test_base.Ba...
29,081
muhanzhang/D-VAE
debugmode.py
BadOptimization.str_diagnostic
str_diagnostic
Return a pretty multiline string representating the cause of the exception.
[ "Return", "a", "pretty", "multiline", "string", "representating", "the", "cause", "of", "the", "exception." ]
def str_diagnostic(self): sio = StringIO() val_str_len_limit = 800 print('BadOptimization Error', super(BadOptimization, self).__str__(), file=sio) print(' Variable: id', id(self.new_r), self.new_r, file=sio) print(' Op', self.new_r.owner, file=sio) print(' Value Type:', type(self.new_r_val),...
['def', 'str_diagnostic(self):', 'sio', '=', 'StringIO()', 'val_str_len_limit', '=', '800', "print('BadOptimization", "Error',", 'super(BadOptimization,', 'self).__str__(),', 'file=sio)', "print('", 'Variable:', "id',", 'id(self.new_r),', 'self.new_r,', 'file=sio)', "print('", "Op',", 'self.new_r.owner,', 'file=sio)', ...
524,763
bm777/object_detection
model.py
ObjectDetector.get_feed_dict_for_all
get_feed_dict_for_all
Get the feed dictionary for both RPN and RCN.
[ "Get", "the", "feed", "dictionary", "for", "both", "RPN", "and", "RCN." ]
def get_feed_dict_for_all(self, batch, is_train, feats=None): if is_train: (_, anchor_files) = batch (gt_anchor_labels, gt_anchor_regs, anchor_masks, anchor_weights, anchor_reg_masks) = self.process_anchor_data(anchor_files) (rois, gt_roi_classes, gt_roi_regs, roi_masks, roi_weights, roi_reg...
['def', 'get_feed_dict_for_all(self,', 'batch,', 'is_train,', 'feats=None):', 'if', 'is_train:', '(_,', 'anchor_files)', '=', 'batch', '(gt_anchor_labels,', 'gt_anchor_regs,', 'anchor_masks,', 'anchor_weights,', 'anchor_reg_masks)', '=', 'self.process_anchor_data(anchor_files)', '(rois,', 'gt_roi_classes,', 'gt_roi_reg...
745,215
RasaHQ/rasa
release.py
version_file_path
version_file_path
Path to the python file containing the version number.
[ "Path", "to", "the", "python", "file", "containing", "the", "version", "number." ]
def version_file_path() -> Path: return project_root() / VERSION_FILE_PATH
['def', 'version_file_path()', '->', 'Path:', 'return', 'project_root()', '/', 'VERSION_FILE_PATH']
837,998
drprojects/superpoint_transformer
data.py
Data.cuda
cuda
Move the NAG with all Data in it to CUDA.
[ "Move", "the", "NAG", "with", "all", "Data", "in", "it", "to", "CUDA." ]
def cuda(self, **kwargs): return self.to('cuda', **kwargs)
['def', 'cuda(self,', '**kwargs):', 'return', "self.to('cuda',", '**kwargs)']
880,775
gregdurrett/nlp-qa-finalproj
utils.py
load_dataset
load_dataset
Loads MRQA-formatted dataset from path.
[ "Loads", "MRQA-formatted", "dataset", "from", "path." ]
def load_dataset(path): with gzip.open(path, 'rb') as f: elems = [json.loads(l.rstrip()) for l in tqdm(f, desc=f"loading '{path}'", leave=False)] (meta, samples) = (elems[0], elems[1:]) return (meta, samples)
['def', 'load_dataset(path):', 'with', 'gzip.open(path,', "'rb')", 'as', 'f:', 'elems', '=', '[json.loads(l.rstrip())', 'for', 'l', 'in', 'tqdm(f,', 'desc=f"loading', '\'{path}\'",', 'leave=False)]', '(meta,', 'samples)', '=', '(elems[0],', 'elems[1:])', 'return', '(meta,', 'samples)']
731,129
myothida/Supervised-Machine-Learning
exceptions.py
ParseBaseException.column
column
Return the 1-based column on the line of text where the exception occurred.
[ "Return", "the", "1-based", "column", "on", "the", "line", "of", "text", "where", "the", "exception", "occurred." ]
def column(self) -> int: return col(self.loc, self.pstr)
['def', 'column(self)', '->', 'int:', 'return', 'col(self.loc,', 'self.pstr)']
445,508
weimin17/Object-Detection_HelmetDetection
runners.py
run_train
run_train
Runs training for a sequential latent variable model.
[ "Runs", "training", "for", "a", "sequential", "latent", "variable", "model." ]
def run_train(config): def create_logging_hook(step, bound_value): bound_label = config.bound + ' bound' if config.normalize_by_seq_len: bound_label += ' per timestep' else: bound_label += ' per sequence' def summary_formatter(log_dict): return '...
['def', 'run_train(config):', 'def', 'create_logging_hook(step,', 'bound_value):', 'bound_label', '=', 'config.bound', '+', "'", "bound'", 'if', 'config.normalize_by_seq_len:', 'bound_label', '+=', "'", 'per', "timestep'", 'else:', 'bound_label', '+=', "'", 'per', "sequence'", 'def', 'summary_formatter(log_dict):', 're...
750,010
zihuitang/medical_AI_platform
__init__.py
Handler.createLock
createLock
Acquire a thread lock for serializing access to the underlying I/O.
[ "Acquire", "a", "thread", "lock", "for", "serializing", "access", "to", "the", "underlying", "I/O." ]
def createLock(self): if threading: self.lock = threading.RLock() else: self.lock = None
['def', 'createLock(self):', 'if', 'threading:', 'self.lock', '=', 'threading.RLock()', 'else:', 'self.lock', '=', 'None']
283,119
mrahtz/learning-from-human-preferences
utils_test.py
TestUtils.test_batch_iter_2
test_batch_iter_2
Check that shuffle=True returns the same data but in a different order.
[ "Check", "that", "shuffle=True", "returns", "the", "same", "data", "but", "in", "a", "different", "order." ]
def test_batch_iter_2(self): expected_data = list(range(16)) actual_data = [] for x in batch_iter(expected_data, batch_size=4, shuffle=True): actual_data.extend(x) self.assertEqual(len(actual_data), len(expected_data)) self.assertEqual(set(actual_data), set(expected_data)) with self.asse...
['def', 'test_batch_iter_2(self):', 'expected_data', '=', 'list(range(16))', 'actual_data', '=', '[]', 'for', 'x', 'in', 'batch_iter(expected_data,', 'batch_size=4,', 'shuffle=True):', 'actual_data.extend(x)', 'self.assertEqual(len(actual_data),', 'len(expected_data))', 'self.assertEqual(set(actual_data),', 'set(expect...
262,143
brightmart/albert_zh
similarity.py
BertSim.model_fn_builder
model_fn_builder
Returns `model_fn` closurimport_tfe for TPUEstimator.
[ "Returns", "`model_fn`", "closurimport_tfe", "for", "TPUEstimator." ]
def model_fn_builder(self, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings): def model_fn(features, labels, mode, params): from tensorflow.python.estimator.model_fn import EstimatorSpec tf.logging.info('*** Features ***') fo...
['def', 'model_fn_builder(self,', 'bert_config,', 'num_labels,', 'init_checkpoint,', 'learning_rate,', 'num_train_steps,', 'num_warmup_steps,', 'use_one_hot_embeddings):', 'def', 'model_fn(features,', 'labels,', 'mode,', 'params):', 'from', 'tensorflow.python.estimator.model_fn', 'import', 'EstimatorSpec', "tf.logging....
32,817
PaddlePaddle/PaddleSpeech
phonectic.py
English.phoneticize
phoneticize
Normalize the input text sequence and convert it into pronunciation sequence.
[ "Normalize", "the", "input", "text", "sequence", "and", "convert", "it", "into", "pronunciation", "sequence." ]
def phoneticize(self, sentence): start = self.vocab.start_symbol end = self.vocab.end_symbol phonemes = ([] if start is None else [start]) + self.backend(sentence) + ([] if end is None else [end]) phonemes = [item for item in phonemes if item in self.vocab.stoi] return phonemes
['def', 'phoneticize(self,', 'sentence):', 'start', '=', 'self.vocab.start_symbol', 'end', '=', 'self.vocab.end_symbol', 'phonemes', '=', '([]', 'if', 'start', 'is', 'None', 'else', '[start])', '+', 'self.backend(sentence)', '+', '([]', 'if', 'end', 'is', 'None', 'else', '[end])', 'phonemes', '=', '[item', 'for', 'item...
277,141
facebookresearch/CompilerGym
llvm.py
benchmark_name
benchmark_name
Enumerate the names of benchmarks.
[ "Enumerate", "the", "names", "of", "benchmarks." ]
def benchmark_name(request) -> str: yield request.param
['def', 'benchmark_name(request)', '->', 'str:', 'yield', 'request.param']
135,895
tensorflow/agents
py_metric.py
PyMetric.prefix
prefix
Prefix for the metric.
[ "Prefix", "for", "the", "metric." ]
def prefix(self) -> Text: return self._prefix
['def', 'prefix(self)', '->', 'Text:', 'return', 'self._prefix']
22,785
ldkong1205/LaserMix
utils.py
points_img2cam
points_img2cam
Project points in image coordinates to camera coordinates.
[ "Project", "points", "in", "image", "coordinates", "to", "camera", "coordinates." ]
def points_img2cam(points: Union[Tensor, np.ndarray], cam2img: Union[Tensor, np.ndarray]) -> Union[Tensor, np.ndarray]: assert cam2img.shape[0] <= 4 assert cam2img.shape[1] <= 4 assert points.shape[1] == 3 xys = points[:, :2] depths = points[:, 2].view(-1, 1) unnormed_xys = torch.cat([xys * dept...
['def', 'points_img2cam(points:', 'Union[Tensor,', 'np.ndarray],', 'cam2img:', 'Union[Tensor,', 'np.ndarray])', '->', 'Union[Tensor,', 'np.ndarray]:', 'assert', 'cam2img.shape[0]', '<=', '4', 'assert', 'cam2img.shape[1]', '<=', '4', 'assert', 'points.shape[1]', '==', '3', 'xys', '=', 'points[:,', ':2]', 'depths', '=', ...
624,389
microsoft/nlp-recipes
dac.py
get_label_values
get_label_values
Get the label values from label IDs.
[ "Get", "the", "label", "values", "from", "label", "IDs." ]
def get_label_values(label_encoder, label_ids): return label_encoder.inverse_transform(label_ids)
['def', 'get_label_values(label_encoder,', 'label_ids):', 'return', 'label_encoder.inverse_transform(label_ids)']
731,177
lalwanii26/openscope-barcodingstim
sweepstim.py
SweepStim.load_config
load_config
Reads the config file for the specified section.
[ "Reads", "the", "config", "file", "for", "the", "specified", "section." ]
def load_config(self, path, section, override={}): config = getConfig(section, path) for k in override.keys(): if k in config.keys(): config[k] = override[k] return config
['def', 'load_config(self,', 'path,', 'section,', 'override={}):', 'config', '=', 'getConfig(section,', 'path)', 'for', 'k', 'in', 'override.keys():', 'if', 'k', 'in', 'config.keys():', 'config[k]', '=', 'override[k]', 'return', 'config']
757,537
myothida/Supervised-Machine-Learning
__init__.py
subset_lookups
subset_lookups
Returns the indices of nonempty features.
[ "Returns", "the", "indices", "of", "nonempty", "features." ]
def subset_lookups(self, lookup_indices): return [r.FeatureIndex for r in self.SubstitutionRecord if r.Feature.subset_lookups(lookup_indices)]
['def', 'subset_lookups(self,', 'lookup_indices):', 'return', '[r.FeatureIndex', 'for', 'r', 'in', 'self.SubstitutionRecord', 'if', 'r.Feature.subset_lookups(lookup_indices)]']
361,149
arshpreetsingh/quantopian-machinelearning
traitlets.py
TraitType.init_default_value
init_default_value
DEPRECATED: Set the static default value for the trait type.
[ "DEPRECATED:", "Set", "the", "static", "default", "value", "for", "the", "trait", "type." ]
def init_default_value(self, obj): warn('init_default_value is deprecated in traitlets 4.0, and may be removed in the future', DeprecationWarning, stacklevel=2) value = self._validate(obj, self.default_value) obj._trait_values[self.name] = value return value
['def', 'init_default_value(self,', 'obj):', "warn('init_default_value", 'is', 'deprecated', 'in', 'traitlets', '4.0,', 'and', 'may', 'be', 'removed', 'in', 'the', "future',", 'DeprecationWarning,', 'stacklevel=2)', 'value', '=', 'self._validate(obj,', 'self.default_value)', 'obj._trait_values[self.name]', '=', 'value'...
893,765
SvenGronauer/phoenix-drone-simulation
data_visualizer.py
remove_battery_compensation
remove_battery_compensation
Remove battery compensation gain from PWM voltages.
[ "Remove", "battery", "compensation", "gain", "from", "PWM", "voltages." ]
def remove_battery_compensation(PWMs: np.ndarray, supply_voltage: float): percentage = PWMs / 65536 volts = percentage * supply_voltage a = -0.0006239 b = 0.088 c = -volts thrust = (-b + np.sqrt(b ** 2 - 4 * a * c)) / (2 * a) PWMs_cleaned = thrust / 60 * 65536 return PWMs_cleaned
['def', 'remove_battery_compensation(PWMs:', 'np.ndarray,', 'supply_voltage:', 'float):', 'percentage', '=', 'PWMs', '/', '65536', 'volts', '=', 'percentage', '*', 'supply_voltage', 'a', '=', '-0.0006239', 'b', '=', '0.088', 'c', '=', '-volts', 'thrust', '=', '(-b', '+', 'np.sqrt(b', '**', '2', '-', '4', '*', 'a', '*',...
769,038
marysia/thesis
patches.py
DataPatches.load
load
Sets class variables train, val and test to contain a Data class instance with the data.
[ "Sets", "class", "variables", "train,", "val", "and", "test", "to", "contain", "a", "Data", "class", "instance", "with", "the", "data." ]
def load(self): self.train = self.get_dataset(self.train_dataset, 'train') print('Train patches loaded.') self.val = self.get_dataset(self.val_dataset, 'val') print('Validation patches loaded.') self.test = self.get_dataset(self.test_dataset, 'test') print('Test patches loaded.')
['def', 'load(self):', 'self.train', '=', 'self.get_dataset(self.train_dataset,', "'train')", "print('Train", 'patches', "loaded.')", 'self.val', '=', 'self.get_dataset(self.val_dataset,', "'val')", "print('Validation", 'patches', "loaded.')", 'self.test', '=', 'self.get_dataset(self.test_dataset,', "'test')", "print('...
354,733
OctoConsulting/octobot
lexinterface.py
wait_until_table_ready
wait_until_table_ready
Indicates when the DynamoDB table is ready.
[ "Indicates", "when", "the", "DynamoDB", "table", "is", "ready." ]
def wait_until_table_ready(table_name: str, max_iterations: int=10) -> bool: iteration_count = 0 while iteration_count < max_iterations: describe_table_response = ddb_client.describe_table(TableName=table_name) table_status = describe_table_response['Table']['TableStatus'] if table_statu...
['def', 'wait_until_table_ready(table_name:', 'str,', 'max_iterations:', 'int=10)', '->', 'bool:', 'iteration_count', '=', '0', 'while', 'iteration_count', '<', 'max_iterations:', 'describe_table_response', '=', 'ddb_client.describe_table(TableName=table_name)', 'table_status', '=', "describe_table_response['Table']['T...
250,000
google-research/text-to-text-transfer-transformer
postprocessors.py
string_label_to_class_id
string_label_to_class_id
Returns index of string_label in label_classes or default if not found.
[ "Returns", "index", "of", "string_label", "in", "label_classes", "or", "default", "if", "not", "found." ]
def string_label_to_class_id(string_label, label_classes, default=-1, **unused_kwargs): if string_label in label_classes: return label_classes.index(string_label) else: return default
['def', 'string_label_to_class_id(string_label,', 'label_classes,', 'default=-1,', '**unused_kwargs):', 'if', 'string_label', 'in', 'label_classes:', 'return', 'label_classes.index(string_label)', 'else:', 'return', 'default']
925,534
deepmind/dm_control
workspaces.py
add_bbox_site
add_bbox_site
Adds a site for visualizing a bounding box to an MJCF model.
[ "Adds", "a", "site", "for", "visualizing", "a", "bounding", "box", "to", "an", "MJCF", "model." ]
def add_bbox_site(body, lower, upper, visible=False, **kwargs): upper = np.array(upper) lower = np.array(lower) pos = (upper + lower) / 2.0 size = np.maximum((upper - lower) / 2.0, _MIN_SITE_DIMENSION) group = None if visible else constants.TASK_SITE_GROUP return body.add('site', type='box', pos...
['def', 'add_bbox_site(body,', 'lower,', 'upper,', 'visible=False,', '**kwargs):', 'upper', '=', 'np.array(upper)', 'lower', '=', 'np.array(lower)', 'pos', '=', '(upper', '+', 'lower)', '/', '2.0', 'size', '=', 'np.maximum((upper', '-', 'lower)', '/', '2.0,', '_MIN_SITE_DIMENSION)', 'group', '=', 'None', 'if', 'visible...
165,179
ChenhongyiYang/PGD
gaussian_target.py
gen_gaussian_target
gen_gaussian_target
Generate 2D gaussian heatmap.
[ "Generate", "2D", "gaussian", "heatmap." ]
def gen_gaussian_target(heatmap, center, radius, k=1): diameter = 2 * radius + 1 gaussian_kernel = gaussian2D(radius, sigma=diameter / 6, dtype=heatmap.dtype, device=heatmap.device) (x, y) = center (height, width) = heatmap.shape[:2] (left, right) = (min(x, radius), min(width - x, radius + 1)) (...
['def', 'gen_gaussian_target(heatmap,', 'center,', 'radius,', 'k=1):', 'diameter', '=', '2', '*', 'radius', '+', '1', 'gaussian_kernel', '=', 'gaussian2D(radius,', 'sigma=diameter', '/', '6,', 'dtype=heatmap.dtype,', 'device=heatmap.device)', '(x,', 'y)', '=', 'center', '(height,', 'width)', '=', 'heatmap.shape[:2]', '...
768,264
TrellixVulnTeam/Unsupervised_Learning_HFI7
managers.py
BlockManager.to_native_types
to_native_types
Convert values to native types (strings / python objects) that are used in formatting (repr / csv).
[ "Convert", "values", "to", "native", "types", "(strings", "/", "python", "objects)", "that", "are", "used", "in", "formatting", "(repr", "/", "csv)." ]
def to_native_types(self, **kwargs) -> 'BlockManager': return self.apply('to_native_types', **kwargs)
['def', 'to_native_types(self,', '**kwargs)', '->', "'BlockManager':", 'return', "self.apply('to_native_types',", '**kwargs)']
453,280
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Wm.wm_sizefrom
wm_sizefrom
Instruct the window manager that the size of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".
[ "Instruct", "the", "window", "manager", "that", "the", "size", "of", "this", "widget", "shall", "be", "defined", "by", "the", "user", "if", "WHO", "is", "\"user\",", "and", "by", "its", "own", "policy", "if", "WHO", "is", "\"program\"." ]
def wm_sizefrom(self, who=None): return self.tk.call('wm', 'sizefrom', self._w, who)
['def', 'wm_sizefrom(self,', 'who=None):', 'return', "self.tk.call('wm',", "'sizefrom',", 'self._w,', 'who)']
376,908
AranGarcia/ArtificialQuest
world2renderer.py
LogSection.reset_logs
reset_logs
Resets to default status when selection is deactivated.
[ "Resets", "to", "default", "status", "when", "selection", "is", "deactivated." ]
def reset_logs(self): self.texts = []
['def', 'reset_logs(self):', 'self.texts', '=', '[]']
70,473
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
_base.py
Future.done
done
Return True of the future was cancelled or finished executing.
[ "Return", "True", "of", "the", "future", "was", "cancelled", "or", "finished", "executing." ]
def done(self): with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]
['def', 'done(self):', 'with', 'self._condition:', 'return', 'self._state', 'in', '[CANCELLED,', 'CANCELLED_AND_NOTIFIED,', 'FINISHED]']
430,215
facebookresearch/fvcore
test_jit_model_analysis.py
TestJitModelAnalysis.test_recursive_scope
test_recursive_scope
Tests that an op is only counted once per module, even if it is in the scope of that module multiple times.
[ "Tests", "that", "an", "op", "is", "only", "counted", "once", "per", "module,", "even", "if", "it", "is", "in", "the", "scope", "of", "that", "module", "multiple", "times." ]
def test_recursive_scope(self) -> None: model = RecursiveScopeNet() inputs = (torch.randn((1, *model.input_size)),) analyzer = FlopCountAnalysis(model, inputs) self.assertEqual(analyzer.total(), model.flops) self.assertEqual(analyzer.total('fc'), model.flops) self.assertEqual(analyzer.uncalled_m...
['def', 'test_recursive_scope(self)', '->', 'None:', 'model', '=', 'RecursiveScopeNet()', 'inputs', '=', '(torch.randn((1,', '*model.input_size)),)', 'analyzer', '=', 'FlopCountAnalysis(model,', 'inputs)', 'self.assertEqual(analyzer.total(),', 'model.flops)', "self.assertEqual(analyzer.total('fc'),", 'model.flops)', 's...
566,002
ethz-asl/ai_for_robotics
GradientDescentOptimizer.py
GradientDescentOptimizer.updateStep
updateStep
Update the NN model parameters given the loss function and a data batch.
[ "Update", "the", "NN", "model", "parameters", "given", "the", "loss", "function", "and", "a", "data", "batch." ]
def updateStep(self, nn, loss_function, x_batch, y_target_batch): gradients = [] avg_batch_loss = 0 batch_size = x_batch.shape[0] for i in range(x_batch.shape[0]): x = np.array([x_batch[i, :]]) y_target = np.array([y_target_batch[i, :]]) y = nn.output(x) avg_batch_loss +=...
['def', 'updateStep(self,', 'nn,', 'loss_function,', 'x_batch,', 'y_target_batch):', 'gradients', '=', '[]', 'avg_batch_loss', '=', '0', 'batch_size', '=', 'x_batch.shape[0]', 'for', 'i', 'in', 'range(x_batch.shape[0]):', 'x', '=', 'np.array([x_batch[i,', ':]])', 'y_target', '=', 'np.array([y_target_batch[i,', ':]])', ...
87,181
weimin17/Object-Detection_HelmetDetection
real_nvp_multiscale_dataset.py
rec_masked_conv_coupling
rec_masked_conv_coupling
Recursion on coupling layers.
[ "Recursion", "on", "coupling", "layers." ]
def rec_masked_conv_coupling(input_, hps, scale_idx, n_scale, use_batch_norm=True, weight_norm=True, train=True): shape = input_.get_shape().as_list() channels = shape[3] residual_blocks = hps.residual_blocks base_dim = hps.base_dim mask = 1.0 use_aff = hps.use_aff res = input_ skip = hp...
['def', 'rec_masked_conv_coupling(input_,', 'hps,', 'scale_idx,', 'n_scale,', 'use_batch_norm=True,', 'weight_norm=True,', 'train=True):', 'shape', '=', 'input_.get_shape().as_list()', 'channels', '=', 'shape[3]', 'residual_blocks', '=', 'hps.residual_blocks', 'base_dim', '=', 'hps.base_dim', 'mask', '=', '1.0', 'use_a...
759,528
KalleHallden/InstaAutomator
_tqdm.py
tqdm.unpause
unpause
Restart tqdm timer from last print time.
[ "Restart", "tqdm", "timer", "from", "last", "print", "time." ]
def unpause(self): cur_t = self._time() self.start_t += cur_t - self.last_print_t self.last_print_t = cur_t
['def', 'unpause(self):', 'cur_t', '=', 'self._time()', 'self.start_t', '+=', 'cur_t', '-', 'self.last_print_t', 'self.last_print_t', '=', 'cur_t']
244,950
ryu-ed/SpaceInvaders_Ros
builder.py
AstroidBuilder.module_build
module_build
Build an astroid from a living module instance.
[ "Build", "an", "astroid", "from", "a", "living", "module", "instance." ]
def module_build(self, module, modname=None): node = None path = getattr(module, '__file__', None) if path is not None: (path_, ext) = os.path.splitext(modutils._path_from_filename(path)) if ext in ('.py', '.pyc', '.pyo') and os.path.exists(path_ + '.py'): node = self.file_build(...
['def', 'module_build(self,', 'module,', 'modname=None):', 'node', '=', 'None', 'path', '=', 'getattr(module,', "'__file__',", 'None)', 'if', 'path', 'is', 'not', 'None:', '(path_,', 'ext)', '=', 'os.path.splitext(modutils._path_from_filename(path))', 'if', 'ext', 'in', "('.py',", "'.pyc',", "'.pyo')", 'and', 'os.path....
394,183
sbjelogr/TransferBoost
lgb.py
LGBMTransferLearner.predict_proba
predict_proba
Predict the probabilities after transfer learning.
[ "Predict", "the", "probabilities", "after", "transfer", "learning." ]
def predict_proba(self, X, tree_index=-1): X_leaves_ixs = self.model.predict(X, pred_leaf=True) probas = self._predict_proba(X_leaves_ixs=X_leaves_ixs, tree_index=tree_index) return probas
['def', 'predict_proba(self,', 'X,', 'tree_index=-1):', 'X_leaves_ixs', '=', 'self.model.predict(X,', 'pred_leaf=True)', 'probas', '=', 'self._predict_proba(X_leaves_ixs=X_leaves_ixs,', 'tree_index=tree_index)', 'return', 'probas']
930,175
eddylau328/fyp-artificial-intelligence-ac-control-device
__init__.py
create_command
create_command
Create an instance of the Command class with the given name.
[ "Create", "an", "instance", "of", "the", "Command", "class", "with", "the", "given", "name." ]
def create_command(name, **kwargs): (module_path, class_name, summary) = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command
['def', 'create_command(name,', '**kwargs):', '(module_path,', 'class_name,', 'summary)', '=', 'commands_dict[name]', 'module', '=', 'importlib.import_module(module_path)', 'command_class', '=', 'getattr(module,', 'class_name)', 'command', '=', 'command_class(name=name,', 'summary=summary,', '**kwargs)', 'return', 'com...
215,851
arshpreetsingh/quantopian-machinelearning
data.py
YamlLexer.something
something
Do not produce empty tokens.
[ "Do", "not", "produce", "empty", "tokens." ]
def something(token_class): def callback(lexer, match, context): text = match.group() if not text: return yield (match.start(), token_class, text) context.pos = match.end() return callback
['def', 'something(token_class):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'if', 'not', 'text:', 'return', 'yield', '(match.start(),', 'token_class,', 'text)', 'context.pos', '=', 'match.end()', 'return', 'callback']
892,663
mrahtz/learning-from-human-preferences
utils_test.py
TestUtils.test_batch_iter_3
test_batch_iter_3
Check that successive calls shuffle in a different order.
[ "Check", "that", "successive", "calls", "shuffle", "in", "a", "different", "order." ]
def test_batch_iter_3(self): data = list(range(16)) out1 = [] for x in batch_iter(data, batch_size=4, shuffle=True): out1.extend(x) out2 = [] for x in batch_iter(data, batch_size=4, shuffle=True): out2.extend(x) self.assertEqual(set(out1), set(out2)) with self.assertRaises(As...
['def', 'test_batch_iter_3(self):', 'data', '=', 'list(range(16))', 'out1', '=', '[]', 'for', 'x', 'in', 'batch_iter(data,', 'batch_size=4,', 'shuffle=True):', 'out1.extend(x)', 'out2', '=', '[]', 'for', 'x', 'in', 'batch_iter(data,', 'batch_size=4,', 'shuffle=True):', 'out2.extend(x)', 'self.assertEqual(set(out1),', '...
262,144
jhultman/vision3d
roi_grid_pool.py
RoiGridPool.build_pointnet
build_pointnet
Copy channel list because PointNet modifies it in-place.
[ "Copy", "channel", "list", "because", "PointNet", "modifies", "it", "in-place." ]
def build_pointnet(self, cfg): pnet = PointnetSAModuleMSG(npoint=-1, radii=cfg.GRIDPOOL.RADII_PN, nsamples=cfg.SAMPLES_PN, mlps=deepcopy(cfg.GRIDPOOL.MLPS_PN), use_xyz=True) return pnet
['def', 'build_pointnet(self,', 'cfg):', 'pnet', '=', 'PointnetSAModuleMSG(npoint=-1,', 'radii=cfg.GRIDPOOL.RADII_PN,', 'nsamples=cfg.SAMPLES_PN,', 'mlps=deepcopy(cfg.GRIDPOOL.MLPS_PN),', 'use_xyz=True)', 'return', 'pnet']
944,833
google-research/scenic
dataset_utils.py
finalize_word_mask_info
finalize_word_mask_info
Format the word mask related information in the batch dict.
[ "Format", "the", "word", "mask", "related", "information", "in", "the", "batch", "dict." ]
def finalize_word_mask_info(batch, spectrogram_feature_name, patch_size, max_num_word_masks, max_num_masked_input_indices): spectrogram = batch[spectrogram_feature_name] len_spec = tf.shape(spectrogram)[0] num_feats = tf.shape(spectrogram)[1] len_spec = tf.cast(len_spec / patch_size[0], tf.int32) * patc...
['def', 'finalize_word_mask_info(batch,', 'spectrogram_feature_name,', 'patch_size,', 'max_num_word_masks,', 'max_num_masked_input_indices):', 'spectrogram', '=', 'batch[spectrogram_feature_name]', 'len_spec', '=', 'tf.shape(spectrogram)[0]', 'num_feats', '=', 'tf.shape(spectrogram)[1]', 'len_spec', '=', 'tf.cast(len_s...
846,383
ldkong1205/LaserMix
tr3d_head.py
TR3DHead.get_targets
get_targets
Compute targets for final locations for a single scene.
[ "Compute", "targets", "for", "final", "locations", "for", "a", "single", "scene." ]
def get_targets(self, points: Tensor, gt_bboxes: BaseInstance3DBoxes, gt_labels: Tensor, num_classes: int) -> Tuple[Tensor, ...]: float_max = points[0].new_tensor(100000000.0) levels = torch.cat([points[i].new_tensor(i, dtype=torch.long).expand(len(points[i])) for i in range(len(points))]) points = torch.ca...
['def', 'get_targets(self,', 'points:', 'Tensor,', 'gt_bboxes:', 'BaseInstance3DBoxes,', 'gt_labels:', 'Tensor,', 'num_classes:', 'int)', '->', 'Tuple[Tensor,', '...]:', 'float_max', '=', 'points[0].new_tensor(100000000.0)', 'levels', '=', 'torch.cat([points[i].new_tensor(i,', 'dtype=torch.long).expand(len(points[i]))'...
624,594
deephyper/deephyper
load_data.py
load_data
load_data
Generate data for linear function -sum(x_i).
[ "Generate", "data", "for", "linear", "function", "-sum(x_i)." ]
def load_data(dim=10, verbose=0): rng = np.random.RandomState(42) size = 10000 prop = 0.8 (a, b) = (0, 100) d = b - a x = np.array([a + rng.random(dim) * d for i in range(size)]) y = np.array([[np.sum(v)] for v in x]) sep_index = int(prop * size) train_X = x[:sep_index] train_y =...
['def', 'load_data(dim=10,', 'verbose=0):', 'rng', '=', 'np.random.RandomState(42)', 'size', '=', '10000', 'prop', '=', '0.8', '(a,', 'b)', '=', '(0,', '100)', 'd', '=', 'b', '-', 'a', 'x', '=', 'np.array([a', '+', 'rng.random(dim)', '*', 'd', 'for', 'i', 'in', 'range(size)])', 'y', '=', 'np.array([[np.sum(v)]', 'for',...
521,083
scikit-learn/scikit-learn
test_coordinate_descent.py
test_enet_sample_weight_does_not_overwrite_sample_weight
test_enet_sample_weight_does_not_overwrite_sample_weight
Check that ElasticNet does not overwrite sample_weights.
[ "Check", "that", "ElasticNet", "does", "not", "overwrite", "sample_weights." ]
def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input): rng = np.random.RandomState(0) (n_samples, n_features) = (10, 5) X = rng.rand(n_samples, n_features) y = rng.rand(n_samples) sample_weight_1_25 = 1.25 * np.ones_like(y) sample_weight = sample_weight_1_25.copy() reg = ...
['def', 'test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):', 'rng', '=', 'np.random.RandomState(0)', '(n_samples,', 'n_features)', '=', '(10,', '5)', 'X', '=', 'rng.rand(n_samples,', 'n_features)', 'y', '=', 'rng.rand(n_samples)', 'sample_weight_1_25', '=', '1.25', '*', 'np.ones_like(y)', 'sample_w...
853,542
JohannesVerherstraeten/semantic-video-segmentation
confusionmetric.py
ConfusionMetric.value
value
Returns: Confustion matrix of K rows and K columns, where rows corresponds to ground-truth targets and columns corresponds to predicted targets.
[ "Returns:", "Confustion", "matrix", "of", "K", "rows", "and", "K", "columns,", "where", "rows", "corresponds", "to", "ground-truth", "targets", "and", "columns", "corresponds", "to", "predicted", "targets." ]
def value(self) -> Tuple[Optional[Any], Dict]: if self.normalized: conf = self.conf.astype(np.float32) return (conf / conf.sum(1).clip(min=1e-12)[:, None], dict()) else: return (self.conf, dict())
['def', 'value(self)', '->', 'Tuple[Optional[Any],', 'Dict]:', 'if', 'self.normalized:', 'conf', '=', 'self.conf.astype(np.float32)', 'return', '(conf', '/', 'conf.sum(1).clip(min=1e-12)[:,', 'None],', 'dict())', 'else:', 'return', '(self.conf,', 'dict())']
342,846
matsu0228/nlp-jp
optionstatus.py
OptionStatus.wait_for_state
wait_for_state
Performs polling of CloudSearch to wait for the ``state`` of this object to change to the provided state.
[ "Performs", "polling", "of", "CloudSearch", "to", "wait", "for", "the", "``state``", "of", "this", "object", "to", "change", "to", "the", "provided", "state." ]
def wait_for_state(self, state): while self.state != state: time.sleep(5) self.refresh()
['def', 'wait_for_state(self,', 'state):', 'while', 'self.state', '!=', 'state:', 'time.sleep(5)', 'self.refresh()']
784,086
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
parser.py
invalid_config_error_message
invalid_config_error_message
Returns a better error message when invalid configuration option is provided.
[ "Returns", "a", "better", "error", "message", "when", "invalid", "configuration", "option", "is", "provided." ]
def invalid_config_error_message(action, key, val): if action in ('store_true', 'store_false'): return '{0} is not a valid value for {1} option, please specify a boolean value like yes/no, true/false or 1/0 instead.'.format(val, key) return '{0} is not a valid value for {1} option, please specify a nume...
['def', 'invalid_config_error_message(action,', 'key,', 'val):', 'if', 'action', 'in', "('store_true',", "'store_false'):", 'return', "'{0}", 'is', 'not', 'a', 'valid', 'value', 'for', '{1}', 'option,', 'please', 'specify', 'a', 'boolean', 'value', 'like', 'yes/no,', 'true/false', 'or', '1/0', "instead.'.format(val,", ...
83,708
adamshamsudeen/vision.ai
globals.py
push_context
push_context
Pushes a new context to the current stack.
[ "Pushes", "a", "new", "context", "to", "the", "current", "stack." ]
def push_context(ctx): _local.__dict__.setdefault('stack', []).append(ctx)
['def', 'push_context(ctx):', "_local.__dict__.setdefault('stack',", '[]).append(ctx)']
942,799
GatorEducator/GatorMiner
test_json_util.py
test_get_json_files
test_get_json_files
Test that get json files return correct json files.
[ "Test", "that", "get", "json", "files", "return", "correct", "json", "files." ]
def test_get_json_files(tmp_path): directory = tmp_path / 'sub' directory.mkdir() para_1 = directory / 'hello.json' para_2 = directory / 'world.json' para_1.write_text('{"assignment": "java-assignment"}') para_2.write_text('{"assignment": "java-assignment"}') output = js.get_json_files(direc...
['def', 'test_get_json_files(tmp_path):', 'directory', '=', 'tmp_path', '/', "'sub'", 'directory.mkdir()', 'para_1', '=', 'directory', '/', "'hello.json'", 'para_2', '=', 'directory', '/', "'world.json'", 'para_1.write_text(\'{"assignment":', '"java-assignment"}\')', 'para_2.write_text(\'{"assignment":', '"java-assignm...
567,463
tobegit3hub/deep_image_model
variables.py
get_variables_by_suffix
get_variables_by_suffix
Gets the list of variables that end with the given suffix.
[ "Gets", "the", "list", "of", "variables", "that", "end", "with", "the", "given", "suffix." ]
def get_variables_by_suffix(suffix, scope=None): return get_variables(scope=scope, suffix=suffix)
['def', 'get_variables_by_suffix(suffix,', 'scope=None):', 'return', 'get_variables(scope=scope,', 'suffix=suffix)']
181,318
lishunyao97/Pun-GAN
train.py
print_step_info
print_step_info
Print all info at the current global step.
[ "Print", "all", "info", "at", "the", "current", "global", "step." ]
def print_step_info(prefix, global_step, info, result_summary, log_f): utils.print_out('%sstep %d lr %g step-time %.2fs wps %.2fK ppl %.2f gN %.2f %s, %s' % (prefix, global_step, info['learning_rate'], info['avg_step_time'], info['speed'], info['train_ppl'], info['avg_grad_norm'], result_summary, time.ctime()), log...
['def', 'print_step_info(prefix,', 'global_step,', 'info,', 'result_summary,', 'log_f):', "utils.print_out('%sstep", '%d', 'lr', '%g', 'step-time', '%.2fs', 'wps', '%.2fK', 'ppl', '%.2f', 'gN', '%.2f', '%s,', "%s'", '%', '(prefix,', 'global_step,', "info['learning_rate'],", "info['avg_step_time'],", "info['speed'],", "...
818,805
surafelml/adapt-mnmt
losses.py
cross_entropy_loss
cross_entropy_loss
Computes the cross entropy loss.
[ "Computes", "the", "cross", "entropy", "loss." ]
def cross_entropy_loss(logits, labels, label_smoothing=0.0, mode=tf.estimator.ModeKeys.TRAIN): cross_entropy = _softmax_cross_entropy(logits, labels, label_smoothing, mode) loss = tf.reduce_sum(cross_entropy) loss_normalizer = tf.cast(tf.shape(cross_entropy)[0], loss.dtype) return (loss, loss_normalizer...
['def', 'cross_entropy_loss(logits,', 'labels,', 'label_smoothing=0.0,', 'mode=tf.estimator.ModeKeys.TRAIN):', 'cross_entropy', '=', '_softmax_cross_entropy(logits,', 'labels,', 'label_smoothing,', 'mode)', 'loss', '=', 'tf.reduce_sum(cross_entropy)', 'loss_normalizer', '=', 'tf.cast(tf.shape(cross_entropy)[0],', 'loss...
407,864
TengXiaoDai/DistributedCrawling
locale.py
atof
atof
Parses a string as a float according to the locale settings.
[ "Parses", "a", "string", "as", "a", "float", "according", "to", "the", "locale", "settings." ]
def atof(string, func=float): return func(delocalize(string))
['def', 'atof(string,', 'func=float):', 'return', 'func(delocalize(string))']
187,856
rifqind/Agent-Programs-3KS1
utils.py
generate_lorem_ipsum
generate_lorem_ipsum
Generate some lorem ipsum for the template.
[ "Generate", "some", "lorem", "ipsum", "for", "the", "template." ]
def generate_lorem_ipsum(n=5, html=True, min=20, max=100): from jinja2.constants import LOREM_IPSUM_WORDS from random import choice, randrange words = LOREM_IPSUM_WORDS.split() result = [] for _ in range(n): next_capitalized = True last_comma = last_fullstop = 0 word = None ...
['def', 'generate_lorem_ipsum(n=5,', 'html=True,', 'min=20,', 'max=100):', 'from', 'jinja2.constants', 'import', 'LOREM_IPSUM_WORDS', 'from', 'random', 'import', 'choice,', 'randrange', 'words', '=', 'LOREM_IPSUM_WORDS.split()', 'result', '=', '[]', 'for', '_', 'in', 'range(n):', 'next_capitalized', '=', 'True', 'last_...
42,397
thuml/Transfer-Learning-Library
ibn.py
resnet101_ibn_b
resnet101_ibn_b
Constructs a ResNet-101-IBN-b model.
[ "Constructs", "a", "ResNet-101-IBN-b", "model." ]
def resnet101_ibn_b(pretrained=False): model = IBNNet(block=Bottleneck, layers=[3, 4, 23, 3], ibn_cfg=('b', 'b', None, None)) if pretrained: model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet101_ibn_b']), strict=False) return model
['def', 'resnet101_ibn_b(pretrained=False):', 'model', '=', 'IBNNet(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', "ibn_cfg=('b',", "'b',", 'None,', 'None))', 'if', 'pretrained:', "model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet101_ibn_b']),", 'strict=False)', 'return', 'model']
921,166
nicknochnack/RealTimeSignLanguageTFJS
nn_layers.py
make_divisible
make_divisible
This is to ensure that all layers have channels that are divisible by 8.
[ "This", "is", "to", "ensure", "that", "all", "layers", "have", "channels", "that", "are", "divisible", "by", "8." ]
def make_divisible(value: float, divisor: int, min_value: Optional[float]=None) -> int: if min_value is None: min_value = divisor new_value = max(min_value, int(value + divisor / 2) // divisor * divisor) if new_value < 0.9 * value: new_value += divisor return new_value
['def', 'make_divisible(value:', 'float,', 'divisor:', 'int,', 'min_value:', 'Optional[float]=None)', '->', 'int:', 'if', 'min_value', 'is', 'None:', 'min_value', '=', 'divisor', 'new_value', '=', 'max(min_value,', 'int(value', '+', 'divisor', '/', '2)', '//', 'divisor', '*', 'divisor)', 'if', 'new_value', '<', '0.9', ...
850,854
holoviz-topics/EarthML
dodo.py
task_small_data_setup
task_small_data_setup
Experimental: Create catalog from real and stubs; substitute for real catalog.
[ "Experimental:", "Create", "catalog", "from", "real", "and", "stubs;", "substitute", "for", "real", "catalog." ]
def task_small_data_setup(): def create_joined_catalog(root='', path='examples', filename='catalog.yml'): import yaml paths = _prepare_paths(root, path, filename) if os.path.exists(paths['temp']): print("Fail: Temp file already exists - try 'doit small_data_cleanup'") ...
['def', 'task_small_data_setup():', 'def', "create_joined_catalog(root='',", "path='examples',", "filename='catalog.yml'):", 'import', 'yaml', 'paths', '=', '_prepare_paths(root,', 'path,', 'filename)', 'if', "os.path.exists(paths['temp']):", 'print("Fail:', 'Temp', 'file', 'already', 'exists', '-', 'try', "'doit", 'sm...
556,318
rudranil723/mini-main
utils.py
handle_error_response
handle_error_response
Translates an error response from an OAuth operation into an OAuthError exception.
[ "Translates", "an", "error", "response", "from", "an", "OAuth", "operation", "into", "an", "OAuthError", "exception." ]
def handle_error_response(response_body): try: error_components = [] error_data = json.loads(response_body) error_components.append('Error code {}'.format(error_data['error'])) if 'error_description' in error_data: error_components.append(': {}'.format(error_data['error_d...
['def', 'handle_error_response(response_body):', 'try:', 'error_components', '=', '[]', 'error_data', '=', 'json.loads(response_body)', "error_components.append('Error", 'code', "{}'.format(error_data['error']))", 'if', "'error_description'", 'in', 'error_data:', "error_components.append(':", "{}'.format(error_data['er...
318,227
aimclub/FEDOT
utils.py
ts_deviance
ts_deviance
This function computes average module of difference between neighboring elements of time series.
[ "This", "function", "computes", "average", "module", "of", "difference", "between", "neighboring", "elements", "of", "time", "series." ]
def ts_deviance(ts: np.array): return np.mean(np.abs(np.diff(ts)))
['def', 'ts_deviance(ts:', 'np.array):', 'return', 'np.mean(np.abs(np.diff(ts)))']
545,929
aamini/evidential-deep-learning
__init__.py
get_correct_model
get_correct_model
Hacky helper function to grab the right model for a given dataset and trainer.
[ "Hacky", "helper", "function", "to", "grab", "the", "right", "model", "for", "a", "given", "dataset", "and", "trainer." ]
def get_correct_model(dataset, trainer): dataset_loader = globals()[dataset] trainer_lookup = trainer.__name__.lower() model_pointer = dataset_loader.__dict__[trainer_lookup] return model_pointer
['def', 'get_correct_model(dataset,', 'trainer):', 'dataset_loader', '=', 'globals()[dataset]', 'trainer_lookup', '=', 'trainer.__name__.lower()', 'model_pointer', '=', 'dataset_loader.__dict__[trainer_lookup]', 'return', 'model_pointer']
563,522
shenyunhang/PDSL
test_time_augmentation_avg.py
transform_proposals
transform_proposals
Apply transformations to the proposals in dataset_dict, if any.
[ "Apply", "transformations", "to", "the", "proposals", "in", "dataset_dict,", "if", "any." ]
def transform_proposals(dataset_dict, image_shape, transforms, *, proposal_topk, min_box_size=0): if 'proposal_file' in dataset_dict: return transform_proposals_seg(dataset_dict, image_shape, transforms, proposal_topk=proposal_topk) boxes = dataset_dict['proposals'].proposal_boxes.tensor.cpu().numpy() ...
['def', 'transform_proposals(dataset_dict,', 'image_shape,', 'transforms,', '*,', 'proposal_topk,', 'min_box_size=0):', 'if', "'proposal_file'", 'in', 'dataset_dict:', 'return', 'transform_proposals_seg(dataset_dict,', 'image_shape,', 'transforms,', 'proposal_topk=proposal_topk)', 'boxes', '=', "dataset_dict['proposals...
279,492
huawei-noah/xingtian
necks.py
make_res_layer_from_code
make_res_layer_from_code
Make res layer from code.
[ "Make", "res", "layer", "from", "code." ]
def make_res_layer_from_code(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False, code=None): if code is None: return make_res_layer(block, inplanes, planes, blocks, stride, dilation, style, with_cp) strides = map(int, code) layers = [] for stride in strides: ...
['def', 'make_res_layer_from_code(block,', 'inplanes,', 'planes,', 'blocks,', 'stride=1,', 'dilation=1,', "style='pytorch',", 'with_cp=False,', 'code=None):', 'if', 'code', 'is', 'None:', 'return', 'make_res_layer(block,', 'inplanes,', 'planes,', 'blocks,', 'stride,', 'dilation,', 'style,', 'with_cp)', 'strides', '=', ...
962,916
sunishsheth2009/ChatterBot
baseparser.py
ConfigOptionParser.get_default_values
get_default_values
Overridding to make updating the defaults after instantiation of the option parser possible, update_defaults() does the dirty work.
[ "Overridding", "to", "make", "updating", "the", "defaults", "after", "instantiation", "of", "the", "option", "parser", "possible,", "update_defaults()", "does", "the", "dirty", "work." ]
def get_default_values(self): if not self.process_default_values: return optparse.Values(self.defaults) defaults = self.update_defaults(self.defaults.copy()) for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): o...
['def', 'get_default_values(self):', 'if', 'not', 'self.process_default_values:', 'return', 'optparse.Values(self.defaults)', 'defaults', '=', 'self.update_defaults(self.defaults.copy())', 'for', 'option', 'in', 'self._get_all_options():', 'default', '=', 'defaults.get(option.dest)', 'if', 'isinstance(default,', 'strin...
532,774
enlite-ai/maze
maze_cli.py
set_matplotlib_backend
set_matplotlib_backend
Switch matplotlib backend for maze runs on headless machines to Agg (non-interactive).
[ "Switch", "matplotlib", "backend", "for", "maze", "runs", "on", "headless", "machines", "to", "Agg", "(non-interactive)." ]
def set_matplotlib_backend() -> None: if not os.environ.get('MPLBACKEND') and (not os.environ.get('DISPLAY')): BColors.print_colored(f'INFO: No display detected! Switching matplotlib to headless backend Agg!', color=BColors.OKBLUE) matplotlib.use('Agg')
['def', 'set_matplotlib_backend()', '->', 'None:', 'if', 'not', "os.environ.get('MPLBACKEND')", 'and', '(not', "os.environ.get('DISPLAY')):", "BColors.print_colored(f'INFO:", 'No', 'display', 'detected!', 'Switching', 'matplotlib', 'to', 'headless', 'backend', "Agg!',", 'color=BColors.OKBLUE)', "matplotlib.use('Agg')"]
646,473
jbwang1997/CrossKD
transforms.py
cat_boxes
cat_boxes
Concatenate boxes with type of tensor or box type.
[ "Concatenate", "boxes", "with", "type", "of", "tensor", "or", "box", "type." ]
def cat_boxes(data_list: List[Union[Tensor, BaseBoxes]], dim: int=0) -> Union[Tensor, BaseBoxes]: if data_list and isinstance(data_list[0], BaseBoxes): return data_list[0].cat(data_list, dim=dim) else: return torch.cat(data_list, dim=dim)
['def', 'cat_boxes(data_list:', 'List[Union[Tensor,', 'BaseBoxes]],', 'dim:', 'int=0)', '->', 'Union[Tensor,', 'BaseBoxes]:', 'if', 'data_list', 'and', 'isinstance(data_list[0],', 'BaseBoxes):', 'return', 'data_list[0].cat(data_list,', 'dim=dim)', 'else:', 'return', 'torch.cat(data_list,', 'dim=dim)']
491,720
deepmind/meltingpot
territory.py
create_avatar_and_associated_objects
create_avatar_and_associated_objects
Returns list of avatars and their associated marking objects.
[ "Returns", "list", "of", "avatars", "and", "their", "associated", "marking", "objects." ]
def create_avatar_and_associated_objects(num_players): avatar_objects = [] additional_objects = [] for player_idx in range(0, num_players): game_object = create_avatar_object(player_idx) avatar_objects.append(game_object) marking_object = create_marking_overlay(player_idx) ad...
['def', 'create_avatar_and_associated_objects(num_players):', 'avatar_objects', '=', '[]', 'additional_objects', '=', '[]', 'for', 'player_idx', 'in', 'range(0,', 'num_players):', 'game_object', '=', 'create_avatar_object(player_idx)', 'avatar_objects.append(game_object)', 'marking_object', '=', 'create_marking_overlay...
285,489
eora-ai/torchok
vit.py
vit_tiny_patch16_384
vit_tiny_patch16_384
ViT-Tiny (Vit-Ti/16) @ 384x384.
[ "ViT-Tiny", "(Vit-Ti/16)", "@", "384x384." ]
def vit_tiny_patch16_384(pretrained=False, **kwargs): model_kwargs = dict(patch_size=16, embed_dim=192, depth=12, num_heads=3, **kwargs) model = _create_vision_transformer('vit_tiny_patch16_384', pretrained=pretrained, **model_kwargs) return model
['def', 'vit_tiny_patch16_384(pretrained=False,', '**kwargs):', 'model_kwargs', '=', 'dict(patch_size=16,', 'embed_dim=192,', 'depth=12,', 'num_heads=3,', '**kwargs)', 'model', '=', "_create_vision_transformer('vit_tiny_patch16_384',", 'pretrained=pretrained,', '**model_kwargs)', 'return', 'model']
903,259
Ruturaj123/Flowchart-Detection
estimators.py
TimeSeriesRegressor.build_raw_serving_input_receiver_fn
build_raw_serving_input_receiver_fn
Build an input_receiver_fn for export_savedmodel which accepts arrays.
[ "Build", "an", "input_receiver_fn", "for", "export_savedmodel", "which", "accepts", "arrays." ]
def build_raw_serving_input_receiver_fn(self, exogenous_features=None, default_batch_size=None, default_series_length=None): if exogenous_features is None: exogenous_features = {} def _serving_input_receiver_fn(): placeholders = {} placeholders[feature_keys.TrainEvalFeatures.TIMES] = ar...
['def', 'build_raw_serving_input_receiver_fn(self,', 'exogenous_features=None,', 'default_batch_size=None,', 'default_series_length=None):', 'if', 'exogenous_features', 'is', 'None:', 'exogenous_features', '=', '{}', 'def', '_serving_input_receiver_fn():', 'placeholders', '=', '{}', 'placeholders[feature_keys.TrainEval...
604,637
lartpang/PySODEvalToolkit
cal_sod_matrics.py
cal_image_matrics
cal_image_matrics
Save the results of all models on different datasets in a `npy` file in the form of a dictionary.
[ "Save", "the", "results", "of", "all", "models", "on", "different", "datasets", "in", "a", "`npy`", "file", "in", "the", "form", "of", "a", "dictionary." ]
def cal_image_matrics(sheet_name: str='results', txt_path: str='', to_append: bool=True, xlsx_path: str='', methods_info: dict=None, datasets_info: dict=None, curves_npy_path: str='./curves.npy', metrics_npy_path: str='./metrics.npy', num_bits: int=3, num_workers: int=2, ncols_tqdm: int=79, metric_names: tuple=('sm', '...
['def', 'cal_image_matrics(sheet_name:', "str='results',", 'txt_path:', "str='',", 'to_append:', 'bool=True,', 'xlsx_path:', "str='',", 'methods_info:', 'dict=None,', 'datasets_info:', 'dict=None,', 'curves_npy_path:', "str='./curves.npy',", 'metrics_npy_path:', "str='./metrics.npy',", 'num_bits:', 'int=3,', 'num_worke...
809,440
AgnostiqHQ/covalent
workflow_stack_test.py
test_electrons_with_positional_args
test_electrons_with_positional_args
Test to check whether an electron can be called with positional arguments inside a lattice.
[ "Test", "to", "check", "whether", "an", "electron", "can", "be", "called", "with", "positional", "arguments", "inside", "a", "lattice." ]
def test_electrons_with_positional_args(): @ct.electron def test_func(a, b): return a + b @ct.lattice def workflow(a, b): return test_func(a, b) dispatch_id = ct.dispatch(workflow)(a=1, b=2) workflow_result = rm.get_result(dispatch_id, wait=True) rm._delete_result(dispatch_...
['def', 'test_electrons_with_positional_args():', '@ct.electron', 'def', 'test_func(a,', 'b):', 'return', 'a', '+', 'b', '@ct.lattice', 'def', 'workflow(a,', 'b):', 'return', 'test_func(a,', 'b)', 'dispatch_id', '=', 'ct.dispatch(workflow)(a=1,', 'b=2)', 'workflow_result', '=', 'rm.get_result(dispatch_id,', 'wait=True)...
490,066
instadeepai/jumanji
utils.py
get_mined_board
get_mined_board
Compute the board with 1 in mine locations, otherwise 0.
[ "Compute", "the", "board", "with", "1", "in", "mine", "locations,", "otherwise", "0." ]
def get_mined_board(state: State) -> chex.Array: return jnp.zeros((state.board.shape[-1] * state.board.shape[-2],), dtype=jnp.int32).at[state.flat_mine_locations].set(IS_MINE)
['def', 'get_mined_board(state:', 'State)', '->', 'chex.Array:', 'return', 'jnp.zeros((state.board.shape[-1]', '*', 'state.board.shape[-2],),', 'dtype=jnp.int32).at[state.flat_mine_locations].set(IS_MINE)']
594,081
ryu-ed/SpaceInvaders_Ros
runtime.py
ObjCSubclass.classmethod
classmethod
Function decorator for class methods.
[ "Function", "decorator", "for", "class", "methods." ]
def classmethod(self, encoding): encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) def decorator(f): def objc_class_method(objc_cls, objc_cmd, *args): py_cls = ObjCClass(objc_cls) py...
['def', 'classmethod(self,', 'encoding):', 'encoding', '=', 'ensure_bytes(encoding)', 'typecodes', '=', 'parse_type_encoding(encoding)', 'typecodes.insert(1,', "b'@:')", 'encoding', '=', "b''.join(typecodes)", 'def', 'decorator(f):', 'def', 'objc_class_method(objc_cls,', 'objc_cmd,', '*args):', 'py_cls', '=', 'ObjCClas...
369,631
flow-project/flow
rewards.py
boolean_action_penalty
boolean_action_penalty
Penalize boolean actions that indicate a switch.
[ "Penalize", "boolean", "actions", "that", "indicate", "a", "switch." ]
def boolean_action_penalty(discrete_actions, gain=1.0): return gain * np.sum(discrete_actions)
['def', 'boolean_action_penalty(discrete_actions,', 'gain=1.0):', 'return', 'gain', '*', 'np.sum(discrete_actions)']
212,084