Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_deployment_timestamp(): # TODO: Support other deployment situations. if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): version_id = os.environ.get('CURRENT_VERSION_ID') major_version, timestamp = version_id.split('...
[ "Returns a unique string represeting the current deployment.\n\n Used for busting caches.\n " ]
Please provide a description of the function:def register(coordinator): if FLAGS.phantomjs_script: utils.verify_binary('phantomjs_binary', ['--version']) assert os.path.exists(FLAGS.phantomjs_script) else: utils.verify_binary('capture_binary', ['--version']) assert FLAGS.ca...
[ "Registers this module as a worker with the given coordinator." ]
Please provide a description of the function:def real_main(new_url=None, baseline_url=None, upload_build_id=None, upload_release_name=None): coordinator = workers.get_coordinator() fetch_worker.register(coordinator) coordinator.start() item = UrlPairDiff( ...
[ "Runs the ur_pair_diff." ]
Please provide a description of the function:def fetch_internal(item, request): # Break client dependence on Flask if internal fetches aren't being used. from flask import make_response from werkzeug.test import EnvironBuilder # Break circular dependencies. from dpxdt.server import app # A...
[ "Fetches the given request by using the local Flask context." ]
Please provide a description of the function:def fetch_normal(item, request): try: conn = urllib2.urlopen(request, timeout=item.timeout_seconds) except urllib2.HTTPError, e: conn = e except (urllib2.URLError, ssl.SSLError), e: # TODO: Make this status more clear item.sta...
[ "Fetches the given request over HTTP." ]
Please provide a description of the function:def register(coordinator): fetch_queue = Queue.Queue() coordinator.register(FetchItem, fetch_queue) for i in xrange(FLAGS.fetch_threads): coordinator.worker_threads.append( FetchThread(fetch_queue, coordinator.input_queue))
[ "Registers this module as a worker with the given coordinator." ]
Please provide a description of the function:def json(self): if self._data_json: return self._data_json if not self.data or self.content_type != 'application/json': return None self._data_json = json.loads(self.data) return self._data_json
[ "Returns de-JSONed data or None if it's a different content type." ]
Please provide a description of the function:def maybe_imgur(self, path): '''Uploads a file to imgur if requested via command line flags. Returns either "path" or "path url" depending on the course of action. ''' if not FLAGS.imgur_client_id: return path im = pyimgu...
[]
Please provide a description of the function:def real_main(release_url=None, tests_json_path=None, upload_build_id=None, upload_release_name=None): coordinator = workers.get_coordinator() fetch_worker.register(coordinator) coordinator.start() data = open(F...
[ "Runs diff_my_images." ]
Please provide a description of the function:def clean_url(url, force_scheme=None): # URL should be ASCII according to RFC 3986 url = str(url) # Collapse ../../ and related url_parts = urlparse.urlparse(url) path_parts = [] for part in url_parts.path.split('/'): if part == '.': ...
[ "Cleans the given URL." ]
Please provide a description of the function:def extract_urls(url, data, unescape=HTMLParser.HTMLParser().unescape): parts = urlparse.urlparse(url) prefix = '%s://%s' % (parts.scheme, parts.netloc) accessed_dir = os.path.dirname(parts.path) if not accessed_dir.endswith('/'): accessed_dir +...
[ "Extracts the URLs from an HTML document." ]
Please provide a description of the function:def prune_urls(url_set, start_url, allowed_list, ignored_list): result = set() for url in url_set: allowed = False for allow_url in allowed_list: if url.startswith(allow_url): allowed = True break ...
[ "Prunes URLs that should be ignored." ]
Please provide a description of the function:def real_main(start_url=None, ignore_prefixes=None, upload_build_id=None, upload_release_name=None): coordinator = workers.get_coordinator() fetch_worker.register(coordinator) coordinator.start() item = SiteDiff...
[ "Runs the site_diff." ]
Please provide a description of the function:def render_or_send(func, message): if request.endpoint != func.func_name: mail.send(message) if (current_user.is_authenticated() and current_user.superuser): return render_template('debug_email.html', message=message)
[ "Renders an email message for debugging or actually sends it." ]
Please provide a description of the function:def send_ready_for_review(build_id, release_name, release_number): build = models.Build.query.get(build_id) if not build.send_email: logging.debug( 'Not sending ready for review email because build does not have ' 'email enabled....
[ "Sends an email indicating that the release is ready for review." ]
Please provide a description of the function:def homepage(): if current_user.is_authenticated(): if not login_fresh(): logging.debug('User needs a fresh token') abort(login.needs_refresh()) auth.claim_invitations(current_user) build_list = operations.UserOps(curren...
[ "Renders the homepage." ]
Please provide a description of the function:def new_build(): form = forms.BuildForm() if form.validate_on_submit(): build = models.Build() form.populate_obj(build) build.owners.append(current_user) db.session.add(build) db.session.flush() auth.save_admin_l...
[ "Page for crediting or editing a build." ]
Please provide a description of the function:def view_build(): build = g.build page_size = min(request.args.get('page_size', 10, type=int), 50) offset = request.args.get('offset', 0, type=int) ops = operations.BuildOps(build.id) has_next_page, candidate_list, stats_counts = ops.get_candidates(...
[ "Page for viewing all releases in a build." ]
Please provide a description of the function:def view_release(): build = g.build if request.method == 'POST': form = forms.ReleaseForm(request.form) else: form = forms.ReleaseForm(request.args) form.validate() ops = operations.BuildOps(build.id) release, run_list, stats_di...
[ "Page for viewing all tests runs in a release." ]
Please provide a description of the function:def _get_artifact_context(run, file_type): sha1sum = None image_file = False log_file = False config_file = False if request.path == '/image': image_file = True if file_type == 'before': sha1sum = run.ref_image el...
[ "Gets the artifact details for the given run and file_type." ]
Please provide a description of the function:def view_run(): build = g.build if request.method == 'POST': form = forms.RunForm(request.form) else: form = forms.RunForm(request.args) form.validate() ops = operations.BuildOps(build.id) run, next_run, previous_run, approval_l...
[ "Page for viewing before/after for a specific test run." ]
Please provide a description of the function:def register(coordinator): timer_queue = Queue.Queue() coordinator.register(TimerItem, timer_queue) coordinator.worker_threads.append( TimerThread(timer_queue, coordinator.input_queue))
[ "Registers this module as a worker with the given coordinator." ]
Please provide a description of the function:def get_coordinator(): workflow_queue = Queue.Queue() complete_queue = Queue.Queue() coordinator = WorkflowThread(workflow_queue, complete_queue) coordinator.register(WorkflowItem, workflow_queue) return coordinator
[ "Creates a coordinator and returns it." ]
Please provide a description of the function:def _print_repr(self, depth): if depth <= 0: return '%s.%s#%d' % ( self.__class__.__module__, self.__class__.__name__, id(self)) return '%s.%s(%s)#%d' % ( self.__class__.__modul...
[ "Print this WorkItem to the given stack depth.\n\n The depth parameter ensures that we can print WorkItems in\n arbitrarily long chains without hitting the max stack depth.\n This can happen with WaitForUrlWorkflowItems, which\n create long chains of small waits.\n " ]
Please provide a description of the function:def error(self): # Copy the error from any failed item to be the error for the whole # barrier. The first error seen "wins". Also handles the case where # the WorkItems passed into the barrier have already completed and # been marked ...
[ "Returns the error for this barrier and all work items, if any." ]
Please provide a description of the function:def outstanding(self): # Allow the same WorkItem to be yielded multiple times but not # count towards blocking the barrier. done_count = 0 for item in self: if not self.wait_any and item.fire_and_forget: # ...
[ "Returns whether or not this barrier has pending work." ]
Please provide a description of the function:def get_item(self): if self.was_list: result = ResultList() for item in self: if isinstance(item, WorkflowItem): if item.done and not item.error: result.append(item.result) ...
[ "Returns the item to send back into the workflow generator." ]
Please provide a description of the function:def start(self): assert not self.interrupted for thread in self.worker_threads: thread.start() WorkerThread.start(self)
[ "Starts the coordinator thread and all related worker threads." ]
Please provide a description of the function:def stop(self): if self.interrupted: return for thread in self.worker_threads: thread.interrupted = True self.interrupted = True
[ "Stops the coordinator thread and all related threads." ]
Please provide a description of the function:def join(self): for thread in self.worker_threads: thread.join() WorkerThread.join(self)
[ "Joins the coordinator thread and all worker threads." ]
Please provide a description of the function:def wait_one(self): while True: try: item = self.output_queue.get(True, self.polltime) except Queue.Empty: continue except KeyboardInterrupt: LOGGER.debug('Exiting') ...
[ "Waits until this worker has finished one work item or died." ]
Please provide a description of the function:def superuser_required(f): @functools.wraps(f) @login_required def wrapped(*args, **kwargs): if not (current_user.is_authenticated() and current_user.superuser): abort(403) return f(*args, **kwargs) return wrapped
[ "Requires the requestor to be a super user." ]
Please provide a description of the function:def can_user_access_build(param_name): build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) if not build_id: logging.debug('Build ID in param_name=%r was missin...
[ "Determines if the current user can access the build ID in the request.\n\n Args:\n param_name: Parameter name to use for getting the build ID from the\n request. Will fetch from GET or POST requests.\n\n Returns:\n The build the user has access to.\n " ]
Please provide a description of the function:def build_access_required(function_or_param_name): def get_wrapper(param_name, f): @functools.wraps(f) def wrapped(*args, **kwargs): g.build = can_user_access_build(param_name) if not utils.is_production(): # I...
[ "Decorator ensures user has access to the build ID in the request.\n\n May be used in two ways:\n\n @build_access_required\n def my_func(build):\n ...\n\n @build_access_required('custom_build_id_param')\n def my_func(build):\n ...\n\n Always calls the given fu...
Please provide a description of the function:def _get_api_key_ops(): auth_header = request.authorization if not auth_header: logging.debug('API request lacks authorization header') abort(flask.Response( 'API key required', 401, {'WWW-Authenticate': 'Basic realm="API ...
[ "Gets the operations.ApiKeyOps instance for the current request." ]
Please provide a description of the function:def current_api_key(): if app.config.get('IGNORE_AUTH'): return models.ApiKey( id='anonymous_superuser', secret='', superuser=True) ops = _get_api_key_ops() api_key = ops.get() logging.debug('Authenticated as ...
[ "Determines the API key for the current request.\n\n Returns:\n The ApiKey instance.\n " ]
Please provide a description of the function:def can_api_key_access_build(param_name): build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) utils.jsonify_assert(build_id, 'build_id required') if app.config.ge...
[ "Determines if the current API key can access the build in the request.\n\n Args:\n param_name: Parameter name to use for getting the build ID from the\n request. Will fetch from GET or POST requests.\n\n Returns:\n (api_key, build) The API Key and the Build it has access to.\n " ]
Please provide a description of the function:def build_api_access_required(f): @functools.wraps(f) def wrapped(*args, **kwargs): g.api_key, g.build = can_api_key_access_build('build_id') return f(*args, **kwargs) return wrapped
[ "Decorator ensures API key has access to the build ID in the request.\n\n Always calls the given function with the models.Build entity as the\n first positional argument.\n " ]
Please provide a description of the function:def superuser_api_key_required(f): @functools.wraps(f) def wrapped(*args, **kwargs): api_key = current_api_key() g.api_key = api_key utils.jsonify_assert( api_key.superuser, 'API key=%r must be a super user' % api...
[ "Decorator ensures only superuser API keys can request this function." ]
Please provide a description of the function:def manage_api_keys(): build = g.build create_form = forms.CreateApiKeyForm() if create_form.validate_on_submit(): api_key = models.ApiKey() create_form.populate_obj(api_key) api_key.id = utils.human_uuid() api_key.secret = ut...
[ "Page for viewing and creating API keys." ]
Please provide a description of the function:def revoke_api_key(): build = g.build form = forms.RevokeApiKeyForm() if form.validate_on_submit(): api_key = models.ApiKey.query.get(form.id.data) if api_key.build_id != build.id: logging.debug('User does not have access to API k...
[ "Form submission handler for revoking API keys." ]
Please provide a description of the function:def claim_invitations(user): # See if there are any build invitations present for the user with this # email address. If so, replace all those invitations with the real user. invitation_user_id = '%s:%s' % ( models.User.EMAIL_INVITATION, user.email_a...
[ "Claims any pending invitations for the given user's email address." ]
Please provide a description of the function:def manage_admins(): build = g.build # Do not show cached data db.session.add(build) db.session.refresh(build) add_form = forms.AddAdminForm() if add_form.validate_on_submit(): invitation_user_id = '%s:%s' % ( models.User.E...
[ "Page for viewing and managing build admins." ]
Please provide a description of the function:def revoke_admin(): build = g.build form = forms.RemoveAdminForm() if form.validate_on_submit(): user = models.User.query.get(form.user_id.data) if not user: logging.debug('User being revoked admin access does not exist.' ...
[ "Form submission handler for revoking admin access to a build." ]
Please provide a description of the function:def save_admin_log(build, **kwargs): message = kwargs.pop('message', None) release = kwargs.pop('release', None) run = kwargs.pop('run', None) if not len(kwargs) == 1: raise TypeError('Must specify a LOG_TYPE argument') log_enum = kwargs.ke...
[ "Saves an action to the admin log." ]
Please provide a description of the function:def view_admin_log(): build = g.build # TODO: Add paging log_list = ( models.AdminLog.query .filter_by(build_id=build.id) .order_by(models.AdminLog.created.desc()) .all()) return render_template( 'view_admin_log...
[ "Page for viewing the log of admin activity." ]
Please provide a description of the function:def verify_binary(flag_name, process_args=None): if process_args is None: process_args = [] path = getattr(FLAGS, flag_name) if not path: logging.error('Flag %r not set' % flag_name) sys.exit(1) with open(os.devnull, 'w') as dev...
[ "Exits the program if the binary from the given flag doesn't run.\n\n Args:\n flag_name: Name of the flag that should be the path to the binary.\n process_args: Args to pass to the binary to do nothing but verify\n that it's working correctly (something like \"--version\") is good.\n ...
Please provide a description of the function:def create_release(): build = g.build release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 'release_name required') url = request.form.get('url') utils.jsonify_assert(release_name, 'url required') release = models.R...
[ "Creates a new release candidate for a build." ]
Please provide a description of the function:def _check_release_done_processing(release): if release.status != models.Release.PROCESSING: # NOTE: This statement also guards for situations where the user has # prematurely specified that the release is good or bad. Once the user # has don...
[ "Moves a release candidate to reviewing if all runs are done." ]
Please provide a description of the function:def _get_release_params(): release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 'release_name required') release_number = request.form.get('release_number', type=int) utils.jsonify_assert(release_number is not None, 'release...
[ "Gets the release params from the current request." ]
Please provide a description of the function:def _find_last_good_run(build): run_name = request.form.get('run_name', type=str) utils.jsonify_assert(run_name, 'run_name required') last_good_release = ( models.Release.query .filter_by( build_id=build.id, status=mo...
[ "Finds the last good release and run for a build." ]
Please provide a description of the function:def find_run(): build = g.build last_good_release, last_good_run = _find_last_good_run(build) if last_good_run: return flask.jsonify( success=True, build_id=build.id, release_name=last_good_release.name, ...
[ "Finds the last good run of the given name for a release." ]
Please provide a description of the function:def _get_or_create_run(build): release_name, release_number = _get_release_params() run_name = request.form.get('run_name', type=str) utils.jsonify_assert(run_name, 'run_name required') release = ( models.Release.query .filter_by(build_i...
[ "Gets a run for a build or creates it if it does not exist." ]
Please provide a description of the function:def _enqueue_capture(build, release, run, url, config_data, baseline=False): # Validate the JSON config parses. try: config_dict = json.loads(config_data) except Exception, e: abort(utils.jsonify_error(e)) # Rewrite the config JSON to in...
[ "Enqueues a task to run a capture process." ]
Please provide a description of the function:def request_run(): build = g.build current_release, current_run = _get_or_create_run(build) current_url = request.form.get('url', type=str) config_data = request.form.get('config', default='{}', type=str) utils.jsonify_assert(current_url, 'url to ca...
[ "Requests a new run for a release candidate." ]
Please provide a description of the function:def report_run(): build = g.build release, run = _get_or_create_run(build) db.session.refresh(run, lockmode='update') current_url = request.form.get('url', type=str) current_image = request.form.get('image', type=str) current_log = request.form...
[ "Reports data for a run for a release candidate." ]
Please provide a description of the function:def runs_done(): build = g.build release_name, release_number = _get_release_params() release = ( models.Release.query .filter_by(build_id=build.id, name=release_name, number=release_number) .with_lockmode('update') .first())...
[ "Marks a release candidate as having all runs reported." ]
Please provide a description of the function:def _save_artifact(build, data, content_type): sha1sum = hashlib.sha1(data).hexdigest() artifact = models.Artifact.query.filter_by(id=sha1sum).first() if artifact: logging.debug('Upload already exists: artifact_id=%r', sha1sum) else: logging...
[ "Saves an artifact to the DB and returns it." ]
Please provide a description of the function:def upload(): build = g.build utils.jsonify_assert(len(request.files) == 1, 'Need exactly one uploaded file') file_storage = request.files.values()[0] data = file_storage.read() content_type, _ = mimetypes.guess_type(file_st...
[ "Uploads an artifact referenced by a run." ]
Please provide a description of the function:def _get_artifact_response(artifact): response = flask.Response( artifact.data, mimetype=artifact.content_type) response.cache_control.public = True response.cache_control.max_age = 8640000 response.set_etag(artifact.id) return respon...
[ "Gets the response object for the given artifact.\n\n This method may be overridden in environments that have a different way of\n storing artifact files, such as on-disk or S3.\n " ]
Please provide a description of the function:def download(): # Allow users with access to the build to download the file. Falls back # to API keys with access to the build. Prefer user first for speed. try: build = auth.can_user_access_build('build_id') except HTTPException: logging...
[ "Downloads an artifact by it's content hash." ]
Please provide a description of the function:def register(coordinator): utils.verify_binary('pdiff_compare_binary', ['-version']) utils.verify_binary('pdiff_composite_binary', ['-version']) assert FLAGS.pdiff_threads > 0 assert FLAGS.queue_server_prefix item = queue_worker.RemoteQueueWorkflow...
[ "Registers this module as a worker with the given coordinator." ]
Please provide a description of the function:def evict(self): logging.debug('Evicting cache for %r', self.cache_key) _clear_version_cache(self.cache_key) # Cause the cache key to be refreshed next time any operation is # run to make sure we don't act on old cached data. ...
[ "Evict all caches related to these operations." ]
Please provide a description of the function:def sort_run(run): # Sort errors first, then by name. Also show errors that were manually # approved, so the paging sort order stays the same even after users # approve a diff on the run page. if run.status in models.Run.DIFF_NEEDED_S...
[ "Sort function for runs within a release." ]
Please provide a description of the function:def parse(obj, required_properties=None, additional_properties=None, ignore_optional_property_errors=None): if not (required_properties is additional_properties is ignore_optional_property_errors is None): with parsing(requi...
[ "Try to parse the given ``obj`` as a validator instance.\n\n :param obj: The object to be parsed. If it is a...:\n\n - :py:class:`Validator` instance, return it.\n - :py:class:`Validator` subclass, instantiate it without arguments and\n return it.\n - :py:attr:`~Validator.name` of a...
Please provide a description of the function:def parsing(**kwargs): from .validators import Object with _VALIDATOR_FACTORIES_LOCK: old_values = {} for key, value in iteritems(kwargs): if value is not None: attr = key.upper() old_values[key] = get...
[ "\n Context manager for overriding the default validator parsing rules for the\n following code block.\n " ]
Please provide a description of the function:def register(name, validator): if not isinstance(validator, Validator): raise TypeError("Validator instance expected, %s given" % validator.__class__) _NAMED_VALIDATORS[name] = validator
[ "Register a validator instance under the given ``name``." ]
Please provide a description of the function:def accepts(**schemas): validate = parse(schemas).validate @decorator def validating(func, *args, **kwargs): validate(inspect.getcallargs(func, *args, **kwargs), adapt=False) return func(*args, **kwargs) return validating
[ "Create a decorator for validating function parameters.\n\n Example::\n\n @accepts(a=\"number\", body={\"+field_ids\": [int], \"is_ok\": bool})\n def f(a, body):\n print (a, body[\"field_ids\"], body.get(\"is_ok\"))\n\n :param schemas: The schema for validating a given parameter.\n ...
Please provide a description of the function:def returns(schema): validate = parse(schema).validate @decorator def validating(func, *args, **kwargs): ret = func(*args, **kwargs) validate(ret, adapt=False) return ret return validating
[ "Create a decorator for validating function return value.\n\n Example::\n @accepts(a=int, b=int)\n @returns(int)\n def f(a, b):\n return a + b\n\n :param schema: The schema for adapting a given parameter.\n " ]
Please provide a description of the function:def adapts(**schemas): validate = parse(schemas).validate @decorator def adapting(func, *args, **kwargs): adapted = validate(inspect.getcallargs(func, *args, **kwargs), adapt=True) argspec = inspect.getargspec(func) if argspec.varar...
[ "Create a decorator for validating and adapting function parameters.\n\n Example::\n\n @adapts(a=\"number\", body={\"+field_ids\": [V.AdaptTo(int)], \"is_ok\": bool})\n def f(a, body):\n print (a, body.field_ids, body.is_ok)\n\n :param schemas: The schema for adapting a given paramete...
Please provide a description of the function:def _ObjectFactory(obj): if isinstance(obj, dict): optional, required = {}, {} for key, value in iteritems(obj): if key.startswith("+"): required[key[1:]] = value elif key.startswith("?"): optio...
[ "Parse a python ``{name: schema}`` dict as an :py:class:`Object` instance.\n\n - A property name prepended by \"+\" is required\n - A property name prepended by \"?\" is optional\n - Any other property is required if :py:attr:`Object.REQUIRED_PROPERTIES`\n is True else it's optional\n " ]
Please provide a description of the function:def get_checksum_metadata_tag(self): if not self._checksums: print("Warning: No checksums have been computed for this file.") return {str(_hash_name): str(_hash_value) for _hash_name, _hash_value in self._checksums.items()}
[ " Returns a map of checksum values by the name of the hashing function that produced it." ]
Please provide a description of the function:def compute_checksum(self): if self._filename.startswith("s3://"): print("Warning: Did not perform client-side checksumming for file in S3. To be implemented.") pass else: checksumCalculator = self.ChecksumCalculat...
[ " Calculates checksums for a given file. " ]
Please provide a description of the function:def get_credentials(self): creds_mgr = CredentialsManager(self) creds = creds_mgr.get_credentials_from_upload_api() return { 'aws_access_key_id': creds['access_key'], 'aws_secret_access_key': creds['secret_key'], ...
[ "\n Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket\n :return: a dict containing AWS credentials in a format suitable for passing to Boto3\n or if capitalized, used as environment variables\n " ]
Please provide a description of the function:def list(self, detail=False): creds_provider = CredentialsManager(upload_area=self) s3agent = S3Agent(credentials_provider=creds_provider) key_prefix = self.uuid + "/" key_prefix_length = len(key_prefix) for page in s3agent.li...
[ "\n A generator that yields information about each file in the upload area\n :param detail: return detailed file information (slower)\n :return: a list of dicts containing at least 'name', or more of detail was requested\n " ]
Please provide a description of the function:def store_file(self, filename, file_content, content_type): return self.upload_service.api_client.store_file(area_uuid=self.uuid, filename=filename, ...
[ "\n Store a small file in an Upload Area\n\n :param str area_uuid: A RFC4122-compliant ID for the upload area\n :param str filename: The name the file will have in the Upload Area\n :param str file_content: The contents of the file\n :param str content_type: The MIME-type for the ...
Please provide a description of the function:def upload_files(self, file_paths, file_size_sum=0, dcp_type="data", target_filename=None, use_transfer_acceleration=True, report_progress=False, sync=True): self._setup_s3_agent_for_file_upload(file_count=len(file_paths), ...
[ "\n A function that takes in a list of file paths and other optional args for parallel file upload\n " ]
Please provide a description of the function:def validate_files(self, file_list, validator_image, original_validation_id="", environment={}): return self.upload_service.api_client.validate_files(area_uuid=self.uuid, file_list=file_list, ...
[ "\n Invoke supplied validator Docker image and give it access to the file/s.\n The validator must be based off the base validator Docker image.\n\n :param list file_list: A list of files within the Upload Area to be validated\n :param str validator_image: the location of a docker image t...
Please provide a description of the function:def checksum_status(self, filename): return self.upload_service.api_client.checksum_status(area_uuid=self.uuid, filename=filename)
[ "\n Retrieve checksum status and values for a file\n\n :param str filename: The name of the file within the Upload Area\n :return: a dict with checksum information\n :rtype: dict\n :raises UploadApiException: if information could not be obtained\n " ]
Please provide a description of the function:def validation_status(self, filename): return self.upload_service.api_client.validation_status(area_uuid=self.uuid, filename=filename)
[ "\n Get status and results of latest validation job for a file.\n\n :param str filename: The name of the file within the Upload Area\n :return: a dict with validation information\n :rtype: dict\n :raises UploadApiException: if information could not be obtained\n " ]
Please provide a description of the function:def check_if_release_is_current(log): if __version__ == '0.0.0': return client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') latest_pypi_version = client.package_releases('hca') latest_version_nums = [int(i) for i in latest_pypi_versio...
[ "Warns the user if their release is behind the latest PyPi __version__." ]
Please provide a description of the function:def _parse_docstring(docstring): this will be the summary :param name: describe the parameter called name. this will be the descriptions * more description * more description This will also be in the description ...
[ "\n Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first\n rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse\n arguments. Any other text is combined and added to the argparse description.\n\n exa...
Please provide a description of the function:def sizeof_fmt(num, suffix='B'): precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15} for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: format_string = "{number:.%df} {unit}{suf...
[ "\n Adapted from https://stackoverflow.com/a/1094933\n Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection\n " ]
Please provide a description of the function:def _item_exists_in_bucket(self, bucket, key, checksums): try: obj = self.target_s3.meta.client.head_object(Bucket=bucket, Key=key) if obj and obj.containsKey('Metadata'): if obj['Metadata'] == checksums: ...
[ " Returns true if the key already exists in the current bucket and the clientside checksum matches the\n file's checksums, and false otherwise." ]
Please provide a description of the function:def upload_to_cloud(file_handles, staging_bucket, replica, from_cloud=False): s3 = boto3.resource("s3") file_uuids = [] key_names = [] abs_file_paths = [] if from_cloud: file_uuids, key_names = _copy_from_s3(file_handles[0], s3) else: ...
[ "\n Upload files to cloud.\n\n :param file_handles: If from_cloud, file_handles is a aws s3 directory path to files with appropriate\n metadata uploaded. Else, a list of binary file_handles to upload.\n :param staging_bucket: The aws bucket to upload the files to.\n :param replic...
Please provide a description of the function:def download(self, bundle_uuid, replica, version="", download_dir="", metadata_files=('*',), data_files=('*',), num_retries=10, min_delay_seconds=0.25): errors = 0 with concurrent.futures.ThreadPoolExecutor(self.thr...
[ "\n Download a bundle and save it to the local filesystem as a directory.\n\n :param str bundle_uuid: The uuid of the bundle to download\n :param str replica: the replica to download from. The supported replicas are: `aws` for Amazon Web Services, and\n `gcp` for Google Cloud Platfor...
Please provide a description of the function:def _download_to_filestore(self, download_dir, dss_file, num_retries=10, min_delay_seconds=0.25): dest_path = self._file_path(dss_file.sha256, download_dir) if os.path.exists(dest_path): logger.info("Skipping download of '%s' because it a...
[ "\n Attempt to download the data and save it in the 'filestore' location dictated by self._file_path()\n " ]
Please provide a description of the function:def _download_file(self, dss_file, dest_path, num_retries=10, min_delay_seconds=0.25): directory, _ = os.path.split(dest_path) if directory: try: os.makedirs(directory) except OSError as e: if e...
[ "\n Attempt to download the data. If a retryable exception occurs, we wait a bit and retry again. The delay\n increases each time we fail and decreases each time we successfully read a block. We set a quota for the\n number of failures that goes up with every successful block read and down w...
Please provide a description of the function:def _do_download_file(self, dss_file, fh, num_retries, min_delay_seconds): hasher = hashlib.sha256() delay = min_delay_seconds retries_left = num_retries while True: try: response = self.get_file._request( ...
[ "\n Abstracts away complications for downloading a file, handles retries and delays, and computes its hash\n " ]
Please provide a description of the function:def _file_path(cls, checksum, download_dir): checksum = checksum.lower() file_prefix = '_'.join(['files'] + list(map(str, cls.DIRECTORY_NAME_LENGTHS))) path_pieces = [download_dir, '.hca', 'v2', file_prefix] checksum_index = 0 ...
[ "\n returns a file's relative local path based on the nesting parameters and the files hash\n :param checksum: a string checksum\n :param download_dir: root directory for filestore\n :return: relative Path object\n " ]
Please provide a description of the function:def _write_output_manifest(self, manifest, filestore_root): output = os.path.basename(manifest) fieldnames, source_manifest = self._parse_manifest(manifest) if 'file_path' not in fieldnames: fieldnames.append('file_path') ...
[ "\n Adds the file path column to the manifest and writes the copy to the current directory. If the original manifest\n is in the current directory it is overwritten with a warning.\n " ]
Please provide a description of the function:def download_manifest_v2(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir='.'): fieldnames, rows = self._parse_manifest(manifest) erro...
[ "\n Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it.\n The files are downloaded in the version 2 format.\n\n This download format will serve as the main storage format for downloaded files. If a user specifies a different\n for...
Please provide a description of the function:def download_manifest(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir=''): file_errors = 0 file_task, bundle_errors = self._download_manifest_tasks(manifest, ...
[ "\n Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it.\n\n :param str manifest: path to a TSV (tab-separated values) file listing files to download\n :param str replica: the replica to download from. The supported replicas are: `aws` fo...
Please provide a description of the function:def upload(self, src_dir, replica, staging_bucket, timeout_seconds=1200): bundle_uuid = str(uuid.uuid4()) version = datetime.utcnow().strftime("%Y-%m-%dT%H%M%S.%fZ") files_to_upload, files_uploaded = [], [] for filename in iter_paths...
[ "\n Upload a directory of files from the local filesystem and create a bundle containing the uploaded files.\n\n :param str src_dir: file path to a directory of files to upload to the replica.\n :param str replica: the replica to upload to. The supported replicas are: `aws` for Amazon Web Servi...
Please provide a description of the function:def iter_paths(src_dir): for x in scandir(os.path.join(src_dir)): if x.is_dir(follow_symlinks=False): for x in iter_paths(x.path): yield x else: yield x
[ "\n Function that recursively locates files within folder\n Note: scandir does not guarantee ordering\n :param src_dir: string for directory to be parsed through\n :return an iterable of DirEntry objects all files within the src_dir\n " ]
Please provide a description of the function:def hardlink(source, link_name): if sys.version_info < (3,) and platform.system() == 'Windows': # pragma: no cover import ctypes create_hard_link = ctypes.windll.kernel32.CreateHardLinkW create_hard_link.argtypes = [ctypes.c_wchar_p, ctypes....
[ "\n Create a hardlink in a portable way\n\n The code for Windows support is adapted from:\n https://github.com/sunshowers/ntfs/blob/master/ntfsutils/hardlink.py\n " ]
Please provide a description of the function:def request_with_retries_on_post_search(self, session, url, query, json_input, stream, headers): # TODO: Revert this PR as soon as the appropriate swagger definitions have percolated up # to prod and merged; see https://github.com/HumanCellAtlas/data...
[ "\n Submit a request and retry POST search requests specifically.\n\n We don't currently retry on POST requests, and this is intended as a temporary fix until\n the swagger is updated and changes applied to prod. In the meantime, this function will add\n retries specifically for POST se...
Please provide a description of the function:def load_swagger_json(swagger_json, ptr_str="$ref"): refs = [] def store_refs(d): if len(d) == 1 and ptr_str in d: refs.append(d) return d swagger_content = json.load(swagger_json, object_hook=store_r...
[ "\n Load the Swagger JSON and resolve {\"$ref\": \"#/...\"} internal JSON Pointer references.\n " ]
Please provide a description of the function:def refresh_swagger(self): try: os.remove(self._get_swagger_filename(self.swagger_url)) except EnvironmentError as e: logger.warn(os.strerror(e.errno)) else: self.__init__()
[ "\n Manually refresh the swagger document. This can help resolve errors communicate with the API.\n " ]
Please provide a description of the function:def login(self, access_token=""): if access_token: credentials = argparse.Namespace(token=access_token, refresh_token=None, id_token=None) else: scopes = ["openid", "email", "offline_access"] from google_auth_oaut...
[ "\n Configure and save {prog} authentication credentials.\n\n This command may open a browser window to ask for your\n consent to use web service authentication credentials.\n " ]