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
myothida/Supervised-Machine-Learning
utils.py
within_delta
within_delta
Useful for comparing two datetimes that may have a negligible difference to be considered equal.
[ "Useful", "for", "comparing", "two", "datetimes", "that", "may", "have", "a", "negligible", "difference", "to", "be", "considered", "equal." ]
def within_delta(dt1, dt2, delta): delta = abs(delta) difference = dt1 - dt2 return -delta <= difference <= delta
['def', 'within_delta(dt1,', 'dt2,', 'delta):', 'delta', '=', 'abs(delta)', 'difference', '=', 'dt1', '-', 'dt2', 'return', '-delta', '<=', 'difference', '<=', 'delta']
360,669
BillZito/transfer-learning
retrain.py
create_bottleneck_file
create_bottleneck_file
Create a single bottleneck file.
[ "Create", "a", "single", "bottleneck", "file." ]
def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): tf.logging.info('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_...
['def', 'create_bottleneck_file(bottleneck_path,', 'image_lists,', 'label_name,', 'index,', 'image_dir,', 'category,', 'sess,', 'jpeg_data_tensor,', 'decoded_image_tensor,', 'resized_input_tensor,', 'bottleneck_tensor):', "tf.logging.info('Creating", 'bottleneck', 'at', "'", '+', 'bottleneck_path)', 'image_path', '=', ...
929,027
kornia/kornia
face_detection.py
FaceDetectorResult.get_keypoint
get_keypoint
The [x y] position of a given facial keypoint.
[ "The", "[x", "y]", "position", "of", "a", "given", "facial", "keypoint." ]
def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor: if keypoint == FaceKeypoint.EYE_LEFT: out = self._data[..., (4, 5)] elif keypoint == FaceKeypoint.EYE_RIGHT: out = self._data[..., (6, 7)] elif keypoint == FaceKeypoint.NOSE: out = self._data[..., (8, 9)] elif keypoi...
['def', 'get_keypoint(self,', 'keypoint:', 'FaceKeypoint)', '->', 'torch.Tensor:', 'if', 'keypoint', '==', 'FaceKeypoint.EYE_LEFT:', 'out', '=', 'self._data[...,', '(4,', '5)]', 'elif', 'keypoint', '==', 'FaceKeypoint.EYE_RIGHT:', 'out', '=', 'self._data[...,', '(6,', '7)]', 'elif', 'keypoint', '==', 'FaceKeypoint.NOSE...
621,589
Ruturaj123/Flowchart-Detection
pixelda_model.py
resnet_stack
resnet_stack
Create a resnet style transfer block.
[ "Create", "a", "resnet", "style", "transfer", "block." ]
def resnet_stack(images, output_shape, hparams, scope=None): end_points = {} if hparams.noise_channel: end_points['noise'] = images[:, :, :, -1] assert images.shape.as_list()[1:3] == output_shape[0:2] with tf.variable_scope(scope, 'resnet_style_transfer', [images]): with slim.arg_scope([...
['def', 'resnet_stack(images,', 'output_shape,', 'hparams,', 'scope=None):', 'end_points', '=', '{}', 'if', 'hparams.noise_channel:', "end_points['noise']", '=', 'images[:,', ':,', ':,', '-1]', 'assert', 'images.shape.as_list()[1:3]', '==', 'output_shape[0:2]', 'with', 'tf.variable_scope(scope,', "'resnet_style_transfe...
585,638
RasaHQ/rasa
loader.py
load_predict_graph_runner
load_predict_graph_runner
Loads a model from an archive and creates the prediction graph runner.
[ "Loads", "a", "model", "from", "an", "archive", "and", "creates", "the", "prediction", "graph", "runner." ]
def load_predict_graph_runner(storage_path: Path, model_archive_path: Path, model_storage_class: Type[ModelStorage], graph_runner_class: Type[GraphRunner]) -> Tuple[ModelMetadata, GraphRunner]: (model_storage, model_metadata) = model_storage_class.from_model_archive(storage_path=storage_path, model_archive_path=mod...
['def', 'load_predict_graph_runner(storage_path:', 'Path,', 'model_archive_path:', 'Path,', 'model_storage_class:', 'Type[ModelStorage],', 'graph_runner_class:', 'Type[GraphRunner])', '->', 'Tuple[ModelMetadata,', 'GraphRunner]:', '(model_storage,', 'model_metadata)', '=', 'model_storage_class.from_model_archive(storag...
837,014
openvinotoolkit/training_extensions
eval_hook.py
DistCustomEvalHook.after_train_epoch
after_train_epoch
Check whether current epoch is to be evaluated or not.
[ "Check", "whether", "current", "epoch", "is", "to", "be", "evaluated", "or", "not." ]
def after_train_epoch(self, runner): if not self.by_epoch or not self.every_n_epochs(runner, self.interval): return self._do_evaluate(runner)
['def', 'after_train_epoch(self,', 'runner):', 'if', 'not', 'self.by_epoch', 'or', 'not', 'self.every_n_epochs(runner,', 'self.interval):', 'return', 'self._do_evaluate(runner)']
917,821
cwlinkem/linkuce
fasta_to_phy.py
parse_fasta
parse_fasta
Takes a fasta file, separates label and sequence.
[ "Takes", "a", "fasta", "file,", "separates", "label", "and", "sequence." ]
def parse_fasta(inp): identifiers = [] sequences = [] current_seq = [] dict = {} for line in inp: stripped = line.strip() if line.startswith('>'): if current_seq: sequences.append(''.join(current_seq)) identifiers.append(stripped[1:]) ...
['def', 'parse_fasta(inp):', 'identifiers', '=', '[]', 'sequences', '=', '[]', 'current_seq', '=', '[]', 'dict', '=', '{}', 'for', 'line', 'in', 'inp:', 'stripped', '=', 'line.strip()', 'if', "line.startswith('>'):", 'if', 'current_seq:', "sequences.append(''.join(current_seq))", 'identifiers.append(stripped[1:])', 'cu...
602,743
TrellixVulnTeam/Unsupervised_Learning_HFI7
indexing.py
maybe_convert_ix
maybe_convert_ix
We likely want to take the cross-product.
[ "We", "likely", "want", "to", "take", "the", "cross-product." ]
def maybe_convert_ix(*args): for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): return args return np.ix_(*args)
['def', 'maybe_convert_ix(*args):', 'for', 'arg', 'in', 'args:', 'if', 'not', 'isinstance(arg,', '(np.ndarray,', 'list,', 'ABCSeries,', 'Index)):', 'return', 'args', 'return', 'np.ix_(*args)']
452,639
secretflow/secretflow
model.py
SSRegression.save_model
save_model
Save fit model in LinearModel format.
[ "Save", "fit", "model", "in", "LinearModel", "format." ]
def save_model(self) -> LinearModel: assert hasattr(self, 'spu_w'), 'please fit model first' return LinearModel(self.spu_w, self.reg_type, self.sig_type)
['def', 'save_model(self)', '->', 'LinearModel:', 'assert', 'hasattr(self,', "'spu_w'),", "'please", 'fit', 'model', "first'", 'return', 'LinearModel(self.spu_w,', 'self.reg_type,', 'self.sig_type)']
856,533
arshpreetsingh/quantopian-machinelearning
test_ops.py
constructor
constructor
Fixture for testing both interval container classes.
[ "Fixture", "for", "testing", "both", "interval", "container", "classes." ]
def constructor(request): return request.param
['def', 'constructor(request):', 'return', 'request.param']
890,572
yihui-he/KL-Loss
task_evaluation.py
evaluate_all
evaluate_all
Evaluate "all" tasks, where "all" includes box detection, instance segmentation, and keypoint detection.
[ "Evaluate", "\"all\"", "tasks,", "where", "\"all\"", "includes", "box", "detection,", "instance", "segmentation,", "and", "keypoint", "detection." ]
def evaluate_all(dataset, all_boxes, all_segms, all_keyps, output_dir, use_matlab=False): all_results = evaluate_boxes(dataset, all_boxes, output_dir, use_matlab=use_matlab) logger.info('Evaluating bounding boxes is done!') if cfg.MODEL.MASK_ON: results = evaluate_masks(dataset, all_boxes, all_segms...
['def', 'evaluate_all(dataset,', 'all_boxes,', 'all_segms,', 'all_keyps,', 'output_dir,', 'use_matlab=False):', 'all_results', '=', 'evaluate_boxes(dataset,', 'all_boxes,', 'output_dir,', 'use_matlab=use_matlab)', "logger.info('Evaluating", 'bounding', 'boxes', 'is', "done!')", 'if', 'cfg.MODEL.MASK_ON:', 'results', '=...
596,493
matsu0228/nlp-jp
mongo_client.py
MongoClient.database_names
database_names
Get a list of the names of all databases on the connected server.
[ "Get", "a", "list", "of", "the", "names", "of", "all", "databases", "on", "the", "connected", "server." ]
def database_names(self): return [db['name'] for db in self._database_default_options('admin').command(SON([('listDatabases', 1), ('nameOnly', True)]))['databases']]
['def', 'database_names(self):', 'return', "[db['name']", 'for', 'db', 'in', "self._database_default_options('admin').command(SON([('listDatabases',", '1),', "('nameOnly',", "True)]))['databases']]"]
804,910
ldkong1205/LaserMix
transforms_3d.py
GlobalRotScaleTrans.transform
transform
Private function to rotate, scale and translate bounding boxes and points.
[ "Private", "function", "to", "rotate,", "scale", "and", "translate", "bounding", "boxes", "and", "points." ]
def transform(self, input_dict: dict) -> dict: if 'transformation_3d_flow' not in input_dict: input_dict['transformation_3d_flow'] = [] self._rot_bbox_points(input_dict) if 'pcd_scale_factor' not in input_dict: self._random_scale(input_dict) self._scale_bbox_points(input_dict) self._...
['def', 'transform(self,', 'input_dict:', 'dict)', '->', 'dict:', 'if', "'transformation_3d_flow'", 'not', 'in', 'input_dict:', "input_dict['transformation_3d_flow']", '=', '[]', 'self._rot_bbox_points(input_dict)', 'if', "'pcd_scale_factor'", 'not', 'in', 'input_dict:', 'self._random_scale(input_dict)', 'self._scale_b...
623,822
suarez12138/AI-Reversi_IMP_TextDichotomy
_layoutbox.py
LayoutBox.update_variables
update_variables
Update *all* the variables that are part of the solver this LayoutBox is created with.
[ "Update", "*all*", "the", "variables", "that", "are", "part", "of", "the", "solver", "this", "LayoutBox", "is", "created", "with." ]
def update_variables(self): self.solver.updateVariables()
['def', 'update_variables(self):', 'self.solver.updateVariables()']
96,968
JohannesAck/tf2multiagentrl
matd3.py
MATD3Agent.update_target_networks
update_target_networks
Implements the updates of the target networks, which slowly follow the real network.
[ "Implements", "the", "updates", "of", "the", "target", "networks,", "which", "slowly", "follow", "the", "real", "network." ]
def update_target_networks(self, tau): def update_target_network(net: tf.keras.Model, target_net: tf.keras.Model): net_weights = np.array(net.get_weights()) target_net_weights = np.array(target_net.get_weights()) new_weights = tau * net_weights + (1.0 - tau) * target_net_weights tar...
['def', 'update_target_networks(self,', 'tau):', 'def', 'update_target_network(net:', 'tf.keras.Model,', 'target_net:', 'tf.keras.Model):', 'net_weights', '=', 'np.array(net.get_weights())', 'target_net_weights', '=', 'np.array(target_net.get_weights())', 'new_weights', '=', 'tau', '*', 'net_weights', '+', '(1.0', '-',...
915,715
jimtin/Stock_Comparison
test_decorators.py
test_deliberately_broken
test_deliberately_broken
A deliberately broken test - we want to skip this one.
[ "A", "deliberately", "broken", "test", "-", "we", "want", "to", "skip", "this", "one." ]
def test_deliberately_broken(): 1 / 0
['def', 'test_deliberately_broken():', '1', '/', '0']
385,416
011235813/cm3
alg_baseline.py
Alg.run_actor
run_actor
Gets actions for all agents as a batch.
[ "Gets", "actions", "for", "all", "agents", "as", "a", "batch." ]
def run_actor(self, local_others, local_v, goals, epsilon, sess): obs_others = np.array(local_others) v_obs = np.array(local_v) feed = {self.obs_others: obs_others, self.v_obs: v_obs, self.v_goal: goals, self.epsilon: epsilon} action_samples_res = sess.run(self.action_samples, feed_dict=feed) return...
['def', 'run_actor(self,', 'local_others,', 'local_v,', 'goals,', 'epsilon,', 'sess):', 'obs_others', '=', 'np.array(local_others)', 'v_obs', '=', 'np.array(local_v)', 'feed', '=', '{self.obs_others:', 'obs_others,', 'self.v_obs:', 'v_obs,', 'self.v_goal:', 'goals,', 'self.epsilon:', 'epsilon}', 'action_samples_res', '...
488,558
Farama-Foundation/Gymnasium
test_delay_observation.py
test_delay_failures
test_delay_failures
Test errors raised by DelayObservation wrapper.
[ "Test", "errors", "raised", "by", "DelayObservation", "wrapper." ]
def test_delay_failures(): env = gym.make('CartPole-v1') with pytest.raises(TypeError, match=re.escape("The delay is expected to be an integer, actual type: <class 'float'>")): DelayObservationV0(env, delay=1.0) with pytest.raises(ValueError, match=re.escape('The delay needs to be greater than zero,...
['def', 'test_delay_failures():', 'env', '=', "gym.make('CartPole-v1')", 'with', 'pytest.raises(TypeError,', 'match=re.escape("The', 'delay', 'is', 'expected', 'to', 'be', 'an', 'integer,', 'actual', 'type:', '<class', '\'float\'>")):', 'DelayObservationV0(env,', 'delay=1.0)', 'with', 'pytest.raises(ValueError,', "matc...
573,567
rifqind/Agent-Programs-3KS1
test_decorators.py
test_skip_dt_decorator
test_skip_dt_decorator
Doctest-skipping decorator should preserve the docstring.
[ "Doctest-skipping", "decorator", "should", "preserve", "the", "docstring." ]
def test_skip_dt_decorator(): check = 'A function whose doctest we need to skip.\n\n >>> 1+1\n 3\n ' val = doctest_bad.__doc__ nt.assert_equal(check, val, "doctest_bad docstrings don't match")
['def', 'test_skip_dt_decorator():', 'check', '=', "'A", 'function', 'whose', 'doctest', 'we', 'need', 'to', 'skip.\\n\\n', '>>>', '1+1\\n', '3\\n', "'", 'val', '=', 'doctest_bad.__doc__', 'nt.assert_equal(check,', 'val,', '"doctest_bad', 'docstrings', "don't", 'match")']
41,804
neel-dey/equivariant-gans
data_utils.py
npy_loader
npy_loader
Utility function to load npy files corresponding to training images and labels.
[ "Utility", "function", "to", "load", "npy", "files", "corresponding", "to", "training", "images", "and", "labels." ]
def npy_loader(dataset, num_classes): data = np.load('./data/{}/train_images.npy'.format(dataset)) labels = np.load('./data/{}/train_labels.npy'.format(dataset)) labels = to_categorical(labels, num_classes=num_classes) return (data, labels)
['def', 'npy_loader(dataset,', 'num_classes):', 'data', '=', "np.load('./data/{}/train_images.npy'.format(dataset))", 'labels', '=', "np.load('./data/{}/train_labels.npy'.format(dataset))", 'labels', '=', 'to_categorical(labels,', 'num_classes=num_classes)', 'return', '(data,', 'labels)']
562,922
deepmind/dm_control
glfw_gui.py
GlfwWindow.set_full_screen
set_full_screen
Expands the main application window to full screen or minimizes it.
[ "Expands", "the", "main", "application", "window", "to", "full", "screen", "or", "minimizes", "it." ]
def set_full_screen(self, enable): if enable == self.is_full_screen: return if enable: self._oldsize = list(self.position) + list(self.shape) def enable_full_screen(window): display = glfw.get_primary_monitor() videomode = glfw.get_video_mode(display) ...
['def', 'set_full_screen(self,', 'enable):', 'if', 'enable', '==', 'self.is_full_screen:', 'return', 'if', 'enable:', 'self._oldsize', '=', 'list(self.position)', '+', 'list(self.shape)', 'def', 'enable_full_screen(window):', 'display', '=', 'glfw.get_primary_monitor()', 'videomode', '=', 'glfw.get_video_mode(display)'...
166,658
tobegit3hub/deep_image_model
tensor_format.py
format_tensor
format_tensor
Generate a RichTextLines object showing a tensor in formatted style.
[ "Generate", "a", "RichTextLines", "object", "showing", "a", "tensor", "in", "formatted", "style." ]
def format_tensor(tensor, tensor_name, include_metadata=False, np_printoptions=None, highlight_options=None): lines = [] if tensor_name is not None: lines.append('Tensor "%s":' % tensor_name) if tensor is None: if lines: lines.append('') lines.append('Uninitialized tensor...
['def', 'format_tensor(tensor,', 'tensor_name,', 'include_metadata=False,', 'np_printoptions=None,', 'highlight_options=None):', 'lines', '=', '[]', 'if', 'tensor_name', 'is', 'not', 'None:', "lines.append('Tensor", '"%s":\'', '%', 'tensor_name)', 'if', 'tensor', 'is', 'None:', 'if', 'lines:', "lines.append('')", "line...
182,419
triaquae/triaquae
util.py
to_current_timezone
to_current_timezone
When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display.
[ "When", "time", "zone", "support", "is", "enabled,", "convert", "aware", "datetimes", "to", "naive", "dateimes", "in", "the", "current", "time", "zone", "for", "display." ]
def to_current_timezone(value): if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return timezone.make_naive(value, current_timezone) return value
['def', 'to_current_timezone(value):', 'if', 'settings.USE_TZ', 'and', 'value', 'is', 'not', 'None', 'and', 'timezone.is_aware(value):', 'current_timezone', '=', 'timezone.get_current_timezone()', 'return', 'timezone.make_naive(value,', 'current_timezone)', 'return', 'value']
423,719
rudranil723/mini-main
repeated.py
Repeated.insert
insert
Insert ``value`` in the sequence before ``index``.
[ "Insert", "``value``", "in", "the", "sequence", "before", "``index``." ]
def insert(self, index: int, value): self.pb.insert(index, value)
['def', 'insert(self,', 'index:', 'int,', 'value):', 'self.pb.insert(index,', 'value)']
269,512
sarnsdev/social-alignment-data-mining
test_samples_generator.py
test_make_classification_informative_features
test_make_classification_informative_features
Test the construction of informative features in make_classification Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and fully-specified `weights`.
[ "Test", "the", "construction", "of", "informative", "features", "in", "make_classification", "Also", "tests", "`n_clusters_per_class`,", "`n_classes`,", "`hypercube`", "and", "fully-specified", "`weights`." ]
def test_make_classification_informative_features(): class_sep = 1000000.0 make = partial(make_classification, class_sep=class_sep, n_redundant=0, n_repeated=0, flip_y=0, shift=0, scale=1, shuffle=False) for (n_informative, weights, n_clusters_per_class) in [(2, [1], 1), (2, [1 / 3] * 3, 1), (2, [1 / 4] * 4...
['def', 'test_make_classification_informative_features():', 'class_sep', '=', '1000000.0', 'make', '=', 'partial(make_classification,', 'class_sep=class_sep,', 'n_redundant=0,', 'n_repeated=0,', 'flip_y=0,', 'shift=0,', 'scale=1,', 'shuffle=False)', 'for', '(n_informative,', 'weights,', 'n_clusters_per_class)', 'in', '...
391,820
rr-learning/transferable_dynamics_dataset
BNN.py
BNNLearner.save
save
Parameters ---------- filename: string used as filename to save a model.
[ "Parameters", "----------", "filename:", "string", "used", "as", "filename", "to", "save", "a", "model." ]
def save(self, filename): if not os.path.exists(filename): os.makedirs(filename) for (i, model) in enumerate(self.models_): torch.save(model.state_dict(), os.path.join(filename, 'state{}.pt'.format(i)))
['def', 'save(self,', 'filename):', 'if', 'not', 'os.path.exists(filename):', 'os.makedirs(filename)', 'for', '(i,', 'model)', 'in', 'enumerate(self.models_):', 'torch.save(model.state_dict(),', 'os.path.join(filename,', "'state{}.pt'.format(i)))"]
929,918
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
base.py
LocalTree.parents
parents
Yield each parent in the family tree.
[ "Yield", "each", "parent", "in", "the", "family", "tree." ]
def parents(self, pred=lambda v: True): while self: if pred(self): yield self self = self.parent
['def', 'parents(self,', 'pred=lambda', 'v:', 'True):', 'while', 'self:', 'if', 'pred(self):', 'yield', 'self', 'self', '=', 'self.parent']
17,500
shery322/Lunar-Lander-ANN
surface_test.py
SurfaceTypeTest.test_get_width__size_and_height
test_get_width__size_and_height
Ensure a surface's size, width and height can be retrieved.
[ "Ensure", "a", "surface's", "size,", "width", "and", "height", "can", "be", "retrieved." ]
def test_get_width__size_and_height(self): for w in xrange_(0, 255, 32): for h in xrange_(0, 127, 15): s = pygame.Surface((w, h)) self.assertEqual(s.get_width(), w) self.assertEqual(s.get_height(), h) self.assertEqual(s.get_size(), (w, h))
['def', 'test_get_width__size_and_height(self):', 'for', 'w', 'in', 'xrange_(0,', '255,', '32):', 'for', 'h', 'in', 'xrange_(0,', '127,', '15):', 's', '=', 'pygame.Surface((w,', 'h))', 'self.assertEqual(s.get_width(),', 'w)', 'self.assertEqual(s.get_height(),', 'h)', 'self.assertEqual(s.get_size(),', '(w,', 'h))']
619,169
devashish-patel/webcam-motion-detector
manager.py
ContentsManager.rename_file
rename_file
Rename a file or directory.
[ "Rename", "a", "file", "or", "directory." ]
def rename_file(self, old_path, new_path): raise NotImplementedError('must be implemented in a subclass')
['def', 'rename_file(self,', 'old_path,', 'new_path):', 'raise', "NotImplementedError('must", 'be', 'implemented', 'in', 'a', "subclass')"]
980,767
hamza-murad/AALU
discovery_v1.py
NluEnrichmentConcepts.from_dict
from_dict
Initialize a NluEnrichmentConcepts object from a json dictionary.
[ "Initialize", "a", "NluEnrichmentConcepts", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': args = {} valid_keys = ['limit'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class NluEnrichmentConcepts: ' + ', '.join(bad_keys)) if 'limit' in _dict: ...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'NluEnrichmentConcepts':", 'args', '=', '{}', 'valid_keys', '=', "['limit']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'NluEnrichmentCo...
5,616
jimtin/Stock_Comparison
paths.py
jupyter_config_path
jupyter_config_path
Return the search path for Jupyter config files as a list.
[ "Return", "the", "search", "path", "for", "Jupyter", "config", "files", "as", "a", "list." ]
def jupyter_config_path(): paths = [jupyter_config_dir()] for p in ENV_CONFIG_PATH: if p not in SYSTEM_CONFIG_PATH: paths.append(p) paths.extend(SYSTEM_CONFIG_PATH) return paths
['def', 'jupyter_config_path():', 'paths', '=', '[jupyter_config_dir()]', 'for', 'p', 'in', 'ENV_CONFIG_PATH:', 'if', 'p', 'not', 'in', 'SYSTEM_CONFIG_PATH:', 'paths.append(p)', 'paths.extend(SYSTEM_CONFIG_PATH)', 'return', 'paths']
386,135
rudranil723/mini-main
well_known_types.py
Duration.FromMilliseconds
FromMilliseconds
Converts milliseconds to Duration.
[ "Converts", "milliseconds", "to", "Duration." ]
def FromMilliseconds(self, millis): self._NormalizeDuration(millis // _MILLIS_PER_SECOND, millis % _MILLIS_PER_SECOND * _NANOS_PER_MILLISECOND)
['def', 'FromMilliseconds(self,', 'millis):', 'self._NormalizeDuration(millis', '//', '_MILLIS_PER_SECOND,', 'millis', '%', '_MILLIS_PER_SECOND', '*', '_NANOS_PER_MILLISECOND)']
318,475
mj-will/nessai
test_plot.py
test_corner_plot
test_corner_plot
Test the corner plot.
[ "Test", "the", "corner", "plot." ]
def test_corner_plot(live_points): fig = plot.corner_plot(live_points) assert fig is not None
['def', 'test_corner_plot(live_points):', 'fig', '=', 'plot.corner_plot(live_points)', 'assert', 'fig', 'is', 'not', 'None']
292,396
boostcampaitech3/level2-semantic-segmentation-level2-cv-16
layer_decay_optimizer_constructor.py
get_num_layer_for_vit
get_num_layer_for_vit
Get the layer id to set the different learning rates.
[ "Get", "the", "layer", "id", "to", "set", "the", "different", "learning", "rates." ]
def get_num_layer_for_vit(var_name, num_max_layer): if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'): return 0 elif var_name.startswith('backbone.patch_embed'): return 0 elif var_name.startswith('backbone.layers'): layer_id = int(var_name.split('.')[...
['def', 'get_num_layer_for_vit(var_name,', 'num_max_layer):', 'if', 'var_name', 'in', "('backbone.cls_token',", "'backbone.mask_token',", "'backbone.pos_embed'):", 'return', '0', 'elif', "var_name.startswith('backbone.patch_embed'):", 'return', '0', 'elif', "var_name.startswith('backbone.layers'):", 'layer_id', '=', "i...
588,713
Ruturaj123/Flowchart-Detection
configure.py
get_python_path
get_python_path
Get the python site package paths.
[ "Get", "the", "python", "site", "package", "paths." ]
def get_python_path(environ_cp): python_paths = [] if environ_cp.get('PYTHONPATH'): python_paths = environ_cp.get('PYTHONPATH').split(':') try: library_paths = site.getsitepackages() except AttributeError: from distutils.sysconfig import get_python_lib library_paths = [ge...
['def', 'get_python_path(environ_cp):', 'python_paths', '=', '[]', 'if', "environ_cp.get('PYTHONPATH'):", 'python_paths', '=', "environ_cp.get('PYTHONPATH').split(':')", 'try:', 'library_paths', '=', 'site.getsitepackages()', 'except', 'AttributeError:', 'from', 'distutils.sysconfig', 'import', 'get_python_lib', 'libra...
586,736
kubeflow/pipelines
_container_op.py
Container.add_volume_devices
add_volume_devices
Add a block device to be used by the container.
[ "Add", "a", "block", "device", "to", "be", "used", "by", "the", "container." ]
def add_volume_devices(self, volume_device) -> 'Container': if not isinstance(volume_device, V1VolumeDevice): raise ValueError('invalid argument. Must be of instance `V1VolumeDevice`.') self.volume_devices = create_and_append(self.volume_devices, volume_device) return self
['def', 'add_volume_devices(self,', 'volume_device)', '->', "'Container':", 'if', 'not', 'isinstance(volume_device,', 'V1VolumeDevice):', 'raise', "ValueError('invalid", 'argument.', 'Must', 'be', 'of', 'instance', "`V1VolumeDevice`.')", 'self.volume_devices', '=', 'create_and_append(self.volume_devices,', 'volume_devi...
780,120
tccbj/deeplabv3_plus_RS
model.py
refine_by_decoder
refine_by_decoder
Adds the decoder to obtain sharper segmentation results.
[ "Adds", "the", "decoder", "to", "obtain", "sharper", "segmentation", "results." ]
def refine_by_decoder(features, end_points, crop_size=None, decoder_output_stride=None, decoder_use_separable_conv=False, model_variant=None, weight_decay=0.0001, reuse=None, is_training=False, fine_tune_batch_norm=False, use_bounded_activation=False): if crop_size is None: raise ValueError('crop_size must ...
['def', 'refine_by_decoder(features,', 'end_points,', 'crop_size=None,', 'decoder_output_stride=None,', 'decoder_use_separable_conv=False,', 'model_variant=None,', 'weight_decay=0.0001,', 'reuse=None,', 'is_training=False,', 'fine_tune_batch_norm=False,', 'use_bounded_activation=False):', 'if', 'crop_size', 'is', 'None...
521,438
RasaHQ/rasa
yaml_story_writer.py
YAMLStoryWriter.dump
dump
Writes Story steps into a target file/stream.
[ "Writes", "Story", "steps", "into", "a", "target", "file/stream." ]
def dump(self, target: Union[Text, Path, yaml.StringIO], story_steps: List[StoryStep], is_appendable: bool=False, is_test_story: bool=False) -> None: result = self.stories_to_yaml(story_steps, is_test_story) if is_appendable and KEY_STORIES in result: result = result[KEY_STORIES] rasa.shared.utils.i...
['def', 'dump(self,', 'target:', 'Union[Text,', 'Path,', 'yaml.StringIO],', 'story_steps:', 'List[StoryStep],', 'is_appendable:', 'bool=False,', 'is_test_story:', 'bool=False)', '->', 'None:', 'result', '=', 'self.stories_to_yaml(story_steps,', 'is_test_story)', 'if', 'is_appendable', 'and', 'KEY_STORIES', 'in', 'resul...
837,601
kaixin96/PANet
blob.py
ones
ones
Return a blob of all ones of the given shape with the correct float or int data type.
[ "Return", "a", "blob", "of", "all", "ones", "of", "the", "given", "shape", "with", "the", "correct", "float", "or", "int", "data", "type." ]
def ones(shape, int32=False): return np.ones(shape, dtype=np.int32 if int32 else np.float32)
['def', 'ones(shape,', 'int32=False):', 'return', 'np.ones(shape,', 'dtype=np.int32', 'if', 'int32', 'else', 'np.float32)']
778,825
open-mmlab/mmdetection3d
paconv.py
PAConv.init_weights
init_weights
Initialize weights of shared MLP layers and BN layers.
[ "Initialize", "weights", "of", "shared", "MLP", "layers", "and", "BN", "layers." ]
def init_weights(self) -> None: if self.bn is not None: constant_init(self.bn, val=1, bias=0)
['def', 'init_weights(self)', '->', 'None:', 'if', 'self.bn', 'is', 'not', 'None:', 'constant_init(self.bn,', 'val=1,', 'bias=0)']
632,047
PaddlePaddle/PARL
communication.py
dumps_return
dumps_return
Serialize the return data of a function.
[ "Serialize", "the", "return", "data", "of", "a", "function." ]
def dumps_return(data): try: ret = serialize(data) except Exception as e: raise SerializeError(e) return ret
['def', 'dumps_return(data):', 'try:', 'ret', '=', 'serialize(data)', 'except', 'Exception', 'as', 'e:', 'raise', 'SerializeError(e)', 'return', 'ret']
278,090
RoundofThree/AIMA-notes
minimax.py
Backgammon.probability
probability
Return the probability of occurrence of a dice roll.
[ "Return", "the", "probability", "of", "occurrence", "of", "a", "dice", "roll." ]
def probability(self, chance): return 1 / 36 if chance[0] == chance[1] else 1 / 18
['def', 'probability(self,', 'chance):', 'return', '1', '/', '36', 'if', 'chance[0]', '==', 'chance[1]', 'else', '1', '/', '18']
86,302
devashish-patel/webcam-motion-detector
management.py
TermManagerBase.make_term_env
make_term_env
Build the environment variables for the process in the terminal.
[ "Build", "the", "environment", "variables", "for", "the", "process", "in", "the", "terminal." ]
def make_term_env(self, height=25, width=80, winheight=0, winwidth=0, **kwargs): env = os.environ.copy() env['TERM'] = self.term_settings.get('type', DEFAULT_TERM_TYPE) dimensions = '%dx%d' % (width, height) if winwidth and winheight: dimensions += ';%dx%d' % (winwidth, winheight) env[ENV_PR...
['def', 'make_term_env(self,', 'height=25,', 'width=80,', 'winheight=0,', 'winwidth=0,', '**kwargs):', 'env', '=', 'os.environ.copy()', "env['TERM']", '=', "self.term_settings.get('type',", 'DEFAULT_TERM_TYPE)', 'dimensions', '=', "'%dx%d'", '%', '(width,', 'height)', 'if', 'winwidth', 'and', 'winheight:', 'dimensions'...
984,847
43Carrig/recurrent_neural_networks_practice
feature_column.py
real_valued_column
real_valued_column
Creates a `_RealValuedColumn` for dense numeric data.
[ "Creates", "a", "`_RealValuedColumn`", "for", "dense", "numeric", "data." ]
def real_valued_column(column_name, dimension=1, default_value=None, dtype=dtypes.float32, normalizer=None): if dimension is None: raise TypeError('dimension must be an integer. Use the _real_valued_var_len_column for variable length features.dimension: {}, column_name: {}'.format(dimension, column_name)) ...
['def', 'real_valued_column(column_name,', 'dimension=1,', 'default_value=None,', 'dtype=dtypes.float32,', 'normalizer=None):', 'if', 'dimension', 'is', 'None:', 'raise', "TypeError('dimension", 'must', 'be', 'an', 'integer.', 'Use', 'the', '_real_valued_var_len_column', 'for', 'variable', 'length', 'features.dimension...
313,398
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
problem_hparams.py
test_problem_hparams
test_problem_hparams
Problem hparams for testing model bodies.
[ "Problem", "hparams", "for", "testing", "model", "bodies." ]
def test_problem_hparams(input_vocab_size=None, target_vocab_size=None): p = TestProblem(input_vocab_size, target_vocab_size) return p.get_hparams()
['def', 'test_problem_hparams(input_vocab_size=None,', 'target_vocab_size=None):', 'p', '=', 'TestProblem(input_vocab_size,', 'target_vocab_size)', 'return', 'p.get_hparams()']
964,959
microsoft/maro
dqn.py
DQNOps.soft_update_target
soft_update_target
Soft update the target policy.
[ "Soft", "update", "the", "target", "policy." ]
def soft_update_target(self) -> None: self._target_policy.soft_update(self._policy, self._soft_update_coef)
['def', 'soft_update_target(self)', '->', 'None:', 'self._target_policy.soft_update(self._policy,', 'self._soft_update_coef)']
628,548
noambassat/SpeechTrainer
direct_url.py
DirectUrl.redacted_url
redacted_url
url with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is ``git`` in the case of a git URL.
[ "url", "with", "user:password", "part", "removed", "unless", "it", "is", "formed", "with", "environment", "variables", "as", "specified", "in", "PEP", "610,", "or", "it", "is", "``git``", "in", "the", "case", "of", "a", "git", "URL." ]
def redacted_url(self): purl = urllib.parse.urlsplit(self.url) netloc = self._remove_auth_from_netloc(purl.netloc) surl = urllib.parse.urlunsplit((purl.scheme, netloc, purl.path, purl.query, purl.fragment)) return surl
['def', 'redacted_url(self):', 'purl', '=', 'urllib.parse.urlsplit(self.url)', 'netloc', '=', 'self._remove_auth_from_netloc(purl.netloc)', 'surl', '=', 'urllib.parse.urlunsplit((purl.scheme,', 'netloc,', 'purl.path,', 'purl.query,', 'purl.fragment))', 'return', 'surl']
894,998
JoyHuYY1412/Class_Imbalanced_Semi_Supervised_Learning
utils.py
para_list
para_list
Run on multiple GPUs in parallel and return list of results.
[ "Run", "on", "multiple", "GPUs", "in", "parallel", "and", "return", "list", "of", "results." ]
def para_list(fn, *args): gpus = len(get_available_gpus()) if gpus <= 1: return zip(*[fn(*args)]) splitted = [tf.split(x, gpus) for x in args] outputs = [] for (gpu, x) in enumerate(zip(*splitted)): with tf.name_scope('tower%d' % gpu): with tf.device(tf.train.replica_devi...
['def', 'para_list(fn,', '*args):', 'gpus', '=', 'len(get_available_gpus())', 'if', 'gpus', '<=', '1:', 'return', 'zip(*[fn(*args)])', 'splitted', '=', '[tf.split(x,', 'gpus)', 'for', 'x', 'in', 'args]', 'outputs', '=', '[]', 'for', '(gpu,', 'x)', 'in', 'enumerate(zip(*splitted)):', 'with', "tf.name_scope('tower%d'", '...
122,270
PJLab-ADG/LoGoNet
transformer.py
TransformerEncoderLayer.forward
forward
Forward function for `TransformerEncoderLayer`.
[ "Forward", "function", "for", "`TransformerEncoderLayer`." ]
def forward(self, x, pos=None, attn_mask=None, key_padding_mask=None): norm_cnt = 0 inp_residual = x for layer in self.order: if layer == 'selfattn': query = key = value = x x = self.self_attn(query, key, value, inp_residual if self.pre_norm else None, query_pos=pos, key_pos=...
['def', 'forward(self,', 'x,', 'pos=None,', 'attn_mask=None,', 'key_padding_mask=None):', 'norm_cnt', '=', '0', 'inp_residual', '=', 'x', 'for', 'layer', 'in', 'self.order:', 'if', 'layer', '==', "'selfattn':", 'query', '=', 'key', '=', 'value', '=', 'x', 'x', '=', 'self.self_attn(query,', 'key,', 'value,', 'inp_residu...
615,446
alibaba/EasyCV
segmentation_eval.py
intersect_and_union
intersect_and_union
Calculate intersection and Union.
[ "Calculate", "intersection", "and", "Union." ]
def intersect_and_union(pred_label, label, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False): pred_label = torch.from_numpy(pred_label) label = torch.from_numpy(label) if label_map is not None: label_copy = label.clone() for (old_id, new_id) in label_map.items(): ...
['def', 'intersect_and_union(pred_label,', 'label,', 'num_classes,', 'ignore_index,', 'label_map=dict(),', 'reduce_zero_label=False):', 'pred_label', '=', 'torch.from_numpy(pred_label)', 'label', '=', 'torch.from_numpy(label)', 'if', 'label_map', 'is', 'not', 'None:', 'label_copy', '=', 'label.clone()', 'for', '(old_id...
546,321
sek788432/Waymo-2D-Object-Detection
utils.py
get_bert_config_from_params
get_bert_config_from_params
Converts a BertConfig to ParamsDict.
[ "Converts", "a", "BertConfig", "to", "ParamsDict." ]
def get_bert_config_from_params(params: params_dict.ParamsDict) -> configs.BertConfig: return configs.BertConfig.from_dict(params.as_dict())
['def', 'get_bert_config_from_params(params:', 'params_dict.ParamsDict)', '->', 'configs.BertConfig:', 'return', 'configs.BertConfig.from_dict(params.as_dict())']
972,750
RasaHQ/rasa
common.py
write_global_config_value
write_global_config_value
Read global Rasa configuration.
[ "Read", "global", "Rasa", "configuration." ]
def write_global_config_value(name: Text, value: Any) -> bool: config_path = rasa.constants.GLOBAL_USER_CONFIG_PATH try: os.makedirs(os.path.dirname(config_path), exist_ok=True) c = read_global_config(config_path) c[name] = value rasa.shared.utils.io.write_yaml(c, rasa.constants....
['def', 'write_global_config_value(name:', 'Text,', 'value:', 'Any)', '->', 'bool:', 'config_path', '=', 'rasa.constants.GLOBAL_USER_CONFIG_PATH', 'try:', 'os.makedirs(os.path.dirname(config_path),', 'exist_ok=True)', 'c', '=', 'read_global_config(config_path)', 'c[name]', '=', 'value', 'rasa.shared.utils.io.write_yaml...
837,837
enuguru/artificial_intelligence_and_machine_learning
filters.py
TransformFilterMaker.getServiceEndpoints
getServiceEndpoints
Returns an iterator of endpoint objects produced by the filter functions.
[ "Returns", "an", "iterator", "of", "endpoint", "objects", "produced", "by", "the", "filter", "functions." ]
def getServiceEndpoints(self, yadis_url, service_element): endpoints = [] for (type_uris, uri, _) in expandService(service_element): endpoint = BasicServiceEndpoint(yadis_url, type_uris, uri, service_element) e = self.applyFilters(endpoint) if e is not None: endpoints.append(...
['def', 'getServiceEndpoints(self,', 'yadis_url,', 'service_element):', 'endpoints', '=', '[]', 'for', '(type_uris,', 'uri,', '_)', 'in', 'expandService(service_element):', 'endpoint', '=', 'BasicServiceEndpoint(yadis_url,', 'type_uris,', 'uri,', 'service_element)', 'e', '=', 'self.applyFilters(endpoint)', 'if', 'e', '...
159,566
am-shashank/artificial-intelligence
misc_util.py
all_strings
all_strings
Return True if all items in lst are string objects.
[ "Return", "True", "if", "all", "items", "in", "lst", "are", "string", "objects." ]
def all_strings(lst): for item in lst: if not is_string(item): return False return True
['def', 'all_strings(lst):', 'for', 'item', 'in', 'lst:', 'if', 'not', 'is_string(item):', 'return', 'False', 'return', 'True']
62,782
kzxuan/pytorch-dnnnlp
utils.py
maximum_prfacc
maximum_prfacc
Get maximum for multiple evaluations.
[ "Get", "maximum", "for", "multiple", "evaluations." ]
def maximum_prfacc(*evals, eval_metric='accuracy'): assert eval_metric in evals[0].keys(), ValueError("Value error of 'eval_metric'.") if eval_metric == 'accuracy': values = [e[eval_metric] for e in evals] else: values = [e[eval_metric]['f1-score'] for e in evals] index = values.index(ma...
['def', 'maximum_prfacc(*evals,', "eval_metric='accuracy'):", 'assert', 'eval_metric', 'in', 'evals[0].keys(),', 'ValueError("Value', 'error', 'of', '\'eval_metric\'.")', 'if', 'eval_metric', '==', "'accuracy':", 'values', '=', '[e[eval_metric]', 'for', 'e', 'in', 'evals]', 'else:', 'values', '=', "[e[eval_metric]['f1-...
814,500
lfovia/QAGANS
download.py
copy_inception
copy_inception
Copy weights and params from the graph in the given TensorFlow session to the Chainer chain.
[ "Copy", "weights", "and", "params", "from", "the", "graph", "in", "the", "given", "TensorFlow", "session", "to", "the", "Chainer", "chain." ]
def copy_inception(sess, model): print('Copying first layers ...') copy_conv(sess, 'conv', model.conv) copy_bn(sess, 'conv/batchnorm', model.bn_conv) copy_conv(sess, 'conv_1', model.conv_1) copy_bn(sess, 'conv_1/batchnorm', model.bn_conv_1) copy_conv(sess, 'conv_2', model.conv_2) copy_bn(ses...
['def', 'copy_inception(sess,', 'model):', "print('Copying", 'first', 'layers', "...')", 'copy_conv(sess,', "'conv',", 'model.conv)', 'copy_bn(sess,', "'conv/batchnorm',", 'model.bn_conv)', 'copy_conv(sess,', "'conv_1',", 'model.conv_1)', 'copy_bn(sess,', "'conv_1/batchnorm',", 'model.bn_conv_1)', 'copy_conv(sess,', "'...
815,990
OpenMDAO/OpenMDAO-Framework
pdcyl_comp.py
PdcylComp.parse_output
parse_output
Parses the PCYL output file and extracts data.
[ "Parses", "the", "PCYL", "output", "file", "and", "extracts", "data." ]
def parse_output(self): infile = FileParser() infile.set_file(self.stdout) self.wwingt = infile.transfer_keyvar('Total Wing Structural Weight', 1) self.wfuselaget = infile.transfer_keyvar('Fuselage Total Structural Weight', 1)
['def', 'parse_output(self):', 'infile', '=', 'FileParser()', 'infile.set_file(self.stdout)', 'self.wwingt', '=', "infile.transfer_keyvar('Total", 'Wing', 'Structural', "Weight',", '1)', 'self.wfuselaget', '=', "infile.transfer_keyvar('Fuselage", 'Total', 'Structural', "Weight',", '1)']
275,294
octree-nn/ocnn-pytorch
octree_conv.py
OctreeConv.forward
forward
Defines the octree convolution.
[ "Defines", "the", "octree", "convolution." ]
def forward(self, data: torch.Tensor, octree: Octree, depth: int): if self.direct_method: col = octree2col(data, octree, depth, self.kernel, self.stride, self.nempty) out = torch.mm(col.flatten(1), self.weights.flatten(0, 1)) else: out = octree_conv(data, self.weights, octree, depth, sel...
['def', 'forward(self,', 'data:', 'torch.Tensor,', 'octree:', 'Octree,', 'depth:', 'int):', 'if', 'self.direct_method:', 'col', '=', 'octree2col(data,', 'octree,', 'depth,', 'self.kernel,', 'self.stride,', 'self.nempty)', 'out', '=', 'torch.mm(col.flatten(1),', 'self.weights.flatten(0,', '1))', 'else:', 'out', '=', 'oc...
249,912
abesapien/EmotionalAI2017
flaskr.py
get_db
get_db
Opens a new database connection if there is none yet for the current application context.
[ "Opens", "a", "new", "database", "connection", "if", "there", "is", "none", "yet", "for", "the", "current", "application", "context." ]
def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db
['def', 'get_db():', 'if', 'not', 'hasattr(g,', "'sqlite_db'):", 'g.sqlite_db', '=', 'connect_db()', 'return', 'g.sqlite_db']
176,064
johschmidt42/PyTorch-Object-Detection-Faster-RCNN-Tutorial
anchor_viewer.py
AnchorViewer.get_first_anchor
get_first_anchor
Returns the first anchor box for the current image.
[ "Returns", "the", "first", "anchor", "box", "for", "the", "current", "image." ]
def get_first_anchor(self): num_anchor_boxes_per_location = len(self.anchor_size[0]) * len(self.aspect_ratios[0]) return [self.anchor_boxes[idx] for idx in range(num_anchor_boxes_per_location)]
['def', 'get_first_anchor(self):', 'num_anchor_boxes_per_location', '=', 'len(self.anchor_size[0])', '*', 'len(self.aspect_ratios[0])', 'return', '[self.anchor_boxes[idx]', 'for', 'idx', 'in', 'range(num_anchor_boxes_per_location)]']
814,926
xmed-lab/URN
self_attention_block.py
SelfAttentionBlock.init_weights
init_weights
Initialize weight of later layer.
[ "Initialize", "weight", "of", "later", "layer." ]
def init_weights(self): if self.out_project is not None: if not isinstance(self.out_project, ConvModule): constant_init(self.out_project, 0)
['def', 'init_weights(self):', 'if', 'self.out_project', 'is', 'not', 'None:', 'if', 'not', 'isinstance(self.out_project,', 'ConvModule):', 'constant_init(self.out_project,', '0)']
930,424
KKKSQJ/DeepLearning
onnx2trt.py
torch_dtype_from_trt
torch_dtype_from_trt
Convert pytorch dtype to TensorRT dtype.
[ "Convert", "pytorch", "dtype", "to", "TensorRT", "dtype." ]
def torch_dtype_from_trt(dtype: trt.DataType) -> torch.dtype: if dtype == trt.bool: return torch.bool elif dtype == trt.int8: return torch.int8 elif dtype == trt.int32: return torch.int32 elif dtype == trt.float16: return torch.float16 elif dtype == trt.float32: ...
['def', 'torch_dtype_from_trt(dtype:', 'trt.DataType)', '->', 'torch.dtype:', 'if', 'dtype', '==', 'trt.bool:', 'return', 'torch.bool', 'elif', 'dtype', '==', 'trt.int8:', 'return', 'torch.int8', 'elif', 'dtype', '==', 'trt.int32:', 'return', 'torch.int32', 'elif', 'dtype', '==', 'trt.float16:', 'return', 'torch.float1...
180,609
lululxvi/deepxde
utils.py
interactive_install_paddle
interactive_install_paddle
Ask the user for installing paddle.
[ "Ask", "the", "user", "for", "installing", "paddle." ]
def interactive_install_paddle(): try: notice = 'Do you want to install the recommended backend Paddle (y/n): ' msg = input(notice) except EOFError: msg = 'n' cnt = 0 while cnt < 3: if msg == 'y': install_paddle() return if msg == 'n': ...
['def', 'interactive_install_paddle():', 'try:', 'notice', '=', "'Do", 'you', 'want', 'to', 'install', 'the', 'recommended', 'backend', 'Paddle', '(y/n):', "'", 'msg', '=', 'input(notice)', 'except', 'EOFError:', 'msg', '=', "'n'", 'cnt', '=', '0', 'while', 'cnt', '<', '3:', 'if', 'msg', '==', "'y':", 'install_paddle()...
536,217
bachiraoun/fullrmc
Collection.py
BiasedRandomFloatGenerator.originalWeights
originalWeights
Original weights as initialized.
[ "Original", "weights", "as", "initialized." ]
def originalWeights(self): return self.__originalWeights
['def', 'originalWeights(self):', 'return', 'self.__originalWeights']
213,711
kukuruza/shuffler
general_test.py
Test_MatchPolygonPoints.test_haveRepeatedPointsAndNameMatter
test_haveRepeatedPointsAndNameMatter
Only the point with matching name is matched out of two points.
[ "Only", "the", "point", "with", "matching", "name", "is", "matched", "out", "of", "two", "points." ]
def test_haveRepeatedPointsAndNameMatter(self): objectid = 1 polygons1 = [(1, objectid, 10, 30, 'name1'), (2, objectid, 10, 30, 'name2')] polygons2 = [(3, objectid, 10, 30, 'name2'), (4, objectid, 200, 200, 'name3')] pairs = general_utils.matchPolygonPoints(polygons1, polygons2, 1.0, False) self.ass...
['def', 'test_haveRepeatedPointsAndNameMatter(self):', 'objectid', '=', '1', 'polygons1', '=', '[(1,', 'objectid,', '10,', '30,', "'name1'),", '(2,', 'objectid,', '10,', '30,', "'name2')]", 'polygons2', '=', '[(3,', 'objectid,', '10,', '30,', "'name2'),", '(4,', 'objectid,', '200,', '200,', "'name3')]", 'pairs', '=', '...
933,913
ryanfwy/image-similarity
model_util.py
DeepModel.preprocess_image
preprocess_image
Process an image to numpy array.
[ "Process", "an", "image", "to", "numpy", "array." ]
def preprocess_image(path): img = process_image.load_img(path, target_size=(224, 224)) x = process_image.img_to_array(img) x = preprocess_input(x) return x
['def', 'preprocess_image(path):', 'img', '=', 'process_image.load_img(path,', 'target_size=(224,', '224))', 'x', '=', 'process_image.img_to_array(img)', 'x', '=', 'preprocess_input(x)', 'return', 'x']
599,123
enuguru/artificial_intelligence_and_machine_learning
base85.py
from_base85
from_base85
Decodes the given base 85 text into an integer.
[ "Decodes", "the", "given", "base", "85", "text", "into", "an", "integer." ]
def from_base85(text): acc = 0 for c in text: acc = acc * 85 + b85dec[c] return acc
['def', 'from_base85(text):', 'acc', '=', '0', 'for', 'c', 'in', 'text:', 'acc', '=', 'acc', '*', '85', '+', 'b85dec[c]', 'return', 'acc']
133,635
aimclub/FEDOT
multi_modal.py
MultiModalData.from_csv
from_csv
Import multimodal data from ``csv``.
[ "Import", "multimodal", "data", "from", "``csv``." ]
def from_csv(cls, file_path: Optional[PathType], delimiter=',', task: Union[Task, str]='classification', text_columns: Optional[Union[str, List[str]]]=None, columns_to_drop: Optional[List[str]]=None, target_columns: Union[str, List[str]]='', index_col: Optional[Union[str, int]]=None, possible_idx_keywords: Optional[Lis...
['def', 'from_csv(cls,', 'file_path:', 'Optional[PathType],', "delimiter=',',", 'task:', 'Union[Task,', "str]='classification',", 'text_columns:', 'Optional[Union[str,', 'List[str]]]=None,', 'columns_to_drop:', 'Optional[List[str]]=None,', 'target_columns:', 'Union[str,', "List[str]]='',", 'index_col:', 'Optional[Union...
545,677
tensorlayer/TensorLayerX
core_mindspore.py
Module.infer
infer
Set this network in evaluation mode.
[ "Set", "this", "network", "in", "evaluation", "mode." ]
def infer(self): self.eval()
['def', 'infer(self):', 'self.eval()']
923,881
sktime/sktime
test_testscenarios.py
test_testscenario_object_multi_call_defaults
test_testscenario_object_multi_call_defaults
Test basic workflow: default args where methods are called multiple times.
[ "Test", "basic", "workflow:", "default", "args", "where", "methods", "are", "called", "multiple", "times." ]
def test_testscenario_object_multi_call_defaults(): obj = MockTestedClass(a='super') scenario = TestScenario(args={'foo': {'b': 'cali'}, 'bar': {'c': 'fragi', 'd': 'listic'}, 'foo-2nd': {'b': 'expi'}, 'bar-2nd': {'c': 'ali', 'd': 'docious'}}, default_arg_sequence=['foo', 'bar', 'foo-2nd', 'bar-2nd'], default_me...
['def', 'test_testscenario_object_multi_call_defaults():', 'obj', '=', "MockTestedClass(a='super')", 'scenario', '=', "TestScenario(args={'foo':", "{'b':", "'cali'},", "'bar':", "{'c':", "'fragi',", "'d':", "'listic'},", "'foo-2nd':", "{'b':", "'expi'},", "'bar-2nd':", "{'c':", "'ali',", "'d':", "'docious'}},", "defaul...
878,164
jshilong/DDQ
deform_conv.py
DeformConv2d.forward
forward
Deformable Convolutional forward function.
[ "Deformable", "Convolutional", "forward", "function." ]
def forward(self, x: Tensor, offset: Tensor) -> Tensor: input_pad = x.size(2) < self.kernel_size[0] or x.size(3) < self.kernel_size[1] if input_pad: pad_h = max(self.kernel_size[0] - x.size(2), 0) pad_w = max(self.kernel_size[1] - x.size(3), 0) x = F.pad(x, (0, pad_w, 0, pad_h), 'constan...
['def', 'forward(self,', 'x:', 'Tensor,', 'offset:', 'Tensor)', '->', 'Tensor:', 'input_pad', '=', 'x.size(2)', '<', 'self.kernel_size[0]', 'or', 'x.size(3)', '<', 'self.kernel_size[1]', 'if', 'input_pad:', 'pad_h', '=', 'max(self.kernel_size[0]', '-', 'x.size(2),', '0)', 'pad_w', '=', 'max(self.kernel_size[1]', '-', '...
499,085
TrellixVulnTeam/Unsupervised_Learning_HFI7
screen.py
screen.lf
lf
This moves the cursor down with scrolling.
[ "This", "moves", "the", "cursor", "down", "with", "scrolling." ]
def lf(self): old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up() self.erase_line()
['def', 'lf(self):', 'old_r', '=', 'self.cur_r', 'self.cursor_down()', 'if', 'old_r', '==', 'self.cur_r:', 'self.scroll_up()', 'self.erase_line()']
454,107
myothida/Supervised-Machine-Learning
bezierTools.py
calcCubicArcLengthC
calcCubicArcLengthC
Calculates the arc length for a cubic Bezier segment.
[ "Calculates", "the", "arc", "length", "for", "a", "cubic", "Bezier", "segment." ]
def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005): mult = 1.0 + 1.5 * tolerance return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4)
['def', 'calcCubicArcLengthC(pt1,', 'pt2,', 'pt3,', 'pt4,', 'tolerance=0.005):', 'mult', '=', '1.0', '+', '1.5', '*', 'tolerance', 'return', '_calcCubicArcLengthCRecurse(mult,', 'pt1,', 'pt2,', 'pt3,', 'pt4)']
360,919
Oneflow-Inc/vision
datasets_utils.py
create_video_folder
create_video_folder
Create a folder of random videos.
[ "Create", "a", "folder", "of", "random", "videos." ]
def create_video_folder(root: Union[str, pathlib.Path], name: Union[str, pathlib.Path], file_name_fn: Callable[[int], str], num_examples: int, size: Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]]=None, fps=25, **kwargs) -> List[pathlib.Path]: if size is None: def size(idx):...
['def', 'create_video_folder(root:', 'Union[str,', 'pathlib.Path],', 'name:', 'Union[str,', 'pathlib.Path],', 'file_name_fn:', 'Callable[[int],', 'str],', 'num_examples:', 'int,', 'size:', 'Optional[Union[Sequence[int],', 'int,', 'Callable[[int],', 'Union[Sequence[int],', 'int]]]]=None,', 'fps=25,', '**kwargs)', '->', ...
957,914
audioku/meta-transfer-learning
meta.py
MetaTrainer.start_session
start_session
The function to start tensorflow session.
[ "The", "function", "to", "start", "tensorflow", "session." ]
def start_session(self): if FLAGS.full_gpu_memory_mode: gpu_config = tf.ConfigProto() gpu_config.gpu_options.per_process_gpu_memory_fraction = FLAGS.gpu_rate self.sess = tf.InteractiveSession(config=gpu_config) else: self.sess = tf.InteractiveSession()
['def', 'start_session(self):', 'if', 'FLAGS.full_gpu_memory_mode:', 'gpu_config', '=', 'tf.ConfigProto()', 'gpu_config.gpu_options.per_process_gpu_memory_fraction', '=', 'FLAGS.gpu_rate', 'self.sess', '=', 'tf.InteractiveSession(config=gpu_config)', 'else:', 'self.sess', '=', 'tf.InteractiveSession()']
633,208
yogeshbalaji/InvGAN
nn.py
load_network_from_checkpoint
load_network_from_checkpoint
Function to read the weights from checkpoint based on json description.
[ "Function", "to", "read", "the", "weights", "from", "checkpoint", "based", "on", "json", "description." ]
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): reader = tf.train.load_checkpoint(checkpoint) variable_map = reader.get_variable_to_shape_map() checkpoint_variable_names = variable_map.keys() with tf.gfile.Open(model_json) as f: list_model_var = json.load(f) net_l...
['def', 'load_network_from_checkpoint(checkpoint,', 'model_json,', 'input_shape=None):', 'reader', '=', 'tf.train.load_checkpoint(checkpoint)', 'variable_map', '=', 'reader.get_variable_to_shape_map()', 'checkpoint_variable_names', '=', 'variable_map.keys()', 'with', 'tf.gfile.Open(model_json)', 'as', 'f:', 'list_model...
576,687
ludwig-ai/ludwig
ray.py
RayDatasetManager.create
create
Create a new Ray dataset with config.
[ "Create", "a", "new", "Ray", "dataset", "with", "config." ]
def create(self, dataset: Union[str, DataFrame], config: ModelConfigDict, training_set_metadata: TrainingSetMetadataDict) -> 'RayDataset': window_size_bytes = self.backend._data_loader_kwargs.get('window_size_bytes', None) return RayDataset(dataset, get_proc_features(config), training_set_metadata, self.backend...
['def', 'create(self,', 'dataset:', 'Union[str,', 'DataFrame],', 'config:', 'ModelConfigDict,', 'training_set_metadata:', 'TrainingSetMetadataDict)', '->', "'RayDataset':", 'window_size_bytes', '=', "self.backend._data_loader_kwargs.get('window_size_bytes',", 'None)', 'return', 'RayDataset(dataset,', 'get_proc_features...
616,654
bnpy/bnpy
TestHDPHMM_ParallelBenchmark.py
Test.setUp
setUp
Launch pool of worker processes, with queues to communicate with.
[ "Launch", "pool", "of", "worker", "processes,", "with", "queues", "to", "communicate", "with." ]
def setUp(self, **kwargs): manager = multiprocessing.Manager() self.JobQ = manager.Queue() self.ResultQ = manager.Queue() (a_L, a_S) = self.hmodel.allocModel.getLocalAndSummaryFunctionHandles() (o_L, o_S) = self.hmodel.obsModel.getLocalAndSummaryFunctionHandles() dataSharedMem = self.Data.getRaw...
['def', 'setUp(self,', '**kwargs):', 'manager', '=', 'multiprocessing.Manager()', 'self.JobQ', '=', 'manager.Queue()', 'self.ResultQ', '=', 'manager.Queue()', '(a_L,', 'a_S)', '=', 'self.hmodel.allocModel.getLocalAndSummaryFunctionHandles()', '(o_L,', 'o_S)', '=', 'self.hmodel.obsModel.getLocalAndSummaryFunctionHandles...
465,510
deepmind/acme
savers.py
save_to_path
save_to_path
Save the state in ckpt_dir.
[ "Save", "the", "state", "in", "ckpt_dir." ]
def save_to_path(ckpt_dir: str, state: CheckpointState): if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) is_numpy = lambda x: isinstance(x, (np.ndarray, jax.Array)) flat_state = tree.flatten(state) nest_exemplar = tree.map_structure(is_numpy, state) array_path = os.path.join(ckpt_dir,...
['def', 'save_to_path(ckpt_dir:', 'str,', 'state:', 'CheckpointState):', 'if', 'not', 'os.path.exists(ckpt_dir):', 'os.makedirs(ckpt_dir)', 'is_numpy', '=', 'lambda', 'x:', 'isinstance(x,', '(np.ndarray,', 'jax.Array))', 'flat_state', '=', 'tree.flatten(state)', 'nest_exemplar', '=', 'tree.map_structure(is_numpy,', 'st...
8,322
myothida/Supervised-Machine-Learning
axislines.py
Axes.grid
grid
Toggle the gridlines, and optionally set the properties of the lines.
[ "Toggle", "the", "gridlines,", "and", "optionally", "set", "the", "properties", "of", "the", "lines." ]
def grid(self, visible=None, which='major', axis='both', **kwargs): super().grid(visible, which=which, axis=axis, **kwargs) if not self._axisline_on: return if visible is None: visible = self.axes.xaxis._minor_tick_kw['gridOn'] or self.axes.xaxis._major_tick_kw['gridOn'] or self.axes.yaxis._...
['def', 'grid(self,', 'visible=None,', "which='major',", "axis='both',", '**kwargs):', 'super().grid(visible,', 'which=which,', 'axis=axis,', '**kwargs)', 'if', 'not', 'self._axisline_on:', 'return', 'if', 'visible', 'is', 'None:', 'visible', '=', "self.axes.xaxis._minor_tick_kw['gridOn']", 'or', "self.axes.xaxis._majo...
363,045
lfovia/QAGANS
download.py
set_tf_params
set_tf_params
Update the parameters of the given chainer model with the downloaded TensorFlow model.
[ "Update", "the", "parameters", "of", "the", "given", "chainer", "model", "with", "the", "downloaded", "TensorFlow", "model." ]
def set_tf_params(model, write_graph=False): with tf.gfile.FastGFile(os.path.join(MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') if write_graph: summary_write...
['def', 'set_tf_params(model,', 'write_graph=False):', 'with', 'tf.gfile.FastGFile(os.path.join(MODEL_DIR,', "'classify_image_graph_def.pb'),", "'rb')", 'as', 'f:', 'graph_def', '=', 'tf.GraphDef()', 'graph_def.ParseFromString(f.read())', '_', '=', 'tf.import_graph_def(graph_def,', "name='')", 'if', 'write_graph:', 'su...
815,992
greydanus/pythonic_ocr
pildriver.py
PILDriver.do_color
do_color
usage: color <image:pic1> Enhance color in the top image.
[ "usage:", "color", "<image:pic1>", "Enhance", "color", "in", "the", "top", "image." ]
def do_color(self): from PIL import ImageEnhance factor = float(self.do_pop()) image = self.do_pop() enhancer = ImageEnhance.Color(image) self.push(enhancer.enhance(factor))
['def', 'do_color(self):', 'from', 'PIL', 'import', 'ImageEnhance', 'factor', '=', 'float(self.do_pop())', 'image', '=', 'self.do_pop()', 'enhancer', '=', 'ImageEnhance.Color(image)', 'self.push(enhancer.enhance(factor))']
298,515
KalleHallden/InstaAutomator
easy_install.py
CommandSpec.from_param
from_param
Construct a CommandSpec from a parameter to build_scripts, which may be None.
[ "Construct", "a", "CommandSpec", "from", "a", "parameter", "to", "build_scripts,", "which", "may", "be", "None." ]
def from_param(cls, param): if isinstance(param, cls): return param if isinstance(param, list): return cls(param) if param is None: return cls.from_environment() return cls.from_string(param)
['def', 'from_param(cls,', 'param):', 'if', 'isinstance(param,', 'cls):', 'return', 'param', 'if', 'isinstance(param,', 'list):', 'return', 'cls(param)', 'if', 'param', 'is', 'None:', 'return', 'cls.from_environment()', 'return', 'cls.from_string(param)']
244,820
astooke/accel_rl
cma_es_lib.py
CMAAdaptSigmaBase.initialize_base
initialize_base
set parameters and state variable based on dimension, mueff and possibly further options.
[ "set", "parameters", "and", "state", "variable", "based", "on", "dimension,", "mueff", "and", "possibly", "further", "options." ]
def initialize_base(self, es): b = 1.0 self.cs = 1.0 * (es.sp.mueff + 2) ** b / (es.N ** b + (es.sp.mueff + 3) ** b) self.ps = np.zeros(es.N) self.is_initialized_base = True return self
['def', 'initialize_base(self,', 'es):', 'b', '=', '1.0', 'self.cs', '=', '1.0', '*', '(es.sp.mueff', '+', '2)', '**', 'b', '/', '(es.N', '**', 'b', '+', '(es.sp.mueff', '+', '3)', '**', 'b)', 'self.ps', '=', 'np.zeros(es.N)', 'self.is_initialized_base', '=', 'True', 'return', 'self']
406,768
cheind/gcsl
coordinate_system.py
CoordinateSystem.transform_object_state
transform_object_state
Transforms the given object state to the coordinate system.
[ "Transforms", "the", "given", "object", "state", "to", "the", "coordinate", "system." ]
def transform_object_state(self, object_id: ObjectId, state: TrackerState): pos = state.pos rot = state.rot vel = state.vel angular_vel = state.angular_vel if pos is not None: if self._global_translation is not None: pos = pos + self._global_translation if object_id in se...
['def', 'transform_object_state(self,', 'object_id:', 'ObjectId,', 'state:', 'TrackerState):', 'pos', '=', 'state.pos', 'rot', '=', 'state.rot', 'vel', '=', 'state.vel', 'angular_vel', '=', 'state.angular_vel', 'if', 'pos', 'is', 'not', 'None:', 'if', 'self._global_translation', 'is', 'not', 'None:', 'pos', '=', 'pos',...
201,828
sunyao123/CRF-semantic-segmentation
crf_model.py
DenseCRF.check_potential
check_potential
Checks `potential` is of correct type and has an apply function.
[ "Checks", "`potential`", "is", "of", "correct", "type", "and", "has", "an", "apply", "function." ]
def check_potential(potential, potential_type=None): potential_type = potentials.Potential if potential_type is None else potential_type potential_name = potential_type.__name__ if not isinstance(potential, potential_type): raise ValueError('{0} is not a {1}'.format(potential.__name__, potential_nam...
['def', 'check_potential(potential,', 'potential_type=None):', 'potential_type', '=', 'potentials.Potential', 'if', 'potential_type', 'is', 'None', 'else', 'potential_type', 'potential_name', '=', 'potential_type.__name__', 'if', 'not', 'isinstance(potential,', 'potential_type):', 'raise', "ValueError('{0}", 'is', 'not...
490,697
openvinotoolkit/training_extensions
convert_public_data_to_cvat.py
read_ava_csv
read_ava_csv
Read ava format annotation csv file.
[ "Read", "ava", "format", "annotation", "csv", "file." ]
def read_ava_csv(csv_path): annot_info = {} with open(csv_path, 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for line in csv_reader: (video_id, frame_idx, bboxes, class_idx) = (line[0], line[1], line[2:6], line[6]) frame_idx = int(f...
['def', 'read_ava_csv(csv_path):', 'annot_info', '=', '{}', 'with', 'open(csv_path,', "'r',", "encoding='utf-8')", 'as', 'csv_file:', 'csv_reader', '=', 'csv.reader(csv_file,', "delimiter=',')", 'for', 'line', 'in', 'csv_reader:', '(video_id,', 'frame_idx,', 'bboxes,', 'class_idx)', '=', '(line[0],', 'line[1],', 'line[...
903,898
anuragranj/coma
utils.py
TextDataset.keep_words
keep_words
Keep the documents given by the index, discard the others.
[ "Keep", "the", "documents", "given", "by", "the", "index,", "discard", "the", "others." ]
def keep_words(self, idx): self.data = self.data[:, idx] self.vocab = [self.vocab[i] for i in idx] try: self.embeddings = self.embeddings[idx, :] except AttributeError: pass
['def', 'keep_words(self,', 'idx):', 'self.data', '=', 'self.data[:,', 'idx]', 'self.vocab', '=', '[self.vocab[i]', 'for', 'i', 'in', 'idx]', 'try:', 'self.embeddings', '=', 'self.embeddings[idx,', ':]', 'except', 'AttributeError:', 'pass']
467,132
sunishsheth2009/ChatterBot
datastructures.py
ETags.is_weak
is_weak
Check if an etag is weak.
[ "Check", "if", "an", "etag", "is", "weak." ]
def is_weak(self, etag): return etag in self._weak
['def', 'is_weak(self,', 'etag):', 'return', 'etag', 'in', 'self._weak']
483,067
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkplot.py
Diff
Diff
Compute the differences between adjacent elements in a sequence.
[ "Compute", "the", "differences", "between", "adjacent", "elements", "in", "a", "sequence." ]
def Diff(t): diffs = [t[i + 1] - t[i] for i in range(len(t) - 1)] return diffs
['def', 'Diff(t):', 'diffs', '=', '[t[i', '+', '1]', '-', 't[i]', 'for', 'i', 'in', 'range(len(t)', '-', '1)]', 'return', 'diffs']
12,766
Eric3911/OpenAGI
megatron_finetune_model.py
MegatronT5FinetuneModel.build_data_loader
build_data_loader
Buld dataloader given an input dataset.
[ "Buld", "dataloader", "given", "an", "input", "dataset." ]
def build_data_loader(self, dataset, global_batch_size, shuffle, num_workers, pin_memory, drop_last): if dataset is None: return None rank = parallel_state.get_data_parallel_rank() world_size = parallel_state.get_data_parallel_world_size() sampler = torch.utils.data.distributed.DistributedSample...
['def', 'build_data_loader(self,', 'dataset,', 'global_batch_size,', 'shuffle,', 'num_workers,', 'pin_memory,', 'drop_last):', 'if', 'dataset', 'is', 'None:', 'return', 'None', 'rank', '=', 'parallel_state.get_data_parallel_rank()', 'world_size', '=', 'parallel_state.get_data_parallel_world_size()', 'sampler', '=', 'to...
273,559
intel/neural-compressor
graph_util.py
GraphRewriterHelper.set_attr_dtype
set_attr_dtype
Set the attribute data type.
[ "Set", "the", "attribute", "data", "type." ]
def set_attr_dtype(node, key, value): node.attr[key].CopyFrom(attr_value_pb2.AttrValue(type=value.as_datatype_enum))
['def', 'set_attr_dtype(node,', 'key,', 'value):', 'node.attr[key].CopyFrom(attr_value_pb2.AttrValue(type=value.as_datatype_enum))']
737,602
sarnsdev/social-alignment-data-mining
test_weight_boosting.py
test_sample_weight_adaboost_regressor
test_sample_weight_adaboost_regressor
AdaBoostRegressor should work without sample_weights in the base estimator The random weighted sampling is done internally in the _boost method in AdaBoostRegressor.
[ "AdaBoostRegressor", "should", "work", "without", "sample_weights", "in", "the", "base", "estimator", "The", "random", "weighted", "sampling", "is", "done", "internally", "in", "the", "_boost", "method", "in", "AdaBoostRegressor." ]
def test_sample_weight_adaboost_regressor(): class DummyEstimator(BaseEstimator): def fit(self, X, y): pass def predict(self, X): return np.zeros(X.shape[0]) boost = AdaBoostRegressor(DummyEstimator(), n_estimators=3) boost.fit(X, y_regr) assert_equal(len(boost...
['def', 'test_sample_weight_adaboost_regressor():', 'class', 'DummyEstimator(BaseEstimator):', 'def', 'fit(self,', 'X,', 'y):', 'pass', 'def', 'predict(self,', 'X):', 'return', 'np.zeros(X.shape[0])', 'boost', '=', 'AdaBoostRegressor(DummyEstimator(),', 'n_estimators=3)', 'boost.fit(X,', 'y_regr)', 'assert_equal(len(bo...
391,952
arshpreetsingh/quantopian-machinelearning
finder.py
NameFinder.filter_name
filter_name
Searches names that are defined in a scope (the different ``filters``), until a name fits.
[ "Searches", "names", "that", "are", "defined", "in", "a", "scope", "(the", "different", "``filters``),", "until", "a", "name", "fits." ]
def filter_name(self, filters): names = [] if self._context.predefined_names and isinstance(self._name, tree.Name): node = self._name while node is not None and (not is_scope(node)): node = node.parent if node.type in ('if_stmt', 'for_stmt', 'comp_for', 'sync_comp_for'): ...
['def', 'filter_name(self,', 'filters):', 'names', '=', '[]', 'if', 'self._context.predefined_names', 'and', 'isinstance(self._name,', 'tree.Name):', 'node', '=', 'self._name', 'while', 'node', 'is', 'not', 'None', 'and', '(not', 'is_scope(node)):', 'node', '=', 'node.parent', 'if', 'node.type', 'in', "('if_stmt',", "'...
887,364
mnot/thor
tcp.py
TcpConnection.close
close
Flush buffered data (if any) and close the connection.
[ "Flush", "buffered", "data", "(if", "any)", "and", "close", "the", "connection." ]
def close(self) -> None: self.pause(True) if self._write_buffer: self._closing = True else: self._close()
['def', 'close(self)', '->', 'None:', 'self.pause(True)', 'if', 'self._write_buffer:', 'self._closing', '=', 'True', 'else:', 'self._close()']
355,119
zoltanbonus/ai50
nim.py
train
train
Train an AI by playing `n` games against itself.
[ "Train", "an", "AI", "by", "playing", "`n`", "games", "against", "itself." ]
def train(n): player = NimAI() for i in range(n): print(f'Playing training game {i + 1}') game = Nim() last = {0: {'state': None, 'action': None}, 1: {'state': None, 'action': None}} while True: state = game.piles.copy() action = player.choose_action(game....
['def', 'train(n):', 'player', '=', 'NimAI()', 'for', 'i', 'in', 'range(n):', "print(f'Playing", 'training', 'game', '{i', '+', "1}')", 'game', '=', 'Nim()', 'last', '=', '{0:', "{'state':", 'None,', "'action':", 'None},', '1:', "{'state':", 'None,', "'action':", 'None}}', 'while', 'True:', 'state', '=', 'game.piles.co...
85,407
AgnostiqHQ/covalent
serialization_test.py
test_lattice_object_serialization
test_lattice_object_serialization
Test that a Lattice object, based on a sub-lattice, is successsfully serialized.
[ "Test", "that", "a", "Lattice", "object,", "based", "on", "a", "sub-lattice,", "is", "successsfully", "serialized." ]
def test_lattice_object_serialization(): lattice_obj = Lattice(sub_lattice_function) function_string = get_serialized_function_str(lattice_obj) expected_string = '\n'.join(['@etron', '@cova.lattice', 'def sub_lattice_function(y):', ' return y']) expected_string += '\n\n\n' assert function_string ...
['def', 'test_lattice_object_serialization():', 'lattice_obj', '=', 'Lattice(sub_lattice_function)', 'function_string', '=', 'get_serialized_function_str(lattice_obj)', 'expected_string', '=', "'\\n'.join(['@etron',", "'@cova.lattice',", "'def", "sub_lattice_function(y):',", "'", 'return', "y'])", 'expected_string', '+...
490,054
aws/sagemaker-python-sdk
renamed_params.py
S3SessionRenamer.calls_to_modify
calls_to_modify
A dictionary mapping S3 utility functions to their respective namespaces.
[ "A", "dictionary", "mapping", "S3", "utility", "functions", "to", "their", "respective", "namespaces." ]
def calls_to_modify(self): return {'download': ('sagemaker.s3.S3Downloader', 's3.S3Downloader', 'S3Downloader'), 'list': ('sagemaker.s3.S3Downloader', 's3.S3Downloader', 'S3Downloader'), 'read_file': ('sagemaker.s3.S3Downloader', 's3.S3Downloader', 'S3Downloader'), 'upload': ('sagemaker.s3.S3Uploader', 's3.S3Upload...
['def', 'calls_to_modify(self):', 'return', "{'download':", "('sagemaker.s3.S3Downloader',", "'s3.S3Downloader',", "'S3Downloader'),", "'list':", "('sagemaker.s3.S3Downloader',", "'s3.S3Downloader',", "'S3Downloader'),", "'read_file':", "('sagemaker.s3.S3Downloader',", "'s3.S3Downloader',", "'S3Downloader'),", "'upload...
829,862
google-research/fixmatch
supervised.py
SupervisedExperiment.get_current_train_step
get_current_train_step
Returns current training step.
[ "Returns", "current", "training", "step." ]
def get_current_train_step(self): return self.optimizer.iterations.numpy()
['def', 'get_current_train_step(self):', 'return', 'self.optimizer.iterations.numpy()']
210,984
tommytracey/DeepRL-P3-Collaboration-Competition
environment.py
UnityEnvironment.close
close
Sends a shutdown signal to the unity environment, and closes the socket connection.
[ "Sends", "a", "shutdown", "signal", "to", "the", "unity", "environment,", "and", "closes", "the", "socket", "connection." ]
def close(self): if self._loaded: self._close() else: raise UnityEnvironmentException('No Unity environment is loaded.')
['def', 'close(self):', 'if', 'self._loaded:', 'self._close()', 'else:', 'raise', "UnityEnvironmentException('No", 'Unity', 'environment', 'is', "loaded.')"]
539,561