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 |
|---|---|---|---|---|---|---|---|---|
Trusted-AI/AIF360 | reject_option_classification.py | RejectOptionClassifier.predict | predict | Predict class labels for the given scores. | [
"Predict",
"class",
"labels",
"for",
"the",
"given",
"scores."
] | def predict(self, X):
scores = self.predict_proba(X)
pos_idx = np.nonzero(self.classes_ == self.pos_label_)[0][0]
y_pred = (scores[:, pos_idx] > self.threshold).astype(int)
return self.classes_[y_pred if pos_idx == 1 else 1 - y_pred] | ['def', 'predict(self,', 'X):', 'scores', '=', 'self.predict_proba(X)', 'pos_idx', '=', 'np.nonzero(self.classes_', '==', 'self.pos_label_)[0][0]', 'y_pred', '=', '(scores[:,', 'pos_idx]', '>', 'self.threshold).astype(int)', 'return', 'self.classes_[y_pred', 'if', 'pos_idx', '==', '1', 'else', '1', '-', 'y_pred]'] | 412,452 |
wandb/wandb | disk.py | Disk.is_available | is_available | Return a new instance of the CPU metrics. | [
"Return",
"a",
"new",
"instance",
"of",
"the",
"CPU",
"metrics."
] | def is_available(cls) -> bool:
return psutil is not None | ['def', 'is_available(cls)', '->', 'bool:', 'return', 'psutil', 'is', 'not', 'None'] | 941,726 |
pramodiperera/virtual-keyboard | logging.py | setup_logging | setup_logging | Configures and sets up all of the logging Returns the requested logging level, as its integer value. | [
"Configures",
"and",
"sets",
"up",
"all",
"of",
"the",
"logging",
"Returns",
"the",
"requested",
"logging",
"level,",
"as",
"its",
"integer",
"value."
] | def setup_logging(verbosity, no_color, user_log_file):
if verbosity >= 2:
level_number = logging.DEBUG
elif verbosity == 1:
level_number = VERBOSE
elif verbosity == -1:
level_number = logging.WARNING
elif verbosity == -2:
level_number = logging.ERROR
elif verbosity <=... | ['def', 'setup_logging(verbosity,', 'no_color,', 'user_log_file):', 'if', 'verbosity', '>=', '2:', 'level_number', '=', 'logging.DEBUG', 'elif', 'verbosity', '==', '1:', 'level_number', '=', 'VERBOSE', 'elif', 'verbosity', '==', '-1:', 'level_number', '=', 'logging.WARNING', 'elif', 'verbosity', '==', '-2:', 'level_num... | 932,077 |
openvinotoolkit/training_extensions | loss_dynamics_mixin.py | DetLossDynamicsTracker.export | export | Export loss dynamics statistics to Datumaro format. | [
"Export",
"loss",
"dynamics",
"statistics",
"to",
"Datumaro",
"format."
] | def export(self, output_path: str) -> None:
dfs = [pd.DataFrame.from_dict({k: (np.array([iter for (iter, _) in arr]), np.array([value for (_, value) in arr])) for (k, arr) in loss_dyns.items()}, orient='index', columns=['iters', f'loss_dynamics_{key.name}']) for (key, loss_dyns) in self._loss_dynamics.items()]
... | ['def', 'export(self,', 'output_path:', 'str)', '->', 'None:', 'dfs', '=', '[pd.DataFrame.from_dict({k:', '(np.array([iter', 'for', '(iter,', '_)', 'in', 'arr]),', 'np.array([value', 'for', '(_,', 'value)', 'in', 'arr]))', 'for', '(k,', 'arr)', 'in', 'loss_dyns.items()},', "orient='index',", "columns=['iters',", "f'los... | 918,130 |
deepmind/acme | mpo.py | compute_nonparametric_kl_from_normalized_weights | compute_nonparametric_kl_from_normalized_weights | Estimate the actualized KL between the non-parametric and target policies. | [
"Estimate",
"the",
"actualized",
"KL",
"between",
"the",
"non-parametric",
"and",
"target",
"policies."
] | def compute_nonparametric_kl_from_normalized_weights(normalized_weights: jnp.ndarray) -> jnp.ndarray:
num_action_samples = normalized_weights.shape[0] / 1.0
integrand = jnp.log(num_action_samples * normalized_weights + 1e-08)
return jnp.sum(normalized_weights * integrand, axis=0) | ['def', 'compute_nonparametric_kl_from_normalized_weights(normalized_weights:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'num_action_samples', '=', 'normalized_weights.shape[0]', '/', '1.0', 'integrand', '=', 'jnp.log(num_action_samples', '*', 'normalized_weights', '+', '1e-08)', 'return', 'jnp.sum(normalized_weights', '*... | 7,826 |
myothida/Supervised-Machine-Learning | test_openml.py | test_fetch_openml_equivalence_array_dataframe | test_fetch_openml_equivalence_array_dataframe | Check the equivalence of the dataset when using `as_frame=False` and `as_frame=True`. | [
"Check",
"the",
"equivalence",
"of",
"the",
"dataset",
"when",
"using",
"`as_frame=False`",
"and",
"`as_frame=True`."
] | def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser):
pytest.importorskip('pandas')
data_id = 61
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch_as_frame_true = fetch_openml(data_id=data_id, as_frame=True, cache=False, parser=parser)
bunch_as_frame_... | ['def', 'test_fetch_openml_equivalence_array_dataframe(monkeypatch,', 'parser):', "pytest.importorskip('pandas')", 'data_id', '=', '61', '_monkey_patch_webbased_functions(monkeypatch,', 'data_id,', 'gzip_response=True)', 'bunch_as_frame_true', '=', 'fetch_openml(data_id=data_id,', 'as_frame=True,', 'cache=False,', 'par... | 363,579 |
PaddlePaddle/PARL | atari_agent.py | AtariAgent.predict | predict | Predict an action when given an observation, a greedy action will be returned. | [
"Predict",
"an",
"action",
"when",
"given",
"an",
"observation,",
"a",
"greedy",
"action",
"will",
"be",
"returned."
] | def predict(self, obs):
if obs.ndim == 3:
obs = np.expand_dims(obs, axis=0)
obs = paddle.to_tensor(obs, dtype='float32')
pred_q = self.alg.predict(obs).detach().numpy().squeeze()
best_actions = np.where(pred_q == pred_q.max())[0]
act = np.random.choice(best_actions)
return act | ['def', 'predict(self,', 'obs):', 'if', 'obs.ndim', '==', '3:', 'obs', '=', 'np.expand_dims(obs,', 'axis=0)', 'obs', '=', 'paddle.to_tensor(obs,', "dtype='float32')", 'pred_q', '=', 'self.alg.predict(obs).detach().numpy().squeeze()', 'best_actions', '=', 'np.where(pred_q', '==', 'pred_q.max())[0]', 'act', '=', 'np.rand... | 277,779 |
myothida/Supervised-Machine-Learning | freetypePen.py | FreeTypePen.outline | outline | Converts the current contours to ``FT_Outline``. | [
"Converts",
"the",
"current",
"contours",
"to",
"``FT_Outline``."
] | def outline(self, transform=None, evenOdd=False):
transform = transform or Transform()
if not hasattr(transform, 'transformPoint'):
transform = Transform(*transform)
n_contours = len(self.contours)
n_points = sum((len(contour.points) for contour in self.contours))
points = []
for contour... | ['def', 'outline(self,', 'transform=None,', 'evenOdd=False):', 'transform', '=', 'transform', 'or', 'Transform()', 'if', 'not', 'hasattr(transform,', "'transformPoint'):", 'transform', '=', 'Transform(*transform)', 'n_contours', '=', 'len(self.contours)', 'n_points', '=', 'sum((len(contour.points)', 'for', 'contour', '... | 361,113 |
Kvatsx/Artificial-Intelligence-Assignments | console_widget.py | ConsoleWidget.eventFilter | eventFilter | Reimplemented to ensure a console-like behavior in the underlying text widgets. | [
"Reimplemented",
"to",
"ensure",
"a",
"console-like",
"behavior",
"in",
"the",
"underlying",
"text",
"widgets."
] | def eventFilter(self, obj, event):
etype = event.type()
self._trigger_is_complete_callback()
if etype == QtCore.QEvent.KeyPress:
key = event.key()
if self._control_key_down(event.modifiers()) and key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, se... | ['def', 'eventFilter(self,', 'obj,', 'event):', 'etype', '=', 'event.type()', 'self._trigger_is_complete_callback()', 'if', 'etype', '==', 'QtCore.QEvent.KeyPress:', 'key', '=', 'event.key()', 'if', 'self._control_key_down(event.modifiers())', 'and', 'key', 'in', 'self._ctrl_down_remap:', 'new_event', '=', 'QtGui.QKeyE... | 77,236 |
akandykeller/NeuralWaveMachines | networks.py | make_flexible_recurrent_net | make_flexible_recurrent_net | Commonly used for creating a flexible recurrences. | [
"Commonly",
"used",
"for",
"creating",
"a",
"flexible",
"recurrences."
] | def make_flexible_recurrent_net(core_type: str, net_type: str, output_dims: int, activate_final: bool=False, name: Optional[str]=None, net_kwargs: Optional[Mapping[str, Any]]=dict(), **latent_system_kwargs):
if net_type != 'mlp':
raise ValueError('We do not support convolutional recurrent nets atm.')
if... | ['def', 'make_flexible_recurrent_net(core_type:', 'str,', 'net_type:', 'str,', 'output_dims:', 'int,', 'activate_final:', 'bool=False,', 'name:', 'Optional[str]=None,', 'net_kwargs:', 'Optional[Mapping[str,', 'Any]]=dict(),', '**latent_system_kwargs):', 'if', 'net_type', '!=', "'mlp':", 'raise', "ValueError('We", 'do',... | 293,695 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_statistics.py | CoerceTest.check_coerce_to | check_coerce_to | Checks that type A coerces to B, including subclasses. | [
"Checks",
"that",
"type",
"A",
"coerces",
"to",
"B,",
"including",
"subclasses."
] | def check_coerce_to(self, A, B):
self.assertCoerceTo(A, B)
class SubclassOfA(A):
pass
self.assertCoerceTo(SubclassOfA, B)
class SubclassOfB(B):
pass
self.assertCoerceTo(A, SubclassOfB)
self.assertCoerceTo(SubclassOfA, SubclassOfB) | ['def', 'check_coerce_to(self,', 'A,', 'B):', 'self.assertCoerceTo(A,', 'B)', 'class', 'SubclassOfA(A):', 'pass', 'self.assertCoerceTo(SubclassOfA,', 'B)', 'class', 'SubclassOfB(B):', 'pass', 'self.assertCoerceTo(A,', 'SubclassOfB)', 'self.assertCoerceTo(SubclassOfA,', 'SubclassOfB)'] | 376,386 |
rishab-sharma/object_detection | mask_rcnn_heads.py | mask_rcnn_fcn_head_v1up4convs | mask_rcnn_fcn_head_v1up4convs | v1up design: 4 * (conv 3x3), convT 2x2. | [
"v1up",
"design:",
"4",
"*",
"(conv",
"3x3),",
"convT",
"2x2."
] | def mask_rcnn_fcn_head_v1up4convs(model, blob_in, dim_in, spatial_scale):
return mask_rcnn_fcn_head_v1upXconvs(model, blob_in, dim_in, spatial_scale, 4) | ['def', 'mask_rcnn_fcn_head_v1up4convs(model,', 'blob_in,', 'dim_in,', 'spatial_scale):', 'return', 'mask_rcnn_fcn_head_v1upXconvs(model,', 'blob_in,', 'dim_in,', 'spatial_scale,', '4)'] | 772,734 |
mvlearn/mvlearn | _testing.py | requires_module | requires_module | Skip a test if package is not available (decorator). | [
"Skip",
"a",
"test",
"if",
"package",
"is",
"not",
"available",
"(decorator)."
] | def requires_module(function, name, call=None):
import pytest
call = 'import %s' % name if call is None else call
reason = 'Test %s skipped, requires %s.' % (function.__name__, name)
try:
(exec(call) in globals(), locals())
except Exception as exc:
if len(str(exc)) > 0 and str(exc) !... | ['def', 'requires_module(function,', 'name,', 'call=None):', 'import', 'pytest', 'call', '=', "'import", "%s'", '%', 'name', 'if', 'call', 'is', 'None', 'else', 'call', 'reason', '=', "'Test", '%s', 'skipped,', 'requires', "%s.'", '%', '(function.__name__,', 'name)', 'try:', '(exec(call)', 'in', 'globals(),', 'locals()... | 651,406 |
weimin17/Object-Detection_HelmetDetection | resnet_run_loop.py | resnet_main | resnet_main | Shared main loop for ResNet Models. | [
"Shared",
"main",
"loop",
"for",
"ResNet",
"Models."
] | def resnet_main(flags_obj, model_function, input_function, dataset_name, shape=None):
model_helpers.apply_clean(flags.FLAGS)
os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
session_config = tf.ConfigProto(inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads, intra_op_parallelism_threads=flags... | ['def', 'resnet_main(flags_obj,', 'model_function,', 'input_function,', 'dataset_name,', 'shape=None):', 'model_helpers.apply_clean(flags.FLAGS)', "os.environ['TF_ENABLE_WINOGRAD_NONFUSED']", '=', "'1'", 'session_config', '=', 'tf.ConfigProto(inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads,', 'intra... | 761,129 |
gunthercox/ChatterBot | wrappers.py | BaseRequest.host_url | host_url | Just the host with scheme as IRI. | [
"Just",
"the",
"host",
"with",
"scheme",
"as",
"IRI."
] | def host_url(self):
return get_current_url(self.environ, host_only=True, trusted_hosts=self.trusted_hosts) | ['def', 'host_url(self):', 'return', 'get_current_url(self.environ,', 'host_only=True,', 'trusted_hosts=self.trusted_hosts)'] | 482,486 |
jimtin/Stock_Comparison | test_execute.py | TestExecute.normalize_output | normalize_output | Normalizes outputs for comparison. | [
"Normalizes",
"outputs",
"for",
"comparison."
] | def normalize_output(output):
output = dict(output)
if 'metadata' in output:
del output['metadata']
if 'text' in output:
output['text'] = re.sub(addr_pat, '<HEXADDR>', output['text'])
if 'text/plain' in output.get('data', {}):
output['data']['text/plain'] = re.sub(addr_pat, '<HEX... | ['def', 'normalize_output(output):', 'output', '=', 'dict(output)', 'if', "'metadata'", 'in', 'output:', 'del', "output['metadata']", 'if', "'text'", 'in', 'output:', "output['text']", '=', 're.sub(addr_pat,', "'<HEXADDR>',", "output['text'])", 'if', "'text/plain'", 'in', "output.get('data',", '{}):', "output['data']['... | 386,278 |
deepmind/meltingpot | clean_up.py | build | build | Build the clean_up substrate given roles. | [
"Build",
"the",
"clean_up",
"substrate",
"given",
"roles."
] | def build(roles: Sequence[str], config: config_dict.ConfigDict) -> Mapping[str, Any]:
del config
num_players = len(roles)
substrate_definition = dict(levelName='clean_up', levelDirectory='meltingpot/lua/levels', numPlayers=num_players, maxEpisodeLengthFrames=5000, spriteSize=8, topology='BOUNDED', simulatio... | ['def', 'build(roles:', 'Sequence[str],', 'config:', 'config_dict.ConfigDict)', '->', 'Mapping[str,', 'Any]:', 'del', 'config', 'num_players', '=', 'len(roles)', 'substrate_definition', '=', "dict(levelName='clean_up',", "levelDirectory='meltingpot/lua/levels',", 'numPlayers=num_players,', 'maxEpisodeLengthFrames=5000,... | 285,304 |
sunishsheth2009/ChatterBot | runtktests.py | check_tk_availability | check_tk_availability | Check that Tk is installed and available. | [
"Check",
"that",
"Tk",
"is",
"installed",
"and",
"available."
] | def check_tk_availability():
global _tk_unavailable
if _tk_unavailable is None:
_tk_unavailable = False
if sys.platform == 'darwin':
from ctypes import cdll, c_int, pointer, Structure
from ctypes.util import find_library
app_services = cdll.LoadLibrary(find_li... | ['def', 'check_tk_availability():', 'global', '_tk_unavailable', 'if', '_tk_unavailable', 'is', 'None:', '_tk_unavailable', '=', 'False', 'if', 'sys.platform', '==', "'darwin':", 'from', 'ctypes', 'import', 'cdll,', 'c_int,', 'pointer,', 'Structure', 'from', 'ctypes.util', 'import', 'find_library', 'app_services', '=',... | 528,289 |
GregorKobsik/Octree-Transformer | sample_utils_test.py | TestPrepareInputForNextLayer_Spatial2.test_correct_return_types_cpu | test_correct_return_types_cpu | Test if the function returns the correct output type on the cpu. | [
"Test",
"if",
"the",
"function",
"returns",
"the",
"correct",
"output",
"type",
"on",
"the",
"cpu."
] | def test_correct_return_types_cpu(self):
self.correct_return_types(device='cpu') | ['def', 'test_correct_return_types_cpu(self):', "self.correct_return_types(device='cpu')"] | 755,140 |
augmentedstartups/AS-One | lr_scheduler.py | warm_cos_lr | warm_cos_lr | Cosine learning rate with warm up. | [
"Cosine",
"learning",
"rate",
"with",
"warm",
"up."
] | def warm_cos_lr(lr, total_iters, warmup_total_iters, warmup_lr_start, iters):
if iters <= warmup_total_iters:
lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start
else:
lr *= 0.5 * (1.0 + math.cos(math.pi * (iters - warmup_total_iters) / (total_iters - warmup_total_i... | ['def', 'warm_cos_lr(lr,', 'total_iters,', 'warmup_total_iters,', 'warmup_lr_start,', 'iters):', 'if', 'iters', '<=', 'warmup_total_iters:', 'lr', '=', '(lr', '-', 'warmup_lr_start)', '*', 'iters', '/', 'float(warmup_total_iters)', '+', 'warmup_lr_start', 'else:', 'lr', '*=', '0.5', '*', '(1.0', '+', 'math.cos(math.pi'... | 402,321 |
deepmind/acme | networks.py | get_default_behavior_policy | get_default_behavior_policy | Selects action according to the training policy. | [
"Selects",
"action",
"according",
"to",
"the",
"training",
"policy."
] | def get_default_behavior_policy(networks: D4PGNetworks, config: d4pg_config.D4PGConfig) -> actor_core_lib.FeedForwardPolicy:
def behavior_policy(params: networks_lib.Params, key: networks_lib.PRNGKey, observation: types.NestedArray):
action = networks.policy_network.apply(params, observation)
if co... | ['def', 'get_default_behavior_policy(networks:', 'D4PGNetworks,', 'config:', 'd4pg_config.D4PGConfig)', '->', 'actor_core_lib.FeedForwardPolicy:', 'def', 'behavior_policy(params:', 'networks_lib.Params,', 'key:', 'networks_lib.PRNGKey,', 'observation:', 'types.NestedArray):', 'action', '=', 'networks.policy_network.app... | 8,085 |
openvinotoolkit/training_extensions | tiling.py | Tile.gen_tiles_single_img | gen_tiles_single_img | Generate tile annotation for a single image. | [
"Generate",
"tile",
"annotation",
"for",
"a",
"single",
"image."
] | def gen_tiles_single_img(self, result: Dict, dataset_idx: int) -> List[Dict]:
tile_list = []
self.random_select_gt(result, self.max_annotation)
gt_bboxes = result.get('gt_bboxes', np.zeros((0, 4), dtype=np.float32))
gt_masks = result.get('gt_masks', None)
gt_bboxes_ignore = result.get('gt_bboxes_ign... | ['def', 'gen_tiles_single_img(self,', 'result:', 'Dict,', 'dataset_idx:', 'int)', '->', 'List[Dict]:', 'tile_list', '=', '[]', 'self.random_select_gt(result,', 'self.max_annotation)', 'gt_bboxes', '=', "result.get('gt_bboxes',", 'np.zeros((0,', '4),', 'dtype=np.float32))', 'gt_masks', '=', "result.get('gt_masks',", 'No... | 918,066 |
rudranil723/mini-main | symbolic.py | as_string | as_string | Return object as STRING expression (string literal constant). | [
"Return",
"object",
"as",
"STRING",
"expression",
"(string",
"literal",
"constant)."
] | def as_string(obj, kind=1):
return Expr(Op.STRING, (obj, kind)) | ['def', 'as_string(obj,', 'kind=1):', 'return', 'Expr(Op.STRING,', '(obj,', 'kind))'] | 322,678 |
PacktPublishing/OpenCV-Computer--Projects-with-Python | utils.py | createCompositeFunc | createCompositeFunc | Return a composite of two functions. | [
"Return",
"a",
"composite",
"of",
"two",
"functions."
] | def createCompositeFunc(func0, func1):
if func0 is None:
return func1
if func1 is None:
return func0
return lambda x: func0(func1(x)) | ['def', 'createCompositeFunc(func0,', 'func1):', 'if', 'func0', 'is', 'None:', 'return', 'func1', 'if', 'func1', 'is', 'None:', 'return', 'func0', 'return', 'lambda', 'x:', 'func0(func1(x))'] | 756,955 |
yinyunie/ScenePriors | test_pointclouds.py | TestPointclouds.init_cloud | init_cloud | Function to generate a Pointclouds object of N meshes with random number of points. | [
"Function",
"to",
"generate",
"a",
"Pointclouds",
"object",
"of",
"N",
"meshes",
"with",
"random",
"number",
"of",
"points."
] | def init_cloud(num_clouds: int=3, max_points: int=100, channels: int=4, lists_to_tensors: bool=False, with_normals: bool=True, with_features: bool=True, min_points: int=0, requires_grad: bool=False):
device = torch.device('cuda:0')
p = torch.randint(low=min_points, high=max_points, size=(num_clouds,))
if li... | ['def', 'init_cloud(num_clouds:', 'int=3,', 'max_points:', 'int=100,', 'channels:', 'int=4,', 'lists_to_tensors:', 'bool=False,', 'with_normals:', 'bool=True,', 'with_features:', 'bool=True,', 'min_points:', 'int=0,', 'requires_grad:', 'bool=False):', 'device', '=', "torch.device('cuda:0')", 'p', '=', 'torch.randint(lo... | 330,060 |
microsoft/InnerEye-DeepLearning | test_segmentation_configs.py | test_head_and_neck_paper_with_mismatched_colours_raises | test_head_and_neck_paper_with_mismatched_colours_raises | Check that passing too many colours raises ValueError exception. | [
"Check",
"that",
"passing",
"too",
"many",
"colours",
"raises",
"ValueError",
"exception."
] | def test_head_and_neck_paper_with_mismatched_colours_raises() -> None:
ground_truth_count = len(DEFAULT_HEAD_AND_NECK_GROUND_TRUTH_IDS) - 2
colours = generate_random_colours_list(RANDOM_COLOUR_GENERATOR, ground_truth_count - 1)
with pytest.raises(ValueError) as e:
assert HeadAndNeckPaper(local_datas... | ['def', 'test_head_and_neck_paper_with_mismatched_colours_raises()', '->', 'None:', 'ground_truth_count', '=', 'len(DEFAULT_HEAD_AND_NECK_GROUND_TRUTH_IDS)', '-', '2', 'colours', '=', 'generate_random_colours_list(RANDOM_COLOUR_GENERATOR,', 'ground_truth_count', '-', '1)', 'with', 'pytest.raises(ValueError)', 'as', 'e:... | 613,555 |
seltzerfish/guardyn | nanopb.py | generate | generate | Add Builder for nanopb protos. | [
"Add",
"Builder",
"for",
"nanopb",
"protos."
] | def generate(env):
env['NANOPB'] = _detect_nanopb(env)
env['PROTOC'] = _detect_protoc(env)
env['PROTOCFLAGS'] = _detect_protocflags(env)
env.SetDefault(PROTOCPATH=['.', os.path.join(env['NANOPB'], 'generator', 'proto')])
env.SetDefault(NANOPB_PROTO_CMD='$PROTOC $PROTOCFLAGS --nanopb_out=. $SOURCES')... | ['def', 'generate(env):', "env['NANOPB']", '=', '_detect_nanopb(env)', "env['PROTOC']", '=', '_detect_protoc(env)', "env['PROTOCFLAGS']", '=', '_detect_protocflags(env)', "env.SetDefault(PROTOCPATH=['.',", "os.path.join(env['NANOPB'],", "'generator',", "'proto')])", "env.SetDefault(NANOPB_PROTO_CMD='$PROTOC", '$PROTOCF... | 572,374 |
shery322/Lunar-Lander-ANN | filelist.py | FileList.debug_print | debug_print | Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. | [
"Print",
"'msg'",
"to",
"stdout",
"if",
"the",
"global",
"DEBUG",
"(taken",
"from",
"the",
"DISTUTILS_DEBUG",
"environment",
"variable)",
"flag",
"is",
"true."
] | def debug_print(self, msg):
from distutils.debug import DEBUG
if DEBUG:
print(msg) | ['def', 'debug_print(self,', 'msg):', 'from', 'distutils.debug', 'import', 'DEBUG', 'if', 'DEBUG:', 'print(msg)'] | 619,609 |
chribsen/simple-machine-learning-examples | pool.py | has_shareable_memory | has_shareable_memory | Return True if a is backed by some mmap buffer directly or not. | [
"Return",
"True",
"if",
"a",
"is",
"backed",
"by",
"some",
"mmap",
"buffer",
"directly",
"or",
"not."
] | def has_shareable_memory(a):
return _get_backing_memmap(a) is not None | ['def', 'has_shareable_memory(a):', 'return', '_get_backing_memmap(a)', 'is', 'not', 'None'] | 939,297 |
GGmorello/fl_gan | mnist_shard_descriptor.py | MnistShardDescriptor.target_shape | target_shape | Return the target shape info. | [
"Return",
"the",
"target",
"shape",
"info."
] | def target_shape(self):
return ['1'] | ['def', 'target_shape(self):', 'return', "['1']"] | 607,930 |
keras-team/keras-cv | densenet_aliases.py | DenseNet121Backbone.presets | presets | Dictionary of preset names and configurations. | [
"Dictionary",
"of",
"preset",
"names",
"and",
"configurations."
] | def presets(cls):
return {'densenet121_imagenet': copy.deepcopy(backbone_presets['densenet121_imagenet'])} | ['def', 'presets(cls):', 'return', "{'densenet121_imagenet':", "copy.deepcopy(backbone_presets['densenet121_imagenet'])}"] | 595,148 |
lambert-x/RVC_Segmentation | class_names.py | voc_palette | voc_palette | Pascal VOC palette for external use. | [
"Pascal",
"VOC",
"palette",
"for",
"external",
"use."
] | def voc_palette():
return [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64,... | ['def', 'voc_palette():', 'return', '[[0,', '0,', '0],', '[128,', '0,', '0],', '[0,', '128,', '0],', '[128,', '128,', '0],', '[0,', '0,', '128],', '[128,', '0,', '128],', '[0,', '128,', '128],', '[128,', '128,', '128],', '[64,', '0,', '0],', '[192,', '0,', '0],', '[64,', '128,', '0],', '[192,', '128,', '0],', '[64,', '... | 828,339 |
asyml/texar-pytorch | t5_decoder.py | T5Decoder.initialize_blocks | initialize_blocks | Helper function to initialize blocks. | [
"Helper",
"function",
"to",
"initialize",
"blocks."
] | def initialize_blocks(self):
for i in range(self._hparams.num_blocks):
attn_module = MultiheadRPRAttention(self._input_size, self._hparams.multihead_attention, stores_relative_position=bool(i == 0))
if self._hparams.dim != attn_module.output_size:
raise ValueError('The output dimension o... | ['def', 'initialize_blocks(self):', 'for', 'i', 'in', 'range(self._hparams.num_blocks):', 'attn_module', '=', 'MultiheadRPRAttention(self._input_size,', 'self._hparams.multihead_attention,', 'stores_relative_position=bool(i', '==', '0))', 'if', 'self._hparams.dim', '!=', 'attn_module.output_size:', 'raise', "ValueError... | 925,197 |
43Carrig/recurrent_neural_networks_practice | random_forest.py | get_model_fn | get_model_fn | Return a model function given a way to construct a graph builder. | [
"Return",
"a",
"model",
"function",
"given",
"a",
"way",
"to",
"construct",
"a",
"graph",
"builder."
] | def get_model_fn(params, graph_builder_class, device_assigner, feature_columns=None, weights_name=None, model_head=None, keys_name=None, early_stopping_rounds=100, early_stopping_loss_threshold=0.001, num_trainers=1, trainer_id=0, report_feature_importances=False, local_eval=False, head_scope=None, include_all_in_servi... | ['def', 'get_model_fn(params,', 'graph_builder_class,', 'device_assigner,', 'feature_columns=None,', 'weights_name=None,', 'model_head=None,', 'keys_name=None,', 'early_stopping_rounds=100,', 'early_stopping_loss_threshold=0.001,', 'num_trainers=1,', 'trainer_id=0,', 'report_feature_importances=False,', 'local_eval=Fal... | 335,302 |
greydanus/mr_london | pildriver.py | PILDriver.do_lighter | do_lighter | usage: lighter <image:pic1> <image:pic2> Pop the two top images, push an image of the lighter pixels of both. | [
"usage:",
"lighter",
"<image:pic1>",
"<image:pic2>",
"Pop",
"the",
"two",
"top",
"images,",
"push",
"an",
"image",
"of",
"the",
"lighter",
"pixels",
"of",
"both."
] | def do_lighter(self):
from PIL import ImageChops
image1 = self.do_pop()
image2 = self.do_pop()
self.push(ImageChops.lighter(image1, image2)) | ['def', 'do_lighter(self):', 'from', 'PIL', 'import', 'ImageChops', 'image1', '=', 'self.do_pop()', 'image2', '=', 'self.do_pop()', 'self.push(ImageChops.lighter(image1,', 'image2))'] | 241,761 |
instadeepai/jumanji | conftest.py | path1 | path1 | Returns: the path of agent 1. | [
"Returns:",
"the",
"path",
"of",
"agent",
"1."
] | def path1() -> chex.Numeric:
return get_path(1) | ['def', 'path1()', '->', 'chex.Numeric:', 'return', 'get_path(1)'] | 594,278 |
google-research/scenic | test_attention.py | MultiScaleDeformableAttentionTest.test_ms_deformable_attn_output_shape | test_ms_deformable_attn_output_shape | Test MultiScaleDeformableAttention output shape. | [
"Test",
"MultiScaleDeformableAttention",
"output",
"shape."
] | def test_ms_deformable_attn_output_shape(self, ref_dim, shapes, embed_dim, num_heads):
rng = random.PRNGKey(8877)
(bs, len_q, num_points, num_levels) = (2, 10, 1, len(shapes))
len_v = np.array(shapes).prod(axis=-1).sum()
query = jnp.array(np.random.normal(size=(bs, len_q, embed_dim)))
ref_points = j... | ['def', 'test_ms_deformable_attn_output_shape(self,', 'ref_dim,', 'shapes,', 'embed_dim,', 'num_heads):', 'rng', '=', 'random.PRNGKey(8877)', '(bs,', 'len_q,', 'num_points,', 'num_levels)', '=', '(2,', '10,', '1,', 'len(shapes))', 'len_v', '=', 'np.array(shapes).prod(axis=-1).sum()', 'query', '=', 'jnp.array(np.random.... | 846,614 |
tomcatmanager/tomcatmanager | models.py | TomcatApplication.directory | directory | The directory on the server where this application resides. | [
"The",
"directory",
"on",
"the",
"server",
"where",
"this",
"application",
"resides."
] | def directory(self):
return self._directory | ['def', 'directory(self):', 'return', 'self._directory'] | 355,607 |
ifwe/digsby | UberCombo.py | UberCombo.GetCount | GetCount | Returns the number of choices in this combobox. | [
"Returns",
"the",
"number",
"of",
"choices",
"in",
"this",
"combobox."
] | def GetCount(self):
return self.menu.Count | ['def', 'GetCount(self):', 'return', 'self.menu.Count'] | 185,655 |
trenton3983/Programming_Computer__with_Python | lktrack.py | LKTracker.track_points | track_points | Track the detected features. | [
"Track",
"the",
"detected",
"features."
] | def track_points(self):
if self.features != []:
self.step()
self.image = cv2.imread(self.imnames[self.current_frame])
self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
tmp = float32(self.features).reshape(-1, 1, 2)
(features, status, track_error) = cv2.calcOpticalFlowP... | ['def', 'track_points(self):', 'if', 'self.features', '!=', '[]:', 'self.step()', 'self.image', '=', 'cv2.imread(self.imnames[self.current_frame])', 'self.gray', '=', 'cv2.cvtColor(self.image,', 'cv2.COLOR_BGR2GRAY)', 'tmp', '=', 'float32(self.features).reshape(-1,', '1,', '2)', '(features,', 'status,', 'track_error)',... | 817,298 |
TARGET-SIDE-DATA-AUG/TSDASG | trainer.py | Trainer.valid_step | valid_step | Do forward pass in evaluation mode. | [
"Do",
"forward",
"pass",
"in",
"evaluation",
"mode."
] | def valid_step(self, sample, raise_oom=False):
if self.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous('valid_step')
xm.mark_step()
with torch.no_grad():
self.model.eval()
self.criterion.eval()
sample = self._prepare_sample(sample)
if sample is No... | ['def', 'valid_step(self,', 'sample,', 'raise_oom=False):', 'if', 'self.tpu:', 'import', 'torch_xla.core.xla_model', 'as', 'xm', "xm.rendezvous('valid_step')", 'xm.mark_step()', 'with', 'torch.no_grad():', 'self.model.eval()', 'self.criterion.eval()', 'sample', '=', 'self._prepare_sample(sample)', 'if', 'sample', 'is',... | 951,889 |
pdebench/PDEBench | utils.py | expand_path | expand_path | Resolve a path that may contain variables and user home directory references. | [
"Resolve",
"a",
"path",
"that",
"may",
"contain",
"variables",
"and",
"user",
"home",
"directory",
"references."
] | def expand_path(path, unique=True):
return os.path.expandvars(os.path.expanduser(path)) | ['def', 'expand_path(path,', 'unique=True):', 'return', 'os.path.expandvars(os.path.expanduser(path))'] | 765,860 |
zbwxp/NRD_decoder | test.py | collect_results_gpu | collect_results_gpu | Collect results with GPU. | [
"Collect",
"results",
"with",
"GPU."
] | def collect_results_gpu(result_part, size):
(rank, world_size) = get_dist_info()
part_tensor = torch.tensor(bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda')
shape_tensor = torch.tensor(part_tensor.shape, device='cuda')
shape_list = [shape_tensor.clone() for _ in range(world_size)]... | ['def', 'collect_results_gpu(result_part,', 'size):', '(rank,', 'world_size)', '=', 'get_dist_info()', 'part_tensor', '=', 'torch.tensor(bytearray(pickle.dumps(result_part)),', 'dtype=torch.uint8,', "device='cuda')", 'shape_tensor', '=', 'torch.tensor(part_tensor.shape,', "device='cuda')", 'shape_list', '=', '[shape_te... | 729,814 |
weimin17/Object-Detection_HelmetDetection | n_gram.py | construct_ngrams_dict | construct_ngrams_dict | Construct a ngram dictionary which maps an ngram tuple to the number of times it appears in the text. | [
"Construct",
"a",
"ngram",
"dictionary",
"which",
"maps",
"an",
"ngram",
"tuple",
"to",
"the",
"number",
"of",
"times",
"it",
"appears",
"in",
"the",
"text."
] | def construct_ngrams_dict(ngrams_list):
counts = {}
for t in ngrams_list:
key = hash_function(t)
if key in counts:
counts[key] += 1
else:
counts[key] = 1
return counts | ['def', 'construct_ngrams_dict(ngrams_list):', 'counts', '=', '{}', 'for', 't', 'in', 'ngrams_list:', 'key', '=', 'hash_function(t)', 'if', 'key', 'in', 'counts:', 'counts[key]', '+=', '1', 'else:', 'counts[key]', '=', '1', 'return', 'counts'] | 758,079 |
rudranil723/mini-main | errcheck.py | check_geom | check_geom | Check a function that returns a geometry. | [
"Check",
"a",
"function",
"that",
"returns",
"a",
"geometry."
] | def check_geom(result, func, cargs):
if isinstance(result, int):
result = c_void_p(result)
if not result:
raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__)
return result | ['def', 'check_geom(result,', 'func,', 'cargs):', 'if', 'isinstance(result,', 'int):', 'result', '=', 'c_void_p(result)', 'if', 'not', 'result:', 'raise', "GDALException('Invalid", 'geometry', 'pointer', 'returned', 'from', '"%s".\'', '%', 'func.__name__)', 'return', 'result'] | 315,199 |
sshleifer/object_detection_kitti | classify_image.py | run_inference_on_image | run_inference_on_image | Runs inference on an image. | [
"Runs",
"inference",
"on",
"an",
"image."
] | def run_inference_on_image(image):
if not tf.gfile.Exists(image):
tf.logging.fatal('File does not exist %s', image)
image_data = tf.gfile.FastGFile(image, 'rb').read()
create_graph()
with tf.Session() as sess:
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
prediction... | ['def', 'run_inference_on_image(image):', 'if', 'not', 'tf.gfile.Exists(image):', "tf.logging.fatal('File", 'does', 'not', 'exist', "%s',", 'image)', 'image_data', '=', 'tf.gfile.FastGFile(image,', "'rb').read()", 'create_graph()', 'with', 'tf.Session()', 'as', 'sess:', 'softmax_tensor', '=', "sess.graph.get_tensor_by_... | 795,835 |
Christopher-Thornton/hmni | preprocess.py | CategoricalVocabulary.freeze | freeze | Freezes the vocabulary, after which new words return unknown token id. | [
"Freezes",
"the",
"vocabulary,",
"after",
"which",
"new",
"words",
"return",
"unknown",
"token",
"id."
] | def freeze(self, freeze=True):
self._freeze = freeze | ['def', 'freeze(self,', 'freeze=True):', 'self._freeze', '=', 'freeze'] | 593,369 |
enuguru/artificial_intelligence_and_machine_learning | etxrd.py | sortedURIs | sortedURIs | Given a Service element, return a list of the contents of all URI tags in priority order. | [
"Given",
"a",
"Service",
"element,",
"return",
"a",
"list",
"of",
"the",
"contents",
"of",
"all",
"URI",
"tags",
"in",
"priority",
"order."
] | def sortedURIs(service_element):
return [uri_element.text for uri_element in prioSort(service_element.findall(uri_tag))] | ['def', 'sortedURIs(service_element):', 'return', '[uri_element.text', 'for', 'uri_element', 'in', 'prioSort(service_element.findall(uri_tag))]'] | 159,542 |
SamHusbands21/thesis | base_layers.py | weight_variable | weight_variable | Initialize weight with: w = truncated normal * sqrt(2 / n) where n = number of neurons feeding into it. | [
"Initialize",
"weight",
"with:",
"w",
"=",
"truncated",
"normal",
"*",
"sqrt(2",
"/",
"n)",
"where",
"n",
"=",
"number",
"of",
"neurons",
"feeding",
"into",
"it."
] | def weight_variable(shape):
initializer = tf.contrib.layers.xavier_initializer()
initial = initializer(shape)
return tf.Variable(initial) | ['def', 'weight_variable(shape):', 'initializer', '=', 'tf.contrib.layers.xavier_initializer()', 'initial', '=', 'initializer(shape)', 'return', 'tf.Variable(initial)'] | 354,697 |
cassianobecker/tgcn | utils.py | TextRCV1.show_classes_per_doc | show_classes_per_doc | Number of classes per document. | [
"Number",
"of",
"classes",
"per",
"document."
] | def show_classes_per_doc(self):
classes_per_doc = np.array(self.target.sum(axis=1)).squeeze()
plt.figure(figsize=(17, 5))
plt.plot(sorted(classes_per_doc[::-1]), '.') | ['def', 'show_classes_per_doc(self):', 'classes_per_doc', '=', 'np.array(self.target.sum(axis=1)).squeeze()', 'plt.figure(figsize=(17,', '5))', 'plt.plot(sorted(classes_per_doc[::-1]),', "'.')"] | 367,263 |
muhanzhang/D-VAE | test_extra_ops.py | test_Unique.test_infer_shape_vector | test_infer_shape_vector | Testing the infer_shape with a vector. | [
"Testing",
"the",
"infer_shape",
"with",
"a",
"vector."
] | def test_infer_shape_vector(self):
x = theano.tensor.vector()
for op in self.ops:
if not op.return_inverse:
continue
if op.return_index:
f = op(x)[2]
else:
f = op(x)[1]
self._compile_and_check([x], [f], [np.asarray(np.array([2, 1, 3, 2]), dtype... | ['def', 'test_infer_shape_vector(self):', 'x', '=', 'theano.tensor.vector()', 'for', 'op', 'in', 'self.ops:', 'if', 'not', 'op.return_inverse:', 'continue', 'if', 'op.return_index:', 'f', '=', 'op(x)[2]', 'else:', 'f', '=', 'op(x)[1]', 'self._compile_and_check([x],', '[f],', '[np.asarray(np.array([2,', '1,', '3,', '2])... | 525,869 |
thaines/helit | params.py | Params.setLinear | setLinear | Sets it to use the linear kernel. | [
"Sets",
"it",
"to",
"use",
"the",
"linear",
"kernel."
] | def setLinear(self):
self.kernel = Kernel.Linear | ['def', 'setLinear(self):', 'self.kernel', '=', 'Kernel.Linear'] | 592,525 |
tensorflow/agents | test_colabs.py | run | run | Runs all notebooks and reports results. | [
"Runs",
"all",
"notebooks",
"and",
"reports",
"results."
] | def run():
os.makedirs(FLAGS.output_dir, exist_ok=True)
if FLAGS.single_colab:
filenames = [FLAGS.single_colab]
else:
filenames = get_test_suite()
passed = []
failed = []
filenames.sort()
for filename in filenames:
logging.info('Testing %s ...', filename)
resu... | ['def', 'run():', 'os.makedirs(FLAGS.output_dir,', 'exist_ok=True)', 'if', 'FLAGS.single_colab:', 'filenames', '=', '[FLAGS.single_colab]', 'else:', 'filenames', '=', 'get_test_suite()', 'passed', '=', '[]', 'failed', '=', '[]', 'filenames.sort()', 'for', 'filename', 'in', 'filenames:', "logging.info('Testing", '%s', "... | 23,173 |
caglar/autoencoders | layer.py | LogisticRegressionLayer.crossentropy_categorical | crossentropy_categorical | Find the categorical crossentropy. | [
"Find",
"the",
"categorical",
"crossentropy."
] | def crossentropy_categorical(self, y):
return T.mean(T.nnet.categorical_crossentropy(self.p_y_given_x, y)) | ['def', 'crossentropy_categorical(self,', 'y):', 'return', 'T.mean(T.nnet.categorical_crossentropy(self.p_y_given_x,', 'y))'] | 419,539 |
rifqind/Agent-Programs-3KS1 | iostream_test.py | TestIOStreamWebMixin.test_future_interface | test_future_interface | Basic test of IOStream's ability to return Futures. | [
"Basic",
"test",
"of",
"IOStream's",
"ability",
"to",
"return",
"Futures."
] | def test_future_interface(self):
stream = self._make_client_iostream()
connect_result = (yield stream.connect(('127.0.0.1', self.get_http_port())))
self.assertIs(connect_result, stream)
yield stream.write(b'GET / HTTP/1.0\r\n\r\n')
first_line = (yield stream.read_until(b'\r\n'))
self.assertEqual... | ['def', 'test_future_interface(self):', 'stream', '=', 'self._make_client_iostream()', 'connect_result', '=', '(yield', "stream.connect(('127.0.0.1',", 'self.get_http_port())))', 'self.assertIs(connect_result,', 'stream)', 'yield', "stream.write(b'GET", '/', "HTTP/1.0\\r\\n\\r\\n')", 'first_line', '=', '(yield', "strea... | 21,547 |
tensorflow/agents | py_policy.py | PyPolicy.action | action | Generates next action given the time_step and policy_state. | [
"Generates",
"next",
"action",
"given",
"the",
"time_step",
"and",
"policy_state."
] | def action(self, time_step: ts.TimeStep, policy_state: types.NestedArray=(), seed: Optional[types.Seed]=None) -> policy_step.PolicyStep:
if seed is not None:
return self._action(time_step, policy_state, seed=seed)
else:
return self._action(time_step, policy_state) | ['def', 'action(self,', 'time_step:', 'ts.TimeStep,', 'policy_state:', 'types.NestedArray=(),', 'seed:', 'Optional[types.Seed]=None)', '->', 'policy_step.PolicyStep:', 'if', 'seed', 'is', 'not', 'None:', 'return', 'self._action(time_step,', 'policy_state,', 'seed=seed)', 'else:', 'return', 'self._action(time_step,', 'p... | 23,569 |
intel/neural-compressor | progressive.py | PytorchProgressivePruner.check_is_pruned_progressive_step | check_is_pruned_progressive_step | Check if a progressive pruning process should be performed at the current step. | [
"Check",
"if",
"a",
"progressive",
"pruning",
"process",
"should",
"be",
"performed",
"at",
"the",
"current",
"step."
] | def check_is_pruned_progressive_step(self, step):
if step < self.start_step or step > self.end_step:
return False
if int(step - self.start_step) % self.pruning_frequency_progressive == 0:
return True
return False | ['def', 'check_is_pruned_progressive_step(self,', 'step):', 'if', 'step', '<', 'self.start_step', 'or', 'step', '>', 'self.end_step:', 'return', 'False', 'if', 'int(step', '-', 'self.start_step)', '%', 'self.pruning_frequency_progressive', '==', '0:', 'return', 'True', 'return', 'False'] | 738,217 |
zihuitang/medical_AI_platform | __init__.py | Wm.wm_frame | wm_frame | Return identifier for decorative frame of this widget if present. | [
"Return",
"identifier",
"for",
"decorative",
"frame",
"of",
"this",
"widget",
"if",
"present."
] | def wm_frame(self):
return self.tk.call('wm', 'frame', self._w) | ['def', 'wm_frame(self):', 'return', "self.tk.call('wm',", "'frame',", 'self._w)'] | 284,166 |
huawei-noah/xingtian | faster_backbone.py | FasterBackbone.call | call | Forward compute of resnet for detection. | [
"Forward",
"compute",
"of",
"resnet",
"for",
"detection."
] | def call(self, x, **kwargs):
out = self.backbone(x)
out = self.adaptiveAvgPool2d(out[-1])
out = self.view(out)
out = self.head(out)
return out | ['def', 'call(self,', 'x,', '**kwargs):', 'out', '=', 'self.backbone(x)', 'out', '=', 'self.adaptiveAvgPool2d(out[-1])', 'out', '=', 'self.view(out)', 'out', '=', 'self.head(out)', 'return', 'out'] | 962,910 |
nlp-uoregon/trankit | seq2seq_utils.py | get_wordvec_file | get_wordvec_file | Lookup the name of the word vectors file, given a directory and the language shorthand. | [
"Lookup",
"the",
"name",
"of",
"the",
"word",
"vectors",
"file,",
"given",
"a",
"directory",
"and",
"the",
"language",
"shorthand."
] | def get_wordvec_file(w2v_name, wordvec_dir, shorthand, wordvec_type=None):
(lcode, tcode) = shorthand.split('_', 1)
word2vec_dir = os.path.join('../..', wordvec_dir, 'word2vec', w2v_name)
fasttext_dir = os.path.join('../..', wordvec_dir, 'fasttext', w2v_name)
lang_dir = None
if wordvec_type is not N... | ['def', 'get_wordvec_file(w2v_name,', 'wordvec_dir,', 'shorthand,', 'wordvec_type=None):', '(lcode,', 'tcode)', '=', "shorthand.split('_',", '1)', 'word2vec_dir', '=', "os.path.join('../..',", 'wordvec_dir,', "'word2vec',", 'w2v_name)', 'fasttext_dir', '=', "os.path.join('../..',", 'wordvec_dir,', "'fasttext',", 'w2v_n... | 920,478 |
rifqind/Agent-Programs-3KS1 | win32.py | Win32Output.write_raw | write_raw | For win32, there is no difference between write and write_raw. | [
"For",
"win32,",
"there",
"is",
"no",
"difference",
"between",
"write",
"and",
"write_raw."
] | def write_raw(self, data):
self.write(data) | ['def', 'write_raw(self,', 'data):', 'self.write(data)'] | 45,456 |
vvittis/Artificial-Intelligence | utils.py | shuffled | shuffled | Randomly shuffle a copy of iterable. | [
"Randomly",
"shuffle",
"a",
"copy",
"of",
"iterable."
] | def shuffled(iterable):
items = list(iterable)
random.shuffle(items)
return items | ['def', 'shuffled(iterable):', 'items', '=', 'list(iterable)', 'random.shuffle(items)', 'return', 'items'] | 121,413 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | new_mean_squared | new_mean_squared | Calculates the new accumulated mean squared of the gradient. | [
"Calculates",
"the",
"new",
"accumulated",
"mean",
"squared",
"of",
"the",
"gradient."
] | def new_mean_squared(grad_vec, decay, ms):
decay_size = decay.get_shape().num_elements()
decay_check_ops = [tf.assert_less_equal(decay, 1.0, summarize=decay_size), tf.assert_greater_equal(decay, 0.0, summarize=decay_size)]
with tf.control_dependencies(decay_check_ops):
grad_squared = tf.square(grad_... | ['def', 'new_mean_squared(grad_vec,', 'decay,', 'ms):', 'decay_size', '=', 'decay.get_shape().num_elements()', 'decay_check_ops', '=', '[tf.assert_less_equal(decay,', '1.0,', 'summarize=decay_size),', 'tf.assert_greater_equal(decay,', '0.0,', 'summarize=decay_size)]', 'with', 'tf.control_dependencies(decay_check_ops):'... | 55,497 |
fudan-zvg/SETR | general_data.py | GeneralData.cuda | cuda | Apply same name function to all tensors in data_fields. | [
"Apply",
"same",
"name",
"function",
"to",
"all",
"tensors",
"in",
"data_fields."
] | def cuda(self):
new_data = self.new()
for (k, v) in self.items():
if isinstance(v, torch.Tensor):
v = v.cuda()
new_data[k] = v
return new_data | ['def', 'cuda(self):', 'new_data', '=', 'self.new()', 'for', '(k,', 'v)', 'in', 'self.items():', 'if', 'isinstance(v,', 'torch.Tensor):', 'v', '=', 'v.cuda()', 'new_data[k]', '=', 'v', 'return', 'new_data'] | 897,842 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | test_analytics.py | s_main_dtypes | s_main_dtypes | A DataFrame with many dtypes * datetime * datetimetz * timedelta * [u]int{8,16,32,64} * float{32,64} The columns are the name of the dtype. | [
"A",
"DataFrame",
"with",
"many",
"dtypes",
"*",
"datetime",
"*",
"datetimetz",
"*",
"timedelta",
"*",
"[u]int{8,16,32,64}",
"*",
"float{32,64}",
"The",
"columns",
"are",
"the",
"name",
"of",
"the",
"dtype."
] | def s_main_dtypes():
df = pd.DataFrame({'datetime': pd.to_datetime(['2003', '2002', '2001', '2002', '2005']), 'datetimetz': pd.to_datetime(['2003', '2002', '2001', '2002', '2005']).tz_localize('US/Eastern'), 'timedelta': pd.to_timedelta(['3d', '2d', '1d', '2d', '5d'])})
for dtype in ['int8', 'int16', 'int32', '... | ['def', 's_main_dtypes():', 'df', '=', "pd.DataFrame({'datetime':", "pd.to_datetime(['2003',", "'2002',", "'2001',", "'2002',", "'2005']),", "'datetimetz':", "pd.to_datetime(['2003',", "'2002',", "'2001',", "'2002',", "'2005']).tz_localize('US/Eastern'),", "'timedelta':", "pd.to_timedelta(['3d',", "'2d',", "'1d',", "'2... | 968,322 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjDataWrapper.nstack | nstack | number of mjtNums that can fit in stack. | [
"number",
"of",
"mjtNums",
"that",
"can",
"fit",
"in",
"stack."
] | def nstack(self):
return self._ptr.contents.nstack | ['def', 'nstack(self):', 'return', 'self._ptr.contents.nstack'] | 440,517 |
devashish-patel/webcam-motion-detector | base64mime.py | header_length | header_length | Return the length of s when it is encoded with base64. | [
"Return",
"the",
"length",
"of",
"s",
"when",
"it",
"is",
"encoded",
"with",
"base64."
] | def header_length(bytearray):
(groups_of_3, leftover) = divmod(len(bytearray), 3)
n = groups_of_3 * 4
if leftover:
n += 4
return n | ['def', 'header_length(bytearray):', '(groups_of_3,', 'leftover)', '=', 'divmod(len(bytearray),', '3)', 'n', '=', 'groups_of_3', '*', '4', 'if', 'leftover:', 'n', '+=', '4', 'return', 'n'] | 977,836 |
subodh-malgonde/semantic-segmentation | rmi.py | RMILoss.forward_sigmoid | forward_sigmoid | Using the sigmiod operation both. | [
"Using",
"the",
"sigmiod",
"operation",
"both."
] | def forward_sigmoid(self, logits_4D, labels_4D, do_rmi=False):
label_mask_3D = labels_4D < self.num_classes
valid_onehot_labels_4D = F.one_hot(labels_4D.long() * label_mask_3D.long(), num_classes=self.num_classes).float()
label_mask_3D = label_mask_3D.float()
label_mask_flat = label_mask_3D.view([-1])
... | ['def', 'forward_sigmoid(self,', 'logits_4D,', 'labels_4D,', 'do_rmi=False):', 'label_mask_3D', '=', 'labels_4D', '<', 'self.num_classes', 'valid_onehot_labels_4D', '=', 'F.one_hot(labels_4D.long()', '*', 'label_mask_3D.long(),', 'num_classes=self.num_classes).float()', 'label_mask_3D', '=', 'label_mask_3D.float()', 'l... | 857,868 |
Ruturaj123/Flowchart-Detection | dnn_linear_combined_test.py | DNNLinearCombinedClassifierTest.testDNNOnly | testDNNOnly | Tests that DNN-only instantiation works. | [
"Tests",
"that",
"DNN-only",
"instantiation",
"works."
] | def testDNNOnly(self):
cont_features = [feature_column.real_valued_column('feature', dimension=4)]
classifier = dnn_linear_combined.DNNLinearCombinedClassifier(n_classes=3, dnn_feature_columns=cont_features, dnn_hidden_units=[3, 3])
classifier.fit(input_fn=test_data.iris_input_multiclass_fn, steps=1000)
... | ['def', 'testDNNOnly(self):', 'cont_features', '=', "[feature_column.real_valued_column('feature',", 'dimension=4)]', 'classifier', '=', 'dnn_linear_combined.DNNLinearCombinedClassifier(n_classes=3,', 'dnn_feature_columns=cont_features,', 'dnn_hidden_units=[3,', '3])', 'classifier.fit(input_fn=test_data.iris_input_mult... | 603,913 |
rail-berkeley/softlearning | feedforward_test.py | FeedforwardTest.test_clone_model | test_clone_model | Make sure that cloning works and clones can predict. | [
"Make",
"sure",
"that",
"cloning",
"works",
"and",
"clones",
"can",
"predict."
] | def test_clone_model(self):
output_shape = (5,)
x_np = np.random.uniform(0, 1, (1, 13)).astype(np.float32)
x = tf.constant(x_np)
fn1 = feedforward_model(output_shape=output_shape, hidden_layer_sizes=(6, 4, 2), name='feedforward_function')
result_1 = fn1([x, x]).numpy()
fn2 = tf.keras.models.clon... | ['def', 'test_clone_model(self):', 'output_shape', '=', '(5,)', 'x_np', '=', 'np.random.uniform(0,', '1,', '(1,', '13)).astype(np.float32)', 'x', '=', 'tf.constant(x_np)', 'fn1', '=', 'feedforward_model(output_shape=output_shape,', 'hidden_layer_sizes=(6,', '4,', '2),', "name='feedforward_function')", 'result_1', '=', ... | 879,280 |
aeon-toolkit/aeon | test_base.py | test_reset_composite | test_reset_composite | Test reset method for correct behaviour, on a composite estimator. | [
"Test",
"reset",
"method",
"for",
"correct",
"behaviour,",
"on",
"a",
"composite",
"estimator."
] | def test_reset_composite():
y = ResetTester(42)
x = ResetTester(a=y)
x.foo(y)
x.d.foo()
x.reset()
assert hasattr(x, 'a')
assert not hasattr(x, 'd')
assert not hasattr(x.a, 'd') | ['def', 'test_reset_composite():', 'y', '=', 'ResetTester(42)', 'x', '=', 'ResetTester(a=y)', 'x.foo(y)', 'x.d.foo()', 'x.reset()', 'assert', 'hasattr(x,', "'a')", 'assert', 'not', 'hasattr(x,', "'d')", 'assert', 'not', 'hasattr(x.a,', "'d')"] | 399,163 |
KalleHallden/InstaAutomator | _tifffile.py | TiffPage.is_rgb | is_rgb | Page contains a RGB image. | [
"Page",
"contains",
"a",
"RGB",
"image."
] | def is_rgb(self):
return 'photometric' in self.tags and self.tags['photometric'].value == 2 | ['def', 'is_rgb(self):', 'return', "'photometric'", 'in', 'self.tags', 'and', "self.tags['photometric'].value", '==', '2'] | 242,562 |
ryu-ed/SpaceInvaders_Ros | ssl_servers.py | StatsRequestHandler.do_HEAD | do_HEAD | Serve a HEAD request. | [
"Serve",
"a",
"HEAD",
"request."
] | def do_HEAD(self):
self.do_GET(send_body=False) | ['def', 'do_HEAD(self):', 'self.do_GET(send_body=False)'] | 395,836 |
intel/neural-compressor | main.py | evaluate | evaluate | Custom evaluate function to inference the model for specified metric on validation dataset. | [
"Custom",
"evaluate",
"function",
"to",
"inference",
"the",
"model",
"for",
"specified",
"metric",
"on",
"validation",
"dataset."
] | def evaluate(model):
postprocess = LabelShift(label_shift=1)
from neural_compressor import METRICS
metrics = METRICS('tensorflow')
metric = metrics['topk']()
latency_list = []
def eval_func(dataloader, metric):
warmup = 5
iteration = None
if FLAGS.benchmark and FLAGS.mod... | ['def', 'evaluate(model):', 'postprocess', '=', 'LabelShift(label_shift=1)', 'from', 'neural_compressor', 'import', 'METRICS', 'metrics', '=', "METRICS('tensorflow')", 'metric', '=', "metrics['topk']()", 'latency_list', '=', '[]', 'def', 'eval_func(dataloader,', 'metric):', 'warmup', '=', '5', 'iteration', '=', 'None',... | 736,442 |
FreshAirTonight/af2complex | r3.py | rots_from_tensor3x3 | rots_from_tensor3x3 | Convert rotations represented as (3, 3) array to Rots. | [
"Convert",
"rotations",
"represented",
"as",
"(3,",
"3)",
"array",
"to",
"Rots."
] | def rots_from_tensor3x3(m: jnp.ndarray) -> Rots:
assert m.shape[-1] == 3
assert m.shape[-2] == 3
return Rots(m[..., 0, 0], m[..., 0, 1], m[..., 0, 2], m[..., 1, 0], m[..., 1, 1], m[..., 1, 2], m[..., 2, 0], m[..., 2, 1], m[..., 2, 2]) | ['def', 'rots_from_tensor3x3(m:', 'jnp.ndarray)', '->', 'Rots:', 'assert', 'm.shape[-1]', '==', '3', 'assert', 'm.shape[-2]', '==', '3', 'return', 'Rots(m[...,', '0,', '0],', 'm[...,', '0,', '1],', 'm[...,', '0,', '2],', 'm[...,', '1,', '0],', 'm[...,', '1,', '1],', 'm[...,', '1,', '2],', 'm[...,', '2,', '0],', 'm[...,... | 400,722 |
stefan-rz/udacity-aind | utils.py | first | first | Return the first element of an iterable or the next element of a generator; or default. | [
"Return",
"the",
"first",
"element",
"of",
"an",
"iterable",
"or",
"the",
"next",
"element",
"of",
"a",
"generator;",
"or",
"default."
] | def first(iterable, default=None):
try:
return iterable[0]
except IndexError:
return default
except TypeError:
return next(iterable, default) | ['def', 'first(iterable,', 'default=None):', 'try:', 'return', 'iterable[0]', 'except', 'IndexError:', 'return', 'default', 'except', 'TypeError:', 'return', 'next(iterable,', 'default)'] | 427,829 |
deepmind/xmanager | async_packager.py | AsyncPackager.package | package | Triggers the packaging of previously added packageables. | [
"Triggers",
"the",
"packaging",
"of",
"previously",
"added",
"packageables."
] | def package(self, extra_packageables: Sequence[job_blocks.Packageable]=()) -> Sequence[job_blocks.Executable]:
with self._lock:
packageables = self._packageables + list(extra_packageables)
futures = self._futures
self._packageables = []
self._futures = []
if not packageables:
... | ['def', 'package(self,', 'extra_packageables:', 'Sequence[job_blocks.Packageable]=())', '->', 'Sequence[job_blocks.Executable]:', 'with', 'self._lock:', 'packageables', '=', 'self._packageables', '+', 'list(extra_packageables)', 'futures', '=', 'self._futures', 'self._packageables', '=', '[]', 'self._futures', '=', '[]... | 968,756 |
sktime/sktime | tfp.py | TFNormal.get_test_params | get_test_params | Return testing parameter settings for the estimator. | [
"Return",
"testing",
"parameter",
"settings",
"for",
"the",
"estimator."
] | def get_test_params(cls, parameter_set='default'):
params1 = {'mu': [[0, 1], [2, 3], [4, 5]], 'sigma': 1}
params2 = {'mu': 0, 'sigma': 1, 'index': pd.Index([1, 2, 5]), 'columns': pd.Index(['a', 'b'])}
return [params1, params2] | ['def', 'get_test_params(cls,', "parameter_set='default'):", 'params1', '=', "{'mu':", '[[0,', '1],', '[2,', '3],', '[4,', '5]],', "'sigma':", '1}', 'params2', '=', "{'mu':", '0,', "'sigma':", '1,', "'index':", 'pd.Index([1,', '2,', '5]),', "'columns':", "pd.Index(['a',", "'b'])}", 'return', '[params1,', 'params2]'] | 877,492 |
tensorflow/data-validation | schema_util.py | get_categorical_features | get_categorical_features | Gets the set containing the names of all categorical features. | [
"Gets",
"the",
"set",
"containing",
"the",
"names",
"of",
"all",
"categorical",
"features."
] | def get_categorical_features(schema: schema_pb2.Schema) -> Set[types.FeaturePath]:
return {feature_path for (feature_path, feature) in get_all_leaf_features(schema) if is_categorical_feature(feature)} | ['def', 'get_categorical_features(schema:', 'schema_pb2.Schema)', '->', 'Set[types.FeaturePath]:', 'return', '{feature_path', 'for', '(feature_path,', 'feature)', 'in', 'get_all_leaf_features(schema)', 'if', 'is_categorical_feature(feature)}'] | 497,634 |
Ruturaj123/Flowchart-Detection | model_analyzer_testlib.py | BuildFullModel | BuildFullModel | Build the full model with conv,rnn,opt. | [
"Build",
"the",
"full",
"model",
"with",
"conv,rnn,opt."
] | def BuildFullModel():
seq = []
for i in range(4):
with variable_scope.variable_scope('inp_%d' % i):
seq.append(array_ops.reshape(BuildSmallModel(), [2, 1, -1]))
cell = rnn_cell.BasicRNNCell(16)
out = rnn.dynamic_rnn(cell, array_ops.concat(seq, axis=1), dtype=dtypes.float32)[0]
ta... | ['def', 'BuildFullModel():', 'seq', '=', '[]', 'for', 'i', 'in', 'range(4):', 'with', "variable_scope.variable_scope('inp_%d'", '%', 'i):', 'seq.append(array_ops.reshape(BuildSmallModel(),', '[2,', '1,', '-1]))', 'cell', '=', 'rnn_cell.BasicRNNCell(16)', 'out', '=', 'rnn.dynamic_rnn(cell,', 'array_ops.concat(seq,', 'ax... | 606,397 |
flavioschneider/rl-transfer- | task_sampler.py | EnvPoolSampler.n_tasks | n_tasks | int: the number of tasks. | [
"int:",
"the",
"number",
"of",
"tasks."
] | def n_tasks(self):
return len(self._envs) | ['def', 'n_tasks(self):', 'return', 'len(self._envs)'] | 861,171 |
myothida/Supervised-Machine-Learning | test_readers.py | TestReaders.cd_and_set_engine | cd_and_set_engine | Change directory and set engine for read_excel calls. | [
"Change",
"directory",
"and",
"set",
"engine",
"for",
"read_excel",
"calls."
] | def cd_and_set_engine(self, engine, datapath, monkeypatch):
func = partial(pd.read_excel, engine=engine)
monkeypatch.chdir(datapath('io', 'data', 'excel'))
monkeypatch.setattr(pd, 'read_excel', func) | ['def', 'cd_and_set_engine(self,', 'engine,', 'datapath,', 'monkeypatch):', 'func', '=', 'partial(pd.read_excel,', 'engine=engine)', "monkeypatch.chdir(datapath('io',", "'data',", "'excel'))", 'monkeypatch.setattr(pd,', "'read_excel',", 'func)'] | 443,745 |
RE-OWOD/RE-OWOD | testing.py | print_csv_format | print_csv_format | Print main metrics in a format similar to Detectron, so that they are easy to copypaste into a spreadsheet. | [
"Print",
"main",
"metrics",
"in",
"a",
"format",
"similar",
"to",
"Detectron,",
"so",
"that",
"they",
"are",
"easy",
"to",
"copypaste",
"into",
"a",
"spreadsheet."
] | def print_csv_format(results):
assert isinstance(results, OrderedDict), results
logger = logging.getLogger(__name__)
for (task, res) in results.items():
important_res = [(k, v) for (k, v) in res.items() if '-' not in k]
logger.info('copypaste: Task: {}'.format(task))
logger.info('cop... | ['def', 'print_csv_format(results):', 'assert', 'isinstance(results,', 'OrderedDict),', 'results', 'logger', '=', 'logging.getLogger(__name__)', 'for', '(task,', 'res)', 'in', 'results.items():', 'important_res', '=', '[(k,', 'v)', 'for', '(k,', 'v)', 'in', 'res.items()', 'if', "'-'", 'not', 'in', 'k]', "logger.info('c... | 848,938 |
matthewmackay/reversible-rnn | ModelConstructor.py | make_encoder | make_encoder | Various encoder dispatcher function. | [
"Various",
"encoder",
"dispatcher",
"function."
] | def make_encoder(opt, embeddings):
if opt.encoder_model == 'Vanilla':
return custom_models.MyEncoder(rnn_type=opt.encoder_rnn_type, nhid=opt.rnn_size, num_layers=opt.enc_layers, embeddings=embeddings, context_type=opt.context_type, slice_dim=opt.slice_dim, dropoute=opt.dropoute, dropouti=opt.dropouti, dropo... | ['def', 'make_encoder(opt,', 'embeddings):', 'if', 'opt.encoder_model', '==', "'Vanilla':", 'return', 'custom_models.MyEncoder(rnn_type=opt.encoder_rnn_type,', 'nhid=opt.rnn_size,', 'num_layers=opt.enc_layers,', 'embeddings=embeddings,', 'context_type=opt.context_type,', 'slice_dim=opt.slice_dim,', 'dropoute=opt.dropou... | 348,616 |
Kvatsx/Artificial-Intelligence-Assignments | data.py | YamlLexer.set_block_scalar_indent | set_block_scalar_indent | Set an explicit indentation level for a block scalar. | [
"Set",
"an",
"explicit",
"indentation",
"level",
"for",
"a",
"block",
"scalar."
] | def set_block_scalar_indent(token_class):
def callback(lexer, match, context):
text = match.group()
context.block_scalar_indent = None
if not text:
return
increment = match.group(1)
if increment:
current_indent = max(context.indent, 0)
inc... | ['def', 'set_block_scalar_indent(token_class):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'context.block_scalar_indent', '=', 'None', 'if', 'not', 'text:', 'return', 'increment', '=', 'match.group(1)', 'if', 'increment:', 'current_indent', '=', 'max(context.indent,', '0)', 'increme... | 77,167 |
aws/sagemaker-python-sdk | _run_context.py | _RunContext.get_current_run | get_current_run | Return the current Run object without dropping it. | [
"Return",
"the",
"current",
"Run",
"object",
"without",
"dropping",
"it."
] | def get_current_run(cls) -> 'Run':
return cls._context_run | ['def', 'get_current_run(cls)', '->', "'Run':", 'return', 'cls._context_run'] | 829,996 |
Farama-Foundation/Minari | common.py | check_env_recovery | check_env_recovery | Test that the recovered environment from MinariDataset is the same as the one used to generate the dataset. | [
"Test",
"that",
"the",
"recovered",
"environment",
"from",
"MinariDataset",
"is",
"the",
"same",
"as",
"the",
"one",
"used",
"to",
"generate",
"the",
"dataset."
] | def check_env_recovery(gymnasium_environment: gym.Env, dataset: MinariDataset):
recovered_env = dataset.recover_environment()
assert recovered_env.spec == gymnasium_environment.spec, f'recovered_env spec: {recovered_env.spec}\noriginal spec: {gymnasium_environment.spec}'
assert data_equivalence(recovered_en... | ['def', 'check_env_recovery(gymnasium_environment:', 'gym.Env,', 'dataset:', 'MinariDataset):', 'recovered_env', '=', 'dataset.recover_environment()', 'assert', 'recovered_env.spec', '==', 'gymnasium_environment.spec,', "f'recovered_env", 'spec:', '{recovered_env.spec}\\noriginal', 'spec:', "{gymnasium_environment.spec... | 670,527 |
LeonhardFeiner/sparse_rcnn | basic_functions.py | slice_tuple_gen | slice_tuple_gen | Generates a tuple of slices to slice a tensor multiple times. | [
"Generates",
"a",
"tuple",
"of",
"slices",
"to",
"slice",
"a",
"tensor",
"multiple",
"times."
] | def slice_tuple_gen(dims: List[int], start_stop_splits: Iterable[torch.tensor]) -> Iterable[Tuple[slice]]:
if any((dim < 0 for dim in dims)):
ellipsis_pos = max(-1, *dims) + 1
array_len = ellipsis_pos + 1 - min(dims)
array = [slice(None)] * array_len
array[ellipsis_pos] = Ellipsis
... | ['def', 'slice_tuple_gen(dims:', 'List[int],', 'start_stop_splits:', 'Iterable[torch.tensor])', '->', 'Iterable[Tuple[slice]]:', 'if', 'any((dim', '<', '0', 'for', 'dim', 'in', 'dims)):', 'ellipsis_pos', '=', 'max(-1,', '*dims)', '+', '1', 'array_len', '=', 'ellipsis_pos', '+', '1', '-', 'min(dims)', 'array', '=', '[sl... | 894,696 |
Westlake-AI/openmixup | classification.py | ClassificationDataset.evaluate | evaluate | The evaluation function to output accuracy. | [
"The",
"evaluation",
"function",
"to",
"output",
"accuracy."
] | def evaluate(self, scores, keyword, logger=None, metric='accuracy', metric_options=None, topk=(1, 5), **kwargs):
if metric_options is None:
metric_options = dict(average_mode='macro')
if isinstance(metric, str):
metrics = [metric]
else:
metrics = metric
eval_res = {}
eval_log... | ['def', 'evaluate(self,', 'scores,', 'keyword,', 'logger=None,', "metric='accuracy',", 'metric_options=None,', 'topk=(1,', '5),', '**kwargs):', 'if', 'metric_options', 'is', 'None:', 'metric_options', '=', "dict(average_mode='macro')", 'if', 'isinstance(metric,', 'str):', 'metrics', '=', '[metric]', 'else:', 'metrics',... | 252,323 |
deepmind/dm_alchemy | unity_python_conversion.py | from_unity_chemistry | from_unity_chemistry | Convert from unity Chemistry object to corresponding python types. | [
"Convert",
"from",
"unity",
"Chemistry",
"object",
"to",
"corresponding",
"python",
"types."
] | def from_unity_chemistry(chemistry: alchemy_pb2.Chemistry, rotation_mapping: alchemy_pb2.RotationMapping) -> utils.Chemistry:
rotation = rotation_from_unity(rotation_mapping)
abs_rotation = stones_and_potions.rotation_from_angles([-abs(a) for a in stones_and_potions.rotation_to_angles(rotation)])
python_sto... | ['def', 'from_unity_chemistry(chemistry:', 'alchemy_pb2.Chemistry,', 'rotation_mapping:', 'alchemy_pb2.RotationMapping)', '->', 'utils.Chemistry:', 'rotation', '=', 'rotation_from_unity(rotation_mapping)', 'abs_rotation', '=', 'stones_and_potions.rotation_from_angles([-abs(a)', 'for', 'a', 'in', 'stones_and_potions.rot... | 522,293 |
ryu-ed/SpaceInvaders_Ros | vertexdomain.py | VertexList.normals | normals | Array of normal vector data. | [
"Array",
"of",
"normal",
"vector",
"data."
] | def normals(self):
if self._normals_cache_version != self.domain._version:
domain = self.domain
attribute = domain.attribute_names['normals']
self._normals_cache = attribute.get_region(attribute.buffer, self.start, self.count)
self._normals_cache_version = domain._version
region ... | ['def', 'normals(self):', 'if', 'self._normals_cache_version', '!=', 'self.domain._version:', 'domain', '=', 'self.domain', 'attribute', '=', "domain.attribute_names['normals']", 'self._normals_cache', '=', 'attribute.get_region(attribute.buffer,', 'self.start,', 'self.count)', 'self._normals_cache_version', '=', 'doma... | 369,544 |
google-research/bleurt | downloaders.py | Importer17.get_ref_segments | get_ref_segments | Fetches source and reference translation segments for language pair. | [
"Fetches",
"source",
"and",
"reference",
"translation",
"segments",
"for",
"language",
"pair."
] | def get_ref_segments(self, lang):
src_subfolder = self.segments_path('source')
ref_subfolder = self.segments_path('reference')
(src_lang, tgt_lang) = separate_lang_pair(lang)
src_file = 'newstest2017-{src}{tgt}-src.{lang}'.format(src=src_lang, tgt=tgt_lang, lang=src_lang)
ref_file = 'newstest2017-{s... | ['def', 'get_ref_segments(self,', 'lang):', 'src_subfolder', '=', "self.segments_path('source')", 'ref_subfolder', '=', "self.segments_path('reference')", '(src_lang,', 'tgt_lang)', '=', 'separate_lang_pair(lang)', 'src_file', '=', "'newstest2017-{src}{tgt}-src.{lang}'.format(src=src_lang,", 'tgt=tgt_lang,', 'lang=src_... | 461,755 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | _base.py | _AxesBase.can_zoom | can_zoom | Return *True* if this axes supports the zoom box button functionality. | [
"Return",
"*True*",
"if",
"this",
"axes",
"supports",
"the",
"zoom",
"box",
"button",
"functionality."
] | def can_zoom(self):
return True | ['def', 'can_zoom(self):', 'return', 'True'] | 257,621 |
paulorauber/rl | replay_buffers.py | stack_tensors | stack_tensors | Zips a list of iterables containing tensor-like objects and stacks the resulting lists of tensors together. | [
"Zips",
"a",
"list",
"of",
"iterables",
"containing",
"tensor-like",
"objects",
"and",
"stacks",
"the",
"resulting",
"lists",
"of",
"tensors",
"together."
] | def stack_tensors(list_of_tensor_iterators: List) -> Tuple[torch.Tensor]:
return tuple((torch.stack(tensors, 0) for tensors in zip(*list_of_tensor_iterators))) | ['def', 'stack_tensors(list_of_tensor_iterators:', 'List)', '->', 'Tuple[torch.Tensor]:', 'return', 'tuple((torch.stack(tensors,', '0)', 'for', 'tensors', 'in', 'zip(*list_of_tensor_iterators)))'] | 858,786 |
Rock-100/MonoDet | api.py | Caffe2Model.save_protobuf | save_protobuf | Save the model as caffe2's protobuf format. | [
"Save",
"the",
"model",
"as",
"caffe2's",
"protobuf",
"format."
] | def save_protobuf(self, output_dir):
logger = logging.getLogger(__name__)
logger.info('Saving model to {} ...'.format(output_dir))
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, 'model.pb'), 'wb') as f:
f.write(self._predict_net.SerializeToString())
with open(os.pa... | ['def', 'save_protobuf(self,', 'output_dir):', 'logger', '=', 'logging.getLogger(__name__)', "logger.info('Saving", 'model', 'to', '{}', "...'.format(output_dir))", 'os.makedirs(output_dir,', 'exist_ok=True)', 'with', 'open(os.path.join(output_dir,', "'model.pb'),", "'wb')", 'as', 'f:', 'f.write(self._predict_net.Seria... | 654,861 |
RozDavid/LanguageGroundedSemseg | utils.py | read_txt | read_txt | Read txt file into lines. | [
"Read",
"txt",
"file",
"into",
"lines."
] | def read_txt(path):
with open(path) as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
return lines | ['def', 'read_txt(path):', 'with', 'open(path)', 'as', 'f:', 'lines', '=', 'f.readlines()', 'lines', '=', '[x.strip()', 'for', 'x', 'in', 'lines]', 'return', 'lines'] | 623,629 |
ratschlab/RGAN | plotting.py | view_marginals_cristobal | view_marginals_cristobal | View marginals of the synthetic data (compare to real data), from the data Cristobal generated. | [
"View",
"marginals",
"of",
"the",
"synthetic",
"data",
"(compare",
"to",
"real",
"data),",
"from",
"the",
"data",
"Cristobal",
"generated."
] | def view_marginals_cristobal(rep=0, epoch=300, zoom=False):
samples_path = paths.eICU_synthetic_dir + 'samples_eICU_cdgan_synthetic_dataset_r' + str(rep) + '_' + str(epoch) + '.pk'
samples = np.load(samples_path)
labels_path = paths.eICU_synthetic_dir + 'labels_eICU_cdgan_synthetic_dataset_r' + str(rep) + '... | ['def', 'view_marginals_cristobal(rep=0,', 'epoch=300,', 'zoom=False):', 'samples_path', '=', 'paths.eICU_synthetic_dir', '+', "'samples_eICU_cdgan_synthetic_dataset_r'", '+', 'str(rep)', '+', "'_'", '+', 'str(epoch)', '+', "'.pk'", 'samples', '=', 'np.load(samples_path)', 'labels_path', '=', 'paths.eICU_synthetic_dir'... | 841,227 |
marcsto/rl | common.py | ModelBasedEnvBase.set_specs_from_env | set_specs_from_env | Sets the specs of the environment from the specs of the given environment. | [
"Sets",
"the",
"specs",
"of",
"the",
"environment",
"from",
"the",
"specs",
"of",
"the",
"given",
"environment."
] | def set_specs_from_env(self, env: EnvBase):
self.observation_spec = env.observation_spec.clone().to(self.device)
self.reward_spec = env.reward_spec.clone().to(self.device)
self.action_spec = env.action_spec.clone().to(self.device)
self.done_spec = env.done_spec.clone().to(self.device)
self.state_spe... | ['def', 'set_specs_from_env(self,', 'env:', 'EnvBase):', 'self.observation_spec', '=', 'env.observation_spec.clone().to(self.device)', 'self.reward_spec', '=', 'env.reward_spec.clone().to(self.device)', 'self.action_spec', '=', 'env.action_spec.clone().to(self.device)', 'self.done_spec', '=', 'env.done_spec.clone().to(... | 859,071 |
myothida/Supervised-Machine-Learning | test_direct.py | test_generator_spawning | test_generator_spawning | Test spawning new generators and bit_generators directly. | [
"Test",
"spawning",
"new",
"generators",
"and",
"bit_generators",
"directly."
] | def test_generator_spawning():
rng = np.random.default_rng()
seq = rng.bit_generator.seed_seq
new_ss = seq.spawn(5)
expected_keys = [seq.spawn_key + (i,) for i in range(5)]
assert [c.spawn_key for c in new_ss] == expected_keys
new_bgs = rng.bit_generator.spawn(5)
expected_keys = [seq.spawn_k... | ['def', 'test_generator_spawning():', 'rng', '=', 'np.random.default_rng()', 'seq', '=', 'rng.bit_generator.seed_seq', 'new_ss', '=', 'seq.spawn(5)', 'expected_keys', '=', '[seq.spawn_key', '+', '(i,)', 'for', 'i', 'in', 'range(5)]', 'assert', '[c.spawn_key', 'for', 'c', 'in', 'new_ss]', '==', 'expected_keys', 'new_bgs... | 442,044 |
weimin17/Object-Detection_HelmetDetection | contextual_bandit.py | ContextualBandit.optimal | optimal | Returns the optimal action (in hindsight) for the number-th context. | [
"Returns",
"the",
"optimal",
"action",
"(in",
"hindsight)",
"for",
"the",
"number-th",
"context."
] | def optimal(self, number):
return np.argmax(self.data[self.order[number]][self.context_dim:]) | ['def', 'optimal(self,', 'number):', 'return', 'np.argmax(self.data[self.order[number]][self.context_dim:])'] | 762,330 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.