def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
               arg_5=None, arg_6=None, **arg_7):
        """Create a webhook.

        Args:
            name(basestring): A user-friendly name for this webhook.
            targetUrl(basestring): The URL that receives POST requests for
                each event.
            resource(basestring): The resource type for the webhook.
            event(basestring): The event type for the webhook.
            filter(basestring): The filter that defines the webhook scope.
            secret(basestring): The secret used to generate payload signature.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Webhook: A Webhook object with the details of the Funcd webhook.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)
        check_type(arg_2, basestring, may_be_none=False)
        check_type(arg_3, basestring, may_be_none=False)
        check_type(arg_4, basestring, may_be_none=False)
        check_type(arg_5, basestring)
        check_type(arg_6, basestring)

        arg_8 = dict_from_items_with_values(
            arg_7,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
        )

        # API request
        arg_9 = arg_0._session.post(API_ENDPOINT, json=arg_8)

        # Return a webhook object Funcd from the response JSON data
        return arg_0._object_factory(OBJECT_TYPE, arg_9)


def Func(arg_0, arg_1):
        """Update the HTTP headers used for requests in this session.

        Note: Updates provided by the dictionary passed as the `headers`
        parameter to this method are merged into the session headers by adding
        new key-value pairs and/or updating the values of existing keys. The
        session headers are not replaced by the provided dictionary.

        Args:
             headers(dict): Updates to the current session headers.

        """
        check_type(arg_1, dict, may_be_none=False)
        arg_0._req_session.headers.update(arg_1)


def Func(arg_0, arg_1):
        """Given a relative or absolute URL; return an absolute URL.

        Args:
            url(basestring): A relative or absolute URL.

        Returns:
            str: An absolute URL.

        """
        arg_2 = urllib.parse.urlparse(arg_1)
        if not arg_2.scheme and not arg_2.netloc:
            # url is a relative URL; combine with base_url
            return urllib.parse.urljoin(str(arg_0.base_url), str(arg_1))
        else:
            # url is already an absolute URL; return as is
            return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, **arg_4):
        """Abstract base method for making Funcs to the Webex Teams APIs.

        This base method:
            * Expands the API endpoint URL to an absolute URL
            * Makes the actual HTTP Func to the API endpoint
            * Provides support for Webex Teams rate-limiting
            * Inspects response codes and raises exceptions as appropriate

        Args:
            method(basestring): The Func-method type ('GET', 'POST', etc.).
            url(basestring): The URL of the API endpoint to be called.
            erc(int): The expected response code that should be returned by the
                Webex Teams API endpoint to indicate success.
            **kwargs: Passed on to the Funcs package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.

        """
        # Ensure the url is an absolute URL
        arg_5 = arg_0.abs_url(arg_2)

        # Update Func kwargs with session defaults
        arg_4.setdefault('timeout', arg_0.single_Func_timeout)

        while True:
            # Make the HTTP Func to the API endpoint
            arg_6 = arg_0._req_session.Func(arg_1, arg_5, **arg_4)

            try:
                # Check the response code for error conditions
                check_response_code(arg_6, arg_3)
            except RateLimitError as e:
                # Catch rate-limit errors
                # Wait and retry if automatic rate-limit handling is enabled
                if arg_0.wait_on_rate_limit:
                    warnings.warn(RateLimitWarning(arg_6))
                    time.sleep(e.retry_after)
                    continue
                else:
                    # Re-raise the RateLimitError
                    raise
            else:
                return arg_6


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        """Sends a GET request.

        Args:
            url(basestring): The URL of the API endpoint.
            params(dict): The parameters for the HTTP GET request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.

        """
        check_type(arg_1, basestring, may_be_none=False)
        check_type(arg_2, dict)

        # Expected response code
        arg_4 = arg_3.pop('erc', EXPECTED_RESPONSE_CODE['GET'])

        arg_5 = arg_0.request('GET', arg_1, arg_4, arg_2=arg_2, **arg_3)
        return extract_and_parse_json(arg_5)


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        """Return a generator that GETs and yields pages of data.

        Provides native support for RFC5988 Web Linking.

        Args:
            url(basestring): The URL of the API endpoint.
            params(dict): The parameters for the HTTP GET request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.

        """
        check_type(arg_1, basestring, may_be_none=False)
        check_type(arg_2, dict)

        # Expected response code
        arg_4 = arg_3.pop('erc', EXPECTED_RESPONSE_CODE['GET'])

        # First request
        arg_5 = arg_0.request('GET', arg_1, arg_4, arg_2=arg_2, **arg_3)

        while True:
            yield extract_and_parse_json(arg_5)

            if arg_5.links.get('next'):
                arg_6 = arg_5.links.get('next').get('url')

                # Patch for Webex Teams 'max=null' in next URL bug.
                # Testing shows that patch is no longer needed; raising a
                # warnning if it is still taking effect;
                # considering for future removal
                arg_6 = _fix_next_url(arg_6)

                # Subsequent requests
                arg_5 = arg_0.request('GET', arg_6, arg_4, **arg_3)

            else:
                break


def Func(arg_0, arg_1, **arg_2):
        """Sends a DELETE request.

        Args:
            url(basestring): The URL of the API endpoint.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.

        """
        check_type(arg_1, basestring, may_be_none=False)

        # Expected response code
        arg_3 = arg_2.pop('erc', EXPECTED_RESPONSE_CODE['DELETE'])

        arg_0.request('DELETE', arg_1, arg_3, **arg_2)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """Create a new guest issuer using the provided issuer token.

        This function returns a guest issuer with an api access token.

        Args:
            subject(basestring): Unique and public identifier
            displayName(basestring): Display Name of the guest user
            issuerToken(basestring): Issuer token from developer hub
            expiration(basestring): Expiration time as a unix timestamp
            secret(basestring): The secret used to sign your guest issuers

        Returns:
            GuestIssuerToken: A Guest Issuer with a valid access token.

        Raises:
            TypeError: If the parameter types are incorrect
            ApiError: If the webex teams cloud returns an error.
        """
        check_type(arg_1, basestring)
        check_type(arg_2, basestring)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, basestring)

        arg_6 = {
            "sub": arg_1,
            "name": arg_2,
            "iss": arg_3,
            "exp": arg_4
        }

        arg_7 = base64.b64decode(arg_5)
        arg_8 = jwt.encode(arg_6, arg_7, algorithm='HS256')

        arg_9 = arg_0._session.base_url + API_ENDPOINT + "/" + "login"
        arg_10 = {
            'Authorization': "Bearer " + arg_8.decode('utf-8')
        }
        arg_11 = requests.post(arg_9, arg_10=arg_10)
        check_response_code(arg_11, EXPECTED_RESPONSE_CODE['GET'])

        return arg_0._object_factory(OBJECT_TYPE, arg_11.json())


def Func(arg_0, arg_1, arg_2=None, arg_3=None,
             arg_4=None, arg_5=None, **arg_6):
        """Lists messages in a room.

        Each message will include content attachments if present.

        The Func API sorts the messages in descending order by creation date.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all messages returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            roomId(basestring): List messages for a room, by ID.
            mentionedPeople(basestring): List messages where the caller is
                mentioned by specifying "me" or the caller `personId`.
            before(basestring): List messages sent before a date and time, in
                ISO8601 format.
            beforeMessage(basestring): List messages sent before a message,
                by ID.
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the messages returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)
        check_type(arg_2, basestring)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, int)

        arg_7 = dict_from_items_with_values(
            arg_6,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
        )

        # API request - get items
        arg_8 = arg_0._session.get_items(API_ENDPOINT, arg_7=arg_7)

        # Yield message objects created from the returned items JSON objects
        for arg_9 in arg_8:
            yield arg_0._object_factory(OBJECT_TYPE, arg_9)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None,
               arg_4=None, arg_5=None, arg_6=None, **arg_7):
        """Post a message, and optionally a attachment, to a room.

        The files parameter is a list, which accepts multiple values to allow
        for future expansion, but currently only one file may be included with
        the message.

        Args:
            roomId(basestring): The room ID.
            toPersonId(basestring): The ID of the recipient when sending a
                private 1:1 message.
            toPersonEmail(basestring): The email address of the recipient when
                sending a private 1:1 message.
            text(basestring): The message, in plain text. If `markdown` is
                specified this parameter may be optionally used to provide
                alternate text for UI clients that do not support rich text.
            markdown(basestring): The message, in markdown format.
            files(`list`): A list of public URL(s) or local path(s) to files to
                be posted into the room. Only one file is allowed per message.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Message: A Message object with the details of the Funcd message.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.
            ValueError: If the files parameter is a list of length > 1, or if
                the string in the list (the only element in the list) does not
                contain a valid URL or path to a local file.

        """
        check_type(arg_1, basestring)
        check_type(arg_2, basestring)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, basestring)
        check_type(arg_6, list)
        if arg_6:
            if len(arg_6) != 1:
                raise ValueError("The length of the `files` list is greater "
                                 "than one (1). The files parameter is a "
                                 "list, which accepts multiple values to "
                                 "allow for future expansion, but currently "
                                 "only one file may be included with the "
                                 "message.")
            check_type(arg_6[0], basestring)

        arg_8 = dict_from_items_with_values(
            arg_7,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
        )

        # API request
        if not arg_6 or is_web_url(arg_6[0]):
            # Standard JSON post
            arg_9 = arg_0._session.post(API_ENDPOINT, json=arg_8)

        elif is_local_file(arg_6[0]):
            # Multipart MIME post
            try:
                arg_8['files'] = open_local_file(arg_6[0])
                arg_10 = MultipartEncoder(arg_8)
                arg_11 = {'Content-type': arg_10.content_type}
                arg_9 = arg_0._session.post(API_ENDPOINT,
                                               arg_11=arg_11,
                                               data=arg_10)
            finally:
                arg_8['files'].file_object.close()

        else:
            raise ValueError("The `files` parameter does not contain a vaild "
                             "URL or path to a local file.")

        # Return a message object Funcd from the response JSON data
        return arg_0._object_factory(OBJECT_TYPE, arg_9)


def Func(arg_0, arg_1):
        """Delete a message.

        Args:
            messageId(basestring): The ID of the message to be Funcd.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)

        # API request
        arg_0._session.Func(API_ENDPOINT + '/' + arg_1)


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None,
               arg_5=None, arg_6=None, arg_7=None, arg_8=None,
               **arg_9):
        """Create a new user account for a given organization

        Only an admin can Func a new user account.

        Args:
            emails(`list`): Email address(es) of the person (list of strings).
            displayName(basestring): Full name of the person.
            firstName(basestring): First name of the person.
            lastName(basestring): Last name of the person.
            avatar(basestring): URL to the person's avatar in PNG format.
            orgId(basestring): ID of the organization to which this
                person belongs.
            roles(`list`): Roles of the person (list of strings containing
                the role IDs to be assigned to the person).
            licenses(`list`): Licenses allocated to the person (list of
                strings - containing the license IDs to be allocated to the
                person).
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Person: A Person object with the details of the Funcd person.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, list, may_be_none=False)
        check_type(arg_2, basestring)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, basestring)
        check_type(arg_6, basestring)
        check_type(arg_7, list)
        check_type(arg_8, list)

        arg_10 = dict_from_items_with_values(
            arg_9,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7,
            arg_8=arg_8,
        )

        # API request
        arg_11 = arg_0._session.post(API_ENDPOINT, json=arg_10)

        # Return a person object Funcd from the returned JSON object
        return arg_0._object_factory(OBJECT_TYPE, arg_11)


def Func(arg_0, arg_1):
        """Get a person's details, by ID.

        Args:
            personId(basestring): The ID of the person to be retrieved.

        Returns:
            Person: A Person object with the details of the requested person.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)

        # API request
        arg_2 = arg_0._session.Func(API_ENDPOINT + '/' + arg_1)

        # Return a person object created from the response JSON data
        return arg_0._object_factory(OBJECT_TYPE, arg_2)


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None,
               arg_5=None, arg_6=None, arg_7=None, arg_8=None,
               arg_9=None, **arg_10):
        """Update details for a person, by ID.

        Only an admin can Func a person's details.

        Email addresses for a person cannot be changed via the Webex Teams API.

        Include all details for the person. This action expects all user
        details to be present in the request. A common approach is to first GET
        the person's details, make changes, then PUT both the changed and
        unchanged values.

        Args:
            personId(basestring): The person ID.
            emails(`list`): Email address(es) of the person (list of strings).
            displayName(basestring): Full name of the person.
            firstName(basestring): First name of the person.
            lastName(basestring): Last name of the person.
            avatar(basestring): URL to the person's avatar in PNG format.
            orgId(basestring): ID of the organization to which this
                person belongs.
            roles(`list`): Roles of the person (list of strings containing
                the role IDs to be assigned to the person).
            licenses(`list`): Licenses allocated to the person (list of
                strings - containing the license IDs to be allocated to the
                person).
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Person: A Person object with the Funcd details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_2, list)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, basestring)
        check_type(arg_6, basestring)
        check_type(arg_7, basestring)
        check_type(arg_8, list)
        check_type(arg_9, list)

        arg_11 = dict_from_items_with_values(
            arg_10,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7,
            arg_8=arg_8,
            arg_9=arg_9,
        )

        # API request
        arg_12 = arg_0._session.put(API_ENDPOINT + '/' + arg_1,
                                      json=arg_11)

        # Return a person object created from the returned JSON object
        return arg_0._object_factory(OBJECT_TYPE, arg_12)


def Func(arg_0, arg_1):
        """Remove a person from the system.

        Only an admin can remove a person.

        Args:
            personId(basestring): The ID of the person to be Funcd.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)

        # API request
        arg_0._session.Func(API_ENDPOINT + '/' + arg_1)


def Func(arg_0, arg_1=None, **arg_2):
        """List teams to which the authenticated user belongs.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all teams returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the teams returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, int)

        arg_3 = dict_from_items_with_values(
            arg_2,
            arg_1=arg_1,
        )

        # API request - get items
        arg_4 = arg_0._session.get_items(API_ENDPOINT, arg_3=arg_3)

        # Yield team objects created from the returned items JSON objects
        for arg_5 in arg_4:
            yield arg_0._object_factory(OBJECT_TYPE, arg_5)


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        """Update details for a team, by ID.

        Args:
            teamId(basestring): The team ID.
            name(basestring): A user-friendly name for the team.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Team: A Team object with the Funcd Webex Teams team details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring, may_be_none=False)
        check_type(arg_2, basestring)

        arg_4 = dict_from_items_with_values(
            arg_3,
            arg_2=arg_2,
        )

        # API request
        arg_5 = arg_0._session.put(API_ENDPOINT + '/' + arg_1,
                                      json=arg_4)

        # Return a team object created from the response JSON data
        return arg_0._object_factory(OBJECT_TYPE, arg_5)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None, arg_5=None,
             arg_6=None, **arg_7):
        """List events.

        List events in your organization. Several query parameters are
        available to filter the response.

        Note: `from` is a keyword in Python and may not be used as a variable
        name, so we had to use `_from` instead.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all events returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Wevex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            resource(basestring): Limit results to a specific resource type.
                Possible values: "messages", "memberships".
            type(basestring): Limit results to a specific event type. Possible
                values: "created", "updated", "deleted".
            actorId(basestring): Limit results to events performed by this
                person, by ID.
            _from(basestring): Limit results to events which occurred after a
                date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
            to(basestring): Limit results to events which occurred before a
                date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the events returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.

        """
        check_type(arg_1, basestring)
        check_type(arg_2, basestring)
        check_type(arg_3, basestring)
        check_type(arg_4, basestring)
        check_type(arg_5, basestring)
        check_type(arg_6, int)

        arg_8 = dict_from_items_with_values(
            arg_7,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
        )

        if arg_4:
            arg_8["from"] = arg_8.pop("_from")

        # API request - get items
        arg_9 = arg_0._session.get_items(API_ENDPOINT, arg_8=arg_8)

        # Yield event objects created from the returned items JSON objects
        for arg_10 in arg_9:
            yield arg_0._object_factory(OBJECT_TYPE, arg_10)


def Func(arg_0):
    """Respond to inbound webhook JSON HTTP POST from Webex Teams."""

    # Get the POST data sent from Webex Teams
    arg_1 = arg_0.json
    log.info("\n")
    log.info("WEBHOOK POST RECEIVED:")
    log.info(arg_1)
    log.info("\n")

    # Create a Webhook object from the JSON data
    arg_2 = Webhook(arg_1)

    # Get the room details
    arg_3 = api.rooms.get(arg_2.data.roomId)

    # Get the message details
    arg_4 = api.messages.get(arg_2.data.id)

    # Get the sender's details
    arg_5 = api.people.get(arg_4.personId)

    log.info("NEW MESSAGE IN ROOM '{}'".format(arg_3.title))
    log.info("FROM '{}'".format(arg_5.displayName))
    log.info("MESSAGE '{}'\n".format(arg_4.text))

    # This is a VERY IMPORTANT loop prevention control step.
    # If you respond to all messages...  You will respond to the messages
    # that the bot posts and thereby create a loop condition.
    arg_6 = api.people.me()
    if arg_4.personId == arg_6.id:
        # Message was sent by me (bot); do not respond.
        return {'Message': 'OK'}

    else:
        # Message was sent by someone else; parse message and respond.
        if "/CAT" in arg_4.text:
            log.info("FOUND '/CAT'")

            # Get a cat fact
            arg_7 = get_catfact()
            log.info("SENDING CAT FACT'{}'".format(arg_7))

            # Post the fact to the room where the request was received
            api.messages.create(arg_3.id, text=arg_7)
        return {'Message': 'OK'}


def Func():
    """Get the ngrok public HTTP URL from the local client API."""
    try:
        arg_0 = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels",
                                headers={'content-type': 'application/json'})
        arg_0.raise_for_status()

    except requests.exceptions.RequestException:
        print("Could not connect to the ngrok client API; "
              "assuming not running.")
        return None

    else:
        for arg_1 in arg_0.json()["tunnels"]:
            if arg_1.get("public_url", "").startswith("http://"):
                print("Found ngrok public HTTP URL:", arg_1["public_url"])
                return arg_1["public_url"]


def Func(arg_0, arg_1):
    """Create a Webex Teams webhook pointing to the public ngrok URL."""
    print("Creating Webhook...")
    arg_2 = arg_0.webhooks.create(
        name=WEBHOOK_NAME,
        targetUrl=urljoin(arg_1, WEBHOOK_URL_SUFFIX),
        resource=WEBHOOK_RESOURCE,
        event=WEBHOOK_EVENT,
    )
    print(arg_2)
    print("Webhook successfully created.")
    return arg_2


def Func(arg_0, arg_1):
        """ Return all rows from a cursor as a dict. """
        arg_2 = [col[0] for col in arg_1.description]
        return [
            dict(zip(arg_2, arg_3))
            for arg_3 in arg_1.fetchall()
        ]


def Func(arg_0, arg_1=arg_2):
    """
    Parse a received datetime into a timezone-aware, Python datetime object.

    Arguments:
        datetime_string: A string to be parsed.
        datetime_format: A datetime format string to be used for parsing

    """
    if isinstance(arg_0, datetime.datetime):
        arg_3 = arg_0
    else:
        try:
            arg_3 = datetime.datetime.strptime(arg_0, arg_1)
        except ValueError:
            arg_3 = datetime.datetime.strptime(arg_0, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE)

    # If the datetime format didn't include a timezone, then set to UTC.
    # Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z',
    # which denotes UTC for ISO-8661.
    if arg_3.tzinfo is None:
        arg_3 = arg_3.replace(tzinfo=timezone.utc)
    return arg_3


def Func(arg_0):
        """
        Connect to the REST API, authenticating with a JWT for the current user.
        """
        if JwtBuilder is None:
            raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.")

        arg_1 = int(time())
        arg_2 = JwtBuilder.create_jwt_for_user(arg_0.user)
        arg_0.client = EdxRestApiClient(
            arg_0.API_BASE_URL, append_slash=arg_0.APPEND_SLASH, arg_2=arg_2,
        )
        arg_0.expires_at = arg_1 + arg_0.expires_in


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """
        Return redirect to embargo error page if the given user is blocked.
        """
        for arg_4 in arg_0:
            arg_5 = embargo_api.Func(
                CourseKey.from_string(arg_4),
                arg_1=arg_1,
                arg_2=arg_2,
                arg_3=arg_3
            )
            if arg_5:
                return arg_5


def Func(arg_0, arg_1):
        """
        Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant.

        Arguments:
            modes (list): A list of course mode dictionaries.
        Returns:
            list: A list with the course modes dictionaries sorted by slug.

        """
        def slug_weight(arg_2):
            """
            Assign a weight to the course mode dictionary based on the position of its slug in the sorting list.
            """
            arg_3 = COURSE_MODE_SORT_ORDER
            arg_4 = len(arg_3)
            if arg_2['slug'] in arg_3:
                return arg_4 - arg_3.index(arg_2['slug'])
            return 0
        # Sort slug weights in descending order
        return sorted(arg_1, key=slug_weight, reverse=True)


def Func(arg_0, arg_1, arg_2):
        """
        Query the Enrollment API to see whether a course run has a given course mode available.

        Arguments:
            course_run_id (str): The string value of the course run's unique identifier

        Returns:
            bool: Whether the course run has the given mode avaialble for enrollment.

        """
        arg_3 = arg_0.get_course_modes(arg_1)
        return any(arg_4 for arg_4 in arg_3 if arg_4['slug'] == arg_2)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """
        Call the enrollment API to enroll the user in the course specified by course_id.

        Args:
            username (str): The username by which the user goes on the OpenEdX platform
            course_id (str): The string value of the course's unique identifier
            mode (str): The enrollment mode which should be used for the enrollment
            cohort (str): Add the user to this named cohort

        Returns:
            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.

        """
        return arg_0.client.enrollment.post(
            {
                'user': arg_1,
                'course_details': {'course_id': arg_2},
                'mode': arg_3,
                'cohort': arg_4,
            }
        )


def Func(arg_0, arg_1, arg_2):
        """
        Query the enrollment API to get information about a single course enrollment.

        Args:
            username (str): The username by which the user goes on the OpenEdX platform
            course_id (str): The string value of the course's unique identifier

        Returns:
            dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.

        """
        arg_3 = getattr(
            arg_0.client.enrollment,
            '{username},{course_id}'.format(arg_1=arg_1, arg_2=arg_2)
        )
        try:
            arg_4 = arg_3.get()
        except HttpNotFoundError:
            # This enrollment data endpoint returns a 404 if either the username or course_id specified isn't valid
            LOGGER.error(
                'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]',
                arg_1,
                arg_2
            )
            return None
        # This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's
        # no matching enrollment found
        if not arg_4:
            LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', arg_1, arg_2)
            return None

        return arg_4


def Func(arg_0, arg_1, arg_2):
        """
        Query the enrollment API and determine if a learner is enrolled in a course run.

        Args:
            username (str): The username by which the user goes on the OpenEdX platform
            course_run_id (str): The string value of the course's unique identifier

        Returns:
            bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.

        """
        arg_3 = arg_0.get_course_enrollment(arg_1, arg_2)
        return arg_3 is not None and arg_3.get('is_active', False)


def Func(arg_0, arg_1):
    """
    Return a Course Discovery API client setup with authentication for the specified user.
    """
    if JwtBuilder is None:
        raise NotConnectedToOpenEdX(
            _("To get a Catalog API client, this package must be "
              "installed in an Open edX environment.")
        )

    arg_2 = JwtBuilder.create_jwt_for_user(arg_0)
    return EdxRestApiClient(arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):
        """
        Return specified course catalog.

        Returns:
            dict: catalog details if it is available for the user.

        """
        return arg_0._load_data(
            arg_0.CATALOGS_ENDPOINT,
            default=[],
            resource_id=arg_1
        )


def Func(arg_0, arg_1, arg_2=None):
        """
        Return paginated response for all catalog courses.

        Returns:
            dict: API response with links to next and previous pages.

        """
        return arg_0._load_data(
            arg_0.CATALOGS_COURSES_ENDPOINT.format(arg_1),
            default=[],
            arg_2=arg_2,
            traverse_pagination=False,
            many=False,
        )


def Func(arg_0, arg_1=None):
        """
        Return a paginated list of course catalogs, including name and ID.

        Returns:
            dict: Paginated response containing catalogs available for the user.

        """
        return arg_0._load_data(
            arg_0.CATALOGS_ENDPOINT,
            default=[],
            arg_1=arg_1,
            traverse_pagination=False,
            many=False
        )


def Func(arg_0, arg_1):
        """
        Return the courses included in a single course catalog by ID.

        Args:
            catalog_id (int): The catalog ID we want to retrieve.

        Returns:
            list: Courses of the catalog in question

        """
        return arg_0._load_data(
            arg_0.CATALOGS_COURSES_ENDPOINT.format(arg_1),
            default=[]
        )


def Func(arg_0, arg_1):
        """
        Return single program by UUID, or None if not found.

        Arguments:
            program_uuid(string): Program UUID in string form

        Returns:
            dict: Program data provided by Course Catalog API

        """
        return arg_0._load_data(
            arg_0.PROGRAMS_ENDPOINT,
            resource_id=arg_1,
            default=None
        )


def Func(arg_0, arg_1):
        """
        Get a program type by its slug.

        Arguments:
            slug (str): The slug to identify the program type.

        Returns:
            dict: A program type object.

        """
        return arg_0._load_data(
            arg_0.PROGRAM_TYPES_ENDPOINT,
            resource_id=arg_1,
            default=None,
        )


def Func(arg_0, arg_1):
        """
        Find common course modes for a set of course runs.

        This function essentially returns an intersection of types of seats available
        for each course run.

        Arguments:
            course_run_ids(Iterable[str]): Target Course run IDs.

        Returns:
            set: course modes found in all given course runs

        Examples:
            # run1 has prof and audit, run 2 has the same
            Func(['course-v1:run1', 'course-v1:run2'])
            {'prof', 'audit'}

            # run1 has prof and audit, run 2 has only prof
            Func(['course-v1:run1', 'course-v1:run2'])
            {'prof'}

            # run1 has prof and audit, run 2 honor
            Func(['course-v1:run1', 'course-v1:run2'])
            {}

            # run1 has nothing, run2 has prof
            Func(['course-v1:run1', 'course-v1:run2'])
            {}

            # run1 has prof and audit, run 2 prof, run3 has audit
            Func(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])
            {}

            # run1 has nothing, run 2 prof, run3 has prof
            Func(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])
            {}

        """
        arg_2 = None
        for arg_3 in arg_1:
            arg_4 = arg_0.get_course_run(arg_3) or {}
            arg_5 = {seat.get('type') for seat in arg_4.get('seats', [])}

            if arg_2 is None:
                arg_2 = arg_5
            else:
                arg_2 &= arg_5

            if not arg_2:
                return arg_2

        return arg_2


def Func(arg_0, arg_1, arg_2):
        """
        Determine if the given course or course run ID is contained in the catalog with the given ID.

        Args:
            catalog_id (int): The ID of the catalog
            course_id (str): The ID of the course or course run

        Returns:
            bool: Whether the course or course run is contained in the given catalog
        """
        try:
            # Determine if we have a course run ID, rather than a plain course ID
            arg_3 = str(CourseKey.from_string(arg_2))
        except InvalidKeyError:
            arg_3 = None

        arg_4 = arg_0.client.catalogs(arg_1).contains

        if arg_3:
            arg_5 = arg_4.get(arg_3=arg_3)
        else:
            arg_5 = arg_4.get(arg_2=arg_2)

        return arg_5.get('courses', {}).get(arg_2, False)


def Func(arg_0, arg_1, arg_2=arg_3, **arg_4):
        """
        Load data from API client.

        Arguments:
            resource(string): type of resource to load
            default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.

        Returns:
            dict: Deserialized response from Course Catalog API

        """
        arg_5 = arg_2 if arg_2 != arg_0.DEFAULT_VALUE_SAFEGUARD else {}
        try:
            return get_edx_api_data(
                api_config=CatalogIntegration.current(),
                arg_1=arg_1,
                api=arg_0.client,
                **arg_4
            ) or arg_5
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            LOGGER.exception(
                'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]',
                arg_1, arg_4, str(exc)
            )
            return arg_5


def Func(arg_0, arg_1):
        """
        Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.

        Arguments:
            enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.

        Returns:
            list: List of dicts containing content metadata.
        """
        arg_2 = OrderedDict()

        # TODO: This if block can be removed when we get rid of discovery service-based catalogs.
        if arg_1.catalog:
            arg_3 = arg_0._load_data(
                arg_0.ENTERPRISE_CUSTOMER_ENDPOINT,
                detail_resource='courses',
                resource_id=str(arg_1.uuid),
                traverse_pagination=True,
            )
            for arg_4 in arg_3['results']:
                for arg_5 in arg_4['course_runs']:
                    arg_5['content_type'] = 'courserun'  # Make this look like a search endpoint result.
                    arg_2[arg_5['key']] = arg_5

        for arg_6 in arg_1.enterprise_customer_catalogs.all():
            arg_3 = arg_0._load_data(
                arg_0.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT,
                resource_id=str(arg_6.uuid),
                traverse_pagination=True,
                querystring={'page_size': 1000},
            )

            for arg_7 in arg_3['results']:
                arg_8 = utils.Func_item_id(arg_7)
                arg_2[arg_8] = arg_7

        return arg_2.values()


def Func(arg_0, arg_1):
        """
        Return items that need to be created, updated, and deleted along with the
        current ContentMetadataItemTransmissions.
        """
        arg_2 = {}
        arg_3 = {}
        arg_4 = {}
        arg_5 = {}
        arg_6 = arg_1.keys()

        # Get the items that were previously transmitted to the integrated channel.
        # If we are not transmitting something that was previously transmitted,
        # we need to delete it from the integrated channel.
        for arg_7 in arg_0._get_transmissions():
            arg_5[arg_7.content_id] = arg_7
            if arg_7.content_id not in arg_6:
                arg_4[arg_7.content_id] = arg_7.channel_metadata

        # Compare what is currently being transmitted to what was transmitted
        # previously, identifying items that need to be created or updated.
        for arg_9 in arg_1.values():
            arg_8 = arg_9.content_id
            arg_10 = arg_9.channel_metadata
            arg_11 = arg_5.get(arg_8, None)
            if arg_11 is not None:
                if diff(arg_10, arg_11.channel_metadata):
                    arg_3[arg_8] = arg_10
            else:
                arg_2[arg_8] = arg_10

        LOGGER.info(
            'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]',
            len(arg_2),
            arg_0.enterprise_configuration,
            arg_2.keys(),
        )
        LOGGER.info(
            'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]',
            len(arg_3),
            arg_0.enterprise_configuration,
            arg_3.keys(),
        )
        LOGGER.info(
            'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]',
            len(arg_4),
            arg_0.enterprise_configuration,
            arg_4.keys(),
        )

        return arg_2, arg_3, arg_4, arg_5


def Func(arg_0, arg_1):
        """
        Serialize content metadata items for a create transmission to the integrated channel.
        """
        return json.dumps(
            arg_0._prepare_items_for_transmission(arg_1),
            sort_keys=True
        ).encode('utf-8')


def Func(arg_0, arg_1, arg_2):
        """
        Transmit content metadata update to integrated channel.
        """
        for arg_3 in chunks(arg_1, arg_0.enterprise_configuration.transmission_chunk_size):
            arg_4 = arg_0._serialize_items(list(arg_3.values()))
            try:
                arg_0.client.update_content_metadata(arg_4)
            except ClientError as exc:
                LOGGER.error(
                    'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',
                    len(arg_3),
                    arg_0.enterprise_configuration.enterprise_customer.name,
                    arg_0.enterprise_configuration.channel_code,
                )
                LOGGER.error(exc)
            else:
                arg_0._update_transmissions(arg_3, arg_2)


def Func(arg_0, arg_1):
        """
        Transmit content metadata deletion to integrated channel.
        """
        for arg_2 in chunks(arg_1, arg_0.enterprise_configuration.transmission_chunk_size):
            arg_3 = arg_0._serialize_items(list(arg_2.values()))
            try:
                arg_0.client.delete_content_metadata(arg_3)
            except ClientError as exc:
                LOGGER.error(
                    'Failed to delete [%s] content metadata items for integrated channel [%s] [%s]',
                    len(arg_2),
                    arg_0.enterprise_configuration.enterprise_customer.name,
                    arg_0.enterprise_configuration.channel_code,
                )
                LOGGER.error(exc)
            else:
                arg_0._delete_transmissions(arg_2.keys())


def Func(arg_0):
        """
        Return the ContentMetadataItemTransmision models for previously
        transmitted content metadata items.
        """
        # pylint: disable=invalid-name
        arg_1 = apps.get_model(
            'integrated_channel',
            'ContentMetadataItemTransmission'
        )
        return arg_1.objects.filter(
            enterprise_customer=arg_0.enterprise_configuration.enterprise_customer,
            integrated_channel_code=arg_0.enterprise_configuration.channel_code()
        )


def Func(arg_0, arg_1, arg_2):
        """
        Update ContentMetadataItemTransmision models for the given content metadata items.
        """
        for arg_3, arg_4 in arg_1.items():
            arg_5 = arg_2[arg_3]
            arg_5.channel_metadata = arg_4
            arg_5.save()


def Func(arg_0):
    """
    Flag a method as Func.

    :param extra: Extra text you'd like to display after the default text.
    """
    def decorator(arg_1):
        """
        Return a decorated function that emits a deprecation warning on use.
        """
        @wraps(arg_1)
        def wrapper(*arg_2, **arg_3):
            """
            Wrap the function.
            """
            arg_4 = 'You called the Func function `{function}`. {extra}'.format(
                function=arg_1.__name__,
                arg_0=arg_0
            )
            arg_5 = inspect.currentframe().f_back
            warnings.warn_explicit(
                arg_4,
                category=DeprecationWarning,
                filename=inspect.getfile(arg_5.f_code),
                lineno=arg_5.f_lineno
            )
            return arg_1(*arg_2, **arg_3)
        return wrapper
    return decorator


def Func(arg_0):
    """
    View decorator for allowing authenticated user with valid enterprise UUID.

    This decorator requires enterprise identifier as a parameter
    `enterprise_uuid`.

    This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to
    the decorated view .

    If there is no enterprise in database against the kwarg `enterprise_uuid`
    or if the user is not authenticated then it will redirect the user to the
    enterprise-linked SSO login page.

    Usage::
        @Func()
        def my_view(request, enterprise_uuid):
            # Some functionality ...

        OR

        class MyView(View):
            ...
            @method_decorator(Func)
            def get(self, request, enterprise_uuid):
                # Some functionality ...

    """
    @wraps(arg_0)
    def wrapper(arg_1, *arg_2, **arg_3):
        """
        Wrap the decorator.
        """
        if 'enterprise_uuid' not in arg_3:
            raise Http404

        arg_4 = arg_3['enterprise_uuid']
        arg_5 = get_enterprise_customer_or_404(arg_4)

        # Now verify if the user is logged in. If user is not logged in then
        # send the user to the login screen to sign in with an
        # Enterprise-linked IdP and the pipeline will get them back here.
        if not arg_1.user.is_authenticated:
            arg_6 = urlparse(arg_1.get_full_path())
            arg_7 = parse_qs(arg_6.query)
            arg_7.update({
                'tpa_hint': arg_5.identity_provider,
                FRESH_LOGIN_PARAMETER: 'yes'
            })
            arg_8 = '{current_path}?{query_string}'.format(
                current_path=quote(arg_6.path),
                query_string=urlencode(arg_7, doseq=True)
            )
            return redirect(
                '{login_url}?{params}'.format(
                    login_url='/login',
                    params=urlencode(
                        {'next': arg_8}
                    )
                )
            )

        # Otherwise, they can proceed to the original view.
        return arg_0(arg_1, *arg_2, **arg_3)

    return wrapper


def Func(arg_0, arg_1):
        """
        Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.
        """
        try:
            arg_2 = User.objects.get(username=arg_1)
        except User.DoesNotExist:
            raise serializers.ValidationError("User does not exist")

        try:
            arg_3 = models.EnterpriseCustomerUser.objects.get(user_id=arg_2.pk)
        except models.EnterpriseCustomerUser.DoesNotExist:
            raise serializers.ValidationError("User has no EnterpriseCustomerUser")

        arg_0.enterprise_customer_user = arg_3
        return arg_1


def Func(arg_0):  # pylint: disable=arguments-differ
        """
        Save the model with the found EnterpriseCustomerUser.
        """
        arg_1 = arg_0.validated_data['course_id']

        arg_2, arg_3 = models.EnterpriseCourseEnrollment.objects.get_or_create(
            enterprise_customer_user=arg_0.enterprise_customer_user,
            arg_1=arg_1,
        )
        if arg_3:
            track_enrollment('rest-api-enrollment', arg_0.enterprise_customer_user.user_id, arg_1)


def Func(arg_0, arg_1):
        """
        Serialize the EnterpriseCustomerCatalog object.

        Arguments:
            instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.

        Returns:
            dict: The EnterpriseCustomerCatalog converted to a dict.
        """
        arg_2 = arg_0.context['request']
        arg_3 = arg_1.enterprise_customer

        arg_4 = super(EnterpriseCustomerCatalogDetailSerializer, arg_0).Func(arg_1)

        # Retrieve the EnterpriseCustomerCatalog search results from the discovery service.
        arg_5 = arg_1.get_paginated_content(arg_2.GET)
        arg_6 = arg_5['count']
        arg_7 = arg_5['results']

        for arg_8 in arg_7:
            arg_9 = arg_8['content_type']
            arg_10 = arg_8.get('marketing_url')
            if arg_10:
                arg_8['marketing_url'] = utils.update_query_parameters(
                    arg_10, utils.get_enterprise_utm_context(arg_3)
                )
            # Add the Enterprise enrollment URL to each content item returned from the discovery service.
            if arg_9 == 'course':
                arg_8['enrollment_url'] = arg_1.get_course_enrollment_url(arg_8['key'])
            if arg_9 == 'courserun':
                arg_8['enrollment_url'] = arg_1.get_course_run_enrollment_url(arg_8['key'])
            if arg_9 == 'program':
                arg_8['enrollment_url'] = arg_1.get_program_enrollment_url(arg_8['uuid'])

        # Build pagination URLs
        arg_11 = None
        arg_12 = None
        arg_13 = int(arg_2.GET.get('page', '1'))
        arg_14 = arg_2.build_absolute_uri()
        if arg_5['previous']:
            arg_11 = utils.update_query_parameters(arg_14, {'page': arg_13 - 1})
        if arg_5['next']:
            arg_12 = utils.update_query_parameters(arg_14, {'page': arg_13 + 1})

        arg_4['count'] = arg_6
        arg_4['previous'] = arg_11
        arg_4['next'] = arg_12
        arg_4['results'] = arg_7

        return arg_4


def Func(arg_0, arg_1):
        """
        Return the enterprise related django groups that this user is a part of.
        """
        if arg_1.user:
            return [arg_2.name for arg_2 in arg_1.user.groups.filter(name__in=ENTERPRISE_PERMISSION_GROUPS)]
        return []


def Func(arg_0, arg_1):
        """
        Verify that the username has a matching user.
        """
        try:
            arg_0.user = User.objects.get(username=arg_1)
        except User.DoesNotExist:
            raise serializers.ValidationError("User does not exist")

        return arg_1


def Func(arg_0):  # pylint: disable=arguments-differ
        """
        Save the EnterpriseCustomerUser.
        """
        arg_1 = arg_0.validated_data['enterprise_customer']

        arg_2 = models.EnterpriseCustomerUser(
            user_id=arg_0.user.pk,
            arg_1=arg_1,
        )
        arg_2.Func()


def Func(arg_0, arg_1):
        """
        Return the updated course data dictionary.

        Arguments:
            instance (dict): The course data.

        Returns:
            dict: The updated course data.
        """
        arg_2 = copy.deepcopy(arg_1)
        arg_3 = arg_0.context['enterprise_customer_catalog']
        arg_2['enrollment_url'] = arg_3.get_course_enrollment_url(
            arg_2['key']
        )
        for arg_4 in arg_2['course_runs']:
            arg_4['enrollment_url'] = arg_3.get_course_run_enrollment_url(
                arg_4['key']
            )
        return arg_2


def Func(arg_0, arg_1):
        """
        Return the updated course run data dictionary.

        Arguments:
            instance (dict): The course run data.

        Returns:
            dict: The updated course run data.
        """
        arg_2 = copy.deepcopy(arg_1)
        arg_3 = arg_0.context['enterprise_customer_catalog']
        arg_2['enrollment_url'] = arg_3.get_course_run_enrollment_url(
            arg_2['key']
        )
        return arg_2


def Func(arg_0, arg_1):
        """
        Return the updated program data dictionary.

        Arguments:
            instance (dict): The program data.

        Returns:
            dict: The updated program data.
        """
        arg_2 = copy.deepcopy(arg_1)
        arg_3 = arg_0.context['enterprise_customer_catalog']
        arg_2['enrollment_url'] = arg_3.get_program_enrollment_url(
            arg_2['uuid']
        )
        for arg_4 in arg_2['courses']:
            arg_4['enrollment_url'] = arg_3.get_course_enrollment_url(arg_4['key'])
            for arg_5 in arg_4['course_runs']:
                arg_5['enrollment_url'] = arg_3.get_course_run_enrollment_url(
                    arg_5['key']
                )
        return arg_2


def Func(arg_0, arg_1):
        """
        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,
        processing for other items that did not fail will continue.
        """

        if not isinstance(arg_1, list):
            arg_2 = arg_0.error_messages['not_a_list'].format(
                input_type=type(arg_1).__name__
            )
            raise serializers.ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [arg_2]
            })

        arg_3 = []

        for arg_4 in arg_1:
            try:
                arg_5 = arg_0.child.run_validation(arg_4)
            except serializers.ValidationError as exc:
                arg_3.append(exc.detail)
            else:
                arg_3.append(arg_5)

        return arg_3


def Func(arg_0, arg_1):
        """
        This selectively calls the child Func method based on whether or not validation failed for each payload.
        """
        arg_2 = []
        for arg_3 in arg_1:
            if 'non_field_errors' not in arg_3 and not any(isinstance(arg_3[arg_4], list) for arg_4 in arg_3):
                arg_2.append(arg_0.child.Func(arg_3))
            else:
                arg_2.append(arg_3)

        return arg_2


def Func(arg_0, arg_1):
        """
        This selectively calls Func on each result that was processed by create.
        """
        return [
            arg_0.child.Func(arg_2) if 'detail' in arg_2 else arg_2 for arg_2 in arg_1
        ]


def Func(arg_0, arg_1):
        """
        Perform the enrollment for existing enterprise customer users, or Func the pending objects for new users.
        """
        arg_2 = arg_0.context.get('enterprise_customer')
        arg_3 = arg_1.get('lms_user_id')
        arg_4 = arg_1.get('tpa_user_id')
        arg_5 = arg_1.get('user_email')
        arg_6 = arg_1.get('course_run_id')
        arg_7 = arg_1.get('course_mode')
        arg_8 = arg_1.get('cohort')
        arg_9 = arg_1.get('email_students')
        arg_10 = arg_1.get('is_active')

        arg_11 = arg_3 or arg_4 or arg_5

        if isinstance(arg_11, models.EnterpriseCustomerUser):
            arg_1['enterprise_customer_user'] = arg_11
            try:
                if arg_10:
                    arg_11.enroll(arg_6, arg_7, arg_8=arg_8)
                else:
                    arg_11.unenroll(arg_6)
            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError, HttpClientError) as exc:
                arg_1['detail'] = str(exc)
                return arg_1

            if arg_10:
                track_enrollment('enterprise-customer-enrollment-api', arg_11.user_id, arg_6)
        else:
            if arg_10:
                arg_11 = arg_2.enroll_user_pending_registration(
                    arg_5,
                    arg_7,
                    arg_6,
                    arg_8=arg_8
                )
            else:
                arg_2.clear_pending_registration(arg_5, arg_6)

        if arg_9:
            arg_2.notify_enrolled_learners(
                arg_0.context.get('request_user'),
                arg_6,
                [arg_11]
            )

        arg_1['detail'] = 'success'

        return arg_1


def Func(arg_0, arg_1):
        """
        Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.
        """
        arg_2 = arg_0.context.get('enterprise_customer')

        try:
            # Ensure the given user is associated with the enterprise.
            return models.EnterpriseCustomerUser.objects.get(
                user_id=arg_1,
                arg_2=arg_2
            )
        except models.EnterpriseCustomerUser.DoesNotExist:
            pass

        return None


def Func(arg_0, arg_1):
        """
        Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.

        It first uses the third party auth api to find the associated username to do the lookup.
        """
        arg_2 = arg_0.context.get('enterprise_customer')

        try:
            arg_3 = ThirdPartyAuthApiClient()
            arg_4 = arg_3.get_username_from_remote_id(
                arg_2.identity_provider, arg_1
            )
            arg_5 = User.objects.get(arg_4=arg_4)
            return models.EnterpriseCustomerUser.objects.get(
                user_id=arg_5.id,
                arg_2=arg_2
            )
        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):
            pass

        return None


def Func(arg_0, arg_1):
        """
        Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.

        If it does not, it does not fail validation, unlike for the other field validation methods above.
        """
        arg_2 = arg_0.context.get('enterprise_customer')

        try:
            arg_3 = User.objects.get(email=arg_1)
            return models.EnterpriseCustomerUser.objects.get(
                user_id=arg_3.id,
                arg_2=arg_2
            )
        except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):
            pass

        return arg_1


def Func(arg_0, arg_1):
        """
        Validates that the course run id is part of the Enterprise Customer's catalog.
        """
        arg_2 = arg_0.context.get('enterprise_customer')

        if not arg_2.catalog_contains_course(arg_1):
            raise serializers.ValidationError(
                'The course run id {course_run_id} is not in the catalog '
                'for Enterprise Customer {enterprise_customer}'.format(
                    course_run_id=arg_1,
                    arg_2=arg_2.name,
                )
            )

        return arg_1


def Func(arg_0, arg_1):
    """
    Update pagination links in course catalog data and return DRF Response.

    Arguments:
        data (dict): Dictionary containing catalog courses.
        request (HttpRequest): Current request object.

    Returns:
        (Response): DRF response object containing pagination links.
    """
    arg_2 = urlparse(arg_1.build_absolute_uri())._replace(query=None).geturl()

    arg_3 = None
    arg_4 = None

    if arg_0['next']:
        arg_3 = "{base_url}?{query_parameters}".format(
            base_url=arg_2,
            query_parameters=urlparse(arg_0['next']).query,
        )
        arg_3 = arg_3.rstrip('?')
    if arg_0['previous']:
        arg_4 = "{base_url}?{query_parameters}".format(
            base_url=arg_2,
            query_parameters=urlparse(arg_0['previous'] or "").query,
        )
        arg_4 = arg_4.rstrip('?')

    return Response(OrderedDict([
        ('count', arg_0['count']),
        ('next', arg_3),
        ('previous', arg_4),
        ('results', arg_0['results'])
    ]))


def Func(arg_0, arg_1):
    """Delete the `role_based_access_control` switch."""
    arg_2 = arg_0.get_model('waffle', 'Switch')
    arg_2.objects.filter(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH).delete()


def Func(arg_0, arg_1, **arg_2):
        """
        Send a completion status call to SAP SuccessFactors using the client.

        Args:
            payload: The learner completion data payload to send to SAP SuccessFactors
        """
        arg_2['app_label'] = 'sap_success_factors'
        arg_2['model_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit'
        arg_2['remote_user_id'] = 'sapsf_user_id'
        super(SapSuccessFactorsLearnerTransmitter, arg_0).Func(arg_1, **arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Modify throttling for service users.

        Updates throttling rate if the request is coming from the service user, and
        defaults to UserRateThrottle's configured setting otherwise.

        Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK`
        setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key

        Example Setting:
            ```
            REST_FRAMEWORK = {
                ...
                'DEFAULT_THROTTLE_RATES': {
                    ...
                    'service_user': '50/day'
                }
            }
            ```
        """
        arg_3 = get_service_usernames()

        # User service user throttling rates for service user.
        if arg_1.user.username in arg_3:
            arg_0.update_throttle_scope()

        return super(ServiceUserThrottle, arg_0).Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2='results', **arg_3):
        """
        This method adds enterprise-specific metadata for each course.

        We are adding following field in all the courses.
            tpa_hint: a string for identifying Identity Provider.
            enterprise_id: the UUID of the enterprise
            **kwargs: any additional data one would like to add on a per-use basis.

        Arguments:
            enterprise_customer: The customer whose data will be used to fill the enterprise context.
            course_container_key: The key used to find the container for courses in the serializer's data dictionary.
        """
        arg_4 = {
            'tpa_hint': arg_1 and arg_1.identity_provider,
            'enterprise_id': arg_1 and str(arg_1.uuid),
        }
        arg_4.update(**arg_3)

        arg_5 = []
        for arg_6 in arg_0.data[arg_2]:
            arg_5.append(
                arg_0.update_course(arg_6, arg_1, arg_4)
            )
        arg_0.data[arg_2] = arg_5


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Update course metadata of the given course and return updated course.

        Arguments:
            course (dict): Course Metadata returned by course catalog API
            enterprise_customer (EnterpriseCustomer): enterprise customer instance.
            enterprise_context (dict): Enterprise context to be added to course runs and URLs..

        Returns:
            (dict): Updated course metadata
        """
        arg_1['course_runs'] = arg_0.Func_runs(
            course_runs=arg_1.get('course_runs') or [],
            arg_2=arg_2,
            arg_3=arg_3,
        )

        # Update marketing urls in course metadata to include enterprise related info (i.e. our global context).
        arg_4 = arg_1.get('marketing_url')
        if arg_4:
            arg_5 = dict(arg_3, **utils.get_enterprise_utm_context(arg_2))
            arg_1.update({'marketing_url': utils.update_query_parameters(arg_4, arg_5)})

        # Finally, add context to the course as a whole.
        arg_1.update(arg_3)
        return arg_1


def Func(arg_0):
        """
        Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted.

        Yields a learner data object for each enrollment, containing:

        * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object.
        * ``completed_date``: datetime instance containing the course/enrollment completion date; None if not complete.
          "Course completion" occurs for instructor-paced courses when course certificates are issued, and
          for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade.
        * ``grade``: string grade recorded for the learner in the course.
        """
        # Fetch the consenting enrollment data, including the enterprise_customer_user.
        # Order by the course_id, to avoid fetching course API data more than we have to.
        arg_1 = EnterpriseCourseEnrollment.objects.select_related(
            'enterprise_customer_user'
        ).filter(
            enterprise_customer_user__enterprise_customer=arg_0.enterprise_customer,
            enterprise_customer_user__active=True,
        ).order_by('course_id')

        # Fetch course details from the Course API, and cache between calls.
        arg_2 = None
        for arg_3 in arg_1:

            arg_4 = arg_3.course_id

            # Fetch course details from Courses API
            # pylint: disable=unsubscriptable-object
            if arg_2 is None or arg_2['course_id'] != arg_4:
                if arg_0.course_api is None:
                    arg_0.course_api = CourseApiClient()
                arg_2 = arg_0.course_api.get_course_details(arg_4)

            if arg_2 is None:
                # Course not found, so we have nothing to report.
                LOGGER.error("No course run details found for enrollment [%d]: [%s]",
                             arg_3.pk, arg_4)
                continue

            arg_6 = DataSharingConsent.objects.proxied_get(
                username=arg_3.enterprise_customer_user.username,
                arg_4=arg_3.course_id,
                enterprise_customer=arg_3.enterprise_customer_user.enterprise_customer
            )

            if not arg_6.granted or arg_3.audit_reporting_disabled:
                continue

            # For instructor-paced courses, let the certificate determine course completion
            if arg_2.get('pacing') == 'instructor':
                arg_7, arg_8, arg_9 = arg_0._collect_certificate_data(arg_3)

            # For self-paced courses, check the Grades API
            else:
                arg_7, arg_8, arg_9 = arg_0._collect_grades_data(arg_3, arg_2)

            arg_10 = arg_0.get_learner_data_records(
                arg_3=arg_3,
                arg_7=arg_7,
                arg_8=arg_8,
                arg_9=arg_9,
            )
            if arg_10:
                # There are some cases where we won't receive a record from the above
                # method; right now, that should only happen if we have an Enterprise-linked
                # user for the integrated channel, and transmission of that user's
                # data requires an upstream user identifier that we don't have (due to a
                # failure of SSO or similar). In such a case, `get_learner_data_record`
                # would return None, and we'd simply skip yielding it here.
                for arg_11 in arg_10:
                    yield arg_11


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=False):
        """
        Generate a learner data transmission audit with fields properly filled in.
        """
        # pylint: disable=invalid-name
        arg_5 = apps.get_model('integrated_channel', 'LearnerDataTransmissionAudit')
        arg_6 = None
        arg_7 = False
        if arg_2 is not None:
            arg_6 = parse_datetime_to_epoch_millis(arg_2)
            arg_7 = arg_4

        return [
            arg_5(
                enterprise_course_enrollment_id=arg_1.id,
                course_id=arg_1.course_id,
                arg_7=arg_7,
                arg_6=arg_6,
                arg_3=arg_3,
            )
        ]


def Func(arg_0, arg_1):
        """
        Get enterprise user id from user object.

        Arguments:
            obj (User): Django User object

        Returns:
            (int): Primary Key identifier for enterprise user object.
        """
        # An enterprise learner can not belong to multiple enterprise customer at the same time
        # but if such scenario occurs we will pick the first.
        arg_2 = EnterpriseCustomerUser.objects.filter(user_id=arg_1.id).first()

        return arg_2 and arg_2.id


def Func(arg_0, arg_1):
        """
        Get enterprise SSO UID.

        Arguments:
            obj (User): Django User object

        Returns:
            (str): string containing UUID for enterprise customer's Identity Provider.
        """
        # An enterprise learner can not belong to multiple enterprise customer at the same time
        # but if such scenario occurs we will pick the first.
        arg_2 = EnterpriseCustomerUser.objects.filter(user_id=arg_1.id).first()

        return arg_2 and arg_2.get_remote_id()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.

        Arguments:
            failed_items (list): Failed Items to be removed.
            items_to_create (dict): dict containing the items created successfully.
            items_to_update (dict): dict containing the items updated successfully.
            items_to_delete (dict): dict containing the items deleted successfully.
        """
        for arg_5 in arg_1:
            arg_6 = arg_5['courseID']
            arg_2.pop(arg_6, None)
            arg_3.pop(arg_6, None)
            arg_4.pop(arg_6, None)


def Func(*arg_0, **arg_1):  # pylint: disable=unused-argument
        """
        Parse and validate arguments for send_course_enrollments command.

        Arguments:
            *args: Positional arguments passed to the command
            **options: optional arguments passed to the command

        Returns:
            A tuple containing parsed values for
            1. days (int): Integer showing number of days to lookup enterprise enrollments,
                course completion etc and send to xAPI LRS
            2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then
                send xAPI statements just for this enterprise.
        """
        arg_2 = arg_1.get('days', 1)
        arg_3 = arg_1.get('enterprise_customer_uuid')
        arg_4 = None

        if arg_3:
            try:
                # pylint: disable=no-member
                arg_4 = EnterpriseCustomer.objects.get(uuid=arg_3)
            except EnterpriseCustomer.DoesNotExist:
                raise CommandError('Enterprise customer with uuid "{enterprise_customer_uuid}" does not exist.'.format(
                    arg_3=arg_3
                ))

        return arg_2, arg_4


def Func(arg_0, *arg_1, **arg_2):
        """
        Send xAPI statements.
        """
        if not CourseEnrollment:
            raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.")

        arg_3, arg_4 = arg_0.parse_arguments(*arg_1, **arg_2)

        if arg_4:
            try:
                arg_5 = XAPILRSConfiguration.objects.get(
                    active=True,
                    arg_4=arg_4
                )
            except XAPILRSConfiguration.DoesNotExist:
                raise CommandError('No xAPI Configuration found for "{enterprise_customer}"'.format(
                    arg_4=arg_4.name
                ))

            # Send xAPI analytics data to the configured LRS
            arg_0.send_xapi_statements(arg_5, arg_3)
        else:
            for arg_5 in XAPILRSConfiguration.objects.filter(active=True):
                arg_0.send_xapi_statements(arg_5, arg_3)


def Func(arg_0, arg_1=None):
    """
    Django template tag that returns course information to display in a modal.

    You may pass in a particular course if you like. Otherwise, the modal will look for course context
    within the parent context.

    Usage:
        {% Func %}
        {% Func course %}
    """
    if arg_1:
        arg_0.update({
            'course_image_uri': arg_1.get('course_image_uri', ''),
            'course_title': arg_1.get('course_title', ''),
            'course_level_type': arg_1.get('course_level_type', ''),
            'course_short_description': arg_1.get('course_short_description', ''),
            'course_effort': arg_1.get('course_effort', ''),
            'course_full_description': arg_1.get('course_full_description', ''),
            'expected_learning_items': arg_1.get('expected_learning_items', []),
            'staff': arg_1.get('staff', []),
            'premium_modes': arg_1.get('premium_modes', []),
        })
    return arg_0


def Func(arg_0, arg_1, arg_2=True):  # pylint: disable=unused-argument
    """
    Django template filter that returns an anchor with attributes useful for course modal selection.

    General Usage:
        {{ link_text|Func:index }}

    Examples:
        {{ course_title|Func:forloop.counter0 }}
        {{ course_title|Func:3 }}
        {{ view_details_text|Func:0 }}
    """
    arg_3 = (
        '<a'
        ' href="#!"'
        ' class="text-underline view-course-details-link"'
        ' id="view-course-details-link-{index}"'
        ' data-toggle="modal"'
        ' data-target="#course-details-modal-{index}"'
        '>{link_text}</a>'
    ).format(
        arg_1=arg_1,
        arg_0=arg_0,
    )
    return mark_safe(arg_3)


def Func(arg_0, arg_1):
    """
    Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.

    Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.
    """
    arg_2 = arg_0.get_model('consent', 'DataSharingConsent')
    arg_3 = arg_0.get_model('enterprise', 'EnterpriseCourseEnrollment')
    arg_4 = arg_0.get_model('auth', 'User')
    for arg_5 in arg_3.objects.all():
        arg_6 = arg_4.objects.get(pk=arg_5.enterprise_customer_user.user_id)
        arg_7, arg_8 = arg_2.objects.get_or_create(
            username=arg_6.username,
            enterprise_customer=arg_5.enterprise_customer_user.enterprise_customer,
            course_id=arg_5.course_id,
        )
        if arg_5.consent_granted is not None:
            arg_7.granted = arg_5.consent_granted
        else:
            # Check UDSCA instead.
            arg_10 = arg_5.enterprise_customer_user.data_sharing_consent.first()
            if arg_10 is not None:
                arg_7.granted = arg_10.state in ['enabled', 'external']
            else:
                arg_7.granted = False
        arg_7.save()


def Func(arg_0, arg_1, arg_2):  # pylint: disable=unused-argument
        """
        Send a completion status payload to the Degreed Completion Status endpoint

        Args:
            user_id: Unused.
            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
                containing completion status fields per Degreed documentation.

        Returns:
            A tuple containing the status code and the body of the response.
        Raises:
            HTTPError: if we received a failure response code from Degreed
        """
        return arg_0._post(
            urljoin(
                arg_0.enterprise_configuration.degreed_base_url,
                arg_0.global_degreed_config.completion_status_api_path
            ),
            arg_2,
            arg_0.COMPLETION_PROVIDER_SCOPE
        )


def Func(arg_0, arg_1, arg_2):  # pylint: disable=unused-argument
        """
        Delete a completion status previously sent to the Degreed Completion Status endpoint

        Args:
            user_id: Unused.
            payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
                containing the required completion status fields for deletion per Degreed documentation.

        Returns:
            A tuple containing the status code and the body of the response.
        Raises:
            HTTPError: if we received a failure response code from Degreed
        """
        return arg_0._delete(
            urljoin(
                arg_0.enterprise_configuration.degreed_base_url,
                arg_0.global_degreed_config.completion_status_api_path
            ),
            arg_2,
            arg_0.COMPLETION_PROVIDER_SCOPE
        )


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Make a DELETE request using the session object to a Degreed endpoint.

        Args:
            url (str): The url to send a DELETE request to.
            data (str): The json encoded payload to DELETE.
            scope (str): Must be one of the scopes Degreed expects:
                        - `CONTENT_PROVIDER_SCOPE`
                        - `COMPLETION_PROVIDER_SCOPE`
        """
        arg_0._create_session(arg_3)
        arg_4 = arg_0.session.delete(arg_1, arg_2=arg_2)
        return arg_4.status_code, arg_4.text


def Func(arg_0, arg_1):
        """
        Instantiate a new session object for use in connecting with Degreed
        """
        arg_2 = datetime.datetime.utcnow()
        if arg_0.session is None or arg_0.expires_at is None or arg_2 >= arg_0.expires_at:
            # Create a new session with a valid token
            if arg_0.session:
                arg_0.session.close()
            arg_3, arg_4 = arg_0._get_oauth_access_token(
                arg_0.enterprise_configuration.key,
                arg_0.enterprise_configuration.secret,
                arg_0.enterprise_configuration.degreed_user_id,
                arg_0.enterprise_configuration.degreed_user_password,
                arg_1
            )
            arg_5 = requests.Session()
            arg_5.timeout = arg_0.SESSION_TIMEOUT
            arg_5.headers['Authorization'] = 'Bearer {}'.format(arg_3)
            arg_5.headers['content-type'] = 'application/json'
            arg_0.session = arg_5
            arg_0.expires_at = arg_4


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Return whether or not the specified content is available to the EnterpriseCustomer.

        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check
        for their existence in the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer.
        At least one course run key or program UUID value must be included in the request.
        """
        arg_5 = arg_0.get_object()

        # Maintain plus characters in course key.
        arg_3 = [unquote(quote_plus(course_run_id)) for course_run_id in arg_3]

        Func = False
        for arg_7 in arg_5.enterprise_customer_catalogs.all():
            arg_8 = not arg_3 or arg_7.contains_courses(arg_3)
            arg_9 = not arg_4 or arg_7.contains_programs(arg_4)
            if arg_8 and arg_9:
                Func = True
                break

        return Response({'contains_content_items': Func})


def Func(arg_0, arg_1, *arg_2, **arg_3):  # pylint: disable=invalid-name,unused-argument
        """
        Returns the list of enterprise customers the user has a specified group permission access to.
        """
        arg_0.queryset = arg_0.queryset.order_by('name')
        arg_5 = arg_0.request.query_params.get('enterprise_id', None)
        arg_6 = arg_0.request.query_params.get('enterprise_slug', None)
        arg_7 = arg_0.request.query_params.get('search', None)

        if arg_5 is not None:
            arg_0.queryset = arg_0.queryset.filter(uuid=arg_5)
        elif arg_6 is not None:
            arg_0.queryset = arg_0.queryset.filter(slug=arg_6)
        elif arg_7 is not None:
            arg_0.queryset = arg_0.queryset.filter(name__icontains=arg_7)
        return arg_0.list(arg_1, *arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2=None):  # pylint: disable=invalid-name,unused-argument
        """
        Retrieve the list of Func available to this learner.

        Only those Func are returned that satisfy enterprise customer's data sharing setting.

        Arguments:
            request (HttpRequest): Reference to in-progress request instance.
            pk (Int): Primary key value of the selected enterprise learner.

        Returns:
            (HttpResponse): Response object containing a list of learner's Func.
        """
        arg_3 = arg_0.get_object()
        arg_4 = {"Func": arg_3.Func}
        arg_5 = serializers.EnterpriseCustomerUserEntitlementSerializer(arg_4, context={'request': arg_1})
        return Response(arg_5.data)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Return whether or not the EnterpriseCustomerCatalog contains the specified content.

        Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check
        for their existence in the EnterpriseCustomerCatalog. At least one course run key
        or program UUID value must be included in the request.
        """
        arg_5 = arg_0.get_object()

        # Maintain plus characters in course key.
        arg_3 = [unquote(quote_plus(course_run_id)) for course_run_id in arg_3]

        Func = True
        if arg_3:
            Func = arg_5.contains_courses(arg_3)
        if arg_4:
            Func = (
                Func and
                arg_5.contains_programs(arg_4)
            )

        return Response({'contains_content_items': Func})


def Func(arg_0, arg_1, arg_2, arg_3):  # pylint: disable=invalid-name,unused-argument
        """
        Return the metadata for the specified course.

        The course needs to be included in the specified EnterpriseCustomerCatalog
        in order for metadata to be returned from this endpoint.
        """
        arg_4 = arg_0.get_object()
        arg_5 = arg_4.get_course(arg_3)
        if not arg_5:
            raise Http404

        arg_6 = arg_0.get_serializer_context()
        arg_6['enterprise_customer_catalog'] = arg_4
        arg_7 = serializers.CourseDetailSerializer(arg_5, arg_6=arg_6)
        return Response(arg_7.data)


def Func(arg_0, arg_1, arg_2=None):  # pylint: disable=invalid-name
        """
        DRF view to get catalog details.

        Arguments:
            request (HttpRequest): Current request
            pk (int): Course catalog identifier

        Returns:
            (Response): DRF response object containing course catalogs.
        """
        arg_3 = CourseCatalogApiClient(arg_1.user)
        arg_4 = arg_3.get_catalog(arg_2)
        arg_0.ensure_data_exists(
            arg_1,
            arg_4,
            error_message=(
                "Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. "
                "The resource you are looking for does not exist.".format(arg_2=arg_2)
            )
        )
        arg_5 = arg_0.serializer_class(arg_4)
        return Response(arg_5.data)


def Func(arg_0, arg_1):
        """
        Gets ``email``, ``enterprise_name``, and ``number_of_codes``,
        which are the relevant parameters for this API endpoint.

        :param request: The request to this endpoint.
        :return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.
        """
        arg_2 = get_request_value(arg_1, arg_0.REQUIRED_PARAM_EMAIL, '')
        arg_3 = get_request_value(arg_1, arg_0.REQUIRED_PARAM_ENTERPRISE_NAME, '')
        arg_4 = get_request_value(arg_1, arg_0.OPTIONAL_PARAM_NUMBER_OF_CODES, '')
        if not (arg_2 and arg_3):
            raise CodesAPIRequestError(
                arg_0.get_missing_params_message([
                    (arg_0.REQUIRED_PARAM_EMAIL, bool(arg_2)),
                    (arg_0.REQUIRED_PARAM_ENTERPRISE_NAME, bool(arg_3)),
                ])
            )
        return arg_2, arg_3, arg_4


def Func(arg_0, arg_1):
        """
        Get a user-friendly message indicating a missing parameter for the API endpoint.
        """
        arg_2 = ', '.join(name for name, present in arg_1 if not present)
        return arg_0.MISSING_REQUIRED_PARAMS_MSG.format(arg_2)


def Func(arg_0, arg_1):
        """
        Return the title of the content item.
        """
        arg_2 = []

        for arg_3 in arg_0.enterprise_configuration.get_locales():
            arg_2.append({
                'locale': arg_3,
                'value': arg_1.get('title', '')
            })

        return arg_2


def Func(arg_0, arg_1):
        """
        Return the description of the content item.
        """
        arg_2 = []

        for arg_3 in arg_0.enterprise_configuration.get_locales():
            arg_2.append({
                'locale': arg_3,
                'value': (
                    arg_1.get('full_description') or
                    arg_1.get('short_description') or
                    arg_1.get('title', '')
                )
            })

        return arg_2


def Func(arg_0, arg_1):
        """
        Return the image URI of the content item.
        """
        arg_2 = ''
        if arg_1['content_type'] in ['course', 'program']:
            arg_2 = arg_1.get('card_image_url')
        elif arg_1['content_type'] == 'courserun':
            arg_2 = arg_1.get('image_url')

        return arg_2


def Func(arg_0, arg_1):
        """
        Return the content metadata item launch points.

        SAPSF allows you to transmit an arry of content launch points which
        are meant to represent sections of a content item which a learner can
        launch into from SAPSF. Currently, we only provide a single launch
        point for a content item.
        """
        return [{
            'providerID': arg_0.enterprise_configuration.provider_id,
            'launchURL': arg_1['enrollment_url'],
            'contentTitle': arg_1['title'],
            'contentID': arg_0.get_content_id(arg_1),
            'launchType': 3,  # This tells SAPSF to launch the course in a new browser window.
            'mobileEnabled': True,  # Always return True per ENT-1401
            'mobileLaunchURL': arg_1['enrollment_url'],
        }]


def Func(arg_0, arg_1):
        """
        Return the title of the courserun content item.
        """
        arg_2 = arg_1.get('title') or ''
        arg_3 = arg_1.get('start')

        if arg_3:
            if course_available_for_enrollment(arg_1):
                arg_2 += ' ({starts}: {:%B %Y})'.format(
                    parse_lms_api_datetime(arg_3),
                    starts=_('Starts')
                )
            else:
                arg_2 += ' ({:%B %Y} - {enrollment_closed})'.format(
                    parse_lms_api_datetime(arg_3),
                    enrollment_closed=_('Enrollment Closed')
                )

        arg_4 = []
        arg_5 = transform_language_code(arg_1.get('content_language', ''))
        for arg_6 in arg_0.enterprise_configuration.get_locales(default_locale=arg_5):
            arg_4.append({
                'locale': arg_6,
                'value': arg_2
            })

        return arg_4


def Func(arg_0, arg_1):
        """
        Return the schedule of the courseun content item.
        """
        arg_2 = arg_1.get('start') or UNIX_MIN_DATE_STRING
        arg_3 = arg_1.get('end') or UNIX_MAX_DATE_STRING
        return [{
            'startDate': parse_datetime_to_epoch_millis(arg_2),
            'endDate': parse_datetime_to_epoch_millis(arg_3),
            'active': current_time_is_in_interval(arg_2, arg_3)
        }]


def Func(arg_0, arg_1):
        """
        Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content
        """
        arg_2 = arg_1.get('key', '')
        if arg_1['content_type'] == 'program':
            arg_2 = arg_1.get('uuid', '')
        return arg_2


def Func(arg_0, arg_1=1.0):
    """
    Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude.

    By default, returns seconds.
    """
    arg_2 = parse_lms_api_datetime(arg_0)
    arg_3 = arg_2 - UNIX_EPOCH
    return int(arg_3.total_seconds() * arg_1)


def Func(arg_0, arg_1):
    """
    Yield successive n-sized Func from dictionary.
    """
    arg_2 = iter(arg_0)
    for arg_3 in range(0, len(arg_0), arg_1):
        yield {arg_4: arg_0[arg_4] for arg_4 in islice(arg_2, arg_1)}


def Func(arg_0, arg_1='{D:02}d {H:02}h {M:02}m {S:02}s', arg_2='timedelta'):
    """
    Convert a datetime.timedelta object or a regular number to a custom-formatted string.

    This function works like the strftime() method works for datetime.datetime
    objects.

    The fmt argument allows custom formatting to be specified.  Fields can
    include seconds, minutes, hours, days, and weeks.  Each field is optional.

    Arguments:
        tdelta (datetime.timedelta, int): time delta object containing the duration or an integer
            to go with the input_type.
        fmt (str): Expected format of the time delta. place holders can only be one of the following.
            1. D to extract days from time delta
            2. H to extract hours from time delta
            3. M to extract months from time delta
            4. S to extract seconds from timedelta
        input_type (str):  The input_type argument allows tdelta to be a regular number instead of the
            default, which is a datetime.timedelta object.
            Valid input_type strings:
                1. 's', 'seconds',
                2. 'm', 'minutes',
                3. 'h', 'hours',
                4. 'd', 'days',
                5. 'w', 'weeks'
    Returns:
        (str): timedelta object interpolated into a string following the given format.

    Examples:
        '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
        '{W}w {D}d {H}:{M:02}:{S:02}'     --> '4w 5d 8:04:02'
        '{D:2}d {H:2}:{M:02}:{S:02}'      --> ' 5d  8:04:02'
        '{H}h {S}s'                       --> '72h 800s'
    """
    # Convert tdelta to integer seconds.
    if arg_2 == 'timedelta':
        arg_3 = int(arg_0.total_seconds())
    elif arg_2 in ['s', 'seconds']:
        arg_3 = int(arg_0)
    elif arg_2 in ['m', 'minutes']:
        arg_3 = int(arg_0) * 60
    elif arg_2 in ['h', 'hours']:
        arg_3 = int(arg_0) * 3600
    elif arg_2 in ['d', 'days']:
        arg_3 = int(arg_0) * 86400
    elif arg_2 in ['w', 'weeks']:
        arg_3 = int(arg_0) * 604800
    else:
        raise ValueError(
            'input_type is not valid. Valid input_type strings are: "timedelta", "s", "m", "h", "d", "w"'
        )

    arg_4 = Formatter()
    arg_5 = [field_tuple[1] for field_tuple in arg_4.parse(arg_1)]
    arg_6 = ('W', 'D', 'H', 'M', 'S')
    arg_7 = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
    arg_8 = {}

    for arg_9 in arg_6:
        if arg_9 in arg_5 and arg_9 in arg_7:
            arg_8[arg_9], arg_3 = divmod(arg_3, arg_7[arg_9])

    return arg_4.format(arg_1, **arg_8)


def Func(arg_0, arg_1):
        """
        Return the transformed version of the course description.

        We choose one value out of the course's full description, short description, and title
        depending on availability and length limits.
        """
        arg_2 = arg_1.get('full_description') or ''
        if 0 < len(arg_2) <= arg_0.LONG_STRING_LIMIT:  # pylint: disable=len-as-condition
            return arg_2
        return arg_1.get('short_description') or arg_1.get('title') or ''


def Func(arg_0, arg_1):
    """
    Delete the file if it already exist and returns the enterprise customer logo image path.

    Arguments:
        instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object
        filename (str): file to upload

    Returns:
        path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()

    """
    arg_2 = os.path.splitext(arg_1)[1].lower()
    arg_3 = str(arg_0.id)
    arg_4 = os.path.join("enterprise/branding/", arg_3, arg_3 + "_logo" + arg_2)
    if default_storage.exists(arg_4):
        default_storage.delete(arg_4)
    return arg_4


def Func(arg_0, arg_1):
        """
        Return link by email.
        """
        try:
            arg_2 = User.objects.get(email=arg_1)
            try:
                return arg_0.get(user_id=arg_2.id)
            except EnterpriseCustomerUser.DoesNotExist:
                pass
        except User.DoesNotExist:
            pass

        try:
            return PendingEnterpriseCustomerUser.objects.get(arg_1=arg_1)
        except PendingEnterpriseCustomerUser.DoesNotExist:
            pass

        return None


def Func(arg_0, arg_1, arg_2):
        """
        Unlink user email from Enterprise Customer.

        If :class:`django.contrib.auth.models.User` instance with specified email does not exist,
        :class:`.PendingEnterpriseCustomerUser` instance is deleted instead.

        Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with
        specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.

        Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of
        :class:`django.contrib.auth.models.User` with specified email exists and corresponding
        :class:`.PendingEnterpriseCustomerUser` instance does not.
        """
        try:
            arg_3 = User.objects.get(email=arg_2)
            # not capturing DoesNotExist intentionally to signal to view that link does not exist
            arg_4 = arg_0.get(arg_1=arg_1, user_id=arg_3.id)
            arg_4.delete()

            if update_user:
                # Remove the SailThru flags for enterprise learner.
                update_user.delay(
                    sailthru_vars={
                        'is_enterprise_learner': False,
                        'enterprise_name': None,
                    },
                    email=arg_2
                )

        except User.DoesNotExist:
            # not capturing DoesNotExist intentionally to signal to view that link does not exist
            arg_5 = PendingEnterpriseCustomerUser.objects.get(
                arg_1=arg_1, arg_2=arg_2
            )
            arg_5.delete()

        LOGGER.info(
            'Enterprise learner {%s} successfully unlinked from Enterprise Customer {%s}',
            arg_2,
            arg_1.name
        )


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
    """
    Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.

    :param username: The user that grants consent
    :param enterprise_customer_uuid: The consent requester
    :param course_id (optional): A course ID to which consent may be related
    :param program_uuid (optional): A program to which consent may be related
    :return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.
    """
    arg_4 = apps.get_model('enterprise', 'EnterpriseCustomer')  # pylint: disable=invalid-name
    try:
        if arg_2:
            return get_course_data_sharing_consent(arg_0, arg_2, arg_1)
        return get_program_data_sharing_consent(arg_0, arg_3, arg_1)
    except arg_4.DoesNotExist:
        return None