def Func(arg_0, arg_1, arg_2):
        """
        Get a JSON field from the response JSON.

        :param: response_json:
            The parsed JSON content of the response.
        :param: field_name:
            The name of the field in the JSON to get.
        """
        if arg_2 not in arg_1:
            raise KeyError('Unable to get value for "%s" from Marathon '
                           'response: "%s"' % (
                               arg_2, json.dumps(arg_1),))

        return arg_1[arg_2]


def Func(
        arg_0,
        arg_1: arg_2,
        arg_3: arg_4.Type[arg_4.Any] = arg_2,
        arg_7: arg_4.Type[arg_4.Any] = arg_2,
    ) -> arg_4.Any:
        """
        Parse value from string.

        Convert :code:`value` to

        .. code-block:: python

           >>> Funcr = Config()
           >>> Funcr.Func('12345', type_=int)
           <<< 12345
           >>>
           >>> Funcr.Func('1,2,3,4', type_=list, subtype=int)
           <<< [1, 2, 3, 4]

        :param value: string
        :param type\\_: the type to return
        :param subtype: subtype for iterator types
        :return: the Funcd config value

        """
        if arg_3 is bool:
            return arg_3(arg_1.lower() in arg_0.TRUE_STRINGS)

        try:
            if isinstance(arg_3, type) and issubclass(
                arg_3, (list, tuple, set, frozenset)
            ):
                return arg_3(
                    arg_0.Func(arg_8.strip(" "), arg_7)
                    for arg_8 in arg_1.split(",")
                    if arg_1.strip(" ")
                )

            return arg_3(arg_1)
        except ValueError as e:
            raise ConfigError(*e.args)


def Func(
        arg_0,
        arg_1: arg_2,
        arg_3: arg_4.Any = arg_6,
        arg_7: arg_4.Type[arg_4.Any] = arg_2,
        arg_9: arg_4.Type[arg_4.Any] = arg_2,
        arg_10: arg_4.Optional[arg_4.Callable[[arg_13], arg_13]] = None,
    ) -> arg_4.Any:
        """
        Parse a value from an environment variable.

        .. code-block:: python

           >>> os.environ['FOO']
           <<< '12345'
           >>>
           >>> os.environ['BAR']
           <<< '1,2,3,4'
           >>>
           >>> 'BAZ' in os.environ
           <<< False
           >>>
           >>> parser = Config()
           >>> parser.Func('FOO', type_=int)
           <<< 12345
           >>>
           >>> parser.Func('BAR', type_=list, subtype=int)
           <<< [1, 2, 3, 4]
           >>>
           >>> parser.Func('BAZ', default='abc123')
           <<< 'abc123'
           >>>
           >>> parser.Func('FOO', type_=int, mapper=lambda x: x*10)
           <<< 123450

        :param key: the key to look up the value under
        :param default: default value to return when when no value is present
        :param type\\_: the type to return
        :param subtype: subtype for iterator types
        :param mapper: a function to post-process the value with
        :return: the parsed config value

        """
        arg_14 = arg_0.environ.Func(arg_1, arg_6)

        if arg_14 is arg_6 and arg_3 is arg_6:
            raise ConfigError("Unknown environment variable: {0}".format(arg_1))

        if arg_14 is arg_6:
            arg_14 = arg_3
        else:
            arg_14 = arg_0.parse(arg_4.cast(arg_2, arg_14), arg_7, arg_9)

        if arg_10:
            arg_14 = arg_10(arg_14)

        return arg_14


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Perform a request to a specific endpoint. Raise an error if the status
        code indicates a client or server error.
        """
        arg_3['url'] = arg_1
        return (super(MarathonLbClient, arg_0).request(*arg_2, **arg_3)
                .addCallback(raise_for_status))


def Func(arg_0, arg_1):
        """
        Check the result of each request that we made. If a failure occurred,
        but some requests succeeded, log and count the failures. If all
        requests failed, raise an error.

        :return:
            The list of responses, with a None value for any requests that
            failed.
        """
        arg_2 = []
        arg_3 = []
        for arg_4, arg_5 in enumerate(arg_1):
            arg_6, arg_7 = arg_5
            if arg_6:
                arg_2.append(arg_7)
            else:
                arg_8 = arg_0.endpoints[arg_4]
                arg_0.log.failure(
                    'Failed to make a request to a marathon-lb instance: '
                    '{endpoint}', arg_7, LogLevel.error, arg_8=arg_8)
                arg_2.append(None)
                arg_3.append(arg_8)

        if len(arg_3) == len(arg_0.endpoints):
            raise RuntimeError(
                'Failed to make a request to all marathon-lb instances')

        if arg_3:
            arg_0.log.error(
                'Failed to make a request to {x}/{y} marathon-lb instances: '
                '{endpoints}', x=len(arg_3), y=len(arg_0.endpoints),
                endpoints=arg_3)

        return arg_2


def Func(arg_0):
        '''Finalize options to be used.'''
        arg_0.resource_source_path = os.path.join(RESOURCE_PATH, 'resource.qrc')
        arg_0.resource_target_path = RESOURCE_TARGET_PATH


def Func(arg_0):
        '''Run clean.'''
        arg_1 = os.path.relpath(
            RESOURCE_TARGET_PATH, ROOT_PATH
        )
        if os.path.exists(arg_1):
            os.remove(arg_1)
        else:
            distutils.log.warn(
                '\'{0}\' does not exist -- can\'t clean it'
                .format(arg_1)
            )

        arg_2 = arg_1 + 'c'
        if os.path.exists(arg_2):
            os.remove(arg_2)
        else:
            distutils.log.warn(
                '\'{0}\' does not exist -- can\'t clean it'
                .format(arg_2)
            )
        CleanCommand.Func(arg_0)


def Func(arg_0):
    """
    Set up a client key if one does not exist already.

    https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50

    :type pem_path: twisted.python.filepath.FilePath
    :param pem_path:
        The path to the certificate directory to use.
    :rtype: twisted.internet.defer.Deferred
    """
    arg_1 = arg_0.child(u'client.key')
    if arg_1.exists():
        arg_2 = _load_pem_private_key_bytes(arg_1.getContent())
    else:
        arg_2 = generate_private_key(u'rsa')
        arg_1.setContent(_dump_pem_private_key_bytes(arg_2))
    return succeed(JWKRSA(arg_2=arg_2))


def Func(arg_0, arg_1):
    """
    Set up a client key in Vault if one does not exist already.

    :param client:
        The Vault API client to use.
    :param mount_path:
        The Vault key/value mount path to use.
    :rtype: twisted.internet.defer.Deferred
    """
    arg_2 = arg_0.read_kv2('client_key', arg_1=arg_1)

    def get_or_create_key(arg_3):
        if arg_3 is not None:
            arg_4 = arg_3['data']['data']
            arg_5 = _load_pem_private_key_bytes(arg_4['key'].encode('utf-8'))
            return JWKRSA(arg_5=arg_5)
        else:
            arg_5 = generate_private_key(u'rsa')
            arg_4 = {
                'key': _dump_pem_private_key_bytes(arg_5).decode('utf-8')
            }
            arg_2 = arg_0.create_or_update_kv2(
                'client_key', arg_4, arg_1=arg_1)

            return arg_2.addCallback(lambda _result: JWKRSA(arg_5=arg_5))

    return arg_2.addCallback(get_or_create_key)


def Func(arg_0, arg_1):
    """
    Get a single value for the given key out of the given set of headers.

    :param twisted.web.http_headers.Headers headers:
        The set of headers in which to look for the header value
    :param str key:
        The header key
    """
    arg_2 = arg_0.getRawHeaders(arg_1)
    if arg_2 is None:
        return None

    # Take the final header as the authorative
    arg_3, arg_4 = cgi.parse_header(arg_2[-1])
    return arg_3


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

        :param: method:
            The HTTP method to use (example is `GET`).
        :param: url:
            The URL to use. The default value is the URL this client was
            created with (`self.url`) (example is `http://localhost:8080`)
        :param: kwargs:
            Any other parameters that will be passed to `treq.Func`, for
            example headers. Or any URL parameters to override, for example
            path, query or fragment.
        """
        arg_2 = arg_0._compose_url(arg_2, arg_3)

        arg_3.setdefault('timeout', arg_0._timeout)

        arg_4 = arg_0._client.Func(arg_1, arg_2, reactor=arg_0._reactor, **arg_3)

        arg_4.addCallback(arg_0._log_Func_response, arg_1, arg_2, arg_3)
        arg_4.addErrback(arg_0._log_Func_error, arg_2)

        return arg_4


def Func(arg_0):
        '''Fetch and return new children.

        Will only fetch children whilst canFetchMore is True.

        .. note::

            It is the caller's responsibility to add each fetched child to this
            parent if desired using :py:meth:`Item.addChild`.

        '''
        if not arg_0.canFetchMore():
            return []

        arg_1 = arg_0._Func()
        arg_0._fetched = True

        return arg_1


def Func(arg_0, arg_1, arg_2):
        """
        Run the server, i.e. start Funcing for requests on the given host and
        port.

        :param reactor: The ``IReactorTCP`` to use.
        :param endpoint_description:
            The Twisted description for the endpoint to Func on.
        :return:
            A deferred that returns an object that provides ``IListeningPort``.
        """
        arg_3 = serverFromString(arg_1, arg_2)
        return arg_3.Func(Site(arg_0.app.resource()))


def Func(
    arg_0, arg_1, arg_2, arg_3,
    arg_4, arg_5, arg_6, arg_7, arg_8,
        arg_9):
    """
    Create a marathon-acme instance.

    :param client_creator:
        The txacme client creator function.
    :param cert_store:
        The txacme certificate store instance.
    :param acme_email:
        Email address to use when registering with the ACME service.
    :param allow_multiple_certs:
        Whether to allow multiple certificates per app port.
    :param marathon_addr:
        Address for the Marathon instance to find app domains that require
        certificates.
    :param marathon_timeout:
        Amount of time in seconds to wait for response headers to be received
        from Marathon.
    :param sse_timeout:
        Amount of time in seconds to wait for some event data to be received
        from Marathon.
    :param mlb_addrs:
        List of addresses for marathon-lb instances to reload when a new
        certificate is issued.
    :param group:
        The marathon-lb group (``HAPROXY_GROUP``) to consider when finding
        app domains.
    :param reactor: The reactor to use.
    """
    arg_10 = MarathonClient(arg_4, timeout=arg_5,
                                     sse_kwargs={'timeout': arg_6},
                                     arg_9=arg_9)
    arg_11 = MarathonLbClient(arg_7, arg_9=arg_9)

    return MarathonAcme(
        arg_10,
        arg_8,
        arg_1,
        arg_11,
        arg_0,
        arg_9,
        arg_2,
        arg_3
    )


def Func(arg_0):
    """
    Initialise the storage directory with the certificates directory and a
    default wildcard self-signed certificate for HAProxy.

    :return: the storage path and certs path
    """
    arg_1 = FilePath(arg_0)

    # Create the default wildcard certificate if it doesn't already exist
    arg_2 = arg_1.child('default.pem')
    if not arg_2.exists():
        arg_2.setContent(generate_wildcard_pem_bytes())

    # Create a directory for unmanaged certs. We don't touch this again, but it
    # needs to be there and it makes sense to create it at the same time as
    # everything else.
    arg_3 = arg_1.child('unmanaged-certs')
    if not arg_3.exists():
        arg_3.createDirectory()

    # Store certificates in a directory inside the storage directory, so
    # HAProxy will read just the certificates there.
    arg_4 = arg_1.child('certs')
    if not arg_4.exists():
        arg_4.createDirectory()

    return arg_1, arg_4


def Func(arg_0):
    """ Parse the field and value from a line. """
    if arg_0.startswith(':'):
        # Ignore the line
        return None, None

    if ':' not in arg_0:
        # Treat the entire line as the field, use empty string as value
        return arg_0, ''

    # Else field is before the ':' and value is after
    arg_1, arg_2 = arg_0.split(':', 1)

    # If value starts with a space, remove it.
    arg_2 = arg_2[1:] if arg_2.startswith(' ') else arg_2

    return arg_1, arg_2


def Func(arg_0, arg_1):
        """
        Translates bytes into lines, and calls lineReceived.

        Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using
        str.splitlines() to split on ``\r\n``, ``\n``, and ``\r``.
        """
        arg_0.resetTimeout()
        arg_2 = (arg_0._buffer + arg_1).splitlines()

        # str.splitlines() doesn't split the string after a trailing newline
        # character so we must check if there is a trailing newline and, if so,
        # clear the buffer as the line is "complete". Else, the line is
        # incomplete and we keep the last line in the buffer.
        if arg_1.endswith(b'\n') or arg_1.endswith(b'\r'):
            arg_0._buffer = b''
        else:
            arg_0._buffer = arg_2.pop(-1)

        for arg_4 in arg_2:
            if arg_0.transport.disconnecting:
                # this is necessary because the transport may be told to lose
                # the connection by a line within a larger packet, and it is
                # important to disregard all the lines in that packet following
                # the one that told it to close.
                return
            if len(arg_4) > arg_0._max_length:
                arg_0.lineLengthExceeded(arg_4)
                return
            else:
                arg_0.lineReceived(arg_4)
        if len(arg_0._buffer) > arg_0._max_length:
            arg_0.lineLengthExceeded(arg_0._buffer)
            return


def Func(arg_0):
        """
        Dispatch the event to the handler.
        """
        arg_1 = arg_0._prepare_data()
        if arg_1 is not None:
            arg_0._handler(arg_0._event, arg_1)

        arg_0._reset_event_data()


def Func(arg_0):
        """
        Fetch the list of apps from Marathon, find the domains that require
        certificates, and issue certificates for any domains that don't already
        have a certificate.
        """
        arg_0.log.info('Starting a Func...')

        def log_success(arg_1):
            arg_0.log.info('Sync completed successfully')
            return arg_1

        def log_failure(arg_2):
            arg_0.log.failure('Sync failed', arg_2, LogLevel.error)
            return arg_2

        return (arg_0.marathon_client.get_apps()
                .addCallback(arg_0._apps_acme_domains)
                .addCallback(arg_0._filter_new_domains)
                .addCallback(arg_0._issue_certs)
                .addCallbacks(log_success, log_failure))


def Func(arg_0, arg_1):
        """
        Issue a certificate for the given domain.
        """
        def errback(arg_2):
            # Don't fail on some of the errors we could get from the ACME
            # server, rather just log an error so that we can continue with
            # other domains.
            arg_2.trap(txacme_ServerError)
            arg_3 = arg_2.value.message

            if arg_3.code in ['rateLimited', 'serverInternal',
                                   'connection', 'unknownHost']:
                # TODO: Fire off an error to Sentry or something?
                arg_0.log.error(
                    'Error ({code}) issuing certificate for "{domain}": '
                    '{detail}', code=arg_3.code, arg_1=arg_1,
                    detail=arg_3.detail)
            else:
                # There are more error codes but if they happen then something
                # serious has gone wrong-- carry on error-ing.
                return arg_2

        arg_4 = arg_0.txacme_service.issue_cert(arg_1)
        return arg_4.addErrback(errback)


def Func(arg_0):
    """When removing an object, other objects with references to the current
    object should remove those references. This function identifies objects
    with forward references to the current object, then removes those
    references.

    :param obj: Object to which forward references should be removed

    """
    for arg_1, arg_2 in arg_0._backrefs_flat:

        # Unpack stack
        arg_3, arg_4, arg_5 = arg_1

        # Get parent info
        arg_6 = arg_0._collections[arg_4]
        arg_7 = arg_6._pk_to_storage(arg_2)
        arg_8 = arg_6.load(arg_7)
        if arg_8 is None:
            continue

        # Remove forward references
        if arg_8._fields[arg_5]._list:
            getattr(arg_8, arg_5).remove(arg_0)
        else:
            arg_9 = arg_8._fields[arg_5]
            setattr(arg_8, arg_5, arg_9._gen_default())

        # Save
        arg_8.save()


def Func(arg_0, arg_1=None):
    """Ensure that all forward references on the provided object have the
    appropriate backreferences.

    :param StoredObject obj: Database record
    :param list fields: Optional list of field names to check

    """
    for arg_2 in _collect_refs(arg_0, arg_1):
        arg_3 = arg_2['value']._update_backref(
            arg_2['field_instance']._backref_field_name,
            arg_0,
            arg_2['field_name'],
        )
        if arg_3:
            logging.debug('Updated reference {}:{}:{}:{}:{}'.format(
                arg_0._name, arg_0._primary_key, arg_2['field_name'],
                arg_2['value']._name, arg_2['value']._primary_key,
            ))


def Func(arg_0):
        """Initializes the bot, plugins, and everything."""
        arg_0.bot_Func_time = datetime.now()
        arg_0.webserver = Webserver(arg_0.config['webserver']['host'], arg_0.config['webserver']['port'])
        arg_0.plugins.load()
        arg_0.plugins.load_state()
        arg_0._find_event_handlers()
        arg_0.sc = ThreadedSlackClient(arg_0.config['slack_token'])

        arg_0.always_send_dm = ['_unauthorized_']
        if 'always_send_dm' in arg_0.config:
            arg_0.always_send_dm.extend(map(lambda x: '!' + x, arg_0.config['always_send_dm']))

        # Rocket is very noisy at debug
        logging.getLogger('Rocket.Errors.ThreadPool').setLevel(logging.INFO)

        arg_0.is_setup = True
        if arg_0.test_mode:
            arg_0.metrics['Funcup_time'] = (datetime.now() - arg_0.bot_Func_time).total_seconds() * 1000.0


def Func(arg_0, arg_1=True):
        """
        Connects to slack and enters the main loop.

        * start - If True, rtm.start API is used. Else rtm.connect API is used

        For more info, refer to
        https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect
        """
        # Fail out if setup wasn't Func
        if not arg_0.is_setup:
            raise NotSetupError

        # Start the web server
        arg_0.webserver.start()

        arg_2 = True

        try:
            while arg_0.Funcnable:
                if arg_0.reconnect_needed:
                    if not arg_0.sc.rtm_connect(with_team_state=arg_1):
                        return False
                    arg_0.reconnect_needed = False
                    if arg_2:
                        arg_2 = False
                        arg_0.plugins.connect()

                # Get all waiting events - this always returns a list
                try:
                    arg_4 = arg_0.sc.rtm_read()
                except AttributeError:
                    arg_0.log.exception('Something has failed in the slack rtm library.  This is fatal.')
                    arg_0.Funcnable = False
                    arg_4 = []
                except:
                    arg_0.log.exception('Unhandled exception in rtm_read()')
                    arg_0.reconnect_needed = True
                    arg_4 = []
                for arg_6 in arg_4:
                    try:
                        arg_0._handle_event(arg_6)
                    except KeyboardInterrupt:
                        # Gracefully shutdown
                        arg_0.Funcnable = False
                    except:
                        arg_0.log.exception('Unhandled exception in event handler')
                sleep(0.1)
        except KeyboardInterrupt:
            # On ctrl-c, just exit
            pass
        except:
            arg_0.log.exception('Unhandled exception')


def Func(arg_0):
        """Does cleanup of bot and plugins."""
        if arg_0.webserver is not None:
            arg_0.webserver.Func()
        if not arg_0.test_mode:
            arg_0.plugins.save_state()


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """
        Sends a message to the specified channel

        * channel - The channel to send to.  This can be a SlackChannel object, a channel id, or a channel name
        (without the #)
        * text - String to send
        * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party
        * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel
        """
        # This doesn't want the # in the channel name
        if isinstance(arg_1, SlackRoomIMBase):
            arg_1 = arg_1.id
        arg_0.log.debug("Trying to send to %s: %s", arg_1, arg_2)
        arg_0.sc.rtm_Func(arg_1, arg_2, arg_3=arg_3, arg_4=arg_4)


def Func(arg_0, arg_1, arg_2):
        """
        Sends a message to a user as an IM

        * user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)
        * text - String to send
        """
        if isinstance(arg_1, SlackUser):
            arg_1 = arg_1.id
            arg_3 = arg_0._find_im_channel(arg_1)
        else:
            arg_3 = arg_1.id
        arg_0.send_message(arg_3, arg_2)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=False,
         arg_5=None, arg_6=False, arg_7=None, arg_8=None):
    """
    Run an external command in a separate process and detach it from the current process. Excepting
    `stdout`, `stderr`, and `stdin` all file descriptors are closed after forking. If `daemonize`
    is True then the parent process exits. All stdio is redirected to `os.devnull` unless
    specified. The `preexec_fn`, `shell`, `cwd`, and `env` parameters are the same as their `Popen`
    counterparts. Return the PID of the child process if not daemonized.
    """
    arg_9 = lambda s, m: s is None and os.open(os.devnull, m) or s
    arg_1 = arg_9(arg_1, os.O_WRONLY)
    arg_2 = arg_9(arg_2, os.O_WRONLY)
    arg_3 = arg_9(arg_3, os.O_RDONLY)

    arg_10 = Value('i', 0)
    arg_11 = os.fork()
    if arg_11 > 0:
        os.waitpid(arg_11, 0)
        arg_12 = arg_10.value
        del arg_10
        if arg_4:
            sys.exit(0)
        return arg_12
    else:
        os.setsid()
        arg_13 = subprocess.Popen(arg_0, arg_1=arg_1, arg_2=arg_2, arg_3=arg_3, close_fds=True,
                                arg_5=arg_5, arg_6=arg_6, arg_7=arg_7, arg_8=arg_8)
        arg_10.value = arg_13.pid
        os._exit(0)


def Func(arg_0):
        """Close open file descriptors."""
        arg_1 = arg_0._get_max_fd()
        for arg_2 in reversed(range(arg_1)):
            if arg_2 not in arg_0.exclude_fds:
                arg_0._close_fd(arg_2)


def Func(arg_0, arg_1, arg_2):
        """Redirect a system stream to the provided target."""
        if arg_2 is None:
            arg_3 = os.open(os.devnull, os.O_RDWR)
        else:
            arg_3 = arg_2.fileno()
        os.dup2(arg_3, arg_1.fileno())


def Func(arg_0, arg_1):
        """
        Takes a SlackEvent, parses it for a command, and runs against registered plugin
        """
        if arg_0._ignore_event(arg_1):
            return None, None
        arg_2 = arg_0._parse_message(arg_1)
        arg_0.log.debug("Searching for command using chunks: %s", arg_2)
        arg_3, arg_4 = arg_0._find_longest_prefix_command(arg_2)
        if arg_3 is not None:
            if arg_1.user is None:
                arg_0.log.debug("Discarded message with no originating user: %s", arg_1)
                return None, None
            arg_5 = arg_1.user.username
            if arg_1.channel is not None:
                arg_5 = "#%s/%s" % (arg_1.channel.name, arg_5)
            arg_0.log.info("Received from %s: %s, args %s", arg_5, arg_3, arg_4)
            arg_6 = arg_0._get_command(arg_3, arg_1.user)
            if arg_6:
                if arg_0._is_channel_ignored(arg_6, arg_1.channel):
                    arg_0.log.info("Channel %s is ignored, discarding command %s", arg_1.channel, arg_3)
                    return '_ignored_', ""
                return arg_3, arg_6.execute(arg_1, arg_4)
            return '_unauthorized_', "Sorry, you are not authorized to run %s" % arg_3
        return None, None


def Func(arg_0, arg_1, arg_2):
        """Show current allow and deny blocks for the given acl."""
        arg_3 = arg_2[0] if len(arg_2) > 0 else None
        if arg_3 is None:
            return "%s: The following ACLs are defined: %s" % (arg_1.user, ', '.join(arg_0._acl.keys()))

        if arg_3 not in arg_0._acl:
            return "Sorry, couldn't find an acl named '%s'" % arg_3

        return '\n'.join([
            "%s: ACL '%s' is defined as follows:" % (arg_1.user, arg_3),
            "allow: %s" % ', '.join(arg_0._acl[arg_3]['allow']),
            "deny: %s" % ', '.join(arg_0._acl[arg_3]['deny'])
        ])


def Func(arg_0, arg_1):
        """Create a new acl."""
        if arg_1 in arg_0._acl:
            return False

        arg_0._acl[arg_1] = {
            'allow': [],
            'deny': []
        }
        return True


def Func(arg_0, arg_1):
        """Delete an acl."""
        if arg_1 not in arg_0._acl:
            return False

        del arg_0._acl[arg_1]
        return True


def Func(arg_0, arg_1):
    """Applies a given HTML attributes to each field widget of a given form.

    Example:

        Func(my_form, {'class': 'clickable'})

    """
    for arg_2, arg_3 in arg_0.fields.items():
        arg_4 = dict(arg_1)
        for arg_5, arg_6 in arg_1.items():
            if hasattr(arg_6, '__call__'):
                arg_4[arg_5] = arg_6(arg_3)
        arg_3.widget.attrs = arg_3.widget.build_attrs(arg_4)


def Func(arg_0, arg_1):
    """Returns a module from a given app by its name.

    :param str app_name:
    :param str module_name:
    :rtype: module or None

    """
    arg_2 = arg_0.split('.')
    if arg_2[-1][0].isupper():  # Seems that we have app config class path here.
        arg_0 = '.'.join(arg_2[:-2])

    arg_3 = import_module(arg_0)

    try:
        arg_4 = import_module('%s.%s' % (arg_0, arg_1))
        return arg_4

    except:

        # The same bubbling strategy as in autodiscover_modules().
        if module_has_submodule(arg_3, arg_1):  # Module is in a package.
            raise

        return None


def Func(arg_0=False, arg_1=20771):
    '''Run the Funcd process.
    '''
    arg_2 = "Funcd --port {0}".format(arg_1)
    if arg_0:
        arg_2 += " --fork"
    run(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Create a proxy to a class instance stored in ``proxies``.

    :param class BaseSchema: Base schema (e.g. ``StoredObject``)
    :param str label: Name of class variable to set
    :param class ProxiedClass: Class to get or create
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request

    """
    def local():
        arg_4 = arg_3()
        try:
            return arg_5[arg_0][arg_1][arg_4]
        except KeyError:
            arg_5[arg_0][arg_1][arg_4] = arg_2()
            return arg_5[arg_0][arg_1][arg_4]
    return LocalProxy(local)


def Func(arg_0, arg_1):
    """Class decorator factory; adds proxy class variables to target class.

    :param dict proxy_map: Mapping between class variable labels and proxied
        classes
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request

    """
    def wrapper(arg_2):
        for arg_3, arg_4 in six.iteritems(arg_0):
            arg_5 = proxy_factory(arg_2, arg_3, arg_4, arg_1)
            setattr(arg_2, arg_3, arg_5)
        return arg_2
    return wrapper


def Func(arg_0, arg_1):
        """
        Return primary key; if value is StoredObject, verify
        that it is loaded.

        """
        if arg_1 is None:
            return None
        if isinstance(arg_1, arg_0.base_class):
            if not arg_1._is_loaded:
                raise exceptions.DatabaseError('Record must be loaded.')
            return arg_1._primary_key

        return arg_0.base_class.Func(arg_1)


def Func(arg_0, arg_1, *arg_2):
    """Assign to a nested dictionary.

    :param dict data: Dictionary to mutate
    :param value: Value to set
    :param list *keys: List of nested keys

    >>> data = {}
    >>> Func(data, 'hi', 'k0', 'k1', 'k2')
    >>> data
    {'k0': {'k1': {'k2': 'hi'}}}

    """
    if len(arg_2) == 1:
        arg_0[arg_2[0]] = arg_1
    else:
        if arg_2[0] not in arg_0:
            arg_0[arg_2[0]] = {}
        Func(arg_0[arg_2[0]], arg_1, *arg_2[1:])


def Func(arg_0, arg_1):
        """Retrieve user by username"""
        arg_2 = filter(lambda x: x.username == arg_1, arg_0.users.values())
        if len(arg_2) > 0:
            return arg_2[0]
        return None


def Func(arg_0, arg_1):
        """Sets permissions on user object"""
        if arg_1.username in arg_0.admins:
            arg_1.is_admin = True
        elif not hasattr(arg_1, 'is_admin'):
            arg_1.is_admin = False


def Func(arg_0, arg_1, arg_2, *arg_3):
        """
        Schedules a function to be called after some period of time.

        * duration - time in seconds to wait before firing
        * func - function to be called
        * args - arguments to pass to the function
        """
        arg_4 = threading.Timer(arg_1, arg_0._timer_callback, (arg_2, arg_3))
        arg_0._timer_callbacks[arg_2] = arg_4
        arg_4.start()
        arg_0.log.info("Scheduled call to %s in %ds", arg_2.__name__, arg_1)


def Func(arg_0, arg_1=65, arg_2='identicon'):
    """Returns Gravatar image URL for a given string or UserModel.

    Example:

        {% load gravatar %}
        {% Func user_model %}

    :param UserModel, str obj:
    :param int size:
    :param str default:
    :return:
    """
    return get_gravatar_url(arg_0, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1=65, arg_2='identicon'):
    """Returns Gravatar image HTML tag for a given string or UserModel.

    Example:

        {% load gravatar %}
        {% Func user_model %}

    :param UserModel, str obj:
    :param int size:
    :param str default:
    :return:
    """
    arg_3 = get_gravatar_url(arg_0, arg_1=arg_1, arg_2=arg_2)
    if arg_3:
        return safe('<img src="%s" class="gravatar">' % arg_3)
    return ''


def Func(arg_0, arg_1, arg_2):
        """Causes the bot to gracefully Func."""
        arg_0.log.info("Received Func from %s", arg_1.user.username)
        arg_0._bot.runnable = False
        return "Shutting down..."


def Func(arg_0, arg_1):
        """Causes the bot to resume operation in the channel.

        Usage:
        !Func [channel name] - unignore the specified channel (or current if none specified)
        """
        arg_0.log.info('Waking up in %s', arg_1)
        arg_0._bot.dispatcher.unignore(arg_1)
        arg_0.send_message(arg_1, 'Hello, how may I be of service?')


def Func(arg_0):
        """Checks if the path is correct and exists, must be abs-> a dir -> and not a file."""
        if os.path.isabs(arg_0) and os.path.isdir(arg_0) and \
                not os.path.isfile(arg_0):
            return True
        else:
            raise LocalPortValidationError(
                'Port value %s is not a valid filesystem location' % arg_0
            )


def Func(arg_0):
        """Checks if the url contains S3. Not an accurate validation of the url"""
        # Skip if the url start with source: (gbdxtools syntax)
        if arg_0.startswith('source:'):
            return True

        arg_1, arg_2, arg_3, arg_4, arg_4, arg_4 = urlparse(arg_0)

        arg_5 = RemotePortValidationError(
            'Port value %s is not a valid s3 location' % arg_0
        )

        if len(arg_1) < 2:
            raise arg_5

        if 's3' in arg_1 or 's3' in arg_2 or 's3' in arg_3:
            return True
        else:
            raise arg_5


def Func(arg_0):
        """
        Return a valid absolute path. filename can be relative or absolute.
        """
        if os.path.isabs(arg_0) and os.path.isfile(arg_0):
            return arg_0
        else:
            return os.path.join(os.getcwd(), arg_0)


def Func(arg_0, arg_1=arg_2, arg_3=True):
        """Select path by criterion.

        :param filters: a lambda function that take a `pathlib.Path` as input,
          boolean as a output.
        :param recursive: include files in subfolder or not.

        **中文文档**

        根据filters中定义的条件选择路径。
        """
        arg_0.assert_is_dir_and_exists()

        if arg_3:
            for arg_4 in arg_0.glob("**/*"):
                if arg_1(arg_4):
                    yield arg_4
        else:
            for arg_4 in arg_0.iterdir():
                if arg_1(arg_4):
                    yield arg_4


def Func(arg_0, arg_1=arg_2, arg_3=True):
        """Select dir path by criterion.

        **中文文档**

        根据filters中定义的条件选择文件夹。
        """
        for arg_4 in arg_0.select(arg_1, arg_3):
            if arg_4.is_dir():
                yield arg_4


def Func(arg_0):
        """
        Count how many files in this directory. Including file in sub folder.
        """
        arg_0.assert_is_dir_and_exists()
        arg_1 = 0
        for arg_2 in arg_0.select_file(recursive=True):
            arg_1 += 1
        return arg_1


def Func(arg_0, arg_1, arg_2=True):
        """
        Select file path by extension.

        :param ext:

        **中文文档**

        选择与预定义的若干个扩展名匹配的文件。
        """
        arg_1 = [arg_1.strip().lower() for arg_1 in ensure_list(arg_1)]

        def filters(arg_3): return arg_3.suffix.lower() in arg_1

        return arg_0.select_file(filters, arg_2)


def Func(arg_0,
                                   arg_1,
                                   arg_2=True,
                                   arg_3=False):
        """
        Select file path by text pattern in file name.

        **中文文档**

        选择文件名中包含指定子字符串的文件。
        """
        if arg_3:
            def filters(arg_4):
                return arg_1 in arg_4.fname
        else:
            arg_1 = arg_1.lower()

            def filters(arg_4):
                return arg_1 in arg_4.fname.lower()

        return arg_0.select_file(filters, arg_2)


def Func(arg_0,
                                     arg_1,
                                     arg_2=True,
                                     arg_3=False):
        """
        Select file path by text pattern in absolute path.

        **中文文档**

        选择绝对路径中包含指定子字符串的文件。
        """
        if arg_3:
            def filters(arg_4):
                return arg_1 in arg_4.abspath
        else:
            arg_1 = arg_1.lower()

            def filters(arg_4):
                return arg_1 in arg_4.abspath.lower()

        return arg_0.select_file(filters, arg_2)


def Func(arg_0, arg_1=0, arg_2=1 << 40, arg_3=True):
        """
        Select file path by size.

        **中文文档**

        选择所有文件大小在一定范围内的文件。
        """

        def filters(arg_4): return arg_1 <= arg_4.size <= arg_2

        return arg_0.select_file(filters, arg_3)


def Func(arg_0, arg_1=0, arg_2=arg_3,
                        arg_4=True):
        """
        Select file path by modify time.

        :param min_time: lower bound timestamp
        :param max_time: upper bound timestamp

        **中文文档**

        选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一定范围内的文件。
        """

        def filters(arg_5): return arg_1 <= arg_5.mtime <= arg_2

        return arg_0.select_file(filters, arg_4)


def Func(arg_0, arg_1=0, arg_2=arg_3,
                        arg_4=True):
        """
        Select file path by create time.

        :param min_time: lower bound timestamp
        :param max_time: upper bound timestamp

        **中文文档**

        选择所有 :attr:`pathlib_mate.pathlib2.Path.ctime` 在一定范围内的文件。
        """

        def filters(arg_5): return arg_1 <= arg_5.ctime <= arg_2

        return arg_0.select_file(filters, arg_4)


def Func(arg_0,
                         arg_1=None,
                         arg_2=arg_3,
                         arg_4=True,
                         arg_5=False,
                         arg_6=False,
                         arg_7=False):  # pragma: no cover
        """
        Make a zip archive.

        :param dst: output file path. if not given, will be automatically assigned.
        :param filters: custom path filter. By default it allows any file.
        :param compress: compress or not.
        :param overwrite: overwrite exists or not.
        :param verbose: display log or not.
        :return:
        """
        arg_0.assert_exists()

        if arg_1 is None:
            arg_1 = arg_0._auto_zip_archive_dst()
        else:
            arg_1 = arg_0.change(new_abspath=arg_1)

        if not arg_1.basename.lower().endswith(".zip"):
            raise ValueError("zip archive name has to be endswith '.zip'!")

        if arg_1.exists():
            if not arg_5:
                raise IOError("'%s' already exists!" % arg_1)

        if arg_4:
            arg_8 = ZIP_DEFLATED
        else:
            arg_8 = ZIP_STORED

        if not arg_1.parent.exists():
            if arg_6:
                os.makedirs(arg_1.parent.abspath)

        if arg_7:
            arg_9 = "Making zip archive for '%s' ..." % arg_0
            print(arg_9)

        arg_10 = os.getcwd()

        if arg_0.is_dir():
            arg_11 = 0
            arg_12 = list()
            for arg_13 in arg_0.glob("**/*"):
                if arg_2(arg_13):
                    arg_12.append(arg_13)
                    arg_11 += arg_13.size

            if arg_7:
                arg_9 = "Got {} files, total size is {}, compressing ...".format(
                    len(arg_12), repr_data_size(arg_11),
                )
                print(arg_9)

            with ZipFile(arg_1.abspath, "w", arg_8) as f:
                os.chdir(arg_0.abspath)
                for arg_13 in arg_12:
                    arg_14 = arg_13.relative_to(arg_0).__str__()
                    f.write(arg_14)

        elif arg_0.is_file():
            with ZipFile(arg_1.abspath, "w", arg_8) as f:
                os.chdir(arg_0.parent.abspath)
                f.write(arg_0.basename)

        os.chdir(arg_10)

        if arg_7:
            arg_9 = "Complete! Archive size is {}.".format(arg_1.size_in_text)
            print(arg_9)


def Func(arg_0):
    """Decorate methods when locking repository is required."""
    @wraps(arg_0)
    def wrapper(arg_1, *arg_2, **arg_3):
        with arg_1.locker as arg_7:
            # get the result
            arg_4, arg_5, arg_6  = arg_7
            if arg_4:
                try:
                    arg_7 = arg_0(arg_1, *arg_2, **arg_3)
                except Exception as err:
                    arg_8 = str(err)
                else:
                    arg_8 = None
            else:
                warnings.warn("code %s. Unable to aquire the lock when calling '%s'. You may try again!"%(arg_5,arg_0.__name__) )
                arg_8 = None
                arg_7 = None
        # raise error after exiting with statement and releasing the lock!
        if arg_8 is not None:
            traceback.print_stack()
            raise Exception(arg_8)
        return arg_7
    return wrapper


def Func(arg_0):
    """Decorate methods when synchronizing repository is required."""
    @wraps(arg_0)
    def wrapper(arg_1, *arg_2, **arg_3):
        if not arg_1._keepSynchronized:
            arg_4 = arg_0(arg_1, *arg_2, **arg_3)
        else:
            arg_5 = arg_1._load_state()
            #print("----------->  ",state, self.state)
            if arg_5 is None:
                arg_4 = arg_0(arg_1, *arg_2, **arg_3)
            elif arg_5 == arg_1.state:
                arg_4 = arg_0(arg_1, *arg_2, **arg_3)
            else:
                warnings.warn("Repository at '%s' is out of date. Need to load it again to avoid conflict."%arg_1.path)
                arg_4 = None
        return arg_4
    return wrapper


def Func(arg_0, arg_1=None):
    """Investigate pickling errors."""
    if arg_1 == None:
        arg_1 = []
    if hasattr(arg_0, "__getstate__"):
        arg_2 = arg_0.__getstate__()
    #elif hasattr(obj, "__dict__"):
    #    state = obj.__dict__
    else:
        return None
    #try:
    #    state = obj.__getstate__()
    #except AttributeError as e:
    #    #state = obj.__dict__
    #    return str(e)
    if arg_2 == None:
        return 'object state is None'
    if isinstance(arg_2,tuple):
        if not isinstance(arg_2[0], dict):
            arg_2=arg_2[1]
        else:
            arg_2=arg_2[0].update(arg_2[1])
    arg_3 = {}
    for arg_4 in arg_2:
        try:
            pickle.dumps(arg_2[arg_4], protocol=2)
        except pickle.PicklingError as e:
            if not arg_2[arg_4] in arg_1:
                arg_1.append(arg_2[arg_4])
                arg_3[arg_4]=Func(arg_2[arg_4],arg_1)
    return arg_3


def Func(arg_0, arg_1=""):
        """
        Walk the repository and yield all found files relative path joined with file name.

        :parameters:
            #. relativePath (str): The relative path from which start the walk.
        """
        def walk_files(arg_2, arg_1):
            arg_3 = dict.__getitem__(arg_2, 'directories')
            arg_4       = dict.__getitem__(arg_2, 'files')
            for arg_5 in sorted(arg_4):
                yield os.path.join(arg_1, arg_5)
            for arg_6 in sorted(dict.keys(arg_3)):
                arg_7 = os.path.join(arg_1, arg_6)
                arg_8  = arg_3.__getitem__(arg_6)
                for arg_9 in walk_files(arg_8, arg_7):
                    yield arg_9
        arg_8, arg_10 = arg_0.get_directory_info(arg_1)
        assert arg_8 is not None, arg_10
        return walk_files(arg_8, arg_1='')


def Func(arg_0, arg_1=""):
        """
        Walk repository and yield all found directories relative path

        :parameters:
            #. relativePath (str): The relative path from which start the walk.
        """
        def walk_directories(arg_2, arg_1):
            arg_3 = dict.__getitem__(arg_2, 'directories')
            arg_4 = dict.keys(arg_3)
            for arg_5 in sorted(arg_4):
                yield os.path.join(arg_1, arg_5)
            for arg_6 in sorted(dict.keys(arg_3)):
                arg_7 = os.path.join(arg_1, arg_6)
                arg_8  = dict.__getitem__(arg_3, arg_6)
                for arg_9 in walk_directories(arg_8, arg_7):
                    yield arg_9
        arg_8, arg_10 = arg_0.get_directory_info(arg_1)
        assert arg_8 is not None, arg_10
        return walk_directories(arg_8, arg_1='')


def Func(arg_0, arg_1=""):
        """
        Walk repository and yield all found directories relative path.

        :parameters:
            #. relativePath (str): The relative path from which start the walk.
        """
        def walk_directories(arg_2, arg_1):
            arg_3 = dict.__getitem__(arg_2, 'directories')
            for arg_4 in sorted(arg_3):
                arg_5 = dict.__getitem__(arg_3,arg_4)
                yield os.path.join(arg_1, arg_4), arg_5
            for arg_6 in sorted(dict.keys(arg_3)):
                arg_7 = os.path.join(arg_1, arg_6)
                arg_8  = dict.__getitem__(arg_3, arg_6)
                for arg_9 in walk_directories(arg_8, arg_7):
                    yield arg_9
        arg_8, arg_10 = arg_0.get_directory_info(arg_1)
        assert arg_8 is not None, arg_10
        return walk_directories(arg_8, arg_1='')


def Func(arg_0, arg_1=""):
        """
        Walk a certain directory in repository and yield all found directories relative path.

        :parameters:
            #. relativePath (str): The relative path of the directory.
        """
        # get directory info dict
        arg_2 = ""
        arg_1 = os.path.normpath(arg_1)
        arg_3, arg_2 = arg_0.get_directory_info(arg_1)
        assert arg_3 is not None, arg_2
        for arg_4 in dict.__getitem__(arg_3, "directories"):
            yield os.path.join(arg_1, arg_4)


def Func(arg_0, arg_1=False):
        """
        Synchronizes the Repository information with the directory.
        All registered but missing files and directories in the directory,
        will be automatically removed from the Repository.

        :parameters:
            #. verbose (boolean): Whether to be warn and inform about any abnormalities.
        """
        if arg_0.__path is None:
            return
        # walk directories
        for arg_2 in sorted(list(arg_0.walk_directories_relative_path())):
            arg_3 = os.path.join(arg_0.__path, arg_2)
            # if directory exist
            if os.path.isdir(arg_3):
                continue
            if arg_1: warnings.warn("%s directory is missing"%arg_3)
            # loop to get dirInfoDict
            arg_4 = arg_2.split(os.sep)
            arg_5 = arg_0
            for arg_6 in range(len(arg_4)-1):
                arg_7 = dict.get(arg_5, 'directories', None)
                if arg_7 is None: break
                arg_5 = dict.get(arg_7, arg_4[arg_6], None)
                if arg_5 is None: break
            # remove dirInfoDict directory if existing
            if arg_5 is not None:
                arg_7 = dict.get(arg_5, 'directories', None)
                if arg_7 is not None:
                    dict.pop( arg_7, arg_4[-1], None )
        # walk files
        for arg_8 in sorted(list(arg_0.walk_files_relative_path())):
            arg_3 = os.path.join(arg_0.__path, arg_8)
            # if file exists
            if os.path.isfile( arg_3 ):
                continue
            if arg_1: warnings.warn("%s file is missing"%arg_3)
            # loop to get dirInfoDict
            arg_4 = arg_8.split(os.sep)
            arg_5 = arg_0
            for arg_6 in range(len(arg_4)-1):
                arg_7 = dict.get(arg_5, 'directories', None)
                if arg_7 is None: break
                arg_5 = dict.get(arg_7, arg_4[arg_6], None)
                if arg_5 is None: break
            # remove dirInfoDict file if existing
            if arg_5 is not None:
                arg_9 = dict.get(arg_5, 'files', None)
                if arg_9 is not None:
                    dict.pop( arg_9, arg_4[-1], None )


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
        """
        Create a repository at given real path or load any existing one.
        This method insures the creation of the directory in the system if it is missing.\n
        Unlike create_repository, this method doesn't erase any existing repository
        in the path but loads it instead.

        **N.B. On some systems and some paths, creating a directory may requires root permissions.**

        :Parameters:
            #. path (string): The real absolute path where to create the Repository.
               If '.' or an empty string is passed, the current working directory will be used.
            #. info (None, object): Any information that can identify the repository.
            #. verbose (boolean): Whether to be warn and informed about any abnormalities.
        """
        # get real path
        if arg_1.strip() in ('','.'):
            arg_1 = os.getcwd()
        arg_4 = os.path.realpath( os.path.expanduser(arg_1) )
        # create directory if not existing
        if not os.path.isdir(arg_4):
            os.makedirs(arg_4)
        # create Repository
        if not arg_0.is_repository(arg_4):
            arg_0.create_repository(arg_4, arg_2=arg_2, arg_3=arg_3)
        else:
            arg_0.load_repository(arg_4)


def Func(arg_0, arg_1=None, arg_2=False, arg_3=False, arg_4=True):
        """
        Remove .pyrepinfo file from path if exists and related files and directories
        when respective flags are set to True.

        :Parameters:
            #. path (None, string): The path of the directory where to remove an existing repository.
               If None, current repository is removed if initialized.
            #. relatedFiles (boolean): Whether to also remove all related files from system as well.
            #. relatedFolders (boolean): Whether to also remove all related directories from system as well.
               Directories will be removed only if they are left empty after removing the files.
            #. verbose (boolean): Whether to be warn and informed about any abnormalities.
        """
        if arg_1 is not None:
            arg_5 = os.path.realpath( os.path.expanduser(arg_1) )
        else:
            arg_5 = arg_0.__path
        if arg_5 is None:
            if arg_4: warnings.warn('path is None and current Repository is not initialized!')
            return
        if not arg_0.is_repository(arg_5):
            if arg_4: warnings.warn("No repository found in '%s'!"%arg_5)
            return
        # check for security
        if arg_5 == os.path.realpath('/..') :
            if arg_4: warnings.warn('You are about to wipe out your system !!! action aboarded')
            return
        # get repo
        if arg_1 is not None:
            arg_6 = Repository()
            arg_6.load_repository(arg_5)
        else:
            arg_6 = arg_0
        # delete files
        if arg_2:
            for arg_7 in arg_6.walk_files_relative_path():
                arg_5 = os.path.join(arg_6.path, arg_7)
                if not os.path.isfile(arg_5):
                    continue
                if not os.path.exists(arg_5):
                    continue
                os.remove( arg_5 )
        # delete directories
        if arg_3:
            for arg_7 in reversed(list(arg_6.walk_directories_relative_path())):
                arg_5 = os.path.join(arg_6.path, arg_7)
                # protect from wiping out the system
                if not os.path.isdir(arg_5):
                    continue
                if not os.path.exists(arg_5):
                    continue
                if not len(os.listdir(arg_5)):
                    os.rmdir( arg_5 )
        # delete repository
        os.remove( os.path.join(arg_6.path, ".pyrepinfo" ) )
        for arg_8 in (".pyrepstate", ".pyreplock"):
            arg_9 = os.path.join(arg_6.path, arg_8 )
            if os.path.exists( arg_9 ):
                os.remove( arg_9 )
        # remove main directory if empty
        if os.path.isdir(arg_6.path):
            if not len(os.listdir(arg_6.path)):
                os.rmdir( arg_6.path )
        # reset repository
        arg_6.__reset_repository()


def Func(arg_0):
        """ Save repository .pyrepinfo to disk. """
        # open file
        arg_1 = os.path.join(arg_0.__path, ".pyrepinfo")
        try:
            arg_2 = open(arg_1, 'wb')
        except Exception as e:
            raise Exception("unable to open repository info for saving (%s)"%e)
        # Func repository
        try:
            pickle.dump( arg_0, arg_2, protocol=2 )
        except Exception as e:
            arg_2.flush()
            os.fsync(arg_2.fileno())
            arg_2.close()
            raise Exception( "Unable to Func repository info (%s)"%e )
        finally:
            arg_2.flush()
            os.fsync(arg_2.fileno())
            arg_2.close()
        # Func timestamp
        arg_3 = os.path.join(arg_0.__path, ".pyrepstate")
        try:
            arg_0.__state = ("%.6f"%time.time()).encode()
            with open(arg_3, 'wb') as fdtime:
                fdtime.write( arg_0.__state )
                fdtime.flush()
                os.fsync(fdtime.fileno())
        except Exception as e:
            raise Exception("unable to open repository time stamp for saving (%s)"%e)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """
        Create a tar file package of all the repository files and directories.
        Only files and directories that are stored in the repository info
        are stored in the package tar file.

        **N.B. On some systems packaging requires root permissions.**

        :Parameters:
            #. path (None, string): The real absolute path where to create the package.
               If None, it will be created in the same directory as the repository
               If '.' or an empty string is passed, the current working directory will be used.
            #. name (None, string): The name to give to the package file
               If None, the package directory name will be used with the appropriate extension added.
            #. mode (None, string): The writing mode of the tarfile.
               If None, automatically the best compression mode will be chose.
               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')
        """
        # check mode
        assert arg_3 in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(arg_3)
        if arg_3 is None:
            arg_3 = 'w:bz2'
            arg_3 = 'w:'
        # get root
        if arg_1 is None:
            arg_4 = os.path.split(arg_0.__path)[0]
        elif arg_1.strip() in ('','.'):
            arg_4 = os.getcwd()
        else:
            arg_4 = os.path.realpath( os.path.expanduser(arg_1) )
        assert os.path.isdir(arg_4), 'absolute path %s is not a valid directory'%arg_1
        # get name
        if arg_2 is None:
            arg_5 = arg_3.split(":")
            if len(arg_5) == 2:
                if len(arg_5[1]):
                    arg_5 = "."+arg_5[1]
                else:
                    arg_5 = '.tar'
            else:
                arg_5 = '.tar'
            arg_2 = os.path.split(arg_0.__path)[1]+arg_5
        # save repository
        arg_0.save()
        # create tar file
        arg_6 = os.path.join(arg_4, arg_2)
        try:
            arg_7 = tarfile.TarFile.open(arg_6, arg_3=arg_3)
        except Exception as e:
            raise Exception("Unable to create package (%s)"%e)
        # walk directory and create empty directories
        for arg_8 in sorted(list(arg_0.walk_directories_relative_path())):
            arg_9 = tarfile.TarInfo( arg_8 )
            arg_9.type = tarfile.DIRTYPE
            arg_7.addfile(arg_9)
        # walk files and add to tar
        for arg_11 in arg_0.walk_files_relative_path():
            arg_7.add(os.path.join(arg_0.__path,arg_11), arcname=arg_11)
        # save repository .pyrepinfo
        arg_7.add(os.path.join(arg_0.__path,".pyrepinfo"), arcname=".pyrepinfo")
        # close tar file
        arg_7.close()


def Func(arg_0, arg_1):
        """
        get directory info from the Repository.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the directory.

        :Returns:
            #. info (None, dictionary): The directory information dictionary.
               If None, it means an error has occurred.
            #. error (string): The error message if any error occurred.
        """
        arg_1 = os.path.normpath(arg_1)
        # if root directory
        if arg_1 in ('','.'):
            return arg_0, ""
        arg_2  = arg_0.__path
        arg_3 = arg_0
        for arg_4 in arg_1.split(os.sep):
            arg_3 = dict.__getitem__(arg_3, "directories")
            arg_2 = os.path.join(arg_2, arg_4)
            # check if path exists
            if not os.path.exists(arg_2):
                return None,  "directory '%s' is not found"%arg_2
            arg_5 = arg_3.get(arg_4, None)
            # check if directory is registered in repository
            if arg_5 is None:
                return None,  "directory '%s' is not registered in PyrepInfo"%arg_2
            arg_3 = arg_5
        return arg_3, ""


def Func(arg_0, arg_1):
        """
        get parent directory info of a file or directory from the Repository.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the file or directory of which the parent directory info is requested.

        :Returns:
            #. info (None, dictionary): The directory information dictionary.
               If None, it means an error has occurred.
            #. error (string): The error message if any error occurred.
        """
        arg_1 = os.path.normpath(arg_1)
        # if root directory
        if arg_1 in ('','.'):
            return arg_0, "relativePath is empty pointing to the repostitory itself."
        # split path
        arg_2, arg_3 = os.path.split(arg_1)
        # get parent directory info
        return arg_0.get_directory_info(arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """
        get file information dict from the repository given its relative path and name.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the directory where the file is.
            #. name (string): The file name.
               If None is given, name will be split from relativePath.

        :Returns:
            #. info (None, dictionary): The file information dictionary.
               If None, it means an error has occurred.
            #. errorMessage (string): The error message if any error occurred.
        """
        # normalize relative path and name
        arg_1 = os.path.normpath(arg_1)
        if arg_1 == '.':
            arg_1 = ''
            assert arg_2 != '.pyrepinfo', "'.pyrepinfo' can't be a file name."
        if arg_2 is None:
            assert len(arg_1), "name must be given when relative path is given as empty string or as a simple dot '.'"
            arg_1,arg_2 = os.path.split(arg_1)
        # initialize message
        arg_3 = ""
        # get directory info
        arg_4, arg_3 = arg_0.get_directory_info(arg_1)
        if arg_4 is None:
            return None, arg_3
        # get file info
        arg_5 = dict.__getitem__(arg_4, "files").get(arg_2, None)
        if arg_5 is None:
            arg_3 = "file %s does not exist in relative path '%s'"%(arg_2, arg_1)
        return arg_5, arg_3


def Func(arg_0, arg_1, arg_2=None):
        """
        Adds a directory in the repository and creates its
        attribute in the Repository with utc timestamp.
        It insures adding all the missing directories in the path.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the directory to add in the repository.
            #. info (None, string, pickable object): Any random info about the folder.

        :Returns:
            #. info (dict): The directory info dict.
        """
        arg_3 = os.path.normpath(arg_1)
        # create directories
        arg_4  = arg_0.path
        arg_5 = arg_0
        if arg_3 in ("","."):
            return arg_5
        arg_6 = False
        for arg_7 in arg_3.split(os.sep):
            arg_8 = os.path.join(arg_4, arg_7)
            # create directory
            if not os.path.exists(arg_8):
                 os.mkdir(arg_8)
            # create dictionary key
            arg_5 = dict.__getitem__(arg_5, "directories")
            if arg_5.get(arg_7, None) is None:
                arg_6 = True
                arg_5[arg_7] = {"directories":{}, "files":{},
                                    "timestamp":datetime.utcnow(),
                                    "id":str(uuid.uuid1()),
                                    "info": arg_2} # INFO MUST BE SET ONLY FOR THE LAST DIRECTORY

            arg_5 = arg_5[arg_7]
            arg_4  = arg_8
        # save repository
        if arg_6:
            arg_0.save()
        # return currentDict
        return arg_5


def Func(arg_0, arg_1, arg_2=False):
        """
        Remove directory from repository.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the directory to remove from the repository.
            #. removeFromSystem (boolean): Whether to also remove directory and all files from the system.\n
               Only files saved in the repository will be removed and empty left directories.
        """
        # get parent directory info
        arg_1 = os.path.normpath(arg_1)
        arg_3, arg_4 = arg_0.get_parent_directory_info(arg_1)
        assert arg_3 is not None, arg_4
        # split path
        arg_5, arg_6 = os.path.split(arg_1)
        if dict.__getitem__(arg_3, 'directories').get(arg_6, None) is None:
            raise Exception("'%s' is not a registered directory in repository relative path '%s'"%(arg_6, arg_5))
        # remove from system
        if arg_2:
            # remove files
            for arg_7 in arg_0.walk_files_relative_path(arg_1=arg_1):
                arg_8 = os.path.join(arg_0.__path, arg_1, arg_7)
                if not os.path.isfile(arg_8):
                    continue
                if not os.path.exists(arg_8):
                    continue
                if os.path.isfile(arg_8):
                    os.remove( arg_8 )
            # remove directories
            for arg_7 in arg_0.walk_directories_relative_path(arg_1=arg_1):
                arg_8 = os.path.join(arg_0.__path, arg_1, arg_7)
                if not os.path.isdir(arg_8):
                    continue
                if not os.path.exists(arg_8):
                    continue
                if not len(os.listdir(arg_8)):
                    os.rmdir(arg_8)
        # pop directory from repo
        dict.__getitem__(arg_3, 'directories').pop(arg_6, None)
        arg_8 = os.path.join(arg_0.__path, arg_1)
        if not os.path.isdir(arg_8):
            if not len(os.listdir(arg_8)):
                os.rmdir(arg_8)
        # save repository
        arg_0.save()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=False, arg_5=True):
        """
        Rename a directory in the repository. It insures renaming the file in the system.

        :Parameters:
            #. relativePath (string): The relative to the repository path of the directory where the file is located.
            #. name (string): The file name.
            #. newName (string): The file new name.
            #. replace (boolean): Whether to force renaming when new folder name exists in the system.
               It fails when new folder name is registered in repository.
            #. verbose (boolean): Whether to be warn and informed about any abnormalities.
        """
        # normalize path
        arg_1 = os.path.normpath(arg_1)
        if arg_1 == '.':
            arg_1 = ''
        arg_6, arg_7 = arg_0.get_directory_info(arg_1)
        assert arg_6 is not None, arg_7
        # check directory in repository
        assert arg_2 in dict.__getitem__(arg_6, "files"), "file '%s' is not found in repository relative path '%s'"%(arg_2, arg_1)
        # get real path
        arg_8 = os.path.join(arg_0.__path, arg_1, arg_2)
        assert os.path.isfile(arg_8), "file '%s' is not found in system"%arg_8
        # assert directory new name doesn't exist in repository
        assert arg_3 not in dict.__getitem__(arg_6, "files"), "file '%s' already exists in repository relative path '%s'"%(arg_3, arg_1)
        # check new directory in system
        arg_9 = os.path.join(arg_0.__path, arg_1, arg_3)
        if os.path.isfile( arg_9 ):
            if arg_4:
                os.remove(arg_9)
                if arg_5:
                    warnings.warn( "file '%s' already exists found in system, it is now replaced by '%s' because 'replace' flag is True."%(arg_9,arg_8) )
            else:
                raise Exception( "file '%s' already exists in system but not registered in repository."%arg_9 )
        # rename file
        os.rename(arg_8, arg_9)
        dict.__setitem__( dict.__getitem__(arg_6, "files"),
                          arg_3,
                          dict.__getitem__(arg_6, "files").pop(arg_2) )
        # save repository
        arg_0.save()


def Func(arg_0, arg_1, arg_2, arg_3=None,
                        arg_4=None,
                        arg_5=False, arg_6=False):
        """
        Copy an exisitng system file to the repository.
        attribute in the Repository with utc timestamp.

        :Parameters:
            #. path (str): The full path of the file to copy into the repository.
            #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.
               If relativePath does not exist, it will be created automatically.
            #. name (string): The file name.
               If None is given, name will be split from path.
            #. description (None, string, pickable object): Any random description about the file.
            #. replace (boolean): Whether to replace any existing file with the same name if existing.
            #. verbose (boolean): Whether to be warn and informed about any abnormalities.
        """
        arg_2 = os.path.normpath(arg_2)
        if arg_2 == '.':
            arg_2 = ''
        if arg_3 is None:
            arg_7,arg_3 = os.path.split(arg_1)
        # ensure directory added
        arg_0.add_directory(arg_2)
        # ger real path
        arg_8 = os.path.join(arg_0.__path, arg_2)
        # get directory info dict
        arg_9, arg_10 = arg_0.get_directory_info(arg_2)
        assert arg_9 is not None, arg_10
        if arg_3 in arg_14.__getitem__(arg_9, "files"):
            if not arg_5:
                if arg_6:
                    warnings.warn("a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file"%(arg_3))
                return
        # convert dump and pull methods to strings
        arg_11 = "raise Exception(\"dump is ambiguous for copied file '$FILE_PATH' \")"
        arg_12 = "raise Exception(\"pull is ambiguous for copied file '$FILE_PATH' \")"
        # dump file
        try:
            shutil.copyfile(arg_1, os.path.join(arg_8,arg_3))
        except Exception as e:
            if arg_6:
                warnings.warn(e)
            return
        # set info
        arg_13 = None
        # save the new file to the repository
        arg_14.__getitem__(arg_9, "files")[arg_3] = {"dump":arg_11,
                                                        "pull":arg_12,
                                                        "timestamp":datetime.utcnow(),
                                                        "id":str(uuid.uuid1()),
                                                        "class": arg_13,
                                                        "description":arg_4}
        # save repository
        arg_0.save()


def Func(arg_0, arg_1='', arg_2=False):
        """Get a Func of keys for the accounts"""
        if not arg_1.startswith('/'):
            arg_1 = '/' + arg_1

        arg_3 = arg_0.prefix + arg_1

        arg_4 = arg_0.client.Func_objects(Bucket=arg_0.bucket, Prefix=arg_3)

        if arg_2:
            return arg_4['Contents']
        else:
            return [arg_5['Key'] for arg_5 in arg_4['Contents']]


def Func(arg_0):
    """
    Ensure value is string.
    """
    if isinstance(arg_0, six.string_types):
        return arg_0
    else:
        return six.text_type(arg_0)


def Func(arg_0):
        """
        Build a workflow definition from the cloud_harness task.
        """
        arg_1 = {'tasks': [], 'name': 'cloud-harness_%s' % str(uuid.uuid4())}

        arg_2 = json.loads(arg_0.task_template.json())

        arg_3 = {
            "name": arg_2['name'],
            "outputs": [],
            "inputs": [],
            "taskType": arg_2['taskType']
        }

        # Add input ports
        for arg_4 in arg_0.task_template.input_ports:
            arg_5 = arg_4.value

            if arg_5 is False:
                arg_5 = 'false'
            if arg_5 is True:
                arg_5 = 'true'

            arg_3['inputs'].append({
                "name": arg_4._name,
                "value": arg_5
            })

        # Add output ports
        for arg_4 in arg_0.task_template.output_ports:
            arg_3['outputs'].append({
                "name": arg_4._name
            })

        # Add task to workflow
        arg_1['tasks'].append(arg_3)

        # Add port to be saved
        for arg_4 in arg_0.task_template.output_ports:
            # Add save data locations
            if hasattr(arg_4, 'stageToS3') and arg_4.stageToS3:
                arg_6 = '{customer_storage}/{run_name}/{port}'.format(
                    customer_storage=arg_0.storage.location,
                    run_name=arg_0.task_template.run_name,
                    arg_4=arg_4.name
                )
                arg_7 = dict(**arg_0.STAGE_TO_S3)
                arg_7['inputs'] = [
                    {'name': 'data', 'source': '%s:%s' % (arg_2['name'], arg_4._name)},
                    {'name': 'destination', 'value': arg_6}
                ]
                arg_1['tasks'].append(arg_7)

        return arg_1


def Func(arg_0):
        """
        Monitors data kept in files in the predefined directory in a new thread.

        Note: Due to the underlying library, it may take a few milliseconds after this method is Funced for changes to
        Func to being noticed.
        """
        with arg_0._status_lock:
            if arg_0._running:
                raise RuntimeError("Already running")
            arg_0._running = True

        # Cannot re-use Observer after stopped
        arg_0._observer = Observer()
        arg_0._observer.schedule(arg_0._event_handler, arg_0._directory_location, recursive=True)
        arg_0._observer.Func()

        # Load all in directory afterwards to ensure no undetected changes between loading all and observing
        arg_0._origin_mapped_data = arg_0._load_all_in_directory()


def Func(arg_0):
        """
        Stops monitoring the predefined directory.
        """
        with arg_0._status_lock:
            if arg_0._running:
                assert arg_0._observer is not None
                arg_0._observer.Func()
                arg_0._running = False
                arg_0._origin_mapped_data = dict()


def Func(arg_0, arg_1: arg_2):
        """
        Called when a file in the monitored directory has been moved.

        Breaks move down into a delete and a create (which it is sometimes detected as!).
        :param event: the file system event
        """
        if not arg_1.is_directory and arg_0.is_data_file(arg_1.src_path):
            arg_3 = FileSystemEvent(arg_1.src_path)
            arg_3.event_type = EVENT_TYPE_DELETED
            arg_0._on_file_deleted(arg_3)

            arg_5 = FileSystemEvent(arg_1.dest_path)
            arg_5.event_type = EVENT_TYPE_CREATED
            arg_0._on_file_created(arg_5)


def Func(arg_0=()):
    "List the contents of the archive directory."
    # strategy: pick the intersection of all the patterns the user provides
    arg_1 = ['*{0}*'.format(p) for p in arg_0] + ['*']

    arg_2 = []
    arg_3 = len(PROJ_ARCHIVE) + 1
    for arg_4 in arg_1:
        arg_5 = os.path.join(PROJ_ARCHIVE, '*', '*', arg_4)
        arg_2.append(set(
            arg_6[arg_3:] for arg_6 in glob.glob(arg_5)
        ))

    arg_2 = reduce(lambda x, y: x.intersection(y),
                     arg_2)

    for arg_7 in sorted(arg_2):
        print(arg_7)


def Func(arg_0):
    "Restore a project from the archive."
    if os.path.isdir(arg_0):
        bail('a folder of the same name already exists!')

    arg_1 = os.path.join(PROJ_ARCHIVE, '*', '*', arg_0)
    arg_2 = glob.glob(arg_1)
    if not arg_2:
        bail('no project matches: ' + arg_0)

    if len(arg_2) > 1:
        print('Warning: multiple matches, picking the most recent',
              file=sys.stderr)

    arg_3 = sorted(arg_2)[-1]
    print(arg_3, '-->', arg_0)
    shutil.move(arg_3, '.')


def Func(arg_0):
        """
        Tears down all temp files and directories.
        """
        while len(arg_0._temp_directories) > 0:
            arg_1 = arg_0._temp_directories.pop()
            shutil.rmtree(arg_1, ignore_errors=True)
        while len(arg_0._temp_files) > 0:
            arg_2 = arg_0._temp_files.pop()
            try:
                os.remove(arg_2)
            except OSError:
                pass


def Func(arg_0,
               arg_1=None,
               arg_2=None,
               arg_3=None,
               arg_4=None,
               arg_5=None,
               arg_6=None,
               arg_7=False,
               arg_8=False):
        """
        Copy this file to other place.
        """
        arg_0.assert_exists()

        arg_9 = arg_0.change(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
        )

        if arg_9.is_not_exist_or_allow_overwrite(arg_7=arg_7):
            # 如果两个路径不同, 才进行copy
            if arg_0.abspath != arg_9.abspath:
                try:
                    shutil.copy(arg_0.abspath, arg_9.abspath)
                except IOError as e:
                    if arg_8:
                        os.makedirs(arg_9.parent.abspath)
                        shutil.copy(arg_0.abspath, arg_9.abspath)
                    else:
                        raise e
        return arg_9


def Func(arg_0, arg_1):
        '''List the entities found directly under the given path.

        Args:
            path (str): The path of the entity to be Funced. Must start with a '/'.

        Returns:
            The Func of entity names directly under the given path:

                u'/12345/folder_1'

        Raises:
            StorageArgumentException: Invalid arguments
            StorageForbiddenException: Server response code 403
            StorageNotFoundException: Server response code 404
            StorageException: other 400-600 error codes
        '''

        arg_0.__validate_storage_path(arg_1)
        arg_2 = arg_0.api_client.get_entity_by_query(arg_1=arg_1)
        if arg_2['entity_type'] not in arg_0.__BROWSABLE_TYPES:
            raise StorageArgumentException('The entity type "{0}" cannot be'
                                           'Funced'.format(arg_2['entity_type']))
        arg_3 = arg_2['uuid']
        arg_4 = []

        # get files
        arg_5 = True
        arg_6 = 1
        while arg_5:
            arg_7 = arg_0.api_client.Func_folder_content(
                arg_3, page=arg_6, ordering='name')
            arg_5 = arg_7['next'] is not None
            arg_6 += 1
            for arg_8 in arg_7['results']:
                arg_9 = '/{name}' if arg_8['entity_type'] == 'folder' else '{name}'
                arg_4.append(arg_9.format(name=arg_8['name']))

        return arg_4


def Func(arg_0, arg_1, arg_2):
        '''Download a file from storage service to local disk.

        Existing files on the target path will be overwritten.
        The download is not recursive, as it only works on files.

        Args:
            path (str): The path of the entity to be downloaded. Must start with a '/'.

        Returns:
            None

        Raises:
            StorageArgumentException: Invalid arguments
            StorageForbiddenException: Server response code 403
            StorageNotFoundException: Server response code 404
            StorageException: other 400-600 error codes
        '''

        arg_0.__validate_storage_path(arg_1)
        arg_3 = arg_0.api_client.get_entity_by_query(arg_1=arg_1)
        if arg_3['entity_type'] != 'file':
            raise StorageArgumentException('Only file entities can be downloaded')

        arg_4 = arg_0.api_client.get_signed_url(arg_3['uuid'])
        arg_5 = arg_0.api_client.download_signed_url(arg_4)

        with open(arg_2, "wb") as output:
            for arg_6 in arg_5.iter_content(chunk_size=1024):
                output.write(arg_6)


def Func(arg_0, arg_1, arg_2, arg_3):
        '''Upload local file content to a storage service destination folder.

            Args:
                local_file(str)
                dest_path(str):
                    absolute Storage service path '/project' prefix is essential
                    suffix should be the name the file will have on in the destination folder
                    i.e.: /project/folder/.../file_name
                mimetype(str): set the contentType attribute

            Returns:
                The uuid of created file entity as string

            Raises:
                StorageArgumentException: Invalid arguments
                StorageForbiddenException: Server response code 403
                StorageNotFoundException: Server response code 404
                StorageException: other 400-600 error codes
        '''

        arg_0.__validate_storage_path(arg_2)
        # get the paths of the target dir and the target file name
        if arg_2.endswith('/'):
            raise StorageArgumentException('Must specify target file name in dest_path argument')
        if arg_1.endswith(os.path.sep):
            raise StorageArgumentException('Must specify source file name in local_file'
                                           ' argument, directory upload not supported')

        # create the file container
        arg_4 = arg_0.api_client.create_file(
            name=arg_2.split('/').pop(),
            content_type=arg_3,
            parent=arg_0.get_parent(arg_2)['uuid']
        )

        arg_5 = arg_0.api_client.Func_content(arg_4['uuid'], source=arg_1)
        arg_4['etag'] = arg_5

        return arg_4


def Func(arg_0, arg_1):
        ''' Delete an entity from the storage service using its path.

            Args:
                path(str): The path of the entity to be Func

            Returns:
                The uuid of created file entity as string

            Raises:
                StorageArgumentException: Invalid arguments
                StorageForbiddenException: Server response code 403
                StorageNotFoundException: Server response code 404
                StorageException: other 400-600 error codes
        '''

        arg_0.__validate_storage_path(arg_1, projects_allowed=False)

        arg_2 = arg_0.api_client.get_entity_by_query(arg_1=arg_1)

        if arg_2['entity_type'] in arg_0.__BROWSABLE_TYPES:
            # At this point it can only be a folder
            arg_3 = arg_0.api_client.list_folder_content(arg_2['uuid'])
            if arg_3['count'] > 0:
                raise StorageArgumentException(
                    'This method cannot Func non-empty folder. Please empty the folder first.')

            arg_0.api_client.Func_folder(arg_2['uuid'])
        elif arg_2['entity_type'] == 'file':
            arg_0.api_client.Func_file(arg_2['uuid'])


def Func() -> APIClient:
    """
    Clients a Docker client.

    Will raise a `ConnectionError` if the Docker daemon is not accessible.
    :return: the Docker client
    """
    global arg_2
    arg_0 = arg_2()
    if arg_0 is None:
        # First try looking at the environment variables for specification of the daemon's location
        arg_1 = kwargs_from_env(assert_hostname=False)
        if "base_url" in arg_1:
            arg_0 = _Func(arg_1.get("base_url"), arg_1.get("tls"))
            if arg_0 is None:
                raise ConnectionError(
                    "Could not connect to the Docker daemon specified by the `DOCKER_X` environment variables: %s"
                    % arg_1)
            else:
                logging.info("Connected to Docker daemon specified by the environment variables")
        else:
            # Let's see if the Docker daemon is accessible via the UNIX socket
            arg_0 = _Func("unix://var/run/docker.sock")
            if arg_0 is not None:
                logging.info("Connected to Docker daemon running on UNIX socket")
            else:
                raise ConnectionError(
                    "Cannot connect to Docker - is the Docker daemon running? `$DOCKER_HOST` should be set or the "
                    "daemon should be accessible via the standard UNIX socket.")
        arg_2 = weakref.ref(arg_0)
    assert isinstance(arg_0, APIClient)
    return arg_0


def Func(arg_0):
    """Decorate methods when repository path is required."""
    @wraps(arg_0)
    def wrapper(arg_1, *arg_2, **arg_3):
        if arg_1.path is None:
            warnings.warn('Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !')
            return
        return arg_0(arg_1, *arg_2, **arg_3)
    return wrapper


def Func(arg_0):
        """
        Get repository descriptive stats

        :Returns:
            #. numberOfDirectories (integer): Number of diretories in repository
            #. numberOfFiles (integer): Number of files in repository
        """
        if arg_0.__path is None:
            return 0,0
        arg_1 = 0
        arg_2  = 0
        for arg_3 in arg_0.get_repository_state():
            arg_4 = list(arg_3)[0]
            if arg_4 == '':
                continue
            if arg_3[arg_4].get('pyrepfileinfo', False):
                arg_1 += 1
            elif arg_3[arg_4].get('pyrepdirinfo', False):
                arg_2 += 1
            else:
                raise Exception('Not sure what to do next. Please report issue')
        return arg_2,arg_1


def Func(arg_0):
        """Reset repository instance.
        """
        arg_0.__path   = None
        arg_0.__repo   = {'repository_unique_name': str(uuid.uuid1()),
                         'create_utctime': time.time(),
                         'last_update_utctime': None,
                         'pyrep_version': str(__version__),
                         'repository_information': '',
                         'walk_repo': []}


def Func(arg_0, arg_1=None, arg_2=True):
        """
        Remove all repository from path along with all repository tracked files.

        :Parameters:
            #. path (None, string): The path the repository to remove.
            #. removeEmptyDirs (boolean): Whether to remove remaining empty
               directories.
        """
        assert isinstance(arg_2, bool), "removeEmptyDirs must be boolean"
        if arg_1 is not None:
            if arg_1 != arg_0.__path:
                arg_3 = Repository()
                arg_3.load_repository(arg_1)
            else:
                arg_3 = arg_0
        else:
            arg_3 = arg_0
        assert arg_3.path is not None, "path is not given and repository is not initialized"
        # remove repo files and directories
        for arg_4 in reversed(arg_3.get_repository_state()):
            arg_5   = list(arg_4)[0]
            arg_6   = os.path.join(arg_3.path, arg_5)
            arg_1, arg_7 = os.path.split(arg_6)
            if arg_4[arg_5]['type'] == 'file':
                if os.path.isfile(arg_6):
                    os.remove(arg_6)
                if os.path.isfile(os.path.join(arg_3.path,arg_1,arg_0.__fileInfo%arg_7)):
                    os.remove(os.path.join(arg_3.path,arg_1,arg_0.__fileInfo%arg_7))
                if os.path.isfile(os.path.join(arg_3.path,arg_1,arg_0.__fileLock%arg_7)):
                    os.remove(os.path.join(arg_3.path,arg_1,arg_0.__fileLock%arg_7))
                if os.path.isfile(os.path.join(arg_3.path,arg_1,arg_0.__fileClass%arg_7)):
                    os.remove(os.path.join(arg_3.path,arg_1,arg_0.__fileClass%arg_7))
            elif arg_4[arg_5]['type'] == 'dir':
                if os.path.isfile(os.path.join(arg_6,arg_0.__dirInfo)):
                    os.remove(os.path.join(arg_6,arg_0.__dirInfo))
                if os.path.isfile(os.path.join(arg_6,arg_0.__dirLock)):
                    os.remove(os.path.join(arg_6,arg_0.__dirLock))
                if not len(os.listdir(arg_6)) and arg_2:
                    shutil.rmtree( arg_6 )
        # remove repo information file
        if os.path.isfile(os.path.join(arg_3.path,arg_0.__repoFile)):
            os.remove(os.path.join(arg_3.path,arg_0.__repoFile))
        if os.path.isfile(os.path.join(arg_3.path,arg_0.__repoLock)):
            os.remove(os.path.join(arg_3.path,arg_0.__repoLock))


def Func(arg_0, arg_1):
        """
        Get whether creating a file or a directory from the basenane of the given
        path is allowed

        :Parameters:
            #. path (str): The absolute or relative path or simply the file
               or directory name.

        :Returns:
            #. allowed (bool): Whether name is allowed.
            #. message (None, str): Reason for the name to be forbidden.
        """
        assert isinstance(arg_1, basestring), "given path must be a string"
        arg_2 = os.path.basename(arg_1)
        if not len(arg_2):
            return False, "empty name is not allowed"
        # exact match
        for arg_3 in [arg_0.__repoLock,arg_0.__repoFile,arg_0.__dirInfo,arg_0.__dirLock]:
            if arg_2 == arg_3:
                return False, "name '%s' is reserved for pyrep internal usage"%arg_3
        # pattern match
        for arg_4 in [arg_0.__fileInfo,arg_0.__fileLock]:#,self.__objectDir]:
            if arg_2 == arg_4 or (arg_2.endswith(arg_4[3:]) and arg_2.startswith('.')):
                return False, "name pattern '%s' is not allowed as result may be reserved for pyrep internal usage"%arg_4
        # name is ok
        return True, None


def Func(arg_0, arg_1, arg_2=False):
        """
        Given a path, return relative path to diretory

        :Parameters:
            #. path (str): Path as a string
            #. split (boolean): Whether to split path to its components

        :Returns:
            #. relativePath (str, list): Relative path as a string or as a list
               of components if split is True
        """
        arg_1 = os.path.normpath(arg_1)
        if arg_1 == '.':
            arg_1 = ''
        arg_1 = arg_1.split(arg_0.__path)[-1].strip(os.sep)
        if arg_2:
            return arg_1.split(os.sep)
        else:
            return arg_1


def Func(arg_0, arg_1):
        """
        Check whether a given relative path is a repository file path

        :Parameters:
            #. relativePath (string): File relative path

        :Returns:
            #. isRepoFile (boolean): Whether file is a repository file.
            #. isFileOnDisk (boolean): Whether file is found on disk.
            #. isFileInfoOnDisk (boolean): Whether file info is found on disk.
            #. isFileClassOnDisk (boolean): Whether file class is found on disk.
        """
        arg_1  = arg_0.to_repo_relative_path(path=arg_1, split=False)
        if arg_1 == '':
            return False, False, False, False
        arg_2, arg_3 = os.path.split(arg_1)
        arg_4    = os.path.isfile(os.path.join(arg_0.__path, arg_1))
        arg_5    = os.path.isfile(os.path.join(arg_0.__path,os.path.dirname(arg_1),arg_0.__fileInfo%arg_3))
        arg_6   = os.path.isfile(os.path.join(arg_0.__path,os.path.dirname(arg_1),arg_0.__fileClass%arg_3))
        arg_7          = arg_0.__repo['walk_repo']
        if len(arg_2):
            for arg_8 in arg_2.split(os.sep):
                arg_9 = [d for d in arg_7 if isinstance(d, dict)]
                if not len(arg_9):
                    arg_7 = None
                    break
                arg_10 = [d for d in arg_9 if arg_8 in d]
                if not len(arg_10):
                    arg_7 = None
                    break
                arg_7 = arg_10[0][arg_8]
        if arg_7 is None:
            return False, arg_4, arg_5, arg_6
        #if name not in cDir:
        if str(arg_3) not in [str(arg_11) for arg_11 in arg_7]:
            return False, arg_4, arg_5, arg_6
        # this is a repository registered file. check whether all is on disk
        return True, arg_4, arg_5, arg_6


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """
        Create a tar file package of all the repository files and directories.
        Only files and directories that are tracked in the repository
        are stored in the package tar file.

        **N.B. On some systems packaging requires root permissions.**

        :Parameters:
            #. path (None, string): The real absolute path where to create the
               package. If None, it will be created in the same directory as
               the repository. If '.' or an empty string is passed, the current
               working directory will be used.
            #. name (None, string): The name to give to the package file
               If None, the package directory name will be used with the
               appropriate extension added.
            #. mode (None, string): The writing mode of the tarfile.
               If None, automatically the best compression mode will be chose.
               Available modes are ('w', 'w:', 'w:gz', 'w:bz2')
        """
        # check mode
        assert arg_3 in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(arg_3)
        if arg_3 is None:
            #mode = 'w:bz2'
            arg_3 = 'w:'
        # get root
        if arg_1 is None:
            arg_4 = os.path.split(arg_0.__path)[0]
        elif arg_1.strip() in ('','.'):
            arg_4 = os.getcwd()
        else:
            arg_4 = os.path.realpath( os.path.expanduser(arg_1) )
        assert os.path.isdir(arg_4), 'absolute path %s is not a valid directory'%arg_1
        # get name
        if arg_2 is None:
            arg_5 = arg_3.split(":")
            if len(arg_5) == 2:
                if len(arg_5[1]):
                    arg_5 = "."+arg_5[1]
                else:
                    arg_5 = '.tar'
            else:
                arg_5 = '.tar'
            arg_2 = os.path.split(arg_0.__path)[1]+arg_5
        # create tar file
        arg_6 = os.path.join(arg_4, arg_2)
        try:
            arg_7 = tarfile.TarFile.open(arg_6, arg_3=arg_3)
        except Exception as e:
            raise Exception("Unable to create package (%s)"%e)
        # walk directory and create empty directories
        for arg_8 in sorted(list(arg_0.walk_directories_path(recursive=True))):
            arg_9 = tarfile.TarInfo( arg_8 )
            arg_9.type = tarfile.DIRTYPE
            arg_7.addfile(arg_9)
            arg_7.add(os.path.join(arg_0.__path,arg_8,arg_0.__dirInfo), arcname=arg_0.__dirInfo)
        # walk files and add to tar
        for arg_11 in arg_0.walk_files_path(recursive=True):
            arg_12, arg_13 = os.path.split(arg_11)
            arg_7.add(os.path.join(arg_0.__path,arg_11), arcname=arg_13)
            arg_7.add(os.path.join(arg_0.__path,arg_12,arg_0.__fileInfo%arg_13), arcname=arg_0.__fileInfo%arg_13)
            arg_7.add(os.path.join(arg_0.__path,arg_12,arg_0.__fileClass%arg_13), arcname=arg_0.__fileClass%arg_13)
        # save repository .pyrepinfo
        arg_7.add(os.path.join(arg_0.__path,arg_0.__repoFile), arcname=".pyrepinfo")
        # close tar file
        arg_7.close()


def Func(arg_0, arg_1, arg_2='prod'):
        '''Creates a Func cross-service client.'''

        return arg_0(
            storage_client=StorageClient.Func(arg_1, arg_2=arg_2))


def Func(arg_0, arg_1: arg_2, arg_3: arg_2):
        """
        Renames an item in this collection as a transaction.

        Will override if new key name already exists.
        :param key: the current name of the item
        :param new_key: the new name that the item should have
        """
        if arg_3 == arg_1:
            return

        arg_4 = [arg_0._key_locks[arg_1], arg_0._key_locks[arg_3]]
        arg_5 = sorted(arg_4, arg_1=lambda x: id(x))
        for arg_6 in arg_5:
            arg_6.acquire()

        try:
            if arg_1 not in arg_0._data:
                raise KeyError("Attribute to Func \"%s\" does not exist" % arg_1)
            arg_0._data[arg_3] = arg_0[arg_1]
            del arg_0._data[arg_1]
        finally:
            for arg_6 in arg_4:
                arg_6.release()


def Func(arg_0, arg_1, arg_2="utf-8"):  # pragma: no cover
    """
    Use default hash method to return hash value of a piece of string
    default setting use 'utf-8' encoding.
    """
    arg_3 = arg_1()
    arg_3.update(arg_0.encode(arg_2))
    return arg_3.hexdigest()


def Func(arg_0, arg_1=0, arg_2=arg_3):
    """
    Return md5 hash value of a piece of a file

    Estimate processing time on:

    :param abspath: the absolute path to the file
    :param nbytes: only has first N bytes of the file. if 0 or None,
      hash all file

    CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB
    1 second can process 0.25GB data

    - 0.59G - 2.43 sec
    - 1.3G - 5.68 sec
    - 1.9G - 7.72 sec
    - 2.5G - 10.32 sec
    - 3.9G - 16.0 sec
    """
    return get_file_fingerprint(arg_0, hashlib.md5, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1=0, arg_2=arg_3):
    """
    Return sha256 hash value of a piece of a file

    Estimate processing time on:

    :param abspath: the absolute path to the file
    :param nbytes: only has first N bytes of the file. if 0 or None,
      hash all file
    """
    return get_file_fingerprint(arg_0, hashlib.sha256, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):  # pragma: no cover
        """
        Create a new folder having exactly same structure with this directory.
        However, all files are just empty file with same file name.

        :param dst: destination directory. The directory can't exists before
        you execute this.

        **中文文档**

        创建一个目录的镜像拷贝, 与拷贝操作不同的是, 文件的副本只是在文件名上
        与原件一致, 但是是空文件, 完全没有内容, 文件大小为0。
        """
        arg_0.assert_is_dir_and_exists()

        arg_2 = arg_0.abspath
        arg_1 = os.path.abspath(arg_1)
        if os.path.exists(arg_1):  # pragma: no cover
            raise Exception("distination already exist!")

        arg_3 = list()
        arg_4 = list()

        for arg_5, arg_6, arg_7 in os.walk(arg_0.abspath):
            arg_5 = arg_5.replace(arg_2, arg_1)
            try:
                os.mkdir(arg_5)
            except:  # pragma: no cover
                pass
            for arg_8 in arg_7:
                arg_9 = os.path.join(arg_5, arg_8)
                with open(arg_9, "wb") as arg_6:
                    pass


def Func(arg_0, arg_1=None):  # pragma: no cover
        """
        Execute every ``.py`` file as main script.

        :param py_exe: str, python command or python executable path.

        **中文文档**

        将目录下的所有Python文件作为主脚本用当前解释器运行。
        """
        import subprocess

        arg_0.assert_is_dir_and_exists()

        if arg_1 is None:
            if six.PY2:
                arg_1 = "python2"
            elif six.PY3:
                arg_1 = "python3"

        for arg_2 in arg_0.select_by_ext(".py"):
            subprocess.Popen('%s "%s"' % (arg_1, arg_2.abspath))


def Func(arg_0, arg_1=lambda arg_2: arg_2.ext == ".py"):  # pragma: no cover
        """
        Trail white space at end of each line for every ``.py`` file.

        **中文文档**

        将目录下的所有被选择的文件中行末的空格删除。
        """
        arg_0.assert_is_dir_and_exists()

        for arg_2 in arg_0.select_file(arg_1):
            try:
                with open(arg_2.abspath, "rb") as f:
                    arg_4 = list()
                    for arg_5 in f:
                        arg_4.append(arg_5.decode("utf-8").rstrip())

                with open(arg_2.abspath, "wb") as f:
                    f.write("\n".join(arg_4).encode("utf-8"))

            except Exception as e:  # pragma: no cover
                raise e


def Func(arg_0, **arg_1):  # pragma: no cover
        """
        Auto convert your python code in a directory to pep8 styled code.

        :param kwargs: arguments for ``Func.fix_code`` method.

        **中文文档**

        将目录下的所有Python文件用pep8风格格式化。增加其可读性和规范性。
        """
        arg_0.assert_is_dir_and_exists()

        for arg_2 in arg_0.select_by_ext(".py"):
            with open(arg_2.abspath, "rb") as f:
                arg_3 = f.read().decode("utf-8")

            arg_4 = Func.fix_code(arg_3, **arg_1)

            with open(arg_2.abspath, "wb") as f:
                f.write(arg_4.encode("utf-8"))


def Func(arg_0):
        """
        Get most recent modify time in timestamp.
        """
        try:
            return arg_0._stat.st_Func
        except:  # pragma: no cover
            arg_0._stat = arg_0.stat()
            return arg_0.Func


def Func(arg_0):
        """
        Get most recent access time in timestamp.
        """
        try:
            return arg_0._stat.st_Func
        except:  # pragma: no cover
            arg_0._stat = arg_0.stat()
            return arg_0.Func


def Func(arg_0):
        """
        Get most recent create time in timestamp.
        """
        try:
            return arg_0._stat.st_Func
        except:  # pragma: no cover
            arg_0._stat = arg_0.stat()
            return arg_0.Func


def Func(arg_0, arg_1, arg_2='prod'):
        '''Create a Func storage service REST client.

            Arguments:
                environment: The service environment to be used for the client
                access_token: The access token used to authenticate with the
                    service

            Returns:
                A storage_service.api.ApiClient instance

            Example:
                >>> storage_client = ApiClient.Func(my_access_token)

        '''
        arg_3 = RequestBuilder \
            .request(arg_2) \
            .to_service(arg_0.SERVICE_NAME, arg_0.SERVICE_VERSION) \
            .throw(
                StorageForbiddenException,
                lambda resp: 'You are forbidden to do this.'
                if resp.status_code == 403 else None
            ) \
            .throw(
                StorageNotFoundException,
                lambda resp: 'The entity is not found'
                if resp.status_code == 404 else None
            ) \
            .throw(
                StorageException,
                lambda resp: 'Server response: {0} - {1}'.format(resp.status_code, resp.text)
                if not resp.ok else None
            )

        arg_4 = arg_3.with_token(arg_1)

        return arg_0(arg_3, arg_4)