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 |
|---|---|---|---|---|---|---|---|---|
RasaHQ/rasa | io.py | write_yaml | write_yaml | Writes a yaml to the file or to the stream. | [
"Writes",
"a",
"yaml",
"to",
"the",
"file",
"or",
"to",
"the",
"stream."
] | def write_yaml(data: Any, target: Union[Text, Path, StringIO], should_preserve_key_order: bool=False) -> None:
_enable_ordered_dict_yaml_dumping()
if should_preserve_key_order:
data = convert_to_ordered_dict(data)
dumper = yaml.YAML()
dumper.width = YAML_LINE_MAX_WIDTH
dumper.representer.add... | ['def', 'write_yaml(data:', 'Any,', 'target:', 'Union[Text,', 'Path,', 'StringIO],', 'should_preserve_key_order:', 'bool=False)', '->', 'None:', '_enable_ordered_dict_yaml_dumping()', 'if', 'should_preserve_key_order:', 'data', '=', 'convert_to_ordered_dict(data)', 'dumper', '=', 'yaml.YAML()', 'dumper.width', '=', 'YA... | 837,804 |
sjtu-marl/malib | offline_dataset_server.py | OfflineDataset.end_producer_pipe | end_producer_pipe | Kill a producer pipe with given name. | [
"Kill",
"a",
"producer",
"pipe",
"with",
"given",
"name."
] | def end_producer_pipe(self, name: str):
if name in self.writer_queues:
queue = self.writer_queues.pop(name)
queue.shutdown() | ['def', 'end_producer_pipe(self,', 'name:', 'str):', 'if', 'name', 'in', 'self.writer_queues:', 'queue', '=', 'self.writer_queues.pop(name)', 'queue.shutdown()'] | 627,448 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | evaluation.py | calculate_parse_metrics | calculate_parse_metrics | Calculate POS/UAS/LAS accuracy based on gold and annotated sentences. | [
"Calculate",
"POS/UAS/LAS",
"accuracy",
"based",
"on",
"gold",
"and",
"annotated",
"sentences."
] | def calculate_parse_metrics(gold_corpus, annotated_corpus):
check.Eq(len(gold_corpus), len(annotated_corpus), 'Corpora are not aligned')
num_tokens = 0
num_correct_pos = 0
num_correct_uas = 0
num_correct_las = 0
for (gold_str, annotated_str) in zip(gold_corpus, annotated_corpus):
gold = ... | ['def', 'calculate_parse_metrics(gold_corpus,', 'annotated_corpus):', 'check.Eq(len(gold_corpus),', 'len(annotated_corpus),', "'Corpora", 'are', 'not', "aligned')", 'num_tokens', '=', '0', 'num_correct_pos', '=', '0', 'num_correct_uas', '=', '0', 'num_correct_las', '=', '0', 'for', '(gold_str,', 'annotated_str)', 'in',... | 111,065 |
thallada/nlp | yesno.py | OpinionClassifier.network | network | Implements the detail of the model. | [
"Implements",
"the",
"detail",
"of",
"the",
"model."
] | def network(self):
self.check_and_create_data()
self.create_shared_params()
q_enc = self.get_enc(self.q_ids, type='q')
a_enc = self.get_enc(self.a_ids, type='q')
q_proj_left = layer.fc(size=self.emb_dim * 2, bias_attr=False, param_attr=Attr.Param(self.name + '_left.wq'), input=q_enc)
q_proj_righ... | ['def', 'network(self):', 'self.check_and_create_data()', 'self.create_shared_params()', 'q_enc', '=', 'self.get_enc(self.q_ids,', "type='q')", 'a_enc', '=', 'self.get_enc(self.a_ids,', "type='q')", 'q_proj_left', '=', 'layer.fc(size=self.emb_dim', '*', '2,', 'bias_attr=False,', 'param_attr=Attr.Param(self.name', '+', ... | 808,644 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | traitlets.py | HasTraits.set_trait | set_trait | Forcibly sets trait attribute, including read-only attributes. | [
"Forcibly",
"sets",
"trait",
"attribute,",
"including",
"read-only",
"attributes."
] | def set_trait(self, name, value):
cls = self.__class__
if not self.has_trait(name):
raise TraitError('Class %s does not have a trait named %s' % (cls.__name__, name))
else:
getattr(cls, name).set(self, value) | ['def', 'set_trait(self,', 'name,', 'value):', 'cls', '=', 'self.__class__', 'if', 'not', 'self.has_trait(name):', 'raise', "TraitError('Class", '%s', 'does', 'not', 'have', 'a', 'trait', 'named', "%s'", '%', '(cls.__name__,', 'name))', 'else:', 'getattr(cls,', 'name).set(self,', 'value)'] | 437,847 |
sunishsheth2009/ChatterBot | reading.py | IndexReader.iter_field | iter_field | Yields (text, terminfo) tuples for all terms in the given field. | [
"Yields",
"(text,",
"terminfo)",
"tuples",
"for",
"all",
"terms",
"in",
"the",
"given",
"field."
] | def iter_field(self, fieldname, prefix=''):
prefix = self._text_to_bytes(fieldname, prefix)
for ((fn, text), terminfo) in self.iter_from(fieldname, prefix):
if fn != fieldname:
return
yield (text, terminfo) | ['def', 'iter_field(self,', 'fieldname,', "prefix=''):", 'prefix', '=', 'self._text_to_bytes(fieldname,', 'prefix)', 'for', '((fn,', 'text),', 'terminfo)', 'in', 'self.iter_from(fieldname,', 'prefix):', 'if', 'fn', '!=', 'fieldname:', 'return', 'yield', '(text,', 'terminfo)'] | 526,299 |
secretflow/secretflow | driver.py | init | init | Connect to an existing Ray cluster or start one and connect to it. | [
"Connect",
"to",
"an",
"existing",
"Ray",
"cluster",
"or",
"start",
"one",
"and",
"connect",
"to",
"it."
] | def init(parties: Union[str, List[str]]=None, address: Optional[str]=None, cluster_config: Dict=None, num_cpus: Optional[int]=None, num_gpus: Optional[int]=None, log_to_driver=True, omp_num_threads: int=None, logging_level: str='info', cross_silo_comm_backend: str='grpc', cross_silo_comm_options: Dict=None, enable_wait... | ['def', 'init(parties:', 'Union[str,', 'List[str]]=None,', 'address:', 'Optional[str]=None,', 'cluster_config:', 'Dict=None,', 'num_cpus:', 'Optional[int]=None,', 'num_gpus:', 'Optional[int]=None,', 'log_to_driver=True,', 'omp_num_threads:', 'int=None,', 'logging_level:', "str='info',", 'cross_silo_comm_backend:', "str... | 856,378 |
bnpy/bnpy | GraphXData.py | GraphXData.add_data | add_data | Updates (in-place) this object by adding new nodes. | [
"Updates",
"(in-place)",
"this",
"object",
"by",
"adding",
"new",
"nodes."
] | def add_data(self, otherDataObj):
self.X = np.vstack([self.X, otherDataObj.X])
self.edges = np.vstack([self.edges, otherDataObj.edges])
self._set_size_attributes(nNodesTotal=self.nNodesTotal + otherDataObj.nNodesTotal, nEdgesTotal=self.nEdgesTotal + otherDataObj.nEdgesTotal) | ['def', 'add_data(self,', 'otherDataObj):', 'self.X', '=', 'np.vstack([self.X,', 'otherDataObj.X])', 'self.edges', '=', 'np.vstack([self.edges,', 'otherDataObj.edges])', 'self._set_size_attributes(nNodesTotal=self.nNodesTotal', '+', 'otherDataObj.nNodesTotal,', 'nEdgesTotal=self.nEdgesTotal', '+', 'otherDataObj.nEdgesT... | 464,514 |
nosmokingbandit/watcher | timeout.py | signalHandler | signalHandler | Signal handler to catch timeout signal: raise Timeout exception. | [
"Signal",
"handler",
"to",
"catch",
"timeout",
"signal:",
"raise",
"Timeout",
"exception."
] | def signalHandler(signum, frame):
raise Timeout('Timeout exceed!') | ['def', 'signalHandler(signum,', 'frame):', 'raise', "Timeout('Timeout", "exceed!')"] | 381,669 |
cvhciKIT/sloth | labeltool.py | LabelTool.fetch_command | fetch_command | Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line if it can't be found. | [
"Tries",
"to",
"fetch",
"the",
"given",
"subcommand,",
"printing",
"a",
"message",
"with",
"the",
"appropriate",
"command",
"called",
"from",
"the",
"command",
"line",
"if",
"it",
"can't",
"be",
"found."
] | def fetch_command(self, subcommand):
try:
app_name = get_commands()[subcommand]
except KeyError:
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % (subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
klass = app_name
else:
... | ['def', 'fetch_command(self,', 'subcommand):', 'try:', 'app_name', '=', 'get_commands()[subcommand]', 'except', 'KeyError:', 'sys.stderr.write("Unknown', 'command:', '%r\\nType', "'%s", "help'", 'for', 'usage.\\n"', '%', '(subcommand,', 'self.prog_name))', 'sys.exit(1)', 'if', 'isinstance(app_name,', 'BaseCommand):', '... | 878,378 |
Constantino/ComputerVision | ar_teapot.py | set_projection_from_camera | set_projection_from_camera | Set view from a camera calibration matrix. | [
"Set",
"view",
"from",
"a",
"camera",
"calibration",
"matrix."
] | def set_projection_from_camera(K):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
fx = K[0, 0]
fy = K[1, 1]
fovy = 2 * arctan(0.5 * height / fy) * 180 / pi
aspect = width * fy / (height * fx)
near = 0.1
far = 100.0
gluPerspective(fovy, aspect, near, far)
glViewport(0, 0, width, hei... | ['def', 'set_projection_from_camera(K):', 'glMatrixMode(GL_PROJECTION)', 'glLoadIdentity()', 'fx', '=', 'K[0,', '0]', 'fy', '=', 'K[1,', '1]', 'fovy', '=', '2', '*', 'arctan(0.5', '*', 'height', '/', 'fy)', '*', '180', '/', 'pi', 'aspect', '=', 'width', '*', 'fy', '/', '(height', '*', 'fx)', 'near', '=', '0.1', 'far', ... | 471,144 |
zihuitang/medical_AI_platform | dis.py | Bytecode.info | info | Return formatted information about the code object. | [
"Return",
"formatted",
"information",
"about",
"the",
"code",
"object."
] | def info(self):
return _format_code_info(self.codeobj) | ['def', 'info(self):', 'return', '_format_code_info(self.codeobj)'] | 280,343 |
ruiwang2021/mvd | video_transforms.py | clip_boxes_to_image | clip_boxes_to_image | Clip an array of boxes to an image with the given height and width. | [
"Clip",
"an",
"array",
"of",
"boxes",
"to",
"an",
"image",
"with",
"the",
"given",
"height",
"and",
"width."
] | def clip_boxes_to_image(boxes, height, width):
clipped_boxes = boxes.copy()
clipped_boxes[:, [0, 2]] = np.minimum(width - 1.0, np.maximum(0.0, boxes[:, [0, 2]]))
clipped_boxes[:, [1, 3]] = np.minimum(height - 1.0, np.maximum(0.0, boxes[:, [1, 3]]))
return clipped_boxes | ['def', 'clip_boxes_to_image(boxes,', 'height,', 'width):', 'clipped_boxes', '=', 'boxes.copy()', 'clipped_boxes[:,', '[0,', '2]]', '=', 'np.minimum(width', '-', '1.0,', 'np.maximum(0.0,', 'boxes[:,', '[0,', '2]]))', 'clipped_boxes[:,', '[1,', '3]]', '=', 'np.minimum(height', '-', '1.0,', 'np.maximum(0.0,', 'boxes[:,',... | 266,838 |
sunishsheth2009/ChatterBot | attributes.py | AttributeImpl.initialize | initialize | Initialize the given state's attribute with an empty value. | [
"Initialize",
"the",
"given",
"state's",
"attribute",
"with",
"an",
"empty",
"value."
] | def initialize(self, state, dict_):
dict_[self.key] = None
return None | ['def', 'initialize(self,', 'state,', 'dict_):', 'dict_[self.key]', '=', 'None', 'return', 'None'] | 481,129 |
keyonvafa/career-code | load_config.py | load_config | load_config | TODO (huxu): move fairseq overwrite to another function. | [
"TODO",
"(huxu):",
"move",
"fairseq",
"overwrite",
"to",
"another",
"function."
] | def load_config(args=None, config_file=None, overwrite_fairseq=False):
if args is not None:
config_file = args.taskconfig
config = recursive_config(config_file)
if config.dataset.subsampling is not None:
batch_size = config.fairseq.dataset.batch_size // config.dataset.subsampling
pri... | ['def', 'load_config(args=None,', 'config_file=None,', 'overwrite_fairseq=False):', 'if', 'args', 'is', 'not', 'None:', 'config_file', '=', 'args.taskconfig', 'config', '=', 'recursive_config(config_file)', 'if', 'config.dataset.subsampling', 'is', 'not', 'None:', 'batch_size', '=', 'config.fairseq.dataset.batch_size',... | 454,910 |
wbw520/NoisyLSTM | tool.py | pad_image | pad_image | Pad an image up to the target size. | [
"Pad",
"an",
"image",
"up",
"to",
"the",
"target",
"size."
] | def pad_image(img, target_size):
rows_missing = target_size[0] - img.shape[2]
cols_missing = target_size[1] - img.shape[3]
padded_img = np.pad(img, ((0, 0), (0, 0), (0, rows_missing), (0, cols_missing)), 'constant')
return padded_img | ['def', 'pad_image(img,', 'target_size):', 'rows_missing', '=', 'target_size[0]', '-', 'img.shape[2]', 'cols_missing', '=', 'target_size[1]', '-', 'img.shape[3]', 'padded_img', '=', 'np.pad(img,', '((0,', '0),', '(0,', '0),', '(0,', 'rows_missing),', '(0,', 'cols_missing)),', "'constant')", 'return', 'padded_img'] | 729,241 |
43Carrig/recurrent_neural_networks_practice | _flagvalues.py | FlagValues.append_flag_values | append_flag_values | Appends flags registered in another FlagValues instance. | [
"Appends",
"flags",
"registered",
"in",
"another",
"FlagValues",
"instance."
] | def append_flag_values(self, flag_values):
for (flag_name, flag) in six.iteritems(flag_values._flags()):
if flag_name == flag.name:
try:
self[flag_name] = flag
except _exceptions.DuplicateFlagError:
raise _exceptions.DuplicateFlagError.from_flag(flag_n... | ['def', 'append_flag_values(self,', 'flag_values):', 'for', '(flag_name,', 'flag)', 'in', 'six.iteritems(flag_values._flags()):', 'if', 'flag_name', '==', 'flag.name:', 'try:', 'self[flag_name]', '=', 'flag', 'except', '_exceptions.DuplicateFlagError:', 'raise', '_exceptions.DuplicateFlagError.from_flag(flag_name,', 's... | 309,632 |
sek788432/Waymo-2D-Object-Detection | utils.py | clip | clip | Return a tf op which clips tensor according to range_. | [
"Return",
"a",
"tf",
"op",
"which",
"clips",
"tensor",
"according",
"to",
"range_."
] | def clip(tensor, range_=None):
if range_ is None:
return tf.identity(tensor)
elif isinstance(range_, (tuple, list)):
assert len(range_) == 2
return tf.clip_by_value(tensor, range_[0], range_[1])
else:
raise NotImplementedError('Unacceptable range input: %r' % range_) | ['def', 'clip(tensor,', 'range_=None):', 'if', 'range_', 'is', 'None:', 'return', 'tf.identity(tensor)', 'elif', 'isinstance(range_,', '(tuple,', 'list)):', 'assert', 'len(range_)', '==', '2', 'return', 'tf.clip_by_value(tensor,', 'range_[0],', 'range_[1])', 'else:', 'raise', "NotImplementedError('Unacceptable", 'range... | 974,407 |
jshilong/DDQ | detectors_resnet.py | Bottleneck.rfp_forward | rfp_forward | The forward function that also takes the RFP features as input. | [
"The",
"forward",
"function",
"that",
"also",
"takes",
"the",
"RFP",
"features",
"as",
"input."
] | def rfp_forward(self, x, rfp_feat):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
out = self.conv2(out)
out = ... | ['def', 'rfp_forward(self,', 'x,', 'rfp_feat):', 'def', '_inner_forward(x):', 'identity', '=', 'x', 'out', '=', 'self.conv1(x)', 'out', '=', 'self.norm1(out)', 'out', '=', 'self.relu(out)', 'if', 'self.with_plugins:', 'out', '=', 'self.forward_plugin(out,', 'self.after_conv1_plugin_names)', 'out', '=', 'self.conv2(out)... | 515,886 |
Caojunxu/AC-FPN | boxes.py | filter_small_boxes | filter_small_boxes | Keep boxes with width and height both greater than min_size. | [
"Keep",
"boxes",
"with",
"width",
"and",
"height",
"both",
"greater",
"than",
"min_size."
] | def filter_small_boxes(boxes, min_size):
w = boxes[:, 2] - boxes[:, 0] + 1
h = boxes[:, 3] - boxes[:, 1] + 1
keep = np.where((w > min_size) & (h > min_size))[0]
return keep | ['def', 'filter_small_boxes(boxes,', 'min_size):', 'w', '=', 'boxes[:,', '2]', '-', 'boxes[:,', '0]', '+', '1', 'h', '=', 'boxes[:,', '3]', '-', 'boxes[:,', '1]', '+', '1', 'keep', '=', 'np.where((w', '>', 'min_size)', '&', '(h', '>', 'min_size))[0]', 'return', 'keep'] | 406,531 |
ArtificialIntelligenceToolkit/aitk.robots | watchers.py | Player.initialize | initialize | Setup the displayer ids to map results to the areas. | [
"Setup",
"the",
"displayer",
"ids",
"to",
"map",
"results",
"to",
"the",
"areas."
] | def initialize(self):
results = self.function(self.control_slider.value)
if not isinstance(results, (list, tuple)):
results = [results]
self.displayers = [display(x, display_id=True) for x in results] | ['def', 'initialize(self):', 'results', '=', 'self.function(self.control_slider.value)', 'if', 'not', 'isinstance(results,', '(list,', 'tuple)):', 'results', '=', '[results]', 'self.displayers', '=', '[display(x,', 'display_id=True)', 'for', 'x', 'in', 'results]'] | 86,656 |
NoGameNoLife00/mybolg | filters.py | do_random | do_random | Return a random item from the sequence. | [
"Return",
"a",
"random",
"item",
"from",
"the",
"sequence."
] | def do_random(environment, seq):
try:
return choice(seq)
except IndexError:
return environment.undefined('No random item, sequence was empty.') | ['def', 'do_random(environment,', 'seq):', 'try:', 'return', 'choice(seq)', 'except', 'IndexError:', 'return', "environment.undefined('No", 'random', 'item,', 'sequence', 'was', "empty.')"] | 289,511 |
QData/deepWordBug | types.py | normpath | normpath | Custom path normalizer that handles Compose-specific edge cases like UNIX paths on Windows hosts and vice-versa. | [
"Custom",
"path",
"normalizer",
"that",
"handles",
"Compose-specific",
"edge",
"cases",
"like",
"UNIX",
"paths",
"on",
"Windows",
"hosts",
"and",
"vice-versa."
] | def normpath(path, win_host=False):
sysnorm = ntpath.normpath if win_host else os.path.normpath
flip_slashes = path.startswith('/') and IS_WINDOWS_PLATFORM
path = sysnorm(path)
if flip_slashes:
path = path.replace('\\', '/')
return path | ['def', 'normpath(path,', 'win_host=False):', 'sysnorm', '=', 'ntpath.normpath', 'if', 'win_host', 'else', 'os.path.normpath', 'flip_slashes', '=', "path.startswith('/')", 'and', 'IS_WINDOWS_PLATFORM', 'path', '=', 'sysnorm(path)', 'if', 'flip_slashes:', 'path', '=', "path.replace('\\\\',", "'/')", 'return', 'path'] | 541,791 |
Eric3911/OpenAGI | app_state.py | AppState.checkpoint_callback_params | checkpoint_callback_params | Sets the name property. | [
"Sets",
"the",
"name",
"property."
] | def checkpoint_callback_params(self, params):
self._checkpoint_callback_params = params | ['def', 'checkpoint_callback_params(self,', 'params):', 'self._checkpoint_callback_params', '=', 'params'] | 274,152 |
paulorauber/rl | collectors.py | recursive_map_to_cpu | recursive_map_to_cpu | Maps the tensors to CPU through a nested dictionary. | [
"Maps",
"the",
"tensors",
"to",
"CPU",
"through",
"a",
"nested",
"dictionary."
] | def recursive_map_to_cpu(dictionary: OrderedDict) -> OrderedDict:
return OrderedDict(**{k: recursive_map_to_cpu(item) if isinstance(item, OrderedDict) else item.cpu() if isinstance(item, torch.Tensor) else item for (k, item) in dictionary.items()}) | ['def', 'recursive_map_to_cpu(dictionary:', 'OrderedDict)', '->', 'OrderedDict:', 'return', 'OrderedDict(**{k:', 'recursive_map_to_cpu(item)', 'if', 'isinstance(item,', 'OrderedDict)', 'else', 'item.cpu()', 'if', 'isinstance(item,', 'torch.Tensor)', 'else', 'item', 'for', '(k,', 'item)', 'in', 'dictionary.items()})'] | 858,574 |
KalleHallden/InstaAutomator | _tifffile.py | TiffPage.is_fluoview | is_fluoview | Page contains FluoView MM_STAMP tag. | [
"Page",
"contains",
"FluoView",
"MM_STAMP",
"tag."
] | def is_fluoview(self):
return 'mm_stamp' in self.tags | ['def', 'is_fluoview(self):', 'return', "'mm_stamp'", 'in', 'self.tags'] | 230,074 |
SimingYan/IAE | __init__.py | ConvolutionalDFNetwork.forward | forward | Performs a forward pass through the network. | [
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"network."
] | def forward(self, p, inputs, **kwargs):
if isinstance(p, dict):
batch_size = p['p'].size(0)
else:
batch_size = p.size(0)
c = self.encode_inputs(inputs)
output = self.decode(p, c, **kwargs)
return output | ['def', 'forward(self,', 'p,', 'inputs,', '**kwargs):', 'if', 'isinstance(p,', 'dict):', 'batch_size', '=', "p['p'].size(0)", 'else:', 'batch_size', '=', 'p.size(0)', 'c', '=', 'self.encode_inputs(inputs)', 'output', '=', 'self.decode(p,', 'c,', '**kwargs)', 'return', 'output'] | 228,295 |
sktime/sktime | test_Rocket.py | test_rocket_on_gunpoint | test_rocket_on_gunpoint | Test of Rocket on gun point. | [
"Test",
"of",
"Rocket",
"on",
"gun",
"point."
] | def test_rocket_on_gunpoint():
(X_training, Y_training) = load_gunpoint(split='train', return_X_y=True)
ROCKET = Rocket(num_kernels=10000, random_state=0)
ROCKET.fit(X_training)
X_training_transform = ROCKET.transform(X_training)
np.testing.assert_equal(X_training_transform.shape, (len(X_training), ... | ['def', 'test_rocket_on_gunpoint():', '(X_training,', 'Y_training)', '=', "load_gunpoint(split='train',", 'return_X_y=True)', 'ROCKET', '=', 'Rocket(num_kernels=10000,', 'random_state=0)', 'ROCKET.fit(X_training)', 'X_training_transform', '=', 'ROCKET.transform(X_training)', 'np.testing.assert_equal(X_training_transfor... | 877,714 |
prof-fabriciogmc/artificial_intelligence | selectors.py | DefaultSelector | DefaultSelector | This function serves as a first call for DefaultSelector to detect if the select module is being monkey-patched incorrectly by eventlet, greenlet, and preserve proper behavior. | [
"This",
"function",
"serves",
"as",
"a",
"first",
"call",
"for",
"DefaultSelector",
"to",
"detect",
"if",
"the",
"select",
"module",
"is",
"being",
"monkey-patched",
"incorrectly",
"by",
"eventlet,",
"greenlet,",
"and",
"preserve",
"proper",
"behavior."
] | def DefaultSelector():
global _DEFAULT_SELECTOR
if _DEFAULT_SELECTOR is None:
if _can_allocate('kqueue'):
_DEFAULT_SELECTOR = KqueueSelector
elif _can_allocate('epoll'):
_DEFAULT_SELECTOR = EpollSelector
elif _can_allocate('poll'):
_DEFAULT_SELECTOR = ... | ['def', 'DefaultSelector():', 'global', '_DEFAULT_SELECTOR', 'if', '_DEFAULT_SELECTOR', 'is', 'None:', 'if', "_can_allocate('kqueue'):", '_DEFAULT_SELECTOR', '=', 'KqueueSelector', 'elif', "_can_allocate('epoll'):", '_DEFAULT_SELECTOR', '=', 'EpollSelector', 'elif', "_can_allocate('poll'):", '_DEFAULT_SELECTOR', '=', '... | 146,424 |
ldkong1205/LaserMix | local_visualizer.py | Det3DLocalVisualizer.draw_seg_mask | draw_seg_mask | Add segmentation mask to visualizer via per-point colorization. | [
"Add",
"segmentation",
"mask",
"to",
"visualizer",
"via",
"per-point",
"colorization."
] | def draw_seg_mask(self, seg_mask_colors: np.ndarray) -> None:
if hasattr(self, 'pcd'):
offset = (np.array(self.pcd.points).max(0) - np.array(self.pcd.points).min(0))[0] * 1.2
mesh_frame = geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[offset, 0, 0])
self.o3d_vis.add_geometry(m... | ['def', 'draw_seg_mask(self,', 'seg_mask_colors:', 'np.ndarray)', '->', 'None:', 'if', 'hasattr(self,', "'pcd'):", 'offset', '=', '(np.array(self.pcd.points).max(0)', '-', 'np.array(self.pcd.points).min(0))[0]', '*', '1.2', 'mesh_frame', '=', 'geometry.TriangleMesh.create_coordinate_frame(size=1,', 'origin=[offset,', '... | 624,473 |
rishikksh20/HiFi-GAN | generator.py | Generator.apply_weight_norm | apply_weight_norm | Apply weight normalization module from all of the layers. | [
"Apply",
"weight",
"normalization",
"module",
"from",
"all",
"of",
"the",
"layers."
] | def apply_weight_norm(self):
def _apply_weight_norm(m):
if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):
torch.nn.utils.weight_norm(m)
self.apply(_apply_weight_norm) | ['def', 'apply_weight_norm(self):', 'def', '_apply_weight_norm(m):', 'if', 'isinstance(m,', 'torch.nn.Conv1d)', 'or', 'isinstance(m,', 'torch.nn.ConvTranspose1d):', 'torch.nn.utils.weight_norm(m)', 'self.apply(_apply_weight_norm)'] | 593,203 |
calico/basenji | basenji_sat_bed.py | satmut_gen | satmut_gen | Construct generator for 1 hot encoded saturation mutagenesis DNA sequences. | [
"Construct",
"generator",
"for",
"1",
"hot",
"encoded",
"saturation",
"mutagenesis",
"DNA",
"sequences."
] | def satmut_gen(seqs_dna, mut_start, mut_end):
for seq_dna in seqs_dna:
seq_1hot = dna_io.dna_1hot(seq_dna)
yield seq_1hot
for mi in range(mut_start, mut_end):
for ni in range(4):
if seq_1hot[mi, ni] == 0:
seq_mut_1hot = np.copy(seq_1hot)
... | ['def', 'satmut_gen(seqs_dna,', 'mut_start,', 'mut_end):', 'for', 'seq_dna', 'in', 'seqs_dna:', 'seq_1hot', '=', 'dna_io.dna_1hot(seq_dna)', 'yield', 'seq_1hot', 'for', 'mi', 'in', 'range(mut_start,', 'mut_end):', 'for', 'ni', 'in', 'range(4):', 'if', 'seq_1hot[mi,', 'ni]', '==', '0:', 'seq_mut_1hot', '=', 'np.copy(seq... | 94,798 |
greydanus/pythonic_ocr | setup.py | is_npy_no_smp | is_npy_no_smp | Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled). | [
"Return",
"True",
"if",
"the",
"NPY_NO_SMP",
"symbol",
"must",
"be",
"defined",
"in",
"public",
"header",
"(when",
"SMP",
"support",
"cannot",
"be",
"reliably",
"enabled)."
] | def is_npy_no_smp():
return 'NPY_NOSMP' in os.environ | ['def', 'is_npy_no_smp():', 'return', "'NPY_NOSMP'", 'in', 'os.environ'] | 299,543 |
salesforce/CodeRL | style_doc.py | style_docstrings_in_code | style_docstrings_in_code | Style all docstrings in some code. | [
"Style",
"all",
"docstrings",
"in",
"some",
"code."
] | def style_docstrings_in_code(code, max_len=119):
splits = code.split('"""')
splits = [s if i % 2 == 0 or _re_doc_ignore.search(splits[i - 1]) is not None else style_docstring(s, max_len=max_len) for (i, s) in enumerate(splits)]
black_errors = '\n\n'.join([s[1] for s in splits if isinstance(s, tuple) and len... | ['def', 'style_docstrings_in_code(code,', 'max_len=119):', 'splits', '=', 'code.split(\'"""\')', 'splits', '=', '[s', 'if', 'i', '%', '2', '==', '0', 'or', '_re_doc_ignore.search(splits[i', '-', '1])', 'is', 'not', 'None', 'else', 'style_docstring(s,', 'max_len=max_len)', 'for', '(i,', 's)', 'in', 'enumerate(splits)]',... | 495,787 |
mozilla/bugbug | test_bug_classification.py | test_non_int_batch | test_non_int_batch | Start with a blank database. | [
"Start",
"with",
"a",
"blank",
"database."
] | def test_non_int_batch(client):
bugs = ['1', '2', '3']
rv = client.post('/component/predict/batch', data=json.dumps({'bugs': bugs}), headers={API_TOKEN: 'test'})
assert rv.status_code == 400
assert rv.json == {'errors': {'bugs': [{'0': ['must be of integer type'], '1': ['must be of integer type'], '2': ... | ['def', 'test_non_int_batch(client):', 'bugs', '=', "['1',", "'2',", "'3']", 'rv', '=', "client.post('/component/predict/batch',", "data=json.dumps({'bugs':", 'bugs}),', 'headers={API_TOKEN:', "'test'})", 'assert', 'rv.status_code', '==', '400', 'assert', 'rv.json', '==', "{'errors':", "{'bugs':", "[{'0':", "['must", '... | 410,353 |
VisualComputingInstitute/3d-semantic- | tf_util.py | batch_norm_for_conv3d | batch_norm_for_conv3d | Batch normalization on 3D convolutional maps. | [
"Batch",
"normalization",
"on",
"3D",
"convolutional",
"maps."
] | def batch_norm_for_conv3d(inputs, is_training, bn_decay, scope):
return batch_norm_template(inputs, is_training, scope, [0, 1, 2, 3], bn_decay) | ['def', 'batch_norm_for_conv3d(inputs,', 'is_training,', 'bn_decay,', 'scope):', 'return', 'batch_norm_template(inputs,', 'is_training,', 'scope,', '[0,', '1,', '2,', '3],', 'bn_decay)'] | 375,986 |
EdinburghNLP/XSum | __init__.py | register_lr_scheduler | register_lr_scheduler | Decorator to register a new LR scheduler. | [
"Decorator",
"to",
"register",
"a",
"new",
"LR",
"scheduler."
] | def register_lr_scheduler(name):
def register_lr_scheduler_cls(cls):
if name in LR_SCHEDULER_REGISTRY:
raise ValueError('Cannot register duplicate LR scheduler ({})'.format(name))
if not issubclass(cls, FairseqLRScheduler):
raise ValueError('LR Scheduler ({}: {}) must extend... | ['def', 'register_lr_scheduler(name):', 'def', 'register_lr_scheduler_cls(cls):', 'if', 'name', 'in', 'LR_SCHEDULER_REGISTRY:', 'raise', "ValueError('Cannot", 'register', 'duplicate', 'LR', 'scheduler', "({})'.format(name))", 'if', 'not', 'issubclass(cls,', 'FairseqLRScheduler):', 'raise', "ValueError('LR", 'Scheduler'... | 374,568 |
ashwin-phadke/cvplayground | preprocessor.py | random_jpeg_quality | random_jpeg_quality | Randomly encode the image to a random JPEG quality level. | [
"Randomly",
"encode",
"the",
"image",
"to",
"a",
"random",
"JPEG",
"quality",
"level."
] | def random_jpeg_quality(image, min_jpeg_quality=0, max_jpeg_quality=100, random_coef=0.0, seed=None, preprocess_vars_cache=None):
def _adjust_jpeg_quality():
generator_func = functools.partial(tf.random_uniform, [], minval=min_jpeg_quality, maxval=max_jpeg_quality, dtype=tf.int32, seed=seed)
qualit... | ['def', 'random_jpeg_quality(image,', 'min_jpeg_quality=0,', 'max_jpeg_quality=100,', 'random_coef=0.0,', 'seed=None,', 'preprocess_vars_cache=None):', 'def', '_adjust_jpeg_quality():', 'generator_func', '=', 'functools.partial(tf.random_uniform,', '[],', 'minval=min_jpeg_quality,', 'maxval=max_jpeg_quality,', 'dtype=t... | 509,933 |
omonimus1/super-computer- | libpython.py | LanguageInfo.runtime_break_functions | runtime_break_functions | Implement this if the list of step-into functions depends on the context. | [
"Implement",
"this",
"if",
"the",
"list",
"of",
"step-into",
"functions",
"depends",
"on",
"the",
"context."
] | def runtime_break_functions(self):
return () | ['def', 'runtime_break_functions(self):', 'return', '()'] | 912,967 |
deepmind/bsuite | terminal_logging.py | value_format | value_format | Convenience function for string formatting. | [
"Convenience",
"function",
"for",
"string",
"formatting."
] | def value_format(value: Any) -> str:
if isinstance(value, numbers.Integral):
return str(value)
if isinstance(value, numbers.Number):
return f'{value:0.4f}'
return str(value) | ['def', 'value_format(value:', 'Any)', '->', 'str:', 'if', 'isinstance(value,', 'numbers.Integral):', 'return', 'str(value)', 'if', 'isinstance(value,', 'numbers.Number):', 'return', "f'{value:0.4f}'", 'return', 'str(value)'] | 410,263 |
openvinotoolkit/training_extensions | ib_loss.py | IBLoss.forward | forward | Forward fuction of IBLoss. | [
"Forward",
"fuction",
"of",
"IBLoss."
] | def forward(self, x, target, feature):
if self._cur_epoch < self._start_epoch:
return super().forward(x, target)
grads = torch.sum(torch.abs(F.softmax(x, dim=1) - F.one_hot(target, self.num_classes)), 1)
feature = torch.sum(torch.abs(feature), 1).reshape(-1, 1)
scaler = grads * feature.reshape(-... | ['def', 'forward(self,', 'x,', 'target,', 'feature):', 'if', 'self._cur_epoch', '<', 'self._start_epoch:', 'return', 'super().forward(x,', 'target)', 'grads', '=', 'torch.sum(torch.abs(F.softmax(x,', 'dim=1)', '-', 'F.one_hot(target,', 'self.num_classes)),', '1)', 'feature', '=', 'torch.sum(torch.abs(feature),', '1).re... | 904,090 |
kornia/kornia | face_detection.py | FaceDetectorResult.xmin | xmin | The bounding box top-left x-coordinate. | [
"The",
"bounding",
"box",
"top-left",
"x-coordinate."
] | def xmin(self) -> torch.Tensor:
return self._data[..., 0] | ['def', 'xmin(self)', '->', 'torch.Tensor:', 'return', 'self._data[...,', '0]'] | 621,585 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | screen.py | screen.put | put | This puts a characters at the current cursor position. | [
"This",
"puts",
"a",
"characters",
"at",
"the",
"current",
"cursor",
"position."
] | def put(self, ch):
if isinstance(ch, bytes):
ch = self._decode(ch)
self.put_abs(self.cur_r, self.cur_c, ch) | ['def', 'put(self,', 'ch):', 'if', 'isinstance(ch,', 'bytes):', 'ch', '=', 'self._decode(ch)', 'self.put_abs(self.cur_r,', 'self.cur_c,', 'ch)'] | 454,111 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | real_nvp_utils.py | standard_normal_sample | standard_normal_sample | Samples from standard Gaussian distribution. | [
"Samples",
"from",
"standard",
"Gaussian",
"distribution."
] | def standard_normal_sample(shape):
return tf.random_normal(shape) | ['def', 'standard_normal_sample(shape):', 'return', 'tf.random_normal(shape)'] | 109,489 |
chainer/chainerrl | train_agent.py | train_agent_with_evaluation | train_agent_with_evaluation | Train an agent while periodically evaluating it. | [
"Train",
"an",
"agent",
"while",
"periodically",
"evaluating",
"it."
] | def train_agent_with_evaluation(agent, env, steps, eval_n_steps, eval_n_episodes, eval_interval, outdir, checkpoint_freq=None, train_max_episode_len=None, step_offset=0, eval_max_episode_len=None, eval_env=None, successful_score=None, step_hooks=(), save_best_so_far_agent=True, logger=None):
logger = logger or logg... | ['def', 'train_agent_with_evaluation(agent,', 'env,', 'steps,', 'eval_n_steps,', 'eval_n_episodes,', 'eval_interval,', 'outdir,', 'checkpoint_freq=None,', 'train_max_episode_len=None,', 'step_offset=0,', 'eval_max_episode_len=None,', 'eval_env=None,', 'successful_score=None,', 'step_hooks=(),', 'save_best_so_far_agent=... | 104,589 |
tensorflow/agents | example_encoding_test.py | example_nested_spec | example_nested_spec | Return an example nested array spec. | [
"Return",
"an",
"example",
"nested",
"array",
"spec."
] | def example_nested_spec(dtype):
low = -10
high = 10
if dtype in (np.uint8, np.uint16):
low += -low
return {'array_spec_1': array_spec.ArraySpec((2, 3), dtype), 'bounded_spec_1': array_spec.BoundedArraySpec((2, 3), dtype, low, high), 'empty_shape': array_spec.BoundedArraySpec((), dtype, low, high... | ['def', 'example_nested_spec(dtype):', 'low', '=', '-10', 'high', '=', '10', 'if', 'dtype', 'in', '(np.uint8,', 'np.uint16):', 'low', '+=', '-low', 'return', "{'array_spec_1':", 'array_spec.ArraySpec((2,', '3),', 'dtype),', "'bounded_spec_1':", 'array_spec.BoundedArraySpec((2,', '3),', 'dtype,', 'low,', 'high),', "'emp... | 23,844 |
dbash/zerowaste | events.py | EventStorage.put_scalar | put_scalar | Add a scalar `value` to the `HistoryBuffer` associated with `name`. | [
"Add",
"a",
"scalar",
"`value`",
"to",
"the",
"`HistoryBuffer`",
"associated",
"with",
"`name`."
] | def put_scalar(self, name, value, smoothing_hint=True):
name = self._current_prefix + name
history = self._history[name]
value = float(value)
history.update(value, self._iter)
self._latest_scalars[name] = (value, self._iter)
existing_hint = self._smoothing_hints.get(name)
if existing_hint is... | ['def', 'put_scalar(self,', 'name,', 'value,', 'smoothing_hint=True):', 'name', '=', 'self._current_prefix', '+', 'name', 'history', '=', 'self._history[name]', 'value', '=', 'float(value)', 'history.update(value,', 'self._iter)', 'self._latest_scalars[name]', '=', '(value,', 'self._iter)', 'existing_hint', '=', 'self.... | 971,567 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | __init__.py | VersionControl.make_rev_args | make_rev_args | Return the RevOptions "extra arguments" to use in obtain(). | [
"Return",
"the",
"RevOptions",
"\"extra",
"arguments\"",
"to",
"use",
"in",
"obtain()."
] | def make_rev_args(self, username, password):
return [] | ['def', 'make_rev_args(self,', 'username,', 'password):', 'return', '[]'] | 259,068 |
jimtin/Stock_Comparison | magic.py | MagicsManager.auto_status | auto_status | Return descriptive string with automagic status. | [
"Return",
"descriptive",
"string",
"with",
"automagic",
"status."
] | def auto_status(self):
return self._auto_status[self.auto_magic] | ['def', 'auto_status(self):', 'return', 'self._auto_status[self.auto_magic]'] | 384,804 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | backend_bases.py | GraphicsContextBase.get_gid | get_gid | Return the object identifier if one is set, None otherwise. | [
"Return",
"the",
"object",
"identifier",
"if",
"one",
"is",
"set,",
"None",
"otherwise."
] | def get_gid(self):
return self._gid | ['def', 'get_gid(self):', 'return', 'self._gid'] | 306,391 |
nicknochnack/RealTimeSignLanguageTFJS | delg_model.py | cosine_classifier_logits | cosine_classifier_logits | Compute cosine classifier logits using ArFace margin. | [
"Compute",
"cosine",
"classifier",
"logits",
"using",
"ArFace",
"margin."
] | def cosine_classifier_logits(prelogits, labels, num_classes, cosine_weights, scale_factor, arcface_margin, training=True):
normalized_prelogits = tf.math.l2_normalize(prelogits, axis=1)
normalized_weights = tf.math.l2_normalize(cosine_weights, axis=0)
cosine_sim = tf.matmul(normalized_prelogits, normalized_... | ['def', 'cosine_classifier_logits(prelogits,', 'labels,', 'num_classes,', 'cosine_weights,', 'scale_factor,', 'arcface_margin,', 'training=True):', 'normalized_prelogits', '=', 'tf.math.l2_normalize(prelogits,', 'axis=1)', 'normalized_weights', '=', 'tf.math.l2_normalize(cosine_weights,', 'axis=0)', 'cosine_sim', '=', ... | 851,687 |
YangLiu9208/TCGL | 1_train_TCGL_UCF101_R3D50.py | order_class_index | order_class_index | Return the index of the order in its full permutation. | [
"Return",
"the",
"index",
"of",
"the",
"order",
"in",
"its",
"full",
"permutation."
] | def order_class_index(order):
classes = list(itertools.permutations(list(range(len(order)))))
return classes.index(tuple(order.tolist())) | ['def', 'order_class_index(order):', 'classes', '=', 'list(itertools.permutations(list(range(len(order)))))', 'return', 'classes.index(tuple(order.tolist()))'] | 365,625 |
rudranil723/mini-main | bezier.py | BezierSegment.point_at_t | point_at_t | Evaluate the curve at a single point, returning a tuple of *d* floats. | [
"Evaluate",
"the",
"curve",
"at",
"a",
"single",
"point,",
"returning",
"a",
"tuple",
"of",
"*d*",
"floats."
] | def point_at_t(self, t):
return tuple(self(t)) | ['def', 'point_at_t(self,', 't):', 'return', 'tuple(self(t))'] | 319,229 |
ifwe/digsby | imwin_tofrom.py | ComboListEditor.OnRemove | OnRemove | Invoked when one of the "remove" menu items is clicked. | [
"Invoked",
"when",
"one",
"of",
"the",
"\"remove\"",
"menu",
"items",
"is",
"clicked."
] | def OnRemove(self, item):
i = self.remove_menu.GetItemIndex(item)
assert len(self.menu_items) <= len(self.remove_menu)
if self.remove_cb(self.seq[i]):
LOG('removing item %d (selection is %s)', i, self.selection)
self.seq.pop(i)
self.remove_menu.RemoveItem(i)
self.menu_items.p... | ['def', 'OnRemove(self,', 'item):', 'i', '=', 'self.remove_menu.GetItemIndex(item)', 'assert', 'len(self.menu_items)', '<=', 'len(self.remove_menu)', 'if', 'self.remove_cb(self.seq[i]):', "LOG('removing", 'item', '%d', '(selection', 'is', "%s)',", 'i,', 'self.selection)', 'self.seq.pop(i)', 'self.remove_menu.RemoveItem... | 185,434 |
huawei-noah/xingtian | task_ops.py | TaskOps.step_name | step_name | Return general step nmae. | [
"Return",
"general",
"step",
"nmae."
] | def step_name(self):
return self._step_name | ['def', 'step_name(self):', 'return', 'self._step_name'] | 962,343 |
asyml/texar-pytorch | data_iterators.py | TrainTestDataIterator.get_val_iterator | get_val_iterator | Obtain an iterator over validation data. | [
"Obtain",
"an",
"iterator",
"over",
"validation",
"data."
] | def get_val_iterator(self) -> Iterable[Batch]:
if self._val_name not in self._datasets:
raise ValueError('Validation data not provided.')
return self.get_iterator(self._val_name) | ['def', 'get_val_iterator(self)', '->', 'Iterable[Batch]:', 'if', 'self._val_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Validation", 'data', 'not', "provided.')", 'return', 'self.get_iterator(self._val_name)'] | 925,045 |
lbkchen/deep-learning | rf3.py | LossMonitor.set_estimator | set_estimator | This function gets called in the same graph as _get_train_ops. | [
"This",
"function",
"gets",
"called",
"in",
"the",
"same",
"graph",
"as",
"_get_train_ops."
] | def set_estimator(self, est):
super(LossMonitor, self).set_estimator(est)
self._loss_op_name = est.training_loss.name | ['def', 'set_estimator(self,', 'est):', 'super(LossMonitor,', 'self).set_estimator(est)', 'self._loss_op_name', '=', 'est.training_loss.name'] | 518,660 |
pipermerriam/flex | test_min_and_max_properties.py | test_max_properties_for_invalid_types | test_max_properties_for_invalid_types | Ensure that the value of `maxProperties` is validated to be numeric. | [
"Ensure",
"that",
"the",
"value",
"of",
"`maxProperties`",
"is",
"validated",
"to",
"be",
"numeric."
] | def test_max_properties_for_invalid_types(value):
with pytest.raises(ValidationError) as err:
schema_validator({'maxProperties': value})
assert_message_in_errors(MESSAGES['type']['invalid'], err.value.detail, 'maxProperties.type') | ['def', 'test_max_properties_for_invalid_types(value):', 'with', 'pytest.raises(ValidationError)', 'as', 'err:', "schema_validator({'maxProperties':", 'value})', "assert_message_in_errors(MESSAGES['type']['invalid'],", 'err.value.detail,', "'maxProperties.type')"] | 211,341 |
mila-iqia/fuel | __init__.py | Transformer.transform_example | transform_example | Transforms a single example. | [
"Transforms",
"a",
"single",
"example."
] | def transform_example(self, example):
raise NotImplementedError('`{}` does not support examples as input, but the wrapped data stream produces examples.'.format(self.__class__.__name__)) | ['def', 'transform_example(self,', 'example):', 'raise', "NotImplementedError('`{}`", 'does', 'not', 'support', 'examples', 'as', 'input,', 'but', 'the', 'wrapped', 'data', 'stream', 'produces', "examples.'.format(self.__class__.__name__))"] | 565,447 |
zichunhao/lgn-autoencoder | utils.py | arcsinh | arcsinh | Self defined arcsinh function if torch is not up to date. | [
"Self",
"defined",
"arcsinh",
"function",
"if",
"torch",
"is",
"not",
"up",
"to",
"date."
] | def arcsinh(z: torch.Tensor) -> torch.Tensor:
return torch.log(z + torch.sqrt(1 + torch.pow(z, 2))) | ['def', 'arcsinh(z:', 'torch.Tensor)', '->', 'torch.Tensor:', 'return', 'torch.log(z', '+', 'torch.sqrt(1', '+', 'torch.pow(z,', '2)))'] | 600,330 |
StatueFungus/autonomous_driving | segment_model.py | SegmentModel.update_point_distance | update_point_distance | Methode berechnet und aktualisiert den Abstand zwischen rechten und linken Punkt (StraÃÂenmarkierung) für dieses Segment. | [
"Methode",
"berechnet",
"und",
"aktualisiert",
"den",
"Abstand",
"zwischen",
"rechten",
"und",
"linken",
"Punkt",
"(StraÃÂenmarkierung)",
"für",
"dieses",
"Segment."
] | def update_point_distance(self):
if self.left_point and self.right_point:
new_distance = self.right_point - self.left_point
self.point_distance = new_distance | ['def', 'update_point_distance(self):', 'if', 'self.left_point', 'and', 'self.right_point:', 'new_distance', '=', 'self.right_point', '-', 'self.left_point', 'self.point_distance', '=', 'new_distance'] | 420,290 |
johnathanlouie/cascaded-refinement-network | crn.py | read_temp_file | read_temp_file | This temporary file specifies from which sample to start processing if the runtime was cut short or start from the beginning if it is missing. | [
"This",
"temporary",
"file",
"specifies",
"from",
"which",
"sample",
"to",
"start",
"processing",
"if",
"the",
"runtime",
"was",
"cut",
"short",
"or",
"start",
"from",
"the",
"beginning",
"if",
"it",
"is",
"missing."
] | def read_temp_file(url):
count = (0, 0)
if os.path.isfile(url):
file = open(url, 'r')
count = tuple(map(int, file.read().split()))
file.close()
return count | ['def', 'read_temp_file(url):', 'count', '=', '(0,', '0)', 'if', 'os.path.isfile(url):', 'file', '=', 'open(url,', "'r')", 'count', '=', 'tuple(map(int,', 'file.read().split()))', 'file.close()', 'return', 'count'] | 456,268 |
ShuvenduRoy/Generative_adversarial_networks | solver.py | Solver.build_model | build_model | Create a generator and a discriminator. | [
"Create",
"a",
"generator",
"and",
"a",
"discriminator."
] | def build_model(self):
if self.dataset in ['CelebA', 'RaFD']:
self.G = Generator(self.g_conv_dim, self.c_dim, self.g_repeat_num)
self.D = Discriminator(self.image_size, self.d_conv_dim, self.c_dim, self.d_repeat_num)
elif self.dataset in ['Both']:
self.G = Generator(self.g_conv_dim, self... | ['def', 'build_model(self):', 'if', 'self.dataset', 'in', "['CelebA',", "'RaFD']:", 'self.G', '=', 'Generator(self.g_conv_dim,', 'self.c_dim,', 'self.g_repeat_num)', 'self.D', '=', 'Discriminator(self.image_size,', 'self.d_conv_dim,', 'self.c_dim,', 'self.d_repeat_num)', 'elif', 'self.dataset', 'in', "['Both']:", 'self... | 556,659 |
Ruturaj123/Flowchart-Detection | controller.py | Controller.get_from_replay_buffer | get_from_replay_buffer | Sample a batch of episodes from the replay buffer. | [
"Sample",
"a",
"batch",
"of",
"episodes",
"from",
"the",
"replay",
"buffer."
] | def get_from_replay_buffer(self, batch_size):
if self.replay_buffer is None or len(self.replay_buffer) < 1 * batch_size:
return (None, None)
desired_count = batch_size * self.max_step
while True:
if batch_size > len(self.replay_buffer):
batch_size = len(self.replay_buffer)
... | ['def', 'get_from_replay_buffer(self,', 'batch_size):', 'if', 'self.replay_buffer', 'is', 'None', 'or', 'len(self.replay_buffer)', '<', '1', '*', 'batch_size:', 'return', '(None,', 'None)', 'desired_count', '=', 'batch_size', '*', 'self.max_step', 'while', 'True:', 'if', 'batch_size', '>', 'len(self.replay_buffer):', '... | 586,253 |
weimin17/Object-Detection_HelmetDetection | dualnet.py | DualNetRunner.run | run | Compute the policy and value output for a given position. | [
"Compute",
"the",
"policy",
"and",
"value",
"output",
"for",
"a",
"given",
"position."
] | def run(self, position, use_random_symmetry=True):
(probs, values) = self.run_many([position], use_random_symmetry=use_random_symmetry)
return (probs[0], values[0]) | ['def', 'run(self,', 'position,', 'use_random_symmetry=True):', '(probs,', 'values)', '=', 'self.run_many([position],', 'use_random_symmetry=use_random_symmetry)', 'return', '(probs[0],', 'values[0])'] | 758,131 |
open-mmlab/mmdetection3d | base_box3d.py | BaseInstance3DBoxes.yaw | yaw | Tensor: A vector with yaw of each box in shape (N, ). | [
"Tensor:",
"A",
"vector",
"with",
"yaw",
"of",
"each",
"box",
"in",
"shape",
"(N,",
")."
] | def yaw(self) -> Tensor:
return self.tensor[:, 6] | ['def', 'yaw(self)', '->', 'Tensor:', 'return', 'self.tensor[:,', '6]'] | 632,228 |
nicknochnack/RealTimeSignLanguageTFJS | ddpg_agent.py | TD3Agent.value_net | value_net | Returns the output of the critic evaluated with the actor. | [
"Returns",
"the",
"output",
"of",
"the",
"critic",
"evaluated",
"with",
"the",
"actor."
] | def value_net(self, states, for_critic_loss=False):
actions = self.actor_net(states)
return self.critic_net(states, actions, for_critic_loss=for_critic_loss) | ['def', 'value_net(self,', 'states,', 'for_critic_loss=False):', 'actions', '=', 'self.actor_net(states)', 'return', 'self.critic_net(states,', 'actions,', 'for_critic_loss=for_critic_loss)'] | 851,758 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | request.py | thishost | thishost | Return the IP addresses of the current host. | [
"Return",
"the",
"IP",
"addresses",
"of",
"the",
"current",
"host."
] | def thishost():
global _thishost
if _thishost is None:
try:
_thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
except socket.gaierror:
_thishost = tuple(socket.gethostbyname_ex('localhost')[2])
return _thishost | ['def', 'thishost():', 'global', '_thishost', 'if', '_thishost', 'is', 'None:', 'try:', '_thishost', '=', 'tuple(socket.gethostbyname_ex(socket.gethostname())[2])', 'except', 'socket.gaierror:', '_thishost', '=', "tuple(socket.gethostbyname_ex('localhost')[2])", 'return', '_thishost'] | 377,199 |
KalleHallden/InstaAutomator | _tifffile.py | TiffTag.as_str | as_str | Return value as human readable string. | [
"Return",
"value",
"as",
"human",
"readable",
"string."
] | def as_str(self):
return str(self.value).split('\n', 1)[0] if self._type != 7 else '<undefined>' | ['def', 'as_str(self):', 'return', "str(self.value).split('\\n',", '1)[0]', 'if', 'self._type', '!=', '7', 'else', "'<undefined>'"] | 230,083 |
matsu0228/nlp-jp | win32_output.py | Win32Output.flush | flush | Write to output stream and flush. | [
"Write",
"to",
"output",
"stream",
"and",
"flush."
] | def flush(self):
if not self._buffer:
self.stdout.flush()
return
data = ''.join(self._buffer)
if _DEBUG_RENDER_OUTPUT:
self.LOG.write(('%r' % data).encode('utf-8') + b'\n')
self.LOG.flush()
for b in data:
written = DWORD()
retval = windll.kernel32.WriteCon... | ['def', 'flush(self):', 'if', 'not', 'self._buffer:', 'self.stdout.flush()', 'return', 'data', '=', "''.join(self._buffer)", 'if', '_DEBUG_RENDER_OUTPUT:', "self.LOG.write(('%r'", '%', "data).encode('utf-8')", '+', "b'\\n')", 'self.LOG.flush()', 'for', 'b', 'in', 'data:', 'written', '=', 'DWORD()', 'retval', '=', 'wind... | 804,594 |
intelligent-environments-lab/CityLearn | building.py | Building.energy_to_electrical_storage | energy_to_electrical_storage | Energy supply from `electrical_device` to building time series, in [kWh]. | [
"Energy",
"supply",
"from",
"`electrical_device`",
"to",
"building",
"time",
"series,",
"in",
"[kWh]."
] | def energy_to_electrical_storage(self) -> np.ndarray:
return np.array(self.electrical_storage.energy_balance, dtype=float).clip(min=0) | ['def', 'energy_to_electrical_storage(self)', '->', 'np.ndarray:', 'return', 'np.array(self.electrical_storage.energy_balance,', 'dtype=float).clip(min=0)'] | 105,311 |
matsu0228/nlp-jp | ldaseqmodel.py | LdaSeqModel.print_topic_times | print_topic_times | Prints one topic showing each time-slice. | [
"Prints",
"one",
"topic",
"showing",
"each",
"time-slice."
] | def print_topic_times(self, topic, top_terms=20):
topics = []
for time in range(0, self.num_time_slices):
topics.append(self.print_topic(topic, time, top_terms))
return topics | ['def', 'print_topic_times(self,', 'topic,', 'top_terms=20):', 'topics', '=', '[]', 'for', 'time', 'in', 'range(0,', 'self.num_time_slices):', 'topics.append(self.print_topic(topic,', 'time,', 'top_terms))', 'return', 'topics'] | 785,835 |
ericgossett/higher-order-graph-convolutional--network | validators.py | config_validator | config_validator | Checks if the config dict contains the required keys. | [
"Checks",
"if",
"the",
"config",
"dict",
"contains",
"the",
"required",
"keys."
] | def config_validator(config):
required_keys = ['name', 'batch_size', 'num_epochs', 'iterations_per_epoch', 'learning_rate', 'summary_dir', 'save_dir', 'saver_max_to_keep']
for key in required_keys:
if key not in config:
raise ConfigMissingARequiredKey("They key '{}' is missing from config di... | ['def', 'config_validator(config):', 'required_keys', '=', "['name',", "'batch_size',", "'num_epochs',", "'iterations_per_epoch',", "'learning_rate',", "'summary_dir',", "'save_dir',", "'saver_max_to_keep']", 'for', 'key', 'in', 'required_keys:', 'if', 'key', 'not', 'in', 'config:', 'raise', 'ConfigMissingARequiredKey(... | 206,507 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | holiday.py | sunday_to_monday | sunday_to_monday | If holiday falls on Sunday, use day thereafter (Monday) instead. | [
"If",
"holiday",
"falls",
"on",
"Sunday,",
"use",
"day",
"thereafter",
"(Monday)",
"instead."
] | def sunday_to_monday(dt: datetime) -> datetime:
if dt.weekday() == 6:
return dt + timedelta(1)
return dt | ['def', 'sunday_to_monday(dt:', 'datetime)', '->', 'datetime:', 'if', 'dt.weekday()', '==', '6:', 'return', 'dt', '+', 'timedelta(1)', 'return', 'dt'] | 453,933 |
scotthuang1989/object_detection_with_tensorflow | model_ptn.py | model_PTN.get_metrics | get_metrics | Aggregate the metrics for voxel generation model. | [
"Aggregate",
"the",
"metrics",
"for",
"voxel",
"generation",
"model."
] | def get_metrics(self, inputs, outputs):
names_to_values = dict()
names_to_updates = dict()
(tmp_values, tmp_updates) = metrics.add_volume_iou_metrics(inputs, outputs)
names_to_values.update(tmp_values)
names_to_updates.update(tmp_updates)
for (name, value) in names_to_values.iteritems():
... | ['def', 'get_metrics(self,', 'inputs,', 'outputs):', 'names_to_values', '=', 'dict()', 'names_to_updates', '=', 'dict()', '(tmp_values,', 'tmp_updates)', '=', 'metrics.add_volume_iou_metrics(inputs,', 'outputs)', 'names_to_values.update(tmp_values)', 'names_to_updates.update(tmp_updates)', 'for', '(name,', 'value)', 'i... | 739,510 |
Kvatsx/Artificial-Intelligence-Assignments | _tifffile.py | str2bytes | str2bytes | Return bytes from unicode string. | [
"Return",
"bytes",
"from",
"unicode",
"string."
] | def str2bytes(s, encoding='cp1252'):
return s.encode(encoding) | ['def', 'str2bytes(s,', "encoding='cp1252'):", 'return', 's.encode(encoding)'] | 37,564 |
Yuting-Gao/DisCo-pytorch | selecsls.py | selecsls42b | selecsls42b | Constructs a SelecSLS42_B model. | [
"Constructs",
"a",
"SelecSLS42_B",
"model."
] | def selecsls42b(pretrained=False, **kwargs):
return _create_selecsls('selecsls42b', pretrained, kwargs) | ['def', 'selecsls42b(pretrained=False,', '**kwargs):', 'return', "_create_selecsls('selecsls42b',", 'pretrained,', 'kwargs)'] | 186,878 |
greydanus/mr_london | wsgi.py | LimitedStream.readline | readline | Reads one line from the stream. | [
"Reads",
"one",
"line",
"from",
"the",
"stream."
] | def readline(self, size=None):
if self._pos >= self.limit:
return self.on_exhausted()
if size is None:
size = self.limit - self._pos
else:
size = min(size, self.limit - self._pos)
try:
line = self._readline(size)
except (ValueError, IOError):
return self.on_di... | ['def', 'readline(self,', 'size=None):', 'if', 'self._pos', '>=', 'self.limit:', 'return', 'self.on_exhausted()', 'if', 'size', 'is', 'None:', 'size', '=', 'self.limit', '-', 'self._pos', 'else:', 'size', '=', 'min(size,', 'self.limit', '-', 'self._pos)', 'try:', 'line', '=', 'self._readline(size)', 'except', '(ValueEr... | 264,305 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjuiItemWrapper.itemid | itemid | id of item within section. | [
"id",
"of",
"item",
"within",
"section."
] | def itemid(self):
return self._ptr.contents.itemid | ['def', 'itemid(self):', 'return', 'self._ptr.contents.itemid'] | 440,688 |
Rose-STL-Lab/DIVE | DiveModel.py | DiveModel.sample_latent_prior | sample_latent_prior | Samples latent variables from the prior distribution. | [
"Samples",
"latent",
"variables",
"from",
"the",
"prior",
"distribution."
] | def sample_latent_prior(self, input):
latent = defaultdict(lambda : None)
batch_size = input.size(0)
N = batch_size * self.n_frames_total * self.total_components
z_prior_mu = Variable(torch.zeros(N, self.appearance_latent_size).cuda())
z_prior_sigma = Variable(torch.ones(N, self.appearance_latent_si... | ['def', 'sample_latent_prior(self,', 'input):', 'latent', '=', 'defaultdict(lambda', ':', 'None)', 'batch_size', '=', 'input.size(0)', 'N', '=', 'batch_size', '*', 'self.n_frames_total', '*', 'self.total_components', 'z_prior_mu', '=', 'Variable(torch.zeros(N,', 'self.appearance_latent_size).cuda())', 'z_prior_sigma', ... | 552,224 |
Ruturaj123/Flowchart-Detection | wishart_test.py | wishart_var | wishart_var | Compute Wishart variance for numpy scale matrix. | [
"Compute",
"Wishart",
"variance",
"for",
"numpy",
"scale",
"matrix."
] | def wishart_var(df, x):
x = np.sqrt(df) * np.asarray(x)
d = np.expand_dims(np.diag(x), -1)
return x ** 2 + np.dot(d, d.T) | ['def', 'wishart_var(df,', 'x):', 'x', '=', 'np.sqrt(df)', '*', 'np.asarray(x)', 'd', '=', 'np.expand_dims(np.diag(x),', '-1)', 'return', 'x', '**', '2', '+', 'np.dot(d,', 'd.T)'] | 602,883 |
rlpy/rlpy | PolicyIteration.py | PolicyIteration.solve | solve | Solve the domain MDP. | [
"Solve",
"the",
"domain",
"MDP."
] | def solve(self):
self.bellmanUpdates = 0
self.policy_improvement_iteration = 0
self.start_time = clock()
if not self.IsTabularRepresentation():
self.logger.error('Policy Iteration works only with a tabular representation.')
return 0
policy = eGreedy(deepcopy(self.representation), eps... | ['def', 'solve(self):', 'self.bellmanUpdates', '=', '0', 'self.policy_improvement_iteration', '=', '0', 'self.start_time', '=', 'clock()', 'if', 'not', 'self.IsTabularRepresentation():', "self.logger.error('Policy", 'Iteration', 'works', 'only', 'with', 'a', 'tabular', "representation.')", 'return', '0', 'policy', '=',... | 333,857 |
triaquae/triaquae | comments.py | RenderCommentFormNode.handle_token | handle_token | Class method to parse render_comment_form and return a Node. | [
"Class",
"method",
"to",
"parse",
"render_comment_form",
"and",
"return",
"a",
"Node."
] | def handle_token(cls, parser, token):
tokens = token.contents.split()
if tokens[1] != 'for':
raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
if len(tokens) == 3:
return cls(object_expr=parser.compile_filter(tokens[2]))
elif len(tokens) == 4:
... | ['def', 'handle_token(cls,', 'parser,', 'token):', 'tokens', '=', 'token.contents.split()', 'if', 'tokens[1]', '!=', "'for':", 'raise', 'template.TemplateSyntaxError("Second', 'argument', 'in', '%r', 'tag', 'must', 'be', '\'for\'"', '%', 'tokens[0])', 'if', 'len(tokens)', '==', '3:', 'return', 'cls(object_expr=parser.c... | 357,220 |
deepmind/acme | agent_distributed_test.py | DistributedAgentTest.test_atari | test_atari | Tests that the agent can run for some steps without crashing. | [
"Tests",
"that",
"the",
"agent",
"can",
"run",
"for",
"some",
"steps",
"without",
"crashing."
] | def test_atari(self):
env_factory = lambda x: fakes.fake_atari_wrapped(oar_wrapper=True)
net_factory = lambda spec: networks.IMPALAAtariNetwork(spec.num_values)
agent = impala.DistributedIMPALA(environment_factory=env_factory, network_factory=net_factory, num_actors=2, batch_size=32, sequence_length=5, sequ... | ['def', 'test_atari(self):', 'env_factory', '=', 'lambda', 'x:', 'fakes.fake_atari_wrapped(oar_wrapper=True)', 'net_factory', '=', 'lambda', 'spec:', 'networks.IMPALAAtariNetwork(spec.num_values)', 'agent', '=', 'impala.DistributedIMPALA(environment_factory=env_factory,', 'network_factory=net_factory,', 'num_actors=2,'... | 7,708 |
hamza-murad/AALU | discovery_v1.py | DocumentCounts.from_dict | from_dict | Initialize a DocumentCounts object from a json dictionary. | [
"Initialize",
"a",
"DocumentCounts",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'DocumentCounts':
args = {}
valid_keys = ['available', 'processing', 'failed', 'pending']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class DocumentCounts: ' + ', '.join(bad_keys))
... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'DocumentCounts':", 'args', '=', '{}', 'valid_keys', '=', "['available',", "'processing',", "'failed',", "'pending']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dict... | 5,554 |
triaquae/triaquae | numbertheory.py | phi | phi | Return the Euler totient function of n. | [
"Return",
"the",
"Euler",
"totient",
"function",
"of",
"n."
] | def phi(n):
assert isinstance(n, integer_types)
if n < 3:
return 1
result = 1
ff = factorization(n)
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e - 1) * (f[0] - 1)
else:
result = result * (f[0] - 1)
return result | ['def', 'phi(n):', 'assert', 'isinstance(n,', 'integer_types)', 'if', 'n', '<', '3:', 'return', '1', 'result', '=', '1', 'ff', '=', 'factorization(n)', 'for', 'f', 'in', 'ff:', 'e', '=', 'f[1]', 'if', 'e', '>', '1:', 'result', '=', 'result', '*', 'f[0]', '**', '(e', '-', '1)', '*', '(f[0]', '-', '1)', 'else:', 'result'... | 356,409 |
google-research/scenic | metrics.py | token_accuracy | token_accuracy | Return the accuracy for LM prediction. | [
"Return",
"the",
"accuracy",
"for",
"LM",
"prediction."
] | def token_accuracy(logits, batch: JTensorDict) -> Dict[str, Tuple[float, int]]:
targets = batch['decoder_target_tokens']
vocab_size = logits.shape[-1]
onehot_targets = common_utils.onehot(targets, vocab_size)
masks = targets > 0
n_corrects = base_model_utils.weighted_correctly_classified(logits, one... | ['def', 'token_accuracy(logits,', 'batch:', 'JTensorDict)', '->', 'Dict[str,', 'Tuple[float,', 'int]]:', 'targets', '=', "batch['decoder_target_tokens']", 'vocab_size', '=', 'logits.shape[-1]', 'onehot_targets', '=', 'common_utils.onehot(targets,', 'vocab_size)', 'masks', '=', 'targets', '>', '0', 'n_corrects', '=', 'b... | 846,855 |
devashish-patel/webcam-motion-detector | utils.py | Cycler.next | next | Goes one item ahead and returns it. | [
"Goes",
"one",
"item",
"ahead",
"and",
"returns",
"it."
] | def next(self):
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv | ['def', 'next(self):', 'rv', '=', 'self.current', 'self.pos', '=', '(self.pos', '+', '1)', '%', 'len(self.items)', 'return', 'rv'] | 979,895 |
myothida/Supervised-Machine-Learning | bezierTools.py | segmentSegmentIntersections | segmentSegmentIntersections | Finds intersections between two segments. | [
"Finds",
"intersections",
"between",
"two",
"segments."
] | def segmentSegmentIntersections(seg1, seg2):
swapped = False
if len(seg2) > len(seg1):
(seg2, seg1) = (seg1, seg2)
swapped = True
if len(seg1) > 2:
if len(seg2) > 2:
intersections = curveCurveIntersections(seg1, seg2)
else:
intersections = curveLineInt... | ['def', 'segmentSegmentIntersections(seg1,', 'seg2):', 'swapped', '=', 'False', 'if', 'len(seg2)', '>', 'len(seg1):', '(seg2,', 'seg1)', '=', '(seg1,', 'seg2)', 'swapped', '=', 'True', 'if', 'len(seg1)', '>', '2:', 'if', 'len(seg2)', '>', '2:', 'intersections', '=', 'curveCurveIntersections(seg1,', 'seg2)', 'else:', 'i... | 360,944 |
sunishsheth2009/ChatterBot | expression.py | Select.append_correlation | append_correlation | append the given correlation expression to this select() construct. | [
"append",
"the",
"given",
"correlation",
"expression",
"to",
"this",
"select()",
"construct."
] | def append_correlation(self, fromclause):
self._should_correlate = False
self._correlate = self._correlate.union([fromclause]) | ['def', 'append_correlation(self,', 'fromclause):', 'self._should_correlate', '=', 'False', 'self._correlate', '=', 'self._correlate.union([fromclause])'] | 534,931 |
RL-MLDM/alphagen | test_genetic.py | test_warm_start | test_warm_start | Check the warm_start functionality works as expected. | [
"Check",
"the",
"warm_start",
"functionality",
"works",
"as",
"expected."
] | def test_warm_start():
est = SymbolicRegressor(population_size=50, generations=10, random_state=0)
est.fit(diabetes.data, diabetes.target)
cold_fitness = est._program.fitness_
cold_program = est._program.__str__()
est.set_params(generations=5, warm_start=True)
assert_raises(ValueError, est.fit, ... | ['def', 'test_warm_start():', 'est', '=', 'SymbolicRegressor(population_size=50,', 'generations=10,', 'random_state=0)', 'est.fit(diabetes.data,', 'diabetes.target)', 'cold_fitness', '=', 'est._program.fitness_', 'cold_program', '=', 'est._program.__str__()', 'est.set_params(generations=5,', 'warm_start=True)', 'assert... | 414,961 |
aimclub/FEDOT | base_preprocessing.py | BasePreprocessor.merge_preprocessors | merge_preprocessors | Combines two preprocessor's objects. | [
"Combines",
"two",
"preprocessor's",
"objects."
] | def merge_preprocessors(api_preprocessor: 'BasePreprocessor', pipeline_preprocessor: 'BasePreprocessor') -> 'BasePreprocessor':
new_data_preprocessor = api_preprocessor
if not new_data_preprocessor.features_encoders:
new_data_preprocessor.features_encoders = pipeline_preprocessor.features_encoders
r... | ['def', 'merge_preprocessors(api_preprocessor:', "'BasePreprocessor',", 'pipeline_preprocessor:', "'BasePreprocessor')", '->', "'BasePreprocessor':", 'new_data_preprocessor', '=', 'api_preprocessor', 'if', 'not', 'new_data_preprocessor.features_encoders:', 'new_data_preprocessor.features_encoders', '=', 'pipeline_prepr... | 545,967 |
deepmind/dm_control | transformations.py | quat_to_mat | quat_to_mat | Return homogeneous rotation matrix from quaternion. | [
"Return",
"homogeneous",
"rotation",
"matrix",
"from",
"quaternion."
] | def quat_to_mat(quat):
q = np.array(quat, dtype=np.float64, copy=True)
nq = np.dot(q, q)
if nq < _TOL:
return np.identity(4)
q *= np.sqrt(2.0 / nq)
q = np.outer(q, q)
return np.array(((1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0], 0.0), (q[1, 2] + q[3, 0], 1.0 - q[1, 1] ... | ['def', 'quat_to_mat(quat):', 'q', '=', 'np.array(quat,', 'dtype=np.float64,', 'copy=True)', 'nq', '=', 'np.dot(q,', 'q)', 'if', 'nq', '<', '_TOL:', 'return', 'np.identity(4)', 'q', '*=', 'np.sqrt(2.0', '/', 'nq)', 'q', '=', 'np.outer(q,', 'q)', 'return', 'np.array(((1.0', '-', 'q[2,', '2]', '-', 'q[3,', '3],', 'q[1,',... | 166,526 |
BlissChapman/ICW-fMRI-GAN | cluster.py | magic | magic | Execute a full clustering analysis pipeline. | [
"Execute",
"a",
"full",
"clustering",
"analysis",
"pipeline."
] | def magic(dataset, method='coactivation', roi_mask=None, coactivation_mask=None, features=None, feature_threshold=0.05, min_voxels_per_study=None, min_studies_per_voxel=None, reduce_reference='pca', n_components=100, distance_metric='correlation', clustering_algorithm='kmeans', n_clusters=5, clustering_kwargs={}, outpu... | ['def', 'magic(dataset,', "method='coactivation',", 'roi_mask=None,', 'coactivation_mask=None,', 'features=None,', 'feature_threshold=0.05,', 'min_voxels_per_study=None,', 'min_studies_per_voxel=None,', "reduce_reference='pca',", 'n_components=100,', "distance_metric='correlation',", "clustering_algorithm='kmeans',", '... | 597,038 |
segmind/cral | core.py | ClassificationPipe.train | train | This function starts the training loop, with metric logging enabled. | [
"This",
"function",
"starts",
"the",
"training",
"loop,",
"with",
"metric",
"logging",
"enabled."
] | def train(self, num_epochs, snapshot_prefix, snapshot_path, snapshot_every_n, batch_size=2, validation_batch_size=None, validate_every_n=1, callbacks=[], steps_per_epoch=None, compile_options=None, log_evry_n_step=100):
assert isinstance(num_epochs, int), 'num epochs to run should be in `int`'
assert os.path.is... | ['def', 'train(self,', 'num_epochs,', 'snapshot_prefix,', 'snapshot_path,', 'snapshot_every_n,', 'batch_size=2,', 'validation_batch_size=None,', 'validate_every_n=1,', 'callbacks=[],', 'steps_per_epoch=None,', 'compile_options=None,', 'log_evry_n_step=100):', 'assert', 'isinstance(num_epochs,', 'int),', "'num", 'epochs... | 490,649 |
RLE-Foundation/rllte | prioritized_replay_storage.py | PrioritizedReplayStorage.sample | sample | Sample from the storage. | [
"Sample",
"from",
"the",
"storage."
] | def sample(self) -> PrioritizedReplayBatch:
if len(self.transitions) == self.storage_size:
priorities = self.priorities
else:
priorities = self.priorities[:self.step]
probs = priorities ** self.alpha
probs /= probs.sum()
indices = np.random.choice(len(self.transitions), self.batch_si... | ['def', 'sample(self)', '->', 'PrioritizedReplayBatch:', 'if', 'len(self.transitions)', '==', 'self.storage_size:', 'priorities', '=', 'self.priorities', 'else:', 'priorities', '=', 'self.priorities[:self.step]', 'probs', '=', 'priorities', '**', 'self.alpha', 'probs', '/=', 'probs.sum()', 'indices', '=', 'np.random.ch... | 333,620 |
scikit-learn/scikit-learn | test_predict_error_display.py | test_prediction_error_display_raise_error | test_prediction_error_display_raise_error | Check that we raise the proper error when making the parameters # validation. | [
"Check",
"that",
"we",
"raise",
"the",
"proper",
"error",
"when",
"making",
"the",
"parameters",
"#",
"validation."
] | def test_prediction_error_display_raise_error(pyplot, class_method, regressor, params, err_type, err_msg):
with pytest.raises(err_type, match=err_msg):
if class_method == 'from_estimator':
PredictionErrorDisplay.from_estimator(regressor, X, y, **params)
else:
y_pred = regress... | ['def', 'test_prediction_error_display_raise_error(pyplot,', 'class_method,', 'regressor,', 'params,', 'err_type,', 'err_msg):', 'with', 'pytest.raises(err_type,', 'match=err_msg):', 'if', 'class_method', '==', "'from_estimator':", 'PredictionErrorDisplay.from_estimator(regressor,', 'X,', 'y,', '**params)', 'else:', 'y... | 853,740 |
KalleHallden/InstaAutomator | util.py | ImageList.meta | meta | The dict with the meta data of this image. | [
"The",
"dict",
"with",
"the",
"meta",
"data",
"of",
"this",
"image."
] | def meta(self):
return self._meta | ['def', 'meta(self):', 'return', 'self._meta'] | 229,945 |
open-mmlab/mmdetection3d | base_box3d.py | BaseInstance3DBoxes.points_in_boxes_part | points_in_boxes_part | Find the box in which each point is. | [
"Find",
"the",
"box",
"in",
"which",
"each",
"point",
"is."
] | def points_in_boxes_part(self, points: Tensor, boxes_override: Optional[Tensor]=None) -> Tensor:
if boxes_override is not None:
boxes = boxes_override
else:
boxes = self.tensor
points_clone = points.clone()[..., :3]
if points_clone.dim() == 2:
points_clone = points_clone.unsqueez... | ['def', 'points_in_boxes_part(self,', 'points:', 'Tensor,', 'boxes_override:', 'Optional[Tensor]=None)', '->', 'Tensor:', 'if', 'boxes_override', 'is', 'not', 'None:', 'boxes', '=', 'boxes_override', 'else:', 'boxes', '=', 'self.tensor', 'points_clone', '=', 'points.clone()[...,', ':3]', 'if', 'points_clone.dim()', '==... | 632,258 |
aws/sagemaker-python-sdk | processing.py | ProcessingJob.prepare_stopping_condition | prepare_stopping_condition | Prepares a dict that represents the job's StoppingCondition. | [
"Prepares",
"a",
"dict",
"that",
"represents",
"the",
"job's",
"StoppingCondition."
] | def prepare_stopping_condition(max_runtime_in_seconds):
return {'MaxRuntimeInSeconds': max_runtime_in_seconds} | ['def', 'prepare_stopping_condition(max_runtime_in_seconds):', 'return', "{'MaxRuntimeInSeconds':", 'max_runtime_in_seconds}'] | 829,562 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.