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
enyac-group/NeuralPower
base.py
BaseLayer.layertype
layertype
The type of this layer.
[ "The", "type", "of", "this", "layer." ]
def layertype(self): return self._layertype
['def', 'layertype(self):', 'return', 'self._layertype']
293,452
liang-hou/slimgan
slimmable_sngan_base.py
SlimmableSNGANBaseDiscriminator.train_step
train_step
Train step function for discirminator.
[ "Train", "step", "function", "for", "discirminator." ]
def train_step(self, real_batch, netG, optD, log_data, device=None, global_step=None, **kwargs): self.zero_grad() (real_images, _) = real_batch batch_size = real_images.shape[0] errD = [] for width_mult in FLAGS.width_mult_list: FLAGS.width_mult = width_mult fake_images = netG.genera...
['def', 'train_step(self,', 'real_batch,', 'netG,', 'optD,', 'log_data,', 'device=None,', 'global_step=None,', '**kwargs):', 'self.zero_grad()', '(real_images,', '_)', '=', 'real_batch', 'batch_size', '=', 'real_images.shape[0]', 'errD', '=', '[]', 'for', 'width_mult', 'in', 'FLAGS.width_mult_list:', 'FLAGS.width_mult'...
878,318
blavad/marl
agent.py
TrainableAgent.update_exploration
update_exploration
Update the exploration process.
[ "Update", "the", "exploration", "process." ]
def update_exploration(self, t): self.exploration.update(t)
['def', 'update_exploration(self,', 't):', 'self.exploration.update(t)']
627,886
jeffnyman/pacumen
environment.py
Environment.get_current_state
get_current_state
Returns the current state of the environment.
[ "Returns", "the", "current", "state", "of", "the", "environment." ]
def get_current_state(self): abstract()
['def', 'get_current_state(self):', 'abstract()']
255,931
alugupta/ares
utils.py
is_distributed
is_distributed
Return True if distributed environment has been initialized.
[ "Return", "True", "if", "distributed", "environment", "has", "been", "initialized." ]
def is_distributed() -> bool: return dist.is_available() and dist.is_initialized()
['def', 'is_distributed()', '->', 'bool:', 'return', 'dist.is_available()', 'and', 'dist.is_initialized()']
402,086
dvlab-research/FocalsConv
oss.py
OSSPath.stem
stem
The final path component, minus its last suffix.
[ "The", "final", "path", "component,", "minus", "its", "last", "suffix." ]
def stem(self): name = self.name i = name.rfind('.') if 0 < i < len(name) - 1: return name[:i] else: return name
['def', 'stem(self):', 'name', '=', 'self.name', 'i', '=', "name.rfind('.')", 'if', '0', '<', 'i', '<', 'len(name)', '-', '1:', 'return', 'name[:i]', 'else:', 'return', 'name']
608,103
yinyunie/ScenePriors
test_acos_linear_extrapolation.py
TestAcosLinearExtrapolation.test_acos
test_acos
Tests whether the function returns correct outputs inside/outside the bounds.
[ "Tests", "whether", "the", "function", "returns", "correct", "outputs", "inside/outside", "the", "bounds." ]
def test_acos(self, batch_size: int=10000): x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size) bounds = 1 - 10.0 ** torch.linspace(-1, -5, 5) for lower_bound in -bounds: for upper_bound in bounds: if upper_bound < lower_bound: continue self....
['def', 'test_acos(self,', 'batch_size:', 'int=10000):', 'x', '=', 'TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size)', 'bounds', '=', '1', '-', '10.0', '**', 'torch.linspace(-1,', '-5,', '5)', 'for', 'lower_bound', 'in', '-bounds:', 'for', 'upper_bound', 'in', 'bounds:', 'if', 'upper_bound', '<', 'lowe...
329,970
WHU-ZQH/E2S2
utils.py
pad_sequence
pad_sequence
Pad extra left/right contexts to the sequence.
[ "Pad", "extra", "left/right", "contexts", "to", "the", "sequence." ]
def pad_sequence(sequence: Tensor, time_axis: int, extra_left_context: int=0, extra_right_context: int=0) -> Tensor: if extra_left_context == 0 and extra_right_context == 0: return sequence tensors_to_concat = [] if extra_left_context: size = (extra_left_context,) fill_value = 0 ...
['def', 'pad_sequence(sequence:', 'Tensor,', 'time_axis:', 'int,', 'extra_left_context:', 'int=0,', 'extra_right_context:', 'int=0)', '->', 'Tensor:', 'if', 'extra_left_context', '==', '0', 'and', 'extra_right_context', '==', '0:', 'return', 'sequence', 'tensors_to_concat', '=', '[]', 'if', 'extra_left_context:', 'size...
555,976
ShuLiu1993/PANet
voc_eval.py
parse_rec
parse_rec
Parse a PASCAL VOC xml file.
[ "Parse", "a", "PASCAL", "VOC", "xml", "file." ]
def parse_rec(filename): tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struc...
['def', 'parse_rec(filename):', 'tree', '=', 'ET.parse(filename)', 'objects', '=', '[]', 'for', 'obj', 'in', "tree.findall('object'):", 'obj_struct', '=', '{}', "obj_struct['name']", '=', "obj.find('name').text", "obj_struct['pose']", '=', "obj.find('pose').text", "obj_struct['truncated']", '=', "int(obj.find('truncate...
778,725
43Carrig/recurrent_neural_networks_practice
function.py
FuncGraph.internal_captures
internal_captures
Placeholders in this function corresponding captured tensors.
[ "Placeholders", "in", "this", "function", "corresponding", "captured", "tensors." ]
def internal_captures(self): return list(self.captures.values())
['def', 'internal_captures(self):', 'return', 'list(self.captures.values())']
336,147
amartya-k/vision
vision_transformer.py
interpolate_embeddings
interpolate_embeddings
This function helps interpolate positional embeddings during checkpoint loading, especially when you want to apply a pre-trained model on images with different resolution.
[ "This", "function", "helps", "interpolate", "positional", "embeddings", "during", "checkpoint", "loading,", "especially", "when", "you", "want", "to", "apply", "a", "pre-trained", "model", "on", "images", "with", "different", "resolution." ]
def interpolate_embeddings(image_size: int, patch_size: int, model_state: 'OrderedDict[str, torch.Tensor]', interpolation_mode: str='bicubic', reset_heads: bool=False) -> 'OrderedDict[str, torch.Tensor]': pos_embedding = model_state['encoder.pos_embedding'] (n, seq_length, hidden_dim) = pos_embedding.shape ...
['def', 'interpolate_embeddings(image_size:', 'int,', 'patch_size:', 'int,', 'model_state:', "'OrderedDict[str,", "torch.Tensor]',", 'interpolation_mode:', "str='bicubic',", 'reset_heads:', 'bool=False)', '->', "'OrderedDict[str,", "torch.Tensor]':", 'pos_embedding', '=', "model_state['encoder.pos_embedding']", '(n,', ...
958,792
deephyper/deephyper
_ray_storage.py
RayStorage.load_all_job_ids
load_all_job_ids
Loads the identifiers of all recorded jobs in the search.
[ "Loads", "the", "identifiers", "of", "all", "recorded", "jobs", "in", "the", "search." ]
def load_all_job_ids(self, search_id: Hashable) -> List[Hashable]: return ray.get(self.memory_storage_actor.load_all_job_ids.remote(search_id))
['def', 'load_all_job_ids(self,', 'search_id:', 'Hashable)', '->', 'List[Hashable]:', 'return', 'ray.get(self.memory_storage_actor.load_all_job_ids.remote(search_id))']
520,840
jimtin/Stock_Comparison
modeline.py
get_filetype_from_buffer
get_filetype_from_buffer
Scan the buffer for modelines and return filetype if one is found.
[ "Scan", "the", "buffer", "for", "modelines", "and", "return", "filetype", "if", "one", "is", "found." ]
def get_filetype_from_buffer(buf, max_lines=5): lines = buf.splitlines() for l in lines[-1:-max_lines - 1:-1]: ret = get_filetype_from_line(l) if ret: return ret for l in lines[max_lines:0:-1]: ret = get_filetype_from_line(l) if ret: return ret ret...
['def', 'get_filetype_from_buffer(buf,', 'max_lines=5):', 'lines', '=', 'buf.splitlines()', 'for', 'l', 'in', 'lines[-1:-max_lines', '-', '1:-1]:', 'ret', '=', 'get_filetype_from_line(l)', 'if', 'ret:', 'return', 'ret', 'for', 'l', 'in', 'lines[max_lines:0:-1]:', 'ret', '=', 'get_filetype_from_line(l)', 'if', 'ret:', '...
358,407
amazon-science/progressive-coordinate-transforms
image_utils.py
plot_points_on_image
plot_points_on_image
Plots points on a camera image.
[ "Plots", "points", "on", "a", "camera", "image." ]
def plot_points_on_image(projected_points, camera_image, rgba_func, bbox_2d, save_path, point_size=5.0): plot_image(camera_image) xs = [] ys = [] colors = [] for point in projected_points: xs.append(point[0]) ys.append(point[1]) colors.append(rgba_func(point[2])) plt.scat...
['def', 'plot_points_on_image(projected_points,', 'camera_image,', 'rgba_func,', 'bbox_2d,', 'save_path,', 'point_size=5.0):', 'plot_image(camera_image)', 'xs', '=', '[]', 'ys', '=', '[]', 'colors', '=', '[]', 'for', 'point', 'in', 'projected_points:', 'xs.append(point[0])', 'ys.append(point[1])', 'colors.append(rgba_f...
817,489
nikos134/Carla-Semantic-Segmentation
Mask_rcnn_test.py
carlaDataset.image_reference
image_reference
Return the carla data of the image.
[ "Return", "the", "carla", "data", "of", "the", "image." ]
def image_reference(self, image_id): info = self.image_info[image_id] if info['source'] == 'carla': return info['id'] else: super(self.__class__).image_reference(self, image_id)
['def', 'image_reference(self,', 'image_id):', 'info', '=', 'self.image_info[image_id]', 'if', "info['source']", '==', "'carla':", 'return', "info['id']", 'else:', 'super(self.__class__).image_reference(self,', 'image_id)']
456,002
AndrewSpano/BSc-Thesis
download_f1kg.py
get_f1kg_texts
get_f1kg_texts
Gets the specified F1KG text files (which do not need parsing, unlike the Perseus files).
[ "Gets", "the", "specified", "F1KG", "text", "files", "(which", "do", "not", "need", "parsing,", "unlike", "the", "Perseus", "files)." ]
def get_f1kg_texts(files): texts = [] for (i, f) in enumerate(files): with open(f, 'r') as fp: texts.append(fp.read()) return texts
['def', 'get_f1kg_texts(files):', 'texts', '=', '[]', 'for', '(i,', 'f)', 'in', 'enumerate(files):', 'with', 'open(f,', "'r')", 'as', 'fp:', 'texts.append(fp.read())', 'return', 'texts']
410,060
RasaHQ/rasa
common.py
module_path_from_instance
module_path_from_instance
Return the module path of an instance's class.
[ "Return", "the", "module", "path", "of", "an", "instance's", "class." ]
def module_path_from_instance(inst: Any) -> Text: return inst.__module__ + '.' + inst.__class__.__name__
['def', 'module_path_from_instance(inst:', 'Any)', '->', 'Text:', 'return', 'inst.__module__', '+', "'.'", '+', 'inst.__class__.__name__']
837,777
neardws/Game-Theoretic-Deep-Reinforcement-Learning
agent_test.py
DistributedAgentTest.test_control_suite
test_control_suite
Tests that the agent can run on the control suite without crashing.
[ "Tests", "that", "the", "agent", "can", "run", "on", "the", "control", "suite", "without", "crashing." ]
def test_control_suite(self): (time_slots, task_list, vehicle_list, edge_list, distance_matrix, channel_condition_matrix, vehicle_index_within_edges, environment_config, environment) = get_default_environment(for_mad5pg=True) spec = make_environment_spec(environment) networks = make_default_MAD3PGNetworks(a...
['def', 'test_control_suite(self):', '(time_slots,', 'task_list,', 'vehicle_list,', 'edge_list,', 'distance_matrix,', 'channel_condition_matrix,', 'vehicle_index_within_edges,', 'environment_config,', 'environment)', '=', 'get_default_environment(for_mad5pg=True)', 'spec', '=', 'make_environment_spec(environment)', 'ne...
199,717
learnables/cherry
rl_tests.py
discount_rewards
discount_rewards
Implementation that works with lists.
[ "Implementation", "that", "works", "with", "lists." ]
def discount_rewards(gamma, rewards, dones, bootstrap=0.0): R = bootstrap discounted = [] length = len(rewards) for t in reversed(range(length)): if dones[t]: R *= 0.0 R = rewards[t] + gamma * R discounted.insert(0, R) return discounted
['def', 'discount_rewards(gamma,', 'rewards,', 'dones,', 'bootstrap=0.0):', 'R', '=', 'bootstrap', 'discounted', '=', '[]', 'length', '=', 'len(rewards)', 'for', 't', 'in', 'reversed(range(length)):', 'if', 'dones[t]:', 'R', '*=', '0.0', 'R', '=', 'rewards[t]', '+', 'gamma', '*', 'R', 'discounted.insert(0,', 'R)', 'ret...
104,978
43Carrig/recurrent_neural_networks_practice
command_parser.py
parse_readable_time_str
parse_readable_time_str
Parses a time string in the format N, Nus, Nms, Ns.
[ "Parses", "a", "time", "string", "in", "the", "format", "N,", "Nus,", "Nms,", "Ns." ]
def parse_readable_time_str(time_str): def parse_positive_float(value_str): value = float(value_str) if value < 0: raise ValueError('Invalid time %s. Time value must be positive.' % value_str) return value time_str = time_str.strip() if time_str.endswith('us'): r...
['def', 'parse_readable_time_str(time_str):', 'def', 'parse_positive_float(value_str):', 'value', '=', 'float(value_str)', 'if', 'value', '<', '0:', 'raise', "ValueError('Invalid", 'time', '%s.', 'Time', 'value', 'must', 'be', "positive.'", '%', 'value_str)', 'return', 'value', 'time_str', '=', 'time_str.strip()', 'if'...
335,863
metadriverse/metadrive
image_to_video.py
image_list_to_video
image_list_to_video
code=mp4v, avc1, x264, h264 etc.
[ "code=mp4v,", "avc1,", "x264,", "h264", "etc." ]
def image_list_to_video(video_name, image_list, code='mp4v'): assert video_name.endswith('.mp4') assert len(image_list) > 0 frame = image_list[0] (height, width, layers) = frame.shape video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*code), 40, (width, height)) for image in tqdm(image_...
['def', 'image_list_to_video(video_name,', 'image_list,', "code='mp4v'):", 'assert', "video_name.endswith('.mp4')", 'assert', 'len(image_list)', '>', '0', 'frame', '=', 'image_list[0]', '(height,', 'width,', 'layers)', '=', 'frame.shape', 'video', '=', 'cv2.VideoWriter(video_name,', 'cv2.VideoWriter_fourcc(*code),', '4...
634,367
rudranil723/mini-main
jwt.py
Credentials.from_service_account_info
from_service_account_info
Creates an Credentials instance from a dictionary.
[ "Creates", "an", "Credentials", "instance", "from", "a", "dictionary." ]
def from_service_account_info(cls, info, **kwargs): signer = _service_account_info.from_dict(info, require=['client_email']) return cls._from_signer_and_info(signer, info, **kwargs)
['def', 'from_service_account_info(cls,', 'info,', '**kwargs):', 'signer', '=', '_service_account_info.from_dict(info,', "require=['client_email'])", 'return', 'cls._from_signer_and_info(signer,', 'info,', '**kwargs)']
317,793
myothida/Supervised-Machine-Learning
_base.py
_AxesBase.draw_artist
draw_artist
Efficiently redraw a single artist.
[ "Efficiently", "redraw", "a", "single", "artist." ]
def draw_artist(self, a): a.draw(self.figure.canvas.get_renderer())
['def', 'draw_artist(self,', 'a):', 'a.draw(self.figure.canvas.get_renderer())']
362,569
weimin17/Object-Detection_HelmetDetection
get_dataset_colormap.py
create_label_colormap
create_label_colormap
Creates a label colormap for the specified dataset.
[ "Creates", "a", "label", "colormap", "for", "the", "specified", "dataset." ]
def create_label_colormap(dataset=_PASCAL): if dataset == _ADE20K: return create_ade20k_label_colormap() elif dataset == _CITYSCAPES: return create_cityscapes_label_colormap() elif dataset == _PASCAL: return create_pascal_label_colormap() else: raise ValueError('Unsupport...
['def', 'create_label_colormap(dataset=_PASCAL):', 'if', 'dataset', '==', '_ADE20K:', 'return', 'create_ade20k_label_colormap()', 'elif', 'dataset', '==', '_CITYSCAPES:', 'return', 'create_cityscapes_label_colormap()', 'elif', 'dataset', '==', '_PASCAL:', 'return', 'create_pascal_label_colormap()', 'else:', 'raise', "V...
749,594
neeharperi/FutureDet
box_np_ops.py
rbbox2d_to_near_bbox
rbbox2d_to_near_bbox
convert rotated bbox to nearest 'standing' or 'lying' bbox.
[ "convert", "rotated", "bbox", "to", "nearest", "'standing'", "or", "'lying'", "bbox." ]
def rbbox2d_to_near_bbox(rbboxes): rots = rbboxes[..., -1] rots_0_pi_div_2 = np.abs(limit_period(rots, 0.5, np.pi)) cond = (rots_0_pi_div_2 > np.pi / 4)[..., np.newaxis] bboxes_center = np.where(cond, rbboxes[:, [0, 1, 3, 2]], rbboxes[:, :4]) bboxes = center_to_minmax_2d(bboxes_center[:, :2], bboxes...
['def', 'rbbox2d_to_near_bbox(rbboxes):', 'rots', '=', 'rbboxes[...,', '-1]', 'rots_0_pi_div_2', '=', 'np.abs(limit_period(rots,', '0.5,', 'np.pi))', 'cond', '=', '(rots_0_pi_div_2', '>', 'np.pi', '/', '4)[...,', 'np.newaxis]', 'bboxes_center', '=', 'np.where(cond,', 'rbboxes[:,', '[0,', '1,', '3,', '2]],', 'rbboxes[:,...
565,722
enuguru/artificial_intelligence_and_machine_learning
io.py
save
save
Pickles object ``p`` and saves it to file ``filename``.
[ "Pickles", "object", "``p``", "and", "saves", "it", "to", "file", "``filename``." ]
def save(p, filename): f = file(filename, 'wb') cPickle.dump(p, f, cPickle.HIGHEST_PROTOCOL) f.close()
['def', 'save(p,', 'filename):', 'f', '=', 'file(filename,', "'wb')", 'cPickle.dump(p,', 'f,', 'cPickle.HIGHEST_PROTOCOL)', 'f.close()']
164,429
RomanoLab/comptox_ai
graph.py
Graph.add_nodes
add_nodes
Add one or more nodes to the graph.
[ "Add", "one", "or", "more", "nodes", "to", "the", "graph." ]
def add_nodes(self, nodes: Union[List[tuple], tuple]): if isinstance(nodes, tuple): self._data.add_node(nodes) elif isinstance(nodes, list): self._data.add_nodes(nodes) else: raise AttributeError('`nodes` must be a node tuple or list of node tuples - got {0}'.format(type(nodes)))
['def', 'add_nodes(self,', 'nodes:', 'Union[List[tuple],', 'tuple]):', 'if', 'isinstance(nodes,', 'tuple):', 'self._data.add_node(nodes)', 'elif', 'isinstance(nodes,', 'list):', 'self._data.add_nodes(nodes)', 'else:', 'raise', "AttributeError('`nodes`", 'must', 'be', 'a', 'node', 'tuple', 'or', 'list', 'of', 'node', 't...
136,127
mfbx9da4/neuron-astrocyte-networks
gfilter.py
Filter.apply
apply
Applies an operation on a population.
[ "Applies", "an", "operation", "on", "a", "population." ]
def apply(self, population): raise NotImplementedError()
['def', 'apply(self,', 'population):', 'raise', 'NotImplementedError()']
722,695
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
real_nvp_multiscale_dataset.py
rec_masked_deconv_coupling
rec_masked_deconv_coupling
Recursion on inverting coupling layers.
[ "Recursion", "on", "inverting", "coupling", "layers." ]
def rec_masked_deconv_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_ log_dif...
['def', 'rec_masked_deconv_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...
109,417
zhaocq-nlp/NJUNMT-tf
rnn_decoder.py
CondAttentionDecoder.default_params
default_params
Returns a dictionary of default parameters of this decoder.
[ "Returns", "a", "dictionary", "of", "default", "parameters", "of", "this", "decoder." ]
def default_params(): return {'attention.class': 'BahdanauAttention', 'attention.params': {}, 'rnn_cell': {'cell_class': 'LSTMCell', 'cell_params': {}, 'dropout_input_keep_prob': 1.0, 'dropout_state_keep_prob': 1.0, 'num_layers': 1}, 'dropout_context_keep_prob': 1.0, 'dropout_hidden_keep_prob': 1.0, 'dropout_embedd...
['def', 'default_params():', 'return', "{'attention.class':", "'BahdanauAttention',", "'attention.params':", '{},', "'rnn_cell':", "{'cell_class':", "'LSTMCell',", "'cell_params':", '{},', "'dropout_input_keep_prob':", '1.0,', "'dropout_state_keep_prob':", '1.0,', "'num_layers':", '1},', "'dropout_context_keep_prob':",...
782,822
openvinotoolkit/training_extensions
config_manager.py
set_workspace
set_workspace
Set workspace path according to arguments.
[ "Set", "workspace", "path", "according", "to", "arguments." ]
def set_workspace(task: str, root: str=None, name: str='otx-workspace'): path = f'{root}/{name}-{task}' if root else f'./{name}-{task}' return path
['def', 'set_workspace(task:', 'str,', 'root:', 'str=None,', 'name:', "str='otx-workspace'):", 'path', '=', "f'{root}/{name}-{task}'", 'if', 'root', 'else', "f'./{name}-{task}'", 'return', 'path']
918,916
simpleai-team/simpleai
models.py
Classifier.classify
classify
Returns the classification for example.
[ "Returns", "the", "classification", "for", "example." ]
def classify(self, example): raise NotImplementedError()
['def', 'classify(self,', 'example):', 'raise', 'NotImplementedError()']
350,615
deepmind/acme
acting.py
make_ensemble_actor_core
make_ensemble_actor_core
Creates an actor core that uses ensemble models.
[ "Creates", "an", "actor", "core", "that", "uses", "ensemble", "models." ]
def make_ensemble_actor_core(networks: mbop_networks.MBOPNetworks, mppi_config: mppi.MPPIConfig, environment_spec: specs.EnvironmentSpec, mean_std: Optional[running_statistics.NestedMeanStd]=None, use_round_robin: bool=True) -> ActorCore: world_model = models.make_ensemble_world_model(networks.world_model_network) ...
['def', 'make_ensemble_actor_core(networks:', 'mbop_networks.MBOPNetworks,', 'mppi_config:', 'mppi.MPPIConfig,', 'environment_spec:', 'specs.EnvironmentSpec,', 'mean_std:', 'Optional[running_statistics.NestedMeanStd]=None,', 'use_round_robin:', 'bool=True)', '->', 'ActorCore:', 'world_model', '=', 'models.make_ensemble...
8,107
salu133445/binarygan
model.py
Model.load_latest
load_latest
Load the model from the latest checkpoint in a directory.
[ "Load", "the", "model", "from", "the", "latest", "checkpoint", "in", "a", "directory." ]
def load_latest(self, checkpoint_dir=None): if checkpoint_dir is None: checkpoint_dir = self.config['checkpoint_dir'] print('[*] Loading checkpoint...') checkpoint_path = tf.train.latest_checkpoint(checkpoint_dir) if checkpoint_path is None: raise ValueError('Checkpoint not found') s...
['def', 'load_latest(self,', 'checkpoint_dir=None):', 'if', 'checkpoint_dir', 'is', 'None:', 'checkpoint_dir', '=', "self.config['checkpoint_dir']", "print('[*]", 'Loading', "checkpoint...')", 'checkpoint_path', '=', 'tf.train.latest_checkpoint(checkpoint_dir)', 'if', 'checkpoint_path', 'is', 'None:', 'raise', "ValueEr...
461,000
matsu0228/nlp-jp
grammar.py
Grammar.dump
dump
Dump the grammar tables to a pickle file.
[ "Dump", "the", "grammar", "tables", "to", "a", "pickle", "file." ]
def dump(self, filename): with open(filename, 'wb') as f: pickle.dump(self.__dict__, f, 2)
['def', 'dump(self,', 'filename):', 'with', 'open(filename,', "'wb')", 'as', 'f:', 'pickle.dump(self.__dict__,', 'f,', '2)']
803,119
tensorly/quantum
op_serializer_test.py
OpSerializerTest.test_can_serialize_operation_subclass
test_can_serialize_operation_subclass
Test can serialize subclass.
[ "Test", "can", "serialize", "subclass." ]
def test_can_serialize_operation_subclass(self, q): serializer = op_serializer.GateOpSerializer(gate_type=GateWithAttribute, serialized_gate_id='my_gate', args=[op_serializer.SerializingArg(serialized_name='my_val', serialized_type=float, op_getter='val')], can_serialize_predicate=lambda x: x.gate.val == 1) sel...
['def', 'test_can_serialize_operation_subclass(self,', 'q):', 'serializer', '=', 'op_serializer.GateOpSerializer(gate_type=GateWithAttribute,', "serialized_gate_id='my_gate',", "args=[op_serializer.SerializingArg(serialized_name='my_val',", 'serialized_type=float,', "op_getter='val')],", 'can_serialize_predicate=lambda...
834,917
santhoshkolloju/Abstractive-Summarization-With-Transfer-
conv_classifiers.py
Conv1DClassifier.layer_outputs
layer_outputs
A list containing output tensors of each layer.
[ "A", "list", "containing", "output", "tensors", "of", "each", "layer." ]
def layer_outputs(self): return self._encoder.layer_outputs
['def', 'layer_outputs(self):', 'return', 'self._encoder.layer_outputs']
406,181
seltzerfish/guardyn
gtest_filter_unittest.py
GTestFilterUnitTest.testFilterDisabledTests
testFilterDisabledTests
Select only the disabled tests to run.
[ "Select", "only", "the", "disabled", "tests", "to", "run." ]
def testFilterDisabledTests(self): self.RunAndVerify('DISABLED_FoobarTest.Test1', []) self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1', ['DISABLED_FoobarTest.Test1']) self.RunAndVerify('*DISABLED_*', []) self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS) self.RunAndVerify(...
['def', 'testFilterDisabledTests(self):', "self.RunAndVerify('DISABLED_FoobarTest.Test1',", '[])', "self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',", "['DISABLED_FoobarTest.Test1'])", "self.RunAndVerify('*DISABLED_*',", '[])', "self.RunAndVerifyAllowingDisabled('*DISABLED_*',", 'DISABLED_TESTS)', "self.R...
572,268
facebookarchive/gnlpy
ipvs_tests.py
TestIpvsClient.test_flush
test_flush
Simply run the flush command.
[ "Simply", "run", "the", "flush", "command." ]
def test_flush(self): self.client.flush()
['def', 'test_flush(self):', 'self.client.flush()']
202,582
zackmcnulty/CSE_446-Machine_Learning
cm.py
revcmap
revcmap
Can only handle specification *data* in dictionary format.
[ "Can", "only", "handle", "specification", "*data*", "in", "dictionary", "format." ]
def revcmap(data): data_r = {} for (key, val) in data.items(): if callable(val): valnew = _reverser(val) else: valnew = [(1.0 - x, y1, y0) for (x, y0, y1) in reversed(val)] data_r[key] = valnew return data_r
['def', 'revcmap(data):', 'data_r', '=', '{}', 'for', '(key,', 'val)', 'in', 'data.items():', 'if', 'callable(val):', 'valnew', '=', '_reverser(val)', 'else:', 'valnew', '=', '[(1.0', '-', 'x,', 'y1,', 'y0)', 'for', '(x,', 'y0,', 'y1)', 'in', 'reversed(val)]', 'data_r[key]', '=', 'valnew', 'return', 'data_r']
194,178
zihuitang/medical_AI_platform
__init__.py
Wm.wm_positionfrom
wm_positionfrom
Instruct the window manager that the position 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", "position", "of", "this", "widget", "shall", "be", "defined", "by", "the", "user", "if", "WHO", "is", "\"user\",", "and", "by", "its", "own", "policy", "if", "WHO", "is", "\"program\"." ]
def wm_positionfrom(self, who=None): return self.tk.call('wm', 'positionfrom', self._w, who)
['def', 'wm_positionfrom(self,', 'who=None):', 'return', "self.tk.call('wm',", "'positionfrom',", 'self._w,', 'who)']
284,180
greydanus/pythonic_ocr
pildriver.py
PILDriver.do_blend
do_blend
usage: blend <image:pic1> <image:pic2> <float:alpha> Replace two images and an alpha with the blended image.
[ "usage:", "blend", "<image:pic1>", "<image:pic2>", "<float:alpha>", "Replace", "two", "images", "and", "an", "alpha", "with", "the", "blended", "image." ]
def do_blend(self): image1 = self.do_pop() image2 = self.do_pop() alpha = float(self.do_pop()) self.push(Image.blend(image1, image2, alpha))
['def', 'do_blend(self):', 'image1', '=', 'self.do_pop()', 'image2', '=', 'self.do_pop()', 'alpha', '=', 'float(self.do_pop())', 'self.push(Image.blend(image1,', 'image2,', 'alpha))']
298,485
Eric3911/OpenAGI
modules.py
DecoderBlockRes4B.prune
prune
Prune the shape of x after transpose convolution.
[ "Prune", "the", "shape", "of", "x", "after", "transpose", "convolution." ]
def prune(self, x, both=False): if both: x = x[:, :, 0:-1, 0:-1] else: x = x[:, :, 0:-1, :] return x
['def', 'prune(self,', 'x,', 'both=False):', 'if', 'both:', 'x', '=', 'x[:,', ':,', '0:-1,', '0:-1]', 'else:', 'x', '=', 'x[:,', ':,', '0:-1,', ':]', 'return', 'x']
250,675
neuroailab/unsup_vvs
model_util.py
projection_head
projection_head
Head for projecting hiddens fo contrastive loss.
[ "Head", "for", "projecting", "hiddens", "fo", "contrastive", "loss." ]
def projection_head(hiddens, is_training, name='head_contrastive'): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): if FLAGS.head_proj_mode == 'none': pass elif FLAGS.head_proj_mode == 'linear': hiddens = linear_layer(hiddens, is_training, FLAGS.head_proj_dim, use_bias=Fal...
['def', 'projection_head(hiddens,', 'is_training,', "name='head_contrastive'):", 'with', 'tf.variable_scope(name,', 'reuse=tf.AUTO_REUSE):', 'if', 'FLAGS.head_proj_mode', '==', "'none':", 'pass', 'elif', 'FLAGS.head_proj_mode', '==', "'linear':", 'hiddens', '=', 'linear_layer(hiddens,', 'is_training,', 'FLAGS.head_proj...
438,455
QData/deepWordBug
cookiejar.py
request_path
request_path
Path component of request-URI, as defined by RFC 2965.
[ "Path", "component", "of", "request-URI,", "as", "defined", "by", "RFC", "2965." ]
def request_path(request): url = request.get_full_url() parts = urlsplit(url) path = escape_path(parts.path) if not path.startswith('/'): path = '/' + path return path
['def', 'request_path(request):', 'url', '=', 'request.get_full_url()', 'parts', '=', 'urlsplit(url)', 'path', '=', 'escape_path(parts.path)', 'if', 'not', "path.startswith('/'):", 'path', '=', "'/'", '+', 'path', 'return', 'path']
543,317
TrellixVulnTeam/Unsupervised_Learning_HFI7
_mysql_builtins.py
update_content
update_content
Overwrite this file with content parsed from MySQL's source code.
[ "Overwrite", "this", "file", "with", "content", "parsed", "from", "MySQL's", "source", "code." ]
def update_content(field_name, content): with open(__file__) as f: data = f.read() re_match = re.compile('^%s\\s*=\\s*\\($.*?^\\s*\\)$' % field_name, re.M | re.S) m = re_match.search(data) if not m: raise ValueError('Could not find an existing definition for %s' % field_name) new_blo...
['def', 'update_content(field_name,', 'content):', 'with', 'open(__file__)', 'as', 'f:', 'data', '=', 'f.read()', 're_match', '=', "re.compile('^%s\\\\s*=\\\\s*\\\\($.*?^\\\\s*\\\\)$'", '%', 'field_name,', 're.M', '|', 're.S)', 'm', '=', 're_match.search(data)', 'if', 'not', 'm:', 'raise', "ValueError('Could", 'not', '...
435,642
RasaHQ/rasa
utils.py
configure_file_logging
configure_file_logging
Configure logging to a file.
[ "Configure", "logging", "to", "a", "file." ]
def configure_file_logging(logger_obj: logging.Logger, log_file: Optional[Text], use_syslog: Optional[bool], syslog_address: Optional[Text]=None, syslog_port: Optional[int]=None, syslog_protocol: Optional[Text]=None) -> None: if use_syslog: formatter = logging.Formatter('%(asctime)s [%(levelname)-5.5s] [%(p...
['def', 'configure_file_logging(logger_obj:', 'logging.Logger,', 'log_file:', 'Optional[Text],', 'use_syslog:', 'Optional[bool],', 'syslog_address:', 'Optional[Text]=None,', 'syslog_port:', 'Optional[int]=None,', 'syslog_protocol:', 'Optional[Text]=None)', '->', 'None:', 'if', 'use_syslog:', 'formatter', '=', "logging....
836,754
clear-nus/MuMMI
dog.py
Physics.ball_to_mouth_distance
ball_to_mouth_distance
Returns the distance from the ball to the mouth.
[ "Returns", "the", "distance", "from", "the", "ball", "to", "the", "mouth." ]
def ball_to_mouth_distance(self): ball_pos = self.named.data.geom_xpos['ball'] upper_bite_pos = self.named.data.site_xpos['upper_bite'] lower_bite_pos = self.named.data.site_xpos['lower_bite'] upper_dist = np.linalg.norm(ball_pos - upper_bite_pos) lower_dist = np.linalg.norm(ball_pos - lower_bite_po...
['def', 'ball_to_mouth_distance(self):', 'ball_pos', '=', "self.named.data.geom_xpos['ball']", 'upper_bite_pos', '=', "self.named.data.site_xpos['upper_bite']", 'lower_bite_pos', '=', "self.named.data.site_xpos['lower_bite']", 'upper_dist', '=', 'np.linalg.norm(ball_pos', '-', 'upper_bite_pos)', 'lower_dist', '=', 'np....
265,945
ZrrSkywalker/I2P-MAE
build.py
build_model_from_cfg
build_model_from_cfg
Build a dataset, defined by `dataset_name`.
[ "Build", "a", "dataset,", "defined", "by", "`dataset_name`." ]
def build_model_from_cfg(cfg, **kwargs): return MODELS.build(cfg, **kwargs)
['def', 'build_model_from_cfg(cfg,', '**kwargs):', 'return', 'MODELS.build(cfg,', '**kwargs)']
571,814
kornia/kornia
test_draw.py
TestDrawPoint.test_draw_point2d_grayscale_third_order
test_draw_point2d_grayscale_third_order
Test plotting multiple [x, y] points on a (1, m, n) image.
[ "Test", "plotting", "multiple", "[x,", "y]", "points", "on", "a", "(1,", "m,", "n)", "image." ]
def test_draw_point2d_grayscale_third_order(self, dtype, device): points = torch.tensor([(1, 3), (2, 4)], device=device) color = torch.tensor([100], dtype=dtype, device=device) img = torch.zeros(1, 8, 8, dtype=dtype, device=device) img = draw_point2d(img, points, color) for (x, y) in points: ...
['def', 'test_draw_point2d_grayscale_third_order(self,', 'dtype,', 'device):', 'points', '=', 'torch.tensor([(1,', '3),', '(2,', '4)],', 'device=device)', 'color', '=', 'torch.tensor([100],', 'dtype=dtype,', 'device=device)', 'img', '=', 'torch.zeros(1,', '8,', '8,', 'dtype=dtype,', 'device=device)', 'img', '=', 'draw_...
622,347
yinyunie/ScenePriors
test_rotation_conversions.py
TestRotationConversion.test_matrix_to_quaternion_corner_case
test_matrix_to_quaternion_corner_case
Check no bad gradients from sqrt(0).
[ "Check", "no", "bad", "gradients", "from", "sqrt(0)." ]
def test_matrix_to_quaternion_corner_case(self): matrix = torch.eye(3, requires_grad=True) target = torch.Tensor([0.984808, 0, 0.174, 0]) optimizer = torch.optim.Adam([matrix], lr=0.05) optimizer.zero_grad() q = matrix_to_quaternion(matrix) loss = torch.sum((q - target) ** 2) loss.backward()...
['def', 'test_matrix_to_quaternion_corner_case(self):', 'matrix', '=', 'torch.eye(3,', 'requires_grad=True)', 'target', '=', 'torch.Tensor([0.984808,', '0,', '0.174,', '0])', 'optimizer', '=', 'torch.optim.Adam([matrix],', 'lr=0.05)', 'optimizer.zero_grad()', 'q', '=', 'matrix_to_quaternion(matrix)', 'loss', '=', 'torc...
330,151
megvii-research/MSCL
base.py
BaseHead.loss
loss
Calculate the loss given output ``cls_score``, target ``labels``.
[ "Calculate", "the", "loss", "given", "output", "``cls_score``,", "target", "``labels``." ]
def loss(self, cls_score, labels, **kwargs): losses = dict() if labels.shape == torch.Size([]): labels = labels.unsqueeze(0) elif labels.dim() == 1 and labels.size()[0] == self.num_classes and (cls_score.size()[0] == 1): labels = labels.unsqueeze(0) if not self.multi_class and cls_score....
['def', 'loss(self,', 'cls_score,', 'labels,', '**kwargs):', 'losses', '=', 'dict()', 'if', 'labels.shape', '==', 'torch.Size([]):', 'labels', '=', 'labels.unsqueeze(0)', 'elif', 'labels.dim()', '==', '1', 'and', 'labels.size()[0]', '==', 'self.num_classes', 'and', '(cls_score.size()[0]', '==', '1):', 'labels', '=', 'l...
264,875
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_main.py
cifar10_model_fn
cifar10_model_fn
Model function for CIFAR-10.
[ "Model", "function", "for", "CIFAR-10." ]
def cifar10_model_fn(features, labels, mode, params): tf.summary.image('images', features, max_outputs=6) network = resnet_model.cifar10_resnet_v2_generator(params['resnet_size'], _NUM_CLASSES, params['data_format']) inputs = tf.reshape(features, [-1, _HEIGHT, _WIDTH, _DEPTH]) logits = network(inputs, m...
['def', 'cifar10_model_fn(features,', 'labels,', 'mode,', 'params):', "tf.summary.image('images',", 'features,', 'max_outputs=6)', 'network', '=', "resnet_model.cifar10_resnet_v2_generator(params['resnet_size'],", '_NUM_CLASSES,', "params['data_format'])", 'inputs', '=', 'tf.reshape(features,', '[-1,', '_HEIGHT,', '_WI...
13,973
DeepGraphLearning/torchdrug
dictionary.py
PerfectHash.hash
hash
Apply the level-1 hash function to the keys.
[ "Apply", "the", "level-1", "hash", "function", "to", "the", "keys." ]
def hash(self, keys): keys = keys % self.prime hash = (keys * self.weight % self.prime).sum(dim=-1) + self.bias return hash % self.prime % self.num_output
['def', 'hash(self,', 'keys):', 'keys', '=', 'keys', '%', 'self.prime', 'hash', '=', '(keys', '*', 'self.weight', '%', 'self.prime).sum(dim=-1)', '+', 'self.bias', 'return', 'hash', '%', 'self.prime', '%', 'self.num_output']
902,663
GeekLiB/keras
theano_backend.py
squeeze
squeeze
Remove a 1-dimension from the tensor at index "axis".
[ "Remove", "a", "1-dimension", "from", "the", "tensor", "at", "index", "\"axis\"." ]
def squeeze(x, axis): shape = list(x.shape) shape.pop(axis) return T.reshape(x, tuple(shape))
['def', 'squeeze(x,', 'axis):', 'shape', '=', 'list(x.shape)', 'shape.pop(axis)', 'return', 'T.reshape(x,', 'tuple(shape))']
247,854
google-research/text-to-text-transfer-transformer
mtf_model.py
MtfModel.train
train
Train the model on the given Mixture or Task.
[ "Train", "the", "model", "on", "the", "given", "Mixture", "or", "Task." ]
def train(self, mixture_or_task_name, steps, init_checkpoint=None, split='train'): vocabulary = mesh_transformer.get_vocabulary(mixture_or_task_name) dataset_fn = functools.partial(mesh_transformer.mesh_train_dataset_fn, mixture_or_task_name=mixture_or_task_name) mtf_utils.train_model(self.estimator(vocabul...
['def', 'train(self,', 'mixture_or_task_name,', 'steps,', 'init_checkpoint=None,', "split='train'):", 'vocabulary', '=', 'mesh_transformer.get_vocabulary(mixture_or_task_name)', 'dataset_fn', '=', 'functools.partial(mesh_transformer.mesh_train_dataset_fn,', 'mixture_or_task_name=mixture_or_task_name)', 'mtf_utils.train...
925,643
weimin17/Object-Detection_HelmetDetection
util.py
get_generator_conditioning
get_generator_conditioning
Generates TFGAN conditioning inputs for evaluation.
[ "Generates", "TFGAN", "conditioning", "inputs", "for", "evaluation." ]
def get_generator_conditioning(batch_size, num_classes): if batch_size % num_classes != 0: raise ValueError('`batch_size` %i must be evenly divisible by `num_classes` %i.' % (batch_size, num_classes)) labels = [lbl for lbl in xrange(num_classes) for _ in xrange(batch_size // num_classes)] return tf....
['def', 'get_generator_conditioning(batch_size,', 'num_classes):', 'if', 'batch_size', '%', 'num_classes', '!=', '0:', 'raise', "ValueError('`batch_size`", '%i', 'must', 'be', 'evenly', 'divisible', 'by', '`num_classes`', "%i.'", '%', '(batch_size,', 'num_classes))', 'labels', '=', '[lbl', 'for', 'lbl', 'in', 'xrange(n...
762,843
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjuiStateWrapper.nrect
nrect
number of rectangles used.
[ "number", "of", "rectangles", "used." ]
def nrect(self): return self._ptr.contents.nrect
['def', 'nrect(self):', 'return', 'self._ptr.contents.nrect']
440,664
Trusted-AI/AIX360
gce.py
GroupedCEExplainer.set_params
set_params
Set parameters for the explainer.
[ "Set", "parameters", "for", "the", "explainer." ]
def set_params(self, *argv, **kwargs): self._params.update(kwargs) return self
['def', 'set_params(self,', '*argv,', '**kwargs):', 'self._params.update(kwargs)', 'return', 'self']
413,267
AiIsBetter/computer_vision
yacs.py
CfgNode.clone
clone
Recursively copy this CfgNode.
[ "Recursively", "copy", "this", "CfgNode." ]
def clone(self): return copy.deepcopy(self)
['def', 'clone(self):', 'return', 'copy.deepcopy(self)']
475,750
elastic/eland
transformers.py
_SentenceTransformerWrapper.forward
forward
Wrap the input and output to conform to the native process interface.
[ "Wrap", "the", "input", "and", "output", "to", "conform", "to", "the", "native", "process", "interface." ]
def forward(self, input_ids: Tensor, attention_mask: Tensor, token_type_ids: Tensor, position_ids: Tensor) -> Tensor: inputs = {'input_ids': input_ids, 'attention_mask': attention_mask, 'token_type_ids': token_type_ids, 'position_ids': position_ids} if isinstance(self._hf_model.config, transformers.DistilBertCo...
['def', 'forward(self,', 'input_ids:', 'Tensor,', 'attention_mask:', 'Tensor,', 'token_type_ids:', 'Tensor,', 'position_ids:', 'Tensor)', '->', 'Tensor:', 'inputs', '=', "{'input_ids':", 'input_ids,', "'attention_mask':", 'attention_mask,', "'token_type_ids':", 'token_type_ids,', "'position_ids':", 'position_ids}', 'if...
561,363
jymChen/Diaformer
modeling_utils.py
PreTrainedModel.prune_heads
prune_heads
Prunes heads of the base model.
[ "Prunes", "heads", "of", "the", "base", "model." ]
def prune_heads(self, heads_to_prune): base_model = getattr(self, self.base_model_prefix, self) base_model._prune_heads(heads_to_prune)
['def', 'prune_heads(self,', 'heads_to_prune):', 'base_model', '=', 'getattr(self,', 'self.base_model_prefix,', 'self)', 'base_model._prune_heads(heads_to_prune)']
550,120
alex-petrenko/sample-factory
doom_model.py
make_vizdoom_encoder
make_vizdoom_encoder
Factory function as required by the API.
[ "Factory", "function", "as", "required", "by", "the", "API." ]
def make_vizdoom_encoder(cfg: Config, obs_space: ObsSpace) -> Encoder: return VizdoomEncoder(cfg, obs_space)
['def', 'make_vizdoom_encoder(cfg:', 'Config,', 'obs_space:', 'ObsSpace)', '->', 'Encoder:', 'return', 'VizdoomEncoder(cfg,', 'obs_space)']
329,089
materialsvirtuallab/mlearn
calcs.py
DefectFormation.calculate
calculate
Calculate the vacancy formation given Potential class.
[ "Calculate", "the", "vacancy", "formation", "given", "Potential", "class." ]
def calculate(self): with ScratchDir('.'): (input_file, energy_per_atom, num_atoms) = self._setup() p = subprocess.Popen([self.LMP_EXE, '-in', input_file], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = 'LAMMPS exited...
['def', 'calculate(self):', 'with', "ScratchDir('.'):", '(input_file,', 'energy_per_atom,', 'num_atoms)', '=', 'self._setup()', 'p', '=', 'subprocess.Popen([self.LMP_EXE,', "'-in',", 'input_file],', 'stdout=subprocess.PIPE)', 'stdout', '=', 'p.communicate()[0]', 'rc', '=', 'p.returncode', 'if', 'rc', '!=', '0:', 'error...
630,334
Megvii-BaseDetection/DynamicRouting
catalog.py
Metadata.set
set
Set multiple metadata with kwargs.
[ "Set", "multiple", "metadata", "with", "kwargs." ]
def set(self, **kwargs): for (k, v) in kwargs.items(): setattr(self, k, v) return self
['def', 'set(self,', '**kwargs):', 'for', '(k,', 'v)', 'in', 'kwargs.items():', 'setattr(self,', 'k,', 'v)', 'return', 'self']
555,151
rudranil723/mini-main
polygon.py
Polygon.num_interior_rings
num_interior_rings
Return the number of interior rings.
[ "Return", "the", "number", "of", "interior", "rings." ]
def num_interior_rings(self): return capi.get_nrings(self.ptr)
['def', 'num_interior_rings(self):', 'return', 'capi.get_nrings(self.ptr)']
315,363
MushroomRL/mushroom-rl
spaces.py
Discrete.shape
shape
Returns: The shape of the space that is always (1,).
[ "Returns:", "The", "shape", "of", "the", "space", "that", "is", "always", "(1,)." ]
def shape(self): return (1,)
['def', 'shape(self):', 'return', '(1,)']
266,163
ryu-ed/SpaceInvaders_Ros
settings.py
should_skip
should_skip
Returns True if the file and/or folder should be skipped based on the passed in settings.
[ "Returns", "True", "if", "the", "file", "and/or", "folder", "should", "be", "skipped", "based", "on", "the", "passed", "in", "settings." ]
def should_skip(filename, config, path=''): os_path = os.path.join(path, filename) normalized_path = os_path.replace('\\', '/') if normalized_path[1:2] == ':': normalized_path = normalized_path[2:] if path and config['safety_excludes']: check_exclude = '/' + filename.replace('\\', '/') +...
['def', 'should_skip(filename,', 'config,', "path=''):", 'os_path', '=', 'os.path.join(path,', 'filename)', 'normalized_path', '=', "os_path.replace('\\\\',", "'/')", 'if', 'normalized_path[1:2]', '==', "':':", 'normalized_path', '=', 'normalized_path[2:]', 'if', 'path', 'and', "config['safety_excludes']:", 'check_excl...
396,149
metadriverse/metadrive
pg_map_manager.py
PGMapManager.clear_objects
clear_objects
As Map instance should not be recycled, we will forcefully destroy useless map instances.
[ "As", "Map", "instance", "should", "not", "be", "recycled,", "we", "will", "forcefully", "destroy", "useless", "map", "instances." ]
def clear_objects(self, *args, **kwargs): return super(PGMapManager, self).clear_objects(*args, force_destroy=True, **kwargs)
['def', 'clear_objects(self,', '*args,', '**kwargs):', 'return', 'super(PGMapManager,', 'self).clear_objects(*args,', 'force_destroy=True,', '**kwargs)']
633,899
ilya16/MultINN
multinn.py
MultINN.loss
loss
MultINN model loss op.
[ "MultINN", "model", "loss", "op." ]
def loss(self): return self._model.loss
['def', 'loss(self):', 'return', 'self._model.loss']
644,290
tobegit3hub/deep_image_model
linear_test.py
LinearClassifierTest.testMultiClass_MatrixData_Labels1D
testMultiClass_MatrixData_Labels1D
Same as the last test, but labels shape is [150] instead of [150, 1].
[ "Same", "as", "the", "last", "test,", "but", "labels", "shape", "is", "[150]", "instead", "of", "[150,", "1]." ]
def testMultiClass_MatrixData_Labels1D(self): def _input_fn(): iris = tf.contrib.learn.datasets.load_iris() return ({'feature': tf.constant(iris.data, dtype=tf.float32)}, tf.constant(iris.target, shape=[150], dtype=tf.int32)) feature_column = tf.contrib.layers.real_valued_column('feature', dime...
['def', 'testMultiClass_MatrixData_Labels1D(self):', 'def', '_input_fn():', 'iris', '=', 'tf.contrib.learn.datasets.load_iris()', 'return', "({'feature':", 'tf.constant(iris.data,', 'dtype=tf.float32)},', 'tf.constant(iris.target,', 'shape=[150],', 'dtype=tf.int32))', 'feature_column', '=', "tf.contrib.layers.real_valu...
181,749
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.mat_reflectance
mat_reflectance
reflectance (0: disable) (nmat x 1).
[ "reflectance", "(0:", "disable)", "(nmat", "x", "1)." ]
def mat_reflectance(self): return util.buf_to_npy(self._ptr.contents.mat_reflectance, (self.nmat,))
['def', 'mat_reflectance(self):', 'return', 'util.buf_to_npy(self._ptr.contents.mat_reflectance,', '(self.nmat,))']
440,389
aws/sagemaker-python-sdk
_feature_processor_lineage.py
FeatureProcessorLineageHandler.upsert_tags_for_lineage_resources
upsert_tags_for_lineage_resources
Add or update tags for lineage resources using tags attached to sagemaker pipeline as source of truth.
[ "Add", "or", "update", "tags", "for", "lineage", "resources", "using", "tags", "attached", "to", "sagemaker", "pipeline", "as", "source", "of", "truth." ]
def upsert_tags_for_lineage_resources(self, tags: List[Dict[str, str]]) -> None: if not tags: return pipeline_context: Context = self._get_pipeline_context() current_pipeline_version_context: Context = self._get_pipeline_version_context(last_update_time=pipeline_context.properties[LAST_UPDATE_TIME])...
['def', 'upsert_tags_for_lineage_resources(self,', 'tags:', 'List[Dict[str,', 'str]])', '->', 'None:', 'if', 'not', 'tags:', 'return', 'pipeline_context:', 'Context', '=', 'self._get_pipeline_context()', 'current_pipeline_version_context:', 'Context', '=', 'self._get_pipeline_version_context(last_update_time=pipeline_c...
830,111
sktime/sktime
test_mlflow_sktime_model_export.py
test_signature_and_example_for_pyfunc_predict
test_signature_and_example_for_pyfunc_predict
Test saving of mlflow signature and example for pyfunc predict.
[ "Test", "saving", "of", "mlflow", "signature", "and", "example", "for", "pyfunc", "predict." ]
def test_signature_and_example_for_pyfunc_predict(auto_arima_model, model_path, test_data_airline, use_signature, use_example): from mlflow.models import Model, infer_signature from mlflow.models.utils import _read_example from sktime.utils import mlflow_sktime model_path_primary = model_path.joinpath('...
['def', 'test_signature_and_example_for_pyfunc_predict(auto_arima_model,', 'model_path,', 'test_data_airline,', 'use_signature,', 'use_example):', 'from', 'mlflow.models', 'import', 'Model,', 'infer_signature', 'from', 'mlflow.models.utils', 'import', '_read_example', 'from', 'sktime.utils', 'import', 'mlflow_sktime', ...
878,060
myothida/Supervised-Machine-Learning
_win32_console.py
GetConsoleMode
GetConsoleMode
Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
[ "Retrieves", "the", "current", "input", "mode", "of", "a", "console's", "input", "buffer", "or", "the", "current", "output", "mode", "of", "a", "console", "screen", "buffer." ]
def GetConsoleMode(std_handle: wintypes.HANDLE) -> int: console_mode = wintypes.DWORD() success = bool(_GetConsoleMode(std_handle, console_mode)) if not success: raise LegacyWindowsError('Unable to get legacy Windows Console Mode') return console_mode.value
['def', 'GetConsoleMode(std_handle:', 'wintypes.HANDLE)', '->', 'int:', 'console_mode', '=', 'wintypes.DWORD()', 'success', '=', 'bool(_GetConsoleMode(std_handle,', 'console_mode))', 'if', 'not', 'success:', 'raise', "LegacyWindowsError('Unable", 'to', 'get', 'legacy', 'Windows', 'Console', "Mode')", 'return', 'console...
445,162
oarriaga/paz
boxes.py
extract_bounding_box_corners
extract_bounding_box_corners
Extracts the (x_min, y_min, z_min) and the (x_max, y_max, z_max) coordinates from an array of points3D # Arguments points3D: Array (num_points, 3) # Returns Left-down-bottom corner (x_min, y_min, z_min) and right-up-top (x_max, y_max, z_max) corner.
[ "Extracts", "the", "(x_min,", "y_min,", "z_min)", "and", "the", "(x_max,", "y_max,", "z_max)", "coordinates", "from", "an", "array", "of", "points3D", "#", "Arguments", "points3D:", "Array", "(num_points,", "3)", "#", "Returns", "Left-down-bottom", "corner", "(x_m...
def extract_bounding_box_corners(points3D): XYZ_min = np.min(points3D, axis=0) XYZ_max = np.max(points3D, axis=0) return (XYZ_min, XYZ_max)
['def', 'extract_bounding_box_corners(points3D):', 'XYZ_min', '=', 'np.min(points3D,', 'axis=0)', 'XYZ_max', '=', 'np.max(points3D,', 'axis=0)', 'return', '(XYZ_min,', 'XYZ_max)']
765,241
nhsx/SynthVAE
hyper_transformer.py
HyperTransformer.fit
fit
Fit the transformers to the data.
[ "Fit", "the", "transformers", "to", "the", "data." ]
def fit(self, data): self._input_columns = list(data.columns) self._populate_field_data_types(data) for field in self.field_transformers: if self._field_in_data(field, data): data = self._fit_field_transformer(data, field, self.field_transformers[field]) for (field, data_type) in sel...
['def', 'fit(self,', 'data):', 'self._input_columns', '=', 'list(data.columns)', 'self._populate_field_data_types(data)', 'for', 'field', 'in', 'self.field_transformers:', 'if', 'self._field_in_data(field,', 'data):', 'data', '=', 'self._fit_field_transformer(data,', 'field,', 'self.field_transformers[field])', 'for', ...
906,274
amazon-science/semimtr-text-recognition
utils.py
MyDataParallel.gather
gather
Gathers tensors from different GPUs on a specified device (-1 means the CPU).
[ "Gathers", "tensors", "from", "different", "GPUs", "on", "a", "specified", "device", "(-1", "means", "the", "CPU)." ]
def gather(self, outputs, target_device): def gather_map(outputs): out = outputs[0] if isinstance(out, (str, int, float)): return out if isinstance(out, list) and isinstance(out[0], str): return [o for out in outputs for o in out] if isinstance(out, torch.Ten...
['def', 'gather(self,', 'outputs,', 'target_device):', 'def', 'gather_map(outputs):', 'out', '=', 'outputs[0]', 'if', 'isinstance(out,', '(str,', 'int,', 'float)):', 'return', 'out', 'if', 'isinstance(out,', 'list)', 'and', 'isinstance(out[0],', 'str):', 'return', '[o', 'for', 'out', 'in', 'outputs', 'for', 'o', 'in', ...
343,581
enuguru/artificial_intelligence_and_machine_learning
analyzers.py
IDAnalyzer
IDAnalyzer
Deprecated, just use an IDTokenizer directly, with a LowercaseFilter if desired.
[ "Deprecated,", "just", "use", "an", "IDTokenizer", "directly,", "with", "a", "LowercaseFilter", "if", "desired." ]
def IDAnalyzer(lowercase=False): tokenizer = IDTokenizer() if lowercase: tokenizer = tokenizer | LowercaseFilter() return tokenizer
['def', 'IDAnalyzer(lowercase=False):', 'tokenizer', '=', 'IDTokenizer()', 'if', 'lowercase:', 'tokenizer', '=', 'tokenizer', '|', 'LowercaseFilter()', 'return', 'tokenizer']
162,355
kubeflow/pipelines
compiler_utils.py
get_dependencies
get_dependencies
Gets dependent groups and tasks for all tasks and groups.
[ "Gets", "dependent", "groups", "and", "tasks", "for", "all", "tasks", "and", "groups." ]
def get_dependencies(pipeline: pipeline_context.Pipeline, task_name_to_parent_groups: Mapping[str, List[str]], group_name_to_parent_groups: Mapping[str, List[str]], group_name_to_group: Mapping[str, tasks_group.TasksGroup], condition_channels: Dict[str, pipeline_channel.PipelineChannel]) -> Mapping[str, List[GroupOrTas...
['def', 'get_dependencies(pipeline:', 'pipeline_context.Pipeline,', 'task_name_to_parent_groups:', 'Mapping[str,', 'List[str]],', 'group_name_to_parent_groups:', 'Mapping[str,', 'List[str]],', 'group_name_to_group:', 'Mapping[str,', 'tasks_group.TasksGroup],', 'condition_channels:', 'Dict[str,', 'pipeline_channel.Pipel...
779,926
OpenMDAO/OpenMDAO-Framework
log.py
_LogListener.port
port
Port server is listening on.
[ "Port", "server", "is", "listening", "on." ]
def port(self): return self._port
['def', 'port(self):', 'return', 'self._port']
276,292
Victor-Martinez-Pozos/stacked_capsule_autoencoders
data_config.py
make_mnist
make_mnist
Creates the MNIST dataset.
[ "Creates", "the", "MNIST", "dataset." ]
def make_mnist(config): def to_float(x): return tf.to_float(x) / 255.0 transform = [to_float] if config.canvas_size != 28: transform.append(functools.partial(preprocess.pad_and_shift, output_size=config.canvas_size, shift=None)) batch_size = config.batch_size res = AttrDict(trainset...
['def', 'make_mnist(config):', 'def', 'to_float(x):', 'return', 'tf.to_float(x)', '/', '255.0', 'transform', '=', '[to_float]', 'if', 'config.canvas_size', '!=', '28:', 'transform.append(functools.partial(preprocess.pad_and_shift,', 'output_size=config.canvas_size,', 'shift=None))', 'batch_size', '=', 'config.batch_siz...
873,326
calico/basenji
basenji_test_genes.py
gene_table
gene_table
Print a gene-based statistics table and scatter plot for the given target indexes.
[ "Print", "a", "gene-based", "statistics", "table", "and", "scatter", "plot", "for", "the", "given", "target", "indexes." ]
def gene_table(gene_targets, gene_preds, gene_iter, target_labels, target_indexes, out_prefix, plot_scatter): num_genes = gene_targets.shape[0] table_out = open('%s_table.txt' % out_prefix, 'w') for ti in target_indexes: gti = np.log2(gene_targets[:, ti].astype('float32') + 1) gpi = np.log2(...
['def', 'gene_table(gene_targets,', 'gene_preds,', 'gene_iter,', 'target_labels,', 'target_indexes,', 'out_prefix,', 'plot_scatter):', 'num_genes', '=', 'gene_targets.shape[0]', 'table_out', '=', "open('%s_table.txt'", '%', 'out_prefix,', "'w')", 'for', 'ti', 'in', 'target_indexes:', 'gti', '=', 'np.log2(gene_targets[:...
94,888
zcablii/LSKNet
gmm.py
GaussianMixture.get_score
get_score
Computes the log-likelihood of the data under the model.
[ "Computes", "the", "log-likelihood", "of", "the", "data", "under", "the", "model." ]
def get_score(self, x, sum_data=True): weighted_log_prob = self.estimate_log_prob(x) + torch.log(self.pi).unsqueeze(1) per_sample_score = torch.logsumexp(weighted_log_prob, dim=2) if sum_data: return per_sample_score.sum(dim=1) else: return per_sample_score.squeeze(-1)
['def', 'get_score(self,', 'x,', 'sum_data=True):', 'weighted_log_prob', '=', 'self.estimate_log_prob(x)', '+', 'torch.log(self.pi).unsqueeze(1)', 'per_sample_score', '=', 'torch.logsumexp(weighted_log_prob,', 'dim=2)', 'if', 'sum_data:', 'return', 'per_sample_score.sum(dim=1)', 'else:', 'return', 'per_sample_score.squ...
616,068
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pdb.py
Pdb.do_continue
do_continue
c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.
[ "c(ont(inue))", "Continue", "execution,", "only", "stop", "when", "a", "breakpoint", "is", "encountered." ]
def do_continue(self, arg): if not self.nosigint: try: Pdb._previous_sigint_handler = signal.signal(signal.SIGINT, self.sigint_handler) except ValueError: pass self.set_continue() return 1
['def', 'do_continue(self,', 'arg):', 'if', 'not', 'self.nosigint:', 'try:', 'Pdb._previous_sigint_handler', '=', 'signal.signal(signal.SIGINT,', 'self.sigint_handler)', 'except', 'ValueError:', 'pass', 'self.set_continue()', 'return', '1']
429,125
matsu0228/nlp-jp
serverextensions.py
ListServerExtensionsApp.list_server_extensions
list_server_extensions
List all enabled and disabled server extensions, by config path Enabled extensions are validated, potentially generating warnings.
[ "List", "all", "enabled", "and", "disabled", "server", "extensions,", "by", "config", "path", "Enabled", "extensions", "are", "validated,", "potentially", "generating", "warnings." ]
def list_server_extensions(self): config_dirs = jupyter_config_path() for config_dir in config_dirs: cm = BaseJSONConfigManager(parent=self, config_dir=config_dir) data = cm.get('jupyter_notebook_config') server_extensions = data.setdefault('NotebookApp', {}).setdefault('nbserver_extensi...
['def', 'list_server_extensions(self):', 'config_dirs', '=', 'jupyter_config_path()', 'for', 'config_dir', 'in', 'config_dirs:', 'cm', '=', 'BaseJSONConfigManager(parent=self,', 'config_dir=config_dir)', 'data', '=', "cm.get('jupyter_notebook_config')", 'server_extensions', '=', "data.setdefault('NotebookApp',", "{}).s...
790,509
matsu0228/nlp-jp
nbbase.py
new_notebook
new_notebook
Create a notebook by name, id and a list of worksheets.
[ "Create", "a", "notebook", "by", "name,", "id", "and", "a", "list", "of", "worksheets." ]
def new_notebook(cells=None): nb = NotebookNode() if cells is not None: nb.cells = cells else: nb.cells = [] return nb
['def', 'new_notebook(cells=None):', 'nb', '=', 'NotebookNode()', 'if', 'cells', 'is', 'not', 'None:', 'nb.cells', '=', 'cells', 'else:', 'nb.cells', '=', '[]', 'return', 'nb']
790,381
rudranil723/mini-main
_metadata.py
ping
ping
Checks to see if the metadata server is available.
[ "Checks", "to", "see", "if", "the", "metadata", "server", "is", "available." ]
def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3): retries = 0 while retries < retry_count: try: response = request(url=_METADATA_IP_ROOT, method='GET', headers=_METADATA_HEADERS, timeout=timeout) metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER) ...
['def', 'ping(request,', 'timeout=_METADATA_DEFAULT_TIMEOUT,', 'retry_count=3):', 'retries', '=', '0', 'while', 'retries', '<', 'retry_count:', 'try:', 'response', '=', 'request(url=_METADATA_IP_ROOT,', "method='GET',", 'headers=_METADATA_HEADERS,', 'timeout=timeout)', 'metadata_flavor', '=', 'response.headers.get(_MET...
317,838
matsu0228/nlp-jp
compilerop.py
CachingCompiler.reset_compiler_flags
reset_compiler_flags
Reset compiler flags to default state.
[ "Reset", "compiler", "flags", "to", "default", "state." ]
def reset_compiler_flags(self): self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
['def', 'reset_compiler_flags(self):', 'self.flags', '=', 'codeop.PyCF_DONT_IMPLY_DEDENT']
786,514
zihuitang/medical_AI_platform
test_subprocess.py
POSIXProcessTestCase.test_small_errpipe_write_fd
test_small_errpipe_write_fd
Issue #15798: Popen should work when stdio fds are available.
[ "Issue", "#15798:", "Popen", "should", "work", "when", "stdio", "fds", "are", "available." ]
def test_small_errpipe_write_fd(self): new_stdin = os.dup(0) new_stdout = os.dup(1) try: os.close(0) os.close(1) subprocess.Popen([sys.executable, '-c', "print('AssertionError:0:CLOEXEC failure.')"]).wait() finally: os.dup2(new_stdin, 0) os.dup2(new_stdout, 1) ...
['def', 'test_small_errpipe_write_fd(self):', 'new_stdin', '=', 'os.dup(0)', 'new_stdout', '=', 'os.dup(1)', 'try:', 'os.close(0)', 'os.close(1)', 'subprocess.Popen([sys.executable,', "'-c',", '"print(\'AssertionError:0:CLOEXEC', 'failure.\')"]).wait()', 'finally:', 'os.dup2(new_stdin,', '0)', 'os.dup2(new_stdout,', '1...
283,649
nilearn/nilearn
test_load_confounds.py
test_non_steady_state
test_non_steady_state
Warn when 'non_steady_state' is in strategy.
[ "Warn", "when", "'non_steady_state'", "is", "in", "strategy." ]
def test_non_steady_state(tmp_path): (img, _) = create_tmp_filepath(tmp_path, copy_confounds=True) warning_message = 'Non-steady state' with pytest.warns(UserWarning, match=warning_message): load_confounds(img, strategy=('non_steady_state', 'motion'))
['def', 'test_non_steady_state(tmp_path):', '(img,', '_)', '=', 'create_tmp_filepath(tmp_path,', 'copy_confounds=True)', 'warning_message', '=', "'Non-steady", "state'", 'with', 'pytest.warns(UserWarning,', 'match=warning_message):', 'load_confounds(img,', "strategy=('non_steady_state',", "'motion'))"]
723,939
hamza-murad/AALU
natural_language_understanding_v1.py
KeywordsResult.from_dict
from_dict
Initialize a KeywordsResult object from a json dictionary.
[ "Initialize", "a", "KeywordsResult", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'KeywordsResult': args = {} valid_keys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class KeywordsResult: ' + ', '.join(bad_ke...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'KeywordsResult':", 'args', '=', '{}', 'valid_keys', '=', "['count',", "'relevance',", "'text',", "'emotion',", "'sentiment']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'i...
5,941
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
datasets.py
Dataset.size
size
Dataset size (number of samples).
[ "Dataset", "size", "(number", "of", "samples)." ]
def size(self): return len(self.data)
['def', 'size(self):', 'return', 'len(self.data)']
55,587
BMW-InnovationLab/BMW-Semantic--Training-GUI
utils.py
Track.is_deleted
is_deleted
Returns True if this track is dead and should be deleted.
[ "Returns", "True", "if", "this", "track", "is", "dead", "and", "should", "be", "deleted." ]
def is_deleted(self): return self.state == TrackState.Deleted
['def', 'is_deleted(self):', 'return', 'self.state', '==', 'TrackState.Deleted']
463,596
PaddlePaddle/Paddle3D
base_model.py
Base3DModel.input_spec
input_spec
Input Tensor specifier when exporting the model.
[ "Input", "Tensor", "specifier", "when", "exporting", "the", "model." ]
def input_spec(self) -> paddle.static.InputSpec: data = {_input['name']: paddle.static.InputSpec(**_input) for _input in self.inputs} return [data]
['def', 'input_spec(self)', '->', 'paddle.static.InputSpec:', 'data', '=', "{_input['name']:", 'paddle.static.InputSpec(**_input)', 'for', '_input', 'in', 'self.inputs}', 'return', '[data]']
777,372
zihuitang/medical_AI_platform
test_statistics.py
UnivariateCommonMixin.prepare_data
prepare_data
Return int data for various tests.
[ "Return", "int", "data", "for", "various", "tests." ]
def prepare_data(self): data = list(range(10)) while data == sorted(data): random.shuffle(data) return data
['def', 'prepare_data(self):', 'data', '=', 'list(range(10))', 'while', 'data', '==', 'sorted(data):', 'random.shuffle(data)', 'return', 'data']
283,628
kornia/kornia
extract_patches.py
compute_padding
compute_padding
Compute required padding to ensure chaining of :func:`extract_tensor_patches` and :func:`combine_tensor_patches` produces expected result.
[ "Compute", "required", "padding", "to", "ensure", "chaining", "of", ":func:`extract_tensor_patches`", "and", ":func:`combine_tensor_patches`", "produces", "expected", "result." ]
def compute_padding(original_size: Union[int, Tuple[int, int]], window_size: Union[int, Tuple[int, int]]) -> Tuple[int, int, int, int]: original_size = cast(Tuple[int, int], _pair(original_size)) window_size = cast(Tuple[int, int], _pair(window_size)) def paddim(dim1: int, dim2: int) -> Tuple[int, int]: ...
['def', 'compute_padding(original_size:', 'Union[int,', 'Tuple[int,', 'int]],', 'window_size:', 'Union[int,', 'Tuple[int,', 'int]])', '->', 'Tuple[int,', 'int,', 'int,', 'int]:', 'original_size', '=', 'cast(Tuple[int,', 'int],', '_pair(original_size))', 'window_size', '=', 'cast(Tuple[int,', 'int],', '_pair(window_size...
621,582
instadeepai/jumanji
utils.py
can_move_left_row_cond
can_move_left_row_cond
Terminate loop when valid move is found or origin reaches end of row.
[ "Terminate", "loop", "when", "valid", "move", "is", "found", "or", "origin", "reaches", "end", "of", "row." ]
def can_move_left_row_cond(carry: CanMoveCarry) -> chex.Numeric: return ~carry.can_move & (carry.origin_idx < carry.row.shape[0])
['def', 'can_move_left_row_cond(carry:', 'CanMoveCarry)', '->', 'chex.Numeric:', 'return', '~carry.can_move', '&', '(carry.origin_idx', '<', 'carry.row.shape[0])']
594,005
alibaba/EasyCV
pose_transforms.py
rotate_point
rotate_point
Rotate a point by an angle.
[ "Rotate", "a", "point", "by", "an", "angle." ]
def rotate_point(pt, angle_rad): assert len(pt) == 2 (sn, cs) = (np.sin(angle_rad), np.cos(angle_rad)) new_x = pt[0] * cs - pt[1] * sn new_y = pt[0] * sn + pt[1] * cs rotated_pt = [new_x, new_y] return rotated_pt
['def', 'rotate_point(pt,', 'angle_rad):', 'assert', 'len(pt)', '==', '2', '(sn,', 'cs)', '=', '(np.sin(angle_rad),', 'np.cos(angle_rad))', 'new_x', '=', 'pt[0]', '*', 'cs', '-', 'pt[1]', '*', 'sn', 'new_y', '=', 'pt[0]', '*', 'sn', '+', 'pt[1]', '*', 'cs', 'rotated_pt', '=', '[new_x,', 'new_y]', 'return', 'rotated_pt'...
546,383
LUMIA-Group/Leveraging-Self-Supervised-Learning-for-AVSR
general.py
num_params
num_params
Function that outputs the number of total and trainable paramters in the model.
[ "Function", "that", "outputs", "the", "number", "of", "total", "and", "trainable", "paramters", "in", "the", "model." ]
def num_params(model): numTotalParams = sum([params.numel() for params in model.parameters()]) numTrainableParams = sum([params.numel() for params in model.parameters() if params.requires_grad]) return (numTotalParams, numTrainableParams)
['def', 'num_params(model):', 'numTotalParams', '=', 'sum([params.numel()', 'for', 'params', 'in', 'model.parameters()])', 'numTrainableParams', '=', 'sum([params.numel()', 'for', 'params', 'in', 'model.parameters()', 'if', 'params.requires_grad])', 'return', '(numTotalParams,', 'numTrainableParams)']
216,550