Parse the package __init__ file to find a variable so that it's not
    in multiple places.
196750
def read_init(key):
    
    filename = os.path.join("traces", "__init__.py")
    result = None
    with open(filename) as stream:
        for line in stream:
            if key in line:
                result = line.split('=')[-1].strip().replace("'", "")

    # throw error if version isn't in __init__ file
    if result is None:
        raise ValueError('must define %s in %s' % (key, filename))

    return result
1041775
def check_python_import(package_or_module):
    '''
    
    '''
    logger = logging.getLogger(__name__)
    logger.debug("Checking python import '%s'...", package_or_module)
    loader = pkgutil.get_loader(package_or_module)
    found = loader is not None
    if found:
        logger.debug("Python %s '%s' found",
                     "package" if loader.is_package(package_or_module)
                     else "module", package_or_module)
    else:  # pragma: no cover
        logger.debug("Python import '%s' not found", package_or_module)
    return found
955750
def _analyze_ini_file(self, add_header=False):
        
        def wrapped(file, filename):
            potential_secrets = {}

            with self.non_quoted_string_regex():
                for value, lineno in IniFileParser(
                    file,
                    add_header,
                    exclude_lines_regex=self.exclude_lines_regex,
                ).iterator():
                    potential_secrets.update(self.analyze_string(
                        value,
                        lineno,
                        filename,
                    ))

            return potential_secrets

        return wrapped
1212642
def infer_module_name(filename, fspath):
    """"""
    filename, _ = os.path.splitext(filename)
    for f in fspath:
        short_name = f.relative_path(filename)
        if short_name:
            # The module name for __init__.py files is the directory.
            if short_name.endswith(os.path.sep + "__init__"):
                short_name = short_name[:short_name.rfind(os.path.sep)]
            return short_name.replace(os.path.sep, '.')
    # We have not found filename relative to anywhere in pythonpath.
    return ''
271650
public void initializePackageContents() {
		if (isInitialized) return;
		isInitialized = true;

		// Initialize package
		setName(eNAME);
		setNsPrefix(eNS_PREFIX);
		setNsURI(eNS_URI);

		// Create type parameters

		// Set bounds for type parameters

		// Add supertypes to classes
		unknsfEClass.getESuperTypes().add(this.getSF());
		sfGrouperEClass.getESuperTypes().add(this.getSF());

		// Initialize classes and features; add operations and parameters
		initEClass(afpEClass, org.afplib.base.AFP.class, "AFP", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEReference(getAFP_StructuredFields(), this.getSF(), null, "structuredFields", null, 0, -1, org.afplib.base.AFP.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);

		initEClass(sfEClass, org.afplib.base.SF.class, "SF", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEAttribute(getSF_Number(), ecorePackage.getELong(), "number", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getSF_Offset(), ecorePackage.getELong(), "offset", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getSF_Id(), ecorePackage.getEInt(), "id", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getSF_Length(), ecorePackage.getEInt(), "length", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEReference(getSF_Children(), this.getSF(), null, "children", null, 0, -1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getSF_RawData(), ecorePackage.getEByteArray(), "rawData", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getSF_Charset(), this.getCharset(), "charset", null, 0, 1, org.afplib.base.SF.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);

		addEOperation(sfEClass, ecorePackage.getEBoolean(), "isBegin", 0, 1, IS_UNIQUE, IS_ORDERED);

		addEOperation(sfEClass, ecorePackage.getEBoolean(), "isEnd", 0, 1, IS_UNIQUE, IS_ORDERED);

		EOperation op = addEOperation(sfEClass, ecorePackage.getEBoolean(), "isDefault", 0, 1, IS_UNIQUE, IS_ORDERED);
		addEParameter(op, ecorePackage.getEString(), "value", 0, 1, IS_UNIQUE, IS_ORDERED);

		initEClass(unknsfEClass, org.afplib.base.UNKNSF.class, "UNKNSF", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);

		initEClass(sfGrouperEClass, SFGrouper.class, "SFGrouper", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);

		initEClass(tripletEClass, Triplet.class, "Triplet", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEAttribute(getTriplet_Label(), ecorePackage.getEString(), "label", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getTriplet_Charset(), this.getCharset(), "charset", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getTriplet_FileOffset(), ecorePackage.getELong(), "fileOffset", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getTriplet_TripletLength(), ecorePackage.getEInt(), "tripletLength", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getTriplet_TripletId(), ecorePackage.getEInt(), "tripletId", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getTriplet_TripletNumber(), ecorePackage.getEInt(), "tripletNumber", null, 0, 1, Triplet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);

		// Initialize data types
		initEDataType(modcaStringEDataType, String.class, "ModcaString", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
		initEDataType(modcaString4EDataType, String.class, "ModcaString4", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
		initEDataType(modcaString8EDataType, String.class, "ModcaString8", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
		initEDataType(modcaString32EDataType, String.class, "ModcaString32", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
		initEDataType(charsetEDataType, Charset.class, "Charset", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);

		// Create resource
		createResource(eNS_URI);

		// Create annotations
		// http:///org/eclipse/emf/ecore/util/ExtendedMetaData
		createExtendedMetaDataAnnotations();
	}
884735
public final void variableInitializer() throws RecognitionException {
		int variableInitializer_StartIndex = input.index();

		try {
			if ( state.backtracking>0 && alreadyParsedRule(input, 44) ) { return; }

			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:495:5: ( arrayInitializer | expression )
			int alt60=2;
			int LA60_0 = input.LA(1);
			if ( (LA60_0==121) ) {
				alt60=1;
			}
			else if ( ((LA60_0 >= CharacterLiteral && LA60_0 <= DecimalLiteral)||LA60_0==FloatingPointLiteral||(LA60_0 >= HexLiteral && LA60_0 <= Identifier)||(LA60_0 >= OctalLiteral && LA60_0 <= StringLiteral)||LA60_0==29||LA60_0==36||(LA60_0 >= 40 && LA60_0 <= 41)||(LA60_0 >= 44 && LA60_0 <= 45)||LA60_0==53||LA60_0==65||LA60_0==67||(LA60_0 >= 70 && LA60_0 <= 71)||LA60_0==77||(LA60_0 >= 79 && LA60_0 <= 80)||LA60_0==82||LA60_0==85||LA60_0==92||LA60_0==94||(LA60_0 >= 97 && LA60_0 <= 98)||LA60_0==105||LA60_0==108||LA60_0==111||LA60_0==115||LA60_0==118||LA60_0==126) ) {
				alt60=2;
			}

			else {
				if (state.backtracking>0) {state.failed=true; return;}
				NoViableAltException nvae =
					new NoViableAltException("", 60, 0, input);
				throw nvae;
			}

			switch (alt60) {
				case 1 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:495:7: arrayInitializer
					{
					pushFollow(FOLLOW_arrayInitializer_in_variableInitializer1507);
					arrayInitializer();
					state._fsp--;
					if (state.failed) return;
					}
					break;
				case 2 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:496:9: expression
					{
					pushFollow(FOLLOW_expression_in_variableInitializer1517);
					expression();
					state._fsp--;
					if (state.failed) return;
					}
					break;

			}
		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
			if ( state.backtracking>0 ) { memoize(input, 44, variableInitializer_StartIndex); }

		}
	}
212441
def find_path_package(thepath):
    
    pname = find_path_package_name(thepath)
    if not pname:
        return None
    fromlist = b'' if six.PY2 else ''
    return __import__(pname, globals(), locals(), [fromlist])
1252970
def write_init_files(packages):
    
    init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__)

try:
    from .__doc__ import __doc__
except ImportError:
    pass
"""
    for package in packages:
        path = os.path.join('src', package.replace('.', os.sep), '__init__.py')
        if os.path.exists(path):
            with open(path) as f:
                old_text = f.read()
        else:
            old_text = ''
        if old_text != init_text:
            with open(path, 'w') as f:
                f.write(init_text)
163026
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, 'get_filename'):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, 'is_package'):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path
467441
def get_version(package):
    
    init_py = readfile(os.path.join(package, '__init__.py'))
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
1292429
def _parse_packages(self, value):
        
        find_directives = ['find:', 'find_namespace:']
        trimmed_value = value.strip()

        if trimmed_value not in find_directives:
            return self._parse_list(value)

        findns = trimmed_value == find_directives[1]
        if findns and not PY3:
            raise DistutilsOptionError(
                'find_namespace: directive is unsupported on Python < 3.3')

        # Read function arguments from a dedicated section.
        find_kwargs = self.parse_section_packages__find(
            self.sections.get('packages.find', {}))

        if findns:
            from setuptools import find_namespace_packages as find_packages
        else:
            from setuptools import find_packages

        return find_packages(**find_kwargs)
411108
def _has_init(directory):
    
    mod_or_pack = os.path.join(directory, "__init__")
    for ext in PY_SOURCE_EXTS + ("pyc", "pyo"):
        if os.path.exists(mod_or_pack + "." + ext):
            return mod_or_pack + "." + ext
    return None
494111
def _parse_attr(cls, value, package_dir=None):
        
        attr_directive = 'attr:'
        if not value.startswith(attr_directive):
            return value

        attrs_path = value.replace(attr_directive, '').strip().split('.')
        attr_name = attrs_path.pop()

        module_name = '.'.join(attrs_path)
        module_name = module_name or '__init__'

        parent_path = os.getcwd()
        if package_dir:
            if attrs_path[0] in package_dir:
                # A custom path was specified for the module we want to import
                custom_path = package_dir[attrs_path[0]]
                parts = custom_path.rsplit('/', 1)
                if len(parts) > 1:
                    parent_path = os.path.join(os.getcwd(), parts[0])
                    module_name = parts[1]
                else:
                    module_name = custom_path
            elif '' in package_dir:
                # A custom parent directory was specified for all root modules
                parent_path = os.path.join(os.getcwd(), package_dir[''])
        sys.path.insert(0, parent_path)
        try:
            module = import_module(module_name)
            value = getattr(module, attr_name)

        finally:
            sys.path = sys.path[1:]

        return value
1249012
def _load_init(self, data, ctx):
        """"""
        if self.shape:
            for self_dim, data_dim in zip(self.shape, data.shape):
                assert self_dim in (0, data_dim), \
                    "Failed loading Parameter '%s' from saved params: " \
                    "shape incompatible expected %s vs saved %s"%(
                        self.name, str(self.shape), str(data.shape))
            self.shape = tuple(i if i != 0 else j for i, j in zip(self.shape, data.shape))
        if self.dtype:
            assert np.dtype(self.dtype).type == data.dtype, \
                "Failed loading Parameter '%s' from saved params: " \
                "dtype incompatible expected %s vs saved %s"%(
                    self.name, str(self.dtype), str(data.dtype))
        if self._stype != data.stype:
            data = data.tostype(self._stype)
        if isinstance(ctx, Context):
            ctx = [ctx]
        if self._data is None:
            if self._deferred_init:
                assert ctx is None or set(ctx) == set(self._deferred_init[1]), \
                    "Failed to load Parameter '%s' on %s because it was " \
                    "previous initialized on %s."%(
                        self.name, str(ctx), str(self.list_ctx()))
                ctx = self._deferred_init[1]
            elif ctx is None:
                ctx = [cpu()]
            self._init_impl(data, ctx)
        else:
            assert ctx is None or set(ctx) == set(self.list_ctx()), \
                "Failed to load Parameter '%s' on %s because it was " \
                "previous initialized on %s."%(
                    self.name, str(ctx), str(self.list_ctx()))
            self.set_data(data)
        self._deferred_init = ()
588437
def init_app(self, app):
        """"""
        prefix_len = len(self.prefix)
        for varname, value in os.environ.items():
            if not varname.startswith(self.prefix):
                continue

            # Prepare values
            varname = varname[prefix_len:]
            value = value or app.config.get(varname)

            # Evaluate value
            try:
                value = ast.literal_eval(value)
            except (SyntaxError, ValueError):
                pass

            # Set value
            app.config[varname] = value
289191
def initpkg(pkgname, exportdefs, attr=None, eager=False):
    
    attr = attr or {}
    oldmod = sys.modules.get(pkgname)
    d = {}
    f = getattr(oldmod, '__file__', None)
    if f:
        f = _py_abspath(f)
    d['__file__'] = f
    if hasattr(oldmod, '__version__'):
        d['__version__'] = oldmod.__version__
    if hasattr(oldmod, '__loader__'):
        d['__loader__'] = oldmod.__loader__
    if hasattr(oldmod, '__path__'):
        d['__path__'] = [_py_abspath(p) for p in oldmod.__path__]
    if hasattr(oldmod, '__package__'):
        d['__package__'] = oldmod.__package__
    if '__doc__' not in exportdefs and getattr(oldmod, '__doc__', None):
        d['__doc__'] = oldmod.__doc__
    d.update(attr)
    if hasattr(oldmod, "__dict__"):
        oldmod.__dict__.update(d)
    mod = ApiModule(pkgname, exportdefs, implprefix=pkgname, attr=d)
    sys.modules[pkgname] = mod
    # eagerload in bypthon to avoid their monkeypatching breaking packages
    if 'bpython' in sys.modules or eager:
        for module in list(sys.modules.values()):
            if isinstance(module, ApiModule):
                module.__dict__
1005411
def unpack_variable(var):
    """"""
    # If we actually get a structure instance, handle turning that into a variable
    if var.dataType == stream.STRUCTURE:
        return None, struct_to_dtype(var), 'Structure'
    elif var.dataType == stream.SEQUENCE:
        log.warning('Sequence support not implemented!')

    dt = data_type_to_numpy(var.dataType, var.unsigned)
    if var.dataType == stream.OPAQUE:
        type_name = 'opaque'
    elif var.dataType == stream.STRING:
        type_name = 'string'
    else:
        type_name = dt.name

    if var.data:
        log.debug('Storing variable data: %s %s', dt, var.data)
        if var.dataType == stream.STRING:
            data = var.data
        else:
            # Always sent big endian
            data = np.frombuffer(var.data, dtype=dt.newbyteorder('>'))
    else:
        data = None

    return data, dt, type_name