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 |
|---|---|---|---|---|---|---|---|---|
triaquae/triaquae | srs.py | SpatialReference.inverse_flattening | inverse_flattening | Returns the Inverse Flattening for this Spatial Reference. | [
"Returns",
"the",
"Inverse",
"Flattening",
"for",
"this",
"Spatial",
"Reference."
] | def inverse_flattening(self):
return capi.invflattening(self.ptr, byref(c_int())) | ['def', 'inverse_flattening(self):', 'return', 'capi.invflattening(self.ptr,', 'byref(c_int()))'] | 357,652 |
mlogic/capes-oss | LustreGame.py | Lustre.observe_from_db | observe_from_db | Return observation vector using ReplayDB. | [
"Return",
"observation",
"vector",
"using",
"ReplayDB."
] | def observe_from_db(self) -> np.ndarray:
return self.db.get_last_n_observation()[0] | ['def', 'observe_from_db(self)', '->', 'np.ndarray:', 'return', 'self.db.get_last_n_observation()[0]'] | 108,987 |
RLE-Foundation/rllte | squashed_normal.py | SquashedNormal.log_prob | log_prob | Scores the sample by inverting the transform(s) and computing the score using the score of the base distribution and the log abs det jacobian. | [
"Scores",
"the",
"sample",
"by",
"inverting",
"the",
"transform(s)",
"and",
"computing",
"the",
"score",
"using",
"the",
"score",
"of",
"the",
"base",
"distribution",
"and",
"the",
"log",
"abs",
"det",
"jacobian."
] | def log_prob(self, actions: th.Tensor) -> th.Tensor:
return self.dist.log_prob(actions) | ['def', 'log_prob(self,', 'actions:', 'th.Tensor)', '->', 'th.Tensor:', 'return', 'self.dist.log_prob(actions)'] | 333,671 |
omonimus1/super-computer- | collector.py | LinkCollector.fetch_page | fetch_page | Fetch an HTML page containing package links. | [
"Fetch",
"an",
"HTML",
"page",
"containing",
"package",
"links."
] | def fetch_page(self, location):
return _get_html_page(location, session=self.session) | ['def', 'fetch_page(self,', 'location):', 'return', '_get_html_page(location,', 'session=self.session)'] | 913,104 |
enuguru/artificial_intelligence_and_machine_ | plugins.py | OperatorsPlugin.do_operators | do_operators | This filter finds PrefixOperator, PostfixOperator, and InfixOperator nodes in the tree and calls their logic to rearrange the nodes. | [
"This",
"filter",
"finds",
"PrefixOperator,",
"PostfixOperator,",
"and",
"InfixOperator",
"nodes",
"in",
"the",
"tree",
"and",
"calls",
"their",
"logic",
"to",
"rearrange",
"the",
"nodes."
] | def do_operators(self, parser, group):
for (tagger, _) in self.ops:
optype = tagger.optype
gtype = tagger.grouptype
if tagger.leftassoc:
i = 0
while i < len(group):
t = group[i]
if isinstance(t, optype) and t.grouptype is gtype:
... | ['def', 'do_operators(self,', 'parser,', 'group):', 'for', '(tagger,', '_)', 'in', 'self.ops:', 'optype', '=', 'tagger.optype', 'gtype', '=', 'tagger.grouptype', 'if', 'tagger.leftassoc:', 'i', '=', '0', 'while', 'i', '<', 'len(group):', 't', '=', 'group[i]', 'if', 'isinstance(t,', 'optype)', 'and', 't.grouptype', 'is'... | 162,666 |
yinyunie/ScenePriors | test_render_meshes.py | TestRenderMeshes.test_joined_spheres | test_joined_spheres | Test a list of Meshes can be joined as a single mesh and the single mesh is rendered correctly with Phong, Gouraud and Flat Shaders. | [
"Test",
"a",
"list",
"of",
"Meshes",
"can",
"be",
"joined",
"as",
"a",
"single",
"mesh",
"and",
"the",
"single",
"mesh",
"is",
"rendered",
"correctly",
"with",
"Phong,",
"Gouraud",
"and",
"Flat",
"Shaders."
] | def test_joined_spheres(self):
device = torch.device('cuda:0')
sphere_list = [ico_sphere(3, device), ico_sphere(4, device)]
scales = [0.25, 1]
offsets = [1.2, -0.3]
sphere_mesh_list = []
for i in range(len(sphere_list)):
verts = sphere_list[i].verts_padded() * scales[i]
verts[0, ... | ['def', 'test_joined_spheres(self):', 'device', '=', "torch.device('cuda:0')", 'sphere_list', '=', '[ico_sphere(3,', 'device),', 'ico_sphere(4,', 'device)]', 'scales', '=', '[0.25,', '1]', 'offsets', '=', '[1.2,', '-0.3]', 'sphere_mesh_list', '=', '[]', 'for', 'i', 'in', 'range(len(sphere_list)):', 'verts', '=', 'spher... | 330,119 |
enuguru/artificial_intelligence_and_machine_ | git.py | generate_authors | generate_authors | Create AUTHORS file using git commits. | [
"Create",
"AUTHORS",
"file",
"using",
"git",
"commits."
] | def generate_authors(git_dir=None, dest_dir='.', option_dict=dict()):
should_skip = options.get_boolean_option(option_dict, 'skip_authors', 'SKIP_GENERATE_AUTHORS')
if should_skip:
return
start = time.time()
old_authors = os.path.join(dest_dir, 'AUTHORS.in')
new_authors = os.path.join(dest_d... | ['def', 'generate_authors(git_dir=None,', "dest_dir='.',", 'option_dict=dict()):', 'should_skip', '=', 'options.get_boolean_option(option_dict,', "'skip_authors',", "'SKIP_GENERATE_AUTHORS')", 'if', 'should_skip:', 'return', 'start', '=', 'time.time()', 'old_authors', '=', 'os.path.join(dest_dir,', "'AUTHORS.in')", 'ne... | 159,628 |
dibyaghosh/gcsl | hardware_robot.py | HardwareRobotComponent.time | time | Returns the time (total sum of timesteps) since the last reset. | [
"Returns",
"the",
"time",
"(total",
"sum",
"of",
"timesteps)",
"since",
"the",
"last",
"reset."
] | def time(self) -> float:
return self._time | ['def', 'time(self)', '->', 'float:', 'return', 'self._time'] | 201,754 |
allenai/deepfigures-open | test_renderers.py | PDFRendererSubclassTestMixin.test_uses_cache | test_uses_cache | Test that the rendered uses existing copies of the files. | [
"Test",
"that",
"the",
"rendered",
"uses",
"existing",
"copies",
"of",
"the",
"files."
] | def test_uses_cache(self):
ext = 'png'
with self.setup_and_teardown(ext=ext):
self.pdf_renderer.render(pdf_path=self.pdf_path, output_dir=self.tmp_output_dir, ext=ext, check_retcode=True)
output_dir_paths = [os.path.join(dir_path, file_name) for (dir_path, dir_names, file_names) in os.walk(self.... | ['def', 'test_uses_cache(self):', 'ext', '=', "'png'", 'with', 'self.setup_and_teardown(ext=ext):', 'self.pdf_renderer.render(pdf_path=self.pdf_path,', 'output_dir=self.tmp_output_dir,', 'ext=ext,', 'check_retcode=True)', 'output_dir_paths', '=', '[os.path.join(dir_path,', 'file_name)', 'for', '(dir_path,', 'dir_names,... | 520,495 |
hitchtest/hitch | commandline.py | init | init | Initialize hitch in this directory. | [
"Initialize",
"hitch",
"in",
"this",
"directory."
] | def init(python, virtualenv):
if virtualenv is None:
if call(['which', 'virtualenv'], stdout=PIPE, stderr=PIPE) != 0:
stderr.write(languagestrings.YOU_MUST_HAVE_VIRTUALENV_INSTALLED)
stderr.flush()
exit(1)
virtualenv = check_output(['which', 'virtualenv']).decode(... | ['def', 'init(python,', 'virtualenv):', 'if', 'virtualenv', 'is', 'None:', 'if', "call(['which',", "'virtualenv'],", 'stdout=PIPE,', 'stderr=PIPE)', '!=', '0:', 'stderr.write(languagestrings.YOU_MUST_HAVE_VIRTUALENV_INSTALLED)', 'stderr.flush()', 'exit(1)', 'virtualenv', '=', "check_output(['which',", "'virtualenv']).d... | 206,542 |
sanujkul/Artificial-Intelligence | search.py | exact_sqrt | exact_sqrt | If n2 is a perfect square, return its square root, else raise error. | [
"If",
"n2",
"is",
"a",
"perfect",
"square,",
"return",
"its",
"square",
"root,",
"else",
"raise",
"error."
] | def exact_sqrt(n2):
n = int(np.sqrt(n2))
assert n * n == n2
return n | ['def', 'exact_sqrt(n2):', 'n', '=', 'int(np.sqrt(n2))', 'assert', 'n', '*', 'n', '==', 'n2', 'return', 'n'] | 118,287 |
Farama-Foundation/Shimmy | atari_env.py | AtariEnv.clone_full_state | clone_full_state | Deprecated method which would clone the emulator and system state. | [
"Deprecated",
"method",
"which",
"would",
"clone",
"the",
"emulator",
"and",
"system",
"state."
] | def clone_full_state(self) -> ale_py.ALEState:
logger.warn('`clone_full_state()` is deprecated and will be removed in a future release of `ale-py`. Please use `clone_state(include_rng=True)` which is equivalent to `clone_full_state`. ')
return self.ale.cloneSystemState() | ['def', 'clone_full_state(self)', '->', 'ale_py.ALEState:', "logger.warn('`clone_full_state()`", 'is', 'deprecated', 'and', 'will', 'be', 'removed', 'in', 'a', 'future', 'release', 'of', '`ale-py`.', 'Please', 'use', '`clone_state(include_rng=True)`', 'which', 'is', 'equivalent', 'to', '`clone_full_state`.', "')", 'ret... | 900,993 |
enuguru/artificial_intelligence_and_machine_learning | doctest.py | DocTestRunner.report_unexpected_exception | report_unexpected_exception | Report that the given example raised an unexpected exception. | [
"Report",
"that",
"the",
"given",
"example",
"raised",
"an",
"unexpected",
"exception."
] | def report_unexpected_exception(self, out, test, example, exc_info):
out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) | ['def', 'report_unexpected_exception(self,', 'out,', 'test,', 'example,', 'exc_info):', 'out(self._failure_header(test,', 'example)', '+', "'Exception", "raised:\\n'", '+', '_indent(_exception_traceback(exc_info)))'] | 131,700 |
NoGameNoLife00/mybolg | itsdangerous.py | Serializer.load | load | Like :meth:`loads` but loads from a file. | [
"Like",
":meth:`loads`",
"but",
"loads",
"from",
"a",
"file."
] | def load(self, f, salt=None):
return self.loads(f.read(), salt) | ['def', 'load(self,', 'f,', 'salt=None):', 'return', 'self.loads(f.read(),', 'salt)'] | 289,084 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | Text2TextProblem.dataset_splits | dataset_splits | Splits of data to produce and number of output shards for each. | [
"Splits",
"of",
"data",
"to",
"produce",
"and",
"number",
"of",
"output",
"shards",
"for",
"each."
] | def dataset_splits(self):
return [{'split': problem.DatasetSplit.TRAIN, 'shards': 100}, {'split': problem.DatasetSplit.EVAL, 'shards': 1}] | ['def', 'dataset_splits(self):', 'return', "[{'split':", 'problem.DatasetSplit.TRAIN,', "'shards':", '100},', "{'split':", 'problem.DatasetSplit.EVAL,', "'shards':", '1}]'] | 965,003 |
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations | models.py | nature_cnn | nature_cnn | CNN from Nature paper. | [
"CNN",
"from",
"Nature",
"paper."
] | def nature_cnn(unscaled_images, **conv_kwargs):
scaled_images = tf.cast(unscaled_images, tf.float32) / 255.0
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2), **conv_kwargs))
h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_... | ['def', 'nature_cnn(unscaled_images,', '**conv_kwargs):', 'scaled_images', '=', 'tf.cast(unscaled_images,', 'tf.float32)', '/', '255.0', 'activ', '=', 'tf.nn.relu', 'h', '=', 'activ(conv(scaled_images,', "'c1',", 'nf=32,', 'rf=8,', 'stride=4,', 'init_scale=np.sqrt(2),', '**conv_kwargs))', 'h2', '=', 'activ(conv(h,', "'... | 432,440 |
shery322/Lunar-Lander-ANN | cdrom_test.py | CDROMModuleTest.test_init | test_init | Ensure module still initialized after multiple init() calls. | [
"Ensure",
"module",
"still",
"initialized",
"after",
"multiple",
"init()",
"calls."
] | def test_init(self):
pygame.cdrom.init()
pygame.cdrom.init()
self.assertTrue(pygame.cdrom.get_init()) | ['def', 'test_init(self):', 'pygame.cdrom.init()', 'pygame.cdrom.init()', 'self.assertTrue(pygame.cdrom.get_init())'] | 618,894 |
OpenMDAO/OpenMDAO-Framework | hasparameters.py | ParameterBase.get_referenced_compnames | get_referenced_compnames | Return a set of Component names based on the pathnames of Variables referenced in our target string. | [
"Return",
"a",
"set",
"of",
"Component",
"names",
"based",
"on",
"the",
"pathnames",
"of",
"Variables",
"referenced",
"in",
"our",
"target",
"string."
] | def get_referenced_compnames(self):
return self._expreval.get_referenced_compnames() | ['def', 'get_referenced_compnames(self):', 'return', 'self._expreval.get_referenced_compnames()'] | 275,775 |
sshleifer/object_detection_kitti | block_base.py | CreateBlockUpdates | CreateBlockUpdates | Combines all updates from the blocks in the graph. | [
"Combines",
"all",
"updates",
"from",
"the",
"blocks",
"in",
"the",
"graph."
] | def CreateBlockUpdates():
stack = _block_stacks[tf.get_default_graph()]
if not stack:
return []
return stack[0].CreateUpdateOps() | ['def', 'CreateBlockUpdates():', 'stack', '=', '_block_stacks[tf.get_default_graph()]', 'if', 'not', 'stack:', 'return', '[]', 'return', 'stack[0].CreateUpdateOps()'] | 794,673 |
devashish-patel/webcam-motion-detector | buffer_mapping.py | BufferMapping.pop_focus | pop_focus | Pop buffer from the focus stack. | [
"Pop",
"buffer",
"from",
"the",
"focus",
"stack."
] | def pop_focus(self, cli):
if len(self.focus_stack) > 1:
self.focus_stack.pop()
else:
raise IndexError('Cannot pop last item from the focus stack.') | ['def', 'pop_focus(self,', 'cli):', 'if', 'len(self.focus_stack)', '>', '1:', 'self.focus_stack.pop()', 'else:', 'raise', "IndexError('Cannot", 'pop', 'last', 'item', 'from', 'the', 'focus', "stack.')"] | 983,695 |
Eric3911/OpenAGI | app_state.py | AppState.model_parallel_size | model_parallel_size | Property sets the number of GPUs in each model parallel group. | [
"Property",
"sets",
"the",
"number",
"of",
"GPUs",
"in",
"each",
"model",
"parallel",
"group."
] | def model_parallel_size(self, size):
self._model_parallel_size = size | ['def', 'model_parallel_size(self,', 'size):', 'self._model_parallel_size', '=', 'size'] | 274,106 |
intel/neural-compressor | pythonic_config.py | AccuracyCriterion.absolute | absolute | Set tolerable_loss and criterion to absolute. | [
"Set",
"tolerable_loss",
"and",
"criterion",
"to",
"absolute."
] | def absolute(self, absolute):
self.criterion = 'absolute'
self.tolerable_loss = absolute | ['def', 'absolute(self,', 'absolute):', 'self.criterion', '=', "'absolute'", 'self.tolerable_loss', '=', 'absolute'] | 738,234 |
liber145/rlpack | base.py | Base.save_model | save_model | Save model to `save_path`. | [
"Save",
"model",
"to",
"`save_path`."
] | def save_model(self):
save_dir = os.path.join(self.save_path, 'model')
os.makedirs(save_dir, exist_ok=True)
global_step = self.sess.run(tf.train.get_global_step())
self.saver.save(self.sess, os.path.join(save_dir, 'model'), global_step, write_meta_graph=True) | ['def', 'save_model(self):', 'save_dir', '=', 'os.path.join(self.save_path,', "'model')", 'os.makedirs(save_dir,', 'exist_ok=True)', 'global_step', '=', 'self.sess.run(tf.train.get_global_step())', 'self.saver.save(self.sess,', 'os.path.join(save_dir,', "'model'),", 'global_step,', 'write_meta_graph=True)'] | 825,068 |
voxel51/fiftyone | base.py | ResponsivePlot.connect | connect | Connects this plot, if necessary. | [
"Connects",
"this",
"plot,",
"if",
"necessary."
] | def connect(self):
if self.is_connected:
return
if self.is_frozen:
self._reopen()
self._frozen = False
self._connect()
self._connected = True
self._disconnected = False | ['def', 'connect(self):', 'if', 'self.is_connected:', 'return', 'if', 'self.is_frozen:', 'self._reopen()', 'self._frozen', '=', 'False', 'self._connect()', 'self._connected', '=', 'True', 'self._disconnected', '=', 'False'] | 583,602 |
Feaxure-fresh/TL-Bearing-Fault-Diagnosis | XJTU_op.py | data_load | data_load | This function is mainly used to generate test data and training data. | [
"This",
"function",
"is",
"mainly",
"used",
"to",
"generate",
"test",
"data",
"and",
"training",
"data."
] | def data_load(filename, label, data, lab):
fl = pd.read_csv(filename)
fl = fl['Horizontal_vibration_signals']
fl = fl.values
fl = fl.reshape(-1, 1)
(start, end) = (0, signal_size)
while end <= fl.shape[0]:
data.append(fl[start:end])
lab.append(label)
start += signal_size
... | ['def', 'data_load(filename,', 'label,', 'data,', 'lab):', 'fl', '=', 'pd.read_csv(filename)', 'fl', '=', "fl['Horizontal_vibration_signals']", 'fl', '=', 'fl.values', 'fl', '=', 'fl.reshape(-1,', '1)', '(start,', 'end)', '=', '(0,', 'signal_size)', 'while', 'end', '<=', 'fl.shape[0]:', 'data.append(fl[start:end])', 'l... | 917,482 |
nosmokingbandit/watcher | plugins.py | Monitor.start | start | Start our callback in its own background thread. | [
"Start",
"our",
"callback",
"in",
"its",
"own",
"background",
"thread."
] | def start(self):
if self.frequency > 0:
threadname = self.name or self.__class__.__name__
if self.thread is None:
self.thread = BackgroundTask(self.frequency, self.callback, bus=self.bus)
self.thread.setName(threadname)
self.thread.start()
self.bus.log... | ['def', 'start(self):', 'if', 'self.frequency', '>', '0:', 'threadname', '=', 'self.name', 'or', 'self.__class__.__name__', 'if', 'self.thread', 'is', 'None:', 'self.thread', '=', 'BackgroundTask(self.frequency,', 'self.callback,', 'bus=self.bus)', 'self.thread.setName(threadname)', 'self.thread.start()', "self.bus.log... | 381,509 |
vikrant7/mobile-vod-bottleneck-lstm | box_utils_numpy.py | iou_of | iou_of | Return intersection-over-union (Jaccard index) of boxes. | [
"Return",
"intersection-over-union",
"(Jaccard",
"index)",
"of",
"boxes."
] | def iou_of(boxes0, boxes1, eps=1e-05):
overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2])
overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:])
overlap_area = area_of(overlap_left_top, overlap_right_bottom)
area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
area1 = area_of(... | ['def', 'iou_of(boxes0,', 'boxes1,', 'eps=1e-05):', 'overlap_left_top', '=', 'np.maximum(boxes0[...,', ':2],', 'boxes1[...,', ':2])', 'overlap_right_bottom', '=', 'np.minimum(boxes0[...,', '2:],', 'boxes1[...,', '2:])', 'overlap_area', '=', 'area_of(overlap_left_top,', 'overlap_right_bottom)', 'area0', '=', 'area_of(bo... | 626,287 |
Rock-100/MonoDet | caffe2_modeling.py | Caffe2MetaArch.get_caffe2_inputs | get_caffe2_inputs | Convert pytorch-style structured inputs to caffe2-style inputs that are tuples of tensors. | [
"Convert",
"pytorch-style",
"structured",
"inputs",
"to",
"caffe2-style",
"inputs",
"that",
"are",
"tuples",
"of",
"tensors."
] | def get_caffe2_inputs(self, batched_inputs):
return convert_batched_inputs_to_c2_format(batched_inputs, self._wrapped_model.backbone.size_divisibility, self._wrapped_model.device) | ['def', 'get_caffe2_inputs(self,', 'batched_inputs):', 'return', 'convert_batched_inputs_to_c2_format(batched_inputs,', 'self._wrapped_model.backbone.size_divisibility,', 'self._wrapped_model.device)'] | 654,869 |
michaelchen110/Grammar-Correction | bert.py | read_examples | read_examples | Read a list of `InputExample`s from an input file. | [
"Read",
"a",
"list",
"of",
"`InputExample`s",
"from",
"an",
"input",
"file."
] | def read_examples(input_file):
examples = []
unique_id = 0
with open(input_file, 'r', encoding='utf-8') as reader:
while True:
line = reader.readline()
if not line:
break
line = line.strip()
text_a = None
text_b = None
... | ['def', 'read_examples(input_file):', 'examples', '=', '[]', 'unique_id', '=', '0', 'with', 'open(input_file,', "'r',", "encoding='utf-8')", 'as', 'reader:', 'while', 'True:', 'line', '=', 'reader.readline()', 'if', 'not', 'line:', 'break', 'line', '=', 'line.strip()', 'text_a', '=', 'None', 'text_b', '=', 'None', 'm',... | 579,011 |
DYZhang09/SAM3D | convert_votenet_checkpoints.py | parse_config | parse_config | Parse config from strings. | [
"Parse",
"config",
"from",
"strings."
] | def parse_config(config_strings):
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
f.write(config_strings)
config = Config.fromfile(config_path)
if 'pool_mod' in config.model.backbone:
config.model.backbone.pop('pool_mod... | ['def', 'parse_config(config_strings):', 'temp_file', '=', 'tempfile.NamedTemporaryFile()', 'config_path', '=', "f'{temp_file.name}.py'", 'with', 'open(config_path,', "'w')", 'as', 'f:', 'f.write(config_strings)', 'config', '=', 'Config.fromfile(config_path)', 'if', "'pool_mod'", 'in', 'config.model.backbone:', "config... | 845,236 |
sunishsheth2009/ChatterBot | serving.py | make_server | make_server | Create a new server instance that is either threaded, or forks or just processes one request after another. | [
"Create",
"a",
"new",
"server",
"instance",
"that",
"is",
"either",
"threaded,",
"or",
"forks",
"or",
"just",
"processes",
"one",
"request",
"after",
"another."
] | def make_server(host, port, app=None, threaded=False, processes=1, request_handler=None, passthrough_errors=False, ssl_context=None):
if threaded and processes > 1:
raise ValueError('cannot have a multithreaded and multi process server.')
elif threaded:
return ThreadedWSGIServer(host, port, app,... | ['def', 'make_server(host,', 'port,', 'app=None,', 'threaded=False,', 'processes=1,', 'request_handler=None,', 'passthrough_errors=False,', 'ssl_context=None):', 'if', 'threaded', 'and', 'processes', '>', '1:', 'raise', "ValueError('cannot", 'have', 'a', 'multithreaded', 'and', 'multi', 'process', "server.')", 'elif', ... | 483,344 |
weimin17/Object-Detection_HelmetDetection | datasets.py | random_binary | random_binary | Returns a randomly generated dataset of binary values. | [
"Returns",
"a",
"randomly",
"generated",
"dataset",
"of",
"binary",
"values."
] | def random_binary(n_features, n_samples, random_seed=None):
random_seed = np.random.randint(MAX_SEED) if random_seed is None else random_seed
np.random.seed(random_seed)
x = np.random.randint(2, size=(n_samples, n_features))
y = np.zeros((n_samples, 1))
return Dataset(x.astype('float32'), y.astype('... | ['def', 'random_binary(n_features,', 'n_samples,', 'random_seed=None):', 'random_seed', '=', 'np.random.randint(MAX_SEED)', 'if', 'random_seed', 'is', 'None', 'else', 'random_seed', 'np.random.seed(random_seed)', 'x', '=', 'np.random.randint(2,', 'size=(n_samples,', 'n_features))', 'y', '=', 'np.zeros((n_samples,', '1)... | 763,270 |
Prarthana25/Artificial-Intelligence | utils.py | dot_product | dot_product | Return the sum of the element-wise product of vectors x and y. | [
"Return",
"the",
"sum",
"of",
"the",
"element-wise",
"product",
"of",
"vectors",
"x",
"and",
"y."
] | def dot_product(x, y):
return sum((_x * _y for (_x, _y) in zip(x, y))) | ['def', 'dot_product(x,', 'y):', 'return', 'sum((_x', '*', '_y', 'for', '(_x,', '_y)', 'in', 'zip(x,', 'y)))'] | 119,798 |
voxel51/fiftyone | stages.py | Select.sample_ids | sample_ids | The list of sample IDs to select. | [
"The",
"list",
"of",
"sample",
"IDs",
"to",
"select."
] | def sample_ids(self):
return self._sample_ids | ['def', 'sample_ids(self):', 'return', 'self._sample_ids'] | 583,340 |
rudranil723/mini-main | __init__.py | Stack.forward | forward | Move the position forward and return the current element. | [
"Move",
"the",
"position",
"forward",
"and",
"return",
"the",
"current",
"element."
] | def forward(self):
self._pos = min(self._pos + 1, len(self._elements) - 1)
return self() | ['def', 'forward(self):', 'self._pos', '=', 'min(self._pos', '+', '1,', 'len(self._elements)', '-', '1)', 'return', 'self()'] | 320,084 |
bhateharsh/computer_vision | image_iter.py | FaceImageIter.reset | reset | Resets the iterator to the beginning of the data. | [
"Resets",
"the",
"iterator",
"to",
"the",
"beginning",
"of",
"the",
"data."
] | def reset(self):
print('call reset()')
self.cur = 0
if self.shuffle:
random.shuffle(self.seq)
if self.seq is None and self.imgrec is not None:
self.imgrec.reset() | ['def', 'reset(self):', "print('call", "reset()')", 'self.cur', '=', '0', 'if', 'self.shuffle:', 'random.shuffle(self.seq)', 'if', 'self.seq', 'is', 'None', 'and', 'self.imgrec', 'is', 'not', 'None:', 'self.imgrec.reset()'] | 500,648 |
ludwig-ai/ludwig | explanation.py | Explanation.to_array | to_array | Convert the explanation to a 2D array of shape (num_labels, num_features). | [
"Convert",
"the",
"explanation",
"to",
"a",
"2D",
"array",
"of",
"shape",
"(num_labels,",
"num_features)."
] | def to_array(self) -> npt.NDArray[np.float64]:
return np.array([le.to_array() for le in self.label_explanations]) | ['def', 'to_array(self)', '->', 'npt.NDArray[np.float64]:', 'return', 'np.array([le.to_array()', 'for', 'le', 'in', 'self.label_explanations])'] | 616,772 |
feast-dev/feast | registry_diff.py | diff_between | diff_between | Returns the difference between the current and desired repo states. | [
"Returns",
"the",
"difference",
"between",
"the",
"current",
"and",
"desired",
"repo",
"states."
] | def diff_between(registry: BaseRegistry, current_project: str, desired_repo_contents: RepoContents) -> RegistryDiff:
diff = RegistryDiff()
(objs_to_keep, objs_to_delete, objs_to_update, objs_to_add) = extract_objects_for_keep_delete_update_add(registry, current_project, desired_repo_contents)
for object_typ... | ['def', 'diff_between(registry:', 'BaseRegistry,', 'current_project:', 'str,', 'desired_repo_contents:', 'RepoContents)', '->', 'RegistryDiff:', 'diff', '=', 'RegistryDiff()', '(objs_to_keep,', 'objs_to_delete,', 'objs_to_update,', 'objs_to_add)', '=', 'extract_objects_for_keep_delete_update_add(registry,', 'current_pr... | 544,317 |
apple/ml-cvnets | checkpoint_utils.py | save_checkpoint | save_checkpoint | Save checkpoints corresponding to the current state of the training. | [
"Save",
"checkpoints",
"corresponding",
"to",
"the",
"current",
"state",
"of",
"the",
"training."
] | def save_checkpoint(iterations: int, epoch: int, model: torch.nn.Module, optimizer: Union[BaseOptim, torch.optim.Optimizer], best_metric: float, is_best: bool, save_dir: str, gradient_scaler: torch.cuda.amp.GradScaler, model_ema: Optional[torch.nn.Module]=None, is_ema_best: bool=False, ema_best_metric: Optional[float]=... | ['def', 'save_checkpoint(iterations:', 'int,', 'epoch:', 'int,', 'model:', 'torch.nn.Module,', 'optimizer:', 'Union[BaseOptim,', 'torch.optim.Optimizer],', 'best_metric:', 'float,', 'is_best:', 'bool,', 'save_dir:', 'str,', 'gradient_scaler:', 'torch.cuda.amp.GradScaler,', 'model_ema:', 'Optional[torch.nn.Module]=None,... | 629,531 |
nicknochnack/RealTimeSignLanguageTFJS | autoaugment_utils.py | shear_y_only_bboxes | shear_y_only_bboxes | Apply shear_y to each bbox in the image with probability prob. | [
"Apply",
"shear_y",
"to",
"each",
"bbox",
"in",
"the",
"image",
"with",
"probability",
"prob."
] | def shear_y_only_bboxes(image, bboxes, prob, level, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, shear_y, func_changes_bbox, level, replace) | ['def', 'shear_y_only_bboxes(image,', 'bboxes,', 'prob,', 'level,', 'replace):', 'func_changes_bbox', '=', 'False', 'prob', '=', '_scale_bbox_only_op_probability(prob)', 'return', '_apply_multi_bbox_augmentation_wrapper(image,', 'bboxes,', 'prob,', 'shear_y,', 'func_changes_bbox,', 'level,', 'replace)'] | 830,806 |
Ruturaj123/Flowchart-Detection | fractional_max_pool_op_test.py | FractionalMaxPoolTest.testLargePoolingRatio | testLargePoolingRatio | Test when pooling ratio is not within [1, 2). | [
"Test",
"when",
"pooling",
"ratio",
"is",
"not",
"within",
"[1,",
"2)."
] | def testLargePoolingRatio(self):
pseudo_random = True
overlapping = True
num_batches = 3
num_channels = 3
num_rows = 30
num_cols = 50
tensor_shape = (num_batches, num_rows, num_cols, num_channels)
for row_ratio in [math.sqrt(11), math.sqrt(37)]:
for col_ratio in [math.sqrt(11), m... | ['def', 'testLargePoolingRatio(self):', 'pseudo_random', '=', 'True', 'overlapping', '=', 'True', 'num_batches', '=', '3', 'num_channels', '=', '3', 'num_rows', '=', '30', 'num_cols', '=', '50', 'tensor_shape', '=', '(num_batches,', 'num_rows,', 'num_cols,', 'num_channels)', 'for', 'row_ratio', 'in', '[math.sqrt(11),',... | 605,624 |
StarBeta/Thought-SC2 | my_sc2_env.py | SC2Env.step | step | Apply actions, step the world forward, and return observations. | [
"Apply",
"actions,",
"step",
"the",
"world",
"forward,",
"and",
"return",
"observations."
] | def step(self, actions):
if self._state == environment.StepType.LAST:
return self.reset()
self._parallel.run(((c.act, self._features.transform_action(o.observation, a)) for (c, o, a) in zip(self._controllers, self._obs, actions)))
self._state = environment.StepType.MID
return self._step() | ['def', 'step(self,', 'actions):', 'if', 'self._state', '==', 'environment.StepType.LAST:', 'return', 'self.reset()', 'self._parallel.run(((c.act,', 'self._features.transform_action(o.observation,', 'a))', 'for', '(c,', 'o,', 'a)', 'in', 'zip(self._controllers,', 'self._obs,', 'actions)))', 'self._state', '=', 'environ... | 916,176 |
replit-archive/empythoned | charset.py | Charset.encoded_header_len | encoded_header_len | Return the length of the encoded header string. | [
"Return",
"the",
"length",
"of",
"the",
"encoded",
"header",
"string."
] | def encoded_header_len(self, s):
cset = self.get_output_charset()
if self.header_encoding == BASE64:
return email.base64mime.base64_len(s) + len(cset) + MISC_LEN
elif self.header_encoding == QP:
return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN
elif self.header_encoding... | ['def', 'encoded_header_len(self,', 's):', 'cset', '=', 'self.get_output_charset()', 'if', 'self.header_encoding', '==', 'BASE64:', 'return', 'email.base64mime.base64_len(s)', '+', 'len(cset)', '+', 'MISC_LEN', 'elif', 'self.header_encoding', '==', 'QP:', 'return', 'email.quoprimime.header_quopri_len(s)', '+', 'len(cse... | 177,509 |
rudranil723/mini-main | request.py | Request.getresponse | getresponse | Send all data and wait for response. | [
"Send",
"all",
"data",
"and",
"wait",
"for",
"response."
] | def getresponse(self):
if getattr(self._connection, 'sock', None) is None:
self._connect()
end = self._prepage_end_request_data()
if end is not None:
self.send(end.encode('utf-8'))
self._beforegetresponce()
return self._connection.getresponse() | ['def', 'getresponse(self):', 'if', 'getattr(self._connection,', "'sock',", 'None)', 'is', 'None:', 'self._connect()', 'end', '=', 'self._prepage_end_request_data()', 'if', 'end', 'is', 'not', 'None:', "self.send(end.encode('utf-8'))", 'self._beforegetresponce()', 'return', 'self._connection.getresponse()'] | 314,119 |
athms/evaluating-deeplight-transfer | model.py | model.interpret | interpret | Interpret decoding decision for volume. | [
"Interpret",
"decoding",
"decision",
"for",
"volume."
] | def interpret(self, volume):
if self._R is None:
raise NotImplementedError('LRP is not initialized. Please call .setup_lrp() first.')
volume = self._add_channel_dim(volume)
volume = self._tranpose_volumes(volume)
volume = self._stack_volumes(volume)
R = self.sess.run(self._R, feed_dict={self... | ['def', 'interpret(self,', 'volume):', 'if', 'self._R', 'is', 'None:', 'raise', "NotImplementedError('LRP", 'is', 'not', 'initialized.', 'Please', 'call', '.setup_lrp()', "first.')", 'volume', '=', 'self._add_channel_dim(volume)', 'volume', '=', 'self._tranpose_volumes(volume)', 'volume', '=', 'self._stack_volumes(volu... | 563,469 |
mkusner/grammarVAE | test_basic.py | TestARange.test_dtype_cache | test_dtype_cache | Checks that the same Op is returned on repeated calls to arange using the same dtype, but not for different dtypes. | [
"Checks",
"that",
"the",
"same",
"Op",
"is",
"returned",
"on",
"repeated",
"calls",
"to",
"arange",
"using",
"the",
"same",
"dtype,",
"but",
"not",
"for",
"different",
"dtypes."
] | def test_dtype_cache(self):
(start, stop, step) = iscalars('start', 'stop', 'step')
out1 = arange(start, stop, step)
out2 = arange(start, stop, step, dtype=out1.dtype)
out3 = arange(start, stop, 2.0, dtype=out1.dtype)
out4 = arange(start, stop, 2.0)
assert out1.owner.op is out2.owner.op
asse... | ['def', 'test_dtype_cache(self):', '(start,', 'stop,', 'step)', '=', "iscalars('start',", "'stop',", "'step')", 'out1', '=', 'arange(start,', 'stop,', 'step)', 'out2', '=', 'arange(start,', 'stop,', 'step,', 'dtype=out1.dtype)', 'out3', '=', 'arange(start,', 'stop,', '2.0,', 'dtype=out1.dtype)', 'out4', '=', 'arange(st... | 580,165 |
CAMeL-Lab/camel_tools | test_charmap.py | TestCharMapperBuiltinMapper.test_builtinmapper_bw2hsb | test_builtinmapper_bw2hsb | Test that the builtin 'bw2hsb' scheme is loaded without errors. | [
"Test",
"that",
"the",
"builtin",
"'bw2hsb'",
"scheme",
"is",
"loaded",
"without",
"errors."
] | def test_builtinmapper_bw2hsb(self):
assert CharMapper.builtin_mapper('bw2hsb') | ['def', 'test_builtinmapper_bw2hsb(self):', 'assert', "CharMapper.builtin_mapper('bw2hsb')"] | 411,215 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_utils.py | VideoProblem.extra_reading_spec | extra_reading_spec | Additional data fields to store on disk and their decoders. | [
"Additional",
"data",
"fields",
"to",
"store",
"on",
"disk",
"and",
"their",
"decoders."
] | def extra_reading_spec(self):
return ({}, {}) | ['def', 'extra_reading_spec(self):', 'return', '({},', '{})'] | 965,073 |
AndrewYinLi/lstm-neural-network-spam-filter | dependencygraph.py | malt_demo | malt_demo | A demonstration of the result of reading a dependency version of the first sentence of the Penn Treebank. | [
"A",
"demonstration",
"of",
"the",
"result",
"of",
"reading",
"a",
"dependency",
"version",
"of",
"the",
"first",
"sentence",
"of",
"the",
"Penn",
"Treebank."
] | def malt_demo(nx=False):
dg = DependencyGraph('Pierre NNP 2 NMOD\nVinken NNP 8 SUB\n, , 2 P\n61 CD 5 NMOD\nyears NNS 6 AMOD\nold JJ 2 NMOD\n, , 2 P\nwill MD 0 ROOT\njoin VB 8 VC\nthe ... | ['def', 'malt_demo(nx=False):', 'dg', '=', "DependencyGraph('Pierre", 'NNP', '2', 'NMOD\\nVinken', 'NNP', '8', 'SUB\\n,', ',', '2', 'P\\n61', 'CD', '5', 'NMOD\\nyears', 'NNS', '6', 'AMOD\\nold', 'JJ', '2', 'NMOD\\n,', ',', '2', 'P\\nwill', 'MD', '0', 'ROOT\\njoin', 'VB', '8', 'VC\\nthe', 'DT', '11', 'NMOD\\nboard', 'NN... | 218,104 |
google-research/scenic | trainer.py | init_state | init_state | Initialize the train state. | [
"Initialize",
"the",
"train",
"state."
] | def init_state(model: base_model.BaseModel, dataset: dataset_utils.Dataset, config: ml_collections.ConfigDict, workdir: str, rng: jnp.ndarray, writer: metric_writers.MetricWriter):
input_spec = {key[:-5]: dataset.meta_data[key] for key in dataset.meta_data if key[-5:] == '_spec'}
(rng, init_rng) = jax.random.sp... | ['def', 'init_state(model:', 'base_model.BaseModel,', 'dataset:', 'dataset_utils.Dataset,', 'config:', 'ml_collections.ConfigDict,', 'workdir:', 'str,', 'rng:', 'jnp.ndarray,', 'writer:', 'metric_writers.MetricWriter):', 'input_spec', '=', '{key[:-5]:', 'dataset.meta_data[key]', 'for', 'key', 'in', 'dataset.meta_data',... | 846,773 |
brendanm12345/imageSequenceGeneration | release.py | global_version_update | global_version_update | Update the version in all needed files. | [
"Update",
"the",
"version",
"in",
"all",
"needed",
"files."
] | def global_version_update(version, patch=False):
for (pattern, fname) in REPLACE_FILES.items():
update_version_in_file(fname, version, pattern)
if not patch:
update_version_in_examples(version) | ['def', 'global_version_update(version,', 'patch=False):', 'for', '(pattern,', 'fname)', 'in', 'REPLACE_FILES.items():', 'update_version_in_file(fname,', 'version,', 'pattern)', 'if', 'not', 'patch:', 'update_version_in_examples(version)'] | 610,419 |
implus/GFocalV2 | yolact_head.py | YOLACTProtonet.crop | crop | Crop predicted masks by zeroing out everything not in the predicted bbox. | [
"Crop",
"predicted",
"masks",
"by",
"zeroing",
"out",
"everything",
"not",
"in",
"the",
"predicted",
"bbox."
] | def crop(self, masks, boxes, padding=1):
(h, w, n) = masks.size()
(x1, x2) = self.sanitize_coordinates(boxes[:, 0], boxes[:, 2], w, padding, cast=False)
(y1, y2) = self.sanitize_coordinates(boxes[:, 1], boxes[:, 3], h, padding, cast=False)
rows = torch.arange(w, device=masks.device, dtype=x1.dtype).view... | ['def', 'crop(self,', 'masks,', 'boxes,', 'padding=1):', '(h,', 'w,', 'n)', '=', 'masks.size()', '(x1,', 'x2)', '=', 'self.sanitize_coordinates(boxes[:,', '0],', 'boxes[:,', '2],', 'w,', 'padding,', 'cast=False)', '(y1,', 'y2)', '=', 'self.sanitize_coordinates(boxes[:,', '1],', 'boxes[:,', '3],', 'h,', 'padding,', 'cas... | 557,641 |
lhotse-speech/lhotse | array.py | TemporalArray.with_path_prefix | with_path_prefix | Return a copy of the array with ``path`` added as a prefix to the ``storage_path`` member. | [
"Return",
"a",
"copy",
"of",
"the",
"array",
"with",
"``path``",
"added",
"as",
"a",
"prefix",
"to",
"the",
"``storage_path``",
"member."
] | def with_path_prefix(self, path: Pathlike) -> 'TemporalArray':
return fastcopy(self, array=self.array.with_path_prefix(path)) | ['def', 'with_path_prefix(self,', 'path:', 'Pathlike)', '->', "'TemporalArray':", 'return', 'fastcopy(self,', 'array=self.array.with_path_prefix(path))'] | 600,377 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | wmt_utils.py | is_pos_tag | is_pos_tag | Check if token is a part-of-speech tag. | [
"Check",
"if",
"token",
"is",
"a",
"part-of-speech",
"tag."
] | def is_pos_tag(token):
return token in ['CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNS', 'NNP', 'NNPS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP', 'WP$', 'WRB', '.', ',', ':', ')', '-LRB-', '(', '-RR... | ['def', 'is_pos_tag(token):', 'return', 'token', 'in', "['CC',", "'CD',", "'DT',", "'EX',", "'FW',", "'IN',", "'JJ',", "'JJR',", "'JJS',", "'LS',", "'MD',", "'NN',", "'NNS',", "'NNP',", "'NNPS',", "'PDT',", "'POS',", "'PRP',", "'PRP$',", "'RB',", "'RBR',", "'RBS',", "'RP',", "'SYM',", "'TO',", "'UH',", "'VB',", "'VBD',... | 50,289 |
FilipMiscevic/random_walk | rw.py | create_irt_graph | create_irt_graph | Determine the IRT for patch entry positions normalized to the average long-term IRT within one trial. | [
"Determine",
"the",
"IRT",
"for",
"patch",
"entry",
"positions",
"normalized",
"to",
"the",
"average",
"long-term",
"IRT",
"within",
"one",
"trial."
] | def create_irt_graph(b, cat, multi=False):
orders = []
n = []
p = []
irts = []
if multi == True:
size = len(cat)
for (q, w) in enumerate(cat):
neg_order = []
pos_order = []
for (j, k) in enumerate(w):
if k >= w[len(w) - 1]:
... | ['def', 'create_irt_graph(b,', 'cat,', 'multi=False):', 'orders', '=', '[]', 'n', '=', '[]', 'p', '=', '[]', 'irts', '=', '[]', 'if', 'multi', '==', 'True:', 'size', '=', 'len(cat)', 'for', '(q,', 'w)', 'in', 'enumerate(cat):', 'neg_order', '=', '[]', 'pos_order', '=', '[]', 'for', '(j,', 'k)', 'in', 'enumerate(w):', '... | 304,283 |
yinyunie/ScenePriors | pluggable.py | IO.save_mesh | save_mesh | Attempt to save a mesh to the given file, using a registered format. | [
"Attempt",
"to",
"save",
"a",
"mesh",
"to",
"the",
"given",
"file,",
"using",
"a",
"registered",
"format."
] | def save_mesh(self, data: Meshes, path: Union[str, Path], binary: Optional[bool]=None, include_textures: bool=True, **kwargs) -> None:
if len(data) != 1:
raise ValueError('Can only save a single mesh.')
for mesh_interpreter in self.mesh_interpreters:
success = mesh_interpreter.save(data, path, p... | ['def', 'save_mesh(self,', 'data:', 'Meshes,', 'path:', 'Union[str,', 'Path],', 'binary:', 'Optional[bool]=None,', 'include_textures:', 'bool=True,', '**kwargs)', '->', 'None:', 'if', 'len(data)', '!=', '1:', 'raise', "ValueError('Can", 'only', 'save', 'a', 'single', "mesh.')", 'for', 'mesh_interpreter', 'in', 'self.me... | 329,745 |
Farama-Foundation/Minigrid | minigrid_env.py | MiniGridEnv.right_vec | right_vec | Get the vector pointing to the right of the agent. | [
"Get",
"the",
"vector",
"pointing",
"to",
"the",
"right",
"of",
"the",
"agent."
] | def right_vec(self):
(dx, dy) = self.dir_vec
return np.array((-dy, dx)) | ['def', 'right_vec(self):', '(dx,', 'dy)', '=', 'self.dir_vec', 'return', 'np.array((-dy,', 'dx))'] | 271,476 |
googleapis/python-aiplatform | client.py | DatasetServiceClient.saved_query_path | saved_query_path | Returns a fully-qualified saved_query string. | [
"Returns",
"a",
"fully-qualified",
"saved_query",
"string."
] | def saved_query_path(project: str, location: str, dataset: str, saved_query: str) -> str:
return 'projects/{project}/locations/{location}/datasets/{dataset}/savedQueries/{saved_query}'.format(project=project, location=location, dataset=dataset, saved_query=saved_query) | ['def', 'saved_query_path(project:', 'str,', 'location:', 'str,', 'dataset:', 'str,', 'saved_query:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/datasets/{dataset}/savedQueries/{saved_query}'.format(project=project,", 'location=location,', 'dataset=dataset,', 'saved_query=saved_query)'] | 810,334 |
caiiiac/Machine-Learning-with-Python | misc_util.py | msvc_version | msvc_version | Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise. | [
"Return",
"version",
"major",
"and",
"minor",
"of",
"compiler",
"instance",
"if",
"it",
"is",
"MSVC,",
"raise",
"an",
"exception",
"otherwise."
] | def msvc_version(compiler):
if not compiler.compiler_type == 'msvc':
raise ValueError('Compiler instance is not msvc (%s)' % compiler.compiler_type)
return compiler._MSVCCompiler__version | ['def', 'msvc_version(compiler):', 'if', 'not', 'compiler.compiler_type', '==', "'msvc':", 'raise', "ValueError('Compiler", 'instance', 'is', 'not', 'msvc', "(%s)'", '%', 'compiler.compiler_type)', 'return', 'compiler._MSVCCompiler__version'] | 717,060 |
vbelz/audio_classification | cookies.py | morsel_to_cookie | morsel_to_cookie | Convert a Morsel object into a Cookie containing the one k/v pair. | [
"Convert",
"a",
"Morsel",
"object",
"into",
"a",
"Cookie",
"containing",
"the",
"one",
"k/v",
"pair."
] | def morsel_to_cookie(morsel):
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b... | ['def', 'morsel_to_cookie(morsel):', 'expires', '=', 'None', 'if', "morsel['max-age']:", 'try:', 'expires', '=', 'int(time.time()', '+', "int(morsel['max-age']))", 'except', 'ValueError:', 'raise', "TypeError('max-age:", '%s', 'must', 'be', "integer'", '%', "morsel['max-age'])", 'elif', "morsel['expires']:", 'time_temp... | 403,901 |
Happy-zyy/Machine-Learning | FirstDT.py | print_leaf | print_leaf | A nicer way to print the predictions at a leaf. | [
"A",
"nicer",
"way",
"to",
"print",
"the",
"predictions",
"at",
"a",
"leaf."
] | def print_leaf(counts):
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = str(int(counts[lbl] / total * 100)) + '%'
return probs | ['def', 'print_leaf(counts):', 'total', '=', 'sum(counts.values())', '*', '1.0', 'probs', '=', '{}', 'for', 'lbl', 'in', 'counts.keys():', 'probs[lbl]', '=', 'str(int(counts[lbl]', '/', 'total', '*', '100))', '+', "'%'", 'return', 'probs'] | 190,729 |
nchah/nlpml-project | word2vec-optimized.py | Word2Vec.build_eval_graph | build_eval_graph | Build the evaluation graph. | [
"Build",
"the",
"evaluation",
"graph."
] | def build_eval_graph(self):
opts = self._options
analogy_a = tf.placeholder(dtype=tf.int32)
analogy_b = tf.placeholder(dtype=tf.int32)
analogy_c = tf.placeholder(dtype=tf.int32)
nemb = tf.nn.l2_normalize(self._w_in, 1)
a_emb = tf.gather(nemb, analogy_a)
b_emb = tf.gather(nemb, analogy_b)
... | ['def', 'build_eval_graph(self):', 'opts', '=', 'self._options', 'analogy_a', '=', 'tf.placeholder(dtype=tf.int32)', 'analogy_b', '=', 'tf.placeholder(dtype=tf.int32)', 'analogy_c', '=', 'tf.placeholder(dtype=tf.int32)', 'nemb', '=', 'tf.nn.l2_normalize(self._w_in,', '1)', 'a_emb', '=', 'tf.gather(nemb,', 'analogy_a)',... | 731,613 |
eth-sri/debin | structs.py | ELFStructs.create_basic_structs | create_basic_structs | Create word-size related structs and ehdr struct needed for initial determining of ELF type. | [
"Create",
"word-size",
"related",
"structs",
"and",
"ehdr",
"struct",
"needed",
"for",
"initial",
"determining",
"of",
"ELF",
"type."
] | def create_basic_structs(self):
if self.little_endian:
self.Elf_byte = ULInt8
self.Elf_half = ULInt16
self.Elf_word = ULInt32
self.Elf_word64 = ULInt64
self.Elf_addr = ULInt32 if self.elfclass == 32 else ULInt64
self.Elf_offset = self.Elf_addr
self.Elf_sword =... | ['def', 'create_basic_structs(self):', 'if', 'self.little_endian:', 'self.Elf_byte', '=', 'ULInt8', 'self.Elf_half', '=', 'ULInt16', 'self.Elf_word', '=', 'ULInt32', 'self.Elf_word64', '=', 'ULInt64', 'self.Elf_addr', '=', 'ULInt32', 'if', 'self.elfclass', '==', '32', 'else', 'ULInt64', 'self.Elf_offset', '=', 'self.El... | 516,632 |
LiDan456/GAN-AD | plotting.py | reconstruction_errors | reconstruction_errors | Plot two histogram of the reconstruction errors. | [
"Plot",
"two",
"histogram",
"of",
"the",
"reconstruction",
"errors."
] | def reconstruction_errors(identifier, train_errors, vali_errors, generated_errors, random_errors):
print(identifier)
(fig, axarr) = plt.subplots(4, 1, sharex=True, figsize=(4, 8))
axarr[0].hist(train_errors, normed=1, color='green', bins=50)
axarr[0].set_title('train reconstruction errors')
axarr[1]... | ['def', 'reconstruction_errors(identifier,', 'train_errors,', 'vali_errors,', 'generated_errors,', 'random_errors):', 'print(identifier)', '(fig,', 'axarr)', '=', 'plt.subplots(4,', '1,', 'sharex=True,', 'figsize=(4,', '8))', 'axarr[0].hist(train_errors,', 'normed=1,', "color='green',", 'bins=50)', "axarr[0].set_title(... | 566,311 |
caiiiac/Machine-Learning-with-Python | test_mlab.py | gaussian_kde_custom_tests.test_single_dataset_element | test_single_dataset_element | Pass a single dataset element into the GaussianKDE class. | [
"Pass",
"a",
"single",
"dataset",
"element",
"into",
"the",
"GaussianKDE",
"class."
] | def test_single_dataset_element(self):
assert_raises(ValueError, mlab.GaussianKDE, [42]) | ['def', 'test_single_dataset_element(self):', 'assert_raises(ValueError,', 'mlab.GaussianKDE,', '[42])'] | 716,696 |
PyRetri/PyRetri | reid_overall.py | ReIDOverAll.compute_ap_cmc | compute_ap_cmc | Calculate the ap and cmc for one query. | [
"Calculate",
"the",
"ap",
"and",
"cmc",
"for",
"one",
"query."
] | def compute_ap_cmc(self, index: np.ndarray, good_index: np.ndarray, junk_index: np.ndarray) -> (float, torch.tensor):
ap = 0
cmc = torch.IntTensor(len(index)).zero_()
if good_index.size == 0:
cmc[0] = -1
return (ap, cmc)
mask = np.in1d(index, junk_index, invert=True)
index = index[ma... | ['def', 'compute_ap_cmc(self,', 'index:', 'np.ndarray,', 'good_index:', 'np.ndarray,', 'junk_index:', 'np.ndarray)', '->', '(float,', 'torch.tensor):', 'ap', '=', '0', 'cmc', '=', 'torch.IntTensor(len(index)).zero_()', 'if', 'good_index.size', '==', '0:', 'cmc[0]', '=', '-1', 'return', '(ap,', 'cmc)', 'mask', '=', 'np.... | 297,186 |
rifqind/Agent-Programs-3KS1 | prefilter.py | PrefilterManager.handlers | handlers | Return a dict of all the handlers. | [
"Return",
"a",
"dict",
"of",
"all",
"the",
"handlers."
] | def handlers(self):
return self._handlers | ['def', 'handlers(self):', 'return', 'self._handlers'] | 41,222 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | module_proxy_wrapper.py | ModuleProxyWrapper.state_dict | state_dict | Forward to the twice-wrapped module. | [
"Forward",
"to",
"the",
"twice-wrapped",
"module."
] | def state_dict(self, *args, **kwargs):
return self.module.module.state_dict(*args, **kwargs) | ['def', 'state_dict(self,', '*args,', '**kwargs):', 'return', 'self.module.module.state_dict(*args,', '**kwargs)'] | 103,708 |
nflick/asu-cse-471 | entropy.py | entropy | entropy | Returns the entropy of the proportion q. | [
"Returns",
"the",
"entropy",
"of",
"the",
"proportion",
"q."
] | def entropy(q):
if q <= 0 or q >= 1:
return 0
return q * math.log(1 / q, 2) + (1 - q) * math.log(1 / (1 - q), 2) | ['def', 'entropy(q):', 'if', 'q', '<=', '0', 'or', 'q', '>=', '1:', 'return', '0', 'return', 'q', '*', 'math.log(1', '/', 'q,', '2)', '+', '(1', '-', 'q)', '*', 'math.log(1', '/', '(1', '-', 'q),', '2)'] | 92,522 |
weimin17/Object-Detection_HelmetDetection | train_utils.py | get_model_init_fn | get_model_init_fn | Gets the function initializing model variables from a checkpoint. | [
"Gets",
"the",
"function",
"initializing",
"model",
"variables",
"from",
"a",
"checkpoint."
] | def get_model_init_fn(train_logdir, tf_initial_checkpoint, initialize_last_layer, last_layers, ignore_missing_vars=False):
if tf_initial_checkpoint is None:
tf.logging.info('Not initializing the model from a checkpoint.')
return None
if tf.train.latest_checkpoint(train_logdir):
tf.loggin... | ['def', 'get_model_init_fn(train_logdir,', 'tf_initial_checkpoint,', 'initialize_last_layer,', 'last_layers,', 'ignore_missing_vars=False):', 'if', 'tf_initial_checkpoint', 'is', 'None:', "tf.logging.info('Not", 'initializing', 'the', 'model', 'from', 'a', "checkpoint.')", 'return', 'None', 'if', 'tf.train.latest_check... | 749,617 |
taokong/FoveaBox | transforms.py | bbox2roi | bbox2roi | Convert a list of bboxes to roi format. | [
"Convert",
"a",
"list",
"of",
"bboxes",
"to",
"roi",
"format."
] | def bbox2roi(bbox_list):
rois_list = []
for (img_id, bboxes) in enumerate(bbox_list):
if bboxes.size(0) > 0:
img_inds = bboxes.new_full((bboxes.size(0), 1), img_id)
rois = torch.cat([img_inds, bboxes[:, :4]], dim=-1)
else:
rois = bboxes.new_zeros((0, 5))
... | ['def', 'bbox2roi(bbox_list):', 'rois_list', '=', '[]', 'for', '(img_id,', 'bboxes)', 'in', 'enumerate(bbox_list):', 'if', 'bboxes.size(0)', '>', '0:', 'img_inds', '=', 'bboxes.new_full((bboxes.size(0),', '1),', 'img_id)', 'rois', '=', 'torch.cat([img_inds,', 'bboxes[:,', ':4]],', 'dim=-1)', 'else:', 'rois', '=', 'bbox... | 564,084 |
aisingapore/PeekingDuck | postprocessing.py | affine_transform_xy | affine_transform_xy | Apply respective affine transform on array of points. | [
"Apply",
"respective",
"affine",
"transform",
"on",
"array",
"of",
"points."
] | def affine_transform_xy(keypoints: np.ndarray, affine_matrices: np.ndarray) -> np.ndarray:
transformed_matrices = []
keypoints = np.dstack((keypoints, np.ones((keypoints.shape[0], keypoints.shape[1], 1))))
for (affine_matrix, keypoint) in zip(affine_matrices, keypoints):
transformed_keypoint = np.do... | ['def', 'affine_transform_xy(keypoints:', 'np.ndarray,', 'affine_matrices:', 'np.ndarray)', '->', 'np.ndarray:', 'transformed_matrices', '=', '[]', 'keypoints', '=', 'np.dstack((keypoints,', 'np.ones((keypoints.shape[0],', 'keypoints.shape[1],', '1))))', 'for', '(affine_matrix,', 'keypoint)', 'in', 'zip(affine_matrices... | 766,947 |
mfbx9da4/neuron-astrocyte-networks | leastsquares.py | LSTD_PI_policy | LSTD_PI_policy | Alternative version of LSPI using value functions instead of state-action values as intermediate. | [
"Alternative",
"version",
"of",
"LSPI",
"using",
"value",
"functions",
"instead",
"of",
"state-action",
"values",
"as",
"intermediate."
] | def LSTD_PI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20):
def veval(T):
return LSTD_values(T, R, fMap, discountFactor)
return policyIteration(Ts, R, discountFactor, VEvaluator=veval, initpolicy=initpolicy, maxIters=maxIters) | ['def', 'LSTD_PI_policy(fMap,', 'Ts,', 'R,', 'discountFactor,', 'initpolicy=None,', 'maxIters=20):', 'def', 'veval(T):', 'return', 'LSTD_values(T,', 'R,', 'fMap,', 'discountFactor)', 'return', 'policyIteration(Ts,', 'R,', 'discountFactor,', 'VEvaluator=veval,', 'initpolicy=initpolicy,', 'maxIters=maxIters)'] | 723,157 |
AiIsBetter/computer_vision | inputs_test.py | InputsTest.test_predict_input | test_predict_input | Tests the predict input function. | [
"Tests",
"the",
"predict",
"input",
"function."
] | def test_predict_input(self):
configs = _get_configs_for_model('ssd_inception_v2_pets')
predict_input_fn = inputs.create_predict_input_fn(model_config=configs['model'], predict_input_config=configs['eval_input_configs'][0])
serving_input_receiver = predict_input_fn()
image = serving_input_receiver.featu... | ['def', 'test_predict_input(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", 'predict_input_fn', '=', "inputs.create_predict_input_fn(model_config=configs['model'],", "predict_input_config=configs['eval_input_configs'][0])", 'serving_input_receiver', '=', 'predict_input_fn()', 'image', '=', '... | 503,560 |
enuguru/artificial_intelligence_and_machine_ | models.py | Response.apparent_encoding | apparent_encoding | The apparent encoding, provided by the lovely Charade library (Thanks, Ian!). | [
"The",
"apparent",
"encoding,",
"provided",
"by",
"the",
"lovely",
"Charade",
"library",
"(Thanks,",
"Ian!)."
] | def apparent_encoding(self):
return chardet.detect(self.content)['encoding'] | ['def', 'apparent_encoding(self):', 'return', "chardet.detect(self.content)['encoding']"] | 163,796 |
enuguru/artificial_intelligence_and_machine_learning | sql.py | TokenList.get_real_name | get_real_name | Returns the real name (object name) of this identifier. | [
"Returns",
"the",
"real",
"name",
"(object",
"name)",
"of",
"this",
"identifier."
] | def get_real_name(self):
dot = self.token_next_match(0, T.Punctuation, '.')
if dot is not None:
return self._get_first_name(self.token_index(dot))
return self._get_first_name() | ['def', 'get_real_name(self):', 'dot', '=', 'self.token_next_match(0,', 'T.Punctuation,', "'.')", 'if', 'dot', 'is', 'not', 'None:', 'return', 'self._get_first_name(self.token_index(dot))', 'return', 'self._get_first_name()'] | 131,915 |
srai-lab/srai | test_gtfs_loader.py | test_validation_error | test_validation_error | Test checks if GTFSLoader raises ValueError on validation error. | [
"Test",
"checks",
"if",
"GTFSLoader",
"raises",
"ValueError",
"on",
"validation",
"error."
] | def test_validation_error(mocker: MockerFixture, gtfs_validation_error: pd.DataFrame) -> None:
feed_mock = mocker.MagicMock()
feed_mock.configure_mock(**{'validate.return_value': gtfs_validation_error})
warning_mock = mocker.patch('warnings.warn')
loader = GTFSLoader()
with pytest.raises(ValueError)... | ['def', 'test_validation_error(mocker:', 'MockerFixture,', 'gtfs_validation_error:', 'pd.DataFrame)', '->', 'None:', 'feed_mock', '=', 'mocker.MagicMock()', "feed_mock.configure_mock(**{'validate.return_value':", 'gtfs_validation_error})', 'warning_mock', '=', "mocker.patch('warnings.warn')", 'loader', '=', 'GTFSLoader... | 372,018 |
googleapis/python-aiplatform | client.py | JobServiceClient.tensorboard_path | tensorboard_path | Returns a fully-qualified tensorboard string. | [
"Returns",
"a",
"fully-qualified",
"tensorboard",
"string."
] | def tensorboard_path(project: str, location: str, tensorboard: str) -> str:
return 'projects/{project}/locations/{location}/tensorboards/{tensorboard}'.format(project=project, location=location, tensorboard=tensorboard) | ['def', 'tensorboard_path(project:', 'str,', 'location:', 'str,', 'tensorboard:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/tensorboards/{tensorboard}'.format(project=project,", 'location=location,', 'tensorboard=tensorboard)'] | 813,067 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | QualityWrapper.numquads | numquads | number of quads for box rendering. | [
"number",
"of",
"quads",
"for",
"box",
"rendering."
] | def numquads(self):
return self._ptr.contents.numquads | ['def', 'numquads(self):', 'return', 'self._ptr.contents.numquads'] | 440,172 |
scotthuang1989/object_detection_with_tensorflow | objective.py | discounted_two_sided_sum | discounted_two_sided_sum | Discounted two-sided sum of time-major values. | [
"Discounted",
"two-sided",
"sum",
"of",
"time-major",
"values."
] | def discounted_two_sided_sum(values, discount, rollout):
roll = float(rollout)
discount_filter = tf.reshape(discount ** tf.abs(tf.range(-roll + 1, roll)), [-1, 1, 1])
expanded_values = tf.concat([tf.zeros([rollout - 1, tf.shape(values)[1]]), values, tf.zeros([rollout - 1, tf.shape(values)[1]])], 0)
conv... | ['def', 'discounted_two_sided_sum(values,', 'discount,', 'rollout):', 'roll', '=', 'float(rollout)', 'discount_filter', '=', 'tf.reshape(discount', '**', 'tf.abs(tf.range(-roll', '+', '1,', 'roll)),', '[-1,', '1,', '1])', 'expanded_values', '=', 'tf.concat([tf.zeros([rollout', '-', '1,', 'tf.shape(values)[1]]),', 'valu... | 739,476 |
aisingapore/PeekingDuck | test_hrnet.py | TestHrnet.test_no_human_image | test_no_human_image | Tests HRnet on images with no humans present. | [
"Tests",
"HRnet",
"on",
"images",
"with",
"no",
"humans",
"present."
] | def test_no_human_image(self, no_human_image, hrnet_config):
no_human_img = cv2.imread(no_human_image)
hrnet = Node(hrnet_config)
output = hrnet.run({'img': no_human_img, 'bboxes': np.empty((0, 4))})
expected_output = {'keypoints': np.zeros(0), 'keypoint_scores': np.zeros(0), 'keypoint_conns': np.zeros(... | ['def', 'test_no_human_image(self,', 'no_human_image,', 'hrnet_config):', 'no_human_img', '=', 'cv2.imread(no_human_image)', 'hrnet', '=', 'Node(hrnet_config)', 'output', '=', "hrnet.run({'img':", 'no_human_img,', "'bboxes':", 'np.empty((0,', '4))})', 'expected_output', '=', "{'keypoints':", 'np.zeros(0),', "'keypoint_... | 767,233 |
pylabel-project/pylabel | visualize.py | Visualize.ShowBoundingBoxes | ShowBoundingBoxes | Enter a filename or index number and return the image with the bounding boxes drawn. | [
"Enter",
"a",
"filename",
"or",
"index",
"number",
"and",
"return",
"the",
"image",
"with",
"the",
"bounding",
"boxes",
"drawn."
] | def ShowBoundingBoxes(self, img_id: int=0, img_filename: str='') -> Image:
ds = self.dataset
if type(img_id) == str:
img_filename = img_id
if img_filename == '':
df_single_img_annots = ds.df.loc[ds.df.img_id == img_id]
else:
df_single_img_annots = ds.df.loc[ds.df.img_filename == ... | ['def', 'ShowBoundingBoxes(self,', 'img_id:', 'int=0,', 'img_filename:', "str='')", '->', 'Image:', 'ds', '=', 'self.dataset', 'if', 'type(img_id)', '==', 'str:', 'img_filename', '=', 'img_id', 'if', 'img_filename', '==', "'':", 'df_single_img_annots', '=', 'ds.df.loc[ds.df.img_id', '==', 'img_id]', 'else:', 'df_single... | 819,819 |
ratschlab/dpsom | somvae_model.py | SOMVAE.z_q_neighbors | z_q_neighbors | Aggregates the respective neighbors in the SOM for every embedding in z_q. | [
"Aggregates",
"the",
"respective",
"neighbors",
"in",
"the",
"SOM",
"for",
"every",
"embedding",
"in",
"z_q."
] | def z_q_neighbors(self):
k_1 = self.k // self.som_dim[1]
k_2 = self.k % self.som_dim[1]
k_stacked = tf.stack([k_1, k_2], axis=1)
k1_not_top = tf.less(k_1, tf.constant(self.som_dim[0] - 1, dtype=tf.int64))
k1_not_bottom = tf.greater(k_1, tf.constant(0, dtype=tf.int64))
k2_not_right = tf.less(k_2,... | ['def', 'z_q_neighbors(self):', 'k_1', '=', 'self.k', '//', 'self.som_dim[1]', 'k_2', '=', 'self.k', '%', 'self.som_dim[1]', 'k_stacked', '=', 'tf.stack([k_1,', 'k_2],', 'axis=1)', 'k1_not_top', '=', 'tf.less(k_1,', 'tf.constant(self.som_dim[0]', '-', '1,', 'dtype=tf.int64))', 'k1_not_bottom', '=', 'tf.greater(k_1,', '... | 167,019 |
myothida/Supervised-Machine-Learning | ast.py | GlyphClassDefStatement.build | build | Calls the builder's ``add_glyphClassDef`` callback. | [
"Calls",
"the",
"builder's",
"``add_glyphClassDef``",
"callback."
] | def build(self, builder):
base = self.baseGlyphs.glyphSet() if self.baseGlyphs else tuple()
liga = self.ligatureGlyphs.glyphSet() if self.ligatureGlyphs else tuple()
mark = self.markGlyphs.glyphSet() if self.markGlyphs else tuple()
comp = self.componentGlyphs.glyphSet() if self.componentGlyphs else tupl... | ['def', 'build(self,', 'builder):', 'base', '=', 'self.baseGlyphs.glyphSet()', 'if', 'self.baseGlyphs', 'else', 'tuple()', 'liga', '=', 'self.ligatureGlyphs.glyphSet()', 'if', 'self.ligatureGlyphs', 'else', 'tuple()', 'mark', '=', 'self.markGlyphs.glyphSet()', 'if', 'self.markGlyphs', 'else', 'tuple()', 'comp', '=', 's... | 360,850 |
ldkong1205/LaserMix | indoor_metric.py | Indoor2DMetric.compute_metrics | compute_metrics | Compute the metrics from processed results. | [
"Compute",
"the",
"metrics",
"from",
"processed",
"results."
] | def compute_metrics(self, results: list) -> Dict[str, float]:
logger: MMLogger = MMLogger.get_current_instance()
(annotations, preds) = zip(*results)
eval_results = OrderedDict()
for iou_thr_2d_single in self.iou_thr:
(mean_ap, _) = eval_map(preds, annotations, scale_ranges=None, iou_thr=iou_thr... | ['def', 'compute_metrics(self,', 'results:', 'list)', '->', 'Dict[str,', 'float]:', 'logger:', 'MMLogger', '=', 'MMLogger.get_current_instance()', '(annotations,', 'preds)', '=', 'zip(*results)', 'eval_results', '=', 'OrderedDict()', 'for', 'iou_thr_2d_single', 'in', 'self.iou_thr:', '(mean_ap,', '_)', '=', 'eval_map(p... | 623,886 |
ryu-ed/SpaceInvaders_Ros | test_spectral.py | TestLombscargle.test_frequency | test_frequency | Test if frequency location of peak corresponds to frequency of generated input signal. | [
"Test",
"if",
"frequency",
"location",
"of",
"peak",
"corresponds",
"to",
"frequency",
"of",
"generated",
"input",
"signal."
] | def test_frequency(self):
ampl = 2.0
w = 1.0
phi = 0.5 * np.pi
nin = 100
nout = 1000
p = 0.7
np.random.seed(2353425)
r = np.random.rand(nin)
t = np.linspace(0.01 * np.pi, 10.0 * np.pi, nin)[r >= p]
x = ampl * np.sin(w * t + phi)
f = np.linspace(0.01, 10.0, nout)
P = lombs... | ['def', 'test_frequency(self):', 'ampl', '=', '2.0', 'w', '=', '1.0', 'phi', '=', '0.5', '*', 'np.pi', 'nin', '=', '100', 'nout', '=', '1000', 'p', '=', '0.7', 'np.random.seed(2353425)', 'r', '=', 'np.random.rand(nin)', 't', '=', 'np.linspace(0.01', '*', 'np.pi,', '10.0', '*', 'np.pi,', 'nin)[r', '>=', 'p]', 'x', '=', ... | 370,969 |
43Carrig/recurrent_neural_networks_practice | batch_ops_test.py | BatchOpsTest.testBatchFunctionOpWithCapturedInput | testBatchFunctionOpWithCapturedInput | Tests that batch_function op works with captured input. | [
"Tests",
"that",
"batch_function",
"op",
"works",
"with",
"captured",
"input."
] | def testBatchFunctionOpWithCapturedInput(self):
with self.test_session() as sess:
captured_inp0 = array_ops.placeholder_with_default(2, shape=[])
captured_inp1 = array_ops.placeholder_with_default(1, shape=[])
inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])
@function.Defu... | ['def', 'testBatchFunctionOpWithCapturedInput(self):', 'with', 'self.test_session()', 'as', 'sess:', 'captured_inp0', '=', 'array_ops.placeholder_with_default(2,', 'shape=[])', 'captured_inp1', '=', 'array_ops.placeholder_with_default(1,', 'shape=[])', 'inp', '=', 'array_ops.placeholder(dtype=dtypes.int32,', 'shape=[1]... | 312,460 |
wandb/wandb | test_spec.py | test_3_2_2_2 | test_3_2_2_2 | Make sure callbacks are never called more than once. | [
"Make",
"sure",
"callbacks",
"are",
"never",
"called",
"more",
"than",
"once."
] | def test_3_2_2_2():
c = Counter()
p1 = Promise.resolve(5)
p2 = p1.then(lambda v: c.tick())
p2._wait()
try:
p1.do_resolve(5)
assert False
except AssertionError:
pass
assert 1 == c.value() | ['def', 'test_3_2_2_2():', 'c', '=', 'Counter()', 'p1', '=', 'Promise.resolve(5)', 'p2', '=', 'p1.then(lambda', 'v:', 'c.tick())', 'p2._wait()', 'try:', 'p1.do_resolve(5)', 'assert', 'False', 'except', 'AssertionError:', 'pass', 'assert', '1', '==', 'c.value()'] | 941,973 |
PacktPublishing/Hands-On-Artificial--for-Banking | req_uninstall.py | StashedUninstallPathSet.stash | stash | Stashes the directory or file and returns its new location. | [
"Stashes",
"the",
"directory",
"or",
"file",
"and",
"returns",
"its",
"new",
"location."
] | def stash(self, path):
if os.path.isdir(path):
new_path = self._get_directory_stash(path)
else:
new_path = self._get_file_stash(path)
self._moves.append((path, new_path))
if os.path.isdir(path) and os.path.isdir(new_path):
os.rmdir(new_path)
renames(path, new_path)
return... | ['def', 'stash(self,', 'path):', 'if', 'os.path.isdir(path):', 'new_path', '=', 'self._get_directory_stash(path)', 'else:', 'new_path', '=', 'self._get_file_stash(path)', 'self._moves.append((path,', 'new_path))', 'if', 'os.path.isdir(path)', 'and', 'os.path.isdir(new_path):', 'os.rmdir(new_path)', 'renames(path,', 'ne... | 237,511 |
jariasf/GMVAE | gmvae.py | GMVAE.encoder_y | encoder_y | Computes the inference distribution q(y | x). | [
"Computes",
"the",
"inference",
"distribution",
"q(y",
"|",
"x)."
] | def encoder_y(self, x):
x = tf.cast(x, dtype=tf.float32)
return self._encoder_y(x) | ['def', 'encoder_y(self,', 'x):', 'x', '=', 'tf.cast(x,', 'dtype=tf.float32)', 'return', 'self._encoder_y(x)'] | 578,491 |
rudranil723/mini-main | tree.py | TreeSegmentWidget.replace_child | replace_child | Replace the child ``oldchild`` with ``newchild``. | [
"Replace",
"the",
"child",
"``oldchild``",
"with",
"``newchild``."
] | def replace_child(self, oldchild, newchild):
index = self._subtrees.index(oldchild)
self._subtrees[index] = newchild
self._remove_child_widget(oldchild)
self._add_child_widget(newchild)
self.update(newchild) | ['def', 'replace_child(self,', 'oldchild,', 'newchild):', 'index', '=', 'self._subtrees.index(oldchild)', 'self._subtrees[index]', '=', 'newchild', 'self._remove_child_widget(oldchild)', 'self._add_child_widget(newchild)', 'self.update(newchild)'] | 321,179 |
RasaHQ/rasa | prepare_nightly_release.py | create_argument_parser | create_argument_parser | Parse all the command line arguments for the release script. | [
"Parse",
"all",
"the",
"command",
"line",
"arguments",
"for",
"the",
"release",
"script."
] | def create_argument_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description='prepare the next nightly release')
parser.add_argument('--next_version', type=str, help='Rasa nightly version number')
return parser | ['def', 'create_argument_parser()', '->', 'argparse.ArgumentParser:', 'parser', '=', "argparse.ArgumentParser(description='prepare", 'the', 'next', 'nightly', "release')", "parser.add_argument('--next_version',", 'type=str,', "help='Rasa", 'nightly', 'version', "number')", 'return', 'parser'] | 837,987 |
TingtingHuang/CSE-511A-Introduction-to-- | valueIterationAgents.py | ValueIterationAgent.getAction | getAction | Returns the policy at the state (no exploration). | [
"Returns",
"the",
"policy",
"at",
"the",
"state",
"(no",
"exploration)."
] | def getAction(self, state):
return self.getPolicy(state) | ['def', 'getAction(self,', 'state):', 'return', 'self.getPolicy(state)'] | 192,944 |
surafelml/adapt-mnmt | model.py | Model.get_assets | get_assets | Returns additional assets used by this model. | [
"Returns",
"additional",
"assets",
"used",
"by",
"this",
"model."
] | def get_assets(self, metadata, asset_dir):
assets = self._initialize(metadata, asset_dir=asset_dir)
tf.reset_default_graph()
return assets | ['def', 'get_assets(self,', 'metadata,', 'asset_dir):', 'assets', '=', 'self._initialize(metadata,', 'asset_dir=asset_dir)', 'tf.reset_default_graph()', 'return', 'assets'] | 407,980 |
fudan-zvg/SeaFormer | accuracy.py | Accuracy.forward | forward | Forward function to calculate accuracy. | [
"Forward",
"function",
"to",
"calculate",
"accuracy."
] | def forward(self, pred, target):
return accuracy(pred, target, self.topk, self.thresh) | ['def', 'forward(self,', 'pred,', 'target):', 'return', 'accuracy(pred,', 'target,', 'self.topk,', 'self.thresh)'] | 855,951 |
PacktPublishing/Hands-On-Artificial--for-Banking | _termui_impl.py | ProgressBar.generator | generator | Return a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. | [
"Return",
"a",
"generator",
"which",
"yields",
"the",
"items",
"added",
"to",
"the",
"bar",
"during",
"construction,",
"and",
"updates",
"the",
"progress",
"bar",
"*after*",
"the",
"yielded",
"block",
"returns."
] | def generator(self):
if not self.entered:
raise RuntimeError('You need to use progress bars in a with block.')
if self.is_hidden:
for rv in self.iter:
yield rv
else:
for rv in self.iter:
self.current_item = rv
yield rv
self.update(1)
... | ['def', 'generator(self):', 'if', 'not', 'self.entered:', 'raise', "RuntimeError('You", 'need', 'to', 'use', 'progress', 'bars', 'in', 'a', 'with', "block.')", 'if', 'self.is_hidden:', 'for', 'rv', 'in', 'self.iter:', 'yield', 'rv', 'else:', 'for', 'rv', 'in', 'self.iter:', 'self.current_item', '=', 'rv', 'yield', 'rv'... | 234,820 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | caption_generator.py | CaptionGenerator.beam_search | beam_search | Runs beam search caption generation on a single image. | [
"Runs",
"beam",
"search",
"caption",
"generation",
"on",
"a",
"single",
"image."
] | def beam_search(self, sess, encoded_image):
initial_state = self.model.feed_image(sess, encoded_image)
initial_beam = Caption(sentence=[self.vocab.start_id], state=initial_state[0], logprob=0.0, score=0.0, metadata=[''])
partial_captions = TopN(self.beam_size)
partial_captions.push(initial_beam)
com... | ['def', 'beam_search(self,', 'sess,', 'encoded_image):', 'initial_state', '=', 'self.model.feed_image(sess,', 'encoded_image)', 'initial_beam', '=', 'Caption(sentence=[self.vocab.start_id],', 'state=initial_state[0],', 'logprob=0.0,', 'score=0.0,', "metadata=[''])", 'partial_captions', '=', 'TopN(self.beam_size)', 'par... | 55,010 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | graph_builder_test.py | GraphBuilderTest.assertNotEmpty | assertNotEmpty | Assert that an object has non-zero length. | [
"Assert",
"that",
"an",
"object",
"has",
"non-zero",
"length."
] | def assertNotEmpty(self, container, msg=None):
if not isinstance(container, collections.Sized):
self.fail('Expected a Sized object, got: {!r}'.format(type(container).__name__), msg)
if not len(container):
self.fail('{!r} has length of 0.'.format(container), msg) | ['def', 'assertNotEmpty(self,', 'container,', 'msg=None):', 'if', 'not', 'isinstance(container,', 'collections.Sized):', "self.fail('Expected", 'a', 'Sized', 'object,', 'got:', "{!r}'.format(type(container).__name__),", 'msg)', 'if', 'not', 'len(container):', "self.fail('{!r}", 'has', 'length', 'of', "0.'.format(contai... | 28,321 |
cheng052/BRNet | sparse_unet.py | SparseUNet.decoder_layer_forward | decoder_layer_forward | Forward of upsample and residual block. | [
"Forward",
"of",
"upsample",
"and",
"residual",
"block."
] | def decoder_layer_forward(self, x_lateral, x_bottom, lateral_layer, merge_layer, upsample_layer):
x = lateral_layer(x_lateral)
x.features = torch.cat((x_bottom.features, x.features), dim=1)
x_merge = merge_layer(x)
x = self.reduce_channel(x, x_merge.features.shape[1])
x.features = x_merge.features +... | ['def', 'decoder_layer_forward(self,', 'x_lateral,', 'x_bottom,', 'lateral_layer,', 'merge_layer,', 'upsample_layer):', 'x', '=', 'lateral_layer(x_lateral)', 'x.features', '=', 'torch.cat((x_bottom.features,', 'x.features),', 'dim=1)', 'x_merge', '=', 'merge_layer(x)', 'x', '=', 'self.reduce_channel(x,', 'x_merge.featu... | 409,924 |
AgnostiqHQ/covalent | result.py | Result.status | status | Status of current dispatch. | [
"Status",
"of",
"current",
"dispatch."
] | def status(self) -> Status:
return self._status | ['def', 'status(self)', '->', 'Status:', 'return', 'self._status'] | 489,478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.