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
kcg2015/Vehicle-Detection-and-Tracking
main.py
assign_detections_to_trackers
assign_detections_to_trackers
From current list of trackers and new detections, output matched detections, unmatchted trackers, unmatched detections.
[ "From", "current", "list", "of", "trackers", "and", "new", "detections,", "output", "matched", "detections,", "unmatchted", "trackers,", "unmatched", "detections." ]
def assign_detections_to_trackers(trackers, detections, iou_thrd=0.3): IOU_mat = np.zeros((len(trackers), len(detections)), dtype=np.float32) for (t, trk) in enumerate(trackers): for (d, det) in enumerate(detections): IOU_mat[t, d] = box_iou2(trk, det) matched_idx = linear_assignment(-IO...
['def', 'assign_detections_to_trackers(trackers,', 'detections,', 'iou_thrd=0.3):', 'IOU_mat', '=', 'np.zeros((len(trackers),', 'len(detections)),', 'dtype=np.float32)', 'for', '(t,', 'trk)', 'in', 'enumerate(trackers):', 'for', '(d,', 'det)', 'in', 'enumerate(detections):', 'IOU_mat[t,', 'd]', '=', 'box_iou2(trk,', 'd...
931,320
kkk324/Vehicle-Distance-Detection
voc_to_tfrecords.py
process_image
process_image
Decode image at given path.
[ "Decode", "image", "at", "given", "path." ]
def process_image(image_path): with open(image_path, 'rb') as f: image_data = f.read() image = decoder_sess.run(decoded_jpeg, feed_dict={image_placeholder: image_data}) assert len(image.shape) == 3 height = image.shape[0] width = image.shape[2] assert image.shape[2] == 3 return (imag...
['def', 'process_image(image_path):', 'with', 'open(image_path,', "'rb')", 'as', 'f:', 'image_data', '=', 'f.read()', 'image', '=', 'decoder_sess.run(decoded_jpeg,', 'feed_dict={image_placeholder:', 'image_data})', 'assert', 'len(image.shape)', '==', '3', 'height', '=', 'image.shape[0]', 'width', '=', 'image.shape[2]',...
931,361
mme/vergeml
cache.py
_CacheFileContent.read
read
Read the content index from file.
[ "Read", "the", "content", "index", "from", "file." ]
def read(self, file, path): (pos,) = struct.unpack('<Q', file.read(8)) if pos == 0: raise VergeMLError('Invalid cache file: {}'.format(path)) file.seek(pos) (self.index, self.meta, self.info) = pickle.load(file)
['def', 'read(self,', 'file,', 'path):', '(pos,)', '=', "struct.unpack('<Q',", 'file.read(8))', 'if', 'pos', '==', '0:', 'raise', "VergeMLError('Invalid", 'cache', 'file:', "{}'.format(path))", 'file.seek(pos)', '(self.index,', 'self.meta,', 'self.info)', '=', 'pickle.load(file)']
931,489
mme/vergeml
cache.py
_CacheFileContent.write
write
Write the content index to file and update the header.
[ "Write", "the", "content", "index", "to", "file", "and", "update", "the", "header." ]
def write(self, file): pos = file.tell() pickle.dump((self.index, self.meta, self.info), file) file.seek(0) file.write(struct.pack('<Q', pos))
['def', 'write(self,', 'file):', 'pos', '=', 'file.tell()', 'pickle.dump((self.index,', 'self.meta,', 'self.info),', 'file)', 'file.seek(0)', "file.write(struct.pack('<Q',", 'pos))']
931,490
mme/vergeml
command.py
_CommandCallProxy.class_wrapper
class_wrapper
Wraps a class command.
[ "Wraps", "a", "class", "command." ]
def class_wrapper(klass, name): def _wrapper(*args, **kwargs): return _CommandCallProxy(name, klass(*args, **kwargs)) return _wrapper
['def', 'class_wrapper(klass,', 'name):', 'def', '_wrapper(*args,', '**kwargs):', 'return', '_CommandCallProxy(name,', 'klass(*args,', '**kwargs))', 'return', '_wrapper']
931,495
mme/vergeml
command.py
Command.discover
discover
Discover the command configuration defined on a method or object.
[ "Discover", "the", "command", "configuration", "defined", "on", "a", "method", "or", "object." ]
def discover(obj, plugins=PLUGINS): res = None if hasattr(obj, _CMD_META_KEY): res = getattr(obj, _CMD_META_KEY) res.plugins = plugins for option in res.options: option.plugins = plugins return res
['def', 'discover(obj,', 'plugins=PLUGINS):', 'res', '=', 'None', 'if', 'hasattr(obj,', '_CMD_META_KEY):', 'res', '=', 'getattr(obj,', '_CMD_META_KEY)', 'res.plugins', '=', 'plugins', 'for', 'option', 'in', 'res.options:', 'option.plugins', '=', 'plugins', 'return', 'res']
931,497
mme/vergeml
command.py
Command.parse
parse
Parse command line options.
[ "Parse", "command", "line", "options." ]
def parse(self, argv): res = {} (at_names, rest) = parse_trained_models(argv) sub_res = self._parse_subcommand(argv, rest) if sub_res is not None: return sub_res at_opt = self._parse_at_option(at_names, res) assert self.name == rest.pop(0) if self.free_form: return (res.get(a...
['def', 'parse(self,', 'argv):', 'res', '=', '{}', '(at_names,', 'rest)', '=', 'parse_trained_models(argv)', 'sub_res', '=', 'self._parse_subcommand(argv,', 'rest)', 'if', 'sub_res', 'is', 'not', 'None:', 'return', 'sub_res', 'at_opt', '=', 'self._parse_at_option(at_names,', 'res)', 'assert', 'self.name', '==', 'rest.p...
931,500
mme/vergeml
config.py
parse_device
parse_device
Parse the device section of the config file.
[ "Parse", "the", "device", "section", "of", "the", "config", "file." ]
def parse_device(section, device_id=None, device_memory=None): section = deepcopy(section or {}) if isinstance(section, str): section = {'id': section} if device_id: section['id'] = device_id if device_memory: section['memory'] = device_memory res = {'id': 'auto', 'memory': '...
['def', 'parse_device(section,', 'device_id=None,', 'device_memory=None):', 'section', '=', 'deepcopy(section', 'or', '{})', 'if', 'isinstance(section,', 'str):', 'section', '=', "{'id':", 'section}', 'if', 'device_id:', "section['id']", '=', 'device_id', 'if', 'device_memory:', "section['memory']", '=', 'device_memory...
931,501
mme/vergeml
config.py
load_yaml_file
load_yaml_file
Load a yaml config file.
[ "Load", "a", "yaml", "config", "file." ]
def load_yaml_file(filename, label='config file', loader=yaml.Loader): try: with open(filename, 'r') as file: res = yaml.load(file.read(), Loader=loader) or {} if not isinstance(res, dict): msg = f'Please ensure that {label} consists of key value pairs.' ...
['def', 'load_yaml_file(filename,', "label='config", "file',", 'loader=yaml.Loader):', 'try:', 'with', 'open(filename,', "'r')", 'as', 'file:', 'res', '=', 'yaml.load(file.read(),', 'Loader=loader)', 'or', '{}', 'if', 'not', 'isinstance(res,', 'dict):', 'msg', '=', "f'Please", 'ensure', 'that', '{label}', 'consists', '...
931,504
mme/vergeml
config.py
yaml_find_definition
yaml_find_definition
Find the location of the definition of key in the YAML source.
[ "Find", "the", "location", "of", "the", "definition", "of", "key", "in", "the", "YAML", "source." ]
def yaml_find_definition(stream, key, kind='key'): assert kind in ('key', 'value') keys = list(map(lambda k: int(k) if k.isdigit() else k, key.split('.'))) level = -1 matches = [False] * len(keys) indices = [] ann = _YAMLAnalyzer(stream) tok = ann.get_token() while tok: if isinst...
['def', 'yaml_find_definition(stream,', 'key,', "kind='key'):", 'assert', 'kind', 'in', "('key',", "'value')", 'keys', '=', 'list(map(lambda', 'k:', 'int(k)', 'if', 'k.isdigit()', 'else', 'k,', "key.split('.')))", 'level', '=', '-1', 'matches', '=', '[False]', '*', 'len(keys)', 'indices', '=', '[]', 'ann', '=', '_YAMLA...
931,505
mme/vergeml
data.py
Data.num_samples
num_samples
Return the number of samples in split.
[ "Return", "the", "number", "of", "samples", "in", "split." ]
def num_samples(self, split): self.loader.begin_read_samples() res = self.loader.num_samples(split) self.loader.end_read_samples() return res
['def', 'num_samples(self,', 'split):', 'self.loader.begin_read_samples()', 'res', '=', 'self.loader.num_samples(split)', 'self.loader.end_read_samples()', 'return', 'res']
931,508
mme/vergeml
env.py
Environment.set
set
Set a value by its path.
[ "Set", "a", "value", "by", "its", "path." ]
def set(self, path, value): dict_set_path(self._config, path, value)
['def', 'set(self,', 'path,', 'value):', 'dict_set_path(self._config,', 'path,', 'value)']
931,516
mme/vergeml
env.py
Environment.samples_dir
samples_dir
Return the samples_dir or throw an error if it does not exist.
[ "Return", "the", "samples_dir", "or", "throw", "an", "error", "if", "it", "does", "not", "exist." ]
def samples_dir(self): samples_dir = self._config['samples-dir'] if not os.path.exists(samples_dir): raise VergeMLError(f'Could not find samples directory: {samples_dir}') elif not os.path.isdir(samples_dir): raise VergeMLError(f'Configured samples-dir is not a directory: {samples_dir}') ...
['def', 'samples_dir(self):', 'samples_dir', '=', "self._config['samples-dir']", 'if', 'not', 'os.path.exists(samples_dir):', 'raise', "VergeMLError(f'Could", 'not', 'find', 'samples', 'directory:', "{samples_dir}')", 'elif', 'not', 'os.path.isdir(samples_dir):', 'raise', "VergeMLError(f'Configured", 'samples-dir', 'is...
931,517
mme/vergeml
env.py
Environment.cancel_training
cancel_training
Cancel a training session.
[ "Cancel", "a", "training", "session." ]
def cancel_training(self): assert self.training, 'Must call start_training() first.' self.results.add({'status': 'CANCELED', 'training-end': time.time()}) self.results.flush() self.training.end() self.training = None
['def', 'cancel_training(self):', 'assert', 'self.training,', "'Must", 'call', 'start_training()', "first.'", "self.results.add({'status':", "'CANCELED',", "'training-end':", 'time.time()})', 'self.results.flush()', 'self.training.end()', 'self.training', '=', 'None']
931,524
mme/vergeml
env.py
Environment.data
data
Return the data loader.
[ "Return", "the", "data", "loader." ]
def data(self): if not self._data: self._data = Data(self, plugins=self.plugins) return self._data
['def', 'data(self):', 'if', 'not', 'self._data:', 'self._data', '=', 'Data(self,', 'plugins=self.plugins)', 'return', 'self._data']
931,525
mme/vergeml
env.py
Environment.progress_callback
progress_callback
Get a generic callback to capture training progress.
[ "Get", "a", "generic", "callback", "to", "capture", "training", "progress." ]
def progress_callback(self, epochs=None, steps=None, display_progress='epochs-steps', stats=_DEFAULT_STATS): assert self.training, 'Must call start_training() before calling progress_callback()' assert display_progress in ('epochs', 'steps', 'epochs-steps', None) stats = deepcopy(stats) return self.trai...
['def', 'progress_callback(self,', 'epochs=None,', 'steps=None,', "display_progress='epochs-steps',", 'stats=_DEFAULT_STATS):', 'assert', 'self.training,', "'Must", 'call', 'start_training()', 'before', 'calling', "progress_callback()'", 'assert', 'display_progress', 'in', "('epochs',", "'steps',", "'epochs-steps',", '...
931,527
mme/vergeml
env.py
Environment.keras_callback
keras_callback
Get a callback suitable for passing to keras to get training feedback.
[ "Get", "a", "callback", "suitable", "for", "passing", "to", "keras", "to", "get", "training", "feedback." ]
def keras_callback(self, display_progress='epochs-steps', stats=_DEFAULT_STATS): assert self.training, 'Must call start_training() before calling keras_callback()' return KerasLibrary.callback(self, display_progress, stats)
['def', 'keras_callback(self,', "display_progress='epochs-steps',", 'stats=_DEFAULT_STATS):', 'assert', 'self.training,', "'Must", 'call', 'start_training()', 'before', 'calling', "keras_callback()'", 'return', 'KerasLibrary.callback(self,', 'display_progress,', 'stats)']
931,528
mme/vergeml
env.py
Environment.tensorflow_session
tensorflow_session
Create a new tensorflow session as configured in the environment.
[ "Create", "a", "new", "tensorflow", "session", "as", "configured", "in", "the", "environment." ]
def tensorflow_session(self): return TensorFlowLibrary.create_session(self)
['def', 'tensorflow_session(self):', 'return', 'TensorFlowLibrary.create_session(self)']
931,529
mme/vergeml
img.py
fixext
fixext
Change the format of files with the wrong extension.
[ "Change", "the", "format", "of", "files", "with", "the", "wrong", "extension." ]
def fixext(path, img): (path, ext) = os.path.splitext(path) if img.format: return path + '.' + img.format.lower() elif img.mode == 'RGBA': return path + '.png' elif ext.lower() not in ['.jpg', '.jpeg', '.png', '.bmp']: return path + '.png' else: return path + ext
['def', 'fixext(path,', 'img):', '(path,', 'ext)', '=', 'os.path.splitext(path)', 'if', 'img.format:', 'return', 'path', '+', "'.'", '+', 'img.format.lower()', 'elif', 'img.mode', '==', "'RGBA':", 'return', 'path', '+', "'.png'", 'elif', 'ext.lower()', 'not', 'in', "['.jpg',", "'.jpeg',", "'.png',", "'.bmp']:", 'return...
931,532
mme/vergeml
io.py
SourcePlugin.transform
transform
Return the sample with x and y transformed to its final form.
[ "Return", "the", "sample", "with", "x", "and", "y", "transformed", "to", "its", "final", "form." ]
def transform(self, sample): raise NotImplementedError
['def', 'transform(self,', 'sample):', 'raise', 'NotImplementedError']
931,540
mme/vergeml
io.py
SourcePlugin.preview_filename
preview_filename
Generate a filename for previews, appending a number when the file already exists.
[ "Generate", "a", "filename", "for", "previews,", "appending", "a", "number", "when", "the", "file", "already", "exists." ]
def preview_filename(self, path): if not os.path.exists(path): return path pcounter = SourcePlugin._COUNTER if not path in pcounter: pcounter[path] = 1 (fname, ext) = os.path.splitext(path) counter = pcounter[path] while os.path.exists('{}_{}{}'.format(fname, counter, ext)): ...
['def', 'preview_filename(self,', 'path):', 'if', 'not', 'os.path.exists(path):', 'return', 'path', 'pcounter', '=', 'SourcePlugin._COUNTER', 'if', 'not', 'path', 'in', 'pcounter:', 'pcounter[path]', '=', '1', '(fname,', 'ext)', '=', 'os.path.splitext(path)', 'counter', '=', 'pcounter[path]', 'while', "os.path.exists('...
931,550
mme/vergeml
loader.py
Loader.progress_callback
progress_callback
Set this callback in order to receive progress updates.
[ "Set", "this", "callback", "in", "order", "to", "receive", "progress", "updates." ]
def progress_callback(self): return self._progress_callback
['def', 'progress_callback(self):', 'return', 'self._progress_callback']
931,553
mme/vergeml
loader.py
Loader.begin_read_samples
begin_read_samples
Prepare to start reading samples.
[ "Prepare", "to", "start", "reading", "samples." ]
def begin_read_samples(self): raise NotImplementedError
['def', 'begin_read_samples(self):', 'raise', 'NotImplementedError']
931,555
mme/vergeml
loader.py
Loader.perform_read
perform_read
Perform the actual read operation on the cache object.
[ "Perform", "the", "actual", "read", "operation", "on", "the", "cache", "object." ]
def perform_read(self, split: str, index: int, n_samples: int=1): return self.cache[split].read(index, n_samples)
['def', 'perform_read(self,', 'split:', 'str,', 'index:', 'int,', 'n_samples:', 'int=1):', 'return', 'self.cache[split].read(index,', 'n_samples)']
931,558
mme/vergeml
random_robot.py
random_robot_name
random_robot_name
Construct a random robot name.
[ "Construct", "a", "random", "robot", "name." ]
def random_robot_name(moment_of_birth, dest=None): random.seed(moment_of_birth) adj = random.choice(_ADJ) noun = random.choice(_NOUN) name = '{}-{}'.format(adj, noun).lower() if dest and os.path.exists(os.path.join(dest, name)): return random_robot_name(datetime.now(), dest) return name
['def', 'random_robot_name(moment_of_birth,', 'dest=None):', 'random.seed(moment_of_birth)', 'adj', '=', 'random.choice(_ADJ)', 'noun', '=', 'random.choice(_NOUN)', 'name', '=', "'{}-{}'.format(adj,", 'noun).lower()', 'if', 'dest', 'and', 'os.path.exists(os.path.join(dest,', 'name)):', 'return', 'random_robot_name(date...
931,571
mme/vergeml
random_robot.py
ascii_robot
ascii_robot
Generate random robot ascii art.
[ "Generate", "random", "robot", "ascii", "art." ]
def ascii_robot(moment_of_birth, name, include_phrase=True): random.seed(moment_of_birth) def paste(cur, *lines): cur = list(cur) for line in lines: if len(line) > len(cur): cur += [' '] * (len(line) - len(cur)) for (i, char) in enumerate(line): ...
['def', 'ascii_robot(moment_of_birth,', 'name,', 'include_phrase=True):', 'random.seed(moment_of_birth)', 'def', 'paste(cur,', '*lines):', 'cur', '=', 'list(cur)', 'for', 'line', 'in', 'lines:', 'if', 'len(line)', '>', 'len(cur):', 'cur', '+=', "['", "']", '*', '(len(line)', '-', 'len(cur))', 'for', '(i,', 'char)', 'in...
931,572
mme/vergeml
utils.py
wrap_text
wrap_text
Wrap text to be readable in the terminal.
[ "Wrap", "text", "to", "be", "readable", "in", "the", "terminal." ]
def wrap_text(text): res = [] for para in text.split('\n\n'): if para.splitlines()[0].strip().endswith(':'): res.append(para) else: res.append(textwrap.fill(para, drop_whitespace=True, fix_sentence_endings=True)) return '\n\n'.join(res)
['def', 'wrap_text(text):', 'res', '=', '[]', 'for', 'para', 'in', "text.split('\\n\\n'):", 'if', "para.splitlines()[0].strip().endswith(':'):", 'res.append(para)', 'else:', 'res.append(textwrap.fill(para,', 'drop_whitespace=True,', 'fix_sentence_endings=True))', 'return', "'\\n\\n'.join(res)"]
931,574
mme/vergeml
utils.py
introspect
introspect
Introspect a function call.
[ "Introspect", "a", "function", "call." ]
def introspect(call): spec = inspect.getfullargspec(call) args = spec.args defaults = dict(zip(reversed(spec.args), reversed(spec.defaults or []))) types = spec.annotations return _Intro(args, defaults, types)
['def', 'introspect(call):', 'spec', '=', 'inspect.getfullargspec(call)', 'args', '=', 'spec.args', 'defaults', '=', 'dict(zip(reversed(spec.args),', 'reversed(spec.defaults', 'or', '[])))', 'types', '=', 'spec.annotations', 'return', '_Intro(args,', 'defaults,', 'types)']
931,575
mme/vergeml
utils.py
dict_del_path
dict_del_path
Delete a value from a dict using path syntax.
[ "Delete", "a", "value", "from", "a", "dict", "using", "path", "syntax." ]
def dict_del_path(dic, path): if isinstance(path, str): path = path.split('.') if len(path) == 1: del [dic[path[0]]] else: (pat, *rest) = path dict_del_path(dic[pat], rest) if not dic[pat]: del dic[pat]
['def', 'dict_del_path(dic,', 'path):', 'if', 'isinstance(path,', 'str):', 'path', '=', "path.split('.')", 'if', 'len(path)', '==', '1:', 'del', '[dic[path[0]]]', 'else:', '(pat,', '*rest)', '=', 'path', 'dict_del_path(dic[pat],', 'rest)', 'if', 'not', 'dic[pat]:', 'del', 'dic[pat]']
931,578
mme/vergeml
utils.py
dict_get_path
dict_get_path
Get the value of a dict using path syntax.
[ "Get", "the", "value", "of", "a", "dict", "using", "path", "syntax." ]
def dict_get_path(dic, path, default=_DEFAULT): cur = dic for pat in path.split('.'): if isinstance(cur, dict) and pat in cur: cur = cur[pat] elif default != _DEFAULT: return default else: raise KeyError(path) return cur
['def', 'dict_get_path(dic,', 'path,', 'default=_DEFAULT):', 'cur', '=', 'dic', 'for', 'pat', 'in', "path.split('.'):", 'if', 'isinstance(cur,', 'dict)', 'and', 'pat', 'in', 'cur:', 'cur', '=', 'cur[pat]', 'elif', 'default', '!=', '_DEFAULT:', 'return', 'default', 'else:', 'raise', 'KeyError(path)', 'return', 'cur']
931,580
mme/vergeml
utils.py
dict_paths
dict_paths
Get paths in a dict.
[ "Get", "paths", "in", "a", "dict." ]
def dict_paths(dic, path=None): res = [] if path: if not dict_has_path(dic, path): return res value = dict_get_path(dic, path) else: value = dic if not isinstance(dic, dict): return res def _collect_path(dic, path): for (k, val) in dic.items(): ...
['def', 'dict_paths(dic,', 'path=None):', 'res', '=', '[]', 'if', 'path:', 'if', 'not', 'dict_has_path(dic,', 'path):', 'return', 'res', 'value', '=', 'dict_get_path(dic,', 'path)', 'else:', 'value', '=', 'dic', 'if', 'not', 'isinstance(dic,', 'dict):', 'return', 'res', 'def', '_collect_path(dic,', 'path):', 'for', '(k...
931,581
mme/vergeml
utils.py
parse_trained_models
parse_trained_models
Parse @syntax for specifying trained models on the command line.
[ "Parse", "@syntax", "for", "specifying", "trained", "models", "on", "the", "command", "line." ]
def parse_trained_models(argv): names = [] for part in argv: if re.match('^@[a-zA-Z0-9_-]+$', part): names.append(part[1:]) else: break rest = argv[len(names):] return (names, rest)
['def', 'parse_trained_models(argv):', 'names', '=', '[]', 'for', 'part', 'in', 'argv:', 'if', "re.match('^@[a-zA-Z0-9_-]+$',", 'part):', 'names.append(part[1:])', 'else:', 'break', 'rest', '=', 'argv[len(names):]', 'return', '(names,', 'rest)']
931,582
mme/vergeml
utils.py
xlink
xlink
Cross platform file links.
[ "Cross", "platform", "file", "links." ]
def xlink(src, dst): os.symlink(src, dst)
['def', 'xlink(src,', 'dst):', 'os.symlink(src,', 'dst)']
931,586
mme/vergeml
__main__.py
run
run
Run from command line.
[ "Run", "from", "command", "line." ]
def run(argv, plugins=PLUGINS): try: argv = _forgive_wrong_option_order(argv) (args, rest) = _parsebase(argv) except getopt.GetoptError as err: if err.opt: opt = err.opt.lstrip('-') dashes = '-' if len(opt) == 1 else '--' raise VergeMLError(f'Invalid o...
['def', 'run(argv,', 'plugins=PLUGINS):', 'try:', 'argv', '=', '_forgive_wrong_option_order(argv)', '(args,', 'rest)', '=', '_parsebase(argv)', 'except', 'getopt.GetoptError', 'as', 'err:', 'if', 'err.opt:', 'opt', '=', "err.opt.lstrip('-')", 'dashes', '=', "'-'", 'if', 'len(opt)', '==', '1', 'else', "'--'", 'raise', "...
931,587
mme/vergeml
__main__.py
print_version
print_version
Print VergeML version and versions of various libraries used.
[ "Print", "VergeML", "version", "and", "versions", "of", "various", "libraries", "used." ]
def print_version(): print('----------------') print(f'VergeML {__version__}') print('----------------') print('') print('Installed Libraries:') print('') sys.stdout.flush() for (lib, label) in [(PythonInterpreter, 'Python'), (NumPyLibrary, 'Numpy'), (TensorFlowLibrary, 'TensorFlow'), (K...
['def', 'print_version():', "print('----------------')", "print(f'VergeML", "{__version__}')", "print('----------------')", "print('')", "print('Installed", "Libraries:')", "print('')", 'sys.stdout.flush()', 'for', '(lib,', 'label)', 'in', '[(PythonInterpreter,', "'Python'),", '(NumPyLibrary,', "'Numpy'),", '(TensorFlo...
931,588
aledelmo/VesselsSegmentation
surgery.py
interp
interp
Set weights of each layer in layers to bilinear kernels for interpolation.
[ "Set", "weights", "of", "each", "layer", "in", "layers", "to", "bilinear", "kernels", "for", "interpolation." ]
def interp(net, layers): for l in layers: (m, k, h, w) = net.params[l][0].data.shape if m != k and k != 1: print('input + output channels need to be the same or |output| == 1') raise ValueError if h != w: print('filters need to be square') rais...
['def', 'interp(net,', 'layers):', 'for', 'l', 'in', 'layers:', '(m,', 'k,', 'h,', 'w)', '=', 'net.params[l][0].data.shape', 'if', 'm', '!=', 'k', 'and', 'k', '!=', '1:', "print('input", '+', 'output', 'channels', 'need', 'to', 'be', 'the', 'same', 'or', '|output|', '==', "1')", 'raise', 'ValueError', 'if', 'h', '!=', ...
931,602
crowsonkb/vgg_loss
helpers.py
inspect_outputs
inspect_outputs
Registers hooks on each submodule that print their outputs.
[ "Registers", "hooks", "on", "each", "submodule", "that", "print", "their", "outputs." ]
def inspect_outputs(module): def make_hook(name): return lambda m, i, o: print(f'({name}) {type(m).__name__}: {o}') for (name, mod) in module.named_children(): mod.register_forward_hook(make_hook(name))
['def', 'inspect_outputs(module):', 'def', 'make_hook(name):', 'return', 'lambda', 'm,', 'i,', 'o:', "print(f'({name})", '{type(m).__name__}:', "{o}')", 'for', '(name,', 'mod)', 'in', 'module.named_children():', 'mod.register_forward_hook(make_hook(name))']
931,615
roseperrone/video-object-detection
video_id_fetcher.py
get_noun_ids_and_video_ids
get_noun_ids_and_video_ids
Returns: an OrderedDict that contains alphabetically ordered nouns as keys, and each value is a list of `num_videos_per_noun` video ids of videos that likely contain that noun, as per the search queries in `QUERIES_AND_NOUNS`.
[ "Returns:", "an", "OrderedDict", "that", "contains", "alphabetically", "ordered", "nouns", "as", "keys,", "and", "each", "value", "is", "a", "list", "of", "`num_videos_per_noun`", "video", "ids", "of", "videos", "that", "likely", "contain", "that", "noun,", "as"...
def get_noun_ids_and_video_ids(num_videos_per_noun): d = defaultdict(list) for (noun, queries) in invert_dictionary(QUERIES_AND_NOUNS).iteritems(): videos_per_query = num_videos_per_noun / len(queries) remainder = num_videos_per_noun - videos_per_query * len(queries) for query in queries...
['def', 'get_noun_ids_and_video_ids(num_videos_per_noun):', 'd', '=', 'defaultdict(list)', 'for', '(noun,', 'queries)', 'in', 'invert_dictionary(QUERIES_AND_NOUNS).iteritems():', 'videos_per_query', '=', 'num_videos_per_noun', '/', 'len(queries)', 'remainder', '=', 'num_videos_per_noun', '-', 'videos_per_query', '*', '...
931,640
openai/vime
bnn.py
BNNLayer.save_old_params
save_old_params
Save old parameter values for KL calculation.
[ "Save", "old", "parameter", "values", "for", "KL", "calculation." ]
def save_old_params(self): self.mu_old.set_value(self.mu.get_value()) self.rho_old.set_value(self.rho.get_value()) self.b_mu_old.set_value(self.b_mu.get_value()) self.b_rho_old.set_value(self.b_rho.get_value())
['def', 'save_old_params(self):', 'self.mu_old.set_value(self.mu.get_value())', 'self.rho_old.set_value(self.rho.get_value())', 'self.b_mu_old.set_value(self.b_mu.get_value())', 'self.b_rho_old.set_value(self.b_rho.get_value())']
931,733
openai/vime
bnn.py
BNNLayer.reset_to_old_params
reset_to_old_params
Reset to old parameter values for KL calculation.
[ "Reset", "to", "old", "parameter", "values", "for", "KL", "calculation." ]
def reset_to_old_params(self): self.mu.set_value(self.mu_old.get_value()) self.rho.set_value(self.rho_old.get_value()) self.b_mu.set_value(self.b_mu_old.get_value()) self.b_rho.set_value(self.b_rho_old.get_value())
['def', 'reset_to_old_params(self):', 'self.mu.set_value(self.mu_old.get_value())', 'self.rho.set_value(self.rho_old.get_value())', 'self.b_mu.set_value(self.b_mu_old.get_value())', 'self.b_rho.set_value(self.b_rho_old.get_value())']
931,734
hailanyi/VirConv
dataset.py
DatasetTemplate.partition
partition
partition the points into several bins.
[ "partition", "the", "points", "into", "several", "bins." ]
def partition(self, points, num=10, max_dis=60, rate=0.2): points_list = [] inter = max_dis / num all_points_num = points.shape[0] points_num_acc = 0 position = num - 1 distant_points_num_acc = 0 for i in range(num): i = num - i - 1 if i == num - 1: min_mask = poi...
['def', 'partition(self,', 'points,', 'num=10,', 'max_dis=60,', 'rate=0.2):', 'points_list', '=', '[]', 'inter', '=', 'max_dis', '/', 'num', 'all_points_num', '=', 'points.shape[0]', 'points_num_acc', '=', '0', 'position', '=', 'num', '-', '1', 'distant_points_num_acc', '=', '0', 'for', 'i', 'in', 'range(num):', 'i', '...
931,760
hailanyi/VirConv
spconv_backbone.py
index2uv3d
index2uv3d
convert the 3D voxel indices to image pixel indices.
[ "convert", "the", "3D", "voxel", "indices", "to", "image", "pixel", "indices." ]
def index2uv3d(indices, batch_size, calib, stride, x_trans_train, trans_param): new_uv = indices.clone().int() for b_i in range(batch_size): cur_in = indices[indices[:, 0] == b_i] cur_pts = index2points(cur_in, stride=stride) if trans_param is not None: transed = x_trans_trai...
['def', 'index2uv3d(indices,', 'batch_size,', 'calib,', 'stride,', 'x_trans_train,', 'trans_param):', 'new_uv', '=', 'indices.clone().int()', 'for', 'b_i', 'in', 'range(batch_size):', 'cur_in', '=', 'indices[indices[:,', '0]', '==', 'b_i]', 'cur_pts', '=', 'index2points(cur_in,', 'stride=stride)', 'if', 'trans_param', ...
931,775
hailanyi/VirConv
spconv_backbone.py
layer_voxel_discard
layer_voxel_discard
discard the voxels based on the given rate.
[ "discard", "the", "voxels", "based", "on", "the", "given", "rate." ]
def layer_voxel_discard(sparse_t, rat=0.15): if rat == 0: return len = sparse_t.features.shape[0] randoms = np.random.permutation(len) randoms = torch.from_numpy(randoms[0:int(len * (1 - rat))]).to(sparse_t.features.device) sparse_t = replace_feature(sparse_t, sparse_t.features[randoms]) ...
['def', 'layer_voxel_discard(sparse_t,', 'rat=0.15):', 'if', 'rat', '==', '0:', 'return', 'len', '=', 'sparse_t.features.shape[0]', 'randoms', '=', 'np.random.permutation(len)', 'randoms', '=', 'torch.from_numpy(randoms[0:int(len', '*', '(1', '-', 'rat))]).to(sparse_t.features.device)', 'sparse_t', '=', 'replace_featur...
931,777
hailanyi/VirConv
metrics.py
log10
log10
Convert a new tensor with the base-10 logarithm of the elements of x.
[ "Convert", "a", "new", "tensor", "with", "the", "base-10", "logarithm", "of", "the", "elements", "of", "x." ]
def log10(x): return torch.log(x) / lg_e_10
['def', 'log10(x):', 'return', 'torch.log(x)', '/', 'lg_e_10']
931,816
pramodiperera/virtual-keyboard
_in_process.py
prepare_metadata_for_build_editable
prepare_metadata_for_build_editable
Invoke optional prepare_metadata_for_build_editable Implements a fallback by building an editable wheel if the hook isn't defined, unless _allow_fallback is False in which case HookMissing is raised.
[ "Invoke", "optional", "prepare_metadata_for_build_editable", "Implements", "a", "fallback", "by", "building", "an", "editable", "wheel", "if", "the", "hook", "isn't", "defined,", "unless", "_allow_fallback", "is", "False", "in", "which", "case", "HookMissing", "is", ...
def prepare_metadata_for_build_editable(metadata_directory, config_settings, _allow_fallback): backend = _build_backend() try: hook = backend.prepare_metadata_for_build_editable except AttributeError: if not _allow_fallback: raise HookMissing() try: build_hook...
['def', 'prepare_metadata_for_build_editable(metadata_directory,', 'config_settings,', '_allow_fallback):', 'backend', '=', '_build_backend()', 'try:', 'hook', '=', 'backend.prepare_metadata_for_build_editable', 'except', 'AttributeError:', 'if', 'not', '_allow_fallback:', 'raise', 'HookMissing()', 'try:', 'build_hook'...
932,515
pramodiperera/virtual-keyboard
_parser.py
load
load
Parse TOML from a file object.
[ "Parse", "TOML", "from", "a", "file", "object." ]
def load(fp: TextIO, *, parse_float: ParseFloat=float) -> Dict[str, Any]: s = fp.read() return loads(s, parse_float=parse_float)
['def', 'load(fp:', 'TextIO,', '*,', 'parse_float:', 'ParseFloat=float)', '->', 'Dict[str,', 'Any]:', 's', '=', 'fp.read()', 'return', 'loads(s,', 'parse_float=parse_float)']
932,631
batra-mlp-lab/visdial-rl
questioner.py
Questioner.forward
forward
Forward pass the last observed question to compute its log likelihood under the current decoder RNN state.
[ "Forward", "pass", "the", "last", "observed", "question", "to", "compute", "its", "log", "likelihood", "under", "the", "current", "decoder", "RNN", "state." ]
def forward(self): encStates = self.encoder() if len(self.questions) == 0: raise Exception('Must provide question if not sampling one.') decIn = self.questions[-1] logProbs = self.decoder(encStates, inputSeq=decIn) return logProbs
['def', 'forward(self):', 'encStates', '=', 'self.encoder()', 'if', 'len(self.questions)', '==', '0:', 'raise', "Exception('Must", 'provide', 'question', 'if', 'not', 'sampling', "one.')", 'decIn', '=', 'self.questions[-1]', 'logProbs', '=', 'self.decoder(encStates,', 'inputSeq=decIn)', 'return', 'logProbs']
933,545
lmzh123/ships_detection
sliding_window.py
pyramid
pyramid
This function returns a set of scaled images known as the image pyramid, the initial image is downscaled by a certain scale until the minimum size of the image is reached.
[ "This", "function", "returns", "a", "set", "of", "scaled", "images", "known", "as", "the", "image", "pyramid,", "the", "initial", "image", "is", "downscaled", "by", "a", "certain", "scale", "until", "the", "minimum", "size", "of", "the", "image", "is", "re...
def pyramid(image, scale=1.5, minSize=(30, 30)): yield image while True: w = int(image.shape[1] / scale) image = imutils.resize(image, width=w) if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]: break yield image
['def', 'pyramid(image,', 'scale=1.5,', 'minSize=(30,', '30)):', 'yield', 'image', 'while', 'True:', 'w', '=', 'int(image.shape[1]', '/', 'scale)', 'image', '=', 'imutils.resize(image,', 'width=w)', 'if', 'image.shape[0]', '<', 'minSize[1]', 'or', 'image.shape[1]', '<', 'minSize[0]:', 'break', 'yield', 'image']
933,665
kukuruza/shuffler
shuffler_cli.py
connect
connect
Connect to a new or existing database.
[ "Connect", "to", "a", "new", "or", "existing", "database." ]
def connect(in_db_path=None, out_db_path=None): if in_db_path is not None and (not op.exists(in_db_path)): raise FileNotFoundError('in_db_path specified but does not exist: %s' % in_db_path) logging.info('in_db_path: %s', in_db_path) logging.info('out_db_path: %s', out_db_path) if in_db_path is...
['def', 'connect(in_db_path=None,', 'out_db_path=None):', 'if', 'in_db_path', 'is', 'not', 'None', 'and', '(not', 'op.exists(in_db_path)):', 'raise', "FileNotFoundError('in_db_path", 'specified', 'but', 'does', 'not', 'exist:', "%s'", '%', 'in_db_path)', "logging.info('in_db_path:", "%s',", 'in_db_path)', "logging.info...
933,773
kukuruza/shuffler
backend_db.py
connect
connect
Connect to database in different ways.
[ "Connect", "to", "database", "in", "different", "ways." ]
def connect(in_db_path, how): if how == 'read_only': conn = sqlite3.connect('file:%s?mode=ro' % in_db_path, uri=True) elif how == 'load_to_memory': conn = _load_db_to_memory(in_db_path) elif how == 'as_write': conn = sqlite3.connect(in_db_path) return conn
['def', 'connect(in_db_path,', 'how):', 'if', 'how', '==', "'read_only':", 'conn', '=', "sqlite3.connect('file:%s?mode=ro'", '%', 'in_db_path,', 'uri=True)', 'elif', 'how', '==', "'load_to_memory':", 'conn', '=', '_load_db_to_memory(in_db_path)', 'elif', 'how', '==', "'as_write':", 'conn', '=', 'sqlite3.connect(in_db_p...
933,774
kukuruza/shuffler
backend_db.py
createDb
createDb
Creates all the necessary tables and indexes.
[ "Creates", "all", "the", "necessary", "tables", "and", "indexes." ]
def createDb(conn): cursor = conn.cursor() conn.execute('PRAGMA user_version = 5') createTableImages(cursor) createTableObjects(cursor) createTableProperties(cursor) createTablePolygons(cursor) createTableMatches(cursor)
['def', 'createDb(conn):', 'cursor', '=', 'conn.cursor()', "conn.execute('PRAGMA", 'user_version', '=', "5')", 'createTableImages(cursor)', 'createTableObjects(cursor)', 'createTableProperties(cursor)', 'createTablePolygons(cursor)', 'createTableMatches(cursor)']
933,775
kukuruza/shuffler
backend_db.py
retireTables
retireTables
Changes names of tables to ***_old, and recreates brand-new tables.
[ "Changes", "names", "of", "tables", "to", "***_old,", "and", "recreates", "brand-new", "tables." ]
def retireTables(cursor, names=None): if names is None or 'images' in names: cursor.execute('ALTER TABLE images RENAME TO images_old') createTableImages(cursor) if names is None or 'objects' in names: cursor.execute('ALTER TABLE objects RENAME TO objects_old') createTableObjects(...
['def', 'retireTables(cursor,', 'names=None):', 'if', 'names', 'is', 'None', 'or', "'images'", 'in', 'names:', "cursor.execute('ALTER", 'TABLE', 'images', 'RENAME', 'TO', "images_old')", 'createTableImages(cursor)', 'if', 'names', 'is', 'None', 'or', "'objects'", 'in', 'names:', "cursor.execute('ALTER", 'TABLE', 'objec...
933,776
kukuruza/shuffler
backend_db.py
makeTimeString
makeTimeString
Write a time string in Shuffler format.
[ "Write", "a", "time", "string", "in", "Shuffler", "format." ]
def makeTimeString(time): return datetime.strftime(time, '%Y-%m-%d %H:%M:%S.%f')
['def', 'makeTimeString(time):', 'return', 'datetime.strftime(time,', "'%Y-%m-%d", "%H:%M:%S.%f')"]
933,778
kukuruza/shuffler
backend_db.py
parseTimeString
parseTimeString
Parses the Shuffler format.
[ "Parses", "the", "Shuffler", "format." ]
def parseTimeString(timestring): return datetime.strptime(timestring, '%Y-%m-%d %H:%M:%S.%f')
['def', 'parseTimeString(timestring):', 'return', 'datetime.strptime(timestring,', "'%Y-%m-%d", "%H:%M:%S.%f')"]
933,779
kukuruza/shuffler
backend_db.py
objectEntryToDict
objectEntryToDict
Convert the tuple returned by sqlite3 SELECT into dict.
[ "Convert", "the", "tuple", "returned", "by", "sqlite3", "SELECT", "into", "dict." ]
def objectEntryToDict(entry): return {'objectid': entry[0], 'imagefile': entry[1], 'x1': entry[2], 'y1': entry[3], 'width': entry[4], 'height': entry[5], 'name': entry[6], 'score': entry[7]}
['def', 'objectEntryToDict(entry):', 'return', "{'objectid':", 'entry[0],', "'imagefile':", 'entry[1],', "'x1':", 'entry[2],', "'y1':", 'entry[3],', "'width':", 'entry[4],', "'height':", 'entry[5],', "'name':", 'entry[6],', "'score':", 'entry[7]}']
933,782
kukuruza/shuffler
dataframe.py
Dataframe.save
save
Save open database in Shuffler format, without closing.
[ "Save", "open", "database", "in", "Shuffler", "format,", "without", "closing." ]
def save(self, out_db_path): if self.temp_db_path is None: raise IOError('File was created in-memory. Can not save file.') self.conn.commit() shutil.move(self.temp_db_path, out_db_path) self.temp_db_path = None
['def', 'save(self,', 'out_db_path):', 'if', 'self.temp_db_path', 'is', 'None:', 'raise', "IOError('File", 'was', 'created', 'in-memory.', 'Can', 'not', 'save', "file.')", 'self.conn.commit()', 'shutil.move(self.temp_db_path,', 'out_db_path)', 'self.temp_db_path', '=', 'None']
933,793
kukuruza/shuffler
dataframe.py
Dataframe.close
close
Close an open database.
[ "Close", "an", "open", "database." ]
def close(self): self._clean_up()
['def', 'close(self):', 'self._clean_up()']
933,794
kukuruza/shuffler
shuffler_dataset.py
DatasetWriter.addImage
addImage
Add the image path to the database and (maybe) write an image to disk.
[ "Add", "the", "image", "path", "to", "the", "database", "and", "(maybe)", "write", "an", "image", "to", "disk." ]
def addImage(self, image_dict): if not isinstance(image_dict, Mapping): raise TypeError('image_dict should be a dict, not %s' % type(image_dict)) if ('image' in image_dict) == ('imagefile' in image_dict): raise ValueError('Exactly one of "image" or "imagefile" must be specified.') if 'image'...
['def', 'addImage(self,', 'image_dict):', 'if', 'not', 'isinstance(image_dict,', 'Mapping):', 'raise', "TypeError('image_dict", 'should', 'be', 'a', 'dict,', 'not', "%s'", '%', 'type(image_dict))', 'if', "('image'", 'in', 'image_dict)', '==', "('imagefile'", 'in', 'image_dict):', 'raise', "ValueError('Exactly", 'one', ...
933,795
kukuruza/shuffler
shuffler_dataset_test.py
TestDatasetWriter.test_failed_record_maskfile
test_failed_record_maskfile
Should fail to record an maskfile of mask that does not exist.
[ "Should", "fail", "to", "record", "an", "maskfile", "of", "mask", "that", "does", "not", "exist." ]
def test_failed_record_maskfile(self): out_db_file = op.join(self.work_dir, 'out.db') image_path = op.join(self.work_dir, 'images') image = np.zeros((100, 100, 3), dtype=np.uint8) self.writer = DatasetWriter(out_db_file, image_path=image_path) with self.assertRaises(ValueError): self.writer....
['def', 'test_failed_record_maskfile(self):', 'out_db_file', '=', 'op.join(self.work_dir,', "'out.db')", 'image_path', '=', 'op.join(self.work_dir,', "'images')", 'image', '=', 'np.zeros((100,', '100,', '3),', 'dtype=np.uint8)', 'self.writer', '=', 'DatasetWriter(out_db_file,', 'image_path=image_path)', 'with', 'self.a...
933,798
kukuruza/shuffler
utils.py
buildImageSample
buildImageSample
Load images and get necessary information from object_entry to make a frame.
[ "Load", "images", "and", "get", "necessary", "information", "from", "object_entry", "to", "make", "a", "frame." ]
def buildImageSample(image_entry, cursor, imreader, where_object='TRUE'): imagefile = backend_db.imageField(image_entry, 'imagefile') maskfile = backend_db.imageField(image_entry, 'maskfile') image_width = backend_db.imageField(image_entry, 'width') image_height = backend_db.imageField(image_entry, 'hei...
['def', 'buildImageSample(image_entry,', 'cursor,', 'imreader,', "where_object='TRUE'):", 'imagefile', '=', 'backend_db.imageField(image_entry,', "'imagefile')", 'maskfile', '=', 'backend_db.imageField(image_entry,', "'maskfile')", 'image_width', '=', 'backend_db.imageField(image_entry,', "'width')", 'image_height', '=...
933,801
kukuruza/shuffler
utils.py
checkTransformGroup
checkTransformGroup
Check the type of "transform_group", used in Pytorch and Keras.
[ "Check", "the", "type", "of", "\"transform_group\",", "used", "in", "Pytorch", "and", "Keras." ]
def checkTransformGroup(transform_group): if transform_group is None or callable(transform_group): return elif isinstance(transform_group, list): for transform in transform_group: if not callable(transform): raise TypeError('Transform "%s" is not callable.' % transfor...
['def', 'checkTransformGroup(transform_group):', 'if', 'transform_group', 'is', 'None', 'or', 'callable(transform_group):', 'return', 'elif', 'isinstance(transform_group,', 'list):', 'for', 'transform', 'in', 'transform_group:', 'if', 'not', 'callable(transform):', 'raise', "TypeError('Transform", '"%s"', 'is', 'not', ...
933,804
kukuruza/shuffler
utils.py
checkWhereImage
checkWhereImage
Check the type of "where_image", used in Pytorch and Keras.
[ "Check", "the", "type", "of", "\"where_image\",", "used", "in", "Pytorch", "and", "Keras." ]
def checkWhereImage(where_image): if not isinstance(where_image, str): raise TypeError('where_image is not str, but %s.' % type(where_image))
['def', 'checkWhereImage(where_image):', 'if', 'not', 'isinstance(where_image,', 'str):', 'raise', "TypeError('where_image", 'is', 'not', 'str,', 'but', "%s.'", '%', 'type(where_image))']
933,805
kukuruza/shuffler
utils.py
checkWhereObject
checkWhereObject
Check the type of "where_object", used in Pytorch and Keras.
[ "Check", "the", "type", "of", "\"where_object\",", "used", "in", "Pytorch", "and", "Keras." ]
def checkWhereObject(where_object): if not isinstance(where_object, str): raise TypeError('where_object is not str, but %s.' % type(where_object))
['def', 'checkWhereObject(where_object):', 'if', 'not', 'isinstance(where_object,', 'str):', 'raise', "TypeError('where_object", 'is', 'not', 'str,', 'but', "%s.'", '%', 'type(where_object))']
933,806
kukuruza/shuffler
generators.py
ImageGenerator.close
close
Crucial when the object is contructed in the 'w' mode.
[ "Crucial", "when", "the", "object", "is", "contructed", "in", "the", "'w'", "mode." ]
def close(self): self.conn.close()
['def', 'close(self):', 'self.conn.close()']
933,807
kukuruza/shuffler
generators_demo.py
make_model
make_model
Make a simple two-layer convolutional model.
[ "Make", "a", "simple", "two-layer", "convolutional", "model." ]
def make_model(input_shape, num_classes): model = tf.keras.Sequential([tf.keras.layers.Input(shape=input_shape), tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(64, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPo...
['def', 'make_model(input_shape,', 'num_classes):', 'model', '=', 'tf.keras.Sequential([tf.keras.layers.Input(shape=input_shape),', 'tf.keras.layers.Conv2D(32,', 'kernel_size=(3,', '3),', "activation='relu'),", 'tf.keras.layers.MaxPooling2D(pool_size=(2,', '2)),', 'tf.keras.layers.Conv2D(64,', 'kernel_size=(3,', '3),',...
933,813
kukuruza/shuffler
detectron2.py
register_object_dataset
register_object_dataset
This function registers a dataset in Detectron2 based on Shuffler db.
[ "This", "function", "registers", "a", "dataset", "in", "Detectron2", "based", "on", "Shuffler", "db." ]
def register_object_dataset(dataset_name, *args, **kwargs): detectron2.data.DatasetCatalog.register(dataset_name, functools.partial(_object_dataset_function, *args, **kwargs))
['def', 'register_object_dataset(dataset_name,', '*args,', '**kwargs):', 'detectron2.data.DatasetCatalog.register(dataset_name,', 'functools.partial(_object_dataset_function,', '*args,', '**kwargs))']
933,817
kukuruza/shuffler
evaluate.py
getPrecRecall
getPrecRecall
Accumulate into Precision-Recall curve.
[ "Accumulate", "into", "Precision-Recall", "curve." ]
def getPrecRecall(tp, fp, fn): ROC = np.zeros((256, 2), dtype=float) for val in range(256): if tp[val] == 0 and fp[val] == 0: precision = -1.0 else: precision = tp[val] / float(tp[val] + fp[val]) if tp[val] == 0 and fn[val] == 0: recall = -1.0 ...
['def', 'getPrecRecall(tp,', 'fp,', 'fn):', 'ROC', '=', 'np.zeros((256,', '2),', 'dtype=float)', 'for', 'val', 'in', 'range(256):', 'if', 'tp[val]', '==', '0', 'and', 'fp[val]', '==', '0:', 'precision', '=', '-1.0', 'else:', 'precision', '=', 'tp[val]', '/', 'float(tp[val]', '+', 'fp[val])', 'if', 'tp[val]', '==', '0',...
933,819
kukuruza/shuffler
filtering_test.py
Test_filterBadImages_CarsDb.test_single_thread_all_ok
test_single_thread_all_ok
Tests the single-thread mode when all images are ok.
[ "Tests", "the", "single-thread", "mode", "when", "all", "images", "are", "ok." ]
def test_single_thread_all_ok(self): c = self.conn.cursor() args = argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR, force_single_thread=True) filtering.filterBadImages(c, args) c.execute('SELECT COUNT(1) FROM images') self.assertEqual(c.fetchone()[0], 3)
['def', 'test_single_thread_all_ok(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', 'argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR,', 'force_single_thread=True)', 'filtering.filterBadImages(c,', 'args)', "c.execute('SELECT", 'COUNT(1)', 'FROM', "images')", 'self.assertEqual(c.fetchone()[0],'...
933,831
kukuruza/shuffler
filtering_test.py
Test_filterBadImages_CarsDb.test_single_thread_missing
test_single_thread_missing
Tests deleting a missing image in the single-thread mode.
[ "Tests", "deleting", "a", "missing", "image", "in", "the", "single-thread", "mode." ]
def test_single_thread_missing(self): c = self.conn.cursor() c.execute('INSERT INTO images(imagefile) VALUES ("non-existent.jpg")') args = argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR, force_single_thread=True) filtering.filterBadImages(c, args) c.execute('SELECT COUNT(1) FRO...
['def', 'test_single_thread_missing(self):', 'c', '=', 'self.conn.cursor()', "c.execute('INSERT", 'INTO', 'images(imagefile)', 'VALUES', '("non-existent.jpg")\')', 'args', '=', 'argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR,', 'force_single_thread=True)', 'filtering.filterBadImages(c,', 'args)', ...
933,833
kukuruza/shuffler
filtering_test.py
Test_filterObjectsInsideCertainObjects_SyntheticDb.test_empty
test_empty
Should succeed without issues.
[ "Should", "succeed", "without", "issues." ]
def test_empty(self): c = self.conn.cursor() c.execute('INSERT INTO images(imagefile) VALUES ("image0")') args = argparse.Namespace(where_shadowing_objects='TRUE', where_object='TRUE', keep=False) filtering.filterObjectsInsideCertainObjects(c, args) args = argparse.Namespace(where_shadowing_objects=...
['def', 'test_empty(self):', 'c', '=', 'self.conn.cursor()', "c.execute('INSERT", 'INTO', 'images(imagefile)', 'VALUES', '("image0")\')', 'args', '=', "argparse.Namespace(where_shadowing_objects='TRUE',", "where_object='TRUE',", 'keep=False)', 'filtering.filterObjectsInsideCertainObjects(c,', 'args)', 'args', '=', "arg...
933,836
kukuruza/shuffler
gui.py
KeyReader.parse
parse
Get the corresponding action for a pressed button.
[ "Get", "the", "corresponding", "action", "for", "a", "pressed", "button." ]
def parse(self, button): if button == -1: return None if chr(button) in self.keysmap: logging.info('Found char "%s" for pressed ASCII %d in the table.', chr(button), button) button = chr(button) if button in self.keysmap: logging.info('Value for pressed "%s" is "%s".', str(bu...
['def', 'parse(self,', 'button):', 'if', 'button', '==', '-1:', 'return', 'None', 'if', 'chr(button)', 'in', 'self.keysmap:', "logging.info('Found", 'char', '"%s"', 'for', 'pressed', 'ASCII', '%d', 'in', 'the', "table.',", 'chr(button),', 'button)', 'button', '=', 'chr(button)', 'if', 'button', 'in', 'self.keysmap:', "...
933,845
kukuruza/shuffler
matplotlib.py
drawScoredPolygon
drawScoredPolygon
Draw a polygon on top of Matplotlib axes.
[ "Draw", "a", "polygon", "on", "top", "of", "Matplotlib", "axes." ]
def drawScoredPolygon(ax, polygon, label=None, score=None): if score is None: score = 1.0 cmap = cm.get_cmap('jet').reversed() rgba = cmap(float(score)) polygon = np.array(polygon) rect = patches.Polygon(xy=polygon, linewidth=1, edgecolor=rgba, facecolor='none') ax.add_patch(rect) xm...
['def', 'drawScoredPolygon(ax,', 'polygon,', 'label=None,', 'score=None):', 'if', 'score', 'is', 'None:', 'score', '=', '1.0', 'cmap', '=', "cm.get_cmap('jet').reversed()", 'rgba', '=', 'cmap(float(score))', 'polygon', '=', 'np.array(polygon)', 'rect', '=', 'patches.Polygon(xy=polygon,', 'linewidth=1,', 'edgecolor=rgba...
933,847
kukuruza/shuffler
modify_test.py
Test_addPictures_SyntheticDb.test_NoMasks
test_NoMasks
Add 3 images without masks.
[ "Add", "3", "images", "without", "masks." ]
def test_NoMasks(self): c = self.conn.cursor() args = argparse.Namespace(rootdir='testdata', image_pattern='testdata/moon/images/*.jpg', mask_pattern=None, width_hint=None, height_hint=None) modify.addPictures(c, args) c.execute('SELECT imagefile,maskfile,width,height FROM images') actual = c.fetcha...
['def', 'test_NoMasks(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', "argparse.Namespace(rootdir='testdata',", "image_pattern='testdata/moon/images/*.jpg',", 'mask_pattern=None,', 'width_hint=None,', 'height_hint=None)', 'modify.addPictures(c,', 'args)', "c.execute('SELECT", 'imagefile,maskfile,width,height', 'F...
933,852
kukuruza/shuffler
modify_test.py
Test_addPictures_SyntheticDb.test_ImagesAndMasks_WidthAndHeightHint
test_ImagesAndMasks_WidthAndHeightHint
Add 3 pictures, with height and width hint.
[ "Add", "3", "pictures,", "with", "height", "and", "width", "hint." ]
def test_ImagesAndMasks_WidthAndHeightHint(self): c = self.conn.cursor() args = argparse.Namespace(rootdir='testdata', image_pattern='testdata/moon/images/*.jpg', mask_pattern='testdata/moon/masks/*.png', width_hint=120, height_hint=80) modify.addPictures(c, args) c.execute('SELECT imagefile,maskfile,wi...
['def', 'test_ImagesAndMasks_WidthAndHeightHint(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', "argparse.Namespace(rootdir='testdata',", "image_pattern='testdata/moon/images/*.jpg',", "mask_pattern='testdata/moon/masks/*.png',", 'width_hint=120,', 'height_hint=80)', 'modify.addPictures(c,', 'args)', "c.execute('...
933,854
kukuruza/shuffler
modify_test.py
Test_headImages_SyntheticDb.test_tooMuch
test_tooMuch
When asked for more images that the db has, return all images.
[ "When", "asked", "for", "more", "images", "that", "the", "db", "has,", "return", "all", "images." ]
def test_tooMuch(self): c = self.conn.cursor() args = argparse.Namespace(n=5) modify.headImages(c, args) c.execute('SELECT imagefile FROM images') actual = c.fetchall() expected = [('image0',), ('image1',)] self.assertEqual(actual, expected)
['def', 'test_tooMuch(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', 'argparse.Namespace(n=5)', 'modify.headImages(c,', 'args)', "c.execute('SELECT", 'imagefile', 'FROM', "images')", 'actual', '=', 'c.fetchall()', 'expected', '=', "[('image0',),", "('image1',)]", 'self.assertEqual(actual,', 'expected)']
933,855
kukuruza/shuffler
modify_test.py
Test_headImages_SyntheticDb.test_invalid
test_invalid
When asked for <= 0 images, raises an error.
[ "When", "asked", "for", "<=", "0", "images,", "raises", "an", "error." ]
def test_invalid(self): c = self.conn.cursor() args = argparse.Namespace(n=0) with self.assertRaises(ValueError): modify.headImages(c, args) args = argparse.Namespace(n=-5) with self.assertRaises(ValueError): modify.headImages(c, args)
['def', 'test_invalid(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', 'argparse.Namespace(n=0)', 'with', 'self.assertRaises(ValueError):', 'modify.headImages(c,', 'args)', 'args', '=', 'argparse.Namespace(n=-5)', 'with', 'self.assertRaises(ValueError):', 'modify.headImages(c,', 'args)']
933,856
kukuruza/shuffler
modify_test.py
Test_syncRoundedCoordinatesWithDb_SyntheticDb.test_polygons
test_polygons
Sync x or y in 'polygons', whichever has changed.
[ "Sync", "x", "or", "y", "in", "'polygons',", "whichever", "has", "changed." ]
def test_polygons(self): vals = [(0, 10, 20), (1, 10, 20), (2, 10, 20), (3, 10, 20), (4, 10, 20), (5, 10, 20)] vals_ref = [(0, 10, 20), (1, 10.1, 20), (2, 10, 20.2), (3, 10.1, 20.2), (4, 15, 25), (6, 10, 20)] self._insertPolygonsValue(vals, vals_ref) c = self.conn.cursor() modify.syncRoundedCoordina...
['def', 'test_polygons(self):', 'vals', '=', '[(0,', '10,', '20),', '(1,', '10,', '20),', '(2,', '10,', '20),', '(3,', '10,', '20),', '(4,', '10,', '20),', '(5,', '10,', '20)]', 'vals_ref', '=', '[(0,', '10,', '20),', '(1,', '10.1,', '20),', '(2,', '10,', '20.2),', '(3,', '10.1,', '20.2),', '(4,', '15,', '25),', '(6,',...
933,866
kukuruza/shuffler
__init__.py
add_subparsers
add_subparsers
Adds subparsers for each operation to the provided parser.
[ "Adds", "subparsers", "for", "each", "operation", "to", "the", "provided", "parser." ]
def add_subparsers(parser): subparsers = parser.add_subparsers() modify.add_parsers(subparsers) filtering.add_parsers(subparsers) gui.add_parsers(subparsers) info.add_parsers(subparsers) media.add_parsers(subparsers) evaluate.add_parsers(subparsers) labelme.add_parsers(subparsers) ki...
['def', 'add_subparsers(parser):', 'subparsers', '=', 'parser.add_subparsers()', 'modify.add_parsers(subparsers)', 'filtering.add_parsers(subparsers)', 'gui.add_parsers(subparsers)', 'info.add_parsers(subparsers)', 'media.add_parsers(subparsers)', 'evaluate.add_parsers(subparsers)', 'labelme.add_parsers(subparsers)', '...
933,867
kukuruza/shuffler
yolo_test.py
Test_exportYolo_carsDb.test_carsOnly_symlinkImages
test_carsOnly_symlinkImages
Only check if symlinks exist.
[ "Only", "check", "if", "symlinks", "exist." ]
def test_carsOnly_symlinkImages(self): c = self.conn.cursor() args = argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR, yolo_dir=op.join(self.temp_dir), copy_images=False, symlink_images=True, subset='car', classes=['car'], as_polygons=False, dirtree_level_for_name=1, fix_invalid_image_names=...
['def', 'test_carsOnly_symlinkImages(self):', 'c', '=', 'self.conn.cursor()', 'args', '=', 'argparse.Namespace(rootdir=testing_utils.Test_carsDb.CARS_DB_ROOTDIR,', 'yolo_dir=op.join(self.temp_dir),', 'copy_images=False,', 'symlink_images=True,', "subset='car',", "classes=['car'],", 'as_polygons=False,', 'dirtree_level_...
933,868
kukuruza/shuffler
boxes.py
getIoUPolygon
getIoUPolygon
Computes intersection over union for two polygons.
[ "Computes", "intersection", "over", "union", "for", "two", "polygons." ]
def getIoUPolygon(yxs1, yxs2): validatePolygon(yxs1) validatePolygon(yxs2) p1 = ShapelyPolygon(yxs1) p2 = ShapelyPolygon(yxs2) area1 = p1.area area2 = p2.area intersection = p1.intersection(p2).area logging.info(p1.intersection(p2)) union = area1 + area2 - intersection logging.in...
['def', 'getIoUPolygon(yxs1,', 'yxs2):', 'validatePolygon(yxs1)', 'validatePolygon(yxs2)', 'p1', '=', 'ShapelyPolygon(yxs1)', 'p2', '=', 'ShapelyPolygon(yxs2)', 'area1', '=', 'p1.area', 'area2', '=', 'p2.area', 'intersection', '=', 'p1.intersection(p2).area', 'logging.info(p1.intersection(p2))', 'union', '=', 'area1', ...
933,872
kukuruza/shuffler
boxes.py
expandPolygon
expandPolygon
Expand polygon from its avg(ymin, ymax), avg(xmin, xmax) in all directions.
[ "Expand", "polygon", "from", "its", "avg(ymin,", "ymax),", "avg(xmin,", "xmax)", "in", "all", "directions." ]
def expandPolygon(ys, xs, perc): if isinstance(ys, np.ndarray) and isinstance(xs, np.ndarray): validatePolygon(np.stack((ys, xs)).transpose()) else: validatePolygon(zip(ys, xs)) (perc_y, perc_x) = perc if (perc_y, perc_x) == (0, 0): return (ys, xs) if perc_y < -0.5 or perc_x ...
['def', 'expandPolygon(ys,', 'xs,', 'perc):', 'if', 'isinstance(ys,', 'np.ndarray)', 'and', 'isinstance(xs,', 'np.ndarray):', 'validatePolygon(np.stack((ys,', 'xs)).transpose())', 'else:', 'validatePolygon(zip(ys,', 'xs))', '(perc_y,', 'perc_x)', '=', 'perc', 'if', '(perc_y,', 'perc_x)', '==', '(0,', '0):', 'return', '...
933,874
kukuruza/shuffler
boxes.py
cropPatch
cropPatch
Crop a patch from the image.
[ "Crop", "a", "patch", "from", "the", "image." ]
def cropPatch(image, roi, edge, target_height, target_width): logging.debug('Cropping with ROI: %s', str(roi)) if edge != 'original' and (target_height is None or not isinstance(target_height, int) or target_width is None or (not isinstance(target_width, int))): raise RuntimeError('When edge is not "ori...
['def', 'cropPatch(image,', 'roi,', 'edge,', 'target_height,', 'target_width):', "logging.debug('Cropping", 'with', 'ROI:', "%s',", 'str(roi))', 'if', 'edge', '!=', "'original'", 'and', '(target_height', 'is', 'None', 'or', 'not', 'isinstance(target_height,', 'int)', 'or', 'target_width', 'is', 'None', 'or', '(not', 'i...
933,877
kukuruza/shuffler
draw.py
drawMaskOnImage
drawMaskOnImage
Draw a mask on the image, with colors.
[ "Draw", "a", "mask", "on", "the", "image,", "with", "colors." ]
def drawMaskOnImage(img, mask, alpha=0.5, labelmap=None): if not len(img.shape) == 3: raise NotImplementedError('Only color images are supported now.') if labelmap is not None: mask = general_utils.applyMaskMapping(mask, labelmap).astype(np.uint8) if len(mask.shape) == 2: mask = cv2....
['def', 'drawMaskOnImage(img,', 'mask,', 'alpha=0.5,', 'labelmap=None):', 'if', 'not', 'len(img.shape)', '==', '3:', 'raise', "NotImplementedError('Only", 'color', 'images', 'are', 'supported', "now.')", 'if', 'labelmap', 'is', 'not', 'None:', 'mask', '=', 'general_utils.applyMaskMapping(mask,', 'labelmap).astype(np.ui...
933,882
kukuruza/shuffler
draw_test.py
Test_drawFilledRoi.test_regular_fullfill
test_regular_fullfill
fill_opacity=1 must fill the area completely.
[ "fill_opacity=1", "must", "fill", "the", "area", "completely." ]
def test_regular_fullfill(self): image = imageio.imread('imageio:chelsea.png') expected_image = image.copy() expected_image[50:150, 100:200] = self.RED draw_utils._drawFilledRoi(image, (50, 100, 150, 200), self.RED, fill_opacity=1) np.testing.assert_almost_equal(image, expected_image, 0.0001)
['def', 'test_regular_fullfill(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'expected_image', '=', 'image.copy()', 'expected_image[50:150,', '100:200]', '=', 'self.RED', 'draw_utils._drawFilledRoi(image,', '(50,', '100,', '150,', '200),', 'self.RED,', 'fill_opacity=1)', 'np.testing.assert_almost_equa...
933,884
kukuruza/shuffler
draw_test.py
Test_drawFilledRoi.test_float_roi
test_float_roi
Test that it does not break for non-integer ROI.
[ "Test", "that", "it", "does", "not", "break", "for", "non-integer", "ROI." ]
def test_float_roi(self): image = imageio.imread('imageio:chelsea.png') draw_utils._drawFilledRoi(image, (50.3, 100.7, 150.1, 200), self.RED, fill_opacity=1)
['def', 'test_float_roi(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'draw_utils._drawFilledRoi(image,', '(50.3,', '100.7,', '150.1,', '200),', 'self.RED,', 'fill_opacity=1)']
933,885
kukuruza/shuffler
draw_test.py
Test_drawFilledRoi.test_grayscale_fullfill
test_grayscale_fullfill
Grayscale images should be processed correctly.
[ "Grayscale", "images", "should", "be", "processed", "correctly." ]
def test_grayscale_fullfill(self): image = imageio.imread('imageio:camera.png') assert len(image.shape) == 2, 'camera.png was expected to be grayscale' expected_image = image.copy() expected_image[50:150, 100:200] = 255 draw_utils._drawFilledRoi(image, (50, 100, 150, 200), 255, fill_opacity=1) n...
['def', 'test_grayscale_fullfill(self):', 'image', '=', "imageio.imread('imageio:camera.png')", 'assert', 'len(image.shape)', '==', '2,', "'camera.png", 'was', 'expected', 'to', 'be', "grayscale'", 'expected_image', '=', 'image.copy()', 'expected_image[50:150,', '100:200]', '=', '255', 'draw_utils._drawFilledRoi(image,...
933,887
kukuruza/shuffler
draw_test.py
Test_drawFilledRoi.test_off_boundary1_fullfill
test_off_boundary1_fullfill
ROI out of image boundary must be processed correctly.
[ "ROI", "out", "of", "image", "boundary", "must", "be", "processed", "correctly." ]
def test_off_boundary1_fullfill(self): image = imageio.imread('imageio:chelsea.png') expected_image = image.copy() expected_image[0:150, 200:451] = self.RED draw_utils._drawFilledRoi(image, (-100, 200, 150, 600), self.RED, fill_opacity=1) np.testing.assert_almost_equal(image, expected_image, 0.0001)
['def', 'test_off_boundary1_fullfill(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'expected_image', '=', 'image.copy()', 'expected_image[0:150,', '200:451]', '=', 'self.RED', 'draw_utils._drawFilledRoi(image,', '(-100,', '200,', '150,', '600),', 'self.RED,', 'fill_opacity=1)', 'np.testing.assert_almo...
933,888
kukuruza/shuffler
draw_test.py
Test_drawFilledPolygon.test_float_polygon
test_float_polygon
Test that it does not break for non-integer polygon.
[ "Test", "that", "it", "does", "not", "break", "for", "non-integer", "polygon." ]
def test_float_polygon(self): image = imageio.imread('imageio:chelsea.png') draw_utils._drawFilledPolygon(image, [(50.1, 100.2), (50.3, 300.4), (150.5, 300.6), (150, 100)], self.RED, fill_opacity=1)
['def', 'test_float_polygon(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'draw_utils._drawFilledPolygon(image,', '[(50.1,', '100.2),', '(50.3,', '300.4),', '(150.5,', '300.6),', '(150,', '100)],', 'self.RED,', 'fill_opacity=1)']
933,891
kukuruza/shuffler
draw_test.py
Test_drawFilledPolygon.test_invalid_polygon
test_invalid_polygon
Bad polygons must be quietly ignored.
[ "Bad", "polygons", "must", "be", "quietly", "ignored." ]
def test_invalid_polygon(self): image = imageio.imread('imageio:chelsea.png') expected_image = image.copy() draw_utils._drawFilledPolygon(image, [(50, 100), (50, 200)], self.RED, fill_opacity=1) np.testing.assert_almost_equal(image, expected_image, 0.0001)
['def', 'test_invalid_polygon(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'expected_image', '=', 'image.copy()', 'draw_utils._drawFilledPolygon(image,', '[(50,', '100),', '(50,', '200)],', 'self.RED,', 'fill_opacity=1)', 'np.testing.assert_almost_equal(image,', 'expected_image,', '0.0001)']
933,892
kukuruza/shuffler
draw_test.py
Test_drawFilledPolygon.test_regular_nofill
test_regular_nofill
fill_opacity=0 must have no effect on the image.
[ "fill_opacity=0", "must", "have", "no", "effect", "on", "the", "image." ]
def test_regular_nofill(self): image = imageio.imread('imageio:chelsea.png') expected_image = image.copy() draw_utils._drawFilledPolygon(image, [(50, 100), (50, 200), (150, 200), (150, 100)], self.RED, fill_opacity=0) np.testing.assert_almost_equal(image, expected_image, 0.0001)
['def', 'test_regular_nofill(self):', 'image', '=', "imageio.imread('imageio:chelsea.png')", 'expected_image', '=', 'image.copy()', 'draw_utils._drawFilledPolygon(image,', '[(50,', '100),', '(50,', '200),', '(150,', '200),', '(150,', '100)],', 'self.RED,', 'fill_opacity=0)', 'np.testing.assert_almost_equal(image,', 'ex...
933,893
kukuruza/shuffler
general.py
takeSubpath
takeSubpath
Takes dirtree_level parts of the path from the end.
[ "Takes", "dirtree_level", "parts", "of", "the", "path", "from", "the", "end." ]
def takeSubpath(path, dirtree_level=None): if len(path) == 0: raise ValueError('The path can not be an empty string.') if dirtree_level is None: return path elif dirtree_level <= 0: raise ValueError('dirtree_level must be None or a positive integer.') parts = path.split(op.sep) ...
['def', 'takeSubpath(path,', 'dirtree_level=None):', 'if', 'len(path)', '==', '0:', 'raise', "ValueError('The", 'path', 'can', 'not', 'be', 'an', 'empty', "string.')", 'if', 'dirtree_level', 'is', 'None:', 'return', 'path', 'elif', 'dirtree_level', '<=', '0:', 'raise', "ValueError('dirtree_level", 'must', 'be', 'None',...
933,897
kukuruza/shuffler
general.py
bbox2polygon
bbox2polygon
A rectangular polygon is added for the objectid if it is missing polygons.
[ "A", "rectangular", "polygon", "is", "added", "for", "the", "objectid", "if", "it", "is", "missing", "polygons." ]
def bbox2polygon(cursor, objectid): cursor.execute('SELECT COUNT(1) FROM polygons WHERE objectid=?', (objectid,)) if cursor.fetchone()[0] > 0: return cursor.execute('SELECT * FROM objects WHERE objectid=?', (objectid,)) object_entry = cursor.fetchone() if object_entry is None: raise ...
['def', 'bbox2polygon(cursor,', 'objectid):', "cursor.execute('SELECT", 'COUNT(1)', 'FROM', 'polygons', 'WHERE', "objectid=?',", '(objectid,))', 'if', 'cursor.fetchone()[0]', '>', '0:', 'return', "cursor.execute('SELECT", '*', 'FROM', 'objects', 'WHERE', "objectid=?',", '(objectid,))', 'object_entry', '=', 'cursor.fetc...
933,902
kukuruza/shuffler
general.py
polygons2mask
polygons2mask
A mask is created around each object by painting inside polygons.
[ "A", "mask", "is", "created", "around", "each", "object", "by", "painting", "inside", "polygons." ]
def polygons2mask(cursor, objectid): cursor.execute('SELECT i.width,i.height FROM images i INNER JOIN objects o ON i.imagefile=o.imagefile WHERE objectid=?', (objectid,)) width_and_height = cursor.fetchone() if width_and_height is None: raise RuntimeError('Failed to find image dim for object %d' % o...
['def', 'polygons2mask(cursor,', 'objectid):', "cursor.execute('SELECT", 'i.width,i.height', 'FROM', 'images', 'i', 'INNER', 'JOIN', 'objects', 'o', 'ON', 'i.imagefile=o.imagefile', 'WHERE', "objectid=?',", '(objectid,))', 'width_and_height', '=', 'cursor.fetchone()', 'if', 'width_and_height', 'is', 'None:', 'raise', "...
933,904
kukuruza/shuffler
general_test.py
Test_MatchPolygonPoints.test_identicalAndNameMatter
test_identicalAndNameMatter
Identical points are not matched if names differ.
[ "Identical", "points", "are", "not", "matched", "if", "names", "differ." ]
def test_identicalAndNameMatter(self): objectid = 1 polygons1 = [(1, objectid, 10, 30, 'name1')] polygons2 = [(2, objectid, 10, 30, 'name2')] pairs = general_utils.matchPolygonPoints(polygons1, polygons2, 1.0, False) self.assertEqual(pairs, [])
['def', 'test_identicalAndNameMatter(self):', 'objectid', '=', '1', 'polygons1', '=', '[(1,', 'objectid,', '10,', '30,', "'name1')]", 'polygons2', '=', '[(2,', 'objectid,', '10,', '30,', "'name2')]", 'pairs', '=', 'general_utils.matchPolygonPoints(polygons1,', 'polygons2,', '1.0,', 'False)', 'self.assertEqual(pairs,', ...
933,909
kukuruza/shuffler
general_test.py
Test_MatchPolygonPoints.test_someMatchingPointsAndNameIgnored
test_someMatchingPointsAndNameIgnored
Some points are matched, names are ignored.
[ "Some", "points", "are", "matched,", "names", "are", "ignored." ]
def test_someMatchingPointsAndNameIgnored(self): objectid = 1 polygons1 = [(1, objectid, 100, 100, 'name1'), (2, objectid, 10, 30, 'name2')] polygons2 = [(3, objectid, 10, 30, 'name2'), (4, objectid, 200, 200, 'name3')] pairs = general_utils.matchPolygonPoints(polygons1, polygons2, 1.0, True) self.a...
['def', 'test_someMatchingPointsAndNameIgnored(self):', 'objectid', '=', '1', 'polygons1', '=', '[(1,', 'objectid,', '100,', '100,', "'name1'),", '(2,', 'objectid,', '10,', '30,', "'name2')]", 'polygons2', '=', '[(3,', 'objectid,', '10,', '30,', "'name2'),", '(4,', 'objectid,', '200,', '200,', "'name3')]", 'pairs', '='...
933,910
kukuruza/shuffler
general_test.py
Test_MatchPolygonPoints.test_haveNameIsNull
test_haveNameIsNull
Only the point with matching name is matched out of two points.
[ "Only", "the", "point", "with", "matching", "name", "is", "matched", "out", "of", "two", "points." ]
def test_haveNameIsNull(self): objectid = 1 polygons1 = [(1, objectid, 10, 30, None), (2, objectid, 20, 40, 'name1'), (3, objectid, 30, 50, 'name2')] polygons2 = [(4, objectid, 30, 50, 'name2'), (5, objectid, 20, 40, 'name1'), (6, objectid, 10, 30, None)] pairs = general_utils.matchPolygonPoints(polygon...
['def', 'test_haveNameIsNull(self):', 'objectid', '=', '1', 'polygons1', '=', '[(1,', 'objectid,', '10,', '30,', 'None),', '(2,', 'objectid,', '20,', '40,', "'name1'),", '(3,', 'objectid,', '30,', '50,', "'name2')]", 'polygons2', '=', '[(4,', 'objectid,', '30,', '50,', "'name2'),", '(5,', 'objectid,', '20,', '40,', "'n...
933,914
kukuruza/shuffler
parser.py
addWhereImageArgument
addWhereImageArgument
Adds a parser argument common for many operations.
[ "Adds", "a", "parser", "argument", "common", "for", "many", "operations." ]
def addWhereImageArgument(parser: argparse.ArgumentParser): parser.add_argument('--where_image', default='TRUE', help='an SQL "where" clause for the "images" table. E.g. to limit images to JPG pictures from directory "from/mydir", use \'images.imagefile LIKE "from/mydir/%%.JPG"\'')
['def', 'addWhereImageArgument(parser:', 'argparse.ArgumentParser):', "parser.add_argument('--where_image',", "default='TRUE',", "help='an", 'SQL', '"where"', 'clause', 'for', 'the', '"images"', 'table.', 'E.g.', 'to', 'limit', 'images', 'to', 'JPG', 'pictures', 'from', 'directory', '"from/mydir",', 'use', "\\'images.i...
933,916
kukuruza/shuffler
testing.py
Test_DB.assert_objects_count_by_imagefile
assert_objects_count_by_imagefile
Check the number of objects grouped by imagefile.
[ "Check", "the", "number", "of", "objects", "grouped", "by", "imagefile." ]
def assert_objects_count_by_imagefile(self, c, expected): self.verify_that_expected_is_a_list_of_ints(expected) c.execute('SELECT COUNT(o.imagefile) FROM images i LEFT OUTER JOIN objects o ON i.imagefile = o.imagefile GROUP BY i.imagefile') actual = c.fetchall() expected = [(x,) for x in expected] s...
['def', 'assert_objects_count_by_imagefile(self,', 'c,', 'expected):', 'self.verify_that_expected_is_a_list_of_ints(expected)', "c.execute('SELECT", 'COUNT(o.imagefile)', 'FROM', 'images', 'i', 'LEFT', 'OUTER', 'JOIN', 'objects', 'o', 'ON', 'i.imagefile', '=', 'o.imagefile', 'GROUP', 'BY', "i.imagefile')", 'actual', '=...
933,921
kukuruza/shuffler
testing.py
Test_DB.assert_polygons_count_by_object
assert_polygons_count_by_object
Check the number of polygon points grouped by objectid.
[ "Check", "the", "number", "of", "polygon", "points", "grouped", "by", "objectid." ]
def assert_polygons_count_by_object(self, c, expected): self.verify_that_expected_is_a_list_of_ints(expected) c.execute('SELECT COUNT(p.objectid) FROM objects o LEFT OUTER JOIN polygons p ON p.objectid = o.objectid GROUP BY o.objectid') actual = c.fetchall() expected = [(x,) for x in expected] self....
['def', 'assert_polygons_count_by_object(self,', 'c,', 'expected):', 'self.verify_that_expected_is_a_list_of_ints(expected)', "c.execute('SELECT", 'COUNT(p.objectid)', 'FROM', 'objects', 'o', 'LEFT', 'OUTER', 'JOIN', 'polygons', 'p', 'ON', 'p.objectid', '=', 'o.objectid', 'GROUP', 'BY', "o.objectid')", 'actual', '=', '...
933,922
kukuruza/shuffler
testing.py
Test_DB.assert_objects_count_by_match
assert_objects_count_by_match
Check the number of objects grouped by match.
[ "Check", "the", "number", "of", "objects", "grouped", "by", "match." ]
def assert_objects_count_by_match(self, c, expected): self.verify_that_expected_is_a_list_of_ints(expected) c.execute('SELECT COUNT(1) FROM matches GROUP BY match') actual = c.fetchall() expected = [(x,) for x in expected] self.assertEqual(sorted(actual), sorted(expected), self.summarize_db(c))
['def', 'assert_objects_count_by_match(self,', 'c,', 'expected):', 'self.verify_that_expected_is_a_list_of_ints(expected)', "c.execute('SELECT", 'COUNT(1)', 'FROM', 'matches', 'GROUP', 'BY', "match')", 'actual', '=', 'c.fetchall()', 'expected', '=', '[(x,)', 'for', 'x', 'in', 'expected]', 'self.assertEqual(sorted(actua...
933,923