text:
package com.networknt.light.rule.compiler;

import com.networknt.light.rule.Rule;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.tools.*;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;

/**
 * Compile a String or other {@link CharSequence}, returning a Java
 * {@link Class} instance that may be instantiated. This class is a Facade
 * around {@link JavaCompiler} for a narrower use case, but a bit easier to use.
 *

 * To compile a String containing source for a Java class which implements
 * MyInterface:
 *
 *

 * ClassLoader classLoader = MyClass.class.getClassLoader(); // optional; null is
 * 															// also OK
 * List<Diagnostic> diagnostics = new ArrayList<Diagnostic>(); // optional; null is
 * 															// also OK
 * JavaStringCompiler<Object> compiler = new JavaStringCompiler<MyInterface>(
 * 		classLoader, null);
 * try {
 * 	Class<MyInterface> newClass = compiler.compile("com.mypackage.NewClass",
 * 			stringContaininSourceForNewClass, diagnostics, MyInterface);
 * 	MyInterface instance = newClass.newInstance();
 * 	instance.someOperation(someArgs);
 * } catch (JavaStringCompilerException e) {
 * 	handle(e);
 * } catch (IllegalAccessException e) {
 * 	handle(e);
 * }
 *

 *
 * The source can be in a String, {@link StringBuffer}, or your own class which
 * implements {@link CharSequence}. If you implement your own, it must be thread
 * safe (preferably, immutable.)
 *
 * @author David J. Biesack
 */
public class CharSequenceCompiler<T> {
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CharSequenceCompiler.class);

	// Compiler requires source files with a ".java" extension:
	static final String JAVA_EXTENSION = ".java";

	private final ClassLoaderImpl classLoader;

	// The compiler instance that this facade uses.
	private final JavaCompiler compiler;

	// The compiler options (such as "-target" "1.6").
	private final List<String> options;

	// collect compiler diagnostics in this instance.
	private DiagnosticCollector<JavaFileObject> diagnostics;

	// The FileManager which will store source and class "files".
	private final FileManagerImpl javaFileManager;

	/**
	 * Construct a new instance which delegates to the named class loader.
	 *
	 * @param loader
	 *            the application ClassLoader. The compiler will look through to
	 *            this // class loader for dependent classes
	 * @param options
	 *            The compiler options (such as "-target" "1.5"). See the usage
	 *            for javac
	 * @throws IllegalStateException
	 *             if the Java compiler cannot be loaded.
	 */
	public CharSequenceCompiler(ClassLoader loader, Iterable<String> options) {
		compiler = ToolProvider.getSystemJavaCompiler();
		if (compiler == null) {
			throw new IllegalStateException(
					"Cannot find the system Java compiler. "
							+ "Check that your class path includes tools.jar");
		}
		classLoader = new ClassLoaderImpl(loader);
		diagnostics = new DiagnosticCollector<JavaFileObject>();
		//final JavaFileManager fileManager = compiler.getStandardFileManager(
		//		diagnostics, null, null);
		StandardJavaFileManager standardJavaFileManager = compiler
				.getStandardFileManager(diagnostics, null, null);
		final JavaFileManager fileManager = new CustomClassloaderJavaFileManager(
				loader, standardJavaFileManager);
		// create our FileManager which chains to the default file manager
		// and our ClassLoader
		javaFileManager = new FileManagerImpl(fileManager, classLoader);
		this.options = new ArrayList<String>();
		if (options != null) { // make a save copy of input options
			for (String option : options) {
				this.options.add(option);
			}
		}
	}

	/**
	 * Compile Java source in <var>javaSource</name> and return the resulting
	 * class.
	 *

	 * Thread safety: this method is thread safe if the <var>javaSource</var>
	 * and <var>diagnosticsList</var> are isolated to this thread.
	 *
	 * @param qualifiedClassName
	 *            The fully qualified class name.
	 * @param javaSource
	 *            Complete java source, including a package statement and a
	 *            class, interface, or annotation declaration.
	 * @param diagnosticsList
	 *            Any diagnostics generated by compiling the source are added to
	 *            this collector.
	 * @param types
	 *            zero or more Class objects representing classes or interfaces
	 *            that the resulting class must be assignable (castable) to.
	 * @return a Class which is generated by compiling the source
	 * @throws CharSequenceCompilerException
	 *             if the source cannot be compiled - for example, if it
	 *             contains syntax or semantic errors or if dependent classes
	 *             cannot be found.
	 * @throws ClassCastException
	 *             if the generated class is not assignable to all the optional
	 *             <var>types</var>.
	 */
	public synchronized Class<T> compile(final String qualifiedClassName,
			final CharSequence javaSource,
			final DiagnosticCollector<JavaFileObject> diagnosticsList,
			final Class<?>... types) throws CharSequenceCompilerException,
			ClassCastException {
		if (diagnosticsList != null)
			diagnostics = diagnosticsList;
		else
			diagnostics = new DiagnosticCollector<JavaFileObject>();
		Map<String, CharSequence> classes = new HashMap<String, CharSequence>(1);
		classes.put(qualifiedClassName, javaSource);
		Map<String, Class<T>> compiled = compile(classes, diagnosticsList);
		Class<T> newClass = compiled.get(qualifiedClassName);
		return castable(newClass, types);
	}

	/**
	 * Compile multiple Java source strings and return a Map containing the
	 * resulting classes.
	 *

	 * Thread safety: this method is thread safe if the <var>classes</var> and
	 * <var>diagnosticsList</var> are isolated to this thread.
	 *
	 * @param classes
	 *            A Map whose keys are qualified class names and whose values
	 *            are the Java source strings containing the definition of the
	 *            class. A map value may be null, indicating that compiled class
	 *            is expected, although no source exists for it (it may be a
	 *            non-public class contained in one of the other strings.)
	 * @param diagnosticsList
	 *            Any diagnostics generated by compiling the source are added to
	 *            this list.
	 * @return A mapping of qualified class names to their corresponding
	 *         classes. The map has the same keys as the input
	 *         <var>classes</var>; the values are the corresponding Class
	 *         objects.
	 * @throws CharSequenceCompilerException
	 *             if the source cannot be compiled
	 */
	public synchronized Map<String, Class<T>> compile(
			final Map<String, CharSequence> classes,
			final DiagnosticCollector<JavaFileObject> diagnosticsList)
			throws CharSequenceCompilerException {
		List<JavaFileObject> sources = new ArrayList<JavaFileObject>();
		for (Entry<String, CharSequence> entry : classes.entrySet()) {
			String qualifiedClassName = entry.getKey();
			CharSequence javaSource = entry.getValue();
			if (javaSource != null) {
				final int dotPos = qualifiedClassName.lastIndexOf('.');
				final String className = dotPos == -1 ? qualifiedClassName
						: qualifiedClassName.substring(dotPos + 1);
				final String packageName = dotPos == -1 ? ""
						: qualifiedClassName.substring(0, dotPos);
				final JavaFileObjectImpl source = new JavaFileObjectImpl(
						className, javaSource);
				sources.add(source);
				// Store the source file in the FileManager via package/class
				// name.
				// For source files, we add a .java extension
				javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH,
						packageName, className + JAVA_EXTENSION, source);
			}
		}
		// Get a CompliationTask from the compiler and compile the sources
		final CompilationTask task = compiler.getTask(null, javaFileManager,
				diagnostics, options, null, sources);
		final Boolean result = task.call();
		if (result == null || !result.booleanValue()) {
			throw new CharSequenceCompilerException("Compilation failed.",
					classes.keySet(), diagnostics);
		}
		try {
			// For each class name in the inpput map, get its compiled
			// class and put it in the output map
			Map<String, Class<T>> compiled = new HashMap<String, Class<T>>();
			for (String qualifiedClassName : classes.keySet()) {
				final Class<T> newClass = loadClass(qualifiedClassName);
				compiled.put(qualifiedClassName, newClass);
			}
			return compiled;
		} catch (ClassNotFoundException e) {
            logger.error("Exception:", e);
			throw new CharSequenceCompilerException(classes.keySet(), e,
					diagnostics);
		} catch (IllegalArgumentException e) {
            logger.error("Exception:", e);
			throw new CharSequenceCompilerException(classes.keySet(), e,
					diagnostics);
		} catch (SecurityException e) {
            logger.error("Exception:", e);
			throw new CharSequenceCompilerException(classes.keySet(), e,
					diagnostics);
		}
	}

    /**
     * Compile multiple Java source strings and return a Map containing the
     * resulting classes.
     *

     * Thread safety: this method is thread safe if the <var>classes</var> and
     * <var>diagnosticsList</var> are isolated to this thread.
     *
     * @param classes
     *            A Map whose keys are qualified class names and whose values
     *            are the Java source strings containing the definition of the
     *            class. A map value may be null, indicating that compiled class
     *            is expected, although no source exists for it (it may be a
     *            non-public class contained in one of the other strings.)
     * @return A mapping of qualified class names to their corresponding
     *         classes. The map has the same keys as the input
     *         <var>classes</var>; the values are the corresponding Class
     *         objects.
     * @throws CharSequenceCompilerException
     *             if the source cannot be compiled
     */
    public synchronized void compile(
            final Map<String, String> classes, Map<String, Rule> ruleCache)
            throws CharSequenceCompilerException {
        List<JavaFileObject> sources = new ArrayList<JavaFileObject>();
        for (Entry<String, String> entry : classes.entrySet()) {
            String qualifiedClassName = entry.getKey();
            CharSequence javaSource = entry.getValue();
            if (javaSource != null) {
                final int dotPos = qualifiedClassName.lastIndexOf('.');
                final String className = dotPos == -1 ? qualifiedClassName
                        : qualifiedClassName.substring(dotPos + 1);
                final String packageName = dotPos == -1 ? ""
                        : qualifiedClassName.substring(0, dotPos);
                final JavaFileObjectImpl source = new JavaFileObjectImpl(
                        className, javaSource);
                sources.add(source);
                // Store the source file in the FileManager via package/class
                // name.
                // For source files, we add a .java extension
                javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH,
                        packageName, className + JAVA_EXTENSION, source);
            }
        }
        // Get a CompliationTask from the compiler and compile the sources
        final CompilationTask task = compiler.getTask(null, javaFileManager,
				diagnostics, options, null, sources);
        final Boolean result = task.call();
        if (result == null || !result.booleanValue()) {
            for(Diagnostic d: diagnostics.getDiagnostics()) {
				logger.error(d.toString());
			}
			throw new CharSequenceCompilerException("Compilation failed.",
                    classes.keySet(), diagnostics);
        }
        try {
            // For each class name in the compile map, get its compiled class and put it in the ruleCache
            for (String qualifiedClassName : classes.keySet()) {
                Class<Rule> newClass = (Class<Rule>)loadClass(qualifiedClassName);
                // test if it is abstract
                if(!Modifier.isAbstract(newClass.getModifiers())) {
                    Rule rule = newClass.newInstance();
                    ruleCache.put(qualifiedClassName, rule);
                }
            }
        } catch (ClassNotFoundException e) {
            logger.error("Exception:", e);
            throw new CharSequenceCompilerException(classes.keySet(), e,
                    diagnostics);
        } catch (IllegalArgumentException e) {
            logger.error("Exception:", e);
            throw new CharSequenceCompilerException(classes.keySet(), e,
                    diagnostics);
        } catch (SecurityException e) {
            logger.error("Exception:", e);
            throw new CharSequenceCompilerException(classes.keySet(), e,
                    diagnostics);
        } catch (InstantiationException e) {
            logger.error("Exception:", e);
            throw new CharSequenceCompilerException(classes.keySet(), e,
                    diagnostics);
        } catch (IllegalAccessException e) {
            logger.error("Exception:", e);
            throw new CharSequenceCompilerException(classes.keySet(), e,
                    diagnostics);
        }
    }

	/**
	 * Load a class that was generated by this instance or accessible from its
	 * parent class loader. Use this method if you need access to additional
	 * classes compiled by
	 * {@link #compile(String, CharSequence, DiagnosticCollector, Class...)
	 * compile()}, for example if the primary class contained nested classes or
	 * additional non-public classes.
	 *
	 * @param qualifiedClassName
	 *            the name of the compiled class you wish to load
	 * @return a Class instance named by <var>qualifiedClassName</var>
	 * @throws ClassNotFoundException
	 *             if no such class is found.
	 */
	@SuppressWarnings("unchecked")
	public Class<T> loadClass(final String qualifiedClassName)
			throws ClassNotFoundException {
		return (Class<T>) classLoader.loadClass(qualifiedClassName);
	}

	/**
	 * Check that the <var>newClass</var> is a subtype of all the type
	 * parameters and throw a ClassCastException if not.
	 *
	 * @param types
	 *            zero of more classes or interfaces that the
	 *            <var>newClass</var> must be castable to.
	 * @return <var>newClass</var> if it is castable to all the types
	 * @throws ClassCastException
	 *             if <var>newClass</var> is not castable to all the types.
	 */
	private Class<T> castable(Class<T> newClass, Class<?>... types)
			throws ClassCastException {
		for (Class<?> type : types)
			if (!type.isAssignableFrom(newClass)) {
				throw new ClassCastException(type.getName());
			}
		return newClass;
	}

	/**
	 * COnverts a String to a URI.
	 *
	 * @param name
	 *            a file name
	 * @return a URI
	 */
	static URI toURI(String name) {
		try {
			return new URI(name);
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @return This compiler's class loader.
	 */
	public ClassLoader getClassLoader() {
		return javaFileManager.getClassLoader();
	}
}

/**
 * A JavaFileManager which manages Java source and classes. This FileManager
 * delegates to the JavaFileManager and the ClassLoaderImpl provided in the
 * constructor. The sources are all in memory CharSequence instances and the
 * classes are all in memory byte arrays.
 */
final class FileManagerImpl extends ForwardingJavaFileManager<JavaFileManager> {
	// the delegating class loader (passed to the constructor)
	private final ClassLoaderImpl classLoader;

	// Internal map of filename URIs to JavaFileObjects.
	private final Map<URI, JavaFileObject> fileObjects = new HashMap<URI, JavaFileObject>();

	/**
	 * Construct a new FileManager which forwards to the <var>fileManager</var>
	 * for source and to the <var>classLoader</var> for classes
	 *
	 * @param fileManager
	 *            another FileManager that this instance delegates to for
	 *            additional source.
	 * @param classLoader
	 *            a ClassLoader which contains dependent classes that the
	 *            compiled classes will require when compiling them.
	 */
	public FileManagerImpl(JavaFileManager fileManager,
			ClassLoaderImpl classLoader) {
		super(fileManager);
		this.classLoader = classLoader;
	}

	/**
	 * @return the class loader which this file manager delegates to
	 */
	public ClassLoader getClassLoader() {
		return classLoader;
	}

	/**
	 * For a given file <var>location</var>, return a FileObject from which the
	 * compiler can obtain source or byte code.
	 *
	 * @param location
	 *            an abstract file location
	 * @param packageName
	 *            the package name for the file
	 * @param relativeName
	 *            the file's relative name
	 * @return a FileObject from this or the delegated FileManager
	 * @see javax.tools.ForwardingJavaFileManager#getFileForInput(javax.tools.JavaFileManager.Location,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public FileObject getFileForInput(Location location, String packageName,
			String relativeName) throws IOException {
		FileObject o = fileObjects
				.get(uri(location, packageName, relativeName));
		if (o != null)
			return o;
		return super.getFileForInput(location, packageName, relativeName);
	}

	/**
	 * Store a file that may be retrieved later with
	 * {@link #getFileForInput(javax.tools.JavaFileManager.Location, String, String)}
	 *
	 * @param location
	 *            the file location
	 * @param packageName
	 *            the Java class' package name
	 * @param relativeName
	 *            the relative name
	 * @param file
	 *            the file object to store for later retrieval
	 */
	public void putFileForInput(StandardLocation location, String packageName,
			String relativeName, JavaFileObject file) {
		fileObjects.put(uri(location, packageName, relativeName), file);
	}

	/**
	 * Convert a location and class name to a URI
	 */
	private URI uri(Location location, String packageName, String relativeName) {
		return CharSequenceCompiler.toURI(location.getName() + '/'
				+ packageName + '/' + relativeName);
	}

	/**
	 * Create a JavaFileImpl for an output class file and store it in the
	 * classloader.
	 *
	 * @see javax.tools.ForwardingJavaFileManager#getJavaFileForOutput(javax.tools.JavaFileManager.Location,
	 *      java.lang.String, javax.tools.JavaFileObject.Kind,
	 *      javax.tools.FileObject)
	 */
	@Override
	public JavaFileObject getJavaFileForOutput(Location location,
			String qualifiedName, Kind kind, FileObject outputFile)
			throws IOException {
		JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
		classLoader.add(qualifiedName, file);
		return file;
	}

	@Override
	public ClassLoader getClassLoader(JavaFileManager.Location location) {
		return classLoader;
	}

	@Override
	public String inferBinaryName(Location loc, JavaFileObject file) {
		String result;
		// For our JavaFileImpl instances, return the file's name, else
		// simply run the default implementation
		if (file instanceof JavaFileObjectImpl)
			result = file.getName();
		else
			result = super.inferBinaryName(loc, file);
		return result;
	}

	@Override
	public Iterable<JavaFileObject> list(Location location, String packageName,
			Set<Kind> kinds, boolean recurse) throws IOException {
		Iterable<JavaFileObject> result = super.list(location, packageName,
				kinds, recurse);
		ArrayList<JavaFileObject> files = new ArrayList<JavaFileObject>();
		if (location == StandardLocation.CLASS_PATH
				&& kinds.contains(JavaFileObject.Kind.CLASS)) {
			for (JavaFileObject file : fileObjects.values()) {
				if (file.getKind() == Kind.CLASS
						&& file.getName().startsWith(packageName))
					files.add(file);
			}
			files.addAll(classLoader.files());
		} else if (location == StandardLocation.SOURCE_PATH
				&& kinds.contains(JavaFileObject.Kind.SOURCE)) {
			for (JavaFileObject file : fileObjects.values()) {
				if (file.getKind() == Kind.SOURCE
						&& file.getName().startsWith(packageName))
					files.add(file);
			}
		}
		for (JavaFileObject file : result) {
			files.add(file);
		}
		return files;
	}
}

/**
 * A JavaFileObject which contains either the source text or the compiler
 * generated class. This class is used in two cases.
 *

 *
This instance uses it to store the source which is passed to the
 * compiler. This uses the
 * {@link JavaFileObjectImpl#JavaFileObjectImpl(String, CharSequence)}
 * constructor.
 *
The Java compiler also creates instances (indirectly through the
 * FileManagerImplFileManager) when it wants to create a JavaFileObject for the
 * .class output. This uses the
 * {@link JavaFileObjectImpl#JavaFileObjectImpl(String, JavaFileObject.Kind)}
 * constructor.
 *

 * This class does not attempt to reuse instances (there does not seem to be a
 * need, as it would require adding a Map for the purpose, and this would also
 * prevent garbage collection of class byte code.)
 */
final class JavaFileObjectImpl extends SimpleJavaFileObject {
	// If kind == CLASS, this stores byte code from openOutputStream
	private ByteArrayOutputStream byteCode;

	// if kind == SOURCE, this contains the source text
	private final CharSequence source;

	/**
	 * Construct a new instance which stores source
	 *
	 * @param baseName
	 *            the base name
	 * @param source
	 *            the source code
	 */
	JavaFileObjectImpl(final String baseName, final CharSequence source) {
		super(CharSequenceCompiler.toURI(baseName
				+ CharSequenceCompiler.JAVA_EXTENSION), Kind.SOURCE);
		this.source = source;
	}

	/**
	 * Construct a new instance
	 *
	 * @param name
	 *            the file name
	 * @param kind
	 *            the kind of file
	 */
	JavaFileObjectImpl(final String name, final Kind kind) {
		super(CharSequenceCompiler.toURI(name), kind);
		source = null;
	}

	/**
	 * Return the source code content
	 *
	 * @see javax.tools.SimpleJavaFileObject#getCharContent(boolean)
	 */
	@Override
	public CharSequence getCharContent(final boolean ignoreEncodingErrors)
			throws UnsupportedOperationException {
		if (source == null)
			throw new UnsupportedOperationException("getCharContent()");
		return source;
	}

	/**
	 * Return an input stream for reading the byte code
	 *
	 * @see javax.tools.SimpleJavaFileObject#openInputStream()
	 */
	@Override
	public InputStream openInputStream() {
		return new ByteArrayInputStream(getByteCode());
	}

	/**
	 * Return an output stream for writing the bytecode
	 *
	 * @see javax.tools.SimpleJavaFileObject#openOutputStream()
	 */
	@Override
	public OutputStream openOutputStream() {
		byteCode = new ByteArrayOutputStream();
		return byteCode;
	}

	/**
	 * @return the byte code generated by the compiler
	 */
	byte[] getByteCode() {
		return byteCode.toByteArray();
	}
}

/**
 * A custom ClassLoader which maps class names to JavaFileObjectImpl instances.
 */
final class ClassLoaderImpl extends ClassLoader {
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ClassLoaderImpl.class);

	private final Map<String, JavaFileObject> classes = new HashMap<String, JavaFileObject>();

	ClassLoaderImpl(final ClassLoader parentClassLoader) {
		super(parentClassLoader);
	}

	/**
	 * @return An collection of JavaFileObject instances for the classes in the
	 *         class loader.
	 */
	Collection<JavaFileObject> files() {
		return Collections.unmodifiableCollection(classes.values());
	}

	@Override
	protected Class<?> findClass(final String qualifiedClassName)
			throws ClassNotFoundException {
		JavaFileObject file = classes.get(qualifiedClassName);
		if (file != null) {
			byte[] bytes = ((JavaFileObjectImpl) file).getByteCode();
			return defineClass(qualifiedClassName, bytes, 0, bytes.length);
		}
		// Workaround for "feature" in Java 6
		// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434149
		try {
			Class<?> c = Class.forName(qualifiedClassName);
			return c;
		} catch (ClassNotFoundException nf) {
			// Ignore and fall through
		}
		return super.findClass(qualifiedClassName);
	}

	/**
	 * Add a class name/JavaFileObject mapping
	 *
	 * @param qualifiedClassName
	 *            the name
	 * @param javaFile
	 *            the file associated with the name
	 */
	void add(final String qualifiedClassName, final JavaFileObject javaFile) {
		classes.put(qualifiedClassName, javaFile);
	}

	@Override
	protected synchronized Class<?> loadClass(final String name,
			final boolean resolve) throws ClassNotFoundException {
		return super.loadClass(name, resolve);
	}

	@Override
	public InputStream getResourceAsStream(final String name) {
		if (name.endsWith(".class")) {
			String qualifiedClassName = name.substring(0,
					name.length() - ".class".length()).replace('/', '.');
			JavaFileObjectImpl file = (JavaFileObjectImpl) classes
					.get(qualifiedClassName);
			if (file != null) {
				return new ByteArrayInputStream(file.getByteCode());
			}
		}
		return super.getResourceAsStream(name);
	}
}


text:
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit

import os, sqlite3

# Imports for Web Sockets
from threading import Lock

# Local Imports
import settings
from streaming import DataFlow, Credentials, CredentialsManager

test_arr = []

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)

thread = None
thread_lock = Lock()
flow = None

@app.cli.command()
def configure():
    path = settings.CREDENTIALS_PATH
    manager = CredentialsManager(path)

    if os.path.exists(path):
        cred = manager.read()
    else:
        cred = Credentials()

    user_input = lambda msg: input(msg).strip()
    promptify  = lambda text: text.replace('_', ' ').title()

    for key in cred:
        val = user_input(promptify(key) + ' [' + cred[key] + ']: ')
        cred[key] = val

    manager.write(cred)

""" Default home page.

Allows user to choose a table to display or view a live stream of a
pre-determiend query.

"""
@app.route('/', methods=['GET'])
def index():
    conn = sqlite3.connect('sql/TweetInfo.db')

    # Grab list of table names
    tableNamesList = conn.execute("select name from sqlite_master where type = "
                                    "'table'")

    return render_template("index.html", tableNamesList=tableNamesList)

""" Page with graphs of user-specified table.

Results page that shows graphs of a specified query. The page is generated based
on user table choice (POST requet).

"""
@app.route('/results', methods=['POST','GET'])
def results():
    # Dispaly results
    try:
        # Connect to database
        conn = sqlite3.connect('sql/TweetInfo.db')

        # Get the chosen table
        table_choice = request.form.get('table_choice')

        # Select chosen table
        cursor = conn.execute("SELECT * FROM " + str(table_choice[2:-3]))

        # Format data for highCharts
        tweetsList = []
        posData = []
        negData = []
        index = -1
        for row in cursor:
            index += 1

            # Ignore the highlighted tweets
            if(index < 20 and len(row) > 150): continue

            timeMS = row[1] * 1000      # Micro -> MiliSeconds
            sentiment = row[3] * 100
            tweetId = row[0]
            tweetsList.append({ 'x': timeMS,
                                'y' : sentiment,
                                'tweetId' : tweetId,
                                'tweetText' : row[2]
                             })

        # FIXME do this sorting later
        # Must sort, tweets can be scraped out of order.
        tweetsList = sorted(tweetsList, key=lambda k: k['x'])

        return render_template("results.html", tweetsList=tweetsList,
                table_choice=table_choice[2:-3])
    except:
        return render_template("error.html")

""" Streaming page with live graph.

Displays a live graph of sentiment over time with a pre-determined selection of
search queries. (Typically updated with trending tweets)

"""
@app.route('/hashtags', methods=['GET'])
def hashtags():
    from hashtag_finder import calfire_hashtags
    return jsonify(result=calfire_hashtags('CAL_FIRE'))

@app.route('/streaming', methods=['POST','GET'])
def stream():
    return render_template("streaming.html", async_mode=socketio.async_mode)

def background_thread(message):
    global flow
    print("Stream is flowing...")
    flow = DataFlow.factory(message['flow type'])
    flow.start(message, socketio)

@socketio.on('stop_stream', namespace='/streaming')
def stop_stream():
    global thread
    print("Stream flow is ending...")
    thread = None
    flow.stop()

@socketio.on('start_stream', namespace='/streaming')
def start_stream(message):
    global thread
    with thread_lock:
        if thread is None:
            print("Starting thread...")
            thread = socketio.start_background_task(background_thread, message)

if __name__ == "__main__":
    print("Running server...")
    socketio.run(app, debug=1)

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.ApiDesignGuidelines.Analyzers
{
    /// <summary>
    /// CA2226: Operators should have symmetrical overloads
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public sealed class CSharpOperatorsShouldHaveSymmetricalOverloadsAnalyzer : OperatorsShouldHaveSymmetricalOverloadsAnalyzer
    {

    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask2 Example</title>
</head>
<body>
    Say Hello to my little friend:{{thing}}
    Alas, it just destroyed {{place}}
</body>
</html>


text:
import os

from oslo_serialization import jsonutils
import six
from six.moves import urllib
import yaml

from senlin.common.i18n import _

# Try LibYAML if available
if hasattr(yaml, 'CSafeLoader'):
    Loader = yaml.CSafeLoader
else:
    Loader = yaml.SafeLoader

if hasattr(yaml, 'CSafeDumper'):
    Dumper = yaml.CSafeDumper
else:
    Dumper = yaml.SafeDumper

class YamlLoader(Loader):
    def normalise_file_path_to_url(self, path):
        if urllib.parse.urlparse(path).scheme:
            return path
        path = os.path.abspath(path)
        return urllib.parse.urljoin('file:',
                                    urllib.request.pathname2url(path))

    def include(self, node):
        try:
            url = self.normalise_file_path_to_url(self.construct_scalar(node))
            tmpl = urllib.request.urlopen(url).read()
            return yaml.load(tmpl, Loader)
        except urllib.error.URLError as ex:
            raise IOError('Failed retrieving file %s: %s' %
                          (url, six.text_type(ex)))

    def process_unicode(self, node):
        # Override the default string handling function to always return
        # unicode objects
        return self.construct_scalar(node)

YamlLoader.add_constructor('!include', YamlLoader.include)
YamlLoader.add_constructor(u'tag:yaml.org,2002:str',
                           YamlLoader.process_unicode)
YamlLoader.add_constructor(u'tag:yaml.org,2002:timestamp',
                           YamlLoader.process_unicode)

def simple_parse(in_str):
    try:
        out_dict = jsonutils.loads(in_str)
    except ValueError:
        try:
            out_dict = yaml.load(in_str, Loader=YamlLoader)
        except yaml.YAMLError as yea:
            yea = six.text_type(yea)
            msg = _('Error parsing input: %s') % yea
            raise ValueError(msg)
        else:
            if out_dict is None:
                out_dict = {}

    if not isinstance(out_dict, dict):
        msg = _('The input is not a JSON object or YAML mapping.')
        raise ValueError(msg)

    return out_dict


text:
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var _ = require('underscore');
var moment = require('moment');
var $ = require('jquery');
var Utils = require('../../helpers/utils');
require('../form-components/index');
require('datepicker');
var datePickerTemplate = require('./date-picker-range-form.tpl');
var template = require('./date-picker-range.tpl');
var MAX_RANGE = 30;

/**
 * Custom picer for a dates range.
 */
module.exports = CoreView.extend({

  className: 'DatePicker',

  options: {
    flat: true,
    date: ['2008-07-31', '2008-07-31'],
    current: '2008-07-31',
    calendars: 2,
    mode: 'range',
    starts: 1
  },

  events: {
    'click .js-dates': '_toggleCalendar',
    'click .js-fourHours': '_setLastFourHours',
    'click .js-oneDay': '_setLastDay',
    'click .js-oneWeek': '_setLastWeek'
  },

  initialize: function (opts) {
    this.model = new Backbone.Model({
      fromDate: '',
      fromHour: 0,
      fromMin: 0,
      toDate: '',
      toHour: 23,
      toMin: 59,
      user_timezone: 0 // Explained as GMT+0
    });

    this.template = opts.template || template;
    this._initBinds();
    this._setDefaultDate();
  },

  render: function () {
    var self = this;

    this.clearSubViews();

    this.$el.append(
      this.template(
        _.extend(
          this.model.attributes,
          {
            max_days: MAX_RANGE,
            pad: Utils.pad
          }
        )
      )
    );

    setTimeout(function () {
      self._initCalendar();
      self._hideCalendar();
      self._initTimers();
    }, 100);

    return this;
  },

  _initBinds: function () {
    this.model.bind('change', this._setValues, this);
    this.model.bind('change', this._onValuesChange, this);
    $(document).bind('click', this._onDocumentClick.bind(this));
  },

  _destroyBinds: function () {
    $(document).unbind('click', this._onDocumentClick.bind(this));
  },

  _setValues: function (m, c) {
    var text = _t('components.datepicker.dates-placeholder');
    var data = this.model.attributes;

    if (data.fromDate && data.toDate) {
      text =
        _t('components.datepicker.from') + ' ' +
        '' +
        this.model.get('fromDate') + ' ' +
        (Utils.pad(this.model.get('fromHour'), 2) + ':' + Utils.pad(this.model.get('fromMin'), 2)) +
        '' +
        ' ' + _t('components.datepicker.to') + ' ' +
        '' +
        this.model.get('toDate') + ' ' +
        (Utils.pad(this.model.get('toHour'), 2) + ':' + Utils.pad(this.model.get('toMin'), 2)) +
        '' +
        '';
    }

    this.$('.DatePicker-dates').html(text);
  },

  _setDefaultDate: function () {
    var datesUTC = this.model.get('user_timezone');
    var today = moment().utc(datesUTC);
    var previous = moment().utc(datesUTC).subtract((MAX_RANGE - 1), 'days');
    this.options.date = [previous.format('YYYY-MM-DD'), today.format('YYYY-MM-DD')];
    this.options.current = today.format('YYYY-MM-DD');
    this._setModelFromPrevious(previous);
  },

  _initCalendar: function () {
    var selector = '.DatePicker-calendar';

    // Can't initialize calendar if not already present in document... avoid errors being thrown
    if (!document.body.contains(this.$(selector)[0])) return;

    this.calendar = this.$(selector).DatePicker(
      _.extend(this.options, {
        onChange: this._onDatesChange.bind(this),
        onRender: function (d) { // Disable future dates and dates < MAX_RANGE days ago
          var date = d.valueOf();
          var now = new Date();

          var thirtyDaysAgo = new Date();
          thirtyDaysAgo.setDate(now.getDate() - MAX_RANGE);

          return (date < thirtyDaysAgo) || (date > now) ? { disabled: true } : '';
        }
      })
    );
  },

  _onDatesChange: function (formatted, dates) {
    // Check if selected dates have more than MAX_RANGE days
    var start = moment(formatted[0]);
    var end = moment(formatted[1]);

    if (Math.abs(start.diff(end, 'days')) > MAX_RANGE) {
      formatted[1] = moment(formatted[0]).add('days', MAX_RANGE).format('YYYY-MM-DD');
      this.$('.DatePicker-calendar').DatePickerSetDate([formatted[0], formatted[1]]);
    }

    this.model.set({
      fromDate: formatted[0],
      toDate: formatted[1]
    });
  },

  _hideCalendar: function (e) {
    if (e) this.killEvent(e);
    this.$('.DatePicker-dropdown').hide();
  },

  _toggleCalendar: function (ev) {
    if (ev) this.killEvent(ev);
    this.$('.DatePicker-dropdown').toggle();
  },

  _setLastFourHours: function () {
    var previous = moment().utc(0).subtract(4, 'hours');
    this._setModelFromPrevious(previous);
    this._setDatepickerFromPrevious(previous);
    this.closeCalendar();
  },

  _setLastDay: function () {
    var previous = moment().utc(0).subtract(1, 'day');
    this._setModelFromPrevious(previous);
    this._setDatepickerFromPrevious(previous);
    this.closeCalendar();
  },

  _setLastWeek: function () {
    var previous = moment().utc(0).subtract(1, 'week');
    this._setModelFromPrevious(previous);
    this._setDatepickerFromPrevious(previous);
    this.closeCalendar();
  },

  _setModelFromPrevious: function (previous) {
    var today = moment().utc(0);

    this.model.set({
      fromDate: previous.format('YYYY-MM-DD'),
      fromHour: parseInt(previous.format('H'), 10),
      fromMin: parseInt(previous.format('m'), 10),
      toDate: today.format('YYYY-MM-DD'),
      toHour: parseInt(today.format('H'), 10),
      toMin: parseInt(today.format('m'), 10)
    });
  },

  _setDatepickerFromPrevious: function (previous) {
    var today = moment().utc(0);
    this.$('.DatePicker-calendar').DatePickerSetDate([ previous.format('YYYY-MM-DD'), today.format('YYYY-MM-DD') ]);
  },

  _initTimers: function () {
    var generateNumberType = function (min, max) {
      var title = max === 23
        ? _t('components.datepicker.hour')
        : _t('components.datepicker.min');
      return {
        type: 'Number',
        title: title,
        validators: ['required', {
          type: 'interval',
          min: min,
          max: max
        }]
      };
    };

    this.model.schema = {
      fromHour: generateNumberType(0, 23),
      fromMin: generateNumberType(0, 59),
      toHour: generateNumberType(0, 23),
      toMin: generateNumberType(0, 59)
    };

    this._datesForm = new Backbone.Form({
      model: this.model,
      template: datePickerTemplate
    });

    this._datesForm.bind('change', function () {
      this.commit();
    });
    this.$('.js-timers').append(this._datesForm.render().el);
  },

  _onValuesChange: function () {
    this.trigger('changeDate', this.model.toJSON(), this);
  },

  getDates: function () {
    return this.model.toJSON();
  },

  closeCalendar: function () {
    this.$('.DatePicker-dropdown').hide();
  },

  _onDocumentClick: function (e) {
    var $el = $(e.target);

    if ($el.closest('.DatePicker').length === 0) {
      this.closeCalendar();
    }
  },

  clean: function () {
    this._datesForm.remove();
    this._destroyBinds();
    this.closeCalendar();
    this.$('.DatePicker-calendar').DatePickerHide();
    CoreView.prototype.clean.call(this);
  }

});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.apache.taverna.server.master.worker.CompletionNotifier (Apache Taverna Server 3.1.0-incubating API)</title>
<meta name="date" content="2018-01-18">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.taverna.server.master.worker.CompletionNotifier

Packages that use CompletionNotifier

Package
Description

org.apache.taverna.server.master.worker

A Taverna Server back-end that works by forking off workflow executors.

Uses of CompletionNotifier in org.apache.taverna.server.master.worker

Classes in org.apache.taverna.server.master.worker that implement CompletionNotifier

Modifier and Type
Class and Description

class
SimpleFormattedCompletionNotifier

Completion notifier that sends messages by email.

class
VelocityCompletionNotifier

Methods in org.apache.taverna.server.master.worker with parameters of type CompletionNotifier

Modifier and Type
Method and Description

void
RunDBSupport.setNotifier(CompletionNotifier notifier)

void
RunDatabase.setNotifier(CompletionNotifier n)

Method parameters in org.apache.taverna.server.master.worker with type arguments of type CompletionNotifier

Modifier and Type
Method and Description

void
RunDatabase.setTypeNotifiers(List<CompletionNotifier> notifiers)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015–2018 The Apache Software Foundation. All rights reserved.


text:
that I'm trying to make for myself, based on [Skeleton](http://getskeleton.com).

Read the Skeleton_README file for information on Skeleton.


text:
@interface NSNull(IgnoreMessages)
- (void)forwardInvocation:(NSInvocation *)anInvocation;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
@end


text:
/* $Id: $ */

/////////////////////////////////////////////////
// AliAnalysisTaskCMEV0PID:
// analysis task for ZDC gain Equalization
// and CME analysis for identified particles
// using VZERO (and ZDC) Detector
// Author: Rihan Haque (mhaque@cern.ch)
// and R Sultana
/////////////////////////////////////////////////

#ifndef AliAnalysisTaskCMEV0PID_H
#define AliAnalysisTaskCMEV0PID_H

#include "AliAnalysisTaskSE.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH3F.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TList.h"
#include "TFile.h"
#include "TString.h"
#include "TProfile.h"
#include "TProfile2D.h"
#include "TStopwatch.h"

class    AliVEvent;
class    AliVVertex;
class    AliESDEvent;
class    AliAODEvent;
class    AliPIDResponse;
class    AliMultSelection;
class    AliAnalysisUtils;

class AliAnalysisTaskCMEV0PID : public AliAnalysisTaskSE {

 public:

  AliAnalysisTaskCMEV0PID();
  AliAnalysisTaskCMEV0PID(const char *name);
  virtual ~AliAnalysisTaskCMEV0PID();
  virtual void UserCreateOutputObjects();
  virtual void UserExec(Option_t * /*option*/);

  //User Defined Functions:
  void SetFilterBit(Int_t b)                  {this->fFilterBit = b;}
  void SetNSigmaCutTPC(Double_t b)            {this->fNSigmaCut = b;}
  void SetPtRangeMin(Double_t b)              {this->fMinPtCut  = b;}
  void SetPtRangeMax(Double_t b)              {this->fMaxPtCut  = b;}
  void SetEtaRangeMin(Double_t b)             {this->fMinEtaCut = b;}
  void SetEtaRangeMax(Double_t b)             {this->fMaxEtaCut = b;}

  void SetTrackCutdEdxMin(Float_t   dEd)      {this->fdEdxMin = dEd; }
  void SetTrackCutDCAxyMax(Double_t  dc)      {this->fDCAxyMax = dc; }
  void SetTrackCutDCAzMax(Double_t   dc)      {this->fDCAzMax  = dc; }
  void SetTrackCutChi2Min(Double_t  chi)      {this->fTrkChi2Min = chi; }
  void SetTrackCutNclusterMin(Int_t ncl)      {this->fTPCclustMin = ncl; }
  void SetFlagUseKinkTracks(Bool_t kink)      {this->bUseKinkTracks = kink; }

  void SetEventPlaneHarmonic(Int_t pn)            {this->gPsiN     = pn;}
  void SetHarmonicsFor3Particle(Int_t n, Int_t m) {this->gN = n; this->gM = m;}

  void SetCollisionSystem(TString s)          {this->sNucleiTP  = s;}
  void SetCentralityPercentileMin(Double_t b) {this->fCentralityPercentMin = b;}
  void SetCentralityPercentileMax(Double_t b) {this->fCentralityPercentMax = b;}
  void SetPileUpCutParam(Float_t m,Float_t c) {this->fPileUpSlopeParm = m;  this->fPileUpConstParm = c;}

  void SetFlagForMCcorrection(Bool_t b)       {this->bApplyMCcorr    = b;}
  void SetFlagV0MGainCorr(Bool_t b)           {this->bV0MGainCorr    = b;}
  void SetFlagSkipPileUpCuts(Bool_t b)        {this->bSkipPileUpCut  = b;}
  void SetFlagFillNUAforPID(Bool_t b)         {this->bFillNUAHistPID = b;}

  void SetFBEfficiencyList(TList *flist)      {this->fListFBHijing   = flist;}
  void SetFBEfficiencyFilePath(TString path)  {this->sPathOfMCFile   = path;}
  void SetListForNUACorr(TList *fln)          {this->fListNUACorr    = fln;}
  void SetListForV0MCorr(TList *flv)          {this->fListV0MCorr    = flv;}

 protected:

 private:

  AliVEvent             *fVevent;             //! event
  AliESDEvent           *fESD;                //! esd
  AliAODEvent           *fAOD;                //! aod
  AliPIDResponse        *fPIDResponse;        //! PID response Handler
  AliMultSelection      *fMultSelection;      //!
  AliAnalysisUtils      *fAnalysisUtil;       //! Event selection
  TList                 *fListHist;           //!
  TFile                 *mfileFBHijing;       //!
  TList                 *fListFBHijing;       //!
  TList                 *fListNUACorr;        //
  TList                 *fListV0MCorr;        //
  //histograms:
  TH1F         *fHistTaskConfigParameters;   //! Task input parameters FB / cut values etc.
  TH1F                  *fHistPileUpCount;   //!
  TH1F               *fHistMultSelPUCount;   //!
  TH2F                  *fHistEtaPtBefore;   //! Eta-Pt acceptance
  TH2F                   *fHistEtaPtAfter;   //! Eta-Pt acceptance
  TH2F        *fHistTPCvsGlobalMultBefore;   //!
  TH2F         *fHistTPCvsGlobalMultAfter;   //!

  TH2F             *fHistTPCdEdxvsPBefore;   //!
  TH2F              *fHistTPCdEdxvsPAfter;   //!
  TH2F             *fHistTOFBetavsPBefore;   //!
  TH2F              *fHistTOFBetavsPAfter;   //!
  TH2F            *fHistTOFMassvsPtBefore;   //!

  TH2F                *fHistTOFMatchCount;   //!

  TH2F            *fHistTPCVsESDTrkBefore;   //!
  TH2F             *fHistTPCVsESDTrkAfter;   //!

  TH2F           *fHistTPConlyVsCL1Before;   //!
  TH2F           *fHistTPConlyVsV0MBefore;   //!
  TH2F            *fHistTPConlyVsCL1After;   //!
  TH2F            *fHistTPConlyVsV0MAfter;   //!
  TH2F            *fHistGlobalVsV0MBefore;   //!
  TH2F             *fHistGlobalVsV0MAfter;   //!

  TH2F              *fHistRawVsCorrMultFB;   //!
  TH2F                *hCentvsTPCmultCuts;   //!

  TH2F             *fHV0AEventPlaneVsCent;   //!
  TH2F             *fHV0CEventPlaneVsCent;   //!
  TH2F            *fHTPCAEventPlaneVsCent;   //!
  TH2F            *fHTPCCEventPlaneVsCent;   //!
  TH2F                    *fV0MultChVsRun;   //!   To fill VOM multiplicity

  TH1F                   *fCentDistBefore;   //!   without PileUp cut
  TH1F                    *fCentDistAfter;   //!   with PileUp cut
  TH1D                      *fHCorrectV0M;   //!   To read Gain Correction file.
  TH2D                   *fHAvgerageQnV0A;   //!   V0A Average <Qn>, n=2,3
  TH2D                   *fHAvgerageQnV0C;   //!   V0C Average <Qn>, n=2,3

  TProfile              *fV0AQ2xVsCentRun; //!
  TProfile              *fV0AQ2yVsCentRun; //!
  TProfile              *fV0CQ2xVsCentRun; //!
  TProfile              *fV0CQ2yVsCentRun; //!
  TProfile              *fV0AQ3xVsCentRun; //!
  TProfile              *fV0AQ3yVsCentRun; //!
  TProfile              *fV0CQ3xVsCentRun; //!
  TProfile              *fV0CQ3yVsCentRun; //!

  TProfile              *fTPCAQ2xVsCentRun; //!
  TProfile              *fTPCAQ2yVsCentRun; //!
  TProfile              *fTPCCQ2xVsCentRun; //!
  TProfile              *fTPCCQ2yVsCentRun; //!
  TProfile              *fTPCAQ3xVsCentRun; //!
  TProfile              *fTPCAQ3yVsCentRun; //!
  TProfile              *fTPCCQ3xVsCentRun; //!
  TProfile              *fTPCCQ3yVsCentRun; //!
  TProfile              *fTPCAQ4xVsCentRun; //!
  TProfile              *fTPCAQ4yVsCentRun; //!
  TProfile              *fTPCCQ4xVsCentRun; //!
  TProfile              *fTPCCQ4yVsCentRun; //!

  TStopwatch                 watch;  //!

  Int_t                 fFilterBit;  //
  Int_t                         gN;  //
  Int_t                         gM;  //
  Int_t                      gPsiN;  //
  Int_t                 fOldRunNum;  //!
  Int_t                fEventCount;  //!
  Int_t               fTPCclustMin;  //

  Double_t               fNSigmaCut;  //
  Double_t                fMinPtCut;  //
  Double_t                fMaxPtCut;  //
  Double_t               fMinEtaCut;  //
  Double_t               fMaxEtaCut;  //
  Double_t              fTrkChi2Min;  //
  Double_t                fDCAxyMax;  //
  Double_t                 fDCAzMax;  //
  Float_t                  fdEdxMin;  //

  Double_t    fCentralityPercentMin;  //
  Double_t    fCentralityPercentMax;  //
  Double_t         fPileUpSlopeParm;  //
  Double_t         fPileUpConstParm;  //

  Bool_t               bApplyMCcorr;  //
  Bool_t               bV0MGainCorr;  //
  Bool_t             bSkipPileUpCut;  //
  Bool_t            bFillNUAHistPID;  //
  Bool_t             bUseKinkTracks;  //

  TString             sPathOfMCFile;  //
  TString                 sNucleiTP;  //

  TH1F            *fHistEventCount;   //!    last in the list

  //-------- Arrays ----------
  TH1F           *fHistPtwithTPCNsigma[3];   //!
  TH1F          *fHistPtwithTOFmasscut[3];   //!
  TH1F           *fHistPtwithTOFSignal[3];   //!
  TH2F        *fHistTOFnSigmavsPtAfter[3];   //!
  TH2F        *fHistTPCnSigmavsPtAfter[3];   //!
  TH3F     *fHistTPCTOFnSigmavsPtAfter[3];   //!
  TH2F       *fHistTPCdEdxvsPtPIDAfter[3];   //!

  TH3D                  *fHCorrectNUApos[5];   //! 5 centrality bin, read NUA from file
  TH3D                  *fHCorrectNUAneg[5];   //! 5 centrality bin, read NUA from file

  TH3D              *fHCorrectNUAposPion[5];   //! 5 centrality bin, read NUA from file
  TH3D              *fHCorrectNUAnegPion[5];   //! 5 centrality bin, read NUA from file

  TH3D              *fHCorrectNUAposKaon[5];   //! 5 centrality bin, read NUA from file
  TH3D              *fHCorrectNUAnegKaon[5];   //! 5 centrality bin, read NUA from file

  TH3D            *fHCorrectNUAposProton[5];   //! 5 centrality bin, read NUA from file
  TH3D            *fHCorrectNUAnegProton[5];   //! 5 centrality bin, read NUA from file

  //CME Using Event plane method: Charge
  TProfile     *fHist_Corr3p_EP_Norm_PN[2][4];  //!
  TProfile     *fHist_Corr3p_EP_Norm_PP[2][4];  //!
  TProfile     *fHist_Corr3p_EP_Norm_NN[2][4];  //!
  TProfile     *fHist_Reso2n_EP_Norm_Det[2][4]; //!

  //CME Using Event plane method: Pion
  TProfile     *fHist_Corr3p_Pion_EP_Norm_PN[2][4];  //!
  TProfile     *fHist_Corr3p_Pion_EP_Norm_PP[2][4];  //!
  TProfile     *fHist_Corr3p_Pion_EP_Norm_NN[2][4];  //!

  //CME Using Event plane method: Kaon
  TProfile     *fHist_Corr3p_Kaon_EP_Norm_PN[2][4];  //!
  TProfile     *fHist_Corr3p_Kaon_EP_Norm_PP[2][4];  //!
  TProfile     *fHist_Corr3p_Kaon_EP_Norm_NN[2][4];  //!

  //CME Using Event plane method: Proton
  TProfile     *fHist_Corr3p_Proton_EP_Norm_PN[2][4];  //!
  TProfile     *fHist_Corr3p_Proton_EP_Norm_PP[2][4];  //!
  TProfile     *fHist_Corr3p_Proton_EP_Norm_NN[2][4];  //!

  // NUA histograms:
  TH3F        *fHist3DEtaPhiVz_Pos_Run[4][5];  //! 4 particle 5 centrality bin
  TH3F        *fHist3DEtaPhiVz_Neg_Run[4][5];  //! 4 particle 5 centrality bin

  TH1D           *fFB_Efficiency_Cent[10];   //!

  //--------- PileUp Functions -----------
  Bool_t CheckEventIsPileUp(AliAODEvent* faod);
  Bool_t PileUpMultiVertex(const AliAODEvent* faod);
  double GetWDist(const AliVVertex* v0, const AliVVertex* v1);

  //for NUA and gain corrections:
  void  GetNUACorrectionHist(Int_t run);
  void  GetV0MCorrectionHist(Int_t run);

  //----------- other functions ----------
  void  SetUpCentralityOutlierCut();
  void  SetupEventAndTaskConfigInfo();
  void  SetupMCcorrectionMap(TString sMCfilePath);
  Int_t GetCentralityScaled0to10(Double_t fCent);

  AliAnalysisTaskCMEV0PID(const AliAnalysisTaskCMEV0PID &other);
  AliAnalysisTaskCMEV0PID &operator=(const AliAnalysisTaskCMEV0PID &other);
  ClassDef(AliAnalysisTaskCMEV0PID, 1)

};

#endif


text:
{{vm.kategori._id ? 'Edit Kategori' : 'New Kategori'}}

    <form name="vm.form.kategoriForm" class="form-horizontal" ng-submit="vm.save(vm.form.kategoriForm.$valid)" novalidate>
      <fieldset>

          Name
          <input name="name" type="text" ng-model="vm.kategori.name" id="name" class="form-control" placeholder="Name" required>

Kategori name is required.

          <button type="submit" class="btn btn-default">{{vm.kategori._id ? 'Update' : 'Create'}}</button>

      </fieldset>
    </form>


text:
Example Maven Pomless plugin

This is showcase for https://github.com/takari/takari-plugin-testing-project/issues/10


text:
package com.google.inject.grapher;

import com.google.common.base.Objects;
import com.google.inject.Key;

/**
 * ID of a node in the graph. An ID is given by a {@link Key} and a node type, which is used to
 * distinguish instances and implementation classes for the same key. For example
 * {@code bind(Integer.class).toInstance(42)} produces two nodes: an
 * interface node with the key of {@code Key<Integer>} and an instance node with the same
 * {@link Key} and value of 42.
 *
 * @author bojand@google.com (Bojan Djordjevic)
 */
public final class NodeId {

  /** Type of node. */
  public enum NodeType {
    /** Type or class node. */
    TYPE,

    /** Instance node, used when something is bound to an instance. */
    INSTANCE
  }

  private final Key<?> key;
  private final NodeType nodeType;

  private NodeId(Key<?> key, NodeType nodeType) {
    this.key = key;
    this.nodeType = nodeType;
  }

  public static NodeId newTypeId(Key<?> key) {
    return new NodeId(key, NodeType.TYPE);
  }

  public static NodeId newInstanceId(Key<?> key) {
    return new NodeId(key, NodeType.INSTANCE);
  }

  public Key<?> getKey() {
    return key;
  }

  @Override public int hashCode() {
    return Objects.hashCode(key, nodeType);
  }

  @Override public boolean equals(Object obj) {
    if (!(obj.getClass().equals(NodeId.class))) {
      return false;
    }
    NodeId other = (NodeId) obj;
    return Objects.equal(key, other.key) && Objects.equal(nodeType, other.nodeType);
  }

  @Override public String toString() {
    return "NodeId{nodeType=" + nodeType + " key=" + key + "}";
  }
}


text:
function [tlow, tup] = thresholds( GM, WM )
% FORMAT [tlow, tup] = thresholds (GM, WM)
%
% Bei den beiden Patametern handelt es sich um das Grey-Matter-Bild
% bzw. White-Matter-Bild.
% Mit dieser Funktion werden die beiden Schwellen berechnet, die für die
% Binarisierung benötigt werden.

gmMean = spm_summarise(GM, 'all', @mean);
gmStd = spm_summarise(GM, 'all', @std);
wmMean = spm_summarise(WM, 'all', @mean);
wmStd = spm_summarise(WM, 'all', @std);

tup = gmMean + 1/2*gmStd;
tlow = wmMean + 1/2*wmStd;

end


text:
package com.ebay.jetstream.event.processor;

import com.ebay.jetstream.event.JetstreamEvent;

/**
 * This is very special kind of event serving one and only one purpose: to let processor thread know that it's time to
 * say goodbye.
 *
 * @author snikolaev
 *
 */
public class ShutdownJetstreamEvent extends JetstreamEvent {

}


text:
package org.beesden.shop.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.beesden.shop.model.Address;
import org.beesden.shop.model.Basket;
import org.beesden.shop.model.Customer;
import org.beesden.shop.model.DeliveryCharge;
import org.beesden.shop.model.Tender;
import org.beesden.shop.service.BasketService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/checkout/")
public class CheckoutView extends ViewUpdate {

	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String placeOrder(HttpServletRequest request, ModelMap model) {
		logger.info("Placing order");
		Long start = System.currentTimeMillis();
		Map<String, Object> config = getConfig(request);
		// Don't process if the basket is empty
		if (basket.getItems() == null || basket.getItems().size() < 1) {
			return "redirect:/checkout/basket";
		}
		List<String> errors = updateBasket(request);
		errors = validateOrder(request, errors);
		if (errors.size() > 0) {
			request.getSession().setAttribute("messages", errors);
			return "redirect:/checkout/summary";
		}
		// Finalise the order attributes
		Basket order = basketService.assembleOrder(basket, fetchCustomer());
		order = basketService.objectCreate(order);
		model.addAttribute("order", order);
		basket.setOrderPlaced(new Date());
		return isAjax(model, request, "checkout.confirmation", config, start);
	}

	@RequestMapping(value = "/delivery", method = RequestMethod.GET)
	public String showDeliveryOptions(HttpServletRequest request, ModelMap model) {
		logger.info("Delivery options page requested");
		return isCheckout(model, request, "checkout.delivery");
	}

	@RequestMapping(value = "/confirmation", method = RequestMethod.GET)
	public String showOrderConfirmation(HttpServletRequest request, ModelMap model) {
		logger.info("Order confirmation page requested");
		return "redirect:/checkout/basket";
	}

	@RequestMapping(value = "/payment", method = RequestMethod.GET)
	public String showPayment(ModelMap model, HttpServletRequest request) {
		logger.info("Received request to show checkout summary");
		return isCheckout(model, request, "checkout.payment");
	}

	@RequestMapping(value = "/shipping", method = RequestMethod.GET)
	public String showShipping(HttpServletRequest request, ModelMap model) {
		logger.info("Shipping address page requested");
		return isCheckout(model, request, "checkout.shipping");
	}

	@RequestMapping(value = "/summary", method = RequestMethod.GET)
	public String showSummary(ModelMap model, HttpServletRequest request) {
		logger.info("Received request to show checkout summary");
		return isCheckout(model, request, "checkout.summary");
	}

	public List<String> updateBasket(HttpServletRequest request) {
		logger.info("Updating checkout details");
		List<String> errors = new ArrayList<String>();
		Customer customer = fetchCustomer();

		// Check for terms and conditions acceptance
		Boolean termsAgree = Boolean.parseBoolean(request.getParameter("termsAgree"));
		basket.setTermsAgree(termsAgree);

		// Select a delivery option
		String deliveryChargeId = request.getParameter("deliveryCharge");
		if (deliveryChargeId != null) {
			logger.info("Updating delivery charge");
			String dbQuery = deliveryChargeService.getQuery(deliveryChargeId, null, 1, null);
			DeliveryCharge charge = deliveryChargeService.findOne(dbQuery);
			if (charge != null) {
				basket.setDeliveryCharge(charge);
			}
		}

		// Generate initial address variables
		Address address = new Address();
		String selectAddress = request.getParameter("selectAddress");
		String addressId = request.getParameter("selectAddressId");
		String addressType = request.getParameter("addressType");
		// Create / update an address
		if (selectAddress != null) {
			if (selectAddress.equals("existingAddress")) {
				logger.info("Select a saved " + addressType + " address: " + addressId);
				String dbQuery = addressService.getQueryCustomer(addressId, customer.getId().toString(), 1);
				address = addressService.findOne(dbQuery);
				if (address == null) {
					errors = addError(errors, "invalid.address.id");
				}
			} else {
				logger.info("Create a new " + addressType + "address");
				address = createAddress(request, address, true);
				address.setCreatedBy(customer.getName());
				address.setDateCreated(new Date());
				address.setLastEditedBy(customer.getName());
				address.setLastEdited(new Date());
				// Link the address to the customer
				address.setCustomer(customer);
				addressService.objectUpdate(address);
			}
			// Attach address to basket if delivery
			if (addressType.equals("delivery")) {
				logger.info("Set delivery address");
				basket.setDeliveryAddress(address);
			}
		}

		// Generate initial payment details variables
		Tender paymentDetails = new Tender();
		if (basket.getPaymentDetails() != null) {
			paymentDetails = basket.getPaymentDetails();
		}
		String updatePayment = request.getParameter("updatePayment");
		String tenderId = request.getParameter("paymentId");

		if (updatePayment != null) {
			if (updatePayment.equals("savedTender") && tenderId != null) {
				logger.info("Select a saved payment card: " + tenderId);
				String dbQuery = tenderService.getQueryCustomer(tenderId, customer.getId().toString(), 1);
				paymentDetails = tenderService.findOne(dbQuery);
				if (paymentDetails == null) {
					errors = addError(errors, "invalid.tender.id");
				}
			} else if (updatePayment.equals("newTender")) {
				logger.info("Create a new payment card");
				paymentDetails = setPaymentDetails(request, paymentDetails);
				paymentDetails.setCustomer(customer);
				paymentDetails.setCreatedBy(customer.getName());
				paymentDetails.setDateCreated(new Date());
				tenderService.objectUpdate(paymentDetails);
			}

			// Attach address to order tender if payment
			if (addressType.equals("payment") && !updatePayment.equals("savedTender")) {
				logger.info("Set payment address");
				paymentDetails.setAddress(address);
			}
			;
			basket.setPaymentDetails(paymentDetails);
		}

		// Update the basket totals
		basket = BasketService.setTotals(basket);
		return errors;
	}

	@RequestMapping(value = "/delivery", method = RequestMethod.POST)
	public String updateDelivery(HttpServletRequest request, ModelMap model) {
		logger.info("Updating shipping address");
		List<String> errors = updateBasket(request);
		if (errors.size() > 0) {
			request.getSession().setAttribute("messages", errors);
			return "redirect:/checkout/delivery";
		}
		return "redirect:/checkout/payment";
	}

	@RequestMapping(value = "/payment", method = RequestMethod.POST)
	public String updatePayment(HttpServletRequest request, ModelMap model) {
		logger.info("Updating payment details");
		List<String> errors = updateBasket(request);
		if (errors.size() > 0) {
			request.getSession().setAttribute("messages", errors);
			return "redirect:/checkout/payment";
		}
		return "redirect:/checkout/summary";
	}

	@RequestMapping(value = "/shipping", method = RequestMethod.POST)
	public String updateShipping(HttpServletRequest request, ModelMap model) {
		logger.info("Updating shipping address");
		List<String> errors = updateBasket(request);
		if (errors.size() > 0) {
			request.getSession().setAttribute("messages", errors);
			return "redirect:/checkout/shipping";
		}
		return "redirect:/checkout/delivery";
	}

	public List<String> validateOrder(HttpServletRequest request, List<String> errors) {
		if (!basket.getTermsAgree()) {
			errors = addError(errors, "order.terms.agree");
		}
		if (basket.getDeliveryCharge() == null) {
			errors = addError(errors, "order.delivery.charge");
		}
		return errors;
	}
}


text:
fn main() {
	// 1) ; after expressions:
	let adult = true;
	let age = if adult { "+18"; } else { "-18"; };
	println!("Age is {:?}", age); // Age is ()
	// the following gives
	// error: mismatched types: expected `&str`, found `()` (expected &-ptr, found ())
	// let age: &str = if adult { "+18"; } else { "-18"; };

	// 2) block without {  } ?
	let n = 10;
	// if n > 5  println!("n is bigger than 5");
	// error: expected `{`, found `println`
	// help: place this code inside a block

	// 3) block without {  } ?
	let health = -3;
	// let result = if health <=0 { "Game over man!" };
	// error: if may be missing an else clause: expected `()`,
	// found `&'static str` (expected (), found &-ptr)
	// This doesn't work because the absence of the else part is viewed as else { () }
	//where () is a unit value of type (), which is not of type string
	// correction:
	let result = if health <=0 { "Game over man!" } else { "" };
}


text:
// @Filename: file1.ts
export class Calculator {
    handleChar() {}
}

export function test() {

}

export function test2() {

}

// @Filename: file2.ts
import c = require('./file1')


text:
const ClientCommand = require('./_base-command.js');

/**
 * Retrieves the current window position.
 *
 * For clients which are compatible with the [W3C Webdriver API](https://w3c.github.io/webdriver/), `getWindowPosition` is an alias of `getWindowRect`.
 *
 * The `getWindowRect` command returns both dimensions and position of the window, using the `windowRect` protocol command.
 *
 * @example
 * module.exports = {
 *   'demo test .getWindowPosition()': function(browser) {
 *      // Retrieve the attributes
 *      browser.getWindowPosition(function(value) {
 *        console.log(value);
 *      });
 *   },
 *
 *   'getWindowPosition ES6 demo test': async function(browser) {
 *      const value = await browser.getWindowPosition();
 *      console.log('value', value);
 *   }
 * }
 *
 * @method getWindowPosition
 * @syntax .getWindowPosition([callback])
 * @param {function} callback Callback function to be called when the command finishes.
 * @see windowRect
 * @api protocol.contexts
 */
class GetWindowPosition extends ClientCommand {
  get returnsFullResultObject() {
    return false;
  }

  get resolvesWithFullResultObject() {
    return false;
  }

  performAction(callback) {
    this.api.windowPosition('current', callback);
  }
}

module.exports = GetWindowPosition;


text:
import time
import httplib2
import simplejson

ASSOPYURL = 'http://assopy.pycon.it/conference/getinfo.py/'
CACHETIME = 5 * 60

_HTTP = httplib2.Http()
_CACHE = {}

def _get(url):
    now = time.time()
    try:
        timestamp, response = _CACHE[url]
    except KeyError:
        pass
    else:
        if now <= timestamp + CACHETIME:
            return response
    response = _HTTP.request(url)
    _CACHE[url] = time.time(), response

    return response

def attendeeCount():
    """
    Restituisce il numero di partecipanti al pycon
    """
    response, content = _get(ASSOPYURL + 'sold')
    try:
        return int(content)
    except (ValueError, TypeError):
        return -1

if __name__ == '__main__':
    print 'partecipanti', attendeeCount()