body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
|---|---|---|---|---|---|---|---|---|---|
a692df10cb40b41a1439d4533abffb5440e85bb3b377d79b8624ab08dabec7f2
|
def _create(self, fname):
'call oc create on a filename'
return self.openshift_cmd(['create', '-f', fname])
|
call oc create on a filename
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_create
|
vizakua/openshift-tools
| 164
|
python
|
def _create(self, fname):
return self.openshift_cmd(['create', '-f', fname])
|
def _create(self, fname):
return self.openshift_cmd(['create', '-f', fname])<|docstring|>call oc create on a filename<|endoftext|>
|
8dd9833238f3f996f501c8bf3442238d508e3f4dfda1d03920554b684159508c
|
def _delete(self, resource, name=None, selector=None):
'call oc delete on a resource'
cmd = ['delete', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift_cmd(cmd)
|
call oc delete on a resource
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_delete
|
vizakua/openshift-tools
| 164
|
python
|
def _delete(self, resource, name=None, selector=None):
cmd = ['delete', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift_cmd(cmd)
|
def _delete(self, resource, name=None, selector=None):
cmd = ['delete', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
elif (name is not None):
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift_cmd(cmd)<|docstring|>call oc delete on a resource<|endoftext|>
|
2ed9ad15b512973fe18904ed37f8e3d7b5796b3267f67146f6bb379613695f21
|
def _process(self, template_name, create=False, params=None, template_data=None):
"process a template\n\n template_name: the name of the template to process\n create: whether to send to oc create after processing\n params: the parameters for the template\n template_data: the incoming template's data; instead of a file\n "
cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ['{}={}'.format(key, str(value).replace("'", '"')) for (key, value) in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if ((results['returncode'] != 0) or (not create)):
return results
fname = Utils.create_tmpfile((template_name + '-'))
yed = Yedit(fname, results['results'])
yed.write()
atexit.register(Utils.cleanup, [fname])
return self.openshift_cmd(['create', '-f', fname])
|
process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template's data; instead of a file
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_process
|
vizakua/openshift-tools
| 164
|
python
|
def _process(self, template_name, create=False, params=None, template_data=None):
"process a template\n\n template_name: the name of the template to process\n create: whether to send to oc create after processing\n params: the parameters for the template\n template_data: the incoming template's data; instead of a file\n "
cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ['{}={}'.format(key, str(value).replace("'", '"')) for (key, value) in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if ((results['returncode'] != 0) or (not create)):
return results
fname = Utils.create_tmpfile((template_name + '-'))
yed = Yedit(fname, results['results'])
yed.write()
atexit.register(Utils.cleanup, [fname])
return self.openshift_cmd(['create', '-f', fname])
|
def _process(self, template_name, create=False, params=None, template_data=None):
"process a template\n\n template_name: the name of the template to process\n create: whether to send to oc create after processing\n params: the parameters for the template\n template_data: the incoming template's data; instead of a file\n "
cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ['{}={}'.format(key, str(value).replace("'", '"')) for (key, value) in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if ((results['returncode'] != 0) or (not create)):
return results
fname = Utils.create_tmpfile((template_name + '-'))
yed = Yedit(fname, results['results'])
yed.write()
atexit.register(Utils.cleanup, [fname])
return self.openshift_cmd(['create', '-f', fname])<|docstring|>process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template's data; instead of a file<|endoftext|>
|
30514e3f8d27f23b25c1cc2ad898f09c0a0e5c672796b9700176224e7baac867
|
def _get(self, resource, name=None, selector=None, field_selector=None):
'return a resource by name '
cmd = ['get', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
if (field_selector is not None):
cmd.append('--field-selector={}'.format(field_selector))
if ((selector is None) and (field_selector is None) and (name is not None)):
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
if ('items' in rval):
rval['results'] = rval['items']
elif (not isinstance(rval['results'], list)):
rval['results'] = [rval['results']]
return rval
|
return a resource by name
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_get
|
vizakua/openshift-tools
| 164
|
python
|
def _get(self, resource, name=None, selector=None, field_selector=None):
' '
cmd = ['get', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
if (field_selector is not None):
cmd.append('--field-selector={}'.format(field_selector))
if ((selector is None) and (field_selector is None) and (name is not None)):
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
if ('items' in rval):
rval['results'] = rval['items']
elif (not isinstance(rval['results'], list)):
rval['results'] = [rval['results']]
return rval
|
def _get(self, resource, name=None, selector=None, field_selector=None):
' '
cmd = ['get', resource]
if (selector is not None):
cmd.append('--selector={}'.format(selector))
if (field_selector is not None):
cmd.append('--field-selector={}'.format(field_selector))
if ((selector is None) and (field_selector is None) and (name is not None)):
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
if ('items' in rval):
rval['results'] = rval['items']
elif (not isinstance(rval['results'], list)):
rval['results'] = [rval['results']]
return rval<|docstring|>return a resource by name<|endoftext|>
|
afb31a339b76d4fde7087bd404723421ff6280b4b42fa8adf6a5aa4f25ba60b8
|
def _schedulable(self, node=None, selector=None, schedulable=True):
' perform oadm manage-node scheduable '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
perform oadm manage-node scheduable
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_schedulable
|
vizakua/openshift-tools
| 164
|
python
|
def _schedulable(self, node=None, selector=None, schedulable=True):
' '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
def _schedulable(self, node=None, selector=None, schedulable=True):
' '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')<|docstring|>perform oadm manage-node scheduable<|endoftext|>
|
318867fb078ef15fff70e381998ab887148d302e8901b39ce6fab8faa6cdb550
|
def _list_pods(self, node=None, selector=None, pod_selector=None):
' perform oadm list pods\n\n node: the node in which to list pods\n selector: the label selector filter if provided\n pod_selector: the pod selector filter if provided\n '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_list_pods
|
vizakua/openshift-tools
| 164
|
python
|
def _list_pods(self, node=None, selector=None, pod_selector=None):
' perform oadm list pods\n\n node: the node in which to list pods\n selector: the label selector filter if provided\n pod_selector: the pod selector filter if provided\n '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
def _list_pods(self, node=None, selector=None, pod_selector=None):
' perform oadm list pods\n\n node: the node in which to list pods\n selector: the label selector filter if provided\n pod_selector: the pod selector filter if provided\n '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')<|docstring|>perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided<|endoftext|>
|
703e61a02593cb6b7e768836c2620125c954b78170a3fac3ec6ded5d5a948b01
|
def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
' perform oadm manage-node evacuate '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
perform oadm manage-node evacuate
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_evacuate
|
vizakua/openshift-tools
| 164
|
python
|
def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
' '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
' '
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')<|docstring|>perform oadm manage-node evacuate<|endoftext|>
|
2eda309abed3b679b92162eaed5e480085e5fb0ffd59ecb6297d43df40f070d6
|
def _version(self):
' return the openshift version'
return self.openshift_cmd(['version'], output=True, output_type='raw')
|
return the openshift version
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_version
|
vizakua/openshift-tools
| 164
|
python
|
def _version(self):
' '
return self.openshift_cmd(['version'], output=True, output_type='raw')
|
def _version(self):
' '
return self.openshift_cmd(['version'], output=True, output_type='raw')<|docstring|>return the openshift version<|endoftext|>
|
6cbbda4490bbf732270c31b8aaa5ee52a76f0299bcae22c0447d86b6e39227b6
|
def _import_image(self, url=None, name=None, tag=None):
' perform image import '
cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
|
perform image import
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_import_image
|
vizakua/openshift-tools
| 164
|
python
|
def _import_image(self, url=None, name=None, tag=None):
' '
cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
|
def _import_image(self, url=None, name=None, tag=None):
' '
cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)<|docstring|>perform image import<|endoftext|>
|
26a2819a30032f778a8e34a08a57b8fe1d4bfee5dd7d36912b5c5ba9ba05e266
|
def _run(self, cmds, input_data):
' Actually executes the command. This makes mocking easier. '
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env)
(stdout, stderr) = proc.communicate(input_data)
return (proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8'))
|
Actually executes the command. This makes mocking easier.
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_run
|
vizakua/openshift-tools
| 164
|
python
|
def _run(self, cmds, input_data):
' '
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env)
(stdout, stderr) = proc.communicate(input_data)
return (proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8'))
|
def _run(self, cmds, input_data):
' '
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env)
(stdout, stderr) = proc.communicate(input_data)
return (proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8'))<|docstring|>Actually executes the command. This makes mocking easier.<|endoftext|>
|
ee8eadd7696996bf04cf46e34269bae42f0e65e488a5e9aa54f091cc15802369
|
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
'Base command for oc '
cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif ((self.namespace is not None) and (self.namespace.lower() not in ['none', 'emtpy'])):
cmds.extend(['-n', self.namespace])
if self.verbose:
print(' '.join(cmds))
try:
(returncode, stdout, stderr) = self._run(cmds, input_data)
except OSError as ex:
(returncode, stdout, stderr) = (1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex))
rval = {'returncode': returncode, 'cmd': ' '.join(cmds)}
if (output_type == 'json'):
rval['results'] = {}
if (output and stdout):
try:
rval['results'] = json.loads(stdout)
except ValueError as verr:
if ('No JSON object could be decoded' in verr.args):
rval['err'] = verr.args
elif (output_type == 'raw'):
rval['results'] = (stdout if output else '')
if self.verbose:
print('STDOUT: {0}'.format(stdout))
print('STDERR: {0}'.format(stderr))
if (('err' in rval) or (returncode != 0)):
rval.update({'stderr': stderr, 'stdout': stdout})
return rval
|
Base command for oc
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
openshift_cmd
|
vizakua/openshift-tools
| 164
|
python
|
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
' '
cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif ((self.namespace is not None) and (self.namespace.lower() not in ['none', 'emtpy'])):
cmds.extend(['-n', self.namespace])
if self.verbose:
print(' '.join(cmds))
try:
(returncode, stdout, stderr) = self._run(cmds, input_data)
except OSError as ex:
(returncode, stdout, stderr) = (1, , 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex))
rval = {'returncode': returncode, 'cmd': ' '.join(cmds)}
if (output_type == 'json'):
rval['results'] = {}
if (output and stdout):
try:
rval['results'] = json.loads(stdout)
except ValueError as verr:
if ('No JSON object could be decoded' in verr.args):
rval['err'] = verr.args
elif (output_type == 'raw'):
rval['results'] = (stdout if output else )
if self.verbose:
print('STDOUT: {0}'.format(stdout))
print('STDERR: {0}'.format(stderr))
if (('err' in rval) or (returncode != 0)):
rval.update({'stderr': stderr, 'stdout': stdout})
return rval
|
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
' '
cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif ((self.namespace is not None) and (self.namespace.lower() not in ['none', 'emtpy'])):
cmds.extend(['-n', self.namespace])
if self.verbose:
print(' '.join(cmds))
try:
(returncode, stdout, stderr) = self._run(cmds, input_data)
except OSError as ex:
(returncode, stdout, stderr) = (1, , 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex))
rval = {'returncode': returncode, 'cmd': ' '.join(cmds)}
if (output_type == 'json'):
rval['results'] = {}
if (output and stdout):
try:
rval['results'] = json.loads(stdout)
except ValueError as verr:
if ('No JSON object could be decoded' in verr.args):
rval['err'] = verr.args
elif (output_type == 'raw'):
rval['results'] = (stdout if output else )
if self.verbose:
print('STDOUT: {0}'.format(stdout))
print('STDERR: {0}'.format(stderr))
if (('err' in rval) or (returncode != 0)):
rval.update({'stderr': stderr, 'stdout': stdout})
return rval<|docstring|>Base command for oc<|endoftext|>
|
ec17e23f57dfa0fef6da895fb708e906a674b4b5f4bce2f03558772839176809
|
@staticmethod
def _write(filename, contents):
' Actually write the file contents to disk. This helps with mocking. '
with open(filename, 'w') as sfd:
sfd.write(str(contents))
|
Actually write the file contents to disk. This helps with mocking.
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
_write
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def _write(filename, contents):
' '
with open(filename, 'w') as sfd:
sfd.write(str(contents))
|
@staticmethod
def _write(filename, contents):
' '
with open(filename, 'w') as sfd:
sfd.write(str(contents))<|docstring|>Actually write the file contents to disk. This helps with mocking.<|endoftext|>
|
7f0af4d1bcfceb52b80af3f7914e823252a4c7c22813d19055b5359725fc5da8
|
@staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
' create a file in tmp with name and contents'
tmp = Utils.create_tmpfile(prefix=rname)
if (ftype == 'yaml'):
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif (ftype == 'json'):
Utils._write(tmp, json.dumps(data))
else:
Utils._write(tmp, data)
atexit.register(Utils.cleanup, [tmp])
return tmp
|
create a file in tmp with name and contents
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
create_tmp_file_from_contents
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
' '
tmp = Utils.create_tmpfile(prefix=rname)
if (ftype == 'yaml'):
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif (ftype == 'json'):
Utils._write(tmp, json.dumps(data))
else:
Utils._write(tmp, data)
atexit.register(Utils.cleanup, [tmp])
return tmp
|
@staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
' '
tmp = Utils.create_tmpfile(prefix=rname)
if (ftype == 'yaml'):
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif (ftype == 'json'):
Utils._write(tmp, json.dumps(data))
else:
Utils._write(tmp, data)
atexit.register(Utils.cleanup, [tmp])
return tmp<|docstring|>create a file in tmp with name and contents<|endoftext|>
|
8d261448b523572d6c73044ce061fdc5610e75035791990e8c849ce7c9c0f0ed
|
@staticmethod
def create_tmpfile_copy(inc_file):
'create a temporary copy of a file'
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
|
create a temporary copy of a file
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
create_tmpfile_copy
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def create_tmpfile_copy(inc_file):
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
|
@staticmethod
def create_tmpfile_copy(inc_file):
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile<|docstring|>create a temporary copy of a file<|endoftext|>
|
daac9d8c91fa886bc955095cbcc985b8d3fab962f6c16edec4f43ba3dbc1af31
|
@staticmethod
def create_tmpfile(prefix='tmp'):
' Generates and returns a temporary file name '
with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
|
Generates and returns a temporary file name
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
create_tmpfile
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def create_tmpfile(prefix='tmp'):
' '
with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
|
@staticmethod
def create_tmpfile(prefix='tmp'):
' '
with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name<|docstring|>Generates and returns a temporary file name<|endoftext|>
|
9ffef46811828eff2be487317ecdbaecb78949462e8bde3ac436794093f339fd
|
@staticmethod
def create_tmp_files_from_contents(content, content_type=None):
'Turn an array of dict: filename, content into a files array'
if (not isinstance(content, list)):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents((item['path'] + '-'), item['data'], ftype=content_type)
files.append({'name': os.path.basename(item['path']), 'path': path})
return files
|
Turn an array of dict: filename, content into a files array
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
create_tmp_files_from_contents
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def create_tmp_files_from_contents(content, content_type=None):
if (not isinstance(content, list)):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents((item['path'] + '-'), item['data'], ftype=content_type)
files.append({'name': os.path.basename(item['path']), 'path': path})
return files
|
@staticmethod
def create_tmp_files_from_contents(content, content_type=None):
if (not isinstance(content, list)):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents((item['path'] + '-'), item['data'], ftype=content_type)
files.append({'name': os.path.basename(item['path']), 'path': path})
return files<|docstring|>Turn an array of dict: filename, content into a files array<|endoftext|>
|
db86e4ef1d575e7ae6b9c94e37cedc4cf2047dc8d53a4adf4466bf7317db0f34
|
@staticmethod
def cleanup(files):
'Clean up on exit '
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
|
Clean up on exit
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
cleanup
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def cleanup(files):
' '
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
|
@staticmethod
def cleanup(files):
' '
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)<|docstring|>Clean up on exit<|endoftext|>
|
16a28890f6c34a19fc7c33f9746b778e338386e85a01b703fa417a3cac9db13d
|
@staticmethod
def exists(results, _name):
' Check to see if the results include the name '
if (not results):
return False
if Utils.find_result(results, _name):
return True
return False
|
Check to see if the results include the name
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
exists
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def exists(results, _name):
' '
if (not results):
return False
if Utils.find_result(results, _name):
return True
return False
|
@staticmethod
def exists(results, _name):
' '
if (not results):
return False
if Utils.find_result(results, _name):
return True
return False<|docstring|>Check to see if the results include the name<|endoftext|>
|
676c6e62cd600eb31deef7739c803b3376e28f61033cb41eb8c9591c76c09654
|
@staticmethod
def find_result(results, _name):
' Find the specified result by name'
rval = None
for result in results:
if (('metadata' in result) and (result['metadata']['name'] == _name)):
rval = result
break
return rval
|
Find the specified result by name
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
find_result
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def find_result(results, _name):
' '
rval = None
for result in results:
if (('metadata' in result) and (result['metadata']['name'] == _name)):
rval = result
break
return rval
|
@staticmethod
def find_result(results, _name):
' '
rval = None
for result in results:
if (('metadata' in result) and (result['metadata']['name'] == _name)):
rval = result
break
return rval<|docstring|>Find the specified result by name<|endoftext|>
|
8a6f8db2f7a454b73114ba86b5e3eda7ba12d2b63eb0be2cb7f0de456beaf978
|
@staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
' return the service file '
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if (sfile_type == 'yaml'):
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif (sfile_type == 'json'):
contents = json.loads(contents)
return contents
|
return the service file
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_resource_file
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
' '
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if (sfile_type == 'yaml'):
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif (sfile_type == 'json'):
contents = json.loads(contents)
return contents
|
@staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
' '
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if (sfile_type == 'yaml'):
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif (sfile_type == 'json'):
contents = json.loads(contents)
return contents<|docstring|>return the service file<|endoftext|>
|
0bf23ae9dd100d1aa6e19cd91b2718fe871490cee5afa001dd3564724790ae37
|
@staticmethod
def filter_versions(stdout):
' filter the oc version output '
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if (not line):
continue
if line.startswith(term):
version_dict[term] = line.split()[(- 1)]
if ('openshift' not in version_dict):
version_dict['openshift'] = version_dict['oc']
return version_dict
|
filter the oc version output
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
filter_versions
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def filter_versions(stdout):
' '
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if (not line):
continue
if line.startswith(term):
version_dict[term] = line.split()[(- 1)]
if ('openshift' not in version_dict):
version_dict['openshift'] = version_dict['oc']
return version_dict
|
@staticmethod
def filter_versions(stdout):
' '
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if (not line):
continue
if line.startswith(term):
version_dict[term] = line.split()[(- 1)]
if ('openshift' not in version_dict):
version_dict['openshift'] = version_dict['oc']
return version_dict<|docstring|>filter the oc version output<|endoftext|>
|
7c35fc92464e2a6f758cf964f03d0253f58a030faa82adf9fc1ac0efdfe0acf3
|
@staticmethod
def add_custom_versions(versions):
' create custom versions strings '
versions_dict = {}
for (tech, version) in versions.items():
if ('-' in version):
version = version.split('-')[0]
if version.startswith('v'):
versions_dict[(tech + '_numeric')] = version[1:].split('+')[0]
versions_dict[(tech + '_short')] = version[1:4]
return versions_dict
|
create custom versions strings
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
add_custom_versions
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def add_custom_versions(versions):
' '
versions_dict = {}
for (tech, version) in versions.items():
if ('-' in version):
version = version.split('-')[0]
if version.startswith('v'):
versions_dict[(tech + '_numeric')] = version[1:].split('+')[0]
versions_dict[(tech + '_short')] = version[1:4]
return versions_dict
|
@staticmethod
def add_custom_versions(versions):
' '
versions_dict = {}
for (tech, version) in versions.items():
if ('-' in version):
version = version.split('-')[0]
if version.startswith('v'):
versions_dict[(tech + '_numeric')] = version[1:].split('+')[0]
versions_dict[(tech + '_short')] = version[1:4]
return versions_dict<|docstring|>create custom versions strings<|endoftext|>
|
2487642f62d766286cf42766241a01d181189b259c23fba74e91308004b7dcf9
|
@staticmethod
def openshift_installed():
' check if openshift is installed '
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch('name', 'atomic-openshift')
return (rpmquery.count() > 0)
|
check if openshift is installed
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
openshift_installed
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def openshift_installed():
' '
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch('name', 'atomic-openshift')
return (rpmquery.count() > 0)
|
@staticmethod
def openshift_installed():
' '
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch('name', 'atomic-openshift')
return (rpmquery.count() > 0)<|docstring|>check if openshift is installed<|endoftext|>
|
7bc1c5ebd2d25a97db2bf12d638f17290a5c76efc3dacacf5ec88d50255ebd26
|
@staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
' Given a user defined definition, compare it with the results given back by our query. '
skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for (key, value) in result_def.items():
if (key in skip):
continue
if isinstance(value, list):
if (key not in user_def):
if debug:
print(('User data does not have key [%s]' % key))
print(('User data: %s' % user_def))
return False
if (not isinstance(user_def[key], list)):
if debug:
print(('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])))
return False
if (len(user_def[key]) != len(value)):
if debug:
print('List lengths are not equal.')
print(('key=[%s]: user_def[%s] != value[%s]' % (key, len(user_def[key]), len(value))))
print(('user_def: %s' % user_def[key]))
print(('value: %s' % value))
return False
for values in zip(user_def[key], value):
if (isinstance(values[0], dict) and isinstance(values[1], dict)):
if debug:
print('sending list - list')
print(type(values[0]))
print(type(values[1]))
result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
if (not result):
print('list compare returned false')
return False
elif (value != user_def[key]):
if debug:
print('value should be identical')
print(user_def[key])
print(value)
return False
elif isinstance(value, dict):
if (key not in user_def):
if debug:
print(('user_def does not have key [%s]' % key))
return False
if (not isinstance(user_def[key], dict)):
if debug:
print('dict returned false: not instance of dict')
return False
api_values = (set(value.keys()) - set(skip))
user_values = (set(user_def[key].keys()) - set(skip))
if (api_values != user_values):
if debug:
print('keys are not equal in dict')
print(user_values)
print(api_values)
return False
result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
if (not result):
if debug:
print('dict returned false')
print(result)
return False
elif ((key not in user_def) or (value != user_def[key])):
if debug:
print('value not equal; user_def does not have key')
print(key)
print(value)
if (key in user_def):
print(user_def[key])
return False
if debug:
print('returning true')
return True
|
Given a user defined definition, compare it with the results given back by our query.
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
check_def_equal
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
' '
skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for (key, value) in result_def.items():
if (key in skip):
continue
if isinstance(value, list):
if (key not in user_def):
if debug:
print(('User data does not have key [%s]' % key))
print(('User data: %s' % user_def))
return False
if (not isinstance(user_def[key], list)):
if debug:
print(('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])))
return False
if (len(user_def[key]) != len(value)):
if debug:
print('List lengths are not equal.')
print(('key=[%s]: user_def[%s] != value[%s]' % (key, len(user_def[key]), len(value))))
print(('user_def: %s' % user_def[key]))
print(('value: %s' % value))
return False
for values in zip(user_def[key], value):
if (isinstance(values[0], dict) and isinstance(values[1], dict)):
if debug:
print('sending list - list')
print(type(values[0]))
print(type(values[1]))
result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
if (not result):
print('list compare returned false')
return False
elif (value != user_def[key]):
if debug:
print('value should be identical')
print(user_def[key])
print(value)
return False
elif isinstance(value, dict):
if (key not in user_def):
if debug:
print(('user_def does not have key [%s]' % key))
return False
if (not isinstance(user_def[key], dict)):
if debug:
print('dict returned false: not instance of dict')
return False
api_values = (set(value.keys()) - set(skip))
user_values = (set(user_def[key].keys()) - set(skip))
if (api_values != user_values):
if debug:
print('keys are not equal in dict')
print(user_values)
print(api_values)
return False
result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
if (not result):
if debug:
print('dict returned false')
print(result)
return False
elif ((key not in user_def) or (value != user_def[key])):
if debug:
print('value not equal; user_def does not have key')
print(key)
print(value)
if (key in user_def):
print(user_def[key])
return False
if debug:
print('returning true')
return True
|
@staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
' '
skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for (key, value) in result_def.items():
if (key in skip):
continue
if isinstance(value, list):
if (key not in user_def):
if debug:
print(('User data does not have key [%s]' % key))
print(('User data: %s' % user_def))
return False
if (not isinstance(user_def[key], list)):
if debug:
print(('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])))
return False
if (len(user_def[key]) != len(value)):
if debug:
print('List lengths are not equal.')
print(('key=[%s]: user_def[%s] != value[%s]' % (key, len(user_def[key]), len(value))))
print(('user_def: %s' % user_def[key]))
print(('value: %s' % value))
return False
for values in zip(user_def[key], value):
if (isinstance(values[0], dict) and isinstance(values[1], dict)):
if debug:
print('sending list - list')
print(type(values[0]))
print(type(values[1]))
result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
if (not result):
print('list compare returned false')
return False
elif (value != user_def[key]):
if debug:
print('value should be identical')
print(user_def[key])
print(value)
return False
elif isinstance(value, dict):
if (key not in user_def):
if debug:
print(('user_def does not have key [%s]' % key))
return False
if (not isinstance(user_def[key], dict)):
if debug:
print('dict returned false: not instance of dict')
return False
api_values = (set(value.keys()) - set(skip))
user_values = (set(user_def[key].keys()) - set(skip))
if (api_values != user_values):
if debug:
print('keys are not equal in dict')
print(user_values)
print(api_values)
return False
result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
if (not result):
if debug:
print('dict returned false')
print(result)
return False
elif ((key not in user_def) or (value != user_def[key])):
if debug:
print('value not equal; user_def does not have key')
print(key)
print(value)
if (key in user_def):
print(user_def[key])
return False
if debug:
print('returning true')
return True<|docstring|>Given a user defined definition, compare it with the results given back by our query.<|endoftext|>
|
257e2389bbc3ebd07b473758bf933a95d1288813ab21367be8af1e157892f130
|
@property
def config_options(self):
' return config options '
return self._options
|
return config options
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
config_options
|
vizakua/openshift-tools
| 164
|
python
|
@property
def config_options(self):
' '
return self._options
|
@property
def config_options(self):
' '
return self._options<|docstring|>return config options<|endoftext|>
|
a32badabf51f1ec4008d38812000d5bf5ffb06dbc25078b80186c1798fbfe206
|
def to_option_list(self, ascommalist=''):
'return all options as a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs'
return self.stringify(ascommalist)
|
return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
to_option_list
|
vizakua/openshift-tools
| 164
|
python
|
def to_option_list(self, ascommalist=):
'return all options as a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs'
return self.stringify(ascommalist)
|
def to_option_list(self, ascommalist=):
'return all options as a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs'
return self.stringify(ascommalist)<|docstring|>return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs<|endoftext|>
|
16bbc17f9d4d38cedb3ac2289b45d0267aa8692871c9c24ba596672f703f33ac
|
def stringify(self, ascommalist=''):
' return the options hash as cli params in a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs '
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if (data['include'] and ((data['value'] is not None) or isinstance(data['value'], int))):
if (key == ascommalist):
val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval
|
return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
stringify
|
vizakua/openshift-tools
| 164
|
python
|
def stringify(self, ascommalist=):
' return the options hash as cli params in a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs '
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if (data['include'] and ((data['value'] is not None) or isinstance(data['value'], int))):
if (key == ascommalist):
val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval
|
def stringify(self, ascommalist=):
' return the options hash as cli params in a string\n if ascommalist is set to the name of a key, and\n the value of that key is a dict, format the dict\n as a list of comma delimited key=value pairs '
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if (data['include'] and ((data['value'] is not None) or isinstance(data['value'], int))):
if (key == ascommalist):
val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval<|docstring|>return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs<|endoftext|>
|
5c0fb559c8e9721627fab652de8d958a245d42cb5a808e8f263e1ccfb18e59e0
|
def __init__(self, content=None):
' Constructor for deploymentconfig '
if (not content):
content = DeploymentConfig.default_deployment_config
super(DeploymentConfig, self).__init__(content=content)
|
Constructor for deploymentconfig
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
__init__
|
vizakua/openshift-tools
| 164
|
python
|
def __init__(self, content=None):
' '
if (not content):
content = DeploymentConfig.default_deployment_config
super(DeploymentConfig, self).__init__(content=content)
|
def __init__(self, content=None):
' '
if (not content):
content = DeploymentConfig.default_deployment_config
super(DeploymentConfig, self).__init__(content=content)<|docstring|>Constructor for deploymentconfig<|endoftext|>
|
87e2c794a086e7438e3b905a2366640d1d9a391dc9e0172b483b7266f1fa0f57
|
def add_env_value(self, key, value):
' add key, value pair to env array '
rval = False
env = self.get_env_vars()
if env:
env.append({'name': key, 'value': value})
rval = True
else:
result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
rval = result[0]
return rval
|
add key, value pair to env array
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
add_env_value
|
vizakua/openshift-tools
| 164
|
python
|
def add_env_value(self, key, value):
' '
rval = False
env = self.get_env_vars()
if env:
env.append({'name': key, 'value': value})
rval = True
else:
result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
rval = result[0]
return rval
|
def add_env_value(self, key, value):
' '
rval = False
env = self.get_env_vars()
if env:
env.append({'name': key, 'value': value})
rval = True
else:
result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
rval = result[0]
return rval<|docstring|>add key, value pair to env array<|endoftext|>
|
bfc8eda6aedec7d26637bcb4b74028af9295d3ce2df10730761882e6145ae8ce
|
def exists_env_value(self, key, value):
' return whether a key, value pair exists '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if ((result['name'] == key) and (result['value'] == value)):
return True
return False
|
return whether a key, value pair exists
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
exists_env_value
|
vizakua/openshift-tools
| 164
|
python
|
def exists_env_value(self, key, value):
' '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if ((result['name'] == key) and (result['value'] == value)):
return True
return False
|
def exists_env_value(self, key, value):
' '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if ((result['name'] == key) and (result['value'] == value)):
return True
return False<|docstring|>return whether a key, value pair exists<|endoftext|>
|
c9790feb76296d89b3b7387aabd6948b757284c2b713f72dcf295f26593b1f12
|
def exists_env_key(self, key):
' return whether a key, value pair exists '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if (result['name'] == key):
return True
return False
|
return whether a key, value pair exists
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
exists_env_key
|
vizakua/openshift-tools
| 164
|
python
|
def exists_env_key(self, key):
' '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if (result['name'] == key):
return True
return False
|
def exists_env_key(self, key):
' '
results = self.get_env_vars()
if (not results):
return False
for result in results:
if (result['name'] == key):
return True
return False<|docstring|>return whether a key, value pair exists<|endoftext|>
|
1408706c79e8f282c016bcf69f6bc29770ca90ba184edb6ed226decbd520d8b5
|
def get_env_var(self, key):
'return a environment variables '
results = (self.get(DeploymentConfig.env_path) or [])
if (not results):
return None
for env_var in results:
if (env_var['name'] == key):
return env_var
return None
|
return a environment variables
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_env_var
|
vizakua/openshift-tools
| 164
|
python
|
def get_env_var(self, key):
' '
results = (self.get(DeploymentConfig.env_path) or [])
if (not results):
return None
for env_var in results:
if (env_var['name'] == key):
return env_var
return None
|
def get_env_var(self, key):
' '
results = (self.get(DeploymentConfig.env_path) or [])
if (not results):
return None
for env_var in results:
if (env_var['name'] == key):
return env_var
return None<|docstring|>return a environment variables<|endoftext|>
|
741a77aaccbef2425b4b9bc0b0f2e0b37149a301ff27eb7891fec25dbd564602
|
def get_env_vars(self):
'return a environment variables '
return (self.get(DeploymentConfig.env_path) or [])
|
return a environment variables
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_env_vars
|
vizakua/openshift-tools
| 164
|
python
|
def get_env_vars(self):
' '
return (self.get(DeploymentConfig.env_path) or [])
|
def get_env_vars(self):
' '
return (self.get(DeploymentConfig.env_path) or [])<|docstring|>return a environment variables<|endoftext|>
|
0645ac982af0eca287a29d878fd71805568397030485689f238230b7e013a912
|
def delete_env_var(self, keys):
'delete a list of keys '
if (not isinstance(keys, list)):
keys = [keys]
env_vars_array = self.get_env_vars()
modified = False
idx = None
for key in keys:
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
modified = True
del env_vars_array[idx]
if modified:
return True
return False
|
delete a list of keys
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
delete_env_var
|
vizakua/openshift-tools
| 164
|
python
|
def delete_env_var(self, keys):
' '
if (not isinstance(keys, list)):
keys = [keys]
env_vars_array = self.get_env_vars()
modified = False
idx = None
for key in keys:
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
modified = True
del env_vars_array[idx]
if modified:
return True
return False
|
def delete_env_var(self, keys):
' '
if (not isinstance(keys, list)):
keys = [keys]
env_vars_array = self.get_env_vars()
modified = False
idx = None
for key in keys:
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
modified = True
del env_vars_array[idx]
if modified:
return True
return False<|docstring|>delete a list of keys<|endoftext|>
|
7146b9e5a6a351cfd67987fcc600ec660f1e6c93b97531ed97b5e356c5f8d01d
|
def update_env_var(self, key, value):
'place an env in the env var list'
env_vars_array = self.get_env_vars()
idx = None
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
env_vars_array[idx]['value'] = value
else:
self.add_env_value(key, value)
return True
|
place an env in the env var list
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
update_env_var
|
vizakua/openshift-tools
| 164
|
python
|
def update_env_var(self, key, value):
env_vars_array = self.get_env_vars()
idx = None
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
env_vars_array[idx]['value'] = value
else:
self.add_env_value(key, value)
return True
|
def update_env_var(self, key, value):
env_vars_array = self.get_env_vars()
idx = None
for (env_idx, env_var) in enumerate(env_vars_array):
if (env_var['name'] == key):
idx = env_idx
break
if idx:
env_vars_array[idx]['value'] = value
else:
self.add_env_value(key, value)
return True<|docstring|>place an env in the env var list<|endoftext|>
|
ac2adbae3b95a8d67030e038d7537b30a25ef78bbfd0d618136108fe4a73a503
|
def exists_volume_mount(self, volume_mount):
' return whether a volume mount exists '
exist_volume_mounts = self.get_volume_mounts()
if (not exist_volume_mounts):
return False
volume_mount_found = False
for exist_volume_mount in exist_volume_mounts:
if (exist_volume_mount['name'] == volume_mount['name']):
volume_mount_found = True
break
return volume_mount_found
|
return whether a volume mount exists
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
exists_volume_mount
|
vizakua/openshift-tools
| 164
|
python
|
def exists_volume_mount(self, volume_mount):
' '
exist_volume_mounts = self.get_volume_mounts()
if (not exist_volume_mounts):
return False
volume_mount_found = False
for exist_volume_mount in exist_volume_mounts:
if (exist_volume_mount['name'] == volume_mount['name']):
volume_mount_found = True
break
return volume_mount_found
|
def exists_volume_mount(self, volume_mount):
' '
exist_volume_mounts = self.get_volume_mounts()
if (not exist_volume_mounts):
return False
volume_mount_found = False
for exist_volume_mount in exist_volume_mounts:
if (exist_volume_mount['name'] == volume_mount['name']):
volume_mount_found = True
break
return volume_mount_found<|docstring|>return whether a volume mount exists<|endoftext|>
|
4e16bc790573cb4262305a110c60c49230aa046222ef3ef8fdf46815040ede1e
|
def exists_volume(self, volume):
' return whether a volume exists '
exist_volumes = self.get_volumes()
volume_found = False
for exist_volume in exist_volumes:
if (exist_volume['name'] == volume['name']):
volume_found = True
break
return volume_found
|
return whether a volume exists
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
exists_volume
|
vizakua/openshift-tools
| 164
|
python
|
def exists_volume(self, volume):
' '
exist_volumes = self.get_volumes()
volume_found = False
for exist_volume in exist_volumes:
if (exist_volume['name'] == volume['name']):
volume_found = True
break
return volume_found
|
def exists_volume(self, volume):
' '
exist_volumes = self.get_volumes()
volume_found = False
for exist_volume in exist_volumes:
if (exist_volume['name'] == volume['name']):
volume_found = True
break
return volume_found<|docstring|>return whether a volume exists<|endoftext|>
|
d8830a92243eaa6efe79a66bd05143ac026ebc54de07a0f5c8a3ba7e3897ac84
|
def find_volume_by_name(self, volume, mounts=False):
' return the index of a volume '
volumes = []
if mounts:
volumes = self.get_volume_mounts()
else:
volumes = self.get_volumes()
for exist_volume in volumes:
if (exist_volume['name'] == volume['name']):
return exist_volume
return None
|
return the index of a volume
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
find_volume_by_name
|
vizakua/openshift-tools
| 164
|
python
|
def find_volume_by_name(self, volume, mounts=False):
' '
volumes = []
if mounts:
volumes = self.get_volume_mounts()
else:
volumes = self.get_volumes()
for exist_volume in volumes:
if (exist_volume['name'] == volume['name']):
return exist_volume
return None
|
def find_volume_by_name(self, volume, mounts=False):
' '
volumes = []
if mounts:
volumes = self.get_volume_mounts()
else:
volumes = self.get_volumes()
for exist_volume in volumes:
if (exist_volume['name'] == volume['name']):
return exist_volume
return None<|docstring|>return the index of a volume<|endoftext|>
|
cb2bda7f19b2f9932ca34163f84f6d8a50e23a54d4d9d4766e7859ed684ad3ac
|
def get_replicas(self):
' return replicas setting '
return self.get(DeploymentConfig.replicas_path)
|
return replicas setting
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_replicas
|
vizakua/openshift-tools
| 164
|
python
|
def get_replicas(self):
' '
return self.get(DeploymentConfig.replicas_path)
|
def get_replicas(self):
' '
return self.get(DeploymentConfig.replicas_path)<|docstring|>return replicas setting<|endoftext|>
|
922514f829fb63dee9bc950f1118bbff71b8d8d3f3dda4a4b7b57589c655f07c
|
def get_volume_mounts(self):
'return volume mount information '
return self.get_volumes(mounts=True)
|
return volume mount information
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_volume_mounts
|
vizakua/openshift-tools
| 164
|
python
|
def get_volume_mounts(self):
' '
return self.get_volumes(mounts=True)
|
def get_volume_mounts(self):
' '
return self.get_volumes(mounts=True)<|docstring|>return volume mount information<|endoftext|>
|
ce97afd45828f74fbfd800617ce2eb3aa6b0e38af1b75021e65f9a3a293f6489
|
def get_volumes(self, mounts=False):
'return volume mount information '
if mounts:
return (self.get(DeploymentConfig.volume_mounts_path) or [])
return (self.get(DeploymentConfig.volumes_path) or [])
|
return volume mount information
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get_volumes
|
vizakua/openshift-tools
| 164
|
python
|
def get_volumes(self, mounts=False):
' '
if mounts:
return (self.get(DeploymentConfig.volume_mounts_path) or [])
return (self.get(DeploymentConfig.volumes_path) or [])
|
def get_volumes(self, mounts=False):
' '
if mounts:
return (self.get(DeploymentConfig.volume_mounts_path) or [])
return (self.get(DeploymentConfig.volumes_path) or [])<|docstring|>return volume mount information<|endoftext|>
|
b5a62853b102a967e48b416ca165ba082335c548db3f8db840d18ec1c27872ce
|
def delete_volume_by_name(self, volume):
'delete a volume '
modified = False
exist_volume_mounts = self.get_volume_mounts()
exist_volumes = self.get_volumes()
del_idx = None
for (idx, exist_volume) in enumerate(exist_volumes):
if (('name' in exist_volume) and (exist_volume['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volumes[del_idx]
modified = True
del_idx = None
for (idx, exist_volume_mount) in enumerate(exist_volume_mounts):
if (('name' in exist_volume_mount) and (exist_volume_mount['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volume_mounts[idx]
modified = True
return modified
|
delete a volume
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
delete_volume_by_name
|
vizakua/openshift-tools
| 164
|
python
|
def delete_volume_by_name(self, volume):
' '
modified = False
exist_volume_mounts = self.get_volume_mounts()
exist_volumes = self.get_volumes()
del_idx = None
for (idx, exist_volume) in enumerate(exist_volumes):
if (('name' in exist_volume) and (exist_volume['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volumes[del_idx]
modified = True
del_idx = None
for (idx, exist_volume_mount) in enumerate(exist_volume_mounts):
if (('name' in exist_volume_mount) and (exist_volume_mount['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volume_mounts[idx]
modified = True
return modified
|
def delete_volume_by_name(self, volume):
' '
modified = False
exist_volume_mounts = self.get_volume_mounts()
exist_volumes = self.get_volumes()
del_idx = None
for (idx, exist_volume) in enumerate(exist_volumes):
if (('name' in exist_volume) and (exist_volume['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volumes[del_idx]
modified = True
del_idx = None
for (idx, exist_volume_mount) in enumerate(exist_volume_mounts):
if (('name' in exist_volume_mount) and (exist_volume_mount['name'] == volume['name'])):
del_idx = idx
break
if (del_idx != None):
del exist_volume_mounts[idx]
modified = True
return modified<|docstring|>delete a volume<|endoftext|>
|
e4e51f49ace21f4f0b5bc58bb887925b31d75fe65e6580783ca67d9a6a4feaeb
|
def add_volume_mount(self, volume_mount):
' add a volume or volume mount to the proper location '
exist_volume_mounts = self.get_volume_mounts()
if ((not exist_volume_mounts) and volume_mount):
self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
else:
exist_volume_mounts.append(volume_mount)
|
add a volume or volume mount to the proper location
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
add_volume_mount
|
vizakua/openshift-tools
| 164
|
python
|
def add_volume_mount(self, volume_mount):
' '
exist_volume_mounts = self.get_volume_mounts()
if ((not exist_volume_mounts) and volume_mount):
self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
else:
exist_volume_mounts.append(volume_mount)
|
def add_volume_mount(self, volume_mount):
' '
exist_volume_mounts = self.get_volume_mounts()
if ((not exist_volume_mounts) and volume_mount):
self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
else:
exist_volume_mounts.append(volume_mount)<|docstring|>add a volume or volume mount to the proper location<|endoftext|>
|
5071300e3aba623c49af3ae1b24911407a46eb207a0e2cc2887df435fca9951a
|
def add_volume(self, volume):
' add a volume or volume mount to the proper location '
exist_volumes = self.get_volumes()
if (not volume):
return
if (not exist_volumes):
self.put(DeploymentConfig.volumes_path, [volume])
else:
exist_volumes.append(volume)
|
add a volume or volume mount to the proper location
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
add_volume
|
vizakua/openshift-tools
| 164
|
python
|
def add_volume(self, volume):
' '
exist_volumes = self.get_volumes()
if (not volume):
return
if (not exist_volumes):
self.put(DeploymentConfig.volumes_path, [volume])
else:
exist_volumes.append(volume)
|
def add_volume(self, volume):
' '
exist_volumes = self.get_volumes()
if (not volume):
return
if (not exist_volumes):
self.put(DeploymentConfig.volumes_path, [volume])
else:
exist_volumes.append(volume)<|docstring|>add a volume or volume mount to the proper location<|endoftext|>
|
7a86d0c1ec7d2a0f1fff7e10048b0ff85ff13965f943481568fb44066da2568a
|
def update_replicas(self, replicas):
' update replicas value '
self.put(DeploymentConfig.replicas_path, replicas)
|
update replicas value
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
update_replicas
|
vizakua/openshift-tools
| 164
|
python
|
def update_replicas(self, replicas):
' '
self.put(DeploymentConfig.replicas_path, replicas)
|
def update_replicas(self, replicas):
' '
self.put(DeploymentConfig.replicas_path, replicas)<|docstring|>update replicas value<|endoftext|>
|
95d73b5662786c0e9dfe9161a53e5ce6c7dc67e5e4ffe0f6b22890ef41b0a0a3
|
def update_volume(self, volume):
'place an env in the env var list'
exist_volumes = self.get_volumes()
if (not volume):
return False
update_idx = None
for (idx, exist_vol) in enumerate(exist_volumes):
if (exist_vol['name'] == volume['name']):
update_idx = idx
break
if (update_idx != None):
exist_volumes[update_idx] = volume
else:
self.add_volume(volume)
return True
|
place an env in the env var list
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
update_volume
|
vizakua/openshift-tools
| 164
|
python
|
def update_volume(self, volume):
exist_volumes = self.get_volumes()
if (not volume):
return False
update_idx = None
for (idx, exist_vol) in enumerate(exist_volumes):
if (exist_vol['name'] == volume['name']):
update_idx = idx
break
if (update_idx != None):
exist_volumes[update_idx] = volume
else:
self.add_volume(volume)
return True
|
def update_volume(self, volume):
exist_volumes = self.get_volumes()
if (not volume):
return False
update_idx = None
for (idx, exist_vol) in enumerate(exist_volumes):
if (exist_vol['name'] == volume['name']):
update_idx = idx
break
if (update_idx != None):
exist_volumes[update_idx] = volume
else:
self.add_volume(volume)
return True<|docstring|>place an env in the env var list<|endoftext|>
|
515dd9888daf74374c7fa1f3c1af9c74404f73f6fd357d2736837f98f6cacb28
|
def update_volume_mount(self, volume_mount):
'place an env in the env var list'
modified = False
exist_volume_mounts = self.get_volume_mounts()
if (not volume_mount):
return False
for exist_vol_mount in exist_volume_mounts:
if (exist_vol_mount['name'] == volume_mount['name']):
if (('mountPath' in exist_vol_mount) and (str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']))):
exist_vol_mount['mountPath'] = volume_mount['mountPath']
modified = True
break
if (not modified):
self.add_volume_mount(volume_mount)
modified = True
return modified
|
place an env in the env var list
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
update_volume_mount
|
vizakua/openshift-tools
| 164
|
python
|
def update_volume_mount(self, volume_mount):
modified = False
exist_volume_mounts = self.get_volume_mounts()
if (not volume_mount):
return False
for exist_vol_mount in exist_volume_mounts:
if (exist_vol_mount['name'] == volume_mount['name']):
if (('mountPath' in exist_vol_mount) and (str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']))):
exist_vol_mount['mountPath'] = volume_mount['mountPath']
modified = True
break
if (not modified):
self.add_volume_mount(volume_mount)
modified = True
return modified
|
def update_volume_mount(self, volume_mount):
modified = False
exist_volume_mounts = self.get_volume_mounts()
if (not volume_mount):
return False
for exist_vol_mount in exist_volume_mounts:
if (exist_vol_mount['name'] == volume_mount['name']):
if (('mountPath' in exist_vol_mount) and (str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']))):
exist_vol_mount['mountPath'] = volume_mount['mountPath']
modified = True
break
if (not modified):
self.add_volume_mount(volume_mount)
modified = True
return modified<|docstring|>place an env in the env var list<|endoftext|>
|
59f41a47d16b1d38ebf8386a9678385f70efd17c0f152b80634047a327e1a072
|
def needs_update_volume(self, volume, volume_mount):
' verify a volume update is needed '
exist_volume = self.find_volume_by_name(volume)
exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
results = []
results.append((exist_volume['name'] == volume['name']))
if ('secret' in volume):
results.append(('secret' in exist_volume))
results.append((exist_volume['secret']['secretName'] == volume['secret']['secretName']))
results.append((exist_volume_mount['name'] == volume_mount['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('emptyDir' in volume):
results.append((exist_volume_mount['name'] == volume['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('persistentVolumeClaim' in volume):
pvc = 'persistentVolumeClaim'
results.append((pvc in exist_volume))
if results[(- 1)]:
results.append((exist_volume[pvc]['claimName'] == volume[pvc]['claimName']))
if ('claimSize' in volume[pvc]):
results.append((exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize']))
elif ('hostpath' in volume):
results.append(('hostPath' in exist_volume))
results.append((exist_volume['hostPath']['path'] == volume_mount['mountPath']))
return (not all(results))
|
verify a volume update is needed
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
needs_update_volume
|
vizakua/openshift-tools
| 164
|
python
|
def needs_update_volume(self, volume, volume_mount):
' '
exist_volume = self.find_volume_by_name(volume)
exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
results = []
results.append((exist_volume['name'] == volume['name']))
if ('secret' in volume):
results.append(('secret' in exist_volume))
results.append((exist_volume['secret']['secretName'] == volume['secret']['secretName']))
results.append((exist_volume_mount['name'] == volume_mount['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('emptyDir' in volume):
results.append((exist_volume_mount['name'] == volume['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('persistentVolumeClaim' in volume):
pvc = 'persistentVolumeClaim'
results.append((pvc in exist_volume))
if results[(- 1)]:
results.append((exist_volume[pvc]['claimName'] == volume[pvc]['claimName']))
if ('claimSize' in volume[pvc]):
results.append((exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize']))
elif ('hostpath' in volume):
results.append(('hostPath' in exist_volume))
results.append((exist_volume['hostPath']['path'] == volume_mount['mountPath']))
return (not all(results))
|
def needs_update_volume(self, volume, volume_mount):
' '
exist_volume = self.find_volume_by_name(volume)
exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
results = []
results.append((exist_volume['name'] == volume['name']))
if ('secret' in volume):
results.append(('secret' in exist_volume))
results.append((exist_volume['secret']['secretName'] == volume['secret']['secretName']))
results.append((exist_volume_mount['name'] == volume_mount['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('emptyDir' in volume):
results.append((exist_volume_mount['name'] == volume['name']))
results.append((exist_volume_mount['mountPath'] == volume_mount['mountPath']))
elif ('persistentVolumeClaim' in volume):
pvc = 'persistentVolumeClaim'
results.append((pvc in exist_volume))
if results[(- 1)]:
results.append((exist_volume[pvc]['claimName'] == volume[pvc]['claimName']))
if ('claimSize' in volume[pvc]):
results.append((exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize']))
elif ('hostpath' in volume):
results.append(('hostPath' in exist_volume))
results.append((exist_volume['hostPath']['path'] == volume_mount['mountPath']))
return (not all(results))<|docstring|>verify a volume update is needed<|endoftext|>
|
98097dd827dd2964d3ffe5b567749f104334b269eb66bb38497581a78e2656bd
|
def needs_update_replicas(self, replicas):
' verify whether a replica update is needed '
current_reps = self.get(DeploymentConfig.replicas_path)
return (not (current_reps == replicas))
|
verify whether a replica update is needed
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
needs_update_replicas
|
vizakua/openshift-tools
| 164
|
python
|
def needs_update_replicas(self, replicas):
' '
current_reps = self.get(DeploymentConfig.replicas_path)
return (not (current_reps == replicas))
|
def needs_update_replicas(self, replicas):
' '
current_reps = self.get(DeploymentConfig.replicas_path)
return (not (current_reps == replicas))<|docstring|>verify whether a replica update is needed<|endoftext|>
|
6ddc809566bc993a93276ece76d5b036feb0534fc80dbbac5fbdb095b6d3c4cb
|
def __init__(self, content):
' Constructor for ReplicationController '
super(ReplicationController, self).__init__(content=content)
|
Constructor for ReplicationController
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
__init__
|
vizakua/openshift-tools
| 164
|
python
|
def __init__(self, content):
' '
super(ReplicationController, self).__init__(content=content)
|
def __init__(self, content):
' '
super(ReplicationController, self).__init__(content=content)<|docstring|>Constructor for ReplicationController<|endoftext|>
|
71a1cd9567eaf7a09667cee583e7a7bf60cc5ace56c5dec0c115b29fa57a280a
|
def __init__(self, resource_name, namespace, replicas, kind, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False):
' Constructor for OCScale '
super(OCScale, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
self.kind = kind
self.replicas = replicas
self.name = resource_name
self._resource = None
|
Constructor for OCScale
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
__init__
|
vizakua/openshift-tools
| 164
|
python
|
def __init__(self, resource_name, namespace, replicas, kind, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False):
' '
super(OCScale, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
self.kind = kind
self.replicas = replicas
self.name = resource_name
self._resource = None
|
def __init__(self, resource_name, namespace, replicas, kind, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False):
' '
super(OCScale, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
self.kind = kind
self.replicas = replicas
self.name = resource_name
self._resource = None<|docstring|>Constructor for OCScale<|endoftext|>
|
8dd6806ade6379530ee0c4389e811a75450814a59d438e5378e53065ab2bd3ee
|
@property
def resource(self):
' property function for resource var '
if (not self._resource):
self.get()
return self._resource
|
property function for resource var
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
resource
|
vizakua/openshift-tools
| 164
|
python
|
@property
def resource(self):
' '
if (not self._resource):
self.get()
return self._resource
|
@property
def resource(self):
' '
if (not self._resource):
self.get()
return self._resource<|docstring|>property function for resource var<|endoftext|>
|
2637b610f53b8880eba7f74f2db1ec43cc3c2356f9783575de9db3e430c6e39d
|
@resource.setter
def resource(self, data):
' setter function for resource var '
self._resource = data
|
setter function for resource var
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
resource
|
vizakua/openshift-tools
| 164
|
python
|
@resource.setter
def resource(self, data):
' '
self._resource = data
|
@resource.setter
def resource(self, data):
' '
self._resource = data<|docstring|>setter function for resource var<|endoftext|>
|
c67890813eb5910e42f6e9140fe21f8209666479632cd7f99fc0241ea5530140
|
def get(self):
'return replicas information '
vol = self._get(self.kind, self.name)
if (vol['returncode'] == 0):
if (self.kind == 'dc'):
self.resource = DeploymentConfig(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
if (self.kind == 'rc'):
self.resource = ReplicationController(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
return vol
|
return replicas information
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
get
|
vizakua/openshift-tools
| 164
|
python
|
def get(self):
' '
vol = self._get(self.kind, self.name)
if (vol['returncode'] == 0):
if (self.kind == 'dc'):
self.resource = DeploymentConfig(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
if (self.kind == 'rc'):
self.resource = ReplicationController(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
return vol
|
def get(self):
' '
vol = self._get(self.kind, self.name)
if (vol['returncode'] == 0):
if (self.kind == 'dc'):
self.resource = DeploymentConfig(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
if (self.kind == 'rc'):
self.resource = ReplicationController(content=vol['results'][0])
vol['results'] = [self.resource.get_replicas()]
return vol<|docstring|>return replicas information<|endoftext|>
|
84351d64f6bef0cba2802ff9d43fe80ae65bf33e7ef221cd7a595c2a9f9e49df
|
def put(self):
'update replicas into dc '
self.resource.update_replicas(self.replicas)
return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
|
update replicas into dc
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
put
|
vizakua/openshift-tools
| 164
|
python
|
def put(self):
' '
self.resource.update_replicas(self.replicas)
return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
|
def put(self):
' '
self.resource.update_replicas(self.replicas)
return self._replace_content(self.kind, self.name, self.resource.yaml_dict)<|docstring|>update replicas into dc<|endoftext|>
|
2ec7ca52c0cdb2aa2741275adbc717aca22f839e371c48fe0a214b93bab31719
|
def needs_update(self):
' verify whether an update is needed '
return self.resource.needs_update_replicas(self.replicas)
|
verify whether an update is needed
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
needs_update
|
vizakua/openshift-tools
| 164
|
python
|
def needs_update(self):
' '
return self.resource.needs_update_replicas(self.replicas)
|
def needs_update(self):
' '
return self.resource.needs_update_replicas(self.replicas)<|docstring|>verify whether an update is needed<|endoftext|>
|
34fa1449339139658e13fe1db93a42ed922fd1a60eafb7996c2a55d5cde3531e
|
@staticmethod
def run_ansible(params, check_mode):
'perform the idempotent ansible logic'
oc_scale = OCScale(params['name'], params['namespace'], params['replicas'], params['kind'], params['kubeconfig'], verbose=params['debug'])
state = params['state']
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
if (state == 'list'):
return {'changed': False, 'result': api_rval['results'], 'state': 'list'}
elif (state == 'present'):
if oc_scale.needs_update():
if check_mode:
return {'changed': True, 'result': 'CHECK_MODE: Would have updated.'}
api_rval = oc_scale.put()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'result': api_rval['results'], 'state': 'present'}
return {'changed': False, 'result': api_rval['results'], 'state': 'present'}
return {'failed': True, 'msg': 'Unknown state passed. [{}]'.format(state)}
|
perform the idempotent ansible logic
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
|
run_ansible
|
vizakua/openshift-tools
| 164
|
python
|
@staticmethod
def run_ansible(params, check_mode):
oc_scale = OCScale(params['name'], params['namespace'], params['replicas'], params['kind'], params['kubeconfig'], verbose=params['debug'])
state = params['state']
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
if (state == 'list'):
return {'changed': False, 'result': api_rval['results'], 'state': 'list'}
elif (state == 'present'):
if oc_scale.needs_update():
if check_mode:
return {'changed': True, 'result': 'CHECK_MODE: Would have updated.'}
api_rval = oc_scale.put()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'result': api_rval['results'], 'state': 'present'}
return {'changed': False, 'result': api_rval['results'], 'state': 'present'}
return {'failed': True, 'msg': 'Unknown state passed. [{}]'.format(state)}
|
@staticmethod
def run_ansible(params, check_mode):
oc_scale = OCScale(params['name'], params['namespace'], params['replicas'], params['kind'], params['kubeconfig'], verbose=params['debug'])
state = params['state']
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
if (state == 'list'):
return {'changed': False, 'result': api_rval['results'], 'state': 'list'}
elif (state == 'present'):
if oc_scale.needs_update():
if check_mode:
return {'changed': True, 'result': 'CHECK_MODE: Would have updated.'}
api_rval = oc_scale.put()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
api_rval = oc_scale.get()
if (api_rval['returncode'] != 0):
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'result': api_rval['results'], 'state': 'present'}
return {'changed': False, 'result': api_rval['results'], 'state': 'present'}
return {'failed': True, 'msg': 'Unknown state passed. [{}]'.format(state)}<|docstring|>perform the idempotent ansible logic<|endoftext|>
|
77810b0613ac44b307c6099cc9c43019aa06ba1ecaea85f0b7b3be6019366b43
|
def polygon_to_bitmap(polygons, height, width):
'Convert masks from the form of polygons to bitmaps.\n\n Args:\n polygons (list[ndarray]): masks in polygon representation\n height (int): mask height\n width (int): mask width\n\n Return:\n ndarray: the converted masks in bitmap representation\n '
rles = maskUtils.frPyObjects(polygons, height, width)
rle = maskUtils.merge(rles)
bitmap_mask = maskUtils.decode(rle).astype(np.bool)
return bitmap_mask
|
Convert masks from the form of polygons to bitmaps.
Args:
polygons (list[ndarray]): masks in polygon representation
height (int): mask height
width (int): mask width
Return:
ndarray: the converted masks in bitmap representation
|
mmdet/core/mask/structures.py
|
polygon_to_bitmap
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def polygon_to_bitmap(polygons, height, width):
'Convert masks from the form of polygons to bitmaps.\n\n Args:\n polygons (list[ndarray]): masks in polygon representation\n height (int): mask height\n width (int): mask width\n\n Return:\n ndarray: the converted masks in bitmap representation\n '
rles = maskUtils.frPyObjects(polygons, height, width)
rle = maskUtils.merge(rles)
bitmap_mask = maskUtils.decode(rle).astype(np.bool)
return bitmap_mask
|
def polygon_to_bitmap(polygons, height, width):
'Convert masks from the form of polygons to bitmaps.\n\n Args:\n polygons (list[ndarray]): masks in polygon representation\n height (int): mask height\n width (int): mask width\n\n Return:\n ndarray: the converted masks in bitmap representation\n '
rles = maskUtils.frPyObjects(polygons, height, width)
rle = maskUtils.merge(rles)
bitmap_mask = maskUtils.decode(rle).astype(np.bool)
return bitmap_mask<|docstring|>Convert masks from the form of polygons to bitmaps.
Args:
polygons (list[ndarray]): masks in polygon representation
height (int): mask height
width (int): mask width
Return:
ndarray: the converted masks in bitmap representation<|endoftext|>
|
a4e7176d939cec1e390c6c45f65989c349e8d7cd5e262832f01037da39464307
|
@abstractmethod
def rescale(self, scale, interpolation='nearest'):
'Rescale masks as large as possible while keeping the aspect ratio.\n For details can refer to `mmcv.imrescale`.\n\n Args:\n scale (tuple[int]): The maximum size (h, w) of rescaled mask.\n interpolation (str): Same as :func:`mmcv.imrescale`.\n\n Returns:\n BaseInstanceMasks: The rescaled masks.\n '
|
Rescale masks as large as possible while keeping the aspect ratio.
For details can refer to `mmcv.imrescale`.
Args:
scale (tuple[int]): The maximum size (h, w) of rescaled mask.
interpolation (str): Same as :func:`mmcv.imrescale`.
Returns:
BaseInstanceMasks: The rescaled masks.
|
mmdet/core/mask/structures.py
|
rescale
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def rescale(self, scale, interpolation='nearest'):
'Rescale masks as large as possible while keeping the aspect ratio.\n For details can refer to `mmcv.imrescale`.\n\n Args:\n scale (tuple[int]): The maximum size (h, w) of rescaled mask.\n interpolation (str): Same as :func:`mmcv.imrescale`.\n\n Returns:\n BaseInstanceMasks: The rescaled masks.\n '
|
@abstractmethod
def rescale(self, scale, interpolation='nearest'):
'Rescale masks as large as possible while keeping the aspect ratio.\n For details can refer to `mmcv.imrescale`.\n\n Args:\n scale (tuple[int]): The maximum size (h, w) of rescaled mask.\n interpolation (str): Same as :func:`mmcv.imrescale`.\n\n Returns:\n BaseInstanceMasks: The rescaled masks.\n '<|docstring|>Rescale masks as large as possible while keeping the aspect ratio.
For details can refer to `mmcv.imrescale`.
Args:
scale (tuple[int]): The maximum size (h, w) of rescaled mask.
interpolation (str): Same as :func:`mmcv.imrescale`.
Returns:
BaseInstanceMasks: The rescaled masks.<|endoftext|>
|
2b1cbd2bba446b19b1160cf681d17a3452688768aad0a3319977fb8f895692e7
|
@abstractmethod
def resize(self, out_shape, interpolation='nearest'):
'Resize masks to the given out_shape.\n\n Args:\n out_shape: Target (h, w) of resized mask.\n interpolation (str): See :func:`mmcv.imresize`.\n\n Returns:\n BaseInstanceMasks: The resized masks.\n '
|
Resize masks to the given out_shape.
Args:
out_shape: Target (h, w) of resized mask.
interpolation (str): See :func:`mmcv.imresize`.
Returns:
BaseInstanceMasks: The resized masks.
|
mmdet/core/mask/structures.py
|
resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def resize(self, out_shape, interpolation='nearest'):
'Resize masks to the given out_shape.\n\n Args:\n out_shape: Target (h, w) of resized mask.\n interpolation (str): See :func:`mmcv.imresize`.\n\n Returns:\n BaseInstanceMasks: The resized masks.\n '
|
@abstractmethod
def resize(self, out_shape, interpolation='nearest'):
'Resize masks to the given out_shape.\n\n Args:\n out_shape: Target (h, w) of resized mask.\n interpolation (str): See :func:`mmcv.imresize`.\n\n Returns:\n BaseInstanceMasks: The resized masks.\n '<|docstring|>Resize masks to the given out_shape.
Args:
out_shape: Target (h, w) of resized mask.
interpolation (str): See :func:`mmcv.imresize`.
Returns:
BaseInstanceMasks: The resized masks.<|endoftext|>
|
d164f449c13ef660140ca7af6c26da4091ddf29ca0775cca57bec077083baebe
|
@abstractmethod
def flip(self, flip_direction='horizontal'):
"Flip masks alone the given direction.\n\n Args:\n flip_direction (str): Either 'horizontal' or 'vertical'.\n\n Returns:\n BaseInstanceMasks: The flipped masks.\n "
|
Flip masks alone the given direction.
Args:
flip_direction (str): Either 'horizontal' or 'vertical'.
Returns:
BaseInstanceMasks: The flipped masks.
|
mmdet/core/mask/structures.py
|
flip
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def flip(self, flip_direction='horizontal'):
"Flip masks alone the given direction.\n\n Args:\n flip_direction (str): Either 'horizontal' or 'vertical'.\n\n Returns:\n BaseInstanceMasks: The flipped masks.\n "
|
@abstractmethod
def flip(self, flip_direction='horizontal'):
"Flip masks alone the given direction.\n\n Args:\n flip_direction (str): Either 'horizontal' or 'vertical'.\n\n Returns:\n BaseInstanceMasks: The flipped masks.\n "<|docstring|>Flip masks alone the given direction.
Args:
flip_direction (str): Either 'horizontal' or 'vertical'.
Returns:
BaseInstanceMasks: The flipped masks.<|endoftext|>
|
1beedfa0070b330cf39fe583fb5fa8f52cced75404b2eae308dec543fa3957c2
|
@abstractmethod
def pad(self, out_shape, pad_val):
'Pad masks to the given size of (h, w).\n\n Args:\n out_shape (tuple[int]): Target (h, w) of padded mask.\n pad_val (int): The padded value.\n\n Returns:\n BaseInstanceMasks: The padded masks.\n '
|
Pad masks to the given size of (h, w).
Args:
out_shape (tuple[int]): Target (h, w) of padded mask.
pad_val (int): The padded value.
Returns:
BaseInstanceMasks: The padded masks.
|
mmdet/core/mask/structures.py
|
pad
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def pad(self, out_shape, pad_val):
'Pad masks to the given size of (h, w).\n\n Args:\n out_shape (tuple[int]): Target (h, w) of padded mask.\n pad_val (int): The padded value.\n\n Returns:\n BaseInstanceMasks: The padded masks.\n '
|
@abstractmethod
def pad(self, out_shape, pad_val):
'Pad masks to the given size of (h, w).\n\n Args:\n out_shape (tuple[int]): Target (h, w) of padded mask.\n pad_val (int): The padded value.\n\n Returns:\n BaseInstanceMasks: The padded masks.\n '<|docstring|>Pad masks to the given size of (h, w).
Args:
out_shape (tuple[int]): Target (h, w) of padded mask.
pad_val (int): The padded value.
Returns:
BaseInstanceMasks: The padded masks.<|endoftext|>
|
016ffbbacfda6ad80310e61a7ffbec7ea722ed07627a6ae36ca90a83efb3abe8
|
@abstractmethod
def crop(self, bbox):
'Crop each mask by the given bbox.\n\n Args:\n bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).\n\n Return:\n BaseInstanceMasks: The cropped masks.\n '
|
Crop each mask by the given bbox.
Args:
bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).
Return:
BaseInstanceMasks: The cropped masks.
|
mmdet/core/mask/structures.py
|
crop
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def crop(self, bbox):
'Crop each mask by the given bbox.\n\n Args:\n bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).\n\n Return:\n BaseInstanceMasks: The cropped masks.\n '
|
@abstractmethod
def crop(self, bbox):
'Crop each mask by the given bbox.\n\n Args:\n bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).\n\n Return:\n BaseInstanceMasks: The cropped masks.\n '<|docstring|>Crop each mask by the given bbox.
Args:
bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ).
Return:
BaseInstanceMasks: The cropped masks.<|endoftext|>
|
1416fd4ee6e15ec95ea2165b9e4ab4bb4caeec81b0af39dba8b92dfd7fba7423
|
@abstractmethod
def crop_and_resize(self, bboxes, out_shape, inds, device, interpolation='bilinear', binarize=True):
'Crop and resize masks by the given bboxes.\n\n This function is mainly used in mask targets computation.\n It firstly align mask to bboxes by assigned_inds, then crop mask by the\n assigned bbox and resize to the size of (mask_h, mask_w)\n\n Args:\n bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)\n out_shape (tuple[int]): Target (h, w) of resized mask\n inds (ndarray): Indexes to assign masks to each bbox,\n shape (N,) and values should be between [0, num_masks - 1].\n device (str): Device of bboxes\n interpolation (str): See `mmcv.imresize`\n binarize (bool): if True fractional values are rounded to 0 or 1\n after the resize operation. if False and unsupported an error\n will be raised. Defaults to True.\n\n Return:\n BaseInstanceMasks: the cropped and resized masks.\n '
|
Crop and resize masks by the given bboxes.
This function is mainly used in mask targets computation.
It firstly align mask to bboxes by assigned_inds, then crop mask by the
assigned bbox and resize to the size of (mask_h, mask_w)
Args:
bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)
out_shape (tuple[int]): Target (h, w) of resized mask
inds (ndarray): Indexes to assign masks to each bbox,
shape (N,) and values should be between [0, num_masks - 1].
device (str): Device of bboxes
interpolation (str): See `mmcv.imresize`
binarize (bool): if True fractional values are rounded to 0 or 1
after the resize operation. if False and unsupported an error
will be raised. Defaults to True.
Return:
BaseInstanceMasks: the cropped and resized masks.
|
mmdet/core/mask/structures.py
|
crop_and_resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def crop_and_resize(self, bboxes, out_shape, inds, device, interpolation='bilinear', binarize=True):
'Crop and resize masks by the given bboxes.\n\n This function is mainly used in mask targets computation.\n It firstly align mask to bboxes by assigned_inds, then crop mask by the\n assigned bbox and resize to the size of (mask_h, mask_w)\n\n Args:\n bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)\n out_shape (tuple[int]): Target (h, w) of resized mask\n inds (ndarray): Indexes to assign masks to each bbox,\n shape (N,) and values should be between [0, num_masks - 1].\n device (str): Device of bboxes\n interpolation (str): See `mmcv.imresize`\n binarize (bool): if True fractional values are rounded to 0 or 1\n after the resize operation. if False and unsupported an error\n will be raised. Defaults to True.\n\n Return:\n BaseInstanceMasks: the cropped and resized masks.\n '
|
@abstractmethod
def crop_and_resize(self, bboxes, out_shape, inds, device, interpolation='bilinear', binarize=True):
'Crop and resize masks by the given bboxes.\n\n This function is mainly used in mask targets computation.\n It firstly align mask to bboxes by assigned_inds, then crop mask by the\n assigned bbox and resize to the size of (mask_h, mask_w)\n\n Args:\n bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)\n out_shape (tuple[int]): Target (h, w) of resized mask\n inds (ndarray): Indexes to assign masks to each bbox,\n shape (N,) and values should be between [0, num_masks - 1].\n device (str): Device of bboxes\n interpolation (str): See `mmcv.imresize`\n binarize (bool): if True fractional values are rounded to 0 or 1\n after the resize operation. if False and unsupported an error\n will be raised. Defaults to True.\n\n Return:\n BaseInstanceMasks: the cropped and resized masks.\n '<|docstring|>Crop and resize masks by the given bboxes.
This function is mainly used in mask targets computation.
It firstly align mask to bboxes by assigned_inds, then crop mask by the
assigned bbox and resize to the size of (mask_h, mask_w)
Args:
bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)
out_shape (tuple[int]): Target (h, w) of resized mask
inds (ndarray): Indexes to assign masks to each bbox,
shape (N,) and values should be between [0, num_masks - 1].
device (str): Device of bboxes
interpolation (str): See `mmcv.imresize`
binarize (bool): if True fractional values are rounded to 0 or 1
after the resize operation. if False and unsupported an error
will be raised. Defaults to True.
Return:
BaseInstanceMasks: the cropped and resized masks.<|endoftext|>
|
741e8c864559cd144717c2bfec384e36b434650032fbc2a429cd6557faf716f6
|
@abstractmethod
def expand(self, expanded_h, expanded_w, top, left):
'see :class:`Expand`.'
|
see :class:`Expand`.
|
mmdet/core/mask/structures.py
|
expand
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def expand(self, expanded_h, expanded_w, top, left):
|
@abstractmethod
def expand(self, expanded_h, expanded_w, top, left):
<|docstring|>see :class:`Expand`.<|endoftext|>
|
4f7ad017a94e92a29a1303dd9dbfa4f9217a428a46ce6aea2d733ad5a151fab0
|
@property
@abstractmethod
def areas(self):
'ndarray: areas of each instance.'
|
ndarray: areas of each instance.
|
mmdet/core/mask/structures.py
|
areas
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@property
@abstractmethod
def areas(self):
|
@property
@abstractmethod
def areas(self):
<|docstring|>ndarray: areas of each instance.<|endoftext|>
|
2dbbe984d852e415b9b51ad89feaaf67322e08bd0781abb725bfb505df1b777b
|
@abstractmethod
def to_ndarray(self):
'Convert masks to the format of ndarray.\n\n Return:\n ndarray: Converted masks in the format of ndarray.\n '
|
Convert masks to the format of ndarray.
Return:
ndarray: Converted masks in the format of ndarray.
|
mmdet/core/mask/structures.py
|
to_ndarray
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def to_ndarray(self):
'Convert masks to the format of ndarray.\n\n Return:\n ndarray: Converted masks in the format of ndarray.\n '
|
@abstractmethod
def to_ndarray(self):
'Convert masks to the format of ndarray.\n\n Return:\n ndarray: Converted masks in the format of ndarray.\n '<|docstring|>Convert masks to the format of ndarray.
Return:
ndarray: Converted masks in the format of ndarray.<|endoftext|>
|
a4b8785a6b899f6763f4684a5747ec3764fed20294664732be2588c12ea7ab77
|
@abstractmethod
def to_tensor(self, dtype, device):
'Convert masks to the format of Tensor.\n\n Args:\n dtype (str): Dtype of converted mask.\n device (torch.device): Device of converted masks.\n\n Returns:\n Tensor: Converted masks in the format of Tensor.\n '
|
Convert masks to the format of Tensor.
Args:
dtype (str): Dtype of converted mask.
device (torch.device): Device of converted masks.
Returns:
Tensor: Converted masks in the format of Tensor.
|
mmdet/core/mask/structures.py
|
to_tensor
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def to_tensor(self, dtype, device):
'Convert masks to the format of Tensor.\n\n Args:\n dtype (str): Dtype of converted mask.\n device (torch.device): Device of converted masks.\n\n Returns:\n Tensor: Converted masks in the format of Tensor.\n '
|
@abstractmethod
def to_tensor(self, dtype, device):
'Convert masks to the format of Tensor.\n\n Args:\n dtype (str): Dtype of converted mask.\n device (torch.device): Device of converted masks.\n\n Returns:\n Tensor: Converted masks in the format of Tensor.\n '<|docstring|>Convert masks to the format of Tensor.
Args:
dtype (str): Dtype of converted mask.
device (torch.device): Device of converted masks.
Returns:
Tensor: Converted masks in the format of Tensor.<|endoftext|>
|
0201336016ef7cb4e3d6fbe6fdeda65edc22f8e074635c8abdd9ccb393c5cfa7
|
@abstractmethod
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n Translated masks.\n '
|
Translate the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
offset (int | float): The offset for translate.
direction (str): The translate direction, either "horizontal"
or "vertical".
fill_val (int | float): Border value. Default 0.
interpolation (str): Same as :func:`mmcv.imtranslate`.
Returns:
Translated masks.
|
mmdet/core/mask/structures.py
|
translate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n Translated masks.\n '
|
@abstractmethod
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n Translated masks.\n '<|docstring|>Translate the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
offset (int | float): The offset for translate.
direction (str): The translate direction, either "horizontal"
or "vertical".
fill_val (int | float): Border value. Default 0.
interpolation (str): Same as :func:`mmcv.imtranslate`.
Returns:
Translated masks.<|endoftext|>
|
9aa4bf4d0c6eb9443072a6bcc75184ea1eddca311ad50b2de43ad35fc754639e
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border. Default 0.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n ndarray: Sheared masks.\n '
|
Shear the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
magnitude (int | float): The magnitude used for shear.
direction (str): The shear direction, either "horizontal"
or "vertical".
border_value (int | tuple[int]): Value used in case of a
constant border. Default 0.
interpolation (str): Same as in :func:`mmcv.imshear`.
Returns:
ndarray: Sheared masks.
|
mmdet/core/mask/structures.py
|
shear
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border. Default 0.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n ndarray: Sheared masks.\n '
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border. Default 0.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n ndarray: Sheared masks.\n '<|docstring|>Shear the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
magnitude (int | float): The magnitude used for shear.
direction (str): The shear direction, either "horizontal"
or "vertical".
border_value (int | tuple[int]): Value used in case of a
constant border. Default 0.
interpolation (str): Same as in :func:`mmcv.imshear`.
Returns:
ndarray: Sheared masks.<|endoftext|>
|
6b95eaa2b928e8f5a78451f6c35bbf17034e6b6c6d34d43c10005e3cd490202b
|
@abstractmethod
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n Rotated masks.\n '
|
Rotate the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
angle (int | float): Rotation angle in degrees. Positive values
mean counter-clockwise rotation.
center (tuple[float], optional): Center point (w, h) of the
rotation in source image. If not specified, the center of
the image will be used.
scale (int | float): Isotropic scale factor.
fill_val (int | float): Border value. Default 0 for masks.
Returns:
Rotated masks.
|
mmdet/core/mask/structures.py
|
rotate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@abstractmethod
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n Rotated masks.\n '
|
@abstractmethod
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the masks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n Rotated masks.\n '<|docstring|>Rotate the masks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
angle (int | float): Rotation angle in degrees. Positive values
mean counter-clockwise rotation.
center (tuple[float], optional): Center point (w, h) of the
rotation in source image. If not specified, the center of
the image will be used.
scale (int | float): Isotropic scale factor.
fill_val (int | float): Border value. Default 0 for masks.
Returns:
Rotated masks.<|endoftext|>
|
86a571a5537ed25e7f4c67bd32fc2a8a0b85916e86df5508e6f0dfeb893feb0a
|
def __getitem__(self, index):
'Index the BitmapMask.\n\n Args:\n index (int | ndarray): Indices in the format of integer or ndarray.\n\n Returns:\n :obj:`BitmapMasks`: Indexed bitmap masks.\n '
masks = self.masks[index].reshape((- 1), self.height, self.width)
return BitmapMasks(masks, self.height, self.width)
|
Index the BitmapMask.
Args:
index (int | ndarray): Indices in the format of integer or ndarray.
Returns:
:obj:`BitmapMasks`: Indexed bitmap masks.
|
mmdet/core/mask/structures.py
|
__getitem__
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def __getitem__(self, index):
'Index the BitmapMask.\n\n Args:\n index (int | ndarray): Indices in the format of integer or ndarray.\n\n Returns:\n :obj:`BitmapMasks`: Indexed bitmap masks.\n '
masks = self.masks[index].reshape((- 1), self.height, self.width)
return BitmapMasks(masks, self.height, self.width)
|
def __getitem__(self, index):
'Index the BitmapMask.\n\n Args:\n index (int | ndarray): Indices in the format of integer or ndarray.\n\n Returns:\n :obj:`BitmapMasks`: Indexed bitmap masks.\n '
masks = self.masks[index].reshape((- 1), self.height, self.width)
return BitmapMasks(masks, self.height, self.width)<|docstring|>Index the BitmapMask.
Args:
index (int | ndarray): Indices in the format of integer or ndarray.
Returns:
:obj:`BitmapMasks`: Indexed bitmap masks.<|endoftext|>
|
e2bb24a92fdedffe0772510c49048819a9c27794aab8b5139fbfc7494fe97b4c
|
def __len__(self):
'Number of masks.'
return len(self.masks)
|
Number of masks.
|
mmdet/core/mask/structures.py
|
__len__
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def __len__(self):
return len(self.masks)
|
def __len__(self):
return len(self.masks)<|docstring|>Number of masks.<|endoftext|>
|
b7e17a9a2110c3452bdc8af39ec9cf372dfa14a2538d2ac1b84b68a503eadf09
|
def rescale(self, scale, interpolation='nearest'):
'See :func:`BaseInstanceMasks.rescale`.'
if (len(self.masks) == 0):
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)
else:
rescaled_masks = np.stack([mmcv.imrescale(mask, scale, interpolation=interpolation) for mask in self.masks])
(height, width) = rescaled_masks.shape[1:]
return BitmapMasks(rescaled_masks, height, width)
|
See :func:`BaseInstanceMasks.rescale`.
|
mmdet/core/mask/structures.py
|
rescale
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def rescale(self, scale, interpolation='nearest'):
if (len(self.masks) == 0):
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)
else:
rescaled_masks = np.stack([mmcv.imrescale(mask, scale, interpolation=interpolation) for mask in self.masks])
(height, width) = rescaled_masks.shape[1:]
return BitmapMasks(rescaled_masks, height, width)
|
def rescale(self, scale, interpolation='nearest'):
if (len(self.masks) == 0):
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8)
else:
rescaled_masks = np.stack([mmcv.imrescale(mask, scale, interpolation=interpolation) for mask in self.masks])
(height, width) = rescaled_masks.shape[1:]
return BitmapMasks(rescaled_masks, height, width)<|docstring|>See :func:`BaseInstanceMasks.rescale`.<|endoftext|>
|
28316eed3a7ae1bc510fdd18c6e1d8a5d5f33f7cc2959d2bb9610144b6314547
|
def resize(self, out_shape, interpolation='nearest'):
'See :func:`BaseInstanceMasks.resize`.'
if (len(self.masks) == 0):
resized_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
resized_masks = np.stack([mmcv.imresize(mask, out_shape[::(- 1)], interpolation=interpolation) for mask in self.masks])
return BitmapMasks(resized_masks, *out_shape)
|
See :func:`BaseInstanceMasks.resize`.
|
mmdet/core/mask/structures.py
|
resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def resize(self, out_shape, interpolation='nearest'):
if (len(self.masks) == 0):
resized_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
resized_masks = np.stack([mmcv.imresize(mask, out_shape[::(- 1)], interpolation=interpolation) for mask in self.masks])
return BitmapMasks(resized_masks, *out_shape)
|
def resize(self, out_shape, interpolation='nearest'):
if (len(self.masks) == 0):
resized_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
resized_masks = np.stack([mmcv.imresize(mask, out_shape[::(- 1)], interpolation=interpolation) for mask in self.masks])
return BitmapMasks(resized_masks, *out_shape)<|docstring|>See :func:`BaseInstanceMasks.resize`.<|endoftext|>
|
56236017ab975a92a69d05d7ff960437199ff3fcf9523faaaf0a0dd0b9cd43b5
|
def flip(self, flip_direction='horizontal'):
'See :func:`BaseInstanceMasks.flip`.'
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = self.masks
else:
flipped_masks = np.stack([mmcv.imflip(mask, direction=flip_direction) for mask in self.masks])
return BitmapMasks(flipped_masks, self.height, self.width)
|
See :func:`BaseInstanceMasks.flip`.
|
mmdet/core/mask/structures.py
|
flip
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def flip(self, flip_direction='horizontal'):
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = self.masks
else:
flipped_masks = np.stack([mmcv.imflip(mask, direction=flip_direction) for mask in self.masks])
return BitmapMasks(flipped_masks, self.height, self.width)
|
def flip(self, flip_direction='horizontal'):
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = self.masks
else:
flipped_masks = np.stack([mmcv.imflip(mask, direction=flip_direction) for mask in self.masks])
return BitmapMasks(flipped_masks, self.height, self.width)<|docstring|>See :func:`BaseInstanceMasks.flip`.<|endoftext|>
|
a44e2720f7ea7d2836cc0448e17c3b62bf13e8b2bbe3a025bc3b4fd8970ef4ec
|
def pad(self, out_shape, pad_val=0):
'See :func:`BaseInstanceMasks.pad`.'
if (len(self.masks) == 0):
padded_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
padded_masks = np.stack([mmcv.impad(mask, shape=out_shape, pad_val=pad_val) for mask in self.masks])
return BitmapMasks(padded_masks, *out_shape)
|
See :func:`BaseInstanceMasks.pad`.
|
mmdet/core/mask/structures.py
|
pad
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def pad(self, out_shape, pad_val=0):
if (len(self.masks) == 0):
padded_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
padded_masks = np.stack([mmcv.impad(mask, shape=out_shape, pad_val=pad_val) for mask in self.masks])
return BitmapMasks(padded_masks, *out_shape)
|
def pad(self, out_shape, pad_val=0):
if (len(self.masks) == 0):
padded_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
padded_masks = np.stack([mmcv.impad(mask, shape=out_shape, pad_val=pad_val) for mask in self.masks])
return BitmapMasks(padded_masks, *out_shape)<|docstring|>See :func:`BaseInstanceMasks.pad`.<|endoftext|>
|
b6901846d621385bdc73e81f0c92902c251a90ff3bfcfa73df374a10d76be6c6
|
def crop(self, bbox):
'See :func:`BaseInstanceMasks.crop`.'
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[(:, y1:(y1 + h), x1:(x1 + w))]
return BitmapMasks(cropped_masks, h, w)
|
See :func:`BaseInstanceMasks.crop`.
|
mmdet/core/mask/structures.py
|
crop
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def crop(self, bbox):
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[(:, y1:(y1 + h), x1:(x1 + w))]
return BitmapMasks(cropped_masks, h, w)
|
def crop(self, bbox):
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[(:, y1:(y1 + h), x1:(x1 + w))]
return BitmapMasks(cropped_masks, h, w)<|docstring|>See :func:`BaseInstanceMasks.crop`.<|endoftext|>
|
4bc88355e62f79b80bc248f096888edb347b56dc8ccdc6c75a5eb29a0570764a
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
'See :func:`BaseInstanceMasks.crop_and_resize`.'
if (len(self.masks) == 0):
empty_masks = np.empty((0, *out_shape), dtype=np.uint8)
return BitmapMasks(empty_masks, *out_shape)
if isinstance(bboxes, np.ndarray):
bboxes = torch.from_numpy(bboxes).to(device=device)
if isinstance(inds, np.ndarray):
inds = torch.from_numpy(inds).to(device=device)
num_bbox = bboxes.shape[0]
fake_inds = torch.arange(num_bbox, device=device).to(dtype=bboxes.dtype)[(:, None)]
rois = torch.cat([fake_inds, bboxes], dim=1)
rois = rois.to(device=device)
if (num_bbox > 0):
gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(0, inds).to(dtype=rois.dtype)
targets = roi_align(gt_masks_th[(:, None, :, :)], rois, out_shape, 1.0, 0, 'avg', True).squeeze(1)
if binarize:
resized_masks = (targets >= 0.5).cpu().numpy()
else:
resized_masks = targets.cpu().numpy()
else:
resized_masks = []
return BitmapMasks(resized_masks, *out_shape)
|
See :func:`BaseInstanceMasks.crop_and_resize`.
|
mmdet/core/mask/structures.py
|
crop_and_resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
if (len(self.masks) == 0):
empty_masks = np.empty((0, *out_shape), dtype=np.uint8)
return BitmapMasks(empty_masks, *out_shape)
if isinstance(bboxes, np.ndarray):
bboxes = torch.from_numpy(bboxes).to(device=device)
if isinstance(inds, np.ndarray):
inds = torch.from_numpy(inds).to(device=device)
num_bbox = bboxes.shape[0]
fake_inds = torch.arange(num_bbox, device=device).to(dtype=bboxes.dtype)[(:, None)]
rois = torch.cat([fake_inds, bboxes], dim=1)
rois = rois.to(device=device)
if (num_bbox > 0):
gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(0, inds).to(dtype=rois.dtype)
targets = roi_align(gt_masks_th[(:, None, :, :)], rois, out_shape, 1.0, 0, 'avg', True).squeeze(1)
if binarize:
resized_masks = (targets >= 0.5).cpu().numpy()
else:
resized_masks = targets.cpu().numpy()
else:
resized_masks = []
return BitmapMasks(resized_masks, *out_shape)
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
if (len(self.masks) == 0):
empty_masks = np.empty((0, *out_shape), dtype=np.uint8)
return BitmapMasks(empty_masks, *out_shape)
if isinstance(bboxes, np.ndarray):
bboxes = torch.from_numpy(bboxes).to(device=device)
if isinstance(inds, np.ndarray):
inds = torch.from_numpy(inds).to(device=device)
num_bbox = bboxes.shape[0]
fake_inds = torch.arange(num_bbox, device=device).to(dtype=bboxes.dtype)[(:, None)]
rois = torch.cat([fake_inds, bboxes], dim=1)
rois = rois.to(device=device)
if (num_bbox > 0):
gt_masks_th = torch.from_numpy(self.masks).to(device).index_select(0, inds).to(dtype=rois.dtype)
targets = roi_align(gt_masks_th[(:, None, :, :)], rois, out_shape, 1.0, 0, 'avg', True).squeeze(1)
if binarize:
resized_masks = (targets >= 0.5).cpu().numpy()
else:
resized_masks = targets.cpu().numpy()
else:
resized_masks = []
return BitmapMasks(resized_masks, *out_shape)<|docstring|>See :func:`BaseInstanceMasks.crop_and_resize`.<|endoftext|>
|
d6a174e448411f65a74ffdfe401da5568093a8607498a88cb79e87c14f25bcea
|
def expand(self, expanded_h, expanded_w, top, left):
'See :func:`BaseInstanceMasks.expand`.'
if (len(self.masks) == 0):
expanded_mask = np.empty((0, expanded_h, expanded_w), dtype=np.uint8)
else:
expanded_mask = np.zeros((len(self), expanded_h, expanded_w), dtype=np.uint8)
expanded_mask[(:, top:(top + self.height), left:(left + self.width))] = self.masks
return BitmapMasks(expanded_mask, expanded_h, expanded_w)
|
See :func:`BaseInstanceMasks.expand`.
|
mmdet/core/mask/structures.py
|
expand
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def expand(self, expanded_h, expanded_w, top, left):
if (len(self.masks) == 0):
expanded_mask = np.empty((0, expanded_h, expanded_w), dtype=np.uint8)
else:
expanded_mask = np.zeros((len(self), expanded_h, expanded_w), dtype=np.uint8)
expanded_mask[(:, top:(top + self.height), left:(left + self.width))] = self.masks
return BitmapMasks(expanded_mask, expanded_h, expanded_w)
|
def expand(self, expanded_h, expanded_w, top, left):
if (len(self.masks) == 0):
expanded_mask = np.empty((0, expanded_h, expanded_w), dtype=np.uint8)
else:
expanded_mask = np.zeros((len(self), expanded_h, expanded_w), dtype=np.uint8)
expanded_mask[(:, top:(top + self.height), left:(left + self.width))] = self.masks
return BitmapMasks(expanded_mask, expanded_h, expanded_w)<|docstring|>See :func:`BaseInstanceMasks.expand`.<|endoftext|>
|
ae455b6a67e64caeff11b80047d21e46a5d8e711b49ec5d6adaa0588f8dfe4d0
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n BitmapMasks: Translated BitmapMasks.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random(dtype=np.uint8)\n >>> out_shape = (32, 32)\n >>> offset = 4\n >>> direction = \'horizontal\'\n >>> fill_val = 0\n >>> interpolation = \'bilinear\'\n >>> # Note, There seem to be issues when:\n >>> # * out_shape is different than self\'s shape\n >>> # * the mask dtype is not supported by cv2.AffineWarp\n >>> new = self.translate(out_shape, offset, direction, fill_val,\n >>> interpolation)\n >>> assert len(new) == len(self)\n >>> assert new.height, new.width == out_shape\n '
if (len(self.masks) == 0):
translated_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
translated_masks = mmcv.imtranslate(self.masks.transpose((1, 2, 0)), offset, direction, border_value=fill_val, interpolation=interpolation)
if (translated_masks.ndim == 2):
translated_masks = translated_masks[(:, :, None)]
translated_masks = translated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(translated_masks, *out_shape)
|
Translate the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
offset (int | float): The offset for translate.
direction (str): The translate direction, either "horizontal"
or "vertical".
fill_val (int | float): Border value. Default 0 for masks.
interpolation (str): Same as :func:`mmcv.imtranslate`.
Returns:
BitmapMasks: Translated BitmapMasks.
Example:
>>> from mmdet.core.mask.structures import BitmapMasks
>>> self = BitmapMasks.random(dtype=np.uint8)
>>> out_shape = (32, 32)
>>> offset = 4
>>> direction = 'horizontal'
>>> fill_val = 0
>>> interpolation = 'bilinear'
>>> # Note, There seem to be issues when:
>>> # * out_shape is different than self's shape
>>> # * the mask dtype is not supported by cv2.AffineWarp
>>> new = self.translate(out_shape, offset, direction, fill_val,
>>> interpolation)
>>> assert len(new) == len(self)
>>> assert new.height, new.width == out_shape
|
mmdet/core/mask/structures.py
|
translate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n BitmapMasks: Translated BitmapMasks.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random(dtype=np.uint8)\n >>> out_shape = (32, 32)\n >>> offset = 4\n >>> direction = \'horizontal\'\n >>> fill_val = 0\n >>> interpolation = \'bilinear\'\n >>> # Note, There seem to be issues when:\n >>> # * out_shape is different than self\'s shape\n >>> # * the mask dtype is not supported by cv2.AffineWarp\n >>> new = self.translate(out_shape, offset, direction, fill_val,\n >>> interpolation)\n >>> assert len(new) == len(self)\n >>> assert new.height, new.width == out_shape\n '
if (len(self.masks) == 0):
translated_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
translated_masks = mmcv.imtranslate(self.masks.transpose((1, 2, 0)), offset, direction, border_value=fill_val, interpolation=interpolation)
if (translated_masks.ndim == 2):
translated_masks = translated_masks[(:, :, None)]
translated_masks = translated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(translated_masks, *out_shape)
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=0, interpolation='bilinear'):
'Translate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n offset (int | float): The offset for translate.\n direction (str): The translate direction, either "horizontal"\n or "vertical".\n fill_val (int | float): Border value. Default 0 for masks.\n interpolation (str): Same as :func:`mmcv.imtranslate`.\n\n Returns:\n BitmapMasks: Translated BitmapMasks.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random(dtype=np.uint8)\n >>> out_shape = (32, 32)\n >>> offset = 4\n >>> direction = \'horizontal\'\n >>> fill_val = 0\n >>> interpolation = \'bilinear\'\n >>> # Note, There seem to be issues when:\n >>> # * out_shape is different than self\'s shape\n >>> # * the mask dtype is not supported by cv2.AffineWarp\n >>> new = self.translate(out_shape, offset, direction, fill_val,\n >>> interpolation)\n >>> assert len(new) == len(self)\n >>> assert new.height, new.width == out_shape\n '
if (len(self.masks) == 0):
translated_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
translated_masks = mmcv.imtranslate(self.masks.transpose((1, 2, 0)), offset, direction, border_value=fill_val, interpolation=interpolation)
if (translated_masks.ndim == 2):
translated_masks = translated_masks[(:, :, None)]
translated_masks = translated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(translated_masks, *out_shape)<|docstring|>Translate the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
offset (int | float): The offset for translate.
direction (str): The translate direction, either "horizontal"
or "vertical".
fill_val (int | float): Border value. Default 0 for masks.
interpolation (str): Same as :func:`mmcv.imtranslate`.
Returns:
BitmapMasks: Translated BitmapMasks.
Example:
>>> from mmdet.core.mask.structures import BitmapMasks
>>> self = BitmapMasks.random(dtype=np.uint8)
>>> out_shape = (32, 32)
>>> offset = 4
>>> direction = 'horizontal'
>>> fill_val = 0
>>> interpolation = 'bilinear'
>>> # Note, There seem to be issues when:
>>> # * out_shape is different than self's shape
>>> # * the mask dtype is not supported by cv2.AffineWarp
>>> new = self.translate(out_shape, offset, direction, fill_val,
>>> interpolation)
>>> assert len(new) == len(self)
>>> assert new.height, new.width == out_shape<|endoftext|>
|
be6b3488b7b53dc2ab3cb38a819ff27f726c122395d7ee5ad8277e1d507d26e8
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n BitmapMasks: The sheared masks.\n '
if (len(self.masks) == 0):
sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
sheared_masks = mmcv.imshear(self.masks.transpose((1, 2, 0)), magnitude, direction, border_value=border_value, interpolation=interpolation)
if (sheared_masks.ndim == 2):
sheared_masks = sheared_masks[(:, :, None)]
sheared_masks = sheared_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(sheared_masks, *out_shape)
|
Shear the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
magnitude (int | float): The magnitude used for shear.
direction (str): The shear direction, either "horizontal"
or "vertical".
border_value (int | tuple[int]): Value used in case of a
constant border.
interpolation (str): Same as in :func:`mmcv.imshear`.
Returns:
BitmapMasks: The sheared masks.
|
mmdet/core/mask/structures.py
|
shear
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n BitmapMasks: The sheared masks.\n '
if (len(self.masks) == 0):
sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
sheared_masks = mmcv.imshear(self.masks.transpose((1, 2, 0)), magnitude, direction, border_value=border_value, interpolation=interpolation)
if (sheared_masks.ndim == 2):
sheared_masks = sheared_masks[(:, :, None)]
sheared_masks = sheared_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(sheared_masks, *out_shape)
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'Shear the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n magnitude (int | float): The magnitude used for shear.\n direction (str): The shear direction, either "horizontal"\n or "vertical".\n border_value (int | tuple[int]): Value used in case of a\n constant border.\n interpolation (str): Same as in :func:`mmcv.imshear`.\n\n Returns:\n BitmapMasks: The sheared masks.\n '
if (len(self.masks) == 0):
sheared_masks = np.empty((0, *out_shape), dtype=np.uint8)
else:
sheared_masks = mmcv.imshear(self.masks.transpose((1, 2, 0)), magnitude, direction, border_value=border_value, interpolation=interpolation)
if (sheared_masks.ndim == 2):
sheared_masks = sheared_masks[(:, :, None)]
sheared_masks = sheared_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(sheared_masks, *out_shape)<|docstring|>Shear the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
magnitude (int | float): The magnitude used for shear.
direction (str): The shear direction, either "horizontal"
or "vertical".
border_value (int | tuple[int]): Value used in case of a
constant border.
interpolation (str): Same as in :func:`mmcv.imshear`.
Returns:
BitmapMasks: The sheared masks.<|endoftext|>
|
742b6511105d59563e62438d5f46040f7932098b599828190153034863fef636
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n BitmapMasks: Rotated BitmapMasks.\n '
if (len(self.masks) == 0):
rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)
else:
rotated_masks = mmcv.imrotate(self.masks.transpose((1, 2, 0)), angle, center=center, scale=scale, border_value=fill_val)
if (rotated_masks.ndim == 2):
rotated_masks = rotated_masks[(:, :, None)]
rotated_masks = rotated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(rotated_masks, *out_shape)
|
Rotate the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
angle (int | float): Rotation angle in degrees. Positive values
mean counter-clockwise rotation.
center (tuple[float], optional): Center point (w, h) of the
rotation in source image. If not specified, the center of
the image will be used.
scale (int | float): Isotropic scale factor.
fill_val (int | float): Border value. Default 0 for masks.
Returns:
BitmapMasks: Rotated BitmapMasks.
|
mmdet/core/mask/structures.py
|
rotate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n BitmapMasks: Rotated BitmapMasks.\n '
if (len(self.masks) == 0):
rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)
else:
rotated_masks = mmcv.imrotate(self.masks.transpose((1, 2, 0)), angle, center=center, scale=scale, border_value=fill_val)
if (rotated_masks.ndim == 2):
rotated_masks = rotated_masks[(:, :, None)]
rotated_masks = rotated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(rotated_masks, *out_shape)
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'Rotate the BitmapMasks.\n\n Args:\n out_shape (tuple[int]): Shape for output mask, format (h, w).\n angle (int | float): Rotation angle in degrees. Positive values\n mean counter-clockwise rotation.\n center (tuple[float], optional): Center point (w, h) of the\n rotation in source image. If not specified, the center of\n the image will be used.\n scale (int | float): Isotropic scale factor.\n fill_val (int | float): Border value. Default 0 for masks.\n\n Returns:\n BitmapMasks: Rotated BitmapMasks.\n '
if (len(self.masks) == 0):
rotated_masks = np.empty((0, *out_shape), dtype=self.masks.dtype)
else:
rotated_masks = mmcv.imrotate(self.masks.transpose((1, 2, 0)), angle, center=center, scale=scale, border_value=fill_val)
if (rotated_masks.ndim == 2):
rotated_masks = rotated_masks[(:, :, None)]
rotated_masks = rotated_masks.transpose((2, 0, 1)).astype(self.masks.dtype)
return BitmapMasks(rotated_masks, *out_shape)<|docstring|>Rotate the BitmapMasks.
Args:
out_shape (tuple[int]): Shape for output mask, format (h, w).
angle (int | float): Rotation angle in degrees. Positive values
mean counter-clockwise rotation.
center (tuple[float], optional): Center point (w, h) of the
rotation in source image. If not specified, the center of
the image will be used.
scale (int | float): Isotropic scale factor.
fill_val (int | float): Border value. Default 0 for masks.
Returns:
BitmapMasks: Rotated BitmapMasks.<|endoftext|>
|
a60fe5156806cb36c05a2ff98d877e5fd5c7bf38a65d98f8ec57c5bb9e6ec6d2
|
@property
def areas(self):
'See :py:attr:`BaseInstanceMasks.areas`.'
return self.masks.sum((1, 2))
|
See :py:attr:`BaseInstanceMasks.areas`.
|
mmdet/core/mask/structures.py
|
areas
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@property
def areas(self):
return self.masks.sum((1, 2))
|
@property
def areas(self):
return self.masks.sum((1, 2))<|docstring|>See :py:attr:`BaseInstanceMasks.areas`.<|endoftext|>
|
f000263e6431e0eb439ed7c1d51ea4e01ed30eb5e4f2fda35d83a8052b611013
|
def to_ndarray(self):
'See :func:`BaseInstanceMasks.to_ndarray`.'
return self.masks
|
See :func:`BaseInstanceMasks.to_ndarray`.
|
mmdet/core/mask/structures.py
|
to_ndarray
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def to_ndarray(self):
return self.masks
|
def to_ndarray(self):
return self.masks<|docstring|>See :func:`BaseInstanceMasks.to_ndarray`.<|endoftext|>
|
50e84606abc9c3e14c34507e738f04bcbd08c3a2ddd3fffdf4b305fc90c5b918
|
def to_tensor(self, dtype, device):
'See :func:`BaseInstanceMasks.to_tensor`.'
return torch.tensor(self.masks, dtype=dtype, device=device)
|
See :func:`BaseInstanceMasks.to_tensor`.
|
mmdet/core/mask/structures.py
|
to_tensor
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def to_tensor(self, dtype, device):
return torch.tensor(self.masks, dtype=dtype, device=device)
|
def to_tensor(self, dtype, device):
return torch.tensor(self.masks, dtype=dtype, device=device)<|docstring|>See :func:`BaseInstanceMasks.to_tensor`.<|endoftext|>
|
3c248c5c05f4600eb5ff40a02396607e3cfc0ee0a93a0c38b7b6725c8745e733
|
@classmethod
def random(cls, num_masks=3, height=32, width=32, dtype=np.uint8, rng=None):
"Generate random bitmap masks for demo / testing purposes.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random()\n >>> print('self = {}'.format(self))\n self = BitmapMasks(num_masks=3, height=32, width=32)\n "
from mmdet.utils.util_random import ensure_rng
rng = ensure_rng(rng)
masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)
self = cls(masks, height=height, width=width)
return self
|
Generate random bitmap masks for demo / testing purposes.
Example:
>>> from mmdet.core.mask.structures import BitmapMasks
>>> self = BitmapMasks.random()
>>> print('self = {}'.format(self))
self = BitmapMasks(num_masks=3, height=32, width=32)
|
mmdet/core/mask/structures.py
|
random
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
@classmethod
def random(cls, num_masks=3, height=32, width=32, dtype=np.uint8, rng=None):
"Generate random bitmap masks for demo / testing purposes.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random()\n >>> print('self = {}'.format(self))\n self = BitmapMasks(num_masks=3, height=32, width=32)\n "
from mmdet.utils.util_random import ensure_rng
rng = ensure_rng(rng)
masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)
self = cls(masks, height=height, width=width)
return self
|
@classmethod
def random(cls, num_masks=3, height=32, width=32, dtype=np.uint8, rng=None):
"Generate random bitmap masks for demo / testing purposes.\n\n Example:\n >>> from mmdet.core.mask.structures import BitmapMasks\n >>> self = BitmapMasks.random()\n >>> print('self = {}'.format(self))\n self = BitmapMasks(num_masks=3, height=32, width=32)\n "
from mmdet.utils.util_random import ensure_rng
rng = ensure_rng(rng)
masks = (rng.rand(num_masks, height, width) > 0.1).astype(dtype)
self = cls(masks, height=height, width=width)
return self<|docstring|>Generate random bitmap masks for demo / testing purposes.
Example:
>>> from mmdet.core.mask.structures import BitmapMasks
>>> self = BitmapMasks.random()
>>> print('self = {}'.format(self))
self = BitmapMasks(num_masks=3, height=32, width=32)<|endoftext|>
|
d19f5a6ad49f3be7233a2e10c5e912b49ee070ccc08fe387acb515d3742f6059
|
def __getitem__(self, index):
'Index the polygon masks.\n\n Args:\n index (ndarray | List): The indices.\n\n Returns:\n :obj:`PolygonMasks`: The indexed polygon masks.\n '
if isinstance(index, np.ndarray):
index = index.tolist()
if isinstance(index, list):
masks = [self.masks[i] for i in index]
else:
try:
masks = self.masks[index]
except Exception:
raise ValueError(f'Unsupported input of type {type(index)} for indexing!')
if (len(masks) and isinstance(masks[0], np.ndarray)):
masks = [masks]
return PolygonMasks(masks, self.height, self.width)
|
Index the polygon masks.
Args:
index (ndarray | List): The indices.
Returns:
:obj:`PolygonMasks`: The indexed polygon masks.
|
mmdet/core/mask/structures.py
|
__getitem__
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def __getitem__(self, index):
'Index the polygon masks.\n\n Args:\n index (ndarray | List): The indices.\n\n Returns:\n :obj:`PolygonMasks`: The indexed polygon masks.\n '
if isinstance(index, np.ndarray):
index = index.tolist()
if isinstance(index, list):
masks = [self.masks[i] for i in index]
else:
try:
masks = self.masks[index]
except Exception:
raise ValueError(f'Unsupported input of type {type(index)} for indexing!')
if (len(masks) and isinstance(masks[0], np.ndarray)):
masks = [masks]
return PolygonMasks(masks, self.height, self.width)
|
def __getitem__(self, index):
'Index the polygon masks.\n\n Args:\n index (ndarray | List): The indices.\n\n Returns:\n :obj:`PolygonMasks`: The indexed polygon masks.\n '
if isinstance(index, np.ndarray):
index = index.tolist()
if isinstance(index, list):
masks = [self.masks[i] for i in index]
else:
try:
masks = self.masks[index]
except Exception:
raise ValueError(f'Unsupported input of type {type(index)} for indexing!')
if (len(masks) and isinstance(masks[0], np.ndarray)):
masks = [masks]
return PolygonMasks(masks, self.height, self.width)<|docstring|>Index the polygon masks.
Args:
index (ndarray | List): The indices.
Returns:
:obj:`PolygonMasks`: The indexed polygon masks.<|endoftext|>
|
e2bb24a92fdedffe0772510c49048819a9c27794aab8b5139fbfc7494fe97b4c
|
def __len__(self):
'Number of masks.'
return len(self.masks)
|
Number of masks.
|
mmdet/core/mask/structures.py
|
__len__
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def __len__(self):
return len(self.masks)
|
def __len__(self):
return len(self.masks)<|docstring|>Number of masks.<|endoftext|>
|
6132c3974738ac0e89e78364dfc01eeeaedfbd001e6a3622ffc2823ce13992cc
|
def rescale(self, scale, interpolation=None):
'see :func:`BaseInstanceMasks.rescale`'
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
if (len(self.masks) == 0):
rescaled_masks = PolygonMasks([], new_h, new_w)
else:
rescaled_masks = self.resize((new_h, new_w))
return rescaled_masks
|
see :func:`BaseInstanceMasks.rescale`
|
mmdet/core/mask/structures.py
|
rescale
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def rescale(self, scale, interpolation=None):
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
if (len(self.masks) == 0):
rescaled_masks = PolygonMasks([], new_h, new_w)
else:
rescaled_masks = self.resize((new_h, new_w))
return rescaled_masks
|
def rescale(self, scale, interpolation=None):
(new_w, new_h) = mmcv.rescale_size((self.width, self.height), scale)
if (len(self.masks) == 0):
rescaled_masks = PolygonMasks([], new_h, new_w)
else:
rescaled_masks = self.resize((new_h, new_w))
return rescaled_masks<|docstring|>see :func:`BaseInstanceMasks.rescale`<|endoftext|>
|
699aef9cfa20dff17609487d3b0b856077eab06c38f0e97446cd57100054c965
|
def resize(self, out_shape, interpolation=None):
'see :func:`BaseInstanceMasks.resize`'
if (len(self.masks) == 0):
resized_masks = PolygonMasks([], *out_shape)
else:
h_scale = (out_shape[0] / self.height)
w_scale = (out_shape[1] / self.width)
resized_masks = []
for poly_per_obj in self.masks:
resized_poly = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_poly.append(p)
resized_masks.append(resized_poly)
resized_masks = PolygonMasks(resized_masks, *out_shape)
return resized_masks
|
see :func:`BaseInstanceMasks.resize`
|
mmdet/core/mask/structures.py
|
resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def resize(self, out_shape, interpolation=None):
if (len(self.masks) == 0):
resized_masks = PolygonMasks([], *out_shape)
else:
h_scale = (out_shape[0] / self.height)
w_scale = (out_shape[1] / self.width)
resized_masks = []
for poly_per_obj in self.masks:
resized_poly = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_poly.append(p)
resized_masks.append(resized_poly)
resized_masks = PolygonMasks(resized_masks, *out_shape)
return resized_masks
|
def resize(self, out_shape, interpolation=None):
if (len(self.masks) == 0):
resized_masks = PolygonMasks([], *out_shape)
else:
h_scale = (out_shape[0] / self.height)
w_scale = (out_shape[1] / self.width)
resized_masks = []
for poly_per_obj in self.masks:
resized_poly = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_poly.append(p)
resized_masks.append(resized_poly)
resized_masks = PolygonMasks(resized_masks, *out_shape)
return resized_masks<|docstring|>see :func:`BaseInstanceMasks.resize`<|endoftext|>
|
db2898f413a356c8094a1420f4c819d47050c78a457629da4351e29a8f1ba4af
|
def flip(self, flip_direction='horizontal'):
'see :func:`BaseInstanceMasks.flip`'
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = PolygonMasks([], self.height, self.width)
else:
flipped_masks = []
for poly_per_obj in self.masks:
flipped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (flip_direction == 'horizontal'):
p[0::2] = (self.width - p[0::2])
elif (flip_direction == 'vertical'):
p[1::2] = (self.height - p[1::2])
else:
p[0::2] = (self.width - p[0::2])
p[1::2] = (self.height - p[1::2])
flipped_poly_per_obj.append(p)
flipped_masks.append(flipped_poly_per_obj)
flipped_masks = PolygonMasks(flipped_masks, self.height, self.width)
return flipped_masks
|
see :func:`BaseInstanceMasks.flip`
|
mmdet/core/mask/structures.py
|
flip
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def flip(self, flip_direction='horizontal'):
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = PolygonMasks([], self.height, self.width)
else:
flipped_masks = []
for poly_per_obj in self.masks:
flipped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (flip_direction == 'horizontal'):
p[0::2] = (self.width - p[0::2])
elif (flip_direction == 'vertical'):
p[1::2] = (self.height - p[1::2])
else:
p[0::2] = (self.width - p[0::2])
p[1::2] = (self.height - p[1::2])
flipped_poly_per_obj.append(p)
flipped_masks.append(flipped_poly_per_obj)
flipped_masks = PolygonMasks(flipped_masks, self.height, self.width)
return flipped_masks
|
def flip(self, flip_direction='horizontal'):
assert (flip_direction in ('horizontal', 'vertical', 'diagonal'))
if (len(self.masks) == 0):
flipped_masks = PolygonMasks([], self.height, self.width)
else:
flipped_masks = []
for poly_per_obj in self.masks:
flipped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (flip_direction == 'horizontal'):
p[0::2] = (self.width - p[0::2])
elif (flip_direction == 'vertical'):
p[1::2] = (self.height - p[1::2])
else:
p[0::2] = (self.width - p[0::2])
p[1::2] = (self.height - p[1::2])
flipped_poly_per_obj.append(p)
flipped_masks.append(flipped_poly_per_obj)
flipped_masks = PolygonMasks(flipped_masks, self.height, self.width)
return flipped_masks<|docstring|>see :func:`BaseInstanceMasks.flip`<|endoftext|>
|
93411e7ef246ec6bed3a977f6af591eb4dc887b2a0605b17441622b6eca6baeb
|
def crop(self, bbox):
'see :func:`BaseInstanceMasks.crop`'
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = PolygonMasks([], h, w)
else:
cropped_masks = []
for poly_per_obj in self.masks:
cropped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
cropped_poly_per_obj.append(p)
cropped_masks.append(cropped_poly_per_obj)
cropped_masks = PolygonMasks(cropped_masks, h, w)
return cropped_masks
|
see :func:`BaseInstanceMasks.crop`
|
mmdet/core/mask/structures.py
|
crop
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def crop(self, bbox):
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = PolygonMasks([], h, w)
else:
cropped_masks = []
for poly_per_obj in self.masks:
cropped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
cropped_poly_per_obj.append(p)
cropped_masks.append(cropped_poly_per_obj)
cropped_masks = PolygonMasks(cropped_masks, h, w)
return cropped_masks
|
def crop(self, bbox):
assert isinstance(bbox, np.ndarray)
assert (bbox.ndim == 1)
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
if (len(self.masks) == 0):
cropped_masks = PolygonMasks([], h, w)
else:
cropped_masks = []
for poly_per_obj in self.masks:
cropped_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
cropped_poly_per_obj.append(p)
cropped_masks.append(cropped_poly_per_obj)
cropped_masks = PolygonMasks(cropped_masks, h, w)
return cropped_masks<|docstring|>see :func:`BaseInstanceMasks.crop`<|endoftext|>
|
deba89578e51e2e2749bb6e503f0779677d3a4fc2a0fbc0268afc9b9c18da912
|
def pad(self, out_shape, pad_val=0):
'padding has no effect on polygons`'
return PolygonMasks(self.masks, *out_shape)
|
padding has no effect on polygons`
|
mmdet/core/mask/structures.py
|
pad
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def pad(self, out_shape, pad_val=0):
return PolygonMasks(self.masks, *out_shape)
|
def pad(self, out_shape, pad_val=0):
return PolygonMasks(self.masks, *out_shape)<|docstring|>padding has no effect on polygons`<|endoftext|>
|
4eae10bf95ad4fd77c87c748d5d35e21bdbe9c2cb3a473d15b0f86267d33d55e
|
def expand(self, *args, **kwargs):
'TODO: Add expand for polygon'
raise NotImplementedError
|
TODO: Add expand for polygon
|
mmdet/core/mask/structures.py
|
expand
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def expand(self, *args, **kwargs):
raise NotImplementedError
|
def expand(self, *args, **kwargs):
raise NotImplementedError<|docstring|>TODO: Add expand for polygon<|endoftext|>
|
3935d55f7070f7ebc455fe823a6e7593af898ab19db912c2bb57fe487f051118
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
'see :func:`BaseInstanceMasks.crop_and_resize`'
(out_h, out_w) = out_shape
if (len(self.masks) == 0):
return PolygonMasks([], out_h, out_w)
if (not binarize):
raise ValueError('Polygons are always binary, setting binarize=False is unsupported')
resized_masks = []
for i in range(len(bboxes)):
mask = self.masks[inds[i]]
bbox = bboxes[(i, :)]
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
h_scale = (out_h / max(h, 0.1))
w_scale = (out_w / max(w, 0.1))
resized_mask = []
for p in mask:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_mask.append(p)
resized_masks.append(resized_mask)
return PolygonMasks(resized_masks, *out_shape)
|
see :func:`BaseInstanceMasks.crop_and_resize`
|
mmdet/core/mask/structures.py
|
crop_and_resize
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
(out_h, out_w) = out_shape
if (len(self.masks) == 0):
return PolygonMasks([], out_h, out_w)
if (not binarize):
raise ValueError('Polygons are always binary, setting binarize=False is unsupported')
resized_masks = []
for i in range(len(bboxes)):
mask = self.masks[inds[i]]
bbox = bboxes[(i, :)]
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
h_scale = (out_h / max(h, 0.1))
w_scale = (out_w / max(w, 0.1))
resized_mask = []
for p in mask:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_mask.append(p)
resized_masks.append(resized_mask)
return PolygonMasks(resized_masks, *out_shape)
|
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear', binarize=True):
(out_h, out_w) = out_shape
if (len(self.masks) == 0):
return PolygonMasks([], out_h, out_w)
if (not binarize):
raise ValueError('Polygons are always binary, setting binarize=False is unsupported')
resized_masks = []
for i in range(len(bboxes)):
mask = self.masks[inds[i]]
bbox = bboxes[(i, :)]
(x1, y1, x2, y2) = bbox
w = np.maximum((x2 - x1), 1)
h = np.maximum((y2 - y1), 1)
h_scale = (out_h / max(h, 0.1))
w_scale = (out_w / max(w, 0.1))
resized_mask = []
for p in mask:
p = p.copy()
p[0::2] = (p[0::2] - bbox[0])
p[1::2] = (p[1::2] - bbox[1])
p[0::2] = (p[0::2] * w_scale)
p[1::2] = (p[1::2] * h_scale)
resized_mask.append(p)
resized_masks.append(resized_mask)
return PolygonMasks(resized_masks, *out_shape)<|docstring|>see :func:`BaseInstanceMasks.crop_and_resize`<|endoftext|>
|
44972638a4d411f572afb8d5e7c32d37b20788daffaa664fb97f1f96f89ee1b6
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=None, interpolation=None):
"Translate the PolygonMasks.\n\n Example:\n >>> self = PolygonMasks.random(dtype=np.int)\n >>> out_shape = (self.height, self.width)\n >>> new = self.translate(out_shape, 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501\n "
assert ((fill_val is None) or (fill_val == 0)), f'Here fill_val is not used, and defaultly should be None or 0. got {fill_val}.'
if (len(self.masks) == 0):
translated_masks = PolygonMasks([], *out_shape)
else:
translated_masks = []
for poly_per_obj in self.masks:
translated_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (direction == 'horizontal'):
p[0::2] = np.clip((p[0::2] + offset), 0, out_shape[1])
elif (direction == 'vertical'):
p[1::2] = np.clip((p[1::2] + offset), 0, out_shape[0])
translated_poly_per_obj.append(p)
translated_masks.append(translated_poly_per_obj)
translated_masks = PolygonMasks(translated_masks, *out_shape)
return translated_masks
|
Translate the PolygonMasks.
Example:
>>> self = PolygonMasks.random(dtype=np.int)
>>> out_shape = (self.height, self.width)
>>> new = self.translate(out_shape, 4., direction='horizontal')
>>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])
>>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501
|
mmdet/core/mask/structures.py
|
translate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=None, interpolation=None):
"Translate the PolygonMasks.\n\n Example:\n >>> self = PolygonMasks.random(dtype=np.int)\n >>> out_shape = (self.height, self.width)\n >>> new = self.translate(out_shape, 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501\n "
assert ((fill_val is None) or (fill_val == 0)), f'Here fill_val is not used, and defaultly should be None or 0. got {fill_val}.'
if (len(self.masks) == 0):
translated_masks = PolygonMasks([], *out_shape)
else:
translated_masks = []
for poly_per_obj in self.masks:
translated_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (direction == 'horizontal'):
p[0::2] = np.clip((p[0::2] + offset), 0, out_shape[1])
elif (direction == 'vertical'):
p[1::2] = np.clip((p[1::2] + offset), 0, out_shape[0])
translated_poly_per_obj.append(p)
translated_masks.append(translated_poly_per_obj)
translated_masks = PolygonMasks(translated_masks, *out_shape)
return translated_masks
|
def translate(self, out_shape, offset, direction='horizontal', fill_val=None, interpolation=None):
"Translate the PolygonMasks.\n\n Example:\n >>> self = PolygonMasks.random(dtype=np.int)\n >>> out_shape = (self.height, self.width)\n >>> new = self.translate(out_shape, 4., direction='horizontal')\n >>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])\n >>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501\n "
assert ((fill_val is None) or (fill_val == 0)), f'Here fill_val is not used, and defaultly should be None or 0. got {fill_val}.'
if (len(self.masks) == 0):
translated_masks = PolygonMasks([], *out_shape)
else:
translated_masks = []
for poly_per_obj in self.masks:
translated_poly_per_obj = []
for p in poly_per_obj:
p = p.copy()
if (direction == 'horizontal'):
p[0::2] = np.clip((p[0::2] + offset), 0, out_shape[1])
elif (direction == 'vertical'):
p[1::2] = np.clip((p[1::2] + offset), 0, out_shape[0])
translated_poly_per_obj.append(p)
translated_masks.append(translated_poly_per_obj)
translated_masks = PolygonMasks(translated_masks, *out_shape)
return translated_masks<|docstring|>Translate the PolygonMasks.
Example:
>>> self = PolygonMasks.random(dtype=np.int)
>>> out_shape = (self.height, self.width)
>>> new = self.translate(out_shape, 4., direction='horizontal')
>>> assert np.all(new.masks[0][0][1::2] == self.masks[0][0][1::2])
>>> assert np.all(new.masks[0][0][0::2] == self.masks[0][0][0::2] + 4) # noqa: E501<|endoftext|>
|
7827481f02cd2f85d240041f960ead018e9964b33820132ba7b6fd6451b2c567
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
'See :func:`BaseInstanceMasks.shear`.'
if (len(self.masks) == 0):
sheared_masks = PolygonMasks([], *out_shape)
else:
sheared_masks = []
if (direction == 'horizontal'):
shear_matrix = np.stack([[1, magnitude], [0, 1]]).astype(np.float32)
elif (direction == 'vertical'):
shear_matrix = np.stack([[1, 0], [magnitude, 1]]).astype(np.float32)
for poly_per_obj in self.masks:
sheared_poly = []
for p in poly_per_obj:
p = np.stack([p[0::2], p[1::2]], axis=0)
new_coords = np.matmul(shear_matrix, p)
new_coords[(0, :)] = np.clip(new_coords[(0, :)], 0, out_shape[1])
new_coords[(1, :)] = np.clip(new_coords[(1, :)], 0, out_shape[0])
sheared_poly.append(new_coords.transpose((1, 0)).reshape((- 1)))
sheared_masks.append(sheared_poly)
sheared_masks = PolygonMasks(sheared_masks, *out_shape)
return sheared_masks
|
See :func:`BaseInstanceMasks.shear`.
|
mmdet/core/mask/structures.py
|
shear
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
if (len(self.masks) == 0):
sheared_masks = PolygonMasks([], *out_shape)
else:
sheared_masks = []
if (direction == 'horizontal'):
shear_matrix = np.stack([[1, magnitude], [0, 1]]).astype(np.float32)
elif (direction == 'vertical'):
shear_matrix = np.stack([[1, 0], [magnitude, 1]]).astype(np.float32)
for poly_per_obj in self.masks:
sheared_poly = []
for p in poly_per_obj:
p = np.stack([p[0::2], p[1::2]], axis=0)
new_coords = np.matmul(shear_matrix, p)
new_coords[(0, :)] = np.clip(new_coords[(0, :)], 0, out_shape[1])
new_coords[(1, :)] = np.clip(new_coords[(1, :)], 0, out_shape[0])
sheared_poly.append(new_coords.transpose((1, 0)).reshape((- 1)))
sheared_masks.append(sheared_poly)
sheared_masks = PolygonMasks(sheared_masks, *out_shape)
return sheared_masks
|
def shear(self, out_shape, magnitude, direction='horizontal', border_value=0, interpolation='bilinear'):
if (len(self.masks) == 0):
sheared_masks = PolygonMasks([], *out_shape)
else:
sheared_masks = []
if (direction == 'horizontal'):
shear_matrix = np.stack([[1, magnitude], [0, 1]]).astype(np.float32)
elif (direction == 'vertical'):
shear_matrix = np.stack([[1, 0], [magnitude, 1]]).astype(np.float32)
for poly_per_obj in self.masks:
sheared_poly = []
for p in poly_per_obj:
p = np.stack([p[0::2], p[1::2]], axis=0)
new_coords = np.matmul(shear_matrix, p)
new_coords[(0, :)] = np.clip(new_coords[(0, :)], 0, out_shape[1])
new_coords[(1, :)] = np.clip(new_coords[(1, :)], 0, out_shape[0])
sheared_poly.append(new_coords.transpose((1, 0)).reshape((- 1)))
sheared_masks.append(sheared_poly)
sheared_masks = PolygonMasks(sheared_masks, *out_shape)
return sheared_masks<|docstring|>See :func:`BaseInstanceMasks.shear`.<|endoftext|>
|
636dd3f67f162bab1932b8964271e8a330262367877ec5b2964a86841159f0fc
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
'See :func:`BaseInstanceMasks.rotate`.'
if (len(self.masks) == 0):
rotated_masks = PolygonMasks([], *out_shape)
else:
rotated_masks = []
rotate_matrix = cv2.getRotationMatrix2D(center, (- angle), scale)
for poly_per_obj in self.masks:
rotated_poly = []
for p in poly_per_obj:
p = p.copy()
coords = np.stack([p[0::2], p[1::2]], axis=1)
coords = np.concatenate((coords, np.ones((coords.shape[0], 1), coords.dtype)), axis=1)
rotated_coords = np.matmul(rotate_matrix[(None, :, :)], coords[(:, :, None)])[(..., 0)]
rotated_coords[(:, 0)] = np.clip(rotated_coords[(:, 0)], 0, out_shape[1])
rotated_coords[(:, 1)] = np.clip(rotated_coords[(:, 1)], 0, out_shape[0])
rotated_poly.append(rotated_coords.reshape((- 1)))
rotated_masks.append(rotated_poly)
rotated_masks = PolygonMasks(rotated_masks, *out_shape)
return rotated_masks
|
See :func:`BaseInstanceMasks.rotate`.
|
mmdet/core/mask/structures.py
|
rotate
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
if (len(self.masks) == 0):
rotated_masks = PolygonMasks([], *out_shape)
else:
rotated_masks = []
rotate_matrix = cv2.getRotationMatrix2D(center, (- angle), scale)
for poly_per_obj in self.masks:
rotated_poly = []
for p in poly_per_obj:
p = p.copy()
coords = np.stack([p[0::2], p[1::2]], axis=1)
coords = np.concatenate((coords, np.ones((coords.shape[0], 1), coords.dtype)), axis=1)
rotated_coords = np.matmul(rotate_matrix[(None, :, :)], coords[(:, :, None)])[(..., 0)]
rotated_coords[(:, 0)] = np.clip(rotated_coords[(:, 0)], 0, out_shape[1])
rotated_coords[(:, 1)] = np.clip(rotated_coords[(:, 1)], 0, out_shape[0])
rotated_poly.append(rotated_coords.reshape((- 1)))
rotated_masks.append(rotated_poly)
rotated_masks = PolygonMasks(rotated_masks, *out_shape)
return rotated_masks
|
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0):
if (len(self.masks) == 0):
rotated_masks = PolygonMasks([], *out_shape)
else:
rotated_masks = []
rotate_matrix = cv2.getRotationMatrix2D(center, (- angle), scale)
for poly_per_obj in self.masks:
rotated_poly = []
for p in poly_per_obj:
p = p.copy()
coords = np.stack([p[0::2], p[1::2]], axis=1)
coords = np.concatenate((coords, np.ones((coords.shape[0], 1), coords.dtype)), axis=1)
rotated_coords = np.matmul(rotate_matrix[(None, :, :)], coords[(:, :, None)])[(..., 0)]
rotated_coords[(:, 0)] = np.clip(rotated_coords[(:, 0)], 0, out_shape[1])
rotated_coords[(:, 1)] = np.clip(rotated_coords[(:, 1)], 0, out_shape[0])
rotated_poly.append(rotated_coords.reshape((- 1)))
rotated_masks.append(rotated_poly)
rotated_masks = PolygonMasks(rotated_masks, *out_shape)
return rotated_masks<|docstring|>See :func:`BaseInstanceMasks.rotate`.<|endoftext|>
|
dfeda3c618bf738f4e65adcd6d5d4270a5fd02f19051d314caa71f69947e636b
|
def to_bitmap(self):
'convert polygon masks to bitmap masks.'
bitmap_masks = self.to_ndarray()
return BitmapMasks(bitmap_masks, self.height, self.width)
|
convert polygon masks to bitmap masks.
|
mmdet/core/mask/structures.py
|
to_bitmap
|
ange33333333/2021_VRDL-HW3
| 20,190
|
python
|
def to_bitmap(self):
bitmap_masks = self.to_ndarray()
return BitmapMasks(bitmap_masks, self.height, self.width)
|
def to_bitmap(self):
bitmap_masks = self.to_ndarray()
return BitmapMasks(bitmap_masks, self.height, self.width)<|docstring|>convert polygon masks to bitmap masks.<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.