Call a C function and return its return value as a Python string.

    :param cfunc:   C function to call
    :param args:    Arguments to call function with
    :rtype:         str
163559
def get_string(cfunc, *args):
    
    cstr = get_ctype("const char**", cfunc, *args)
    return backend.ffi.string(cstr).decode() if cstr else None
36690
def WrapCFTypeInPython(self, obj):
    
    obj_type = self.dll.CFGetTypeID(obj)
    if obj_type == self.dll.CFBooleanGetTypeID():
      return CFBoolean(obj)
    elif obj_type == self.dll.CFNumberGetTypeID():
      return CFNumber(obj)
    elif obj_type == self.dll.CFStringGetTypeID():
      return CFString(obj)
    elif obj_type == self.dll.CFDictionaryGetTypeID():
      return CFDictionary(obj)
    elif obj_type == self.dll.CFArrayGetTypeID():
      return CFArray(obj)
    else:
      raise TypeError('Unknown type for object: {0}'.format(obj))
1177879
def exec_argparse_funckw(func, globals_=None, defaults={}, **kwargs):
    
    import utool as ut
    funckw = ut.get_func_kwargs(func)
    funckw.update(defaults)
    parsekw = ut.argparse_dict(funckw, **kwargs)
    if globals_:
        globals_.update(parsekw)
    return parsekw
1231757
def call(function):
    
    message = 'call:%s.%s' % (function.__module__,function.__name__)
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        _collect(message)
        return function(*args, **kwargs)

    return wrapper
670769
def cc_run (args):
    
    prog = b"int main(){}\n"
    pipe = subprocess.Popen(args,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
    pipe.communicate(input=prog)
    if os.WIFEXITED(pipe.returncode):
        return os.WEXITSTATUS(pipe.returncode) == 0
    return False
8750
def execstr_funckw(func):
    
    import utool as ut
    funckw = ut.get_func_kwargs(func)
    return ut.execstr_dict(funckw, explicit=True)
1259458
def perform_command(self):
        
        if len(self.actual_arguments) < 2:
            return self.print_help()
        input_file_path = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        output_text_format = self.has_option_with_value(u"--format")
        if output_text_format is None:
            output_text_format = u"%.18e"
        output_binary = self.has_option([u"-b", u"--binary"])
        output_npz = self.has_option([u"-z", u"--npz"])
        output_npy = self.has_option([u"-n", u"--npy"])
        delete_first = self.has_option([u"-d", u"--delete-first"])
        transpose = self.has_option([u"-t", u"--transpose"])

        self.check_c_extensions("cmfcc")
        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        try:
            mfccs = AudioFileMFCC(input_file_path, rconf=self.rconf, logger=self.logger).all_mfcc
            if delete_first:
                mfccs = mfccs[1:, :]
            if transpose:
                mfccs = mfccs.transpose()
            if output_binary:
                # save as a raw C float64 binary file
                mapped = numpy.memmap(output_file_path, dtype="float64", mode="w+", shape=mfccs.shape)
                mapped[:] = mfccs[:]
                mapped.flush()
                del mapped
            elif output_npz:
                # save as a .npz compressed binary file
                with io.open(output_file_path, "wb") as output_file:
                    numpy.savez(output_file, mfccs)
            elif output_npy:
                # save as a .npy binary file
                with io.open(output_file_path, "wb") as output_file:
                    numpy.save(output_file, mfccs)
            else:
                # save as a text file
                # NOTE: in Python 2, passing the fmt value a Unicode string crashes NumPy
                #       hence, converting back to bytes, which works in Python 3 too
                numpy.savetxt(output_file_path, mfccs, fmt=gf.safe_bytes(output_text_format))
            self.print_info(u"MFCCs shape: %d %d" % (mfccs.shape))
            self.print_success(u"MFCCs saved to '%s'" % (output_file_path))
            return self.NO_ERROR_EXIT_CODE
        except AudioFileConverterError:
            self.print_error(u"Unable to call the ffmpeg executable '%s'" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]))
            self.print_error(u"Make sure the path to ffmpeg is correct")
        except (AudioFileUnsupportedFormatError, AudioFileNotInitializedError):
            self.print_error(u"Cannot read file '%s'" % (input_file_path))
            self.print_error(u"Check that its format is supported by ffmpeg")
        except OSError:
            self.print_error(u"Cannot write file '%s'" % (output_file_path))

        return self.ERROR_EXIT_CODE
291465
def call(func, args):
    
    assert hasattr(func, '__call__'), 'Cannot call func: {}'.format(
        func.__name__)
    raw_func = (
        func if isinstance(func, FunctionType) else func.__class__.__call__)
    hints = collections.defaultdict(lambda: Any, get_type_hints(raw_func))
    argspec = _getargspec(raw_func)
    named_args = {}
    varargs = ()
    for k, nk, v in _normalize(args):
        if nk == argspec.varargs:
            hints[nk] = Tuple[hints[nk], ...]
        elif nk not in argspec.args and argspec.varkw in hints:
            hints[nk] = hints[argspec.varkw]
        try:
            value = cast(hints[nk], v)
        except TypeError as e:
            _LOGGER.exception(e)
            six.raise_from(exc.InvalidCliValueError(k, v), e)
        if nk == argspec.varargs:
            varargs = value
        elif (nk in argspec.args or argspec.varkw) and (
                nk not in named_args or named_args[nk] is None):
            named_args[nk] = value
    return func(*varargs, **named_args)
72619
def command(func):
    
    # pylint: disable=protected-access,unused-variable
    nargs = numargs(func)
    if nargs > 0:
        raise WrongNumberOfArguments(
            f'Decorated function "{func.__name__}" should have no arguments, it has {nargs}.'
        )
    app = func()
    if app is None:
        raise TypeError(
            'No `App` instance was returned. '
            'In the function decorated with @command, '
            'return the `App` instance so it can be built.'
        )
    if not isinstance(app, App):
        raise TypeError(
            f'Returned value {app} is of type {type(app)}, '
            'it needs to be a bowtie.App instance.'
        )

    @click.group(options_metavar='[--help]')
    def cmd():
        """Bowtie CLI to help build and run your app."""

    @cmd.command(add_help_option=False)
    def build():
        """Write the app, downloads the packages, and bundles it with Webpack."""
        app._build()

    @cmd.command(add_help_option=False)
    @click.option('--host', '-h', default='0.0.0.0', type=str)
    @click.option('--port', '-p', default=9991, type=int)
    def run(host, port):
        """Build the app and serve it."""
        app._build()
        app._serve(host, port)

    @cmd.command(add_help_option=True)
    @click.option('--host', '-h', default='0.0.0.0', type=str)
    @click.option('--port', '-p', default=9991, type=int)
    def serve(host, port):
        """Serve the Bowtie app."""
        app._serve(host, port)

    @cmd.command(context_settings=dict(ignore_unknown_options=True),
                 add_help_option=False)
    @click.argument('extra', nargs=-1, type=click.UNPROCESSED)
    def dev(extra):
        """Recompile the app for development."""
        line = (_WEBPACK, '--config', 'webpack.dev.js') + extra
        call(line, cwd=app._build_dir)

    @cmd.command(context_settings=dict(ignore_unknown_options=True),
                 add_help_option=False)
    @click.argument('extra', nargs=-1, type=click.UNPROCESSED)
    def prod(extra):
        """Recompile the app for production."""
        line = (_WEBPACK, '--config', 'webpack.prod.js', '--progress') + extra
        call(line, cwd=app._build_dir)

    locale = inspect.stack()[1][0].f_locals
    module = locale.get("__name__")

    if module == "__main__":
        try:
            arg = sys.argv[1:]
        except IndexError:
            arg = ('--help',)
        # pylint: disable=too-many-function-args
        sys.exit(cmd(arg))

    return cmd
450476
def perform_command(self):
        
        if len(self.actual_arguments) < 2:
            return self.print_help()
        audio_file_path = self.actual_arguments[0]
        mode = self.actual_arguments[1]
        if mode not in [u"speech", u"nonspeech", u"both"]:
            return self.print_help()
        output_file_path = None
        if len(self.actual_arguments) >= 3:
            output_file_path = self.actual_arguments[2]
        output_time = not self.has_option([u"-i", u"--index"])

        self.check_c_extensions("cmfcc")
        if not self.check_input_file(audio_file_path):
            return self.ERROR_EXIT_CODE
        if (output_file_path is not None) and (not self.check_output_file(output_file_path)):
            return self.ERROR_EXIT_CODE

        self.print_info(u"Reading audio...")
        try:
            audio_file_mfcc = AudioFileMFCC(audio_file_path, rconf=self.rconf, logger=self.logger)
        except AudioFileConverterError:
            self.print_error(u"Unable to call the ffmpeg executable '%s'" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]))
            self.print_error(u"Make sure the path to ffmpeg is correct")
            return self.ERROR_EXIT_CODE
        except (AudioFileUnsupportedFormatError, AudioFileNotInitializedError):
            self.print_error(u"Cannot read file '%s'" % (audio_file_path))
            self.print_error(u"Check that its format is supported by ffmpeg")
            return self.ERROR_EXIT_CODE
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while reading the audio file:")
            self.print_error(u"%s" % exc)
            return self.ERROR_EXIT_CODE
        self.print_info(u"Reading audio... done")

        self.print_info(u"Executing VAD...")
        audio_file_mfcc.run_vad()
        self.print_info(u"Executing VAD... done")

        speech = audio_file_mfcc.intervals(speech=True, time=output_time)
        nonspeech = audio_file_mfcc.intervals(speech=False, time=output_time)
        if mode == u"speech":
            if output_time:
                intervals = [(i.begin, i.end) for i in speech]
                template = u"%.3f\t%.3f"
            else:
                intervals = speech
                template = u"%d\t%d"
        elif mode == u"nonspeech":
            if output_time:
                intervals = [(i.begin, i.end) for i in nonspeech]
                template = u"%.3f\t%.3f"
            else:
                intervals = nonspeech
                template = u"%d\t%d"
        elif mode == u"both":
            if output_time:
                speech = [(i.begin, i.end, u"speech") for i in speech]
                nonspeech = [(i.begin, i.end, u"nonspeech") for i in nonspeech]
                template = u"%.3f\t%.3f\t%s"
            else:
                speech = [(i[0], i[1], u"speech") for i in speech]
                nonspeech = [(i[0], i[1], u"nonspeech") for i in nonspeech]
                template = u"%d\t%d\t%s"
            intervals = sorted(speech + nonspeech)
        self.write_to_file(output_file_path, intervals, template)

        return self.NO_ERROR_EXIT_CODE
837308
def log(fn):
    

    def func(*args, **kwargs):
        arg_string = ""
        for i in range(0, len(args)):
            var_name = fn.__code__.co_varnames[i]
            if var_name != "self":
                arg_string += var_name + ":" + str(args[i]) + ","
        arg_string = arg_string[0:len(arg_string) - 1]
        string = (RED + BOLD + '>> ' + END + 'Calling {0}({1})'.format(fn.__code__.co_name, arg_string))
        if len(kwargs):
            string = (RED + BOLD + '>> ' + END + 'Calling {0} with args {1} and kwargs {2}'.format(fn.__code__.co_name,
                                                                                                   arg_string, kwargs))
        print(string)
        result = fn(*args, **kwargs)
        string = BLUE + BOLD + '<< ' + END + 'Return {0} with result :{1}'.format(fn.__code__.co_name, result)
        print(string)
        return result

    return func
834624
def libvlc_vprinterr(fmt, ap):
    '''
    '''
    f = _Cfunctions.get('libvlc_vprinterr', None) or \
        _Cfunction('libvlc_vprinterr', ((1,), (1,),), None,
                    ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p)
    return f(fmt, ap)
1175038
def const_return(func):
    
    result = _undef

    def ret_call(*args, **kwargs):
        nonlocal result
        if result is _undef:
            result = func(*args, **kwargs)
        return result

    return ret_call
1241819
def make_c_args(arg_pairs):
    
    logging.debug(arg_pairs)
    c_args = [
        '{} {}'.format(arg_type, arg_name) if arg_name else arg_type
        for dummy_number, arg_type, arg_name in sorted(arg_pairs)
    ]
    return ', '.join(c_args)
284710
def wrap_python_function(cls, fn):
        
        def wrapped(sass_arg):
            # TODO enforce no units for trig?
            python_arg = sass_arg.value
            python_ret = fn(python_arg)
            sass_ret = cls(
                python_ret,
                unit_numer=sass_arg.unit_numer,
                unit_denom=sass_arg.unit_denom)
            return sass_ret

        return wrapped
1243309
def command(func_or_args=None):
    
    def decorator(f):
        f.__args__ = args
        return f
    if type(func_or_args) == type(decorator):
        args = {}
        return decorator(func_or_args)
    args = func_or_args
    return decorator
170977
def invoke(self, function_name, raw_python=False, command=None, no_color=False):
        

        # There are three likely scenarios for 'command' here:
        #   command, which is a modular function path
        #   raw_command, which is a string of python to execute directly
        #   manage, which is a Django-specific management command invocation
        key = command if command is not None else 'command'
        if raw_python:
            command = {'raw_command': function_name}
        else:
            command = {key: function_name}

        # Can't use hjson
        import json as json

        response = self.zappa.invoke_lambda_function(
            self.lambda_name,
            json.dumps(command),
            invocation_type='RequestResponse',
        )

        if 'LogResult' in response:
            if no_color:
                print(base64.b64decode(response['LogResult']))
            else:
                decoded = base64.b64decode(response['LogResult']).decode()
                formatted = self.format_invoke_command(decoded)
                colorized = self.colorize_invoke_command(formatted)
                print(colorized)
        else:
            print(response)

        # For a successful request FunctionError is not in response.
        # https://github.com/Miserlou/Zappa/pull/1254/
        if 'FunctionError' in response:
            raise ClickException(
                "{} error occurred while invoking command.".format(response['FunctionError'])
)