text:
package org.ebayopensource.turmeric.tools.annoparser.config;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.ebayopensource.turmeric.tools.annoparser.commons.FactoryTypes;
import org.ebayopensource.turmeric.tools.annoparser.context.Context;
import org.ebayopensource.turmeric.tools.annoparser.context.OutputGenaratorParam;
import org.ebayopensource.turmeric.tools.annoparser.exception.AnnotationParserException;
import org.ebayopensource.turmeric.tools.annoparser.exception.ConfigurationException;
import org.ebayopensource.turmeric.tools.annoparser.outputgenerator.OutputGenerator;
import org.ebayopensource.turmeric.tools.annoparser.parser.AnnotationParser;
import org.ebayopensource.turmeric.tools.annoparser.utils.Utils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * This Class reads the Configurations XML's and creates the context.
 *
 * @author sdaripelli
 */
public class ConfigurationReader {

	static {
		Logger.getLogger(ConfigurationReader.class.getName()).setLevel(
				Level.SEVERE);
	}

	/**
	 * Load configurations.
	 *
	 * @param configFile
	 *            the config file
	 */
	public static void loadConfigurations(String configFile) {
		try {
			loadConfigurations(convertToURL(configFile).openStream());
		} catch (IOException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Configuration File does not exist", e);
			throw new ConfigurationException(
					"Failed to load the configuration file. Configuration File does not exist. Cause for the exception: "
							+ e.getMessage(), e);
		}
	}

	/**
	 * Convert to url. The path supplied is first tried as a URL external form
	 * string, if it fails it is tried as a Class path resource, Then it is
	 * tried as a local file path.
	 *
	 * @param path
	 *            the path
	 * @return the uRL
	 */
	public static URL convertToURL(String path) {
		URL url = null;
		try {
			url = new URL(path);
		} catch (MalformedURLException e) {
			url = Thread.currentThread().getContextClassLoader()
					.getResource(path);
			if (url == null) {
				File file = new File(path);
				if (file.exists()) {
					try {
						url = file.toURI().toURL();
					} catch (MalformedURLException e1) {
						Logger.getLogger(ConfigurationReader.class.getName())
								.log(Level.SEVERE, path + " is Not valid", e);
						throw new ConfigurationException(
								"Failed to convert the " + path + "to URL/URI."
										+ path + " is Not valid", e);
					}
				}
			}
		}
		if (url == null) {
			throw new ConfigurationException("Failed to convert the " + path
					+ "to URL/URI." + path + " is Not valid");
		}
		return url;
	}

	/**
	 * Load configurations from the file path specified.
	 *
	 * @param config
	 *            the config
	 */
	public static void loadConfigurations(InputStream config) {

		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Entering loadConfigurations method in ConfigurationReader",
				config);
		try {
			// System.out.println("2" + config);
			Document document = getDocument(config);
			if (document == null) {
				Logger.getLogger(ConfigurationReader.class.getName()).log(
						Level.SEVERE, "Configuration File is not valid");
				throw new ConfigurationException(
						"Failed to load the Configuration. Configuration File is not valid");
			}
			Context context = Context.getContext();
			NodeList nodeList = document.getElementsByTagName("outputcss");
			Node node = nodeList.item(0);
			if (node != null) {
				String css = node.getTextContent();
				context.setCssFilePath(css);
			}

			populateAnnotationParsers(document, context);
			populateOutputGenerators(document, context);
			nodeList = document.getElementsByTagName("outputdir");
			node = nodeList.item(0);
			if (node != null) {
				String outputdir = node.getTextContent();
				context.setOutputDir(outputdir);
			}
			populateDocuments(document, context);
			populateFactoryClasses(document, context);
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.FINER,
					"Exiting loadConfigurations method in ConfigurationReader",
					new Object[] { document, context });
		} catch (SAXException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Configuration File not valid", e);
			StringBuffer sbf = new StringBuffer(
					"Failed to load Configuration file. Configuration File not valid. Cause for the failure: "
							+ e.getMessage());
			throw new ConfigurationException(sbf.toString(), e);
		} catch (IOException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Configuration File does not exist", e);
			StringBuffer sbf = new StringBuffer(
					"Failed to load Configuration file. Configuration File does not exist. Cause for the failure: "
							+ e.getMessage());
			throw new ConfigurationException(sbf.toString(), e);
		}
	}

	/**
	 * Load default configuration.
	 */
	public static void loadDefaultConfiguration() {
		InputStream is = ConfigurationReader.class.getClassLoader()
				.getResourceAsStream("Configuration.xml");
		Logger.getLogger(ConfigurationReader.class.getName())
				.log(Level.FINER,
						"Entering loadConfigurations method in ConfigurationReader",
						is);
		loadConfigurations(is);
	}

	/**
	 * Populate annotation parsers.
	 *
	 * @param document
	 *            the document
	 * @param context
	 *            the context
	 */
	private static void populateAnnotationParsers(Document document,
			Context context) {
		Logger.getLogger(ConfigurationReader.class.getName())
				.log(Level.FINER,
						"Entering populateAnnotationParsers method in ConfigurationReader",
						new Object[] { document, context });
		try {
			NodeList nodeList = document.getElementsByTagName("defaultparser");
			Node node = nodeList.item(0);
			if (node != null) {
				String defaultParser = node.getTextContent();

				if (defaultParser != null) {
					defaultParser = defaultParser.trim();
					if (!Utils.isEmpty(defaultParser)) {
						Class<? extends AnnotationParser> clazz = Thread
								.currentThread().getContextClassLoader()
								.loadClass(defaultParser.trim())
								.asSubclass(AnnotationParser.class);
						context.setDefaultAnnotationParser(clazz.newInstance());
					}
				}
			}

			nodeList = document.getElementsByTagName("annoparsers");
			node = (org.w3c.dom.Element) nodeList.item(0);
			if (node != null) {
				for (Node childNode = node.getFirstChild(); childNode != null;) {

					Node nextChild = childNode.getNextSibling();
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						String tagName = getTagValue(
								(org.w3c.dom.Element) childNode, "tagname");
						String parserClass = getTagValue(
								(org.w3c.dom.Element) childNode, "parserclass");
						if (tagName != null && parserClass != null) {
							Class<? extends AnnotationParser> clazz = Thread
									.currentThread().getContextClassLoader()
									.loadClass(parserClass.trim())
									.asSubclass(AnnotationParser.class);
							context.addParser(tagName, clazz.newInstance());
						}
					}
					childNode = nextChild;
				}
			}
		} catch (ClassNotFoundException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Custom Annotation Parser Class  Not Found.",
					e);
			throw new AnnotationParserException(
					"Failed to populate the Annotation Parser Class. Custom Annotation Parser Class  Not Found.",
					e);
		} catch (IllegalAccessException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE,
					"Could not access Custom Annotation Parser Class", e);
			throw new AnnotationParserException(
					"Failed to populate the Annotation Parser Class. Could not access Custom Annotation Parser Class ",
					e);
		} catch (InstantiationException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE,
					"Could not instantiate Custom Annotation Parser Class ", e);
		}
		Logger.getLogger(ConfigurationReader.class.getName())
				.log(Level.FINER,
						"Exiting populateAnnotationParsers method in ConfigurationReader",
						new Object[] { document, context });
	}

	private static void populateFactoryClasses(Document document,
			Context context) {
		Logger.getLogger(ConfigurationReader.class.getName())
				.log(Level.FINER,
						"Entering populateFactoryClasses method in ConfigurationReader",
						new Object[] { document, context });
		try {
			NodeList nodeList = document.getElementsByTagName("factoryclasses");
			Node node = (org.w3c.dom.Element) nodeList.item(0);
			if (node != null) {
				for (Node childNode = node.getFirstChild(); childNode != null;) {

					Node nextChild = childNode.getNextSibling();
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						String tagName = getTagValue(
								(org.w3c.dom.Element) childNode, "type");
						String parserClass = getTagValue(
								(org.w3c.dom.Element) childNode, "class");
						if (tagName != null && parserClass != null) {
							Class clazz = Thread.currentThread()
									.getContextClassLoader()
									.loadClass(parserClass.trim());
							context.addFactoryClass(
									FactoryTypes.valueOf(tagName), clazz);
						}
					}
					childNode = nextChild;
				}
			}
		} catch (ClassNotFoundException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Custom Annotation Parser Class  Not Found.",
					e);
			throw new AnnotationParserException(
					"Failed to populate the Factory Class. Class  Not Found.",
					e);
		}
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Exiting populateFactoryClasses method in ConfigurationReader",
				new Object[] { document, context });
	}

	/**
	 * Populate documents.
	 *
	 * @param document
	 *            the document
	 * @param context
	 *            the context
	 */
	private static void populateDocuments(Document document, Context context) {
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Entering populateDocuments in ConfigurationReader",
				new Object[] { document, context });
		NodeList nodeList = document.getElementsByTagName("documents");
		Node node = (org.w3c.dom.Element) nodeList.item(0);
		if (node != null) {
			for (Node childNode = node.getFirstChild(); childNode != null;) {

				Node nextChild = childNode.getNextSibling();
				if (childNode.getNodeType() == Node.ELEMENT_NODE) {
					String documentPath = childNode.getTextContent();
					context.addDocument(documentPath);

				}
				childNode = nextChild;
			}
		}
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Exiting populateDocuments in ConfigurationReader",
				new Object[] { document, context });
	}

	/**
	 * Populate output generators.
	 *
	 * @param document
	 *            the document
	 * @param context
	 *            the context
	 */
	private static void populateOutputGenerators(Document document,
			Context context) {
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Entering populateOutputGenerators in ConfigurationReader",
				new Object[] { document, context });
		NodeList nodeList = document.getElementsByTagName("outputgenerators");
		Node node = (org.w3c.dom.Element) nodeList.item(0);
		if (node != null) {
			for (Node childNode = node.getFirstChild(); childNode != null;) {
				Node nextChild = childNode.getNextSibling();
				if (childNode.getNodeType() == Node.ELEMENT_NODE) {
					String opgenName = getTagValue(
							(org.w3c.dom.Element) childNode, "class");
					String disabled = "false";
					if (childNode.getAttributes() != null
							&& childNode.getAttributes().getNamedItem(
									"disabled") != null) {
						disabled = childNode.getAttributes()
								.getNamedItem("disabled").getNodeValue();
					}
					String name = null;
					if (childNode.getAttributes() != null
							&& childNode.getAttributes().getNamedItem("name") != null) {
						name = childNode.getAttributes().getNamedItem("name")
								.getNodeValue();
					}
					if ("true".equals(disabled)) {
						if (context.getOutputGenerators() != null) {
							context.getOutputGenerators().remove(name);
						}
					} else if (opgenName != null) {
						try {
							OutputGenaratorParam outputGenaratorParam = new OutputGenaratorParam();
							Class<? extends OutputGenerator> clazz = Thread
									.currentThread().getContextClassLoader()
									.loadClass(opgenName.trim())
									.asSubclass(OutputGenerator.class);
							OutputGenerator generator = clazz.newInstance();
							outputGenaratorParam.setOutputGenerator(generator);
							outputGenaratorParam.setName(name);
							outputGenaratorParam.setOutputDir(getTagValue(
									(org.w3c.dom.Element) childNode,
									"outputdir"));
							outputGenaratorParam
									.setParameters(getOutputParameters(childNode));
							context.addOutputGenerator(outputGenaratorParam);
						} catch (ClassNotFoundException e) {
							Logger.getLogger(
									ConfigurationReader.class.getName()).log(
									Level.SEVERE,
									"Custom Output generator Class "
											+ opgenName + " Not Found.", e);
							throw new AnnotationParserException(
									"Failed to populate the Output Generator Class. Custom Output generator Class "
											+ opgenName + " Not Found.", e);
						} catch (IllegalAccessException e) {
							Logger.getLogger(
									ConfigurationReader.class.getName()).log(
									Level.SEVERE,
									"Could not access Output generator Class "
											+ opgenName, e);
							throw new AnnotationParserException(
									"Failed to populate the Output Generator Class. Could not access Output generator Class "
											+ opgenName, e);
						} catch (InstantiationException e) {
							Logger.getLogger(
									ConfigurationReader.class.getName()).log(
									Level.SEVERE,
									"Could not instantiate Output generator Class "
											+ opgenName, e);
							throw new AnnotationParserException(
									"Failed to populate the Output Generator Class. Could not instantiate Output generator Class "
											+ opgenName, e);
						}
					}
				}
				childNode = nextChild;
			}
		}
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Exiting populateOutputGenerators in ConfigurationReader",
				new Object[] { document, context });
	}

	/**
	 * Gets the output parameters.
	 *
	 * @param node
	 *            the node
	 * @return the output parameters
	 */
	private static Map<String, String> getOutputParameters(Node node) {
		Map<String, String> retMap = null;
		org.w3c.dom.Element element = (org.w3c.dom.Element) node;
		NodeList nodeList = element.getElementsByTagName("parameters");
		if (nodeList != null) {
			retMap = new HashMap<String, String>();
			org.w3c.dom.Element parametersElem = (org.w3c.dom.Element) nodeList
					.item(0);
			if (parametersElem != null) {
				NodeList parameters = parametersElem
						.getElementsByTagName("parameter");
				if (parameters != null) {
					for (int i = 0; i < parameters.getLength(); i++) {
						org.w3c.dom.Element parameter = (org.w3c.dom.Element) parameters
								.item(i);
						retMap.put(getTagValue(parameter, "name"),
								getTagValue(parameter, "value"));
					}
				}
			}
		}
		return retMap;
	}

	/**
	 * Gets the tag value.
	 *
	 * @param childNode
	 *            the child node
	 * @param tag
	 *            the tag
	 * @return the tag value
	 */
	private static String getTagValue(org.w3c.dom.Element childNode, String tag) {
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Entering getTagValue in ConfigurationReader",
				new Object[] { childNode, tag });
		String tagName = null;
		NodeList nodeList = childNode.getElementsByTagName(tag);
		Node node = (org.w3c.dom.Element) nodeList.item(0);
		if (node != null) {
			tagName = node.getTextContent();
		}
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Exiting getTagValue in ConfigurationReader", tag);
		return tagName;

	}

	/**
	 * Gets the document.
	 *
	 * @param config
	 *            the config
	 * @return the document
	 * @throws SAXException
	 *             the sAX exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private static Document getDocument(InputStream config)
			throws SAXException, IOException {
		Logger.getLogger(ConfigurationReader.class.getName()).log(Level.FINER,
				"Entering getDocument in ConfigurationReader",
				new Object[] { config });
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document doc = builder.parse(config);
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.FINER, "Exiting getDocument in ConfigurationReader",
					new Object[] { doc });
			return doc;
		} catch (ParserConfigurationException e) {
			Logger.getLogger(ConfigurationReader.class.getName()).log(
					Level.SEVERE, "Configuration File not correct", e);
			throw new ConfigurationException(
					"Failed to load the Configuration File. Configuration File is not valid. Cause for the Exception is : "
							+ e.getMessage(), e);
		}
	}
}


text:
package org.mockito.asm.util;

import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.List;

import org.mockito.asm.AnnotationVisitor;
import org.mockito.asm.Attribute;
import org.mockito.asm.ClassAdapter;
import org.mockito.asm.ClassReader;
import org.mockito.asm.ClassVisitor;
import org.mockito.asm.FieldVisitor;
import org.mockito.asm.MethodVisitor;
import org.mockito.asm.Opcodes;
import org.mockito.asm.Type;
import org.mockito.asm.tree.ClassNode;
import org.mockito.asm.tree.MethodNode;
import org.mockito.asm.tree.TryCatchBlockNode;
import org.mockito.asm.tree.analysis.Analyzer;
import org.mockito.asm.tree.analysis.Frame;
import org.mockito.asm.tree.analysis.SimpleVerifier;

/**
 * A {@link ClassAdapter} that checks that its methods are properly used. More
 * precisely this class adapter checks each method call individually, based
 * only on its arguments, but does not check the sequence
 * of method calls. For example, the invalid sequence
 * <tt>visitField(ACC_PUBLIC, "i", "I", null)</tt> <tt>visitField(ACC_PUBLIC,
 * "i", "D", null)</tt>
 * will not be detected by this class adapter.
 *
 *
CheckClassAdapter can be also used to verify bytecode
 * transformations in order to make sure transformed bytecode is sane. For
 * example:
 *
 *

 *   InputStream is = ...; // get bytes for the source class
 *   ClassReader cr = new ClassReader(is);
 *   ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
 *   ClassVisitor cv = new MyClassAdapter(new CheckClassAdapter(cw));
 *   cr.accept(cv, 0);
 *
 *   StringWriter sw = new StringWriter();
 *   PrintWriter pw = new PrintWriter(sw);
 *   CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), false, pw);
 *   assertTrue(sw.toString(), sw.toString().length()==0);
 *

 *
 * Above code runs transformed bytecode trough the
 * CheckClassAdapter. It won't be exactly the same verification
 * as JVM does, but it run data flow analysis for the code of each method and
 * checks that expectations are met for each method instruction.
 *
 *
If method bytecode has errors, assertion text will show the erroneous
 * instruction number and dump of the failed method with information about
 * locals and stack slot for each instruction. For example (format is -
 * insnNumber locals : stack):
 *
 *

 * org.mockito.asm.tree.analysis.AnalyzerException: Error at instruction 71: Expected I, but found .
 *   at org.mockito.asm.tree.analysis.Analyzer.analyze(Analyzer.java:289)
 *   at org.mockito.asm.util.CheckClassAdapter.verify(CheckClassAdapter.java:135)
 * ...
 * remove()V
 * 00000 LinkedBlockingQueue$Itr . . . . . . . .  :
 *   ICONST_0
 * 00001 LinkedBlockingQueue$Itr . . . . . . . .  : I
 *   ISTORE 2
 * 00001 LinkedBlockingQueue$Itr . I . . . . . .  :
 * ...
 *
 * 00071 LinkedBlockingQueue$Itr . I . . . . . .  :
 *   ILOAD 1
 * 00072 ?
 *   INVOKESPECIAL java/lang/Integer.<init> (I)V
 * ...
 *

 *
 * In the above output you can see that variable 1 loaded by
 * ILOAD 1 instruction at position 00071 is not
 * initialized. You can also see that at the beginning of the method (code
 * inserted by the transformation) variable 2 is initialized.
 *
 *
Note that when used like that, CheckClassAdapter.verify()
 * can trigger additional class loading, because it is using
 * SimpleVerifier.
 *
 * @author Eric Bruneton
 */
public class CheckClassAdapter extends ClassAdapter {

    /**
     * <tt>true</tt> if the visit method has been called.
     */
    private boolean start;

    /**
     * <tt>true</tt> if the visitSource method has been called.
     */
    private boolean source;

    /**
     * <tt>true</tt> if the visitOuterClass method has been called.
     */
    private boolean outer;

    /**
     * <tt>true</tt> if the visitEnd method has been called.
     */
    private boolean end;

    /**
     * Checks a given class.
 Usage: CheckClassAdapter <fully qualified
     * class name or class file name>
     *
     * @param args the command line arguments.
     *
     * @throws Exception if the class cannot be found, or if an IO exception
     *         occurs.
     */
    public static void main(final String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Verifies the given class.");
            System.err.println("Usage: CheckClassAdapter "
                    + "<fully qualified class name or class file name>");
            return;
        }
        ClassReader cr;
        if (args[0].endsWith(".class")) {
            cr = new ClassReader(new FileInputStream(args[0]));
        } else {
            cr = new ClassReader(args[0]);
        }

        verify(cr, false, new PrintWriter(System.err));
    }

    /**
     * Checks a given class
     *
     * @param cr a ClassReader that contains bytecode for the
     *        analysis.
     * @param dump true if bytecode should be printed out not only when errors
     *        are found.
     * @param pw write where results going to be printed
     */
    public static void verify(
        final ClassReader cr,
        final boolean dump,
        final PrintWriter pw)
    {
        ClassNode cn = new ClassNode();
        cr.accept(new CheckClassAdapter(cn), ClassReader.SKIP_DEBUG);

        Type syperType = cn.superName == null
                ? null
                : Type.getObjectType(cn.superName);
        List methods = cn.methods;
        for (int i = 0; i < methods.size(); ++i) {
            MethodNode method = (MethodNode) methods.get(i);
            Analyzer a = new Analyzer(new SimpleVerifier(Type.getObjectType(cn.name),
                    syperType,
                    false));
            try {
                a.analyze(cn.name, method);
                if (!dump) {
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace(pw);
            }
            Frame[] frames = a.getFrames();

            TraceMethodVisitor mv = new TraceMethodVisitor();

            pw.println(method.name + method.desc);
            for (int j = 0; j < method.instructions.size(); ++j) {
                method.instructions.get(j).accept(mv);

                StringBuffer s = new StringBuffer();
                Frame f = frames[j];
                if (f == null) {
                    s.append('?');
                } else {
                    for (int k = 0; k < f.getLocals(); ++k) {
                        s.append(getShortName(f.getLocal(k).toString()))
                                .append(' ');
                    }
                    s.append(" : ");
                    for (int k = 0; k < f.getStackSize(); ++k) {
                        s.append(getShortName(f.getStack(k).toString()))
                                .append(' ');
                    }
                }
                while (s.length() < method.maxStack + method.maxLocals + 1) {
                    s.append(' ');
                }
                pw.print(Integer.toString(j + 100000).substring(1));
                pw.print(" " + s + " : " + mv.buf); // mv.text.get(j));
            }
            for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
                ((TryCatchBlockNode) method.tryCatchBlocks.get(j)).accept(mv);
                pw.print(" " + mv.buf);
            }
            pw.println();
        }
        pw.flush();
    }

    private static String getShortName(final String name) {
        int n = name.lastIndexOf('/');
        int k = name.length();
        if (name.charAt(k - 1) == ';') {
            k--;
        }
        return n == -1 ? name : name.substring(n + 1, k);
    }

    /**
     * Constructs a new {@link CheckClassAdapter}.
     *
     * @param cv the class visitor to which this adapter must delegate calls.
     */
    public CheckClassAdapter(final ClassVisitor cv) {
        super(cv);
    }

    // ------------------------------------------------------------------------
    // Implementation of the ClassVisitor interface
    // ------------------------------------------------------------------------

    public void visit(
        final int version,
        final int access,
        final String name,
        final String signature,
        final String superName,
        final String[] interfaces)
    {
        if (start) {
            throw new IllegalStateException("visit must be called only once");
        }
        start = true;
        checkState();
        checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL
                + Opcodes.ACC_SUPER + Opcodes.ACC_INTERFACE
                + Opcodes.ACC_ABSTRACT + Opcodes.ACC_SYNTHETIC
                + Opcodes.ACC_ANNOTATION + Opcodes.ACC_ENUM
                + Opcodes.ACC_DEPRECATED);
        if (name == null || !name.endsWith("package-info")) {
            CheckMethodAdapter.checkInternalName(name, "class name");
        }
        if ("java/lang/Object".equals(name)) {
            if (superName != null) {
                throw new IllegalArgumentException("The super class name of the Object class must be 'null'");
            }
        } else {
            CheckMethodAdapter.checkInternalName(superName, "super class name");
        }
        if (signature != null) {
            CheckMethodAdapter.checkClassSignature(signature);
        }
        if ((access & Opcodes.ACC_INTERFACE) != 0) {
            if (!"java/lang/Object".equals(superName)) {
                throw new IllegalArgumentException("The super class name of interfaces must be 'java/lang/Object'");
            }
        }
        if (interfaces != null) {
            for (int i = 0; i < interfaces.length; ++i) {
                CheckMethodAdapter.checkInternalName(interfaces[i],
                        "interface name at index " + i);
            }
        }
        cv.visit(version, access, name, signature, superName, interfaces);
    }

    public void visitSource(final String file, final String debug) {
        checkState();
        if (source) {
            throw new IllegalStateException("visitSource can be called only once.");
        }
        source = true;
        cv.visitSource(file, debug);
    }

    public void visitOuterClass(
        final String owner,
        final String name,
        final String desc)
    {
        checkState();
        if (outer) {
            throw new IllegalStateException("visitOuterClass can be called only once.");
        }
        outer = true;
        if (owner == null) {
            throw new IllegalArgumentException("Illegal outer class owner");
        }
        if (desc != null) {
            CheckMethodAdapter.checkMethodDesc(desc);
        }
        cv.visitOuterClass(owner, name, desc);
    }

    public void visitInnerClass(
        final String name,
        final String outerName,
        final String innerName,
        final int access)
    {
        checkState();
        CheckMethodAdapter.checkInternalName(name, "class name");
        if (outerName != null) {
            CheckMethodAdapter.checkInternalName(outerName, "outer class name");
        }
        if (innerName != null) {
            CheckMethodAdapter.checkIdentifier(innerName, "inner class name");
        }
        checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE
                + Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC
                + Opcodes.ACC_FINAL + Opcodes.ACC_INTERFACE
                + Opcodes.ACC_ABSTRACT + Opcodes.ACC_SYNTHETIC
                + Opcodes.ACC_ANNOTATION + Opcodes.ACC_ENUM);
        cv.visitInnerClass(name, outerName, innerName, access);
    }

    public FieldVisitor visitField(
        final int access,
        final String name,
        final String desc,
        final String signature,
        final Object value)
    {
        checkState();
        checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE
                + Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC
                + Opcodes.ACC_FINAL + Opcodes.ACC_VOLATILE
                + Opcodes.ACC_TRANSIENT + Opcodes.ACC_SYNTHETIC
                + Opcodes.ACC_ENUM + Opcodes.ACC_DEPRECATED);
        CheckMethodAdapter.checkIdentifier(name, "field name");
        CheckMethodAdapter.checkDesc(desc, false);
        if (signature != null) {
            CheckMethodAdapter.checkFieldSignature(signature);
        }
        if (value != null) {
            CheckMethodAdapter.checkConstant(value);
        }
        FieldVisitor av = cv.visitField(access, name, desc, signature, value);
        return new CheckFieldAdapter(av);
    }

    public MethodVisitor visitMethod(
        final int access,
        final String name,
        final String desc,
        final String signature,
        final String[] exceptions)
    {
        checkState();
        checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE
                + Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC
                + Opcodes.ACC_FINAL + Opcodes.ACC_SYNCHRONIZED
                + Opcodes.ACC_BRIDGE + Opcodes.ACC_VARARGS + Opcodes.ACC_NATIVE
                + Opcodes.ACC_ABSTRACT + Opcodes.ACC_STRICT
                + Opcodes.ACC_SYNTHETIC + Opcodes.ACC_DEPRECATED);
        CheckMethodAdapter.checkMethodIdentifier(name, "method name");
        CheckMethodAdapter.checkMethodDesc(desc);
        if (signature != null) {
            CheckMethodAdapter.checkMethodSignature(signature);
        }
        if (exceptions != null) {
            for (int i = 0; i < exceptions.length; ++i) {
                CheckMethodAdapter.checkInternalName(exceptions[i],
                        "exception name at index " + i);
            }
        }
        return new CheckMethodAdapter(cv.visitMethod(access,
                name,
                desc,
                signature,
                exceptions));
    }

    public AnnotationVisitor visitAnnotation(
        final String desc,
        final boolean visible)
    {
        checkState();
        CheckMethodAdapter.checkDesc(desc, false);
        return new CheckAnnotationAdapter(cv.visitAnnotation(desc, visible));
    }

    public void visitAttribute(final Attribute attr) {
        checkState();
        if (attr == null) {
            throw new IllegalArgumentException("Invalid attribute (must not be null)");
        }
        cv.visitAttribute(attr);
    }

    public void visitEnd() {
        checkState();
        end = true;
        cv.visitEnd();
    }

    // ------------------------------------------------------------------------
    // Utility methods
    // ------------------------------------------------------------------------

    /**
     * Checks that the visit method has been called and that visitEnd has not
     * been called.
     */
    private void checkState() {
        if (!start) {
            throw new IllegalStateException("Cannot visit member before visit has been called.");
        }
        if (end) {
            throw new IllegalStateException("Cannot visit member after visitEnd has been called.");
        }
    }

    /**
     * Checks that the given access flags do not contain invalid flags. This
     * method also checks that mutually incompatible flags are not set
     * simultaneously.
     *
     * @param access the access flags to be checked
     * @param possibleAccess the valid access flags.
     */
    static void checkAccess(final int access, final int possibleAccess) {
        if ((access & ~possibleAccess) != 0) {
            throw new IllegalArgumentException("Invalid access flags: "
                    + access);
        }
        int pub = (access & Opcodes.ACC_PUBLIC) == 0 ? 0 : 1;
        int pri = (access & Opcodes.ACC_PRIVATE) == 0 ? 0 : 1;
        int pro = (access & Opcodes.ACC_PROTECTED) == 0 ? 0 : 1;
        if (pub + pri + pro > 1) {
            throw new IllegalArgumentException("public private and protected are mutually exclusive: "
                    + access);
        }
        int fin = (access & Opcodes.ACC_FINAL) == 0 ? 0 : 1;
        int abs = (access & Opcodes.ACC_ABSTRACT) == 0 ? 0 : 1;
        if (fin + abs > 1) {
            throw new IllegalArgumentException("final and abstract are mutually exclusive: "
                    + access);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation DSTBlockButton

- (DSTBlockButton *)initWithTitle:(NSString *)title block:(DSTButtonPressBlock)block {
    self = [super init];
    if (self) {
        _title = title;
        _block = block;
    }
    return self;
}

+ (DSTBlockButton *)buttonWithTitle:(NSString *)title block:(DSTButtonPressBlock)block {
    return [[DSTBlockButton alloc] initWithTitle:title block:block];
}

@end


text:
module Olson

using Base.Dates

import ..TimeZones: TZDATA_DIR, COMPILED_DIR, ZERO, MIN_GMT_OFFSET, MAX_GMT_OFFSET,
    MIN_SAVE, MAX_SAVE, ABS_DIFF_OFFSET, Time, toseconds
import ..TimeZones: TimeZone, FixedTimeZone, VariableTimeZone, Transition, Time

const REGIONS = (
    "africa", "antarctica", "asia", "australasia",
    "europe", "northamerica", "southamerica",
)

# Zone type maps to an Olson Timezone database entity
type Zone
    gmtoffset::Time
    save::Time
    rules::AbstractString
    format::AbstractString
    until::Nullable{DateTime}
    until_flag::Char
end

function Base.isless(x::Zone,y::Zone)
    x_dt = get(x.until, typemax(DateTime))
    y_dt = get(y.until, typemax(DateTime))

    # Easy to compare until's if they are using the same flag. Alternatively, it should
    # be safe to compare different until flags if the DateTimes are far enough apart.
    if x.until_flag == y.until_flag || abs(x_dt - y_dt) > ABS_DIFF_OFFSET
        return isless(x_dt, y_dt)
    else
        error("Unable to compare zones when until datetimes are too close and flags are mixed")
    end
end

# Rules govern how Daylight Savings transitions happen for a given timezone
type Rule
    from::Nullable{Int}  # First year rule applies
    to::Nullable{Int}    # Rule applies up until, but not including this year
    month::Int           # Month in which DST transition happens
    on::Function         # Anonymous boolean function to determine day
    at::Time             # Hour and minute at which the transition happens
    at_flag::Char        # Local wall time (w), UTC time (u), Local Standard time (s)
    save::Time           # How much time is "saved" in daylight savings transition
    letter::AbstractString  # Timezone abbr letter(s). ie. CKT ("") => CKHST ("HS")
end

typealias ZoneDict Dict{AbstractString,Array{Zone}}
typealias RuleDict Dict{AbstractString,Array{Rule}}
typealias OrderedRuleDict Dict{AbstractString,Array{Tuple{Date,Rule}}}

# Min and max years that we create DST transition instants for (inclusive)
const MINYEAR = 1800
const MAXYEAR = 2038

const MINDATETIME = DateTime(MINYEAR,1,1)
const MAXDATETIME = DateTime(MAXYEAR,12,31)

# Helper functions/data
const MONTHS = Dict("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,
                "Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12)

const DAYS = Dict("Mon"=>1,"Tue"=>2,"Wed"=>3,"Thu"=>4,"Fri"=>5,"Sat"=>6,"Sun"=>7)

# Create adjuster functions such as "lastSun".
for (abbr, dayofweek) in DAYS
    sym = symbol("last" * abbr)
    @eval (
        function $sym(dt)
            return dayofweek(dt) == $dayofweek &&
            dayofweekofmonth(dt) == daysofweekinmonth(dt)
        end
    )
end

function parseflag(s::AbstractString)
    if s == "" || s == "w"
        return 'w'
    elseif s == "u"
        return 'u'
    elseif s == "s"
        return 's'
    else
        error("Unhandled flag $s")
    end
end

# Olson timezone dates can be a single year (1900), yyyy-mm-dd (1900-Jan-01),
# or minute-precision (1900-Jan-01 2:00).
# They can also be given in Local Wall Time, UTC time (u), or Local Standard time (s)
function parsedate(s::AbstractString)
    s = replace(s, r"\s+", " ")
    num_periods = length(split(s, " "))
    s, flag = num_periods > 3 && isalpha(s[end]) ? (s[1:end-1], s[end:end]) : (s, "")
    if contains(s,"lastSun")
        dt = DateTime(replace(s, "lastSun", "1", 1), "yyyy uuu d H:MM:SS")
        dt = tonext(lastSun, dt; same=true)
    elseif contains(s,"lastSat")
        dt = DateTime(replace(s, "lastSat", "1", 1), "yyyy uuu d H:MM:SS")
        dt = tonext(lastSat, dt; same=true)
    elseif contains(s,"Sun>=1")
        dt = DateTime(replace(s,"Sun>=", "", 1),"yyyy uuu d H:MM:SS")
        dt = tonext(d -> dayofweek(d) == Sun, dt; same=true)
    else
        format = join(split("yyyy uuu dd HH:MM:SS", " ")[1:num_periods], ' ')
        periods = Dates.parse(s, DateFormat(format))

        # Deal with zone "Pacific/Apia" which has a 24:00 datetime.
        if length(periods) > 3 && periods[4] == Hour(24)
            periods[4] = Hour(0)
            periods[3] += Day(1)
        end
        dt = DateTime(periods...)
    end

    # TODO: I feel like there are issues here.
    # If the time is UTC, we add back the offset and any saved amount
    # If it's local standard time, we just need to add any saved amount
    # return letter == 's' ? (dt - save) : (dt - offset - save)

    return dt, parseflag(flag)
end

function asutc(dt::DateTime, flag::Char, offset::Time, save::Time)
    if flag == 'u'
        # In UTC
        return dt
    elseif flag == 'w'
        # In local wall time, add back offset and saved amount
        return dt - offset - save
    elseif flag == 's'
        # In local standard time, add back any saved amount
        return dt - offset
    else
        error("Unknown flag: $flag")
    end
end

function ruleparse(from, to, rule_type, month, on, at, save, letter)
    from_int = Nullable{Int}(from == "min" ? nothing : parse(Int, from))
    to_int = Nullable{Int}(to == "only" ? from_int : to == "max" ? nothing : parse(Int, to))
    month_int = MONTHS[month]

    # Now we need to get the right anonymous function
    # for determining the right day for transitioning
    if ismatch(r"last\w\w\w", on)
        # We pre-built these functions above
        # They follow the format: "lastSun", "lastMon".
        on_func = eval(symbol(on))
    elseif ismatch(r"\w\w\w[<>]=\d\d?", on)
        # The first day of the week that occurs before or after a given day of month.
        # i.e. Sun>=8 refers to the Sunday after the 8th of the month
        # or in other words, the 2nd Sunday.
        dow = DAYS[match(r"\w\w\w", on).match]
        dom = parse(Int, match(r"\d\d?", on).match)
        if ismatch(r"<=", on)
            on_func = @eval (dt -> day(dt) <= $dom && dayofweek(dt) == $dow)
        else
            on_func = @eval (dt -> day(dt) >= $dom && dayofweek(dt) == $dow)
        end
    elseif ismatch(r"\d\d?", on)
        # Matches just a plain old day of the month
        dom = parse(Int, on)
        on_func = @eval (dt -> day(dt) == $dom)
    else
        error("Can't parse day of month for DST change")
    end
    # Now we get the time of the transition
    c = at[end:end]
    at_hm = Time(isalpha(c) ? at[1:end-1] : at)
    at_flag = parseflag(isalpha(c) ? c : "")
    save_hm = Time(save)
    letter = letter == "-" ? "" : letter

    # Report unexpected save values that could cause issues during resolve.
    save_hm < MIN_SAVE && warn("Discovered save $save_hm less than the expected min $MIN_SAVE")
    save_hm > MAX_SAVE && warn("Discovered save $save_hm larger than the expected max $MAX_SAVE")

    # Now we've finally parsed everything we need
    return Rule(
        from_int,
        to_int,
        month_int,
        on_func,
        at_hm,
        at_flag,
        save_hm,
        letter,
    )
end

function zoneparse(gmtoff, rules, format, until="")
    # Get our offset and abbreviation string for this period
    offset = Time(gmtoff)

    # Report unexpected offsets that could cause issues during resolve.
    offset < MIN_GMT_OFFSET && warn("Discovered offset $offset less than the expected min $MIN_GMT_OFFSET")
    offset > MAX_GMT_OFFSET && warn("Discovered offset $offset larger than the expected max $MAX_GMT_OFFSET")

    format = format == "zzz" ? "" : format

    # Parse the date the line rule applies up to
    until_tuple = until == "" ? (nothing, 'w') : parsedate(until)
    until_dt, until_flag = Nullable{DateTime}(until_tuple[1]), until_tuple[2]

    if rules == "-" || ismatch(r"\d",rules)
        save = Time(rules)
        rules = ""
    else
        save = ZERO
    end

    return Zone(
        offset,
        save,
        rules,
        format,
        until_dt,
        until_flag,
    )
end

"""
Rules are typically ordered by the "from" than "in" fields. Since rules also
contain a "to" field the written ordering can be problematic for resolving
timezone transitions.

Example:

    # Rule  NAME    FROM    TO  TYPE    IN  ON  AT      SAVE    LETTER/S
    Rule    Poland  1918    1919    -   Sep 16  2:00s   0       -
    Rule    Poland  1919    only    -   Apr 15  2:00s   1:00    S
    Rule    Poland  1944    only    -   Apr  3  2:00s   1:00    S

    Processing rules by iterating through years would generate:

    # ON         AT      SAVE    LETTER/S
    1918-09-16   2:00s   0       -
    1919-09-16   2:00s   0       -
    1919-04-15   2:00s   1:00    S
    1944-04-03   2:00s   1:00    S
"""
function order_rules(rules::Array{Rule})
    date_rules = Tuple{Date,Rule}[]

    # Note: Typically rules are orderd by "from" and "in". Unfortunately
    for rule in rules
        # Replicate the rule for each year that it is effective.
        for rule_year in get(rule.from, MINYEAR):get(rule.to, MAXYEAR)
            # Determine the rule transition day by starting at the
            # beginning of the month and applying our "on" function
            # until we reach the correct day.
            date = Date(rule_year, rule.month)
            try
                # The "on" function should evaluate to a day within the current month.
                date = tonext(rule.on, date; same=true, limit=daysinmonth(date))
            catch e
                if isa(e, ArgumentError)
                    error("Unable to find matching day in month $(year(date))/$(month(date))")
                else
                    rethrow(e)
                end
            end
            push!(date_rules, (date, rule))
        end
    end

    sort!(date_rules, by=el -> el[1])

    # Since we are not yet taking offsets or flags into account yet
    # there is a small chance that the results are not ordered correctly.
    last_date = typemin(Date)
    for (i, (date, rule)) in enumerate(date_rules)
        if i > 1 && date - last_date <= ABS_DIFF_OFFSET
            error("Dates are probably not in order")
        end
        last_date = date
    end

    return date_rules
end

"""
Resolves a named zone into TimeZone. Updates ordered with any new rules that
were required to be ordered.
"""
function resolve!(zone_name::AbstractString, zoneset::ZoneDict, ruleset::RuleDict,
    ordered::OrderedRuleDict; debug=false)

    transitions = Transition[]

    # Set some default values and starting DateTime increment and away we go...
    start_utc = MINDATETIME
    save = ZERO
    letter = ""

    ordered_rules = Dict{AbstractString,Array{Tuple{Date,Rule}}}()
    # zones = Set{FixedTimeZone}()

    # Zone needs to be in ascending order to ensure that start_utc is being applied
    # to the correct transition.
    for zone in sort(zoneset[zone_name])
        offset = zone.gmtoffset
        format = zone.format
        # save = zone.save
        rule_name = zone.rules
        until = get(zone.until, MAXDATETIME)

        if rule_name == ""
            save = zone.save
            abbr = format

            if debug
                rule_name = "\"\""  # Just for display purposes
                println("Zone Start $rule_name, $(zone.gmtoffset), $save, $(start_utc)u, $(until)$(zone.until_flag), $abbr")
            end

            tz = FixedTimeZone(abbr, toseconds(offset), toseconds(save))
            push!(transitions, Transition(start_utc, tz))
        else
            if !haskey(ordered, rule_name)
                ordered[rule_name] = order_rules(ruleset[rule_name])
            end

            # TODO: We could avoid this search if the rule_name haven't changed since the
            # last iteration.
            rules = ordered[rule_name]
            index = searchsortedlast(rules, start_utc, by=el -> isa(el, Tuple) ? el[1] : el)

            # If start occurs prior to the first rule it can be expected in standard-time.
            if index == 0
                save = ZERO

                # Find the first occurrence of of standard-time
                for (date, rule) in rules
                    if rule.save == save
                        letter = rule.letter
                        break
                    end
                end
            else
                date, rule = rules[index]
                save = rule.save
                letter = rule.letter
            end

            # Note: using @sprintf would make sense but unfortunately it doesn't accept a
            # format as a variable.
            abbr = replace(format,"%s",letter,1)

            debug && println("Zone Start $rule_name, $(zone.gmtoffset), $save, $(start_utc)u, $(until)$(zone.until_flag), $abbr")

            tz = FixedTimeZone(abbr, toseconds(offset), toseconds(save))
            push!(transitions, Transition(start_utc, tz))

            for (date, rule) in rules[max(index,1):end]
                # TODO: Problematic if rule date close to until and offset is a large positive.
                date > until && break

                # Add "at" since it could be larger than 23:59:59.
                dt = DateTime(date) + rule.at

                # Convert rule and until datetimes into UTC using the latest
                # offset and save values that occurred prior to this rule.
                dt_utc = asutc(dt, rule.at_flag, offset, save)
                until_utc = asutc(until, zone.until_flag, offset, save)

                dt_utc < until_utc || break

                # Need to be careful when we update save/letter.
                save = rule.save
                letter = rule.letter
                abbr = replace(format,"%s",letter,1)

                if debug
                    status = start_utc <= dt_utc ? "Rule" : "Skip"
                    println("$status $(year(date)), $(dt)$(rule.at_flag), $(dt_utc)u, $save, $abbr")
                end

                # TODO: Is start_utc inclusive or exclusive?
                start_utc <= dt_utc || continue

                tz = FixedTimeZone(abbr, toseconds(offset), toseconds(save))

                # TODO: We can maybe reduce memory usage by reusing the same
                # FixedTimeZone object.
                # Note: By default pushing onto a set will replace objects.
                # if !(tz in zones)
                #     push!(zones, tz)
                # else
                #     tz = first(intersect(zones, Set([tz])))
                # end

                push!(transitions, Transition(dt_utc, tz))
            end
        end

        start_utc = asutc(until, zone.until_flag, offset, save)

        debug && println("Zone End   $rule_name, $offset, $save, $(start_utc)u")
        start_utc >= MAXDATETIME && break
    end

    # Note: Transitions array is expected to be ordered and should be if both
    # zones and rules were ordered.
    if length(transitions) > 1
        return VariableTimeZone(zone_name, transitions)
    else
        # Although unlikely the timezone name in the transition and the zone_name
        # could be different. We'll ignore this issue at the moment.
        return transitions[1].zone
    end
end

function resolve(zoneset::ZoneDict, ruleset::RuleDict; debug=false)
    ordered = OrderedRuleDict()
    timezones = Dict{AbstractString,TimeZone}()

    for zone_name in keys(zoneset)
        tz = resolve!(zone_name, zoneset, ruleset, ordered, debug=debug)
        timezones[zone_name] = tz
    end

    return timezones
end

function resolve(zone_name::AbstractString, zoneset::ZoneDict, ruleset::RuleDict; debug=false)
    ordered = OrderedRuleDict()
    return resolve!(zone_name, zoneset, ruleset, ordered, debug=debug)
end

function tzparse(tzfile::AbstractString)
    zones = ZoneDict()
    rules = RuleDict()
    links = Dict{AbstractString,AbstractString}()

    # For the intial pass we'll collect the zone and rule lines.
    open(tzfile) do fp
        kind = name = ""
        for line in eachline(fp)
            # Lines that start with whitespace can be considered a "continuation line"
            # which means the last found kind/name should persist.
            persist = ismatch(r"^\s", line)

            line = strip(replace(chomp(line), r"#.*$", ""))
            length(line) > 0 || continue
            line = replace(line, r"\s+", " ")

            if !persist
                kind, name, line = split(line, ' '; limit=3)
            end

            if kind == "Rule"
                rule = ruleparse(split(line, ' ')...)
                rules[name] = push!(get(rules, name, Rule[]), rule)
            elseif kind == "Zone"
                zone = zoneparse(split(line, ' '; limit=4)...)
                zones[name] = push!(get(zones, name, Zone[]), zone)
            elseif kind == "Link"
                dest = line
                links[dest] = name
            else
                warn("Unhandled line found with type: $kind")
            end
        end
    end

    # Turn links into zones.
    # Note: it would be more computationally efficient to pass the links around
    # and only resolve a zone once.
    for (dest, source) in links
        zones[dest] = zones[source]
    end

    return zones, rules
end

function load(tzdata_dir::AbstractString=TZDATA_DIR)
    timezones = Dict{AbstractString,TimeZone}()
    for region in REGIONS
        zones, rules = tzparse(joinpath(tzdata_dir, region))
        merge!(timezones, resolve(zones, rules))
    end
    return timezones
end

function compile(tzdata_dir::AbstractString=TZDATA_DIR, dest_dir::AbstractString=COMPILED_DIR)
    timezones = load(tzdata_dir)

    isdir(dest_dir) || error("Destination directory doesn't exist")

    for (name, timezone) in timezones
        parts = split(name, "/")
        tz_dir, tz_file = joinpath(dest_dir, parts[1:end-1]...), parts[end]

        isdir(tz_dir) || mkpath(tz_dir)

        open(joinpath(tz_dir, tz_file), "w") do fp
            serialize(fp, timezone)
        end
    end
end

end # module


text:
<?php

/* @Framework/FormTable/button_row.html.php */
class __TwigTemplate_3dac14d39f36c55dd4f75d907f87f8f4094c2e8a5448161696b0a485cbce2cb0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_070f72927efddd3de60d4f177e408f745e9f5740a84da822711d9cd5363fc883 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_070f72927efddd3de60d4f177e408f745e9f5740a84da822711d9cd5363fc883->enter($__internal_070f72927efddd3de60d4f177e408f745e9f5740a84da822711d9cd5363fc883_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Framework/FormTable/button_row.html.php"));

        // line 1
        echo "

        <?php echo \$view['form']->widget(\$form) ?>

";

        $__internal_070f72927efddd3de60d4f177e408f745e9f5740a84da822711d9cd5363fc883->leave($__internal_070f72927efddd3de60d4f177e408f745e9f5740a84da822711d9cd5363fc883_prof);

    }

    public function getTemplateName()
    {
        return "@Framework/FormTable/button_row.html.php";
    }

    public function getDebugInfo()
    {
        return array (  22 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("

        <?php echo \$view['form']->widget(\$form) ?>

", "@Framework/FormTable/button_row.html.php", "C:\\wamp\\www\\ecommerce\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\FrameworkBundle\\Resources\\views\\FormTable\\button_row.html.php");
    }
}


text:
.. _reference/worker:

=============================
Working off Asynchronous Jobs
=============================

A merchant implementation serving **django-SHOP**, usually runs a few asynchronous jobs, such as
cleaning stale entries, sending e-mail and building the search index. In Django, there are many
ways to handle this, usually by integrating `Celery into Django`_. However, a Celery setup is
unnecessarily complicated and usually not required. Instead we can handle all of our asynchronous
jobs using a short Python script, referred to as "The Worker" in the documentation. This
stand-alone program runs in the same environment as our Django app.

Here is a short example, which can be used as a blueprint for your own implementation:

.. code-block:: python
	:caption: worker.py

	#!/usr/bin/env python
	import os
	import redis
	import schedule
	import time

	if __name__ == '__main__':
	    from django import setup
	    from django.conf import settings
	    from django.core.management import call_command

	    # initialize Django
	    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_shop.settings')
	    setup()

	    # schedule jobs
	    schedule.every().sunday.do(call_command, 'shopcustomers', delete_expired=True)
	    schedule.every().day.at('10:00').do(call_command, 'rebuild_index', interactive=False)
	    schedule.every().minute.do(call_command, 'send_queued_mail')

	    if hasattr(settings, 'SESSION_REDIS'):
	        redis_con = dict((key, settings.SESSION_REDIS[key]) for key in ['host', 'port', 'db', 'socket_timeout'])
	        pool = redis.ConnectionPool(**redis_con)
	        r = redis.Redis(connection_pool=pool)
	        pubsub = r.pubsub()
	        pubsub.subscribe('django-SHOP')
	    else:
	        # we don't have a Redis message queue, emulate `pubsub`
	        pubsub = type(str('PubSub'), (), {'get_message': lambda s, timeout=1: time.sleep(timeout)})()

	    while True:  # the main loop
	        message = pubsub.get_message(timeout=60)
	        if message and message['data'] == 'send_queued_mail':
	            call_command('send_queued_mail')
	        schedule.run_pending()

Here we schedule three jobs:

* Once a week we remove customers, whose session expired and which never made it to the checkout.
* Once a day we rebuild the search index for the Elasticsearch database.
* At least once a minute we send emails pending in the queue. If Redis is configured, **django-SHOP**
  uses its internal message broker, and whenever an email is added to the queue, the asynchronous
  worker is notified, in order to send it straightaway.

.. _Celery into Django: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html


text:
/** @file awa_clientd_cmdline.h
 *  @brief The header file for the command line option parser
 *  generated by GNU Gengetopt version 2.22.6
 *  http://www.gnu.org/software/gengetopt.
 *  DO NOT modify this file, since it can be overwritten
 *  @author GNU Gengetopt by Lorenzo Bettini */

#ifndef AWA_CLIENTD_CMDLINE_H
#define AWA_CLIENTD_CMDLINE_H

/* If we use autoconf.  */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h> /* for FILE */

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#ifndef CMDLINE_PARSER_PACKAGE
/** @brief the program name (used for printing errors) */
#define CMDLINE_PARSER_PACKAGE "awa_clientd"
#endif

#ifndef CMDLINE_PARSER_PACKAGE_NAME
/** @brief the complete program name (used for help and version) */
#define CMDLINE_PARSER_PACKAGE_NAME "awa_clientd"
#endif

#ifndef CMDLINE_PARSER_VERSION
/** @brief the program version */
#define CMDLINE_PARSER_VERSION VERSION
#endif

/** @brief Where the command line options are stored */
struct gengetopt_args_info
{
  const char *help_help; /**< @brief Print help and exit help description.  */
  int port_arg;	/**< @brief Use local port number PORT for CoAP communications - zero will select random port (default='0').  */
  char * port_orig;	/**< @brief Use local port number PORT for CoAP communications - zero will select random port original value given at command line.  */
  const char *port_help; /**< @brief Use local port number PORT for CoAP communications - zero will select random port help description.  */
  int addressFamily_arg;	/**< @brief Address family for network interface. AF=4 for IPv4, AF=6 for IPv6 (default='4').  */
  char * addressFamily_orig;	/**< @brief Address family for network interface. AF=4 for IPv4, AF=6 for IPv6 original value given at command line.  */
  const char *addressFamily_help; /**< @brief Address family for network interface. AF=4 for IPv4, AF=6 for IPv6 help description.  */
  int ipcPort_arg;	/**< @brief Use port number PORT for IPC communications (default='12345').  */
  char * ipcPort_orig;	/**< @brief Use port number PORT for IPC communications original value given at command line.  */
  const char *ipcPort_help; /**< @brief Use port number PORT for IPC communications help description.  */
  char * endPointName_arg;	/**< @brief Use NAME as client end point name (default='Awa Client').  */
  char * endPointName_orig;	/**< @brief Use NAME as client end point name original value given at command line.  */
  const char *endPointName_help; /**< @brief Use NAME as client end point name help description.  */
  char * bootstrap_arg;	/**< @brief Use bootstrap server URI.  */
  char * bootstrap_orig;	/**< @brief Use bootstrap server URI original value given at command line.  */
  const char *bootstrap_help; /**< @brief Use bootstrap server URI help description.  */
  char * factoryBootstrap_arg;	/**< @brief Load factory bootstrap information from FILE.  */
  char * factoryBootstrap_orig;	/**< @brief Load factory bootstrap information from FILE original value given at command line.  */
  const char *factoryBootstrap_help; /**< @brief Load factory bootstrap information from FILE help description.  */
  int secure_flag;	/**< @brief CoAP communications are secured with DTLS (default=off).  */
  const char *secure_help; /**< @brief CoAP communications are secured with DTLS help description.  */
  char * pskIdentity_arg;	/**< @brief Default Identity of associated pre-shared key for DTLS.  */
  char * pskIdentity_orig;	/**< @brief Default Identity of associated pre-shared key for DTLS original value given at command line.  */
  const char *pskIdentity_help; /**< @brief Default Identity of associated pre-shared key for DTLS help description.  */
  char * pskKey_arg;	/**< @brief Default pre-shared key for DTLS as a hex string.  */
  char * pskKey_orig;	/**< @brief Default pre-shared key for DTLS as a hex string original value given at command line.  */
  const char *pskKey_help; /**< @brief Default pre-shared key for DTLS as a hex string help description.  */
  char * certificate_arg;	/**< @brief Load client certificate from FILE.  */
  char * certificate_orig;	/**< @brief Load client certificate from FILE original value given at command line.  */
  const char *certificate_help; /**< @brief Load client certificate from FILE help description.  */
  int defaultContentType_arg;	/**< @brief Default content type to use when a request doesn't specify one (TLV=1542, JSON=50) (default='0').  */
  char * defaultContentType_orig;	/**< @brief Default content type to use when a request doesn't specify one (TLV=1542, JSON=50) original value given at command line.  */
  const char *defaultContentType_help; /**< @brief Default content type to use when a request doesn't specify one (TLV=1542, JSON=50) help description.  */
  char ** objDefs_arg;	/**< @brief Load object and resource definitions from FILE.  */
  char ** objDefs_orig;	/**< @brief Load object and resource definitions from FILE original value given at command line.  */
  unsigned int objDefs_min; /**< @brief Load object and resource definitions from FILE's minimum occurreces */
  unsigned int objDefs_max; /**< @brief Load object and resource definitions from FILE's maximum occurreces */
  const char *objDefs_help; /**< @brief Load object and resource definitions from FILE help description.  */
  int daemonize_flag;	/**< @brief Detach process from terminal and run in the background (default=off).  */
  const char *daemonize_help; /**< @brief Detach process from terminal and run in the background help description.  */
  int verbose_flag;	/**< @brief Generate verbose output (default=off).  */
  const char *verbose_help; /**< @brief Generate verbose output help description.  */
  char * logFile_arg;	/**< @brief Log output to FILE.  */
  char * logFile_orig;	/**< @brief Log output to FILE original value given at command line.  */
  const char *logFile_help; /**< @brief Log output to FILE help description.  */
  int version_flag;	/**< @brief Print version and exit (default=off).  */
  const char *version_help; /**< @brief Print version and exit help description.  */

  unsigned int help_given ;	/**< @brief Whether help was given.  */
  unsigned int port_given ;	/**< @brief Whether port was given.  */
  unsigned int addressFamily_given ;	/**< @brief Whether addressFamily was given.  */
  unsigned int ipcPort_given ;	/**< @brief Whether ipcPort was given.  */
  unsigned int endPointName_given ;	/**< @brief Whether endPointName was given.  */
  unsigned int bootstrap_given ;	/**< @brief Whether bootstrap was given.  */
  unsigned int factoryBootstrap_given ;	/**< @brief Whether factoryBootstrap was given.  */
  unsigned int secure_given ;	/**< @brief Whether secure was given.  */
  unsigned int pskIdentity_given ;	/**< @brief Whether pskIdentity was given.  */
  unsigned int pskKey_given ;	/**< @brief Whether pskKey was given.  */
  unsigned int certificate_given ;	/**< @brief Whether certificate was given.  */
  unsigned int defaultContentType_given ;	/**< @brief Whether defaultContentType was given.  */
  unsigned int objDefs_given ;	/**< @brief Whether objDefs was given.  */
  unsigned int daemonize_given ;	/**< @brief Whether daemonize was given.  */
  unsigned int verbose_given ;	/**< @brief Whether verbose was given.  */
  unsigned int logFile_given ;	/**< @brief Whether logFile was given.  */
  unsigned int version_given ;	/**< @brief Whether version was given.  */

  char **inputs ; /**< @brief unamed options (options without names) */
  unsigned inputs_num ; /**< @brief unamed options number */
} ;

/** @brief The additional parameters to pass to parser functions */
struct cmdline_parser_params
{
  int override; /**< @brief whether to override possibly already present options (default 0) */
  int initialize; /**< @brief whether to initialize the option structure gengetopt_args_info (default 1) */
  int check_required; /**< @brief whether to check that all required options were provided (default 1) */
  int check_ambiguity; /**< @brief whether to check for options already specified in the option structure gengetopt_args_info (default 0) */
  int print_errors; /**< @brief whether getopt_long should print an error message for a bad option (default 1) */
} ;

/** @brief the purpose string of the program */
extern const char *gengetopt_args_info_purpose;
/** @brief the usage string of the program */
extern const char *gengetopt_args_info_usage;
/** @brief the description string of the program */
extern const char *gengetopt_args_info_description;
/** @brief all the lines making the help output */
extern const char *gengetopt_args_info_help[];

/**
 * The command line parser
 * @param argc the number of command line options
 * @param argv the command line options
 * @param args_info the structure where option information will be stored
 * @return 0 if everything went fine, NON 0 if an error took place
 */
int cmdline_parser (int argc, char **argv,
  struct gengetopt_args_info *args_info);

/**
 * The command line parser (version with additional parameters - deprecated)
 * @param argc the number of command line options
 * @param argv the command line options
 * @param args_info the structure where option information will be stored
 * @param override whether to override possibly already present options
 * @param initialize whether to initialize the option structure my_args_info
 * @param check_required whether to check that all required options were provided
 * @return 0 if everything went fine, NON 0 if an error took place
 * @deprecated use cmdline_parser_ext() instead
 */
int cmdline_parser2 (int argc, char **argv,
  struct gengetopt_args_info *args_info,
  int override, int initialize, int check_required);

/**
 * The command line parser (version with additional parameters)
 * @param argc the number of command line options
 * @param argv the command line options
 * @param args_info the structure where option information will be stored
 * @param params additional parameters for the parser
 * @return 0 if everything went fine, NON 0 if an error took place
 */
int cmdline_parser_ext (int argc, char **argv,
  struct gengetopt_args_info *args_info,
  struct cmdline_parser_params *params);

/**
 * Save the contents of the option struct into an already open FILE stream.
 * @param outfile the stream where to dump options
 * @param args_info the option struct to dump
 * @return 0 if everything went fine, NON 0 if an error took place
 */
int cmdline_parser_dump(FILE *outfile,
  struct gengetopt_args_info *args_info);

/**
 * Save the contents of the option struct into a (text) file.
 * This file can be read by the config file parser (if generated by gengetopt)
 * @param filename the file where to save
 * @param args_info the option struct to save
 * @return 0 if everything went fine, NON 0 if an error took place
 */
int cmdline_parser_file_save(const char *filename,
  struct gengetopt_args_info *args_info);

/**
 * Print the help
 */
void cmdline_parser_print_help(void);
/**
 * Print the version
 */
void cmdline_parser_print_version(void);

/**
 * Initializes all the fields a cmdline_parser_params structure
 * to their default values
 * @param params the structure to initialize
 */
void cmdline_parser_params_init(struct cmdline_parser_params *params);

/**
 * Allocates dynamically a cmdline_parser_params structure and initializes
 * all its fields to their default values
 * @return the created and initialized cmdline_parser_params structure
 */
struct cmdline_parser_params *cmdline_parser_params_create(void);

/**
 * Initializes the passed gengetopt_args_info structure's fields
 * (also set default values for options that have a default)
 * @param args_info the structure to initialize
 */
void cmdline_parser_init (struct gengetopt_args_info *args_info);
/**
 * Deallocates the string fields of the gengetopt_args_info structure
 * (but does not deallocate the structure itself)
 * @param args_info the structure to deallocate
 */
void cmdline_parser_free (struct gengetopt_args_info *args_info);

/**
 * Checks that all the required options were specified
 * @param args_info the structure to check
 * @param prog_name the name of the program that will be used to print
 *   possible errors
 * @return
 */
int cmdline_parser_required (struct gengetopt_args_info *args_info,
  const char *prog_name);

extern const char *cmdline_parser_addressFamily_values[];  /**< @brief Possible values for addressFamily. */

#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* AWA_CLIENTD_CMDLINE_H */


text:
describe("Sort tests", function () {
    var u = require('../utils');
    var methods = require('../src/ch02');
    var N, A, B;

    beforeEach(function () {
        N = 1000;
        A = u.randomArray(N);
        B = u.copyArray(A);
        B.sort(u.compareInt);
    });

    it("Performs insertion sort correctly", function () {
        methods.insertionSort(A);
        expect(u.arrayEquals(A, B)).toBe(true);
    });

    it("Performs merge sort correctly", function () {
        A = methods.mergeSort(A);
        expect(u.arrayEquals(A, B)).toBe(true);
    });
});


text:
package dk.aau.sw402F15.tests.scanner;

import dk.aau.sw402F15.parser.lexer.LexerException;
import dk.aau.sw402F15.parser.parser.ParserException;
import dk.aau.sw402F15.tests.ScannerTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.IOException;
import java.util.Arrays;

/**
 * Created by sahb on 08/04/15.
 */
@RunWith(Parameterized.class)
public class FunctionDefinition extends ScannerTest {

    @Parameterized.Parameters
    public static Iterable<? extends Object> data() {
        return Arrays.asList("void", "bool", "char", "double", "float", "int", "long", "input", "output", "timer");
    }

    private String type;

    public FunctionDefinition(String type) {
        this.type = type;
    }

    @Test
    public void testFunctionDefinition() throws ParserException, IOException, LexerException {
        checkCode(type + " func() { }");
    }

    @Test
    public void testFunctionWithSingleFormalParameter() throws ParserException, IOException, LexerException {
        checkCode(type + " func(int i) { }");
    }

    @Test
    public void testFunctionWithMultipleFormalParameters() throws ParserException, IOException, LexerException {
        checkCode(type + " func(int i, float j) { }");
        checkCode(type + " func(int i, float j, char k) { }");
    }

    @Test(expected = ParserException.class)
    public void testFunctionWithVoidFormalParameter() throws ParserException, IOException, LexerException {
        checkCode(type + " func(void v) { }");
    }
}


text:
from __future__ import absolute_import, division, print_function

import argparse
from itertools import imap
import multiprocessing
import sys

from gensim import models

from dossier.fc import FeatureCollectionChunk
from dossier.store import Store
from dossier.store.store import fc_dumps
from dossier.models.etl import Ads, Scrapy, add_sip_to_fc
import kvlayer
import yakonfig

HBASE_MAX_KEY_VALUE_SIZE = 10 * 1024 * 1024 - 100

def batch_progress(cids_and_fcs, add, limit=5, batch_size=100):
    def status(*args, **kwargs):
        kwargs['end'] = ''
        args = list(args)
        args[0] = '\033[2K\r' + args[0]
        print(*args, **kwargs)
        sys.stdout.flush()

    total = 'all' if limit is None else str(limit)
    status('0 of %s done' % total)
    batch = []
    last_cid = None
    for i, (cid, fc) in enumerate(cids_and_fcs, 1):
        if fc is None:
            continue
        # Since we can restart the scanner, we may end up regenerating
        # FCs for the same key in the same batch. This results in
        # undefined behavior in kvlayer.
        if not any(cid == cid2 for cid2, _ in batch):
            # HBase doesn't allow more than 10MB for any particular key/value.
            # This is supposedly configurable, but it's unclear how to
            # configure it with happybase.
            if data_size(cid, fc) <= HBASE_MAX_KEY_VALUE_SIZE:
                batch.append((cid, fc))

        if len(batch) >= batch_size:
            add(batch)
            last_cid = batch[-1][0]
            batch = []
        if i % 100 == 0:
            status('%d of %s done (last id: %r)'
                   % (i, 'all' if limit is None else str(limit), last_cid))
    if len(batch) > 0:
        add(batch)
    status('done')

def data_size(cid, fc):
    return len(cid) + len(fc_dumps(fc))

class App(yakonfig.cmd.ArgParseCmd):
    def __init__(self, *args, **kwargs):
        yakonfig.cmd.ArgParseCmd.__init__(self, *args, **kwargs)
        self._store = None
        self._chunk = None
        self.tfidf = None

    @property
    def store(self):
        if self._store is None:
            feature_indexes = None
            try:
                conf = yakonfig.get_global_config('dossier.store')
                feature_indexes = conf['feature_indexes']
            except KeyError:
                pass
            self._store = Store(kvlayer.client(),
                                feature_indexes=feature_indexes)
        return self._store

    def done(self):
        if self._chunk is not None:
            self._chunk.flush()

    def get_output_accumulator(self, output_path=None):
        if output_path is not None:
            self._chunk = FeatureCollectionChunk(path=output_path, mode='wb')
        def add(cids_and_fcs):
            if self.tfidf is not None:
                for _, fc in cids_and_fcs:
                    add_sip_to_fc(fc, self.tfidf)
            if output_path is not None:
                for _, fc in cids_and_fcs:
                    self._chunk.add(fc)
            else:
                self.store.put(cids_and_fcs)
        return add

    def get_mapper(self, args):
        cpus = getattr(args, 'processes', 1)
        if cpus == 1:
            return imap
        else:
            pool = multiprocessing.Pool(processes=cpus)
            return pool.imap

    def args_etl_ads(self, p):
        p.add_argument('--host', default='localhost')
        p.add_argument('--port', default=9090, type=int)
        p.add_argument('--table-prefix', default='')
        p.add_argument('--limit', default=None, type=int)
        p.add_argument('--batch-size', default=1000, type=int)
        p.add_argument('--start', default=None, type=str)
        p.add_argument('--stop', default=None, type=str)
        p.add_argument('-p', '--processes',
                       default=multiprocessing.cpu_count(), type=int)
        p.add_argument('-o', '--output', default=None)
        p.add_argument('--tfidf', default=None, type=str,
                       help='Path to TF-IDF background model. Can be '
                            'generated with the `dossier.etl tfidf` script.')

    def do_etl_ads(self, args):
        if args.tfidf is not None:
            self.tfidf = models.TfidfModel.load(args.tfidf)
        etl = Ads(args.host, args.port, table_prefix=args.table_prefix)
        gen = etl.cids_and_fcs(self.get_mapper(args), args.start, args.stop,
                               limit=args.limit)
        self.etl(args, etl, gen)

    def args_etl_scrapy(self, p):
        p.add_argument('-p', '--processes',
                       default=multiprocessing.cpu_count(), type=int)
        p.add_argument('--batch-size', default=1000, type=int)
        p.add_argument('--limit', default=None, type=int)
        p.add_argument('-o', '--output', default=None)
        p.add_argument('--url-prefix', default=None,
                       help='Override the URL prefix to use when fixing '
                            'relative URLs. When omitted, detect '
                            'automatically.')
        p.add_argument('--tfidf', default=None, type=str,
                       help='Path to TF-IDF background model. Can be '
                            'generated with the `dossier.etl tfidf` script.')
        p.add_argument('input',
                       help='Scrapy data. Only supports CSV format currently.')

    def do_etl_scrapy(self, args):
        if args.tfidf is not None:
            self.tfidf = models.TfidfModel.load(args.tfidf)

        url_prefix = args.url_prefix
        if url_prefix is None:
            url_prefix = Scrapy.detect_url_prefix(open(args.input))
            if url_prefix is not None:
                print('Auto-detected URL prefix:', url_prefix)
        etl = Scrapy(open(args.input), url_prefix=url_prefix)
        gen = etl.cids_and_fcs(self.get_mapper(args), limit=args.limit)
        self.etl(args, etl, gen)

    def etl(self, args, etl, gen):
        add = self.get_output_accumulator(args.output)
        try:
            batch_progress(gen, add, limit=args.limit,
                           batch_size=args.batch_size)
        finally:
            self.done()

def main():
    p = argparse.ArgumentParser(
        description='Utilities for generating FCs from artifacts.')
    app = App()
    app.add_arguments(p)
    args = yakonfig.parse_args(p, [kvlayer, yakonfig])
    app.main(args)

if __name__ == '__main__':
    main()


text:
package my_Packege.appmanager;

import my_Packege.model.ContactData;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ContactHelper extends HelperBase {

  public ContactHelper(FirefoxDriver wd){
    super(wd);
  }

  public void selectContact(){
    if (!wd.findElement(By.id("MassCB")).isSelected()) {
      wd.findElement(By.id("MassCB")).click();
    }

  }

  public void submitNewContactCreation() {
      clik(By.xpath("//div[@id='content']/form/input[21]"));
  }

  public void fillNewContactForm(ContactData contactData) {
      type(By.name("firstname"),contactData.getFirst_name());
      type(By.name("middlename"),contactData.getMiddle_name());
      type(By.name("lastname"),contactData.getLast_name());
      type(By.name("nickname"),contactData.getNickname());
      type(By.name("title"),contactData.getTitle());
      type(By.name("company"),contactData.getCompany());
      type(By.name("address"),contactData.getAddress());
      type(By.name("home"),contactData.getTelephone_home());
      type(By.name("mobile"),contactData.getTelephone_mobile());
      type(By.name("work"),contactData.getTelephone_work());
      type(By.name("fax"),contactData.getFax());

  }

  public void deletionContact() {
    clik(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
  }

  public void closeWindoow() {
    wd.switchTo().alert().accept();
  }
}


text:
#ifndef ALI_STACK_H
#define ALI_STACK_H

/* $Id$ */

//  Particles stack class
//  Implements the TMCVirtualStack of the Virtual Monte Carlo
//  Author A.Morsch

class TClonesArray;
class TFile;
class TObjArray;
class TParticle;
class TString;
class TTree;
#include <TClonesArray.h>
#include <TArrayI.h>
#include <TVirtualMCStack.h>

class AliHeader;

enum {kKeepBit=1, kDaughtersBit=2, kDoneBit=4, kTransportBit=BIT(14)};

class AliStack : public TVirtualMCStack
{
  public:
    // creators, destructors
    AliStack(Int_t size, const char* name = "");
    AliStack();
    AliStack(const AliStack& st);
    virtual ~AliStack();
    AliStack& operator=(const AliStack& st)
      {st.Copy(*this); return(*this);}

    // methods

    virtual void  PushTrack(Int_t done, Int_t parent, Int_t pdg,
                           const Float_t *pmom, const Float_t *vpos, const Float_t *polar,
                           Float_t tof, TMCProcess mech, Int_t &ntr,
                           Float_t weight, Int_t is);

    virtual void  PushTrack(Int_t done, Int_t parent, Int_t pdg,
                           Double_t px, Double_t py, Double_t pz, Double_t e,
                           Double_t vx, Double_t vy, Double_t vz, Double_t tof,
                           Double_t polx, Double_t poly, Double_t polz,
                           TMCProcess mech, Int_t &ntr, Double_t weight,
                           Int_t is);

    virtual TParticle* PopNextTrack(Int_t& track);
    virtual TParticle* GetCurrentTrack() const {return fCurrentTrack;}
    virtual TParticle* PopPrimaryForTracking(Int_t i);

    void   ConnectTree(TTree* tree);
    Bool_t GetEvent();
    Bool_t PurifyKine(Float_t rmax = -1., Float_t zmax = -1.);
    Bool_t ReorderKine();
    void   FinishEvent();
    void   FlagTrack(Int_t track);
    void   KeepTrack(Int_t itrack);
    void   Clean(Int_t size = 0);
    void   Reset(Int_t size = 0);
    void   DumpPart(Int_t i) const;
    void   DumpPStack ();
    void   DumpLoadedStack () const;

    // set methods
    void  SetNtrack(Int_t ntrack);
    virtual void  SetCurrentTrack(Int_t track);
    void  SetHighWaterMark(Int_t hgwmk);
    // get methods
    virtual Int_t GetNtrack() const;
    Int_t       GetNprimary() const;
    Int_t       GetNtransported() const;
    virtual Int_t GetCurrentTrackNumber() const;
    virtual Int_t GetCurrentParentTrackNumber() const;
    TParticle*  Particle(Int_t id, Bool_t useInEmbedding=kFALSE);
    Int_t       GetPrimary(Int_t id, Bool_t useInEmbedding=kFALSE);
    TTree*      TreeK() const {return fTreeK;}
    TParticle*  ParticleFromTreeK(Int_t id, Bool_t useInEmbedding=kFALSE) const;
    Int_t       TreeKEntry(Int_t id, Bool_t useInEmbedding=kFALSE) const;
    Bool_t      IsPhysicalPrimary(Int_t i, Bool_t useInEmbedding=kFALSE);
    Bool_t      IsSecondaryFromWeakDecay(Int_t index, Bool_t useInEmbedding=kFALSE);
    Bool_t      IsSecondaryFromMaterial (Int_t index, Bool_t useInEmbedding=kFALSE);
    Int_t       TrackLabel(Int_t label) const {return fTrackLabelMap[label];}
    Int_t*      TrackLabelMap() {return fTrackLabelMap.GetArray();}
    const TObjArray*  Particles() const;

    void        SetMCEmbeddingFlag(Bool_t v=kTRUE)        {fMCEmbeddingFlag = v;}
    Bool_t      GetMCEmbeddingFlag()                const {return fMCEmbeddingFlag;}
    static const char*   GetEmbeddingBKGPathsKey() {return fgkEmbedPathsKey;}

  protected:
    // methods
    void  CleanParents();
    void  ResetArrays(Int_t size);
    TParticle* GetParticleMapEntry(Int_t id) const;
    TParticle* GetNextParticle();
    Bool_t KeepPhysics(const TParticle* part, Float_t rmax = -1, Float_t zmax = -1.);
    Bool_t IsStable(Int_t pdg) const;
  private:
    void Copy(TObject &st) const;

    // data members
    TClonesArray   fParticles;         //! Pointer to list of particles
    TObjArray      fParticleMap;       //! Map of particles in the supporting TClonesArray
    TArrayI        fParticleFileMap;   //  Map for particle ids
    TParticle     *fParticleBuffer;    //! Pointer to current particle for writing
    TParticle     *fCurrentTrack;      //! Pointer to particle currently transported
    TTree         *fTreeK;             //! Particle stack
    Int_t          fNtrack;            //  Number of tracks
    Int_t          fNprimary;          //  Number of primaries
    Int_t	   fNtransported;      //  Number of particles to be transported
    Int_t          fCurrent;           //! Last track returned from the stack
    Int_t          fCurrentPrimary;    //! Last primary track returned from the stack
    Int_t          fHgwmk;             //! Last track purified
    Int_t          fLoadPoint;         //! Next free position in the particle buffer
    TArrayI        fTrackLabelMap;     //! Map of track labels
    Bool_t         fMCEmbeddingFlag;   //! Flag that this is a top stack of embedded MC

    static TParticle* fgDummyParticle;     // dummy particle returned in Stack::Particle call in embedding mode
    static const Char_t *fgkEmbedPathsKey;       // keyword for embedding paths

    ClassDef(AliStack,6) //Particles stack
};

// inline

inline void  AliStack::SetNtrack(Int_t ntrack)
{ fNtrack = ntrack; }

inline Int_t AliStack::GetNtrack() const
{ return fNtrack; }

inline Int_t AliStack::GetNprimary() const
{ return fNprimary; }

inline Int_t AliStack::GetNtransported() const
{ return fNtransported; }

inline Int_t AliStack::GetCurrentTrackNumber() const
{ return fCurrent; }

inline const TObjArray* AliStack::Particles() const
{ return &fParticleMap; }

// inline protected

inline TParticle* AliStack::GetParticleMapEntry(Int_t id) const
{ return (TParticle*) fParticleMap.At(id); }

#endif //ALI_STACK_H


text:
package com.cloudera.oryx.kafka.util;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.zookeeper.server.DatadirCleanupManager;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.oryx.common.io.IOUtils;
import com.cloudera.oryx.common.lang.JVMUtils;
import com.cloudera.oryx.common.settings.ConfigUtils;

/**
 * This class contains code copied from Zookeeper's QuorumPeerMain and ZooKeeperServerMain.
 * It runs a local instance of Zookeeper, which can be useful for testing.
 */
public final class LocalZKServer implements Closeable {

  private static final Logger log = LoggerFactory.getLogger(LocalZKServer.class);

  private final int port;
  private Path dataDir;
  private DatadirCleanupManager purgeManager;
  private ZooKeeperServer zkServer;
  private FileTxnSnapLog transactionLog;
  private ServerCnxnFactory connectionFactory;
  private boolean closed;

  /**
   * Creates an instance that will run Zookeeper on the given port.
   *
   * @param port port on which Zookeeper will listen
   */
  public LocalZKServer(int port) {
    this.port = port;
  }

  public int getPort() {
    return port;
  }

  /**
   * Starts Zookeeper.
   *
   * @throws IOException if an error occurs during initialization
   * @throws InterruptedException if an error occurs during initialization
   */
  public synchronized void start() throws IOException, InterruptedException {
    log.info("Starting Zookeeper on port {}", port);

    dataDir = Files.createTempDirectory(LocalZKServer.class.getSimpleName());
    dataDir.toFile().deleteOnExit();

    QuorumPeerConfig quorumConfig = new QuorumPeerConfig();
    try {
      quorumConfig.parseProperties(ConfigUtils.keyValueToProperties(
          "dataDir", dataDir.toAbsolutePath(),
          "clientPort", port
      ));
    } catch (QuorumPeerConfig.ConfigException e) {
      throw new IllegalArgumentException(e);
    }

    purgeManager =
        new DatadirCleanupManager(quorumConfig.getDataDir(),
                                  quorumConfig.getDataLogDir(),
                                  quorumConfig.getSnapRetainCount(),
                                  quorumConfig.getPurgeInterval());
    purgeManager.start();

    ServerConfig serverConfig = new ServerConfig();
    serverConfig.readFrom(quorumConfig);

    zkServer = new ZooKeeperServer();
    zkServer.setTickTime(serverConfig.getTickTime());
    zkServer.setMinSessionTimeout(serverConfig.getMinSessionTimeout());
    zkServer.setMaxSessionTimeout(serverConfig.getMaxSessionTimeout());

    // These two ServerConfig methods returned String in 3.4.x and File in 3.5.x
    transactionLog = new FileTxnSnapLog(new File(serverConfig.getDataLogDir().toString()),
                                        new File(serverConfig.getDataDir().toString()));
    zkServer.setTxnLogFactory(transactionLog);

    connectionFactory = ServerCnxnFactory.createFactory();
    connectionFactory.configure(serverConfig.getClientPortAddress(), serverConfig.getMaxClientCnxns());
    connectionFactory.startup(zkServer);
  }

  /**
   * Blocks until Zookeeper terminates.
   *
   * @throws InterruptedException if the caller thread is interrupted while waiting
   */
  public void await() throws InterruptedException {
    connectionFactory.join();
  }

  /**
   * Shuts down Zookeeper.
   */
  @Override
  public synchronized void close() throws IOException {
    log.info("Closing...");
    if (closed) {
      return;
    }
    closed = true;
    if (connectionFactory != null) {
      connectionFactory.shutdown();
      connectionFactory = null;
    }
    if (zkServer != null) {
      zkServer.shutdown();
      zkServer = null;
    }
    if (transactionLog != null) {
      transactionLog.close();
      transactionLog = null;
    }
    if (purgeManager != null) {
      purgeManager.shutdown();
      purgeManager = null;
    }
    if (dataDir != null) {
      IOUtils.deleteRecursively(dataDir);
      dataDir = null;
    }
  }

  public static void main(String[] args) throws Exception {
    int port = args.length > 0 ? Integer.parseInt(args[0]) : IOUtils.chooseFreePort();
    try (final LocalZKServer zkServer = new LocalZKServer(port)) {
      JVMUtils.closeAtShutdown(zkServer);
      zkServer.start();
      zkServer.await();
    }
  }

}


text:
require 'builder'

# Examples
#<?xml version="1.0" encoding="UTF-8"?>
#<page version="2.0" xmlns:meta="http://whoisd.eyeline.com/sads/meta">
#  <title id="">DPC Mobile: Search by Person</title>
#
Please enter name of Person

#  <navigation id="">
#    <link accesskey="*" pageId="search_by_person_submit"></link>
#  </navigation>
#</page>
#
#<?xml version="1.0" encoding="UTF-8"?>
#<page version="2.0" xmlns:meta="http://whoisd.eyeline.com/sads/meta">
#<title id="">DPC Mobile: Search by Person</title>
#

#    <input navigationId="submit" name="name_of_person" title="Please enter name of Person" />
#

#  <navigation id="submit">
#    <link accesskey="1" pageId="search_by_person_submit">Ok</link>
#  </navigation>
#</page>

module SadsXml
  class Sads
    attr_accessor :title, :messages, :navigations, :inputs, :submit_page, :sms_message,
      :banner_targets, :banner_position, :request_attributes, :sanitize

    DEFAULTS = {
      :navigation => {
        :type => 'nav'
      }
    }

    def initialize
      @sanitize = false
      @title = ''
      @inputs = []
      @navigations = { :default => [] }
      @messages = { :top => '', :bottom => '' }
      @banner_targets = []
      @banner_position = :bottom
      @request_attributes = []
    end

    def message=(message)
      self.set_message(:default, message)
    end

    def submit_page=(page_link)
      # workaround for SADS Absolute Path
      #page_link.gsub!(/^\/yp_mobile\//, '') unless page_link.match(/\.html$/)
      @submit_page = page_link
    end

    def ussd_length
      counter = 0
      counter += @title.length + 2 unless @title.blank?

      @messages.each do |key, message|
        counter += message.length + 1 unless message.blank?
      end

      @navigations.each do |key, links|
        links.each do |link|
          counter += link[:title].length + link[:accesskey].length + 2
        end
      end

      @inputs.each do |input|
        counter += input[:title].length + 2
      end

      counter -= 1
      return counter
    end

    def one_ussd_message
      ussd_length <= 160
    end

    def one_ussd_message_characters_left
      160 - ussd_length
    end

    def add_navigation(link, navigation_id = :default)
      @navigations[navigation_id] = [] if @navigations[navigation_id].nil?

      # workaround for SADS Absolute Path
      #link[:pageId].gsub!(/^\/yp_mobile\//, '') unless link[:pageId].match(/\.html$/)

      @navigations[navigation_id]<< DEFAULTS[:navigation].merge(link)
    end

    def add_attribute(req_attribute)
      @request_attributes<< req_attribute
    end

    def set_message(id, message)
      @messages[id.to_sym] = message
    end

    def add_input(input)
      @inputs<< input
    end

    def sanitize(text)
      return text.to_ascii if @sanitize
      return text
    end

    def to_sads
      xml = Builder::XmlMarkup.new
      xml.instruct!
      xml.page :version => "2.0", "xmlns:meta" => "http://whoisd.eyeline.com/sads/meta" do
        xml.title sanitize(@title), :id => ''

        @messages.each do |key, message|
          object_hash = {}
          object_hash[:id] = key.to_s unless key == :default

          xml.div object_hash do
            unless message.blank?
              xml.div do
                lines = sanitize(message).split("\n").reverse
                while line = lines.pop
                  xml.text! line
                  xml.br if lines.any?
                end
              end
            end
            if @banner_position.to_s == key.to_s and @banner_targets.any?
              xml.br
              xml.br unless message.blank?
              xml.meta :banner, :target => @banner_targets.join(',')
            end
          end
        end

        xml.div sanitize(@sms_message), :type => 'sms' unless sms_message.blank?

        if @inputs.any?
          xml.div do
            @inputs.each do |input|
              xml.input input
            end
          end
        end

        navigations.each do |key, links|
          if links.any?
            object_hash = {}
            object_hash[:id] = key.to_s unless key == :default

            xml.navigation object_hash do
              links.each do |link| xml.link sanitize(link[:title].strip), link.except(:title) end
            end
          end # eo if links.any?

          if @inputs.any?
            xml.navigation :id => 'submit' do
              xml.link :accesskey => '1', :pageId => @submit_page
            end
          end
        end

        if @request_attributes.any?
          xml.attributes do
            @request_attributes.each do |attribute|
              xml.attribute attribute
            end
          end
        end
      end
    end

  end
end


text:
"use strict";
import path from "path";
import resolveModule from "./utils/resolve-module"
export const createMapper = (mapperName) => {
    return resolveModule(mapperName, path.join(__dirname, "mappers"));
};


text:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using WebsitePanel.WebDavPortal.DependencyInjection;
using WebsitePanel.WebDavPortal.Models;
using WebsitePanel.WebDavPortal.UI.Routes;

namespace WebsitePanel.WebDavPortal.CustomAttributes
{
    public class LdapAuthorizationAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult(AccountRouteNames.Login, null);
        }
    }
}


text:
<?php declare(strict_types=1);

namespace Room11\Jeeves\Storage\File;

use Amp\Promise;
use Room11\Jeeves\Storage\Admin as AdminStorage;
use Room11\StackChat\Client\Client as ChatClient;
use Room11\StackChat\Room\AclDataAccessor;
use Room11\StackChat\Room\Room as ChatRoom;
use function Amp\resolve;

class Admin implements AdminStorage
{
    private $accessor;
    private $chatClient;
    private $aclDataAccessor;
    private $dataFileTemplate;

    public function __construct(
        JsonFileAccessor $accessor,
        ChatClient $chatClient,
        AclDataAccessor $aclDataAccessor,
        string $dataFile
    ) {
        $this->accessor = $accessor;
        $this->chatClient = $chatClient;
        $this->aclDataAccessor = $aclDataAccessor;
        $this->dataFileTemplate = $dataFile;
    }

    public function getAll(ChatRoom $room): Promise
    {
        return resolve(function() use($room) {
            $owners = array_keys(yield $this->aclDataAccessor->getRoomOwners($room));

            $admins = yield $this->accessor->writeCallback(function($data) use($owners) {
                return array_values(array_diff($data, $owners));
            }, $this->dataFileTemplate, $room);

            return [
                'owners' => $owners,
                'admins' => $admins,
            ];
        });
    }

    public function isAdmin(ChatRoom $room, int $userId): Promise
    {
        return resolve(function() use($room, $userId) {
            // inb4 people "testing" removing me from the admin list
            if ($userId === 508666) {
                return true;
            }

            $administrators = yield $this->getAll($room);

            return ($administrators['owners'] === [] && $administrators['admins'] === [])
                || in_array($userId, $administrators['owners'], true)
                || in_array($userId, $administrators['admins'], true);
        });
    }

    public function add(ChatRoom $room, int $userId): Promise
    {
        return $this->accessor->writeCallback(function($data) use($userId) {
            $data[] = $userId;
            return array_unique($data);
        }, $this->dataFileTemplate, $room);
    }

    public function remove(ChatRoom $room, int $userId): Promise
    {
        return $this->accessor->writeCallback(function($data) use($userId) {
            if (false !== $key = array_search($userId, $data)) {
                array_splice($data, $key, 1);
            }
            return $data;
        }, $this->dataFileTemplate, $room);
    }
}