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 |
|---|---|---|---|---|---|---|---|---|
ReynoldZhao/Features_Detection_and_Matching | featuresUIpy3.py | customLoader | customLoader | This function supports the deserialization of the custom types defined above. | [
"This",
"function",
"supports",
"the",
"deserialization",
"of",
"the",
"custom",
"types",
"defined",
"above."
] | def customLoader(d):
if '__type__' in d:
if d['__type__'] == 'cv2.KeyPoint':
k = cv2.KeyPoint()
k.pt = (float(d['point'][0]), float(d['point'][1]))
k.size = float(d['size'])
k.angle = float(d['angle'])
k.response = float(d['response'])
... | ['def', 'customLoader(d):', 'if', "'__type__'", 'in', 'd:', 'if', "d['__type__']", '==', "'cv2.KeyPoint':", 'k', '=', 'cv2.KeyPoint()', 'k.pt', '=', "(float(d['point'][0]),", "float(d['point'][1]))", 'k.size', '=', "float(d['size'])", 'k.angle', '=', "float(d['angle'])", 'k.response', '=', "float(d['response'])", 'k.oc... | 544,865 |
DrewNF/Tensorflow_Object_Tracking_Video | multiclass_rectangle.py | Rectangle_Multiclass.get_label_string | get_label_string | Get the string of the label of the rect. | [
"Get",
"the",
"string",
"of",
"the",
"label",
"of",
"the",
"rect."
] | def get_label_string(self):
string = ''
if self.label is not 'Not Set':
string = self.label + ' '
return string | ['def', 'get_label_string(self):', 'string', '=', "''", 'if', 'self.label', 'is', 'not', "'Not", "Set':", 'string', '=', 'self.label', '+', "'", "'", 'return', 'string'] | 923,338 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | DeepMergeDict | DeepMergeDict | Recursively merges dict_y into dict_x. | [
"Recursively",
"merges",
"dict_y",
"into",
"dict_x."
] | def DeepMergeDict(dict_x, dict_y, path=None):
if path is None:
path = []
for key in dict_y:
if key in dict_x:
if isinstance(dict_x[key], dict) and isinstance(dict_y[key], dict):
DeepMergeDict(dict_x[key], dict_y[key], path + [str(key)])
elif dict_x[key] ==... | ['def', 'DeepMergeDict(dict_x,', 'dict_y,', 'path=None):', 'if', 'path', 'is', 'None:', 'path', '=', '[]', 'for', 'key', 'in', 'dict_y:', 'if', 'key', 'in', 'dict_x:', 'if', 'isinstance(dict_x[key],', 'dict)', 'and', 'isinstance(dict_y[key],', 'dict):', 'DeepMergeDict(dict_x[key],', 'dict_y[key],', 'path', '+', '[str(k... | 29,750 |
gunthercox/ChatterBot | sessions.py | Session.send | send | Send a given PreparedRequest. | [
"Send",
"a",
"given",
"PreparedRequest."
] | def send(self, request, **kwargs):
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefault('cert', self.cert)
kwargs.setdefault('proxies', self.proxies)
if not isinstance(request, PreparedRequest):
raise ValueError('You can only send PreparedReques... | ['def', 'send(self,', 'request,', '**kwargs):', "kwargs.setdefault('stream',", 'self.stream)', "kwargs.setdefault('verify',", 'self.verify)', "kwargs.setdefault('cert',", 'self.cert)', "kwargs.setdefault('proxies',", 'self.proxies)', 'if', 'not', 'isinstance(request,', 'PreparedRequest):', 'raise', "ValueError('You", '... | 480,629 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_search.py | test_refit_callable_invalid_type | test_refit_callable_invalid_type | Test implementation catches the errors when 'best_index_' returns an invalid result. | [
"Test",
"implementation",
"catches",
"the",
"errors",
"when",
"'best_index_'",
"returns",
"an",
"invalid",
"result."
] | def test_refit_callable_invalid_type():
def refit_callable_invalid_type(cv_results):
return None
(X, y) = make_classification(n_samples=100, n_features=4, random_state=42)
clf = GridSearchCV(LinearSVC(random_state=42), {'C': [0.1, 1]}, scoring='precision', refit=refit_callable_invalid_type)
wit... | ['def', 'test_refit_callable_invalid_type():', 'def', 'refit_callable_invalid_type(cv_results):', 'return', 'None', '(X,', 'y)', '=', 'make_classification(n_samples=100,', 'n_features=4,', 'random_state=42)', 'clf', '=', 'GridSearchCV(LinearSVC(random_state=42),', "{'C':", '[0.1,', '1]},', "scoring='precision',", 'refi... | 437,183 |
deepmind/meltingpot | externality_mushrooms.py | create_marking_overlay | create_marking_overlay | Create a graduated sanctions marking overlay object. | [
"Create",
"a",
"graduated",
"sanctions",
"marking",
"overlay",
"object."
] | def create_marking_overlay(player_idx: int) -> Mapping[str, Any]:
lua_idx = player_idx + 1
marking_object = {'name': 'avatar_marking', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'avatarMarkingWait', 'stateConfigs': [{'state': 'level_1', 'layer': 'superOverlay', 'sprite': 'sprite_for... | ['def', 'create_marking_overlay(player_idx:', 'int)', '->', 'Mapping[str,', 'Any]:', 'lua_idx', '=', 'player_idx', '+', '1', 'marking_object', '=', "{'name':", "'avatar_marking',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'avatarMarkingWait',", "'stateConfigs':", "[{'state... | 285,734 |
gunthercox/ChatterBot | local.py | LocalManager.make_middleware | make_middleware | Wrap a WSGI application so that cleaning up happens after request end. | [
"Wrap",
"a",
"WSGI",
"application",
"so",
"that",
"cleaning",
"up",
"happens",
"after",
"request",
"end."
] | def make_middleware(self, app):
def application(environ, start_response):
return ClosingIterator(app(environ, start_response), self.cleanup)
return application | ['def', 'make_middleware(self,', 'app):', 'def', 'application(environ,', 'start_response):', 'return', 'ClosingIterator(app(environ,', 'start_response),', 'self.cleanup)', 'return', 'application'] | 483,267 |
TonyLianLong/VAI-ReinforcementLearning | renderer.py | SceneCamera.set_fixed_mode | set_fixed_mode | Fixes the camera in a pre-defined position, taking away all DOF. | [
"Fixes",
"the",
"camera",
"in",
"a",
"pre-defined",
"position,",
"taking",
"away",
"all",
"DOF."
] | def set_fixed_mode(self, fixed_camera_id):
if fixed_camera_id < 0:
return
self._camera.trackbodyid = _NO_BODY_TRACKED_INDEX
self._camera.fixedcamid = fixed_camera_id
self._camera.type_ = enums.mjtCamera.mjCAMERA_FIXED | ['def', 'set_fixed_mode(self,', 'fixed_camera_id):', 'if', 'fixed_camera_id', '<', '0:', 'return', 'self._camera.trackbodyid', '=', '_NO_BODY_TRACKED_INDEX', 'self._camera.fixedcamid', '=', 'fixed_camera_id', 'self._camera.type_', '=', 'enums.mjtCamera.mjCAMERA_FIXED'] | 441,059 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | patheffects.py | Stroke.draw_path | draw_path | draw the path with updated gc. | [
"draw",
"the",
"path",
"with",
"updated",
"gc."
] | def draw_path(self, renderer, gc, tpath, affine, rgbFace):
gc0 = renderer.new_gc()
gc0.copy_properties(gc)
gc0 = self._update_gc(gc0, self._gc)
trans = self._offset_transform(renderer, affine)
renderer.draw_path(gc0, tpath, trans, rgbFace)
gc0.restore() | ['def', 'draw_path(self,', 'renderer,', 'gc,', 'tpath,', 'affine,', 'rgbFace):', 'gc0', '=', 'renderer.new_gc()', 'gc0.copy_properties(gc)', 'gc0', '=', 'self._update_gc(gc0,', 'self._gc)', 'trans', '=', 'self._offset_transform(renderer,', 'affine)', 'renderer.draw_path(gc0,', 'tpath,', 'trans,', 'rgbFace)', 'gc0.resto... | 306,900 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_utils.py | write_datafiles | write_datafiles | Load and preprocess images from a directory and write them to a file. | [
"Load",
"and",
"preprocess",
"images",
"from",
"a",
"directory",
"and",
"write",
"them",
"to",
"a",
"file."
] | def write_datafiles(directory, write_file, resize=True, rotate=False, new_width=IMAGE_NEW_SIZE, new_height=IMAGE_NEW_SIZE, first_label=0):
imgwidth = IMAGE_ORIGINAL_SIZE
imgheight = IMAGE_ORIGINAL_SIZE
logging.info('Reading the data.')
(images, labels, info) = crawl_directory(directory, augment_with_rot... | ['def', 'write_datafiles(directory,', 'write_file,', 'resize=True,', 'rotate=False,', 'new_width=IMAGE_NEW_SIZE,', 'new_height=IMAGE_NEW_SIZE,', 'first_label=0):', 'imgwidth', '=', 'IMAGE_ORIGINAL_SIZE', 'imgheight', '=', 'IMAGE_ORIGINAL_SIZE', "logging.info('Reading", 'the', "data.')", '(images,', 'labels,', 'info)', ... | 49,544 |
facebookresearch/CutLER | transform.py | HFlip_rotated_box | HFlip_rotated_box | Apply the horizontal flip transform on rotated boxes. | [
"Apply",
"the",
"horizontal",
"flip",
"transform",
"on",
"rotated",
"boxes."
] | def HFlip_rotated_box(transform, rotated_boxes):
rotated_boxes[:, 0] = transform.width - rotated_boxes[:, 0]
rotated_boxes[:, 4] = -rotated_boxes[:, 4]
return rotated_boxes | ['def', 'HFlip_rotated_box(transform,', 'rotated_boxes):', 'rotated_boxes[:,', '0]', '=', 'transform.width', '-', 'rotated_boxes[:,', '0]', 'rotated_boxes[:,', '4]', '=', '-rotated_boxes[:,', '4]', 'return', 'rotated_boxes'] | 509,155 |
tk1980/GaussianPooling | resnet.py | resnext50_32x4d | resnext50_32x4d | Constructs a ResNeXt-50 32x4d model. | [
"Constructs",
"a",
"ResNeXt-50",
"32x4d",
"model."
] | def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) | ['def', 'resnext50_32x4d(pretrained=False,', 'progress=True,', '**kwargs):', "kwargs['groups']", '=', '32', "kwargs['width_per_group']", '=', '4', 'return', "_resnet('resnext50_32x4d',", 'Bottleneck,', '[3,', '4,', '6,', '3],', 'pretrained,', 'progress,', '**kwargs)'] | 201,233 |
DeepX-inc/machina | base.py | BasePol.convert_ac_for_real | convert_ac_for_real | Converting action which is output of network for real world value. | [
"Converting",
"action",
"which",
"is",
"output",
"of",
"network",
"for",
"real",
"world",
"value."
] | def convert_ac_for_real(self, x):
if not self.discrete:
(lb, ub) = (self.action_space.low, self.action_space.high)
if self.normalize_ac:
x = lb + (x + 1.0) * 0.5 * (ub - lb)
x = np.clip(x, lb, ub)
else:
x = np.clip(x, lb, ub)
return x | ['def', 'convert_ac_for_real(self,', 'x):', 'if', 'not', 'self.discrete:', '(lb,', 'ub)', '=', '(self.action_space.low,', 'self.action_space.high)', 'if', 'self.normalize_ac:', 'x', '=', 'lb', '+', '(x', '+', '1.0)', '*', '0.5', '*', '(ub', '-', 'lb)', 'x', '=', 'np.clip(x,', 'lb,', 'ub)', 'else:', 'x', '=', 'np.clip(x... | 218,878 |
pythonlessons/mltu | layers.py | SelfAttention.call | call | Apply the self-attention mechanism to the input tensor. | [
"Apply",
"the",
"self-attention",
"mechanism",
"to",
"the",
"input",
"tensor."
] | def call(self, inputs: tf.Tensor) -> tf.Tensor:
(_, h, w, c) = inputs.shape
q = self.query_conv(inputs)
k = self.key_conv(inputs)
v = self.value_conv(inputs)
q_reshaped = tf.reshape(q, [-1, h * w, c // self.num_heads])
k_reshaped = tf.reshape(k, [-1, h * w, c // self.num_heads])
v_reshaped =... | ['def', 'call(self,', 'inputs:', 'tf.Tensor)', '->', 'tf.Tensor:', '(_,', 'h,', 'w,', 'c)', '=', 'inputs.shape', 'q', '=', 'self.query_conv(inputs)', 'k', '=', 'self.key_conv(inputs)', 'v', '=', 'self.value_conv(inputs)', 'q_reshaped', '=', 'tf.reshape(q,', '[-1,', 'h', '*', 'w,', 'c', '//', 'self.num_heads])', 'k_resh... | 631,008 |
Kvatsx/Artificial-Intelligence-Assignments | parser.py | Parser.parse_for | parse_for | Parse a for loop. | [
"Parse",
"a",
"for",
"loop."
] | def parse_for(self):
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False, extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
... | ['def', 'parse_for(self):', 'lineno', '=', "self.stream.expect('name:for').lineno", 'target', '=', "self.parse_assign_target(extra_end_rules=('name:in',))", "self.stream.expect('name:in')", 'iter', '=', 'self.parse_tuple(with_condexpr=False,', "extra_end_rules=('name:recursive',))", 'test', '=', 'None', 'if', "self.str... | 39,343 |
RaoUmer/SRResCGAN | utils_model.py | init_msra | init_msra | Initializes the input tensor with weights according to He initialization. | [
"Initializes",
"the",
"input",
"tensor",
"with",
"weights",
"according",
"to",
"He",
"initialization."
] | def init_msra(tensor):
(output_channels, input_channels, H, W) = tensor.shape
tensor.data.copy_(th.randn_like(tensor).mul(th.sqrt(th.Tensor([2])).type_as(tensor).div(H * W * input_channels))) | ['def', 'init_msra(tensor):', '(output_channels,', 'input_channels,', 'H,', 'W)', '=', 'tensor.shape', 'tensor.data.copy_(th.randn_like(tensor).mul(th.sqrt(th.Tensor([2])).type_as(tensor).div(H', '*', 'W', '*', 'input_channels)))'] | 897,574 |
xiaoaleiBLUE/computer_vision | static_shape.py | get_batch_size | get_batch_size | Returns batch size from the tensor shape. | [
"Returns",
"batch",
"size",
"from",
"the",
"tensor",
"shape."
] | def get_batch_size(tensor_shape):
tensor_shape.assert_has_rank(rank=4)
return tensor_shape[0].value | ['def', 'get_batch_size(tensor_shape):', 'tensor_shape.assert_has_rank(rank=4)', 'return', 'tensor_shape[0].value'] | 513,780 |
KKKSQJ/DeepLearning | optimizer.py | build_optimizer | build_optimizer | Build optimizer, set weight decay of normalization to 0 by default. | [
"Build",
"optimizer,",
"set",
"weight",
"decay",
"of",
"normalization",
"to",
"0",
"by",
"default."
] | def build_optimizer(config, model):
skip = {}
skip_keywords = {}
if hasattr(model, 'no_weight_decay'):
skip = model.no_weight_decay()
if hasattr(model, 'no_weight_decay_keywords'):
skip_keywords = model.no_weight_decay_keywords()
parameters = set_weight_decay(model, skip, skip_keywor... | ['def', 'build_optimizer(config,', 'model):', 'skip', '=', '{}', 'skip_keywords', '=', '{}', 'if', 'hasattr(model,', "'no_weight_decay'):", 'skip', '=', 'model.no_weight_decay()', 'if', 'hasattr(model,', "'no_weight_decay_keywords'):", 'skip_keywords', '=', 'model.no_weight_decay_keywords()', 'parameters', '=', 'set_we... | 128,719 |
deepmind/dm_control | util.py | Integrator.value | value | Returns the averaged value. | [
"Returns",
"the",
"averaged",
"value."
] | def value(self):
return self._value | ['def', 'value(self):', 'return', 'self._value'] | 165,709 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Base.iterEpilogue | iterEpilogue | Yields the items in the epilogue of this template. | [
"Yields",
"the",
"items",
"in",
"the",
"epilogue",
"of",
"this",
"template."
] | def iterEpilogue(self):
return chain(*(h(self) for h in self.configHandlers('Epilogue'))) | ['def', 'iterEpilogue(self):', 'return', 'chain(*(h(self)', 'for', 'h', 'in', "self.configHandlers('Epilogue')))"] | 10,788 |
google-research/scenic | util.py | replace_usage_of_field_references | replace_usage_of_field_references | Replaces the usages of the field references. | [
"Replaces",
"the",
"usages",
"of",
"the",
"field",
"references."
] | def replace_usage_of_field_references(obj: Union[ml_collections.ConfigDict, Mapping[str, Any], Iterable[Any], ml_collections.FieldReference], field_reference_replace_map: MutableMapping[int, ml_collections.FieldReference]) -> None:
if isinstance(obj, ml_collections.FieldReference):
for (i, op) in enumerate(... | ['def', 'replace_usage_of_field_references(obj:', 'Union[ml_collections.ConfigDict,', 'Mapping[str,', 'Any],', 'Iterable[Any],', 'ml_collections.FieldReference],', 'field_reference_replace_map:', 'MutableMapping[int,', 'ml_collections.FieldReference])', '->', 'None:', 'if', 'isinstance(obj,', 'ml_collections.FieldRefer... | 846,867 |
arshpreetsingh/quantopian-machinelearning | tarfile.py | TarFile.makefifo | makefifo | Make a fifo called targetpath. | [
"Make",
"a",
"fifo",
"called",
"targetpath."
] | def makefifo(self, tarinfo, targetpath):
if hasattr(os, 'mkfifo'):
os.mkfifo(targetpath)
else:
raise ExtractError('fifo not supported by system') | ['def', 'makefifo(self,', 'tarinfo,', 'targetpath):', 'if', 'hasattr(os,', "'mkfifo'):", 'os.mkfifo(targetpath)', 'else:', 'raise', "ExtractError('fifo", 'not', 'supported', 'by', "system')"] | 891,579 |
Kvatsx/Artificial-Intelligence-Assignments | ultratb.py | TBTools.color_toggle | color_toggle | Toggle between the currently active color scheme and NoColor. | [
"Toggle",
"between",
"the",
"currently",
"active",
"color",
"scheme",
"and",
"NoColor."
] | def color_toggle(self):
if self.color_scheme_table.active_scheme_name == 'NoColor':
self.color_scheme_table.set_active_scheme(self.old_scheme)
self.Colors = self.color_scheme_table.active_colors
else:
self.old_scheme = self.color_scheme_table.active_scheme_name
self.color_scheme_... | ['def', 'color_toggle(self):', 'if', 'self.color_scheme_table.active_scheme_name', '==', "'NoColor':", 'self.color_scheme_table.set_active_scheme(self.old_scheme)', 'self.Colors', '=', 'self.color_scheme_table.active_colors', 'else:', 'self.old_scheme', '=', 'self.color_scheme_table.active_scheme_name', "self.color_sch... | 38,252 |
JunshengFu/semantic_segmentation | rmi.py | RMILoss.rmi_lower_bound | rmi_lower_bound | calculate the lower bound of the region mutual information. | [
"calculate",
"the",
"lower",
"bound",
"of",
"the",
"region",
"mutual",
"information."
] | def rmi_lower_bound(self, labels_4D, probs_4D):
assert labels_4D.size() == probs_4D.size()
(p, s) = (self.rmi_pool_size, self.rmi_pool_stride)
if self.rmi_pool_stride > 1:
if self.rmi_pool_way == 0:
labels_4D = F.max_pool2d(labels_4D, kernel_size=p, stride=s, padding=self.kernel_padding)... | ['def', 'rmi_lower_bound(self,', 'labels_4D,', 'probs_4D):', 'assert', 'labels_4D.size()', '==', 'probs_4D.size()', '(p,', 's)', '=', '(self.rmi_pool_size,', 'self.rmi_pool_stride)', 'if', 'self.rmi_pool_stride', '>', '1:', 'if', 'self.rmi_pool_way', '==', '0:', 'labels_4D', '=', 'F.max_pool2d(labels_4D,', 'kernel_size... | 871,693 |
open-mmlab/mmselfsup | deepcluster_hook.py | DeepClusterHook.before_train | before_train | Run cluster before training. | [
"Run",
"cluster",
"before",
"training."
] | def before_train(self, runner) -> None:
self.data_loader = runner.train_dataloader
if self.initial:
self.deepcluster(runner) | ['def', 'before_train(self,', 'runner)', '->', 'None:', 'self.data_loader', '=', 'runner.train_dataloader', 'if', 'self.initial:', 'self.deepcluster(runner)'] | 240,321 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | sample_generation_tools.py | get_psd | get_psd | Take a detector recording and calculate the Power Spectral Density (PSD). | [
"Take",
"a",
"detector",
"recording",
"and",
"calculate",
"the",
"Power",
"Spectral",
"Density",
"(PSD)."
] | def get_psd(real_strain, sampling_rate=4096):
nfft = 2 * sampling_rate
(power_spectrum, frequencies) = mlab.psd(real_strain, NFFT=nfft, Fs=sampling_rate)
psd = interp1d(frequencies, power_spectrum)
return psd | ['def', 'get_psd(real_strain,', 'sampling_rate=4096):', 'nfft', '=', '2', '*', 'sampling_rate', '(power_spectrum,', 'frequencies)', '=', 'mlab.psd(real_strain,', 'NFFT=nfft,', 'Fs=sampling_rate)', 'psd', '=', 'interp1d(frequencies,', 'power_spectrum)', 'return', 'psd'] | 18,476 |
flavioschneider/rl-transfer- | _dtypes.py | InProgressEpisode.step | step | Step the episode using an action from an agent. | [
"Step",
"the",
"episode",
"using",
"an",
"action",
"from",
"an",
"agent."
] | def step(self, action, agent_info):
es = self.env.step(action)
self.observations.append(es.observation)
self.rewards.append(es.reward)
self.actions.append(es.action)
for (k, v) in agent_info.items():
self.agent_infos[k].append(v)
for (k, v) in es.env_info.items():
self.env_infos[... | ['def', 'step(self,', 'action,', 'agent_info):', 'es', '=', 'self.env.step(action)', 'self.observations.append(es.observation)', 'self.rewards.append(es.reward)', 'self.actions.append(es.action)', 'for', '(k,', 'v)', 'in', 'agent_info.items():', 'self.agent_infos[k].append(v)', 'for', '(k,', 'v)', 'in', 'es.env_info.it... | 861,294 |
xyc2690/Raspberry_ObjectDetection_Camera | model_tpu.py | create_estimator | create_estimator | Creates an `Estimator` object. | [
"Creates",
"an",
"`Estimator`",
"object."
] | def create_estimator(run_config, hparams, pipeline_config_path, train_steps=None, eval_steps=None, train_batch_size=None, model_fn_creator=model.create_model_fn, use_tpu=False, num_shards=1, params=None, **kwargs):
configs = config_util.get_configs_from_pipeline_file(pipeline_config_path)
configs = config_util.... | ['def', 'create_estimator(run_config,', 'hparams,', 'pipeline_config_path,', 'train_steps=None,', 'eval_steps=None,', 'train_batch_size=None,', 'model_fn_creator=model.create_model_fn,', 'use_tpu=False,', 'num_shards=1,', 'params=None,', '**kwargs):', 'configs', '=', 'config_util.get_configs_from_pipeline_file(pipeline... | 838,426 |
sktime/sktime | test_convert_to.py | test_convert_to_mtype_list | test_convert_to_mtype_list | Testing convert_to call to_type being a list, of same scitype. | [
"Testing",
"convert_to",
"call",
"to_type",
"being",
"a",
"list,",
"of",
"same",
"scitype."
] | def test_convert_to_mtype_list():
target_list = MTYPES_SERIES[:2]
scitype = SCITYPES[0]
from_fixt_on = get_examples(mtype=MTYPES_SERIES[1], as_scitype=scitype).get(0)
from_fixt_off = get_examples(mtype=MTYPES_SERIES[2], as_scitype=scitype).get(0)
exp_fixt_on = get_examples(mtype=MTYPES_SERIES[1], as... | ['def', 'test_convert_to_mtype_list():', 'target_list', '=', 'MTYPES_SERIES[:2]', 'scitype', '=', 'SCITYPES[0]', 'from_fixt_on', '=', 'get_examples(mtype=MTYPES_SERIES[1],', 'as_scitype=scitype).get(0)', 'from_fixt_off', '=', 'get_examples(mtype=MTYPES_SERIES[2],', 'as_scitype=scitype).get(0)', 'exp_fixt_on', '=', 'get... | 886,139 |
YGZWQZD/LAMDA-SSL | TFIDFReplacement.py | TFIDFReplacement.reset_random_prob | reset_random_prob | Generate many random numbers at the same time and cache them. | [
"Generate",
"many",
"random",
"numbers",
"at",
"the",
"same",
"time",
"and",
"cache",
"them."
] | def reset_random_prob(self):
self.random_prob_cache = np.random.random(size=(self.cache_len,))
self.random_prob_ptr = self.cache_len - 1 | ['def', 'reset_random_prob(self):', 'self.random_prob_cache', '=', 'np.random.random(size=(self.cache_len,))', 'self.random_prob_ptr', '=', 'self.cache_len', '-', '1'] | 261,874 |
ludwig-ai/ludwig | test_preprocessing.py | test_read_image_failure_default_image | test_read_image_failure_default_image | Tests that the default image used when an image cannot be read has the correct properties. | [
"Tests",
"that",
"the",
"default",
"image",
"used",
"when",
"an",
"image",
"cannot",
"be",
"read",
"has",
"the",
"correct",
"properties."
] | def test_read_image_failure_default_image(monkeypatch, tmpdir, csv_filename):
def mock_read_binary_files(self, column, map_fn, file_size):
return column.map(lambda x: None)
monkeypatch.setattr(ludwig.backend.base.LocalPreprocessingMixin, 'read_binary_files', mock_read_binary_files)
image_feature_co... | ['def', 'test_read_image_failure_default_image(monkeypatch,', 'tmpdir,', 'csv_filename):', 'def', 'mock_read_binary_files(self,', 'column,', 'map_fn,', 'file_size):', 'return', 'column.map(lambda', 'x:', 'None)', 'monkeypatch.setattr(ludwig.backend.base.LocalPreprocessingMixin,', "'read_binary_files',", 'mock_read_bina... | 617,271 |
myothida/Supervised-Machine-Learning | transforms.py | BboxBase.extents | extents | Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`). | [
"Return",
"(:attr:`x0`,",
":attr:`y0`,",
":attr:`x1`,",
":attr:`y1`)."
] | def extents(self):
return self.get_points().flatten() | ['def', 'extents(self):', 'return', 'self.get_points().flatten()'] | 362,358 |
caiiiac/Machine-Learning-with-Python | ticker.py | OldScalarFormatter.pprint_val | pprint_val | Formats the value `x` based on the size of the axis range `d`. | [
"Formats",
"the",
"value",
"`x`",
"based",
"on",
"the",
"size",
"of",
"the",
"axis",
"range",
"`d`."
] | def pprint_val(self, x, d):
if abs(x) < 10000.0 and x == int(x):
return '%d' % x
if d < 0.01:
fmt = '%1.3e'
elif d < 0.1:
fmt = '%1.3f'
elif d > 100000.0:
fmt = '%1.1e'
elif d > 10:
fmt = '%1.1f'
elif d > 1:
fmt = '%1.2f'
else:
fmt = '%... | ['def', 'pprint_val(self,', 'x,', 'd):', 'if', 'abs(x)', '<', '10000.0', 'and', 'x', '==', 'int(x):', 'return', "'%d'", '%', 'x', 'if', 'd', '<', '0.01:', 'fmt', '=', "'%1.3e'", 'elif', 'd', '<', '0.1:', 'fmt', '=', "'%1.3f'", 'elif', 'd', '>', '100000.0:', 'fmt', '=', "'%1.1e'", 'elif', 'd', '>', '10:', 'fmt', '=', "'... | 716,095 |
triaquae/triaquae | models.py | AbstractUser.get_full_name | get_full_name | Returns the first_name plus the last_name, with a space in between. | [
"Returns",
"the",
"first_name",
"plus",
"the",
"last_name,",
"with",
"a",
"space",
"in",
"between."
] | def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip() | ['def', 'get_full_name(self):', 'full_name', '=', "'%s", "%s'", '%', '(self.first_name,', 'self.last_name)', 'return', 'full_name.strip()'] | 357,094 |
MushroomRL/mushroom-rl | grid_world.py | compute_reward | compute_reward | Compute the reward matrix. | [
"Compute",
"the",
"reward",
"matrix."
] | def compute_reward(grid_map, cell_list, pos_rew, neg_rew):
g = np.array(grid_map)
c = np.array(cell_list)
n_states = len(c)
r = np.zeros((n_states, 4, n_states))
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def give_reward(t, rew):
for x in np.argwhere(g == t):
j = np.whe... | ['def', 'compute_reward(grid_map,', 'cell_list,', 'pos_rew,', 'neg_rew):', 'g', '=', 'np.array(grid_map)', 'c', '=', 'np.array(cell_list)', 'n_states', '=', 'len(c)', 'r', '=', 'np.zeros((n_states,', '4,', 'n_states))', 'directions', '=', '[[-1,', '0],', '[1,', '0],', '[0,', '-1],', '[0,', '1]]', 'def', 'give_reward(t,... | 266,049 |
suhyeonlee/WildNet | cityscapes.py | colorize_mask | colorize_mask | Colorize a segmentation mask. | [
"Colorize",
"a",
"segmentation",
"mask."
] | def colorize_mask(mask):
new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P')
new_mask.putpalette(palette)
return new_mask | ['def', 'colorize_mask(mask):', 'new_mask', '=', "Image.fromarray(mask.astype(np.uint8)).convert('P')", 'new_mask.putpalette(palette)', 'return', 'new_mask'] | 985,890 |
taniyariar/Natural-Language-Processing | Sentence.py | Sentence.cleanSentence | cleanSentence | Returns a new sentence with all datum's having error removed. | [
"Returns",
"a",
"new",
"sentence",
"with",
"all",
"datum's",
"having",
"error",
"removed."
] | def cleanSentence(self):
sentence = Sentence()
for datum in self.data:
clean = datum.fixError()
sentence.append(clean)
return sentence | ['def', 'cleanSentence(self):', 'sentence', '=', 'Sentence()', 'for', 'datum', 'in', 'self.data:', 'clean', '=', 'datum.fixError()', 'sentence.append(clean)', 'return', 'sentence'] | 683,612 |
jinfanhahaha/base-cifar-10-recurrent--.github.io | ResNet-34.py | load_data | load_data | read data from data file. | [
"read",
"data",
"from",
"data",
"file."
] | def load_data(filename):
with open(filename, 'rb') as f:
data = pickle.load(f, encoding='bytes')
return (data[b'data'], data[b'labels']) | ['def', 'load_data(filename):', 'with', 'open(filename,', "'rb')", 'as', 'f:', 'data', '=', 'pickle.load(f,', "encoding='bytes')", 'return', "(data[b'data'],", "data[b'labels'])"] | 94,357 |
chenbinghui1/DSL | assign_result.py | AssignResult.set_extra_property | set_extra_property | Set user-defined new property. | [
"Set",
"user-defined",
"new",
"property."
] | def set_extra_property(self, key, value):
assert key not in self.info
self._extra_properties[key] = value | ['def', 'set_extra_property(self,', 'key,', 'value):', 'assert', 'key', 'not', 'in', 'self.info', 'self._extra_properties[key]', '=', 'value'] | 167,419 |
shiwt03/SSformer | pytorch2torchscript.py | pytorch2libtorch | pytorch2libtorch | Export Pytorch model to TorchScript model and verify the outputs are same between Pytorch and TorchScript. | [
"Export",
"Pytorch",
"model",
"to",
"TorchScript",
"model",
"and",
"verify",
"the",
"outputs",
"are",
"same",
"between",
"Pytorch",
"and",
"TorchScript."
] | def pytorch2libtorch(model, input_shape, show=False, output_file='tmp.pt', verify=False):
if isinstance(model.decode_head, nn.ModuleList):
num_classes = model.decode_head[-1].num_classes
else:
num_classes = model.decode_head.num_classes
mm_inputs = _demo_mm_inputs(input_shape, num_classes)
... | ['def', 'pytorch2libtorch(model,', 'input_shape,', 'show=False,', "output_file='tmp.pt',", 'verify=False):', 'if', 'isinstance(model.decode_head,', 'nn.ModuleList):', 'num_classes', '=', 'model.decode_head[-1].num_classes', 'else:', 'num_classes', '=', 'model.decode_head.num_classes', 'mm_inputs', '=', '_demo_mm_inputs... | 872,030 |
myothida/Supervised-Machine-Learning | backend_bases.py | GraphicsContextBase.get_hatch | get_hatch | Get the current hatch style. | [
"Get",
"the",
"current",
"hatch",
"style."
] | def get_hatch(self):
return self._hatch | ['def', 'get_hatch(self):', 'return', 'self._hatch'] | 361,729 |
yanqi1811/transfer-learning | seq2seq.py | sample | sample | Perform sampling and calculate KL divergence. | [
"Perform",
"sampling",
"and",
"calculate",
"KL",
"divergence."
] | def sample(means, logvars, latent_dim, iaf=True, kl_min=None, anneal=False, kl_rate=None, dtype=None):
if iaf:
with tf.variable_scope('iaf'):
prior = DiagonalGaussian(tf.zeros_like(means, dtype=dtype), tf.zeros_like(logvars, dtype=dtype))
posterior = DiagonalGaussian(means, logvars)
... | ['def', 'sample(means,', 'logvars,', 'latent_dim,', 'iaf=True,', 'kl_min=None,', 'anneal=False,', 'kl_rate=None,', 'dtype=None):', 'if', 'iaf:', 'with', "tf.variable_scope('iaf'):", 'prior', '=', 'DiagonalGaussian(tf.zeros_like(means,', 'dtype=dtype),', 'tf.zeros_like(logvars,', 'dtype=dtype))', 'posterior', '=', 'Diag... | 929,542 |
thaines/helit | model.py | Model.getB | getB | Returns the addative offset of the function defined by the support vectors to locate the decision boundary at 0. | [
"Returns",
"the",
"addative",
"offset",
"of",
"the",
"function",
"defined",
"by",
"the",
"support",
"vectors",
"to",
"locate",
"the",
"decision",
"boundary",
"at",
"0."
] | def getB(self):
return self.b | ['def', 'getB(self):', 'return', 'self.b'] | 592,487 |
flow-project/flow | test_scenario_base_class.py | TestEvenStartPos.test_base | test_base | Tests that get_even_start_pos function evenly distributed vehicles in a network. | [
"Tests",
"that",
"get_even_start_pos",
"function",
"evenly",
"distributed",
"vehicles",
"in",
"a",
"network."
] | def test_base(self):
initial_config = InitialConfig(lanes_distribution=1)
self.setUp_gen_start_pos(initial_config)
ids = self.env.k.vehicle.get_ids()
veh_pos = np.array([self.env.k.vehicle.get_x_by_id(veh_id) for veh_id in ids])
nth_headway = np.mod(np.append(veh_pos[1:], veh_pos[0]) - veh_pos, self... | ['def', 'test_base(self):', 'initial_config', '=', 'InitialConfig(lanes_distribution=1)', 'self.setUp_gen_start_pos(initial_config)', 'ids', '=', 'self.env.k.vehicle.get_ids()', 'veh_pos', '=', 'np.array([self.env.k.vehicle.get_x_by_id(veh_id)', 'for', 'veh_id', 'in', 'ids])', 'nth_headway', '=', 'np.mod(np.append(veh_... | 212,514 |
jimtin/Stock_Comparison | ols.py | MovingOLS.std_err | std_err | Returns the standard err values. | [
"Returns",
"the",
"standard",
"err",
"values."
] | def std_err(self):
return DataFrame(self._std_err_raw, columns=self.beta.columns, index=self._result_index) | ['def', 'std_err(self):', 'return', 'DataFrame(self._std_err_raw,', 'columns=self.beta.columns,', 'index=self._result_index)'] | 388,117 |
cheind/gcsl | math_utils_test.py | AverageQuaternionsTest.test_multiple_identity | test_multiple_identity | Average multiple copies of a quaternion should equal itself. | [
"Average",
"multiple",
"copies",
"of",
"a",
"quaternion",
"should",
"equal",
"itself."
] | def test_multiple_identity(self):
test_quat = euler2quat(np.pi / 4, np.pi / 4, np.pi / 4)
avg_quat = average_quaternions([test_quat, test_quat, test_quat])
np.testing.assert_array_almost_equal(avg_quat, test_quat) | ['def', 'test_multiple_identity(self):', 'test_quat', '=', 'euler2quat(np.pi', '/', '4,', 'np.pi', '/', '4,', 'np.pi', '/', '4)', 'avg_quat', '=', 'average_quaternions([test_quat,', 'test_quat,', 'test_quat])', 'np.testing.assert_array_almost_equal(avg_quat,', 'test_quat)'] | 202,104 |
deepmind/meltingpot | running_with_scissors_in_the_matrix__one_shot.py | create_scene | create_scene | Creates the global scene. | [
"Creates",
"the",
"global",
"scene."
] | def create_scene():
scene = {'name': 'scene', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'scene', 'stateConfigs': [{'state': 'scene'}]}}, {'component': 'Transform'}, {'component': 'TheMatrix', 'kwargs': {'disallowUnreadyInteractions': True, 'matrix': [[0, -10, 10], [10, 0, -10], [-10, 1... | ['def', 'create_scene():', 'scene', '=', "{'name':", "'scene',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'scene',", "'stateConfigs':", "[{'state':", "'scene'}]}},", "{'component':", "'Transform'},", "{'component':", "'TheMatrix',", "'kwargs':", "{'disallowUnreadyInteracti... | 285,835 |
intel/neural-compressor | gather.py | GatherOperator.convert | convert | Convert to QOperator format. | [
"Convert",
"to",
"QOperator",
"format."
] | def convert(self, convert_format):
node = self.node
parents = self.quantizer.model.get_parents(node)
children = self.quantizer.model.get_children(node)
if any([i.op_type == 'DequantizeLinear' for i in parents]):
from onnx import numpy_helper
inputs = []
inputs.append(parents[0].i... | ['def', 'convert(self,', 'convert_format):', 'node', '=', 'self.node', 'parents', '=', 'self.quantizer.model.get_parents(node)', 'children', '=', 'self.quantizer.model.get_children(node)', 'if', 'any([i.op_type', '==', "'DequantizeLinear'", 'for', 'i', 'in', 'parents]):', 'from', 'onnx', 'import', 'numpy_helper', 'inpu... | 737,536 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | index.py | FoundCandidates.iter_all | iter_all | Iterate through all candidates. | [
"Iterate",
"through",
"all",
"candidates."
] | def iter_all(self):
return iter(self._candidates) | ['def', 'iter_all(self):', 'return', 'iter(self._candidates)'] | 949,995 |
georghess/voxel-mae | waymo_converter.py | Waymo2KITTI.save_calib | save_calib | Parse and save the calibration data. | [
"Parse",
"and",
"save",
"the",
"calibration",
"data."
] | def save_calib(self, frame, file_idx, frame_idx):
T_front_cam_to_ref = np.array([[0.0, -1.0, 0.0], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]])
camera_calibs = []
R0_rect = [f'{i:e}' for i in np.eye(3).flatten()]
Tr_velo_to_cams = []
calib_context = ''
for camera in frame.context.camera_calibrations:
... | ['def', 'save_calib(self,', 'frame,', 'file_idx,', 'frame_idx):', 'T_front_cam_to_ref', '=', 'np.array([[0.0,', '-1.0,', '0.0],', '[0.0,', '0.0,', '-1.0],', '[1.0,', '0.0,', '0.0]])', 'camera_calibs', '=', '[]', 'R0_rect', '=', "[f'{i:e}'", 'for', 'i', 'in', 'np.eye(3).flatten()]', 'Tr_velo_to_cams', '=', '[]', 'calib_... | 380,834 |
weimin17/Object-Detection_HelmetDetection | preprocess.py | process_light_curve | process_light_curve | Removes low-frequency variability from a light curve. | [
"Removes",
"low-frequency",
"variability",
"from",
"a",
"light",
"curve."
] | def process_light_curve(all_time, all_flux):
(all_time, all_flux) = util.split(all_time, all_flux, gap_width=0.75)
spline = kepler_spline.fit_kepler_spline(all_time, all_flux, verbose=False)[0]
time = np.concatenate(all_time)
flux = np.concatenate(all_flux)
spline = np.concatenate(spline)
finite... | ['def', 'process_light_curve(all_time,', 'all_flux):', '(all_time,', 'all_flux)', '=', 'util.split(all_time,', 'all_flux,', 'gap_width=0.75)', 'spline', '=', 'kepler_spline.fit_kepler_spline(all_time,', 'all_flux,', 'verbose=False)[0]', 'time', '=', 'np.concatenate(all_time)', 'flux', '=', 'np.concatenate(all_flux)', '... | 761,578 |
luuuyi/RefineDet.PyTorch | box_utils.py | point_form | point_form | Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. | [
"Convert",
"prior_boxes",
"to",
"(xmin,",
"ymin,",
"xmax,",
"ymax)",
"representation",
"for",
"comparison",
"to",
"point",
"form",
"ground",
"truth",
"data."
] | def point_form(boxes):
return torch.cat((boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, :2] + boxes[:, 2:] / 2), 1) | ['def', 'point_form(boxes):', 'return', 'torch.cat((boxes[:,', ':2]', '-', 'boxes[:,', '2:]', '/', '2,', 'boxes[:,', ':2]', '+', 'boxes[:,', '2:]', '/', '2),', '1)'] | 832,723 |
megvii-research/TreeEnergyLoss | palette.py | get_lip_colors | get_lip_colors | Returns the color map for visualizing the segmentation mask. | [
"Returns",
"the",
"color",
"map",
"for",
"visualizing",
"the",
"segmentation",
"mask."
] | def get_lip_colors():
n = 20
colors = [0] * (n * 3)
for j in range(0, n):
lab = j
colors[j * 3 + 0] = 0
colors[j * 3 + 1] = 0
colors[j * 3 + 2] = 0
i = 0
while lab:
colors[j * 3 + 0] |= (lab >> 0 & 1) << 7 - i
colors[j * 3 + 1] |= (lab ... | ['def', 'get_lip_colors():', 'n', '=', '20', 'colors', '=', '[0]', '*', '(n', '*', '3)', 'for', 'j', 'in', 'range(0,', 'n):', 'lab', '=', 'j', 'colors[j', '*', '3', '+', '0]', '=', '0', 'colors[j', '*', '3', '+', '1]', '=', '0', 'colors[j', '*', '3', '+', '2]', '=', '0', 'i', '=', '0', 'while', 'lab:', 'colors[j', '*',... | 951,467 |
feast-dev/feast | athena_source.py | AthenaSource.get_table_column_names_and_types | get_table_column_names_and_types | Returns a mapping of column names to types for this Athena source. | [
"Returns",
"a",
"mapping",
"of",
"column",
"names",
"to",
"types",
"for",
"this",
"Athena",
"source."
] | def get_table_column_names_and_types(self, config: RepoConfig) -> Iterable[Tuple[str, str]]:
from botocore.exceptions import ClientError
from feast.infra.offline_stores.contrib.athena_offline_store.athena import AthenaOfflineStoreConfig
from feast.infra.utils import aws_utils
assert isinstance(config.of... | ['def', 'get_table_column_names_and_types(self,', 'config:', 'RepoConfig)', '->', 'Iterable[Tuple[str,', 'str]]:', 'from', 'botocore.exceptions', 'import', 'ClientError', 'from', 'feast.infra.offline_stores.contrib.athena_offline_store.athena', 'import', 'AthenaOfflineStoreConfig', 'from', 'feast.infra.utils', 'import'... | 544,420 |
Ruturaj123/Flowchart-Detection | skip_gram_ops_test.py | SkipGramOpsTest.test_skip_gram_sample_random_skips | test_skip_gram_sample_random_skips | Tests skip-gram with min_skips != max_skips, with random output. | [
"Tests",
"skip-gram",
"with",
"min_skips",
"!=",
"max_skips,",
"with",
"random",
"output."
] | def test_skip_gram_sample_random_skips(self):
random_seed.set_random_seed(42)
input_tensor = constant_op.constant([b'the', b'quick', b'brown', b'fox', b'jumps', b'over'])
(tokens, labels) = text.skip_gram_sample(input_tensor, min_skips=1, max_skips=2, seed=9)
(expected_tokens, expected_labels) = self._s... | ['def', 'test_skip_gram_sample_random_skips(self):', 'random_seed.set_random_seed(42)', 'input_tensor', '=', "constant_op.constant([b'the',", "b'quick',", "b'brown',", "b'fox',", "b'jumps',", "b'over'])", '(tokens,', 'labels)', '=', 'text.skip_gram_sample(input_tensor,', 'min_skips=1,', 'max_skips=2,', 'seed=9)', '(exp... | 604,614 |
pasus/Reinforcement-Learning-Book | dynamics_prior_gmm.py | DynamicsPriorGMM.initial_state | initial_state | Return dynamics prior for initial time step. | [
"Return",
"dynamics",
"prior",
"for",
"initial",
"time",
"step."
] | def initial_state(self):
mu0 = np.mean(self.X[:, 0, :], axis=0)
Phi = np.diag(np.var(self.X[:, 0, :], axis=0))
n0 = self.X.shape[2] * self._strength
m = self.X.shape[2] * self._strength
n0 = 1.0
m = 1.0
Phi = Phi * m
return (mu0, Phi, m, n0) | ['def', 'initial_state(self):', 'mu0', '=', 'np.mean(self.X[:,', '0,', ':],', 'axis=0)', 'Phi', '=', 'np.diag(np.var(self.X[:,', '0,', ':],', 'axis=0))', 'n0', '=', 'self.X.shape[2]', '*', 'self._strength', 'm', '=', 'self.X.shape[2]', '*', 'self._strength', 'n0', '=', '1.0', 'm', '=', '1.0', 'Phi', '=', 'Phi', '*', 'm... | 340,730 |
jimtin/Stock_Comparison | filters.py | do_center | do_center | Centers the value in a field of a given width. | [
"Centers",
"the",
"value",
"in",
"a",
"field",
"of",
"a",
"given",
"width."
] | def do_center(value, width=80):
return text_type(value).center(width) | ['def', 'do_center(value,', 'width=80):', 'return', 'text_type(value).center(width)'] | 385,806 |
alisadeghian/PGMGAN | pbar.py | print | print | When within a progress loop, will print above the progress loop. | [
"When",
"within",
"a",
"progress",
"loop,",
"will",
"print",
"above",
"the",
"progress",
"loop."
] | def print(*args):
global next_description
next_description = None
if default_verbosity:
msg = ' '.join((str(s) for s in args))
if tqdm is None:
python_print(msg)
else:
tqdm.write(msg) | ['def', 'print(*args):', 'global', 'next_description', 'next_description', '=', 'None', 'if', 'default_verbosity:', 'msg', '=', "'", "'.join((str(s)", 'for', 's', 'in', 'args))', 'if', 'tqdm', 'is', 'None:', 'python_print(msg)', 'else:', 'tqdm.write(msg)'] | 768,421 |
matsu0228/nlp-jp | misc_util.py | filter_sources | filter_sources | Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively. | [
"Return",
"four",
"lists",
"of",
"filenames",
"containing",
"C,",
"C++,",
"Fortran,",
"and",
"Fortran",
"90",
"module",
"sources,",
"respectively."
] | def filter_sources(sources):
c_sources = []
cxx_sources = []
f_sources = []
fmodule_sources = []
for source in sources:
if fortran_ext_match(source):
modules = _get_f90_modules(source)
if modules:
fmodule_sources.append(source)
else:
... | ['def', 'filter_sources(sources):', 'c_sources', '=', '[]', 'cxx_sources', '=', '[]', 'f_sources', '=', '[]', 'fmodule_sources', '=', '[]', 'for', 'source', 'in', 'sources:', 'if', 'fortran_ext_match(source):', 'modules', '=', '_get_f90_modules(source)', 'if', 'modules:', 'fmodule_sources.append(source)', 'else:', 'f_s... | 790,985 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | get_inception_scores | get_inception_scores | Get Inception score for some images. | [
"Get",
"Inception",
"score",
"for",
"some",
"images."
] | def get_inception_scores(images, batch_size, num_inception_images):
images.shape[0:1].assert_is_compatible_with([batch_size])
if batch_size % num_inception_images != 0:
raise ValueError('`batch_size` must be divisible by `num_inception_images`.')
size = 299
resized_images = tf.image.resize_bilin... | ['def', 'get_inception_scores(images,', 'batch_size,', 'num_inception_images):', 'images.shape[0:1].assert_is_compatible_with([batch_size])', 'if', 'batch_size', '%', 'num_inception_images', '!=', '0:', 'raise', "ValueError('`batch_size`", 'must', 'be', 'divisible', 'by', "`num_inception_images`.')", 'size', '=', '299'... | 48,533 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Cdf.Value | Value | Returns InverseCDF(p), the value that corresponds to probability p. | [
"Returns",
"InverseCDF(p),",
"the",
"value",
"that",
"corresponds",
"to",
"probability",
"p."
] | def Value(self, p):
if p < 0 or p > 1:
raise ValueError('Probability p must be in range [0, 1]')
index = bisect.bisect_left(self.ps, p)
return self.xs[index] | ['def', 'Value(self,', 'p):', 'if', 'p', '<', '0', 'or', 'p', '>', '1:', 'raise', "ValueError('Probability", 'p', 'must', 'be', 'in', 'range', '[0,', "1]')", 'index', '=', 'bisect.bisect_left(self.ps,', 'p)', 'return', 'self.xs[index]'] | 19,610 |
ashwanitanwar/nmt-transfer-learning-xlm-r | trainer.py | Trainer.get_lr | get_lr | Get the current learning rate. | [
"Get",
"the",
"current",
"learning",
"rate."
] | def get_lr(self):
return self.optimizer.get_lr() | ['def', 'get_lr(self):', 'return', 'self.optimizer.get_lr()'] | 733,964 |
Hadishh/cs188 | capture.py | GameState.generateSuccessor | generateSuccessor | Returns the successor state (a GameState object) after the specified agent takes the action. | [
"Returns",
"the",
"successor",
"state",
"(a",
"GameState",
"object)",
"after",
"the",
"specified",
"agent",
"takes",
"the",
"action."
] | def generateSuccessor(self, agentIndex, action):
state = GameState(self)
AgentRules.applyAction(state, action, agentIndex)
AgentRules.checkDeath(state, agentIndex)
state.data._agentMoved = agentIndex
state.data.score += state.data.scoreChange
state.data.timeleft = self.data.timeleft - 1
stat... | ['def', 'generateSuccessor(self,', 'agentIndex,', 'action):', 'state', '=', 'GameState(self)', 'AgentRules.applyAction(state,', 'action,', 'agentIndex)', 'AgentRules.checkDeath(state,', 'agentIndex)', 'state.data._agentMoved', '=', 'agentIndex', 'state.data.score', '+=', 'state.data.scoreChange', 'state.data.timeleft',... | 224,039 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_env | configure_env | Configuration for environment settings. | [
"Configuration",
"for",
"environment",
"settings."
] | def configure_env(self, cfg):
patch_persistent_workers(cfg)
self.configure_device(cfg)
self.configure_samples_per_gpu(cfg) | ['def', 'configure_env(self,', 'cfg):', 'patch_persistent_workers(cfg)', 'self.configure_device(cfg)', 'self.configure_samples_per_gpu(cfg)'] | 917,771 |
sktime/sktime | test_bagging.py | test_bagging_forecaster_forecaster_type_error | test_bagging_forecaster_forecaster_type_error | Test that the right exception is raised for invalid forecaster. | [
"Test",
"that",
"the",
"right",
"exception",
"is",
"raised",
"for",
"invalid",
"forecaster."
] | def test_bagging_forecaster_forecaster_type_error(forecaster):
y = load_airline()
with pytest.raises(TypeError) as ex:
f = BaggingForecaster(bootstrap_transformer=STLBootstrapTransformer(sp=12), forecaster=forecaster)
f.fit(y)
msg = 'forecaster in BaggingForecaster should be an sktime Fo... | ['def', 'test_bagging_forecaster_forecaster_type_error(forecaster):', 'y', '=', 'load_airline()', 'with', 'pytest.raises(TypeError)', 'as', 'ex:', 'f', '=', 'BaggingForecaster(bootstrap_transformer=STLBootstrapTransformer(sp=12),', 'forecaster=forecaster)', 'f.fit(y)', 'msg', '=', "'forecaster", 'in', 'BaggingForecaste... | 877,207 |
iffiX/machin | buffer_d.py | DistributedBuffer.size | size | Returns: Length of current local buffer. | [
"Returns:",
"Length",
"of",
"current",
"local",
"buffer."
] | def size(self):
with self.wr_lock:
return super().size() | ['def', 'size(self):', 'with', 'self.wr_lock:', 'return', 'super().size()'] | 620,307 |
ZhAnGToNG1/transfer_learning_cspt | delta_xywh_bbox_coder.py | DeltaXYWHBBoxCoder.decode | decode | Apply transformation `pred_bboxes` to `boxes`. | [
"Apply",
"transformation",
"`pred_bboxes`",
"to",
"`boxes`."
] | def decode(self, bboxes, pred_bboxes, max_shape=None, wh_ratio_clip=16 / 1000):
assert pred_bboxes.size(0) == bboxes.size(0)
if pred_bboxes.ndim == 3:
assert pred_bboxes.size(1) == bboxes.size(1)
if pred_bboxes.ndim == 2 and (not torch.onnx.is_in_onnx_export()):
decoded_bboxes = delta2bbox(b... | ['def', 'decode(self,', 'bboxes,', 'pred_bboxes,', 'max_shape=None,', 'wh_ratio_clip=16', '/', '1000):', 'assert', 'pred_bboxes.size(0)', '==', 'bboxes.size(0)', 'if', 'pred_bboxes.ndim', '==', '3:', 'assert', 'pred_bboxes.size(1)', '==', 'bboxes.size(1)', 'if', 'pred_bboxes.ndim', '==', '2', 'and', '(not', 'torch.onnx... | 963,697 |
google-research/scenic | test_matchers.py | MatchingTest.TestLazyMatcher.test_lazy_matcher | test_lazy_matcher | Test across varying number of boxes. | [
"Test",
"across",
"varying",
"number",
"of",
"boxes."
] | def test_lazy_matcher(self, nbx, nby):
cost_matrix = jnp.zeros((3, nbx, nby), dtype=jnp.float32)
expected_indices_per_row = jnp.array(list(range(min(nbx, nby))))
indices = matchers.lazy_matcher(cost_matrix)
self.assertEqual(indices.shape, (3, 2, min(nbx, nby)))
for idx in indices:
(src, tgt)... | ['def', 'test_lazy_matcher(self,', 'nbx,', 'nby):', 'cost_matrix', '=', 'jnp.zeros((3,', 'nbx,', 'nby),', 'dtype=jnp.float32)', 'expected_indices_per_row', '=', 'jnp.array(list(range(min(nbx,', 'nby))))', 'indices', '=', 'matchers.lazy_matcher(cost_matrix)', 'self.assertEqual(indices.shape,', '(3,', '2,', 'min(nbx,', '... | 846,296 |
arshpreetsingh/quantopian-machinelearning | test_paths.py | test_get_ipython_dir_6 | test_get_ipython_dir_6 | test_get_ipython_dir_6, use home over XDG if defined and neither exist. | [
"test_get_ipython_dir_6,",
"use",
"home",
"over",
"XDG",
"if",
"defined",
"and",
"neither",
"exist."
] | def test_get_ipython_dir_6():
xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
os.mkdir(xdg)
shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
print(paths._writable_dir)
with patch_get_home_dir(HOME_TEST_DIR), patch.object(paths, 'get_xdg_dir', return_value=xdg), patch('os.name', 'posix'), modified... | ['def', 'test_get_ipython_dir_6():', 'xdg', '=', 'os.path.join(HOME_TEST_DIR,', "'somexdg')", 'os.mkdir(xdg)', 'shutil.rmtree(os.path.join(HOME_TEST_DIR,', "'.ipython'))", 'print(paths._writable_dir)', 'with', 'patch_get_home_dir(HOME_TEST_DIR),', 'patch.object(paths,', "'get_xdg_dir',", 'return_value=xdg),', "patch('o... | 886,722 |
ldkong1205/LaserMix | kitti2d_dataset.py | Kitti2DDataset.drop_arrays_by_name | drop_arrays_by_name | Drop irrelevant ground truths by name. | [
"Drop",
"irrelevant",
"ground",
"truths",
"by",
"name."
] | def drop_arrays_by_name(self, gt_names, used_classes):
inds = [i for (i, x) in enumerate(gt_names) if x not in used_classes]
inds = np.array(inds, dtype=np.int64)
return inds | ['def', 'drop_arrays_by_name(self,', 'gt_names,', 'used_classes):', 'inds', '=', '[i', 'for', '(i,', 'x)', 'in', 'enumerate(gt_names)', 'if', 'x', 'not', 'in', 'used_classes]', 'inds', '=', 'np.array(inds,', 'dtype=np.int64)', 'return', 'inds'] | 623,760 |
awslabs/mxnet-lambda | futures.py | TransferFuture.set_exception | set_exception | Sets the exception on the future. | [
"Sets",
"the",
"exception",
"on",
"the",
"future."
] | def set_exception(self, exception):
if not self.done():
raise TransferNotDoneError('set_exception can only be called once the transfer is complete.')
self._coordinator.set_exception(exception, override=True) | ['def', 'set_exception(self,', 'exception):', 'if', 'not', 'self.done():', 'raise', "TransferNotDoneError('set_exception", 'can', 'only', 'be', 'called', 'once', 'the', 'transfer', 'is', "complete.')", 'self._coordinator.set_exception(exception,', 'override=True)'] | 288,951 |
scotthuang1989/object_detection_with_tensorflow | metrics.py | add_image_pred_metrics | add_image_pred_metrics | Computes the image prediction metrics. | [
"Computes",
"the",
"image",
"prediction",
"metrics."
] | def add_image_pred_metrics(inputs, outputs, num_views, upscale_factor):
names_to_values = dict()
names_to_updates = dict()
for k in xrange(num_views):
(tmp_value, tmp_update) = tf.contrib.metrics.streaming_mean_squared_error(outputs['images_%d' % (k + 1)], inputs['images_%d' % (k + 1)])
name... | ['def', 'add_image_pred_metrics(inputs,', 'outputs,', 'num_views,', 'upscale_factor):', 'names_to_values', '=', 'dict()', 'names_to_updates', '=', 'dict()', 'for', 'k', 'in', 'xrange(num_views):', '(tmp_value,', 'tmp_update)', '=', "tf.contrib.metrics.streaming_mean_squared_error(outputs['images_%d'", '%', '(k', '+', '... | 739,506 |
f-dangel/cockpit | quantity.py | Quantity.compute | compute | Evaluate quantity at a step in training. | [
"Evaluate",
"quantity",
"at",
"a",
"step",
"in",
"training."
] | def compute(self, global_step, params, batch_loss):
raise NotImplementedError | ['def', 'compute(self,', 'global_step,', 'params,', 'batch_loss):', 'raise', 'NotImplementedError'] | 493,093 |
marcsto/rl | decision_transformer.py | DTLoss.forward | forward | Compute the loss for the Online Decision Transformer. | [
"Compute",
"the",
"loss",
"for",
"the",
"Online",
"Decision",
"Transformer."
] | def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
target_actions = tensordict.get(self.tensor_keys.action).detach()
pred_actions = self.actor_network(tensordict, params=self.actor_network_params).get(self.tensor_keys.action)
loss = distance_loss(pred_actions, target_actions, loss_function=sel... | ['def', 'forward(self,', 'tensordict:', 'TensorDictBase)', '->', 'TensorDictBase:', 'target_actions', '=', 'tensordict.get(self.tensor_keys.action).detach()', 'pred_actions', '=', 'self.actor_network(tensordict,', 'params=self.actor_network_params).get(self.tensor_keys.action)', 'loss', '=', 'distance_loss(pred_actions... | 859,337 |
open-mmlab/mmtracking | transforms.py | bbox_cxcyah_to_xyxy | bbox_cxcyah_to_xyxy | Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2). | [
"Convert",
"bbox",
"coordinates",
"from",
"(cx,",
"cy,",
"ratio,",
"h)",
"to",
"(x1,",
"y1,",
"x2,",
"y2)."
] | def bbox_cxcyah_to_xyxy(bboxes):
(cx, cy, ratio, h) = bboxes.split((1, 1, 1, 1), dim=-1)
w = ratio * h
x1y1x2y2 = [cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0]
return torch.cat(x1y1x2y2, dim=-1) | ['def', 'bbox_cxcyah_to_xyxy(bboxes):', '(cx,', 'cy,', 'ratio,', 'h)', '=', 'bboxes.split((1,', '1,', '1,', '1),', 'dim=-1)', 'w', '=', 'ratio', '*', 'h', 'x1y1x2y2', '=', '[cx', '-', 'w', '/', '2.0,', 'cy', '-', 'h', '/', '2.0,', 'cx', '+', 'w', '/', '2.0,', 'cy', '+', 'h', '/', '2.0]', 'return', 'torch.cat(x1y1x2y2,'... | 625,663 |
kubeflow/pipelines | _container_op.py | Container.add_resource_request | add_resource_request | Add the resource request of the container. | [
"Add",
"the",
"resource",
"request",
"of",
"the",
"container."
] | def add_resource_request(self, resource_name, value) -> 'Container':
self.resources = self.resources or V1ResourceRequirements()
self.resources.requests = self.resources.requests or {}
self.resources.requests.update({resource_name: value})
return self | ['def', 'add_resource_request(self,', 'resource_name,', 'value)', '->', "'Container':", 'self.resources', '=', 'self.resources', 'or', 'V1ResourceRequirements()', 'self.resources.requests', '=', 'self.resources.requests', 'or', '{}', 'self.resources.requests.update({resource_name:', 'value})', 'return', 'self'] | 780,109 |
43Carrig/recurrent_neural_networks_practice | gen_image_ops.py | resize_nearest_neighbor | resize_nearest_neighbor | Resize `images` to `size` using nearest neighbor interpolation. | [
"Resize",
"`images`",
"to",
"`size`",
"using",
"nearest",
"neighbor",
"interpolation."
] | def resize_nearest_neighbor(images, size, align_corners=False, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if align_corners is None:
align_corners = False
align_corners = _execute.make_bool(align_corners, 'align_corners')
(_, _, _... | ['def', 'resize_nearest_neighbor(images,', 'size,', 'align_corners=False,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'align_corners', 'is', 'None:', 'align_corners', '=', 'False', 'align_corners', '=', '_execute.make_bool(align_corn... | 337,881 |
lhotse-speech/lhotse | opensmile.py | OpenSmileConfig.featuresets_names | featuresets_names | Returns list of strings with names of pretrained FeatureSets available in opensmile. | [
"Returns",
"list",
"of",
"strings",
"with",
"names",
"of",
"pretrained",
"FeatureSets",
"available",
"in",
"opensmile."
] | def featuresets_names():
assert is_module_available('opensmile'), 'To use opensmile extractors, please "pip install opensmile" first.'
import opensmile
return list(opensmile.FeatureSet.__members__) | ['def', 'featuresets_names():', 'assert', "is_module_available('opensmile'),", "'To", 'use', 'opensmile', 'extractors,', 'please', '"pip', 'install', 'opensmile"', "first.'", 'import', 'opensmile', 'return', 'list(opensmile.FeatureSet.__members__)'] | 600,881 |
swisscom/cleanerversion | models.py | VersionManager.as_of | as_of | Filters Versionables at a given time :param time: The timestamp (including timezone info) at which Versionables shall be retrieved :return: A QuerySet containing the base for a timestamped query. | [
"Filters",
"Versionables",
"at",
"a",
"given",
"time",
":param",
"time:",
"The",
"timestamp",
"(including",
"timezone",
"info)",
"at",
"which",
"Versionables",
"shall",
"be",
"retrieved",
":return:",
"A",
"QuerySet",
"containing",
"the",
"base",
"for",
"a",
"tim... | def as_of(self, time=None):
return self.get_queryset().as_of(time) | ['def', 'as_of(self,', 'time=None):', 'return', 'self.get_queryset().as_of(time)'] | 122,397 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | is_tfrecord_input | is_tfrecord_input | Checks if input is a TFRecord or list of TFRecords. | [
"Checks",
"if",
"input",
"is",
"a",
"TFRecord",
"or",
"list",
"of",
"TFRecords."
] | def is_tfrecord_input(inp):
def _is_tfrecord(inp):
if not isinstance(inp, str):
return False
(_, extension) = os.path.splitext(inp)
return extension == '.tfrecord'
if isinstance(inp, str):
return _is_tfrecord(inp)
if isinstance(inp, list):
return all(map(... | ['def', 'is_tfrecord_input(inp):', 'def', '_is_tfrecord(inp):', 'if', 'not', 'isinstance(inp,', 'str):', 'return', 'False', '(_,', 'extension)', '=', 'os.path.splitext(inp)', 'return', 'extension', '==', "'.tfrecord'", 'if', 'isinstance(inp,', 'str):', 'return', '_is_tfrecord(inp)', 'if', 'isinstance(inp,', 'list):', '... | 29,772 |
unixpickle/anyrl-py | test_rollers.py | test_ep_basic_equivalence | test_ep_basic_equivalence | Test that EpisodeRoller is equivalent to a BasicRoller when run on a single environment. | [
"Test",
"that",
"EpisodeRoller",
"is",
"equivalent",
"to",
"a",
"BasicRoller",
"when",
"run",
"on",
"a",
"single",
"environment."
] | def test_ep_basic_equivalence(stateful, state_tuple, limits):
def env_fn():
return SimpleEnv(3, (4, 5), 'uint8')
env = env_fn()
model = SimpleModel(env.action_space.low.shape, stateful=stateful, state_tuple=state_tuple)
basic_roller = BasicRoller(env, model, **limits)
expected = basic_rolle... | ['def', 'test_ep_basic_equivalence(stateful,', 'state_tuple,', 'limits):', 'def', 'env_fn():', 'return', 'SimpleEnv(3,', '(4,', '5),', "'uint8')", 'env', '=', 'env_fn()', 'model', '=', 'SimpleModel(env.action_space.low.shape,', 'stateful=stateful,', 'state_tuple=state_tuple)', 'basic_roller', '=', 'BasicRoller(env,', '... | 33,950 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | static_shape.py | get_depth | get_depth | Returns depth from the tensor shape. | [
"Returns",
"depth",
"from",
"the",
"tensor",
"shape."
] | def get_depth(tensor_shape):
tensor_shape.assert_has_rank(rank=4)
return tensor_shape[3].value | ['def', 'get_depth(tensor_shape):', 'tensor_shape.assert_has_rank(rank=4)', 'return', 'tensor_shape[3].value'] | 52,314 |
aasimkhan0207/computer_vision | cpp_lint.py | _FunctionState.End | End | Stop analyzing function body. | [
"Stop",
"analyzing",
"function",
"body."
] | def End(self):
self.in_a_function = False | ['def', 'End(self):', 'self.in_a_function', '=', 'False'] | 473,733 |
CouLiBaLy-B/Unsupervised-Learning | network.py | VariationalAutoencoder_Linear.forward | forward | Forward computations of the multi-layer autoencoder. | [
"Forward",
"computations",
"of",
"the",
"multi-layer",
"autoencoder."
] | def forward(self, x, encode=False, decode=False):
encoded = torch.zeros([], dtype=torch.float32)
decoded = torch.zeros([], dtype=torch.float32)
if encode:
encoded = self.encoder(x.view(-1, self.img_size))
z_mu = self.enc_fc1(encoded)
z_var = self.enc_fc2(encoded)
if decode:
... | ['def', 'forward(self,', 'x,', 'encode=False,', 'decode=False):', 'encoded', '=', 'torch.zeros([],', 'dtype=torch.float32)', 'decoded', '=', 'torch.zeros([],', 'dtype=torch.float32)', 'if', 'encode:', 'encoded', '=', 'self.encoder(x.view(-1,', 'self.img_size))', 'z_mu', '=', 'self.enc_fc1(encoded)', 'z_var', '=', 'self... | 353,264 |
fudan-zvg/SETR | trident_roi_head.py | TridentRoIHead.merge_trident_bboxes | merge_trident_bboxes | Merge bbox predictions of each branch. | [
"Merge",
"bbox",
"predictions",
"of",
"each",
"branch."
] | def merge_trident_bboxes(self, trident_det_bboxes, trident_det_labels):
if trident_det_bboxes.numel() == 0:
det_bboxes = trident_det_bboxes.new_zeros((0, 5))
det_labels = trident_det_bboxes.new_zeros((0,), dtype=torch.long)
else:
nms_bboxes = trident_det_bboxes[:, :4]
nms_scores ... | ['def', 'merge_trident_bboxes(self,', 'trident_det_bboxes,', 'trident_det_labels):', 'if', 'trident_det_bboxes.numel()', '==', '0:', 'det_bboxes', '=', 'trident_det_bboxes.new_zeros((0,', '5))', 'det_labels', '=', 'trident_det_bboxes.new_zeros((0,),', 'dtype=torch.long)', 'else:', 'nms_bboxes', '=', 'trident_det_bboxes... | 898,374 |
IceClear/MW-GAN | matlab_functions.py | cubic | cubic | cubic function used for calculate_weights_indices. | [
"cubic",
"function",
"used",
"for",
"calculate_weights_indices."
] | def cubic(x):
absx = torch.abs(x)
absx2 = absx ** 2
absx3 = absx ** 3
return (1.5 * absx3 - 2.5 * absx2 + 1) * (absx <= 1).type_as(absx) + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2) * ((absx > 1) * (absx <= 2)).type_as(absx) | ['def', 'cubic(x):', 'absx', '=', 'torch.abs(x)', 'absx2', '=', 'absx', '**', '2', 'absx3', '=', 'absx', '**', '3', 'return', '(1.5', '*', 'absx3', '-', '2.5', '*', 'absx2', '+', '1)', '*', '(absx', '<=', '1).type_as(absx)', '+', '(-0.5', '*', 'absx3', '+', '2.5', '*', 'absx2', '-', '4', '*', 'absx', '+', '2)', '*', '(... | 651,527 |
enuguru/artificial_intelligence_and_machine_learning | log.py | InstanceLogger.critical | critical | Delegate a critical call to the underlying logger. | [
"Delegate",
"a",
"critical",
"call",
"to",
"the",
"underlying",
"logger."
] | def critical(self, msg, *args, **kwargs):
self.log(logging.CRITICAL, msg, *args, **kwargs) | ['def', 'critical(self,', 'msg,', '*args,', '**kwargs):', 'self.log(logging.CRITICAL,', 'msg,', '*args,', '**kwargs)'] | 131,784 |
lizoyu/cse511a-2017fall | captureAgents.py | CaptureAgent.getCurrentObservation | getCurrentObservation | Returns the GameState object corresponding this agent's current observation (the observed state of the game - this may not include all of your opponent's agent locations exactly). | [
"Returns",
"the",
"GameState",
"object",
"corresponding",
"this",
"agent's",
"current",
"observation",
"(the",
"observed",
"state",
"of",
"the",
"game",
"-",
"this",
"may",
"not",
"include",
"all",
"of",
"your",
"opponent's",
"agent",
"locations",
"exactly)."
] | def getCurrentObservation(self):
return self.observationHistory[-1] | ['def', 'getCurrentObservation(self):', 'return', 'self.observationHistory[-1]'] | 193,366 |
adamshamsudeen/vision.ai | datastructures.py | HeaderSet.add | add | Add a new header to the set. | [
"Add",
"a",
"new",
"header",
"to",
"the",
"set."
] | def add(self, header):
self.update((header,)) | ['def', 'add(self,', 'header):', 'self.update((header,))'] | 944,408 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | progressive.py | ProgressiveModel.BuildGraph | BuildGraph | Build the graph corresponding to the progressive BRNN model. | [
"Build",
"the",
"graph",
"corresponding",
"to",
"the",
"progressive",
"BRNN",
"model."
] | def BuildGraph(self, input_codes):
layer_depth = self._config['layer_depth']
layer_count = self._config['layer_count']
code_shape = input_codes.get_shape()
code_depth = code_shape[-1].value
if self._config['coded_layer_count'] > 0:
prefix_depth = self._config['coded_layer_count'] * layer_dep... | ['def', 'BuildGraph(self,', 'input_codes):', 'layer_depth', '=', "self._config['layer_depth']", 'layer_count', '=', "self._config['layer_count']", 'code_shape', '=', 'input_codes.get_shape()', 'code_depth', '=', 'code_shape[-1].value', 'if', "self._config['coded_layer_count']", '>', '0:', 'prefix_depth', '=', "self._co... | 47,405 |
funkelab/gunpowder | profiling.py | ProfilingStats.span_time | span_time | Time between the first call to start() and last call to stop() over any timing. | [
"Time",
"between",
"the",
"first",
"call",
"to",
"start()",
"and",
"last",
"call",
"to",
"stop()",
"over",
"any",
"timing."
] | def span_time(self):
(start, stop) = self.span()
return stop - start | ['def', 'span_time(self):', '(start,', 'stop)', '=', 'self.span()', 'return', 'stop', '-', 'start'] | 572,754 |
Kvatsx/Artificial-Intelligence-Assignments | contour.py | ContourLabeler.too_close | too_close | Return *True* if a label is already near this location. | [
"Return",
"*True*",
"if",
"a",
"label",
"is",
"already",
"near",
"this",
"location."
] | def too_close(self, x, y, lw):
for loc in self.labelXYs:
d = np.sqrt((x - loc[0]) ** 2 + (y - loc[1]) ** 2)
if d < 1.2 * lw:
return True
return False | ['def', 'too_close(self,', 'x,', 'y,', 'lw):', 'for', 'loc', 'in', 'self.labelXYs:', 'd', '=', 'np.sqrt((x', '-', 'loc[0])', '**', '2', '+', '(y', '-', 'loc[1])', '**', '2)', 'if', 'd', '<', '1.2', '*', 'lw:', 'return', 'True', 'return', 'False'] | 424 |
70Shubham07/NaturalLanguageProcessing | trigram_model.py | TrigramModel.smoothed_trigram_probability | smoothed_trigram_probability | COMPLETE THIS METHOD (PART 4) Returns the smoothed trigram probability (using linear interpolation). | [
"COMPLETE",
"THIS",
"METHOD",
"(PART",
"4)",
"Returns",
"the",
"smoothed",
"trigram",
"probability",
"(using",
"linear",
"interpolation)."
] | def smoothed_trigram_probability(self, trigram):
lambda1 = 1 / 3.0
lambda2 = 1 / 3.0
lambda3 = 1 / 3.0
smoothed_trigram = lambda1 * self.raw_trigram_probability(trigram)
smoothed_bigram = lambda2 * self.raw_bigram_probability(trigram[1:])
smoothed_unigram = lambda3 * self.raw_unigram_probability... | ['def', 'smoothed_trigram_probability(self,', 'trigram):', 'lambda1', '=', '1', '/', '3.0', 'lambda2', '=', '1', '/', '3.0', 'lambda3', '=', '1', '/', '3.0', 'smoothed_trigram', '=', 'lambda1', '*', 'self.raw_trigram_probability(trigram)', 'smoothed_bigram', '=', 'lambda2', '*', 'self.raw_bigram_probability(trigram[1:]... | 677,278 |
BarisYazici/deep-rl-grasping | transformations.py | Arcball.matrix | matrix | Return homogeneous rotation matrix. | [
"Return",
"homogeneous",
"rotation",
"matrix."
] | def matrix(self):
return quaternion_matrix(self._qnow) | ['def', 'matrix(self):', 'return', 'quaternion_matrix(self._qnow)'] | 519,547 |
huawei-noah/xingtian | cifar100.py | Cifar100Config.rules | rules | Return rules for checking. | [
"Return",
"rules",
"for",
"checking."
] | def rules(cls):
rules_Cifar100 = {'common': {'type': dict}, 'train': {'type': dict}, 'val': {'type': dict}, 'test': {'type': dict}}
return rules_Cifar100 | ['def', 'rules(cls):', 'rules_Cifar100', '=', "{'common':", "{'type':", 'dict},', "'train':", "{'type':", 'dict},', "'val':", "{'type':", 'dict},', "'test':", "{'type':", 'dict}}', 'return', 'rules_Cifar100'] | 962,556 |
ucas-vg/PointTinyBenchmark | mobilenet_v2.py | MobileNetV2.make_layer | make_layer | Stack InvertedResidual blocks to build a layer for MobileNetV2. | [
"Stack",
"InvertedResidual",
"blocks",
"to",
"build",
"a",
"layer",
"for",
"MobileNetV2."
] | def make_layer(self, out_channels, num_blocks, stride, expand_ratio):
layers = []
for i in range(num_blocks):
if i >= 1:
stride = 1
layers.append(InvertedResidual(self.in_channels, out_channels, mid_channels=int(round(self.in_channels * expand_ratio)), stride=stride, with_expand_conv... | ['def', 'make_layer(self,', 'out_channels,', 'num_blocks,', 'stride,', 'expand_ratio):', 'layers', '=', '[]', 'for', 'i', 'in', 'range(num_blocks):', 'if', 'i', '>=', '1:', 'stride', '=', '1', 'layers.append(InvertedResidual(self.in_channels,', 'out_channels,', 'mid_channels=int(round(self.in_channels', '*', 'expand_ra... | 781,530 |
sunishsheth2009/ChatterBot | test.py | Client.patch | patch | Like open but method is enforced to PATCH. | [
"Like",
"open",
"but",
"method",
"is",
"enforced",
"to",
"PATCH."
] | def patch(self, *args, **kw):
kw['method'] = 'PATCH'
return self.open(*args, **kw) | ['def', 'patch(self,', '*args,', '**kw):', "kw['method']", '=', "'PATCH'", 'return', 'self.open(*args,', '**kw)'] | 482,297 |
hamza-murad/AALU | discovery_v1.py | MetricTokenAggregation.from_dict | from_dict | Initialize a MetricTokenAggregation object from a json dictionary. | [
"Initialize",
"a",
"MetricTokenAggregation",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation':
args = {}
valid_keys = ['event_type', 'results']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class MetricTokenAggregation: ' + ', '.join(bad_keys))
if '... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'MetricTokenAggregation':", 'args', '=', '{}', 'valid_keys', '=', "['event_type',", "'results']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'clas... | 5,608 |
rishab-sharma/object_detection | model.py | ObjectDetector.process_anchor_data | process_anchor_data | Prepare the anchor data for training RPN. | [
"Prepare",
"the",
"anchor",
"data",
"for",
"training",
"RPN."
] | def process_anchor_data(self, anchor_files):
gt_anchor_labels = []
gt_anchor_regs = []
anchor_masks = []
anchor_weights = []
anchor_reg_masks = []
t = self.num_anchor_type
for i in range(self.batch_size):
anchor_data = np.load(anchor_files[i])
labels = anchor_data['labels']
... | ['def', 'process_anchor_data(self,', 'anchor_files):', 'gt_anchor_labels', '=', '[]', 'gt_anchor_regs', '=', '[]', 'anchor_masks', '=', '[]', 'anchor_weights', '=', '[]', 'anchor_reg_masks', '=', '[]', 't', '=', 'self.num_anchor_type', 'for', 'i', 'in', 'range(self.batch_size):', 'anchor_data', '=', 'np.load(anchor_fil... | 745,102 |
caiiiac/Machine-Learning-with-Python | ltisys.py | StateSpace.C | C | Output matrix of the `StateSpace` system. | [
"Output",
"matrix",
"of",
"the",
"`StateSpace`",
"system."
] | def C(self):
return self._C | ['def', 'C(self):', 'return', 'self._C'] | 719,831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.