become_daemon function wrapper

    In Django 1.9, 'become_daemon' is removed.
    It means compatibility.
15122
def become_daemon(*args, **kwargs):
    
    if django.VERSION >= (1, 9):
        from .daemonize import become_daemon
    else:
        from django.utils.daemonize import become_daemon
    return become_daemon(*args, **kwargs)
1373599
def daemon(args):
    
    if os.environ.get(DVC_DAEMON):
        logger.debug("skipping launching a new daemon.")
        return

    cmd = [sys.executable]
    if not is_binary():
        cmd += ["-m", "dvc"]
    cmd += ["daemon", "-q"] + args

    env = fix_env()
    file_path = os.path.abspath(inspect.stack()[0][1])
    env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2(
        os.path.dirname(os.path.dirname(file_path))
    )
    env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1")

    _spawn(cmd, env)
940193
def django_api(
            self,
            name,
            introduced_at,
            undocumented=False,
            deprecated_at=None,
            title=None,
            **options):
        
        from acceptable.djangoutil import DjangoAPI
        location = get_callsite_location()
        api = DjangoAPI(
            self,
            name,
            introduced_at,
            options,
            location=location,
            undocumented=undocumented,
            deprecated_at=deprecated_at,
            title=title,
        )
        self.metadata.register_api(self.name, self.group, api)
        return api
123650
function checkEnv() {
        async.series([
            function(cb) {
                childProcess.exec(
                    'python -c "import django; print(django.get_version())"',
                    function(err, version) {
                        if (err || !/^1\.7/.test(version)) {
                            return cb(new Error(
                                'Django 1.7 environment is not working'
                            ));
                        }
                        cb();
                    });
            }
        ], function(err) {
            if (err) {
                console.error(chalk.red('\nFATAL: ' + err.message +
                    '\n'));
            }
        });
    }
485160
def daemonize(pidfile=None):
    

    # Prevent core dumps
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))

    # Change working directory
    os.chdir("/")

    # Change file creation mask
    os.umask(0)

    # Detach process context: do double fork
    pid = os.fork()
    if pid > 0:
        os._exit(0)
    os.setsid()
    pid = os.fork()
    if pid > 0:
        os._exit(0)

    # Create signal handler for SIGTERM
    def terminate(signal, stack_frame):
        msg = 'Terminating on signal {}'.format(signal)
        logger.info(msg)
        raise SystemExit(msg)
    signal.signal(signal.SIGTERM, terminate)

    # Redirect input/output streams
    streams = [sys.stdin, sys.stdout, sys.stderr]
    for stream in streams:
        devnull = os.open(os.devnull, os.O_RDWR)
        os.dup2(devnull, stream.fileno())

    # Close file descriptors
    for fd in [stream.fileno() for stream in streams]:
        try:
            os.close(fd)
        except OSError as err:
            if err.errno == errno.EBADF:
                # File descriptor was not open
                pass

    # Create pidfile
    if pidfile is None or pidfile.strip() == '':
        logger.debug('Empty pidfile set')
    else:
        pid = os.getpid()
        try:
            with open(pidfile, 'w') as f:
                f.write('{}\n'.format(pid))
                f.close()
        except EnvironmentError:
            logger.error('Failed to create pidfile at {}'.format(pidfile))

        def remove_pid_file():
            os.remove(pidfile)

        atexit.register(remove_pid_file)

    logger.debug('Process daemonized')
1109503
def replaced_by_django_migrations(func, *args, **kwargs):
    """"""

    DjangoSettings()  # trigger helpful messages if Django is missing

    import django
    if django.VERSION >= (1, 7):
        print("Django 1.7+ has its own migrations system.")
        print("Use this instead: `invoke managepy makemigrations`")
        sys.exit(1)
    return func(*args, **kwargs)
1211556
def register_dispatch_wrapper(wrapper):
    

    signature = inspect.getargspec(wrapper)
    if any([len(signature.args) != 1,
            signature.varargs is None,
            signature.keywords is None]):
        raise TypeError("Wrapper signature mismatch")

    def _wrapper(func, *args, **kwargs):
        """Exception handling"""
        try:
            return wrapper(func, *args, **kwargs)
        except Exception as e:
            # Kill subprocess
            _state["currentServer"].stop()
            traceback.print_exc()
            raise e

    _state["dispatchWrapper"] = _wrapper
251420
def deprecated(new_name: str):
    
    def decorator(func):
        @wraps(func)
        def new_func(*args, **kwargs):
            warnings.simplefilter('always', DeprecationWarning)  # turn off filter
            warnings.warn(
                'Use {0} instead of {1}, {1} will be removed in the future.'
                .format(new_name, func.__name__),
                category=DeprecationWarning,
                stacklevel=2,
            )
            warnings.simplefilter('default', DeprecationWarning)  # reset filter
            return func(*args, **kwargs)
        setattr(new_func, '__deprecated', True)
        return new_func
    return decorator
624617
def api(self):
        
        functions = [x[0]for x in inspect.getmembers(self, predicate=inspect.ismethod)
                     if not x[0].startswith('_')]

        full_api = {
            'doc': u"When posting data you have to use the JSON format.",
            'api': []
        }
        my_daemon_type = "%s" % getattr(self.app, 'type', 'unknown')
        my_address = getattr(self.app, 'host_name', getattr(self.app, 'name', 'unknown'))
        if getattr(self.app, 'address', '127.0.0.1') not in ['127.0.0.1']:
            # If an address is explicitely specified, I must use it!
            my_address = self.app.address
        for fun in functions:
            endpoint = {
                'daemon': my_daemon_type,
                'name': fun,
                'doc': getattr(self, fun).__doc__,
                'uri': '%s://%s:%s/%s' % (getattr(self.app, 'scheme', 'http'),
                                          my_address,
                                          self.app.port, fun),
                'args': {}
            }

            try:
                spec = inspect.getfullargspec(getattr(self, fun))
            except Exception:  # pylint: disable=broad-except
                # pylint: disable=deprecated-method
                spec = inspect.getargspec(getattr(self, fun))
            args = [a for a in spec.args if a not in ('self', 'cls')]
            if spec.defaults:
                a_dict = dict(list(zip(args, spec.defaults)))
            else:
                a_dict = dict(list(zip(args, ("No default value",) * len(args))))

            endpoint["args"] = a_dict
            full_api['api'].append(endpoint)

        return full_api
585149
def obsolete_client(func):
    """"""

    @functools.wraps(func)
    def new_func(*args, **kwargs):
        raise ObsoleteException(
            "{} has been removed from this version of the library. "
            "Please refer to current documentation for guidance."
            .format(func.__name__)
        )

    return new_func
423221
def on(self, type):
        ''''''
        def decorator(self, func):
            '''decorated functions should be written as class methods
                @on('join')
                def on_join(self, channel):
                    print("Joined channel %s" % channel)
            '''
            self._handlers[type].append(func)
            return func

        return decorator
1062775
def deprecated(version, *replacement):
    

    def deprecated_wrapper(func):
        replacement_message = 'Use {} instead'.format(', '.join(
            ["'{}'".format(_get_func_fq_name(x))
             for x in replacement]))
        log_message = ("'{}' is deprecated, {}"
                       "".format(_get_func_fq_name(func), replacement_message))
        # func.__doc__ = replacement[0].__doc__

        func_path = _get_func_path(func)
        doc_replacement = []
        for x in replacement:
            if func_path == _get_func_path(x):
                doc_replacement.append(':func:`{}`'.format(_func_name(x)))
            else:
                doc_replacement.append(
                    ':func:`{}`'.format(_get_func_fq_name(x)))

        func.__doc__ = """
            .. deprecated:: {}
               Use {} instead
               
               {} 
            """.format(version,
                       ', '.join(doc_replacement),
                       func.__doc__ if func.__doc__ else '')

        @wraps(func)
        def wrapper(*args, **kwargs):
            log.warning(log_message)
            return func(*args, **kwargs)

        return wrapper

    return deprecated_wrapper
1366039
def _enable_cleanup(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        result = func(*args, **kwargs)
        self.cleanup(self)
        return result

    return wrapper
421175
def main():
    
    try:
        args = parse_daemon_args()
        daemon = Alignak(**args.__dict__)
        daemon.main()
    except Exception as exp:  # pylint: disable=broad-except
        sys.stderr.write("*** Daemon exited because: %s" % str(exp))
        traceback.print_exc()
        exit(1)
568800
def takes_instance_or_queryset(func):
    """"""
    @wraps(func)
    def decorated_function(self, request, queryset):
        # func follows the prototype documented at:
        # https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions
        if not isinstance(queryset, QuerySet):
            try:
                # Django >=1.8
                queryset = self.get_queryset(request).filter(pk=queryset.pk)
            except AttributeError:
                try:
                    # Django >=1.6,<1.8
                    model = queryset._meta.model
                except AttributeError:  # pragma: no cover
                    # Django <1.6
                    model = queryset._meta.concrete_model
                queryset = model.objects.filter(pk=queryset.pk)
        return func(self, request, queryset)
    return decorated_function
1190026
def deprecated(func, msg=None):
    

    message = msg or "Use of deprecated function '{}`.".format(func.__name__)

    @functools.wraps(func)
    def wrapper_func(*args, **kwargs):
        warnings.warn(message, DeprecationWarning, stacklevel=2)
        return func(*args, **kwargs)

    return wrapper_func
482829
def daemonize!
      if JRUBY
        # It's not a true daemon but when executed with & works like one
        thread = Thread.new {daemon_execute}
        thread.join

      elsif RUBY_VERSION < "1.9"
        logger.debug "Parent Process: #{Process.pid}"
        exit!(0) if fork
        logger.debug "Child Process: #{Process.pid}"
        daemon_execute

      else
        Process.daemon(true, true)
        daemon_execute
      end
    end