sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
def check_version():
"""
Tells you if you have an old version of intern.
"""
import requests
r = requests.get('https://pypi.python.org/pypi/intern/json').json()
r = r['info']['version']
if r != __version__:
print("You are using version {}. A newer version of intern is available: {} ".format(__version__, r) +
"\n\n'pip install -U intern' to update.")
return r
|
Tells you if you have an old version of intern.
|
entailment
|
def check_channel(fcn):
"""Decorator that ensures a valid channel passed in.
Args:
fcn (function): Function that has a ChannelResource as its second argument.
Returns:
(function): Wraps given function with one that checks for a valid channel.
"""
def wrapper(*args, **kwargs):
if not isinstance(args[1], ChannelResource):
raise RuntimeError('resource must be an instance of intern.resource.boss.ChannelResource.')
if not args[1].cutout_ready:
raise PartialChannelResourceError(
'ChannelResource not fully initialized. Use intern.remote.BossRemote.get_channel({}, {}, {})'.format(
args[1].name, args[1].coll_name, args[1].exp_name))
return fcn(*args, **kwargs)
return wrapper
|
Decorator that ensures a valid channel passed in.
Args:
fcn (function): Function that has a ChannelResource as its second argument.
Returns:
(function): Wraps given function with one that checks for a valid channel.
|
entailment
|
def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], access_mode=CacheMode.no_cache, **kwargs):
"""Get a cutout from the volume service.
Args:
resource (intern.resource.boss.resource.ChannelResource): Channel or layer resource.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
id_list (optional [list[int]]): list of object ids to filter the cutout by.
no_cache (optional [boolean]): specifies the use of cache to be True or False.
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
Returns:
(numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
Raises:
requests.HTTPError on error.
"""
return self.service.get_cutout(
resource, resolution, x_range, y_range, z_range, time_range, id_list,
self.url_prefix, self.auth, self.session, self.session_send_opts, access_mode, **kwargs)
|
Get a cutout from the volume service.
Args:
resource (intern.resource.boss.resource.ChannelResource): Channel or layer resource.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
id_list (optional [list[int]]): list of object ids to filter the cutout by.
no_cache (optional [boolean]): specifies the use of cache to be True or False.
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
Returns:
(numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
Raises:
requests.HTTPError on error.
|
entailment
|
def reserve_ids(self, resource, num_ids):
"""Reserve a block of unique, sequential ids for annotations.
Args:
resource (intern.resource.Resource): Resource should be an annotation channel.
num_ids (int): Number of ids to reserve.
Returns:
(int): First id reserved.
"""
return self.service.reserve_ids(
resource, num_ids,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Reserve a block of unique, sequential ids for annotations.
Args:
resource (intern.resource.Resource): Resource should be an annotation channel.
num_ids (int): Number of ids to reserve.
Returns:
(int): First id reserved.
|
entailment
|
def get_bounding_box(self, resource, resolution, id, bb_type='loose'):
"""Get bounding box containing object specified by id.
Currently only supports 'loose' bounding boxes. The bounding box
returned is cuboid aligned.
Args:
resource (intern.resource.Resource): Resource compatible with annotation operations.
resolution (int): 0 indicates native resolution.
id (int): Id of object of interest.
bb_type (optional[string]): Defaults to 'loose'.
Returns:
(dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]}
"""
return self.service.get_bounding_box(
resource, resolution, id, bb_type,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Get bounding box containing object specified by id.
Currently only supports 'loose' bounding boxes. The bounding box
returned is cuboid aligned.
Args:
resource (intern.resource.Resource): Resource compatible with annotation operations.
resolution (int): 0 indicates native resolution.
id (int): Id of object of interest.
bb_type (optional[string]): Defaults to 'loose'.
Returns:
(dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]}
|
entailment
|
def get_ids_in_region(
self, resource, resolution,
x_range, y_range, z_range, time_range=[0, 1]):
"""Get all ids in the region defined by x_range, y_range, z_range.
Args:
resource (intern.resource.Resource): An annotation channel.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40. Defaults to [0, 1].
Returns:
(list[int]): Example: [1, 2, 25].
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
"""
return self.service.get_ids_in_region(
resource, resolution, x_range, y_range, z_range, time_range,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Get all ids in the region defined by x_range, y_range, z_range.
Args:
resource (intern.resource.Resource): An annotation channel.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40. Defaults to [0, 1].
Returns:
(list[int]): Example: [1, 2, 25].
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
|
entailment
|
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs):
"""
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
"""
return self.service.get_neuroglancer_link(resource, resolution, x_range, y_range, z_range, self.url_prefix, **kwargs)
|
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
|
entailment
|
def list(self, resource, url_prefix, auth, session, send_opts):
"""List metadata keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(list): List of key names.
Raises:
requests.HTTPError on failure.
"""
req = self.get_metadata_request(
resource, 'GET', 'application/json', url_prefix, auth)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
keys_dict = resp.json()
return keys_dict['keys']
err = ('List failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(err, request = req, response = resp)
|
List metadata keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(list): List of key names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def create(self, resource, keys_vals, url_prefix, auth, session, send_opts):
"""Create the given key-value pairs for the given resource.
Will attempt to create all key-value pairs even if a failure is encountered.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
keys_vals (dictionary): The metadata to associate with the resource.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Raises:
HTTPErrorList on failure.
"""
success = True
exc = HTTPErrorList('At least one key-value create failed.')
for pair in keys_vals.items():
key = pair[0]
value = pair[1]
req = self.get_metadata_request(
resource, 'POST', 'application/json', url_prefix, auth,
key, value)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 201:
continue
err = (
'Create failed for {}: {}:{}, got HTTP response: ({}) - {}'
.format(resource.name, key, value, resp.status_code, resp.text))
exc.http_errors.append(HTTPError(err, request=req, response=resp))
success = False
if not success:
raise exc
|
Create the given key-value pairs for the given resource.
Will attempt to create all key-value pairs even if a failure is encountered.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
keys_vals (dictionary): The metadata to associate with the resource.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Raises:
HTTPErrorList on failure.
|
entailment
|
def get_bit_width(self, resource):
"""Method to return the bit width for blosc based on the Resource"""
datatype = resource.datatype
if "uint" in datatype:
bit_width = int(datatype.split("uint")[1])
else:
raise ValueError("Unsupported datatype: {}".format(datatype))
return bit_width
|
Method to return the bit width for blosc based on the Resource
|
entailment
|
def create_cutout(
self, resource, resolution, x_range, y_range, z_range, time_range, numpyVolume,
url_prefix, auth, session, send_opts):
"""Upload a cutout to the Boss data store.
Args:
resource (intern.resource.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
numpyVolume (numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
"""
if numpyVolume.ndim == 3:
# Can't have time
if time_range is not None:
raise ValueError(
"You must provide a 4D matrix if specifying a time range")
elif numpyVolume.ndim == 4:
# must have time
if time_range is None:
raise ValueError(
"You must specifying a time range if providing a 4D matrix")
else:
raise ValueError(
"Invalid data format. Only 3D or 4D cutouts are supported. " +
"Number of dimensions: {}".format(numpyVolume.ndim)
)
# Check to see if this volume is larger than 1GB. If so, chunk it into
# several smaller bites:
if (
(x_range[1] - x_range[0]) *
(y_range[1] - y_range[0]) *
(z_range[1] - z_range[0])
) > 1024 * 1024 * 32 * 2:
blocks = block_compute(
x_range[0], x_range[1],
y_range[0], y_range[1],
z_range[0], z_range[1],
block_size=(1024, 1024, 32)
)
for b in blocks:
_data = np.ascontiguousarray(
numpyVolume[
b[2][0] - z_range[0]: b[2][1] - z_range[0],
b[1][0] - y_range[0]: b[1][1] - y_range[0],
b[0][0] - x_range[0]: b[0][1] - x_range[0]
],
dtype=numpyVolume.dtype
)
self.create_cutout(
resource, resolution, b[0], b[1], b[2],
time_range, _data, url_prefix, auth, session, send_opts
)
return
compressed = blosc.compress(
numpyVolume, typesize=self.get_bit_width(resource)
)
req = self.get_cutout_request(
resource, 'POST', 'application/blosc',
url_prefix, auth,
resolution, x_range, y_range, z_range, time_range, numpyVolume=compressed)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 201:
return
msg = ('Create cutout failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp)
|
Upload a cutout to the Boss data store.
Args:
resource (intern.resource.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
numpyVolume (numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
|
entailment
|
def get_cutout(
self, resource, resolution, x_range, y_range, z_range, time_range, id_list,
url_prefix, auth, session, send_opts, access_mode=CacheMode.no_cache, **kwargs
):
"""
Upload a cutout to the Boss data store.
Args:
resource (intern.resource.resource.Resource): Resource compatible
with cutout operations
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range ([list[int]]|None): time range such as [30, 40] which means t>=30 and t<40.
id_list (list[int]): list of object ids to filter the cutout by.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
chunk_size (optional Tuple[int, int, int]): The chunk size to request
Returns:
(numpy.array): A 3D or 4D numpy matrix in ZXY(time) order.
Raises:
requests.HTTPError
"""
chunk_size = kwargs.pop("chunk_size", (512, 512, 16 * 8))
# TODO: magic number
chunk_limit = (chunk_size[0] * chunk_size[1] * chunk_size[2]) * 1.2
# Check to see if this volume is larger than a single request. If so,
# chunk it into several smaller bites:
if time_range:
cutout_size = (
(x_range[1] - x_range[0]) *
(y_range[1] - y_range[0]) *
(z_range[1] - z_range[0]) *
(time_range[1] - time_range[0])
)
else:
cutout_size = (
(x_range[1] - x_range[0]) *
(y_range[1] - y_range[0]) *
(z_range[1] - z_range[0])
)
if cutout_size > chunk_limit:
blocks = block_compute(
x_range[0], x_range[1],
y_range[0], y_range[1],
z_range[0], z_range[1],
block_size=chunk_size
)
result = np.ndarray((
z_range[1] - z_range[0],
y_range[1] - y_range[0],
x_range[1] - x_range[0]
), dtype=resource.datatype)
for b in blocks:
_data = self.get_cutout(
resource, resolution, b[0], b[1], b[2],
time_range, id_list, url_prefix, auth, session, send_opts,
access_mode, **kwargs
)
result[
b[2][0] - z_range[0] : b[2][1] - z_range[0],
b[1][0] - y_range[0] : b[1][1] - y_range[0],
b[0][0] - x_range[0] : b[0][1] - x_range[0]
] = _data
return result
req = self.get_cutout_request(
resource, 'GET', 'application/blosc',
url_prefix, auth,
resolution, x_range, y_range, z_range, time_range, access_mode=access_mode,
id_list=id_list, **kwargs
)
prep = session.prepare_request(req)
# Hack in Accept header for now.
prep.headers['Accept'] = 'application/blosc'
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
raw_data = blosc.decompress(resp.content)
data_mat = np.fromstring(raw_data, dtype=resource.datatype)
if time_range:
# Reshape including time
return np.reshape(data_mat,
(time_range[1] - time_range[0],
z_range[1] - z_range[0],
y_range[1] - y_range[0],
x_range[1] - x_range[0]),
order='C')
else:
# Reshape without including time
return np.reshape(data_mat,
(z_range[1] - z_range[0],
y_range[1] - y_range[0],
x_range[1] - x_range[0]),
order='C')
msg = ('Get cutout failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp)
|
Upload a cutout to the Boss data store.
Args:
resource (intern.resource.resource.Resource): Resource compatible
with cutout operations
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range ([list[int]]|None): time range such as [30, 40] which means t>=30 and t<40.
id_list (list[int]): list of object ids to filter the cutout by.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
chunk_size (optional Tuple[int, int, int]): The chunk size to request
Returns:
(numpy.array): A 3D or 4D numpy matrix in ZXY(time) order.
Raises:
requests.HTTPError
|
entailment
|
def reserve_ids(
self, resource, num_ids,
url_prefix, auth, session, send_opts):
"""Reserve a block of unique, sequential ids for annotations.
Args:
resource (intern.resource.Resource): Resource should be an annotation channel.
num_ids (int): Number of ids to reserve.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(int): First id reserved.
Raises:
(TypeError): resource is not a channel or not an annotation channel.
"""
if not isinstance(resource, ChannelResource):
raise TypeError('resource must be ChannelResource')
if resource.type != 'annotation':
raise TypeError('Channel is not an annotation channel')
req = self.get_reserve_request(
resource, 'GET', 'application/json', url_prefix, auth, num_ids)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
json_data = resp.json()
return int(json_data['start_id'])
msg = ('Reserve ids failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp)
|
Reserve a block of unique, sequential ids for annotations.
Args:
resource (intern.resource.Resource): Resource should be an annotation channel.
num_ids (int): Number of ids to reserve.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(int): First id reserved.
Raises:
(TypeError): resource is not a channel or not an annotation channel.
|
entailment
|
def get_bounding_box(
self, resource, resolution, _id, bb_type,
url_prefix, auth, session, send_opts):
"""Get bounding box containing object specified by id.
Currently only supports 'loose' bounding boxes. The bounding box
returned is cuboid aligned.
Args:
resource (intern.resource.Resource): Resource compatible with annotation operations.
resolution (int): 0 indicates native resolution.
_id (int): Id of object of interest.
bb_type (string): Defaults to 'loose'.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]}
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
"""
if not isinstance(resource, ChannelResource):
raise TypeError('resource must be ChannelResource')
if resource.type != 'annotation':
raise TypeError('Channel is not an annotation channel')
req = self.get_bounding_box_request(
resource, 'GET', 'application/json', url_prefix, auth, resolution,
_id, bb_type)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
json_data = resp.json()
return json_data
msg = ('Get bounding box failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp)
|
Get bounding box containing object specified by id.
Currently only supports 'loose' bounding boxes. The bounding box
returned is cuboid aligned.
Args:
resource (intern.resource.Resource): Resource compatible with annotation operations.
resolution (int): 0 indicates native resolution.
_id (int): Id of object of interest.
bb_type (string): Defaults to 'loose'.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]}
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
|
entailment
|
def get_ids_in_region(
self, resource, resolution, x_range, y_range, z_range, time_range,
url_prefix, auth, session, send_opts):
"""Get all ids in the region defined by x_range, y_range, z_range.
Args:
resource (intern.resource.Resource): An annotation channel.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (list[int]]): time range such as [30, 40] which means t>=30 and t<40.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(list[int]): Example: [1, 2, 25].
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
"""
if not isinstance(resource, ChannelResource):
raise TypeError('resource must be ChannelResource')
if resource.type != 'annotation':
raise TypeError('Channel is not an annotation channel')
req = self.get_ids_request(
resource, 'GET', 'application/json', url_prefix, auth,
resolution, x_range, y_range, z_range, time_range)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
json_data = resp.json()
id_str_list = json_data['ids']
id_int_list = [int(i) for i in id_str_list]
return id_int_list
msg = ('Get bounding box failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp)
|
Get all ids in the region defined by x_range, y_range, z_range.
Args:
resource (intern.resource.Resource): An annotation channel.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (list[int]]): time range such as [30, 40] which means t>=30 and t<40.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dictionary): Additional arguments to pass to session.send().
Returns:
(list[int]): Example: [1, 2, 25].
Raises:
requests.HTTPError
TypeError: if resource is not an annotation channel.
|
entailment
|
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, url_prefix, **kwargs):
"""
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
url_prefix (string): Protocol + host such as https://api.theboss.io
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
"""
link = "https://neuroglancer.theboss.io/#!{'layers':{'" + str(resource.name) + "':{'type':'" + resource.type + "'_'source':" + "'boss://" + url_prefix+ "/" + resource.coll_name + "/" + resource.exp_name + "/" + resource.name + "'}}_'navigation':{'pose':{'position':{'voxelCoordinates':[" + str(x_range[0]) + "_" + str(y_range[0]) + "_" + str(z_range[0]) + "]}}}}"
return link
|
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
url_prefix (string): Protocol + host such as https://api.theboss.io
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
|
entailment
|
def get_graphviz_dot(machine):
"""
Return the graph of the state machine.
The format is the dot format for Graphviz, and can be directly used as input
to Graphviz.
To learn more about Graphviz, visit https://graphviz.gitlab.io.
**Display in Jupyter Notebook**
Install Python support for Graphviz via `pip install graphviz`.
Install Graphviz.
In a notebook, build a stmpy.Machine. Then, declare a cell with the
following content:
from graphviz import Source
src = Source(stmpy.get_graphviz_dot(stm))
src
**Using Graphviz on the Command Line**
Write the graph file with the following code:
with open("graph.gv", "w") as file:
print(stmpy.get_graphviz_dot(stm), file=file)
You can now use the command line tools from Graphviz to create a graphic
file with the graph. For instance:
dot -Tsvg graph.gv -o graph.svg
"""
s = []
s.append('digraph G {\n')
s.append('node [shape=box style=rounded fontname=Helvetica];\n')
s.append('edge [ fontname=Helvetica ];\n')
# initial state
s.append('initial [shape=point width=0.2];\n')
# final states
counter = 1
for t_id in machine._table:
transition = machine._table[t_id]
if not transition.internal:
if transition.target is 'final':
s.append('f{} [shape=doublecircle width=0.1 label="" style=filled fillcolor=black];\n'.format(counter))
counter = counter + 1
for state_name in machine._states:
s.append(_print_state(machine._states[state_name]))
# initial transition
counter = 0
s.append(_print_transition(machine._intial_transition, counter))
counter = 1
for t_id in machine._table:
transition = machine._table[t_id]
if not transition.internal:
s.append(_print_transition(transition, counter))
counter = counter + 1
s.append('}')
return ''.join(s)
|
Return the graph of the state machine.
The format is the dot format for Graphviz, and can be directly used as input
to Graphviz.
To learn more about Graphviz, visit https://graphviz.gitlab.io.
**Display in Jupyter Notebook**
Install Python support for Graphviz via `pip install graphviz`.
Install Graphviz.
In a notebook, build a stmpy.Machine. Then, declare a cell with the
following content:
from graphviz import Source
src = Source(stmpy.get_graphviz_dot(stm))
src
**Using Graphviz on the Command Line**
Write the graph file with the following code:
with open("graph.gv", "w") as file:
print(stmpy.get_graphviz_dot(stm), file=file)
You can now use the command line tools from Graphviz to create a graphic
file with the graph. For instance:
dot -Tsvg graph.gv -o graph.svg
|
entailment
|
def _parse_arg_list(arglist):
"""
Parses a list of arguments.
Arguments are expected to be split by a comma, surrounded by any amount
of whitespace. Arguments are then run through Python's eval() method.
"""
args = []
for arg in arglist.split(','):
arg = arg.strip()
if arg: # string is not empty
args.append(eval(arg))
return args
|
Parses a list of arguments.
Arguments are expected to be split by a comma, surrounded by any amount
of whitespace. Arguments are then run through Python's eval() method.
|
entailment
|
def _parse_action(action):
"""
Parses a single action item, for instance one of the following:
m; m(); m(True); m(*)
The brackets must match.
"""
i_open = action.find('(')
if i_open is -1:
# return action name, finished
return {'name': action, 'args': [], 'event_args': False}
# we need to parse the arguments
i_close = action.rfind(')')
if i_close is -1:
raise Exception('Bracket in argument opened but not closed.')
action_name = action[:i_open]
arglist = action[i_open+1:i_close].strip()
if not arglist:
# no arglist, just return method name
return {'name': action_name, 'args': [], 'event_args': False}
if '*' in arglist:
return {'name': action_name, 'args': [], 'event_args': True}
return {'name': action_name, 'args': _parse_arg_list(arglist), 'event_args': False}
|
Parses a single action item, for instance one of the following:
m; m(); m(True); m(*)
The brackets must match.
|
entailment
|
def _parse_action_list_attribute(attribute):
"""
Parses a list of actions, as found in the effect attribute of
transitions, and the enry and exit actions of states.
Actions are separated by a semicolon, surrounded by any amount of
whitespace. A action can have the following form:
m; m(); m(True); m(*)
The asterisk that the state machine should provide the args and
kwargs from the incoming event.
"""
actions = []
for action_call in attribute.split(';'):
action_call = action_call.strip()
if action_call: # string is not empty
actions.append(_parse_action(action_call))
return actions
|
Parses a list of actions, as found in the effect attribute of
transitions, and the enry and exit actions of states.
Actions are separated by a semicolon, surrounded by any amount of
whitespace. A action can have the following form:
m; m(); m(True); m(*)
The asterisk that the state machine should provide the args and
kwargs from the incoming event.
|
entailment
|
def print_status(self):
"""Provide a snapshot of the current status."""
s = []
s.append('=== State Machines: ===\n')
for stm_id in Driver._stms_by_id:
stm = Driver._stms_by_id[stm_id]
s.append(' - {} in state {}\n'.format(stm.id, stm.state))
s.append('=== Events in Queue: ===\n')
for event in self._event_queue.queue:
if event is not None:
s.append(' - {} for {} with args:{} kwargs:{}\n'.format(
event['id'], event['stm'].id,
event['args'], event['kwargs']))
s.append('=== Active Timers: {} ===\n'.format(len(self._timer_queue)))
for timer in self._timer_queue:
s.append(' - {} for {} with timeout {}\n'.format(
timer['id'], timer['stm'].id, timer['timeout']))
s.append('=== ================ ===\n')
return ''.join(s)
|
Provide a snapshot of the current status.
|
entailment
|
def add_machine(self, machine):
"""Add the state machine to this driver."""
self._logger.debug('Adding machine {} to driver'.format(machine.id))
machine._driver = self
machine._reset()
if machine.id is not None:
# TODO warning when STM already registered
Driver._stms_by_id[machine.id] = machine
self._add_event(event_id=None, args=[], kwargs={}, stm=machine)
|
Add the state machine to this driver.
|
entailment
|
def start(self, max_transitions=None, keep_active=False):
"""
Start the driver.
This method creates a thread which runs the event loop.
The method returns immediately. To wait until the driver
finishes, use `stmpy.Driver.wait_until_finished`.
`max_transitions`: execute only this number of transitions, then stop
`keep_active`: When true, keep the driver running even when all state
machines terminated
"""
self._active = True
self._max_transitions = max_transitions
self._keep_active = keep_active
self.thread = Thread(target=self._start_loop)
self.thread.start()
|
Start the driver.
This method creates a thread which runs the event loop.
The method returns immediately. To wait until the driver
finishes, use `stmpy.Driver.wait_until_finished`.
`max_transitions`: execute only this number of transitions, then stop
`keep_active`: When true, keep the driver running even when all state
machines terminated
|
entailment
|
def wait_until_finished(self):
"""Blocking method to wait until the driver finished its execution."""
try:
self.thread.join()
except KeyboardInterrupt:
self._logger.debug('Keyboard interrupt detected, stopping driver.')
self._active = False
self._wake_queue()
|
Blocking method to wait until the driver finished its execution.
|
entailment
|
def _check_timers(self):
"""
Check for expired timers.
If there are any timers that expired, place them in the event
queue.
"""
if self._timer_queue:
timer = self._timer_queue[0]
if timer['timeout_abs'] < _current_time_millis():
# the timer is expired, remove first element in queue
self._timer_queue.pop(0)
# put into the event queue
self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))
self._add_event(timer['id'], [], {}, timer['stm'], front=True)
# not necessary to set next timeout,
# complete check timers will be called again
else:
self._next_timeout = (
timer['timeout_abs'] - _current_time_millis()) / 1000
if self._next_timeout < 0:
self._next_timeout = 0
else:
self._next_timeout = None
|
Check for expired timers.
If there are any timers that expired, place them in the event
queue.
|
entailment
|
def send(self, message_id, stm_id, args=[], kwargs={}):
"""
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier added to the driver.
"""
if stm_id not in Driver._stms_by_id:
self._logger.warn('Machine with name {} cannot be found. '
'Ignoring message {}.'.format(stm_id, message_id))
else:
stm = Driver._stms_by_id[stm_id]
self._add_event(message_id, args, kwargs, stm)
|
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier added to the driver.
|
entailment
|
def start_timer(self, timer_id, timeout):
"""
Start a timer or restart an active one.
The timeout is given in milliseconds. If a timer with the
same name already exists, it is restarted with the specified timeout.
Note that the timeout is intended as the minimum time until the timer's
expiration, but may vary due to the state of the event queue and the
load of the system.
"""
self._logger.debug('Start timer {} in stm {}'.format(timer_id, self.id))
self._driver._start_timer(timer_id, timeout, self)
|
Start a timer or restart an active one.
The timeout is given in milliseconds. If a timer with the
same name already exists, it is restarted with the specified timeout.
Note that the timeout is intended as the minimum time until the timer's
expiration, but may vary due to the state of the event queue and the
load of the system.
|
entailment
|
def stop_timer(self, timer_id):
"""
Stop a timer.
If the timer is not active, nothing happens.
"""
self._logger.debug('Stop timer {} in stm {}'.format(timer_id, self.id))
self._driver._stop_timer(timer_id, self)
|
Stop a timer.
If the timer is not active, nothing happens.
|
entailment
|
def send(self, message_id, args=[], kwargs={}):
"""
Send a message to this state machine.
To send a message to a state machine by its name, use
`stmpy.Driver.send` instead.
"""
self._logger.debug('Send {} in stm {}'.format(message_id, self.id))
self._driver._add_event(
event_id=message_id, args=args, kwargs=kwargs, stm=self)
|
Send a message to this state machine.
To send a message to a state machine by its name, use
`stmpy.Driver.send` instead.
|
entailment
|
def datatype(self, value):
"""
Args:
value (string): 'uint8', 'uint16', 'uint64'
Raises:
ValueError
"""
self._datatype = self.validate_datatype(value)
self._cutout_ready = True
|
Args:
value (string): 'uint8', 'uint16', 'uint64'
Raises:
ValueError
|
entailment
|
def list(self, resource):
"""List metadata keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
Returns:
(list): List of key names.
Raises:
requests.HTTPError on failure.
"""
return self.service.list(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
List metadata keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
Returns:
(list): List of key names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_groups(self, filtr=None):
"""Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (optional[string|None]): ['member'|'maintainer'] or defaults to None.
Returns:
(list[string]): List of group names.
Raises:
requests.HTTPError on failure.
"""
return self.service.list_groups(
filtr, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (optional[string|None]): ['member'|'maintainer'] or defaults to None.
Returns:
(list[string]): List of group names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_group(self, name, user_name=None):
"""Get owner of group and the resources it's attached to.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in determining if user is a member of the given group.
Returns:
(dict): Keys include 'owner', 'name', 'resources'.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_group(
name, user_name, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Get owner of group and the resources it's attached to.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in determining if user is a member of the given group.
Returns:
(dict): Keys include 'owner', 'name', 'resources'.
Raises:
requests.HTTPError on failure.
|
entailment
|
def create_group(self, name):
"""Create a new group.
Args:
name (string): Name of the group to create.
Raises:
requests.HTTPError on failure.
"""
self.service.create_group(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Create a new group.
Args:
name (string): Name of the group to create.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_group(self, name):
"""Delete given group.
Args:
name (string): Name of group.
Raises:
requests.HTTPError on failure.
"""
self.service.delete_group(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Delete given group.
Args:
name (string): Name of group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_group_members(self, name):
"""Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
"""
return self.service.list_group_members(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_group_maintainers(self, name):
"""Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
"""
return self.service.list_group_maintainers(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
|
entailment
|
def add_group_maintainer(self, name, user):
"""Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
version (optional[string]): Version of the Boss API to use. Defaults to the latest supported version.
Raises:
requests.HTTPError on failure.
"""
self.service.add_group_maintainer(
name, user, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
version (optional[string]): Version of the Boss API to use. Defaults to the latest supported version.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_group_maintainer(self, grp_name, user):
"""Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
"""
self.service.delete_group_maintainer(
grp_name, user, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_permissions(self, group_name=None, resource=None):
"""List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
"""
return self.service.list_permissions(group_name, resource,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_permissions(self, grp_name, resource, permissions):
""" Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failure.
"""
self.service.add_permissions(
grp_name, resource, permissions,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_permissions(self, grp_name, resource):
"""Removes permissions from the group for the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
Raises:
requests.HTTPError on failure.
"""
self.service.delete_permissions(
grp_name, resource, self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Removes permissions from the group for the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_user_role(self, user, role):
"""Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
"""
self.service.add_user_role(
user, role,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_user_roles(self, user):
"""Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_user_roles(
user, self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_user(
self, user, first_name=None, last_name=None, email=None, password=None):
"""Add a new user.
Args:
user (string): User name.
first_name (optional[string]): User's first name. Defaults to None.
last_name (optional[string]): User's last name. Defaults to None.
email: (optional[string]): User's email address. Defaults to None.
password: (optional[string]): User's password. Defaults to None.
Raises:
requests.HTTPError on failure.
"""
self.service.add_user(
user, first_name, last_name, email, password,
self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Add a new user.
Args:
user (string): User name.
first_name (optional[string]): User's first name. Defaults to None.
last_name (optional[string]): User's last name. Defaults to None.
email: (optional[string]): User's email address. Defaults to None.
password: (optional[string]): User's password. Defaults to None.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_user(self, user):
"""Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_user(self, user):
"""Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
"""
self.service.delete_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts)
|
Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
|
entailment
|
def create(self, resource):
"""Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
"""
return self.service.create(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get(self, resource):
"""Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
"""
return self.service.get(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts)
|
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def snap_to_cube(q_start, q_stop, chunk_depth=16, q_index=1):
"""
For any q in {x, y, z, t}
Takes in a q-range and returns a 1D bound that starts at a cube
boundary and ends at another cube boundary and includes the volume
inside the bounds. For instance, snap_to_cube(2, 3) = (1, 17)
Arguments:
q_start (int): The lower bound of the q bounding box of volume
q_stop (int): The upper bound of the q bounding box of volume
chunk_depth (int : CHUNK_DEPTH) The size of the chunk in this
volume (use ``get_info()``)
q_index (int : 1): The starting index of the volume (in q)
Returns:
2-tuple: (lo, hi) bounding box for the volume
"""
lo = 0
hi = 0
# Start by indexing everything at zero for our own sanity
q_start -= q_index
q_stop -= q_index
if q_start % chunk_depth == 0:
lo = q_start
else:
lo = q_start - (q_start % chunk_depth)
if q_stop % chunk_depth == 0:
hi = q_stop
else:
hi = q_stop + (chunk_depth - q_stop % chunk_depth)
return [lo + q_index, hi + q_index + 1]
|
For any q in {x, y, z, t}
Takes in a q-range and returns a 1D bound that starts at a cube
boundary and ends at another cube boundary and includes the volume
inside the bounds. For instance, snap_to_cube(2, 3) = (1, 17)
Arguments:
q_start (int): The lower bound of the q bounding box of volume
q_stop (int): The upper bound of the q bounding box of volume
chunk_depth (int : CHUNK_DEPTH) The size of the chunk in this
volume (use ``get_info()``)
q_index (int : 1): The starting index of the volume (in q)
Returns:
2-tuple: (lo, hi) bounding box for the volume
|
entailment
|
def block_compute(x_start, x_stop,
y_start, y_stop,
z_start, z_stop,
origin=(0, 0, 0),
block_size=(512, 512, 16)):
"""
Get bounding box coordinates (in 3D) of small cutouts to request in
order to reconstitute a larger cutout.
Arguments:
x_start (int): The lower bound of dimension x
x_stop (int): The upper bound of dimension x
y_start (int): The lower bound of dimension y
y_stop (int): The upper bound of dimension y
z_start (int): The lower bound of dimension z
z_stop (int): The upper bound of dimension z
Returns:
[((x_start, x_stop), (y_start, y_stop), (z_start, z_stop)), ... ]
"""
# x
x_bounds = range(origin[0], x_stop + block_size[0], block_size[0])
x_bounds = [x for x in x_bounds if (x > x_start and x < x_stop)]
if len(x_bounds) is 0:
x_slices = [(x_start, x_stop)]
else:
x_slices = []
for start_x in x_bounds[:-1]:
x_slices.append((start_x, start_x + block_size[0]))
x_slices.append((x_start, x_bounds[0]))
x_slices.append((x_bounds[-1], x_stop))
# y
y_bounds = range(origin[1], y_stop + block_size[1], block_size[1])
y_bounds = [y for y in y_bounds if (y > y_start and y < y_stop)]
if len(y_bounds) is 0:
y_slices = [(y_start, y_stop)]
else:
y_slices = []
for start_y in y_bounds[:-1]:
y_slices.append((start_y, start_y + block_size[1]))
y_slices.append((y_start, y_bounds[0]))
y_slices.append((y_bounds[-1], y_stop))
# z
z_bounds = range(origin[2], z_stop + block_size[2], block_size[2])
z_bounds = [z for z in z_bounds if (z > z_start and z < z_stop)]
if len(z_bounds) is 0:
z_slices = [(z_start, z_stop)]
else:
z_slices = []
for start_z in z_bounds[:-1]:
z_slices.append((start_z, start_z + block_size[2]))
z_slices.append((z_start, z_bounds[0]))
z_slices.append((z_bounds[-1], z_stop))
# alright, yuck. but now we have {x, y, z}_slices, each of which hold the
# start- and end-points of each cube-aligned boundary. For instance, if you
# requested z-slices 4 through 20, it holds [(4, 16), (16, 20)].
# For my next trick, I'll convert these to a list of:
# ((x_start, x_stop), (y_start, y_stop), (z_start, z_stop))
chunks = []
for x in x_slices:
for y in y_slices:
for z in z_slices:
chunks.append((x, y, z))
return chunks
|
Get bounding box coordinates (in 3D) of small cutouts to request in
order to reconstitute a larger cutout.
Arguments:
x_start (int): The lower bound of dimension x
x_stop (int): The upper bound of dimension x
y_start (int): The lower bound of dimension y
y_stop (int): The upper bound of dimension y
z_start (int): The lower bound of dimension z
z_stop (int): The upper bound of dimension z
Returns:
[((x_start, x_stop), (y_start, y_stop), (z_start, z_stop)), ... ]
|
entailment
|
def _init_project_service(self, version):
"""
Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)
self._token_project = project_cfg[CONFIG_TOKEN]
proto = project_cfg[CONFIG_PROTOCOL]
host = project_cfg[CONFIG_HOST]
self._project = ProjectService(host, version)
self._project.base_protocol = proto
self._project.set_auth(self._token_project)
|
Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
|
entailment
|
def _init_metadata_service(self, version):
"""
Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
metadata_cfg = self._load_config_section(CONFIG_METADATA_SECTION)
self._token_metadata = metadata_cfg[CONFIG_TOKEN]
proto = metadata_cfg[CONFIG_PROTOCOL]
host = metadata_cfg[CONFIG_HOST]
self._metadata = MetadataService(host, version)
self._metadata.base_protocol = proto
self._metadata.set_auth(self._token_metadata)
|
Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
|
entailment
|
def _init_volume_service(self, version):
"""
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
volume_cfg = self._load_config_section(CONFIG_VOLUME_SECTION)
self._token_volume = volume_cfg[CONFIG_TOKEN]
proto = volume_cfg[CONFIG_PROTOCOL]
host = volume_cfg[CONFIG_HOST]
self._volume = VolumeService(host, version)
self._volume.base_protocol = proto
self._volume.set_auth(self._token_volume)
|
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
|
entailment
|
def _load_config_section(self, section_name):
"""
Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters
"""
if self._config.has_section(section_name):
# Load specific section
section = dict(self._config.items(section_name))
elif self._config.has_section("Default"):
# Load Default section
section = dict(self._config.items("Default"))
else:
raise KeyError((
"'{}' was not found in the configuration file and no default " +
"configuration was provided."
).format(section_name))
# Make sure section is valid
if "protocol" in section and "host" in section and "token" in section:
return section
else:
raise KeyError(
"Missing values in configuration data. " +
"Must contain: protocol, host, token"
)
|
Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters
|
entailment
|
def list_groups(self, filtr=None):
"""
Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (optional[string|None]): ['member'|'maintainer']
Returns:
(list[string]): List of group names.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_groups(filtr)
|
Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (optional[string|None]): ['member'|'maintainer']
Returns:
(list[string]): List of group names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_group(self, name, user_name=None):
"""
Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determining if user is a member of the given group.
Returns:
(mixed): Dictionary if getting group information or bool if a user
name is supplied.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_group(name, user_name)
|
Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determining if user is a member of the given group.
Returns:
(mixed): Dictionary if getting group information or bool if a user
name is supplied.
Raises:
requests.HTTPError on failure.
|
entailment
|
def create_group(self, name):
"""
Create a new group.
Args:
name (string): Name of the group to create.
Returns:
(bool): True on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.create_group(name)
|
Create a new group.
Args:
name (string): Name of the group to create.
Returns:
(bool): True on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_group(self, name):
"""
Delete given group.
Args:
name (string): Name of group.
Returns:
(bool): True on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.delete_group(name)
|
Delete given group.
Args:
name (string): Name of group.
Returns:
(bool): True on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_group_members(self, name):
"""
Get the members of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_members(name)
|
Get the members of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_group_member(self, grp_name, user):
"""
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_group_member(grp_name, user)
|
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_group_member(self, grp_name, user):
"""
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to delete from the group.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_group_member(grp_name, user)
|
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to delete from the group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_is_group_member(self, grp_name, user):
"""
Check if the given user is a member of the named group.
Note that a group maintainer is not considered a member unless the
user is also explicitly added as a member.
Args:
name (string): Name of group.
user_name (string): User of interest.
Returns:
(bool): False if user not a member.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_is_group_member(grp_name, user)
|
Check if the given user is a member of the named group.
Note that a group maintainer is not considered a member unless the
user is also explicitly added as a member.
Args:
name (string): Name of group.
user_name (string): User of interest.
Returns:
(bool): False if user not a member.
|
entailment
|
def list_group_maintainers(self, name):
"""
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_maintainers(name)
|
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_group_maintainer(self, name, user):
"""
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_group_maintainer(name, user)
|
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_group_maintainer(self, grp_name, user):
"""
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_group_maintainer(grp_name, user)
|
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_is_group_maintainer(self, grp_name, user):
"""
Check if the given user is a member of the named group.
Args:
name (string): Name of group.
user (string): User of interest.
Returns:
(bool): False if user not a member.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_is_group_maintainer(grp_name, user)
|
Check if the given user is a member of the named group.
Args:
name (string): Name of group.
user (string): User of interest.
Returns:
(bool): False if user not a member.
|
entailment
|
def list_permissions(self, group_name=None, resource=None):
"""
List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_permissions(group_name, resource)
|
List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_permissions(self, grp_name, resource):
"""
Get permissions associated the group has with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_permissions(grp_name, resource)
|
Get permissions associated the group has with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_permissions(self, grp_name, resource, permissions):
"""
Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_permissions(grp_name, resource, permissions)
|
Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
|
entailment
|
def update_permissions(self, grp_name, resource, permissions):
"""
Update permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.update_permissions(grp_name, resource, permissions)
|
Update permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_permissions(self, grp_name, resource):
"""
Removes permissions from the group for the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_permissions(grp_name, resource)
|
Removes permissions from the group for the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_user_roles(self, user):
"""
Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_roles(user)
|
Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_user_role(self, user, role):
"""
Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_user_role(user, role)
|
Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_user_role(self, user, role):
"""
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_user_role(user, role)
|
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_user(self, user):
"""
Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_user(user)
|
Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_user_groups(self, user):
"""
Get user's group memberships.
Args:
user (string): User name.
Returns:
(list): User's groups.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_groups(user)
|
Get user's group memberships.
Args:
user (string): User name.
Returns:
(list): User's groups.
Raises:
requests.HTTPError on failure.
|
entailment
|
def add_user(
self, user,
first_name=None, last_name=None,
email=None, password=None
):
"""
Add a new user.
Args:
user (string): User name.
first_name (optional[string]): User's first name. Defaults to None.
last_name (optional[string]): User's last name. Defaults to None.
email: (optional[string]): User's email address. Defaults to None.
password: (optional[string]): User's password. Defaults to None.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_user(
user, first_name, last_name, email, password)
|
Add a new user.
Args:
user (string): User name.
first_name (optional[string]): User's first name. Defaults to None.
last_name (optional[string]): User's last name. Defaults to None.
email: (optional[string]): User's email address. Defaults to None.
password: (optional[string]): User's password. Defaults to None.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_user(self, user):
"""
Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_user(user)
|
Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
|
entailment
|
def _list_resource(self, resource):
"""
List all instances of the given resource type.
Use the specific list_<resource>() methods instead:
list_collections()
list_experiments()
list_channels()
list_coordinate_frames()
Args:
resource (intern.resource.boss.BossResource): resource.name may be
an empty string.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return super(BossRemote, self).list_project(resource=resource)
|
List all instances of the given resource type.
Use the specific list_<resource>() methods instead:
list_collections()
list_experiments()
list_channels()
list_coordinate_frames()
Args:
resource (intern.resource.boss.BossResource): resource.name may be
an empty string.
Returns:
(list)
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_experiments(self, collection_name):
"""
List all experiments that belong to a collection.
Args:
collection_name (string): Name of the parent collection.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
exp = ExperimentResource(
name='', collection_name=collection_name, coord_frame='foo')
return self._list_resource(exp)
|
List all experiments that belong to a collection.
Args:
collection_name (string): Name of the parent collection.
Returns:
(list)
Raises:
requests.HTTPError on failure.
|
entailment
|
def list_channels(self, collection_name, experiment_name):
"""
List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
dont_care = 'image'
chan = ChannelResource(
name='', collection_name=collection_name,
experiment_name=experiment_name, type=dont_care)
return self._list_resource(chan)
|
List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_channel(self, chan_name, coll_name, exp_name):
"""
Helper that gets a fully initialized ChannelResource for an *existing* channel.
Args:
chan_name (str): Name of channel.
coll_name (str): Name of channel's collection.
exp_name (str): Name of channel's experiment.
Returns:
(intern.resource.boss.ChannelResource)
"""
chan = ChannelResource(chan_name, coll_name, exp_name)
return self.get_project(chan)
|
Helper that gets a fully initialized ChannelResource for an *existing* channel.
Args:
chan_name (str): Name of channel.
coll_name (str): Name of channel's collection.
exp_name (str): Name of channel's experiment.
Returns:
(intern.resource.boss.ChannelResource)
|
entailment
|
def create_project(self, resource):
"""
Create the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.create(resource)
|
Create the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def get_project(self, resource):
"""
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well
as any parents must be identified to succeed.
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get(resource)
|
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well
as any parents must be identified to succeed.
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def update_project(self, resource_name, resource):
"""
Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the
resource is getting its name changed).
resource (intern.resource.boss.BossResource): New attributes for
the resource.
Returns:
(intern.resource.boss.BossResource): Returns updated resource of
given type on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.update(resource_name, resource)
|
Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the
resource is getting its name changed).
resource (intern.resource.boss.BossResource): New attributes for
the resource.
Returns:
(intern.resource.boss.BossResource): Returns updated resource of
given type on success.
Raises:
requests.HTTPError on failure.
|
entailment
|
def delete_project(self, resource):
"""
Deletes the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Raises:
requests.HTTPError on a failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete(resource)
|
Deletes the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Raises:
requests.HTTPError on a failure.
|
entailment
|
def list_metadata(self, resource):
"""
List all keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(list)
Raises:
requests.HTTPError on a failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.list(resource)
|
List all keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(list)
Raises:
requests.HTTPError on a failure.
|
entailment
|
def create_metadata(self, resource, keys_vals):
"""
Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.create(resource, keys_vals)
|
Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Raises:
HTTPErrorList on failure.
|
entailment
|
def get_metadata(self, resource, keys):
"""
Gets the values for given keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Returns:
(dictionary)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.get(resource, keys)
|
Gets the values for given keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Returns:
(dictionary)
Raises:
HTTPErrorList on failure.
|
entailment
|
def update_metadata(self, resource, keys_vals):
"""
Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.update(resource, keys_vals)
|
Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.
Raises:
HTTPErrorList on failure.
|
entailment
|
def delete_metadata(self, resource, keys):
"""
Deletes the given key-value pairs associated with the given resource.
Will attempt to delete all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.delete(resource, keys)
|
Deletes the given key-value pairs associated with the given resource.
Will attempt to delete all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Raises:
HTTPErrorList on failure.
|
entailment
|
def parse_bossURI(self, uri): # type: (str) -> Resource
"""
Parse a bossDB URI and handle malform errors.
Arguments:
uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
Returns:
Resource
"""
t = uri.split("://")[1].split("/")
if len(t) is 3:
return self.get_channel(t[2], t[0], t[1])
raise ValueError("Cannot parse URI " + uri + ".")
|
Parse a bossDB URI and handle malform errors.
Arguments:
uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
Returns:
Resource
|
entailment
|
def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], no_cache=None, access_mode=CacheMode.no_cache, **kwargs):
"""Get a cutout from the volume service.
Note that access_mode=no_cache is desirable when reading large amounts of
data at once. In these cases, the data is not first read into the
cache, but instead, is sent directly from the data store to the
requester.
Args:
resource (intern.resource.boss.resource.ChannelResource | str): Channel or layer Resource. If a
string is provided instead, BossRemote.parse_bossURI is called instead on a URI-formatted
string of the form `bossdb://collection/experiment/channel`.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
id_list (optional [list[int]]): list of object ids to filter the cutout by.
no_cache (optional [boolean or None]): Deprecated way to specify the use of cache to be True or False.
access_mode should be used instead
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
TODO: Add mode to documentation
Returns:
(numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
Raises:
requests.HTTPError on error.
"""
if no_cache is not None:
warnings.warn("The no-cache option has been deprecated and will not be used in future versions of intern.")
warnings.warn("Please from intern.service.boss.volume import CacheMode and use access_mode=CacheMode.[cache,no-cache,raw] instead.")
if no_cache and access_mode != CacheMode.no_cache:
warnings.warn("Both no_cache and access_mode were used, please use access_mode only. As no_cache has been deprecated. ")
warnings.warn("Your request will be made using the default mode no_cache.")
access_mode=CacheMode.no_cache
if no_cache:
access_mode=CacheMode.no_cache
elif no_cache == False:
access_mode=CacheMode.cache
return self._volume.get_cutout(resource, resolution, x_range, y_range, z_range, time_range, id_list, access_mode, **kwargs)
|
Get a cutout from the volume service.
Note that access_mode=no_cache is desirable when reading large amounts of
data at once. In these cases, the data is not first read into the
cache, but instead, is sent directly from the data store to the
requester.
Args:
resource (intern.resource.boss.resource.ChannelResource | str): Channel or layer Resource. If a
string is provided instead, BossRemote.parse_bossURI is called instead on a URI-formatted
string of the form `bossdb://collection/experiment/channel`.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
id_list (optional [list[int]]): list of object ids to filter the cutout by.
no_cache (optional [boolean or None]): Deprecated way to specify the use of cache to be True or False.
access_mode should be used instead
access_mode (optional [Enum]): Identifies one of three cache access options:
cache = Will check both cache and for dirty keys
no_cache = Will skip cache check but check for dirty keys
raw = Will skip both the cache and dirty keys check
TODO: Add mode to documentation
Returns:
(numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
Raises:
requests.HTTPError on error.
|
entailment
|
def get_experiment(self, coll_name, exp_name):
"""
Convenience method that gets experiment resource.
Args:
coll_name (str): Collection name
exp_name (str): Experiment name
Returns:
(ExperimentResource)
"""
exp = ExperimentResource(exp_name, coll_name)
return self.get_project(exp)
|
Convenience method that gets experiment resource.
Args:
coll_name (str): Collection name
exp_name (str): Experiment name
Returns:
(ExperimentResource)
|
entailment
|
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs):
"""
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
"""
return self._volume.get_neuroglancer_link(resource, resolution, x_range, y_range, z_range, **kwargs)
|
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
Returns:
(string): Return neuroglancer link.
Raises:
RuntimeError when given invalid resource.
Other exceptions may be raised depending on the volume service's implementation.
|
entailment
|
def views(model: "Model") -> list:
"""Return a model's views keyed on what events they respond to.
Model views are added by calling :func:`view` on a model.
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
return model._model_views[:]
|
Return a model's views keyed on what events they respond to.
Model views are added by calling :func:`view` on a model.
|
entailment
|
def view(model: "Model", *functions: Callable) -> Optional[Callable]:
"""A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items, events):
for e in events:
print(e)
items.append(1)
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
def setup(function: Callable):
model._model_views.append(function)
return function
if functions:
for f in functions:
setup(f)
else:
return setup
|
A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items, events):
for e in events:
print(e)
items.append(1)
|
entailment
|
def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._before
self._before = callback
return self
|
Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
|
entailment
|
def after(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._after
self._after = callback
return self
|
Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.