Instruction:
Can you tell what is the following Python 3 function doing
def h1(title, line=OVERLINE):
    width = utils.term.width
    printy(bold(title.center(width)).as_utf8)
    printy(bold((line * width)[:width]).as_utf8)

Response: Prints bold text with line beneath it spanning width of terminal


Instruction:
Can you tell what is the following Python 3 function doing
def parse_color(color):
    if isinstance(color, basestring):
        color = grapefruit.Color.NewFromHtml(color)
    if isinstance(color, int):
        (r, g, b) = xterm256.xterm_to_rgb(color)
    elif hasattr(color, 'rgb'):
        (r, g, b) = [int(c * 255.0) for c in color.rgb]
    else:
        (r, g, b) = color
    assert isinstance(r, int) and 0 <= r <= 255
    assert isinstance(g, int) and 0 <= g <= 255
    assert isinstance(b, int) and 0 <= b <= 255
    return (r, g, b)

Response: r Converts a color into an r g b tuple


Instruction:
Implement a function in Python 3 to
print a section of the terminal

Response:
def section(title, bar=OVERLINE, strm=sys.stdout):
    """Helper function for testing demo routines
    """
    width = utils.term.width
    printy(bold(title.center(width)))
    printy(bold((bar * width)[:width]))


Instruction:
Can you tell what is the following Python 3 function doing
def workerTypeUpdated(self, *args, **kwargs):

        ref = {
            'exchange': 'worker-type-updated',
            'name': 'workerTypeUpdated',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'http://schemas.taskcluster.net/aws-provisioner/v1/worker-type-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)

Response: This is a simple workerTypeUpdated message. It is a simple function that returns a message that is published to the master.


Instruction:
Here you have a function in Python 3, explain what it does
def workerTypeRemoved(self, *args, **kwargs):

        ref = {
            'exchange': 'worker-type-removed',
            'name': 'workerTypeRemoved',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'http://schemas.taskcluster.net/aws-provisioner/v1/worker-type-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)

Response: This method is used to publish a WorkerType Removed Message to this base class. It is used to remove a WorkerType from a Taskcluster topic.


Instruction:
Here you have a function in Python 3, explain what it does
def jobs(self, *args, **kwargs):

        ref = {
            'exchange': 'jobs',
            'name': 'jobs',
            'routingKey': [
                {
                    'multipleWords': False,
                    'name': 'destination',
                },
                {
                    'multipleWords': False,
                    'name': 'project',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/pulse-job.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)

Response: This is an alias for the jobs method in Treeherder. It is used to create and publish a new Job Messages to Treeherder.


Instruction:
Write a Python 3 script to
create a set of temporary credentials for the given clientId and accessToken.

Response:
def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None):
    """ Create a set of temporary credentials

    Callers should not apply any clock skew; clock drift is accounted for by
    auth service.

    clientId: the issuing clientId
    accessToken: the issuer's accessToken
    start: start time of credentials (datetime.datetime)
    expiry: expiration time of credentials, (datetime.datetime)
    scopes: list of scopes granted
    name: credential name (optional)

    Returns a dictionary in the form:
        { 'clientId': str, 'accessToken: str, 'certificate': str}
    """

    for scope in scopes:
        if not isinstance(scope, six.string_types):
            raise exceptions.TaskclusterFailure('Scope must be string')

    # Credentials can only be valid for 31 days.  I hope that
    # this is validated on the server somehow...

    if expiry - start > datetime.timedelta(days=31):
        raise exceptions.TaskclusterFailure('Only 31 days allowed')

    # We multiply times by 1000 because the auth service is JS and as a result
    # uses milliseconds instead of seconds
    cert = dict(
        version=1,
        scopes=scopes,
        start=calendar.timegm(start.utctimetuple()) * 1000,
        expiry=calendar.timegm(expiry.utctimetuple()) * 1000,
        seed=utils.slugId().encode('ascii') + utils.slugId().encode('ascii'),
    )

    # if this is a named temporary credential, include the issuer in the certificate
    if name:
        cert['issuer'] = utils.toStr(clientId)

    sig = ['version:' + utils.toStr(cert['version'])]
    if name:
        sig.extend([
            'clientId:' + utils.toStr(name),
            'issuer:' + utils.toStr(clientId),
        ])
    sig.extend([
        'seed:' + utils.toStr(cert['seed']),
        'start:' + utils.toStr(cert['start']),
        'expiry:' + utils.toStr(cert['expiry']),
        'scopes:'
    ] + scopes)
    sigStr = '\n'.join(sig).encode()

    if isinstance(accessToken, six.text_type):
        accessToken = accessToken.encode()
    sig = hmac.new(accessToken, sigStr, hashlib.sha256).digest()

    cert['signature'] = utils.encodeStringForB64Header(sig)

    newToken = hmac.new(accessToken, cert['seed'], hashlib.sha256).digest()
    newToken = utils.makeB64UrlSafe(utils.encodeStringForB64Header(newToken)).replace(b'=', b'')

    return {
        'clientId': name or clientId,
        'accessToken': newToken,
        'certificate': utils.dumpJson(cert),
    }


Instruction:
How would you implement a function in Python 3 that
makes an ext for Hawk authentication

Response:
def makeHawkExt(self):
        """ Make an 'ext' for Hawk authentication """
        o = self.options
        c = o.get('credentials', {})
        if c.get('clientId') and c.get('accessToken'):
            ext = {}
            cert = c.get('certificate')
            if cert:
                if six.PY3 and isinstance(cert, six.binary_type):
                    cert = cert.decode()
                if isinstance(cert, six.string_types):
                    cert = json.loads(cert)
                ext['certificate'] = cert

            if 'authorizedScopes' in o:
                ext['authorizedScopes'] = o['authorizedScopes']

            # .encode('base64') inserts a newline, which hawk doesn't
            # like but doesn't strip itself
            return utils.makeB64UrlSafe(utils.encodeStringForB64Header(utils.dumpJson(ext)).strip())
        else:
            return {}


Instruction:
Create a Python 3 function for
building a signed URL.

Response:
def buildSignedUrl(self, methodName, *args, **kwargs):
        """ Build a signed URL.  This URL contains the credentials needed to access
        a resource."""

        if 'expiration' in kwargs:
            expiration = kwargs['expiration']
            del kwargs['expiration']
        else:
            expiration = self.options['signedUrlExpiration']

        expiration = int(time.time() + expiration)  # Mainly so that we throw if it's not a number

        requestUrl = self.buildUrl(methodName, *args, **kwargs)

        if not self._hasCredentials():
            raise exceptions.TaskclusterAuthFailure('Invalid Hawk Credentials')

        clientId = utils.toStr(self.options['credentials']['clientId'])
        accessToken = utils.toStr(self.options['credentials']['accessToken'])

        def genBewit():
            # We need to fix the output of get_bewit.  It returns a url-safe base64
            # encoded string, which contains a list of tokens separated by '\'.
            # The first one is the clientId, the second is an int, the third is
            # url-safe base64 encoded MAC, the fourth is the ext param.
            # The problem is that the nested url-safe base64 encoded MAC must be
            # base64 (i.e. not url safe) or server-side will complain.

            # id + '\\' + exp + '\\' + mac + '\\' + options.ext;
            resource = mohawk.base.Resource(
                credentials={
                    'id': clientId,
                    'key': accessToken,
                    'algorithm': 'sha256',
                },
                method='GET',
                ext=utils.toStr(self.makeHawkExt()),
                url=requestUrl,
                timestamp=expiration,
                nonce='',
                # content='',
                # content_type='',
            )
            bewit = mohawk.bewit.get_bewit(resource)
            return bewit.rstrip('=')

        bewit = genBewit()

        if not bewit:
            raise exceptions.TaskclusterFailure('Did not receive a bewit')

        u = urllib.parse.urlparse(requestUrl)

        qs = u.query
        if qs:
            qs += '&'
        qs += 'bewit=%s' % bewit

        return urllib.parse.urlunparse((
            u.scheme,
            u.netloc,
            u.path,
            u.params,
            qs,
            u.fragment,
        ))


Instruction:
Implement a Python 3 function for
constructing a URL for the given route on this service based on the rootUrl

Response:
def _constructUrl(self, route):
        """Construct a URL for the given route on this service, based on the
        rootUrl"""
        return liburls.api(
            self.options['rootUrl'],
            self.serviceName,
            self.apiVersion,
            route.rstrip('/'))


Instruction:
How would you explain what the following Python 3 function does
def _processArgs(self, entry, *_args, **_kwargs):

        # We need the args to be a list so we can mutate them
        args = list(_args)
        kwargs = copy.deepcopy(_kwargs)

        reqArgs = entry['args']
        routeParams = {}

        query = {}
        payload = None
        kwApiArgs = {}

        paginationHandler = None
        paginationLimit = None

        # There are three formats for calling methods:
        #   1. method(v1, v1, payload)
        #   2. method(payload, k1=v1, k2=v2)
        #   3. method(payload=payload, query=query, params={k1: v1, k2: v2})
        if len(kwargs) == 0:
            if 'input' in entry and len(args) == len(reqArgs) + 1:
                payload = args.pop()
            if len(args) != len(reqArgs):
                log.debug(args)
                log.debug(reqArgs)
                raise exceptions.TaskclusterFailure('Incorrect number of positional arguments')
            log.debug('Using method(v1, v2, payload) calling convention')
        else:
            # We're considering kwargs which are the api route parameters to be
            # called 'flat' because they're top level keys.  We're special
            # casing calls which have only api-arg kwargs and possibly a payload
            # value and handling them directly.
            isFlatKwargs = True
            if len(kwargs) == len(reqArgs):
                for arg in reqArgs:
                    if not kwargs.get(arg, False):
                        isFlatKwargs = False
                        break
                if 'input' in entry and len(args) != 1:
                    isFlatKwargs = False
                if 'input' not in entry and len(args) != 0:
                    isFlatKwargs = False
                else:
                    pass  # We're using payload=, query= and param=
            else:
                isFlatKwargs = False

            # Now we're going to handle the two types of kwargs.  The first is
            # 'flat' ones, which are where the api params
            if isFlatKwargs:
                if 'input' in entry:
                    payload = args.pop()
                kwApiArgs = kwargs
                log.debug('Using method(payload, k1=v1, k2=v2) calling convention')
                warnings.warn(
                    "The method(payload, k1=v1, k2=v2) calling convention will soon be deprecated",
                    PendingDeprecationWarning
                )
            else:
                kwApiArgs = kwargs.get('params', {})
                payload = kwargs.get('payload', None)
                query = kwargs.get('query', {})
                paginationHandler = kwargs.get('paginationHandler', None)
                paginationLimit = kwargs.get('paginationLimit', None)
                log.debug('Using method(payload=payload, query=query, params={k1: v1, k2: v2}) calling convention')

        if 'input' in entry and isinstance(payload, type(None)):
            raise exceptions.TaskclusterFailure('Payload is required')

        # These all need to be rendered down to a string, let's just check that
        # they are up front and fail fast
        for arg in args:
            if not isinstance(arg, six.string_types) and not isinstance(arg, int):
                raise exceptions.TaskclusterFailure(
                    'Positional arg "%s" to %s is not a string or int' % (arg, entry['name']))

        for name, arg in six.iteritems(kwApiArgs):
            if not isinstance(arg, six.string_types) and not isinstance(arg, int):
                raise exceptions.TaskclusterFailure(
                    'KW arg "%s: %s" to %s is not a string or int' % (name, arg, entry['name']))

        if len(args) > 0 and len(kwApiArgs) > 0:
            raise exceptions.TaskclusterFailure('Specify either positional or key word arguments')

        # We know for sure that if we don't give enough arguments that the call
        # should fail.  We don't yet know if we should fail because of two many
        # arguments because we might be overwriting positional ones with kw ones
        if len(reqArgs) > len(args) + len(kwApiArgs):
            raise exceptions.TaskclusterFailure(
                '%s takes %d args, only %d were given' % (
                    entry['name'], len(reqArgs), len(args) + len(kwApiArgs)))

        # We also need to error out when we have more positional args than required
        # because we'll need to go through the lists of provided and required args
        # at the same time.  Not disqualifying early means we'll get IndexErrors if
        # there are more positional arguments than required
        if len(args) > len(reqArgs):
            raise exceptions.TaskclusterFailure('%s called with too many positional args',
                                                entry['name'])

        i = 0
        for arg in args:
            log.debug('Found a positional argument: %s', arg)
            routeParams[reqArgs[i]] = arg
            i += 1

        log.debug('After processing positional arguments, we have: %s', routeParams)

        routeParams.update(kwApiArgs)

        log.debug('After keyword arguments, we have: %s', routeParams)

        if len(reqArgs) != len(routeParams):
            errMsg = '%s takes %s args, %s given' % (
                entry['name'],
                ','.join(reqArgs),
                routeParams.keys())
            log.error(errMsg)
            raise exceptions.TaskclusterFailure(errMsg)

        for reqArg in reqArgs:
            if reqArg not in routeParams:
                errMsg = '%s requires a "%s" argument which was not provided' % (
                    entry['name'], reqArg)
                log.error(errMsg)
                raise exceptions.TaskclusterFailure(errMsg)

        return routeParams, payload, query, paginationHandler, paginationLimit

Response: This method takes a single entry and returns what the internal state of the object is.


Instruction:
Write a Python 3 script for
giving a route like "/task/<taskId > artifacts and a mapping like {"taskId": 12345 } return a string like "/task/<taskId > artifacts

Response:
def _subArgsInRoute(self, entry, args):
        """ Given a route like "/task/<taskId>/artifacts" and a mapping like
        {"taskId": "12345"}, return a string like "/task/12345/artifacts"
        """

        route = entry['route']

        for arg, val in six.iteritems(args):
            toReplace = "<%s>" % arg
            if toReplace not in route:
                raise exceptions.TaskclusterFailure(
                    'Arg %s not found in route for %s' % (arg, entry['name']))
            val = urllib.parse.quote(str(val).encode("utf-8"), '')
            route = route.replace("<%s>" % arg, val)

        return route.lstrip('/')


Instruction:
Make a summary of the following Python 3 code
def _hasCredentials(self):
        cred = self.options.get('credentials')
        return (
            cred and
            'clientId' in cred and
            'accessToken' in cred and
            cred['clientId'] and
            cred['accessToken']
        )

Response: Return True if credentials is given


Instruction:
Here you have a function in Python 3, explain what it does
def _makeHttpRequest(self, method, route, payload):

        url = self._constructUrl(route)
        log.debug('Full URL used is: %s', url)

        hawkExt = self.makeHawkExt()

        # Serialize payload if given
        if payload is not None:
            payload = utils.dumpJson(payload)

        # Do a loop of retries
        retry = -1  # we plus first in the loop, and attempt 1 is retry 0
        retries = self.options['maxRetries']
        while retry < retries:
            retry += 1
            # if this isn't the first retry then we sleep
            if retry > 0:
                time.sleep(utils.calculateSleepTime(retry))
            # Construct header
            if self._hasCredentials():
                sender = mohawk.Sender(
                    credentials={
                        'id': self.options['credentials']['clientId'],
                        'key': self.options['credentials']['accessToken'],
                        'algorithm': 'sha256',
                    },
                    ext=hawkExt if hawkExt else {},
                    url=url,
                    content=payload if payload else '',
                    content_type='application/json' if payload else '',
                    method=method,
                )

                headers = {'Authorization': sender.request_header}
            else:
                log.debug('Not using hawk!')
                headers = {}
            if payload:
                # Set header for JSON if payload is given, note that we serialize
                # outside this loop.
                headers['Content-Type'] = 'application/json'

            log.debug('Making attempt %d', retry)
            try:
                response = utils.makeSingleHttpRequest(method, url, payload, headers)
            except requests.exceptions.RequestException as rerr:
                if retry < retries:
                    log.warn('Retrying because of: %s' % rerr)
                    continue
                # raise a connection exception
                raise exceptions.TaskclusterConnectionError(
                    "Failed to establish connection",
                    superExc=rerr
                )

            # Handle non 2xx status code and retry if possible
            status = response.status_code
            if status == 204:
                return None

            # Catch retryable errors and go to the beginning of the loop
            # to do the retry
            if 500 <= status and status < 600 and retry < retries:
                log.warn('Retrying because of a %s status code' % status)
                continue

            # Throw errors for non-retryable errors
            if status < 200 or status >= 300:
                data = {}
                try:
                    data = response.json()
                except Exception:
                    pass  # Ignore JSON errors in error messages
                # Find error message
                message = "Unknown Server Error"
                if isinstance(data, dict):
                    message = data.get('message')
                else:
                    if status == 401:
                        message = "Authentication Error"
                    elif status == 500:
                        message = "Internal Server Error"
                # Raise TaskclusterAuthFailure if this is an auth issue
                if status == 401:
                    raise exceptions.TaskclusterAuthFailure(
                        message,
                        status_code=status,
                        body=data,
                        superExc=None
                    )
                # Raise TaskclusterRestFailure for all other issues
                raise exceptions.TaskclusterRestFailure(
                    message,
                    status_code=status,
                    body=data,
                    superExc=None
                )

            # Try to load JSON
            try:
                return response.json()
            except ValueError:
                return {"response": response}

        # This code-path should be unreachable
        assert False, "Error from last retry should have been raised!"

Response: This method is used to make an HTTP request for the Taskcluster API endpoint. It will attempt to make a single HTTP request.


Instruction:
Can you generate the documentation for the following Python 3 function
async def _makeHttpRequest(self, method, route, payload):

        url = self._constructUrl(route)
        log.debug('Full URL used is: %s', url)

        hawkExt = self.makeHawkExt()

        # Serialize payload if given
        if payload is not None:
            payload = utils.dumpJson(payload)

        # Do a loop of retries
        retry = -1  # we plus first in the loop, and attempt 1 is retry 0
        retries = self.options['maxRetries']
        while retry < retries:
            retry += 1
            # if this isn't the first retry then we sleep
            if retry > 0:
                snooze = float(retry * retry) / 10.0
                log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
                await asyncio.sleep(utils.calculateSleepTime(retry))
            # Construct header
            if self._hasCredentials():
                sender = mohawk.Sender(
                    credentials={
                        'id': self.options['credentials']['clientId'],
                        'key': self.options['credentials']['accessToken'],
                        'algorithm': 'sha256',
                    },
                    ext=hawkExt if hawkExt else {},
                    url=url,
                    content=payload if payload else '',
                    content_type='application/json' if payload else '',
                    method=method,
                )

                headers = {'Authorization': sender.request_header}
            else:
                log.debug('Not using hawk!')
                headers = {}
            if payload:
                # Set header for JSON if payload is given, note that we serialize
                # outside this loop.
                headers['Content-Type'] = 'application/json'

            log.debug('Making attempt %d', retry)
            try:
                response = await asyncutils.makeSingleHttpRequest(
                    method, url, payload, headers, session=self.session
                )
            except aiohttp.ClientError as rerr:
                if retry < retries:
                    log.warn('Retrying because of: %s' % rerr)
                    continue
                # raise a connection exception
                raise exceptions.TaskclusterConnectionError(
                    "Failed to establish connection",
                    superExc=rerr
                )

            status = response.status
            if status == 204:
                return None

            # Catch retryable errors and go to the beginning of the loop
            # to do the retry
            if 500 <= status and status < 600 and retry < retries:
                log.warn('Retrying because of a %s status code' % status)
                continue

            # Throw errors for non-retryable errors
            if status < 200 or status >= 300:
                # Parse messages from errors
                data = {}
                try:
                    data = await response.json()
                except Exception:
                    pass  # Ignore JSON errors in error messages
                # Find error message
                message = "Unknown Server Error"
                if isinstance(data, dict):
                    message = data.get('message')
                else:
                    if status == 401:
                        message = "Authentication Error"
                    elif status == 500:
                        message = "Internal Server Error"
                    else:
                        message = "Unknown Server Error %s\n%s" % (str(status), str(data)[:1024])
                # Raise TaskclusterAuthFailure if this is an auth issue
                if status == 401:
                    raise exceptions.TaskclusterAuthFailure(
                        message,
                        status_code=status,
                        body=data,
                        superExc=None
                    )
                # Raise TaskclusterRestFailure for all other issues
                raise exceptions.TaskclusterRestFailure(
                    message,
                    status_code=status,
                    body=data,
                    superExc=None
                )

            # Try to load JSON
            try:
                await response.release()
                return await response.json()
            except (ValueError, aiohttp.client_exceptions.ContentTypeError):
                return {"response": response}

        # This code-path should be unreachable
        assert False, "Error from last retry should have been raised!"

Response: This method is used to make an HTTP request for the API endpoint. It will attempt to make a new HTTP request.


Instruction:
How would you implement a function in Python 3 that
lists worker types with details Return a list of worker types, including some summary information about current capacity for each. While this list includes all defined worker types, there may be running EC2 instances for deleted worker types that are not included here. The list is unordered. This method gives output: ``http://schemas.taskcluster.net/aws-provisioner/v1/list-worker-types-summaries-response.json#`` This method is ``stable``

Response:
def listWorkerTypeSummaries(self, *args, **kwargs):
        """
        List worker types with details

        Return a list of worker types, including some summary information about
        current capacity for each.  While this list includes all defined worker types,
        there may be running EC2 instances for deleted worker types that are not
        included here.  The list is unordered.

        This method gives output: ``http://schemas.taskcluster.net/aws-provisioner/v1/list-worker-types-summaries-response.json#``

        This method is ``stable``
        """

        return self._makeApiCall(self.funcinfo["listWorkerTypeSummaries"], *args, **kwargs)


Instruction:
Write a Python 3 function for
getting Worker Type Last Modified Time This method is provided to allow workers to see when they were last modified. The value provided through UserData can be compared against this value to see if changes have been made If the worker type definition has not been changed, the date should be identical as it is the same stored value. This method gives output: ``http://schemas.taskcluster.net/aws-provisioner/v1/get-worker-type-last-modified.json#`` This method is ``stable``

Response:
def workerTypeLastModified(self, *args, **kwargs):
        """
        Get Worker Type Last Modified Time

        This method is provided to allow workers to see when they were
        last modified.  The value provided through UserData can be
        compared against this value to see if changes have been made
        If the worker type definition has not been changed, the date
        should be identical as it is the same stored value.

        This method gives output: ``http://schemas.taskcluster.net/aws-provisioner/v1/get-worker-type-last-modified.json#``

        This method is ``stable``
        """

        return self._makeApiCall(self.funcinfo["workerTypeLastModified"], *args, **kwargs)


Instruction:
Explain what the following Python 3 code does
def removeWorkerType(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["removeWorkerType"], *args, **kwargs)

Response: This method deletes a worker type definition from the storage table. This method is only applicable to background workers.


Instruction:
Can you tell what is the following Python 3 function doing
def getSecret(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["getSecret"], *args, **kwargs)

Response: Get a Secret from storage


Instruction:
Can you generate the documentation for the following Python 3 function
def instanceStarted(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["instanceStarted"], *args, **kwargs)

Response:
Report an instance starting by giving its id as well
        as its security token


Instruction:
Write a Python 3 script for
getting AWS State for a given worker type

Response:
def state(self, *args, **kwargs):
        """
        Get AWS State for a worker type

        Return the state of a given workertype as stored by the provisioner.
        This state is stored as three lists: 1 for running instances, 1 for
        pending requests.  The `summary` property contains an updated summary
        similar to that returned from `listWorkerTypeSummaries`.

        This method is ``stable``
        """

        return self._makeApiCall(self.funcinfo["state"], *args, **kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
async def set(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["set"], *args, **kwargs)

Response:
Set Secret

        Set the secret associated with some key.  If the secret already exists, it is
        updated instead.

        This method takes input: ``v1/secret.json#``

        This method is ``stable``


Instruction:
Implement a function in Python 3 to
delete a secret from a key set

Response:
async def remove(self, *args, **kwargs):
        """
        Delete Secret

        Delete the secret associated with some key.

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["remove"], *args, **kwargs)


Instruction:
Can you write a function in Python 3 where it
gets a specific key from the secret store

Response:
async def get(self, *args, **kwargs):
        """
        Read Secret

        Read the secret associated with some key.  If the secret has recently
        expired, the response code 410 is returned.  If the caller lacks the
        scope necessary to get the secret, the call will fail with a 403 code
        regardless of whether the secret exists.

        This method gives output: ``v1/secret.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["get"], *args, **kwargs)


Instruction:
Write a Python 3 function for
getting input from the command line and validates it.

Response:
def input_object(prompt_text, cast = None, default = None,
                 prompt_ext = ': ', castarg = [], castkwarg = {}):
    """Gets input from the command line and validates it.

    prompt_text
        A string. Used to prompt the user. Do not include a trailing
        space.

    prompt_ext
        Added on to the prompt at the end. At the moment this must not
        include any control stuff because it is send directly to
        raw_input

    cast
        This can be any callable object (class, function, type, etc). It
        simply calls the cast with the given arguements and returns the
        result. If a ValueError is raised, it
        will output an error message and prompt the user again.

        Because some builtin python objects don't do casting in the way
        that we might like you can easily write a wrapper function that
        looks and the input and returns the appropriate object or exception.
        Look in the cast submodule for examples.

        If cast is None, then it will do nothing (and you will have a string)

    default
        function returns this value if the user types nothing in. This is
        can be used to cancel the input so-to-speek

    castarg, castkwarg
        list and dictionary. Extra arguments passed on to the cast.
    """
    while True:
        stdout.write(prompt_text)
        value = stdout.raw_input(prompt_ext)
        if value == '': return default
        try:
            if cast != None: value = cast(value, *castarg, **castkwarg)
        except ValueError as details:
            if cast in NICE_INPUT_ERRORS: # see comment above this constant
                stderr.write(ERROR_MESSAGE % (NICE_INPUT_ERRORS[cast] % details))
            else: stderr.write(ERROR_MESSAGE % (DEFAULT_INPUT_ERRORS % str(details)))
            continue
        return value


Instruction:
Explain what the following Python 3 code does
def query(question, values, default=None, list_values = False, ignorecase = True ):
    values = list(values)
    for i in range(len(values)):
        if not isinstance(values[i], dict):
            values[i] = {'values': [values[i]]}
    try:
        import readline, rlcomplete
        wordlist = [ str(v) for value in values
                    for v in value['values']]
        completer = rlcomplete.ListCompleter(wordlist, ignorecase)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(completer.complete)
    except ImportError:
        pass
    valuelist = []
    for item in values:
        entry = ( display('bright', item.get('fg'), item.get('bg')) +
            str(item['values'][0]) + display(['default']) )
        if str(item['values'][0]) == str(default): entry = '['+entry+']'
        if list_values: entry += ' : ' + item['desc']
        valuelist.append(entry)
    if list_values: question += os.linesep + os.linesep.join(valuelist) + os.linesep
    else: question += ' (' + '/'.join(valuelist) + ')'
    return input_object(question, cast = query_cast, default=default,
                 castarg=[values,ignorecase])

Response: This function is used to query the user for a specific language of the language of the user.


Instruction:
Can you tell what is the following Python 3 function doing
def getHookStatus(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["getHookStatus"], *args, **kwargs)

Response: This endpoint returns the current status of the hook.


Instruction:
Implement a function in Python 3 to
create a hook This endpoint will create a new hook. The caller's credentials must include the role that will be used to create the task. That role must satisfy task.scopes as well as the necessary scopes to add the task to the queue. This method takes input: ``v1/create-hook-request.json#`` This method gives output: ``v1/hook-definition.json#`` This method is ``stable``

Response:
def createHook(self, *args, **kwargs):
        """
        Create a hook

        This endpoint will create a new hook.

        The caller's credentials must include the role that will be used to
        create the task.  That role must satisfy task.scopes as well as the
        necessary scopes to add the task to the queue.

        This method takes input: ``v1/create-hook-request.json#``

        This method gives output: ``v1/hook-definition.json#``

        This method is ``stable``
        """

        return self._makeApiCall(self.funcinfo["createHook"], *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def listLastFires(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["listLastFires"], *args, **kwargs)

Response: This endpoint returns information about the last few times this hook has been fired


Instruction:
Create a Python 3 function to
task Defined Messages When a task is created or just defined a message is posted to this exchange. This message exchange is mainly useful when tasks are scheduled by a scheduler that uses `defineTask` as this does not make the task `pending`. Thus, no `taskPending` message is published. Please, note that messages are also published on this exchange if defined using `createTask`. This exchange outputs: ``v1/task-defined-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required) * taskId: `taskId` for the task this message concerns (required) * runId: `runId` of latest run for the task, `_` if no run is exists for the task. * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. * provisionerId: `provisionerId` this task is targeted at. (required) * workerType: `workerType` this task must run on. (required) * schedulerId: `schedulerId` this task was created by. (required) * taskGroupId: `taskGroupId` this task was created in. (required) * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.

Response:
def taskDefined(self, *args, **kwargs):
        """
        Task Defined Messages

        When a task is created or just defined a message is posted to this
        exchange.

        This message exchange is mainly useful when tasks are scheduled by a
        scheduler that uses `defineTask` as this does not make the task
        `pending`. Thus, no `taskPending` message is published.
        Please, note that messages are also published on this exchange if defined
        using `createTask`.

        This exchange outputs: ``v1/task-defined-message.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskId: `taskId` for the task this message concerns (required)

         * runId: `runId` of latest run for the task, `_` if no run is exists for the task.

         * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task.

         * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task.

         * provisionerId: `provisionerId` this task is targeted at. (required)

         * workerType: `workerType` this task must run on. (required)

         * schedulerId: `schedulerId` this task was created by. (required)

         * taskGroupId: `taskGroupId` this task was created in. (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-defined',
            'name': 'taskDefined',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-defined-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
Write a Python 3 function that can
task Pending Messages When a task becomes `pending` a message is posted to this exchange. This is useful for workers who doesn't want to constantly poll the queue for new tasks. The queue will also be authority for task states and claims. But using this exchange workers should be able to distribute work efficiently and they would be able to reduce their polling interval significantly without affecting general responsiveness. This exchange outputs: ``v1/task-pending-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required) * taskId: `taskId` for the task this message concerns (required) * runId: `runId` of latest run for the task, `_` if no run is exists for the task. (required) * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. * provisionerId: `provisionerId` this task is targeted at. (required) * workerType: `workerType` this task must run on. (required) * schedulerId: `schedulerId` this task was created by. (required) * taskGroupId: `taskGroupId` this task was created in. (required) * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.

Response:
def taskPending(self, *args, **kwargs):
        """
        Task Pending Messages

        When a task becomes `pending` a message is posted to this exchange.

        This is useful for workers who doesn't want to constantly poll the queue
        for new tasks. The queue will also be authority for task states and
        claims. But using this exchange workers should be able to distribute work
        efficiently and they would be able to reduce their polling interval
        significantly without affecting general responsiveness.

        This exchange outputs: ``v1/task-pending-message.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskId: `taskId` for the task this message concerns (required)

         * runId: `runId` of latest run for the task, `_` if no run is exists for the task. (required)

         * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task.

         * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task.

         * provisionerId: `provisionerId` this task is targeted at. (required)

         * workerType: `workerType` this task must run on. (required)

         * schedulerId: `schedulerId` this task was created by. (required)

         * taskGroupId: `taskGroupId` this task was created in. (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-pending',
            'name': 'taskPending',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-pending-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def taskRunning(self, *args, **kwargs):

        ref = {
            'exchange': 'task-running',
            'name': 'taskRunning',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-running-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)

Response: This method is used to create the Task Running Messages in the base class. It is called by the worker to create the task running message.


Instruction:
How would you explain what the following Python 3 function does
def artifactCreated(self, *args, **kwargs):

        ref = {
            'exchange': 'artifact-created',
            'name': 'artifactCreated',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/artifact-created-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)

Response: The createArtifact method is called when the queue is created. This method is called when the queue is created and the message is published to the queue.


Instruction:
How would you code a function in Python 3 to
task Completed Messages When a task is successfully completed by a worker a message is posted this exchange. This message is routed using the `runId`, `workerGroup` and `workerId` that completed the task. But information about additional runs is also available from the task status structure. This exchange outputs: ``v1/task-completed-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required) * taskId: `taskId` for the task this message concerns (required) * runId: `runId` of latest run for the task, `_` if no run is exists for the task. (required) * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. (required) * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. (required) * provisionerId: `provisionerId` this task is targeted at. (required) * workerType: `workerType` this task must run on. (required) * schedulerId: `schedulerId` this task was created by. (required) * taskGroupId: `taskGroupId` this task was created in. (required) * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.

Response:
def taskCompleted(self, *args, **kwargs):
        """
        Task Completed Messages

        When a task is successfully completed by a worker a message is posted
        this exchange.
        This message is routed using the `runId`, `workerGroup` and `workerId`
        that completed the task. But information about additional runs is also
        available from the task status structure.

        This exchange outputs: ``v1/task-completed-message.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskId: `taskId` for the task this message concerns (required)

         * runId: `runId` of latest run for the task, `_` if no run is exists for the task. (required)

         * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. (required)

         * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. (required)

         * provisionerId: `provisionerId` this task is targeted at. (required)

         * workerType: `workerType` this task must run on. (required)

         * schedulerId: `schedulerId` this task was created by. (required)

         * taskGroupId: `taskGroupId` this task was created in. (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-completed',
            'name': 'taskCompleted',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-completed-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
How would you implement a function in Python 3 that
tasks Failed Messages When a task ran, but failed to complete successfully a message is posted to this exchange. This is same as worker ran task-specific code, but the task specific code exited non-zero. This exchange outputs: ``v1/task-failed-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required) * taskId: `taskId` for the task this message concerns (required) * runId: `runId` of latest run for the task, `_` if no run is exists for the task. * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. * provisionerId: `provisionerId` this task is targeted at. (required) * workerType: `workerType` this task must run on. (required) * schedulerId: `schedulerId` this task was created by. (required) * taskGroupId: `taskGroupId` this task was created in. (required) * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.

Response:
def taskFailed(self, *args, **kwargs):
        """
        Task Failed Messages

        When a task ran, but failed to complete successfully a message is posted
        to this exchange. This is same as worker ran task-specific code, but the
        task specific code exited non-zero.

        This exchange outputs: ``v1/task-failed-message.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskId: `taskId` for the task this message concerns (required)

         * runId: `runId` of latest run for the task, `_` if no run is exists for the task.

         * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task.

         * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task.

         * provisionerId: `provisionerId` this task is targeted at. (required)

         * workerType: `workerType` this task must run on. (required)

         * schedulerId: `schedulerId` this task was created by. (required)

         * taskGroupId: `taskGroupId` this task was created in. (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-failed',
            'name': 'taskFailed',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-failed-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
How would you code a function in Python 3 to
task Exception Messages Whenever Taskcluster fails to run a message is posted to this exchange. This happens if the task isn't completed before its `deadlìne`, all retries failed (i.e. workers stopped responding), the task was canceled by another entity, or the task carried a malformed payload. The specific _reason_ is evident from that task status structure, refer to the `reasonResolved` property for the last run. This exchange outputs: ``v1/task-exception-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required) * taskId: `taskId` for the task this message concerns (required) * runId: `runId` of latest run for the task, `_` if no run is exists for the task. * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task. * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task. * provisionerId: `provisionerId` this task is targeted at. (required) * workerType: `workerType` this task must run on. (required) * schedulerId: `schedulerId` this task was created by. (required) * taskGroupId: `taskGroupId` this task was created in. (required) * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.

Response:
def taskException(self, *args, **kwargs):
        """
        Task Exception Messages

        Whenever Taskcluster fails to run a message is posted to this exchange.
        This happens if the task isn't completed before its `deadlìne`,
        all retries failed (i.e. workers stopped responding), the task was
        canceled by another entity, or the task carried a malformed payload.

        The specific _reason_ is evident from that task status structure, refer
        to the `reasonResolved` property for the last run.

        This exchange outputs: ``v1/task-exception-message.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskId: `taskId` for the task this message concerns (required)

         * runId: `runId` of latest run for the task, `_` if no run is exists for the task.

         * workerGroup: `workerGroup` of latest run for the task, `_` if no run is exists for the task.

         * workerId: `workerId` of latest run for the task, `_` if no run is exists for the task.

         * provisionerId: `provisionerId` this task is targeted at. (required)

         * workerType: `workerType` this task must run on. (required)

         * schedulerId: `schedulerId` this task was created by. (required)

         * taskGroupId: `taskGroupId` this task was created in. (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-exception',
            'name': 'taskException',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskId',
                },
                {
                    'multipleWords': False,
                    'name': 'runId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerGroup',
                },
                {
                    'multipleWords': False,
                    'name': 'workerId',
                },
                {
                    'multipleWords': False,
                    'name': 'provisionerId',
                },
                {
                    'multipleWords': False,
                    'name': 'workerType',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-exception-message.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
How would you code a function in Python 3 to
task Group Resolved Messages

Response:
def taskGroupResolved(self, *args, **kwargs):
        """
        Task Group Resolved Messages

        A message is published on task-group-resolved whenever all submitted
        tasks (whether scheduled or unscheduled) for a given task group have
        been resolved, regardless of whether they resolved as successful or
        not. A task group may be resolved multiple times, since new tasks may
        be submitted against an already resolved task group.

        This exchange outputs: ``v1/task-group-resolved.json#``This exchange takes the following keys:

         * routingKeyKind: Identifier for the routing-key kind. This is always `'primary'` for the formalized routing key. (required)

         * taskGroupId: `taskGroupId` for the task-group this message concerns (required)

         * schedulerId: `schedulerId` for the task-group this message concerns (required)

         * reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
        """

        ref = {
            'exchange': 'task-group-resolved',
            'name': 'taskGroupResolved',
            'routingKey': [
                {
                    'constant': 'primary',
                    'multipleWords': False,
                    'name': 'routingKeyKind',
                },
                {
                    'multipleWords': False,
                    'name': 'taskGroupId',
                },
                {
                    'multipleWords': False,
                    'name': 'schedulerId',
                },
                {
                    'multipleWords': True,
                    'name': 'reserved',
                },
            ],
            'schema': 'v1/task-group-resolved.json#',
        }
        return self._makeTopicExchange(ref, *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def matchuserhome(prefix):
        if not prefix.startswith('~'):
            raise ValueError("prefix must start with ~")
        try: import pwd
        except ImportError:
            try: import winpwd as pwd
            except ImportError: return []
        return ['~' + u[0] for u in pwd.getpwall() if u[0].startswith(prefix[1:])]

Response: To find matches that start with prefix. This function returns a list of possible matches in form of [ ~user ~user.


Instruction:
Explain what the following Python 3 code does
def completelist(self, text):
        path = os.path.expanduser(text)
        if len(path) == 0 or path[0] != os.path.sep:
            path = os.path.join(os.getcwd(), path)
        if text == '~':
            dpath = dtext = ''
            bpath = '~'
            files = ['~/']
        elif text.startswith('~') and text.find('/', 1) < 0:
            return self.matchuserhome(text)
        else:
            dtext = os.path.dirname(text)
            dpath = os.path.dirname(path)
            bpath = os.path.basename(path)
            files = os.listdir(dpath)
        if bpath =='':
            matches = [self.buildpath(text, f) for f in files if not f.startswith('.')]
        else:
            matches = [self.buildpath(dtext, f) for f in files if f.startswith(bpath)]
        if len(matches) == 0 and os.path.basename(path)=='..':
            files = os.listdir(path)
            matches = [os.path.join(text, f) for f in files]
        return matches

Response:
Return a list of potential matches for completion

        n. b. you want to complete to a file in the current working directory that starts with ~


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def status(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["status"], *args, **kwargs)

Response:
Get task status

        Get task status structure from `taskId`

        This method gives output: ``v1/task-status-response.json#``

        This method is ``stable``


Instruction:
How would you explain what the following Python 3 function does
async def listTaskGroup(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["listTaskGroup"], *args, **kwargs)

Response:
List Task Group

        List tasks sharing the same `taskGroupId`.

        As a task-group may contain an unbounded number of tasks, this end-point
        may return a `continuationToken`. To continue listing tasks you must call
        the `listTaskGroup` again with the `continuationToken` as the
        query-string option `continuationToken`.

        By default this end-point will try to return up to 1000 members in one
        request. But it **may return less**, even if more tasks are available.
        It may also return a `continuationToken` even though there are no more
        results. However, you can only be sure to have seen all results if you
        keep calling `listTaskGroup` with the last `continuationToken` until you
        get a result without a `continuationToken`.

        If you are not interested in listing all the members at once, you may
        use the query-string option `limit` to return fewer.

        This method gives output: ``v1/list-task-group-response.json#``

        This method is ``stable``


Instruction:
Create a Python 3 function to
list Dependent Tasks This method returns a list of tasks that depend on the given taskId.

Response:
async def listDependentTasks(self, *args, **kwargs):
        """
        List Dependent Tasks

        List tasks that depend on the given `taskId`.

        As many tasks from different task-groups may dependent on a single tasks,
        this end-point may return a `continuationToken`. To continue listing
        tasks you must call `listDependentTasks` again with the
        `continuationToken` as the query-string option `continuationToken`.

        By default this end-point will try to return up to 1000 tasks in one
        request. But it **may return less**, even if more tasks are available.
        It may also return a `continuationToken` even though there are no more
        results. However, you can only be sure to have seen all results if you
        keep calling `listDependentTasks` with the last `continuationToken` until
        you get a result without a `continuationToken`.

        If you are not interested in listing all the tasks at once, you may
        use the query-string option `limit` to return fewer.

        This method gives output: ``v1/list-dependent-tasks-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["listDependentTasks"], *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def createTask(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["createTask"], *args, **kwargs)

Response: Create a new task in the scheduler.


Instruction:
Write a Python 3 script for
claiming pending tasks for the given provisionerId and workerType queue.

Response:
async def claimWork(self, *args, **kwargs):
        """
        Claim Work

        Claim pending task(s) for the given `provisionerId`/`workerType` queue.

        If any work is available (even if fewer than the requested number of
        tasks, this will return immediately. Otherwise, it will block for tens of
        seconds waiting for work.  If no work appears, it will return an emtpy
        list of tasks.  Callers should sleep a short while (to avoid denial of
        service in an error condition) and call the endpoint again.  This is a
        simple implementation of "long polling".

        This method takes input: ``v1/claim-work-request.json#``

        This method gives output: ``v1/claim-work-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["claimWork"], *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def reclaimTask(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["reclaimTask"], *args, **kwargs)

Response: Reclaim a task from a specific runId.


Instruction:
Here you have a function in Python 3, explain what it does
async def getArtifact(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["getArtifact"], *args, **kwargs)

Response: Get an artifact from a specific run.


Instruction:
Write a Python 3 function that can
get Artifacts from Run

Response:
async def listArtifacts(self, *args, **kwargs):
        """
        Get Artifacts from Run

        Returns a list of artifacts and associated meta-data for a given run.

        As a task may have many artifacts paging may be necessary. If this
        end-point returns a `continuationToken`, you should call the end-point
        again with the `continuationToken` as the query-string option:
        `continuationToken`.

        By default this end-point will list up-to 1000 artifacts in a single page
        you may limit this with the query-string parameter `limit`.

        This method gives output: ``v1/list-artifacts-response.json#``

        This method is ``experimental``
        """

        return await self._makeApiCall(self.funcinfo["listArtifacts"], *args, **kwargs)


Instruction:
Make a summary of the following Python 3 code
async def getWorkerType(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["getWorkerType"], *args, **kwargs)

Response: This method returns a worker - type from a provisioner.


Instruction:
Write a Python 3 function that can
update a worker-type Declare a workerType, supplying some details about it. `declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are possessed. For example, a request to update the `gecko-b-1-w2008` worker-type within the `aws-provisioner-v1` provisioner with a body `{description: 'This worker type is great'}` would require you to have the scope `queue:declare-worker-type:aws-provisioner-v1/gecko-b-1-w2008#description`. This method takes input: ``v1/update-workertype-request.json#`` This method gives output: ``v1/workertype-response.json#`` This method is ``experimental``

Response:
async def declareWorkerType(self, *args, **kwargs):
        """
        Update a worker-type

        Declare a workerType, supplying some details about it.

        `declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are
        possessed. For example, a request to update the `gecko-b-1-w2008` worker-type within the `aws-provisioner-v1`
        provisioner with a body `{description: 'This worker type is great'}` would require you to have the scope
        `queue:declare-worker-type:aws-provisioner-v1/gecko-b-1-w2008#description`.

        This method takes input: ``v1/update-workertype-request.json#``

        This method gives output: ``v1/workertype-response.json#``

        This method is ``experimental``
        """

        return await self._makeApiCall(self.funcinfo["declareWorkerType"], *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def listWorkers(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["listWorkers"], *args, **kwargs)

Response: This method returns a list of all active workers of a workerType.


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def getWorker(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["getWorker"], *args, **kwargs)

Response: Get a worker from a worker - type.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def file(value, **kwarg):
    #a bit weird, but I don't want to hard code default values
    try:
        f = open(value, **kwarg)
    except IOError as e:
        raise ValueError("unable to open %s : %s" % (path.abspath(value), e))
    return f

Response: returns a file object


Instruction:
Can you generate the documentation for the following Python 3 function
def calculateSleepTime(attempt):
    if attempt <= 0:
        return 0

    # We subtract one to get exponents: 1, 2, 3, 4, 5, ..
    delay = float(2 ** (attempt - 1)) * float(DELAY_FACTOR)
    # Apply randomization factor
    delay = delay * (RANDOMIZATION_FACTOR * (random.random() * 2 - 1) + 1)
    # Always limit with a maximum delay
    return min(delay, MAX_DELAY)

Response: Calculate sleep time based on the attempt number.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fromNow(offset, dateObj=None):

    # We want to handle past dates as well as future
    future = True
    offset = offset.lstrip()
    if offset.startswith('-'):
        future = False
        offset = offset[1:].lstrip()
    if offset.startswith('+'):
        offset = offset[1:].lstrip()

    # Parse offset
    m = r.match(offset)
    if m is None:
        raise ValueError("offset string: '%s' does not parse" % offset)

    # In order to calculate years and months we need to calculate how many days
    # to offset the offset by, since timedelta only goes as high as weeks
    days = 0
    hours = 0
    minutes = 0
    seconds = 0
    if m.group('years'):
        years = int(m.group('years'))
        days += 365 * years
    if m.group('months'):
        months = int(m.group('months'))
        days += 30 * months
    days += int(m.group('days') or 0)
    hours += int(m.group('hours') or 0)
    minutes += int(m.group('minutes') or 0)
    seconds += int(m.group('seconds') or 0)

    # Offset datetime from utc
    delta = datetime.timedelta(
        weeks=int(m.group('weeks') or 0),
        days=days,
        hours=hours,
        minutes=minutes,
        seconds=seconds,
    )

    if not dateObj:
        dateObj = datetime.datetime.utcnow()

    return dateObj + delta if future else dateObj - delta

Response: Generate a datetime. datetime instance which is offset using a string.


Instruction:
Make a summary of the following Python 3 code
def dumpJson(obj, **kwargs):
    def handleDateAndBinaryForJs(x):
        if six.PY3 and isinstance(x, six.binary_type):
            x = x.decode()
        if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
            return stringDate(x)
        else:
            return x
    d = json.dumps(obj, separators=(',', ':'), default=handleDateAndBinaryForJs, **kwargs)
    assert '\n' not in d
    return d

Response: Match JS s JSON. stringify.


Instruction:
Can you create a Python 3 function that
makes a base64 string URL Safe

Response:
def makeB64UrlSafe(b64str):
    """ Make a base64 string URL Safe """
    if isinstance(b64str, six.text_type):
        b64str = b64str.encode()
    # see RFC 4648, sec. 5
    return b64str.replace(b'+', b'-').replace(b'/', b'_')


Instruction:
Explain what the following Python 3 code does
def encodeStringForB64Header(s):
    if isinstance(s, six.text_type):
        s = s.encode()
    return base64.encodestring(s).strip().replace(b'\n', b'')

Response: Encodes a string for use in a base64 - encoded HTTP header.


Instruction:
Given the following Python 3 function, write the documentation
def stableSlugId():
    _cache = {}

    def closure(name):
        if name not in _cache:
            _cache[name] = slugId()
        return _cache[name]

    return closure

Response: Returns a closure which can be used to generate stable slugIds for a single node.


Instruction:
Can you implement a function in Python 3 that
returns True if all of the required scope sets in the list of assumed scopes are satisfied.

Response:
def scopeMatch(assumedScopes, requiredScopeSets):
    """
        Take a list of a assumed scopes, and a list of required scope sets on
        disjunctive normal form, and check if any of the required scope sets are
        satisfied.

        Example:

            requiredScopeSets = [
                ["scopeA", "scopeB"],
                ["scopeC"]
            ]

        In this case assumed_scopes must contain, either:
        "scopeA" AND "scopeB", OR just "scopeC".
    """
    for scopeSet in requiredScopeSets:
        for requiredScope in scopeSet:
            for scope in assumedScopes:
                if scope == requiredScope:
                    # requiredScope satisifed, no need to check more scopes
                    break
                if scope.endswith("*") and requiredScope.startswith(scope[:-1]):
                    # requiredScope satisifed, no need to check more scopes
                    break
            else:
                # requiredScope not satisfied, stop checking scopeSet
                break
        else:
            # scopeSet satisfied, so we're happy
            return True
    # none of the requiredScopeSets were satisfied
    return False


Instruction:
Here you have a function in Python 3, explain what it does
def makeHttpRequest(method, url, payload, headers, retries=MAX_RETRIES, session=None):
    retry = -1
    response = None
    while retry < retries:
        retry += 1
        # if this isn't the first retry then we sleep
        if retry > 0:
            snooze = float(retry * retry) / 10.0
            log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
            time.sleep(snooze)

        # Seek payload to start, if it is a file
        if hasattr(payload, 'seek'):
            payload.seek(0)

        log.debug('Making attempt %d', retry)
        try:
            response = makeSingleHttpRequest(method, url, payload, headers, session)
        except requests.exceptions.RequestException as rerr:
            if retry < retries:
                log.warn('Retrying because of: %s' % rerr)
                continue
            # raise a connection exception
            raise rerr
        # Handle non 2xx status code and retry if possible
        try:
            response.raise_for_status()
        except requests.exceptions.RequestException:
            pass
        status = response.status_code
        if 500 <= status and status < 600 and retry < retries:
            if retry < retries:
                log.warn('Retrying because of: %d status' % status)
                continue
            else:
                raise exceptions.TaskclusterRestFailure("Unknown Server Error", superExc=None)
        return response

    # This code-path should be unreachable
    assert False, "Error from last retry should have been raised!"

Response: Make an HTTP request and retry it until success.


Instruction:
Can you implement a function in Python 3 that
checks if certificate is expired

Response:
def isExpired(certificate):
    """ Check if certificate is expired """
    if isinstance(certificate, six.string_types):
        certificate = json.loads(certificate)
    expiry = certificate.get('expiry', 0)
    return expiry < int(time.time() * 1000) + 20 * 60


Instruction:
Can you implement a function in Python 3 that
fetches root URL and credentials from the standard TASKCLUSTER_… environment variables and return them in a format suitable for passing to a client constructor.

Response:
def optionsFromEnvironment(defaults=None):
    """Fetch root URL and credentials from the standard TASKCLUSTER_…
    environment variables and return them in a format suitable for passing to a
    client constructor."""
    options = defaults or {}
    credentials = options.get('credentials', {})

    rootUrl = os.environ.get('TASKCLUSTER_ROOT_URL')
    if rootUrl:
        options['rootUrl'] = rootUrl

    clientId = os.environ.get('TASKCLUSTER_CLIENT_ID')
    if clientId:
        credentials['clientId'] = clientId

    accessToken = os.environ.get('TASKCLUSTER_ACCESS_TOKEN')
    if accessToken:
        credentials['accessToken'] = accessToken

    certificate = os.environ.get('TASKCLUSTER_CERTIFICATE')
    if certificate:
        credentials['certificate'] = certificate

    if credentials:
        options['credentials'] = credentials

    return options


Instruction:
Explain what the following Python 3 code does
def xterm_to_rgb(xcolor):
    assert 0 <= xcolor <= 255
    if xcolor < 16:
        # basic colors
        return BASIC16[xcolor]
    elif 16 <= xcolor <= 231:
        # color cube
        xcolor -= 16
        return (CUBE_STEPS[xcolor // 36 % 6],
                CUBE_STEPS[xcolor // 6 % 6],
                CUBE_STEPS[xcolor % 6])
    elif 232 <= xcolor <= 255:
        # gray tone
        c = 8 + (xcolor - 232) * 0x0A
        return (c, c, c)

Response: Convert an xterm Color ID to an RGB value.


Instruction:
Explain what the following Python 3 code does
def rgb_to_xterm(r, g, b):
    if r < 5 and g < 5 and b < 5:
        return 16
    best_match = 0
    smallest_distance = 10000000000
    for c in range(16, 256):
        d = (COLOR_TABLE[c][0] - r) ** 2 + \
            (COLOR_TABLE[c][1] - g) ** 2 + \
            (COLOR_TABLE[c][2] - b) ** 2
        if d < smallest_distance:
            smallest_distance = d
            best_match = c
    return best_match

Response: Quantize RGB values to an xterm 256 - color ID


Instruction:
How would you explain what the following Python 3 function does
def compile_speedup():
    import os
    import ctypes
    from os.path import join, dirname, getmtime, exists, expanduser
    # library = join(dirname(__file__), '_xterm256.so')
    library = expanduser('~/.xterm256.so')
    sauce = join(dirname(__file__), '_xterm256.c')
    if not exists(library) or getmtime(sauce) > getmtime(library):
        build = "gcc -fPIC -shared -o %s %s" % (library, sauce)
        if (os.system(build + " >/dev/null 2>&1") != 0):
            raise OSError("GCC error")
    xterm256_c = ctypes.cdll.LoadLibrary(library)
    xterm256_c.init()
    def xterm_to_rgb(xcolor):
        res = xterm256_c.xterm_to_rgb_i(xcolor)
        return ((res >> 16) & 0xFF, (res >> 8) & 0xFF, res & 0xFF)
    return (xterm256_c.rgb_to_xterm, xterm_to_rgb)

Response: Try to compile the C version of this module.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main():
    import optparse
    parser = optparse.OptionParser()
    parser.add_option(
        "-w", "--width", dest="width", type="int", default=None,
        help=("Width of printed image in characters.  Default: %default"))
    (options, args) = parser.parse_args(args=sys.argv[1:])
    for imgpath in args:
        for line in Image(imgpath, options.width):
            printy(line)

Response: Main function for the catulous - image command.


Instruction:
Can you tell what is the following Python 3 function doing
def reduce(self, colors):
        need_reset = False
        line = []
        for color, items in itertools.groupby(colors):
            if color is None:
                if need_reset:
                    line.append("\x1b[49m")
                    need_reset = False
                line.append(self.pad * len(list(items)))
            elif color == "EOL":
                if need_reset:
                    line.append("\x1b[49m")
                    need_reset = False
                    yield "".join(line)
                else:
                    line.pop()
                    yield "".join(line)
                line = []
            else:
                need_reset = True
                line.append("\x1b[48;5;%dm%s" % (
                    color, self.pad * len(list(items))))

Response: Reduces the color codes into optimized text.


Instruction:
Given the following Python 3 function, write the documentation
def convert(self):
        (width, height) = self.img.size
        bgcolor = utils.term.bgcolor
        self.img.load()
        for y in range(height):
            for x in range(width):
                rgba = self.img.getpixel((x, y))
                if len(rgba) == 4 and rgba[3] == 0:
                    yield None
                elif len(rgba) == 3 or rgba[3] == 255:
                    yield xterm256.rgb_to_xterm(*rgba[:3])
                else:
                    color = grapefruit.Color.NewFromRgb(
                        *[c / 255.0 for c in rgba])
                    rgba = grapefruit.Color.AlphaBlend(color, bgcolor).rgb
                    yield xterm256.rgb_to_xterm(
                        *[int(c * 255.0) for c in rgba])
            yield "EOL"

Response: Yields xterm color codes for each pixel in image


Instruction:
Implement a function in Python 3 to
get Taskcluster credentials given a suitable `access_token` Given an OIDC `access_token` from a trusted OpenID provider, return a set of Taskcluster credentials for use on behalf of the identified user. This method is typically not called with a Taskcluster client library and does not accept Hawk credentials. The `access_token` should be given in an `Authorization` header: ``` Authorization: Bearer abc.xyz ``` The `access_token` is first verified against the named :provider, then passed to the provider's APIBuilder to retrieve a user profile. That profile is then used to generate Taskcluster credentials appropriate to the user. Note that the resulting credentials may or may not include a `certificate` property. Callers should be prepared for either alternative. The given credentials will expire in a relatively short time. Callers should monitor this expiration and refresh the credentials if necessary, by calling this endpoint again, if they have expired. This method gives output: ``v1/oidc-credentials-response.json#`` This method is ``experimental``

Response:
def oidcCredentials(self, *args, **kwargs):
        """
        Get Taskcluster credentials given a suitable `access_token`

        Given an OIDC `access_token` from a trusted OpenID provider, return a
        set of Taskcluster credentials for use on behalf of the identified
        user.

        This method is typically not called with a Taskcluster client library
        and does not accept Hawk credentials. The `access_token` should be
        given in an `Authorization` header:
        ```
        Authorization: Bearer abc.xyz
        ```

        The `access_token` is first verified against the named
        :provider, then passed to the provider's APIBuilder to retrieve a user
        profile. That profile is then used to generate Taskcluster credentials
        appropriate to the user. Note that the resulting credentials may or may
        not include a `certificate` property. Callers should be prepared for either
        alternative.

        The given credentials will expire in a relatively short time. Callers should
        monitor this expiration and refresh the credentials if necessary, by calling
        this endpoint again, if they have expired.

        This method gives output: ``v1/oidc-credentials-response.json#``

        This method is ``experimental``
        """

        return self._makeApiCall(self.funcinfo["oidcCredentials"], *args, **kwargs)


Instruction:
Create a Python 3 function to
list of Builds A paginated list of builds that have been run in Taskcluster. Can be filtered on various git-specific fields. This method gives output: ``v1/build-list.json#`` This method is ``experimental``

Response:
async def builds(self, *args, **kwargs):
        """
        List of Builds

        A paginated list of builds that have been run in
        Taskcluster. Can be filtered on various git-specific
        fields.

        This method gives output: ``v1/build-list.json#``

        This method is ``experimental``
        """

        return await self._makeApiCall(self.funcinfo["builds"], *args, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def repository(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["repository"], *args, **kwargs)

Response:
Get Repository Info

        Returns any repository metadata that is
        useful within Taskcluster related services.

        This method gives output: ``v1/repository.json#``

        This method is ``experimental``


Instruction:
How would you code a function in Python 3 to
create a status for a given changeset.

Response:
async def createStatus(self, *args, **kwargs):
        """
        Post a status against a given changeset

        For a given changeset (SHA) of a repository, this will attach a "commit status"
        on github. These statuses are links displayed next to each revision.
        The status is either OK (green check) or FAILURE (red cross),
        made of a custom title and link.

        This method takes input: ``v1/create-status.json#``

        This method is ``experimental``
        """

        return await self._makeApiCall(self.funcinfo["createStatus"], *args, **kwargs)


Instruction:
How would you explain what the following Python 3 function does
async def email(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["email"], *args, **kwargs)

Response: Send an email to a specific address


Instruction:
Can you generate the documentation for the following Python 3 function
async def pulse(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["pulse"], *args, **kwargs)

Response: This method is used to publish a message on a pulse with the given routingKey.


Instruction:
Make a summary of the following Python 3 code
async def resetAccessToken(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["resetAccessToken"], *args, **kwargs)

Response: Reset an existing accessToken


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def role(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["role"], *args, **kwargs)

Response: Get information about a single role


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def azureAccounts(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["azureAccounts"], *args, **kwargs)

Response: This method returns a list of all Azure accounts managed by Taskcluster Auth.


Instruction:
Can you write a function in Python 3 where it
authenticates Hawk Request Validate the request signature given on input and return list of scopes that the authenticating client has. This method is used by other services that wish rely on Taskcluster credentials for authentication. This way we can use Hawk without having the secret credentials leave this service. This method takes input: ``v1/authenticate-hawk-request.json#`` This method gives output: ``v1/authenticate-hawk-response.json#`` This method is ``stable``

Response:
async def authenticateHawk(self, *args, **kwargs):
        """
        Authenticate Hawk Request

        Validate the request signature given on input and return list of scopes
        that the authenticating client has.

        This method is used by other services that wish rely on Taskcluster
        credentials for authentication. This way we can use Hawk without having
        the secret credentials leave this service.

        This method takes input: ``v1/authenticate-hawk-request.json#``

        This method gives output: ``v1/authenticate-hawk-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["authenticateHawk"], *args, **kwargs)


Instruction:
Write a Python 3 script to
list hook groups This endpoint will return a list of all hook groups with at least one hook. This method gives output: ``v1/list-hook-groups-response.json#`` This method is ``stable``

Response:
async def listHookGroups(self, *args, **kwargs):
        """
        List hook groups

        This endpoint will return a list of all hook groups with at least one hook.

        This method gives output: ``v1/list-hook-groups-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["listHookGroups"], *args, **kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
async def listHooks(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["listHooks"], *args, **kwargs)

Response: This endpoint returns a list of all the hook definitions within a given hook group.


Instruction:
Explain what the following Python 3 code does
async def hook(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["hook"], *args, **kwargs)

Response: Get the hook definition for the given hookGroupId and hookId


Instruction:
Can you generate the documentation for the following Python 3 function
async def updateHook(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["updateHook"], *args, **kwargs)

Response: This endpoint updates a hook in the specified hierarchy.


Instruction:
Create a Python 3 function to
delete a hook This endpoint will remove a hook definition. This method is ``stable``

Response:
async def removeHook(self, *args, **kwargs):
        """
        Delete a hook

        This endpoint will remove a hook definition.

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["removeHook"], *args, **kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
async def triggerHook(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["triggerHook"], *args, **kwargs)

Response: Trigger a hook that creates a new task from a hook definition.


Instruction:
Make a summary of the following Python 3 code
async def getTriggerToken(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["getTriggerToken"], *args, **kwargs)

Response: This method returns a unique secret token for the specified hook.


Instruction:
How would you code a function in Python 3 to
reset a trigger token for a given hook

Response:
async def resetTriggerToken(self, *args, **kwargs):
        """
        Reset a trigger token

        Reset the token for triggering a given hook. This invalidates token that
        may have been issued via getTriggerToken with a new token.

        This method gives output: ``v1/trigger-token-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["resetTriggerToken"], *args, **kwargs)


Instruction:
Implement a Python 3 function for
triggering a hook with a valid token.

Response:
async def triggerHookWithToken(self, *args, **kwargs):
        """
        Trigger a hook with a token

        This endpoint triggers a defined hook with a valid token.

        The HTTP payload must match the hooks `triggerSchema`.  If it does, it is
        provided as the `payload` property of the JSON-e context used to render the
        task template.

        This method takes input: ``v1/trigger-hook.json#``

        This method gives output: ``v1/trigger-hook-response.json#``

        This method is ``stable``
        """

        return await self._makeApiCall(self.funcinfo["triggerHookWithToken"], *args, **kwargs)