INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return parent of * index *. | def parent(self, index):
'''Return parent of *index*.'''
if not index.isValid():
return QModelIndex()
item = index.internalPointer()
if not item:
return QModelIndex()
parent = item.parent
if not parent or parent == self.root:
return Q... |
Return data for * index * according to * role *. | def data(self, index, role):
'''Return data for *index* according to *role*.'''
if not index.isValid():
return None
column = index.column()
item = index.internalPointer()
if role == self.ITEM_ROLE:
return item
elif role == Qt.DisplayRole:
... |
Return label for * section * according to * orientation * and * role *. | def headerData(self, section, orientation, role):
'''Return label for *section* according to *orientation* and *role*.'''
if orientation == Qt.Horizontal:
if section < len(self.columns):
column = self.columns[section]
if role == Qt.DisplayRole:
... |
Return if * index * has children. | def hasChildren(self, index):
'''Return if *index* has children.
Optimised to avoid loading children at this stage.
'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
if not item:
return False
... |
Return if more data available for * index *. | def canFetchMore(self, index):
'''Return if more data available for *index*.'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
return item.canFetchMore() |
Fetch additional data under * index *. | def fetchMore(self, index):
'''Fetch additional data under *index*.'''
if not index.isValid():
item = self.root
else:
item = index.internalPointer()
if item.canFetchMore():
startIndex = len(item.children)
additionalChildren = item.fetchChi... |
Return ordering of * left * vs * right *. | def lessThan(self, left, right):
'''Return ordering of *left* vs *right*.'''
sourceModel = self.sourceModel()
if sourceModel:
leftItem = sourceModel.item(left)
rightItem = sourceModel.item(right)
if (isinstance(leftItem, Directory)
and not isi... |
Return index of item with * path *. | def pathIndex(self, path):
'''Return index of item with *path*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return QModelIndex()
return self.mapFromSource(sourceModel.pathIndex(path)) |
Return item at * index *. | def item(self, index):
'''Return item at *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.item(self.mapToSource(index)) |
Return icon for index. | def icon(self, index):
'''Return icon for index.'''
sourceModel = self.sourceModel()
if not sourceModel:
return None
return sourceModel.icon(self.mapToSource(index)) |
Return if * index * has children. | def hasChildren(self, index):
'''Return if *index* has children.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.hasChildren(self.mapToSource(index)) |
Return if more data available for * index *. | def canFetchMore(self, index):
'''Return if more data available for *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.canFetchMore(self.mapToSource(index)) |
Fetch additional data under * index *. | def fetchMore(self, index):
'''Fetch additional data under *index*.'''
sourceModel = self.sourceModel()
if not sourceModel:
return False
return sourceModel.fetchMore(self.mapToSource(index)) |
Return appropriate icon for * specification *. | def icon(self, specification):
'''Return appropriate icon for *specification*.
*specification* should be either:
* An instance of :py:class:`riffle.model.Item`
* One of the defined icon types (:py:class:`IconType`)
'''
if isinstance(specification, riffle.model.... |
Return appropriate icon type for * item *. | def type(self, item):
'''Return appropriate icon type for *item*.'''
iconType = IconType.Unknown
if isinstance(item, riffle.model.Computer):
iconType = IconType.Computer
elif isinstance(item, riffle.model.Mount):
iconType = IconType.Mount
elif isinstanc... |
Run an external command in a separate process and detach it from the current process. Excepting stdout stderr and stdin all file descriptors are closed after forking. If daemonize is True then the parent process exits. All stdio is redirected to os. devnull unless specified. The preexec_fn shell cwd and env parameters ... | def call(args, stdout=None, stderr=None, stdin=None, daemonize=False,
preexec_fn=None, shell=False, cwd=None, env=None):
"""
Run an external command in a separate process and detach it from the current process. Excepting
`stdout`, `stderr`, and `stdin` all file descriptors are closed after forking.... |
Return the maximum file descriptor value. | def _get_max_fd(self):
"""Return the maximum file descriptor value."""
limits = resource.getrlimit(resource.RLIMIT_NOFILE)
result = limits[1]
if result == resource.RLIM_INFINITY:
result = maxfd
return result |
Close a file descriptor if it is open. | def _close_fd(self, fd):
"""Close a file descriptor if it is open."""
try:
os.close(fd)
except OSError, exc:
if exc.errno != errno.EBADF:
msg = "Failed to close file descriptor {}: {}".format(fd, exc)
raise Error(msg) |
Close open file descriptors. | def _close_open_fds(self):
"""Close open file descriptors."""
maxfd = self._get_max_fd()
for fd in reversed(range(maxfd)):
if fd not in self.exclude_fds:
self._close_fd(fd) |
Redirect a system stream to the provided target. | def _redirect(self, stream, target):
"""Redirect a system stream to the provided target."""
if target is None:
target_fd = os.open(os.devnull, os.O_RDWR)
else:
target_fd = target.fileno()
os.dup2(target_fd, stream.fileno()) |
Applies a given HTML attributes to each field widget of a given form. | def set_form_widgets_attrs(form, attrs):
"""Applies a given HTML attributes to each field widget of a given form.
Example:
set_form_widgets_attrs(my_form, {'class': 'clickable'})
"""
for _, field in form.fields.items():
attrs_ = dict(attrs)
for name, val in attrs.items():
... |
Returns a certain model as defined in a string formatted <app_name >. <model_name >. | def get_model_class_from_string(model_path):
"""Returns a certain model as defined in a string formatted `<app_name>.<model_name>`.
Example:
model = get_model_class_from_string('myapp.MyModel')
"""
try:
app_name, model_name = model_path.split('.')
except ValueError:
raise ... |
Tries to get a site URL from environment and settings in the following order: | def get_site_url(request=None):
"""Tries to get a site URL from environment and settings
in the following order:
1. (SITE_PROTO / SITE_SCHEME) + SITE_DOMAIN
2. SITE_URL
3. Django Sites contrib
4. Request object
:param HttpRequest request: Request object to deduce URL from.
:rtype: str
... |
Returns a module from a given app by its name. | def import_app_module(app_name, module_name):
"""Returns a module from a given app by its name.
:param str app_name:
:param str module_name:
:rtype: module or None
"""
name_split = app_name.split('.')
if name_split[-1][0].isupper(): # Seems that we have app config class path here.
... |
Imports modules from registered apps using given module name and returns them as a list. | def import_project_modules(module_name):
"""Imports modules from registered apps using given module name
and returns them as a list.
:param str module_name:
:rtype: list
"""
from django.conf import settings
submodules = []
for app in settings.INSTALLED_APPS:
module = import_ap... |
Similar to built - in include template tag but allowing template variables to be used in template name and a fallback template thus making the tag more dynamic. | def include_(parser, token):
"""Similar to built-in ``include`` template tag, but allowing
template variables to be used in template name and a fallback template,
thus making the tag more dynamic.
.. warning:: Requires Django 1.8+
Example:
{% load etc_misc %}
{% include_ "sub_{{ p... |
Return a list of all repository objects in the repofiles in the repo folder specified: return: | def repositories(self):
"""
Return a list of all repository objects in the repofiles in the repo folder specified
:return:
"""
for repo_path in self.path.glob('*.repo'):
for id, repository in self._get_repo_file(repo_path).repositories:
yield id, repos... |
Lazy load RepoFile objects on demand.: param repo_path:: return: | def _get_repo_file(self, repo_path):
"""
Lazy load RepoFile objects on demand.
:param repo_path:
:return:
"""
if repo_path not in self._repo_files:
self._repo_files[repo_path] = RepoFile(repo_path)
return self._repo_files[repo_path] |
Given a URL return a package: param url:: return: | def from_url(url):
"""
Given a URL, return a package
:param url:
:return:
"""
package_data = HTTPClient().http_request(url=url, decode=None)
return Package(raw_data=package_data) |
Read the contents of the rpm itself: return: | def dependencies(self):
"""
Read the contents of the rpm itself
:return:
"""
cpio = self.rpm.gzip_file.read()
content = cpio.read()
return [] |
Returns Gravatar image URL for a given string or UserModel. | def gravatar_get_url(obj, size=65, default='identicon'):
"""Returns Gravatar image URL for a given string or UserModel.
Example:
{% load gravatar %}
{% gravatar_get_url user_model %}
:param UserModel, str obj:
:param int size:
:param str default:
:return:
"""
return ge... |
Returns Gravatar image HTML tag for a given string or UserModel. | def gravatar_get_img(obj, size=65, default='identicon'):
"""Returns Gravatar image HTML tag for a given string or UserModel.
Example:
{% load gravatar %}
{% gravatar_get_img user_model %}
:param UserModel, str obj:
:param int size:
:param str default:
:return:
"""
url ... |
Parses an xml_path with the inherited xml parser: param xml_path:: return: | def parse(cls, xml_path):
"""
Parses an xml_path with the inherited xml parser
:param xml_path:
:return:
"""
parser = etree.XMLParser(target=cls.xml_parse())
return etree.parse(xml_path, parser) |
Load the repo database from the remote source and then parse it.: return: | def load(self):
"""
Load the repo database from the remote source, and then parse it.
:return:
"""
data = self.http_request(self.location())
self._parse(data)
return self |
Register a task for a python dict: param task_def: dict defining gbdx task | def register_task(self, task_def):
'''
Register a task for a python dict
:param task_def: dict defining gbdx task
'''
r = self.session.post(
self.task_url,
data=task_def,
headers={'Content-Type': 'application/json', 'Accept': 'application/json'... |
Delete a task from the platforms regoistry: param task_name: name of the task to delete | def delete_task(self, task_name):
'''
Delete a task from the platforms regoistry
:param task_name: name of the task to delete
'''
response = self.session.delete('%s/%s' % (self.task_url, task_name))
if response.status_code == 200:
return response.status_code,... |
Get input string port value: param port_name:: param default:: return:: rtype: | def get_input_string_port(self, port_name, default=None):
"""
Get input string port value
:param port_name:
:param default:
:return: :rtype:
"""
if self.__string_input_ports:
return self.__string_input_ports.get(port_name, default)
return defau... |
Set output string port value: param port_name:: param value:: return:: rtype: | def set_output_string_port(self, port_name, value):
"""
Set output string port value
:param port_name:
:param value:
:return: :rtype:
"""
if not self.__string_output_ports:
self.__string_output_ports = {}
self.__string_output_ports[port_name] ... |
: param success_or_fail: string that is success or fail: param message: | def finalize(self, success_or_fail, message=''):
"""
:param success_or_fail: string that is 'success' or 'fail'
:param message:
"""
self.logit.debug('String OutputPorts: %s' % self.__string_output_ports)
if self.__string_output_ports:
with open(os.path.join(se... |
List the ports contents by file type or all.: param extensions: string extensions single string or list of extensions.: return: A list of full path names of each file. | def list_files(self, extensions=None):
"""
List the ports contents by file type or all.
:param extensions: string extensions, single string or list of extensions.
:return: A list of full path names of each file.
"""
if self.type.lower() != 'directory':
raise V... |
Checks if the path is correct and exists must be abs - > a dir - > and not a file. | def is_valid_filesys(path):
"""Checks if the path is correct and exists, must be abs-> a dir -> and not a file."""
if os.path.isabs(path) and os.path.isdir(path) and \
not os.path.isfile(path):
return True
else:
raise LocalPortValidationError(
... |
Checks if the url contains S3. Not an accurate validation of the url | def is_valid_s3_url(url):
"""Checks if the url contains S3. Not an accurate validation of the url"""
# Skip if the url start with source: (gbdxtools syntax)
if url.startswith('source:'):
return True
scheme, netloc, path, _, _, _ = urlparse(url)
port_except = RemoteP... |
Execute the command from the arguments.: return: None or Error | def invoke(self):
"""
Execute the command from the arguments.
:return: None or Error
"""
for key in self.FUNCTION_KEYS.keys():
if self._arguments[key] is True:
self.FUNCTION_KEYS[key]() |
Register the anonymouse task or overwrite it.: return: success or fail message. | def _register_anonymous_task(self):
"""
Register the anonymouse task or overwrite it.
:return: success or fail message.
"""
is_overwrite = self._arguments.get('--overwrite')
task_name = "CloudHarness_Anonymous_Task"
task_srv = TaskService()
if is_overwri... |
Method for creating a new Application Template. USAGE: cloud - harness create <dir_name > [ -- destination = <path > ] | def _create_app(self):
"""
Method for creating a new Application Template.
USAGE: cloud-harness create <dir_name> [--destination=<path>]
"""
template_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), self.TEMPLATE_FOLDER, self.TEMPLATE_... |
Method for running a custom Application Templates. NOTES: * The default name of the application is app. py. So this function is going to look for app. py unless the -- file option is provide with a different file name. * The generated source bundle will package everything in the work_path. If large files not required f... | def _run_app(self):
"""
Method for running a custom Application Templates.
NOTES:
* The default name of the application is app.py. So this function is going to look
for app.py, unless the --file option is provide with a different file name.
* The generated sou... |
Write a config file to the source bundle location to identify the entry point.: param template_file: path to the task template subclass ( executable ) | def _write_config_file(template_file):
"""
Write a config file to the source bundle location to identify the entry point.
:param template_file: path to the task template subclass (executable)
"""
config_filename = '.cloud_harness_config.json'
config_path = os.path.dirname... |
Import the file and inspect for subclass of TaskTemplate.: param template_file: filename to import. | def _get_class(template_file):
"""
Import the file and inspect for subclass of TaskTemplate.
:param template_file: filename to import.
"""
with warnings.catch_warnings():
# suppress warning from importing
warnings.filterwarnings("ignore", category=RuntimeW... |
Return a valid absolute path. filename can be relative or absolute. | def _get_template_abs_path(filename):
"""
Return a valid absolute path. filename can be relative or absolute.
"""
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
else:
return os.path.join(os.getcwd(), filename) |
Upload a list of files to a users account location: param source_files: list of files to upload or single file name: param s3_folder: the user location to upload to. | def upload(self, source_files, s3_folder=None):
"""
Upload a list of files to a users account location
:param source_files: list of files to upload, or single file name
:param s3_folder: the user location to upload to.
"""
if s3_folder is None:
folder = self.... |
download all files from a users account location: param local_port_path: the local path where the data is to download to: param key_name: can start with self. prefix or taken as relative to prefix. | def download(self, local_port_path, key_names): # pragma: no cover
"""
download all files from a users account location
:param local_port_path: the local path where the data is to download to
:param key_name: can start with self.prefix or taken as relative to prefix.
Example:
... |
Get a list of keys for the accounts | def list(self, s3_folder='', full_key_data=False):
"""Get a list of keys for the accounts"""
if not s3_folder.startswith('/'):
s3_folder = '/' + s3_folder
s3_prefix = self.prefix + s3_folder
bucket_data = self.client.list_objects(Bucket=self.bucket, Prefix=s3_prefix)
... |
Build a workflow definition from the cloud_harness task. | def _build_worklfow_json(self):
"""
Build a workflow definition from the cloud_harness task.
"""
wf_json = {'tasks': [], 'name': 'cloud-harness_%s' % str(uuid.uuid4())}
task_def = json.loads(self.task_template.json())
d = {
"name": task_def['name'],
... |
Execute the cloud_harness task. | def execute(self, override_wf_json=None):
"""
Execute the cloud_harness task.
"""
r = self.gbdx.post(
self.URL,
json=self.json if override_wf_json is None else override_wf_json
)
try:
r.raise_for_status()
except:
pr... |
Monitor the workflows events and display spinner while running.: param workflow: the workflow object | def monitor_run(self): # pragma: no cover
"""
Monitor the workflows events and display spinner while running.
:param workflow: the workflow object
"""
spinner = itertools.cycle(['-', '/', '|', '\\'])
while not self.complete:
for i in xrange(300):
... |
: param success_or_fail: string that is success or fail: param message: | def finalize(self, success_or_fail, message=''):
"""
:param success_or_fail: string that is 'success' or 'fail'
:param message:
"""
if not self.__remote_run:
return json.dumps({'status': success_or_fail, 'reason': message}, indent=4)
else:
super(Ta... |
Iterate through the task outputs. Two scenarios: - User is running locally check that output folders exist. - User is running remotely when docker container runs filesystem check that output folders exist. - Else do nothing.: return: None | def check_and_create_outputs(self):
"""
Iterate through the task outputs.
Two scenarios:
- User is running locally, check that output folders exist.
- User is running remotely, when docker container runs filesystem, check that output folders exist.
- Else, do ... |
Takes the workflow value for each port and does the following: * If local filesystem - > Uploads locally files to s3. S3 location will be as follows: gbd - customer - data/ <acct_id >/ <workflow_name >/ <task_name >/ <port_name >/ * If S3 url - > do nothing.: returns the update workflow with S3 urls. | def upload_input_ports(self, port_list=None, exclude_list=None):
"""
Takes the workflow value for each port and does the following:
* If local filesystem -> Uploads locally files to s3.
S3 location will be as follows:
gbd-customer-data/<acct_id>/<workflow_... |
Find files for the local_path and return tuples of filename and keynames: param local_path: the local path to search for files: param prefix: the S3 prefix for each key name on S3 | def _get_port_files(local_path, prefix):
"""
Find files for the local_path and return tuples of filename and keynames
:param local_path: the local path to search for files
:param prefix: the S3 prefix for each key name on S3
"""
source_files = []
for root, dirs, ... |
Move an active project to the archive. | def archive(folder, dry_run=False):
"Move an active project to the archive."
# error handling on archive_dir already done in main()
for f in folder:
if not os.path.exists(f):
bail('folder does not exist: ' + f)
_archive_safe(folder, PROJ_ARCHIVE, dry_run=dry_run) |
The equivalent of mkdir - p in shell. | def _mkdir(p):
"The equivalent of 'mkdir -p' in shell."
isdir = os.path.isdir
stack = [os.path.abspath(p)]
while not isdir(stack[-1]):
parent_dir = os.path.dirname(stack[-1])
stack.append(parent_dir)
while stack:
p = stack.pop()
if not isdir(p):
os.mkdir... |
List the contents of the archive directory. | def list(pattern=()):
"List the contents of the archive directory."
# strategy: pick the intersection of all the patterns the user provides
globs = ['*{0}*'.format(p) for p in pattern] + ['*']
matches = []
offset = len(PROJ_ARCHIVE) + 1
for suffix in globs:
glob_pattern = os.path.join(P... |
Restore a project from the archive. | def restore(folder):
"Restore a project from the archive."
if os.path.isdir(folder):
bail('a folder of the same name already exists!')
pattern = os.path.join(PROJ_ARCHIVE, '*', '*', folder)
matches = glob.glob(pattern)
if not matches:
bail('no project matches: ' + folder)
if le... |
Create new storage service client. | def new(cls, access_token, environment='prod'):
'''Create new storage service client.
Arguments:
environment(str): The service environment to be used for the client.
'prod' or 'dev'.
access_token(str): The access token used to authenticate with th... |
List the entities found directly under the given path. | def list(self, path):
'''List the entities found directly under the given path.
Args:
path (str): The path of the entity to be listed. Must start with a '/'.
Returns:
The list of entity names directly under the given path:
u'/12345/folder_1'
Ra... |
Download a file from storage service to local disk. | def download_file(self, path, target_path):
'''Download a file from storage service to local disk.
Existing files on the target path will be overwritten.
The download is not recursive, as it only works on files.
Args:
path (str): The path of the entity to be downloaded. Mus... |
Check if a certain path exists in the storage service. | def exists(self, path):
'''Check if a certain path exists in the storage service.
Args:
path (str): The path to be checked
Returns:
True if the path exists, False otherwise
Raises:
StorageArgumentException: Invalid arguments
StorageForbi... |
Get the parent entity of the entity pointed by the given path. | def get_parent(self, path):
'''Get the parent entity of the entity pointed by the given path.
Args:
path (str): The path of the entity whose parent is needed
Returns:
A JSON object of the parent entity if found.
Raises:
StorageArgumentException: Inv... |
Create a folder in the storage service pointed by the given path. | def mkdir(self, path):
'''Create a folder in the storage service pointed by the given path.
Args:
path (str): The path of the folder to be created
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForbiddenExceptio... |
Upload local file content to a storage service destination folder. | def upload_file(self, local_file, dest_path, mimetype):
'''Upload local file content to a storage service destination folder.
Args:
local_file(str)
dest_path(str):
absolute Storage service path '/project' prefix is essential
su... |
Delete an entity from the storage service using its path. | def delete(self, path):
''' Delete an entity from the storage service using its path.
Args:
path(str): The path of the entity to be delete
Returns:
The uuid of created file entity as string
Raises:
StorageArgumentException: I... |
Validate a string as a valid storage path | def __validate_storage_path(cls, path, projects_allowed=True):
'''Validate a string as a valid storage path'''
if not path or not isinstance(path, str) or path[0] != '/' or path == '/':
raise StorageArgumentException(
'The path must be a string, start with a slash (/), and b... |
Check cloud - harness code is valid. task schema validation is left to the API endpoint.: param remote: Flag indicating if the task is being ran on the platform or not.: return: is valid or not. | def is_valid(self, remote=False):
"""
Check cloud-harness code is valid. task schema validation is
left to the API endpoint.
:param remote: Flag indicating if the task is being ran on the platform or not.
:return: is valid or not.
"""
if len(self.input_ports) < 1... |
This function computes a graph of nearest - neighbors for each sample point in data and returns the median of the distribution of distances between those nearest - neighbors the distance metric being specified by metric. Parameters ---------- data: array of shape ( n_samples n_features ) The data - set a fraction of wh... | def median_min_distance(data, metric):
"""This function computes a graph of nearest-neighbors for each sample point in
'data' and returns the median of the distribution of distances between those
nearest-neighbors, the distance metric being specified by 'metric'.
Parameters
----------
... |
For each sample point of the data - set data estimate a local density in feature space by counting the number of neighboring data - points within a particular region centered around that sample point. Parameters ---------- data: array of shape ( n_samples n_features ) The data - set a fraction of whose sample points wi... | def get_local_densities(data, kernel_mult = 2.0, metric = 'manhattan'):
"""For each sample point of the data-set 'data', estimate a local density in feature
space by counting the number of neighboring data-points within a particular
region centered around that sample point.
Parameters
-... |
The i - th sample point of the data - set data is selected by density sampling with a probability given by: | 0 if outlier_density > LD [ i ] ; P ( keep the i - th data - point ) = | 1 if outlier_density < = LD [ i ] < = target_density ; | target_density/ LD [ i ] if LD [ i ] > target_density. Here LD [ i ] denotes the... | def density_sampling(data, local_densities = None, metric = 'manhattan',
kernel_mult = 2.0, outlier_percentile = 0.01,
target_percentile = 0.05, desired_samples = None):
"""The i-th sample point of the data-set 'data' is selected by density sampling
with a probabi... |
Creates a new cross - service client. | def new(cls, access_token, environment='prod'):
'''Creates a new cross-service client.'''
return cls(
storage_client=StorageClient.new(access_token, environment=environment)) |
Create a new storage service REST client. | def new(cls, access_token, environment='prod'):
'''Create a new storage service REST client.
Arguments:
environment: The service environment to be used for the client
access_token: The access token used to authenticate with the
service
... |
Remove empty ( None ) valued keywords and self from function parameters | def _prep_params(params):
'''Remove empty (None) valued keywords and self from function parameters'''
return {k: v for (k, v) in params.items() if v is not None and k != 'self'} |
Get generic entity by UUID. | def get_entity_details(self, entity_id):
'''Get generic entity by UUID.
Args:
entity_id (str): The UUID of the requested entity.
Returns:
A dictionary describing the entity::
{
u'collab_id': 2271,
u'created_by':... |
Retrieve entity by query param which can be either uuid/ path/ metadata. | def get_entity_by_query(self, uuid=None, path=None, metadata=None):
'''Retrieve entity by query param which can be either uuid/path/metadata.
Args:
uuid (str): The UUID of the requested entity.
path (str): The path of the requested entity.
metadata (dict): A dictiona... |
Set metadata for an entity. | def set_metadata(self, entity_type, entity_id, metadata):
'''Set metadata for an entity.
Args:
entity_type (str): Type of the entity. Admitted values: ['project',
'folder', 'file'].
entity_id (str): The UUID of the entity to be modified.
metadata (dic... |
Get metadata of an entity. | def get_metadata(self, entity_type, entity_id):
'''Get metadata of an entity.
Args:
entity_type (str): Type of the entity. Admitted values: ['project',
'folder', 'file'].
entity_id (str): The UUID of the entity to be modified.
Returns:
A dict... |
Update the metadata of an entity. | def update_metadata(self, entity_type, entity_id, metadata):
'''Update the metadata of an entity.
Existing non-modified metadata will not be affected.
Args:
entity_type (str): Type of the entity. Admitted values: 'project',
'folder', 'file'.
entity_id (s... |
Delete the selected metadata entries of an entity. | def delete_metadata(self, entity_type, entity_id, metadata_keys):
'''Delete the selected metadata entries of an entity.
Only deletes selected metadata keys, for a complete wipe, use set_metadata.
Args:
entity_type (str): Type of the entity. Admitted values: ['project',
... |
List all the projects the user have access to. | def list_projects(self, hpc=None, access=None, name=None, collab_id=None,
page_size=DEFAULT_PAGE_SIZE, page=None, ordering=None):
'''List all the projects the user have access to.
This function does not retrieve all results, pages have
to be manually retrieved by t... |
Get information on a given project | def get_project_details(self, project_id):
'''Get information on a given project
Args:
project_id (str): The UUID of the requested project.
Returns:
A dictionary describing the project::
{
u'collab_id': 2271,
u'created_by': u... |
Create a new project. | def create_project(self, collab_id):
'''Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
... |
Delete a project. It will recursively delete all the content. | def delete_project(self, project):
'''Delete a project. It will recursively delete all the content.
Args:
project (str): The UUID of the project to be deleted.
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForb... |
Create a new folder. | def create_folder(self, name, parent):
'''Create a new folder.
Args:
name (srt): The name of the folder.
parent (str): The UUID of the parent entity. The parent must be a
project or a folder.
Returns:
A dictionary of details of the created fo... |
Get information on a given folder. | def get_folder_details(self, folder):
'''Get information on a given folder.
Args:
folder (str): The UUID of the requested folder.
Returns:
A dictionary of the folder details if found::
{
u'created_by': u'303447',
... |
List files and folders ( not recursively ) contained in the folder. | def list_folder_content(self, folder, name=None, entity_type=None,
content_type=None, page_size=DEFAULT_PAGE_SIZE,
page=None, ordering=None):
'''List files and folders (not recursively) contained in the folder.
This function does not retrieve all ... |
Delete a folder. It will recursively delete all the content. | def delete_folder(self, folder):
'''Delete a folder. It will recursively delete all the content.
Args:
folder_id (str): The UUID of the folder to be deleted.
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForbid... |
Upload a file content. The file entity must already exist. | def upload_file_content(self, file_id, etag=None, source=None, content=None):
'''Upload a file content. The file entity must already exist.
If an ETag is provided the file stored on the server is verified
against it. If it does not match, StorageException is raised.
This means the clien... |
Copy file content from source file to target file. | def copy_file_content(self, file_id, source_file):
'''Copy file content from source file to target file.
Args:
file_id (str): The UUID of the file whose content is written.
source_file (str): The UUID of the file whose content is copied.
Returns:
None
... |
Download file content. | def download_file_content(self, file_id, etag=None):
'''Download file content.
Args:
file_id (str): The UUID of the file whose content is requested
etag (str): If the content is not changed since the provided ETag,
the content won't be downloaded. If the content ... |
Get a signed unauthenticated URL. | def get_signed_url(self, file_id):
'''Get a signed unauthenticated URL.
It can be used to download the file content without the need for a
token. The signed URL expires after 5 seconds.
Args:
file_id (str): The UUID of the file to get the link for.
Returns:
... |
Delete a file. | def delete_file(self, file_id):
'''Delete a file.
Args:
file_id (str): The UUID of the file to delete.
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForbiddenException: Server response code 403
Stor... |
pymongo expects a dict | def emit(self, record):
""" pymongo expects a dict """
msg = self.format(record)
if not isinstance(msg, dict):
msg = json.loads(msg)
self.collection.insert(msg) |
Sets the service name and version the request should target | def to_service(self, service, version):
'''Sets the service name and version the request should target
Args:
service (str): The name of the service as displayed in the services.json file
version (str): The version of the service as displayed in the services.json file
Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.