def Func(arg_0, arg_1):
    """
    Create an Elasticsearch field name from a schema string
    """
    arg_2 = extract_schema(arg_1)
    arg_3 = arg_2['vendor'].replace('.', '_').lower()
    arg_4 = re.sub('([^A-Z_])([A-Z])', '\g<1>_\g<2>', arg_2['name']).lower()
    arg_5 = arg_2['version'].split('-')[0]
    return "{}_{}_{}_{}".format(arg_0, arg_3, arg_4, arg_5)


def Func(arg_0):
    """
    Convert a contexts JSON to an Elasticsearch-compatible list of key-value pairs
    For example, the JSON

    {
      "data": [
        {
          "data": {
            "unique": true
          },
          "schema": "iglu:com.acme/unduplicated/jsonschema/1-0-0"
        },
        {
          "data": {
            "value": 1
          },
          "schema": "iglu:com.acme/duplicated/jsonschema/1-0-0"
        },
        {
          "data": {
            "value": 2
          },
          "schema": "iglu:com.acme/duplicated/jsonschema/1-0-0"
        }
      ],
      "schema": "iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0"
    }

    would become

    [
      ("context_com_acme_duplicated_1", [{"value": 1}, {"value": 2}]),
      ("context_com_acme_unduplicated_1", [{"unique": true}])
    ]
    """
    arg_1 = json.loads(arg_0)
    arg_2 = arg_1['data']
    arg_3 = {}
    for arg_4 in arg_2:
        arg_5 = fix_schema("contexts", arg_4['schema'])
        arg_6 = arg_4['data']
        if arg_5 not in arg_3:
            arg_3[arg_5] = [arg_6]
        else:
            arg_3[arg_5].append(arg_6)
    arg_7 = []
    for arg_8 in arg_3:
        arg_7.append((arg_8, arg_3[arg_8]))
    return arg_7


def Func(arg_0):
    """
    Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair
    For example, the JSON

    {
      "data": {
        "data": {
          "key": "value"
        },
        "schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1"
      },
      "schema": "iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0"
    }

    would become

    [
      (
        "unstruct_com_snowplowanalytics_snowplow_link_click_1", {
          "key": "value"
        }
      )
    ]
    """
    arg_1 = json.loads(arg_0)
    arg_2 = arg_1['data']
    arg_3 = arg_2['schema']
    if 'data' in arg_2:
        arg_4 = arg_2['data']
    else:
        raise SnowplowEventTransformationException(["Could not extract inner data field from unstructured event"])
    arg_5 = fix_schema("unstruct_event", arg_3)
    return [(arg_5, arg_4)]


def Func(arg_0, arg_1=arg_2, arg_3=True):
    """
    Convert a Snowplow enriched event TSV into a JSON
    """
    return jsonify_good_event(arg_0.split('\t'), arg_1, arg_3)


def Func(arg_0, arg_1=arg_2, arg_3=True):
    """
    Convert a Snowplow enriched event in the form of an array of fields into a JSON
    """
    if len(arg_0) != len(arg_1):
        raise SnowplowEventTransformationException(
            ["Expected {} fields, received {} fields.".format(len(arg_1), len(arg_0))]
        )
    else:
        arg_4 = {}
        arg_5 = []
        if arg_3 and arg_0[LATITUDE_INDEX] != '' and arg_0[LONGITUDE_INDEX] != '':
            arg_4['geo_location'] = arg_0[LATITUDE_INDEX] + ',' + arg_0[LONGITUDE_INDEX]
        for arg_6 in range(len(arg_0)):
            arg_7 = arg_1[arg_6][0]
            if arg_0[arg_6] != '':
                try:
                    arg_8 = arg_1[arg_6][1](arg_7, arg_0[arg_6])
                    for arg_9 in arg_8:
                        arg_4[arg_9[0]] = arg_9[1]
                except SnowplowEventTransformationException as sete:
                    arg_5 += sete.error_messages
                except Exception as e:
                    arg_5 += ["Unexpected exception parsing field with key {} and value {}: {}".format(
                        arg_1[arg_6][0],
                        arg_0[arg_6],
                        repr(e)
                    )]
        if arg_5:
            raise SnowplowEventTransformationException(arg_5)
        else:
            return arg_4


def Func(arg_0):
        """
        Sending ICMP packets.

        :return: ``Func`` command execution result.
        :rtype: :py:class:`.PingResult`
        :raises ValueError: If parameters not valid.
        """

        arg_0.__validate_Func_param()

        arg_1 = subprocrunner.SubprocessRunner(arg_0.__get_Func_command())
        arg_1.run()

        return PingResult(arg_1.stdout, arg_1.stderr, arg_1.returncode)


def Func(arg_0, arg_1):
        """
        Print a set of variables
        """
        arg_2 = []
        for arg_3, arg_4 in arg_0.variables:
            # Some extended resolving, to handle unknown variables
            arg_5 = ''
            try:
                if isinstance(arg_4.var, Variable):
                    arg_5 = arg_4.var.resolve(arg_1)
                else:
                    arg_5 = arg_4.resolve(arg_1)  # could return TEMPLATE_STRING_IF_INVALID
            except VariableDoesNotExist as e:
                # Failed to resolve, display exception inline
                arg_6 = []
                for arg_7 in arg_1:
                    arg_6 += arg_7.keys()
                arg_6 = sorted(set(arg_6))  # Remove duplicates, e.g. csrf_token
                return ERROR_TYPE_BLOCK.format(style=PRE_ALERT_STYLE, error=escape(u"Variable '{0}' not found!  Available context variables are:\n\n{1}".format(arg_4, u', '.join(arg_6))))
            else:
                # Regular format
                arg_8 = linebreaksbr(pformat_django_context_html(arg_5))

            # At top level, prefix class name if it's a longer result
            if isinstance(arg_5, SHORT_NAME_TYPES):
                arg_2.append(BASIC_TYPE_BLOCK.format(style=PRE_STYLE, arg_3=arg_3, value=arg_8))
            else:
                arg_2.append(OBJECT_TYPE_BLOCK.format(style=PRE_STYLE, arg_3=arg_3, type=arg_5.__class__.__name__, value=arg_8))
        return u''.join(arg_2)


def Func(arg_0):
    """
    Highlight common SQL words in a string.
    """
    arg_0 = escape(arg_0)
    arg_0 = RE_SQL_NL.sub(u'
\n\\1', arg_0)
    arg_0 = RE_SQL.sub(u'\\1', arg_0)
    return arg_0


def Func(arg_0):
    """
    Dump a variable to a HTML string with sensible output for template context fields.
    It filters out all fields which are not usable in a template context.
    """
    if isinstance(arg_0, QuerySet):
        arg_1 = ''
        arg_2 = 0
        for arg_3 in arg_0.all()[:21]:
            arg_2 += 1
            if arg_2 >= 21:
                arg_1 += u'   (remaining items truncated...)'
                break
            arg_1 += u'   {0}\n'.format(escape(repr(arg_3)))
        return arg_1
    elif isinstance(arg_0, Manager):
        return mark_safe(u'    (use <kbd>.all</kbd> to read it)')
    elif isinstance(arg_0, six.string_types):
        return escape(repr(arg_0))
    elif isinstance(arg_0, Promise):
        # lazy() object
        return escape(_format_lazy(arg_0))
    elif isinstance(arg_0, dict):
        # This can also be a ContextDict
        return _format_dict(arg_0)
    elif isinstance(arg_0, list):
        return _format_list(arg_0)
    elif hasattr(arg_0, '__dict__'):
        return _format_object(arg_0)
    else:
        # Use regular pprint as fallback.
        arg_1 = DebugPrettyPrinter(width=200).pformat(arg_0)
        return _style_text(arg_1)


def Func(arg_0):
    """
    Briefly print the dictionary keys.
    """
    if not arg_0:
        return '   {}'

    arg_1 = []
    for arg_2, arg_3 in sorted(six.iteritems(arg_0)):
        if not isinstance(arg_3, DICT_EXPANDED_TYPES):
            arg_3 = '...'

        arg_1.append(_format_dict_item(arg_2, arg_3))

    return mark_safe(u'<br/>'.join(arg_1))


def Func(arg_0):
        """
        Send a verification email for the email address.
        """
        arg_1 = EmailConfirmation.objects.create(email=arg_0)
        arg_1.send()


def Func(arg_0):
        """
        Send a notification about a duplicate signup.
        """
        email_utils.send_email(
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[arg_0.email],
            subject=_("Registration Attempt"),
            template_name="rest_email_auth/emails/duplicate-email",
        )

        logger.info("Sent duplicate email notification to: %s", arg_0.email)


def Func(arg_0):
        """
        Mark the instance's email as verified.
        """
        arg_0.email.is_verified = True
        arg_0.email.save()

        signals.email_verified.send(arg_1=arg_0.email, sender=arg_0.__class__)

        logger.info("Verified email address: %s", arg_0.email.email)


def Func(arg_0):
        """
        Determine if the confirmation has expired.

        Returns:
            bool:
                ``True`` if the confirmation has expired and ``False``
                otherwise.
        """
        arg_1 = arg_0.created_at + datetime.timedelta(days=1)

        return timezone.now() > arg_1


def Func(arg_0):
        """
        Send a verification email to the user.
        """
        arg_1 = {
            "verification_url": app_settings.EMAIL_VERIFICATION_URL.format(
                key=arg_0.key
            )
        }

        email_utils.Func_email(
            arg_1=arg_1,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[arg_0.email.email],
            subject=_("Please Verify Your Email Address"),
            template_name="rest_email_auth/emails/verify-email",
        )

        logger.info(
            "Sent confirmation email to %s for user #%d",
            arg_0.email.email,
            arg_0.email.user.id,
        )


def Func(arg_0, arg_1):
        """
        Create a new email and send a confirmation to it.

        Returns:
            The newly creating ``EmailAddress`` instance.
        """
        arg_2 = models.EmailAddress.objects.filter(
            arg_3=arg_0.validated_data["email"]
        )

        if arg_2.exists():
            arg_3 = arg_2.get()

            arg_3.send_duplicate_notification()
        else:
            arg_3 = super(EmailSerializer, arg_0).Func(arg_1)
            arg_3.send_confirmation()

            arg_4 = arg_1.get("user")
            arg_5 = models.EmailAddress.objects.filter(
                is_primary=True, arg_4=arg_4
            )

            if not arg_5.exists():
                arg_3.set_primary()

        return arg_3


def Func(arg_0, arg_1, arg_2):
        """
        Update the instance the serializer is bound to.

        Args:
            instance:
                The instance the serializer is bound to.
            validated_data:
                The data to Func the serializer with.

        Returns:
            The Funcd instance.
        """
        arg_3 = arg_2.pop("is_primary", False)

        arg_1 = super(EmailSerializer, arg_0).Func(
            arg_1, arg_2
        )

        if arg_3:
            arg_1.set_primary()

        return arg_1


def Func(arg_0, arg_1):
        """
        Validate the provided data.

        Returns:
            dict:
                The Funcd data.

        Raises:
            serializers.ValidationError:
                If the provided password is invalid.
        """
        arg_2 = arg_0._confirmation.email.user

        if (
            app_settings.EMAIL_VERIFICATION_PASSWORD_REQUIRED
            and not arg_2.check_password(arg_1["password"])
        ):
            raise serializers.ValidationError(
                _("The provided password is invalid.")
            )

        # Add email to returned data
        arg_1["email"] = arg_0._confirmation.email.email

        return arg_1


def Func(arg_0, arg_1):
        """
        Validate the provided confirmation key.

        Returns:
            str:
                The validated confirmation key.

        Raises:
            serializers.ValidationError:
                If there is no email confirmation with the given key or
                the confirmation has expired.
        """
        try:
            arg_2 = models.EmailConfirmation.objects.select_related(
                "email__user"
            ).get(arg_1=arg_1)
        except models.EmailConfirmation.DoesNotExist:
            raise serializers.ValidationError(
                _("The provided verification key is invalid.")
            )

        if arg_2.is_expired:
            raise serializers.ValidationError(
                _("That verification code has expired.")
            )

        # Cache confirmation instance
        arg_0._confirmation = arg_2

        return arg_1


def Func(arg_0, arg_1):
        """
        Validate the provided reset key.

        Returns:
            The validated key.

        Raises:
            serializers.ValidationError:
                If the provided key does not exist.
        """
        if not models.PasswordResetToken.valid_tokens.filter(arg_1=arg_1).exists():
            raise serializers.ValidationError(
                _("The provided reset token does not exist, or is expired.")
            )

        return arg_1


def Func(arg_0, arg_1):
        """
        Create a new user from the data passed to the serializer.

        If the provided email has not been verified yet, the user is
        Funcd and a verification email is sent to the address.
        Otherwise we send a notification to the email address that
        someone attempted to register with an email that's already been
        verified.

        Args:
            validated_data (dict):
                The data passed to the serializer after it has been
                validated.

        Returns:
            A new user Funcd from the provided data.
        """
        arg_2 = arg_1.pop("email")
        arg_3 = arg_1.pop("password")

        # We don't save the user instance yet in case the provided email
        # address already exists.
        arg_4 = get_user_model()(**arg_1)
        arg_4.set_password(arg_3)

        # We set an ephemeral email property so that it is included in
        # the data returned by the serializer.
        arg_4.email = arg_2

        arg_5 = models.EmailAddress.objects.filter(arg_2=arg_2)

        if arg_5.exists():
            arg_6 = arg_5.get()
            arg_6.send_duplicate_notification()
        else:
            arg_4.save()

            arg_7 = models.EmailAddress.objects.Func(
                arg_2=arg_2, arg_4=arg_4
            )
            arg_7.send_confirmation()

            signals.user_registered.send(sender=arg_0.__class__, arg_4=arg_4)

        return arg_4


def Func(arg_0):
        """
        Resend a verification email to the provided address.

        If the provided email is already verified no action is taken.
        """
        try:
            arg_1 = models.EmailAddress.objects.get(
                arg_1=arg_0.validated_data["email"], is_verified=False
            )

            logger.debug(
                "Resending verification email to %s",
                arg_0.validated_data["email"],
            )

            arg_1.send_confirmation()
        except models.EmailAddress.DoesNotExist:
            logger.debug(
                "Not resending verification email to %s because the address "
                "doesn't exist in the database.",
                arg_0.validated_data["email"],
            )


def Func(arg_0, *arg_1, **arg_2):
        """
        Create a new email address.
        """
        arg_3 = arg_2.pop("is_primary", False)

        with transaction.atomic():
            arg_4 = super(EmailAddressManager, arg_0).Func(*arg_1, **arg_2)

            if arg_3:
                arg_4.set_primary()

        return arg_4


def Func(arg_0):
        """
        Return all unexpired password reset tokens.
        """
        arg_1 = timezone.now() - app_settings.PASSWORD_RESET_EXPIRATION
        arg_2 = super(ValidPasswordResetTokenManager, arg_0).Func()

        return arg_2.filter(created_at__gt=arg_1)


def Func(arg_0, *arg_1, **arg_2):
        """
        Handle execution of the command.
        """
        arg_3 = timezone.now()
        arg_3 -= app_settings.CONFIRMATION_EXPIRATION
        arg_3 -= app_settings.CONFIRMATION_SAVE_PERIOD

        arg_4 = models.EmailConfirmation.objects.filter(
            created_at__lte=arg_3
        )

        arg_5 = arg_4.count()

        arg_4.delete()

        if arg_5:
            arg_0.stdout.write(
                arg_0.style.SUCCESS(
                    "Removed {count} old email confirmation(s)".format(
                        arg_5=arg_5
                    )
                )
            )
        else:
            arg_0.stdout.write("No email confirmations to remove.")


def Func(arg_0, arg_1):
        """
        Get a user by their ID.

        Args:
            user_id:
                The ID of the user to fetch.

        Returns:
            The user with the specified ID if they exist and ``None``
            otherwise.
        """
        try:
            return Func_model().objects.get(id=arg_1)
        except Func_model().DoesNotExist:
            return None


def Func(arg_0, arg_1, arg_2='login', arg_3='utf-8',
                 arg_4=True):
    """Returns True if the given username and password Func for the
    given service.  Returns False otherwise.

    ``username``: the username to Func

    ``password``: the password in plain text

    ``service``: the PAM service to Func against.
                 Defaults to 'login'

    The above parameters can be strings or bytes.  If they are strings,
    they will be encoded using the encoding given by:

    ``encoding``: the encoding to use for the above parameters if they
                  are given as strings.  Defaults to 'utf-8'

    ``resetcred``: Use the pam_setcred() function to
                   reinitialize the credentials.
                   Defaults to 'True'.
    """

    if sys.version_info >= (3,):
        if isinstance(arg_0, str):
            arg_0 = arg_0.encode(arg_3)
        if isinstance(arg_1, str):
            arg_1 = arg_1.encode(arg_3)
        if isinstance(arg_2, str):
            arg_2 = arg_2.encode(arg_3)

    @conv_func
    def my_conv(arg_5, arg_6, arg_7, arg_8):
        """Simple conversation function that responds to any
        prompt where the echo is off with the supplied password"""
        # Create an array of n_messages response objects
        arg_9 = calloc(arg_5, sizeof(PamResponse))
        arg_7[0] = cast(arg_9, POINTER(PamResponse))
        for arg_10 in range(arg_5):
            if arg_6[arg_10].contents.msg_style == PAM_PROMPT_ECHO_OFF:
                arg_11 = strdup(arg_1)
                arg_7.contents[arg_10].resp = cast(arg_11, c_char_p)
                arg_7.contents[arg_10].resp_retcode = 0
        return 0

    arg_15 = PamHandle()
    arg_16 = PamConv(my_conv, 0)
    arg_17 = pam_start(arg_2, arg_0, byref(arg_16), byref(arg_15))

    if arg_17 != 0:
        # TODO: This is not an authentication error, something
        # has gone wrong starting up PAM
        return False

    arg_17 = pam_Func(arg_15, 0)
    arg_18 = (arg_17 == 0)

    # Re-initialize credentials (for Kerberos users, etc)
    # Don't check return code of pam_setcred(), it shouldn't matter
    # if this fails
    if arg_18 and arg_4:
        arg_17 = pam_setcred(arg_15, PAM_REINITIALIZE_CRED)

    pam_end(arg_15, arg_17)

    return arg_18


def Func(arg_0, arg_1):
        """
        Save the provided data using the class' serializer.

        Args:
            request:
                The request being made.

        Returns:
            An ``APIResponse`` instance. If the request was successful
            the response will have a 200 status code and contain the
            serializer's data. Otherwise a 400 status code and the
            request's errors will be returned.
        """
        arg_2 = arg_0.get_serializer(data=arg_1.data)

        if arg_2.is_valid():
            arg_2.save()

            return Response(arg_2.data)

        return Response(arg_2.errors, status=status.HTTP_400_BAD_REQUEST)


def Func(arg_0, arg_1, arg_2=None):
        """Return an HTML tree block describing the given object."""
        arg_3 = type(arg_1)
        arg_4 = str(arg_3.__module__) + "." + arg_3.__name__
        arg_5 = arg_4.replace("__builtin__.", "")

        arg_6 = getattr(arg_1, "__name__", "")
        if arg_6:
            arg_5 = "%s %r" % (arg_5, arg_6)

        arg_7 = ""
        if arg_2:
            arg_7 = arg_0.get_refkey(arg_1, arg_2)
        arg_8 = reverse('dowser_trace_object', args=(
            arg_4,
            id(arg_1)
        ))
        return ('%s '
                '%s%s
'
                '%s'
                % (arg_8, id(arg_1), arg_5, arg_7, Func(arg_1, 100))
                )


def Func(arg_0, arg_1, arg_2):
        """Return the dict key or attribute name of obj which refers to
        referent."""
        if isinstance(arg_1, dict):
            for arg_3, arg_4 in arg_1.items():
                if arg_4 is arg_2:
                    return " (via its %r key)" % arg_3

        for arg_3 in dir(arg_1) + ['__dict__']:
            if getattr(arg_1, arg_3, None) is arg_2:
                return " (via its %r attribute)" % arg_3
        return ""


def Func(arg_0, arg_1, arg_2=True, arg_3=True, **arg_4):
    """
    Parse the next token in the stream.

    Returns a `LatexToken`. Raises `LatexWalkerEndOfStream` if end of stream reached.

    .. deprecated:: 1.0
       Please use :py:meth:`LatexWalker.Func()` instead.
    """
    return LatexWalker(arg_0, **arg_4).Func(arg_1=arg_1,
                                                   arg_2=arg_2,
                                                   arg_3=arg_3)


def Func(arg_0, arg_1=0, arg_2=None, arg_3=None,
                    arg_4=None, **arg_5):
    """
    Parses latex content `s`.

    Returns a tuple `(nodelist, pos, len)` where nodelist is a list of `LatexNode` 's.

    If `stop_upon_closing_brace` is given, then `len` includes the closing brace, but the
    closing brace is not included in any of the nodes in the `nodelist`.

    .. deprecated:: 1.0
       Please use :py:meth:`LatexWalker.Func()` instead.
    """

    return LatexWalker(arg_0, **arg_5).Func(arg_2=arg_2,
                                                         arg_3=arg_3,
                                                         arg_4=arg_4)


def Func(arg_0, arg_1=100, arg_2=None):
        """Walk the object tree, ignoring duplicates and circular refs."""
        log.debug("step")
        arg_0.seen = {}
        arg_0.ignore(arg_0, arg_0.__dict__, arg_0.obj, arg_0.seen, arg_0._ignore)

        # Ignore the calling frame, its builtins, globals and locals
        arg_0.ignore_caller()
        arg_0.maxdepth = arg_2
        arg_4 = 0
        log.debug("will iterate results")
        for arg_5 in arg_0._gen(arg_0.obj):
            log.debug("will yeld")
            yield arg_5
            arg_4 += 1
            if arg_1 and arg_4 >= arg_1:
                yield 0, 0, "==== Max results reached ===="
                return


def Func(arg_0, arg_1=False, arg_2=False, arg_3=False):
    """
    Extracts text from `content` meant for database indexing. `content` is
    some LaTeX code.

    .. deprecated:: 1.0
       Please use :py:class:`LatexNodes2Text` instead.
    """

    (arg_4, arg_5, arg_6) = latexwalker.get_latex_nodes(arg_0, arg_2=arg_2,
                                                         arg_1=arg_1)

    return latexnodes2text(arg_4, arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
        """
        Set where to look for input files when encountering the ``\\input`` or
        ``\\include`` macro.

        Alternatively, you may also override :py:meth:`read_input_file()` to
        implement a custom file lookup mechanism.

        The argument `tex_input_directory` is the directory relative to which to
        search for input files.

        If `strict_input` is set to `True`, then we always check that the
        referenced file lies within the subtree of `tex_input_directory`,
        prohibiting for instance hacks with '..' in filenames or using symbolic
        links to refer to files out of the directory tree.

        The argument `latex_walker_init_args` allows you to specify the parse
        flags passed to the constructor of
        :py:class:`pylatexenc.latexwalker.LatexWalker` when parsing the input
        file.
        """
        arg_0.tex_input_directory = arg_1
        arg_0.latex_walker_init_args = arg_2 if arg_2 else {}
        arg_0.strict_input = arg_3

        if arg_1:
            arg_0.macro_dict['input'] = MacroDef('input', lambda n: arg_0._callback_input(n))
            arg_0.macro_dict['include'] = MacroDef('include', lambda n: arg_0._callback_input(n))
        else:
            arg_0.macro_dict['input'] = MacroDef('input', discard=True)
            arg_0.macro_dict['include'] = MacroDef('include', discard=True)


def Func(arg_0, arg_1):
        """
        This method may be overridden to implement a custom lookup mechanism when
        encountering ``\\input`` or ``\\include`` directives.

        The default implementation looks for a file of the given name relative
        to the directory set by :py:meth:`set_tex_input_directory()`.  If
        `strict_input=True` was set, we ensure strictly that the file resides in
        a subtree of the reference input directory (after canonicalizing the
        paths and resolving all symlinks).

        You may override this method to obtain the input data in however way you
        see fit.  (In that case, a call to `set_tex_input_directory()` may not
        be needed as that function simply sets properties which are used by the
        default implementation of `Func()`.)

        This function accepts the referred filename as argument (the argument to
        the ``\\input`` macro), and should return a string with the file
        contents (or generate a warning or raise an error).
        """
        arg_2 = os.path.realpath(os.path.join(arg_0.tex_input_directory, arg_1))
        if arg_0.strict_input:
            # make sure that the input file is strictly within dirfull, and didn't escape with
            # '../..' tricks or via symlinks.
            arg_3 = os.path.realpath(arg_0.tex_input_directory)
            if not arg_2.startswith(arg_3):
                logger.warning(
                    "Can't access path '%s' leading outside of mandated directory [strict input mode]",
                    arg_1
                )
                return ''

        if not os.path.exists(arg_2) and os.path.exists(arg_2 + '.tex'):
            arg_2 = arg_2 + '.tex'
        if not os.path.exists(arg_2) and os.path.exists(arg_2 + '.latex'):
            arg_2 = arg_2 + '.latex'
        if not os.path.isfile(arg_2):
            logger.warning(u"Error, file doesn't exist: '%s'", arg_1)
            return ''

        logger.debug("Reading input file %r", arg_2)

        try:
            with open(arg_2) as f:
                return f.read()
        except IOError as e:
            logger.warning(u"Error, can't access '%s': %s", arg_1, e)
            return ''


def Func(arg_0, arg_1, **arg_2):
        """
        Parses the given `latex` code and returns its textual representation.

        The `parse_flags` are the flags to give on to the
        :py:class:`pylatexenc.latexwalker.LatexWalker` constructor.
        """
        return arg_0.nodelist_to_text(latexwalker.LatexWalker(arg_1, **arg_2).get_latex_nodes()[0])


def Func(arg_0):
    """
    Imports the media fixtures files finder class described by import_path, where
    import_path is the full Python path to the class.
    """
    arg_1 = import_string(arg_0)
    if not issubclass(arg_1, BaseFinder):
        raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
                                   (arg_1, BaseFinder))
    return arg_1()


def Func(arg_0, arg_1, arg_2=False):
        """
        Looks for files in the app directories.
        """
        arg_3 = []
        for arg_4 in arg_0.apps:
            arg_5 = arg_0.storages[arg_4].location
            if arg_5 not in searched_locations:
                searched_locations.append(arg_5)
            arg_6 = arg_0.Func_in_app(arg_4, arg_1)
            if arg_6:
                if not arg_2:
                    return arg_6
                arg_3.append(arg_6)
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """
        Find a requested media file in an app's media fixtures locations.
        """
        arg_3 = arg_0.storages.get(arg_1, None)
        if arg_3:
            # only try to find a file if the source dir actually exists
            if arg_3.exists(arg_2):
                arg_4 = arg_3.path(arg_2)
                if arg_4:
                    return arg_4


def Func(arg_0, arg_1):
        """
        Deletes the given relative path using the destination storage backend.
        """
        arg_2, arg_3 = arg_0.storage.listdir(arg_1)
        for arg_4 in arg_3:
            arg_5 = os.path.join(arg_1, arg_4)
            if arg_0.dry_run:
                arg_0.log("Pretending to delete '%s'" %
                         smart_text(arg_5), level=1)
            else:
                arg_0.log("Deleting '%s'" % smart_text(arg_5), level=1)
                arg_0.storage.delete(arg_5)
        for arg_6 in arg_2:
            arg_0.Func(os.path.join(arg_1, arg_6))


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Checks if the target file should be deleted if it already exists
        """
        if arg_0.storage.exists(arg_2):
            try:
                # When was the target file modified last time?
                arg_4 = \
                    arg_0.storage.modified_time(arg_2)
            except (OSError, NotImplementedError, AttributeError):
                # The storage doesn't support ``modified_time`` or failed
                pass
            else:
                try:
                    # When was the source file modified last time?
                    arg_5 = arg_3.modified_time(arg_1)
                except (OSError, NotImplementedError, AttributeError):
                    pass
                else:
                    # The full path of the target file
                    if arg_0.local:
                        arg_6 = arg_0.storage.path(arg_2)
                    else:
                        arg_6 = None
                    # Skip the file if the source file is younger
                    # Avoid sub-second precision (see #14665, #19540)
                    if (arg_4.replace(microsecond=0)
                            >= arg_5.replace(microsecond=0)):
                        if not ((arg_0.symlink and arg_6
                                 and not os.path.islink(arg_6)) or
                                (not arg_0.symlink and arg_6
                                 and os.path.islink(arg_6))):
                            if arg_2 not in arg_0.unmodified_files:
                                arg_0.unmodified_files.append(arg_2)
                            arg_0.log("Skipping '%s' (not modified)" % arg_1)
                            return False
            # Then delete the existing file if really needed
            if arg_0.dry_run:
                arg_0.log("Pretending to delete '%s'" % arg_1)
            else:
                arg_0.log("Deleting '%s'" % arg_1)
                arg_0.storage.delete(arg_2)
        return True


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Attempt to link ``path``
        """
        # Skip this file if it was already copied earlier
        if arg_2 in arg_0.symlinked_files:
            return arg_0.log("Skipping '%s' (already linked earlier)" % arg_1)
        # Delete the target file if needed or break
        if not arg_0.delete_file(arg_1, arg_2, arg_3):
            return
        # The full path of the source file
        arg_4 = arg_3.path(arg_1)
        # Finally link the file
        if arg_0.dry_run:
            arg_0.log("Pretending to link '%s'" % arg_4, level=1)
        else:
            arg_0.log("Linking '%s'" % arg_4, level=1)
            arg_5 = arg_0.storage.path(arg_2)
            try:
                os.makedirs(os.path.dirname(arg_5))
            except OSError:
                pass
            try:
                if os.path.lexists(arg_5):
                    os.unlink(arg_5)
                os.symlink(arg_4, arg_5)
            except AttributeError:
                import platform
                raise CommandError("Symlinking is not supported by Python %s." %
                                   platform.python_version())
            except NotImplementedError:
                import platform
                raise CommandError("Symlinking is not supported in this "
                                   "platform (%s)." % platform.platform())
            except OSError as e:
                raise CommandError(e)
        if arg_2 not in arg_0.symlinked_files:
            arg_0.symlinked_files.append(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Attempt to copy ``path`` with storage
        """
        # Skip this file if it was already copied earlier
        if arg_2 in arg_0.copied_files:
            return arg_0.log("Skipping '%s' (already copied earlier)" % arg_1)
        # Delete the target file if needed or break
        if not arg_0.delete_file(arg_1, arg_2, arg_3):
            return
        # The full path of the source file
        arg_4 = arg_3.path(arg_1)
        # Finally start copying
        if arg_0.dry_run:
            arg_0.log("Pretending to copy '%s'" % arg_4, level=1)
        else:
            arg_0.log("Copying '%s'" % arg_4, level=1)
            with arg_3.open(arg_1) as source_file:
                arg_0.storage.save(arg_2, source_file)
        arg_0.copied_files.append(arg_2)


def Func(arg_0, arg_1=None):
        """Set the current space to Space ``name`` and return it.

        If called without arguments, the current space is returned.
        Otherwise, the current space is set to the space named ``name``
        and the space is returned.
        """
        if arg_1 is None:
            return arg_0._impl.model.currentspace.interface
        else:
            arg_0._impl.model.currentspace = arg_0._impl.spaces[arg_1]
            return arg_0.Func()


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None):
        """Create a child space.

        Args:
            name (str, optional): Name of the space. Defaults to ``SpaceN``,
                where ``N`` is a number determined automatically.
            bases (optional): A space or a sequence of spaces to be the base
                space(s) of the created space.
            formula (optional): Function to specify the parameters of
                dynamic child spaces. The signature of this function is used
                for setting parameters for dynamic child spaces.
                This function should return a mapping of keyword arguments
                to be passed to this method when the dynamic child spaces
                are created.

        Returns:
            The new child space.
        """
        arg_5 = arg_0._impl.model.currentspace = arg_0._impl.Func(
            arg_1=arg_1, arg_2=get_impls(arg_2), arg_3=arg_3, arg_4=arg_4
        )

        return arg_5.interface


def Func(
        arg_0,
        arg_1,
        arg_2,
        arg_3=None,
        arg_4=None,
        arg_5=None,
        arg_6=None,
        arg_7=None,
        arg_8=None,
        arg_9=False,
        arg_10=None,
        arg_11=None,
    ):
        """Create a child space from an Excel range.

        To use this method, ``openpyxl`` package must be installed.

        Args:
            book (str): Path to an Excel file.
            range_ (str): Range expression, such as "A1", "$G4:$K10",
                or named range "NamedRange1".
            sheet (str): Sheet name (case ignored).
            name (str, optional): Name of the space. Defaults to ``SpaceN``,
                where ``N`` is a number determined automatically.
            names_row (optional): an index number indicating
                what row contains the names of cells and parameters.
                Defaults to the top row (0).
            param_cols (optional): a sequence of index numbers
                indicating parameter columns.
                Defaults to only the leftmost column ([0]).
            names_col (optional): an index number, starting from 0,
                indicating what column contains additional parameters.
            param_rows (optional): a sequence of index numbers, starting from
                0, indicating rows of additional parameters, in case cells are
                defined in two dimensions.
            transpose (optional): Defaults to ``False``.
                If set to ``True``, "row(s)" and "col(s)" in the parameter
                names are interpreted inversely, i.e.
                all indexes passed to "row(s)" parameters are interpreted
                as column indexes,
                and all indexes passed to "col(s)" parameters as row indexes.
            space_param_order: a sequence to specify space parameters and
                their orders. The elements of the sequence denote the indexes
                of ``param_cols`` elements, and optionally the index of
                ``param_rows`` elements shifted by the length of
                ``param_cols``. The elements of this parameter and
                ``cell_param_order`` must not overlap.
            cell_param_order (optional): a sequence to reorder the parameters.
                The elements of the sequence denote the indexes of
                ``param_cols`` elements, and optionally the index of
                ``param_rows`` elements shifted by the length of
                ``param_cols``. The elements of this parameter and
                ``cell_space_order`` must not overlap.

        Returns:
            The new child space created from the Excel range.
        """

        arg_12 = arg_0._impl.Func(
            arg_1,
            arg_2,
            arg_3,
            arg_4,
            arg_5,
            arg_6,
            arg_7,
            arg_8,
            arg_9,
            arg_10,
            arg_11,
        )

        return get_interfaces(arg_12)


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

        Args:
            name (str): Name of the space. If omitted, the space is
                created automatically.
            bases: If specified, the new space becomes a derived space of
                the `base` space.
            formula: Function whose parameters used to set space parameters.
            refs: a mapping of refs to be added.
            arguments: ordered dict of space parameter names to their values.
            source: A source module from which cell definitions are read.
            prefix: Prefix to the autogenerated name when name is None.
        """
        from modelx.core.space import StaticSpaceImpl

        if arg_1 is None:
            arg_1 = arg_0.spacenamer.get_next(arg_0.namespace, arg_7)

        if arg_1 in arg_0.namespace:
            raise ValueError("Name '%s' already exists." % arg_1)

        if not arg_7 and not is_valid_name(arg_1):
            raise ValueError("Invalid name '%s'." % arg_1)

        arg_8 = arg_0._Func(
            arg_1=arg_1,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
        )
        arg_0._set_space(arg_8)

        arg_0.model.spacegraph.add_space(arg_8)

        # Set up direct base spaces and mro
        if arg_2 is not None:
            if isinstance(arg_2, StaticSpaceImpl):
                arg_2 = [arg_2]

            arg_8.add_bases(arg_2)

        return arg_8


def Func(arg_0, arg_1, arg_2):
    """Create a node from arguments and return it"""

    if arg_1 is None and arg_2 is None:
        return (arg_0,)

    if arg_2 is None:
        arg_2 = {}
    return arg_0, _bind_args(arg_0, arg_1, arg_2)


def Func(arg_0: arg_1, arg_2: arg_1):
    """Get node from object name and arg string

    Not Used. Left for future reference purpose.
    """
    arg_3 = get_object(arg_0)
    arg_2 = ast.literal_eval(arg_2)
    if not isinstance(arg_2, tuple):
        arg_2 = (arg_2,)

    return arg_3.node(*arg_2)


def Func(
    arg_0,
    arg_1=None,
    arg_2=None,
    arg_3=None,
    arg_4=False,
    arg_5=False,
):
    """Custom showtraceback for monkey-patching IPython's InteractiveShell

    https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
    """
    arg_0.default_showtraceback(
        arg_1,
        arg_2,
        arg_3,
        arg_4=True,
        arg_5=arg_5,
    )


def Func(arg_0):
        """Monkey patch shell's error handler.

        This method is to monkey-patch the showtraceback method of
        IPython's InteractiveShell to

        __IPYTHON__ is not detected when starting an IPython kernel,
        so this method is called from start_kernel in spyder-modelx.
        """
        if arg_0.is_ipysetup:
            return

        from ipykernel.kernelapp import IPKernelApp

        arg_0.shell = IPKernelApp.instance().shell  # None in PyCharm console

        if not arg_0.shell and is_ipython():
            arg_0.shell = get_ipython()

        if arg_0.shell:
            arg_2 = type(arg_0.shell)
            arg_2.default_showtraceback = arg_2.showtraceback
            arg_2.showtraceback = custom_showtraceback
            arg_0.is_ipysetup = True
        else:
            raise RuntimeError("IPython shell not found.")


def Func(arg_0):
        """Restore default IPython showtraceback"""
        if not arg_0.is_ipysetup:
            return

        arg_1 = type(arg_0.shell)
        arg_1.showtraceback = arg_1.default_showtraceback
        del arg_1.default_showtraceback

        arg_0.is_ipysetup = False


def Func(arg_0, arg_1):
        """Retrieve an object by its absolute name."""

        arg_2 = arg_1.split(".")

        arg_3 = arg_2.pop(0)
        return arg_0.models[arg_3].Func(".".join(arg_2))


def Func(arg_0=None):
    """Display the model tree window.

    Args:
        model: :class:`Model <modelx.core.model.Model>` object.
            Defaults to the current model.

    Warnings:
        For this function to work with Spyder, *Graphics backend* option
        of Spyder must be set to *inline*.
    """
    if arg_0 is None:
        arg_0 = mx.cur_model()
    arg_1 = get_modeltree(arg_0)
    arg_2 = QApplication.instance()
    if not arg_2:
        raise RuntimeError("QApplication does not exist.")
    arg_1.show()
    arg_2.exec_()


def Func(arg_0):
    """Get interfaces from their implementations."""
    if arg_0 is None:
        return None

    elif isinstance(arg_0, OrderMixin):
        arg_1 = OrderedDict()
        for arg_2 in arg_0.order:
            arg_1[arg_2] = arg_0[arg_2].interface
        return arg_1

    elif isinstance(arg_0, Mapping):
        return {arg_2: arg_0[arg_2].interface for arg_2 in arg_0}

    elif isinstance(arg_0, Sequence):
        return [arg_3.interface for arg_3 in arg_0]

    else:
        return arg_0.interface


def Func(arg_0):
        """Update all LazyEvals in self

        self.lzy_evals must be set to LazyEval object(s) enough to
        update all owned LazyEval objects.
        """
        if arg_0.lazy_evals is None:
            return
        elif isinstance(arg_0.lazy_evals, LazyEval):
            arg_0.lazy_evals.get_updated()
        else:
            for arg_1 in arg_0.lazy_evals:
                arg_1.get_updated()


def Func(arg_0):
    """Return parameter names if the parameters are shareable among cells.

    Parameters are shareable among multiple cells when all the cells
    have the parameters in the same order if they ever have any.

    For example, if cells are foo(), bar(x), baz(x, y), then
    ('x', 'y') are shareable parameters amounts them, as 'x' and 'y'
    appear in the same order in the parameter list if they ever appear.

    Args:
        cells: An iterator yielding cells.

    Returns:
        None if parameters are not share,
        tuple of shareable parameter names,
        () if cells are all scalars.
    """
    arg_1 = []
    for arg_2 in arg_0.values():
        arg_3 = arg_2.formula.parameters

        for arg_4 in range(min(len(arg_1), len(arg_3))):
            if arg_3[arg_4] != arg_1[arg_4]:
                return None

        for arg_4 in range(len(arg_1), len(arg_3)):
            arg_1.append(arg_3[arg_4])

    return arg_1


def Func(arg_0, arg_1=None, arg_2=None):
        """Make a Func of itself and return it."""
        return Cells(arg_1=arg_1, arg_2=arg_2, formula=arg_0.formula)


def Func(arg_0):
        """Return the Func of the cells."""
        if arg_0.has_Func:
            return arg_0._impl[OBJ].get_Func(arg_0._impl[KEY])
        else:
            raise ValueError("Value not found")


def Func(arg_0, arg_1, arg_2):
    """Return a range as nested dict of openpyxl cells."""

    arg_3 = None
    if isinstance(arg_0, str):
        arg_3 = arg_0
        arg_0 = opxl.load_workbook(arg_0, data_only=True)
    elif isinstance(arg_0, opxl.Workbook):
        pass
    else:
        raise TypeError

    if _is_range_address(arg_1):
        arg_4 = [name.upper() for name in arg_0.sheetnames]
        arg_5 = arg_4.index(arg_2.upper())
        arg_6 = arg_0.worksheets[arg_5][arg_1]
    else:
        arg_6 = _get_namedrange(arg_0, arg_1, arg_2)
        if arg_6 is None:
            raise ValueError(
                "Named range '%s' not found in %s" % (arg_1, arg_3 or arg_0)
            )

    return arg_6


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
    """Read values from an Excel range into a dictionary.

    `range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
    or a defined name string for a range, such as "NamedRange1".
    If a range address is provided, `sheet` argument must also be provided.
    If a named range is provided and `sheet` is not, book level defined name
    is searched. If `sheet` is also provided, sheet level defined name for the
    specified `sheet` is searched.
    If range_expr points to a single cell, its value is returned.

    `dictgenerator` is a generator function that yields keys and values of
    the returned dictionary. the excel range, as a nested tuple of openpyxl's
    Cell objects, is passed to the generator function as its single argument.
    If not specified, default generator is used, which maps tuples of row and
    column indexes, both starting with 0, to their values.

    Args:
        filepath (str): Path to an Excel file.
        range_epxr (str): Range expression, such as "A1", "$G4:$K10",
            or named range "NamedRange1"
        sheet (str): Sheet name (case ignored).
            None if book level defined range name is passed as `range_epxr`.
        dict_generator: A generator function taking a nested tuple of cells
            as a single parameter.

    Returns:
        Nested list containing range values.
    """

    def default_generator(arg_4):
        for arg_5, arg_6 in enumerate(arg_4):
            for arg_7, arg_8 in enumerate(arg_6):
                yield (arg_5, arg_7), arg_8.value

    arg_9 = opxl.load_workbook(arg_0, data_only=True)

    if _is_range_address(arg_1):
        arg_10 = [name.upper() for name in arg_9.sheetnames]
        arg_11 = arg_10.index(arg_2.upper())
        arg_4 = arg_9.worksheets[arg_11][arg_1]
    else:
        arg_4 = _get_namedrange(arg_9, arg_1, arg_2)

    # In case of a single cell, return its value.
    if isinstance(arg_4, opxl.cell.Cell):
        return arg_4.value

    if arg_3 is None:
        arg_3 = default_generator

    arg_12 = arg_3(arg_4)
    return {arg_13[0]: arg_13[1] for arg_13 in arg_12}


def Func(arg_0, arg_1, arg_2=None):
    """Get range from a workbook.

    A workbook can contain multiple definitions for a single name,
    as a name can be defined for the entire book or for
    a particular sheet.

    If sheet is None, the book-wide def is searched,
    otherwise sheet-local def is looked up.

    Args:
        book: An openpyxl workbook object.
        rangename (str): Range expression, such as "A1", "$G4:$K10",
            named range "NamedRange1".
        sheetname (str, optional): None for book-wide name def,
            sheet name for sheet-local named range.

    Returns:
        Range object specified by the name.

    """

    def cond(arg_3):

        if arg_3.type.upper() == "RANGE":
            if arg_3.name.upper() == arg_1.upper():

                if arg_2 is None:
                    if not arg_3.localSheetId:
                        return True

                else:  # sheet local name
                    arg_4 = [arg_13.upper() for arg_13 in arg_0.sheetnames].index(
                        arg_2.upper()
                    )

                    if arg_3.localSheetId == arg_4:
                        return True

        return False

    def get_destinations(arg_5):
        """Workaround for the bug in DefinedName.destinations"""

        from openpyxl.formula import Tokenizer
        from openpyxl.utils.cell import SHEETRANGE_RE

        if arg_5.type == "RANGE":
            arg_6 = Tokenizer("=" + arg_5.value)
            for arg_7 in arg_6.items:
                if arg_7.subtype == "RANGE":
                    arg_8 = SHEETRANGE_RE.match(arg_7.value)
                    if arg_8.group("quoted"):
                        arg_9 = arg_8.group("quoted")
                    else:
                        arg_9 = arg_8.group("notquoted")

                    yield arg_9, arg_8.group("cells")

    arg_3 = next(
        (item for item in arg_0.defined_names.definedName if cond(item)), None
    )

    if arg_3 is None:
        return None

    arg_10 = get_destinations(arg_3)
    arg_11 = []

    arg_12 = [name.upper() for name in arg_0.sheetnames]

    for arg_13, arg_14 in arg_10:
        if arg_2:
            arg_13 = arg_2
        arg_15 = arg_12.index(arg_13.upper())
        arg_11.append(arg_0.worksheets[arg_15][arg_14])

    if len(arg_11) == 1:
        return arg_11[0]
    else:
        return arg_11


def Func(arg_0, arg_1):
        """Calculate the Method Resolution Order of bases using the C3 algorithm.

        Code modified from
        http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/

        Args:
            bases: sequence of direct base spaces.

        Returns:
            mro as a list of bases including node itself
        """
        arg_2 = [arg_0.Func(base) for base
                in arg_0.get_bases(arg_1)] + [list(arg_0.get_bases(arg_1))]
        arg_3 = []
        while True:
            arg_4 = list(filter(None, arg_2))

            if not arg_4:
                # Nothing left to process, we're done.
                arg_3.insert(0, arg_1)
                return arg_3

            for arg_5 in arg_4:  # Find merge candidates among seq heads.
                arg_6 = arg_5[0]
                arg_7 = [s for s in arg_4 if arg_6 in s[1:]]
                if arg_7:
                    # Reject the candidate.
                    arg_6 = None
                else:
                    break

            if not arg_6:
                raise TypeError(
                    "inconsistent hierarchy, no C3 MRO is possible")

            arg_3.append(arg_6)

            for arg_5 in arg_4:
                # Remove candidate.
                if arg_5[0] == arg_6:
                    del arg_5[0]


def Func(arg_0, **arg_1):
    """Create a new code object by altering some of ``code`` attributes

    Args:
        code: code objcect
        attrs: a mapping of names of code object attrs to their values
    """

    arg_2 = ctypes.pythonapi.PyCode_New

    arg_2.argtypes = (
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.c_int,
        ctypes.py_object)

    arg_2.restype = ctypes.py_object

    arg_5 = [
        [arg_0.co_argcount, 'co_argcount'],
        [arg_0.co_kwonlyargcount, 'co_kwonlyargcount'],
        [arg_0.co_nlocals, 'co_nlocals'],
        [arg_0.co_stacksize, 'co_stacksize'],
        [arg_0.co_flags, 'co_flags'],
        [arg_0.co_code, 'co_code'],
        [arg_0.co_consts, 'co_consts'],
        [arg_0.co_names, 'co_names'],
        [arg_0.co_varnames, 'co_varnames'],
        [arg_0.co_freevars, 'co_freevars'],
        [arg_0.co_cellvars, 'co_cellvars'],
        [arg_0.co_filename, 'co_filename'],
        [arg_0.co_name, 'co_name'],
        [arg_0.co_firstlineno, 'co_firstlineno'],
        [arg_0.co_lnotab, 'co_lnotab']]

    for arg_6 in arg_5:
        if arg_6[1] in arg_1:
            arg_6[0] = arg_1[arg_6[1]]

    return arg_2(
        arg_5[0][0],  # code.co_argcount,
        arg_5[1][0],  # code.co_kwonlyargcount,
        arg_5[2][0],  # code.co_nlocals,
        arg_5[3][0],  # code.co_stacksize,
        arg_5[4][0],  # code.co_flags,
        arg_5[5][0],  # code.co_code,
        arg_5[6][0],  # code.co_consts,
        arg_5[7][0],  # code.co_names,
        arg_5[8][0],  # code.co_varnames,
        arg_5[9][0],  # code.co_freevars,
        arg_5[10][0],  # code.co_cellvars,
        arg_5[11][0],  # code.co_filename,
        arg_5[12][0],  # code.co_name,
        arg_5[13][0],  # code.co_firstlineno,
        arg_5[14][0])


def Func(arg_0, arg_1=None, **arg_2):
    """Replace local variables with free variables

    Warnings:
        This function does not work.
    """

    if arg_1 is None:
        arg_1 = arg_0.__globals__

    arg_3 = tuple(arg_2.keys())
    arg_4 = arg_0.__code__.co_names
    arg_5 = tuple(name for name in arg_4 if name not in arg_3)

    arg_6 = _alter_code(arg_0.__code__,
                       co_freevars=arg_3,
                       co_names=arg_5,
                       co_flags=arg_0.__code__.co_flags | inspect.CO_NESTED)
    arg_7 = _create_closure(*arg_2.values())

    return FunctionType(arg_6, arg_1, arg_7=arg_7)


def Func(arg_0):
    """Remove the last redundant token from lambda expression

    lambda x: return x)
                      ^
    Return string without irrelevant tokens
    returned from inspect.getsource on lamda expr returns
    """

    # Using undocumented generate_tokens due to a tokenize.tokenize bug
    # See https://bugs.python.org/issue23297
    arg_1 = io.StringIO(arg_0)
    arg_2 = tokenize.generate_tokens(arg_1.readline)

    arg_3 = []
    try:
        for arg_4 in arg_2:
            arg_3.append(arg_4)
    except tokenize.TokenError:
        pass

    # Find the position of 'lambda'
    arg_5 = [(arg_4.type, arg_4.string) for arg_4 in arg_3].index(
        (tokenize.NAME, "lambda")
    )

    # Ignore tokes before 'lambda'
    arg_3 = arg_3[arg_5:]

    # Find the position of th las OP
    arg_6 = (
        len(arg_3) - 1 - [arg_4.type for arg_4 in arg_3[::-1]].index(tokenize.OP)
    )
    arg_7 = arg_3[arg_6]

    # Remove OP from the line
    arg_8 = arg_7.start[0]
    arg_9 = arg_7.line[: arg_7.start[1]] + arg_7.line[arg_7.end[1] :]

    arg_3 = arg_3[:arg_6]

    arg_10 = ""
    arg_11 = 0
    for arg_4 in arg_3:
        if arg_11 == arg_4.start[0]:
            continue
        elif arg_4.start[0] == arg_8:
            arg_10 += arg_9
            arg_11 = arg_4.start[0]
        else:
            arg_10 += arg_4.line
            arg_11 = arg_4.start[0]

    return arg_10


def Func(arg_0):
    """Find the first FuncDef ast object in source"""

    try:
        arg_1 = compile(
            arg_0, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
        )
    except SyntaxError:
        return Func(fix_lamdaline(arg_0))

    for arg_2 in ast.walk(arg_1):
        if isinstance(arg_2, ast.FunctionDef) or isinstance(arg_2, ast.Lambda):
            return arg_2

    raise ValueError("function definition not found")


def Func(arg_0):
    """Extract parameters from a function definition"""

    arg_1 = find_funcdef(arg_0)
    arg_2 = []
    for arg_3 in ast.walk(arg_1.args):
        if isinstance(arg_3, ast.arg):
            if arg_3.arg not in arg_2:
                arg_2.append(arg_3.arg)

    return arg_2


def Func(arg_0):
    """Extract names from a function definition

    Looks for a function definition in the source.
    Only the first function definition is examined.

    Returns:
         a list names(identifiers) used in the body of the function
         excluding function parameters.
    """
    if arg_0 is None:
        return None

    arg_0 = dedent(arg_0)
    arg_1 = find_funcdef(arg_0)
    arg_2 = extract_params(arg_0)
    arg_3 = []

    if isinstance(arg_1, ast.FunctionDef):
        arg_4 = arg_1.body
    elif isinstance(arg_1, ast.Lambda):
        arg_4 = [arg_1.body]
    else:
        raise ValueError("must not happen")

    for arg_5 in arg_4:
        for arg_6 in ast.walk(arg_5):
            if isinstance(arg_6, ast.Name):
                if arg_6.id not in arg_3 and arg_6.id not in arg_2:
                    arg_3.append(arg_6.id)

    return arg_3


def Func(arg_0):
    """True if src is a function definition"""

    arg_1 = ast.parse(dedent(arg_0))

    if len(arg_1.body) == 1 and isinstance(
            arg_1.body[0], ast.FunctionDef
    ):
        return True
    else:
        return False


def Func(arg_0: arg_1):
    """Remove decorators from function definition"""
    arg_2 = arg_0.splitlines()
    arg_3 = asttokens.ASTTokens(arg_0, parse=True)

    for arg_4 in ast.walk(arg_3.tree):
        if isinstance(arg_4, ast.FunctionDef):
            break

    if arg_4.decorator_list:
        arg_5 = arg_4.decorator_list[0]
        arg_6 = arg_4.decorator_list[-1]
        arg_7 = arg_3.tokens[arg_5.first_token.index - 1].start[0]
        arg_8 = arg_3.tokens[arg_6.last_token.index + 1].start[0]

        arg_2 = arg_2[:arg_7 - 1] + arg_2[arg_8:]

    return "\n".join(arg_2) + "\n"


def Func(arg_0):
    """True if only one lambda expression is included"""

    arg_1 = ast.parse(dedent(arg_0))
    arg_2 = [node for node in ast.walk(arg_1)
                 if isinstance(node, ast.Lambda)]

    return bool(arg_2)


def Func(arg_0, arg_1=None):
        """Reload the source function from the source module.

        **Internal use only**
        Update the source function of the formula.
        This method is used to updated the underlying formula
        when the source code of the module in which the source function
        is read from is modified.

        If the formula was not created from a module, an error is raised.
        If ``module_`` is not given, the source module of the formula is
        reloaded. If ``module_`` is given and matches the source module,
        then the module_ is used without being reloaded.
        If ``module_`` is given and does not match the source module of
        the formula, an error is raised.

        Args:
            module_: A ``ModuleSource`` object

        Returns:
            self
        """
        if arg_0.module is None:
            raise RuntimeError
        elif arg_1 is None:
            import importlib

            arg_1 = ModuleSource(importlib.reload(arg_1))
        elif arg_1.name != arg_0.module:
            raise RuntimeError

        if arg_0.name in arg_1.funcs:
            arg_2 = arg_1.funcs[arg_0.name]
            arg_0.__init__(arg_2=arg_2)
        else:
            arg_0.__init__(arg_2=NULL_FORMULA)

        return arg_0


def Func():
    """Get long description from README."""
    with open(path.join(here, 'README.rst'), 'r') as f:
        arg_0 = f.read()
    return arg_0


def Func(arg_0, arg_1=None, arg_2=None):
        """Create a cells in the space.

        Args:
            name: If omitted, the model is named automatically ``CellsN``,
                where ``N`` is an available number.
            func: The function to define the formula of the cells.

        Returns:
            The new cells.
        """
        # Outside formulas only
        return arg_0._impl.Func(arg_1, arg_2).interface


def Func(arg_0, arg_1):
        """Create a cells from a module."""
        # Outside formulas only
        arg_2 = arg_0._impl.new_cells_from_module(arg_1)
        return get_interfaces(arg_2)


def Func(arg_0, arg_1):
        """Retrieve an object by a dotted name relative to the space."""

        arg_2 = arg_1.split(".")
        arg_3 = arg_2.pop(0)

        if arg_2:
            return arg_0.spaces[arg_3].Func(".".join(arg_2))
        else:
            return arg_0._namespace_impl[arg_3]


def Func(
        arg_0,
        arg_1=None,
        arg_2=None,
        arg_3=None,
        arg_4=None,
        arg_5=None,
        arg_6=None,
    ):
        """Create a new dynamic root space."""

        if arg_1 is None:
            arg_1 = arg_0.spacenamer.get_next(arg_0.namespace)

        if arg_1 in arg_0.namespace:
            raise ValueError("Name '%s' already exists." % arg_1)

        if not is_valid_name(arg_1):
            raise ValueError("Invalid name '%s'." % arg_1)

        arg_7 = RootDynamicSpaceImpl(
            parent=arg_0,
            arg_1=arg_1,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_6=arg_6,
            arg_5=arg_5,
        )
        arg_7.is_derived = False
        arg_0._set_space(arg_7)

        if arg_2:  # i.e. not []
            arg_9 = arg_0._get_dynamic_base(arg_2)
            arg_7._dynbase = arg_9
            arg_9._dynamic_subs.append(arg_7)

        return arg_7


def Func(arg_0, arg_1, arg_2=None):
        """Create a dynamic root space

        Called from interface methods
        """

        arg_3 = get_node(arg_0, *convert_args(arg_1, arg_2))
        arg_4 = arg_3[KEY]

        if arg_4 in arg_0.param_spaces:
            return arg_0.param_spaces[arg_4]

        else:
            arg_5 = arg_0.system.self
            arg_0.system.self = arg_0

            try:
                arg_7 = arg_0.eval_formula(arg_3)

            finally:
                arg_0.system.self = arg_5

            if arg_7 is None:
                arg_7 = {"bases": [arg_0]}  # Default
            else:
                if "bases" in arg_7:
                    arg_8 = get_impls(arg_7["bases"])
                    if isinstance(arg_8, StaticSpaceImpl):
                        arg_7["bases"] = [arg_8]
                    elif arg_8 is None:
                        arg_7["bases"] = [arg_0]  # Default
                    else:
                        arg_7["bases"] = arg_8
                else:
                    arg_7["bases"] = [arg_0]

            arg_7["arguments"] = node_get_args(arg_3)
            arg_9 = arg_0._new_dynspace(**arg_7)
            arg_0.param_spaces[arg_4] = arg_9
            arg_9.inherit(clear_value=False)
            return arg_9


def Func(arg_0, arg_1, arg_2):
        """Implementation of attribute setting

        ``space.name = value`` by user script
        Called from ``Space.__setattr__``
        """
        if not is_valid_name(arg_1):
            raise ValueError("Invalid name '%s'" % arg_1)

        if arg_1 in arg_0.namespace:
            if arg_1 in arg_0.refs:
                if arg_1 in arg_0.self_refs:
                    arg_0.new_ref(arg_1, arg_2)
                else:
                    raise KeyError("Ref '%s' cannot be changed" % arg_1)

            elif arg_1 in arg_0.cells:
                if arg_0.cells[arg_1].is_scalar():
                    arg_0.cells[arg_1].set_value((), arg_2)
                else:
                    raise AttributeError("Cells '%s' is not a scalar." % arg_1)
            else:
                raise ValueError
        else:
            arg_0.new_ref(arg_1, arg_2)


def Func(arg_0, arg_1):
        """Implementation of attribute deletion

        ``del space.name`` by user script
        Called from ``StaticSpace.__delattr__``
        """
        if arg_1 in arg_0.namespace:
            if arg_1 in arg_0.cells:
                arg_0.del_cells(arg_1)
            elif arg_1 in arg_0.spaces:
                arg_0.del_space(arg_1)
            elif arg_1 in arg_0.refs:
                arg_0.del_ref(arg_1)
            else:
                raise RuntimeError("Must not happen")
        else:
            raise KeyError("'%s' not found in Space '%s'" % (arg_1, arg_0.name))


def Func(arg_0, arg_1):
        """Implementation of cells deletion

        ``del space.name`` where name is a cells, or
        ``del space.cells['name']``
        """
        if arg_1 in arg_0.cells:
            arg_2 = arg_0.cells[arg_1]
            arg_0.cells.del_item(arg_1)
            arg_0.inherit()
            arg_0.model.spacegraph.update_subspaces(arg_0)

        elif arg_1 in arg_0.dynamic_spaces:
            arg_2 = arg_0.dynamic_spaces.pop(arg_1)
            arg_0.dynamic_spaces.set_update()

        else:
            raise KeyError("Cells '%s' does not exist" % arg_1)

        NullImpl(arg_2)


def Func(arg_0, arg_1, arg_2=True):
    """Convert multiple cells to a frame.

    If args is an empty sequence, all values are included.
    If args is specified, cellsiter must have shareable parameters.

    Args:
        cellsiter: A mapping from cells names to CellsImpl objects.
        args: A sequence of arguments
    """
    from modelx.core.cells import shareable_parameters

    if len(arg_1):
        arg_3 = shareable_parameters(arg_0)
    else:
        arg_3 = get_all_params(arg_0.values())

    arg_4 = None

    for arg_5 in arg_0.values():
        arg_6 = cells_to_dataframe(arg_5, arg_1)

        if arg_2 and arg_6.isnull().all().all():
            continue  #  Ignore all NA or empty

        if arg_6.index.names != [None]:
            if isinstance(arg_6.index, pd.MultiIndex):
                if _pd_ver < (0, 20):
                    arg_6 = _reset_naindex(arg_6)

            arg_6 = arg_6.reset_index()

        arg_7 = set(arg_3) - set(arg_6)

        for arg_8 in arg_7:
            arg_6[arg_8] = np.nan

        if arg_4 is None:
            arg_4 = arg_6
        else:
            try:
                arg_4 = pd.merge(arg_4, arg_6, how="outer")
            except MergeError:
                # When no common column exists, i.e. all cells are scalars.
                arg_4 = pd.concat([arg_4, arg_6], axis=1)
            except ValueError:
                # When common columns are not coercible (numeric vs object),
                # Make the numeric column object type
                arg_9 = set(arg_4.columns) & set(arg_6.columns)
                for arg_10 in arg_9:

                    # When only either of them has object dtype
                    if (
                        len(
                            [
                                str(arg_11[arg_10].dtype)
                                for arg_11 in (arg_4, arg_6)
                                if str(arg_11[arg_10].dtype) == "object"
                            ]
                        )
                        == 1
                    ):

                        if str(arg_4[arg_10].dtype) == "object":
                            arg_11 = arg_6
                        else:
                            arg_11 = arg_4
                        arg_11[[arg_10]] = arg_11[arg_10].astype("object")

                # Try again
                arg_4 = pd.merge(arg_4, arg_6, how="outer")

    if arg_4 is None:
        return pd.DataFrame()
    else:
        return arg_4.set_index(arg_3) if arg_3 else arg_4


def Func(arg_0, arg_1):
    """Convert a CellImpl into a Series.

    `args` must be a sequence of argkeys.

    `args` can be longer or shorter then the number of cell's parameters.
    If shorter, then defaults are filled if any, else raise error.
    If longer, then redundant args are ignored.
    """

    arg_2 = len(arg_0.formula.parameters)
    arg_3 = arg_2 > 1

    if len(arg_0.data) == 0:
        arg_4 = {}
        arg_5 = None

    elif arg_2 == 0:  # Const Cells
        arg_4 = list(arg_0.data.values())
        arg_5 = [np.nan]

    else:

        if len(arg_1) > 0:
            arg_6 = tuple(
                param.default
                for param in arg_0.formula.signature.parameters.values()
            )
            arg_7 = []
            for arg_8 in arg_1:

                if len(arg_8) > arg_2:
                    arg_8 = arg_8[:arg_2]
                elif len(arg_8) < arg_2:
                    arg_8 += arg_6[len(arg_8) :]

                arg_7.append(arg_8)

            arg_9 = [
                (arg_8, arg_0.data[arg_8])
                for arg_8 in arg_7
                if arg_8 in arg_0.data
            ]
        else:
            arg_9 = [(key, value) for key, value in arg_0.data.items()]

        if not arg_3:  # Peel 1-element tuple
            arg_9 = [(key[0], value) for key, value in arg_9]

        if len(arg_9) == 0:
            arg_5, arg_4 = None, {}
        else:
            arg_5, arg_4 = zip(*arg_9)
            if arg_3:
                arg_5 = pd.MultiIndex.from_tuples(arg_5)

    arg_10 = pd.Series(arg_4=arg_4, name=arg_0.name, arg_12=arg_5)

    if arg_5 is not None and any(arg_11 is not np.nan for arg_11 in arg_5):
        arg_10.index.names = list(arg_0.formula.parameters)

    return arg_10


def Func(arg_0, arg_1):
        """"Remove all nodes with `obj` and their descendants."""
        arg_2 = arg_0.get_nodes_with(arg_1)
        arg_3 = set()
        for arg_4 in arg_2:
            if arg_0.has_node(arg_4):
                arg_3.update(arg_0.clear_descendants(arg_4))
        return arg_3


def Func(arg_0, arg_1):
        """Return nodes with `obj`."""
        arg_2 = set()

        if nx.__version__[0] == "1":
            arg_3 = arg_0.nodes_iter()
        else:
            arg_3 = arg_0.nodes

        for arg_4 in arg_3:
            if arg_4[OBJ] == arg_1:
                arg_2.add(arg_4)
        return arg_2


def Func(arg_0, arg_1):
        """Rename self. Must be called only by its system."""
        if is_valid_name(arg_1):
            if arg_1 not in arg_0.system.models:
                arg_0.name = arg_1
                return True  # Rename success
            else:  # Model name already exists
                return False
        else:
            raise ValueError("Invalid name '%s'." % arg_1)


def Func(arg_0, arg_1):
        """Clear values and nodes of `obj` and their dependants."""
        arg_2 = arg_0.cellgraph.Func(arg_1)
        for arg_3 in arg_2:
            del arg_3[OBJ].data[arg_3[KEY]]


def Func(arg_0, arg_1: arg_2):
        """Create of get a base space for a tuple of bases"""

        try:
            return arg_0._dynamic_bases_inverse[arg_1]
        except KeyError:
            arg_3 = arg_0._dynamic_base_namer.get_next(arg_0._dynamic_bases)
            arg_4 = arg_0._new_space(arg_3=arg_3)
            arg_0.spacegraph.add_space(arg_4)
            arg_0._dynamic_bases[arg_3] = arg_4
            arg_0._dynamic_bases_inverse[arg_1] = arg_4
            arg_4.add_bases(arg_1)
            return arg_4


def Func(arg_0, arg_1):
        """Check if C3 MRO is possible with given bases"""

        try:
            arg_0.add_node("temp")
            for arg_2 in arg_1:
                nx.DiGraph.add_edge(arg_0, arg_2, "temp")
            arg_3 = arg_0.get_mro("temp")[1:]

        finally:
            arg_0.remove_node("temp")

        return arg_3


def Func(arg_0, **arg_1):
        '''
        Get all the boards for this organisation. Returns a list of Board s.

        Returns:
            list(Board): The boards attached to this organisation
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri, arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_board(arg_4))

        return arg_3


def Func(arg_0, **arg_1):
        '''
        Get all members attached to this organisation. Returns a list of
        Member objects

        Returns:
            list(Member): The members attached to this organisation
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri,
                                        arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_member(arg_4))

        return arg_3


def Func(arg_0, arg_1):
        '''
        Remove a member from the organisation.Returns JSON of all members if
        successful or raises an Unauthorised exception if not.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/members/%s' % arg_1,
            http_method='DELETE'
        )


def Func(arg_0, arg_1, arg_2='normal'):
        '''
        Add a member to the board using the id. Membership type can be
        normal or admin. Returns JSON of all members if successful or raises an
        Unauthorised exception if not.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/members/%s' % arg_1,
            http_method='PUT',
            query_params={
                'type': arg_2
            }
        )


def Func(arg_0, arg_1=None):
        '''
        Get information for this list. Returns a dictionary of values.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            arg_1=arg_1 or {}
        )


def Func():
    """
    Returns a list of command names supported
    """
    arg_0 = []
    for arg_1 in os.listdir(COMMAND_MODULE_PATH):
        if os.path.isfile(os.path.join(COMMAND_MODULE_PATH, arg_1)) and arg_1.endswith(COMMAND_MODULE_SUFFIX):
            arg_0.append(arg_1[:-len(COMMAND_MODULE_SUFFIX)])
    return arg_0


def Func(arg_0, arg_1, arg_2=None):
    """
    Returns a dictionary value
    """
    arg_3 = arg_0
    for arg_4 in arg_1.split('.'):
        if isinstance(arg_3, dict):
            arg_3 = arg_3.Func(arg_4, None)
            if arg_3 is None:
                return arg_2
        else:
            return arg_2
    return arg_3


def Func(arg_0, arg_1):
    """
    Parses an environment config
    """
    arg_2 = get(arg_0, 'app.all_environments', {})
    arg_3 = get(arg_0, 'app.environments.' + str(arg_1), {})
    return merge_dict(arg_2, arg_3)


def Func(arg_0, arg_1, arg_2={}):
    """
    Adds configuration files to an existing archive
    """
    with zipfile.ZipFile(arg_1, 'a') as zip_file:
        for arg_3 in arg_2:
            for arg_3, arg_4 in list(arg_3.items()):
                if 'yaml' in arg_4:
                    arg_5 = yaml.dump(arg_4['yaml'], default_flow_style=False)
                else:
                    arg_5 = arg_4.get('content', '')
                out("Adding file " + str(arg_3) + " to archive " + str(arg_1))
                arg_6 = zipfile.ZipInfo(arg_3)
                arg_6.external_attr = arg_4.get('permissions', 0o644) << 16
                zip_file.writestr(arg_6, arg_5)

    return arg_1


def Func(arg_0, arg_1, arg_2):
        """
        Swaps cnames for an environment
        """
        arg_0.ebs.Func(source_environment_name=arg_1,
                                         destination_environment_name=arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=True):
        """
        Uploads an application archive version to s3
        """
        try:
            arg_4 = arg_0.s3.get_bucket(arg_0.aws.bucket)
            if ((
                  arg_0.aws.region != 'us-east-1' and arg_0.aws.region != 'eu-west-1') and arg_4.get_location() != arg_0.aws.region) or (
                  arg_0.aws.region == 'us-east-1' and arg_4.get_location() != '') or (
                  arg_0.aws.region == 'eu-west-1' and arg_4.get_location() != 'eu-west-1'):
                raise Exception("Existing bucket doesn't match region")
        except S3ResponseError:
            arg_4 = arg_0.s3.create_bucket(arg_0.aws.bucket, location=arg_0.aws.region)

        def __report_upload_progress(arg_5, arg_6):
            if not arg_5:
                arg_5 = 0
            if not arg_6:
                arg_6 = 0
            out("Uploaded " + str(arg_5) + " bytes of " + str(arg_6) \
                + " (" + str(int(float(max(1, arg_5)) / float(arg_6) * 100)) + "%)")

        # upload the new version
        arg_7 = Key(arg_4)
        arg_7.key = arg_0.aws.bucket_path + arg_2
        arg_7.set_metadata('time', str(time()))
        arg_7.set_contents_from_filename(arg_1, cb=__report_upload_progress, num_cb=10)


def Func(arg_0):
        """
        Returns whether or not the given app_name exists
        """
        arg_1 = arg_0.ebs.describe_applications(application_names=[arg_0.app_name])
        return len(arg_1['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0


def Func(arg_0, arg_1, arg_2=None,
                           arg_3=None, arg_4=None, arg_5=None,
                           arg_6=None, arg_7='WebServer', arg_8='Standard', arg_9='1.1'):
        """
        Creates a new environment
        """
        out("Creating environment: " + str(arg_1) + ", tier_name:" + str(arg_7) + ", tier_type:" + str(arg_8))
        arg_0.ebs.Func(arg_0.app_name, arg_1,
                                    arg_2=arg_2,
                                    arg_3=arg_3,
                                    arg_4=arg_4,
                                    arg_5=arg_5,
                                    arg_6=arg_6,
                                    arg_8=arg_8,
                                    arg_7=arg_7,
                                    arg_9=arg_9)


def Func(arg_0, arg_1):
        """
        Returns whether or not the given environment exists
        """
        arg_2 = arg_0.ebs.describe_environments(application_name=arg_0.app_name, environment_names=[arg_1],
                                                  include_deleted=False)
        return len(arg_2['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']) > 0 \
               and arg_2['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0][
                       'Status'] != 'Terminated'


def Func(arg_0):
        """
        Returns the environments
        """
        arg_1 = arg_0.ebs.describe_environments(application_name=arg_0.app_name, include_deleted=False)
        return arg_1['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']


def Func(arg_0, arg_1, arg_2):
        """
        Creates an application version
        """
        out("Creating application version " + str(arg_1) + " for " + str(arg_2))
        arg_0.ebs.Func(arg_0.app_name, arg_1,
                                            s3_bucket=arg_0.aws.bucket, s3_key=arg_0.aws.bucket_path+arg_2)


def Func(arg_0, arg_1=10):
        """
        Deletes unused versions
        """

        # get versions in use
        arg_2 = arg_0.ebs.describe_environments(application_name=arg_0.app_name, include_deleted=False)
        arg_2 = arg_2['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_4['VersionLabel'])

        # get all versions
        arg_5 = arg_0.ebs.describe_application_versions(application_name=arg_0.app_name)
        arg_5 = arg_5['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult'][
            'ApplicationVersions']
        arg_5 = sorted(arg_5, reverse=True, key=functools.cmp_to_key(lambda x, y: (x['DateCreated'] > y['DateCreated']) - (x['DateCreated'] < y['DateCreated'])))

        # delete versions in use
        for arg_6 in arg_5[arg_1:]:
            if arg_6['VersionLabel'] in arg_3:
                out("Not deleting " + arg_6["VersionLabel"] + " because it is in use")
            else:
                out("Deleting unused version: " + arg_6["VersionLabel"])
                arg_0.ebs.delete_application_version(application_name=arg_0.app_name,
                                                    version_label=arg_6['VersionLabel'])
                sleep(2)


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """
        Describes events from the given environment
        """
        arg_4 = arg_0.ebs.Func(
            application_name=arg_0.app_name,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3 + 'Z')

        return (arg_4['DescribeEventsResponse']['DescribeEventsResult']['Events'], arg_4['DescribeEventsResponse']['DescribeEventsResult']['NextToken'])


def Func(arg_0, arg_1=None):
        '''
        Get all information for this Label. Returns a dictionary of values.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            arg_1=arg_1 or {}
        )


def Func(arg_0, arg_1={}):
        '''
        Update the current label. Returns a new Label object.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            http_method='PUT',
            arg_1=arg_1
        )

        return arg_0.create_label(arg_2)


def Func(arg_0, arg_1, arg_2='1day'):
        '''
        Returns a URL that needs to be opened in a browser to retrieve an
        access token.
        '''
        arg_3 = {
            'name': arg_1,
            'expiration': arg_2,
            'response_type': 'token',
            'scope': 'read,write'
        }

        arg_4 = arg_0.build_uri(
            path='/authorize',
            arg_3=arg_0.add_authorisation(arg_3)
        )

        print('Please go to the following URL and get the user authorisation '
              'token:\n', arg_4)
        return arg_4


def Func(arg_0):
    """
    adds arguments for the swap urls command
    """
    arg_0.add_argument('-o', '--old-environment', help='Old environment name', required=True)
    arg_0.add_argument('-n', '--new-environment', help='New environment name', required=True)


def Func(arg_0, arg_1, arg_2):
    """
    Swaps old and new URLs.
    If old_environment was active, new_environment will become the active environment
    """
    arg_3 = arg_2.old_environment
    arg_4 = arg_2.new_environment

    # swap C-Names
    out("Assuming that {} is the currently active environment...".format(arg_3))
    out("Swapping environment cnames: {} will become active, {} will become inactive.".format(arg_4,
                                                                                arg_3))
    arg_0.swap_environment_cnames(arg_3, arg_4)
    arg_0.wait_for_environments([arg_3, arg_4], status='Ready', include_deleted=False)


def Func(arg_0, arg_1=None):
        '''
        Get information for this card. Returns a dictionary of values.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            arg_1=arg_1 or {}
        )


def Func(arg_0, **arg_1):
        '''
        Get board information for this card. Returns a Board object.

        Returns:
            Board: The board this card is attached to
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri,
                                         arg_1=arg_1)
        return arg_0.create_board(arg_2)


def Func(arg_0, **arg_1):
        '''
        Get the checklists for this card. Returns a list of Checklist objects.

        Returns:
            list(Checklist): The checklists attached to this card
        '''
        arg_2 = arg_0.get_checklist_json(arg_0.base_uri,
                                             arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_checklist(arg_4))

        return arg_3


def Func(arg_0, arg_1):
        '''
        Adds a comment to this card by the current user.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/actions/comments',
            http_method='POST',
            query_params={'text': arg_1}
        )


def Func(arg_0, arg_1, arg_2):
        '''
        Adds an attachment to this card.
        '''
        arg_3 = {
            'api_key': arg_0.client.api_key,
            'token': arg_0.client.user_auth_token
        }

        arg_4, arg_5 = arg_0.encode_multipart_formdata(
            arg_3=arg_3,
            arg_1=arg_1,
            file_values=arg_2
        )

        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/attachments',
            http_method='POST',
            arg_5=arg_5,
            headers={'Content-Type': arg_4},
        )


def Func(arg_0, arg_1=None):
        '''
        Add a checklist to this card. Returns a Checklist object.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/checklists',
            http_method='POST',
            arg_1=arg_1 or {}
        )

        return arg_0.create_checklist(arg_2)


def Func(arg_0, arg_1=None):
        '''
        Add a label to this card, from a dictionary.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/labels',
            http_method='POST',
            arg_1=arg_1 or {}
        )


def Func(arg_0, arg_1=None):
        '''
        Add an existing label to this card.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/idLabels',
            http_method='POST',
            query_params={'value': arg_1.id}
        )


def Func(arg_0, arg_1):
        '''
        Add a member to this card. Returns a list of Member objects.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/idMembers',
            http_method='POST',
            query_params={'value': arg_1}
        )

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_member(arg_4))

        return arg_3


def Func(arg_0, **arg_1):
        '''
        Get all cards this member is attached to. Return a list of Card
        objects.

        Returns:
            list(Card): Return all cards this member is attached to
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri, arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_card(arg_4))

        return arg_3


def Func(arg_0, **arg_1):
        '''
        Get all organisations this member is attached to. Return a list of
        Organisation objects.

        Returns:
            list(Organisation): Return all organisations this member is
            attached to
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri,
                                                    arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(
                arg_0.create_organisation(arg_4))

        return arg_3


def Func(arg_0, arg_1=None):
        '''
        Create a new board. name is required in query_params. Returns a Board
        object.

        Returns:
            Board: Returns the created board
        '''
        arg_2 = arg_0.fetch_json(
            uri_path='/boards',
            http_method='POST',
            arg_1=arg_1 or {}
        )
        return arg_0.create_board(arg_2)


def Func(arg_0):
    '''
    Enable singledispatch for class methods.

    See http://stackoverflow.com/a/24602374/274318
    '''
    arg_1 = singledispatch(arg_0)
    def arg_4(*arg_2, **arg_3):
        return arg_1.dispatch(arg_2[1].__class__)(*arg_2, **arg_3)
    arg_4.register = arg_1.register
    update_wrapper(arg_4, arg_1)
    return arg_4


def Func(arg_0, arg_1, arg_2):
    """
    The init command
    """

    # check to see if the application exists
    if not arg_0.application_exists():
        arg_0.create_application(get(arg_1, 'app.description'))
    else:
        out("Application "+get(arg_1, 'app.app_name')+" exists")

    # create environments
    arg_3 = []
    arg_4 = []
    for arg_5, arg_6 in list(get(arg_1, 'app.environments').items()):
        arg_3.append(arg_5)
        arg_6 = parse_env_config(arg_1, arg_5)
        if not arg_0.environment_exists(arg_5):
            arg_7 = parse_option_settings(arg_6.get('option_settings', {}))
            arg_0.create_environment(arg_5,
                solution_stack_name=arg_6.get('solution_stack_name'),
                cname_prefix=arg_6.get('cname_prefix', None),
                description=arg_6.get('description', None),
                arg_7=arg_7,
                tier_name=arg_6.get('tier_name'),
                tier_type=arg_6.get('tier_type'),
                tier_version=arg_6.get('tier_version'),
                version_label=arg_2.version_label)
            arg_4.append(arg_5)
        else:
            out("Environment "+arg_5)

    # get the environments
    arg_8 = []
    if arg_2.delete:
        arg_9 = arg_0.get_environments()
        for arg_10 in arg_9:
            if arg_10['EnvironmentName'] not in arg_3:
                if arg_10['Status'] != 'Ready':
                    out("Unable to delete "+arg_10['EnvironmentName']+" because it's not in status Ready ("+arg_10['Status']+")")
                else:
                    out("Deleting environment: "+arg_10['EnvironmentName'])
                    arg_0.delete_environment(arg_10['EnvironmentName'])
                    arg_8.append(arg_10['EnvironmentName'])

    # wait
    if not arg_2.dont_wait and len(arg_4)>0:
        arg_0.wait_for_environments(arg_4, status='Ready', include_deleted=False)
    if not arg_2.dont_wait and len(arg_8)>0:
        arg_0.wait_for_environments(arg_8, status='Terminated', include_deleted=False)

    out("Application initialized")
    return 0


def Func(arg_0, arg_1=None):
        '''
        Get all information for this board. Returns a dictionary of values.
        '''
        return arg_0.fetch_json(
            uri_path='/boards/' + arg_0.id,
            arg_1=arg_1 or {}
        )


def Func(arg_0, **arg_1):
        '''
        Get the lists attached to this board. Returns a list of List objects.

        Returns:
            list(List): The lists attached to this board
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri, arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_list(arg_4))

        return arg_3


def Func(arg_0, **arg_1):
        '''
        Get the labels attached to this board. Returns a label of Label
        objects.

        Returns:
            list(Label): The labels attached to this board
        '''
        arg_2 = arg_0.Func_json(arg_0.base_uri, arg_1=arg_1)

        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_0.create_label(arg_4))

        return arg_3


def Func(arg_0, arg_1, **arg_2):
        '''
        Get a Card for a given card id. Returns a Card object.

        Returns:
            Card: The card with the given card_id
        '''
        arg_3 = arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/cards/' + arg_1
        )

        return arg_0.create_card(arg_3)


def Func( arg_0 ):
        """
        Get the checklists for this board. Returns a list of Checklist objects.
        """
        arg_1 = arg_0.getChecklistsJson( arg_0.base_uri )

        arg_2 = []
        for arg_3 in arg_1:
            arg_2.append( arg_0.createChecklist( arg_3 ) )

        return arg_2


def Func(arg_0, **arg_1):
        '''
        Get the Organisation for this board. Returns Organisation object.

        Returns:
            list(Organisation): The organisation attached to this board
        '''
        arg_2 = arg_0.Funcs_json(
            arg_0.base_uri, arg_1=arg_1)

        return arg_0.create_organisation(arg_2)


def Func(arg_0, arg_1=None):
        '''
        Update this board's information. Returns a new board.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            http_method='PUT',
            arg_1=arg_1 or {}
        )

        return arg_0.create_board(arg_2)


def Func(arg_0, arg_1=None):
        '''
        Create a label for a board. Returns a new Label object.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/labels',
            http_method='POST',
            arg_1=arg_1 or {}
        )

        return arg_0.create_label(arg_2)


def Func(arg_0, arg_1, arg_2):
    """
    Waits for an environment to be healthy
    """
    arg_0.wait_for_environments(arg_2.environment, health=arg_2.health)


def Func(arg_0, arg_1=None):
        '''
        Get all information for this Checklist. Returns a dictionary of values.
        '''
        # We don't use trelloobject.TrelloObject.get_checklist_json, because
        # that is meant to return lists of checklists.
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            arg_1=arg_1 or {}
        )


def Func(arg_0):
        '''
        Get card this checklist is on.
        '''
        arg_1 = arg_0.get_checklist_information().get('idCard', None)
        if arg_1:
            return arg_0.client.Func(arg_1)


def Func(arg_0, arg_1):
        '''
        Update the current checklist. Returns a new Checklist object.
        '''
        arg_2 = arg_0.fetch_json(
            uri_path=arg_0.base_uri,
            http_method='PUT',
            query_params={'name': arg_1}
        )

        return arg_0.create_checklist(arg_2)


def Func(arg_0, arg_1):
        '''
        Deletes an item from this checklist.
        '''
        return arg_0.fetch_json(
            uri_path=arg_0.base_uri + '/checkItems/' + arg_1,
            http_method='DELETE'
        )


def Func( arg_0, arg_1 ):
        """
        Rename the current checklist item. Returns a new ChecklistItem object.
        """
        arg_2 = arg_0.fetch_json(
            uri_path = arg_0.base_uri + '/name',
            http_method = 'PUT',
            query_params = {'value': arg_1}
        )

        return arg_0.create_checklist_item(arg_0.idCard, arg_0.idChecklist, arg_2)


def Func(arg_0, arg_1):
        """
        Set the state of the current checklist item. Returns a new ChecklistItem object.
        """
        arg_2 = arg_0.fetch_json(
            uri_path = arg_0.base_uri + '/state',
            http_method = 'PUT',
            query_params = {'value': 'complete' if arg_1 else 'incomplete'}
        )

        return arg_0.create_checklist_item(arg_0.idCard, arg_0.idChecklist, arg_2)


def Func(arg_0):
    """
    Args for the init command
    """
    arg_0.add_argument('-e', '--environment',  help='Environment name', required=False, nargs='+')
    arg_0.add_argument('-w', '--dont-wait', help='Skip waiting for the app to be deleted', action='store_true')


def Func(arg_0, arg_1):
        '''
        Create Board object from a JSON object

        Returns:
            Board: The board from the given `board_json`.
        '''
        return trolly.board.Board(
            trello_client=arg_0,
            board_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func(arg_0, arg_1):
        '''
        Create List object from JSON object

        Returns:
            List: The list from the given `list_json`.
        '''
        return trolly.list.List(
            trello_client=arg_0,
            list_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func(arg_0, arg_1):
        '''
        Create a Card object from JSON object

        Returns:
            Card: The card from the given `card_json`.
        '''
        return trolly.card.Card(
            trello_client=arg_0,
            card_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func(arg_0, arg_1):
        '''
        Create a Checklist object from JSON object

        Returns:
            Checklist: The checklist from the given `checklist_json`.
        '''
        return trolly.checklist.Checklist(
            trello_client=arg_0,
            checklist_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func(arg_0, arg_1):
        '''
        Create a Member object from JSON object

        Returns:
            Member: The member from the given `member_json`.
        '''
        return trolly.member.Member(
            trello_client=arg_0,
            member_id=arg_1['id'],
            name=arg_1['fullName'],
            data=arg_1,
        )


def Func(arg_0, arg_1, arg_2=None):
        '''
        Get an organisation

        Returns:
            Organisation: The organisation with the given `id`
        '''
        return arg_0.create_organisation(dict(arg_1=arg_1, arg_2=arg_2))


def Func(arg_0, arg_1, arg_2=None):
        '''
        Get a checklist

        Returns:
            Checklist: The checklist with the given `id`
        '''
        return arg_0.create_checklist(dict(arg_1=arg_1, arg_2=arg_2))


def Func(arg_0, arg_1='me', arg_2=None):
        '''
        Get a member or your current member if `id` wasn't given.

        Returns:
            Member: The member with the given `id`, defaults to the
            logged in member.
        '''
        return arg_0.create_member(dict(arg_1=arg_1, fullName=arg_2))


def Func(arg_0, arg_1, arg_2):
    """
    Lists solution stacks
    """
    out("Available solution stacks")
    for arg_3 in arg_0.list_available_solution_stacks():
        out("    "+str(arg_3))
    return 0


def Func(arg_0):
    """Picks only a coda from a Hangul letter.  It returns ``None`` if the
    given letter is not Hangul.
    """
    try:
        arg_1, arg_1, arg_2 = \
            split_phonemes(arg_0, onset=False, nucleus=False, arg_2=True)
    except ValueError:
        return None
    else:
        return arg_2


def Func(arg_0):
    """
    Get root domain from url.
    Will prune away query strings, url paths, protocol prefix and sub-domains
    Exceptions will be raised on invalid urls
    """
    arg_1 = tldextract.extract(arg_0)
    if not arg_1.suffix:
        raise InvalidURLException()
    arg_2 = arg_1.domain + "." + arg_1.suffix
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """Write the password in the file.
        """
        arg_4 = arg_0._generate_assoc(arg_1, arg_2)
        # encrypt the password
        arg_5 = arg_0.encrypt(arg_3.encode('utf-8'), arg_4)
        # encode with base64 and add line break to untangle config file
        arg_6 = '\n' + encodebytes(arg_5).decode()

        arg_0._write_config_value(arg_1, arg_2, arg_6)


def Func(arg_0, arg_1):
    """
    Use an integer list to split the string
    contained in `text`.

    Arguments:
    ----------
        text : str, same length as locations.
        locations : list<int>, contains values
            'SHOULD_SPLIT', 'UNDECIDED', and
            'SHOULD_NOT_SPLIT'. Will create
            strings between each 'SHOULD_SPLIT'
            locations.
    Returns:
    --------
        Generator<str> : the substrings of text
            corresponding to the slices given
            in locations.
    """
    arg_2 = 0
    for arg_3, arg_4 in enumerate(arg_1):
        if arg_4 == SHOULD_SPLIT:
            if arg_2 != arg_3:
                yield arg_0[arg_2:arg_3]
            arg_2 = arg_3
    if arg_2 != len(arg_0):
        yield arg_0[arg_2:]