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 |
|---|---|---|---|---|---|---|---|---|
secretflow/secretflow | partition.py | PdPartition.value_counts | value_counts | Return a Series containing counts of unique values. | [
"Return",
"a",
"Series",
"containing",
"counts",
"of",
"unique",
"values."
] | def value_counts(self, *args, **kwargs) -> 'PartitionBase':
return self.__partition_wrapper(pd.DataFrame.value_counts, *args, **kwargs) | ['def', 'value_counts(self,', '*args,', '**kwargs)', '->', "'PartitionBase':", 'return', 'self.__partition_wrapper(pd.DataFrame.value_counts,', '*args,', '**kwargs)'] | 856,343 |
devashish-patel/webcam-motion-detector | call_tip_widget.py | CallTipWidget.eventFilter | eventFilter | Reimplemented to hide on certain key presses and on text edit focus changes. | [
"Reimplemented",
"to",
"hide",
"on",
"certain",
"key",
"presses",
"and",
"on",
"text",
"edit",
"focus",
"changes."
] | def eventFilter(self, obj, event):
if obj == self._text_edit:
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
key = event.key()
if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.hide()
elif key == QtCore.Qt.Key_Escape:
... | ['def', 'eventFilter(self,', 'obj,', 'event):', 'if', 'obj', '==', 'self._text_edit:', 'etype', '=', 'event.type()', 'if', 'etype', '==', 'QtCore.QEvent.KeyPress:', 'key', '=', 'event.key()', 'if', 'key', 'in', '(QtCore.Qt.Key_Enter,', 'QtCore.Qt.Key_Return):', 'self.hide()', 'elif', 'key', '==', 'QtCore.Qt.Key_Escape:... | 984,370 |
KKKSQJ/DeepLearning | onnx2trt.py | torch_device_from_trt | torch_device_from_trt | Convert pytorch device to TensorRT device. | [
"Convert",
"pytorch",
"device",
"to",
"TensorRT",
"device."
] | def torch_device_from_trt(device: trt.TensorLocation):
if device == trt.TensorLocation.DEVICE:
return torch.device('cuda')
elif device == trt.TensorLocation.HOST:
return torch.device('cpu')
else:
return TypeError(f'{device} is not supported by torch') | ['def', 'torch_device_from_trt(device:', 'trt.TensorLocation):', 'if', 'device', '==', 'trt.TensorLocation.DEVICE:', 'return', "torch.device('cuda')", 'elif', 'device', '==', 'trt.TensorLocation.HOST:', 'return', "torch.device('cpu')", 'else:', 'return', "TypeError(f'{device}", 'is', 'not', 'supported', 'by', "torch')"... | 180,604 |
aeon-toolkit/aeon | test_pipeline.py | test_nesting_pipelines | test_nesting_pipelines | Test that nesting of pipelines works. | [
"Test",
"that",
"nesting",
"of",
"pipelines",
"works."
] | def test_nesting_pipelines():
from aeon.forecasting.ets import AutoETS
from aeon.transformations.compose import OptionalPassthrough
from aeon.transformations.series.boxcox import LogTransformer
from aeon.transformations.series.detrend import Detrender
from aeon.utils._testing.scenarios_forecasting i... | ['def', 'test_nesting_pipelines():', 'from', 'aeon.forecasting.ets', 'import', 'AutoETS', 'from', 'aeon.transformations.compose', 'import', 'OptionalPassthrough', 'from', 'aeon.transformations.series.boxcox', 'import', 'LogTransformer', 'from', 'aeon.transformations.series.detrend', 'import', 'Detrender', 'from', 'aeon... | 399,640 |
Ruturaj123/Flowchart-Detection | sparse_ops.py | serialize_sparse | serialize_sparse | Serialize a `SparseTensor` into a string 3-vector (1-D `Tensor`) object. | [
"Serialize",
"a",
"`SparseTensor`",
"into",
"a",
"string",
"3-vector",
"(1-D",
"`Tensor`)",
"object."
] | def serialize_sparse(sp_input, name=None):
sp_input = _convert_to_sparse_tensor(sp_input)
return gen_sparse_ops._serialize_sparse(sp_input.indices, sp_input.values, sp_input.dense_shape, name=name) | ['def', 'serialize_sparse(sp_input,', 'name=None):', 'sp_input', '=', '_convert_to_sparse_tensor(sp_input)', 'return', 'gen_sparse_ops._serialize_sparse(sp_input.indices,', 'sp_input.values,', 'sp_input.dense_shape,', 'name=name)'] | 606,123 |
scikit-learn/scikit-learn | test_common_curve_display.py | test_display_curve_error_classifier | test_display_curve_error_classifier | Check that a proper error is raised when only binary classification is supported. | [
"Check",
"that",
"a",
"proper",
"error",
"is",
"raised",
"when",
"only",
"binary",
"classification",
"is",
"supported."
] | def test_display_curve_error_classifier(pyplot, data, data_binary, Display):
(X, y) = data
(X_binary, y_binary) = data_binary
clf = DecisionTreeClassifier().fit(X, y)
msg = "Expected 'estimator' to be a binary classifier. Got 3 classes instead."
with pytest.raises(ValueError, match=msg):
Dis... | ['def', 'test_display_curve_error_classifier(pyplot,', 'data,', 'data_binary,', 'Display):', '(X,', 'y)', '=', 'data', '(X_binary,', 'y_binary)', '=', 'data_binary', 'clf', '=', 'DecisionTreeClassifier().fit(X,', 'y)', 'msg', '=', '"Expected', "'estimator'", 'to', 'be', 'a', 'binary', 'classifier.', 'Got', '3', 'classe... | 853,719 |
xiongfengyan/gcnn | graph.py | distance_lshforest | distance_lshforest | Return an approximation of the k-nearest cosine distances. | [
"Return",
"an",
"approximation",
"of",
"the",
"k-nearest",
"cosine",
"distances."
] | def distance_lshforest(z, k=4, metric='cosine'):
assert metric is 'cosine'
lshf = sklearn.neighbors.LSHForest()
lshf.fit(z)
(dist, idx) = lshf.kneighbors(z, n_neighbors=k + 1)
assert dist.min() < 1e-10
dist[dist < 0] = 0
return (dist, idx) | ['def', 'distance_lshforest(z,', 'k=4,', "metric='cosine'):", 'assert', 'metric', 'is', "'cosine'", 'lshf', '=', 'sklearn.neighbors.LSHForest()', 'lshf.fit(z)', '(dist,', 'idx)', '=', 'lshf.kneighbors(z,', 'n_neighbors=k', '+', '1)', 'assert', 'dist.min()', '<', '1e-10', 'dist[dist', '<', '0]', '=', '0', 'return', '(di... | 201,346 |
Katja-M/Python_NaturalLanguageProcessing | framenet.py | FramenetCorpusReader.docs | docs | Return a list of the annotated full-text documents in FrameNet, optionally filtered by a regex to be matched against the document name. | [
"Return",
"a",
"list",
"of",
"the",
"annotated",
"full-text",
"documents",
"in",
"FrameNet,",
"optionally",
"filtered",
"by",
"a",
"regex",
"to",
"be",
"matched",
"against",
"the",
"document",
"name."
] | def docs(self, name=None):
return PrettyLazyMap(lambda x: self.doc(x.ID), self.docs_metadata(name)) | ['def', 'docs(self,', 'name=None):', 'return', 'PrettyLazyMap(lambda', 'x:', 'self.doc(x.ID),', 'self.docs_metadata(name))'] | 866,200 |
kubeflow/pipelines | auth.py | id_token_from_refresh_token | id_token_from_refresh_token | Returns ID token from refresh token. | [
"Returns",
"ID",
"token",
"from",
"refresh",
"token."
] | def id_token_from_refresh_token(client_id: str, client_secret: str, refresh_token: str, audience: str) -> str:
payload = {'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token, 'grant_type': 'refresh_token', 'audience': audience}
res = requests.post(OAUTH_TOKEN_URI, data=payload... | ['def', 'id_token_from_refresh_token(client_id:', 'str,', 'client_secret:', 'str,', 'refresh_token:', 'str,', 'audience:', 'str)', '->', 'str:', 'payload', '=', "{'client_id':", 'client_id,', "'client_secret':", 'client_secret,', "'refresh_token':", 'refresh_token,', "'grant_type':", "'refresh_token',", "'audience':", ... | 779,887 |
zhyhan/TransPar | util.py | generate_target | generate_target | Generate heatamap for joints. | [
"Generate",
"heatamap",
"for",
"joints."
] | def generate_target(joints, joints_vis, heatmap_size, sigma, image_size):
num_joints = joints.shape[0]
target_weight = np.ones((num_joints, 1), dtype=np.float32)
target_weight[:, 0] = joints_vis[:, 0]
target = np.zeros((num_joints, heatmap_size[1], heatmap_size[0]), dtype=np.float32)
tmp_size = sigm... | ['def', 'generate_target(joints,', 'joints_vis,', 'heatmap_size,', 'sigma,', 'image_size):', 'num_joints', '=', 'joints.shape[0]', 'target_weight', '=', 'np.ones((num_joints,', '1),', 'dtype=np.float32)', 'target_weight[:,', '0]', '=', 'joints_vis[:,', '0]', 'target', '=', 'np.zeros((num_joints,', 'heatmap_size[1],', '... | 356,056 |
pnb/dlwed17 | vae_lstm.py | kl_batch_warmup | kl_batch_warmup | Callback to increase the weight of the KL divergence term in the loss function gradually over the course of many batches. | [
"Callback",
"to",
"increase",
"the",
"weight",
"of",
"the",
"KL",
"divergence",
"term",
"in",
"the",
"loss",
"function",
"gradually",
"over",
"the",
"course",
"of",
"many",
"batches."
] | def kl_batch_warmup(batch, logs):
if batch <= KL_WARMUP_BATCHES:
cur_val = K.get_value(kl_warmup_coeff)
if cur_val < 1.0:
K.set_value(kl_warmup_coeff, cur_val + 1.0 / KL_WARMUP_BATCHES) | ['def', 'kl_batch_warmup(batch,', 'logs):', 'if', 'batch', '<=', 'KL_WARMUP_BATCHES:', 'cur_val', '=', 'K.get_value(kl_warmup_coeff)', 'if', 'cur_val', '<', '1.0:', 'K.set_value(kl_warmup_coeff,', 'cur_val', '+', '1.0', '/', 'KL_WARMUP_BATCHES)'] | 521,900 |
googleapis/python-aiplatform | client.py | PipelineServiceClient.parse_training_pipeline_path | parse_training_pipeline_path | Parses a training_pipeline path into its component segments. | [
"Parses",
"a",
"training_pipeline",
"path",
"into",
"its",
"component",
"segments."
] | def parse_training_pipeline_path(path: str) -> Dict[str, str]:
m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/trainingPipelines/(?P<training_pipeline>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_training_pipeline_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/trainingPipelines/(?P<training_pipeline>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 811,566 |
open-mmlab/mmdetection3d | loading.py | LoadPointsFromFile.transform | transform | Method to load points data from file. | [
"Method",
"to",
"load",
"points",
"data",
"from",
"file."
] | def transform(self, results: dict) -> dict:
pts_file_path = results['lidar_points']['lidar_path']
points = self._load_points(pts_file_path)
points = points.reshape(-1, self.load_dim)
points = points[:, self.use_dim]
if self.norm_intensity:
assert len(self.use_dim) >= 4, f'When using intensit... | ['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'pts_file_path', '=', "results['lidar_points']['lidar_path']", 'points', '=', 'self._load_points(pts_file_path)', 'points', '=', 'points.reshape(-1,', 'self.load_dim)', 'points', '=', 'points[:,', 'self.use_dim]', 'if', 'self.norm_intensity:', 'assert', 'le... | 631,716 |
palVikram/Machine-Learning-using-Python | cmodule.py | get_gcc_shared_library_arg | get_gcc_shared_library_arg | Return the platform-dependent GCC argument for shared libraries. | [
"Return",
"the",
"platform-dependent",
"GCC",
"argument",
"for",
"shared",
"libraries."
] | def get_gcc_shared_library_arg():
if sys.platform == 'darwin':
return '-dynamiclib'
else:
return '-shared' | ['def', 'get_gcc_shared_library_arg():', 'if', 'sys.platform', '==', "'darwin':", 'return', "'-dynamiclib'", 'else:', 'return', "'-shared'"] | 621,289 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | configuration.py | Configuration.save | save | Save the current in-memory state. | [
"Save",
"the",
"current",
"in-memory",
"state."
] | def save(self):
self._ensure_have_load_only()
for (fname, parser) in self._modified_parsers:
logger.info('Writing to %s', fname)
ensure_dir(os.path.dirname(fname))
with open(fname, 'w') as f:
parser.write(f) | ['def', 'save(self):', 'self._ensure_have_load_only()', 'for', '(fname,', 'parser)', 'in', 'self._modified_parsers:', "logger.info('Writing", 'to', "%s',", 'fname)', 'ensure_dir(os.path.dirname(fname))', 'with', 'open(fname,', "'w')", 'as', 'f:', 'parser.write(f)'] | 454,160 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.acceptDot | acceptDot | Accept and process a dotted expression. | [
"Accept",
"and",
"process",
"a",
"dotted",
"expression."
] | def acceptDot(self, node, memo):
expr = self.factory.expr
self.fs = FS.l + '.' + FS.r
(self.left, self.right) = visitors = (expr(parent=self), expr())
self.zipWalk(node.children, visitors, memo) | ['def', 'acceptDot(self,', 'node,', 'memo):', 'expr', '=', 'self.factory.expr', 'self.fs', '=', 'FS.l', '+', "'.'", '+', 'FS.r', '(self.left,', 'self.right)', '=', 'visitors', '=', '(expr(parent=self),', 'expr())', 'self.zipWalk(node.children,', 'visitors,', 'memo)'] | 17,174 |
jay-johnson/network-pipeline | icmp_send_msg.py | verbose_ping | verbose_ping | Send >count< ping to >destIP< with the given >timeout< and display the result. | [
"Send",
">count<",
"ping",
"to",
">destIP<",
"with",
"the",
"given",
">timeout<",
"and",
"display",
"the",
"result."
] | def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False):
signal.signal(signal.SIGINT, signal_handler)
if hasattr(signal, 'SIGBREAK'):
signal.signal(signal.SIGBREAK, signal_handler)
myStats = MyStats()
mySeqNumber = 0
try:
destIP... | ['def', 'verbose_ping(hostname,', 'timeout=WAIT_TIMEOUT,', 'count=NUM_PACKETS,', 'packet_size=PACKET_SIZE,', 'path_finder=False):', 'signal.signal(signal.SIGINT,', 'signal_handler)', 'if', 'hasattr(signal,', "'SIGBREAK'):", 'signal.signal(signal.SIGBREAK,', 'signal_handler)', 'myStats', '=', 'MyStats()', 'mySeqNumber',... | 736,389 |
kubeflow/pipelines | compile_.py | is_pipeline_func | is_pipeline_func | Checks if a function is a pipeline function. | [
"Checks",
"if",
"a",
"function",
"is",
"a",
"pipeline",
"function."
] | def is_pipeline_func(func: Callable) -> bool:
return isinstance(func, graph_component.GraphComponent) | ['def', 'is_pipeline_func(func:', 'Callable)', '->', 'bool:', 'return', 'isinstance(func,', 'graph_component.GraphComponent)'] | 779,827 |
bytedance/ParaGen | label_smoothed_ctc.py | LabelSmoothedCTC.build | build | Build a label smoothed cross entropy loss over model. | [
"Build",
"a",
"label",
"smoothed",
"cross",
"entropy",
"loss",
"over",
"model."
] | def build(self, model, padding_idx=-1, blank_idx=0):
self._model = model
self._padding_idx = padding_idx
self._blank_id = blank_idx
self.ctc_loss = torch.nn.CTCLoss(blank=self._blank_id, reduction='none', zero_infinity=True) | ['def', 'build(self,', 'model,', 'padding_idx=-1,', 'blank_idx=0):', 'self._model', '=', 'model', 'self._padding_idx', '=', 'padding_idx', 'self._blank_id', '=', 'blank_idx', 'self.ctc_loss', '=', 'torch.nn.CTCLoss(blank=self._blank_id,', "reduction='none',", 'zero_infinity=True)'] | 779,383 |
weimin17/Object-Detection_HelmetDetection | seq2seq_vd.py | gen_encoder | gen_encoder | Define the Encoder graph. | [
"Define",
"the",
"Encoder",
"graph."
] | def gen_encoder(hparams, inputs, targets_present, is_training, reuse=None):
if FLAGS.seq2seq_share_embedding:
with tf.variable_scope('decoder/rnn'):
embedding = tf.get_variable('embedding', [FLAGS.vocab_size, hparams.gen_rnn_size])
with tf.variable_scope('encoder', reuse=reuse):
def... | ['def', 'gen_encoder(hparams,', 'inputs,', 'targets_present,', 'is_training,', 'reuse=None):', 'if', 'FLAGS.seq2seq_share_embedding:', 'with', "tf.variable_scope('decoder/rnn'):", 'embedding', '=', "tf.get_variable('embedding',", '[FLAGS.vocab_size,', 'hparams.gen_rnn_size])', 'with', "tf.variable_scope('encoder',", 'r... | 763,718 |
Kaleidophon/deep-significance | test_aso.py | ASOTechnicalTests.test_compute_violation_ratio_correlation | test_compute_violation_ratio_correlation | Test whether violation ratio is being computed correctly. | [
"Test",
"whether",
"violation",
"ratio",
"is",
"being",
"computed",
"correctly."
] | def test_compute_violation_ratio_correlation(self):
samples_normal2 = np.random.normal(scale=2, size=self.num_samples)
violation_ratios = []
inv_sqw_dists = []
for loc in np.arange(0, 1, 0.05):
samples_normal1 = np.random.normal(loc=loc, size=self.num_samples)
violation_ratio = compute_v... | ['def', 'test_compute_violation_ratio_correlation(self):', 'samples_normal2', '=', 'np.random.normal(scale=2,', 'size=self.num_samples)', 'violation_ratios', '=', '[]', 'inv_sqw_dists', '=', '[]', 'for', 'loc', 'in', 'np.arange(0,', '1,', '0.05):', 'samples_normal1', '=', 'np.random.normal(loc=loc,', 'size=self.num_sam... | 519,600 |
tobegit3hub/deep_image_model | function.py | _DefinedFunction.python_grad_func | python_grad_func | Python gradient function callable. | [
"Python",
"gradient",
"function",
"callable."
] | def python_grad_func(self):
return self._python_grad_func | ['def', 'python_grad_func(self):', 'return', 'self._python_grad_func'] | 182,500 |
scikit-learn-contrib/imbalanced-learn | base.py | SMOTENC.ohe_ | ohe_ | One-hot encoder used to encode the categorical features. | [
"One-hot",
"encoder",
"used",
"to",
"encode",
"the",
"categorical",
"features."
] | def ohe_(self):
warnings.warn("'ohe_' attribute has been deprecated in 0.11 and will be removed in 0.13. Use 'categorical_encoder_' instead.", FutureWarning)
return self.categorical_encoder_ | ['def', 'ohe_(self):', 'warnings.warn("\'ohe_\'', 'attribute', 'has', 'been', 'deprecated', 'in', '0.11', 'and', 'will', 'be', 'removed', 'in', '0.13.', 'Use', "'categorical_encoder_'", 'instead.",', 'FutureWarning)', 'return', 'self.categorical_encoder_'] | 610,660 |
googleapis/python-aiplatform | client.py | ScheduleServiceClient.parse_pipeline_job_path | parse_pipeline_job_path | Parses a pipeline_job path into its component segments. | [
"Parses",
"a",
"pipeline_job",
"path",
"into",
"its",
"component",
"segments."
] | def parse_pipeline_job_path(path: str) -> Dict[str, str]:
m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/pipelineJobs/(?P<pipeline_job>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_pipeline_job_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/pipelineJobs/(?P<pipeline_job>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 811,733 |
Bismarrck/kcon | predictor.py | KcnnPredictor.k_max | k_max | Return the many-body expansion factor for this model. | [
"Return",
"the",
"many-body",
"expansion",
"factor",
"for",
"this",
"model."
] | def k_max(self):
return self._transformer.k_max | ['def', 'k_max(self):', 'return', 'self._transformer.k_max'] | 247,524 |
oegedijk/explainerdashboard | explainer_methods.py | get_decisionpath_df | get_decisionpath_df | summarize the path through a DecisionTree for a specific observation. | [
"summarize",
"the",
"path",
"through",
"a",
"DecisionTree",
"for",
"a",
"specific",
"observation."
] | def get_decisionpath_df(decision_tree, observation, pos_label=1):
nodes = decision_tree.predict_path(observation)
decisiontree_df = pd.DataFrame(columns=['node_id', 'average', 'feature', 'value', 'split', 'direction', 'left', 'right', 'diff'])
if decision_tree.is_classifier():
def node_pred_proba(n... | ['def', 'get_decisionpath_df(decision_tree,', 'observation,', 'pos_label=1):', 'nodes', '=', 'decision_tree.predict_path(observation)', 'decisiontree_df', '=', "pd.DataFrame(columns=['node_id',", "'average',", "'feature',", "'value',", "'split',", "'direction',", "'left',", "'right',", "'diff'])", 'if', 'decision_tree.... | 563,798 |
rifqind/Agent-Programs-3KS1 | __init__.py | FCompiler.get_flags_arch | get_flags_arch | List of architecture dependent compiler flags. | [
"List",
"of",
"architecture",
"dependent",
"compiler",
"flags."
] | def get_flags_arch(self):
return [] | ['def', 'get_flags_arch(self):', 'return', '[]'] | 43,682 |
HighnessAtharva/VocabCLI | Study.py | quiz_learning | quiz_learning | Quiz words in learning list. | [
"Quiz",
"words",
"in",
"learning",
"list."
] | def quiz_learning(number: Optional[int]=None) -> None:
conn = createConnection()
c = conn.cursor()
with contextlib.suppress(NoWordsInLearningListException):
if count_learning() == 0:
raise NoWordsInLearningListException()
if not number:
c.execute('SELECT DISTINCT word FROM wo... | ['def', 'quiz_learning(number:', 'Optional[int]=None)', '->', 'None:', 'conn', '=', 'createConnection()', 'c', '=', 'conn.cursor()', 'with', 'contextlib.suppress(NoWordsInLearningListException):', 'if', 'count_learning()', '==', '0:', 'raise', 'NoWordsInLearningListException()', 'if', 'not', 'number:', "c.execute('SELE... | 946,303 |
kornia/kornia | luv.py | luv_to_rgb | luv_to_rgb | Convert a Luv image to RGB. | [
"Convert",
"a",
"Luv",
"image",
"to",
"RGB."
] | def luv_to_rgb(image: torch.Tensor, eps: float=1e-12) -> torch.Tensor:
if not isinstance(image, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(image)}')
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f'Input size must have a shape of (*, 3, H, W).... | ['def', 'luv_to_rgb(image:', 'torch.Tensor,', 'eps:', 'float=1e-12)', '->', 'torch.Tensor:', 'if', 'not', 'isinstance(image,', 'torch.Tensor):', 'raise', "TypeError(f'Input", 'type', 'is', 'not', 'a', 'torch.Tensor.', 'Got', "{type(image)}')", 'if', 'len(image.shape)', '<', '3', 'or', 'image.shape[-3]', '!=', '3:', 'ra... | 621,556 |
weimin17/Object-Detection_HelmetDetection | data_download.py | parse_args | parse_args | Parses arguments and returns a tuple (known_args, unparsed_args). | [
"Parses",
"arguments",
"and",
"returns",
"a",
"tuple",
"(known_args,",
"unparsed_args)."
] | def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='/tmp/higgs_data', help='Directory to download higgs dataset and store training/eval data.')
return parser.parse_known_args() | ['def', 'parse_args():', 'parser', '=', 'argparse.ArgumentParser()', "parser.add_argument('--data_dir',", 'type=str,', "default='/tmp/higgs_data',", "help='Directory", 'to', 'download', 'higgs', 'dataset', 'and', 'store', 'training/eval', "data.')", 'return', 'parser.parse_known_args()'] | 748,540 |
open-mmlab/mmdetection3d | eval.py | kitti_eval_coco_style | kitti_eval_coco_style | coco style evaluation of kitti. | [
"coco",
"style",
"evaluation",
"of",
"kitti."
] | def kitti_eval_coco_style(gt_annos, dt_annos, current_classes):
class_to_name = {0: 'Car', 1: 'Pedestrian', 2: 'Cyclist', 3: 'Van', 4: 'Person_sitting'}
class_to_range = {0: [0.5, 0.95, 10], 1: [0.25, 0.7, 10], 2: [0.25, 0.7, 10], 3: [0.5, 0.95, 10], 4: [0.25, 0.7, 10]}
name_to_class = {v: n for (n, v) in c... | ['def', 'kitti_eval_coco_style(gt_annos,', 'dt_annos,', 'current_classes):', 'class_to_name', '=', '{0:', "'Car',", '1:', "'Pedestrian',", '2:', "'Cyclist',", '3:', "'Van',", '4:', "'Person_sitting'}", 'class_to_range', '=', '{0:', '[0.5,', '0.95,', '10],', '1:', '[0.25,', '0.7,', '10],', '2:', '[0.25,', '0.7,', '10],'... | 631,777 |
gilis-rnd/openNMT-arabic-transfer-learning | model_builder.py | build_decoder | build_decoder | Various decoder dispatcher function. | [
"Various",
"decoder",
"dispatcher",
"function."
] | def build_decoder(opt, embeddings):
dec_type = 'ifrnn' if opt.decoder_type == 'rnn' and opt.input_feed else opt.decoder_type
return str2dec[dec_type].from_opt(opt, embeddings) | ['def', 'build_decoder(opt,', 'embeddings):', 'dec_type', '=', "'ifrnn'", 'if', 'opt.decoder_type', '==', "'rnn'", 'and', 'opt.input_feed', 'else', 'opt.decoder_type', 'return', 'str2dec[dec_type].from_opt(opt,', 'embeddings)'] | 757,166 |
vghost2008/wml1 | coco_evaluation_test.py | CocoKeypointEvaluationTest.testFiltersDetectionsFromOtherCategories | testFiltersDetectionsFromOtherCategories | Tests that the evaluator ignores detections from other categories. | [
"Tests",
"that",
"the",
"evaluator",
"ignores",
"detections",
"from",
"other",
"categories."
] | def testFiltersDetectionsFromOtherCategories(self):
category_keypoint_dict = _get_category_keypoints_dict()
coco_evaluator = coco_evaluation.CocoKeypointEvaluator(category_id=2, category_keypoints=category_keypoint_dict['person'], class_text='dog')
coco_evaluator.add_single_ground_truth_image_info(image_id=... | ['def', 'testFiltersDetectionsFromOtherCategories(self):', 'category_keypoint_dict', '=', '_get_category_keypoints_dict()', 'coco_evaluator', '=', 'coco_evaluation.CocoKeypointEvaluator(category_id=2,', "category_keypoints=category_keypoint_dict['person'],", "class_text='dog')", "coco_evaluator.add_single_ground_truth_... | 960,336 |
201608040228/-Natural-Language-Processing | vocab.py | Vocab.convert_to_ids | convert_to_ids | Convert a list of tokens to ids, use unk_token if the token is not in vocab. | [
"Convert",
"a",
"list",
"of",
"tokens",
"to",
"ids,",
"use",
"unk_token",
"if",
"the",
"token",
"is",
"not",
"in",
"vocab."
] | def convert_to_ids(self, tokens):
vec = [self.get_id(label) for label in tokens]
return vec | ['def', 'convert_to_ids(self,', 'tokens):', 'vec', '=', '[self.get_id(label)', 'for', 'label', 'in', 'tokens]', 'return', 'vec'] | 375,175 |
pramodiperera/virtual-keyboard | installer.py | strip_marker | strip_marker | Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored. | [
"Return",
"a",
"new",
"requirement",
"without",
"the",
"environment",
"marker",
"to",
"avoid",
"calling",
"pip",
"with",
"something",
"like",
"`babel;",
"extra",
"==",
"\"i18n\"`,",
"which",
"would",
"always",
"be",
"ignored."
] | def strip_marker(req):
req = pkg_resources.Requirement.parse(str(req))
req.marker = None
return req | ['def', 'strip_marker(req):', 'req', '=', 'pkg_resources.Requirement.parse(str(req))', 'req.marker', '=', 'None', 'return', 'req'] | 932,922 |
Eric3911/OpenAGI | eval_neural_rescorer.py | compute_wer | compute_wer | Sorts the candidates based on the scores and calculates the WER with the new top candidates. | [
"Sorts",
"the",
"candidates",
"based",
"on",
"the",
"scores",
"and",
"calculates",
"the",
"WER",
"with",
"the",
"new",
"top",
"candidates."
] | def compute_wer(dists, scores, total_len):
indices = scores.max(dim=1, keepdim=True)[1]
wer = dists.gather(dim=1, index=indices).sum() / total_len
wer = wer.item()
return wer | ['def', 'compute_wer(dists,', 'scores,', 'total_len):', 'indices', '=', 'scores.max(dim=1,', 'keepdim=True)[1]', 'wer', '=', 'dists.gather(dim=1,', 'index=indices).sum()', '/', 'total_len', 'wer', '=', 'wer.item()', 'return', 'wer'] | 274,253 |
arshpreetsingh/quantopian-machinelearning | conftest.py | axis | axis | Fixture for returning the axis numbers of a DataFrame. | [
"Fixture",
"for",
"returning",
"the",
"axis",
"numbers",
"of",
"a",
"DataFrame."
] | def axis(request):
return request.param | ['def', 'axis(request):', 'return', 'request.param'] | 889,477 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | transformer_nat.py | encode | encode | Transformer preparations and encoder. | [
"Transformer",
"preparations",
"and",
"encoder."
] | def encode(x, x_space, hparams, name):
with tf.variable_scope(name):
(encoder_input, encoder_self_attention_bias, ed) = transformer.transformer_prepare_encoder(x, x_space, hparams)
encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)
return (transformer.transformer_encoder(enc... | ['def', 'encode(x,', 'x_space,', 'hparams,', 'name):', 'with', 'tf.variable_scope(name):', '(encoder_input,', 'encoder_self_attention_bias,', 'ed)', '=', 'transformer.transformer_prepare_encoder(x,', 'x_space,', 'hparams)', 'encoder_input', '=', 'tf.nn.dropout(encoder_input,', '1.0', '-', 'hparams.dropout)', 'return', ... | 965,866 |
georghess/voxel-mae | nuscenes_converter.py | get_2d_boxes | get_2d_boxes | Get the 2D annotation records for a given `sample_data_token`. | [
"Get",
"the",
"2D",
"annotation",
"records",
"for",
"a",
"given",
"`sample_data_token`."
] | def get_2d_boxes(nusc, sample_data_token: str, visibilities: List[str], mono3d=True):
sd_rec = nusc.get('sample_data', sample_data_token)
assert sd_rec['sensor_modality'] == 'camera', 'Error: get_2d_boxes only works for camera sample_data!'
if not sd_rec['is_key_frame']:
raise ValueError('The 2D re-... | ['def', 'get_2d_boxes(nusc,', 'sample_data_token:', 'str,', 'visibilities:', 'List[str],', 'mono3d=True):', 'sd_rec', '=', "nusc.get('sample_data',", 'sample_data_token)', 'assert', "sd_rec['sensor_modality']", '==', "'camera',", "'Error:", 'get_2d_boxes', 'only', 'works', 'for', 'camera', "sample_data!'", 'if', 'not',... | 380,823 |
kubeflow/pipelines | component.py | automl_export_model_to_gcs | automl_export_model_to_gcs | Exports a trained model to a user specified Google Cloud Storage location. | [
"Exports",
"a",
"trained",
"model",
"to",
"a",
"user",
"specified",
"Google",
"Cloud",
"Storage",
"location."
] | def automl_export_model_to_gcs(model_path: str, gcs_output_uri_prefix: str, model_format: str='tf_saved_model') -> NamedTuple('Outputs', [('model_directory', 'Uri')]):
from google.cloud import automl
client = automl.AutoMlClient()
response = client.export_model(name=model_path, output_config=automl.ModelExp... | ['def', 'automl_export_model_to_gcs(model_path:', 'str,', 'gcs_output_uri_prefix:', 'str,', 'model_format:', "str='tf_saved_model')", '->', "NamedTuple('Outputs',", "[('model_directory',", "'Uri')]):", 'from', 'google.cloud', 'import', 'automl', 'client', '=', 'automl.AutoMlClient()', 'response', '=', 'client.export_mo... | 770,698 |
Eli-YiLi/WSSS_MMSeg | base.py | BaseSegmentor.init_weights | init_weights | Initialize the weights in segmentor. | [
"Initialize",
"the",
"weights",
"in",
"segmentor."
] | def init_weights(self, pretrained=None):
if pretrained is not None:
logger = logging.getLogger()
logger.info(f'load model from: {pretrained}') | ['def', 'init_weights(self,', 'pretrained=None):', 'if', 'pretrained', 'is', 'not', 'None:', 'logger', '=', 'logging.getLogger()', "logger.info(f'load", 'model', 'from:', "{pretrained}')"] | 961,194 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.acceptInstanceof | acceptInstanceof | Accept and process an instanceof expression. | [
"Accept",
"and",
"process",
"an",
"instanceof",
"expression."
] | def acceptInstanceof(self, node, memo):
self.fs = 'isinstance({right}, ({left}, ))'
self.right = self.factory.expr(parent=self)
self.right.walk(node.firstChildOfType(tokens.IDENT), memo)
self.left = self.factory.expr(parent=self)
self.left.walk(node.firstChildOfType(tokens.TYPE), memo) | ['def', 'acceptInstanceof(self,', 'node,', 'memo):', 'self.fs', '=', "'isinstance({right},", '({left},', "))'", 'self.right', '=', 'self.factory.expr(parent=self)', 'self.right.walk(node.firstChildOfType(tokens.IDENT),', 'memo)', 'self.left', '=', 'self.factory.expr(parent=self)', 'self.left.walk(node.firstChildOfType(... | 17,177 |
rahlk/Bellwether | hsic.py | CHSIC.UnBiasedHSICFast | UnBiasedHSICFast | Fast computation of the biased HSIC when the kernel matrix for the data and the HLH matrix for the labels are already computed. | [
"Fast",
"computation",
"of",
"the",
"biased",
"HSIC",
"when",
"the",
"kernel",
"matrix",
"for",
"the",
"data",
"and",
"the",
"HLH",
"matrix",
"for",
"the",
"labels",
"are",
"already",
"computed."
] | def UnBiasedHSICFast(self, kMat, lMat, sL, ssL):
nx = kMat.shape
assert kMat.shape == lMat.shape, 'Argument 1 and 2 have different shapes'
sK = numpy.sum(kMat, axis=1)
ssK = numpy.sum(sK)
return (numpy.sum(numpy.sum(kMat * lMat)) + ssK * ssL / ((nx[0] - 1) * (nx[0] - 2)) - 2 * numpy.sum(sK * sL) / (... | ['def', 'UnBiasedHSICFast(self,', 'kMat,', 'lMat,', 'sL,', 'ssL):', 'nx', '=', 'kMat.shape', 'assert', 'kMat.shape', '==', 'lMat.shape,', "'Argument", '1', 'and', '2', 'have', 'different', "shapes'", 'sK', '=', 'numpy.sum(kMat,', 'axis=1)', 'ssK', '=', 'numpy.sum(sK)', 'return', '(numpy.sum(numpy.sum(kMat', '*', 'lMat)... | 432,294 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjvGeomWrapper.texcoord | texcoord | mesh geom has texture coordinates. | [
"mesh",
"geom",
"has",
"texture",
"coordinates."
] | def texcoord(self):
return self._ptr.contents.texcoord | ['def', 'texcoord(self):', 'return', 'self._ptr.contents.texcoord'] | 440,728 |
Deci-AI/super-gradients | detection_sub_classing_test.py | TestDetectionDatasetSubclassing.test_wrong_subclass | test_wrong_subclass | Check that ValueError is raised when class_inclusion_list includes a class that does not exist. | [
"Check",
"that",
"ValueError",
"is",
"raised",
"when",
"class_inclusion_list",
"includes",
"a",
"class",
"that",
"does",
"not",
"exist."
] | def test_wrong_subclass(self):
with self.assertRaises(DatasetValidationException):
DummyDetectionDataset(input_dim=(640, 512), class_inclusion_list=['non_existing_class'], target_format=XYXY_LABEL)
with self.assertRaises(DatasetValidationException):
DummyDetectionDataset(input_dim=(640, 512), cl... | ['def', 'test_wrong_subclass(self):', 'with', 'self.assertRaises(DatasetValidationException):', 'DummyDetectionDataset(input_dim=(640,', '512),', "class_inclusion_list=['non_existing_class'],", 'target_format=XYXY_LABEL)', 'with', 'self.assertRaises(DatasetValidationException):', 'DummyDetectionDataset(input_dim=(640,'... | 880,655 |
kornia/kornia | camera_model.py | CameraModelBase.image_size | image_size | Returns the image size of the camera model. | [
"Returns",
"the",
"image",
"size",
"of",
"the",
"camera",
"model."
] | def image_size(self) -> ImageSize:
return self._image_size | ['def', 'image_size(self)', '->', 'ImageSize:', 'return', 'self._image_size'] | 622,264 |
NetManAIOps/OmniAnomaly | vae.py | VAE.reconstruct | reconstruct | Sample reconstructed `x` from :math:`p(x|h(z))`, where `z` is (are) sampled from :math:`q(z|h(x))` using the specified observation `x`. | [
"Sample",
"reconstructed",
"`x`",
"from",
":math:`p(x|h(z))`,",
"where",
"`z`",
"is",
"(are)",
"sampled",
"from",
":math:`q(z|h(x))`",
"using",
"the",
"specified",
"observation",
"`x`."
] | def reconstruct(self, x, n_z=None, n_x=None, posterior_flow=None):
with tf.name_scope('VAE.reconstruct'):
q_net = self.variational(x, n_z=n_z, posterior_flow=posterior_flow)
model = self.model(z=q_net['z'], n_z=n_z, n_x=n_x)
return model['x'] | ['def', 'reconstruct(self,', 'x,', 'n_z=None,', 'n_x=None,', 'posterior_flow=None):', 'with', "tf.name_scope('VAE.reconstruct'):", 'q_net', '=', 'self.variational(x,', 'n_z=n_z,', 'posterior_flow=posterior_flow)', 'model', '=', "self.model(z=q_net['z'],", 'n_z=n_z,', 'n_x=n_x)', 'return', "model['x']"] | 250,280 |
KarimMibrahim/Recurrent-Neural-Network-Implementation | gradient_check.py | eval_numerical_gradient_array | eval_numerical_gradient_array | Evaluate a numeric gradient for a function that accepts a numpy array and returns a numpy array. | [
"Evaluate",
"a",
"numeric",
"gradient",
"for",
"a",
"function",
"that",
"accepts",
"a",
"numpy",
"array",
"and",
"returns",
"a",
"numpy",
"array."
] | def eval_numerical_gradient_array(f, x, df, h=1e-05):
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h
pos = f(x).copy()
x[ix] = oldval - h
neg... | ['def', 'eval_numerical_gradient_array(f,', 'x,', 'df,', 'h=1e-05):', 'grad', '=', 'np.zeros_like(x)', 'it', '=', 'np.nditer(x,', "flags=['multi_index'],", "op_flags=['readwrite'])", 'while', 'not', 'it.finished:', 'ix', '=', 'it.multi_index', 'oldval', '=', 'x[ix]', 'x[ix]', '=', 'oldval', '+', 'h', 'pos', '=', 'f(x).... | 309,297 |
voxel51/fiftyone | fields.py | EmbeddedDocumentField.get_field | get_field | Returns the field for the provided path, or ``None``. | [
"Returns",
"the",
"field",
"for",
"the",
"provided",
"path,",
"or",
"``None``."
] | def get_field(self, path):
chunks = path.split('.', 1)
if len(chunks) > 1:
field = self._fields.get(chunks[0], None)
while isinstance(field, ListField):
field = field.field
if not isinstance(field, EmbeddedDocumentField):
return None
return field.get_field... | ['def', 'get_field(self,', 'path):', 'chunks', '=', "path.split('.',", '1)', 'if', 'len(chunks)', '>', '1:', 'field', '=', 'self._fields.get(chunks[0],', 'None)', 'while', 'isinstance(field,', 'ListField):', 'field', '=', 'field.field', 'if', 'not', 'isinstance(field,', 'EmbeddedDocumentField):', 'return', 'None', 'ret... | 583,112 |
Katja-M/Python_NaturalLanguageProcessing | util.py | CanvasWidget.unbind_drag | unbind_drag | Remove a callback that was registered with ``bind_drag``. | [
"Remove",
"a",
"callback",
"that",
"was",
"registered",
"with",
"``bind_drag``."
] | def unbind_drag(self):
try:
del self.__callbacks['drag']
except:
pass | ['def', 'unbind_drag(self):', 'try:', 'del', "self.__callbacks['drag']", 'except:', 'pass'] | 866,432 |
enyac-group/NeuralPower | comm.py | ButterflyMixing.all_reduce | all_reduce | It allows partial reduction. | [
"It",
"allows",
"partial",
"reduction."
] | def all_reduce(self, data_in_bytes):
one_link_time = self._time_in_communication(data_in_bytes)
return one_link_time | ['def', 'all_reduce(self,', 'data_in_bytes):', 'one_link_time', '=', 'self._time_in_communication(data_in_bytes)', 'return', 'one_link_time'] | 293,437 |
facebookresearch/CompilerGym | e_greedy_test.py | test_select_best_action_closed_environment | test_select_best_action_closed_environment | Test that select_best_action() recovers from an environment whose service has closed. | [
"Test",
"that",
"select_best_action()",
"recovers",
"from",
"an",
"environment",
"whose",
"service",
"has",
"closed."
] | def test_select_best_action_closed_environment(env: LlvmEnv):
env.reward_space = 'IrInstructionCount'
env.reset(benchmark='cbench-v1/crc32')
with ThreadPoolExecutor() as executor:
best_a = select_best_action(env, executor)
env.close()
best_b = select_best_action(env, executor)
... | ['def', 'test_select_best_action_closed_environment(env:', 'LlvmEnv):', 'env.reward_space', '=', "'IrInstructionCount'", "env.reset(benchmark='cbench-v1/crc32')", 'with', 'ThreadPoolExecutor()', 'as', 'executor:', 'best_a', '=', 'select_best_action(env,', 'executor)', 'env.close()', 'best_b', '=', 'select_best_action(e... | 135,752 |
OpenMDAO/OpenMDAO-Framework | multifi_cokriging_surrogate.py | MultiFiCoKrigingSurrogate.train | train | Train the surrogate model with the given set of inputs and outputs. | [
"Train",
"the",
"surrogate",
"model",
"with",
"the",
"given",
"set",
"of",
"inputs",
"and",
"outputs."
] | def train(self, X, Y):
(X, Y) = self._fit_adapter(X, Y)
self.model.fit(X, Y, tol=self.tolerance, initial_range=self.initial_range) | ['def', 'train(self,', 'X,', 'Y):', '(X,', 'Y)', '=', 'self._fit_adapter(X,', 'Y)', 'self.model.fit(X,', 'Y,', 'tol=self.tolerance,', 'initial_range=self.initial_range)'] | 275,616 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | vgslspecs_test.py | VgslspecsTest.testSameSizeParallel | testSameSizeParallel | Parallel affects depth, but not scale. | [
"Parallel",
"affects",
"depth,",
"but",
"not",
"scale."
] | def testSameSizeParallel(self):
self.ExpectScaledSize('[Cs5,5,16 (Lfx{MyLSTM}32 Lrx32 Lbx16)]', (self.batch_size, self.max_height, self.max_width, 96)) | ['def', 'testSameSizeParallel(self):', "self.ExpectScaledSize('[Cs5,5,16", '(Lfx{MyLSTM}32', 'Lrx32', "Lbx16)]',", '(self.batch_size,', 'self.max_height,', 'self.max_width,', '96))'] | 110,650 |
matsu0228/nlp-jp | test_path.py | test_get_home_dir_8 | test_get_home_dir_8 | Using registry hack for 'My Documents', os=='nt' HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. | [
"Using",
"registry",
"hack",
"for",
"'My",
"Documents',",
"os=='nt'",
"HOMESHARE,",
"HOMEDRIVE,",
"HOMEPATH,",
"USERPROFILE",
"and",
"others",
"are",
"missing."
] | def test_get_home_dir_8():
os.name = 'nt'
for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
env.pop(key, None)
class key:
def Close(self):
pass
with patch.object(wreg, 'OpenKey', return_value=key()), patch.object(wreg, 'QueryValueEx', return_value=[a... | ['def', 'test_get_home_dir_8():', 'os.name', '=', "'nt'", 'for', 'key', 'in', "['HOME',", "'HOMESHARE',", "'HOMEDRIVE',", "'HOMEPATH',", "'USERPROFILE']:", 'env.pop(key,', 'None)', 'class', 'key:', 'def', 'Close(self):', 'pass', 'with', 'patch.object(wreg,', "'OpenKey',", 'return_value=key()),', 'patch.object(wreg,', "... | 787,544 |
deepmind/acme | measurement_metrics.py | MeasurementObserver.observe | observe | Records one environment step. | [
"Records",
"one",
"environment",
"step."
] | def observe(self, env: dm_env.Environment, timestep: dm_env.TimeStep, action: np.ndarray) -> None:
self._measurements.append(timestep.observation) | ['def', 'observe(self,', 'env:', 'dm_env.Environment,', 'timestep:', 'dm_env.TimeStep,', 'action:', 'np.ndarray)', '->', 'None:', 'self._measurements.append(timestep.observation)'] | 8,468 |
xmax1/dvae | dropout.py | schedule | schedule | Generator for a dropout schedule. | [
"Generator",
"for",
"a",
"dropout",
"schedule."
] | def schedule(start=0.0, stop=1.0, step=1.0):
dropout = start
while True:
yield dropout
dropout = min(dropout + step, stop) | ['def', 'schedule(start=0.0,', 'stop=1.0,', 'step=1.0):', 'dropout', '=', 'start', 'while', 'True:', 'yield', 'dropout', 'dropout', '=', 'min(dropout', '+', 'step,', 'stop)'] | 555,101 |
43Carrig/recurrent_neural_networks_practice | file_io.py | read_file_to_string | read_file_to_string | Reads the entire contents of a file to a string. | [
"Reads",
"the",
"entire",
"contents",
"of",
"a",
"file",
"to",
"a",
"string."
] | def read_file_to_string(filename, binary_mode=False):
if binary_mode:
f = FileIO(filename, mode='rb')
else:
f = FileIO(filename, mode='r')
return f.read() | ['def', 'read_file_to_string(filename,', 'binary_mode=False):', 'if', 'binary_mode:', 'f', '=', 'FileIO(filename,', "mode='rb')", 'else:', 'f', '=', 'FileIO(filename,', "mode='r')", 'return', 'f.read()'] | 337,038 |
RozDavid/LanguageGroundedSemseg | distributed.py | init_process_group | init_process_group | Initializes the default process group. | [
"Initializes",
"the",
"default",
"process",
"group."
] | def init_process_group(proc_rank, world_size):
torch.cuda.set_device(proc_rank)
torch.distributed.init_process_group(backend='nccl', init_method='tcp://{}:{}'.format('localhost', '10001'), world_size=world_size, rank=proc_rank) | ['def', 'init_process_group(proc_rank,', 'world_size):', 'torch.cuda.set_device(proc_rank)', "torch.distributed.init_process_group(backend='nccl',", "init_method='tcp://{}:{}'.format('localhost',", "'10001'),", 'world_size=world_size,', 'rank=proc_rank)'] | 623,614 |
Speedwagon13/CS-3600-Introduction-to-- | numbers.py | Integral.numerator | numerator | Integers are their own numerators. | [
"Integers",
"are",
"their",
"own",
"numerators."
] | def numerator(self):
return +self | ['def', 'numerator(self):', 'return', '+self'] | 139,903 |
jiansfoggy/16-720B | keypointDetect.py | getLocalExtrema | getLocalExtrema | Returns local extrema points in both scale and space using the DoGPyramid INPUTS DoG_pyramid - size (imH, imW, len(levels) - 1) matrix of the DoG pyramid DoG_levels - The levels of the pyramid where the blur at each level is outputs principal_curvature - size (imH, imW, len(levels) - 1) matrix contains the curvature r... | [
"Returns",
"local",
"extrema",
"points",
"in",
"both",
"scale",
"and",
"space",
"using",
"the",
"DoGPyramid",
"INPUTS",
"DoG_pyramid",
"-",
"size",
"(imH,",
"imW,",
"len(levels)",
"-",
"1)",
"matrix",
"of",
"the",
"DoG",
"pyramid",
"DoG_levels",
"-",
"The",
... | def getLocalExtrema(DoG_pyramid, DoG_levels, principal_curvature, th_contrast=0.03, th_r=12):
(imh, imw, iml) = DoG_pyramid.shape
extremaTensor = np.zeros((11, imh, imw, iml))
for layer in range(0, iml):
temp_pyramid = np.pad(DoG_pyramid[:, :, layer], (1, 1), mode='constant', constant_values=0)
... | ['def', 'getLocalExtrema(DoG_pyramid,', 'DoG_levels,', 'principal_curvature,', 'th_contrast=0.03,', 'th_r=12):', '(imh,', 'imw,', 'iml)', '=', 'DoG_pyramid.shape', 'extremaTensor', '=', 'np.zeros((11,', 'imh,', 'imw,', 'iml))', 'for', 'layer', 'in', 'range(0,', 'iml):', 'temp_pyramid', '=', 'np.pad(DoG_pyramid[:,', ':,... | 375,396 |
Yuting-Gao/DisCo-pytorch | selecsls.py | selecsls84 | selecsls84 | Constructs a SelecSLS84 model. | [
"Constructs",
"a",
"SelecSLS84",
"model."
] | def selecsls84(pretrained=False, **kwargs):
return _create_selecsls('selecsls84', pretrained, kwargs) | ['def', 'selecsls84(pretrained=False,', '**kwargs):', 'return', "_create_selecsls('selecsls84',", 'pretrained,', 'kwargs)'] | 186,881 |
rudranil723/mini-main | color.py | Color.downgrade | downgrade | Downgrade a color system to a system with fewer colors. | [
"Downgrade",
"a",
"color",
"system",
"to",
"a",
"system",
"with",
"fewer",
"colors."
] | def downgrade(self, system: ColorSystem) -> 'Color':
if self.type in (ColorType.DEFAULT, system):
return self
if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
assert self.triplet is not None
(_h, l, s) = rgb_to_hls(*self.triplet.normalized)
if s < 0.15... | ['def', 'downgrade(self,', 'system:', 'ColorSystem)', '->', "'Color':", 'if', 'self.type', 'in', '(ColorType.DEFAULT,', 'system):', 'return', 'self', 'if', 'system', '==', 'ColorSystem.EIGHT_BIT', 'and', 'self.system', '==', 'ColorSystem.TRUECOLOR:', 'assert', 'self.triplet', 'is', 'not', 'None', '(_h,', 'l,', 's)', '=... | 268,875 |
dibyaghosh/gcsl | coordinate_system.py | CoordinateSystem.set_global_transform | set_global_transform | Sets the global transform. | [
"Sets",
"the",
"global",
"transform."
] | def set_global_transform(self, translation: np.ndarray, rotation: np.ndarray):
(trans, rot) = self._check_transform(translation, rotation)
self._global_translation = trans
self._global_rotation = rot | ['def', 'set_global_transform(self,', 'translation:', 'np.ndarray,', 'rotation:', 'np.ndarray):', '(trans,', 'rot)', '=', 'self._check_transform(translation,', 'rotation)', 'self._global_translation', '=', 'trans', 'self._global_rotation', '=', 'rot'] | 201,816 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | tix.py | TixWidget.subwidget | subwidget | Return the named subwidget (which must have been created by the sub-class). | [
"Return",
"the",
"named",
"subwidget",
"(which",
"must",
"have",
"been",
"created",
"by",
"the",
"sub-class)."
] | def subwidget(self, name):
n = self._subwidget_name(name)
if not n:
raise TclError('Subwidget ' + name + ' not child of ' + self._name)
n = n[len(self._w) + 1:]
return self._nametowidget(n) | ['def', 'subwidget(self,', 'name):', 'n', '=', 'self._subwidget_name(name)', 'if', 'not', 'n:', 'raise', "TclError('Subwidget", "'", '+', 'name', '+', "'", 'not', 'child', 'of', "'", '+', 'self._name)', 'n', '=', 'n[len(self._w)', '+', '1:]', 'return', 'self._nametowidget(n)'] | 376,636 |
ilya16/MultINN | rnn.py | RNN.attn_length | attn_length | int: The size of the attention window. | [
"int:",
"The",
"size",
"of",
"the",
"attention",
"window."
] | def attn_length(self):
return self._attn_length | ['def', 'attn_length(self):', 'return', 'self._attn_length'] | 644,211 |
Farama-Foundation/Gymnasium | test_rescale_action.py | test_rescale_action_wrapper | test_rescale_action_wrapper | Test that the action is rescale within a min / max bound. | [
"Test",
"that",
"the",
"action",
"is",
"rescale",
"within",
"a",
"min",
"/",
"max",
"bound."
] | def test_rescale_action_wrapper():
env = GenericTestEnv(step_func=record_action_step, action_space=Box(np.array([0, 1]), np.array([1, 3])))
wrapped_env = RescaleActionV0(env, min_action=np.array([-5, 0]), max_action=np.array([5, 1]))
assert wrapped_env.action_space == Box(np.array([-5, 0]), np.array([5, 1])... | ['def', 'test_rescale_action_wrapper():', 'env', '=', 'GenericTestEnv(step_func=record_action_step,', 'action_space=Box(np.array([0,', '1]),', 'np.array([1,', '3])))', 'wrapped_env', '=', 'RescaleActionV0(env,', 'min_action=np.array([-5,', '0]),', 'max_action=np.array([5,', '1]))', 'assert', 'wrapped_env.action_space',... | 573,600 |
matsu0228/nlp-jp | demo.py | Demo.back | back | Move the seek pointer back num blocks (default is 1). | [
"Move",
"the",
"seek",
"pointer",
"back",
"num",
"blocks",
"(default",
"is",
"1)."
] | def back(self, num=1):
self.seek(self.block_index - num) | ['def', 'back(self,', 'num=1):', 'self.seek(self.block_index', '-', 'num)'] | 787,171 |
pytorch/rl | gym.py | gym_backend | gym_backend | Returns the gym backend, or a sumbodule of it. | [
"Returns",
"the",
"gym",
"backend,",
"or",
"a",
"sumbodule",
"of",
"it."
] | def gym_backend(submodule=None):
global IMPORT_ERROR
global DEFAULT_GYM
if DEFAULT_GYM is None:
try:
import gymnasium as gym
except ImportError as err:
IMPORT_ERROR = err
try:
import gym as gym
except ImportError as err:
... | ['def', 'gym_backend(submodule=None):', 'global', 'IMPORT_ERROR', 'global', 'DEFAULT_GYM', 'if', 'DEFAULT_GYM', 'is', 'None:', 'try:', 'import', 'gymnasium', 'as', 'gym', 'except', 'ImportError', 'as', 'err:', 'IMPORT_ERROR', '=', 'err', 'try:', 'import', 'gym', 'as', 'gym', 'except', 'ImportError', 'as', 'err:', 'IMPO... | 859,042 |
jwwangchn/NWD | loading.py | LoadAnnotations.process_polygons | process_polygons | Convert polygons to list of ndarray and filter invalid polygons. | [
"Convert",
"polygons",
"to",
"list",
"of",
"ndarray",
"and",
"filter",
"invalid",
"polygons."
] | def process_polygons(self, polygons):
polygons = [np.array(p) for p in polygons]
valid_polygons = []
for polygon in polygons:
if len(polygon) % 2 == 0 and len(polygon) >= 6:
valid_polygons.append(polygon)
return valid_polygons | ['def', 'process_polygons(self,', 'polygons):', 'polygons', '=', '[np.array(p)', 'for', 'p', 'in', 'polygons]', 'valid_polygons', '=', '[]', 'for', 'polygon', 'in', 'polygons:', 'if', 'len(polygon)', '%', '2', '==', '0', 'and', 'len(polygon)', '>=', '6:', 'valid_polygons.append(polygon)', 'return', 'valid_polygons'] | 724,705 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | random_color_jitter | random_color_jitter | Perform random color jitter. | [
"Perform",
"random",
"color",
"jitter."
] | def random_color_jitter(image, p=1.0, color_jitter_strength=1.0, impl='simclrv2'):
def _transform(image):
color_jitter_t = functools.partial(color_jitter, strength=color_jitter_strength, impl=impl)
image = random_apply(color_jitter_t, p=0.8, x=image)
return random_apply(to_grayscale, p=0.2,... | ['def', 'random_color_jitter(image,', 'p=1.0,', 'color_jitter_strength=1.0,', "impl='simclrv2'):", 'def', '_transform(image):', 'color_jitter_t', '=', 'functools.partial(color_jitter,', 'strength=color_jitter_strength,', 'impl=impl)', 'image', '=', 'random_apply(color_jitter_t,', 'p=0.8,', 'x=image)', 'return', 'random... | 973,372 |
intelligent-environments-lab/CityLearn | base.py | Agent.observation_names | observation_names | Names of active observations that can be used to map observation values. | [
"Names",
"of",
"active",
"observations",
"that",
"can",
"be",
"used",
"to",
"map",
"observation",
"values."
] | def observation_names(self) -> List[List[str]]:
return self.__observation_names | ['def', 'observation_names(self)', '->', 'List[List[str]]:', 'return', 'self.__observation_names'] | 105,502 |
facebookresearch/CompilerGym | env_without_bazel_test.py | test_double_reset | test_double_reset | Test that reset() can be called twice. | [
"Test",
"that",
"reset()",
"can",
"be",
"called",
"twice."
] | def test_double_reset(env: CompilerEnv):
env.reset()
assert env.in_episode
env.reset()
assert env.in_episode | ['def', 'test_double_reset(env:', 'CompilerEnv):', 'env.reset()', 'assert', 'env.in_episode', 'env.reset()', 'assert', 'env.in_episode'] | 125,675 |
openvinotoolkit/training_extensions | mask_to_bbox.py | mask_to_border | mask_to_border | Make a border by using a binary mask. | [
"Make",
"a",
"border",
"by",
"using",
"a",
"binary",
"mask."
] | def mask_to_border(mask):
(h, w) = mask.shape
border = np.zeros((h, w))
contours = find_contours(mask, 0.5)
for contour in contours:
for c in contour:
x = int(c[0])
y = int(c[1])
border[x][y] = 1
return border | ['def', 'mask_to_border(mask):', '(h,', 'w)', '=', 'mask.shape', 'border', '=', 'np.zeros((h,', 'w))', 'contours', '=', 'find_contours(mask,', '0.5)', 'for', 'contour', 'in', 'contours:', 'for', 'c', 'in', 'contour:', 'x', '=', 'int(c[0])', 'y', '=', 'int(c[1])', 'border[x][y]', '=', '1', 'return', 'border'] | 918,020 |
zhiweichen0012/E2Net | viz.py | draw_text | draw_text | Draw text on an image. | [
"Draw",
"text",
"on",
"an",
"image."
] | def draw_text(img, pos, text, color, font_scale=0.4):
img = img.astype(np.uint8)
(x0, y0) = (int(pos[0]), int(pos[1]))
font = cv2.FONT_HERSHEY_SIMPLEX
((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1)
if x0 + text_w > img.shape[1]:
x0 = img.shape[1] - text_w
if y0 - int(... | ['def', 'draw_text(img,', 'pos,', 'text,', 'color,', 'font_scale=0.4):', 'img', '=', 'img.astype(np.uint8)', '(x0,', 'y0)', '=', '(int(pos[0]),', 'int(pos[1]))', 'font', '=', 'cv2.FONT_HERSHEY_SIMPLEX', '((text_w,', 'text_h),', '_)', '=', 'cv2.getTextSize(text,', 'font,', 'font_scale,', '1)', 'if', 'x0', '+', 'text_w',... | 174,579 |
AgnostiqHQ/covalent | electron_test.py | test_wait_for_building | test_wait_for_building | Test to check whether the graph is built correctly with `wait_for`. | [
"Test",
"to",
"check",
"whether",
"the",
"graph",
"is",
"built",
"correctly",
"with",
"`wait_for`."
] | def test_wait_for_building():
workflow.build_graph()
assert workflow.transport_graph.get_edge_data(0, 4)[0]['wait_for']
assert workflow.transport_graph.get_edge_data(0, 4)[0]['edge_name'] == '!waiting_edge' | ['def', 'test_wait_for_building():', 'workflow.build_graph()', 'assert', 'workflow.transport_graph.get_edge_data(0,', "4)[0]['wait_for']", 'assert', 'workflow.transport_graph.get_edge_data(0,', "4)[0]['edge_name']", '==', "'!waiting_edge'"] | 489,884 |
triaquae/triaquae | paginator.py | Paginator.page | page | Returns a Page object for the given 1-based page number. | [
"Returns",
"a",
"Page",
"object",
"for",
"the",
"given",
"1-based",
"page",
"number."
] | def page(self, number):
number = self.validate_number(number)
bottom = (number - 1) * self.per_page
top = bottom + self.per_page
if top + self.orphans >= self.count:
top = self.count
return Page(self.object_list[bottom:top], number, self) | ['def', 'page(self,', 'number):', 'number', '=', 'self.validate_number(number)', 'bottom', '=', '(number', '-', '1)', '*', 'self.per_page', 'top', '=', 'bottom', '+', 'self.per_page', 'if', 'top', '+', 'self.orphans', '>=', 'self.count:', 'top', '=', 'self.count', 'return', 'Page(self.object_list[bottom:top],', 'number... | 358,236 |
microsoft/nni | setup_ts.py | prepare_nni_node | prepare_nni_node | Create clean nni_node diretory, then copy node runtime to it. | [
"Create",
"clean",
"nni_node",
"diretory,",
"then",
"copy",
"node",
"runtime",
"to",
"it."
] | def prepare_nni_node():
shutil.rmtree('nni_node', ignore_errors=True)
Path('nni_node').mkdir()
Path('nni_node/__init__.py').write_text('"""NNI node.js modules."""\n')
node_src = Path('toolchain/node', node_executable_in_tarball)
node_dst = Path('nni_node', node_executable)
shutil.copy(node_src, ... | ['def', 'prepare_nni_node():', "shutil.rmtree('nni_node',", 'ignore_errors=True)', "Path('nni_node').mkdir()", 'Path(\'nni_node/__init__.py\').write_text(\'"""NNI', 'node.js', 'modules."""\\n\')', 'node_src', '=', "Path('toolchain/node',", 'node_executable_in_tarball)', 'node_dst', '=', "Path('nni_node',", 'node_execut... | 727,982 |
google-research/scenic | common_utils.py | recursive_reload | recursive_reload | Recursively reload a module and the modules it imports. | [
"Recursively",
"reload",
"a",
"module",
"and",
"the",
"modules",
"it",
"imports."
] | def recursive_reload(module: types.ModuleType, package_restrict: str):
reloaded = set()
if not package_restrict:
raise ValueError('package_restrict must be non-empty.')
def reload(m):
if m in reloaded:
return m
reloaded.add(m)
for attribute_name in dir(m):
... | ['def', 'recursive_reload(module:', 'types.ModuleType,', 'package_restrict:', 'str):', 'reloaded', '=', 'set()', 'if', 'not', 'package_restrict:', 'raise', "ValueError('package_restrict", 'must', 'be', "non-empty.')", 'def', 'reload(m):', 'if', 'm', 'in', 'reloaded:', 'return', 'm', 'reloaded.add(m)', 'for', 'attribute... | 845,992 |
facebookresearch/CompilerGym | llvm_env_test.py | test_apply_state | test_apply_state | Test that apply() on a clean environment produces same state. | [
"Test",
"that",
"apply()",
"on",
"a",
"clean",
"environment",
"produces",
"same",
"state."
] | def test_apply_state(env: LlvmEnv):
env.reward_space = 'IrInstructionCount'
env.reset(benchmark='cbench-v1/crc32')
env.step(env.action_space.flags.index('-mem2reg'))
with gym.make('llvm-v0', reward_space='IrInstructionCount') as other:
other.apply(env.state)
assert other.state == env.sta... | ['def', 'test_apply_state(env:', 'LlvmEnv):', 'env.reward_space', '=', "'IrInstructionCount'", "env.reset(benchmark='cbench-v1/crc32')", "env.step(env.action_space.flags.index('-mem2reg'))", 'with', "gym.make('llvm-v0',", "reward_space='IrInstructionCount')", 'as', 'other:', 'other.apply(env.state)', 'assert', 'other.s... | 125,922 |
intel/neural-compressor | configuration.py | Configuration.is_port_taken | is_port_taken | Return if given port is already in use. | [
"Return",
"if",
"given",
"port",
"is",
"already",
"in",
"use."
] | def is_port_taken(self, port: int) -> bool:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((self.server_address, port))
except socket.error:
return True
finally:
s.close()
return False | ['def', 'is_port_taken(self,', 'port:', 'int)', '->', 'bool:', 's', '=', 'socket.socket(socket.AF_INET,', 'socket.SOCK_STREAM)', 'try:', 's.bind((self.server_address,', 'port))', 'except', 'socket.error:', 'return', 'True', 'finally:', 's.close()', 'return', 'False'] | 721,744 |
sktime/sktime | test_tsfresh.py | test_kind_tsfresh_extractor | test_kind_tsfresh_extractor | Test extractor returns an array of expected num of cols. | [
"Test",
"extractor",
"returns",
"an",
"array",
"of",
"expected",
"num",
"of",
"cols."
] | def test_kind_tsfresh_extractor():
(X, y) = load_arrow_head(return_X_y=True)
(X_train, X_test, y_train, y_test) = train_test_split(X, y)
features_to_calc = ['dim_0__quantile__q_0.6', 'dim_0__longest_strike_above_mean', 'dim_0__variance']
ts_custom = TSFreshFeatureExtractor(kind_to_fc_parameters=features... | ['def', 'test_kind_tsfresh_extractor():', '(X,', 'y)', '=', 'load_arrow_head(return_X_y=True)', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X,', 'y)', 'features_to_calc', '=', "['dim_0__quantile__q_0.6',", "'dim_0__longest_strike_above_mean',", "'dim_0__variance']", 'ts_custom', '=', 'TSFreshF... | 877,776 |
avril-affine/cs224d | model.py | Model.add_loss_op | add_loss_op | Adds ops for loss to the computational graph. | [
"Adds",
"ops",
"for",
"loss",
"to",
"the",
"computational",
"graph."
] | def add_loss_op(self, pred):
raise NotImplementedError('Each Model must re-implement this method.') | ['def', 'add_loss_op(self,', 'pred):', 'raise', "NotImplementedError('Each", 'Model', 'must', 're-implement', 'this', "method.')"] | 506,417 |
YuriyGuts/snake-ai-reinforcement | entities.py | Field.size | size | Get the size of the field (size == width == height). | [
"Get",
"the",
"size",
"of",
"the",
"field",
"(size",
"==",
"width",
"==",
"height)."
] | def size(self):
return len(self.level_map) | ['def', 'size(self):', 'return', 'len(self.level_map)'] | 352,102 |
pipermerriam/flex | common.py | generate_type_validator | generate_type_validator | Generates a callable validator for the given type or iterable of types. | [
"Generates",
"a",
"callable",
"validator",
"for",
"the",
"given",
"type",
"or",
"iterable",
"of",
"types."
] | def generate_type_validator(type_, **kwargs):
if is_non_string_iterable(type_):
types = tuple(type_)
else:
types = (type_,)
if kwargs.get('x-nullable', False) and NULL not in types:
types = types + (NULL,)
return functools.partial(validate_type, types=types) | ['def', 'generate_type_validator(type_,', '**kwargs):', 'if', 'is_non_string_iterable(type_):', 'types', '=', 'tuple(type_)', 'else:', 'types', '=', '(type_,)', 'if', "kwargs.get('x-nullable',", 'False)', 'and', 'NULL', 'not', 'in', 'types:', 'types', '=', 'types', '+', '(NULL,)', 'return', 'functools.partial(validate_... | 211,293 |
arshpreetsingh/quantopian-machinelearning | base.py | Index.inferred_type | inferred_type | Return a string of the type inferred from the values. | [
"Return",
"a",
"string",
"of",
"the",
"type",
"inferred",
"from",
"the",
"values."
] | def inferred_type(self):
return lib.infer_dtype(self, skipna=False) | ['def', 'inferred_type(self):', 'return', 'lib.infer_dtype(self,', 'skipna=False)'] | 890,055 |
rudranil723/mini-main | face.py | GenericStub.inline_stream_stream | inline_stream_stream | Invokes a stream-request-stream-response method. | [
"Invokes",
"a",
"stream-request-stream-response",
"method."
] | def inline_stream_stream(self, group, method, request_iterator, timeout, metadata=None, protocol_options=None):
raise NotImplementedError() | ['def', 'inline_stream_stream(self,', 'group,', 'method,', 'request_iterator,', 'timeout,', 'metadata=None,', 'protocol_options=None):', 'raise', 'NotImplementedError()'] | 318,709 |
oandrienko/fast-semantic-segmentation | pspnet_architecture.py | PSPNetFeatureExtractor.extract_features | extract_features | Extracts half resolution features. | [
"Extracts",
"half",
"resolution",
"features."
] | def extract_features(self, preprocessed_inputs, scope=None):
with tf.variable_scope(scope, values=[preprocessed_inputs], reuse=tf.AUTO_REUSE):
return self._extract_features(preprocessed_inputs, scope) | ['def', 'extract_features(self,', 'preprocessed_inputs,', 'scope=None):', 'with', 'tf.variable_scope(scope,', 'values=[preprocessed_inputs],', 'reuse=tf.AUTO_REUSE):', 'return', 'self._extract_features(preprocessed_inputs,', 'scope)'] | 559,629 |
Megvii-BaseDetection/cvpods | transform_gen.py | check_dtype | check_dtype | Check the image data type and dimensions to ensure that transforms can be applied on it. | [
"Check",
"the",
"image",
"data",
"type",
"and",
"dimensions",
"to",
"ensure",
"that",
"transforms",
"can",
"be",
"applied",
"on",
"it."
] | def check_dtype(img):
assert isinstance(img, np.ndarray), '[TransformGen] Needs an numpy array, but got a {}!'.format(type(img))
assert not isinstance(img.dtype, np.integer) or img.dtype == np.uint8, '[TransformGen] Got image of type {}, use uint8 or floating points instead!'.format(img.dtype)
assert img.nd... | ['def', 'check_dtype(img):', 'assert', 'isinstance(img,', 'np.ndarray),', "'[TransformGen]", 'Needs', 'an', 'numpy', 'array,', 'but', 'got', 'a', "{}!'.format(type(img))", 'assert', 'not', 'isinstance(img.dtype,', 'np.integer)', 'or', 'img.dtype', '==', 'np.uint8,', "'[TransformGen]", 'Got', 'image', 'of', 'type', '{},... | 510,903 |
tianyoul/AI-Robotics-ComputerVision | libardrone.py | at_config_ids | at_config_ids | Set configuration parameters of the drone. | [
"Set",
"configuration",
"parameters",
"of",
"the",
"drone."
] | def at_config_ids(seq, value):
at('CONFIG_IDS', seq, value) | ['def', 'at_config_ids(seq,', 'value):', "at('CONFIG_IDS',", 'seq,', 'value)'] | 412,063 |
nasaharvest/openmapflow | ee_exporter.py | get_ee_task_list | get_ee_task_list | Gets a list of all active tasks in the EE task list. | [
"Gets",
"a",
"list",
"of",
"all",
"active",
"tasks",
"in",
"the",
"EE",
"task",
"list."
] | def get_ee_task_list(key: str='description') -> List[str]:
task_list = ee.data.getTaskList()
return [task[key] for task in tqdm(task_list, desc='Loading Earth Engine tasks') if task['state'] in ['READY', 'RUNNING', 'FAILED']] | ['def', 'get_ee_task_list(key:', "str='description')", '->', 'List[str]:', 'task_list', '=', 'ee.data.getTaskList()', 'return', '[task[key]', 'for', 'task', 'in', 'tqdm(task_list,', "desc='Loading", 'Earth', 'Engine', "tasks')", 'if', "task['state']", 'in', "['READY',", "'RUNNING',", "'FAILED']]"] | 757,119 |
XuelianCheng/SLT-Net | Res2Net_v1b.py | res2net50_v1b_26w_4s | res2net50_v1b_26w_4s | Constructs a Res2Net-50_v1b_26w_4s lib. | [
"Constructs",
"a",
"Res2Net-50_v1b_26w_4s",
"lib."
] | def res2net50_v1b_26w_4s(pretrained=False, **kwargs):
model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=26, scale=4, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s'], map_location='cpu'))
return model | ['def', 'res2net50_v1b_26w_4s(pretrained=False,', '**kwargs):', 'model', '=', 'Res2Net(Bottle2neck,', '[3,', '4,', '6,', '3],', 'baseWidth=26,', 'scale=4,', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s'],", "map_location='cpu'))", 'return', 'model'] | 878,417 |
caiiiac/Machine-Learning-with-Python | patches.py | FancyArrowPatch.get_mutation_aspect | get_mutation_aspect | Return the aspect ratio of the bbox mutation. | [
"Return",
"the",
"aspect",
"ratio",
"of",
"the",
"bbox",
"mutation."
] | def get_mutation_aspect(self):
return self._mutation_aspect | ['def', 'get_mutation_aspect(self):', 'return', 'self._mutation_aspect'] | 715,826 |
mkusner/grammarVAE | cmodule.py | get_lib_extension | get_lib_extension | Return the platform-dependent extension for compiled modules. | [
"Return",
"the",
"platform-dependent",
"extension",
"for",
"compiled",
"modules."
] | def get_lib_extension():
if sys.platform in ['win32', 'cygwin']:
return 'pyd'
else:
return 'so' | ['def', 'get_lib_extension():', 'if', 'sys.platform', 'in', "['win32',", "'cygwin']:", 'return', "'pyd'", 'else:', 'return', "'so'"] | 579,226 |
TonyLianLong/VAI-ReinforcementLearning | cheetah.py | run | run | Returns the run task. | [
"Returns",
"the",
"run",
"task."
] | def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None, setting_kwargs=None):
physics = Physics.from_xml_string(*common.settings.get_model_and_assets_from_setting_kwargs('cheetah.xml', setting_kwargs))
task = Cheetah(random=random)
environment_kwargs = environment_kwargs or {}
retu... | ['def', 'run(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None,', 'setting_kwargs=None):', 'physics', '=', "Physics.from_xml_string(*common.settings.get_model_and_assets_from_setting_kwargs('cheetah.xml',", 'setting_kwargs))', 'task', '=', 'Cheetah(random=random)', 'environment_kwargs', '=', 'e... | 440,834 |
thaines/helit | smp.py | SMP.setSampleCount | setSampleCount | Sets the number of samples to use when approximating the integral. | [
"Sets",
"the",
"number",
"of",
"samples",
"to",
"use",
"when",
"approximating",
"the",
"integral."
] | def setSampleCount(self, count):
self.sampleCount = count | ['def', 'setSampleCount(self,', 'count):', 'self.sampleCount', '=', 'count'] | 592,454 |
ryu-ed/SpaceInvaders_Ros | base.py | GlyphTextureAtlas.apply_blend_state | apply_blend_state | Set the OpenGL blend state for the glyphs in this texture. | [
"Set",
"the",
"OpenGL",
"blend",
"state",
"for",
"the",
"glyphs",
"in",
"this",
"texture."
] | def apply_blend_state(self):
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND) | ['def', 'apply_blend_state(self):', 'glBlendFunc(GL_SRC_ALPHA,', 'GL_ONE_MINUS_SRC_ALPHA)', 'glEnable(GL_BLEND)'] | 369,455 |
CORE-Robotics-Lab/SSRR | cma_es_lib.py | CMADataLogger.register | register | register a `CMAEvolutionStrategy` instance for logging, ``append=True`` appends to previous data logged under the same name, by default previous data are overwritten. | [
"register",
"a",
"`CMAEvolutionStrategy`",
"instance",
"for",
"logging,",
"``append=True``",
"appends",
"to",
"previous",
"data",
"logged",
"under",
"the",
"same",
"name,",
"by",
"default",
"previous",
"data",
"are",
"overwritten."
] | def register(self, es, append=None, modulo=None):
if not isinstance(es, CMAEvolutionStrategy):
raise TypeError('only class CMAEvolutionStrategy can be ' + 'registered for logging')
self.es = es
if append is not None:
self.append = append
if modulo is not None:
self.modulo = modul... | ['def', 'register(self,', 'es,', 'append=None,', 'modulo=None):', 'if', 'not', 'isinstance(es,', 'CMAEvolutionStrategy):', 'raise', "TypeError('only", 'class', 'CMAEvolutionStrategy', 'can', 'be', "'", '+', "'registered", 'for', "logging')", 'self.es', '=', 'es', 'if', 'append', 'is', 'not', 'None:', 'self.append', '='... | 382,638 |
enuguru/artificial_intelligence_and_machine_learning | misc.py | bool_or_none | bool_or_none | Return bool(b), but preserve None. | [
"Return",
"bool(b),",
"but",
"preserve",
"None."
] | def bool_or_none(b):
if b is None:
return None
else:
return bool(b) | ['def', 'bool_or_none(b):', 'if', 'b', 'is', 'None:', 'return', 'None', 'else:', 'return', 'bool(b)'] | 157,470 |
Kvatsx/Artificial-Intelligence-Assignments | textpath.py | TextToPath.get_glyphs_mathtext | get_glyphs_mathtext | convert the string *s* to vertices and codes by parsing it with mathtext. | [
"convert",
"the",
"string",
"*s*",
"to",
"vertices",
"and",
"codes",
"by",
"parsing",
"it",
"with",
"mathtext."
] | def get_glyphs_mathtext(self, prop, s, glyph_map=None, return_new_glyphs_only=False):
prop = prop.copy()
prop.set_size(self.FONT_SCALE)
(width, height, descent, glyphs, rects) = self.mathtext_parser.parse(s, self.DPI, prop)
if not glyph_map:
glyph_map = OrderedDict()
if return_new_glyphs_onl... | ['def', 'get_glyphs_mathtext(self,', 'prop,', 's,', 'glyph_map=None,', 'return_new_glyphs_only=False):', 'prop', '=', 'prop.copy()', 'prop.set_size(self.FONT_SCALE)', '(width,', 'height,', 'descent,', 'glyphs,', 'rects)', '=', 'self.mathtext_parser.parse(s,', 'self.DPI,', 'prop)', 'if', 'not', 'glyph_map:', 'glyph_map'... | 895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.