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 |
|---|---|---|---|---|---|---|---|---|
jshilong/DDQ | base_runner.py | BaseRunner.inner_iter | inner_iter | int: Iteration in an epoch. | [
"int:",
"Iteration",
"in",
"an",
"epoch."
] | def inner_iter(self):
return self._inner_iter | ['def', 'inner_iter(self):', 'return', 'self._inner_iter'] | 515,446 |
jeffnyman/pacumen | utilities.py | lookup | lookup | Gets a method or class from any imported module from its name. | [
"Gets",
"a",
"method",
"or",
"class",
"from",
"any",
"imported",
"module",
"from",
"its",
"name."
] | def lookup(name, namespace):
dots = name.count('.')
if dots > 0:
(module_name, object_name) = ('.'.join(name.split('.')[:-1]), name.split('.')[-1])
the_module = __import__(module_name)
return getattr(the_module, object_name)
else:
modules = [obj for obj in list(namespace.valu... | ['def', 'lookup(name,', 'namespace):', 'dots', '=', "name.count('.')", 'if', 'dots', '>', '0:', '(module_name,', 'object_name)', '=', "('.'.join(name.split('.')[:-1]),", "name.split('.')[-1])", 'the_module', '=', '__import__(module_name)', 'return', 'getattr(the_module,', 'object_name)', 'else:', 'modules', '=', '[obj'... | 255,929 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | anchor_generator_builder.py | build | build | Builds an anchor generator based on the config. | [
"Builds",
"an",
"anchor",
"generator",
"based",
"on",
"the",
"config."
] | def build(anchor_generator_config):
if not isinstance(anchor_generator_config, anchor_generator_pb2.AnchorGenerator):
raise ValueError('anchor_generator_config not of type anchor_generator_pb2.AnchorGenerator')
if anchor_generator_config.WhichOneof('anchor_generator_oneof') == 'grid_anchor_generator':
... | ['def', 'build(anchor_generator_config):', 'if', 'not', 'isinstance(anchor_generator_config,', 'anchor_generator_pb2.AnchorGenerator):', 'raise', "ValueError('anchor_generator_config", 'not', 'of', 'type', "anchor_generator_pb2.AnchorGenerator')", 'if', "anchor_generator_config.WhichOneof('anchor_generator_oneof')", '=... | 56,717 |
suarez12138/AI-Reversi_IMP_TextDichotomy | kernels.py | CompoundKernel.requires_vector_input | requires_vector_input | Returns whether the kernel is defined on discrete structures. | [
"Returns",
"whether",
"the",
"kernel",
"is",
"defined",
"on",
"discrete",
"structures."
] | def requires_vector_input(self):
return np.any([kernel.requires_vector_input for kernel in self.kernels]) | ['def', 'requires_vector_input(self):', 'return', 'np.any([kernel.requires_vector_input', 'for', 'kernel', 'in', 'self.kernels])'] | 101,283 |
dingmyu/D4LCN | core.py | load_weights | load_weights | Simply loads a pytorch models weights from a given path. | [
"Simply",
"loads",
"a",
"pytorch",
"models",
"weights",
"from",
"a",
"given",
"path."
] | def load_weights(model, path, remove_module=False):
dst_weights = model.state_dict()
src_weights = torch.load(path)
dst_keys = list(dst_weights.keys())
src_keys = list(src_weights.keys())
if remove_module:
for key in src_keys:
src_weights[key.replace('module.', '')] = src_weights... | ['def', 'load_weights(model,', 'path,', 'remove_module=False):', 'dst_weights', '=', 'model.state_dict()', 'src_weights', '=', 'torch.load(path)', 'dst_keys', '=', 'list(dst_weights.keys())', 'src_keys', '=', 'list(src_weights.keys())', 'if', 'remove_module:', 'for', 'key', 'in', 'src_keys:', "src_weights[key.replace('... | 526,133 |
43Carrig/recurrent_neural_networks_practice | control_flow_ops.py | ControlFlowContext.ExitGradientColocation | ExitGradientColocation | Start building a gradient colocated with an op. | [
"Start",
"building",
"a",
"gradient",
"colocated",
"with",
"an",
"op."
] | def ExitGradientColocation(self, op, gradient_uid):
if self._outer_context:
self._outer_context.ExitGradientColocation(op, gradient_uid) | ['def', 'ExitGradientColocation(self,', 'op,', 'gradient_uid):', 'if', 'self._outer_context:', 'self._outer_context.ExitGradientColocation(op,', 'gradient_uid)'] | 337,163 |
arshpreetsingh/quantopian-machinelearning | buffer.py | CompletionState.current_completion | current_completion | Return the current completion, or return `None` when no completion is selected. | [
"Return",
"the",
"current",
"completion,",
"or",
"return",
"`None`",
"when",
"no",
"completion",
"is",
"selected."
] | def current_completion(self):
if self.complete_index is not None:
return self.completions[self.complete_index] | ['def', 'current_completion(self):', 'if', 'self.complete_index', 'is', 'not', 'None:', 'return', 'self.completions[self.complete_index]'] | 891,966 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Base.configHandler | configHandler | Returns the config handler for this type of template. | [
"Returns",
"the",
"config",
"handler",
"for",
"this",
"type",
"of",
"template."
] | def configHandler(self, part, suffix='Handler', default=None):
name = '{0}{1}{2}'.format(self.typeName, part, suffix)
return self.config.last(name, default) | ['def', 'configHandler(self,', 'part,', "suffix='Handler',", 'default=None):', 'name', '=', "'{0}{1}{2}'.format(self.typeName,", 'part,', 'suffix)', 'return', 'self.config.last(name,', 'default)'] | 10,878 |
salesforce/CodeRL | logging.py | add_handler | add_handler | adds a handler to the HuggingFace Transformers's root logger. | [
"adds",
"a",
"handler",
"to",
"the",
"HuggingFace",
"Transformers's",
"root",
"logger."
] | def add_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler) | ['def', 'add_handler(handler:', 'logging.Handler)', '->', 'None:', '_configure_library_root_logger()', 'assert', 'handler', 'is', 'not', 'None', '_get_library_root_logger().addHandler(handler)'] | 495,601 |
salesforce/CodeRL | modeling_funnel.py | FunnelAttentionStructure.stride_pool | stride_pool | Perform pooling by stride slicing the tensor along the given axis. | [
"Perform",
"pooling",
"by",
"stride",
"slicing",
"the",
"tensor",
"along",
"the",
"given",
"axis."
] | def stride_pool(self, tensor, axis):
if tensor is None:
return None
if isinstance(axis, (list, tuple)):
for ax in axis:
tensor = self.stride_pool(tensor, ax)
return tensor
if isinstance(tensor, (tuple, list)):
return type(tensor)((self.stride_pool(x, axis) for x i... | ['def', 'stride_pool(self,', 'tensor,', 'axis):', 'if', 'tensor', 'is', 'None:', 'return', 'None', 'if', 'isinstance(axis,', '(list,', 'tuple)):', 'for', 'ax', 'in', 'axis:', 'tensor', '=', 'self.stride_pool(tensor,', 'ax)', 'return', 'tensor', 'if', 'isinstance(tensor,', '(tuple,', 'list)):', 'return', 'type(tensor)((... | 494,649 |
alibaba/EasyCV | ClipBertTwoStream.py | ClipBertTwoStream.forward_test | forward_test | Defines the computation performed at every call when evaluation and testing. | [
"Defines",
"the",
"computation",
"performed",
"at",
"every",
"call",
"when",
"evaluation",
"and",
"testing."
] | def forward_test(self, imgs, text_input_ids, text_input_mask, label=None, **kwargs):
cls_score = self.extract_feat(imgs, text_input_ids, text_input_mask)
if label is not None:
return dict(neck=cls_score.cpu(), label=label.cpu())
else:
result = {}
result['prob'] = self.activate_fn(cls... | ['def', 'forward_test(self,', 'imgs,', 'text_input_ids,', 'text_input_mask,', 'label=None,', '**kwargs):', 'cls_score', '=', 'self.extract_feat(imgs,', 'text_input_ids,', 'text_input_mask)', 'if', 'label', 'is', 'not', 'None:', 'return', 'dict(neck=cls_score.cpu(),', 'label=label.cpu())', 'else:', 'result', '=', '{}', ... | 546,743 |
NUAAXQ/MLCVNet | CGNL.py | SpatialCGNLx.kernel | kernel | The non-linear kernel (Gaussian RBF). | [
"The",
"non-linear",
"kernel",
"(Gaussian",
"RBF)."
] | def kernel(self, t, p, g, b, c, h, w):
t = t.view(b, 1, c * h * w)
p = p.view(b, 1, c * h * w)
g = g.view(b, c * h * w, 1)
gamma = torch.Tensor(1).fill_(0.0001)
beta = torch.exp(-2 * gamma)
t_taylor = []
p_taylor = []
for order in range(self.order + 1):
alpha = torch.mul(torch.di... | ['def', 'kernel(self,', 't,', 'p,', 'g,', 'b,', 'c,', 'h,', 'w):', 't', '=', 't.view(b,', '1,', 'c', '*', 'h', '*', 'w)', 'p', '=', 'p.view(b,', '1,', 'c', '*', 'h', '*', 'w)', 'g', '=', 'g.view(b,', 'c', '*', 'h', '*', 'w,', '1)', 'gamma', '=', 'torch.Tensor(1).fill_(0.0001)', 'beta', '=', 'torch.exp(-2', '*', 'gamma)... | 630,113 |
liusongxiang/StarGAN-Voice-Conversion | solver.py | Solver.build_tensorboard | build_tensorboard | Build a tensorboard logger. | [
"Build",
"a",
"tensorboard",
"logger."
] | def build_tensorboard(self):
from logger import Logger
self.logger = Logger(self.log_dir) | ['def', 'build_tensorboard(self):', 'from', 'logger', 'import', 'Logger', 'self.logger', '=', 'Logger(self.log_dir)'] | 873,529 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | Model.create_loss | create_loss | Creates all losses required to train the model. | [
"Creates",
"all",
"losses",
"required",
"to",
"train",
"the",
"model."
] | def create_loss(self, data, endpoints):
self.sequence_loss_fn(endpoints.chars_logit, data.labels)
total_loss = slim.losses.get_total_loss()
tf.summary.scalar('TotalLoss', total_loss)
return total_loss | ['def', 'create_loss(self,', 'data,', 'endpoints):', 'self.sequence_loss_fn(endpoints.chars_logit,', 'data.labels)', 'total_loss', '=', 'slim.losses.get_total_loss()', "tf.summary.scalar('TotalLoss',", 'total_loss)', 'return', 'total_loss'] | 20,684 |
jbwang1997/CrossKD | dino.py | DINO.init_weights | init_weights | Initialize weights for Transformer and other components. | [
"Initialize",
"weights",
"for",
"Transformer",
"and",
"other",
"components."
] | def init_weights(self) -> None:
super(DeformableDETR, self).init_weights()
for coder in (self.encoder, self.decoder):
for p in coder.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
for m in self.modules():
if isinstance(m, MultiScaleDeformableAttention):
... | ['def', 'init_weights(self)', '->', 'None:', 'super(DeformableDETR,', 'self).init_weights()', 'for', 'coder', 'in', '(self.encoder,', 'self.decoder):', 'for', 'p', 'in', 'coder.parameters():', 'if', 'p.dim()', '>', '1:', 'nn.init.xavier_uniform_(p)', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', 'MultiSca... | 491,246 |
intel/neural-compressor | quantize_graph_pooling.py | FuseNodeStartWithPooling.get_longest_fuse | get_longest_fuse | Only pooling op itself, no fusion pattern. | [
"Only",
"pooling",
"op",
"itself,",
"no",
"fusion",
"pattern."
] | def get_longest_fuse(self):
return 1 | ['def', 'get_longest_fuse(self):', 'return', '1'] | 737,784 |
gunthercox/ChatterBot | scoping.py | ScopedSession.configure | configure | reconfigure the sessionmaker used by this ScopedSession. | [
"reconfigure",
"the",
"sessionmaker",
"used",
"by",
"this",
"ScopedSession."
] | def configure(self, **kwargs):
if self.registry.has():
warn('At least one scoped session is already present. configure() can not affect sessions that have already been created.')
self.session_factory.configure(**kwargs) | ['def', 'configure(self,', '**kwargs):', 'if', 'self.registry.has():', "warn('At", 'least', 'one', 'scoped', 'session', 'is', 'already', 'present.', 'configure()', 'can', 'not', 'affect', 'sessions', 'that', 'have', 'already', 'been', "created.')", 'self.session_factory.configure(**kwargs)'] | 481,427 |
bislara/Object-detection-GUI | autoaugment_utils.py | policy_v2 | policy_v2 | Additional policy that performs well on object detection. | [
"Additional",
"policy",
"that",
"performs",
"well",
"on",
"object",
"detection."
] | def policy_v2():
policy = [[('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)], [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2), ('Rotate_BBox', 0.8, 10)], [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)], [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8), ('Brightness', 0.0, 10)], [('SolarizeAdd... | ['def', 'policy_v2():', 'policy', '=', "[[('Color',", '0.0,', '6),', "('Cutout',", '0.6,', '8),', "('Sharpness',", '0.4,', '8)],', "[('Rotate_BBox',", '0.4,', '8),', "('Sharpness',", '0.4,', '2),', "('Rotate_BBox',", '0.8,', '10)],', "[('TranslateY_BBox',", '1.0,', '8),', "('AutoContrast',", '0.8,', '2)],', "[('AutoCon... | 726,702 |
AlibabaResearch/efficientteacher | autoaugment_utils.py | shear_with_bboxes | shear_with_bboxes | Applies Shear Transformation to the image and shifts the bboxes. | [
"Applies",
"Shear",
"Transformation",
"to",
"the",
"image",
"and",
"shifts",
"the",
"bboxes."
] | def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):
if shear_horizontal:
image = shear_x(image, level, replace)
else:
image = shear_y(image, level, replace)
(image_height, image_width) = image.shape[:2]
wrapped_shear_bbox = lambda bbox: _shear_bbox(bbox, image_height,... | ['def', 'shear_with_bboxes(image,', 'bboxes,', 'level,', 'replace,', 'shear_horizontal):', 'if', 'shear_horizontal:', 'image', '=', 'shear_x(image,', 'level,', 'replace)', 'else:', 'image', '=', 'shear_y(image,', 'level,', 'replace)', '(image_height,', 'image_width)', '=', 'image.shape[:2]', 'wrapped_shear_bbox', '=', ... | 561,102 |
googleapis/python-aiplatform | client.py | ScheduleServiceClient.parse_custom_job_path | parse_custom_job_path | Parses a custom_job path into its component segments. | [
"Parses",
"a",
"custom_job",
"path",
"into",
"its",
"component",
"segments."
] | def parse_custom_job_path(path: str) -> Dict[str, str]:
m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/customJobs/(?P<custom_job>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_custom_job_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/customJobs/(?P<custom_job>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 813,964 |
cuiziteng/ICCV_MAET | lvis.py | LVISV05Dataset.load_annotations | load_annotations | Load annotation from lvis style annotation file. | [
"Load",
"annotation",
"from",
"lvis",
"style",
"annotation",
"file."
] | def load_annotations(self, ann_file):
try:
import lvis
assert lvis.__version__ >= '10.5.3'
from lvis import LVIS
except AssertionError:
raise AssertionError('Incompatible version of lvis is installed. Run pip uninstall lvis first. Then run pip install mmlvis to install open-mmlab... | ['def', 'load_annotations(self,', 'ann_file):', 'try:', 'import', 'lvis', 'assert', 'lvis.__version__', '>=', "'10.5.3'", 'from', 'lvis', 'import', 'LVIS', 'except', 'AssertionError:', 'raise', "AssertionError('Incompatible", 'version', 'of', 'lvis', 'is', 'installed.', 'Run', 'pip', 'uninstall', 'lvis', 'first.', 'The... | 228,486 |
deepmind/dm_env | specs.py | Array.generate_value | generate_value | Generate a test value which conforms to this spec. | [
"Generate",
"a",
"test",
"value",
"which",
"conforms",
"to",
"this",
"spec."
] | def generate_value(self):
return np.zeros(shape=self.shape, dtype=self.dtype) | ['def', 'generate_value(self):', 'return', 'np.zeros(shape=self.shape,', 'dtype=self.dtype)'] | 166,710 |
weimin17/Object-Detection_HelmetDetection | svtcn_loss.py | masked_maximum | masked_maximum | Computes the axis wise maximum over chosen elements. | [
"Computes",
"the",
"axis",
"wise",
"maximum",
"over",
"chosen",
"elements."
] | def masked_maximum(data, mask, dim=1):
axis_minimums = tf.reduce_min(data, dim, keep_dims=True)
masked_maximums = tf.reduce_max(tf.multiply(data - axis_minimums, mask), dim, keep_dims=True) + axis_minimums
return masked_maximums | ['def', 'masked_maximum(data,', 'mask,', 'dim=1):', 'axis_minimums', '=', 'tf.reduce_min(data,', 'dim,', 'keep_dims=True)', 'masked_maximums', '=', 'tf.reduce_max(tf.multiply(data', '-', 'axis_minimums,', 'mask),', 'dim,', 'keep_dims=True)', '+', 'axis_minimums', 'return', 'masked_maximums'] | 760,705 |
Apress/applied-reinforcement-learning-w-python | trading.py | SpreadTrading.step | step | Take an action (buy/sell/hold) and computes the immediate reward. | [
"Take",
"an",
"action",
"(buy/sell/hold)",
"and",
"computes",
"the",
"immediate",
"reward."
] | def step(self, action):
assert any([(action == x).all() for x in self._actions.values()])
self._action = action
self._iteration += 1
done = False
instant_pnl = 0
info = {}
reward = -self._time_fee
if all(action == self._actions['buy']):
reward -= self._trading_fee
if all(... | ['def', 'step(self,', 'action):', 'assert', 'any([(action', '==', 'x).all()', 'for', 'x', 'in', 'self._actions.values()])', 'self._action', '=', 'action', 'self._iteration', '+=', '1', 'done', '=', 'False', 'instant_pnl', '=', '0', 'info', '=', '{}', 'reward', '=', '-self._time_fee', 'if', 'all(action', '==', "self._ac... | 34,037 |
newsdev/elex | models.py | Election.ballot_measures | ballot_measures | Return list of ballot measure objects with results. | [
"Return",
"list",
"of",
"ballot",
"measure",
"objects",
"with",
"results."
] | def ballot_measures(self):
raw_races = self.get_raw_races(omitResults=True, level='ru', test=self.testresults, national=self.national, apiKey=self.api_key)
race_objs = self.get_race_objects(raw_races)
(races, reporting_units, candidate_reporting_units) = self.get_units(race_objs)
(candidates, ballot_mea... | ['def', 'ballot_measures(self):', 'raw_races', '=', 'self.get_raw_races(omitResults=True,', "level='ru',", 'test=self.testresults,', 'national=self.national,', 'apiKey=self.api_key)', 'race_objs', '=', 'self.get_race_objects(raw_races)', '(races,', 'reporting_units,', 'candidate_reporting_units)', '=', 'self.get_units(... | 175,725 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | parallel.py | closing | closing | Return a context manager making sure the pool closes properly. | [
"Return",
"a",
"context",
"manager",
"making",
"sure",
"the",
"pool",
"closes",
"properly."
] | def closing(pool):
try:
yield pool
finally:
pool.close()
pool.join()
pool.terminate() | ['def', 'closing(pool):', 'try:', 'yield', 'pool', 'finally:', 'pool.close()', 'pool.join()', 'pool.terminate()'] | 454,403 |
matsu0228/nlp-jp | offsetbox.py | OffsetBox.get_visible_children | get_visible_children | Return a list of visible artists it contains. | [
"Return",
"a",
"list",
"of",
"visible",
"artists",
"it",
"contains."
] | def get_visible_children(self):
return [c for c in self._children if c.get_visible()] | ['def', 'get_visible_children(self):', 'return', '[c', 'for', 'c', 'in', 'self._children', 'if', 'c.get_visible()]'] | 788,962 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | network_units.py | get_input_tensor | get_input_tensor | Helper function for constructing an input tensor from all the features. | [
"Helper",
"function",
"for",
"constructing",
"an",
"input",
"tensor",
"from",
"all",
"the",
"features."
] | def get_input_tensor(fixed_embeddings, linked_embeddings):
embeddings = fixed_embeddings + linked_embeddings
if not embeddings:
raise RuntimeError('There needs to be at least one feature set defined.')
return tf.concat([e.tensor for e in embeddings], 1) | ['def', 'get_input_tensor(fixed_embeddings,', 'linked_embeddings):', 'embeddings', '=', 'fixed_embeddings', '+', 'linked_embeddings', 'if', 'not', 'embeddings:', 'raise', "RuntimeError('There", 'needs', 'to', 'be', 'at', 'least', 'one', 'feature', 'set', "defined.')", 'return', 'tf.concat([e.tensor', 'for', 'e', 'in', ... | 111,251 |
Kvatsx/Artificial-Intelligence-Assignments | test_nbconvertapp.py | TestNbConvertApp.test_markdown_display_priority | test_markdown_display_priority | Check to see if markdown conversion embeds PNGs, even if an (unsupported) PDF is present. | [
"Check",
"to",
"see",
"if",
"markdown",
"conversion",
"embeds",
"PNGs,",
"even",
"if",
"an",
"(unsupported)",
"PDF",
"is",
"present."
] | def test_markdown_display_priority(self):
with self.create_temp_cwd(['markdown_display_priority.ipynb']):
self.nbconvert('--log-level 0 --to markdown "markdown_display_priority.ipynb"')
assert os.path.isfile('markdown_display_priority.md')
with io.open('markdown_display_priority.md') as f:
... | ['def', 'test_markdown_display_priority(self):', 'with', "self.create_temp_cwd(['markdown_display_priority.ipynb']):", "self.nbconvert('--log-level", '0', '--to', 'markdown', '"markdown_display_priority.ipynb"\')', 'assert', "os.path.isfile('markdown_display_priority.md')", 'with', "io.open('markdown_display_priority.m... | 1,900 |
BlueMirrors/cvu | yolov5_tensorrt.py | Yolov5.get_supported_dtypes | get_supported_dtypes | Method to check if fp16 and int8 are suuported on the platform. | [
"Method",
"to",
"check",
"if",
"fp16",
"and",
"int8",
"are",
"suuported",
"on",
"the",
"platform."
] | def get_supported_dtypes(builder) -> List[str]:
supported_dtypes = ['fp32']
if builder.platform_has_fast_fp16:
supported_dtypes.append('fp16')
if builder.platform_has_fast_int8:
supported_dtypes.append('int8')
return supported_dtypes | ['def', 'get_supported_dtypes(builder)', '->', 'List[str]:', 'supported_dtypes', '=', "['fp32']", 'if', 'builder.platform_has_fast_fp16:', "supported_dtypes.append('fp16')", 'if', 'builder.platform_has_fast_int8:', "supported_dtypes.append('int8')", 'return', 'supported_dtypes'] | 524,119 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | util.py | get_infogan_noise | get_infogan_noise | Get unstructured and structured noise for InfoGAN. | [
"Get",
"unstructured",
"and",
"structured",
"noise",
"for",
"InfoGAN."
] | def get_infogan_noise(batch_size, categorical_dim, structured_continuous_dim, total_continuous_noise_dims):
unstructured_noise = tf.random_normal([batch_size, total_continuous_noise_dims - structured_continuous_dim])
categorical_dist = ds.Categorical(logits=tf.zeros([categorical_dim]))
categorical_noise = c... | ['def', 'get_infogan_noise(batch_size,', 'categorical_dim,', 'structured_continuous_dim,', 'total_continuous_noise_dims):', 'unstructured_noise', '=', 'tf.random_normal([batch_size,', 'total_continuous_noise_dims', '-', 'structured_continuous_dim])', 'categorical_dist', '=', 'ds.Categorical(logits=tf.zeros([categorical... | 54,904 |
awslabs/predictive-maintenance-using-- | _decorators.py | Substitution.from_params | from_params | In the case where the params is a mutable sequence (list or dictionary) and it may change before this class is called, one may explicitly use a reference to the params rather than using *args or **kwargs which will copy the values and not reference them. | [
"In",
"the",
"case",
"where",
"the",
"params",
"is",
"a",
"mutable",
"sequence",
"(list",
"or",
"dictionary)",
"and",
"it",
"may",
"change",
"before",
"this",
"class",
"is",
"called,",
"one",
"may",
"explicitly",
"use",
"a",
"reference",
"to",
"the",
"para... | def from_params(cls, params):
result = cls()
result.params = params
return result | ['def', 'from_params(cls,', 'params):', 'result', '=', 'cls()', 'result.params', '=', 'params', 'return', 'result'] | 824,332 |
matsu0228/nlp-jp | texmanager.py | TexManager.get_text_width_height_descent | get_text_width_height_descent | return width, heigth and descent of the text. | [
"return",
"width,",
"heigth",
"and",
"descent",
"of",
"the",
"text."
] | def get_text_width_height_descent(self, tex, fontsize, renderer=None):
if tex.strip() == '':
return (0, 0, 0)
if renderer:
dpi_fraction = renderer.points_to_pixels(1.0)
else:
dpi_fraction = 1.0
if rcParams['text.latex.preview']:
basefile = self.get_basefile(tex, fontsize)... | ['def', 'get_text_width_height_descent(self,', 'tex,', 'fontsize,', 'renderer=None):', 'if', 'tex.strip()', '==', "'':", 'return', '(0,', '0,', '0)', 'if', 'renderer:', 'dpi_fraction', '=', 'renderer.points_to_pixels(1.0)', 'else:', 'dpi_fraction', '=', '1.0', 'if', "rcParams['text.latex.preview']:", 'basefile', '=', '... | 789,230 |
open-mmlab/mmselfsup | odc.py | ODC.predict | predict | The forward function in testing. | [
"The",
"forward",
"function",
"in",
"testing."
] | def predict(self, inputs: List[torch.Tensor], data_samples: List[SelfSupDataSample], **kwargs) -> List[SelfSupDataSample]:
feature = self.extract_feat(inputs)
if self.with_neck:
feature = self.neck(feature)
outs = self.head.logits(feature)
keys = [f'head{i}' for i in self.backbone.out_indices]
... | ['def', 'predict(self,', 'inputs:', 'List[torch.Tensor],', 'data_samples:', 'List[SelfSupDataSample],', '**kwargs)', '->', 'List[SelfSupDataSample]:', 'feature', '=', 'self.extract_feat(inputs)', 'if', 'self.with_neck:', 'feature', '=', 'self.neck(feature)', 'outs', '=', 'self.head.logits(feature)', 'keys', '=', "[f'he... | 240,383 |
neuroailab/VIE | resnet_model_slowfast.py | conv3d_fixed_padding | conv3d_fixed_padding | Strided 3-D convolution with explicit padding. | [
"Strided",
"3-D",
"convolution",
"with",
"explicit",
"padding."
] | def conv3d_fixed_padding(inputs, filters, kernel_size, time_kernel_size, strides, data_format, time_stride=1):
if strides > 1 or time_stride > 1:
inputs = fixed_padding_3d(inputs, kernel_size, time_kernel_size, data_format)
return tf.layers.conv3d(inputs=inputs, filters=filters, kernel_size=(time_kernel... | ['def', 'conv3d_fixed_padding(inputs,', 'filters,', 'kernel_size,', 'time_kernel_size,', 'strides,', 'data_format,', 'time_stride=1):', 'if', 'strides', '>', '1', 'or', 'time_stride', '>', '1:', 'inputs', '=', 'fixed_padding_3d(inputs,', 'kernel_size,', 'time_kernel_size,', 'data_format)', 'return', 'tf.layers.conv3d(i... | 380,061 |
Liusifei/UVC | test_utils.py | to_one_hot | to_one_hot | Take integer y (tensor or variable) with n dims & convert it to 1-hot representation with n+1 dims. | [
"Take",
"integer",
"y",
"(tensor",
"or",
"variable)",
"with",
"n",
"dims",
"&",
"convert",
"it",
"to",
"1-hot",
"representation",
"with",
"n+1",
"dims."
] | def to_one_hot(y_tensor, n_dims=None):
if n_dims is None:
n_dims = int(y_tensor.max() + 1)
(_, h, w) = y_tensor.size()
y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)
n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1
y_one_hot = torch.zeros(y_tensor.size()[0], n_... | ['def', 'to_one_hot(y_tensor,', 'n_dims=None):', 'if', 'n_dims', 'is', 'None:', 'n_dims', '=', 'int(y_tensor.max()', '+', '1)', '(_,', 'h,', 'w)', '=', 'y_tensor.size()', 'y_tensor', '=', 'y_tensor.type(torch.LongTensor).view(-1,', '1)', 'n_dims', '=', 'n_dims', 'if', 'n_dims', 'is', 'not', 'None', 'else', 'int(torch.m... | 439,168 |
flow-project/flow | wave_attenuation.py | v_eq_max_function | v_eq_max_function | Return the error between the desired and actual equivalent gap. | [
"Return",
"the",
"error",
"between",
"the",
"desired",
"and",
"actual",
"equivalent",
"gap."
] | def v_eq_max_function(v, *args):
(num_vehicles, length) = args
s_eq_max = (length - num_vehicles * 5) / (num_vehicles - 1)
v0 = 30
s0 = 2
tau = 1
gamma = 4
error = s_eq_max - (s0 + v * tau) * (1 - (v / v0) ** gamma) ** (-0.5)
return error | ['def', 'v_eq_max_function(v,', '*args):', '(num_vehicles,', 'length)', '=', 'args', 's_eq_max', '=', '(length', '-', 'num_vehicles', '*', '5)', '/', '(num_vehicles', '-', '1)', 'v0', '=', '30', 's0', '=', '2', 'tau', '=', '1', 'gamma', '=', '4', 'error', '=', 's_eq_max', '-', '(s0', '+', 'v', '*', 'tau)', '*', '(1', '... | 211,765 |
netket/netket | _grad.py | grad | grad | Creates a function which evaluates the gradient of ``fun``. | [
"Creates",
"a",
"function",
"which",
"evaluates",
"the",
"gradient",
"of",
"``fun``."
] | def grad(fun: Callable, argnums: Union[int, Sequence[int]]=0, has_aux: bool=False, allow_int: bool=False) -> Callable:
value_and_grad_f = value_and_grad(fun, argnums, has_aux=has_aux, allow_int=allow_int)
def grad_f(*args, **kwargs):
(_, g) = value_and_grad_f(*args, **kwargs)
return g
def ... | ['def', 'grad(fun:', 'Callable,', 'argnums:', 'Union[int,', 'Sequence[int]]=0,', 'has_aux:', 'bool=False,', 'allow_int:', 'bool=False)', '->', 'Callable:', 'value_and_grad_f', '=', 'value_and_grad(fun,', 'argnums,', 'has_aux=has_aux,', 'allow_int=allow_int)', 'def', 'grad_f(*args,', '**kwargs):', '(_,', 'g)', '=', 'val... | 736,086 |
navarmn/Elman_neural_network | func_inspect.py | format_call | format_call | Returns a nicely formatted statement displaying the function call with the given arguments. | [
"Returns",
"a",
"nicely",
"formatted",
"statement",
"displaying",
"the",
"function",
"call",
"with",
"the",
"given",
"arguments."
] | def format_call(func, args, kwargs, object_name='Memory'):
(path, signature) = format_signature(func, *args, **kwargs)
msg = '%s\n[%s] Calling %s...\n%s' % (80 * '_', object_name, path, signature)
return msg | ['def', 'format_call(func,', 'args,', 'kwargs,', "object_name='Memory'):", '(path,', 'signature)', '=', 'format_signature(func,', '*args,', '**kwargs)', 'msg', '=', "'%s\\n[%s]", 'Calling', "%s...\\n%s'", '%', '(80', '*', "'_',", 'object_name,', 'path,', 'signature)', 'return', 'msg'] | 175,788 |
tobegit3hub/deep_image_model | control_flow_ops.py | IsLoopExit | IsLoopExit | Return true if `op` is an Exit. | [
"Return",
"true",
"if",
"`op`",
"is",
"an",
"Exit."
] | def IsLoopExit(op):
return op.type == 'Exit' or op.type == 'RefExit' | ['def', 'IsLoopExit(op):', 'return', 'op.type', '==', "'Exit'", 'or', 'op.type', '==', "'RefExit'"] | 182,800 |
zhejz/carla-roach | join.py | Join.load_network | load_network | Load a network for a given model definition . | [
"Load",
"a",
"network",
"for",
"a",
"given",
"model",
"definition",
"."
] | def load_network(self, checkpoint):
coil_logger.add_message('Loading', {'Model': {'Loaded checkpoint: ' + str(checkpoint)}}) | ['def', 'load_network(self,', 'checkpoint):', "coil_logger.add_message('Loading',", "{'Model':", "{'Loaded", 'checkpoint:', "'", '+', 'str(checkpoint)}})'] | 455,956 |
google-research/bleurt | evaluator.py | grouped_wmt_kendall | grouped_wmt_kendall | Groups translations by source and computes WMT's Kendall variant. | [
"Groups",
"translations",
"by",
"source",
"and",
"computes",
"WMT's",
"Kendall",
"variant."
] | def grouped_wmt_kendall(df, year=2019, threshold=25):
tf.logging.debug('Subset size: {}'.format(len(df.index)))
n_sentences = df['reference'].nunique()
tf.logging.debug('Number of reference sentences: {}'.format(n_sentences))
df = df.dropna(subset=['bleurt'])
groups = df.groupby(['reference'])
(... | ['def', 'grouped_wmt_kendall(df,', 'year=2019,', 'threshold=25):', "tf.logging.debug('Subset", 'size:', "{}'.format(len(df.index)))", 'n_sentences', '=', "df['reference'].nunique()", "tf.logging.debug('Number", 'of', 'reference', 'sentences:', "{}'.format(n_sentences))", 'df', '=', "df.dropna(subset=['bleurt'])", 'grou... | 461,771 |
triaquae/triaquae | options.py | BaseModelAdmin.formfield_for_manytomany | formfield_for_manytomany | Get a form Field for a ManyToManyField. | [
"Get",
"a",
"form",
"Field",
"for",
"a",
"ManyToManyField."
] | def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if not db_field.rel.through._meta.auto_created:
return None
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, self.admin_site, using=db)
... | ['def', 'formfield_for_manytomany(self,', 'db_field,', 'request=None,', '**kwargs):', 'if', 'not', 'db_field.rel.through._meta.auto_created:', 'return', 'None', 'db', '=', "kwargs.get('using')", 'if', 'db_field.name', 'in', 'self.raw_id_fields:', "kwargs['widget']", '=', 'widgets.ManyToManyRawIdWidget(db_field.rel,', '... | 356,946 |
mariacer/cl_in_rnns | dataset.py | Dataset.num_test_samples | num_test_samples | Getter for read-only attribute :attr:`num_test_samples`. | [
"Getter",
"for",
"read-only",
"attribute",
":attr:`num_test_samples`."
] | def num_test_samples(self):
return np.size(self._data['test_inds']) | ['def', 'num_test_samples(self):', 'return', "np.size(self._data['test_inds'])"] | 122,718 |
nicknochnack/RealTimeSignLanguageTFJS | mask_ops.py | paste_instance_masks | paste_instance_masks | Paste instance masks to generate the image segmentation results. | [
"Paste",
"instance",
"masks",
"to",
"generate",
"the",
"image",
"segmentation",
"results."
] | def paste_instance_masks(masks, detected_boxes, image_height, image_width):
def expand_boxes(boxes, scale):
w_half = boxes[:, 2] * 0.5
h_half = boxes[:, 3] * 0.5
x_c = boxes[:, 0] + w_half
y_c = boxes[:, 1] + h_half
w_half *= scale
h_half *= scale
boxes_exp =... | ['def', 'paste_instance_masks(masks,', 'detected_boxes,', 'image_height,', 'image_width):', 'def', 'expand_boxes(boxes,', 'scale):', 'w_half', '=', 'boxes[:,', '2]', '*', '0.5', 'h_half', '=', 'boxes[:,', '3]', '*', '0.5', 'x_c', '=', 'boxes[:,', '0]', '+', 'w_half', 'y_c', '=', 'boxes[:,', '1]', '+', 'h_half', 'w_half... | 850,877 |
ryu-ed/SpaceInvaders_Ros | socketserver.py | ThreadingMixIn.process_request | process_request | Start a new thread to process the request. | [
"Start",
"a",
"new",
"thread",
"to",
"process",
"the",
"request."
] | def process_request(self, request, client_address):
t = threading.Thread(target=self.process_request_thread, args=(request, client_address))
t.daemon = self.daemon_threads
t.start() | ['def', 'process_request(self,', 'request,', 'client_address):', 't', '=', 'threading.Thread(target=self.process_request_thread,', 'args=(request,', 'client_address))', 't.daemon', '=', 'self.daemon_threads', 't.start()'] | 395,568 |
matsu0228/nlp-jp | connection.py | MWSConnection.update_report_acknowledgements | update_report_acknowledgements | Updates the acknowledged status of one or more reports. | [
"Updates",
"the",
"acknowledged",
"status",
"of",
"one",
"or",
"more",
"reports."
] | def update_report_acknowledgements(self, request, response, **kw):
return self._post_request(request, kw, response) | ['def', 'update_report_acknowledgements(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)'] | 784,944 |
Crepdo/CS188_Artificial-Intelligence | logic.py | is_var_symbol | is_var_symbol | A logic variable symbol is an initial-lowercase string. | [
"A",
"logic",
"variable",
"symbol",
"is",
"an",
"initial-lowercase",
"string."
] | def is_var_symbol(s):
return is_symbol(s) and s[0].islower() | ['def', 'is_var_symbol(s):', 'return', 'is_symbol(s)', 'and', 's[0].islower()'] | 226,938 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_utils.py | gunzip_file | gunzip_file | Unzips from gz_path into new_path. | [
"Unzips",
"from",
"gz_path",
"into",
"new_path."
] | def gunzip_file(gz_path, new_path):
print('Unpacking %s to %s' % (gz_path, new_path))
with gzip.open(gz_path, 'rb') as gz_file:
with open(new_path, 'wb') as new_file:
for line in gz_file:
new_file.write(line) | ['def', 'gunzip_file(gz_path,', 'new_path):', "print('Unpacking", '%s', 'to', "%s'", '%', '(gz_path,', 'new_path))', 'with', 'gzip.open(gz_path,', "'rb')", 'as', 'gz_file:', 'with', 'open(new_path,', "'wb')", 'as', 'new_file:', 'for', 'line', 'in', 'gz_file:', 'new_file.write(line)'] | 113,342 |
Farama-Foundation/Gymnasium | common.py | PassiveEnvCheckerV0.render | render | Renders the environment that on the first call will run the `passive_env_render_check`. | [
"Renders",
"the",
"environment",
"that",
"on",
"the",
"first",
"call",
"will",
"run",
"the",
"`passive_env_render_check`."
] | def render(self) -> RenderFrame | list[RenderFrame] | None:
if self._checked_render is False:
self._checked_render = True
return env_render_passive_checker(self.env)
else:
return self.env.render() | ['def', 'render(self)', '->', 'RenderFrame', '|', 'list[RenderFrame]', '|', 'None:', 'if', 'self._checked_render', 'is', 'False:', 'self._checked_render', '=', 'True', 'return', 'env_render_passive_checker(self.env)', 'else:', 'return', 'self.env.render()'] | 573,154 |
43Carrig/recurrent_neural_networks_practice | special_math.py | erfinv | erfinv | The inverse function for erf, the error function. | [
"The",
"inverse",
"function",
"for",
"erf,",
"the",
"error",
"function."
] | def erfinv(x, name='erfinv'):
with ops.name_scope(name, values=[x]):
x = ops.convert_to_tensor(x, name='x')
if x.dtype.as_numpy_dtype not in [np.float32, np.float64]:
raise TypeError('x.dtype=%s is not handled, see docstring for supported types.' % x.dtype)
return ndtri((x + 1.0)... | ['def', 'erfinv(x,', "name='erfinv'):", 'with', 'ops.name_scope(name,', 'values=[x]):', 'x', '=', 'ops.convert_to_tensor(x,', "name='x')", 'if', 'x.dtype.as_numpy_dtype', 'not', 'in', '[np.float32,', 'np.float64]:', 'raise', "TypeError('x.dtype=%s", 'is', 'not', 'handled,', 'see', 'docstring', 'for', 'supported', "type... | 339,220 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjrContextWrapper.windowStereo | windowStereo | is stereo available for default/window framebuffer. | [
"is",
"stereo",
"available",
"for",
"default/window",
"framebuffer."
] | def windowStereo(self):
return self._ptr.contents.windowStereo | ['def', 'windowStereo(self):', 'return', 'self._ptr.contents.windowStereo'] | 440,661 |
43Carrig/recurrent_neural_networks_practice | control_flow_util.py | GetOutputContext | GetOutputContext | Return the control flow context for the output of an op. | [
"Return",
"the",
"control",
"flow",
"context",
"for",
"the",
"output",
"of",
"an",
"op."
] | def GetOutputContext(op):
ctxt = op._get_control_flow_context()
if ctxt is not None and IsLoopExit(op):
ctxt = ctxt.outer_context
return ctxt | ['def', 'GetOutputContext(op):', 'ctxt', '=', 'op._get_control_flow_context()', 'if', 'ctxt', 'is', 'not', 'None', 'and', 'IsLoopExit(op):', 'ctxt', '=', 'ctxt.outer_context', 'return', 'ctxt'] | 337,199 |
EducationalTestingService/skll | test_ablation.py | TestAblation.tearDownClass | tearDownClass | Clean up after tests. | [
"Clean",
"up",
"after",
"tests."
] | def tearDownClass(cls):
for output_file in output_dir.glob('ablation_cv_*'):
unlink(output_file)
config_files = ['test_ablation.cfg', 'test_ablation_all_combos.cfg', 'test_ablation_feature_hasher.cfg', 'test_ablation_feature_hasher_all_combos.cfg', 'test_ablation_sampler.cfg', 'test_ablation_sampler_all... | ['def', 'tearDownClass(cls):', 'for', 'output_file', 'in', "output_dir.glob('ablation_cv_*'):", 'unlink(output_file)', 'config_files', '=', "['test_ablation.cfg',", "'test_ablation_all_combos.cfg',", "'test_ablation_feature_hasher.cfg',", "'test_ablation_feature_hasher_all_combos.cfg',", "'test_ablation_sampler.cfg',",... | 885,005 |
shery322/Lunar-Lander-ANN | mask_test.py | MaskTypeTest.todo_test_centroid | todo_test_centroid | Ensure a mask's centroid is correctly calculated. | [
"Ensure",
"a",
"mask's",
"centroid",
"is",
"correctly",
"calculated."
] | def todo_test_centroid(self):
self.fail() | ['def', 'todo_test_centroid(self):', 'self.fail()'] | 619,046 |
zhang614/MicroGrid | hb.py | HBInfo.dump | dump | Gives the header corresponding to this instance as a string. | [
"Gives",
"the",
"header",
"corresponding",
"to",
"this",
"instance",
"as",
"a",
"string."
] | def dump(self):
header = [self.title.ljust(72) + self.key.ljust(8)]
header.append('%14d%14d%14d%14d' % (self.total_nlines, self.pointer_nlines, self.indices_nlines, self.values_nlines))
header.append('%14s%14d%14d%14d%14d' % (self.mxtype.fortran_format.ljust(14), self.nrows, self.ncols, self.nnon_zeros, 0))... | ['def', 'dump(self):', 'header', '=', '[self.title.ljust(72)', '+', 'self.key.ljust(8)]', "header.append('%14d%14d%14d%14d'", '%', '(self.total_nlines,', 'self.pointer_nlines,', 'self.indices_nlines,', 'self.values_nlines))', "header.append('%14s%14d%14d%14d%14d'", '%', '(self.mxtype.fortran_format.ljust(14),', 'self.n... | 669,168 |
calico/basenji | basenji_test_genes.py | normalize_targets | normalize_targets | Normalize gene-target values across targets. | [
"Normalize",
"gene-target",
"values",
"across",
"targets."
] | def normalize_targets(gene_values, log_pseudo=1, outlier_mult=10):
if log_pseudo is not None:
gene_values = np.log2(gene_values + log_pseudo)
gene_values_tmean = gene_values.mean(axis=0, dtype='float32')
gene_values_tmmean = gene_values_tmean.mean()
inlier_indexes = []
for ti in range(len(ge... | ['def', 'normalize_targets(gene_values,', 'log_pseudo=1,', 'outlier_mult=10):', 'if', 'log_pseudo', 'is', 'not', 'None:', 'gene_values', '=', 'np.log2(gene_values', '+', 'log_pseudo)', 'gene_values_tmean', '=', 'gene_values.mean(axis=0,', "dtype='float32')", 'gene_values_tmmean', '=', 'gene_values_tmean.mean()', 'inlie... | 94,889 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | cifar10.py | get_split | get_split | Gets a dataset tuple with instructions for reading cifar10. | [
"Gets",
"a",
"dataset",
"tuple",
"with",
"instructions",
"for",
"reading",
"cifar10."
] | def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
if split_name not in SPLITS_TO_SIZES:
raise ValueError('split name %s was not recognized.' % split_name)
if not file_pattern:
file_pattern = _FILE_PATTERN
file_pattern = os.path.join(dataset_dir, file_pattern % split_nam... | ['def', 'get_split(split_name,', 'dataset_dir,', 'file_pattern=None,', 'reader=None):', 'if', 'split_name', 'not', 'in', 'SPLITS_TO_SIZES:', 'raise', "ValueError('split", 'name', '%s', 'was', 'not', "recognized.'", '%', 'split_name)', 'if', 'not', 'file_pattern:', 'file_pattern', '=', '_FILE_PATTERN', 'file_pattern', '... | 26,861 |
deepmind/dm_alchemy | stones_and_potions.py | latent_dirs_on_stone | latent_dirs_on_stone | Filters possible latent and stone directions given a stone and partial map. | [
"Filters",
"possible",
"latent",
"and",
"stone",
"directions",
"given",
"a",
"stone",
"and",
"partial",
"map."
] | def latent_dirs_on_stone(perceived_stone: AlignedStone, latent_dim: int, partial_stone_map: PartialStoneMap, latent_dirs_stone_dirs: Sequence[Tuple[int, int]]) -> Tuple[bool, List[int]]:
expected_stone_dir = -perceived_stone.aligned_coords[latent_dim]
new_coords = np.copy(perceived_stone.aligned_coords)
new... | ['def', 'latent_dirs_on_stone(perceived_stone:', 'AlignedStone,', 'latent_dim:', 'int,', 'partial_stone_map:', 'PartialStoneMap,', 'latent_dirs_stone_dirs:', 'Sequence[Tuple[int,', 'int]])', '->', 'Tuple[bool,', 'List[int]]:', 'expected_stone_dir', '=', '-perceived_stone.aligned_coords[latent_dim]', 'new_coords', '=', ... | 522,277 |
enuguru/artificial_intelligence_and_machine_ | schema.py | ControlledSchema.upgrade | upgrade | Upgrade (or downgrade) to a specified version, or latest version. | [
"Upgrade",
"(or",
"downgrade)",
"to",
"a",
"specified",
"version,",
"or",
"latest",
"version."
] | def upgrade(self, version=None):
changeset = self.changeset(version)
for (ver, change) in changeset:
self.runchange(ver, change, changeset.step) | ['def', 'upgrade(self,', 'version=None):', 'changeset', '=', 'self.changeset(version)', 'for', '(ver,', 'change)', 'in', 'changeset:', 'self.runchange(ver,', 'change,', 'changeset.step)'] | 129,903 |
eddylau328/fyp-artificial-intelligence-ac-control-device | proto_builder_test.py | ProtoBuilderTest.testMakeSimpleProtoClass | testMakeSimpleProtoClass | Test that we can create a proto class. | [
"Test",
"that",
"we",
"can",
"create",
"a",
"proto",
"class."
] | def testMakeSimpleProtoClass(self):
proto_cls = proto_builder.MakeSimpleProtoClass(self._fields, full_name='net.proto2.python.public.proto_builder_test.Test')
proto = proto_cls()
proto.foo = 12345
proto.bar = 'asdf'
self.assertMultiLineEqual('bar: "asdf"\nfoo: 12345\n', text_format.MessageToString(p... | ['def', 'testMakeSimpleProtoClass(self):', 'proto_cls', '=', 'proto_builder.MakeSimpleProtoClass(self._fields,', "full_name='net.proto2.python.public.proto_builder_test.Test')", 'proto', '=', 'proto_cls()', 'proto.foo', '=', '12345', 'proto.bar', '=', "'asdf'", "self.assertMultiLineEqual('bar:", '"asdf"\\nfoo:', "12345... | 215,352 |
yinyunie/ScenePriors | vis_utils.py | make_depth_image | make_depth_image | Convert a batch of depth maps to a grayscale image. | [
"Convert",
"a",
"batch",
"of",
"depth",
"maps",
"to",
"a",
"grayscale",
"image."
] | def make_depth_image(depths: torch.Tensor, masks: torch.Tensor, max_quantile: float=0.98, min_quantile: float=0.02, min_out_depth: float=0.1, max_out_depth: float=0.9) -> torch.Tensor:
normfacs = []
for (d, m) in zip(depths, masks):
ok = (d.view(-1) > 1e-06) * (m.view(-1) > 0.5)
if ok.sum() <= 1... | ['def', 'make_depth_image(depths:', 'torch.Tensor,', 'masks:', 'torch.Tensor,', 'max_quantile:', 'float=0.98,', 'min_quantile:', 'float=0.02,', 'min_out_depth:', 'float=0.1,', 'max_out_depth:', 'float=0.9)', '->', 'torch.Tensor:', 'normfacs', '=', '[]', 'for', '(d,', 'm)', 'in', 'zip(depths,', 'masks):', 'ok', '=', '(d... | 329,733 |
matsu0228/nlp-jp | table.py | Table.update_from_response | update_from_response | Update the state of the Table object based on the response data received from Amazon DynamoDB. | [
"Update",
"the",
"state",
"of",
"the",
"Table",
"object",
"based",
"on",
"the",
"response",
"data",
"received",
"from",
"Amazon",
"DynamoDB."
] | def update_from_response(self, response):
if 'Table' in response:
self._dict.update(response['Table'])
elif 'TableDescription' in response:
self._dict.update(response['TableDescription'])
if 'KeySchema' in self._dict:
self._schema = Schema(self._dict['KeySchema']) | ['def', 'update_from_response(self,', 'response):', 'if', "'Table'", 'in', 'response:', "self._dict.update(response['Table'])", 'elif', "'TableDescription'", 'in', 'response:', "self._dict.update(response['TableDescription'])", 'if', "'KeySchema'", 'in', 'self._dict:', 'self._schema', '=', "Schema(self._dict['KeySchema... | 784,285 |
google-research/scenic | test_axial_resnet.py | AxialResNetTest.test_axial_residual_stage_output_shape | test_axial_residual_stage_output_shape | Tests AxialResNetStage module given different strides. | [
"Tests",
"AxialResNetStage",
"module",
"given",
"different",
"strides."
] | def test_axial_residual_stage_output_shape(self, strides, bottleneck, block_size, expected_output_shape):
rng = random.PRNGKey(0)
x = jnp.ones((10, 32, 32, 64))
axial_attention_configs = ml_collections.ConfigDict({'num_heads': 4})
aru_module = axial_resnet.AxialResNetStage(block_size=block_size, nout=12... | ['def', 'test_axial_residual_stage_output_shape(self,', 'strides,', 'bottleneck,', 'block_size,', 'expected_output_shape):', 'rng', '=', 'random.PRNGKey(0)', 'x', '=', 'jnp.ones((10,', '32,', '32,', '64))', 'axial_attention_configs', '=', "ml_collections.ConfigDict({'num_heads':", '4})', 'aru_module', '=', 'axial_resne... | 846,729 |
Bismarrck/kcon | kcnn.py | get_f_loss | get_f_loss | Return the total loss tensor of forces only. | [
"Return",
"the",
"total",
"loss",
"tensor",
"of",
"forces",
"only."
] | def get_f_loss(f_true, f_calc):
return _get_rmse_loss(f_true, f_calc, scope='fRMSE', summary_norms=True) | ['def', 'get_f_loss(f_true,', 'f_calc):', 'return', '_get_rmse_loss(f_true,', 'f_calc,', "scope='fRMSE',", 'summary_norms=True)'] | 247,507 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | _pydecimal.py | Decimal.is_infinite | is_infinite | Return True if self is infinite; otherwise return False. | [
"Return",
"True",
"if",
"self",
"is",
"infinite;",
"otherwise",
"return",
"False."
] | def is_infinite(self):
return self._exp == 'F' | ['def', 'is_infinite(self):', 'return', 'self._exp', '==', "'F'"] | 429,983 |
DeepGraphLearning/torchdrug | property_prediction.py | InteractionPrediction.preprocess | preprocess | Compute the mean and derivation for each task on the training set. | [
"Compute",
"the",
"mean",
"and",
"derivation",
"for",
"each",
"task",
"on",
"the",
"training",
"set."
] | def preprocess(self, train_set, valid_set, test_set):
values = defaultdict(list)
for sample in train_set:
if not sample.get('labeled', True):
continue
for task in self.task:
if not math.isnan(sample[task]):
values[task].append(sample[task])
mean = []
... | ['def', 'preprocess(self,', 'train_set,', 'valid_set,', 'test_set):', 'values', '=', 'defaultdict(list)', 'for', 'sample', 'in', 'train_set:', 'if', 'not', "sample.get('labeled',", 'True):', 'continue', 'for', 'task', 'in', 'self.task:', 'if', 'not', 'math.isnan(sample[task]):', 'values[task].append(sample[task])', 'me... | 902,894 |
Kvatsx/Artificial-Intelligence-Assignments | datetime.py | datetime.timetz | timetz | Return the time part, with same tzinfo. | [
"Return",
"the",
"time",
"part,",
"with",
"same",
"tzinfo."
] | def timetz(self):
return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo) | ['def', 'timetz(self):', 'return', 'time(self.hour,', 'self.minute,', 'self.second,', 'self.microsecond,', 'self._tzinfo)'] | 36,652 |
thaines/helit | solve_weave.py | gibbs | gibbs | Does iters number of Gibbs iterations. | [
"Does",
"iters",
"number",
"of",
"Gibbs",
"iterations."
] | def gibbs(s, iters, next):
dist = numpy.empty(s.topicCount.shape[0], dtype=numpy.float_)
topicWordCount = s.topicWordCount
topicCount = s.topicCount
docTopicCount = s.docTopicCount
docCount = s.docCount
state = s.state
alpha = s.alpha
beta = s.beta
boostAmount = s.alpha * (s.alphaMul... | ['def', 'gibbs(s,', 'iters,', 'next):', 'dist', '=', 'numpy.empty(s.topicCount.shape[0],', 'dtype=numpy.float_)', 'topicWordCount', '=', 's.topicWordCount', 'topicCount', '=', 's.topicCount', 'docTopicCount', '=', 's.docTopicCount', 'docCount', '=', 's.docCount', 'state', '=', 's.state', 'alpha', '=', 's.alpha', 'beta'... | 592,153 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | component.py | ComponentBuilderBase.attr | attr | Returns the value of the component attribute with the |name|. | [
"Returns",
"the",
"value",
"of",
"the",
"component",
"attribute",
"with",
"the",
"|name|."
] | def attr(self, name):
return self._attrs[name] | ['def', 'attr(self,', 'name):', 'return', 'self._attrs[name]'] | 28,134 |
matsu0228/nlp-jp | widgets.py | RectangleSelector.extents | extents | Return (xmin, xmax, ymin, ymax). | [
"Return",
"(xmin,",
"xmax,",
"ymin,",
"ymax)."
] | def extents(self):
(x0, y0, width, height) = self._rect_bbox
(xmin, xmax) = sorted([x0, x0 + width])
(ymin, ymax) = sorted([y0, y0 + height])
return (xmin, xmax, ymin, ymax) | ['def', 'extents(self):', '(x0,', 'y0,', 'width,', 'height)', '=', 'self._rect_bbox', '(xmin,', 'xmax)', '=', 'sorted([x0,', 'x0', '+', 'width])', '(ymin,', 'ymax)', '=', 'sorted([y0,', 'y0', '+', 'height])', 'return', '(xmin,', 'xmax,', 'ymin,', 'ymax)'] | 789,427 |
EducationalTestingService/skll | test_input.py | TestInput.test_learning_curve_objectives_unsupported_error | test_learning_curve_objectives_unsupported_error | Test that config parsing raises error for `objectives` with learning curves. | [
"Test",
"that",
"config",
"parsing",
"raises",
"error",
"for",
"`objectives`",
"with",
"learning",
"curves."
] | def test_learning_curve_objectives_unsupported_error(self):
values_to_fill_dict = {'experiment_name': 'config_parsing', 'task': 'learning_curve', 'train_directory': train_dir, 'featuresets': "[['f1', 'f2', 'f3']]", 'learners': "['LogisticRegression', 'MultinomialNB']", 'logs': output_dir, 'results': output_dir, 'gr... | ['def', 'test_learning_curve_objectives_unsupported_error(self):', 'values_to_fill_dict', '=', "{'experiment_name':", "'config_parsing',", "'task':", "'learning_curve',", "'train_directory':", 'train_dir,', "'featuresets':", '"[[\'f1\',', "'f2',", '\'f3\']]",', "'learners':", '"[\'LogisticRegression\',', '\'Multinomial... | 885,195 |
matsu0228/nlp-jp | cmdshell.py | SSHClient.shell | shell | Start an interactive shell session with the remote host. | [
"Start",
"an",
"interactive",
"shell",
"session",
"with",
"the",
"remote",
"host."
] | def shell(self):
channel = self._ssh_client.invoke_shell()
interactive_shell(channel) | ['def', 'shell(self):', 'channel', '=', 'self._ssh_client.invoke_shell()', 'interactive_shell(channel)'] | 784,879 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | core.py | Command.get_short_help_str | get_short_help_str | Gets short help for the command or makes it by shortening the long help string. | [
"Gets",
"short",
"help",
"for",
"the",
"command",
"or",
"makes",
"it",
"by",
"shortening",
"the",
"long",
"help",
"string."
] | def get_short_help_str(self, limit=45):
return self.short_help or (self.help and make_default_short_help(self.help, limit)) or '' | ['def', 'get_short_help_str(self,', 'limit=45):', 'return', 'self.short_help', 'or', '(self.help', 'and', 'make_default_short_help(self.help,', 'limit))', 'or', "''"] | 101,833 |
facebookresearch/minihack | base.py | MiniHack.get_screen_description | get_screen_description | Returns the description of the screen on (x,y) coordinates. | [
"Returns",
"the",
"description",
"of",
"the",
"screen",
"on",
"(x,y)",
"coordinates."
] | def get_screen_description(self, x, y, observation=None):
if observation is None:
observation = self.last_observation
des_arr = observation[self._scr_descr_index][y, x]
symb_len = np.where(des_arr == 0)[0][0]
return des_arr[:symb_len].tobytes().decode('utf-8') | ['def', 'get_screen_description(self,', 'x,', 'y,', 'observation=None):', 'if', 'observation', 'is', 'None:', 'observation', '=', 'self.last_observation', 'des_arr', '=', 'observation[self._scr_descr_index][y,', 'x]', 'symb_len', '=', 'np.where(des_arr', '==', '0)[0][0]', 'return', "des_arr[:symb_len].tobytes().decode(... | 670,697 |
ludwig-ai/ludwig | test_cli.py | test_reproducible_cli_runs | test_reproducible_cli_runs | Test for reproducible training using `ludwig experiment|train --dataset`. | [
"Test",
"for",
"reproducible",
"training",
"using",
"`ludwig",
"experiment|train",
"--dataset`."
] | def test_reproducible_cli_runs(backend: str, type_of_run: str, random_seed: int, second_seed_offset: int, csv_filename: str, tmpdir: pathlib.Path) -> None:
config_filename = os.path.join(tmpdir, 'config.yaml')
dataset_filename = _prepare_data(csv_filename, config_filename)
if backend == 'local':
com... | ['def', 'test_reproducible_cli_runs(backend:', 'str,', 'type_of_run:', 'str,', 'random_seed:', 'int,', 'second_seed_offset:', 'int,', 'csv_filename:', 'str,', 'tmpdir:', 'pathlib.Path)', '->', 'None:', 'config_filename', '=', 'os.path.join(tmpdir,', "'config.yaml')", 'dataset_filename', '=', '_prepare_data(csv_filename... | 617,238 |
rlgraph/rlgraph | test_ray_value_worker.py | TestRayWorker.test_metrics | test_metrics | Tests metric collection for 1 and multiple environments. | [
"Tests",
"metric",
"collection",
"for",
"1",
"and",
"multiple",
"environments."
] | def test_metrics(self):
agent_config = config_from_path('configs/apex_agent_cartpole.json')
ray_spec = agent_config['execution_spec'].pop('ray_spec')
ray_spec['worker_spec']['worker_sample_size'] = 50
worker_spec = ray_spec['worker_spec']
worker = RayValueWorker.as_remote().remote(agent_config, ray_... | ['def', 'test_metrics(self):', 'agent_config', '=', "config_from_path('configs/apex_agent_cartpole.json')", 'ray_spec', '=', "agent_config['execution_spec'].pop('ray_spec')", "ray_spec['worker_spec']['worker_sample_size']", '=', '50', 'worker_spec', '=', "ray_spec['worker_spec']", 'worker', '=', 'RayValueWorker.as_remo... | 862,802 |
shanglianlm0525/CvPytorch | yolox_pai_efficient_rep.py | YOLOXPAIEfficientRep.build_stem_layer | build_stem_layer | Build a stem layer. | [
"Build",
"a",
"stem",
"layer."
] | def build_stem_layer(self):
return RepVGGBlock(in_channels=self.in_channels, out_channels=self.out_channels[0], kernel_size=3, stride=2) | ['def', 'build_stem_layer(self):', 'return', 'RepVGGBlock(in_channels=self.in_channels,', 'out_channels=self.out_channels[0],', 'kernel_size=3,', 'stride=2)'] | 523,544 |
enuguru/artificial_intelligence_and_machine_learning | filters.py | CompoundFilter.getServiceEndpoints | getServiceEndpoints | Generate all endpoint objects for all of the subfilters of this filter and return their concatenation. | [
"Generate",
"all",
"endpoint",
"objects",
"for",
"all",
"of",
"the",
"subfilters",
"of",
"this",
"filter",
"and",
"return",
"their",
"concatenation."
] | def getServiceEndpoints(self, yadis_url, service_element):
endpoints = []
for subfilter in self.subfilters:
endpoints.extend(subfilter.getServiceEndpoints(yadis_url, service_element))
return endpoints | ['def', 'getServiceEndpoints(self,', 'yadis_url,', 'service_element):', 'endpoints', '=', '[]', 'for', 'subfilter', 'in', 'self.subfilters:', 'endpoints.extend(subfilter.getServiceEndpoints(yadis_url,', 'service_element))', 'return', 'endpoints'] | 130,455 |
replit-archive/empythoned | ttk.py | OptionMenu.set_menu | set_menu | Build a new menu of radiobuttons with *values and optionally a default value. | [
"Build",
"a",
"new",
"menu",
"of",
"radiobuttons",
"with",
"*values",
"and",
"optionally",
"a",
"default",
"value."
] | def set_menu(self, default=None, *values):
menu = self['menu']
menu.delete(0, 'end')
for val in values:
menu.add_radiobutton(label=val, command=Tkinter._setit(self._variable, val, self._callback))
if default:
self._variable.set(default) | ['def', 'set_menu(self,', 'default=None,', '*values):', 'menu', '=', "self['menu']", 'menu.delete(0,', "'end')", 'for', 'val', 'in', 'values:', 'menu.add_radiobutton(label=val,', 'command=Tkinter._setit(self._variable,', 'val,', 'self._callback))', 'if', 'default:', 'self._variable.set(default)'] | 176,802 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pixelda_task_towers.py | pose_mini_tower | pose_mini_tower | Task tower for the pose_mini dataset. | [
"Task",
"tower",
"for",
"the",
"pose_mini",
"dataset."
] | def pose_mini_tower(images, num_classes=11, is_training=False, reuse_private=False, private_scope='pose_mini', reuse_shared=False, shared_scope='task_model'):
with tf.variable_scope(private_scope, reuse=reuse_private):
net = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = slim.max_pool2d(net, [... | ['def', 'pose_mini_tower(images,', 'num_classes=11,', 'is_training=False,', 'reuse_private=False,', "private_scope='pose_mini',", 'reuse_shared=False,', "shared_scope='task_model'):", 'with', 'tf.variable_scope(private_scope,', 'reuse=reuse_private):', 'net', '=', 'slim.conv2d(images,', '32,', '[5,', '5],', "scope='con... | 54,489 |
sunishsheth2009/ChatterBot | orderinglist.py | count_from_n_factory | count_from_n_factory | Numbering function: consecutive integers starting at arbitrary start. | [
"Numbering",
"function:",
"consecutive",
"integers",
"starting",
"at",
"arbitrary",
"start."
] | def count_from_n_factory(start):
def f(index, collection):
return index + start
try:
f.__name__ = 'count_from_%i' % start
except TypeError:
pass
return f | ['def', 'count_from_n_factory(start):', 'def', 'f(index,', 'collection):', 'return', 'index', '+', 'start', 'try:', 'f.__name__', '=', "'count_from_%i'", '%', 'start', 'except', 'TypeError:', 'pass', 'return', 'f'] | 481,108 |
QData/deepWordBug | test_gitwildmatch.py | GitWildMatchTest.test_03_only_double_asterisk | test_03_only_double_asterisk | Tests a double-asterisk pattern which matches everything. | [
"Tests",
"a",
"double-asterisk",
"pattern",
"which",
"matches",
"everything."
] | def test_03_only_double_asterisk(self):
(regex, include) = GitWildMatchPattern.pattern_to_regex('**')
self.assertTrue(include)
self.assertEqual(regex, '^.+$') | ['def', 'test_03_only_double_asterisk(self):', '(regex,', 'include)', '=', "GitWildMatchPattern.pattern_to_regex('**')", 'self.assertTrue(include)', 'self.assertEqual(regex,', "'^.+$')"] | 543,725 |
alexmojaki/funcfinder | math.py | is_even | is_even | Returns True if the number is even, otherwise False. | [
"Returns",
"True",
"if",
"the",
"number",
"is",
"even,",
"otherwise",
"False."
] | def is_even(func):
assertTrue(func(2))
assertFalse(func(3))
assertTrue(func(4))
assertTrue(func(2.0))
assertFalse(func(3.0))
assertTrue(func(4.0))
even = True
for i in xrange(-100, 100):
assertEqual(func(i), even)
even = not even | ['def', 'is_even(func):', 'assertTrue(func(2))', 'assertFalse(func(3))', 'assertTrue(func(4))', 'assertTrue(func(2.0))', 'assertFalse(func(3.0))', 'assertTrue(func(4.0))', 'even', '=', 'True', 'for', 'i', 'in', 'xrange(-100,', '100):', 'assertEqual(func(i),', 'even)', 'even', '=', 'not', 'even'] | 214,023 |
zhaocq-nlp/NJUNMT-tf | common_attention.py | BahdanauAttention.default_params | default_params | Returns a dictionary of default parameters of this attention. | [
"Returns",
"a",
"dictionary",
"of",
"default",
"parameters",
"of",
"this",
"attention."
] | def default_params():
return {'num_units': 512, 'dropout_attention_keep_prob': 1.0} | ['def', 'default_params():', 'return', "{'num_units':", '512,', "'dropout_attention_keep_prob':", '1.0}'] | 782,861 |
ajMIT95/MIT_Artificial_Intelligence_Labs | lab7.py | positiveness | positiveness | Computes the expression (w dot x + b) for the given Point x. | [
"Computes",
"the",
"expression",
"(w",
"dot",
"x",
"+",
"b)",
"for",
"the",
"given",
"Point",
"x."
] | def positiveness(svm, point):
return dot_product(svm.w, point.coords) + svm.b | ['def', 'positiveness(svm,', 'point):', 'return', 'dot_product(svm.w,', 'point.coords)', '+', 'svm.b'] | 239,379 |
jeromewang-github/computer_vision | cpp_lint.py | FileInfo.FullName | FullName | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix."
] | def FullName(self):
return os.path.abspath(self._filename).replace('\\', '/') | ['def', 'FullName(self):', 'return', "os.path.abspath(self._filename).replace('\\\\',", "'/')"] | 473,006 |
nilearn/nilearn | test_html_stat_map.py | test_save_sprite | test_save_sprite | Test covers _save_sprite as well as _bytesIO_to_base64. | [
"Test",
"covers",
"_save_sprite",
"as",
"well",
"as",
"_bytesIO_to_base64."
] | def test_save_sprite():
data = np.random.RandomState(42).uniform(size=140).reshape(7, 5, 4)
mask = np.zeros((7, 5, 4), dtype=int)
mask[1:-1, 1:-1, 1:-1] = 1
sprite_io = BytesIO()
html_stat_map._save_sprite(data, sprite_io, vmin=0, vmax=1, mask=mask, format='png')
sprite_base64 = html_stat_map._b... | ['def', 'test_save_sprite():', 'data', '=', 'np.random.RandomState(42).uniform(size=140).reshape(7,', '5,', '4)', 'mask', '=', 'np.zeros((7,', '5,', '4),', 'dtype=int)', 'mask[1:-1,', '1:-1,', '1:-1]', '=', '1', 'sprite_io', '=', 'BytesIO()', 'html_stat_map._save_sprite(data,', 'sprite_io,', 'vmin=0,', 'vmax=1,', 'mask... | 724,117 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | network_base.py | FeedForwardNetworkBase.layer_names | layer_names | A list of uniquified layer names. | [
"A",
"list",
"of",
"uniquified",
"layer",
"names."
] | def layer_names(self):
return self._layer_names | ['def', 'layer_names(self):', 'return', 'self._layer_names'] | 406,264 |
surafelml/adapt-mnmt | sequence_to_sequence.py | guided_alignment_cost | guided_alignment_cost | Computes the guided alignment cost. | [
"Computes",
"the",
"guided",
"alignment",
"cost."
] | def guided_alignment_cost(attention_probs, gold_alignment, sequence_length, guided_alignment_type, guided_alignment_weight=1):
weights = tf.sequence_mask(sequence_length, maxlen=tf.shape(attention_probs)[1], dtype=attention_probs.dtype)
if guided_alignment_type == 'ce':
cross_entropy = -tf.reduce_sum(tf... | ['def', 'guided_alignment_cost(attention_probs,', 'gold_alignment,', 'sequence_length,', 'guided_alignment_type,', 'guided_alignment_weight=1):', 'weights', '=', 'tf.sequence_mask(sequence_length,', 'maxlen=tf.shape(attention_probs)[1],', 'dtype=attention_probs.dtype)', 'if', 'guided_alignment_type', '==', "'ce':", 'cr... | 407,985 |
rifqind/Agent-Programs-3KS1 | server.py | TelnetConnection.send | send | Send text to the client. | [
"Send",
"text",
"to",
"the",
"client."
] | def send(self, formatted_text):
formatted_text = to_formatted_text(formatted_text)
print_formatted_text(self.vt100_output, formatted_text, self.style or DummyStyle()) | ['def', 'send(self,', 'formatted_text):', 'formatted_text', '=', 'to_formatted_text(formatted_text)', 'print_formatted_text(self.vt100_output,', 'formatted_text,', 'self.style', 'or', 'DummyStyle())'] | 45,081 |
openml-labs/gama | nsga2.py | NSGAMeta.crowd_compare | crowd_compare | Favor higher rank, if equal, favor less crowded. | [
"Favor",
"higher",
"rank,",
"if",
"equal,",
"favor",
"less",
"crowded."
] | def crowd_compare(self, other: 'NSGAMeta') -> int:
self_better = self.rank < other.rank or (self.rank == other.rank and self.distance > other.distance)
return -1 if self_better else 1 | ['def', 'crowd_compare(self,', 'other:', "'NSGAMeta')", '->', 'int:', 'self_better', '=', 'self.rank', '<', 'other.rank', 'or', '(self.rank', '==', 'other.rank', 'and', 'self.distance', '>', 'other.distance)', 'return', '-1', 'if', 'self_better', 'else', '1'] | 566,150 |
aleju/computer-vision-algorithms | gauss.py | apply_gauss | apply_gauss | Apply a gaussian filter to an image. | [
"Apply",
"a",
"gaussian",
"filter",
"to",
"an",
"image."
] | def apply_gauss(img, filter_mask):
return signal.correlate(img, filter_mask, mode='same') / np.sum(filter_mask) | ['def', 'apply_gauss(img,', 'filter_mask):', 'return', 'signal.correlate(img,', 'filter_mask,', "mode='same')", '/', 'np.sum(filter_mask)'] | 467,539 |
Eric3911/OpenAGI | transformer_utils.py | transformer_weights_init | transformer_weights_init | Initialize different weights in Transformer model. | [
"Initialize",
"different",
"weights",
"in",
"Transformer",
"model."
] | def transformer_weights_init(module, std_init_range=0.02, xavier=True):
if isinstance(module, nn.Linear):
if xavier:
nn.init.xavier_uniform_(module.weight)
else:
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
if module.bias is not None:
nn.in... | ['def', 'transformer_weights_init(module,', 'std_init_range=0.02,', 'xavier=True):', 'if', 'isinstance(module,', 'nn.Linear):', 'if', 'xavier:', 'nn.init.xavier_uniform_(module.weight)', 'else:', 'nn.init.normal_(module.weight,', 'mean=0.0,', 'std=std_init_range)', 'if', 'module.bias', 'is', 'not', 'None:', 'nn.init.co... | 273,126 |
for-ai/rl | tensor_specs.py | CompositeSpec.empty | empty | Create a spec like self, but with no entries. | [
"Create",
"a",
"spec",
"like",
"self,",
"but",
"with",
"no",
"entries."
] | def empty(self):
try:
device = self.device
except RuntimeError:
device = self._device
return self.__class__({}, device=device, shape=self.shape) | ['def', 'empty(self):', 'try:', 'device', '=', 'self.device', 'except', 'RuntimeError:', 'device', '=', 'self._device', 'return', 'self.__class__({},', 'device=device,', 'shape=self.shape)'] | 858,752 |
Ruturaj123/Flowchart-Detection | linear_test.py | LinearClassifierTest.testLogisticRegression_MatrixData_Labels1D | testLogisticRegression_MatrixData_Labels1D | Same as the last test, but labels shape is [100] instead of [100, 1]. | [
"Same",
"as",
"the",
"last",
"test,",
"but",
"labels",
"shape",
"is",
"[100]",
"instead",
"of",
"[100,",
"1]."
] | def testLogisticRegression_MatrixData_Labels1D(self):
def _input_fn():
iris = _prepare_iris_data_for_logistic_regression()
return ({'feature': constant_op.constant(iris.data, dtype=dtypes.float32)}, constant_op.constant(iris.target, shape=[100], dtype=dtypes.int32))
feature_column = feature_col... | ['def', 'testLogisticRegression_MatrixData_Labels1D(self):', 'def', '_input_fn():', 'iris', '=', '_prepare_iris_data_for_logistic_regression()', 'return', "({'feature':", 'constant_op.constant(iris.data,', 'dtype=dtypes.float32)},', 'constant_op.constant(iris.target,', 'shape=[100],', 'dtype=dtypes.int32))', 'feature_c... | 604,018 |
gunthercox/ChatterBot | posixpath.py | abspath | abspath | Return an absolute path. | [
"Return",
"an",
"absolute",
"path."
] | def abspath(path):
if not isabs(path):
if isinstance(path, unicode):
cwd = os.getcwdu()
else:
cwd = os.getcwd()
path = join(cwd, path)
return normpath(path) | ['def', 'abspath(path):', 'if', 'not', 'isabs(path):', 'if', 'isinstance(path,', 'unicode):', 'cwd', '=', 'os.getcwdu()', 'else:', 'cwd', '=', 'os.getcwd()', 'path', '=', 'join(cwd,', 'path)', 'return', 'normpath(path)'] | 528,072 |
43Carrig/recurrent_neural_networks_practice | local_cli_wrapper.py | LocalCLIDebugWrapperSession.add_tensor_filter | add_tensor_filter | Add a tensor filter. | [
"Add",
"a",
"tensor",
"filter."
] | def add_tensor_filter(self, filter_name, tensor_filter):
self._tensor_filters[filter_name] = tensor_filter | ['def', 'add_tensor_filter(self,', 'filter_name,', 'tensor_filter):', 'self._tensor_filters[filter_name]', '=', 'tensor_filter'] | 336,046 |
rudranil723/mini-main | util.py | get_pattern_context | get_pattern_context | Get the pattern context. | [
"Get",
"the",
"pattern",
"context."
] | def get_pattern_context(pattern: str, index: int) -> Tuple[str, int, int]:
last = 0
current_line = 1
col = 1
text = []
line = 1
offset = None
for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
linetext = pattern[last:m.start(0)]
if not len(m.group(0)) and (not len(text)):
... | ['def', 'get_pattern_context(pattern:', 'str,', 'index:', 'int)', '->', 'Tuple[str,', 'int,', 'int]:', 'last', '=', '0', 'current_line', '=', '1', 'col', '=', '1', 'text', '=', '[]', 'line', '=', '1', 'offset', '=', 'None', 'for', 'm', 'in', 'RE_PATTERN_LINE_SPLIT.finditer(pattern):', 'linetext', '=', 'pattern[last:m.s... | 270,623 |
sunishsheth2009/ChatterBot | expression.py | null | null | Return a :class:`_Null` object, which compiles to ``NULL``. | [
"Return",
"a",
":class:`_Null`",
"object,",
"which",
"compiles",
"to",
"``NULL``."
] | def null():
return _Null() | ['def', 'null():', 'return', '_Null()'] | 481,600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.