Instruments the passed class file so that it contains debug
information extraction from annotations.
167767
@Requires("bytecode != null")
  @Ensures("result != null")
  private byte[] instrumentWithDebug(byte[] bytecode) {
    ClassReader reader = new ClassReader(bytecode);
    ClassWriter writer = new NonLoadingClassWriter(reader, 0);
    reader.accept(new HelperClassAdapter(writer), ClassReader.EXPAND_FRAMES);
    return writer.toByteArray();
  }
627559
List<String> listCompiledClasses(final File classFolder) {
        List<String> classNames = new ArrayList<String>();
        if (!classFolder.exists()) {
            getLog().info("Class folder does not exist; skipping scan");
            return classNames;
        }
        final String extension = ".class";
        final DirectoryScanner directoryScanner = new DirectoryScanner();
        directoryScanner.setBasedir(classFolder);
        directoryScanner.setIncludes(new String[] { "**" + File.separator + "*" + extension });
        directoryScanner.scan();
        String[] files = directoryScanner.getIncludedFiles();

        String className;
        for (String file : files) {
            className = file.substring(0, file.length() - extension.length()).replace(File.separator, ".");
            classNames.add(className);
        }

        return classNames;
    }
199997
def get_class(name, config_key, module):
    """"""
    clsmembers = inspect.getmembers(module, inspect.isclass)
    for string_name, act_class in clsmembers:
        if string_name == name:
            return act_class

    # Check if the user has specified a plugin and if the class is in there
    cfg = get_project_configuration()
    if config_key in cfg:
        modname = os.path.splitext(os.path.basename(cfg[config_key]))[0]
        if os.path.isfile(cfg[config_key]):
            usermodule = imp.load_source(modname, cfg[config_key])
            clsmembers = inspect.getmembers(usermodule, inspect.isclass)
            for string_name, act_class in clsmembers:
                if string_name == name:
                    return act_class
        else:
            logging.warning("File '%s' does not exist. Adjust ~/.hwrtrc.",
                            cfg['data_analyzation_plugins'])

    logging.debug("Unknown class '%s'.", name)
    return None
1276222
def debug_file(self):
        """"""
        self.switch_to_plugin()
        current_editor = self.get_current_editor()
        if current_editor is not None:
            current_editor.sig_debug_start.emit()
        self.run_file(debug=True)
318480
def _extract(__func__, kwds, keys, classname, probe=True):
    

    # Add docs and name
    kwds['doc'] = __func__.__doc__
    if not 'name' in kwds:
        kwds['name'] = __func__.__name__
    # kwds.update({'doc':__func__.__doc__, 'name':__func__.__name__})

    # Instanitate dictionary of parents
    parents = {}

    # This gets used by stochastic to check for long-format logp and random:
    if probe:
        cur_status = check_special_methods()
        disable_special_methods()
        # Define global tracing function (I assume this is for debugging??)
        # No, it's to get out the logp and random functions, if they're in
        # there.

        def probeFunc(frame, event, arg):
            if event == 'return':
                locals = frame.f_locals
                kwds.update(dict((k, locals.get(k)) for k in keys))
                sys.settrace(None)
            return probeFunc

        sys.settrace(probeFunc)

        # Get the functions logp and random (complete interface).
        # Disable special methods to prevent the formation of a hurricane of
        # Deterministics
        try:
            __func__()
        except:
            if 'logp' in keys:
                kwds['logp'] = __func__
            else:
                kwds['eval'] = __func__
        # Reenable special methods.
        if cur_status:
            enable_special_methods()

    for key in keys:
        if not key in kwds:
            kwds[key] = None

    for key in ['logp', 'eval']:
        if key in keys:
            if kwds[key] is None:
                kwds[key] = __func__

    # Build parents dictionary by parsing the __func__tion's arguments.
    (args, defaults) = get_signature(__func__)

    if defaults is None:
        defaults = ()

    # Make sure all parents were defined
    arg_deficit = (len(args) - ('value' in args)) - len(defaults)
    if arg_deficit > 0:
        err_str =  classname + ' ' + __func__.__name__ + \
            ': no parent provided for the following labels:'
        for i in range(arg_deficit):
            err_str += " " + args[i + ('value' in args)]
            if i < arg_deficit - 1:
                err_str += ','
        raise ValueError(err_str)

    # Fill in parent dictionary
    try:
        parents.update(dict(zip(args[-len(defaults):], defaults)))
    except TypeError:
        pass

    value = parents.pop('value', None)

    return (value, parents)
1065074
def _tools_classpath_pairs(self, dest_dir):
    """"""
    tools_classpath = self._tools_classpath
    return [(entry, os.path.join(dest_dir, '{}-{}'.format(idx, os.path.basename(entry))))
            for idx, entry in enumerate(tools_classpath)]
1285074
public void instrumentWithProbes(Collection<Class<?>> classes) {
        for (Class<?> clazz : classes) {
            try {
                instrumentation.retransformClasses(clazz);
            } catch (Throwable t) {
            }
        }
    }
13910
def _collect_classes(m):
    
    from f311 import filetypes as ft
    from f311 import explorer as ex

    def _extend(classes, newclasses):
        """Filters out classes already present in list.

        This shouldn't be necessary, but collaborators may accidentally import already loaded
        classes into the datatypes namespace"""
        classes.extend([class_ for class_ in newclasses if class_ not in classes])
        # classes.extend(newclasses)

    file_classes = [class_ for class_ in a99.get_classes_in_module(m, ft.DataFile) if class_.flag_collect]

    # Classes to consider when attempts to load a text file (see load_any_file())
    _extend(_classes_txt, [class_ for class_ in file_classes if class_.flag_txt])

    # Classes to consider when attempts to load a binary file (see load_any_file())
    _extend(_classes_bin, [class_ for class_ in file_classes if not class_.flag_txt])
    # Adds Classes to consider when attempts to load a spectrum file (see load_spectrum())
    _extend(_classes_sp, [class_ for class_ in file_classes if issubclass(class_, ft.FileSpectrum)])
    # All kwown File* classes
    _extend(_classes_file, file_classes)
    # All kwnown Vis* classes

    _extend(_classes_vis, a99.get_classes_in_module(m, ex.Vis))

    global _classes_file_superclass
    _classes_file_superclass = [cls.__bases__[0] for cls in _classes_file]
1274474
def _annotate_imm(cls):
    '''
    
    '''
    dat = {}
    cls._pimms_immutable_data_ = dat
    # First, crawl this class's static members to see what has been added...
    mems = inspect.getmembers(cls)
    immmems = [m for m in mems
               if isinstance(m[1], types.FunctionType)
               if hasattr(m[1], '_pimms_immutable_data_')]
    dat['params'] = {}
    dat['values'] = {}
    dat['checks'] = {}
    dat['consts'] = {}
    for (fname,f) in immmems:
        if 'is_param' in f._pimms_immutable_data_:
            dat['params'][f.__name__] = (
                None if 'default_value' not in dat else (dat['default_value'],),
                f, [], [], [])
        elif 'is_value' in f._pimms_immutable_data_:
            inputs = f._pimms_immutable_data_['inputs']
            dat['values'][f.__name__] = (inputs, f, [])
            if len(inputs) == 0:
                dat['consts'][f.__name__] = ([], [])
        elif 'is_check' in f._pimms_immutable_data_:
            dat['checks'][f.__name__] = (f._pimms_immutable_data_['inputs'], f)
    # That grabs all the relevant immutable data; we now have two tasks:
    # (1) merge with parent immutable classes to generate final value/param/check lists
    # --- to do this, we start by getting the class hierarchy
    mro = [c for c in inspect.getmro(cls) if c is not cls and is_imm_type(c)]
    # --- now walk through, merging each
    for parent in mro: _imm_merge_class(cls, parent)
    # (2) resolve dependencies
    _imm_resolve_deps(cls)
    return cls
918798
public static void scanClassPathForFormattingAnnotations() {

		ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

		// scan classpath and filter out classes that don't begin with "com.nds"
		Reflections reflections = new Reflections("com.nds","com.cisco");

		Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);

//        Reflections ciscoReflections = new Reflections("com.cisco");
//
//        annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));

		for (Class<?> markerClass : annotated) {

			// if the marker class is indeed implementing FoundationLoggingMarker
			// interface
			if (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {

				final Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;

				executorService.execute(new Runnable() {

					@Override
					public void run() {

						if (markersMap.get(clazz) == null) {
							try {
								// generate formatter class for this marker
								// class
								generateAndUpdateFormatterInMap(clazz);
							} catch (Exception e) {
								LOGGER.trace("problem generating formatter class from static scan method. error is: " + e.toString());
							}
						}

					}
				});

			} else {// if marker class does not implement FoundationLoggingMarker
					// interface, log ERROR

				// verify the LOGGER was initialized. It might not be as this
				// Method is called in a static block
				if (LOGGER == null) {
					LOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);
				}
				LOGGER.error("Formatter annotations should only appear on foundationLoggingMarker implementations");
			}
		}

		try {
			TimeUnit.SECONDS.sleep(30);
		} catch (InterruptedException e) {
			LOGGER.trace(e.toString(), e);
		}
		executorService.shutdown();
		// try {
		// executorService.awaitTermination(15, TimeUnit.SECONDS);
		// } catch (InterruptedException e) {
		// LOGGER.error("creation of formatters has been interrupted");
		// }
	}
964292
public void scanClass(InputStream bits) throws IOException
    {
        DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
        ClassFile cf = null;
        try
        {
            cf = new ClassFile(dstream);

            String className = cf.getName();
            List<String> annotations = new ArrayList<String>();

            accumulateAnnotations(annotations, (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));
            accumulateAnnotations(annotations,
                    (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));

            // iterate through all valid annotations
            for (String validAnn : getValidAnnotations())
            {
                // check if the current class has one?
                if (annotations.contains(validAnn))
                {
                    // fire all listeners
                    for (AnnotationDiscoveryListener listener : getAnnotationDiscoveryListeners())
                    {
                        listener.discovered(className);
                    }
                }
            }

        }
        finally
        {
            dstream.close();
            bits.close();
        }
    }
1024894
private static void analyzeClassFile(org.jacoco.previous.core.analysis.Analyzer analyzer, File classFile) {
    try (InputStream inputStream = new FileInputStream(classFile)) {
      analyzer.analyzeClass(inputStream, classFile.getPath());
    } catch (IOException e) {
      // (Godin): in fact JaCoCo includes name into exception
      JaCoCoExtensions.logger().warn("Exception during analysis of file " + classFile.getAbsolutePath(), e);
    }
  }
1179750
private Instrumenter getInstrumenter(Log log, List<String> classpath) throws MojoExecutionException {
        List<File> classpathFiles;
        try {
            log.debug("Getting compile classpath");
            classpathFiles = classpath
                    .stream().map(x -> new File(x)).collect(Collectors.toList());

            log.debug("Classpath for instrumentation is as follows: " + classpathFiles);
        } catch (Exception ex) {
            throw new MojoExecutionException("Unable to get compile classpath elements", ex);
        }

        log.debug("Creating instrumenter...");

        try {
            return new Instrumenter(classpathFiles);
        } catch (Exception ex) {
            throw new MojoExecutionException("Unable to create instrumenter", ex);
        }
    }
1328690
def addinstance(self, testfile, features, classlabel="?"):
        """"""

        features = self.validatefeatures(features)

        if self.delimiter in classlabel:
            raise ValueError("Class label contains delimiter: " + self.delimiter)


        f = io.open(testfile,'a', encoding=self.encoding)
        f.write(self.delimiter.join(features) + self.delimiter + classlabel + "\n")
        f.close()
188629
public void executeInstrumentation() throws IOException {
        errors.clear();

        // Iterate over all entries in the classes list
        for (File f : this.classFiles) {
            try {
                if (!f.canRead() || !f.canWrite()) {
                    throw new IOException(f + " can not be replaced");
                }
                instrumentClassFile(f);
            } catch (Exception e) {
                e.printStackTrace();
                errors.add(e);
            }
        }

        // Iterate over all entries in the jar list
        for (File f : this.jarFiles) {
            try {
                instrumentZipFile(f);
            } catch (Exception e) {
                e.printStackTrace();
                errors.add(e);
            }
        }

        // Chain the first exception and report the error count
        if (!errors.isEmpty()) {
            Throwable t = errors.get(0);
            IOException ioe = new IOException(errors.size() + " errors occurred");
            ioe.initCause(t);
            throw ioe;
        }
    }
880907
Collection<Class<?>> processNewListeners(Collection<ProbeListener> listeners) {
        Set<Class<?>> classesToTransform = new HashSet<Class<?>>();

        Set<ProbeListener> matchingListeners = new HashSet<ProbeListener>();
        Set<Class<?>> monitorableTemp;
        synchronized (this.monitorable) {
            monitorableTemp = new HashSet<Class<?>>(this.monitorable);
        }
        for (Class<?> clazz : monitorableTemp /* instrumentation.getAllLoadedClasses() */) {
            if (!isMonitorable(clazz)) {
                continue;
            }
            for (ProbeListener listener : listeners) {
                ProbeFilter filter = listener.getProbeFilter();
                if (filter.matches(clazz)) {
                    matchingListeners.add(listener);
                }
            }
            if (!matchingListeners.isEmpty()) {
                classesToTransform.add(clazz);
                addInterestedByClass(clazz, matchingListeners);
            }
            matchingListeners.clear();
        }

        return classesToTransform;
    }
1347677
def autodoc_process_docstring(app, what, name, obj, options, lines):
    
    # check that only symbols that can be directly imported from ``callee``
    # package are being documented
    _, symbol = name.rsplit('.', 1)
    if symbol not in callee.__all__:
        raise SphinxError(
            "autodoc'd '%s' is not a part of the public API!" % name)

    # for classes exempt from automatic merging of class & __init__ docs,
    # pretend their __init__ methods have no docstring at all,
    # so that nothing will be appended to the class's docstring
    if what == 'class' and name in autoclass_content_exceptions:
        # amusingly, when autodoc reads the constructor's docstring
        # for appending it to class docstring, it will report ``what``
        # as 'class' (again!); hence we must check what it actually read
        ctor_docstring_lines = prepare_docstring(obj.__init__.__doc__)
        if lines == ctor_docstring_lines:
            lines[:] = []