Search is not available for this dataset
text stringlengths 75 104k |
|---|
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
... |
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.
... |
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... |
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... |
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... |
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] |
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) |
def dependencies(self):
"""
Read the contents of the rpm itself
:return:
"""
cpio = self.rpm.gzip_file.read()
content = cpio.read()
return [] |
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... |
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 ... |
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) |
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 |
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'... |
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,... |
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... |
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] ... |
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... |
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... |
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(
... |
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... |
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]() |
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... |
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_... |
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... |
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... |
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... |
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) |
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.... |
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:
... |
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)
... |
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'],
... |
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... |
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):
... |
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... |
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 ... |
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_... |
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, ... |
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) |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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
----------
... |
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
-... |
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... |
def new(cls, access_token, environment='prod'):
'''Creates a new cross-service client.'''
return cls(
storage_client=StorageClient.new(access_token, environment=environment)) |
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
... |
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'} |
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':... |
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... |
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... |
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... |
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... |
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',
... |
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... |
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... |
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,
... |
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... |
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... |
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',
... |
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 ... |
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... |
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... |
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
... |
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 ... |
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:
... |
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... |
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) |
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... |
def with_headers(self, headers):
'''Adds headers to the request
Args:
headers (dict): The headers to add the request headers
Returns:
The request builder instance in order to chain calls
'''
copy = headers.copy()
copy.update(self._headers)
... |
def with_params(self, params):
'''Adds parameters to the request params
Args:
params (dict): The parameters to add to the request params
Returns:
The request builder instance in order to chain calls
'''
copy = params.copy()
copy.update(self._para... |
def throw(self, exception_class, should_throw):
'''Defines if the an exception should be thrown after the request is sent
Args:
exception_class (class): The class of the exception to instantiate
should_throw (function): The predicate that should indicate if the exception
... |
def run_command(cmd):
"""
Run the command, piping stderr to stdout.
Sends output to stdout.
:param cmd: The list for args to pass to the process
"""
try:
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr... |
def extract_source(bundle_path, source_path):
"""
Extract the source bundle
:param bundle_path: path to the aource bundle *.tar.gz
:param source_path: path to location where to extractall
"""
with tarfile.open(bundle_path, 'r:gz') as tf:
tf.extractall(path=source_path)
logger.debug("... |
def printer(data):
"""
response is json or straight text.
:param data:
:return:
"""
data = str(data) # Get rid of unicode
if not isinstance(data, str):
output = json.dumps(
data,
sort_keys=True,
indent=4,
separators=(',', ': ')
... |
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
list_display = []
for field_name in self.list_display:
try:
db_field = self.model._meta.get_field(field_name)
... |
def map_job(job, func, inputs, *args):
"""
Spawns a tree of jobs to avoid overloading the number of jobs spawned by a single parent.
This function is appropriate to use when batching samples greater than 1,000.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param function func: Fu... |
def gatk_genotype_gvcfs(job,
gvcfs,
ref, fai, ref_dict,
annotations=None,
emit_threshold=10.0, call_threshold=30.0,
unsafe_mode=False):
"""
Runs GenotypeGVCFs on one or more gVCFs generated by... |
def run_oncotator(job, vcf_id, oncotator_db):
"""
Uses Oncotator to add cancer relevant variant annotations to a VCF file. Oncotator can accept
other genome builds, but the output VCF is based on hg19.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str vcf_id: FileStoreID fo... |
def sort(self, f=lambda d: d["t"]):
"""Sort here works by sorting by timestamp by default"""
list.sort(self, key=f)
return self |
def t(self):
"""Returns just the timestamp portion of the datapoints as a list.
The timestamps are in python datetime's date format."""
return list(map(lambda x: datetime.datetime.fromtimestamp(x["t"]), self.raw())) |
def writeJSON(self, filename):
"""Writes the data to the given file::
DatapointArray([{"t": unix timestamp, "d": data}]).writeJSON("myfile.json")
The data can later be loaded using loadJSON.
"""
with open(filename, "w") as f:
json.dump(self, f) |
def loadJSON(self, filename):
"""Adds the data from a JSON file. The file is expected to be in datapoint format::
d = DatapointArray().loadJSON("myfile.json")
"""
with open(filename, "r") as f:
self.merge(json.load(f))
return self |
def loadExport(self, folder):
"""Adds the data from a ConnectorDB export. If it is a stream export, then the folder
is the location of the export. If it is a device export, then the folder is the export folder
with the stream name as a subdirectory
If it is a user export, you will use t... |
def tshift(self, t):
"""Shifts all timestamps in the datapoint array by the given number of seconds.
It is the same as the 'tshift' pipescript transform.
Warning: The shift is performed in-place! This means that it modifies the underlying array::
d = DatapointArray([{"t":56,"d":1}]... |
def sum(self):
"""Gets the sum of the data portions of all datapoints within"""
raw = self.raw()
s = 0
for i in range(len(raw)):
s += raw[i]["d"]
return s |
def rfxcom(device):
"""Start the event loop to collect data from the serial device."""
# If the device isn't passed in, look for it in the config.
if device is None:
device = app.config.get('DEVICE')
# If the device is *still* none, error.
if device is None:
print("The serial devic... |
def create_user(username):
"Create a new user."
password = prompt_pass("Enter password")
user = User(username=username, password=password)
db.session.add(user)
db.session.commit() |
def to_iri(iri):
"""
Safely quotes an IRI in a way that is resilient to unicode and incorrect
arguments (checks for RFC 3987 compliance and falls back to percent encoding)
"""
# First decode the IRI if needed (python 2)
if sys.version_info[0] < 3:
if not isinstance(iri, unicode):
... |
async def parse_vn_results(soup):
"""
Parse Visual Novel search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a name and id.
"""
soup = soup.find_all('td', class_='tc1')
vns = []
for item in soup[1:]:
vns.append({'name': item.string, 'id': ... |
async def parse_release_results(soup):
"""
Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group and Name.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.