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 |
|---|---|---|---|---|---|---|---|---|
NREL/sup3r | test_data_handling_h5_cc.py | test_solar_val_data | test_solar_val_data | Validation data is not enabled for solar CC model, test that the batch handler does not have validation data. | [
"Validation",
"data",
"is",
"not",
"enabled",
"for",
"solar",
"CC",
"model,",
"test",
"that",
"the",
"batch",
"handler",
"does",
"not",
"have",
"validation",
"data."
] | def test_solar_val_data():
handler = DataHandlerH5SolarCC(INPUT_FILE_S, FEATURES_S, **dh_kwargs)
batcher = BatchHandlerCC([handler], batch_size=1, n_batches=10, s_enhance=2, sub_daily_shape=8)
n = 0
for _ in batcher.val_data:
n += 1
assert n == 0
assert not batcher.val_data.any() | ['def', 'test_solar_val_data():', 'handler', '=', 'DataHandlerH5SolarCC(INPUT_FILE_S,', 'FEATURES_S,', '**dh_kwargs)', 'batcher', '=', 'BatchHandlerCC([handler],', 'batch_size=1,', 'n_batches=10,', 's_enhance=2,', 'sub_daily_shape=8)', 'n', '=', '0', 'for', '_', 'in', 'batcher.val_data:', 'n', '+=', '1', 'assert', 'n',... | 912,726 |
sunishsheth2009/ChatterBot | reading.py | TermInfo.max_weight | max_weight | Returns the number of times the term appears in the document in which it appears the most. | [
"Returns",
"the",
"number",
"of",
"times",
"the",
"term",
"appears",
"in",
"the",
"document",
"in",
"which",
"it",
"appears",
"the",
"most."
] | def max_weight(self):
return self._maxweight | ['def', 'max_weight(self):', 'return', 'self._maxweight'] | 526,283 |
zihuitang/medical_AI_platform | install.py | install.dump_dirs | dump_dirs | Dumps the list of user options. | [
"Dumps",
"the",
"list",
"of",
"user",
"options."
] | def dump_dirs(self, msg):
if not DEBUG:
return
from distutils.fancy_getopt import longopt_xlate
log.debug(msg + ':')
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == '=':
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
... | ['def', 'dump_dirs(self,', 'msg):', 'if', 'not', 'DEBUG:', 'return', 'from', 'distutils.fancy_getopt', 'import', 'longopt_xlate', 'log.debug(msg', '+', "':')", 'for', 'opt', 'in', 'self.user_options:', 'opt_name', '=', 'opt[0]', 'if', 'opt_name[-1]', '==', "'=':", 'opt_name', '=', 'opt_name[0:-1]', 'if', 'opt_name', 'i... | 282,340 |
fmassa/vision | losses.py | make_gaussian_kernel | make_gaussian_kernel | Function to create a 2D Gaussian kernel. | [
"Function",
"to",
"create",
"a",
"2D",
"Gaussian",
"kernel."
] | def make_gaussian_kernel(kernel_size: int, sigma: float) -> torch.Tensor:
x = torch.arange(kernel_size, dtype=torch.float32)
y = torch.arange(kernel_size, dtype=torch.float32)
x = x - (kernel_size - 1) / 2
y = y - (kernel_size - 1) / 2
(x, y) = torch.meshgrid(x, y)
grid = (x ** 2 + y ** 2) / (2 ... | ['def', 'make_gaussian_kernel(kernel_size:', 'int,', 'sigma:', 'float)', '->', 'torch.Tensor:', 'x', '=', 'torch.arange(kernel_size,', 'dtype=torch.float32)', 'y', '=', 'torch.arange(kernel_size,', 'dtype=torch.float32)', 'x', '=', 'x', '-', '(kernel_size', '-', '1)', '/', '2', 'y', '=', 'y', '-', '(kernel_size', '-', ... | 957,755 |
Daniel-Liu-c0deb0t/3D-Neural-Network-Adversarial-Attacks | plyfile.py | PlyListProperty.dtype | dtype | List properties always have a numpy dtype of "object". | [
"List",
"properties",
"always",
"have",
"a",
"numpy",
"dtype",
"of",
"\"object\"."
] | def dtype(self, byte_order='='):
return '|O' | ['def', 'dtype(self,', "byte_order='='):", 'return', "'|O'"] | 375,922 |
myothida/Supervised-Machine-Learning | builder.py | ClassPairPosSubtableBuilder.addSubtableBreak | addSubtableBreak | Add an explicit subtable break at this point. | [
"Add",
"an",
"explicit",
"subtable",
"break",
"at",
"this",
"point."
] | def addSubtableBreak(self):
self.forceSubtableBreak_ = True | ['def', 'addSubtableBreak(self):', 'self.forceSubtableBreak_', '=', 'True'] | 361,091 |
weimin17/Object-Detection_HelmetDetection | train_utils.py | run_training | run_training | Sets up and runs training loop. | [
"Sets",
"up",
"and",
"runs",
"training",
"loop."
] | def run_training(train_op, loss, global_step, variables_to_restore=None, pretrained_model_dir=None):
tf.gfile.MakeDirs(FLAGS.train_dir)
if pretrained_model_dir:
assert variables_to_restore
tf.logging.info('Will attempt restore from %s: %s', pretrained_model_dir, variables_to_restore)
sav... | ['def', 'run_training(train_op,', 'loss,', 'global_step,', 'variables_to_restore=None,', 'pretrained_model_dir=None):', 'tf.gfile.MakeDirs(FLAGS.train_dir)', 'if', 'pretrained_model_dir:', 'assert', 'variables_to_restore', "tf.logging.info('Will", 'attempt', 'restore', 'from', '%s:', "%s',", 'pretrained_model_dir,', 'v... | 761,485 |
VinF/deer | simple_maze_env.py | MyEnv.get_higher_dim_obs | get_higher_dim_obs | Obtain the high-dimensional observation from indices of the agent position and the indices of the reward positions. | [
"Obtain",
"the",
"high-dimensional",
"observation",
"from",
"indices",
"of",
"the",
"agent",
"position",
"and",
"the",
"indices",
"of",
"the",
"reward",
"positions."
] | def get_higher_dim_obs(self, indices_agent, indices_reward):
obs = copy.deepcopy(self._map)
obs = obs / 1.0
obs = np.repeat(np.repeat(obs, 6, axis=0), 6, axis=1)
agent_obs = np.zeros((6, 6))
agent_obs[0, 2] = 0.7
agent_obs[1, 0:5] = 0.8
agent_obs[2, 1:4] = 0.8
agent_obs[3, 1:4] = 0.8
... | ['def', 'get_higher_dim_obs(self,', 'indices_agent,', 'indices_reward):', 'obs', '=', 'copy.deepcopy(self._map)', 'obs', '=', 'obs', '/', '1.0', 'obs', '=', 'np.repeat(np.repeat(obs,', '6,', 'axis=0),', '6,', 'axis=1)', 'agent_obs', '=', 'np.zeros((6,', '6))', 'agent_obs[0,', '2]', '=', '0.7', 'agent_obs[1,', '0:5]', '... | 183,688 |
enuguru/artificial_intelligence_and_machine_ | control.py | Coverage.analysis | analysis | Like `analysis2` but doesn't return excluded line numbers. | [
"Like",
"`analysis2`",
"but",
"doesn't",
"return",
"excluded",
"line",
"numbers."
] | def analysis(self, morf):
(f, s, _, m, mf) = self.analysis2(morf)
return (f, s, m, mf) | ['def', 'analysis(self,', 'morf):', '(f,', 's,', '_,', 'm,', 'mf)', '=', 'self.analysis2(morf)', 'return', '(f,', 's,', 'm,', 'mf)'] | 157,300 |
ryu-ed/SpaceInvaders_Ros | runtime.py | should_use_fpret | should_use_fpret | Determine if objc_msgSend_fpret is required to return a floating point type. | [
"Determine",
"if",
"objc_msgSend_fpret",
"is",
"required",
"to",
"return",
"a",
"floating",
"point",
"type."
] | def should_use_fpret(restype):
if not __i386__:
return False
if __LP64__ and restype == c_longdouble:
return True
if not __LP64__ and restype in (c_float, c_double, c_longdouble):
return True
return False | ['def', 'should_use_fpret(restype):', 'if', 'not', '__i386__:', 'return', 'False', 'if', '__LP64__', 'and', 'restype', '==', 'c_longdouble:', 'return', 'True', 'if', 'not', '__LP64__', 'and', 'restype', 'in', '(c_float,', 'c_double,', 'c_longdouble):', 'return', 'True', 'return', 'False'] | 369,617 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | placement_mesh_impl.py | PlacementMeshImpl.laid_out_pnum | laid_out_pnum | Returns a LaidOutTensor containing the processor number. | [
"Returns",
"a",
"LaidOutTensor",
"containing",
"the",
"processor",
"number."
] | def laid_out_pnum(self):
return self.LaidOutTensor(list(range(self.size))) | ['def', 'laid_out_pnum(self):', 'return', 'self.LaidOutTensor(list(range(self.size)))'] | 965,566 |
accel-brain/accel-brain-code | cropping_rotation_iterator.py | CroppingRotationIterator.create_pretext_task_samples | create_pretext_task_samples | Create samples for pretext_task. | [
"Create",
"samples",
"for",
"pretext_task."
] | def create_pretext_task_samples(self, target_domain_batch_arr):
arr = target_domain_batch_arr.detach()
pretext_arr_1 = arr[:, :, :target_domain_batch_arr.shape[2] // 2, :target_domain_batch_arr.shape[3] // 2]
pretext_arr_2 = arr[:, :, target_domain_batch_arr.shape[2] // 2:, :target_domain_batch_arr.shape[3]... | ['def', 'create_pretext_task_samples(self,', 'target_domain_batch_arr):', 'arr', '=', 'target_domain_batch_arr.detach()', 'pretext_arr_1', '=', 'arr[:,', ':,', ':target_domain_batch_arr.shape[2]', '//', '2,', ':target_domain_batch_arr.shape[3]', '//', '2]', 'pretext_arr_2', '=', 'arr[:,', ':,', 'target_domain_batch_arr... | 6,718 |
sunishsheth2009/ChatterBot | mapper.py | Mapper.get_property | get_property | return a MapperProperty associated with the given key. | [
"return",
"a",
"MapperProperty",
"associated",
"with",
"the",
"given",
"key."
] | def get_property(self, key, _compile_mappers=True):
if _compile_mappers and _new_mappers:
configure_mappers()
try:
return self._props[key]
except KeyError:
raise sa_exc.InvalidRequestError("Mapper '%s' has no property '%s'" % (self, key)) | ['def', 'get_property(self,', 'key,', '_compile_mappers=True):', 'if', '_compile_mappers', 'and', '_new_mappers:', 'configure_mappers()', 'try:', 'return', 'self._props[key]', 'except', 'KeyError:', 'raise', 'sa_exc.InvalidRequestError("Mapper', "'%s'", 'has', 'no', 'property', '\'%s\'"', '%', '(self,', 'key))'] | 534,644 |
alex-petrenko/sample-factory | simplified_sampling_api.py | SamplingLoop.start | start | Model initialization should kickstart the sampling loop. | [
"Model",
"initialization",
"should",
"kickstart",
"the",
"sampling",
"loop."
] | def start(self, init_model_data: Optional[Dict[PolicyID, InitModelData]]=None):
for policy_id in range(self.cfg.num_policies):
if init_model_data is None:
self.model_initialized.emit(None)
else:
self.model_initialized.emit(init_model_data[policy_id]) | ['def', 'start(self,', 'init_model_data:', 'Optional[Dict[PolicyID,', 'InitModelData]]=None):', 'for', 'policy_id', 'in', 'range(self.cfg.num_policies):', 'if', 'init_model_data', 'is', 'None:', 'self.model_initialized.emit(None)', 'else:', 'self.model_initialized.emit(init_model_data[policy_id])'] | 328,992 |
Ruturaj123/Flowchart-Detection | select.py | select_ops | select_ops | Helper to select operations. | [
"Helper",
"to",
"select",
"operations."
] | def select_ops(*args, **kwargs):
graph = None
positive_filter = None
restrict_ops_regex = False
for (k, v) in iteritems(kwargs):
if k == 'graph':
graph = v
if graph is not None and (not isinstance(graph, tf_ops.Graph)):
raise TypeError('Expected a tf.Graph... | ['def', 'select_ops(*args,', '**kwargs):', 'graph', '=', 'None', 'positive_filter', '=', 'None', 'restrict_ops_regex', '=', 'False', 'for', '(k,', 'v)', 'in', 'iteritems(kwargs):', 'if', 'k', '==', "'graph':", 'graph', '=', 'v', 'if', 'graph', 'is', 'not', 'None', 'and', '(not', 'isinstance(graph,', 'tf_ops.Graph)):', ... | 603,135 |
sek788432/Waymo-2D-Object-Detection | retinanet_parser.py | pad_groundtruths_to_fixed_size | pad_groundtruths_to_fixed_size | Pads the first dimension of groundtruths labels to the fixed size. | [
"Pads",
"the",
"first",
"dimension",
"of",
"groundtruths",
"labels",
"to",
"the",
"fixed",
"size."
] | def pad_groundtruths_to_fixed_size(gt, n):
gt['boxes'] = input_utils.pad_to_fixed_size(gt['boxes'], n, -1)
gt['is_crowds'] = input_utils.pad_to_fixed_size(gt['is_crowds'], n, 0)
gt['areas'] = input_utils.pad_to_fixed_size(gt['areas'], n, -1)
gt['classes'] = input_utils.pad_to_fixed_size(gt['classes'], n... | ['def', 'pad_groundtruths_to_fixed_size(gt,', 'n):', "gt['boxes']", '=', "input_utils.pad_to_fixed_size(gt['boxes'],", 'n,', '-1)', "gt['is_crowds']", '=', "input_utils.pad_to_fixed_size(gt['is_crowds'],", 'n,', '0)', "gt['areas']", '=', "input_utils.pad_to_fixed_size(gt['areas'],", 'n,', '-1)', "gt['classes']", '=', "... | 973,478 |
rudranil723/mini-main | state.py | get_related_models_tuples | get_related_models_tuples | Return a list of typical (app_label, model_name) tuples for all related models for the given model. | [
"Return",
"a",
"list",
"of",
"typical",
"(app_label,",
"model_name)",
"tuples",
"for",
"all",
"related",
"models",
"for",
"the",
"given",
"model."
] | def get_related_models_tuples(model):
return {(rel_mod._meta.app_label, rel_mod._meta.model_name) for rel_mod in _get_related_models(model)} | ['def', 'get_related_models_tuples(model):', 'return', '{(rel_mod._meta.app_label,', 'rel_mod._meta.model_name)', 'for', 'rel_mod', 'in', '_get_related_models(model)}'] | 315,958 |
myothida/Supervised-Machine-Learning | configTools.py | Options.register | register | Create and register a new option. | [
"Create",
"and",
"register",
"a",
"new",
"option."
] | def register(self, name: str, help: str, default: Any, parse: Callable[[str], Any], validate: Optional[Callable[[Any], bool]]=None) -> Option:
return self.register_option(Option(name, help, default, parse, validate)) | ['def', 'register(self,', 'name:', 'str,', 'help:', 'str,', 'default:', 'Any,', 'parse:', 'Callable[[str],', 'Any],', 'validate:', 'Optional[Callable[[Any],', 'bool]]=None)', '->', 'Option:', 'return', 'self.register_option(Option(name,', 'help,', 'default,', 'parse,', 'validate))'] | 360,952 |
Katja-M/Python_NaturalLanguageProcessing | subprocess.py | format_command_args | format_command_args | Format command arguments for display. | [
"Format",
"command",
"arguments",
"for",
"display."
] | def format_command_args(args):
return ' '.join((shlex_quote(str(arg)) if isinstance(arg, HiddenText) else shlex_quote(arg) for arg in args)) | ['def', 'format_command_args(args):', 'return', "'", "'.join((shlex_quote(str(arg))", 'if', 'isinstance(arg,', 'HiddenText)', 'else', 'shlex_quote(arg)', 'for', 'arg', 'in', 'args))'] | 868,261 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | sample_players.py | AlphaBetaPlayer.max_value | max_value | Return the value for a loss (-1) if the game is over, otherwise return the maximum value over all legal child nodes. | [
"Return",
"the",
"value",
"for",
"a",
"loss",
"(-1)",
"if",
"the",
"game",
"is",
"over,",
"otherwise",
"return",
"the",
"maximum",
"value",
"over",
"all",
"legal",
"child",
"nodes."
] | def max_value(self, game, depth, alpha, beta):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if self.terminal_test(game):
return -1
if depth <= 0:
return self.score(game, self)
v = float('-inf')
for m in game.get_legal_moves():
v = max(v, self.min_... | ['def', 'max_value(self,', 'game,', 'depth,', 'alpha,', 'beta):', 'if', 'self.time_left()', '<', 'self.TIMER_THRESHOLD:', 'raise', 'SearchTimeout()', 'if', 'self.terminal_test(game):', 'return', '-1', 'if', 'depth', '<=', '0:', 'return', 'self.score(game,', 'self)', 'v', '=', "float('-inf')", 'for', 'm', 'in', 'game.ge... | 427,983 |
lifuguan/ObjectDetection | utils.py | xyxy_to_xywh | xyxy_to_xywh | Convert [x1 y1 x2 y2] box format to [x1 y1 w h] format. | [
"Convert",
"[x1",
"y1",
"x2",
"y2]",
"box",
"format",
"to",
"[x1",
"y1",
"w",
"h]",
"format."
] | def xyxy_to_xywh(xyxy):
if isinstance(xyxy, (list, tuple)):
assert len(xyxy) == 4
(x1, y1) = (xyxy[0], xyxy[1])
w = xyxy[2] - x1 + 1
h = xyxy[3] - y1 + 1
return (x1, y1, w, h)
elif isinstance(xyxy, np.ndarray):
return np.hstack((xyxy[:, 0:2], xyxy[:, 2:4] - xyxy[:... | ['def', 'xyxy_to_xywh(xyxy):', 'if', 'isinstance(xyxy,', '(list,', 'tuple)):', 'assert', 'len(xyxy)', '==', '4', '(x1,', 'y1)', '=', '(xyxy[0],', 'xyxy[1])', 'w', '=', 'xyxy[2]', '-', 'x1', '+', '1', 'h', '=', 'xyxy[3]', '-', 'y1', '+', '1', 'return', '(x1,', 'y1,', 'w,', 'h)', 'elif', 'isinstance(xyxy,', 'np.ndarray):... | 754,781 |
aws/sagemaker-python-sdk | content_types.py | retrieve_default | retrieve_default | Retrieves the default content type for the model matching the given arguments. | [
"Retrieves",
"the",
"default",
"content",
"type",
"for",
"the",
"model",
"matching",
"the",
"given",
"arguments."
] | def retrieve_default(region: Optional[str]=None, model_id: Optional[str]=None, model_version: Optional[str]=None, tolerate_vulnerable_model: bool=False, tolerate_deprecated_model: bool=False, sagemaker_session: Session=DEFAULT_JUMPSTART_SAGEMAKER_SESSION) -> str:
if not jumpstart_utils.is_jumpstart_model_input(mode... | ['def', 'retrieve_default(region:', 'Optional[str]=None,', 'model_id:', 'Optional[str]=None,', 'model_version:', 'Optional[str]=None,', 'tolerate_vulnerable_model:', 'bool=False,', 'tolerate_deprecated_model:', 'bool=False,', 'sagemaker_session:', 'Session=DEFAULT_JUMPSTART_SAGEMAKER_SESSION)', '->', 'str:', 'if', 'not... | 829,418 |
UWARG/computer-vision-python | test_geolocation.py | detection_centre_left_point | detection_centre_left_point | Bounding box is a single point. | [
"Bounding",
"box",
"is",
"a",
"single",
"point."
] | def detection_centre_left_point():
(result, detection) = detections_and_time.Detection.create(np.array([0.0, 1000.0, 0.0, 1000.0], dtype=np.float32), 0, 0.1)
assert result
assert detection is not None
yield detection | ['def', 'detection_centre_left_point():', '(result,', 'detection)', '=', 'detections_and_time.Detection.create(np.array([0.0,', '1000.0,', '0.0,', '1000.0],', 'dtype=np.float32),', '0,', '0.1)', 'assert', 'result', 'assert', 'detection', 'is', 'not', 'None', 'yield', 'detection'] | 470,493 |
TARGET-SIDE-DATA-AUG/TSDASG | average_checkpoints.py | average_checkpoints | average_checkpoints | Loads checkpoints from inputs and returns a model with averaged weights. | [
"Loads",
"checkpoints",
"from",
"inputs",
"and",
"returns",
"a",
"model",
"with",
"averaged",
"weights."
] | def average_checkpoints(inputs):
params_dict = collections.OrderedDict()
params_keys = None
new_state = None
num_models = len(inputs)
for fpath in inputs:
with PathManager.open(fpath, 'rb') as f:
state = torch.load(f, map_location=lambda s, _: torch.serialization.default_restore_... | ['def', 'average_checkpoints(inputs):', 'params_dict', '=', 'collections.OrderedDict()', 'params_keys', '=', 'None', 'new_state', '=', 'None', 'num_models', '=', 'len(inputs)', 'for', 'fpath', 'in', 'inputs:', 'with', 'PathManager.open(fpath,', "'rb')", 'as', 'f:', 'state', '=', 'torch.load(f,', 'map_location=lambda', ... | 952,387 |
rudranil723/mini-main | static.py | PrefixNode.handle_token | handle_token | Class method to parse prefix node and return a Node. | [
"Class",
"method",
"to",
"parse",
"prefix",
"node",
"and",
"return",
"a",
"Node."
] | def handle_token(cls, parser, token, name):
tokens = token.contents.split()
if len(tokens) > 1 and tokens[1] != 'as':
raise template.TemplateSyntaxError("First argument in '%s' must be 'as'" % tokens[0])
if len(tokens) > 1:
varname = tokens[2]
else:
varname = None
return cls(... | ['def', 'handle_token(cls,', 'parser,', 'token,', 'name):', 'tokens', '=', 'token.contents.split()', 'if', 'len(tokens)', '>', '1', 'and', 'tokens[1]', '!=', "'as':", 'raise', 'template.TemplateSyntaxError("First', 'argument', 'in', "'%s'", 'must', 'be', '\'as\'"', '%', 'tokens[0])', 'if', 'len(tokens)', '>', '1:', 'va... | 316,514 |
weimin17/Object-Detection_HelmetDetection | utils.py | stack_pad | stack_pad | Stack tensors along 0-th dim and pad them to be the same shape. | [
"Stack",
"tensors",
"along",
"0-th",
"dim",
"and",
"pad",
"them",
"to",
"be",
"the",
"same",
"shape."
] | def stack_pad(tensors, pad_axes=None, pad_to_lengths=None, dtype=np.float32, pad_value=0):
tensors = [np.asarray(t) for t in tensors]
max_lengths = [max(l) for l in zip(*[t.shape for t in tensors])]
same_axes = dict(enumerate(max_lengths))
if pad_axes is None:
pad_axes = []
if isinstance(pad... | ['def', 'stack_pad(tensors,', 'pad_axes=None,', 'pad_to_lengths=None,', 'dtype=np.float32,', 'pad_value=0):', 'tensors', '=', '[np.asarray(t)', 'for', 't', 'in', 'tensors]', 'max_lengths', '=', '[max(l)', 'for', 'l', 'in', 'zip(*[t.shape', 'for', 't', 'in', 'tensors])]', 'same_axes', '=', 'dict(enumerate(max_lengths))'... | 761,856 |
rudranil723/mini-main | client.py | AdaptationClient.parse_common_folder_path | parse_common_folder_path | Parse a folder path into its component segments. | [
"Parse",
"a",
"folder",
"path",
"into",
"its",
"component",
"segments."
] | def parse_common_folder_path(path: str) -> Dict[str, str]:
m = re.match('^folders/(?P<folder>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_common_folder_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^folders/(?P<folder>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 317,982 |
enuguru/artificial_intelligence_and_machine_ | bccache.py | Bucket.bytecode_from_string | bytecode_from_string | Load bytecode from a string. | [
"Load",
"bytecode",
"from",
"a",
"string."
] | def bytecode_from_string(self, string):
self.load_bytecode(BytesIO(string)) | ['def', 'bytecode_from_string(self,', 'string):', 'self.load_bytecode(BytesIO(string))'] | 158,126 |
tusen-ai/SST | kitti_converter.py | convert_to_kitti_info_version2 | convert_to_kitti_info_version2 | convert kitti info v1 to v2 if possible. | [
"convert",
"kitti",
"info",
"v1",
"to",
"v2",
"if",
"possible."
] | def convert_to_kitti_info_version2(info):
if 'image' not in info or 'calib' not in info or 'point_cloud' not in info:
info['image'] = {'image_shape': info['img_shape'], 'image_idx': info['image_idx'], 'image_path': info['img_path']}
info['calib'] = {'R0_rect': info['calib/R0_rect'], 'Tr_velo_to_cam'... | ['def', 'convert_to_kitti_info_version2(info):', 'if', "'image'", 'not', 'in', 'info', 'or', "'calib'", 'not', 'in', 'info', 'or', "'point_cloud'", 'not', 'in', 'info:', "info['image']", '=', "{'image_shape':", "info['img_shape'],", "'image_idx':", "info['image_idx'],", "'image_path':", "info['img_path']}", "info['cali... | 872,692 |
Kvatsx/Artificial-Intelligence-Assignments | iostream.py | _StreamBuffer.peek | peek | Get a view over at most ``size`` bytes (possibly fewer) at the current buffer position. | [
"Get",
"a",
"view",
"over",
"at",
"most",
"``size``",
"bytes",
"(possibly",
"fewer)",
"at",
"the",
"current",
"buffer",
"position."
] | def peek(self, size):
assert size > 0
try:
(is_memview, b) = self._buffers[0]
except IndexError:
return memoryview(b'')
pos = self._first_pos
if is_memview:
return b[pos:pos + size]
else:
return memoryview(b)[pos:pos + size] | ['def', 'peek(self,', 'size):', 'assert', 'size', '>', '0', 'try:', '(is_memview,', 'b)', '=', 'self._buffers[0]', 'except', 'IndexError:', 'return', "memoryview(b'')", 'pos', '=', 'self._first_pos', 'if', 'is_memview:', 'return', 'b[pos:pos', '+', 'size]', 'else:', 'return', 'memoryview(b)[pos:pos', '+', 'size]'] | 78,637 |
famura/SimuRLacra | base.py | RcsSim.state_space | state_space | Derives the state space from the observation space using _state_from_obs or state_mask. | [
"Derives",
"the",
"state",
"space",
"from",
"the",
"observation",
"space",
"using",
"_state_from_obs",
"or",
"state_mask."
] | def state_space(self) -> Space:
obs_space = self.obs_space
if self._state_from_obs.__func__ != RcsSim._state_from_obs:
return BoxSpace(self._state_from_obs(obs_space.bound_lo), self._state_from_obs(obs_space.bound_up), None)
if self.state_mask is not None:
return obs_space.subspace(self.stat... | ['def', 'state_space(self)', '->', 'Space:', 'obs_space', '=', 'self.obs_space', 'if', 'self._state_from_obs.__func__', '!=', 'RcsSim._state_from_obs:', 'return', 'BoxSpace(self._state_from_obs(obs_space.bound_lo),', 'self._state_from_obs(obs_space.bound_up),', 'None)', 'if', 'self.state_mask', 'is', 'not', 'None:', 'r... | 883,696 |
Deci-AI/super-gradients | processing.py | default_vit_imagenet_processing_params | default_vit_imagenet_processing_params | Processing parameters used by ViT for training resnet on Imagenet dataset. | [
"Processing",
"parameters",
"used",
"by",
"ViT",
"for",
"training",
"resnet",
"on",
"Imagenet",
"dataset."
] | def default_vit_imagenet_processing_params() -> dict:
image_processor = ComposeProcessing([Resize(size=256), CenterCrop(size=224), StandardizeImage(), NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), ImagePermute()])
params = dict(class_names=IMAGENET_CLASSES, image_processor=image_processor)
retu... | ['def', 'default_vit_imagenet_processing_params()', '->', 'dict:', 'image_processor', '=', 'ComposeProcessing([Resize(size=256),', 'CenterCrop(size=224),', 'StandardizeImage(),', 'NormalizeImage(mean=[0.5,', '0.5,', '0.5],', 'std=[0.5,', '0.5,', '0.5]),', 'ImagePermute()])', 'params', '=', 'dict(class_names=IMAGENET_CL... | 880,394 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | enum.py | unique | unique | Class decorator for enumerations ensuring unique member values. | [
"Class",
"decorator",
"for",
"enumerations",
"ensuring",
"unique",
"member",
"values."
] | def unique(enumeration):
duplicates = []
for (name, member) in enumeration.__members__.items():
if name != member.name:
duplicates.append((name, member.name))
if duplicates:
alias_details = ', '.join(['%s -> %s' % (alias, name) for (alias, name) in duplicates])
raise Valu... | ['def', 'unique(enumeration):', 'duplicates', '=', '[]', 'for', '(name,', 'member)', 'in', 'enumeration.__members__.items():', 'if', 'name', '!=', 'member.name:', 'duplicates.append((name,', 'member.name))', 'if', 'duplicates:', 'alias_details', '=', "',", "'.join(['%s", '->', "%s'", '%', '(alias,', 'name)', 'for', '(a... | 801,444 |
google-research/scenic | audiovisual_tfrecord_dataset.py | get_dataset | get_dataset | Returns a generator for dataset. | [
"Returns",
"a",
"generator",
"for",
"dataset."
] | def get_dataset(*, batch_size: int, eval_batch_size: int, num_shards: int, dtype_str: Text='float32', shuffle_seed: Optional[int]=0, rng: Optional[Rng]=None, dataset_configs: ml_collections.ConfigDict, dataset_service_address: Optional[str]=None) -> dataset_utils.Dataset:
del rng
shuffle_buffer_size = dataset_c... | ['def', 'get_dataset(*,', 'batch_size:', 'int,', 'eval_batch_size:', 'int,', 'num_shards:', 'int,', 'dtype_str:', "Text='float32',", 'shuffle_seed:', 'Optional[int]=0,', 'rng:', 'Optional[Rng]=None,', 'dataset_configs:', 'ml_collections.ConfigDict,', 'dataset_service_address:', 'Optional[str]=None)', '->', 'dataset_uti... | 846,482 |
huiminren/RobustVAE | RPCA_VAE.py | batches | batches | Yield successive n-sized batches from l, the last batch is the left indexes. | [
"Yield",
"successive",
"n-sized",
"batches",
"from",
"l,",
"the",
"last",
"batch",
"is",
"the",
"left",
"indexes."
] | def batches(l, n):
for i in range(0, l, n):
yield range(i, min(l, i + n)) | ['def', 'batches(l,', 'n):', 'for', 'i', 'in', 'range(0,', 'l,', 'n):', 'yield', 'range(i,', 'min(l,', 'i', '+', 'n))'] | 826,430 |
fcjian/TOOD | paa_head.py | PAAHead.paa_reassign | paa_reassign | Fit loss to GMM distribution and separate positive, ignore, negative samples again with GMM model. | [
"Fit",
"loss",
"to",
"GMM",
"distribution",
"and",
"separate",
"positive,",
"ignore,",
"negative",
"samples",
"again",
"with",
"GMM",
"model."
] | def paa_reassign(self, pos_losses, label, label_weight, bbox_weight, pos_inds, pos_gt_inds, anchors):
if not len(pos_inds):
return (label, label_weight, bbox_weight, 0)
label = label.clone()
label_weight = label_weight.clone()
bbox_weight = bbox_weight.clone()
num_gt = pos_gt_inds.max() + 1
... | ['def', 'paa_reassign(self,', 'pos_losses,', 'label,', 'label_weight,', 'bbox_weight,', 'pos_inds,', 'pos_gt_inds,', 'anchors):', 'if', 'not', 'len(pos_inds):', 'return', '(label,', 'label_weight,', 'bbox_weight,', '0)', 'label', '=', 'label.clone()', 'label_weight', '=', 'label_weight.clone()', 'bbox_weight', '=', 'bb... | 902,072 |
elliottwu/unsup3d | utils.py | xmkdir | xmkdir | Create directory PATH recursively if it does not exist. | [
"Create",
"directory",
"PATH",
"recursively",
"if",
"it",
"does",
"not",
"exist."
] | def xmkdir(path):
os.makedirs(path, exist_ok=True) | ['def', 'xmkdir(path):', 'os.makedirs(path,', 'exist_ok=True)'] | 378,714 |
flow-project/flow | test_environments.py | TestAccelEnv.test_observed | test_observed | Ensures that the observed ids are returning the correct vehicles. | [
"Ensures",
"that",
"the",
"observed",
"ids",
"are",
"returning",
"the",
"correct",
"vehicles."
] | def test_observed(self):
self.assertTrue(test_observed(env_class=AccelEnv, sim_params=self.sim_params, network=self.network, env_params=self.env_params, expected_observed=['human_0'])) | ['def', 'test_observed(self):', 'self.assertTrue(test_observed(env_class=AccelEnv,', 'sim_params=self.sim_params,', 'network=self.network,', 'env_params=self.env_params,', "expected_observed=['human_0']))"] | 212,432 |
weimin17/Object-Detection_HelmetDetection | transformer_units.py | split_heads | split_heads | Splits channels (dimension 3) into multiple heads (becomes dimension 1). | [
"Splits",
"channels",
"(dimension",
"3)",
"into",
"multiple",
"heads",
"(becomes",
"dimension",
"1)."
] | def split_heads(x, num_heads):
return tf.transpose(split_last_dimension(x, num_heads), [0, 2, 1, 3]) | ['def', 'split_heads(x,', 'num_heads):', 'return', 'tf.transpose(split_last_dimension(x,', 'num_heads),', '[0,', '2,', '1,', '3])'] | 753,516 |
Eric3911/OpenAGI | tabular_tokenizer.py | TabularTokenizer.ids_to_tokens | ids_to_tokens | Converts a sequence of ids in Tabular tokens using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"ids",
"in",
"Tabular",
"tokens",
"using",
"the",
"vocab."
] | def ids_to_tokens(self, ids, skip_special_tokens=False):
tokens = []
sizes = self.code_column.sizes
ids_size = sum(sizes)
cindex = 0
eor_pos = find_index_of(ids, self.eor)
eod_pos = find_index_of(ids, self.eod)
if eor_pos >= 0 and eod_pos >= 0:
idd = min(eor_pos, eod_pos)
cin... | ['def', 'ids_to_tokens(self,', 'ids,', 'skip_special_tokens=False):', 'tokens', '=', '[]', 'sizes', '=', 'self.code_column.sizes', 'ids_size', '=', 'sum(sizes)', 'cindex', '=', '0', 'eor_pos', '=', 'find_index_of(ids,', 'self.eor)', 'eod_pos', '=', 'find_index_of(ids,', 'self.eod)', 'if', 'eor_pos', '>=', '0', 'and', '... | 273,153 |
myothida/Supervised-Machine-Learning | __init__.py | intersect_glyphs | intersect_glyphs | Returns set of intersecting glyphs. | [
"Returns",
"set",
"of",
"intersecting",
"glyphs."
] | def intersect_glyphs(self, glyphs):
return set((g for g in self.glyphs if g in glyphs)) | ['def', 'intersect_glyphs(self,', 'glyphs):', 'return', 'set((g', 'for', 'g', 'in', 'self.glyphs', 'if', 'g', 'in', 'glyphs))'] | 361,139 |
deepmind/trfl | pixel_control_ops_test.py | PixelControlLossTest.setUp | setUp | Defines example data and expected result for the op. | [
"Defines",
"example",
"data",
"and",
"expected",
"result",
"for",
"the",
"op."
] | def setUp(self):
super(PixelControlLossTest, self).setUp()
self.seq_length = 3
self.batch_size = 1
num_actions = 3
obs_shape = (2, 2, num_actions)
self.discount = 0.9
self.cell_size = 1
self.scale = 1.0
self.observations_ph = tf.placeholder(shape=(self.seq_length + 1, self.batch_size... | ['def', 'setUp(self):', 'super(PixelControlLossTest,', 'self).setUp()', 'self.seq_length', '=', '3', 'self.batch_size', '=', '1', 'num_actions', '=', '3', 'obs_shape', '=', '(2,', '2,', 'num_actions)', 'self.discount', '=', '0.9', 'self.cell_size', '=', '1', 'self.scale', '=', '1.0', 'self.observations_ph', '=', 'tf.pl... | 356,228 |
rifqind/Agent-Programs-3KS1 | mixer_test.py | SoundTypeTest.todo_test_sound__from_array | todo_test_sound__from_array | Ensure Sound() creation with an array works. | [
"Ensure",
"Sound()",
"creation",
"with",
"an",
"array",
"works."
] | def todo_test_sound__from_array(self):
self.fail() | ['def', 'todo_test_sound__from_array(self):', 'self.fail()'] | 45,902 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | expert_utils.py | local_moe | local_moe | Call a local mixture of experts. | [
"Call",
"a",
"local",
"mixture",
"of",
"experts."
] | def local_moe(x, train, expert_fn, num_experts, k=1, loss_coef=0.01, hparams=None, pass_x=True, pass_gates=False, additional_dispatch_params=None, name=None):
bneck = DiscreteBottleneck(hparams)
with tf.variable_scope(name, default_name='local_moe'):
centroids = None
x_flat = flatten_all_but_las... | ['def', 'local_moe(x,', 'train,', 'expert_fn,', 'num_experts,', 'k=1,', 'loss_coef=0.01,', 'hparams=None,', 'pass_x=True,', 'pass_gates=False,', 'additional_dispatch_params=None,', 'name=None):', 'bneck', '=', 'DiscreteBottleneck(hparams)', 'with', 'tf.variable_scope(name,', "default_name='local_moe'):", 'centroids', '... | 966,088 |
clvrai/spirl | vis_utils.py | make_image_seq_strip | make_image_seq_strip | Creates image strip where each row contains full rollout of sequence [each element of list makes one row]. | [
"Creates",
"image",
"strip",
"where",
"each",
"row",
"contains",
"full",
"rollout",
"of",
"sequence",
"[each",
"element",
"of",
"list",
"makes",
"one",
"row]."
] | def make_image_seq_strip(imgs, n_logged_samples=5):
plot_imgs = stack_with_separator(imgs, dim=3)[:n_logged_samples]
return stack_with_separator([t[:, 0] for t in torch.split(plot_imgs, 1, dim=1)], dim=3) | ['def', 'make_image_seq_strip(imgs,', 'n_logged_samples=5):', 'plot_imgs', '=', 'stack_with_separator(imgs,', 'dim=3)[:n_logged_samples]', 'return', 'stack_with_separator([t[:,', '0]', 'for', 't', 'in', 'torch.split(plot_imgs,', '1,', 'dim=1)],', 'dim=3)'] | 897,092 |
michiyasunaga/BIFI | trainer.py | Trainer.lr_step | lr_step | Adjust the learning rate at the end of the epoch. | [
"Adjust",
"the",
"learning",
"rate",
"at",
"the",
"end",
"of",
"the",
"epoch."
] | def lr_step(self, epoch, val_loss=None):
self.lr_scheduler.step(epoch, val_loss)
return self.lr_step_update() | ['def', 'lr_step(self,', 'epoch,', 'val_loss=None):', 'self.lr_scheduler.step(epoch,', 'val_loss)', 'return', 'self.lr_step_update()'] | 107,313 |
jonathanking/sidechainnet | measure.py | check_standard_continuous | check_standard_continuous | Asserts that the residue is standard and that the chain is continuous. | [
"Asserts",
"that",
"the",
"residue",
"is",
"standard",
"and",
"that",
"the",
"chain",
"is",
"continuous."
] | def check_standard_continuous(residue, prev_res_num):
if not residue.isstdaa:
raise NonStandardAminoAcidError('Found a non-std AA.')
if residue.getResnum() != prev_res_num:
raise IncompleteStructureError('Chain is missing residues.')
return True | ['def', 'check_standard_continuous(residue,', 'prev_res_num):', 'if', 'not', 'residue.isstdaa:', 'raise', "NonStandardAminoAcidError('Found", 'a', 'non-std', "AA.')", 'if', 'residue.getResnum()', '!=', 'prev_res_num:', 'raise', "IncompleteStructureError('Chain", 'is', 'missing', "residues.')", 'return', 'True'] | 934,119 |
thu-ml/ares | utils.py | get_word_size | get_word_size | Return the number of used GPUs. | [
"Return",
"the",
"number",
"of",
"used",
"GPUs."
] | def get_word_size(group=None):
if is_distributed():
if group is None:
group = dist.distributed_c10d._get_default_group()
return dist.get_world_size(group)
else:
return 1 | ['def', 'get_word_size(group=None):', 'if', 'is_distributed():', 'if', 'group', 'is', 'None:', 'group', '=', 'dist.distributed_c10d._get_default_group()', 'return', 'dist.get_world_size(group)', 'else:', 'return', '1'] | 402,100 |
RasaHQ/rasa_core | trackers.py | DialogueStateTracker.last_executed_action_has | last_executed_action_has | Returns whether last `ActionExecuted` event had a specific name. | [
"Returns",
"whether",
"last",
"`ActionExecuted`",
"event",
"had",
"a",
"specific",
"name."
] | def last_executed_action_has(self, name: Text, skip=0) -> bool:
last = self.get_last_event_for(ActionExecuted, action_names_to_exclude=[ACTION_LISTEN_NAME], skip=skip)
return last is not None and last.action_name == name | ['def', 'last_executed_action_has(self,', 'name:', 'Text,', 'skip=0)', '->', 'bool:', 'last', '=', 'self.get_last_event_for(ActionExecuted,', 'action_names_to_exclude=[ACTION_LISTEN_NAME],', 'skip=skip)', 'return', 'last', 'is', 'not', 'None', 'and', 'last.action_name', '==', 'name'] | 838,247 |
triaquae/triaquae | case.py | TestCase.assertListEqual | assertListEqual | A list-specific equality assertion. | [
"A",
"list-specific",
"equality",
"assertion."
] | def assertListEqual(self, list1, list2, msg=None):
self.assertSequenceEqual(list1, list2, msg, seq_type=list) | ['def', 'assertListEqual(self,', 'list1,', 'list2,', 'msg=None):', 'self.assertSequenceEqual(list1,', 'list2,', 'msg,', 'seq_type=list)'] | 424,255 |
myothida/Supervised-Machine-Learning | buffer.py | PandasBuffer.bufsize | bufsize | Buffer size in bytes. | [
"Buffer",
"size",
"in",
"bytes."
] | def bufsize(self) -> int:
return self._x.size * self._x.dtype.itemsize | ['def', 'bufsize(self)', '->', 'int:', 'return', 'self._x.size', '*', 'self._x.dtype.itemsize'] | 442,962 |
danielyule/hearthbreaker | _utils.py | flatten | flatten | isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument. | [
"isinstance()",
"can",
"accept",
"a",
"bunch",
"of",
"really",
"annoying",
"different",
"types:",
"*",
"a",
"single",
"type",
"*",
"a",
"tuple",
"of",
"types",
"*",
"an",
"arbitrary",
"nested",
"tree",
"of",
"tuples",
"Return",
"a",
"flattened",
"tuple",
"... | def flatten(suitable_for_isinstance):
types = set()
if not isinstance(suitable_for_isinstance, tuple):
suitable_for_isinstance = (suitable_for_isinstance,)
for thing in suitable_for_isinstance:
if isinstance(thing, tuple):
types.update(flatten(thing))
else:
ty... | ['def', 'flatten(suitable_for_isinstance):', 'types', '=', 'set()', 'if', 'not', 'isinstance(suitable_for_isinstance,', 'tuple):', 'suitable_for_isinstance', '=', '(suitable_for_isinstance,)', 'for', 'thing', 'in', 'suitable_for_isinstance:', 'if', 'isinstance(thing,', 'tuple):', 'types.update(flatten(thing))', 'else:'... | 589,133 |
enuguru/artificial_intelligence_and_machine_learning | __init__.py | DebuggedApplication.pin_cookie_name | pin_cookie_name | The name of the pin cookie. | [
"The",
"name",
"of",
"the",
"pin",
"cookie."
] | def pin_cookie_name(self):
if not hasattr(self, '_pin_cookie'):
(self._pin, self._pin_cookie) = get_pin_and_cookie_name(self.app)
return self._pin_cookie | ['def', 'pin_cookie_name(self):', 'if', 'not', 'hasattr(self,', "'_pin_cookie'):", '(self._pin,', 'self._pin_cookie)', '=', 'get_pin_and_cookie_name(self.app)', 'return', 'self._pin_cookie'] | 132,779 |
ArtificialIntelligenceToolkit/aitk.robots | world.py | World.get_time | get_time | Get the simulated time as a formatted string. | [
"Get",
"the",
"simulated",
"time",
"as",
"a",
"formatted",
"string."
] | def get_time(self):
return format_time(self.time) | ['def', 'get_time(self):', 'return', 'format_time(self.time)'] | 86,658 |
lebrice/Sequoia | base_test.py | _TestAvalancheMethod.method | method | Fixture that returns the Method instance to use when testing/debugging. | [
"Fixture",
"that",
"returns",
"the",
"Method",
"instance",
"to",
"use",
"when",
"testing/debugging."
] | def method(cls, config: Config, request) -> AvalancheMethod:
model_type = request.param
return cls.Method(model=model_type, train_mb_size=10, train_epochs=1) | ['def', 'method(cls,', 'config:', 'Config,', 'request)', '->', 'AvalancheMethod:', 'model_type', '=', 'request.param', 'return', 'cls.Method(model=model_type,', 'train_mb_size=10,', 'train_epochs=1)'] | 344,298 |
dgaeta/feedforward-neural-net-SDG-backprop | mnist.py | plot_bad_images | plot_bad_images | This takes a list of images misclassified by a pretty good neural network --- one achieving over 93 percent accuracy --- and turns them into a figure. | [
"This",
"takes",
"a",
"list",
"of",
"images",
"misclassified",
"by",
"a",
"pretty",
"good",
"neural",
"network",
"---",
"one",
"achieving",
"over",
"93",
"percent",
"accuracy",
"---",
"and",
"turns",
"them",
"into",
"a",
"figure."
] | def plot_bad_images(images):
bad_image_indices = [8, 18, 33, 92, 119, 124, 149, 151, 193, 233, 241, 247, 259, 300, 313, 321, 324, 341, 349, 352, 359, 362, 381, 412, 435, 445, 449, 478, 479, 495, 502, 511, 528, 531, 547, 571, 578, 582, 597, 610, 619, 628, 629, 659, 667, 691, 707, 717, 726, 740, 791, 810, 844, 846, 8... | ['def', 'plot_bad_images(images):', 'bad_image_indices', '=', '[8,', '18,', '33,', '92,', '119,', '124,', '149,', '151,', '193,', '233,', '241,', '247,', '259,', '300,', '313,', '321,', '324,', '341,', '349,', '352,', '359,', '362,', '381,', '412,', '435,', '445,', '449,', '478,', '479,', '495,', '502,', '511,', '528,'... | 581,927 |
cslu-nlp/nlup | perceptron.py | Perceptron.register_classes | register_classes | Registers class labels in classifier instance. | [
"Registers",
"class",
"labels",
"in",
"classifier",
"instance."
] | def register_classes(self, classes):
self.classes = tuple(classes) | ['def', 'register_classes(self,', 'classes):', 'self.classes', '=', 'tuple(classes)'] | 731,725 |
MushroomRL/mushroom-rl | lqr.py | compute_lqr_feedback_gain | compute_lqr_feedback_gain | Computes the optimal gain matrix K. | [
"Computes",
"the",
"optimal",
"gain",
"matrix",
"K."
] | def compute_lqr_feedback_gain(lqr, max_iterations=100):
(A, B, Q, R, gamma) = _parse_lqr(lqr)
P = np.eye(Q.shape[0])
K = _compute_riccati_gain(P, A, B, R, gamma)
it = 0
while it < max_iterations:
P = _compute_riccati_rhs(A, B, Q, R, gamma, K, P)
K = _compute_riccati_gain(P, A, B, R, ... | ['def', 'compute_lqr_feedback_gain(lqr,', 'max_iterations=100):', '(A,', 'B,', 'Q,', 'R,', 'gamma)', '=', '_parse_lqr(lqr)', 'P', '=', 'np.eye(Q.shape[0])', 'K', '=', '_compute_riccati_gain(P,', 'A,', 'B,', 'R,', 'gamma)', 'it', '=', '0', 'while', 'it', '<', 'max_iterations:', 'P', '=', '_compute_riccati_rhs(A,', 'B,',... | 266,095 |
tensorflow/quantum | parameter_shift_util_test.py | ParameterShiftUtilTest.test_parse_programs | test_parse_programs | Input & output check for parse_programs(). | [
"Input",
"&",
"output",
"check",
"for",
"parse_programs()."
] | def test_parse_programs(self):
n_qubits = 5
n_programs = 3
n_shifts = 2
symbol_names = ['a', 'b']
n_symbols = len(symbol_names)
sympy_symbols = [sympy.Symbol(s) for s in symbol_names]
coeff = [1.0, -2.0, 3.0, -4.0, 5.0]
q = cirq.GridQubit.rect(1, n_qubits)
c = cirq.Circuit()
c.ap... | ['def', 'test_parse_programs(self):', 'n_qubits', '=', '5', 'n_programs', '=', '3', 'n_shifts', '=', '2', 'symbol_names', '=', "['a',", "'b']", 'n_symbols', '=', 'len(symbol_names)', 'sympy_symbols', '=', '[sympy.Symbol(s)', 'for', 's', 'in', 'symbol_names]', 'coeff', '=', '[1.0,', '-2.0,', '3.0,', '-4.0,', '5.0]', 'q'... | 835,253 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | mailbox.py | Mailbox.keys | keys | Return a list of keys. | [
"Return",
"a",
"list",
"of",
"keys."
] | def keys(self):
return list(self.iterkeys()) | ['def', 'keys(self):', 'return', 'list(self.iterkeys())'] | 428,808 |
tensorflow/agents | common_test.py | PeriodicallyTest.testPeriodNone | testPeriodNone | Tests that the function is never called if period == None. | [
"Tests",
"that",
"the",
"function",
"is",
"never",
"called",
"if",
"period",
"==",
"None."
] | def testPeriodNone(self):
target = tf.compat.v2.Variable(0)
periodic_update = common.periodically(body=lambda : target.assign_add(1), period=None)
self.evaluate(tf.compat.v1.global_variables_initializer())
desired_value = 0
for _ in range(1, 11):
(_, result) = self.evaluate([periodic_update,... | ['def', 'testPeriodNone(self):', 'target', '=', 'tf.compat.v2.Variable(0)', 'periodic_update', '=', 'common.periodically(body=lambda', ':', 'target.assign_add(1),', 'period=None)', 'self.evaluate(tf.compat.v1.global_variables_initializer())', 'desired_value', '=', '0', 'for', '_', 'in', 'range(1,', '11):', '(_,', 'resu... | 23,088 |
eddylau328/fyp-artificial-intelligence-ac-control-device | message.py | Message.Clear | Clear | Clears all data that was set in the message. | [
"Clears",
"all",
"data",
"that",
"was",
"set",
"in",
"the",
"message."
] | def Clear(self):
raise NotImplementedError | ['def', 'Clear(self):', 'raise', 'NotImplementedError'] | 215,210 |
sunishsheth2009/ChatterBot | six.py | itervalues | itervalues | Return an iterator over the values of a dictionary. | [
"Return",
"an",
"iterator",
"over",
"the",
"values",
"of",
"a",
"dictionary."
] | def itervalues(d):
return iter(getattr(d, _itervalues)()) | ['def', 'itervalues(d):', 'return', 'iter(getattr(d,', '_itervalues)())'] | 480,730 |
implus/GFocalV2 | structures.py | PolygonMasks.to_bitmap | to_bitmap | convert polygon masks to bitmap masks. | [
"convert",
"polygon",
"masks",
"to",
"bitmap",
"masks."
] | def to_bitmap(self):
bitmap_masks = self.to_ndarray()
return BitmapMasks(bitmap_masks, self.height, self.width) | ['def', 'to_bitmap(self):', 'bitmap_masks', '=', 'self.to_ndarray()', 'return', 'BitmapMasks(bitmap_masks,', 'self.height,', 'self.width)'] | 557,426 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Base.isPublic | isPublic | True if this item is static. | [
"True",
"if",
"this",
"item",
"is",
"static."
] | def isPublic(self):
return 'public' in self.modifiers | ['def', 'isPublic(self):', 'return', "'public'", 'in', 'self.modifiers'] | 10,782 |
RLE-Foundation/rllte | __init__.py | make_envpool_atari_env | make_envpool_atari_env | Create Atari environments with `envpool`. | [
"Create",
"Atari",
"environments",
"with",
"`envpool`."
] | def make_envpool_atari_env(env_id: str='Alien-v5', num_envs: int=8, device: str='cpu', seed: int=1, asynchronous: bool=True) -> Gymnasium2Torch:
env_kwargs = dict(task_id=env_id, env_type='gymnasium', num_envs=num_envs, batch_size=num_envs, seed=seed, episodic_life=True, reward_clip=False)
if asynchronous:
... | ['def', 'make_envpool_atari_env(env_id:', "str='Alien-v5',", 'num_envs:', 'int=8,', 'device:', "str='cpu',", 'seed:', 'int=1,', 'asynchronous:', 'bool=True)', '->', 'Gymnasium2Torch:', 'env_kwargs', '=', 'dict(task_id=env_id,', "env_type='gymnasium',", 'num_envs=num_envs,', 'batch_size=num_envs,', 'seed=seed,', 'episod... | 333,526 |
xavialex/Streamlit-TF-Real-Time-Object- | box_predictor_builder.py | build_weight_shared_convolutional_keras_box_predictor | build_weight_shared_convolutional_keras_box_predictor | Builds the Keras WeightSharedConvolutionalBoxPredictor from the arguments. | [
"Builds",
"the",
"Keras",
"WeightSharedConvolutionalBoxPredictor",
"from",
"the",
"arguments."
] | def build_weight_shared_convolutional_keras_box_predictor(is_training, num_classes, conv_hyperparams, freeze_batchnorm, inplace_batchnorm_update, num_predictions_per_location_list, depth, num_layers_before_predictor, box_code_size, kernel_size=3, add_background_class=True, class_prediction_bias_init=0.0, use_dropout=Fa... | ['def', 'build_weight_shared_convolutional_keras_box_predictor(is_training,', 'num_classes,', 'conv_hyperparams,', 'freeze_batchnorm,', 'inplace_batchnorm_update,', 'num_predictions_per_location_list,', 'depth,', 'num_layers_before_predictor,', 'box_code_size,', 'kernel_size=3,', 'add_background_class=True,', 'class_pr... | 909,418 |
rudranil723/mini-main | utils.py | ConnectionRouter.get_migratable_models | get_migratable_models | Return app models allowed to be migrated on provided db. | [
"Return",
"app",
"models",
"allowed",
"to",
"be",
"migrated",
"on",
"provided",
"db."
] | def get_migratable_models(self, app_config, db, include_auto_created=False):
models = app_config.get_models(include_auto_created=include_auto_created)
return [model for model in models if self.allow_migrate_model(db, model)] | ['def', 'get_migratable_models(self,', 'app_config,', 'db,', 'include_auto_created=False):', 'models', '=', 'app_config.get_models(include_auto_created=include_auto_created)', 'return', '[model', 'for', 'model', 'in', 'models', 'if', 'self.allow_migrate_model(db,', 'model)]'] | 315,695 |
BMIRDS/deepslide | utils_evaluation.py | get_scores | get_scores | Find the average class accuracy of the predictions. | [
"Find",
"the",
"average",
"class",
"accuracy",
"of",
"the",
"predictions."
] | def get_scores(gt_labels: Dict[str, str], prediction_labels: Dict[str, str], classes: List[str]) -> Tuple[float, np.ndarray]:
class_to_gt_count = {_class: 0 for _class in classes}
class_to_pred_count = {_class: 0 for _class in classes}
gts = []
preds = []
for file in sorted(gt_labels.keys()):
... | ['def', 'get_scores(gt_labels:', 'Dict[str,', 'str],', 'prediction_labels:', 'Dict[str,', 'str],', 'classes:', 'List[str])', '->', 'Tuple[float,', 'np.ndarray]:', 'class_to_gt_count', '=', '{_class:', '0', 'for', '_class', 'in', 'classes}', 'class_to_pred_count', '=', '{_class:', '0', 'for', '_class', 'in', 'classes}',... | 539,800 |
deepmind/dm_control | cmu_2020_tracking.py | cmu_humanoid_tracking | cmu_humanoid_tracking | Requires a CMU humanoid to run down a corridor obstructed by walls. | [
"Requires",
"a",
"CMU",
"humanoid",
"to",
"run",
"down",
"a",
"corridor",
"obstructed",
"by",
"walls."
] | def cmu_humanoid_tracking(random_state=None):
walker_type = cmu_humanoid.CMUHumanoidPositionControlledV2020
arena = arenas.Floor()
task = tracking.MultiClipMocapTracking(walker=walker_type, arena=arena, ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'), dataset='walk_tiny', ref_steps=(1, 2, 3, 4, 5),... | ['def', 'cmu_humanoid_tracking(random_state=None):', 'walker_type', '=', 'cmu_humanoid.CMUHumanoidPositionControlledV2020', 'arena', '=', 'arenas.Floor()', 'task', '=', 'tracking.MultiClipMocapTracking(walker=walker_type,', 'arena=arena,', "ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'),", "dataset='walk_tiny... | 165,058 |
clips/pattern | tree.py | table | table | Returns a string where the tags of tokens in the sentence are organized in outlined columns. | [
"Returns",
"a",
"string",
"where",
"the",
"tags",
"of",
"tokens",
"in",
"the",
"sentence",
"are",
"organized",
"in",
"outlined",
"columns."
] | def table(sentence, fill=1, placeholder='-'):
tags = [WORD, POS, IOB, CHUNK, ROLE, REL, PNP, ANCHOR, LEMMA]
tags += [tag for tag in sentence.token if tag not in tags]
def format(token, tag):
if tag == WORD:
s = token.string
elif tag == POS:
s = token.type
eli... | ['def', 'table(sentence,', 'fill=1,', "placeholder='-'):", 'tags', '=', '[WORD,', 'POS,', 'IOB,', 'CHUNK,', 'ROLE,', 'REL,', 'PNP,', 'ANCHOR,', 'LEMMA]', 'tags', '+=', '[tag', 'for', 'tag', 'in', 'sentence.token', 'if', 'tag', 'not', 'in', 'tags]', 'def', 'format(token,', 'tag):', 'if', 'tag', '==', 'WORD:', 's', '=', ... | 764,772 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | vggish_postprocess.py | Postprocessor.postprocess | postprocess | Applies postprocessing to a batch of embeddings. | [
"Applies",
"postprocessing",
"to",
"a",
"batch",
"of",
"embeddings."
] | def postprocess(self, embeddings_batch):
assert len(embeddings_batch.shape) == 2, 'Expected 2-d batch, got %r' % (embeddings_batch.shape,)
assert embeddings_batch.shape[1] == vggish_params.EMBEDDING_SIZE, 'Bad batch shape: %r' % (embeddings_batch.shape,)
pca_applied = np.dot(self._pca_matrix, embeddings_bat... | ['def', 'postprocess(self,', 'embeddings_batch):', 'assert', 'len(embeddings_batch.shape)', '==', '2,', "'Expected", '2-d', 'batch,', 'got', "%r'", '%', '(embeddings_batch.shape,)', 'assert', 'embeddings_batch.shape[1]', '==', 'vggish_params.EMBEDDING_SIZE,', "'Bad", 'batch', 'shape:', "%r'", '%', '(embeddings_batch.sh... | 46,180 |
intelligent-environments-lab/CityLearn | building.py | DynamicsBuilding.net_electricity_consumption_cost_without_storage_and_partial_load_and_pv | net_electricity_consumption_cost_without_storage_and_partial_load_and_pv | net_electricity_consumption_without_storage_and_partial_load_and_pv` cost time series, in [$]. | [
"net_electricity_consumption_without_storage_and_partial_load_and_pv`",
"cost",
"time",
"series,",
"in",
"[$]."
] | def net_electricity_consumption_cost_without_storage_and_partial_load_and_pv(self) -> np.ndarray:
return self.pricing.electricity_pricing[0:self.time_step + 1] * self.net_electricity_consumption_without_storage_and_partial_load_and_pv | ['def', 'net_electricity_consumption_cost_without_storage_and_partial_load_and_pv(self)', '->', 'np.ndarray:', 'return', 'self.pricing.electricity_pricing[0:self.time_step', '+', '1]', '*', 'self.net_electricity_consumption_without_storage_and_partial_load_and_pv'] | 105,633 |
NJU-LHRS/official-CMID | misc.py | symlink | symlink | Create a symlink, dst -> src. | [
"Create",
"a",
"symlink,",
"dst",
"->",
"src."
] | def symlink(src: str, dst: str, overwrite: bool=True, **kwargs) -> None:
if os.path.lexists(dst) and overwrite:
os.remove(dst)
os.symlink(src, dst, **kwargs) | ['def', 'symlink(src:', 'str,', 'dst:', 'str,', 'overwrite:', 'bool=True,', '**kwargs)', '->', 'None:', 'if', 'os.path.lexists(dst)', 'and', 'overwrite:', 'os.remove(dst)', 'os.symlink(src,', 'dst,', '**kwargs)'] | 250,185 |
triaquae/triaquae | views.py | PasswordResetTest.test_email_found_custom_from | test_email_found_custom_from | Email is sent if a valid email address is provided for password reset when a custom from_email is provided. | [
"Email",
"is",
"sent",
"if",
"a",
"valid",
"email",
"address",
"is",
"provided",
"for",
"password",
"reset",
"when",
"a",
"custom",
"from_email",
"is",
"provided."
] | def test_email_found_custom_from(self):
response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual('staffmember@example.com', mail.outbox[0].from_email) | ['def', 'test_email_found_custom_from(self):', 'response', '=', "self.client.post('/password_reset_from_email/',", "{'email':", "'staffmember@example.com'})", 'self.assertEqual(response.status_code,', '302)', 'self.assertEqual(len(mail.outbox),', '1)', "self.assertEqual('staffmember@example.com',", 'mail.outbox[0].from... | 357,170 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | LoggerAdapter.hasHandlers | hasHandlers | See if the underlying logger has any handlers. | [
"See",
"if",
"the",
"underlying",
"logger",
"has",
"any",
"handlers."
] | def hasHandlers(self):
return self.logger.hasHandlers() | ['def', 'hasHandlers(self):', 'return', 'self.logger.hasHandlers()'] | 431,234 |
PacktPublishing/-Learn-Artificial-Intelligence-with-TensorFlow | cifar10_model.py | inference | inference | Build the CIFAR-10 model. | [
"Build",
"the",
"CIFAR-10",
"model."
] | def inference(image_batch, batch_size=128):
kernel_size = 5
num_kernels_per_conv = 64
conv_block_1 = conv_block(image_batch, filters=num_kernels_per_conv, kernel_size=kernel_size, name='conv_layer_1')
conv_block_2 = conv_block(conv_block_1, filters=num_kernels_per_conv, kernel_size=kernel_size, name='co... | ['def', 'inference(image_batch,', 'batch_size=128):', 'kernel_size', '=', '5', 'num_kernels_per_conv', '=', '64', 'conv_block_1', '=', 'conv_block(image_batch,', 'filters=num_kernels_per_conv,', 'kernel_size=kernel_size,', "name='conv_layer_1')", 'conv_block_2', '=', 'conv_block(conv_block_1,', 'filters=num_kernels_per... | 4,317 |
deepmind/acme | utils.py | to_numpy | to_numpy | Converts a nest of Tensors to a nest of numpy arrays. | [
"Converts",
"a",
"nest",
"of",
"Tensors",
"to",
"a",
"nest",
"of",
"numpy",
"arrays."
] | def to_numpy(nest: types.NestedTensor) -> types.NestedArray:
return tree.map_structure(lambda x: x.numpy(), nest) | ['def', 'to_numpy(nest:', 'types.NestedTensor)', '->', 'types.NestedArray:', 'return', 'tree.map_structure(lambda', 'x:', 'x.numpy(),', 'nest)'] | 7,867 |
rudranil723/mini-main | glifLib.py | Glyph.draw | draw | Draw this glyph onto a *FontTools* Pen. | [
"Draw",
"this",
"glyph",
"onto",
"a",
"*FontTools*",
"Pen."
] | def draw(self, pen, outputImpliedClosingLine=False):
pointPen = PointToSegmentPen(pen, outputImpliedClosingLine=outputImpliedClosingLine)
self.drawPoints(pointPen) | ['def', 'draw(self,', 'pen,', 'outputImpliedClosingLine=False):', 'pointPen', '=', 'PointToSegmentPen(pen,', 'outputImpliedClosingLine=outputImpliedClosingLine)', 'self.drawPoints(pointPen)'] | 317,477 |
arshpreetsingh/quantopian-machinelearning | test_validators.py | TestDraft3Validator.test_any_type_is_redefinable | test_any_type_is_redefinable | Sigh, because why not. | [
"Sigh,",
"because",
"why",
"not."
] | def test_any_type_is_redefinable(self):
Crazy = validators.extend(self.Validator, type_checker=self.Validator.TYPE_CHECKER.redefine('any', lambda checker, thing: isinstance(thing, int)))
validator = Crazy({'type': 'any'})
validator.validate(12)
with self.assertRaises(exceptions.ValidationError):
... | ['def', 'test_any_type_is_redefinable(self):', 'Crazy', '=', 'validators.extend(self.Validator,', "type_checker=self.Validator.TYPE_CHECKER.redefine('any',", 'lambda', 'checker,', 'thing:', 'isinstance(thing,', 'int)))', 'validator', '=', "Crazy({'type':", "'any'})", 'validator.validate(12)', 'with', 'self.assertRaises... | 887,722 |
deepmind/dm_control | basic_rodent_2020.py | rodent_escape_bowl | rodent_escape_bowl | Requires a rodent to climb out of a bowl-shaped terrain. | [
"Requires",
"a",
"rodent",
"to",
"climb",
"out",
"of",
"a",
"bowl-shaped",
"terrain."
] | def rodent_escape_bowl(random_state=None):
walker = rodent.Rat(observable_options={'egocentric_camera': dict(enabled=True)})
arena = bowl.Bowl(size=(20.0, 20.0), aesthetic='outdoor_natural')
task = escape.Escape(walker=walker, arena=arena, physics_timestep=_PHYSICS_TIMESTEP, control_timestep=_CONTROL_TIMEST... | ['def', 'rodent_escape_bowl(random_state=None):', 'walker', '=', "rodent.Rat(observable_options={'egocentric_camera':", 'dict(enabled=True)})', 'arena', '=', 'bowl.Bowl(size=(20.0,', '20.0),', "aesthetic='outdoor_natural')", 'task', '=', 'escape.Escape(walker=walker,', 'arena=arena,', 'physics_timestep=_PHYSICS_TIMESTE... | 165,922 |
thu-ml/ares | registry.py | Registry.get_model | get_model | Get a model object by given name. | [
"Get",
"a",
"model",
"object",
"by",
"given",
"name."
] | def get_model(cls, name):
if cls.mapping['models'].get(name, None):
return cls.mapping['models'].get(name)
raise KeyError(f'{name} is not registered!') | ['def', 'get_model(cls,', 'name):', 'if', "cls.mapping['models'].get(name,", 'None):', 'return', "cls.mapping['models'].get(name)", 'raise', "KeyError(f'{name}", 'is', 'not', "registered!')"] | 402,234 |
lebrice/Sequoia | measure_performance_test.py | test_last_batch | test_last_batch | Test what happens with the last batch, in the case where the batch size doesn't divide the dataset equally. | [
"Test",
"what",
"happens",
"with",
"the",
"last",
"batch,",
"in",
"the",
"case",
"where",
"the",
"batch",
"size",
"doesn't",
"divide",
"the",
"dataset",
"equally."
] | def test_last_batch():
env = make_dummy_env(n_samples=110, batch_size=20)
env = MeasureSLPerformanceWrapper(env, first_epoch_only=True)
for (i, (obs, rew)) in enumerate(env):
assert rew is None
if i != 5:
assert obs.batch_size == 20, i
else:
assert obs.batch_s... | ['def', 'test_last_batch():', 'env', '=', 'make_dummy_env(n_samples=110,', 'batch_size=20)', 'env', '=', 'MeasureSLPerformanceWrapper(env,', 'first_epoch_only=True)', 'for', '(i,', '(obs,', 'rew))', 'in', 'enumerate(env):', 'assert', 'rew', 'is', 'None', 'if', 'i', '!=', '5:', 'assert', 'obs.batch_size', '==', '20,', '... | 349,699 |
pyelasticsearch/pyelasticsearch | json_tests.py | JsonTests.test_tuple_encoding | test_tuple_encoding | Make sure tuples encode as lists. | [
"Make",
"sure",
"tuples",
"encode",
"as",
"lists."
] | def test_tuple_encoding(self):
self.assertEqual(self.conn._encode_json({'hi': (1, 2, 3)}), '{"hi": [1, 2, 3]}') | ['def', 'test_tuple_encoding(self):', "self.assertEqual(self.conn._encode_json({'hi':", '(1,', '2,', '3)}),', '\'{"hi":', '[1,', '2,', "3]}')"] | 296,280 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | blocks.py | ExtensionBlock.concat_same_type | concat_same_type | Concatenate list of single blocks of the same type. | [
"Concatenate",
"list",
"of",
"single",
"blocks",
"of",
"the",
"same",
"type."
] | def concat_same_type(self, to_concat, placement=None):
values = self._holder._concat_same_type([blk.values for blk in to_concat])
placement = placement or slice(0, len(values), 1)
return self.make_block_same_class(values, ndim=self.ndim, placement=placement) | ['def', 'concat_same_type(self,', 'to_concat,', 'placement=None):', 'values', '=', 'self._holder._concat_same_type([blk.values', 'for', 'blk', 'in', 'to_concat])', 'placement', '=', 'placement', 'or', 'slice(0,', 'len(values),', '1)', 'return', 'self.make_block_same_class(values,', 'ndim=self.ndim,', 'placement=placeme... | 83,030 |
mfbx9da4/neuron-astrocyte-networks | temp_node1.py | sigmoid | sigmoid | Calculates the sigmoid . | [
"Calculates",
"the",
"sigmoid",
"."
] | def sigmoid(value):
try:
value = 1.0 / (1.0 + math.exp(-value))
except OverflowError:
value = 0.0
return value | ['def', 'sigmoid(value):', 'try:', 'value', '=', '1.0', '/', '(1.0', '+', 'math.exp(-value))', 'except', 'OverflowError:', 'value', '=', '0.0', 'return', 'value'] | 722,826 |
bitprophet/ssh | test_client.py | SSHClientTest.test_4_auto_add_policy | test_4_auto_add_policy | verify that SSHClient's AutoAddPolicy works. | [
"verify",
"that",
"SSHClient's",
"AutoAddPolicy",
"works."
] | def test_4_auto_add_policy(self):
host_key = ssh.RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = ssh.RSAKey(data=str(host_key))
self.tc = ssh.SSHClient()
self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy())
self.assertEquals(0, len(self.tc.get_host_keys()))
self.tc.conne... | ['def', 'test_4_auto_add_policy(self):', 'host_key', '=', "ssh.RSAKey.from_private_key_file('tests/test_rsa.key')", 'public_host_key', '=', 'ssh.RSAKey(data=str(host_key))', 'self.tc', '=', 'ssh.SSHClient()', 'self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy())', 'self.assertEquals(0,', 'len(self.tc.get_host_keys(... | 372,500 |
googleapis/python-aiplatform | proto_converters.py | ParameterValueConverter.from_proto | from_proto | Returns whichever value that is populated, or None. | [
"Returns",
"whichever",
"value",
"that",
"is",
"populated,",
"or",
"None."
] | def from_proto(cls, proto: study_pb2.Trial.Parameter) -> Optional[ParameterValue]:
potential_value = proto.value
if isinstance(potential_value, float) or isinstance(potential_value, str) or isinstance(potential_value, bool):
return ParameterValue(potential_value)
else:
return None | ['def', 'from_proto(cls,', 'proto:', 'study_pb2.Trial.Parameter)', '->', 'Optional[ParameterValue]:', 'potential_value', '=', 'proto.value', 'if', 'isinstance(potential_value,', 'float)', 'or', 'isinstance(potential_value,', 'str)', 'or', 'isinstance(potential_value,', 'bool):', 'return', 'ParameterValue(potential_valu... | 810,290 |
astooke/rlpyt | base.py | Distribution.sample | sample | Generate random sample(s) from distribution informations. | [
"Generate",
"random",
"sample(s)",
"from",
"distribution",
"informations."
] | def sample(self, dist_info):
raise NotImplementedError | ['def', 'sample(self,', 'dist_info):', 'raise', 'NotImplementedError'] | 334,532 |
Arts-ISIT-LA/la-nlp | test_aspect_sentiment.py | test_attribute_keywords | test_attribute_keywords | Tests that docs are assigned the keywords attribute as expected. | [
"Tests",
"that",
"docs",
"are",
"assigned",
"the",
"keywords",
"attribute",
"as",
"expected."
] | def test_attribute_keywords(doc1, doc2):
assertion1 = 'doc1 should contain keyword %s'
doc1_targets = ['course', 'reading', 'professor']
doc1_keywords = [kw.lemma_.lower() for kw in doc1._.keywords]
for target in doc1_targets:
assert target in doc1_keywords, assertion1 % target
assertion2 = ... | ['def', 'test_attribute_keywords(doc1,', 'doc2):', 'assertion1', '=', "'doc1", 'should', 'contain', 'keyword', "%s'", 'doc1_targets', '=', "['course',", "'reading',", "'professor']", 'doc1_keywords', '=', '[kw.lemma_.lower()', 'for', 'kw', 'in', 'doc1._.keywords]', 'for', 'target', 'in', 'doc1_targets:', 'assert', 'tar... | 622,437 |
mfbx9da4/neuron-astrocyte-networks | temp_node.py | Connection.add_weight | add_weight | This function adds to the weight of the connection, which is proportional to the impact that a lower node's activation will have on an upper node's value. | [
"This",
"function",
"adds",
"to",
"the",
"weight",
"of",
"the",
"connection,",
"which",
"is",
"proportional",
"to",
"the",
"impact",
"that",
"a",
"lower",
"node's",
"activation",
"will",
"have",
"on",
"an",
"upper",
"node's",
"value."
] | def add_weight(self, weight):
err_msg = 'The weight, %s, must be a float value' % weight
if not isinstance(weight, float):
raise ValueError(err_msg)
else:
self._weight += weight | ['def', 'add_weight(self,', 'weight):', 'err_msg', '=', "'The", 'weight,', '%s,', 'must', 'be', 'a', 'float', "value'", '%', 'weight', 'if', 'not', 'isinstance(weight,', 'float):', 'raise', 'ValueError(err_msg)', 'else:', 'self._weight', '+=', 'weight'] | 722,824 |
SamsungLabs/fcaf3d | lyft_dataset.py | output_to_lyft_box | output_to_lyft_box | Convert the output to the box class in the Lyft. | [
"Convert",
"the",
"output",
"to",
"the",
"box",
"class",
"in",
"the",
"Lyft."
] | def output_to_lyft_box(detection):
box3d = detection['boxes_3d']
scores = detection['scores_3d'].numpy()
labels = detection['labels_3d'].numpy()
box_gravity_center = box3d.gravity_center.numpy()
box_dims = box3d.dims.numpy()
box_yaw = box3d.yaw.numpy()
box_yaw = -box_yaw - np.pi / 2
box_... | ['def', 'output_to_lyft_box(detection):', 'box3d', '=', "detection['boxes_3d']", 'scores', '=', "detection['scores_3d'].numpy()", 'labels', '=', "detection['labels_3d'].numpy()", 'box_gravity_center', '=', 'box3d.gravity_center.numpy()', 'box_dims', '=', 'box3d.dims.numpy()', 'box_yaw', '=', 'box3d.yaw.numpy()', 'box_y... | 560,335 |
PacktPublishing/OpenCV-Computer--Projects-with-Python | trackers.py | FaceTracker.update | update | Update the tracked facial features. | [
"Update",
"the",
"tracked",
"facial",
"features."
] | def update(self, image):
self._faces = []
if utils.isGray(image):
image = cv2.equalizeHist(image)
else:
image = cv2.cvtColor(image, cv2.cv.CV_BGR2GRAY)
cv2.equalizeHist(image, image)
minSize = utils.widthHeightDividedBy(image, 8)
faceRects = self._faceClassifier.detectMultiSc... | ['def', 'update(self,', 'image):', 'self._faces', '=', '[]', 'if', 'utils.isGray(image):', 'image', '=', 'cv2.equalizeHist(image)', 'else:', 'image', '=', 'cv2.cvtColor(image,', 'cv2.cv.CV_BGR2GRAY)', 'cv2.equalizeHist(image,', 'image)', 'minSize', '=', 'utils.widthHeightDividedBy(image,', '8)', 'faceRects', '=', 'self... | 756,965 |
clips/pattern | metrics.py | precision | precision | Returns the percentage of correct positive classifications. | [
"Returns",
"the",
"percentage",
"of",
"correct",
"positive",
"classifications."
] | def precision(classify=lambda document: False, documents=[], average=None):
return test(classify, documents, average)[1] | ['def', 'precision(classify=lambda', 'document:', 'False,', 'documents=[],', 'average=None):', 'return', 'test(classify,', 'documents,', 'average)[1]'] | 764,488 |
OpenMDAO/OpenMDAO-Framework | enum.py | Enum.validate | validate | Validates that a specified value is valid for this trait. | [
"Validates",
"that",
"a",
"specified",
"value",
"is",
"valid",
"for",
"this",
"trait."
] | def validate(self, obj, name, value):
try:
val = self._validator.validate(obj, name, value)
except Exception:
self.error(obj, name, value)
return self.valuedict[val] | ['def', 'validate(self,', 'obj,', 'name,', 'value):', 'try:', 'val', '=', 'self._validator.validate(obj,', 'name,', 'value)', 'except', 'Exception:', 'self.error(obj,', 'name,', 'value)', 'return', 'self.valuedict[val]'] | 276,169 |
instadeepai/jumanji | generator_test.py | TestDummyGenerator.test_dummy_generator__call | test_dummy_generator__call | Validate that the dummy instance generator's call function behaves correctly, that it is jit-table and compiles only once, and that it returns the same state for different keys. | [
"Validate",
"that",
"the",
"dummy",
"instance",
"generator's",
"call",
"function",
"behaves",
"correctly,",
"that",
"it",
"is",
"jit-table",
"and",
"compiles",
"only",
"once,",
"and",
"that",
"it",
"returns",
"the",
"same",
"state",
"for",
"different",
"keys."
] | def test_dummy_generator__call(self, dummy_generator: DummyGenerator) -> None:
chex.clear_trace_counter()
call_fn = jax.jit(chex.assert_max_traces(dummy_generator.__call__, n=1))
state1 = call_fn(jax.random.PRNGKey(1))
state2 = call_fn(jax.random.PRNGKey(2))
assert_trees_are_equal(state1, state2) | ['def', 'test_dummy_generator__call(self,', 'dummy_generator:', 'DummyGenerator)', '->', 'None:', 'chex.clear_trace_counter()', 'call_fn', '=', 'jax.jit(chex.assert_max_traces(dummy_generator.__call__,', 'n=1))', 'state1', '=', 'call_fn(jax.random.PRNGKey(1))', 'state2', '=', 'call_fn(jax.random.PRNGKey(2))', 'assert_t... | 594,241 |
scikit-learn/scikit-learn | test_base.py | test_assign_where | test_assign_where | Check the behaviour of the private helpers `_assign_where`. | [
"Check",
"the",
"behaviour",
"of",
"the",
"private",
"helpers",
"`_assign_where`."
] | def test_assign_where(X1_type):
rng = np.random.RandomState(0)
(n_samples, n_features) = (10, 5)
X1 = _convert_container(rng.randn(n_samples, n_features), constructor_name=X1_type)
X2 = rng.randn(n_samples, n_features)
mask = rng.randint(0, 2, size=(n_samples, n_features)).astype(bool)
_assign_w... | ['def', 'test_assign_where(X1_type):', 'rng', '=', 'np.random.RandomState(0)', '(n_samples,', 'n_features)', '=', '(10,', '5)', 'X1', '=', '_convert_container(rng.randn(n_samples,', 'n_features),', 'constructor_name=X1_type)', 'X2', '=', 'rng.randn(n_samples,', 'n_features)', 'mask', '=', 'rng.randint(0,', '2,', 'size=... | 853,428 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | tarfile.py | TarInfo.path | path | In pax headers, "name" is called "path". | [
"In",
"pax",
"headers,",
"\"name\"",
"is",
"called",
"\"path\"."
] | def path(self):
return self.name | ['def', 'path(self):', 'return', 'self.name'] | 801,721 |
HewlettPackard/swarm-learning | tf.py | SwarmCallback.on_train_begin | on_train_begin | Overridden method on_train_begin of Keras Callback. | [
"Overridden",
"method",
"on_train_begin",
"of",
"Keras",
"Callback."
] | def on_train_begin(self, logs=None):
if self.mlPlatform is SLPlatforms.KERAS:
self.__setMLContext(kerasModel=self.model)
self._swarmOnTrainBegin()
if self.mlPlatform == SLPlatforms.KERAS and self.isSwarmTrainingOver:
if not self.mlCtx.model.stop_training:
self.logger.info('Swarm ... | ['def', 'on_train_begin(self,', 'logs=None):', 'if', 'self.mlPlatform', 'is', 'SLPlatforms.KERAS:', 'self.__setMLContext(kerasModel=self.model)', 'self._swarmOnTrainBegin()', 'if', 'self.mlPlatform', '==', 'SLPlatforms.KERAS', 'and', 'self.isSwarmTrainingOver:', 'if', 'not', 'self.mlCtx.model.stop_training:', "self.log... | 882,209 |
fudan-zvg/SeaFormer | adahessian.py | Adahessian.set_hessian | set_hessian | Computes the Hutchinson approximation of the hessian trace and accumulates it for each trainable parameter. | [
"Computes",
"the",
"Hutchinson",
"approximation",
"of",
"the",
"hessian",
"trace",
"and",
"accumulates",
"it",
"for",
"each",
"trainable",
"parameter."
] | def set_hessian(self):
params = []
for p in filter(lambda p: p.grad is not None, self.get_params()):
if self.state[p]['hessian step'] % self.update_each == 0:
params.append(p)
self.state[p]['hessian step'] += 1
if len(params) == 0:
return
if self.generator.device != p... | ['def', 'set_hessian(self):', 'params', '=', '[]', 'for', 'p', 'in', 'filter(lambda', 'p:', 'p.grad', 'is', 'not', 'None,', 'self.get_params()):', 'if', "self.state[p]['hessian", "step']", '%', 'self.update_each', '==', '0:', 'params.append(p)', "self.state[p]['hessian", "step']", '+=', '1', 'if', 'len(params)', '==', ... | 855,822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.