code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if sanitize:
key = ''.join(_x.capitalize() for _x in re.findall(r'\S+', key))
if re.search(r'\s+', value):
value = '_'.join(re.findall(r'\S+', value))
self.user_agent_components[key] = value | def set_user_agent_component(self, key, value, sanitize=True) | Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multiple key/values are separated by a space.
- keys are camel-cased, and cannot contain spaces.
- values cannot contain spaces.
Note: When you set sanitize=false yuu need to make sure the formatting is correct yourself. | 3.342755 | 3.005181 | 1.112331 |
components = ["/".join(x) for x in self.user_agent_components.items()]
return " ".join(components) | def user_agent(self) | Return the formatted user agent string. | 6.52382 | 5.292572 | 1.232637 |
status = resp['status']
if status == 401:
return UnauthorizedError(resp)
elif status == 404:
return NotFoundError(resp)
elif status == 422:
return UnprocessableEntityError(resp)
else:
# generic fallback
return ResponseError(resp) | def factory(resp) | Return a ResponseError subclass based on the API payload.
All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes
More exceptions should be added here when appropriate, and when useful examples of API errors are available. | 2.779568 | 2.466818 | 1.126783 |
if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid order ID: '{id}'. An order ID should start with '{prefix}'.".format(
id=order_id, prefix=self.RESOURCE_ID_PREFIX)
)
result = super(Orders, self).delete(order_id, data)
return self.get_resource_object(result) | def delete(self, order_id, data=None) | Cancel order and return the order object.
Deleting an order causes the order status to change to canceled.
The updated order object is returned. | 3.323716 | 3.343928 | 0.993956 |
url = self._get_link('customer')
if url:
resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)
return Customer(resp) | def customer(self) | Return the customer for this subscription. | 6.760094 | 6.472968 | 1.044358 |
payments = self.client.subscription_payments.on(self).list()
return payments | def payments(self) | Return a list of payments for this subscription. | 15.73885 | 9.750406 | 1.614174 |
req = self.get_group_request(
'GET', 'application/json', url_prefix, auth)
if filtr is not None:
if not filtr == 'member' and not filtr == 'maintainer':
raise RuntimeError(
'filtr must be either "member", "maintainer", or None.')
req.params = {'filter': filtr}
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
resp_json = resp.json()
return resp_json['groups']
msg = ('List groups failed, got HTTP response: ({}) - {}'.format(
resp.status_code, resp.text))
raise HTTPError(msg, request = req, response = resp) | def list_groups(self, filtr, url_prefix, auth, session, send_opts) | Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
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[string]): List of group names.
Raises:
requests.HTTPError on failure. | 3.244494 | 3.142075 | 1.032596 |
req = self.get_group_request(
'DELETE', 'application/json', url_prefix, auth, name)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 204:
return
msg = ('Delete failed for group {}, got HTTP response: ({}) - {}'.format(
name, resp.status_code, resp.text))
raise HTTPError(msg, request = req, response = resp) | def delete_group(self, name, url_prefix, auth, session, send_opts) | Delete given group.
Args:
name (string): Name of group.
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:
requests.HTTPError on failure. | 3.435701 | 3.916995 | 0.877127 |
req = self.get_group_members_request(
'GET', 'application/json', url_prefix, auth, name)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
resp_json = resp.json()
return resp_json['members']
msg = ('Failed getting members of group {}, got HTTP response: ({}) - {}'.format(
name, resp.status_code, resp.text))
raise HTTPError(msg, request = req, response = resp) | def list_group_members(self, name, url_prefix, auth, session, send_opts) | Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
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[string]): List of member names.
Raises:
requests.HTTPError on failure. | 3.236516 | 3.595564 | 0.900141 |
filter_params = {}
if group_name:
filter_params["group"] = group_name
if resource:
filter_params.update(resource.get_dict_route())
req = self.get_permission_request('GET', 'application/json',
url_prefix, auth, query_params=filter_params)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code != 200:
msg = "Failed to get permission sets. "
if group_name:
msg = "{} Group: {}".format(msg, group_name)
if resource:
msg = "{} Resource: {}".format(msg, resource.name)
msg = '{}, got HTTP response: ({}) - {}'.format(msg, resp.status_code, resp.text)
raise HTTPError(msg, request=req, response=resp)
else:
return resp.json()["permission-sets"] | def list_permissions(self, group_name=None, resource=None,
url_prefix=None, auth=None, session=None, send_opts=None) | List the permission sets for the logged in user
Optionally filter by resource or group.
Args:
group_name (string): Name of group to filter on
resource (intern.resource.boss.BossResource): Identifies which data model object to filter on
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[dict]): List of dictionaries of permission sets | 3.112833 | 3.103346 | 1.003057 |
post_data = {"group": group_name,
"permissions": permissions,
}
post_data.update(resource.get_dict_route())
req = self.get_permission_request('POST', 'application/json',
url_prefix, auth, post_data=post_data)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code != 201:
msg = ('Failed adding permissions to group {}, got HTTP response: ({}) - {}'.format(group_name,
resp.status_code,
resp.text))
raise HTTPError(msg, request=req, response=resp) | def add_permissions(self, group_name, resource, permissions, url_prefix, auth, session, send_opts) | Args:
group_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.
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(). | 3.309092 | 3.373099 | 0.981024 |
filter_params = {"group": grp_name}
filter_params.update(resource.get_dict_route())
req = self.get_permission_request('DELETE', 'application/json',
url_prefix, auth, query_params=filter_params)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 204:
return
msg = ('Failed deleting permissions to group {}, got HTTP response: ({}) - {}'.format(
grp_name, resp.status_code, resp.text))
raise HTTPError(msg, request=req, response=resp) | def delete_permissions(self, grp_name, resource, url_prefix, auth, session, send_opts) | Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
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:
requests.HTTPError on failure. | 3.662884 | 3.86116 | 0.948649 |
req = self.get_user_role_request(
'GET', 'application/json', url_prefix, auth,
user)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
return resp.json()
msg = (
'Failed getting roles for user: {}, got HTTP response: ({}) - {}'
.format(user, resp.status_code, resp.text))
raise HTTPError(msg, request = req, response = resp) | def get_user_roles(self, user, url_prefix, auth, session, send_opts) | Get roles associated with the given user.
Args:
user (string): User name.
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 roles that user has.
Raises:
requests.HTTPError on failure. | 3.323765 | 3.850392 | 0.863228 |
req = self.get_user_request(
'POST', 'application/json', url_prefix, auth,
user, first_name, last_name, email, password)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 201:
return
msg = (
'Failed adding user: {}, got HTTP response: ({}) - {}'
.format(user, resp.status_code, resp.text))
raise HTTPError(msg, request = req, response = resp) | def add_user(
self, user, first_name, last_name, email, password,
url_prefix, auth, session, send_opts) | Add a new user.
Args:
user (string): User name.
first_name (string): User's first name.
last_name (string): User's last name.
email: (string): User's email address.
password: (string): User's password.
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:
requests.HTTPError on failure. | 3.130597 | 3.45677 | 0.905642 |
req = self.get_request(
resource, 'GET', 'application/json', url_prefix, auth,
proj_list_req=True)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
return self._get_resource_list(resp.json())
err = ('List failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(err, request = req, response = resp) | def list(self, resource, url_prefix, auth, session, send_opts) | List all resources of the same type as the given resource.
Args:
resource (intern.resource.boss.BossResource): List resources of the same type as this..
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 resources. Each resource is a dictionary.
Raises:
requests.HTTPError on failure. | 3.84905 | 4.393708 | 0.876037 |
# Create a copy of the resource and change its name to resource_name
# in case the update includes changing the name of a resource.
old_resource = copy.deepcopy(resource)
old_resource.name = resource_name
json = self._get_resource_params(resource, for_update=True)
req = self.get_request(old_resource, 'PUT', 'application/json', url_prefix, auth, json=json)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 200:
return self._create_resource_from_dict(resource, resp.json())
err = ('Update failed on {}, got HTTP response: ({}) - {}'.format(
old_resource.name, resp.status_code, resp.text))
raise HTTPError(err, request = req, response = resp) | def update(self, resource_name, resource, url_prefix, auth, session, send_opts) | 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.
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:
(intern.resource.boss.BossResource): Returns updated resource of given type on success.
Raises:
requests.HTTPError on failure. | 3.673215 | 3.674149 | 0.999746 |
req = self.get_request(
resource, 'DELETE', 'application/json', url_prefix, auth)
prep = session.prepare_request(req)
resp = session.send(prep, **send_opts)
if resp.status_code == 204:
return
err = ('Delete failed on {}, got HTTP response: ({}) - {}'.format(
resource.name, resp.status_code, resp.text))
raise HTTPError(err, request = req, response = resp) | def delete(self, resource, url_prefix, auth, session, send_opts) | Deletes the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
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:
requests.HTTPError on failure. | 3.324281 | 3.77289 | 0.881097 |
if isinstance(resource, CollectionResource):
return self._get_collection_params(resource)
if isinstance(resource, ExperimentResource):
return self._get_experiment_params(resource, for_update)
if isinstance(resource, CoordinateFrameResource):
return self._get_coordinate_params(resource, for_update)
if isinstance(resource, ChannelResource):
return self._get_channel_params(resource, for_update)
raise TypeError('resource is not supported type.') | def _get_resource_params(self, resource, for_update=False) | Get dictionary containing all parameters for the given resource.
When getting params for a coordinate frame update, only name and
description are returned because they are the only fields that can
be updated.
Args:
resource (intern.resource.boss.resource.BossResource): A sub-class
whose parameters will be extracted into a dictionary.
for_update (bool): True if params will be used for an update.
Returns:
(dictionary): A dictionary containing the resource's parameters as
required by the Boss API.
Raises:
TypeError if resource is not a supported class. | 2.509197 | 2.273861 | 1.103496 |
if isinstance(resource, CollectionResource):
return self._get_collection(dict)
if isinstance(resource, ExperimentResource):
return self._get_experiment(dict, resource.coll_name)
if isinstance(resource, CoordinateFrameResource):
return self._get_coordinate(dict)
if isinstance(resource, ChannelResource):
return self._get_channel(dict, resource.coll_name, resource.exp_name)
raise TypeError('resource is not supported type.') | def _create_resource_from_dict(self, resource, dict) | Args:
resource (intern.resource.boss.BossResource): Used to determine type of resource to create.
dict (dictionary): JSON data returned by the Boss API.
Returns:
(intern.resource.boss.BossResource): Instance populated with values from dict.
Raises:
KeyError if dict missing required key.
TypeError if resource is not a supported class. | 3.254555 | 3.278947 | 0.992561 |
if 'collections' in rsrc_dict:
return rsrc_dict['collections']
if 'experiments' in rsrc_dict:
return rsrc_dict['experiments']
if 'channels' in rsrc_dict:
return rsrc_dict['channels']
if 'coords' in rsrc_dict:
return rsrc_dict['coords']
raise RuntimeError('Invalid list response received from Boss. No known resource type returned.') | def _get_resource_list(self, rsrc_dict) | Extracts list of resources from the HTTP response.
Args:
rsrc_dict (dict): HTTP response encoded in a dictionary.
Returns:
(list[string]): List of a type of resource (collections, experiments, etc).
Raises:
(RuntimeError): If rsrc_dict does not contain any known resources. | 3.378302 | 2.918991 | 1.157352 |
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 | def check_version() | Tells you if you have an old version of intern. | 3.678595 | 3.257087 | 1.129412 |
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 | 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. | 6.750246 | 6.197877 | 1.089122 |
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) | 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. | 3.199993 | 3.941586 | 0.811854 |
return self.service.reserve_ids(
resource, num_ids,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 7.143125 | 9.465634 | 0.754638 |
return self.service.get_bounding_box(
resource, resolution, id, bb_type,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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]} | 5.421557 | 6.830821 | 0.79369 |
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) | 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. | 3.681455 | 4.844263 | 0.759962 |
return self.service.get_neuroglancer_link(resource, resolution, x_range, y_range, z_range, self.url_prefix, **kwargs) | 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. | 2.610605 | 3.668471 | 0.711633 |
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) | 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. | 3.851709 | 3.76899 | 1.021947 |
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 | 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. | 3.74785 | 3.692544 | 1.014978 |
datatype = resource.datatype
if "uint" in datatype:
bit_width = int(datatype.split("uint")[1])
else:
raise ValueError("Unsupported datatype: {}".format(datatype))
return bit_width | def get_bit_width(self, resource) | Method to return the bit width for blosc based on the Resource | 3.415159 | 3.463132 | 0.986147 |
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) | 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(). | 2.419612 | 2.372317 | 1.019936 |
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) | 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. | 3.494597 | 3.091805 | 1.130277 |
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) | 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. | 3.26665 | 3.075536 | 1.06214 |
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) | 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. | 2.943053 | 2.802294 | 1.05023 |
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 | 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. | 5.68215 | 5.96664 | 0.95232 |
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) | 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 | 2.638297 | 2.829049 | 0.932574 |
args = []
for arg in arglist.split(','):
arg = arg.strip()
if arg: # string is not empty
args.append(eval(arg))
return args | 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. | 3.787129 | 3.261906 | 1.161017 |
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} | def _parse_action(action) | Parses a single action item, for instance one of the following:
m; m(); m(True); m(*)
The brackets must match. | 3.199097 | 3.038278 | 1.052931 |
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 | 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. | 3.731086 | 3.708985 | 1.005959 |
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) | def print_status(self) | Provide a snapshot of the current status. | 3.135955 | 3.01208 | 1.041126 |
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) | def add_machine(self, machine) | Add the state machine to this driver. | 8.606317 | 7.31994 | 1.175736 |
self._active = True
self._max_transitions = max_transitions
self._keep_active = keep_active
self.thread = Thread(target=self._start_loop)
self.thread.start() | 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 | 2.549526 | 2.866495 | 0.889423 |
try:
self.thread.join()
except KeyboardInterrupt:
self._logger.debug('Keyboard interrupt detected, stopping driver.')
self._active = False
self._wake_queue() | def wait_until_finished(self) | Blocking method to wait until the driver finished its execution. | 8.171548 | 6.590801 | 1.239841 |
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 | def _check_timers(self) | Check for expired timers.
If there are any timers that expired, place them in the event
queue. | 4.823108 | 4.543732 | 1.061486 |
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) | 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. | 4.292672 | 3.991754 | 1.075385 |
self._logger.debug('Start timer {} in stm {}'.format(timer_id, self.id))
self._driver._start_timer(timer_id, timeout, self) | 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. | 8.023588 | 10.461576 | 0.766958 |
self._logger.debug('Stop timer {} in stm {}'.format(timer_id, self.id))
self._driver._stop_timer(timer_id, self) | def stop_timer(self, timer_id) | Stop a timer.
If the timer is not active, nothing happens. | 8.459972 | 8.990948 | 0.940943 |
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) | 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. | 8.611626 | 7.377197 | 1.16733 |
self._datatype = self.validate_datatype(value)
self._cutout_ready = True | def datatype(self, value) | Args:
value (string): 'uint8', 'uint16', 'uint64'
Raises:
ValueError | 11.783698 | 13.529829 | 0.870942 |
return self.service.list(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 9.004323 | 15.091009 | 0.596668 |
return self.service.list_groups(
filtr, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 8.75096 | 12.907773 | 0.677961 |
return self.service.get_group(
name, user_name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 7.184222 | 9.953278 | 0.721795 |
self.service.create_group(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | def create_group(self, name) | Create a new group.
Args:
name (string): Name of the group to create.
Raises:
requests.HTTPError on failure. | 10.326289 | 12.069139 | 0.855595 |
self.service.delete_group(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | def delete_group(self, name) | Delete given group.
Args:
name (string): Name of group.
Raises:
requests.HTTPError on failure. | 9.797219 | 11.648832 | 0.841047 |
return self.service.list_group_members(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 7.686241 | 11.80537 | 0.65108 |
return self.service.list_group_maintainers(
name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 7.017509 | 9.124549 | 0.76908 |
self.service.add_group_maintainer(
name, user, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 8.285875 | 10.748593 | 0.77088 |
self.service.delete_group_maintainer(
grp_name, user, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 6.768795 | 9.012046 | 0.751083 |
return self.service.list_permissions(group_name, resource,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 7.57412 | 10.489814 | 0.722045 |
self.service.add_permissions(
grp_name, resource, permissions,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 7.144793 | 8.243573 | 0.866711 |
self.service.delete_permissions(
grp_name, resource, self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 8.163277 | 9.235991 | 0.883855 |
self.service.add_user_role(
user, role,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 8.26069 | 9.913511 | 0.833276 |
return self.service.get_user_roles(
user, self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 8.315775 | 11.192713 | 0.742963 |
self.service.add_user(
user, first_name, last_name, email, password,
self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 6.486533 | 6.205016 | 1.045369 |
return self.service.get_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts) | 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. | 9.006799 | 12.258613 | 0.734732 |
self.service.delete_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts) | def delete_user(self, user) | Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure. | 10.539446 | 12.00437 | 0.877967 |
return self.service.create(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 8.737795 | 12.808826 | 0.68217 |
return self.service.get(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | 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. | 8.434607 | 13.101628 | 0.643783 |
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] | 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 | 2.566855 | 2.685353 | 0.955872 |
# 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 | 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)), ... ] | 1.783092 | 1.796842 | 0.992348 |
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) | 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. | 3.97775 | 4.591182 | 0.866389 |
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) | 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. | 4.088361 | 4.692892 | 0.871182 |
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) | 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. | 4.347859 | 4.927545 | 0.882358 |
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"
) | 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 | 3.131551 | 3.138035 | 0.997934 |
self.project_service.set_auth(self._token_project)
return self.project_service.list_groups(filtr) | 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. | 6.27864 | 9.23538 | 0.679846 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_group(name, user_name) | 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. | 5.717597 | 7.314517 | 0.781678 |
self.project_service.set_auth(self._token_project)
return self.project_service.create_group(name) | 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. | 7.222466 | 8.51048 | 0.848655 |
self.project_service.set_auth(self._token_project)
return self.project_service.delete_group(name) | def delete_group(self, name) | Delete given group.
Args:
name (string): Name of group.
Returns:
(bool): True on success.
Raises:
requests.HTTPError on failure. | 7.095147 | 8.501488 | 0.834577 |
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_members(name) | 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. | 5.798823 | 7.80607 | 0.742861 |
self.project_service.set_auth(self._token_project)
self.project_service.add_group_member(grp_name, user) | 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. | 5.8186 | 6.868574 | 0.847134 |
self.project_service.set_auth(self._token_project)
self.project_service.delete_group_member(grp_name, user) | 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. | 5.554243 | 6.602084 | 0.841286 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_is_group_member(grp_name, user) | 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. | 5.216506 | 6.762443 | 0.771394 |
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_maintainers(name) | 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. | 5.288122 | 7.330538 | 0.721383 |
self.project_service.set_auth(self._token_project)
self.project_service.add_group_maintainer(name, user) | 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. | 5.900413 | 7.307584 | 0.807437 |
self.project_service.set_auth(self._token_project)
self.project_service.delete_group_maintainer(grp_name, user) | 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. | 5.293048 | 6.502391 | 0.814016 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_is_group_maintainer(grp_name, user) | 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. | 5.01307 | 6.1221 | 0.818848 |
self.project_service.set_auth(self._token_project)
return self.project_service.list_permissions(group_name, resource) | 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. | 5.438724 | 7.137312 | 0.762013 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_permissions(grp_name, resource) | 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. | 6.03257 | 7.057653 | 0.854756 |
self.project_service.set_auth(self._token_project)
self.project_service.add_permissions(grp_name, resource, permissions) | 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. | 5.69112 | 6.334089 | 0.898491 |
self.project_service.set_auth(self._token_project)
self.project_service.update_permissions(grp_name, resource, permissions) | 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. | 5.802916 | 6.294782 | 0.921861 |
self.project_service.set_auth(self._token_project)
self.project_service.delete_permissions(grp_name, resource) | 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. | 6.034352 | 6.881392 | 0.876909 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_roles(user) | 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. | 7.181656 | 7.758582 | 0.92564 |
self.project_service.set_auth(self._token_project)
self.project_service.add_user_role(user, role) | 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. | 6.622687 | 7.325322 | 0.904081 |
self.project_service.set_auth(self._token_project)
self.project_service.delete_user_role(user, role) | 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. | 6.179707 | 7.127164 | 0.867064 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_user(user) | 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. | 7.195346 | 9.297421 | 0.773908 |
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_groups(user) | 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. | 6.87366 | 7.766927 | 0.884991 |
self.project_service.set_auth(self._token_project)
self.project_service.add_user(
user, first_name, last_name, email, password) | 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. | 4.718348 | 5.548251 | 0.850421 |
self.project_service.set_auth(self._token_project)
self.project_service.delete_user(user) | def delete_user(self, user) | Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure. | 7.906624 | 9.050507 | 0.873611 |
self.project_service.set_auth(self._token_project)
return super(BossRemote, self).list_project(resource=resource) | 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. | 15.51827 | 14.909971 | 1.040798 |
exp = ExperimentResource(
name='', collection_name=collection_name, coord_frame='foo')
return self._list_resource(exp) | 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. | 14.790358 | 22.371504 | 0.661125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.