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
kujason/monopsr
evaluator_utils.py
run_kitti_native_script_with_low_iou
run_kitti_native_script_with_low_iou
Runs the low iou kitti native code script.
[ "Runs", "the", "low", "iou", "kitti", "native", "code", "script." ]
def run_kitti_native_script_with_low_iou(checkpoint_name, data_split, kitti_score_threshold, global_step): eval_script_dir = monopsr.top_dir() + '/scripts/offline_eval/kitti_native_eval' run_eval_script = eval_script_dir + '/run_eval_low_iou.sh' kitti_predictions_dir = monopsr.data_dir() + '/outputs/{}/pred...
['def', 'run_kitti_native_script_with_low_iou(checkpoint_name,', 'data_split,', 'kitti_score_threshold,', 'global_step):', 'eval_script_dir', '=', 'monopsr.top_dir()', '+', "'/scripts/offline_eval/kitti_native_eval'", 'run_eval_script', '=', 'eval_script_dir', '+', "'/run_eval_low_iou.sh'", 'kitti_predictions_dir', '='...
655,293
matsu0228/nlp-jp
decorator.py
decorate
decorate
decorate(func, caller) decorates a function using a caller.
[ "decorate(func,", "caller)", "decorates", "a", "function", "using", "a", "caller." ]
def decorate(func, caller): evaldict = dict(_call_=caller, _func_=func) fun = FunctionMaker.create(func, 'return _call_(_func_, %(shortsignature)s)', evaldict, __wrapped__=func) if hasattr(func, '__qualname__'): fun.__qualname__ = func.__qualname__ return fun
['def', 'decorate(func,', 'caller):', 'evaldict', '=', 'dict(_call_=caller,', '_func_=func)', 'fun', '=', 'FunctionMaker.create(func,', "'return", '_call_(_func_,', "%(shortsignature)s)',", 'evaldict,', '__wrapped__=func)', 'if', 'hasattr(func,', "'__qualname__'):", 'fun.__qualname__', '=', 'func.__qualname__', 'return...
783,678
yinyunie/ScenePriors
test_materials.py
TestMaterials.test_initialize_materials_broadcast_fail
test_initialize_materials_broadcast_fail
Batch dims have to be the same or 1.
[ "Batch", "dims", "have", "to", "be", "the", "same", "or", "1." ]
def test_initialize_materials_broadcast_fail(self): with self.assertRaises(ValueError): Materials(ambient_color=torch.randn(10, 3), diffuse_color=torch.randn(15, 3))
['def', 'test_initialize_materials_broadcast_fail(self):', 'with', 'self.assertRaises(ValueError):', 'Materials(ambient_color=torch.randn(10,', '3),', 'diffuse_color=torch.randn(15,', '3))']
330,041
43Carrig/recurrent_neural_networks_practice
input_ops.py
auto_shard_dataset
auto_shard_dataset
Shard the input pipeline by sharding the underlying list of files.
[ "Shard", "the", "input", "pipeline", "by", "sharding", "the", "underlying", "list", "of", "files." ]
def auto_shard_dataset(dataset, num_shards, index): def _auto_shard_impl(dataset, found_reader_op): if not found_reader_op: if isinstance(dataset, readers.TextLineDataset) or isinstance(dataset, readers.FixedLengthRecordDataset): filenames_tensor = dataset._filenames ...
['def', 'auto_shard_dataset(dataset,', 'num_shards,', 'index):', 'def', '_auto_shard_impl(dataset,', 'found_reader_op):', 'if', 'not', 'found_reader_op:', 'if', 'isinstance(dataset,', 'readers.TextLineDataset)', 'or', 'isinstance(dataset,', 'readers.FixedLengthRecordDataset):', 'filenames_tensor', '=', 'dataset._filena...
312,779
rudranil723/mini-main
pycodestyle.py
StyleGuide.input_file
input_file
Run all checks on a Python source file.
[ "Run", "all", "checks", "on", "a", "Python", "source", "file." ]
def input_file(self, filename, lines=None, expected=None, line_offset=0): if self.options.verbose: print('checking %s' % filename) fchecker = self.checker_class(filename, lines=lines, options=self.options) return fchecker.check_all(expected=expected, line_offset=line_offset)
['def', 'input_file(self,', 'filename,', 'lines=None,', 'expected=None,', 'line_offset=0):', 'if', 'self.options.verbose:', "print('checking", "%s'", '%', 'filename)', 'fchecker', '=', 'self.checker_class(filename,', 'lines=lines,', 'options=self.options)', 'return', 'fchecker.check_all(expected=expected,', 'line_offse...
314,034
VoraHarsh/iit-cs480-Introduction-to--
games.py
Game.play_game
play_game
Play an n-person, move-alternating game.
[ "Play", "an", "n-person,", "move-alternating", "game." ]
def play_game(self, state, *players): state = state self.display(state) print() while True: for player in players: (move, alphabeta_counter) = player(self, state) state = self.result(state, move) self.display(state) print() if self.term...
['def', 'play_game(self,', 'state,', '*players):', 'state', '=', 'state', 'self.display(state)', 'print()', 'while', 'True:', 'for', 'player', 'in', 'players:', '(move,', 'alphabeta_counter)', '=', 'player(self,', 'state)', 'state', '=', 'self.result(state,', 'move)', 'self.display(state)', 'print()', 'if', 'self.termi...
229,093
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_nca.py
test_finite_differences
test_finite_differences
Test gradient of loss function Assert that the gradient is almost equal to its finite differences approximation.
[ "Test", "gradient", "of", "loss", "function", "Assert", "that", "the", "gradient", "is", "almost", "equal", "to", "its", "finite", "differences", "approximation." ]
def test_finite_differences(): rng = np.random.RandomState(42) (X, y) = make_classification() M = rng.randn(rng.randint(1, X.shape[1] + 1), X.shape[1]) nca = NeighborhoodComponentsAnalysis() nca.n_iter_ = 0 mask = y[:, np.newaxis] == y[np.newaxis, :] def fun(M): return nca._loss_gra...
['def', 'test_finite_differences():', 'rng', '=', 'np.random.RandomState(42)', '(X,', 'y)', '=', 'make_classification()', 'M', '=', 'rng.randn(rng.randint(1,', 'X.shape[1]', '+', '1),', 'X.shape[1])', 'nca', '=', 'NeighborhoodComponentsAnalysis()', 'nca.n_iter_', '=', '0', 'mask', '=', 'y[:,', 'np.newaxis]', '==', 'y[n...
261,181
ludwig-ai/ludwig
metric_utils.py
get_metric_names
get_metric_names
Returns a dict of output_feature_name -> list of metric names.
[ "Returns", "a", "dict", "of", "output_feature_name", "->", "list", "of", "metric", "names." ]
def get_metric_names(output_features: Dict[str, 'OutputFeature']) -> Dict[str, List[str]]: metrics_names = {} for (output_feature_name, output_feature) in output_features.items(): metrics_names[output_feature_name] = sorted(list(get_metric_names_for_type(output_feature.type()))) metrics_names[COMBIN...
['def', 'get_metric_names(output_features:', 'Dict[str,', "'OutputFeature'])", '->', 'Dict[str,', 'List[str]]:', 'metrics_names', '=', '{}', 'for', '(output_feature_name,', 'output_feature)', 'in', 'output_features.items():', 'metrics_names[output_feature_name]', '=', 'sorted(list(get_metric_names_for_type(output_featu...
617,128
43Carrig/recurrent_neural_networks_practice
test_util.py
SetAllNonLazyFields
SetAllNonLazyFields
Sets every non-lazy field in the message to a unique value.
[ "Sets", "every", "non-lazy", "field", "in", "the", "message", "to", "a", "unique", "value." ]
def SetAllNonLazyFields(message): message.optional_int32 = 101 message.optional_int64 = 102 message.optional_uint32 = 103 message.optional_uint64 = 104 message.optional_sint32 = 105 message.optional_sint64 = 106 message.optional_fixed32 = 107 message.optional_fixed64 = 108 message.op...
['def', 'SetAllNonLazyFields(message):', 'message.optional_int32', '=', '101', 'message.optional_int64', '=', '102', 'message.optional_uint32', '=', '103', 'message.optional_uint64', '=', '104', 'message.optional_sint32', '=', '105', 'message.optional_sint64', '=', '106', 'message.optional_fixed32', '=', '107', 'messag...
309,980
AgileRL/AgileRL
evolvable_cnn.py
EvolvableCNN.change_cnn_kernel
change_cnn_kernel
Randomly alters convolution kernel of random CNN layer.
[ "Randomly", "alters", "convolution", "kernel", "of", "random", "CNN", "layer." ]
def change_cnn_kernel(self): if self.multi: if len(self.channel_size) > 1: hidden_layer = np.random.randint(1, min(4, len(self.channel_size)), 1)[0] kernel_size_value = np.random.choice([3, 4, 5, 7]) if self.critic: self.kernel_size[hidden_layer] = tuple((...
['def', 'change_cnn_kernel(self):', 'if', 'self.multi:', 'if', 'len(self.channel_size)', '>', '1:', 'hidden_layer', '=', 'np.random.randint(1,', 'min(4,', 'len(self.channel_size)),', '1)[0]', 'kernel_size_value', '=', 'np.random.choice([3,', '4,', '5,', '7])', 'if', 'self.critic:', 'self.kernel_size[hidden_layer]', '='...
24,160
jimtin/Stock_Comparison
test_interactiveshell.py
TestAstTransformInputRejection.test_input_rejection
test_input_rejection
Check that NodeTransformers can reject input.
[ "Check", "that", "NodeTransformers", "can", "reject", "input." ]
def test_input_rejection(self): expect_exception_tb = tt.AssertPrints('InputRejected: test') expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False) with expect_exception_tb, expect_no_cell_output: ip.run_cell("'unsafe'") with expect_exception_tb, expect_no_cell_output: re...
['def', 'test_input_rejection(self):', 'expect_exception_tb', '=', "tt.AssertPrints('InputRejected:", "test')", 'expect_no_cell_output', '=', 'tt.AssertNotPrints("\'unsafe\'",', 'suppress=False)', 'with', 'expect_exception_tb,', 'expect_no_cell_output:', 'ip.run_cell("\'unsafe\'")', 'with', 'expect_exception_tb,', 'exp...
385,066
rudranil723/mini-main
__init__.py
mail_managers
mail_managers
Send a message to the managers, as defined by the MANAGERS setting.
[ "Send", "a", "message", "to", "the", "managers,", "as", "defined", "by", "the", "MANAGERS", "setting." ]
def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None): if not settings.MANAGERS: return mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection) if...
['def', 'mail_managers(subject,', 'message,', 'fail_silently=False,', 'connection=None,', 'html_message=None):', 'if', 'not', 'settings.MANAGERS:', 'return', 'mail', '=', "EmailMultiAlternatives('%s%s'", '%', '(settings.EMAIL_SUBJECT_PREFIX,', 'subject),', 'message,', 'settings.SERVER_EMAIL,', '[a[1]', 'for', 'a', 'in'...
315,580
ChenhongyiYang/PPAL
infinite_sampler.py
InfiniteBatchSampler.set_epoch
set_epoch
Not supported in `IterationBased` runner.
[ "Not", "supported", "in", "`IterationBased`", "runner." ]
def set_epoch(self, epoch): raise NotImplementedError
['def', 'set_epoch(self,', 'epoch):', 'raise', 'NotImplementedError']
821,417
openvinotoolkit/training_extensions
configurer.py
DetectionConfigurer.configure_model
configure_model
Configuration for model config.
[ "Configuration", "for", "model", "config." ]
def configure_model(self, cfg, data_classes, model_classes, ir_options, **kwargs): super().configure_model(cfg, data_classes, model_classes, ir_options, **kwargs) self.configure_regularization(cfg)
['def', 'configure_model(self,', 'cfg,', 'data_classes,', 'model_classes,', 'ir_options,', '**kwargs):', 'super().configure_model(cfg,', 'data_classes,', 'model_classes,', 'ir_options,', '**kwargs)', 'self.configure_regularization(cfg)']
918,041
datature/portal
__init__.py
wait_for_process
wait_for_process
Wait for the previous atomic function to be completed.
[ "Wait", "for", "the", "previous", "atomic", "function", "to", "be", "completed." ]
def wait_for_process() -> None: while global_store.get_atomic(): time.sleep(0.1)
['def', 'wait_for_process()', '->', 'None:', 'while', 'global_store.get_atomic():', 'time.sleep(0.1)']
820,880
rudranil723/mini-main
geometries.py
GeometryCollection.add
add
Add the geometry to this Geometry Collection.
[ "Add", "the", "geometry", "to", "this", "Geometry", "Collection." ]
def add(self, geom): if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: capi.add_geom(self.ptr, g.ptr) else: capi.add_geom(self.ptr, geom.ptr) elif isinstance(geom, str): tmp = OGRGeometry(geom) capi.add_g...
['def', 'add(self,', 'geom):', 'if', 'isinstance(geom,', 'OGRGeometry):', 'if', 'isinstance(geom,', 'self.__class__):', 'for', 'g', 'in', 'geom:', 'capi.add_geom(self.ptr,', 'g.ptr)', 'else:', 'capi.add_geom(self.ptr,', 'geom.ptr)', 'elif', 'isinstance(geom,', 'str):', 'tmp', '=', 'OGRGeometry(geom)', 'capi.add_geom(se...
315,141
eddylau328/fyp-artificial-intelligence-ac-control-device
_call.py
AioRpcError.initial_metadata
initial_metadata
Returns: The inital metadata received.
[ "Returns:", "The", "inital", "metadata", "received." ]
def initial_metadata(self) -> Optional[Dict]: return self._initial_metadata
['def', 'initial_metadata(self)', '->', 'Optional[Dict]:', 'return', 'self._initial_metadata']
215,640
nicknochnack/RealTimeSignLanguageTFJS
class_utils.py
coco_split_class_ids
coco_split_class_ids
Return the COCO class split ids based on split name and training mode.
[ "Return", "the", "COCO", "class", "split", "ids", "based", "on", "split", "name", "and", "training", "mode." ]
def coco_split_class_ids(split_name): if split_name == 'all': return [] elif split_name == 'voc': return [1, 2, 3, 4, 5, 6, 7, 9, 16, 17, 18, 19, 20, 21, 44, 62, 63, 64, 67, 72] elif split_name == 'nonvoc': return [8, 10, 11, 13, 14, 15, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36...
['def', 'coco_split_class_ids(split_name):', 'if', 'split_name', '==', "'all':", 'return', '[]', 'elif', 'split_name', '==', "'voc':", 'return', '[1,', '2,', '3,', '4,', '5,', '6,', '7,', '9,', '16,', '17,', '18,', '19,', '20,', '21,', '44,', '62,', '63,', '64,', '67,', '72]', 'elif', 'split_name', '==', "'nonvoc':", '...
851,001
nicknochnack/RealTimeSignLanguageTFJS
factory.py
shapeprior_head_generator
shapeprior_head_generator
Generator function for shape prior head architecture.
[ "Generator", "function", "for", "shape", "prior", "head", "architecture." ]
def shapeprior_head_generator(params): head_params = params.shapemask_head return heads.ShapemaskPriorHead(params.architecture.num_classes, head_params.num_downsample_channels, head_params.mask_crop_size, head_params.use_category_for_mask, head_params.shape_prior_path)
['def', 'shapeprior_head_generator(params):', 'head_params', '=', 'params.shapemask_head', 'return', 'heads.ShapemaskPriorHead(params.architecture.num_classes,', 'head_params.num_downsample_channels,', 'head_params.mask_crop_size,', 'head_params.use_category_for_mask,', 'head_params.shape_prior_path)']
850,962
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.geom_bodyid
geom_bodyid
id of geom's body (ngeom x 1).
[ "id", "of", "geom's", "body", "(ngeom", "x", "1)." ]
def geom_bodyid(self): return util.buf_to_npy(self._ptr.contents.geom_bodyid, (self.ngeom,))
['def', 'geom_bodyid(self):', 'return', 'util.buf_to_npy(self._ptr.contents.geom_bodyid,', '(self.ngeom,))']
440,286
megvii-research/MSCL
proposal_utils.py
soft_nms
soft_nms
Soft NMS for temporal proposals.
[ "Soft", "NMS", "for", "temporal", "proposals." ]
def soft_nms(proposals, alpha, low_threshold, high_threshold, top_k): proposals = proposals[proposals[:, -1].argsort()[::-1]] tstart = list(proposals[:, 0]) tend = list(proposals[:, 1]) tscore = list(proposals[:, -1]) rstart = [] rend = [] rscore = [] while len(tscore) > 0 and len(rscore...
['def', 'soft_nms(proposals,', 'alpha,', 'low_threshold,', 'high_threshold,', 'top_k):', 'proposals', '=', 'proposals[proposals[:,', '-1].argsort()[::-1]]', 'tstart', '=', 'list(proposals[:,', '0])', 'tend', '=', 'list(proposals[:,', '1])', 'tscore', '=', 'list(proposals[:,', '-1])', 'rstart', '=', '[]', 'rend', '=', '...
264,796
rudranil723/mini-main
test_marker.py
test_marker_init_transforms
test_marker_init_transforms
Test that initializing marker with transform is a simple addition.
[ "Test", "that", "initializing", "marker", "with", "transform", "is", "a", "simple", "addition." ]
def test_marker_init_transforms(): marker = markers.MarkerStyle('o') t = Affine2D().translate(1, 1) t_marker = markers.MarkerStyle('o', transform=t) assert marker.get_transform() + t == t_marker.get_transform()
['def', 'test_marker_init_transforms():', 'marker', '=', "markers.MarkerStyle('o')", 't', '=', 'Affine2D().translate(1,', '1)', 't_marker', '=', "markers.MarkerStyle('o',", 'transform=t)', 'assert', 'marker.get_transform()', '+', 't', '==', 't_marker.get_transform()']
320,288
microsoft/nni
graph.py
Graph.to_concat_skip_model
to_concat_skip_model
Add a weighted add concatenate connection from after start node to end node.
[ "Add", "a", "weighted", "add", "concatenate", "connection", "from", "after", "start", "node", "to", "end", "node." ]
def to_concat_skip_model(self, start_id, end_id): self.operation_history.append(('to_concat_skip_model', start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] start_node_id = self.layer_id_to_output_node_ids[start_id][0] ...
['def', 'to_concat_skip_model(self,', 'start_id,', 'end_id):', "self.operation_history.append(('to_concat_skip_model',", 'start_id,', 'end_id))', 'filters_end', '=', 'self.layer_list[end_id].output.shape[-1]', 'filters_start', '=', 'self.layer_list[start_id].output.shape[-1]', 'start_node_id', '=', 'self.layer_id_to_ou...
728,371
deepmind/meltingpot
factory_commons.py
get_config
get_config
Default configuration for training on the factory2d level.
[ "Default", "configuration", "for", "training", "on", "the", "factory2d", "level." ]
def get_config(): config = config_dict.ConfigDict() config.recommended_num_players = 12 config.action_set = ACTION_SET config.individual_observation_names = ['RGB', 'READY_TO_SHOOT', 'STAMINA'] config.global_observation_names = ['WORLD.RGB'] config.action_spec = specs.action(len(ACTION_SET)) ...
['def', 'get_config():', 'config', '=', 'config_dict.ConfigDict()', 'config.recommended_num_players', '=', '12', 'config.action_set', '=', 'ACTION_SET', 'config.individual_observation_names', '=', "['RGB',", "'READY_TO_SHOOT',", "'STAMINA']", 'config.global_observation_names', '=', "['WORLD.RGB']", 'config.action_spec'...
285,742
gunthercox/ChatterBot
attributes.py
CollectionAttributeImpl.initialize
initialize
Initialize this attribute with an empty collection.
[ "Initialize", "this", "attribute", "with", "an", "empty", "collection." ]
def initialize(self, state, dict_): (_, user_data) = self._initialize_collection(state) dict_[self.key] = user_data return user_data
['def', 'initialize(self,', 'state,', 'dict_):', '(_,', 'user_data)', '=', 'self._initialize_collection(state)', 'dict_[self.key]', '=', 'user_data', 'return', 'user_data']
481,162
rifqind/Agent-Programs-3KS1
test_traitlets.py
TestForwardDeclaredInstanceList.test_klass
test_klass
Test that the instance klass is properly assigned.
[ "Test", "that", "the", "instance", "klass", "is", "properly", "assigned." ]
def test_klass(self): self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
['def', 'test_klass(self):', "self.assertIs(self.obj.traits()['value']._trait.klass,", 'ForwardDeclaredBar)']
21,661
rudranil723/mini-main
DateTime.py
safelocaltime
safelocaltime
localtime with a safety zone.
[ "localtime", "with", "a", "safety", "zone." ]
def safelocaltime(t): try: return localtime(t) except (ValueError, OverflowError): raise TimeError('The time %f is beyond the range of this Python implementation.' % float(t))
['def', 'safelocaltime(t):', 'try:', 'return', 'localtime(t)', 'except', '(ValueError,', 'OverflowError):', 'raise', "TimeError('The", 'time', '%f', 'is', 'beyond', 'the', 'range', 'of', 'this', 'Python', "implementation.'", '%', 'float(t))']
314,530
matsu0228/nlp-jp
pyplot.py
ishold
ishold
Return the hold status of the current axes.
[ "Return", "the", "hold", "status", "of", "the", "current", "axes." ]
def ishold(): return gca()._hold
['def', 'ishold():', 'return', 'gca()._hold']
789,118
MycroftAI/mycroft-core
settings.py
save_settings
save_settings
Save skill settings to file.
[ "Save", "skill", "settings", "to", "file." ]
def save_settings(skill_dir, skill_settings): settings_path = Path(skill_dir).joinpath('settings.json') if not Path(settings_path).exists(): settings_path.touch(mode=420) with open(str(settings_path), 'w') as settings_file: try: json.dump(skill_settings, settings_file) ex...
['def', 'save_settings(skill_dir,', 'skill_settings):', 'settings_path', '=', "Path(skill_dir).joinpath('settings.json')", 'if', 'not', 'Path(settings_path).exists():', 'settings_path.touch(mode=420)', 'with', 'open(str(settings_path),', "'w')", 'as', 'settings_file:', 'try:', 'json.dump(skill_settings,', 'settings_fil...
290,517
JosephKJ/iOD
catalog.py
DatasetCatalog.get
get
Call the registered function and return its results.
[ "Call", "the", "registered", "function", "and", "return", "its", "results." ]
def get(name): try: f = DatasetCatalog._REGISTERED[name] except KeyError: raise KeyError("Dataset '{}' is not registered! Available datasets are: {}".format(name, ', '.join(DatasetCatalog._REGISTERED.keys()))) return f()
['def', 'get(name):', 'try:', 'f', '=', 'DatasetCatalog._REGISTERED[name]', 'except', 'KeyError:', 'raise', 'KeyError("Dataset', "'{}'", 'is', 'not', 'registered!', 'Available', 'datasets', 'are:', '{}".format(name,', "',", "'.join(DatasetCatalog._REGISTERED.keys())))", 'return', 'f()']
576,787
calico/basenji
basenji_data_gene.py
sufficient_sequence
sufficient_sequence
Return boolean mask specifying genes with sufficient sequence.
[ "Return", "boolean", "mask", "specifying", "genes", "with", "sufficient", "sequence." ]
def sufficient_sequence(fasta_file, genes_df, seq_length, n_allowed_pct): fasta_open = pysam.Fastafile(fasta_file) gene_valid = np.ones(genes_df.shape[0], dtype='bool') gi = 0 for gene in genes_df.itertuples(): chr_len = fasta_open.get_reference_length(gene.chr) mid_pos = (gene.start + g...
['def', 'sufficient_sequence(fasta_file,', 'genes_df,', 'seq_length,', 'n_allowed_pct):', 'fasta_open', '=', 'pysam.Fastafile(fasta_file)', 'gene_valid', '=', 'np.ones(genes_df.shape[0],', "dtype='bool')", 'gi', '=', '0', 'for', 'gene', 'in', 'genes_df.itertuples():', 'chr_len', '=', 'fasta_open.get_reference_length(ge...
94,755
ryu-ed/SpaceInvaders_Ros
surface_test.py
SurfaceTypeTest.test_surface__pixel_format_as_surface_subclass
test_surface__pixel_format_as_surface_subclass
Ensure a subclassed surface can be used for pixel format when creating a new surface.
[ "Ensure", "a", "subclassed", "surface", "can", "be", "used", "for", "pixel", "format", "when", "creating", "a", "new", "surface." ]
def test_surface__pixel_format_as_surface_subclass(self): expected_depth = 16 expected_flags = SRCALPHA expected_size = (13, 37) depth_surface = SurfaceSubclass((11, 21), expected_flags, expected_depth) surface = pygame.Surface(expected_size, 0, depth_surface) self.assertIsNot(surface, depth_sur...
['def', 'test_surface__pixel_format_as_surface_subclass(self):', 'expected_depth', '=', '16', 'expected_flags', '=', 'SRCALPHA', 'expected_size', '=', '(13,', '37)', 'depth_surface', '=', 'SurfaceSubclass((11,', '21),', 'expected_flags,', 'expected_depth)', 'surface', '=', 'pygame.Surface(expected_size,', '0,', 'depth_...
369,163
lonePatient/albert_pytorch
lr_scheduler.py
get_cosine_with_hard_restarts_schedule_with_warmup
get_cosine_with_hard_restarts_schedule_with_warmup
Create a schedule with a learning rate that decreases following the values of the cosine function with several hard restarts, after a warmup period during which it increases linearly between 0 and 1.
[ "Create", "a", "schedule", "with", "a", "learning", "rate", "that", "decreases", "following", "the", "values", "of", "the", "cosine", "function", "with", "several", "hard", "restarts,", "after", "a", "warmup", "period", "during", "which", "it", "increases", "l...
def get_cosine_with_hard_restarts_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=1.0, last_epoch=-1): def lr_lambda(current_step): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) progress = float(current_...
['def', 'get_cosine_with_hard_restarts_schedule_with_warmup(optimizer,', 'num_warmup_steps,', 'num_training_steps,', 'num_cycles=1.0,', 'last_epoch=-1):', 'def', 'lr_lambda(current_step):', 'if', 'current_step', '<', 'num_warmup_steps:', 'return', 'float(current_step)', '/', 'float(max(1,', 'num_warmup_steps))', 'progr...
87,330
danamyu/hedgehog_detector
losses.py
correlation_loss
correlation_loss
Adds a similarity loss term, the correlation between two representations.
[ "Adds", "a", "similarity", "loss", "term,", "the", "correlation", "between", "two", "representations." ]
def correlation_loss(source_samples, target_samples, weight, scope=None): with tf.name_scope('corr_loss'): source_samples -= tf.reduce_mean(source_samples, 0) target_samples -= tf.reduce_mean(target_samples, 0) source_samples = tf.nn.l2_normalize(source_samples, 1) target_samples = t...
['def', 'correlation_loss(source_samples,', 'target_samples,', 'weight,', 'scope=None):', 'with', "tf.name_scope('corr_loss'):", 'source_samples', '-=', 'tf.reduce_mean(source_samples,', '0)', 'target_samples', '-=', 'tf.reduce_mean(target_samples,', '0)', 'source_samples', '=', 'tf.nn.l2_normalize(source_samples,', '1...
589,521
tensorflow/data-validation
stats_impl.py
CombinerFeatureStatsWrapperGenerator.add_input
add_input
Returns result of folding a batch of inputs into wrapper_accumulator.
[ "Returns", "result", "of", "folding", "a", "batch", "of", "inputs", "into", "wrapper_accumulator." ]
def add_input(self, wrapper_accumulator: WrapperAccumulator, input_record_batch: pa.RecordBatch) -> WrapperAccumulator: if self._sample_rate is not None and random.random() > self._sample_rate: return wrapper_accumulator for (feature_path, feature_array, _) in arrow_util.enumerate_arrays(input_record_ba...
['def', 'add_input(self,', 'wrapper_accumulator:', 'WrapperAccumulator,', 'input_record_batch:', 'pa.RecordBatch)', '->', 'WrapperAccumulator:', 'if', 'self._sample_rate', 'is', 'not', 'None', 'and', 'random.random()', '>', 'self._sample_rate:', 'return', 'wrapper_accumulator', 'for', '(feature_path,', 'feature_array,'...
497,457
myothida/Supervised-Machine-Learning
common.py
require_length_match
require_length_match
Check the length of data matches the length of the index.
[ "Check", "the", "length", "of", "data", "matches", "the", "length", "of", "the", "index." ]
def require_length_match(data, index: Index) -> None: if len(data) != len(index): raise ValueError(f'Length of values ({len(data)}) does not match length of index ({len(index)})')
['def', 'require_length_match(data,', 'index:', 'Index)', '->', 'None:', 'if', 'len(data)', '!=', 'len(index):', 'raise', "ValueError(f'Length", 'of', 'values', '({len(data)})', 'does', 'not', 'match', 'length', 'of', 'index', "({len(index)})')"]
442,353
rvl-lab-utoronto/video_similarity_search
checkpoint.py
c2_normal_to_sub_bn
c2_normal_to_sub_bn
Convert BN parameters to Sub-BN parameters if model contains Sub-BNs.
[ "Convert", "BN", "parameters", "to", "Sub-BN", "parameters", "if", "model", "contains", "Sub-BNs." ]
def c2_normal_to_sub_bn(key, model_keys): if 'bn.running_' in key: if key in model_keys: return key new_key = key.replace('bn.running_', 'bn.split_bn.running_') if new_key in model_keys: return new_key else: return key
['def', 'c2_normal_to_sub_bn(key,', 'model_keys):', 'if', "'bn.running_'", 'in', 'key:', 'if', 'key', 'in', 'model_keys:', 'return', 'key', 'new_key', '=', "key.replace('bn.running_',", "'bn.split_bn.running_')", 'if', 'new_key', 'in', 'model_keys:', 'return', 'new_key', 'else:', 'return', 'key']
380,021
stardist/stardist
utils.py
calculate_extents
calculate_extents
Aggregate bounding box sizes of objects in label images.
[ "Aggregate", "bounding", "box", "sizes", "of", "objects", "in", "label", "images." ]
def calculate_extents(lbl, func=np.median): if isinstance(lbl, np.ndarray) and lbl.ndim == 4 or (not isinstance(lbl, np.ndarray) and isinstance(lbl, Iterable)): return func(np.stack([calculate_extents(_lbl, func) for _lbl in lbl], axis=0), axis=0) n = lbl.ndim n in (2, 3) or _raise(ValueError('label...
['def', 'calculate_extents(lbl,', 'func=np.median):', 'if', 'isinstance(lbl,', 'np.ndarray)', 'and', 'lbl.ndim', '==', '4', 'or', '(not', 'isinstance(lbl,', 'np.ndarray)', 'and', 'isinstance(lbl,', 'Iterable)):', 'return', 'func(np.stack([calculate_extents(_lbl,', 'func)', 'for', '_lbl', 'in', 'lbl],', 'axis=0),', 'axi...
873,489
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
streams.py
ANTLRStringStream.reset
reset
Reset the stream so that it's in the same state it was when the object was created *except* the data array is not touched.
[ "Reset", "the", "stream", "so", "that", "it's", "in", "the", "same", "state", "it", "was", "when", "the", "object", "was", "created", "*except*", "the", "data", "array", "is", "not", "touched." ]
def reset(self): self.p = 0 self.line = 1 self.charPositionInLine = 0 self._markers = []
['def', 'reset(self):', 'self.p', '=', '0', 'self.line', '=', '1', 'self.charPositionInLine', '=', '0', 'self._markers', '=', '[]']
9,859
coldmanck/CS5242-Neural-Network-and--Learning-Assignments
data_utils.py
get_CIFAR2_data
get_CIFAR2_data
Load the CIFAR-2 (class0: airplane, class2: bird) dataset from disk and perform preprocessing to prepare it for classifiers.
[ "Load", "the", "CIFAR-2", "(class0:", "airplane,", "class2:", "bird)", "dataset", "from", "disk", "and", "perform", "preprocessing", "to", "prepare", "it", "for", "classifiers." ]
def get_CIFAR2_data(num_training=9800, num_validation=200, num_test=2000, subtract_mean=True): cifar10_dir = 'code_base/datasets/cifar-10-batches-py' (X_train, y_train, X_test, y_test) = load_CIFAR10(cifar10_dir) class0_Xtrain = X_train[np.where(y_train == 0)] class2_Xtrain = X_train[np.where(y_train ==...
['def', 'get_CIFAR2_data(num_training=9800,', 'num_validation=200,', 'num_test=2000,', 'subtract_mean=True):', 'cifar10_dir', '=', "'code_base/datasets/cifar-10-batches-py'", '(X_train,', 'y_train,', 'X_test,', 'y_test)', '=', 'load_CIFAR10(cifar10_dir)', 'class0_Xtrain', '=', 'X_train[np.where(y_train', '==', '0)]', '...
508,322
intel/neural-compressor
bayesian.py
acq_max
acq_max
Find the maximum of the acquisition function parameters.
[ "Find", "the", "maximum", "of", "the", "acquisition", "function", "parameters." ]
def acq_max(ac, gp, y_max, bounds, random_seed, n_warmup=10000, n_iter=10): x_tries = np.random.uniform(bounds[:, 0], bounds[:, 1], size=(n_warmup, bounds.shape[0])) ys = ac(x_tries, gp=gp, y_max=y_max) x_max = x_tries[ys.argmax()] max_acq = ys.max() x_seeds = np.random.uniform(bounds[:, 0], bounds[...
['def', 'acq_max(ac,', 'gp,', 'y_max,', 'bounds,', 'random_seed,', 'n_warmup=10000,', 'n_iter=10):', 'x_tries', '=', 'np.random.uniform(bounds[:,', '0],', 'bounds[:,', '1],', 'size=(n_warmup,', 'bounds.shape[0]))', 'ys', '=', 'ac(x_tries,', 'gp=gp,', 'y_max=y_max)', 'x_max', '=', 'x_tries[ys.argmax()]', 'max_acq', '=',...
738,718
JinliangLu96/CL_UNMT
dictionary.py
Dictionary.index_data
index_data
Index sentences with a dictionary.
[ "Index", "sentences", "with", "a", "dictionary." ]
def index_data(path, bin_path, dico): if bin_path is not None and os.path.isfile(bin_path): print('Loading data from %s ...' % bin_path) data = torch.load(bin_path) assert dico == data['dico'] return data positions = [] sentences = [] unk_words = {} f = open(path, 'r'...
['def', 'index_data(path,', 'bin_path,', 'dico):', 'if', 'bin_path', 'is', 'not', 'None', 'and', 'os.path.isfile(bin_path):', "print('Loading", 'data', 'from', '%s', "...'", '%', 'bin_path)', 'data', '=', 'torch.load(bin_path)', 'assert', 'dico', '==', "data['dico']", 'return', 'data', 'positions', '=', '[]', 'sentence...
123,262
cszmli/Rethink-RL-Sup
dbquery.py
DBQuery.pointer
pointer
Create database pointer for all related domains.
[ "Create", "database", "pointer", "for", "all", "related", "domains." ]
def pointer(self, turn, mapping, db_domains, noisy): pointer_vector = np.zeros(6 * len(db_domains)) for domain in db_domains: constraint = [] for (k, v) in turn[domain].items(): if k in mapping[domain]: constraint.append((mapping[domain][k], v)) entities = sel...
['def', 'pointer(self,', 'turn,', 'mapping,', 'db_domains,', 'noisy):', 'pointer_vector', '=', 'np.zeros(6', '*', 'len(db_domains))', 'for', 'domain', 'in', 'db_domains:', 'constraint', '=', '[]', 'for', '(k,', 'v)', 'in', 'turn[domain].items():', 'if', 'k', 'in', 'mapping[domain]:', 'constraint.append((mapping[domain]...
346,166
Farama-Foundation/Gymnasium
vector_env.py
VectorWrapper.single_action_space
single_action_space
Gets the single action space of the vector environment.
[ "Gets", "the", "single", "action", "space", "of", "the", "vector", "environment." ]
def single_action_space(self) -> gym.Space: if self._single_action_space is None: return self.env.single_action_space return self._single_action_space
['def', 'single_action_space(self)', '->', 'gym.Space:', 'if', 'self._single_action_space', 'is', 'None:', 'return', 'self.env.single_action_space', 'return', 'self._single_action_space']
573,127
ouwei-guo/mit-6.034
lab0.py
sum_of_coordinates
sum_of_coordinates
Given a 2D point (represented as a Point object), returns the sum of its X- and Y-coordinates.
[ "Given", "a", "2D", "point", "(represented", "as", "a", "Point", "object),", "returns", "the", "sum", "of", "its", "X-", "and", "Y-coordinates." ]
def sum_of_coordinates(point): return point.getX() + point.getY()
['def', 'sum_of_coordinates(point):', 'return', 'point.getX()', '+', 'point.getY()']
272,024
kubeflow/pipelines
_container_op.py
BaseOp.add_volume
add_volume
Add K8s volume to the container.
[ "Add", "K8s", "volume", "to", "the", "container." ]
def add_volume(self, volume): self.volumes.append(volume) return self
['def', 'add_volume(self,', 'volume):', 'self.volumes.append(volume)', 'return', 'self']
780,140
tensorflow/privacy
tf_estimator_evaluation_example.py
small_cnn_fn
small_cnn_fn
Setup a small CNN for image classification.
[ "Setup", "a", "small", "CNN", "for", "image", "classification." ]
def small_cnn_fn(features, labels, mode): input_layer = tf.reshape(features['x'], [-1, 32, 32, 3]) for _ in range(3): y = tf.keras.layers.Conv2D(32, (3, 3), activation='relu')(input_layer) y = tf.keras.layers.MaxPool2D()(y) y = tf.keras.layers.Flatten()(y) y = tf.keras.layers.Dense(64, a...
['def', 'small_cnn_fn(features,', 'labels,', 'mode):', 'input_layer', '=', "tf.reshape(features['x'],", '[-1,', '32,', '32,', '3])', 'for', '_', 'in', 'range(3):', 'y', '=', 'tf.keras.layers.Conv2D(32,', '(3,', '3),', "activation='relu')(input_layer)", 'y', '=', 'tf.keras.layers.MaxPool2D()(y)', 'y', '=', 'tf.keras.lay...
824,932
openml-labs/gama
ensemble.py
build_fit_ensemble
build_fit_ensemble
Construct an Ensemble of models, optimizing for metric.
[ "Construct", "an", "Ensemble", "of", "models,", "optimizing", "for", "metric." ]
def build_fit_ensemble(x, y, ensemble_size: int, timeout: float, metric: Metric, evaluation_library: EvaluationLibrary, encoder: Optional[object]=None) -> Ensemble: start_build = time.time() log.debug('Building ensemble.') if metric.task_type == MetricType.REGRESSION: ensemble = EnsembleRegressor(me...
['def', 'build_fit_ensemble(x,', 'y,', 'ensemble_size:', 'int,', 'timeout:', 'float,', 'metric:', 'Metric,', 'evaluation_library:', 'EvaluationLibrary,', 'encoder:', 'Optional[object]=None)', '->', 'Ensemble:', 'start_build', '=', 'time.time()', "log.debug('Building", "ensemble.')", 'if', 'metric.task_type', '==', 'Met...
566,180
openml-labs/gama
individual.py
Individual.pipeline
pipeline
Calls the `to_pipeline` method on itself.
[ "Calls", "the", "`to_pipeline`", "method", "on", "itself." ]
def pipeline(self) -> Pipeline: if self._to_pipeline is None: raise AttributeError('pipeline not available because `to_pipeline` was not set on __init__.') return self._to_pipeline(self)
['def', 'pipeline(self)', '->', 'Pipeline:', 'if', 'self._to_pipeline', 'is', 'None:', 'raise', "AttributeError('pipeline", 'not', 'available', 'because', '`to_pipeline`', 'was', 'not', 'set', 'on', "__init__.')", 'return', 'self._to_pipeline(self)']
566,160
netket/netket
_graph_operator.py
check_acting_on_subspace
check_acting_on_subspace
Check `acting_on_subspace` argument used by various operators.
[ "Check", "`acting_on_subspace`", "argument", "used", "by", "various", "operators." ]
def check_acting_on_subspace(acting_on_subspace, hilbert, graph): if acting_on_subspace is None: acting_on_subspace = list(range(hilbert.size)) elif isinstance(acting_on_subspace, int): start = acting_on_subspace acting_on_subspace = [start + i for i in range(graph.n_nodes)] elif isi...
['def', 'check_acting_on_subspace(acting_on_subspace,', 'hilbert,', 'graph):', 'if', 'acting_on_subspace', 'is', 'None:', 'acting_on_subspace', '=', 'list(range(hilbert.size))', 'elif', 'isinstance(acting_on_subspace,', 'int):', 'start', '=', 'acting_on_subspace', 'acting_on_subspace', '=', '[start', '+', 'i', 'for', '...
736,173
awalsh128/nlp
dureader_eval.py
prepare_prf
prepare_prf
Prepares data for calculation of prf scores.
[ "Prepares", "data", "for", "calculation", "of", "prf", "scores." ]
def prepare_prf(pred_dict, ref_dict): preds = {k: v['entity_answers'] for (k, v) in pred_dict.items()} refs = {k: v['entity_answers'] for (k, v) in ref_dict.items()} return (preds, refs)
['def', 'prepare_prf(pred_dict,', 'ref_dict):', 'preds', '=', '{k:', "v['entity_answers']", 'for', '(k,', 'v)', 'in', 'pred_dict.items()}', 'refs', '=', '{k:', "v['entity_answers']", 'for', '(k,', 'v)', 'in', 'ref_dict.items()}', 'return', '(preds,', 'refs)']
808,855
tensorflow/agents
neural_linucb_agent.py
NeuralLinUCBAgent.compute_loss_using_linucb
compute_loss_using_linucb
Computes the loss using LinUCB.
[ "Computes", "the", "loss", "using", "LinUCB." ]
def compute_loss_using_linucb(self, observation: types.NestedTensor, action: types.Tensor, reward: types.Tensor, weights: Optional[types.Float]=None, training: bool=False) -> tf_agent.LossInfo: del weights (encoded_observation, _) = self._encoding_network(observation, training=training) encoded_observation ...
['def', 'compute_loss_using_linucb(self,', 'observation:', 'types.NestedTensor,', 'action:', 'types.Tensor,', 'reward:', 'types.Tensor,', 'weights:', 'Optional[types.Float]=None,', 'training:', 'bool=False)', '->', 'tf_agent.LossInfo:', 'del', 'weights', '(encoded_observation,', '_)', '=', 'self._encoding_network(obser...
23,254
caiiiac/Machine-Learning-with-Python
plot_directive.py
run_code
run_code
Import a Python module from a path, and run the function given by name, if function_name is not None.
[ "Import", "a", "Python", "module", "from", "a", "path,", "and", "run", "the", "function", "given", "by", "name,", "if", "function_name", "is", "not", "None." ]
def run_code(code, code_path, ns=None, function_name=None): if six.PY2: pwd = os.getcwdu() else: pwd = os.getcwd() old_sys_path = list(sys.path) if setup.config.plot_working_directory is not None: try: os.chdir(setup.config.plot_working_directory) except OSErr...
['def', 'run_code(code,', 'code_path,', 'ns=None,', 'function_name=None):', 'if', 'six.PY2:', 'pwd', '=', 'os.getcwdu()', 'else:', 'pwd', '=', 'os.getcwd()', 'old_sys_path', '=', 'list(sys.path)', 'if', 'setup.config.plot_working_directory', 'is', 'not', 'None:', 'try:', 'os.chdir(setup.config.plot_working_directory)',...
716,560
tensorflow/data-validation
natural_language_domain_inferring_stats_generator.py
NLDomainInferringStatsGenerator.extract_output
extract_output
Return result of converting accumulator into the output value.
[ "Return", "result", "of", "converting", "accumulator", "into", "the", "output", "value." ]
def extract_output(self, accumulator: _PartialNLStats) -> statistics_pb2.FeatureNameStatistics: result = statistics_pb2.FeatureNameStatistics() if not accumulator.invalidate and accumulator.considered >= self._values_threshold: match_ratio = float(accumulator.matched) / accumulator.considered if...
['def', 'extract_output(self,', 'accumulator:', '_PartialNLStats)', '->', 'statistics_pb2.FeatureNameStatistics:', 'result', '=', 'statistics_pb2.FeatureNameStatistics()', 'if', 'not', 'accumulator.invalidate', 'and', 'accumulator.considered', '>=', 'self._values_threshold:', 'match_ratio', '=', 'float(accumulator.matc...
497,493
Kvatsx/Artificial-Intelligence-Assignments
support.py
cpython_only
cpython_only
Decorator for tests only applicable on CPython.
[ "Decorator", "for", "tests", "only", "applicable", "on", "CPython." ]
def cpython_only(test): return impl_detail(cpython=True)(test)
['def', 'cpython_only(test):', 'return', 'impl_detail(cpython=True)(test)']
37,018
paulorauber/rl
multiagent.py
Mixer.mix
mix
Forward pass for the mixer.
[ "Forward", "pass", "for", "the", "mixer." ]
def mix(self, chosen_action_value: torch.Tensor, state: torch.Tensor): raise NotImplementedError
['def', 'mix(self,', 'chosen_action_value:', 'torch.Tensor,', 'state:', 'torch.Tensor):', 'raise', 'NotImplementedError']
859,207
intra2net/guibot
test_finder.py
FinderTest.test_deep_nomatch
test_deep_nomatch
Test for unsuccessful match of different images for all deep (DL) CV backends.
[ "Test", "for", "unsuccessful", "match", "of", "different", "images", "for", "all", "deep", "(DL)", "CV", "backends." ]
def test_deep_nomatch(self): finder = DeepFinder() finder.params['find']['similarity'].value = 0.25 matches = finder.find(Pattern('cat'), Image('all_shapes')) self.assertEqual(len(matches), 0) dumps = self._verify_and_get_dumps(6) self._verify_dumped_images('cat', 'all_shapes', dumps, 'deep') ...
['def', 'test_deep_nomatch(self):', 'finder', '=', 'DeepFinder()', "finder.params['find']['similarity'].value", '=', '0.25', 'matches', '=', "finder.find(Pattern('cat'),", "Image('all_shapes'))", 'self.assertEqual(len(matches),', '0)', 'dumps', '=', 'self._verify_and_get_dumps(6)', "self._verify_dumped_images('cat',", ...
572,661
43Carrig/recurrent_neural_networks_practice
wrappers.py
AuthorizationMixin.authorization
authorization
The `Authorization` object in parsed form.
[ "The", "`Authorization`", "object", "in", "parsed", "form." ]
def authorization(self): header = self.environ.get('HTTP_AUTHORIZATION') return parse_authorization_header(header)
['def', 'authorization(self):', 'header', '=', "self.environ.get('HTTP_AUTHORIZATION')", 'return', 'parse_authorization_header(header)']
340,211
greydanus/pythonic_ocr
core.py
CSRFTokenField.pre_validate
pre_validate
Handle validation of this token field.
[ "Handle", "validation", "of", "this", "token", "field." ]
def pre_validate(self, form): self.csrf_impl.validate_csrf_token(form, self)
['def', 'pre_validate(self,', 'form):', 'self.csrf_impl.validate_csrf_token(form,', 'self)']
301,325
jshilong/DDQ
mean_ap.py
get_cls_group_ofs
get_cls_group_ofs
Get `gt_group_of` of a certain class, which is used in Open Images.
[ "Get", "`gt_group_of`", "of", "a", "certain", "class,", "which", "is", "used", "in", "Open", "Images." ]
def get_cls_group_ofs(annotations, class_id): gt_group_ofs = [] for ann in annotations: gt_inds = ann['labels'] == class_id if ann.get('gt_is_group_ofs', None) is not None: gt_group_ofs.append(ann['gt_is_group_ofs'][gt_inds]) else: gt_group_ofs.append(np.empty((0,...
['def', 'get_cls_group_ofs(annotations,', 'class_id):', 'gt_group_ofs', '=', '[]', 'for', 'ann', 'in', 'annotations:', 'gt_inds', '=', "ann['labels']", '==', 'class_id', 'if', "ann.get('gt_is_group_ofs',", 'None)', 'is', 'not', 'None:', "gt_group_ofs.append(ann['gt_is_group_ofs'][gt_inds])", 'else:', 'gt_group_ofs.appe...
515,738
deepmind/dm_control
core.py
get_schema
get_schema
Returns a string containing the schema used by the MuJoCo XML parser.
[ "Returns", "a", "string", "containing", "the", "schema", "used", "by", "the", "MuJoCo", "XML", "parser." ]
def get_schema(): buf = ctypes.create_string_buffer(100000) mujoco.mj_printSchema(None, buf, len(buf), 0, 0) return buf.value
['def', 'get_schema():', 'buf', '=', 'ctypes.create_string_buffer(100000)', 'mujoco.mj_printSchema(None,', 'buf,', 'len(buf),', '0,', '0)', 'return', 'buf.value']
165,314
ananthpn/nlp
dureader_eval.py
get_all_result
get_all_result
Prepare answers for task 'all'.
[ "Prepare", "answers", "for", "task", "'all'." ]
def get_all_result(qid, pred_result, ref_result): if ref_result[qid]['question_type'] == 'YES_NO': return get_yesno_result(qid, pred_result, ref_result) return get_main_result(qid, pred_result, ref_result)
['def', 'get_all_result(qid,', 'pred_result,', 'ref_result):', 'if', "ref_result[qid]['question_type']", '==', "'YES_NO':", 'return', 'get_yesno_result(qid,', 'pred_result,', 'ref_result)', 'return', 'get_main_result(qid,', 'pred_result,', 'ref_result)']
808,742
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
deep_cnn.py
inference_deeper
inference_deeper
Build a deeper CNN model.
[ "Build", "a", "deeper", "CNN", "model." ]
def inference_deeper(images, dropout=False): if FLAGS.dataset == 'mnist': first_conv_shape = [3, 3, 1, 96] else: first_conv_shape = [3, 3, 3, 96] with tf.variable_scope('conv1') as scope: kernel = _variable_with_weight_decay('weights', shape=first_conv_shape, stddev=0.05, wd=0.0) ...
['def', 'inference_deeper(images,', 'dropout=False):', 'if', 'FLAGS.dataset', '==', "'mnist':", 'first_conv_shape', '=', '[3,', '3,', '1,', '96]', 'else:', 'first_conv_shape', '=', '[3,', '3,', '3,', '96]', 'with', "tf.variable_scope('conv1')", 'as', 'scope:', 'kernel', '=', "_variable_with_weight_decay('weights',", 's...
53,941
brain-research/hyperbolictext
eval_nli.py
load_data
load_data
Load NLI data from given location.
[ "Load", "NLI", "data", "from", "given", "location." ]
def load_data(path_prefix): train_data = NLIData([], [], [], []) dev_data = NLIData([], [], [], []) test_data = NLIData([], [], [], []) def read_file(suffix, nli_tuple): with open('%s_%s.jsonl' % (path_prefix, suffix)) as f: for line in f: data = ast.literal_eval(lin...
['def', 'load_data(path_prefix):', 'train_data', '=', 'NLIData([],', '[],', '[],', '[])', 'dev_data', '=', 'NLIData([],', '[],', '[],', '[])', 'test_data', '=', 'NLIData([],', '[],', '[],', '[])', 'def', 'read_file(suffix,', 'nli_tuple):', 'with', "open('%s_%s.jsonl'", '%', '(path_prefix,', 'suffix))', 'as', 'f:', 'for...
228,100
yanwenjie1/natural_language_processing
functions.py
SpanEvaluator.reset
reset
Reset function empties the evaluation memory for previous mini-batches.
[ "Reset", "function", "empties", "the", "evaluation", "memory", "for", "previous", "mini-batches." ]
def reset(self): self.num_infer_spans = 0 self.num_label_spans = 0 self.num_correct_spans = 0
['def', 'reset(self):', 'self.num_infer_spans', '=', '0', 'self.num_label_spans', '=', '0', 'self.num_correct_spans', '=', '0']
734,552
azadyasar/AI
analysis.py
question2b
question2b
Prefer the close exit (+1), but avoiding the cliff (-10).
[ "Prefer", "the", "close", "exit", "(+1),", "but", "avoiding", "the", "cliff", "(-10)." ]
def question2b(): answerDiscount = None answerNoise = None answerLivingReward = None return (answerDiscount, answerNoise, answerLivingReward)
['def', 'question2b():', 'answerDiscount', '=', 'None', 'answerNoise', '=', 'None', 'answerLivingReward', '=', 'None', 'return', '(answerDiscount,', 'answerNoise,', 'answerLivingReward)']
64,393
johschmidt42/PyTorch-Object-Detection-Faster-RCNN-Tutorial
anchor_viewer.py
AnchorViewer.get_center_points
get_center_points
Returns the center points of the anchor boxes for the current image.
[ "Returns", "the", "center", "points", "of", "the", "anchor", "boxes", "for", "the", "current", "image." ]
def get_center_points(self): return get_center_bounding_box(self.anchor_boxes)
['def', 'get_center_points(self):', 'return', 'get_center_bounding_box(self.anchor_boxes)']
814,927
intel/neural-compressor
parser.py
TensorFlowProfilingParser.unify_time
unify_time
Unify time with unit to micro seconds float value.
[ "Unify", "time", "with", "unit", "to", "micro", "seconds", "float", "value." ]
def unify_time(string_value: str) -> float: search = re.search('(\\d+(\\.\\d+)?)\\s*(\\w+)', string_value) if not search: raise Exception(f'Could not parse {string_value}') value = round(float(search.group(1)), ROUND_PRECISION) unit = search.group(3) unit_map = {'s': 1000000.0, 'sec': 100000...
['def', 'unify_time(string_value:', 'str)', '->', 'float:', 'search', '=', "re.search('(\\\\d+(\\\\.\\\\d+)?)\\\\s*(\\\\w+)',", 'string_value)', 'if', 'not', 'search:', 'raise', "Exception(f'Could", 'not', 'parse', "{string_value}')", 'value', '=', 'round(float(search.group(1)),', 'ROUND_PRECISION)', 'unit', '=', 'sear...
738,954
RasaHQ/rasa
synonyms_parser.py
add_synonyms_from_entities
add_synonyms_from_entities
Adds synonyms found in intent examples.
[ "Adds", "synonyms", "found", "in", "intent", "examples." ]
def add_synonyms_from_entities(plain_text: Text, entities: List[Dict], existing_synonyms: Dict[Text, Any]) -> None: for e in entities: e_text = plain_text[e[ENTITY_ATTRIBUTE_START]:e[ENTITY_ATTRIBUTE_END]] if e_text != e[ENTITY_ATTRIBUTE_VALUE]: add_synonym(e_text, e[ENTITY_ATTRIBUTE_VAL...
['def', 'add_synonyms_from_entities(plain_text:', 'Text,', 'entities:', 'List[Dict],', 'existing_synonyms:', 'Dict[Text,', 'Any])', '->', 'None:', 'for', 'e', 'in', 'entities:', 'e_text', '=', 'plain_text[e[ENTITY_ATTRIBUTE_START]:e[ENTITY_ATTRIBUTE_END]]', 'if', 'e_text', '!=', 'e[ENTITY_ATTRIBUTE_VALUE]:', 'add_synon...
837,697
Eric3911/OpenAGI
data_utils.py
DataStoreObject.local_path
local_path
Return local path of the object.
[ "Return", "local", "path", "of", "the", "object." ]
def local_path(self) -> str: return self._local_path
['def', 'local_path(self)', '->', 'str:', 'return', 'self._local_path']
274,177
Farama-Foundation/Gymnasium-Robotics
__init__.py
register_robotics_envs
register_robotics_envs
Register all environment ID's to Gymnasium.
[ "Register", "all", "environment", "ID's", "to", "Gymnasium." ]
def register_robotics_envs(): def _merge(a, b): a.update(b) return a for reward_type in ['sparse', 'dense']: suffix = 'Dense' if reward_type == 'dense' else '' kwargs = {'reward_type': reward_type} register(id=f'FetchSlide{suffix}-v1', entry_point='gymnasium_robotics.env...
['def', 'register_robotics_envs():', 'def', '_merge(a,', 'b):', 'a.update(b)', 'return', 'a', 'for', 'reward_type', 'in', "['sparse',", "'dense']:", 'suffix', '=', "'Dense'", 'if', 'reward_type', '==', "'dense'", 'else', "''", 'kwargs', '=', "{'reward_type':", 'reward_type}', "register(id=f'FetchSlide{suffix}-v1',", "e...
573,686
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
spec_builder.py
ComponentSpecBuilder.set_transition_system
set_transition_system
Shorthand to set transition_system using kwargs.
[ "Shorthand", "to", "set", "transition_system", "using", "kwargs." ]
def set_transition_system(self, *args, **kwargs): self.spec.transition_system.CopyFrom(self.make_module(*args, **kwargs))
['def', 'set_transition_system(self,', '*args,', '**kwargs):', 'self.spec.transition_system.CopyFrom(self.make_module(*args,', '**kwargs))']
28,624
JDAI-CV/CoTNet-ObjectDetection-InstanceSegmentation
secotnetd.py
make_secotnetd_stage
make_secotnetd_stage
Deprecated alias for backward compatibiltiy.
[ "Deprecated", "alias", "for", "backward", "compatibiltiy." ]
def make_secotnetd_stage(*args, **kwargs): return SECoTNetD.make_stage(*args, **kwargs)
['def', 'make_secotnetd_stage(*args,', '**kwargs):', 'return', 'SECoTNetD.make_stage(*args,', '**kwargs)']
489,329
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
_pydecimal.py
Decimal.is_subnormal
is_subnormal
Return True if self is subnormal; otherwise return False.
[ "Return", "True", "if", "self", "is", "subnormal;", "otherwise", "return", "False." ]
def is_subnormal(self, context=None): if self._is_special or not self: return False if context is None: context = getcontext() return self.adjusted() < context.Emin
['def', 'is_subnormal(self,', 'context=None):', 'if', 'self._is_special', 'or', 'not', 'self:', 'return', 'False', 'if', 'context', 'is', 'None:', 'context', '=', 'getcontext()', 'return', 'self.adjusted()', '<', 'context.Emin']
429,989
43Carrig/recurrent_neural_networks_practice
_argument_parser.py
EnumParser.parse
parse
Determines validity of argument and returns the correct element of enum.
[ "Determines", "validity", "of", "argument", "and", "returns", "the", "correct", "element", "of", "enum." ]
def parse(self, argument): if self.case_sensitive: if argument not in self.enum_values: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return argument elif argument.upper() not in [value.upper() for value in self.enum_values]: r...
['def', 'parse(self,', 'argument):', 'if', 'self.case_sensitive:', 'if', 'argument', 'not', 'in', 'self.enum_values:', 'raise', "ValueError('value", 'should', 'be', 'one', 'of', "<%s>'", '%', "'|'.join(self.enum_values))", 'else:', 'return', 'argument', 'elif', 'argument.upper()', 'not', 'in', '[value.upper()', 'for', ...
309,594
kornia/kornia
image_registrator.py
Similarity.reset_model
reset_model
Initialize the model with identity transform.
[ "Initialize", "the", "model", "with", "identity", "transform." ]
def reset_model(self) -> None: torch.nn.init.zeros_(self.rot) torch.nn.init.zeros_(self.shift) torch.nn.init.ones_(self.scale)
['def', 'reset_model(self)', '->', 'None:', 'torch.nn.init.zeros_(self.rot)', 'torch.nn.init.zeros_(self.shift)', 'torch.nn.init.ones_(self.scale)']
622,153
openvinotoolkit/training_extensions
parameter_group.py
ParameterGroup.get_metadata
get_metadata
Retrieve the metadata for a particular parameter from the group.
[ "Retrieve", "the", "metadata", "for", "a", "particular", "parameter", "from", "the", "group." ]
def get_metadata(self, parameter_name: str) -> dict: parameter = getattr(attr.fields(type(self)), parameter_name, None) if parameter is not None: parameter_metadata = getattr(parameter, 'metadata', {}) metadata_dict = dict(parameter_metadata) parameter_overrides = self.__metadata_overrid...
['def', 'get_metadata(self,', 'parameter_name:', 'str)', '->', 'dict:', 'parameter', '=', 'getattr(attr.fields(type(self)),', 'parameter_name,', 'None)', 'if', 'parameter', 'is', 'not', 'None:', 'parameter_metadata', '=', 'getattr(parameter,', "'metadata',", '{})', 'metadata_dict', '=', 'dict(parameter_metadata)', 'par...
918,409
ruhyadi/yolo3d-lightning
test_sweeps.py
test_hydra_sweep_ddp_sim
test_hydra_sweep_ddp_sim
Test default hydra sweep with ddp sim.
[ "Test", "default", "hydra", "sweep", "with", "ddp", "sim." ]
def test_hydra_sweep_ddp_sim(tmp_path): command = [startfile, '-m', 'hydra.sweep.dir=' + str(tmp_path), 'trainer=ddp_sim', 'trainer.max_epochs=3', '+trainer.limit_train_batches=0.01', '+trainer.limit_val_batches=0.1', '+trainer.limit_test_batches=0.1', 'model.optimizer.lr=0.005,0.01,0.02'] + overrides run_sh_co...
['def', 'test_hydra_sweep_ddp_sim(tmp_path):', 'command', '=', '[startfile,', "'-m',", "'hydra.sweep.dir='", '+', 'str(tmp_path),', "'trainer=ddp_sim',", "'trainer.max_epochs=3',", "'+trainer.limit_train_batches=0.01',", "'+trainer.limit_val_batches=0.1',", "'+trainer.limit_test_batches=0.1',", "'model.optimizer.lr=0.0...
969,220
ludwig-ai/ludwig
test_fields_optimization.py
get_marshmallow_from_dataclass_field
get_marshmallow_from_dataclass_field
Helper method for checking marshmallow metadata succinctly.
[ "Helper", "method", "for", "checking", "marshmallow", "metadata", "succinctly." ]
def get_marshmallow_from_dataclass_field(dfield): return dfield.metadata['marshmallow_field']
['def', 'get_marshmallow_from_dataclass_field(dfield):', 'return', "dfield.metadata['marshmallow_field']"]
617,399
enuguru/artificial_intelligence_and_machine_
searching.py
ResultsPage.docnum
docnum
Returns the document number of the hit at the nth position on this page.
[ "Returns", "the", "document", "number", "of", "the", "hit", "at", "the", "nth", "position", "on", "this", "page." ]
def docnum(self, n): return self.results.docnum(n + self.offset)
['def', 'docnum(self,', 'n):', 'return', 'self.results.docnum(n', '+', 'self.offset)']
133,166
jbwang1997/CrossKD
panoptic_gt_processing.py
preprocess_panoptic_gt
preprocess_panoptic_gt
Preprocess the ground truth for a image.
[ "Preprocess", "the", "ground", "truth", "for", "a", "image." ]
def preprocess_panoptic_gt(gt_labels: Tensor, gt_masks: Tensor, gt_semantic_seg: Tensor, num_things: int, num_stuff: int) -> Tuple[Tensor, Tensor]: num_classes = num_things + num_stuff things_masks = gt_masks.to_tensor(dtype=torch.bool, device=gt_labels.device) if gt_semantic_seg is None: masks = th...
['def', 'preprocess_panoptic_gt(gt_labels:', 'Tensor,', 'gt_masks:', 'Tensor,', 'gt_semantic_seg:', 'Tensor,', 'num_things:', 'int,', 'num_stuff:', 'int)', '->', 'Tuple[Tensor,', 'Tensor]:', 'num_classes', '=', 'num_things', '+', 'num_stuff', 'things_masks', '=', 'gt_masks.to_tensor(dtype=torch.bool,', 'device=gt_label...
491,632
IntelLabs/nlp-architect
rerank_terms.py
RerankTerms.cross_validation_training
cross_validation_training
Perform k fold cross validation and evaluate the results.
[ "Perform", "k", "fold", "cross", "validation", "and", "evaluate", "the", "results." ]
def cross_validation_training(self, verbose=False): final_report = {} (x, y, y_vector, terms, _) = self.load_terms_and_y_labels_and_generate_features(self.train_rerank_data_path) for seed in self.seeds: np.random.seed(seed) for (epochs, batch_size) in self.epochs_and_batch_size: ...
['def', 'cross_validation_training(self,', 'verbose=False):', 'final_report', '=', '{}', '(x,', 'y,', 'y_vector,', 'terms,', '_)', '=', 'self.load_terms_and_y_labels_and_generate_features(self.train_rerank_data_path)', 'for', 'seed', 'in', 'self.seeds:', 'np.random.seed(seed)', 'for', '(epochs,', 'batch_size)', 'in', '...
783,374
deepmind/dm_control
cartpole.py
Balance.get_reward
get_reward
Returns a sparse or a smooth reward, as specified in the constructor.
[ "Returns", "a", "sparse", "or", "a", "smooth", "reward,", "as", "specified", "in", "the", "constructor." ]
def get_reward(self, physics): return self._get_reward(physics, sparse=self._sparse)
['def', 'get_reward(self,', 'physics):', 'return', 'self._get_reward(physics,', 'sparse=self._sparse)']
166,297
google/deepvariant
dashboard_utils.py
create_html_report
create_html_report
Makes the html report with all the charts inserted.
[ "Makes", "the", "html", "report", "with", "all", "the", "charts", "inserted." ]
def create_html_report(specs: List[Dict[Text, alt.Chart]], html_output: Any, title: str='', subtitle: str='', charts_on_separate_lines: bool=False, include_outline: bool=False) -> None: for (i, spec) in enumerate(specs): if not isinstance(spec, dict): raise ValueError(f'item #{i + 1} in specs li...
['def', 'create_html_report(specs:', 'List[Dict[Text,', 'alt.Chart]],', 'html_output:', 'Any,', 'title:', "str='',", 'subtitle:', "str='',", 'charts_on_separate_lines:', 'bool=False,', 'include_outline:', 'bool=False)', '->', 'None:', 'for', '(i,', 'spec)', 'in', 'enumerate(specs):', 'if', 'not', 'isinstance(spec,', 'd...
540,253
famura/SimuRLacra
parallel.py
ParallelTasks.step_rew
step_rew
Get the step reward accumulated from every non-done task.
[ "Get", "the", "step", "reward", "accumulated", "from", "every", "non-done", "task." ]
def step_rew(self, state: np.ndarray, act: np.ndarray, remaining_steps: int) -> float: step_rew = 0.0 for i in range(len(self)): if not (self.succeeded_tasks[i] or self.failed_tasks[i]): step_rew += self._tasks[i].step_rew(state, act, remaining_steps) elif self.hold_rew_when_done: ...
['def', 'step_rew(self,', 'state:', 'np.ndarray,', 'act:', 'np.ndarray,', 'remaining_steps:', 'int)', '->', 'float:', 'step_rew', '=', '0.0', 'for', 'i', 'in', 'range(len(self)):', 'if', 'not', '(self.succeeded_tasks[i]', 'or', 'self.failed_tasks[i]):', 'step_rew', '+=', 'self._tasks[i].step_rew(state,', 'act,', 'remai...
884,021
flow-project/flow
base.py
BaseKernelNetwork.get_edge_list
get_edge_list
Return the names of all edges in the network.
[ "Return", "the", "names", "of", "all", "edges", "in", "the", "network." ]
def get_edge_list(self): raise NotImplementedError
['def', 'get_edge_list(self):', 'raise', 'NotImplementedError']
212,114
Kvatsx/Artificial-Intelligence-Assignments
mixer_test.py
MixerModuleTest.test_get_raw_more
test_get_raw_more
test the array interface a bit better.
[ "test", "the", "array", "interface", "a", "bit", "better." ]
def test_get_raw_more(self): import platform IS_PYPY = 'PyPy' == platform.python_implementation() if IS_PYPY: return from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString except: Bytes_FromString = pythonapi.PyString_FromSt...
['def', 'test_get_raw_more(self):', 'import', 'platform', 'IS_PYPY', '=', "'PyPy'", '==', 'platform.python_implementation()', 'if', 'IS_PYPY:', 'return', 'from', 'ctypes', 'import', 'pythonapi,', 'c_void_p,', 'py_object', 'try:', 'Bytes_FromString', '=', 'pythonapi.PyBytes_FromString', 'except:', 'Bytes_FromString', '=...
76,429
lightonai/dfa-scales-to-modern-deep-learning
lieutils.py
grad_sin_theta_by_theta
grad_sin_theta_by_theta
Computes :math:`\frac{\partial sin \theta}{\partial \theta \theta}`.
[ "Computes", ":math:`\\frac{\\partial", "sin", "\\theta}{\\partial", "\\theta", "\\theta}`." ]
def grad_sin_theta_by_theta(theta: torch.Tensor, eps: float=0.001): result = torch.zeros_like(theta) (s, l) = get_small_and_large_angle_inds(theta, eps) theta_sq = theta ** 2 result[s] = -theta[s] / 3 * (1 - theta_sq[s] / 10 * (1 - theta_sq[s] / 28 * (1 - theta_sq[s] / 54))) result[l] = cos(theta[l]...
['def', 'grad_sin_theta_by_theta(theta:', 'torch.Tensor,', 'eps:', 'float=0.001):', 'result', '=', 'torch.zeros_like(theta)', '(s,', 'l)', '=', 'get_small_and_large_angle_inds(theta,', 'eps)', 'theta_sq', '=', 'theta', '**', '2', 'result[s]', '=', '-theta[s]', '/', '3', '*', '(1', '-', 'theta_sq[s]', '/', '10', '*', '(...
550,008
43Carrig/recurrent_neural_networks_practice
vector_sinh_arcsinh_diag.py
VectorSinhArcsinhDiag.scale
scale
The `LinearOperator` `scale` in `Y := loc + scale @ F(Z) * (2 / F(2)).
[ "The", "`LinearOperator`", "`scale`", "in", "`Y", ":=", "loc", "+", "scale", "@", "F(Z)", "*", "(2", "/", "F(2))." ]
def scale(self): return self._scale
['def', 'scale(self):', 'return', 'self._scale']
312,905
intelligent-environments-lab/CityLearn
building.py
Building.cooling_device
cooling_device
Electric device for meeting space cooling demand and charging `cooling_storage`.
[ "Electric", "device", "for", "meeting", "space", "cooling", "demand", "and", "charging", "`cooling_storage`." ]
def cooling_device(self) -> HeatPump: return self.__cooling_device
['def', 'cooling_device(self)', '->', 'HeatPump:', 'return', 'self.__cooling_device']
105,554
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
inception_v4.py
inception_v4_base
inception_v4_base
Creates the Inception V4 network up to the given final endpoint.
[ "Creates", "the", "Inception", "V4", "network", "up", "to", "the", "given", "final", "endpoint." ]
def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None): end_points = {} def add_and_check_final(name, net): end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionV4', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, s...
['def', 'inception_v4_base(inputs,', "final_endpoint='Mixed_7d',", 'scope=None):', 'end_points', '=', '{}', 'def', 'add_and_check_final(name,', 'net):', 'end_points[name]', '=', 'net', 'return', 'name', '==', 'final_endpoint', 'with', 'tf.variable_scope(scope,', "'InceptionV4',", '[inputs]):', 'with', 'slim.arg_scope([...
27,175
gunthercox/ChatterBot
decorators.py
AttributeValueGenerator.update_generator_registry
update_generator_registry
Adds generator functions to generator_registry.
[ "Adds", "generator", "functions", "to", "generator_registry." ]
def update_generator_registry(self, mapper, class_): for generator in class_.__dict__.values(): if hasattr(generator, '__generates__'): self.generator_registry[class_].append(generator)
['def', 'update_generator_registry(self,', 'mapper,', 'class_):', 'for', 'generator', 'in', 'class_.__dict__.values():', 'if', 'hasattr(generator,', "'__generates__'):", 'self.generator_registry[class_].append(generator)']
535,188
yinguobing/models
shufflenet_v2.py
shuffle_unit_v2
shuffle_unit_v2
Build building blocks for ShuffleNet v2.
[ "Build", "building", "blocks", "for", "ShuffleNet", "v2." ]
def shuffle_unit_v2(split=0.5, downsampling=False, filters=None): if not downsampling: assert split > 0 and split < 1, 'Split value should be in range (0, 1), got {}'.format(split) strides = 2 if downsampling else 1 def forward(inputs): (_, _, _, num_input_channels) = inputs.shape i...
['def', 'shuffle_unit_v2(split=0.5,', 'downsampling=False,', 'filters=None):', 'if', 'not', 'downsampling:', 'assert', 'split', '>', '0', 'and', 'split', '<', '1,', "'Split", 'value', 'should', 'be', 'in', 'range', '(0,', '1),', 'got', "{}'.format(split)", 'strides', '=', '2', 'if', 'downsampling', 'else', '1', 'def', ...
626,427
acba/elm
mltools.py
MLTools.save_regressor
save_regressor
Save current classifier/regressor to file_name file.
[ "Save", "current", "classifier/regressor", "to", "file_name", "file." ]
def save_regressor(self, file_name): try: file = file_name with open(file, 'wb') as f: pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL) except: print('Error while saving ', file_name) return else: print('Saved model as: ', file_name)
['def', 'save_regressor(self,', 'file_name):', 'try:', 'file', '=', 'file_name', 'with', 'open(file,', "'wb')", 'as', 'f:', 'pickle.dump(self,', 'f,', 'protocol=pickle.HIGHEST_PROTOCOL)', 'except:', "print('Error", 'while', 'saving', "',", 'file_name)', 'return', 'else:', "print('Saved", 'model', 'as:', "',", 'file_nam...
561,462
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mesh_tensorflow.py
LayoutRules.tensor_layout
tensor_layout
Computes TensorLayout given a Tensor Shape and a Mesh Shape.
[ "Computes", "TensorLayout", "given", "a", "Tensor", "Shape", "and", "a", "Mesh", "Shape." ]
def tensor_layout(self, tensor_shape, mesh_shape): ret = [self.tensor_dimension_to_mesh_axis(d, mesh_shape) for d in tensor_shape] not_nones = [a for a in ret if a is not None] if len(not_nones) != len(set(not_nones)): raise ValueError('Two Tensor Dimensions may not map to the same Mesh Dimension: l...
['def', 'tensor_layout(self,', 'tensor_shape,', 'mesh_shape):', 'ret', '=', '[self.tensor_dimension_to_mesh_axis(d,', 'mesh_shape)', 'for', 'd', 'in', 'tensor_shape]', 'not_nones', '=', '[a', 'for', 'a', 'in', 'ret', 'if', 'a', 'is', 'not', 'None]', 'if', 'len(not_nones)', '!=', 'len(set(not_nones)):', 'raise', "ValueE...
965,492
CUNY-CL/yoyodyne
util.py
log_arguments
log_arguments
Logs non-null arguments via log_info.
[ "Logs", "non-null", "arguments", "via", "log_info." ]
def log_arguments(args: argparse.Namespace) -> None: log_info('Arguments:') for (arg, val) in vars(args).items(): if val is None: continue log_info(f'\t{arg}: {val!r}')
['def', 'log_arguments(args:', 'argparse.Namespace)', '->', 'None:', "log_info('Arguments:')", 'for', '(arg,', 'val)', 'in', 'vars(args).items():', 'if', 'val', 'is', 'None:', 'continue', "log_info(f'\\t{arg}:", "{val!r}')"]
971,168
vmware-archive/salt-contrib
awsparam.py
get_parameter
get_parameter
Get a parameter by name.
[ "Get", "a", "parameter", "by", "name." ]
def get_parameter(name): region = _get_region() credentials = _get_credentials() ssm = boto3.client('ssm', region_name=region, aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key']) try: response = ssm.get_parameters(Names=[name], WithDecryption=True) ...
['def', 'get_parameter(name):', 'region', '=', '_get_region()', 'credentials', '=', '_get_credentials()', 'ssm', '=', "boto3.client('ssm',", 'region_name=region,', "aws_access_key_id=credentials['access_key'],", "aws_secret_access_key=credentials['secret_key'])", 'try:', 'response', '=', 'ssm.get_parameters(Names=[name...
328,630
mkusner/grammarVAE
subtensor.py
GpuIncSubtensor.do_type_checking
do_type_checking
Should raise NotImplementedError if c_code does not support the types involved in this node.
[ "Should", "raise", "NotImplementedError", "if", "c_code", "does", "not", "support", "the", "types", "involved", "in", "this", "node." ]
def do_type_checking(self, node): if not isinstance(node.inputs[0].type, GpuArrayType): raise NotImplementedError()
['def', 'do_type_checking(self,', 'node):', 'if', 'not', 'isinstance(node.inputs[0].type,', 'GpuArrayType):', 'raise', 'NotImplementedError()']
579,562
Trusted-AI/AIF360
metrics.py
num_pos_neg
num_pos_neg
Compute the number of positive and negative samples.
[ "Compute", "the", "number", "of", "positive", "and", "negative", "samples." ]
def num_pos_neg(y_true, y_pred=None, pos_label=1, sample_weight=None): y = y_true if y_pred is None else y_pred sample_weight = check_inputs(y_true, y, sample_weight, ensure_2d=False)[2] pos = (y == pos_label).tolist() neg = (y != pos_label).tolist() return (sum(sample_weight[pos]), sum(sample_weigh...
['def', 'num_pos_neg(y_true,', 'y_pred=None,', 'pos_label=1,', 'sample_weight=None):', 'y', '=', 'y_true', 'if', 'y_pred', 'is', 'None', 'else', 'y_pred', 'sample_weight', '=', 'check_inputs(y_true,', 'y,', 'sample_weight,', 'ensure_2d=False)[2]', 'pos', '=', '(y', '==', 'pos_label).tolist()', 'neg', '=', '(y', '!=', '...
412,416
weimin17/Object-Detection_HelmetDetection
problem_sets.py
test_problems
test_problems
Test problems for visualizations.
[ "Test", "problems", "for", "visualizations." ]
def test_problems(): tp = [(_Spec(pg.Quadratic, (20,), {'random_seed': 1234}), None, None, 'quad_problem', 5678), (_Spec(pg.Quadratic, (20,), {'noise_stdev': 1.0, 'random_seed': 1234}), None, None, 'quad_problem_noise', 5678), (_Spec(pg.Rosenbrock, (), {'random_seed': 1234}), None, None, 'rosenbrock', 5678), (_Spec...
['def', 'test_problems():', 'tp', '=', '[(_Spec(pg.Quadratic,', '(20,),', "{'random_seed':", '1234}),', 'None,', 'None,', "'quad_problem',", '5678),', '(_Spec(pg.Quadratic,', '(20,),', "{'noise_stdev':", '1.0,', "'random_seed':", '1234}),', 'None,', 'None,', "'quad_problem_noise',", '5678),', '(_Spec(pg.Rosenbrock,', '...
750,385