Evaluation of Python code with inspect information.
166446
async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter):
        

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
                        self.last_result = result

                        header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)

                        for name, res in all_inspections(result):
                            paginator.add_line(f"{name:16.16} :: {res}")

                        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                        await interface.send_to(ctx)
        finally:
            scope.clear_intersection(arg_dict)
166928
function inspect (s) {
  return s
    .replace(/\\/g, '\\\\')
    .replace(/\n/g, '\\n')
    .replace(/\t/g, '\\t')
    .replace(/"/g, '\\"')
    .replace(/\r/g, '\\r')
}
578265
def do_inspect(self, arg):
        
        if arg in self.curframe.f_locals:
            obj = self.curframe.f_locals[arg]
        elif arg in self.curframe.f_globals:
            obj = self.curframe.f_globals[arg]
        else:
            obj = WebPdb.null
        if obj is not WebPdb.null:
            self.console.writeline(
                '{0} = {1}:\n'.format(arg, type(obj))
            )
            for name, value in inspect.getmembers(obj):
                if not (name.startswith('__') and (name.endswith('__'))):
                    self.console.writeline('    {0}: {1}\n'.format(
                        name, self._get_repr(value, pretty=True, indent=8)
                    ))
        else:
            self.console.writeline(
                'NameError: name "{0}" is not defined\n'.format(arg)
            )
        self.console.flush()
447040
def _py_code_clean(lines, tab, executable):
    
    count = 0
    allparams = executable.ordered_parameters
    if type(executable).__name__ == "Function":
        allparams = allparams + [executable]
        
    for p in allparams:
        value = _py_clean(p, tab)
        if value is not None:
            count += 1
            lines.append(value)
            
    return count
677712
function inspect(options){
   options = normalize(options);

   return function(files, metalsmith, done) {

      if (options.disable)
      return done();

      //try {
         var bigJSObject = {};

         if (options.includeMetalsmith) {
            bigJSObject[options.includeMetalsmith] = metalsmith.metadata();
         }

         Object.keys(files).forEach(function(filePath){
            var inData = files[filePath];

            if (options.fileFilter(filePath, inData, metalsmith)) {
               var outData = {};
               Object.keys(inData).forEach(function(key) {
                  if (options.accept(key, inData)) {
                     outData[key] = inData[key];
                  }
               });

               if (!options.contentsAsBuffer && outData.contents)
               outData.contents = inData.contents.toString();

               bigJSObject[filePath] = outData;
            }

         });

         options.printfn(bigJSObject);
         done();

   //   }
   //   catch (err) {
   //      done(err);
   //   }
  };

/**
 * Normalize an `options` dictionary.
 *
 * @param {Object} options
 */

 function normalize(options){
    options = options || {};

    options.printfn = options.printfn || function(obj) {
      console.dir(obj, {colors: true});
    };

   if (!options.accept) {
      if (options.include) {
         options.accept = function(propKey) { return options.include.indexOf(propKey) >= 0; };
      }
      else if (options.exclude){
         options.accept = function(propKey) { return options.exclude.indexOf(propKey) < 0; };
      }
      else {
         options.accept = function() { return true; };
      }
   }

   options.fileFilter = fileFilter(options.filter);

   return options;
};


/* calculate file filter function */
function fileFilter(filter) {
  if (filter) {
     if (typeof filter === 'string') {
        var regex = new RegExp(filter);
        return function(filePath) { return regex.test(filePath); }
     }
     else if (filter instanceof RegExp)
        return function(filePath) { return filter.test(filePath); }
     else {   // must be a function itself
        return filter;
     }
   }
   else  // none, return "pass all"
      return function() { return true; };
}



}
792124
def get_code(self, *args, **kwargs):
    
    # FIXME: Honestly should allow multiple commands
    callback = self._commands[args[0]]
    # TODO: syntax color would be nice
    source = _inspect.getsourcelines(callback)[0]
    """
    source_len = len(source)
    source = PygmentsLexer(CythonLexer).lex_document(source)()
    """
    # FIXME: formatting sucks
    return "\n" + "".join(source)
1158890
def inspect(object):
    
    for k in dir(object):
        try:
            details = getattr(object, k)
        except Exception as e:
            details = e

        try:
            details = str(details)
        except Exception as e:
            details = e

        print("{}: {}".format(k, details), file=sys.stderr)
761427
public static function inspect()
	{
		$backtrace = debug_backtrace();

		// If being called from within, show the file above in the backtrack
		if (strpos($backtrace[0]['file'], 'core/classes/debug.php') !== false)
		{
			$callee = $backtrace[1];
			$label = \Inflector::humanize($backtrace[1]['function']);
		}
		else
		{
			$callee = $backtrace[0];
			$label = 'Debug';
		}

		$arguments = func_get_args();
		$total_arguments = count($arguments);

		$callee['file'] = \Fuel::clean_path($callee['file']);

		if ( ! static::$js_displayed)
		{
			echo <<<JS
<script type="text/javascript">function fuel_debug_toggle(a){if(document.getElementById){if(document.getElementById(a).style.display=="none"){document.getElementById(a).style.display="block"}else{document.getElementById(a).style.display="none"}}else{if(document.layers){if(document.id.display=="none"){document.id.display="block"}else{document.id.display="none"}}else{if(document.all.id.style.display=="none"){document.all.id.style.display="block"}else{document.all.id.style.display="none"}}}};</script>
JS;
			static::$js_displayed = true;
		}
		echo '<div class="fuelphp-inspect" style="font-size: 13px;background: #EEE !important; border:1px solid #666; color: #000 !important; padding:10px;">';
		echo '<h1 style="border-bottom: 1px solid #CCC; padding: 0 0 5px 0; margin: 0 0 5px 0; font: bold 120% sans-serif;">'.$callee['file'].' @ line: '.$callee['line'].'</h1>';
		echo '<pre style="overflow:auto;font-size:100%;">';
		$i = 0;
		foreach ($arguments as $argument)
		{
			echo '<strong>'.$label.' #'.(++$i).' of '.$total_arguments.'</strong>:<br />';
				echo static::format('...', $argument);
			echo '<br />';
		}

		echo "</pre>";
		echo "</div>";
	}
954661
def erlang_inspect(raw = false)
      result = 'fun '
      result << Erlang.inspect(@mod, raw: raw)
      result << ':'
      result << Erlang.inspect(@function, raw: raw)
      result << '/'
      result << Erlang.inspect(@arity, raw: raw)
      return result
    end
140243
def fixcode(**kwargs):
    
    # repository direcotry
    repo_dir = Path(__file__).parent.absolute()

    # source code directory
    source_dir = Path(repo_dir, package.__name__)

    if source_dir.exists():
        print("Source code locate at: '%s'." % source_dir)
        print("Auto pep8 all python file ...")
        source_dir.autopep8(**kwargs)
    else:
        print("Source code directory not found!")

    # unittest code directory
    unittest_dir = Path(repo_dir, "tests")
    if unittest_dir.exists():
        print("Unittest code locate at: '%s'." % unittest_dir)
        print("Auto pep8 all python file ...")
        unittest_dir.autopep8(**kwargs)
    else:
        print("Unittest code directory not found!")

    print("Complete!")
502635
def run(path, code=None, params=None, **meta):
        
        if 'ignore_decorators' in params:
            ignore_decorators = params['ignore_decorators']
        else:
            ignore_decorators = None
        check_source_args = (code, path, ignore_decorators) if THIRD_ARG else (code, path)
        return [{
            'lnum': e.line,
            # Remove colon after error code ("D403: ..." => "D403 ...").
            'text': (e.message[0:4] + e.message[5:]
                     if e.message[4] == ':' else e.message),
            'type': 'D',
            'number': e.code
        } for e in PyDocChecker().check_source(*check_source_args)]
1171395
def eval_now(self, code):
        """"""
        result = eval(self.reformat(code))
        if result is None or isinstance(result, (bool, int, float, complex)):
            return repr(result)
        elif isinstance(result, bytes):
            return "b" + self.wrap_str_of(result)
        elif isinstance(result, str):
            return self.wrap_str_of(result)
        else:
            return None
956784
private void inspectGetters(Method method)
    {
        String methodName = method.getName();
        int prefixLength = 0;
        if (methodName.startsWith(GET_PREFIX)) {
            prefixLength = GET_PREFIX.length();
        }

        if (methodName.startsWith(IS_PREIX)) {
            prefixLength = IS_PREIX.length();
        }
        if(prefixLength == 0)
        {
            return;
        }

        String name = decapitalize(methodName.substring(prefixLength));
        if(!isValidProperty(name))
        {
            return;
        }

        // Check that the return type is not null or void
        Class propertyType = method.getReturnType();

        if (propertyType == null || propertyType == void.class)
        {
            return;
        }

        // isXXX return boolean
        if (prefixLength == 2)
        {
            if (!(propertyType == boolean.class))
            {
                return;
            }
        }

        // validate parameter types
        Class[] paramTypes = method.getParameterTypes();
        if (paramTypes.length > 1 ||
           (paramTypes.length == 1 && paramTypes[0] != int.class))
        {
            return;
        }

        if (!method.isAnnotationPresent(UriTransient.class) && !"class".equals(name))
        {
            Object value = getValue(method);

            if (method.isAnnotationPresent(VarName.class))
            {
                name = method.getAnnotation(VarName.class).value();
            }
            if (value != null)
            {
                pairs.put(name, value);
            }
        }
    }
375135
def get_selection_as_executable_code(self):
        """"""
        ls = self.get_line_separator()

        _indent = lambda line: len(line)-len(line.lstrip())

        line_from, line_to = self.get_selection_bounds()
        text = self.get_selected_text()
        if not text:
            return

        lines = text.split(ls)
        if len(lines) > 1:
            # Multiline selection -> eventually fixing indentation
            original_indent = _indent(self.get_text_line(line_from))
            text = (" "*(original_indent-_indent(lines[0])))+text

        # If there is a common indent to all lines, find it.
        # Moving from bottom line to top line ensures that blank
        # lines inherit the indent of the line *below* it,
        # which is the desired behavior.
        min_indent = 999
        current_indent = 0
        lines = text.split(ls)
        for i in range(len(lines)-1, -1, -1):
            line = lines[i]
            if line.strip():
                current_indent = _indent(line)
                min_indent = min(current_indent, min_indent)
            else:
                lines[i] = ' ' * current_indent
        if min_indent:
            lines = [line[min_indent:] for line in lines]

        # Remove any leading whitespace or comment lines
        # since they confuse the reserved word detector that follows below
        lines_removed = 0
        while lines:
            first_line = lines[0].lstrip()
            if first_line == '' or first_line[0] == '#':
                lines_removed += 1
                lines.pop(0)
            else:
                break

        # Add an EOL character after the last line of code so that it gets
        # evaluated automatically by the console and any quote characters
        # are separated from the triple quotes of runcell
        lines.append(ls)

        # Add removed lines back to have correct traceback line numbers
        leading_lines_str = ls * lines_removed

        return leading_lines_str + ls.join(lines)
685680
def qa(ctx):
    ''''''
    header(qa.__doc__)
    with ctx.cd(ROOT):
        info('Python Static Analysis')
        flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True)
        if flake8_results.failed:
            error('There is some lints to fix')
        else:
            success('No lint to fix')
        info('Ensure PyPI can render README and CHANGELOG')
        readme_results = ctx.run('python setup.py check -r -s', pty=True, warn=True, hide=True)
        if readme_results.failed:
            print(readme_results.stdout)
            error('README and/or CHANGELOG is not renderable by PyPI')
        else:
            success('README and CHANGELOG are renderable by PyPI')
    if flake8_results.failed or readme_results.failed:
        exit('Quality check failed', flake8_results.return_code or readme_results.return_code)
    success('Quality check OK')
1091134
def check(args, source_code, filename=None, options=None):
    """"""
    if args is None:
        return []
    if options is not None:
        args += options
    if any(['pyflakes' in arg for arg in args]):
        #  Pyflakes requires an ending new line (pycodestyle don't! -- see Issue 1123)
        #  Note: this code is not used right now as it is faster to invoke 
        #  pyflakes in current Python interpreter (see `check_with_pyflakes` 
        #  function above) than calling it through a subprocess
        source_code += '\n'
    if filename is None:
        # Creating a temporary file because file does not exist yet 
        # or is not up-to-date
        tempfd = tempfile.NamedTemporaryFile(suffix=".py", delete=False)
        tempfd.write(source_code)
        tempfd.close()
        args.append(tempfd.name)
    else:
        args.append(filename)
    cmd = args[0]
    cmdargs = args[1:]
    proc = programs.run_program(cmd, cmdargs)
    output = proc.communicate()[0].strip().decode().splitlines()
    if filename is None:
        os.unlink(tempfd.name)
    results = []
    coding = encoding.get_coding(source_code)
    lines = source_code.splitlines()
    for line in output:
        lineno = int(re.search(r'(\:[\d]+\:)', line).group()[1:-1])
        try:
            text = to_text_string(lines[lineno-1], coding)
        except TypeError:
            text = to_text_string(lines[lineno-1])
        except UnicodeDecodeError:
            # Needed to handle UnicodeDecodeError and force the use
            # of chardet to detect enconding. See issue 6970
            coding = encoding.get_coding(source_code, force_chardet=True)
            text = to_text_string(lines[lineno-1], coding)
        if 'analysis:ignore' not in text:
            message = line[line.find(': ')+2:]
            results.append((message, lineno))
    return results
1108368
def _gi_build_stub(parent):
    
    classes = {}
    functions = {}
    constants = {}
    methods = {}
    for name in dir(parent):
        if name.startswith("__"):
            continue

        # Check if this is a valid name in python
        if not re.match(_identifier_re, name):
            continue

        try:
            obj = getattr(parent, name)
        except:
            continue

        if inspect.isclass(obj):
            classes[name] = obj
        elif inspect.isfunction(obj) or inspect.isbuiltin(obj):
            functions[name] = obj
        elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj):
            methods[name] = obj
        elif (
            str(obj).startswith("<flags")
            or str(obj).startswith("<enum ")
            or str(obj).startswith("<GType ")
            or inspect.isdatadescriptor(obj)
        ):
            constants[name] = 0
        elif isinstance(obj, (int, str)):
            constants[name] = obj
        elif callable(obj):
            # Fall back to a function for anything callable
            functions[name] = obj
        else:
            # Assume everything else is some manner of constant
            constants[name] = 0

    ret = ""

    if constants:
        ret += "# %s constants\n\n" % parent.__name__
    for name in sorted(constants):
        if name[0].isdigit():
            # GDK has some busted constant names like
            # Gdk.EventType.2BUTTON_PRESS
            continue

        val = constants[name]

        strval = str(val)
        if isinstance(val, str):
            strval = '"%s"' % str(val).replace("\\", "\\\\")
        ret += "%s = %s\n" % (name, strval)

    if ret:
        ret += "\n\n"
    if functions:
        ret += "# %s functions\n\n" % parent.__name__
    for name in sorted(functions):
        ret += "def %s(*args, **kwargs):\n" % name
        ret += "    pass\n"

    if ret:
        ret += "\n\n"
    if methods:
        ret += "# %s methods\n\n" % parent.__name__
    for name in sorted(methods):
        ret += "def %s(self, *args, **kwargs):\n" % name
        ret += "    pass\n"

    if ret:
        ret += "\n\n"
    if classes:
        ret += "# %s classes\n\n" % parent.__name__
    for name, obj in sorted(classes.items()):
        base = "object"
        if issubclass(obj, Exception):
            base = "Exception"
        ret += "class %s(%s):\n" % (name, base)

        classret = _gi_build_stub(obj)
        if not classret:
            classret = "pass\n"

        for line in classret.splitlines():
            ret += "    " + line + "\n"
        ret += "\n"

    return ret