function for reading python imports with skulpt
549530
function builtinRead(x) {
        if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
          throw "File not found: '" + x + "'";
        return Sk.builtinFiles["files"][x];
      }
1283926
def find_imports(filename):
    
    with open(filename) as f:
        root = ast.parse(f.read(), filename)
    visitor = ImportFinder(filename)
    visitor.visit(root)
    return visitor.imports
794258
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData:
    
    # import pandas for conversion of a dict of dicts into a matrix
    # import gzip to read a gzipped file :-)
    import gzip
    from pandas import DataFrame

    dod = {}  # this will contain basically everything
    fh = gzip.open(fspath(filename))
    header = fh.readline()  # read the first line

    for line in fh:
        t = line.decode('ascii').split('\t')  # gzip read bytes, hence the decoding
        try:
            dod[t[1]].update({t[0]:int(t[2])})
        except KeyError:
            dod[t[1]] = {t[0]:int(t[2])}

    df = DataFrame.from_dict(dod, orient='index')  # build the matrix
    df.fillna(value=0., inplace=True)  # many NaN, replace with zeros
    return AnnData(np.array(df), {'obs_names': df.index}, {'var_names': df.columns}, dtype=dtype)
1021573
def _make_skel_func(code, cell_count, base_globals=None):
    
    if base_globals is None:
        base_globals = {}
    elif isinstance(base_globals, string_types):
        base_globals_name = base_globals
        try:
            # First try to reuse the globals from the module containing the
            # function. If it is not possible to retrieve it, fallback to an
            # empty dictionary.
            if importlib is not None:
                base_globals = vars(importlib.import_module(base_globals))
            elif sys.modules.get(base_globals, None) is not None:
                base_globals = vars(sys.modules[base_globals])
            else:
                raise ImportError
        except ImportError:
            base_globals = _dynamic_modules_globals.get(
                    base_globals_name, None)
            if base_globals is None:
                base_globals = _DynamicModuleFuncGlobals()
            _dynamic_modules_globals[base_globals_name] = base_globals

    base_globals['__builtins__'] = __builtins__

    closure = (
        tuple(_make_empty_cell() for _ in range(cell_count))
        if cell_count >= 0 else
        None
    )
    return types.FunctionType(code, base_globals, None, None, closure)
609578
def import_data(self):
        

        tasks_list = self.load_task_list()
        warnings.filterwarnings(
            'ignore', r'Warning: converting a masked element to nan.')
        # FIX
        warnings.filterwarnings('ignore', category=DeprecationWarning)

        # Delete all old (previously constructed) output files
        if self.args.delete_old:
            self.log.warning("Deleting all old entry files.")
            self.delete_old_entry_files()

        # In update mode, load all entry stubs.
        if self.args.load_stubs or self.args.update:
            self.load_stubs()

        if self.args.travis:
            self.log.warning("Running in `travis` mode.")

        prev_priority = 0
        prev_task_name = ''
        # for task, task_obj in tasks_list.items():
        for task_name, task_obj in tasks_list.items():
            if not task_obj.active:
                continue
            self.log.warning("Task: '{}'".format(task_name))

            nice_name = task_obj.nice_name
            mod_name = task_obj.module
            func_name = task_obj.function
            priority = task_obj.priority

            # Make sure things are running in the correct order
            if priority < prev_priority and priority > 0:
                raise RuntimeError("Priority for '{}': '{}', less than prev,"
                                   "'{}': '{}'.\n{}"
                                   .format(task_name, priority, prev_task_name,
                                           prev_priority, task_obj))

            self.log.debug("\t{}, {}, {}, {}".format(nice_name, priority,
                                                     mod_name, func_name))
            mod = importlib.import_module('.' + mod_name, package='astrocats')
            self.current_task = task_obj
            getattr(mod, func_name)(self)

            num_events, num_stubs = self.count()
            self.log.warning("Task finished.  Events: {},  Stubs: {}".format(
                num_events, num_stubs))
            self.journal_entries()
            num_events, num_stubs = self.count()
            self.log.warning("Journal finished.  Events: {}, Stubs: {}".format(
                num_events, num_stubs))

            prev_priority = priority
            prev_task_name = task_name

        process = psutil.Process(os.getpid())
        memory = process.memory_info().rss
        self.log.warning('Memory used (MBs): '
                         '{:,}'.format(memory / 1024. / 1024.))
        return
956174
def dynamic_import(import_string):
    
    # Use rfind rather than rsplit for Python 2.3 compatibility.
    lastdot = import_string.rfind('.')
    if lastdot == -1:
        return __import__(import_string, {}, {}, [])
    module_name, attr = import_string[:lastdot], import_string[lastdot + 1:]
    parent_module = __import__(module_name, {}, {}, [attr])
    return getattr(parent_module, attr)
1318134
def import_name(stref: str):
    
    h = stref
    p = []
    m = None
    try:
        r = importlib.util.find_spec(stref)
    except (AttributeError, ImportError):
        r = None

    if r is not None:
        return importlib.import_module(stref)

    while '.' in h:
        h, t = h.rsplit('.', 1)
        p.append(t)
        if h in sys.modules:
            m = sys.modules[h]
            break

    if m is None:
        m = importlib.import_module(h)

    for i in reversed(p):
        if hasattr(m, i):
            m = getattr(m, i)
        else:
            h += '.' + i
            m = importlib.import_module(h)

    logger.debug('Imported "%s" as %r', stref, m)
    return m
552657
def load_stdlib():
    '''
    '''
    if _stdlib:
        return _stdlib

    prefixes = tuple({os.path.abspath(p) for p in (
        sys.prefix,
        getattr(sys, 'real_prefix', sys.prefix),
        getattr(sys, 'base_prefix', sys.prefix),
    )})

    for sp in sys.path:
        if not sp:
            continue
        _import_paths.append(os.path.abspath(sp))

    stdpaths = tuple({p for p in _import_paths
                      if p.startswith(prefixes) and 'site-packages' not in p})

    _stdlib.update(sys.builtin_module_names)

    for stdpath in stdpaths:
        if not os.path.isdir(stdpath):
            continue

        for item in os.listdir(stdpath):
            if item.startswith('.') or item == 'site-packages':
                continue

            p = os.path.join(stdpath, item)
            if not os.path.isdir(p) and not item.endswith(('.py', '.so')):
                continue

            _stdlib.add(item.split('.', 1)[0])

    return _stdlib
478090
def import_from(name):
    
    obj = name
    if isinstance(name, str) and len(name):
        try:
            obj = locate(name)
            assert obj is not None
        except (AttributeError, TypeError, AssertionError, ErrorDuringImport):
            try:
                name = name.split(".")
                attr = name[-1]
                name = ".".join(name[:-1])
                mod = importlib.import_module(name)
                obj = getattr(mod, attr)
            except (SyntaxError, AttributeError, ImportError, ValueError):
                try:
                    name = name.split(".")
                    attr_sup = name[-1]
                    name = ".".join(name[:-1])
                    mod = importlib.import_module(name)
                    obj = getattr(getattr(mod, attr_sup), attr)
                except:
                    # We give up.
                    pass

    obj = unwrap_obj(obj)
    return obj
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
361652
def get_from_import(self, resource, name):
        """"""
        module_name = libutils.modname(resource)
        names = []
        if isinstance(name, list):
            names = [(imported, None) for imported in name]
        else:
            names = [(name, None), ]
        return FromImport(module_name, 0, tuple(names))
796134
def get_imports(self, ast_body):
        
        imports = []
        for node in ast_body:
            if isinstance(node, ast.Import):
                imports.extend({'target': name.name, 'lineno': node.lineno}
                               for name in node.names)
            elif isinstance(node, ast.ImportFrom):
                for name in node.names:
                    name = (
                        self.absolute_name(self.depth - node.level) + '.'
                        if node.level > 0 else ''
                    ) + (
                        node.module + '.' if node.module else ''
                    ) + name.name
                    imports.append({'target': name, 'lineno': node.lineno})
            elif isinstance(node, Module.RECURSIVE_NODES):
                imports.extend(self.get_imports(node.body))
                if isinstance(node, ast.Try):
                    imports.extend(self.get_imports(node.finalbody))
        return imports
1026836
def read_function(data, window, ij, g_args):
    """"""
    output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max()
    return output
206268
function getImports(sourceFile) {
    var imports = [];
    handleNode(sourceFile);

    function handleNode(node) {
        switch (node.kind) {
            case ts.SyntaxKind.ImportDeclaration:
                imports.push(node.moduleSpecifier.text);
                break;
            case ts.SyntaxKind.ImportEqualsDeclaration:
                imports.push(node.moduleReference.expression.text);
                break;
        }
        ts.forEachChild(node, handleNode);
    }
    return imports;
}
1170314
def runtime_import(object_path):
    """"""
    obj_module, obj_element = object_path.rsplit(".", 1)
    loader = __import__(obj_module, globals(), locals(), [str(obj_element)])
    return getattr(loader, obj_element)
344959
function formatSymbolExport(symbol, namespaces, imports) {
  const name = symbol.name;
  const parts = name.split('~');
  const isNamed = parts[0].indexOf('.') !== -1;
  const nsParts = parts[0].replace(/^module\:/, '').split(/[\/\.]/);
  const last = nsParts.length - 1;
  const importName = isNamed ?
    '_' + nsParts.slice(0, last).join('_') + '$' + nsParts[last] :
    '$' + nsParts.join('$');
  let line = nsParts[0];
  for (let i = 1, ii = nsParts.length; i < ii; ++i) {
    line += `.${nsParts[i]}`;
    namespaces[line] = (line in namespaces ? namespaces[line] : true) && i < ii - 1;
  }
  line += ` = ${importName};`;
  imports[getImport(symbol, nsParts.pop())] = true;
  return line;
}
891346
def to_python(fname, *args):
    
    [node] = read(fname)
    return node_to_obj(node, fname, *args)