text:
package org.javarosa.xform.validator.gui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

import org.javarosa.core.model.FormDef;
import org.javarosa.core.util.Interner;
import org.javarosa.xform.parse.XFormParseException;
import org.javarosa.xform.parse.XFormParserFactory;
import org.javarosa.xform.schema.FormOverview;
import org.javarosa.xform.util.XFormUtils;

/*
 * Written by Brian DeRenzi 2009.
 *
 * Some parts taken from: http://www.javafaq.nu/java-example-code-788.html
 *
 * Parts Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book,
 * please visit http://www.davidflanagan.com/javaexamples3.
 */

public class XFormValidatorGUI extends Frame implements ActionListener, KeyListener, ItemListener {

	private final String PROPERTIES_FILE = new String("settings.properties");
	private final String WTK_PATH = new String("wtk.path");
	private final String NEW_FORM = new String("new.form");
	private final String ORIGINAL_JAR_DIR = new String("original.jar.dir");
	private final String OPEN_XML_WITH = new String("open.xml.with");
	private final String OPEN_AT_END = new String("open.at.end");
	private final String DEPLOY_JAR_PATH = new String("deploy.jar.path");

	private final String JAR_NAME = new String("JavaRosaFormTest.jar");
	private final String JAD_NAME = new String("JavaRosaFormTest.jad");
	private final String FORM_NAME = new String("a.xhtml");

	private final String JAD_START = new String("MIDlet-Name: JavaRosaFormTest\nMIDlet-Version: 0.0.1\n" +
			"MIDlet-Vendor: OpenRosa Consortium\nMIDlet-Jar-URL: JavaRosaFormTest.jar\nMIDlet-Jar-Size: ");
	private final String JAD_FINISH = new String("\nMIDlet-Info-URL: http://code.dimagi.com/JavaRosa/\n" +
			"MIDlet-1: JavaRosaFormTest,,org.javarosa.shellformtest.midlet.JRFormTestMidlet");

	private final int BUFFER = 2048;
	private final int TF_SIZE = 70;

	// Properties that we save
	private String wtkPath = new String("C:\\WTK2.5.2\\");
	private String origJarDir = new String(""); // set in constructor
	private String newForm = new String("C:\\TEST\\b.xml");
	private String deployJar = "";
	private static String openXMLWith = new String("C:\\Program Files\\Internet Explorer\\iexplore.exe");
	private static Boolean openAtEnd = new Boolean(true);

	// For the gui
	private Panel mainScreen = null;
	private CardLayout cl = null;
	private final static String SETTINGS_SCREEN = "SETTINGS_SCREEN";
	private final static String MAIN_SCREEN = "MAIN_SCREEN";
	private Button testBtn = null;
	private Label status = new Label();
	private Label formName = new Label();

	private Checkbox noOpenAtEnd = null;
	private Checkbox yesOpenAtEnd = null;

	private TextField wtkTF = null;
	private TextField jarTF = null;
	private TextField deployJarTF = null;
	private TextField formTF = null;
	private TextField viewerEXE = null;

	private Choice languages = null;

	private BufferLogger bufferedlogger = new BufferLogger();
	public static TextArea textarea = new TextArea("", 24, 80);

	public static XFormValidatorGUI instance = null;
	public static BufferedReader brErr = null;
	public static BufferedReader brOut = null;
	public static Process process = null;

	static Interner<String> interns = new Interner<String>();

	public static void main(String argv[]) {
		XFormValidatorGUI.instance = new XFormValidatorGUI();
		XFormUtils.setXFormParserFactory(new XFormParserFactory(interns));
	}

	public XFormValidatorGUI() {
		super();
		// Destroy the window when the user requests it
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
				// To hell with everything else
				System.exit(0);
			}
		});

		// Set the original JAR directory
		File f = new File(".");
		try {
			this.origJarDir = f.getCanonicalPath() + "/";
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// Read in the properties!
		readProperties();

		this.setTitle("JavaRosa XFormValidator GUI");

		createGUI();

		this.pack();
		setVisible(true);

		// Make the form we're using bold
		Font orig = this.formName.getFont();
		Font bold = orig.deriveFont(orig.getStyle() ^ Font.BOLD);
		this.formName.setFont(bold);
		this.status.setFont(bold);

		// Start a timer!
		Timer t = new Timer();
		t.schedule(new CheckOutput(), 100, 100);

		// Finally, check our settings
		if(!checkParams()) {
			addToTextArea("ERROR! Check settings and make sure you select a valid file!");
		}else {
			addToTextArea("All settings ok.");
		}
	}

	private static void showXMLOutput () {
		try {
			addLineToTextArea("xml output detected");

			String xml = "";
			String line = brOut.readLine();
			while (!"ENDXMLOUTPUT".equals(line)) {
				xml = xml + line;
				line = brOut.readLine();
			}

			addLineToTextArea("xml output: " + xml);

			File tempfile = File.createTempFile("jrxform", ".xml");
			tempfile.deleteOnExit();

			addLineToTextArea("temp file created: " + tempfile.getAbsolutePath());

			BufferedWriter out = new BufferedWriter(new FileWriter(tempfile));
			out.write(xml);
			out.close();

			addLineToTextArea("temp file written");

			if( openAtEnd.booleanValue() ) {
				addLineToTextArea("launching xml viewer:");
				addLineToTextArea("\t" + openXMLWith + " " + tempfile.getAbsolutePath() );
				Runtime.getRuntime().exec(new String[] {openXMLWith, tempfile.getAbsolutePath()});
			} else
				addLineToTextArea("not launching XML viewer");
		} catch (IOException ioe) { }
	}

	// This is such hacky terrible code.  I hope no one ever looks at this file.
	class CheckOutput extends TimerTask {
		public void run() {
			if(brErr != null && brOut != null) {
				// Check if there's output.
				try {
					if(brOut.ready()) {
						String line = brOut.readLine();
						if ("BEGINXMLOUTPUT".equals(line)) {
							showXMLOutput();
						} else {
							addToTextArea(line+"\n");
						}
					}

					if(brErr.ready())
						addToTextArea(brErr.readLine()+"\n");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			int i = 0;
			if( process != null ) {
				try {
					i = process.exitValue();
					process = null;
					addToTextArea("\n==================================\nEmulator exited with code (" + i + ")\n==================================\n");
				}catch(Exception e) {
					// process still going
				}
			}
		}
	}

	public void itemStateChanged(ItemEvent e) {
		// triggered by the checkboxes
		openAtEnd = new Boolean(yesOpenAtEnd.getState());
	}

	/**
	 * Handle button clicks
	 */
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		if (cmd.equals("eval")) {
			// Clear the text area...
			this.textarea.setText("");

			// If user clicked "validate" button
			if(checkNewForm())
				this.validateFile();
		}else if(cmd.equals("test")) {
			// Clear the text area...
			this.textarea.setText("");

			if(!checkParams()) {
				this.addToTextArea("ERROR: Please fix parameters on the settings screen!");
				return;
			}

			// Run validation
			if(!validateFile()) {
				this.addToTextArea("\n\nERROR: cannot launch emulator until file validates!");
				return;
			}

			// We have good params, so save them
			this.writeProperties();

			// Now run!
			this.testBtn.setEnabled(false);
			tryForm();
			this.testBtn.setEnabled(true);
		} else if(cmd.equals("summary")) {
			// Clear the text area...
			this.textarea.setText("");

			// Run validation
			if(!validateFile()) {
				this.addToTextArea("\n\nERROR: cannot launch emulator until file validates!");
				return;
			}

			summarize();

		} else if(cmd.equals("deploy")) {
			// Clear the text area...
			this.textarea.setText("");

			if(!checkDeployJar() || !checkNewForm()) {
				this.addToTextArea("ERROR: Please fix parameters on the settings screen!");
				return;
			}

			// Run validation
			if(!validateFile()) {
				this.addToTextArea("\n\nERROR: cannot deploy form to new jar unless it validates!");
				return;
			}

			// We have good params, so save them
			this.writeProperties();

			// Now run!
			deploy();
		} else if(cmd.equals("jarfile")) {
			// Create a file dialog box to prompt for a new file to display
			FileDialog f = new FileDialog(this, "Choose Jar", FileDialog.LOAD);

			String dir = this.jarTF.getText();
			dir = dir.substring(0,dir.lastIndexOf("\\"));
			System.out.println("default dir: " + dir);
			f.setDirectory(dir);

			// Display the dialog and wait for the user's response
			f.setVisible(true);

			if( f.getFile() == null)
				return;

			if( !f.getFile().equals(this.JAR_NAME) ) {
				reportError("Error! Jar must be named: " + this.JAR_NAME);
				return;
			}

			this.origJarDir = f.getDirectory();
			this.jarTF.setText(f.getDirectory() + f.getFile());

			f.dispose(); // Get rid of the dialog box
			if(checkParams() )
				updateStatus("All settings ok.");

		} else if (cmd.equals("selectdeployjar")) {
			// Create a file dialog box to prompt for a new file to display
			FileDialog f = new FileDialog(this, "Choose Jar", FileDialog.LOAD);

			String dir = this.deployJarTF.getText();
			if(dir.lastIndexOf("\\") != -1) {
				dir = dir.substring(0,dir.lastIndexOf("\\"));
			}
			System.out.println("default dir: " + dir);
			f.setDirectory(dir);

			// Display the dialog and wait for the user's response
			f.setVisible(true);

			if( f.getFile() == null)
				return;

			this.deployJarTF.setText(f.getDirectory() + f.getFile());

			f.dispose(); // Get rid of the dialog box
			if(checkParams() )
				updateStatus("All settings ok.");

		} else if(cmd.equals("form")){
			// Create a file dialog box to prompt for a new file to display
			FileDialog f = new FileDialog(this, "Open XForm", FileDialog.LOAD);

			String dir = this.formTF.getText();
			dir = dir.substring(0,dir.lastIndexOf("\\"));
			System.out.println("default dir: " + dir);
			f.setDirectory(dir);

			// Display the dialog and wait for the user's response
			f.setVisible(true);

			if( f.getFile() == null)
				return;

			this.formName.setText(f.getFile());

			this.newForm = f.getDirectory() + f.getFile();
			this.formTF.setText(this.newForm);

			f.dispose(); // Get rid of the dialog box
			checkParams();
		} else if(cmd.equals("viewerexe")) {
			// Create a file dialog box to prompt for a new file to display
			FileDialog f = new FileDialog(this, "Choose viewer EXE", FileDialog.LOAD);

			f.setFilenameFilter(new FilenameFilter() {
				public boolean accept(File directory, String filename) {
					return (filename.endsWith(".exe"));
				}
			});

			String dir = this.viewerEXE.getText();
			dir = dir.substring(0,dir.lastIndexOf("\\"));
			f.setDirectory(dir);

			// Display the dialog and wait for the user's response
			f.setVisible(true);

			if( f.getFile() == null)
				return;

			openXMLWith = f.getDirectory() + f.getFile();
			this.viewerEXE.setText(openXMLWith);

			f.dispose(); // Get rid of the dialog box

			checkParams();
		} else if(cmd.equals(SETTINGS_SCREEN)) {
			if(checkParams())
				updateStatus("All settings ok.");
			this.cl.show(this.mainScreen, SETTINGS_SCREEN);
		} else if(cmd.equals(MAIN_SCREEN)) {
			this.cl.show(this.mainScreen, MAIN_SCREEN);
		} else if(cmd.equals("save_settings")) {
			if( checkParams() ) {
				this.writeProperties();
				updateStatus("All settings ok. Settings saved.");
			} else
				reportError(status.getText() + " - settings not saved!");
		}
	}

	public static void addLineToTextArea( String s ) {
		addToTextArea(s + "\n");
	}

	// I'm a terrible person
	public static void addToTextArea( String s ) {
		String p = XFormValidatorGUI.textarea.getText();
		if( p == null || p.equals("") )
			XFormValidatorGUI.textarea.setText(s);
		else
			XFormValidatorGUI.textarea.setText(p + s);

		textarea.setCaretPosition(Integer.MAX_VALUE);
	}

	private boolean validateFile() {
		// Clear the buffer
		this.bufferedlogger.flush2();

		// Capture output
		PrintStream ps = new PrintStream(this.bufferedlogger);
		PrintStream origE = System.err;
		PrintStream origO = System.out;
		System.setErr(ps);
		System.setOut(ps);

		updateStatus("Starting validation");
		boolean success = false;

		// Run the test here!
		String xf_name = this.newForm;
			//this.filename.getText();

		System.out.println(Calendar.getInstance().getTime() + "\n");
		System.out.println("XForm validation on file: '" + xf_name + "'...\n");

		FileInputStream is;
		try {
			is = new FileInputStream(xf_name);
		} catch (FileNotFoundException e) {
			System.err.println("Error: the file '" + xf_name
					+ "' could not be found!");
			return false;
		}

		// File found, so save it
		writeProperties();

		// Test!
		try {
			FormDef xform = XFormUtils.getFormFromInputStream(is);
			updateStatus("XForm has probably passed validation.  Please check any warnings");
			System.out.println("\n\n==================================\nXForm has passed parsing validation.  There may still be errors, \nso please check for any warnings and test your form!");
			success = true;
		} catch(XFormParseException xfpe) {
			System.out.print(xfpe.getMessage());
			updateStatus("XForm failed validation, see text area for details.");
			System.out.println("\n\n==================================\nERROR: XForm has failed validation!!");
			success = false;
		} catch(Exception e){
			System.out.println("Unknown error during parsing!");
			e.printStackTrace();
			updateStatus("XForm failed validation, see text area for details.");
			System.out.println("\n\n==================================\nERROR: XForm has failed validation!!");
			success = false;
		}

		// Restore error and out
		System.setErr(origE);
		System.setOut(origO);

		// and show the output
		String prev = this.textarea.getText();
		this.textarea.setText(prev + this.bufferedlogger.flush2());

		return success;
	}

	private void createGUI() {
		this.setPreferredSize(new Dimension(900,570));

		// Create the screen.
		Panel screen = new Panel();
		screen.setLayout(new BorderLayout());

		Panel p = createTabs();
		Panel p2 = createMainScreen();

		screen.add("North", p);
		screen.add("Center", p2);

		this.add(screen);
	}

	private Panel createTabs() {
		Panel p = new Panel();
		p.setLayout(new FlowLayout());
		Button b = new Button("Main Screen");
		b.addActionListener(this);
		b.setActionCommand(MAIN_SCREEN);
		p.add(b);
		b = new Button("Settings");
		b.addActionListener(this);
		b.setActionCommand(SETTINGS_SCREEN);
		p.add(b);
		return p;
	}

	private Panel createMainScreen() {
		mainScreen = new Panel();
		cl = new CardLayout();
		mainScreen.setLayout(cl);
		mainScreen.add(createMainCard(), MAIN_SCREEN);
		mainScreen.add(createSettingsCard(), SETTINGS_SCREEN);
		return mainScreen;
	}

	private Panel createSettingsCard() {
		Panel settings = new Panel();

		// Using gridbag layout
		GridBagConstraints gbc = new GridBagConstraints();
		GridBagLayout gridBag = new GridBagLayout();
		settings.setLayout(gridBag);

		// Status
		Label l = new Label("Status:");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		settings.add(l,gbc);

		updateStatus("The current status will be displayed here.");
		status.setAlignment(Label.LEFT);
		gbc.gridx = 1;
		gbc.gridwidth = 2;
		settings.add(this.status,gbc);

		// WTK DIR
		l = new Label("Set the WTK directory:");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		settings.add(l, gbc);

		this.wtkTF = new TextField(this.wtkPath, this.TF_SIZE);
		this.wtkTF.addKeyListener(this);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		settings.add(this.wtkTF, gbc);

		// JAR
		l = new Label("Chose the JavaRosaFormTest JAR:");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		settings.add(l, gbc);

		this.jarTF = new TextField(this.origJarDir + "\\" + this.JAR_NAME, this.TF_SIZE);
		this.jarTF.addKeyListener(this);
		gbc.gridx = 0;
		gbc.gridwidth = 2;
		settings.add(this.jarTF, gbc);

		Button b = new Button("Choose Jar...");
		b.addActionListener(this);
		b.setActionCommand("jarfile");
		gbc.gridx = 2;
		gbc.weightx = 0;
		gbc.fill = GridBagConstraints.NONE;
		settings.add(b, gbc);

		//Deployment JAR
		Label deploylabel = new Label("Chose the JAR to Deploy to:");
		deploylabel.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		settings.add(deploylabel, gbc);

		this.deployJarTF = new TextField(this.deployJar);
		this.deployJarTF.addKeyListener(this);
		gbc.gridx = 0;
		gbc.gridwidth = 2;
		settings.add(this.deployJarTF, gbc);

		Button deploySelect = new Button("Choose Jar...");
		deploySelect.addActionListener(this);
		deploySelect.setActionCommand("selectdeployjar");
		gbc.gridx = 2;
		gbc.weightx = 0;
		gbc.fill = GridBagConstraints.NONE;
		settings.add(deploySelect, gbc);

		// open at end?
		l = new Label("Open viewer when emulator finishes?");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.NONE;
		settings.add(l, gbc);
		CheckboxGroup cbg = new CheckboxGroup();
		yesOpenAtEnd = new Checkbox("Yes", cbg, openAtEnd.booleanValue());
		yesOpenAtEnd.addItemListener(this);
		noOpenAtEnd = new Checkbox("No", cbg, !openAtEnd.booleanValue());
		noOpenAtEnd.addItemListener(this);
		settings.add(yesOpenAtEnd,gbc);
		settings.add(noOpenAtEnd,gbc);

		// viewer to use
		l = new Label("Choose the executable for the viewer:");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		settings.add(l, gbc);

		this.viewerEXE = new TextField(openXMLWith, this.TF_SIZE);
		this.viewerEXE.addKeyListener(this);
		gbc.gridx = 0;
		gbc.gridwidth = 2;
		settings.add(this.viewerEXE, gbc);

		b = new Button("Choose EXE...");
		b.addActionListener(this);
		b.setActionCommand("viewerexe");
		gbc.gridx = 2;
		gbc.weightx = 0;
		gbc.fill = GridBagConstraints.NONE;
		settings.add(b, gbc);

		// save button
		b = new Button("Save settings");
		b.addActionListener(this);
		b.setActionCommand("save_settings");
		Panel p = new Panel();
		p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
		p.add(b);
		settings.add(p,gbc);

		return settings;
	}

	private Panel createMainCard() {
		Panel main = new Panel();

		// Using gridbag layout
		GridBagConstraints gbc = new GridBagConstraints();
		GridBagLayout gridBag = new GridBagLayout();
		main.setLayout(gridBag);

		// Create a TextArea to display the contents of the file in
		textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
		textarea.setEditable(false);
		textarea.setColumns(120);
		gbc.gridx = 0;
		gbc.gridwidth = 3;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		main.add(textarea,gbc);

		// form
		Label l = new Label("Form to test:");
		l.setAlignment(Label.LEFT);
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		main.add(l, gbc);

		// The form to test
		this.formName = new Label(this.newForm.substring( this.newForm.lastIndexOf("\\")+1));
		gbc.gridx = 1;
		gbc.gridwidth = 2;
		main.add(this.formName, gbc);

		this.formTF = new TextField(this.newForm, this.TF_SIZE);
		this.formTF.addKeyListener(this);
		gbc.gridx = 0;
		gbc.gridwidth = 2;
		main.add(this.formTF, gbc);

		Button b = new Button("Choose form...");
		b.addActionListener(this);
		b.setActionCommand("form");
		gbc.gridx = 2;
		gbc.weightx = 0;
		gbc.fill = GridBagConstraints.NONE;
		main.add(b, gbc);//		this.add(p);

		// Test form button
		gbc.gridwidth = 3;
		gbc.anchor = GridBagConstraints.NORTHEAST;
//		gbc.gridy = 7;
		gbc.gridx = 0;

		// Create a bottom panel to hold a couple of buttons in
		Panel p = new Panel();
		//p.setLayout(new GridLayout(2,4));
		p.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));

		//this.add(p, "South");

		Button eval = new Button("Validate");
		eval.addActionListener(this);
		eval.setActionCommand("eval");

		Panel validatePanel = new Panel();
		validatePanel.setLayout(new GridLayout(2,1));
		validatePanel.add(eval);

		p.add(validatePanel);

		Panel summaryPanel = new Panel();
		summaryPanel.setLayout(new GridLayout(2,1));

		Button summary = new Button("Summarize");
		summary.addActionListener(this);
		summary.setActionCommand("summary");
		summaryPanel.add(summary);

		languages = new Choice();
		languages.add("Language");
		summaryPanel.add(languages);

		p.add(summaryPanel);

		this.testBtn = new Button("Test Form");
		this.testBtn.addActionListener(this);
		this.testBtn.setActionCommand("test");

		Panel testPanel = new Panel();
		testPanel.setLayout(new GridLayout(2,1));
		testPanel.add(testBtn);
		p.add(testPanel);

		Button deploy = new Button("Deploy");
		deploy.addActionListener(this);
		deploy.setActionCommand("deploy");

		Panel deployPanel = new Panel();
		deployPanel.setLayout(new GridLayout(2,1));
		deployPanel.add(deploy);
		p.add(deployPanel);

		main.add(p, gbc);
		textarea.setText("");

		return main;
	}

	private static String extractPath(String file) {
		return file.substring(0,file.lastIndexOf("\\"));
	}

	private void summarize() {
		addToTextArea("\n\n==================================\nForm Summary\n==================================\n");
		updateStatus("Creating Summary");

		FileInputStream in;
		try {
			in = new FileInputStream(newForm);
			FormDef f = XFormUtils.getFormFromInputStream(in);
			addToTextArea(FormOverview.overview(f, this.languages.getSelectedItem()));
			addToTextArea("\n\n==================================\nForm Summary Complete\n==================================\n");
			updateStatus("Summary Completed");
		} catch (FileNotFoundException e) {
			addToTextArea("ERROR! File Not Found Exception when attempting to load form " + newForm);
			e.printStackTrace();
			updateStatus("Error while loading form");
		}

	}

	private void deploy(){
		addToTextArea("\n\n==================================\nStarting deployment\n==================================\n");
		updateStatus("Creating work directory");
		addToTextArea("Creating work directory\n");

		// mkdir work, delete if exists
		File workDir = new File(extractPath(deployJarTF.getText()) + "work");
		if(workDir.exists()) {
			deleteDirectory(workDir);
		}
		workDir.mkdirs();

		updateStatus("Unpacking original JAR");
		addToTextArea("Unpacking original JAR...\n");

		// expand jar into work
		if( !unjar(deployJarTF.getText(), workDir.getAbsolutePath()) )
			return;

		updateStatus("Replacing file");
		addToTextArea("Replacing file\n");

		File newForm = new File(this.newForm);
		String filename = newForm.getName();

		// modify the file
		File form = new File( workDir.getAbsolutePath() + File.separator + filename );

		if(!form.exists()) {
			System.err.println("Error!  Can't find form to replace in JAR file, please make sure you have the correct JAR");
			addToTextArea("\nError!  Can't find form to replace in JAR file, please make sure you have the correct JAR\n");

			deleteDirectory(workDir);
			return;
		}
		if(!newForm.exists()) {
			System.err.println("No new form to copy");
			deleteDirectory(workDir);
			return;
		}
		form.delete();

		try {
			byte []data = new byte[BUFFER];
			form.createNewFile();

			FileInputStream in = new FileInputStream(newForm);
			FileOutputStream out = new FileOutputStream(form);

			int count;
			while((count = in.read(data, 0,
					BUFFER)) != -1) {
				out.write(data, 0, count);
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		updateStatus("Repacking JAR");
		addToTextArea("Repacking JAR...\n");

		File jar = new File(deployJarTF.getText());

		// recompress into test/JavaRosaFormTest.jad
		long size = jar(workDir.getAbsolutePath(), extractPath(deployJarTF.getText()), jar.getName());

		// delete work
		deleteDirectory(workDir);

		// get the JAR size
		String jarSize = new String("" + size);

		updateStatus("Writing Jad File");
		addToTextArea("Writing Jad File...\n");
		// make the jad file
		String outJad = deployJarTF.getText().replaceAll(".jar", ".jad");

		try {
			updateJad(outJad, jarSize);
		} catch(FileNotFoundException e) {
			String message = "Jad file could not be found! Make sure that the file " + outJad + " exists along with your Jar file!\n";
			addToTextArea(message);
			System.err.print(message);
			return;
		}

		// launch emulator
		updateStatus("Form Deployed!");
		addToTextArea("\n\n==================================\nForm Succesfully Deployed!\n==================================\n");
	}

	private void updateJad(String path, String newSize) throws FileNotFoundException {
		File jad = new File(path);
		if(!jad.exists()) {
			throw new FileNotFoundException();
		}

		File newJad = new File(path + ".tmp");
		BufferedWriter writer = null;
		if (newJad.exists()) {
			newJad.delete();
		}
		try {
			newJad.createNewFile();
			writer = new BufferedWriter(new FileWriter(newJad));
		} catch (IOException e) {
			throw new FileNotFoundException("Problem Creating new Jad file");
		}

		BufferedReader reader = new BufferedReader(new FileReader(path));
		try {

		String line = null;
		while((line = reader.readLine()) != null) {
			if(line.indexOf("MIDlet-Jar-Size:") != -1) {
				writer.write("MIDlet-Jar-Size: " + newSize + "\n");
			} else {
				writer.write(line + "\n");
			}
		}

		writer.flush();
		writer.close();
		reader.close();

		if(!newJad.renameTo(jad)) {
			jad.delete();
			if(!newJad.renameTo(jad)) {
				throw new RuntimeException("Could not write new jad file");
			}
		}

		}
		catch(IOException e) {
			//I don't even know.
			throw new RuntimeException("Problem writing jad", e);
		} finally {
			try {
				writer.close();
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("Problem closing the streams for the files. Seriously.", e);
			}
		}
	}

	private void tryForm() {
		addToTextArea("\n\n==================================\nStarting repackage and emulation\n==================================\n");
		updateStatus("Creating work directory");
		addToTextArea("Creating work directory\n");

		// mkdir work, delete if exists
		File workDir = new File(this.origJarDir + "work");
		if(workDir.exists()) {
			deleteDirectory(workDir);
		}
		workDir.mkdirs();

		updateStatus("Unpacking original JAR");
		addToTextArea("Unpacking original JAR...\n");

		// expand jar into work
		if( !unjar(this.origJarDir + this.JAR_NAME, workDir.getAbsolutePath()) )
			return;

		updateStatus("Replacing file");
		addToTextArea("Replacing file\n");

		// modify the file
		File form = new File( workDir.getAbsolutePath() + "/" + this.FORM_NAME );
		File newForm = new File(this.newForm);
		if(!form.exists()) {
			System.err.println("Error!  Can't find form to replace in JAR file, please make sure you have the correct JAR");
			addToTextArea("\nError!  Can't find form to replace in JAR file, please make sure you have the correct JAR\n");

			deleteDirectory(workDir);
			return;
		}
		if(!newForm.exists()) {
			System.err.println("No new form to copy");
			deleteDirectory(workDir);
			return;
		}
		form.delete();

		try {
			byte []data = new byte[BUFFER];
			form.createNewFile();

			FileInputStream in = new FileInputStream(newForm);
			FileOutputStream out = new FileOutputStream(form);

			int count;
			while((count = in.read(data, 0,
					BUFFER)) != -1) {
				out.write(data, 0, count);
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		updateStatus("Creating test directory");
		addToTextArea("Creating test directory\n");

		// mkdir test, delete if exists
		File testDir = new File(this.origJarDir + "test");
		if(testDir.exists()) {
			deleteDirectory(testDir);
		}
		testDir.mkdirs();

		updateStatus("Repacking JAR");
		addToTextArea("Repacking JAR...\n");

		// recompress into test/JavaRosaFormTest.jad
		long size = jar(workDir.getAbsolutePath(), testDir.getAbsolutePath(), this.JAR_NAME);

		// delete work
		deleteDirectory(workDir);

		// get the JAR size
		String jarSize = new String("" + size);

		// make the jad file
		String outJad = new String(testDir.getAbsolutePath() + "\\" + this.JAD_NAME);
		try {
			PrintWriter pw = new PrintWriter(outJad);
			pw.print(this.JAD_START);
			pw.print(jarSize);
			pw.print(this.JAD_FINISH);
			pw.flush();
			pw.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// launch emulator
		updateStatus("Launching emulator!");

		emulate(this.wtkPath, outJad);
	}

	private boolean deleteDirectory(File path) {
		if( path.exists() ) {
			File[] files = path.listFiles();
			for(int i=0; i<files.length; i++) {
				if(files[i].isDirectory()) {
					deleteDirectory(files[i]);
				}
				else {
					files[i].delete();
				}
			}
		}
		return( path.delete() );
	}

	private void writeProperties() {
		Properties p = new Properties();

		// DEFAULT PROPERTIES
		p.setProperty(this.WTK_PATH, this.wtkPath);
		p.setProperty(this.NEW_FORM, this.newForm);
		p.setProperty(this.ORIGINAL_JAR_DIR, this.origJarDir);
		p.setProperty(this.OPEN_XML_WITH, openXMLWith);
		p.setProperty(this.OPEN_AT_END, openAtEnd.toString());
		String deploy =  deployJarTF == null? "" : deployJarTF.getText();
		p.setProperty(this.DEPLOY_JAR_PATH, deploy);

		File f = new File(this.PROPERTIES_FILE);
		try {
			if( !f.exists() )
				f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			p.store(fos, this.PROPERTIES_FILE);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	static boolean noRecurse = false;

	private void readProperties() {
		File f = new File(this.PROPERTIES_FILE);
		if(!f.exists() && !noRecurse) {
			// No settings, so make the default
			System.out.println("Making a properties file");
			writeProperties();
			noRecurse = true;
			readProperties();
			return;
		}

		Properties props = new java.util.Properties();
		try {
			FileInputStream fis = new FileInputStream(f);
			props.load(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Read in properties
		this.wtkPath = props.getProperty(this.WTK_PATH);
		this.newForm = props.getProperty(this.NEW_FORM);
		this.origJarDir = props.getProperty(this.ORIGINAL_JAR_DIR);
		openXMLWith = props.getProperty(this.OPEN_XML_WITH);
		openAtEnd = new Boolean(props.getProperty(this.OPEN_AT_END));
		deployJar = props.getProperty(this.DEPLOY_JAR_PATH);
	}

	private void emulate( String wtkPath, String jad) {
		if (wtkPath.charAt(wtkPath.length() - 1) != '/' && wtkPath.charAt(wtkPath.length() - 1) != '\\')
			wtkPath += "\\";
		wtkPath = "\"" + wtkPath;
		jad = "\"" + jad + "\"";
		try {
			System.out.println("Launching emulator: \n\t" + wtkPath + "bin\\emulator.exe\"" + " -Xheapsize:32M" + " -Xheapsize:32M" + " -Xdescriptor " + jad);
			addToTextArea("\nLaunching emulator: \n\t" + wtkPath + "bin\\emulator.exe\"" + " -Xheapsize:32M" + " -Xdescriptor " + jad + "\n\n");

			process = Runtime.getRuntime().exec( new String[] { wtkPath + "bin\\emulator.exe\"","-Xheapsize:32M","-Xdescriptor", jad } );

			brOut = new BufferedReader(
			        new InputStreamReader(process.getInputStream()) );
			brErr = new BufferedReader(
			        new InputStreamReader(process.getErrorStream()) );

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private long jar(String srcDir, String destDir, String jarname) {
		if (destDir.charAt(destDir.length() - 1) != '/')
			destDir += "\\";
		if (srcDir.charAt(srcDir.length() - 1) != '/')
			srcDir += "\\";
		try {
			FileOutputStream fos = new FileOutputStream(destDir + jarname);
			JarOutputStream out = new JarOutputStream(new BufferedOutputStream(fos));

			// Recursively add all files and directories in the source directory
			jarDirectory(srcDir, "", out);

			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("done creating JAR!");

		File f = new File(destDir + jarname);
		long size = f.length();
		System.out.println("size: " + size );
		return size;
	}

	private void jarDirectory(String srcDir, String currDir, JarOutputStream out) {
		try {
			BufferedInputStream origin = null;
			byte data[] = new byte[BUFFER];
			// get a list of files from current directory
			File f = new File(srcDir + currDir);
			String files[] = f.list();

			for (int i=0; i<files.length; i++) {
				File currFile = new File(srcDir + currDir +  files[i]);
				if(currFile.isDirectory()) {
//					System.out.println("Found directory: " + files[i]);
					jarDirectory(srcDir, currDir + files[i] + "/", out);
					continue;
				}
				FileInputStream fi = new
					FileInputStream(srcDir + currDir + files[i]);

//				System.out.println("Adding: "+currDir + files[i]);

				origin = new BufferedInputStream(fi, BUFFER);
				ZipEntry entry = new ZipEntry(currDir + files[i]);
				out.putNextEntry(entry);
				int count;
				while((count = origin.read(data, 0,
						BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private boolean unjar(String filename, String destDir) {
		final int BUFFER = 2048;
		// Make sure we end in a slash
		if (destDir.charAt(destDir.length() - 1) != '/')
			destDir += "\\";

		try {
			BufferedOutputStream dest = null;
			BufferedInputStream is = null;
			JarEntry entry;
			JarFile jarfile;
			try{
				jarfile = new JarFile(filename);
			}catch(Exception e) {
				addToTextArea("\nError cannot find JAR t unpack: "+filename);
				return false;
			}
			Enumeration e = jarfile.entries();
			while (e.hasMoreElements()) {
				entry = (JarEntry) e.nextElement();
//				System.out.println("Extracting: " + entry);

				if (entry.isDirectory()) {
//					System.out.println("Directory!");
					File d = new File(destDir + entry.getName());
					d.mkdirs();
					continue;
				}

				File f = new File(destDir + entry.getName());
				if (!f.exists()) {
					File f2 = new File(f.getParent());
					f2.mkdirs();
					f.createNewFile();
				} else {
//					System.err.println("Overwriting file!!!!");
					// Should probably not do that?
				}

				is = new BufferedInputStream(jarfile.getInputStream(entry));
				int count;
				byte data[] = new byte[BUFFER];
				FileOutputStream fos = new FileOutputStream(f);
				dest = new BufferedOutputStream(fos, BUFFER);
				while ((count = is.read(data, 0, BUFFER)) != -1) {
					dest.write(data, 0, count);
				}
				dest.flush();
				dest.close();
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	private void updateLang() {
		try {
			languages.removeAll();
			FileInputStream in = new FileInputStream(newForm);
			FormDef f = XFormUtils.getFormFromInputStream(in);
			if (f.getLocalizer() != null) {
				String[] locales = f.getLocalizer().getAvailableLocales();
				for (int i = 0; i < locales.length; ++i) {
					languages.add(locales[i]);
				}
				languages.select(f.getLocalizer().getDefaultLocale());
				languages.setVisible(true);
			} else {
				languages.setVisible(false);
			}
		} catch (Exception e) {
			//All failures here should just get swallowed, this is tertiary functionality
			e.printStackTrace();
			languages.setVisible(false);
		}
	}

	private boolean checkParams() {
		// Make sure everything exists.
		// Check WTK directory
		return checkNewForm() && checkWTK() && checkOriginalJAR();
	}

	private boolean checkNewForm() {
		File form = new File(this.newForm);
		if(!form.exists() || form.isDirectory()) {
			reportError("Error: New form cannot be found!");
			addToTextArea("Error! File \"" + this.newForm + "\" does not exist.  Please choose a new file.\n" );
			return false;
		}

		//Update the Available Languages for Summary
		System.out.println("about to update language");
		updateLang();
		return true;
	}

	private boolean checkOriginalJAR() {
		File jar = new File(this.origJarDir + "/" + this.JAR_NAME);
		if(!jar.exists() || jar.isDirectory()) {
			reportError("Error: " + this.JAR_NAME + " not found in jar directory");
			return false;
		}
		return true;
	}

	private boolean checkDeployJar() {
		File jar = new File(this.deployJarTF.getText());
		if(!jar.exists() || jar.isDirectory()) {
			reportError("Error: no jar file to deploy to found at " + this.deployJarTF);
			return false;
		}
		return true;
	}

	private boolean checkWTK() {
		File wtk = new File(this.wtkPath);
		if(!wtk.exists() || !wtk.isDirectory() ) {
			reportError("Error: WTK directory does not exist!");
			return false;
		}

		// Check that it's actually a WTK install
		File emu = new File(this.wtkPath + "/bin/emulator.exe");
		if(!emu.exists() || emu.isDirectory() ) {
			reportError("Error: WTK directory is not a valid WTK install!");
			return false;
		}

		return true;
	}

	public void keyPressed(KeyEvent arg0) {}

	public void keyReleased(KeyEvent ke) {
		if(ke.getComponent().equals(this.wtkTF)) {
			this.wtkPath = this.wtkTF.getText();
		}else if(ke.getComponent().equals(this.jarTF)) {
			String s = this.jarTF.getText();
			this.origJarDir = s.substring(0,s.lastIndexOf("\\"));
		}else if(ke.getComponent().equals(this.formTF)) {
			String s = this.formTF.getText();
			this.formName.setText(s.substring(s.lastIndexOf("\\")+1));
			this.newForm = s;
		}else if(ke.getComponent().equals(this.viewerEXE)) {
			openXMLWith = this.viewerEXE.getText();
		}
	}

	public void keyTyped(KeyEvent ke) {}

	private void reportError(String e) {
		this.status.setForeground(Color.RED);
		this.status.setText(e);
	}

	private void updateStatus(String s) {
		this.status.setForeground(Color.BLACK);
		this.status.setText(s);
	}

}


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

var HttpPaymentRequiredException = require('../../errors/HttpPaymentRequiredException');

'use strict';

/**
* お客様のご都合により操作を受け付けることができません。
*/
var PaymentUnpayableException = (function (_super) {
    __extends(PaymentUnpayableException, _super);
    /**
    * @constructor
    * @public
    * @param {number} status
    * @param {string} code=null
    * @param {string} message=""
    */
    function PaymentUnpayableException(status, code, message) {
        if (typeof code === "undefined") { code = null; }
        if (typeof message === "undefined") { message = ""; }
        _super.call(this, status, code, message == null || message == "" ? "お客様のご都合により操作を受け付けることができません。" : message);
    }
    return PaymentUnpayableException;
})(HttpPaymentRequiredException);
module.exports = PaymentUnpayableException;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FacebookPollCounter
{
    public class Item
    {
        public string Name { get; set; }
        public string Id { get; set; }
    }
}


text:
package org.eclipse.winery.common.interfaces;

import java.io.IOException;

import org.eclipse.winery.common.ids.GenericId;
import org.eclipse.winery.common.ids.Namespace;
import org.eclipse.winery.common.ids.definitions.TOSCAComponentId;

/**
 * Enables access to the winery repository via Ids defined in package
 * {@link org.eclipse.winery.common.ids}
 *
 * Methods are moved from
 * {@link org.eclipse.winery.repository.backend.IGenericRepository} to here as
 * soon there is an implementation for them. The ultimate goal is to eliminate
 * IGenericRepository
 *
 * These methods are shared between {@link IWineryRepository} and
 * {@link org.eclipse.winery.repository.backend.IRepository}
 */
public interface IWineryRepositoryCommon {

	/**
	 * Deletes the TOSCA element <b>and all sub elements</b> referenced by the
	 * given id from the repository
	 *
	 * We assume that each id is a directory
	 */
	void forceDelete(GenericId id) throws IOException;

	/**
	 * Renames a TOSCA component id
	 *
	 * @param oldId the old id
	 * @param newId the new id
	 */
	void rename(TOSCAComponentId oldId, TOSCAComponentId newId) throws IOException;

	 /**
	  * Deletes all TOSCA components nested in the given namespace
	  *
	  * @param toscaComponentIdClazz the type of TOSCA components to delete
	  * @param namespace the namespace to delete
	  */
	void forceDelete(Class<? extends TOSCAComponentId> toscaComponentIdClazz, Namespace namespace) throws IOException;

}


text:
package org.colorcoding.tools.btulz.shell.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

import org.colorcoding.tools.btulz.shell.Environment;

/**
 * 子项集合
 *
 * @author Niuren.Zhu
 *
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "CommandItems", namespace = Environment.NAMESPACE_BTULZ_SHELL_COMMANDS)
public class CommandItems extends ArrayList<CommandItem> {

	private static final long serialVersionUID = -4475012404050446583L;

	public String getValue(List<Variable> variables) {
		if (variables == null)
			variables = new ArrayList<>();
		StringBuilder stringBuilder = new StringBuilder();
		for (CommandItem item : this) {
			List<Variable> tmpVariables = new ArrayList<>(variables);
			String content = item.getContent();
			String itemValue = item.getValue();
			if (item.getItems().size() > 0) {
				itemValue = item.getItems().getValue(tmpVariables);
			}
			if (itemValue == null) {
				itemValue = "";
			}
			// 替换value中变量
			for (Variable variable : tmpVariables) {
				itemValue = itemValue.replace(variable.getName(), variable.getValue());
			}
			// 替换content中变量
			tmpVariables.add(new Variable(Variable.VARIABLE_NAME_VALUE, itemValue));
			for (Variable variable : tmpVariables) {
				content = content.replace(variable.getName(), variable.getValue());
			}
			stringBuilder.append(content);
		}
		return stringBuilder.toString();
	}

	public CommandItem create() {
		CommandItem item = new CommandItem();
		this.add(item);
		return item;
	}

	/**
	 * 返回所有项目,包括子项
	 *
	 * @return
	 */
	public List<CommandItem> getItems() {
		ArrayList<CommandItem> items = new ArrayList<>();
		for (CommandItem item : this) {
			items.add(item);
			items.addAll(item.getItems().getItems());
		}
		return items;
	}

	/**
	 * 返回数量,包括子项
	 *
	 * @return
	 */
	public int getCount() {
		return this.getItems().size();
	}

	public CommandItem firstOrDefault(Predicate<CommandItem> filter) {
		Objects.requireNonNull(filter);
		for (int i = 0; i < this.size(); i++) {
			CommandItem item = this.get(i);
			if (item == null)
				continue;
			if (filter.test(item))
				return item;
		}
		return null;
	}

	public CommandItem firstOrDefault(Predicate<CommandItem> filter, boolean recursion) {
		CommandItem item = this.firstOrDefault(filter);
		if (item == null && recursion) {
			for (int i = 0; i < this.size(); i++) {
				item = this.get(i);
				item = item.getItems().firstOrDefault(filter, recursion);
				if (item != null) {
					break;
				}
			}
		}
		return item;
	}
}


text:
require 'test_helper'
require 'heat_map_color_support'

class HeatMapColorSupportTest < ActiveSupport::TestCase

  test 'should yield a color for each value in range' do
    helper = HeatMapColorSupport.new('blue', 'green', 0, 100)
    helper.failsafe_color = nil # NNB: for test to work...

    (0..100).each do |i|
      assert helper.color_for(i)
    end
  end

  test 'should yield a color for each value in non-zero range' do
    helper = HeatMapColorSupport.new('blue', 'green', 50, 80)
    helper.failsafe_color = nil # NNB: for test to work...

    (50..80).each do |i|
      assert helper.color_for(i)
    end
  end

end


text:
package gorocksdb

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/facebookgo/ensure"
)

func TestExternalFile(t *testing.T) {
	db := newTestDB(t, "TestDBExternalFile", nil)
	defer db.Close()

	envOpts := NewDefaultEnvOptions()
	opts := NewDefaultOptions()
	w := NewSSTFileWriter(envOpts, opts)
	defer w.Destroy()

	filePath, err := ioutil.TempFile("", "sst-file-test")
	ensure.Nil(t, err)
	defer os.Remove(filePath.Name())

	err = w.Open(filePath.Name())
	ensure.Nil(t, err)

	err = w.Add([]byte("aaa"), []byte("aaaValue"))
	ensure.Nil(t, err)
	err = w.Add([]byte("bbb"), []byte("bbbValue"))
	ensure.Nil(t, err)
	err = w.Add([]byte("ccc"), []byte("cccValue"))
	ensure.Nil(t, err)
	err = w.Add([]byte("ddd"), []byte("dddValue"))
	ensure.Nil(t, err)

	err = w.Finish()
	ensure.Nil(t, err)

	ingestOpts := NewDefaultIngestExternalFileOptions()
	err = db.IngestExternalFile([]string{filePath.Name()}, ingestOpts)
	ensure.Nil(t, err)

	readOpts := NewDefaultReadOptions()

	v1, err := db.Get(readOpts, []byte("aaa"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v1.Data(), []byte("aaaValue"))
	v2, err := db.Get(readOpts, []byte("bbb"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v2.Data(), []byte("bbbValue"))
	v3, err := db.Get(readOpts, []byte("ccc"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v3.Data(), []byte("cccValue"))
	v4, err := db.Get(readOpts, []byte("ddd"))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v4.Data(), []byte("dddValue"))
}


text:
package ru.r2cloud.jradio.grifex;

import java.io.DataInputStream;
import java.io.IOException;

import ru.r2cloud.jradio.fec.ccsds.UncorrectableException;

public class MxlHeader {

	public static final int LENGTH_BYTES = 11;

	private short sync;
	private int primaryId;
	private int secondaryId;
	private int flags;
	private int packetLength;
	private int headerChecksum;

	public MxlHeader() {
		// do nothing
	}

	public MxlHeader(DataInputStream dis) throws IOException, UncorrectableException {
		if (dis.available() < LENGTH_BYTES) {
			throw new UncorrectableException("not enough bytes in the input");
		}
		sync = dis.readShort();
		primaryId = dis.readUnsignedShort();
		secondaryId = dis.readUnsignedShort();
		flags = dis.readUnsignedByte();
		packetLength = dis.readUnsignedByte() | (dis.readUnsignedByte() << 8);
		headerChecksum = dis.readUnsignedShort();
	}

	public short getSync() {
		return sync;
	}

	public void setSync(short sync) {
		this.sync = sync;
	}

	public int getPrimaryId() {
		return primaryId;
	}

	public void setPrimaryId(int primaryId) {
		this.primaryId = primaryId;
	}

	public int getSecondaryId() {
		return secondaryId;
	}

	public void setSecondaryId(int secondaryId) {
		this.secondaryId = secondaryId;
	}

	public int getFlags() {
		return flags;
	}

	public void setFlags(int flags) {
		this.flags = flags;
	}

	public int getPacketLength() {
		return packetLength;
	}

	public void setPacketLength(int packetLength) {
		this.packetLength = packetLength;
	}

	public int getHeaderChecksum() {
		return headerChecksum;
	}

	public void setHeaderChecksum(int headerChecksum) {
		this.headerChecksum = headerChecksum;
	}

}


text:
'use strict';

module.exports = {
  description: ''

  // locals(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  // afterInstall(options) {
  //   // Perform extra work here.
  // }
};


text:
namespace NServiceBus.AcceptanceTests.DataBus
{
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using MessageMutator;
    using NUnit.Framework;

    public class When_sending_databus_properties : NServiceBusAcceptanceTest
    {
        [Test]
        public async Task Should_receive_messages_with_largepayload_correctly()
        {
            var payloadToSend = new byte[PayloadSize];

            var context = await Scenario.Define<Context>()
                .WithEndpoint<Sender>(b => b.When(session => session.Send(new MyMessageWithLargePayload
                {
                    Payload = new DataBusProperty<byte[]>(payloadToSend)
                })))
                .WithEndpoint<Receiver>()
                .Done(c => c.ReceivedPayload != null)
                .Run();

            Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus");
        }

        const int PayloadSize = 100;

        public class Context : ScenarioContext
        {
            public byte[] ReceivedPayload { get; set; }
        }

        public class Sender : EndpointConfigurationBuilder
        {
            public Sender()
            {
                EndpointSetup<DefaultServer>(builder =>
                {
                    var basePath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"databus\sender");
                    builder.UseDataBus<FileShareDataBus>().BasePath(basePath);
                    builder.UseSerialization<JsonSerializer>();
                })
                    .AddMapping<MyMessageWithLargePayload>(typeof(Receiver));
            }
        }

        public class Receiver : EndpointConfigurationBuilder
        {
            public Receiver()
            {
                EndpointSetup<DefaultServer>(builder =>
                {
                    var basePath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"databus\sender");
                    builder.UseDataBus<FileShareDataBus>().BasePath(basePath);
                    builder.UseSerialization<JsonSerializer>();
                    builder.RegisterComponents(c => c.ConfigureComponent<Mutator>(DependencyLifecycle.InstancePerCall));
                });
            }

            public class MyMessageHandler : IHandleMessages<MyMessageWithLargePayload>
            {
                public Context Context { get; set; }

                public Task Handle(MyMessageWithLargePayload messageWithLargePayload, IMessageHandlerContext context)
                {
                    Context.ReceivedPayload = messageWithLargePayload.Payload.Value;

                    return Task.FromResult(0);
                }
            }

            public class Mutator : IMutateIncomingTransportMessages
            {
                public Task MutateIncoming(MutateIncomingTransportMessageContext context)
                {
                    if (context.Body.Length > PayloadSize)
                    {
                        throw new Exception();
                    }
                    return Task.FromResult(0);
                }
            }
        }

        public class MyMessageWithLargePayload : ICommand
        {
            public DataBusProperty<byte[]> Payload { get; set; }
        }
    }
}


text:
<?php

namespace Oro\Bundle\NotificationBundle\Provider;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Oro\Bundle\NotificationBundle\Doctrine\EntityPool;
use Oro\Bundle\NotificationBundle\Event\NotificationEvent;
use Oro\Bundle\PlatformBundle\EventListener\OptionalListenerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * The event listener for Doctrine events that intended to dispatch notification events
 * when entities are created, updated or removed.
 */
class DoctrineListener implements OptionalListenerInterface
{
    /** @var EntityPool */
    private $entityPool;

    /** @var EventDispatcherInterface */
    private $eventDispatcher;

    /** @var bool */
    private $enabled = true;

    /**
     * @param EntityPool               $entityPool
     * @param EventDispatcherInterface $eventDispatcher
     */
    public function __construct(EntityPool $entityPool, EventDispatcherInterface $eventDispatcher)
    {
        $this->entityPool = $entityPool;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * {@inheritdoc}
     */
    public function setEnabled($enabled = true)
    {
        $this->enabled = $enabled;
    }

    /**
     * @param PostFlushEventArgs $args
     */
    public function postFlush(PostFlushEventArgs $args)
    {
        if ($this->enabled) {
            $this->entityPool->persistAndFlush($args->getEntityManager());
        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        if ($this->enabled) {
            $this->dispatch('oro.notification.event.entity_post_update', $args->getEntity());
        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        if ($this->enabled) {
            $this->dispatch('oro.notification.event.entity_post_persist', $args->getEntity());
        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postRemove(LifecycleEventArgs $args)
    {
        if ($this->enabled) {
            $this->dispatch('oro.notification.event.entity_post_remove', $args->getEntity());
        }
    }

    /**
     * @param string $eventName
     * @param object $entity
     */
    private function dispatch($eventName, $entity)
    {
        $this->eventDispatcher->dispatch($eventName, new NotificationEvent($entity));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="AppBundle\Entity\CmsStzefMenus" table="cms_stzef_menus">
    <indexes>
      <index name="fk_CMSstzef_menus_type_access1_idx" columns="id_type_access"/>
      <index name="fk_CMSstzef_menus_CMSstzef_states1_idx" columns="id_state_publication"/>
      <index name="fk_CMSstzef_menus_CMSstzef_users1_idx" columns="creator_user"/>
      <index name="fk_cms_stzef_menus_cms_stzef_menus1_idx" columns="top_menu"/>
      <index name="fk_cms_stzef_menus_cms_stzef_pages1_idx" columns="page"/>
    </indexes>
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="name" type="string" column="name" length="255" nullable="false"/>
    <field name="alias" type="string" column="alias" length="255" nullable="false"/>
    <field name="orden" type="integer" column="orden" nullable="false"/>
    <field name="target" type="string" column="target" nullable="false"/>
    <field name="ifMain" type="boolean" column="if_main" nullable="false"/>
    <field name="dateCreation" type="datetime" column="date_creation" nullable="false"/>
    <field name="modified" type="datetime" column="modified" nullable="true"/>
    <field name="params" type="string" column="params" length="1000" nullable="true"/>
    <many-to-one field="page" target-entity="CmsStzefPages">
      <join-columns>
        <join-column name="page" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="topMenu" target-entity="CmsStzefMenus">
      <join-columns>
        <join-column name="top_menu" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="idTypeAccess" target-entity="CmsStzefTypesAccess">
      <join-columns>
        <join-column name="id_type_access" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="creatorUser" target-entity="CmsStzefUsers">
      <join-columns>
        <join-column name="creator_user" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="idStatePublication" target-entity="CmsStzefStatesPublication">
      <join-columns>
        <join-column name="id_state_publication" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 34: 279 (1895)

#### Original name
Naemaspora strobi Allesch.

### Remarks
null


text:
<!doctype html>

	<meta charset="utf-8">

	<link rel="stylesheet" href="../../../../docs/style.css">

timelinefx:timelinefx.tlGameObject.HandleVector

Property HandleVector:tlVector2

Get/Set the handle of the object. Handle is the origin of the object.
This can be used to dictate where the object is drawn from and also the point at which it is rotated around. By default the handle is set to the center of the object.

Parameters


text:
module MyMaybe where

isJust :: Maybe a -> Bool
isJust Nothing = False
isJust _       = True

isNothing :: Maybe a -> Bool
isNothing = not.isJust

mayybee :: b -> (a -> b) -> Maybe a -> b
mayybee b _ Nothing  = b
mayybee b f (Just a) = f a

fromMaybe :: a -> Maybe a -> a
fromMaybe = flip mayybee id

listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe l = Just $ head l

maybeToList :: Maybe a -> [a]
maybeToList Nothing  = []
maybeToList (Just a) = [a]

catMaybes :: [Maybe a] -> [a]
catMaybes = concat . map maybeToList

flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe l =
    bool Nothing (Just $ catMaybes l) (length l == length (catMaybes l))
  where -- or import Data.Bool
    bool x y b
       | b         = y
       | otherwise = x


text:
@implementation UIButton (WRConvenience)

+ (UIButton *)wr_buttonWithBGImageName:(NSString *)bgImageName {
    UIButton *button = [self wr_buttonWithBGImageName:bgImageName
                                            imageName:nil
                                                title:nil
                                          normalColor:nil
                                     highlightedColor:nil
                                        selectedColor:nil
                                                 font:nil
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:0];
    return button;
}
+ (UIButton *)wr_buttonWithImageName:(NSString *)imageName {
    UIButton *button = [self wr_buttonWithBGImageName:nil
                                            imageName:imageName
                                                title:nil
                                          normalColor:nil
                                     highlightedColor:nil
                                        selectedColor:nil
                                                 font:nil
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:0];
    return button;
}
+ (UIButton *)wr_buttonWithBgNormalColor:(UIColor *)bgNormalColor
                      bgHighlightedColor:(UIColor *)bgHighlightedColor
                                   title:(nullable NSString *)title
                             normalColor:(nullable UIColor *)normalColor
                        highlightedColor:(nullable UIColor *)highlightedColor
                                    font:(nullable UIFont *)font {
    UIImage *bgNormalImage = [UIImage wr_imageWithColor:bgNormalColor];
    UIImage *bgHighlightImage = [UIImage wr_imageWithColor:bgHighlightedColor];

    UIButton *button = [self wr_buttonWithBGImageName:nil
                                            imageName:nil
                                                title:title
                                          normalColor:normalColor
                                     highlightedColor:highlightedColor
                                        selectedColor:nil
                                                 font:font
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:0];
    [button setBackgroundImage:[bgNormalImage stretchableImageWithLeftCapWidth:bgNormalImage.size.width / 2
                                                                  topCapHeight:bgNormalImage.size.height / 2]
                      forState:UIControlStateNormal];
    [button setBackgroundImage:[bgHighlightImage stretchableImageWithLeftCapWidth:bgHighlightImage.size.width / 2
                                                                     topCapHeight:bgHighlightImage.size.height / 2]
                      forState:UIControlStateHighlighted];
    return button;
}
+ (UIButton *)wr_buttonWithTitle:(nullable NSString *)title
                     normalColor:(nullable UIColor *)normalColor
                highlightedColor:(nullable UIColor *)highlightedColor
                            font:(nullable UIFont *)font {
    UIButton *button = [self wr_buttonWithBGImageName:nil
                                            imageName:nil
                                                title:title
                                          normalColor:normalColor
                                     highlightedColor:highlightedColor
                                        selectedColor:nil
                                                 font:font
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:0];
    return button;
}
+ (UIButton *)wr_buttonWithTitle:(nullable NSString *)title
                     normalColor:(nullable UIColor *)normalColor
                highlightedColor:(nullable UIColor *)highlightedColor
                   selectedColor:(nullable UIColor *)selectedColor
                            font:(nullable UIFont *)font {
    UIButton *button = [self wr_buttonWithBGImageName:nil
                                            imageName:nil
                                                title:title
                                          normalColor:normalColor
                                     highlightedColor:highlightedColor
                                        selectedColor:selectedColor
                                                 font:font
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:0];
    return button;
}
+ (UIButton *)wr_buttonWithBGImageName:(nullable NSString *)bgImageName
                                 title:(nullable NSString *)title
                           normalColor:(nullable UIColor *)normalColor
                      highlightedColor:(nullable UIColor *)highlightedColor
                                  font:(nullable UIFont *)font
                          cornerRadius:(CGFloat)cornerRadius {
    UIButton *button = [self wr_buttonWithBGImageName:bgImageName
                                            imageName:nil
                                                title:title
                                          normalColor:normalColor
                                     highlightedColor:highlightedColor
                                        selectedColor:nil
                                                 font:font
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:cornerRadius];
    return button;
}
+ (UIButton *)wr_buttonWithBGImageName:(NSString *)bgImageName
                             imageName:(NSString *)imageName
                                 title:(NSString *)title
                           normalColor:(UIColor *)normalColor
                      highlightedColor:(UIColor *)highlightedColor
                                  font:(UIFont *)font
                          cornerRadius:(CGFloat)cornerRadius {
    UIButton *button = [self wr_buttonWithBGImageName:bgImageName
                                            imageName:imageName
                                                title:title
                                          normalColor:normalColor
                                     highlightedColor:highlightedColor
                                        selectedColor:nil
                                                 font:font
                                         imageIsRight:NO
                                              offsize:0
                                         cornerRadius:cornerRadius];

    return button;
}

+ (UIButton *)wr_buttonWithBGImageName:(nullable NSString *)bgImageName
                             imageName:(nullable NSString *)imageName
                                 title:(nullable NSString *)title
                           normalColor:(nullable UIColor *)normalColor
                      highlightedColor:(nullable UIColor *)highlightedColor
                         selectedColor:(nullable UIColor *)selectedColor
                                  font:(nullable UIFont *)font
                          imageIsRight:(BOOL)imageIsRight
                               offsize:(CGFloat)offsize
                          cornerRadius:(CGFloat)cornerRadius {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    if (![NSObject wr_isEmtpty:bgImageName]) {
        UIImage *normalBGImage = [UIImage imageNamed:bgImageName];
        if (normalBGImage != nil) {
            [button setBackgroundImage:normalBGImage forState:UIControlStateNormal];
        }
        NSString *highlightedBGImageName = [bgImageName stringByAppendingString:@"Highlighted"];
        UIImage *highlightedBGImage = [UIImage imageNamed:highlightedBGImageName];
        if (highlightedBGImage != nil) {
            [button setBackgroundImage:highlightedBGImage forState:UIControlStateHighlighted];
        }
        NSString *selectedBGImageName = [bgImageName stringByAppendingString:@"Selected"];
        UIImage *selectedBGImage = [UIImage imageNamed:selectedBGImageName];
        if (selectedBGImage != nil) {
            [button setBackgroundImage:selectedBGImage forState:UIControlStateSelected];
        }
    }
    if (![NSObject wr_isEmtpty:imageName]) {
        UIImage *normalImage = [UIImage imageNamed:imageName];
        if (normalImage != nil) {
            [button setImage:normalImage forState:UIControlStateNormal];
        }
        NSString *highlightedImageName = [imageName stringByAppendingString:@"Highlighted"];
        UIImage *highlightedImage = [UIImage imageNamed:highlightedImageName];
        if (highlightedImage != nil) {
            [button setImage:highlightedImage forState:UIControlStateHighlighted];
        }
        NSString *selectedImageName = [imageName stringByAppendingString:@"Selected"];
        UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
        if (selectedImage != nil) {
            [button setImage:selectedImage forState:UIControlStateSelected];
        }
    }
    if (![NSObject wr_isEmtpty:title]) {
        [button setTitle:title forState:UIControlStateNormal];
    }
    if (![NSObject wr_isEmtpty:normalColor]) {
        [button setTitleColor:normalColor forState:UIControlStateNormal];
    }
    if (![NSObject wr_isEmtpty:highlightedColor]) {
        [button setTitleColor:highlightedColor forState:UIControlStateHighlighted];
    }
    if (![NSObject wr_isEmtpty:font]) {
        button.titleLabel.font = font;
    }
    if (![NSObject wr_isEmtpty:selectedColor]) {
        [button setTitleColor:selectedColor forState:UIControlStateSelected];
    }
    if (cornerRadius > 0) {
        button.clipsToBounds = YES;
        button.layer.cornerRadius = cornerRadius;
    }
    // 只有同时存在图片和文字时,才存在交换,如果offsize==0,并且图片在左,也没必要执行交换方法
    if (button.currentImage != nil && ![NSObject wr_isEmtpty:button.titleLabel.text] && (offsize > 0 || imageIsRight)) {
        if (imageIsRight) {
            CGFloat titleWidth = button.titleLabel.wr_width;
            CGFloat imageWidth = button.currentImage.size.width;

            [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth)];
            [button setImageEdgeInsets:UIEdgeInsetsMake(0, titleWidth + offsize, 0, -titleWidth - offsize)];
        } else {
            [button setTitleEdgeInsets:UIEdgeInsetsMake(0, offsize, 0, 0)];
        }
    }

    return button;
}
@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>ICSME 2019 - Short Papers Track CFP</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

Short Papers Track - Call for Papers

Important Dates

**All submission dates are at 23:59 AoE (Anywhere on Earth, UTC-12)**

Paper Submission

                        Friday, June 14, 2019

Author Notification

                        Friday, July 12, 2019

Camera Ready Submission

                        Wednesday, July 31, 2019

The Short Papers Track provides an opportunity for sharing valuable early-stage work with the ICMSE community, eliciting feedback, and fostering discussions and collaborations among researchers interested in the broad area of Software Maintenance and Evolution.

The scope of research topics of this track is the same as for the main conference. We encourage researchers and practitioners to submit work-in-progress to discuss ongoing research, negative results, practical experience, challenges or issues related to software maintenance and evolution. The papers in this track do not require a strong empirical evaluation.

Evaluation

All submissions that meet the submission criteria (see below) and fit the scope of the conference will be reviewed by members of the ERA track program committee. Submissions will be evaluated on the basis of soundness, quality and consistency of presentation, position with respect to related work, and evaluation (if available - a complete evaluation is not required).

Submission Criteria and Instructions

We use the double-blind reviewing process. Submissions should not reveal the identity of the authors in any way. This means that authors should:

Leave out author names and affiliations from the body and the metadata of the submitted pdf.

Ensure that any citations to related work by themselves are written in the third person, for example "the prior work of XYZ" as opposed to "our prior work [2]".

Not refer to their personal, lab or university website; similarly, care should be taken with personal accounts on GitHub, Bitbucket, Google Drive, etc.

Not upload unblinded versions of their paper on archival websites during bidding/reviewing, however uploading unblinded versions prior to submission is allowed and sometimes unavoidable (e.g., thesis).

Please see the Double-Blind Reviewing FAQ for more information and guidance.

Submissions must be in English and conform to the ICSME 2019 Formatting Instructions.

Papers must not exceed 5 pages including all text, appendices, figures, tables and references.

All submissions must be in PDF and must be submitted via the ICSME 2019 EasyChair conference management system at https://easychair.org/conferences/?conf=icsme19.

Submissions that are not in compliance with the required submission format or that are out of the scope of the conference will be rejected without being reviewed. Submitted papers must comply with IEEE plagiarism policy and procedures. Papers submitted to the ERA track must not have been published elsewhere and must not be under review or submitted for review elsewhere while under consideration for ICSME 2019.

All authors, reviewers, and organizers are expected to uphold the IEEE Code of Conduct.

Publication and Presentation

All accepted submissions will be published in the proceedings of the ICSME 2019 conference and presented at the main conference.

Track Chairs

Sonia Haiduc, Florida State University, United States

Federica Sarro, University College London, United Kingdom


text:
package org.drools.core.runtime.rule.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.drools.core.QueryResult;
import org.drools.core.rule.Declaration;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;

public class NativeQueryResults
    implements
    QueryResults {

    private org.drools.core.QueryResults results;

    private String[] identifiers;

    public NativeQueryResults() {
    }

    public NativeQueryResults(org.drools.core.QueryResults results) {
        this.results = results;
    }

    public org.drools.core.QueryResults getResults() {
        return results;
    }

    public String[] getIdentifiers() {
        if ( identifiers != null ) {
            return identifiers;
        }
        Declaration[] parameters = this.results.getParameters();

        Set<String> set  = new HashSet<String>();
        for ( Declaration declr : parameters ) {
            set.add( declr.getIdentifier() );
        }

        Collection<Declaration> declrCollection = new ArrayList( results.getDeclarations(0).values() );

        for ( Iterator<Declaration> it =  declrCollection.iterator(); it.hasNext(); ) {
            Declaration declr = it.next();
            if ( set.contains( declr.getIdentifier()  ) ) {
                it.remove();
            }
        }

        String[] declrs = new String[parameters.length + declrCollection.size() ];
        int i = 0;
        for ( Declaration declr : parameters ) {
            declrs[i++] = declr.getIdentifier();
        }
        for ( Declaration declr : declrCollection ) {
            declrs[i++] = declr.getIdentifier();
        }
        identifiers = declrs;
        return identifiers;
    }

    public Map<String, Declaration> getDeclarations() {
        return this.getResults().getDeclarations(0);
    }

    public int size() {
        return this.getResults().size();
    }

    public Iterator<QueryResultsRow> iterator() {
        return new QueryResultsIterator( this.getResults().iterator() );
    }

    private class QueryResultsIterator
        implements
        Iterator<QueryResultsRow> {
        private Iterator<QueryResult> iterator;

        public QueryResultsIterator(final Iterator<QueryResult> iterator) {
            this.iterator = iterator;
        }

        public boolean hasNext() {
            return this.iterator.hasNext();
        }

        public QueryResultsRow next() {
            return new NativeQueryResultRow(this.iterator.next());
        }

        public void remove() {
            this.iterator.remove();
        }

    }

}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt

package com.google.appinventor.components.runtime;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;

import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Component for displaying web pages
 * This is a very limited form of browser.  You can view web pages and
 * click on links. It also handles  Javascript. There are lots of things that could be added,
 * but this component is mostly for viewing individual pages.  It's not intended to take
 * the place of the browser.
 *
 * @author halabelson@google.com (Hal Abelson)
 */

@DesignerComponent(version = YaVersion.WEBVIEWER_COMPONENT_VERSION,
                   category = ComponentCategory.EXPERIMENTAL,
                   description = "Component for viewing Web pages.  The Home URL can be " +
                   "specified in the Designer or in the Blocks Editor.  The view can be set " +
                   "to follow links when they are tapped, and users can fill in Web forms. " +
                   "Warning: This is not a full browser.  For example, pressing the phone's " +
                   "hardware Back key will exit the app, rather than move back in the " +
                   "browser history.")

// TODO(halabelson): Integrate control of the Back key, when we provide it

@SimpleObject
@UsesPermissions(permissionNames = "android.permission.INTERNET")
public final class WebViewer extends AndroidViewComponent {

  private final WebView webview;

  // URL for the WebViewer to load initially
  private String homeUrl;

  // whether or not to follow links when they are tapped
  private boolean followLinks;

  /**
   * Creates a new WebViewer component.
   *
   * @param container  container the component will be placed in
   */
  public WebViewer(ComponentContainer container) {
    super(container);

    webview = new WebView(container.$context());
    webview.setWebViewClient(new WebViewerClient());
    webview.getSettings().setJavaScriptEnabled(true);
    webview.setFocusable(true);
    // enable pinch zooming and zoom controls
    webview.getSettings().setBuiltInZoomControls(true);
    container.$add(this);

    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
              if (!v.hasFocus()) {
                v.requestFocus();
              }
              break;
          }
          return false;
        }
      });

    // set the initial default properties.  Height and Width
    // will be fill-parent, which will be the default for the web viewer.

    followLinks = true;
    HomeUrl("");
    Width(LENGTH_FILL_PARENT);
    Height(LENGTH_FILL_PARENT);
  }

  @Override
  public View getView() {
    return webview;
  }

  // Create a class so we can override the default link following behavior.
  // The handler doesn't do anything on its own.  But returning true means that
  // this do nothing will override the default WebVew behavior.  Returning
  // false means to let the WebView handle the Url.  In other words, returning
  // true will not follow the link, and returning false will follow the link.
  private class WebViewerClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return !followLinks;
    }
  }

  // Components don't normally override Width and Height, but we do it here so that
  // the automatic width and height will be fill parent.
  @Override
  @SimpleProperty()
  public void Width(int width) {
    if (width == LENGTH_PREFERRED) {
      width = LENGTH_FILL_PARENT;
    }
    super.Width(width);
  }

  @Override
  @SimpleProperty()
  public void Height(int height) {
    if (height == LENGTH_PREFERRED) {
      height = LENGTH_FILL_PARENT;
    }
    super.Height(height);
  }

  /**
   * Returns the URL of the page the WebVewier should load
   *
   * @return URL of the page the WebVewier should load
   */
  @SimpleProperty(
      description = "URL of the page the WebViewer should initially open to.  " +
      "Setting this will load the page.",
      category = PropertyCategory.BEHAVIOR)
  public String HomeUrl() {
    return homeUrl;
  }

  /**
   * Specifies the URL of the page the WebVewier should load
   *
   * @param url URL of the page the WebVewier should load
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
                    defaultValue = "")
  @SimpleProperty()
  public void HomeUrl(String url) {
    homeUrl = url;
    // clear the history, since changing Home is a kind of reset
    webview.clearHistory();
    webview.loadUrl(homeUrl);
  }

  /**
   * Returns the URL currently being viewed
   *
   * @return URL of the page being viewed
   */
  @SimpleProperty(
      description = "URL of the page currently viewed.   This could be different from the " +
      "Home URL if new pages were visited by following links.",
      category = PropertyCategory.BEHAVIOR)
  public String CurrentUrl() {
    return (webview.getUrl() == null) ? "" : webview.getUrl();
  }

  /**
   * Returns the title of the page currently being viewed
   *
   * @return title of the page being viewed
   */
  @SimpleProperty(
      description = "Title of the page currently viewed",
      category = PropertyCategory.BEHAVIOR)
  public String CurrentPageTitle() {
    return (webview.getTitle() == null) ? "" : webview.getTitle();
  }

  /** Indicates whether to follow links when they are tapped in the WebViewer
   * @return true or false
   */
  @SimpleProperty(
      description = "Determines whether to follow links when they are tapped in the WebViewer.  " +
      "If you follow links, you can use GoBack and GoForward to navigate the browser history. ",
      category = PropertyCategory.BEHAVIOR)
  public boolean FollowLinks() {
    return followLinks;
  }

  /** Determines whether to follow links when they are tapped
   *
   * @param follow
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN,
                    defaultValue = "True")
  @SimpleProperty()
  public void FollowLinks(boolean follow) {
    followLinks = follow;
  }

  /**
   * Loads the  page from the home URL.  This happens automatically when
   * home URL is changed.
   */
  @SimpleFunction(
      description = "Loads the home URL page.  This happens automatically when " +
      "the home URL is changed.")
  public void GoHome() {
    webview.loadUrl(homeUrl);
  }

  /**
   *  Go back to the previously viewed page.
   */
  @SimpleFunction(
      description = "Go back to the previous page in the history list.  " +
                    "Does nothing if there is no previous page.")
  public void GoBack() {
    if (webview.canGoBack()) {
      webview.goBack();
    }
  }

  /**
   *  Go forward in the history list
   */
  @SimpleFunction(
      description = "Go forward to the next page in the history list.   " +
                    "Does nothing if there is no next page.")
  public void GoForward() {
    if (webview.canGoForward()) {
      webview.goForward();
    }
  }

  /**
   *  @return true if the WebViewer can go forward in the history list
   */
  @SimpleFunction(
      description = "Returns true if the WebViewer can go forward in the history list.")
  public boolean CanGoForward() {
    return webview.canGoForward();
  }

  /**
   *  @return true if the WebViewer can go back in the history list
   */
  @SimpleFunction(
      description = "Returns true if the WebViewer can go back in the history list.")
  public boolean CanGoBack() {
    return webview.canGoBack();
  }

  /**
   *  Load the given URL
   */
  @SimpleFunction(
      description = "Load the page at the given URL.")
  public void GoToUrl(String url) {
    webview.loadUrl(url);
  }

}


text:
package fr.laas.fape.planning.core.planning.search.flaws.flaws;

import fr.laas.fape.planning.core.planning.planner.Planner;
import fr.laas.fape.planning.core.planning.search.flaws.resolvers.Resolver;
import fr.laas.fape.planning.core.planning.states.PartialPlan;

import java.util.List;

/**
 * Represents a flaw in a partial plan.
 * It is used to allow extraction of the resolvers directly from the state.
 */
public abstract class Flaw {

    /**
     * List of resolvers for this flaw.
     *
     * This is stored locally to make sure they are not computed twice.
     */
    public List<Resolver> resolvers = null; // TODO: move back to protected once resources are fixed

    /**
     * Returns the number of resolvers for this flaws.
     * This method is advised when the number of resolver is needed since it does not
     * necessarily generate all resolvers (thus reducing the stress on the garbage collection).
     * @param plan State used to look for resolvers.
     * @param planner The planner instance from which this method is called.
     *                It can be used to look for options as well as general knowledge
     *                on the problem (typically coming from preprocessing)
     * @return Number of resolvers for this flaw.
     */
    public int getNumResolvers(PartialPlan plan, Planner planner) {
        if(resolvers == null)
            resolvers = getResolvers(plan, planner);
        return resolvers.size();
    }

    /**
     * Finds and returns all resolvers for the flaw.
     * Best effort is done to make sure all resolvers are applicable in the state which might
     * result in expensive checks. Also some resolvers might not be applicable.
     *
     * @param plan State used to look for resolvers.
     * @param planner The planner instance from which this method is called.
     *                It can be used to look for options as well as general knowledge
     *                on the problem (typically coming from preprocessing)
     * @return A list of resolvers.
     */
    public abstract List<Resolver> getResolvers(PartialPlan plan, Planner planner);

    public abstract int compareTo(Flaw o);
}


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

namespace Cake\Error\Middleware;

use Cake\Core\App;
use Cake\Core\InstanceConfigTrait;
use Cake\Error\ErrorHandler;
use Cake\Error\ExceptionRenderer;
use Cake\Http\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;

/**
 * Error handling middleware.
 *
 * Traps exceptions and converts them into HTML or content-type appropriate
 * error pages using the CakePHP ExceptionRenderer.
 */
class ErrorHandlerMiddleware implements MiddlewareInterface
{
    use InstanceConfigTrait;

    /**
     * Default configuration values.
     *
     * - `log` Enable logging of exceptions.
     * - `skipLog` List of exceptions to skip logging. Exceptions that
     *   extend one of the listed exceptions will also not be logged. Example:
     *
     *   ```
     *   'skipLog' => ['Cake\Error\NotFoundException', 'Cake\Error\UnauthorizedException']
     *   ```
     *
     * - `trace` Should error logs include stack traces?
     * - `exceptionRenderer` The renderer instance or class name to use or a callable factory
     *   which returns a \Cake\Error\ExceptionRendererInterface instance.
     *   Defaults to \Cake\Error\ExceptionRenderer
     *
     * @var array
     */
    protected $_defaultConfig = [
        'skipLog' => [],
        'log' => true,
        'trace' => false,
        'exceptionRenderer' => ExceptionRenderer::class,
    ];

    /**
     * Error handler instance.
     *
     * @var \Cake\Error\ErrorHandler|null
     */
    protected $errorHandler;

    /**
     * Constructor
     *
     * @param \Cake\Error\ErrorHandler|null $errorHandler The error handler.
     * @param array $config Configuration options for error handler.
     *   These options will be ignored if an ErrorHandler instance is passed as
     *   first argument.
     */
    public function __construct($errorHandler = null, array $config = [])
    {
        $this->setConfig($config);

        if ($errorHandler !== null) {
            $this->errorHandler = $errorHandler;
        }
    }

    /**
     * Wrap the remaining middleware with error handling.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request The request.
     * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
     * @return \Psr\Http\Message\ResponseInterface A response.
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            return $handler->handle($request);
        } catch (Throwable $exception) {
            return $this->handleException($exception, $request);
        }
    }

    /**
     * Handle an exception and generate an error response
     *
     * @param \Throwable $exception The exception to handle.
     * @param \Psr\Http\Message\ServerRequestInterface $request The request.
     * @return \Psr\Http\Message\ResponseInterface A response
     */
    public function handleException(Throwable $exception, ServerRequestInterface $request): ResponseInterface
    {
        $errorHandler = $this->getErrorHandler();

        try {
            $response = $errorHandler->getRenderer($exception, $request)->render();
            $errorHandler->logException($exception, $request);
        } catch (Throwable $internalException) {
            $errorHandler->logException($internalException, $request);
            $response = $this->handleInternalError();
        }

        return $response;
    }

    /**
     * Handle internal errors.
     *
     * @return \Psr\Http\Message\ResponseInterface A response
     */
    protected function handleInternalError(): ResponseInterface
    {
        $response = new Response(['body' => 'An Internal Server Error Occurred']);

        return $response->withStatus(500);
    }

    /**
     * Get a error handler instance
     *
     * @return \Cake\Error\ErrorHandler The error handler.
     */
    protected function getErrorHandler(): ErrorHandler
    {
        if ($this->errorHandler === null) {
            /** @var string $className */
            $className = App::className('ErrorHandler', 'Error');
            /** @var \Cake\Error\ErrorHandler $this->errorHandler */
            $this->errorHandler = new $className($this->getConfig());
        }

        return $this->errorHandler;
    }
}


text:
define([
    'app/lang/topic',
    'app/util/ListenerUtil',
    'dijit/layout/TabContainer',
    'dijit/registry',
    'dojo/_base/declare'
], function(topic, ListenerUtil, TabContainer, registry, declare) {

    return declare("app.widget.TabContainer", TabContainer, {

        /**
         * LatestWidget
         */
        latestWidget : null,

        /**
         * tabLock
         */
        tabLock : false,

        /**
         * Override
         */
        selectChild : function(/* dijit/_WidgetBase|String */page, /* Boolean */animate) {
            if (page.id)
                this.latestWidget = page.id;
            this.inherited(arguments);
        },

        /**
         * Override
         */
        postCreate : function() {
            this.inherited(arguments);
            var _this = this;

            this.own(this.watch('selectedChildWidget', function(name, oval, nval) {
                if (_this.latestWidget)
                    _this.latestWidget = oval.id;
                else
                    _this.latestWidget = nval.id;
            }));

            this.subscribe(ListenerUtil.TOPIC_KEYS.FORM_DATA_CHANGE_TAB_LOCK, function() {
                if (_this.tabLock)
                    _this.selectChild(_this.latestWidget);
                _this.tabLock = false;
            });

        }

    });
});