text:
package org.myrobotlab.framework;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author GroG
 *
 *
 *         References :
 *
 *         http://www.excelsior-usa.com/articles/java-to-exe.html
 *
 *         possible small wrappers mac / linux / windows - http://mypomodoro
 *         .googlecode.com/svn-history/r89/trunk/src/main/java/org
 *         /mypomodoro/util/Restart.java
 *
 *         http://java.dzone.com/articles/programmatically-restart-java
 *         http://stackoverflow
 *         .com/questions/3468987/executing-another-application-from-java
 *
 *
 *         TODO - ARMV 6 7 8 ??? -
 *         http://www.binarytides.com/linux-cpu-information/ - lscpu
 *
 *         Architecture: armv7l Byte Order: Little Endian CPU(s): 4 On-line
 *         CPU(s) list: 0-3 Thread(s) per core: 1 Core(s) per socket: 1
 *         Socket(s): 4
 *
 *
 *         TODO - soft floating point vs hard floating point readelf -A
 *         /proc/self/exe | grep Tag_ABI_VFP_args soft = nothing hard =
 *         Tag_ABI_VFP_args: VFP registers
 *
 *         PACKAGING jsmooth - windows only javafx - 1.76u - more dependencies ?
 *         http://stackoverflow.com/questions/1967549/java-packaging-tools-
 *         alternatives-for-jsmooth-launch4j-onejar
 *
 *
 */
public class Bootstrap {

	static int BUFFER_SIZE = 2048;
	// BAD BAD BUG LEAVING IT COMMENTED
	// THE DANGERS OF STATIC INITIALIZATION !!
	// static PreLogger log = PreLogger.getInstance();
	PreLogger log;

	// TODO classpath order - for quick bleeding edge updates?
	// rsync exploded classpath

	// TODO - check for Java 1.7 or >
	// TODO - addShutdownHook

	// TODO - check for network connectivity
	// TODO - addShutdownHook

	// TODO - proxy
	// -Dhttp.proxyHost=webproxy -Dhttp.proxyPort=80
	// -Dhttps.proxyHost=webproxy -Dhttps.proxyPort=80
	// -Dhttp.proxyUserName="myusername" -Dhttp.proxyPassword="mypassword"

	// TODO? how to get vm args
	// http://stackoverflow.com/questions/1490869/how-to-get-vm-arguments-from-inside-of-java-application
	// http://java.dzone.com/articles/programmatically-restart-java
	// http://stackoverflow.com/questions/9911686/getresource-some-jar-returns-null-although-some-jar-exists-in-geturls
	// RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
	// List<String> arguments = runtimeMxBean.getInputArguments();

	private class StreamGobbler extends Thread {
		InputStream is;
		String type;

		private StreamGobbler(InputStream is, String type) {
			this.is = is;
			this.type = type;
		}

		@Override
		public void run() {
			try {
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				while ((line = br.readLine()) != null) {
					// System.out.println(type + "> " + line);
					log.info(type + "> " + line);
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	public static List<String> getJVMArgs() {
		RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
		return runtimeMxBean.getInputArguments();
	}

	public synchronized void spawn(String[] in) throws IOException, URISyntaxException, InterruptedException {
		log = PreLogger.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		log.info(String.format("\n\nBootstrap starting spawn %s", formatter.format(new Date())));

		log.info("============== args begin ==============");
		List<String> jvmArgs = getJVMArgs();

		log.info(String.format("jvmArgs %s", Arrays.toString(jvmArgs.toArray())));
		log.info(String.format("in %s", Arrays.toString(in)));
		log.info("============== args end ==============");

		// FIXME - details on space / %20 decoding in URI
		// http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
		String protectedDomain = URLDecoder.decode(Bootstrap.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(), "UTF-8");

		// this is null in jar :P
		// String location = File.class.getResource(".").getPath();

		log.info(String.format("protected domain %s", protectedDomain));
		// log.info(String.format("location %s", location));

		// platform id
		Platform platform = Platform.getLocalInstance();
		String platformId = platform.getPlatformId();
		log.info("platform " + platformId);
		String ps = File.pathSeparator;
		String fs = System.getProperty("file.separator");

		ArrayList<String> outArgs = new ArrayList<String>();

		// FIXME FIXME FIXME - it SHOULD NOT be variable path name !!!
		// java setup
		// String class path = System.getProperty("java.class.path"); // wtf -
		// do
		// we have to do this?
		String classpath = String.format("./%s./myrobotlab.jar%s./libraries/jar/*", ps, ps);
		// the java which is executing me will be the java executing runtime
		// java vs javaw ?

		String javaExe = platform.isWindows() ? "javaw" : "java";

		String javaPath = System.getProperty("java.home") + fs + "bin" + fs + javaExe;
		// JNI
		String jniLibraryPath = String.format("-Djava.library.path=libraries/native/%s", platformId);
		// FIXME - JNA path

		// String jvmMemory = "-Xmx2048m -Xms256m";
		Integer totalMemory = getTotalPhysicalMemory();
		if (totalMemory == null) {
			log.info("could not get total physical memory");
		} else {
			log.info("total physical memory returned is %d Mb", totalMemory);
		}

		/* mebbe windows does not like quotes anymore ?
		if (platform.isWindows()) {
			outArgs.add(String.format("\"%s\"", javaPath));
		} else {
			outArgs.add(javaPath);
		}
		*/
		outArgs.add(javaPath);

		// transferring original jvm args
		/* DO NOT TRANSFER ALL DETAILS SHOULD BE DERIVED HERE - NOT PULLED FROM THE
		 * DEFINITION OF THIS CURRENTLY RUN JVM
		 */
		/*
		for (int i = 0; i < jvmArgs.size(); ++i) {
			String jvmArg = jvmArgs.get(i);
			if (!jvmArg.startsWith("-agentlib")) {
				outArgs.add(jvmArgs.get(i));
			}
		}
		*/

		outArgs.add(jniLibraryPath);
		outArgs.add("-cp");
		outArgs.add(classpath);

		// outArgs.add(classpath);
		// outArgs.add("org.myrobotlab.service.Runtime"); DOUBLE ENTRY !

		boolean hasService = false;
		for (int i = 0; i < in.length; ++i){
			String arg = in[i];
			if (arg.startsWith("org.myrobotlab.service")){
				hasService = true;
			}
		}

		if (!hasService){
			outArgs.add("org.myrobotlab.service.Runtime");
		}

		// TODO preserve/serialize command line parameters
		if (in.length > 0) {
			for (int i = 0; i < in.length; ++i) {
				outArgs.add(in[i]);
			}
		} else {
			// (default) - no parameters supplied

			outArgs.add("-service");
			outArgs.add("gui");
			outArgs.add("GUIService");
			outArgs.add("python");
			outArgs.add("Python");
		}

		// ProcessBuilder builder = new ProcessBuilder(path, "-Xmx1024m", "-cp",
		// classpath, ReSpawner.class.getName());

		if (Files.exists(Paths.get("./update/myrobotlab.jar"))) {
			// attempt to process the update
			log.info("update exists archiving current");

			try {
				// if thrown - "file locked" then createBootstrapJar
				// IF THAT THROWS - GIVE UP !!!

				// update available - archive old file
				Path source = Paths.get("./myrobotlab.jar");
				File archiveDir = new File("./archive");
				archiveDir.mkdirs();
				Path target = Paths.get(String.format("./archive/myrobotlab.%s.jar", getVersion()));
				Files.move(source, target, REPLACE_EXISTING);

				// copy update
				log.info("moving update");
				source = Paths.get("./update/myrobotlab.jar");
				target = Paths.get("./myrobotlab.jar");
				Files.move(source, target, REPLACE_EXISTING);
				log.info("moved update !");
			} catch (FileSystemException e) {
				try {
					// FIXME FIXME - normalize the start !!!!
					log.info(String.format("file myrobotlab.jar is locked - ejecting bootstrap.jar - %s", e.getMessage()));
					createBootstrapJar();

					ArrayList<String> bootArgs = new ArrayList<String>();

					bootArgs.add(javaPath);
					bootArgs.add("-jar");
					bootArgs.add("./bootstrap.jar"); // -jar uses manifest
					// bootArgs.add("org.myrobotlab.framework.Bootstrap");
					for (int i = 0; i < in.length; ++i) {
						bootArgs.add(in[i]);
					}
					String cmd = formatList(bootArgs);
					log.info(String.format("bootstrap.jar spawning -> [%s]", cmd));
					ProcessBuilder builder = new ProcessBuilder(bootArgs);
					Process process = builder.start();

					/*
					FIXME - THIS WILL BLOCK AND HOLD THE PROCESS OPEN !!!
					StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");

					// any output?
					// StreamGobbler outputGobbler = new
					// StreamGobbler(process.getInputStream(), "OUTPUT");
					StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");

					// start gobblers
					outputGobbler.start();
					errorGobbler.start();
					*/

					// FIXME process.exitValue() will throw if process has not exited
					//log.info(String.format("done - good luck new bootstrap - exitValue %d", process.exitValue()));

					log.info(String.format("terminating - good luck new bootstrap :)"));
					PreLogger.close();
					System.exit(0);
					return;
				} catch (Exception ex) {
					log.error("PANIC - failed to create bootstrap - terminating - bye :(");
					PreLogger.close();
					log.error(ex);
					return;
				}
			}
		}

		String cmd = formatList(outArgs);
		log.info(String.format("spawning -> [%s]", cmd));
		/*
		 * ArrayList<String> test = new ArrayList<String>();
		 * test.add(String.format("%s", javaPath)); test.add("-cp");
		 * test.add("./myrobotlab.jar:./libraries/jar/*:./");
		 * test.add("org.myrobotlab.service.Runtime");
		 */
		ProcessBuilder builder = new ProcessBuilder(outArgs);// .inheritIO();

		// environment variables setup
		Map<String, String> env = builder.environment();
		if (platform.isLinux()) {
			String ldPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${LD_LIBRARY_PATH}", platformId);
			env.put("LD_LIBRARY_PATH", ldPath);
		} else if (platform.isMac()) {
			String dyPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${DYLD_LIBRARY_PATH}", platformId);
			env.put("DYLD_LIBRARY_PATH", dyPath);
		} else if (platform.isWindows()) {
			String path = String.format("PATH=%%CD%%\\libraries\\native;PATH=%%CD%%\\libraries\\native\\%s;%%PATH%%", platformId);
			env.put("PATH", path);
		} else {
			log.error("unkown operating system");
		}

		// ========== extract if necessary begin ==========
		// check to see if jar directory exists
		File jar = new File("./libraries/jar");
		if (!jar.exists()) {
			jar.mkdirs();
			// TODO - write to preLog.txt and pre-pend/append that to
			// myrobotlab.log !
			// stat all files if !stat extract
			// FIXME - list contents of zip directory

			// extract absolutely required dependencies
			log.info("extracting ./libraries/jar");
			extract("./myrobotlab.jar", "./", "resource/framework/root/", true);
		} else {
			log.info("./libraries/jar already exists, skipping extraction");
		}

		if (!jar.exists() || !jar.isDirectory()) {
			log.error("ERROR libraries/jar does not exist or is not a directory");
		}
		// ========== extract if necessary end ==========

		// you could start more than one process

		// ProcessBuilder.inheritIO() is a little pointless since the Bootstrap
		// is a sabot which
		// will be discarded and terminate - hence no std/io
		// Process process = builder.start();
		// TODO hold on to process - check for zombies - agent control
		// http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
		Process process = builder.start();

		/* FIXME ??? MAYBE THIS IS OK - BUT ON THE BOOTLOADER IT HANGS
		StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");

		// any output?
		// StreamGobbler outputGobbler = new
		// StreamGobbler(process.getInputStream(), "OUTPUT");
		StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");

		// start gobblers
		outputGobbler.start();
		errorGobbler.start();
		*/

		// int ret = process.waitFor();
		// log.info(String.format("process returned %d", ret));

		// Runtime.getRuntime().exec(outArgs.toArray(new
		// String[outArgs.size()]));

		// TODO make new filew or pre-pend to myrobotlab.log
		// THESE WILL HANG THE PROCESS !!!!!
		// inheritIO(process.getInputStream(), System.out);
		// inheritIO(process.getErrorStream(), System.err);
		// process.waitFor();

		log.info(String.format("Bootstrap finished spawn %s", formatter.format(new Date())));
		PreLogger.close();

	}

	public String formatList(ArrayList<String> args) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < args.size(); ++i) {
			sb.append(String.format("%s ", args.get(i)));
		}

		return sb.toString();
	}

	public String getVersion() {
		log = PreLogger.getInstance();
		InputStream isr = Bootstrap.class.getResourceAsStream("/resource/version.txt");
		if (isr == null) {
			log.error("can not find resource [/resource/version.txt]");
			return null;
		}
		return new String(toByteArray(isr));
	}

	public byte[] toByteArray(InputStream is) {
		log = PreLogger.getInstance();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {

			int nRead;
			byte[] data = new byte[16384];

			while ((nRead = is.read(data, 0, data.length)) != -1) {
				baos.write(data, 0, nRead);
			}

			baos.flush();
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			log.error(e);
		}

		return null;
	}

	static public void extract(String resourcePath, String targetDirectory, String filter, boolean overwrite) throws IOException {
		// log.debug(String.format("extractFromResource (%s,%s)", resourcePath,
		// targetDirectory));
		InputStream source = new FileInputStream(resourcePath);

		File target = new File(targetDirectory);

		if (!target.exists() && !target.mkdirs()) {
			source.close();
			throw new IOException("Unable to create directory " + target.getAbsolutePath());
		}

		ZipInputStream in = new ZipInputStream(source);
		try {

			byte[] buffer = new byte[BUFFER_SIZE];

			for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
				// log.info(entry.getName());

				if (filter == null || entry.getName().startsWith(filter)) {

					String filename = entry.getName().substring(filter.length());
					// File file = new File(target, entry.getName());
					File file = new File(target, filename);

					// log.debug("Extracted Resource = " + entry.getName());
					if (entry.isDirectory()) {
						file.mkdirs();
					} else {
						file.getParentFile().mkdirs();
						if (!file.exists() || overwrite) {
							OutputStream out = new FileOutputStream(file);
							try {
								int count;
								while ((count = in.read(buffer)) > 0) {
									out.write(buffer, 0, count);
								}
							} finally {
								out.close();
							}
						}
						in.closeEntry();
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			in.close();
		}
	}

	public void createBootstrapJar() throws IOException {
		ArrayList<String> resources = new ArrayList<String>();
		resources.add("/org/myrobotlab/framework/Bootstrap.class");
		resources.add("/org/myrobotlab/framework/Platform.class");
		resources.add("/org/myrobotlab/framework/PreLogger.class");
		resources.add("/resource/version.txt");
		createJarArchive("bootstrap.jar", resources);
	}

	/**
	 * takes an array list of filenames in current jar (TODO - make debuggable
	 * bin)
	 *
	 * @param archiveFileName
	 * @param tobeJared
	 * @throws IOException
	 */
	public void createJarArchive(String archiveFileName, ArrayList<String> tobeJared) throws IOException {

		File archiveFile = new File(archiveFileName);
		byte buffer[] = new byte[BUFFER_SIZE];
		// Open archive file
		FileOutputStream stream = new FileOutputStream(archiveFile);
		Manifest manifest = new Manifest();

		// http://www.concretepage.com/java/add-manifest-into-jar-file-using-java
		Attributes global = manifest.getMainAttributes();
		global.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
		global.put(new Attributes.Name("Built-By"), String.format("Bootstrap %s", getVersion()));
		// global.put(new Attributes.Name("CLASS_PATH"), "dummy classpath");
		// global.put(new Attributes.Name("CONTENT_TYPE"), "txt/plain");
		// global.put(new Attributes.Name("SIGNATURE_VERSION"), "2.0");
		// global.put(new Attributes.Name("SPECIFICATION_TITLE"),
		// "dummy title");
		// global.put(new Attributes.Name("CLASS_PATH"), "dummy classpath");
		global.put(Attributes.Name.MAIN_CLASS, Bootstrap.class.getCanonicalName());

		JarOutputStream out = new JarOutputStream(stream, manifest);

		for (int i = 0; i < tobeJared.size(); i++) {

			String filename = tobeJared.get(i);
			System.out.println("Adding " + filename);

			// Add archive entry
			// TODO - must handle pathing
			String jarPath;
			if (filename.startsWith("/")) {
				jarPath = filename.substring(1);
			} else {
				jarPath = filename;
			}
			JarEntry jarAdd = new JarEntry(jarPath);
			// jarAdd.setTime(tobeJared[i].lastModified());
			out.putNextEntry(jarAdd);

			// Write file to archive
			// TODO must handle asResource

			// FileInputStream in = new FileInputStream(tobeJared[i]);
			InputStream in = File.class.getResourceAsStream(filename);
			while (true) {
				int nRead = in.read(buffer, 0, buffer.length);
				if (nRead <= 0)
					break;
				out.write(buffer, 0, nRead);
			}
			in.close();
		}

		out.close();
		stream.close();

		System.out.println("Adding completed OK");

	}

	public void spawn(List<String> args) throws IOException, URISyntaxException, InterruptedException {
		spawn(args.toArray(new String[args.size()]));
	}

	public Integer getTotalPhysicalMemory() {
		try {
			com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
			Integer physicalMemorySize = (int) (os.getTotalPhysicalMemorySize() / 1048576);

			return physicalMemorySize;
		} catch (Exception e) {
			log.error("getTotalPhysicalMemory - threw");
		}
		return null;
	}

	public static void main(String[] args) {
		try {
			System.out.println("starting bootstrap");
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.spawn(args);
			System.out.println("leaving bootstrap");
		} catch (Exception e) {
			e.printStackTrace(System.out);
		} finally {
			System.exit(0);
		}
	}

}


text:
A simple shell script that generates file format description data for all
files in a BagIt bag.

## Overview

This script calls upon an instance of the
[DAITSS Format Description Service](https://github.com/daitss/describe)
to generate PREMIS records characterizing each file in a BagIt data directory.
The resulting records are saved in a new tag directory named "premis" inside
the bag's root.

This code is fairly trivial, and can be easily adapted to other use cases.

## Setting up a local instance of the Format Description Service

The best way to use this script is to have a local instance of the Format
Description Service running on your machine, though technically it doesn't
matter what machine you run it on since all of the communication happens over
HTTP.

These steps should help you to set up and run such an instance with minimal
effort.

Requirements:

*   Linux or Mac OSX
*   [RVM](https://rvm.io/)
*   [Java](https://www.java.com/)

(Before you begin: Make sure a Java JRE or JDK is installed somewhere and that
the `JAVA_HOME` environment variable is set to the path where it is located.)

1.  Open a Linux/Mac command line and `cd` into the directory where you want
    the description service to reside. (Inside of this directory is fine if
    you're not sure.)
2.  `curl -L https://github.com/daitss/describe/archive/5035ef1a9a4dd0aea1eedc3f4ad5e8a619974b95.tar.gz | tar zx`
3.  `cd describe-5035ef1a9a4dd0aea1eedc3f4ad5e8a619974b95`
4.  `rvm use 1.9.3`
5.  `bundle install` (you may run into issues here depending on your platform;
    refer to the README.md file in the `describe-5035...` directory for more
    information on setting up the Format Description Service if needed)
6.  `export DAITSS_CONFIG=daitss-config.example.yml`
7.  `export VIRTUAL_HOSTNAME=describe.example.org`
8.  `bundle exec thin start`

## Using the bag-describe shell script

If needed, edit the `bag-describe` file in this directory using a text editor
and change the location specified on the line that reads

    DESCRIBE_URL=http://localhost:3000

to the actual URL and port of your Description Service instance.

Then simply run

    ./bag-describe path/to/your/bag

to start the process. The resulting PREMIS records will be created in a new
directory inside your bag's root called `premis`.

# Using the bag-describe.py Python script

The Python script can be invoked as a standalone script with the following
arguments:

* The URL to the description service
* The path to the bag

For example:

    python bag-describe.py http://localhost:3000 path/to/your/bag

Note: The bag-describe.py module can also be imported into other scripts or
applications. For example:

    from bag-describe import bag-describe
    ...
    bag_describe(description_url, bag_path)

## License

See LICENSE.txt

redpajama_set_name: RedPajamaGithub


text:
import Field from '../field/Field';
import NativePromise from 'native-promise-only';
import _ from 'lodash';

export default class Multivalue extends Field {
  get dataValue() {
    const parent = super.dataValue;

    if (!parent && this.component.multiple) {
      return [];
    }
    return parent;
  }

  set dataValue(value) {
    super.dataValue = value;
  }

  get defaultValue() {
    let value = super.defaultValue;

    if (this.component.multiple) {
      if (_.isArray(value)) {
        value = !value.length ? [super.emptyValue] : value;
      }
      else {
        value = [value];
      }
    }

    return value;
  }

  get addAnother() {
    return this.t(this.component.addAnother || 'Add Another');
  }

  useWrapper() {
    return this.component.hasOwnProperty('multiple') && this.component.multiple;
  }

  render() {
    // If single value field.
    if (!this.useWrapper()) {
      return super.render(
        `<div ref="element">
          ${this.renderElement(
            this.component.type !== 'hidden' ? this.dataValue : ''
          )}
        </div>`
      );
    }

    // Make sure dataValue is in the correct array format.
    let dataValue = this.dataValue;
    if (!Array.isArray(dataValue)) {
      dataValue = dataValue ? [dataValue] : [];
    }

    // If multiple value field.
    return super.render(this.renderTemplate('multiValueTable', {
      rows: dataValue.map(this.renderRow.bind(this)).join(''),
      disabled: this.disabled,
      addAnother: this.addAnother,
    }));
  }

  renderElement() {
    return '';
  }

  renderRow(value, index) {
    return this.renderTemplate('multiValueRow', {
      index,
      disabled: this.disabled,
      element: `${this.renderElement(value, index)}`,
    });
  }

  attach(dom) {
    const superAttach = super.attach(dom);
    this.loadRefs(dom, {
      addButton: 'multiple',
      input: 'multiple',
      removeRow: 'multiple',
      mask: 'multiple',
      select: 'multiple',
    });

    const promises = [];

    this.refs.input.forEach((element, index) => {
      promises.push(this.attachElement.call(this, element, index));
    });

    if (!this.component.multiple) {
      return NativePromise.all(promises);
    }

    this.refs.removeRow.forEach((removeButton, index) => {
      this.addEventListener(removeButton, 'click', (event) => {
        event.preventDefault();
        this.removeValue(index);
      });
    });

    // If single value field.
    this.refs.addButton.forEach((addButton) => {
      this.addEventListener(addButton, 'click', (event) => {
        event.preventDefault();
        this.addValue();
      });
    });
    return superAttach.then(() => {
      return NativePromise.all(promises);
    });
  }

  detach() {
    if (this.refs.input && this.refs.input.length) {
      this.refs.input.forEach((input) => {
        if (input.mask) {
          input.mask.destroy();
        }
        if (input.widget) {
          input.widget.destroy();
        }
      });
    }
    if (this.refs.mask && this.refs.mask.length) {
      this.refs.mask.forEach((input) => {
        if (input.mask) {
          input.mask.destroy();
        }
      });
    }
    super.detach();
  }

  /**
   * Attach inputs to the element.
   *
   * @param element
   * @param index
   */
  attachElement(element, index) {
    this.addEventListener(element, this.inputInfo.changeEvent, () => {
      // Delay update slightly to give input mask a chance to run.
      const textCase = _.get(this.component, 'case', 'mixed');

      if (textCase !== 'mixed') {
        const {
          selectionStart,
          selectionEnd,
        } = element;

        if (textCase === 'uppercase' && element.value) {
          element.value = element.value.toUpperCase();
        }
        if (textCase === 'lowercase' && element.value) {
          element.value = element.value.toLowerCase();
        }

        if (element.selectionStart && element.selectionEnd) {
          element.selectionStart = selectionStart;
          element.selectionEnd = selectionEnd;
        }
      }

      try {
        this.saveCaretPosition(element, index);
      }
      catch (err) {
        console.warn('An error occurred while trying to save caret position', err);
      }

      // If a mask is present, delay the update to allow mask to update first.
      if (element.mask) {
        setTimeout(() => {
          return this.updateValue(null, {
            modified: (this.component.type !== 'hidden')
          }, index);
        }, 1);
      }
      else {
        return this.updateValue(null, {
          modified: (this.component.type !== 'hidden')
        }, index);
      }
    });

    if (!this.attachMultiMask(index)) {
      this.setInputMask(element);

      const valueMask = this.component.inputMask;
      const displayMask = this.component.displayMask;

      if (valueMask && displayMask && displayMask !== valueMask && this.refs.valueMaskInput) {
        this.setInputMask(this.refs.valueMaskInput, valueMask);
      }
    }
  }

  // Saves current caret position to restore it after the component is redrawn
  saveCaretPosition(element, index) {
    if (this.root?.focusedComponent?.path === this.path) {
      this.root.currentSelection = { selection: [element.selectionStart, element.selectionEnd], index };
    }
  }

  onSelectMaskHandler(event) {
    this.updateMask(event.target.maskInput, this.getMaskPattern(event.target.value));
  }

  getMaskPattern(maskName) {
    if (!this.multiMasks) {
      this.multiMasks = {};
    }
    if (this.multiMasks[maskName]) {
      return this.multiMasks[maskName];
    }
    const mask = this.component.inputMasks.find(inputMask => inputMask.label === maskName);
    this.multiMasks[maskName] = mask ? mask.mask : this.component.inputMasks[0].mask;
    return this.multiMasks[maskName];
  }

  attachMultiMask(index) {
    if (!(this.isMultipleMasksField && this.component.inputMasks.length && this.refs.input.length)) {
      return false;
    }

    const maskSelect = this.refs.select[index];
    maskSelect.onchange = this.onSelectMaskHandler.bind(this);
    maskSelect.maskInput = this.refs.mask[index];
    this.setInputMask(maskSelect.maskInput, this.component.inputMasks[0].mask);
    return true;
  }

  updateMask(input, mask) {
    if (!mask) {
      return;
    }
    this.setInputMask(input, mask, !this.component.placeholder);
    this.updateValue();
  }

  /**
   * Adds a new empty value to the data array.
   */
  addNewValue(value) {
    if (value === undefined) {
      value = this.component.defaultValue ?
      this.component.defaultValue : this.emptyValue;
      // If default is an empty aray, default back to empty value.
      if (Array.isArray(value) && value.length === 0) {
        value = this.emptyValue;
      }
    }
    let dataValue = this.dataValue || [];
    if (!Array.isArray(dataValue)) {
      dataValue = [dataValue];
    }

    if (Array.isArray(value)) {
      dataValue = dataValue.concat(value);
    }
    else {
      dataValue.push(value);
    }
    this.dataValue = dataValue;
  }

  /**
   * Adds a new empty value to the data array, and add a new row to contain it.
   */
  addValue() {
    this.addNewValue();
    this.redraw();
    this.checkConditions();
    if (!this.isEmpty(this.dataValue)) {
      this.restoreValue();
    }
    if (this.root) {
      this.root.onChange();
    }
  }
}


text:
<?php

namespace backend\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\Feedback;

class FeedbackController extends BackendController {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['actions' => ['index', 'update', 'delete'], 'allow' => true, 'roles' => ['@']]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex() {
        $var['list'] = Feedback::find()->all();
        return $this->render('index', $var);
    }

    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if (Yii::$app->request->isAjax) {
            $this->commonUpdate($model);
        }

        $var['model'] = $model;
        return $this->render('update', $var);
    }

    public function actionDelete($id) {
        if (Yii::$app->request->isAjax) {
            $model = $this->findModel($id);
            $model->delete() ? $this->ajaxSuccess() : $this->ajaxError();
        }
    }

    protected function findModel($id) {
        if (($model = Feedback::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
"""A simple agent-environment interaction loop."""

import operator
import time
from typing import Optional, Callable

from acme import core
from acme.utils import counting
from acme.utils import loggers

import dm_env
from dm_env import specs
import numpy as np
import tree

class CostEnvironmentLoop(core.Worker):
  """A simple RL environment loop.

  This tracks cost return as well as reward return.

  This takes `Environment` and `Actor` instances and coordinates their
  interaction. Agent is updated if `should_update=True`. This can be used as:

    loop = EnvironmentLoop(environment, actor)
    loop.run(num_episodes)

  A `Counter` instance can optionally be given in order to maintain counts
  between different Acme components. If not given a local Counter will be
  created to maintain counts between calls to the `run` method.

  A `Logger` instance can also be passed in order to control the output of the
  loop. If not given a platform-specific default logger will be used as defined
  by utils.loggers.make_default_logger. A string `label` can be passed to easily
  change the label associated with the default logger; this is ignored if a
  `Logger` instance is given.
  """

  def __init__(
      self,
      environment: dm_env.Environment,
      actor: core.Actor,
      gamma: float,
      num_costs: int,
      cost_fn: Callable[[np.ndarray, np.ndarray], np.ndarray],
      counter: Optional[counting.Counter] = None,
      logger: Optional[loggers.Logger] = None,
      should_update: bool = True,
      label: str = 'environment_loop',
  ):
    self._environment = environment
    self._actor = actor
    self._gamma = gamma
    self._num_costs = num_costs
    self._cost_fn = cost_fn
    if counter is None:
      counter = counting.Counter()
    if logger is None:
      logger = loggers.make_default_logger(label)
    self._counter = counter
    self._logger = logger
    self._should_update = should_update

  def run_episode(self) -> loggers.LoggingData:
    """Run one episode.

    Each episode is a loop which interacts first with the environment to get an
    observation and then give that observation to the agent in order to retrieve
    an action.

    Returns:
      An instance of `loggers.LoggingData` containing episode stats.
    """
    # Reset any counts and start the environment.
    start_time = time.time()
    episode_steps = 0

    # For evaluation, this keeps track of the total undiscounted reward
    # accumulated during the episode.
    episode_return = tree.map_structure(_generate_zeros_from_spec,
                                        self._environment.reward_spec())
    cost_spec = specs.Array(shape=(self._num_costs,), dtype=float, name='cost')
    episode_cost_return = tree.map_structure(_generate_zeros_from_spec,
                                             cost_spec)
    gamma_sum = 0.0

    timestep = self._environment.reset()

    self._actor.observe_first(timestep)

    # Run an episode.
    while not timestep.last():
      # Generate an action from the agent's policy and step the environment.
      action = self._actor.select_action(timestep.observation)
      timestep = self._environment.step(action)

      # Compute a immediate cost for (obs, action).
      # cost_fn is defined in terms of batch input/output
      cost = self._cost_fn(
          tree.map_structure(lambda x: np.array([x]), timestep.observation),
          np.array([action]))[0]

      # Have the agent observe the timestep and let the actor update itself.
      self._actor.observe(action, next_timestep=timestep)
      if self._should_update:
        self._actor.update()

      # Equivalent to: episode_return += timestep.reward
      # We capture the return value because if timestep.reward is a JAX
      # DeviceArray, episode_return will not be mutated in-place. (In all other
      # cases, the returned episode_return will be the same object as the
      # argument episode_return.)
      episode_return = tree.map_structure(operator.iadd, episode_return,
                                          timestep.reward)

      episode_cost_return = tree.map_structure(operator.iadd,
                                               episode_cost_return, cost)
      gamma_sum += self._gamma**episode_steps
      episode_steps += 1

    counts = self._counter.increment(episodes=1, steps=episode_steps)

    # Collect the results and combine with counts.
    steps_per_second = episode_steps / (time.time() - start_time)
    result = {
        'episode_length': episode_steps,
        'episode_return': episode_return,
        'steps_per_second': steps_per_second,
    }

    for k, cost in enumerate(episode_cost_return):
      result[f'episode_cost_return_{k}'] = cost
      result[f'episode_average_cost_{k}'] = cost / episode_steps

    result.update(counts)
    return result

  def run(self,
          *,
          num_episodes: Optional[int] = None,
          num_steps: Optional[int] = None):
    """Perform the run loop.

    Run the environment loop either for `num_episodes` episodes or for at
    least `num_steps` steps (the last episode is always run until completion,
    so the total number of steps may be slightly more than `num_steps`).
    At least one of these two arguments has to be None.

    Upon termination of an episode a new episode will be started. If both
    num_episodes and num_steps arguments are provided, the first criterion met
    between the two will terminate the run loop.

    Args:
      num_episodes: number of episodes to run the loop for.
      num_steps: minimal number of steps to run the loop for.

    Raises:
      ValueError: If both 'num_episodes' and 'num_steps' are not None.
    """

    if not (num_episodes is None or num_steps is None):
      raise ValueError('Either "num_episodes" or "num_steps" should be None.')

    def should_terminate(episode_count: int, step_count: int) -> bool:
      return (num_episodes is not None and
              episode_count >= num_episodes) or (num_steps is not None and
                                                 step_count >= num_steps)

    episode_count = 0
    step_count = 0
    while not should_terminate(episode_count, step_count):
      result = self.run_episode()
      episode_count += 1
      step_count += result['episode_length']
      self._logger.write(result)

def _generate_zeros_from_spec(spec: specs.Array) -> np.ndarray:
  return np.zeros(spec.shape, spec.dtype)


text:
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Samples.VisualStudio.Services.Interfaces;

namespace Microsoft.Samples.VisualStudio.Services
{
	/// <summary>
	/// This is the class that implements the global service. All it needs to do is to implement
	/// the interfaces exposed by this service (in this case IMyGlobalService).
	/// This class also needs to implement the SMyGlobalService interface in order to notify the
	/// package that it is actually implementing this service.
	/// </summary>
	public class MyGlobalService : IMyGlobalService
	{
		// Store in this variable the service provider that will be used to query for other services.
		private IServiceProvider serviceProvider;
		public MyGlobalService(IServiceProvider sp)
		{
			Debug.WriteLine("Constructing a new instance of MyGlobalService");
			serviceProvider = sp;
		}

		#region IMyGlobalService Members
		/// <summary>
		/// Implementation of the function that does not access the local service.
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Microsoft.Samples.VisualStudio.Services.HelperFunctions.WriteOnOutputWindow(System.IServiceProvider,System.String)")]
		public void GlobalServiceFunction()
		{
			string outputText = " ======================================\n" +
			                    "\tGlobalServiceFunction called.\n" +
			                    " ======================================\n";
			HelperFunctions.WriteOnOutputWindow(serviceProvider, outputText);
		}

		/// <summary>
		/// Implementation of the function that will call a method of the local service.
		/// Notice that this class will access the local service using as service provider the one
		/// implemented by ServicesPackage.
		/// </summary>
		public int CallLocalService()
		{
			// Query the service provider for the local service.
			// This object is supposed to be build by ServicesPackage and it pass its service provider
			// to the constructor, so the local service should be found.
			IMyLocalService localService = serviceProvider.GetService(typeof(SMyLocalService)) as IMyLocalService;
			if (null == localService)
			{
				// The local service was not found; write a message on the debug output and exit.
				Debug.WriteLine("Can not get the local service from the global one.");
				return -1;
			}

			// Now call the method of the local service. This will write a message on the output window.
			return localService.LocalServiceFunction();
		}
		#endregion
	}
}


text:
(function (window, document) {
'use strict';

angular.module('valdr')

/**
 * This service provides shared configuration between all valdr-message directive instances like the configured
 * template to render the violation messages and whether or not angular-translate is available.
 */
  .provider('valdrMessage', function () {

    var userDefinedTemplateUrl, userDefinedTemplate,
      messages = {},
      defaultTemplateUrl = 'valdr/default-message.html',
      defaultTemplate =   '
' +
                            '{{ violation.message }}' +
                          '
',
      translateTemplate = '
' +
                            '' +
                          '
';

    this.setTemplate = function (template) {
      userDefinedTemplate = template;
    };

    this.setTemplateUrl = function (templateUrl) {
      userDefinedTemplateUrl = templateUrl;
    };

    this.addMessages = function (newMessages) {
      angular.extend(messages, newMessages);
    };
    var addMessages = this.addMessages;

    this.getMessage = function (typeName, fieldName, validatorName) {
      var fullMessageKey = typeName + '.' + fieldName + '.' + validatorName;
      return messages[fullMessageKey] || messages[validatorName] || '[' + validatorName + ']';
    };
    var getMessage = this.getMessage;

    this.$get = ['$templateCache', '$injector', function ($templateCache, $injector) {

      var angularMessagesEnabled = false;

      function getTranslateService() {
        try {
          return $injector.get('$translate');
        } catch (error) {
          return undefined;
        }
      }

      function getFieldNameKeyGenerator() {
        try {
          return $injector.get('valdrFieldNameKeyGenerator');
        } catch (error) {
          return function(violation) {
            return violation.type + '.' + violation.field;
          };
        }
      }

      var $translate = getTranslateService(),
        translateAvailable = angular.isDefined($translate),
        fieldNameKeyGenerator = getFieldNameKeyGenerator();

      function determineTemplate() {
        if (angular.isDefined(userDefinedTemplate)) {
          return userDefinedTemplate;
        } else if (translateAvailable) {
          return translateTemplate;
        } else {
          return defaultTemplate;
        }
      }

      function updateTemplateCache() {
        $templateCache.put(defaultTemplateUrl, determineTemplate());
        if (userDefinedTemplateUrl && userDefinedTemplate) {
          $templateCache.put(userDefinedTemplateUrl, userDefinedTemplate);
        }
      }

      updateTemplateCache();

      return {
        templateUrl: userDefinedTemplateUrl || defaultTemplateUrl,
        setTemplate: function (newTemplate) {
          userDefinedTemplate = newTemplate;
          updateTemplateCache();
        },
        translateAvailable: translateAvailable,
        $translate: $translate,
        fieldNameKeyGenerator: fieldNameKeyGenerator,
        addMessages: addMessages,
        getMessage: getMessage,
        angularMessagesEnabled: angularMessagesEnabled
      };
    }];
  });

/**
 * This directive appends a validation message to the parent element of any input, select or textarea element, which
 * is nested in a valdr-type directive and has an ng-model bound to it.
 * If the form element is wrapped in an element marked with the class defined in valdrClasses.formGroup,
 * the messages is appended to this element instead of the direct parent.
 * To prevent adding messages to specific input fields, the attribute 'valdr-no-message' can be added to those input
 * or select fields. The valdr-message directive is used to do the actual rendering of the violation messages.
 */
var valdrMessageDirectiveDefinitionFactory = function (restrict) {
    return ['$compile', function ($compile) {
      return {
        restrict: restrict,
        require: ['?^valdrType', '?^ngModel', '?^valdrFormGroup'],
        link: function (scope, element, attrs, controllers) {

          var valdrTypeController = controllers[0],
            ngModelController = controllers[1],
            valdrFormGroupController = controllers[2],
            valdrNoValidate = attrs.valdrNoValidate,
            valdrNoMessage = attrs.valdrNoMessage,
            fieldName = attrs.name;

          /**
           * Don't do anything if
           * - this is an <input> that's not inside of a valdr-type or valdr-form-group block
           * - there is no ng-model bound to input
           * - there is a 'valdr-no-validate' or 'valdr-no-message' attribute present
           */
          if (!valdrTypeController || !valdrFormGroupController || !ngModelController ||
            angular.isDefined(valdrNoValidate) || angular.isDefined(valdrNoMessage)) {
            return;
          }

          var valdrMessageElement = angular.element('');
          $compile(valdrMessageElement)(scope);
          valdrFormGroupController.addMessageElement(ngModelController, valdrMessageElement);

          scope.$on('$destroy', function () {
            valdrFormGroupController.removeMessageElement(ngModelController);
          });

        }
      };
    }];
  },
  valdrMessageElementDirectiveDefinition = valdrMessageDirectiveDefinitionFactory('E'),
  valdrMessageAttributeDirectiveDefinition = valdrMessageDirectiveDefinitionFactory('A');

var nullValdrType = {
  getType: angular.noop
};

angular.module('valdr')
  .directive('input', valdrMessageElementDirectiveDefinition)
  .directive('select', valdrMessageElementDirectiveDefinition)
  .directive('textarea', valdrMessageElementDirectiveDefinition)
  .directive('enableValdrMessage', valdrMessageAttributeDirectiveDefinition)

/**
 * The valdr-message directive is responsible for the rendering of violation messages. The template used for rendering
 * is defined in the valdrMessage service where it can be overridden or a template URL can be configured.
 */
  .directive('valdrMessage',
  ['$rootScope', '$injector', 'valdrMessage', 'valdrUtil', function ($rootScope, $injector, valdrMessage, valdrUtil) {
    return {
      replace: true,
      restrict: 'A',
      scope: {
        formFieldName: '@valdrMessage'
      },
      templateUrl: function () {
        return valdrMessage.templateUrl;
      },
      require: ['^form', '?^valdrType'],
      link: function (scope, element, attrs, controllers) {
        var formController = controllers[0],
          valdrTypeController = controllers[1] || nullValdrType;

        var updateTranslations = function () {
          if (valdrMessage.translateAvailable && angular.isArray(scope.violations)) {
            angular.forEach(scope.violations, function (violation) {
              valdrMessage.$translate(valdrMessage.fieldNameKeyGenerator(violation)).then(function (translation) {
                violation.fieldName = translation;
              });
            });
          }
        };

        var createViolation = function (validatorName) {
          var typeName = valdrTypeController.getType(),
            fieldName = scope.formFieldName;

          return {
            type: typeName,
            field: fieldName,
            validator: validatorName,
            message: valdrMessage.getMessage(typeName, fieldName, validatorName)
          };
        };

        var addViolationsToScope = function () {
          scope.violations = [];

          angular.forEach(scope.formField.valdrViolations, function (violation) {
            scope.violations.push(violation);
          });

          if (valdrMessage.angularMessagesEnabled) {
            angular.forEach(scope.formField.$error, function (isValid, validatorName) {
              if (!valdrUtil.startsWith(validatorName, 'valdr')) {
                scope.violations.push(createViolation(validatorName));
              }
            });
          }

          scope.violation = scope.violations[0];
          updateTranslations();
        };
        var removeViolationsFromScope = function () {
          scope.violations = undefined;
          scope.violation = undefined;
        };

        var watchFormFieldErrors = function () {
          scope.formField = formController[scope.formFieldName];
          if (scope.formField) {
            return {
              valdr: scope.formField.valdrViolations,
              error: scope.formField.$error
            };
          }
        };

        scope.$watch(watchFormFieldErrors, function () {
          if (scope.formField && scope.formField.$invalid) {
            addViolationsToScope();
          } else {
            removeViolationsFromScope();
          }
        }, true);

        $rootScope.$on('$translateChangeSuccess', function () {
          updateTranslations();
        });
      }
    };
  }]);

})(window, document);


text:
.oo-ui-icon-indent {
  background-image: url('themes/apex/images/icons/indent-rtl.png');
  background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/apex/images/icons/indent-rtl.svg');
}
.oo-ui-icon-listBullet {
  background-image: url('themes/apex/images/icons/listBullet-rtl.png');
  background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/apex/images/icons/listBullet-rtl.svg');
}
.oo-ui-icon-listNumbered {
  background-image: url('themes/apex/images/icons/listNumbered-rtl.png');
  background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/apex/images/icons/listNumbered-rtl.svg');
}
.oo-ui-icon-outdent {
  background-image: url('themes/apex/images/icons/outdent-rtl.png');
  background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/apex/images/icons/outdent-rtl.svg');
}


text:
@interface KFImageMessageCell : KFBaseMessageCell

@property (nullable, nonatomic, weak) UIImageView *messageImageView;

@end


text: Um projeto desafio proposto pelo laboratório de Fotônica


text:
module.exports = {
    application(){
        console.log('application');
    },
};


text:
package com.google.security.zynamics.binnavi.API.helpers;

import com.google.security.zynamics.binnavi.Settings.CGlobalSettings;

// ! Used to configure global settings.
/**
 * Provides a few functions to configure global BinNavi settings.
 */
public final class Settings {
  /**
   * You are not supposed to instantiate this class.
   */
  private Settings() {
  }

  // ! Toggle warning dialogs.
  /**
   * Disables or enables warning dialogs. Disabling dialogs is useful for running scripts or plugins
   * that handle errors themselves.
   *
   * @param enabled True, to enable dialogs. False, to disable them.
   */
  public static void setShowDialogs(final boolean enabled) {
    CGlobalSettings.SHOW_DIALOGS = enabled;
  }
}


text:
@interface ViewController ()

@property AVCaptureSession *captureSession;
@property AVCaptureVideoPreviewLayer *previewLayer;
@property IBOutlet UIView *cameraView;

@property NSTimer *calibrationTimer;

@property (nonatomic, retain) PieceView *movingPieceView; //current dropping piece
@property (nonatomic, retain) StackView *pieceStackView; //60*15 grid view for pieces already dropped

@end

@implementation ViewController
@synthesize movingPieceView;

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupCameraView];
    [self setupStackView];

    self.calibrationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(finishedCalibrating) userInfo:nil repeats:NO];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.view addSubview:self.tutorialView];
}

- (void)setupCameraView
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        self.captureSession = [[AVCaptureSession alloc] init];
        [self.captureSession setSessionPreset:AVCaptureSessionPresetPhoto];

        AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
        [self.captureSession addInput:input];
        [self.captureSession setSessionPreset:@"AVCaptureSessionPresetPhoto"];
        [self.captureSession startRunning];

        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
        self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        self.previewLayer.frame = self.view.frame;

        [self.cameraView.layer addSublayer:self.previewLayer];
    }
}

- (void)setupStackView
{
    self.pieceStackView  = [[StackView alloc] initWithFrame:CGRectMake(0, 0, kGridSize * kNUMBER_OF_COLUMN, kGridSize * kNUMBER_OF_ROW)];
    [self.view addSubview:self.pieceStackView];
    [self.view bringSubviewToFront:self.startButton];
    [self.view bringSubviewToFront:self.stopButton];
    [self.view bringSubviewToFront:self.tutorialButton];
    [self.stopButton setHidden:YES];
    [self.view bringSubviewToFront:self.leftButton];
    [self.view bringSubviewToFront:self.rightButton];
    [self.view bringSubviewToFront:self.calibratingView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)startGameClickeed:(id)sender{
    [self.tutorialView setHidden:YES];
    if ([[GameController shareManager] gameStatus] == GameRunning) { //pause game
        [[GameController shareManager] pauseGame];
        [self.startButton setImage:[UIImage imageNamed:@"gtk_media_play_ltr.png"] forState:UIControlStateNormal];
    }
    else if([[GameController shareManager] gameStatus] == GameStopped) { //start game
        [[GameController shareManager] setDelegate:self];
        [[GameController shareManager] startGame];
        [self.startButton setImage:[UIImage imageNamed:@"gtk_media_pause.png"] forState:UIControlStateNormal];
        movingPieceView = [[GameController shareManager] generatePiece];
        [self.view addSubview:movingPieceView];
    }
    else if([[GameController shareManager] gameStatus] == GamePaused) { //resume game
        [self.startButton setImage:[UIImage imageNamed:@"gtk_media_pause.png"] forState:UIControlStateNormal];
        [[GameController shareManager] resumeGame];
    }
    [self.stopButton setHidden:NO];

}

- (IBAction)stopGame:(id)sender{
    [self.stopButton setHidden:YES];
    [self.startButton setImage:[UIImage imageNamed:@"gtk_media_play_ltr.png"] forState:UIControlStateNormal];

    [self removeCurrentPiece];

    [[GameController shareManager] gameOver];
}

- (IBAction)showTutorial:(id)sender{
    if (self.tutorialView.isHidden) {
        [[GameController shareManager] gameOver];
        [self.tutorialView setHidden:NO];
    }
    else{
        [self.tutorialView setHidden:YES];
    }
}

- (void)updateStackView{
    if ([[GameController shareManager] gameStatus] == GameStopped) {
        movingPieceView = nil;
    }
    [self.pieceStackView setNeedsDisplay];
}

- (void)dropNewPiece{
    movingPieceView = [[GameController shareManager] generatePiece];
    [self.view addSubview:movingPieceView];
}

- (void)removeCurrentPiece{
    [movingPieceView removeFromSuperview];
    movingPieceView = nil;
}

- (IBAction)leftClicked:(id)sender{
    [[GameController shareManager] movePieceLeft];
}

- (IBAction)rightClicked:(id)sender{
    [[GameController shareManager] movePieceRight];
}

- (IBAction)respondToScreenTap:(UITapGestureRecognizer *)recognizer
{
    CGPoint location = [recognizer locationInView:self.view];
    if (location.x < (self.view.frame.size.width/2)) {
        [self leftClicked:nil];
    }
    else {
        [self rightClicked:nil];
    }

}

- (IBAction)respondToSwipe:(UITapGestureRecognizer *)recognizer
{
    if ([[GameController shareManager] gameStatus]) {
        [[GameController shareManager] dropPiece];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view != self.pieceStackView) {
        return NO;
    }

    return YES;
}

- (void)refreshStackView
{
    [self.pieceStackView setNeedsDisplay];
}

- (void)finishedCalibrating
{
    [self.calibratingView removeFromSuperview];
}

- (void)updateScore:(int)newScore{
    self.scoreLabel.text = [NSString stringWithFormat:@"%d", newScore];
}

- (void)updateLevel:(int)newLevel{
    self.levelLabel.text = [NSString stringWithFormat:@"%d", newLevel];

    self.gameStatusLabel.text = @"Level Up!!";
    self.gameStatusLabel.alpha = 0.0;
    [self.view bringSubviewToFront:self.gameStatusLabel];
    [UIView animateWithDuration:1.0 animations:^{
        self.gameStatusLabel.hidden = NO;
        self.gameStatusLabel.alpha = 1.0;
    } completion:^(BOOL finished){
        self.gameStatusLabel.alpha = 0.0;
        self.gameStatusLabel.hidden = YES;
    }];
}

- (void)gameOver
{
    [self.startButton setImage:[UIImage imageNamed:@"gtk_media_play_ltr.png"] forState:UIControlStateNormal];
    self.gameStatusLabel.text = @"Game Over!";
    self.gameStatusLabel.alpha = 0.0;
    [self.view bringSubviewToFront:self.gameStatusLabel];
    [UIView animateWithDuration:1.0 animations:^{
        self.gameStatusLabel.hidden = NO;
        self.gameStatusLabel.alpha = 1.0;
    } completion:^(BOOL finished){
        self.gameStatusLabel.alpha = 0.0;
        self.gameStatusLabel.hidden = YES;
    }];
}

@end


text: Base on https://realpython.com/blog/python/the-ultimate-flask-front-end/


text:
package com.baeldung.osgi.sample.service.definition;

public interface Greeter {

    public String sayHiTo(String name);

}


text:
package org.opencb.opencga.app.cli.main.io;

import org.codehaus.jackson.map.ObjectMapper;
import org.opencb.commons.datastore.core.QueryResponse;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;

/**
 * Created by pfurio on 28/07/16.
 */
public class JsonWriter implements IWriter {

    @Override
    public void print(QueryResponse queryResponse, boolean beauty) {
        if (!checkErrors(queryResponse)) {
            generalPrint(queryResponse, beauty);
        }
    }

    @Override
    public void writeToFile(QueryResponse queryResponse, Path filePath, boolean beauty) {
        if (checkErrors(queryResponse)) {
            return;
        }

        // Redirect the output
        try {
            FileOutputStream fos = new FileOutputStream(filePath.toFile());
            PrintStream ps = new PrintStream(fos);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        generalPrint(queryResponse, beauty);
    }

    /**
     * Print errors or warnings and return true if any error was found.
     *
     * @param queryResponse queryResponse object
     * @return true if the query gave an error.
     */
    private boolean checkErrors(QueryResponse queryResponse) {
        if (!queryResponse.getError().isEmpty()) {
            System.out.println(queryResponse.getError());
            return true;
        }

        // Print warnings
        if (!queryResponse.getWarning().isEmpty()) {
            System.out.println(queryResponse.getWarning());
        }

        return false;
    }

    private void generalPrint(QueryResponse queryResponse, boolean beauty) {
        if (beauty) {
            try {
                System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().
                        writeValueAsString(queryResponse.getResponse()));
            } catch (IOException e) {
                System.out.println("Error parsing the queryResponse to print as a beautiful JSON");
            }
        } else {
            System.out.println(queryResponse.getResponse());
        }
    }
}


text:
struct event_base *EventManager::base;
struct event *EventManager::end_game_event;

void EventManager::init() {
  base = event_base_new();
}

void EventManager::trigger_end_game() {
  struct timeval tv = {0,0};
  event_add(end_game_event, &tv);
}


text:
              Previous
             Next

                {{lesson?.description }}

Duration: {{ lesson?.duration }}

{{ lesson?.longDescription }}

                  Edit Lesson
                  Delete


text:
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Sorting.SelectionSortImpl;
using Sorting.SortAlgorithm;

namespace Demo.SelectionSortConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var service = new ServiceCollection();

            var serviceProvider = service.AddSingleton<ISortAlgorithm, SelectionSort>().BuildServiceProvider();
            ISortAlgorithm algorithm = serviceProvider.GetService<ISortAlgorithm>();

            IList<int> array = new[] { 9, 4, 6, 7, 5, 8, 3, 1, 2 };

            Console.WriteLine("Sequence of numbers before:");
            array.Print();

            Console.WriteLine("Sorting --> ");
            algorithm.Sort(array).Wait();

            Console.WriteLine("Sequence of numbers after:");
            array.Print();

            Console.ReadLine();
        }
    }
}


text:
<?php

namespace Fxp\Bundle\SecurityBundle\DependencyInjection;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension as BaseSecurityExtension;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Enhances the access_control section of the SecurityBundle.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class SecurityExtension extends Extension
{
    /**
     * @var BaseSecurityExtension
     */
    private $extension;

    /**
     * Constructor.
     *
     * @param BaseSecurityExtension $extension The Symfony Security Extension
     */
    public function __construct(BaseSecurityExtension $extension)
    {
        $this->extension = $extension;
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias(): string
    {
        return $this->extension->getAlias();
    }

    /**
     * {@inheritdoc}
     */
    public function getNamespace(): string
    {
        return $this->extension->getNamespace();
    }

    /**
     * {@inheritdoc}
     *
     * @return false|string
     */
    public function getXsdValidationBasePath()
    {
        return $this->extension->getXsdValidationBasePath();
    }

    /**
     * Get the configuration.
     *
     * @param array            $config    The config
     * @param ContainerBuilder $container The container
     *
     * @return ConfigurationInterface
     */
    public function getConfiguration(array $config, ContainerBuilder $container): ConfigurationInterface
    {
        return $this->extension->getConfiguration($config, $container);
    }

    /**
     * Add the security factory.
     *
     * @param SecurityFactoryInterface $factory The security factory
     */
    public function addSecurityListenerFactory(SecurityFactoryInterface $factory): void
    {
        $this->extension->addSecurityListenerFactory($factory);
    }

    /**
     * Add the user provider factory.
     *
     * @param UserProviderFactoryInterface $factory The user provider factory
     */
    public function addUserProviderFactory(UserProviderFactoryInterface $factory): void
    {
        $this->extension->addUserProviderFactory($factory);
    }

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        $parentConfigs = [];

        foreach ($configs as $config) {
            if (isset($config['rule'])) {
                unset($config['rule']);
            }

            if (isset($config['access_control'])) {
                unset($config['access_control']);
            }

            $parentConfigs[] = $config;
        }

        $this->extension->load($parentConfigs, $container);
        $this->createAuthorization($configs, $container);
    }

    /**
     * Create the authorization.
     *
     * @param array            $configs   The configs
     * @param ContainerBuilder $container The container
     */
    private function createAuthorization(array $configs, ContainerBuilder $container): void
    {
        $config = $this->processConfiguration(new AccessControlConfiguration(), $configs);

        if (!$config['access_control']) {
            return;
        }

        $container->setParameter('fxp_security.access_control', $config['access_control']);
    }
}


text:
package com.google.cloud.pubsub.sql.providers;

import com.google.auto.service.AutoService;
import com.google.cloud.pubsub.sql.MakePtransform;
import com.google.cloud.pubsub.sql.Rows;
import org.apache.beam.sdk.io.gcp.pubsublite.Uuid;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TypeDescriptor;

@AutoService({StandardSourceProvider.class, StandardSinkProvider.class})
public class KafkaProvider implements StandardSourceProvider, StandardSinkProvider {

  private static final String HEADERS_FIELD = "headers";

  private static final Schema SCHEMA =
      Schema.builder()
          .addByteArrayField(Rows.PAYLOAD_FIELD)
          .addField(HEADERS_FIELD, Rows.ATTRIBUTES_FIELD_TYPE)
          .addField(Rows.EVENT_TIMESTAMP_FIELD, FieldType.DATETIME.withNullable(true))
          .addField(Rows.MESSAGE_KEY_FIELD, FieldType.BYTES)
          .build();

  private static Row toKafkaRow(Row standardRow) {
    // Beam does not support null keys (https://issues.apache.org/jira/browse/BEAM-12008)
    // So generate a random uuid if the key is empty and convert it to a string to get random
    // routing for unkeyed messages (all messages with empty keys route to the same partition).
    byte[] key = standardRow.getBytes(Rows.MESSAGE_KEY_FIELD);
    if (key.length == 0) {
      key = Uuid.random().value().toByteArray();
    }
    return Row.withSchema(SCHEMA)
        .withFieldValue(Rows.PAYLOAD_FIELD, standardRow.getBytes(Rows.PAYLOAD_FIELD))
        .withFieldValue(Rows.MESSAGE_KEY_FIELD, key)
        .withFieldValue(HEADERS_FIELD, standardRow.getBaseValue(Rows.ATTRIBUTES_FIELD))
        .withFieldValue(Rows.EVENT_TIMESTAMP_FIELD,
            standardRow.getDateTime(Rows.EVENT_TIMESTAMP_FIELD))
        .build();
  }

  @Override
  public StandardSink getSink() {
    // Beam does not support null keys (https://issues.apache.org/jira/browse/BEAM-12008)
    // So generate a random float and convert it to a string to get random routing for unkeyed
    // messages (all messages with empty keys route to the same partition).
    //
    // Beam does not support RAND() and cannot generate a random key using SQL.
    return new StandardSink() {
      @Override
      public Schema nativeSchema() {
        return SCHEMA;
      }

      @Override
      public PTransform<PCollection<Row>, PCollection<Row>> transform() {
        return MakePtransform.from(rows -> rows
            .apply(MapElements.into(TypeDescriptor.of(Row.class)).via(KafkaProvider::toKafkaRow))
            .setRowSchema(SCHEMA), "Kafka Sink Transform");
      }
    };
  }

  @Override
  public StandardSource getSource() {
    return new StandardSqlSource() {
      @Override
      public Schema nativeSchema() {
        return SCHEMA;
      }

      @Override
      public String query() {
        return "SELECT event_timestamp, payload, headers AS attributes, message_key FROM PCOLLECTION";
      }
    };
  }

  @Override
  public String identifier() {
    return "kafka";
  }
}


text:
EventManager = {}
EventManager.__index = EventManager

function EventManager.new(name, i)
  local newEventManager = {}
  setmetatable(newEventManager, EventManager)

  newEventManager.events = {}

  return newEventManager
end

function EventManager:addEvent(e)
  print('added ' .. e:toString())
  table.insert(self.events, e)
end

function EventManager:update(input, dt)

  if #self.events > 0 then

    local event = self.events[1]
    event:update(input, dt)

    if event:isDone() then
      print('done ' .. event:toString())
      event.onDone()
      table.remove(self.events, 1)
    end

  end

end

--function EventManager:clear()
--  self.events = {}
--end

return EventManager


text:
package com.wet.wired.jsr.recorder;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

@SuppressWarnings("serial")
public class JRecorder extends JFrame implements ScreenRecorderListener,
      ActionListener {

   private ScreenRecorder recorder;
   private File temp;

   private JButton control;
   private JLabel text;

   private boolean shuttingDown = false;
   private int frameCount = 0;

   public JRecorder() {

      this.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            shutdown();
         }
      });

      control = new JButton("Start Recording");
      control.setActionCommand("start");
      control.addActionListener(this);
      this.getContentPane().add(control, BorderLayout.WEST);

      text = new JLabel("Ready to record");
      this.getContentPane().add(text, BorderLayout.SOUTH);

      this.pack();
      this.setVisible(true);
   }

   public void startRecording(String fileName) {

      setState(Frame.ICONIFIED);
      try {
         Thread.sleep(500);
      } catch (InterruptedException e1) {
      }

      if (recorder != null) {
         return;
      }

      try {
         FileOutputStream oStream = new FileOutputStream(fileName);
         temp = new File(fileName);
         recorder = new DesktopScreenRecorder(oStream, this);
         recorder.startRecording();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void actionPerformed(ActionEvent ev) {
      if (ev.getActionCommand().equals("start") && recorder == null) {
         try {
            temp = File.createTempFile("temp", "rec");

            startRecording(temp.getAbsolutePath());
            control.setActionCommand("stop");
            control.setText("Stop Recording");
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else if (ev.getActionCommand().equals("stop") && recorder != null) {
         text.setText("Stopping");
         recorder.stopRecording();
      }
   }

   public void frameRecorded(boolean fullFrame) {
      frameCount++;
      if (text != null) {
         text.setText("Frame: " + frameCount);
      }
   }

   public void recordingStopped() {

      if (!shuttingDown) {

         UIManager.put("FileChooser.readOnly", true);
         JFileChooser fileChooser = new JFileChooser();
         FileExtensionFilter filter = new FileExtensionFilter();

         filter = new FileExtensionFilter();
         filter.addExtension("cap");
         filter.setDescription("Screen Capture File");

         fileChooser.setFileFilter(filter);
         fileChooser.showSaveDialog(this);

         File target = fileChooser.getSelectedFile();

         if (target != null) {

            if (!target.getName().endsWith(".cap"))
               target = new File(target + ".cap");

            FileHelper.copy(temp, target);
         }

         FileHelper.delete(temp);
         recorder = null;
         frameCount = 0;

         control.setActionCommand("start");
         control.setText("Start Recording");

         text.setText("Ready to record");
      } else
         FileHelper.delete(temp);
   }

   public static void main(String[] args) {

      if (args.length >= 1)
         if (args[0].equals("-white_cursor"))
            DesktopScreenRecorder.useWhiteCursor = true;
         else {
            System.out
                  .println("Usage: java -jar screen_recorder.jar [OPTION]...");
            System.out.println("Start the screen recorder.");
            System.out.println("Options:   ");
            System.out.println("   -white_cursor   record with white cursor");
            System.exit(0);
         }
      @SuppressWarnings("unused")
      JRecorder jRecorder = new JRecorder();
   }

   public void shutdown() {

      shuttingDown = true;

      if (recorder != null)
         recorder.stopRecording();

      dispose();
   }
}


text:
namespace SharpCache.Interfaces
{
    public interface ICache
    {
        string Name { get; }

        CacheValue this[CacheKey key] { get; set; }

        bool Exists(CacheKey key);

        void Clear();

        void Adjust(CacheConfiguration configuration);

        /// <summary>
        /// For debug usage.
        /// </summary>
        string Dump();
    }
}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Bull. Soc. Roy. Bot. Belgique 26:373. 1887

#### Original name
null

### Remarks
null


text:
package com.planet_ink.coffee_mud.core.collections;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Vector;

public class MultiIterator<K> implements Iterator<K>
{
	private final LinkedList<Iterator<K>> iters=new LinkedList<Iterator<K>>();
	private volatile Iterator<K> iter=null;

	public MultiIterator(Iterator<K>[] esets)
	{
		if((esets==null)||(esets.length==0))
			return;
		for(final Iterator<K> I : esets)
			iters.add(I);
	}

	public MultiIterator(Collection<Iterator<K>> esets)
	{
		if((esets==null)||(esets.size()==0))
			return;
		iters.addAll(esets);
		for(final Iterator<K> I : esets)
			iters.add(I);
	}

	public MultiIterator(Iterable<K>[] esets)
	{
		if((esets==null)||(esets.length==0))
			return;
		for(final Iterable<K> I : esets)
			iters.add(I.iterator());
	}

	public MultiIterator(Iterable<? extends Iterable<K>> esets)
	{
		if(esets==null)
			return;
		for(final Iterable<K> I : esets)
			iters.add(I.iterator());
	}

	public MultiIterator()
	{

	}

	public void add(Iterator<K> eset)
	{
		iters.add(eset);
	}

	@Override
	public boolean hasNext()
	{
		boolean hasNext = (iter != null) && iter.hasNext();
		while(!hasNext)
		{
			if(iters.size()==0)
			{
				iter=null;
				return false;
			}
			iter=iters.removeFirst();
			hasNext = (iter != null) && iter.hasNext();
		}
		return hasNext;
	}

	@Override
	public K next()
	{
		if(!hasNext())
			throw new NoSuchElementException();
		return iter.next();
	}

	@Override
	public void remove()
	{
		if(iter != null)
			iter.remove();
	}
}


text:
package com.google.errorprone.annotations;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Indicates that the return value of the annotated method must be used. An error is triggered when
 * one of these methods is called but the result is not used.
 *
 * <p>{@code @CheckReturnValue} may be applied to a class or package to indicate that all methods in
 * that class (including indirectly; that is, methods of inner classes within the annotated class)
 * or package must have their return values used. For convenience, we provide an annotation, {@link
 * CanIgnoreReturnValue}, to exempt specific methods or classes from this behavior.
 */
@Documented
@Target({METHOD, CONSTRUCTOR, TYPE, PACKAGE})
@Retention(RUNTIME)
public @interface CheckReturnValue {}


text:
class SubmissionFavoritesController < FavoritesController

  private

    def get_favable
      @favable = Submission.find(params[:id])
    end

    def get_favorite
      @favorite = current_profile.favorites.submissions.find_by_favable_id(@favable.id)
    end
end


text:
package gov.nih.nci.caadapter.ui.common.tree;

import gov.nih.nci.caadapter.common.Log;
import gov.nih.nci.caadapter.ui.common.TransferableNode;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;

/**
 * This class defines the handling methods to support drop action.
 *
 * @author OWNER: Scott Jiang
 * @author LAST UPDATE $Author: wangeug $
 * @version Since caAdapter v1.2
 *          revision    $Revision: 1.3 $
 *          date        $Date: 2008-10-09 18:17:35 $
 */
public class CSVTreeDropTransferHandler extends TreeDefaultDropTransferHandler
{
	/**
	 * Logging constant used to identify source of log entry, that could be later used to create logging mechanism
	 * to uniquely identify the logged class.
	 */
	private static final String LOGID = "$RCSfile: CSVTreeDropTransferHandler.java,v $";

	/**
	 * String that identifies the class version and solves the serial version UID problem.
	 * This String is for informational purposes only and MUST not be made final.
	 *
	 * @see JBuilder vice javac serial version UID
	 */
	public static String RCSID = "$Header: /share/content/gforge/caadapter/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/common/tree/CSVTreeDropTransferHandler.java,v 1.3 2008-10-09 18:17:35 wangeug Exp $";

	public CSVTreeDropTransferHandler(JTree tree, int action)
	{
		super(tree, action);
	}

	/**
	 * Called by the DropTargetAdapter in dragEnter, dragOver and dragActionChanged
	 * override so as to let the tree expand along selection.
	 */
	public void dragUnderFeedback(boolean ok, DropTargetDragEvent e)
	{
        super.dragUnderFeedback(ok, e);
		Point p = e.getLocation();
		TreePath path = this.getTree().getPathForLocation(p.x, p.y);
		if (path != null)
		{
			this.getTree().setSelectionPath(path);
//	        if(this.getTree().isExpanded(path) == false)
//			{
//		    	this.getTree().expandPath(path);
//			}
		}
	}

	/**
	 * Called by the DropTargetAdapter in dragEnter, dragOver and dragActionChanged
	 * descendant class shall override this function, since current implementation if the node is a leaf, the drop is NOT OK; otherwise, it is OK;
	 *
	 * @return if drop is OK.
	 */
	public boolean isDropOk(DropTargetDragEvent e)
	{
		boolean result = super.isDropOk(e);
		if(!result)
		{//not allowed by super, simply return
			return result;
		}
		TransferableNode transferableNode = obtainTransferableNode(e);
		Point p = e.getLocation();
		TreePath path = this.getTree().getPathForLocation(p.x, p.y);
		if (path == null) return false;
		TreeNode node = (TreeNode) path.getLastPathComponent();
		TreeModel treeModel = this.getTree().getModel();

		if(treeModel instanceof CSVMetadataTreeModel)
		{
			CSVMetadataTreeModel localTreeModel = (CSVMetadataTreeModel) treeModel;
			java.util.List transferredDataList = transferableNode.getSelectionList();
	//		boolean result = false;
			int size = transferredDataList.size();
			for (int i = 0; i < size; i++)
			{
				Object transferData = transferredDataList.get(i);
				/**
				 * if node is not null and it is not the top root, and it is a leaf and
				 * the transfer data is of type DefaultSourceTreeNode
				 */
				if ((node instanceof DefaultMutableTreeNode) && (transferData instanceof DefaultMutableTreeNode))
				{
					result = localTreeModel.isChildAcceptableToParent(
							(DefaultMutableTreeNode) transferData, (DefaultMutableTreeNode) node, e.getDropAction() == DnDConstants.ACTION_COPY);
				}
				else
				{
					result = false;
					break;
				}
			}
		}
		return result;
	}

	/**
	 * Called by the DropTargetAdapter in drop
	 * return true if add action succeeded
	 * otherwise return false
	 */
	public boolean setDropData(Object transferredData, DropTargetDropEvent e, DataFlavor chosen)
	{
		boolean isSuccess = false;
		Point p = e.getLocation();
		TreePath path = this.getTree().getPathForLocation(p.x, p.y);
		if (path == null)
		{
			Log.logInfo(this, this.getClass() + " path is null. cannot find the exact path. Going to find closest path.");
			path = this.getTree().getClosestPathForLocation(p.x, p.y);
			if (path == null)
			{
				Log.logInfo(this, this.getClass() + " path is null. Even cannot find the closest path. setDropData() will reject drop.");
				return false;
			}
		}

		DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) path.getLastPathComponent();
		try
		{

			TransferableNode dragSourceObjectSelection = (TransferableNode) transferredData;

			java.util.List dragSourceObjectList = dragSourceObjectSelection.getSelectionList();
			if (dragSourceObjectList == null || dragSourceObjectList.size() < 1)
			{
				return false;
			}
			TreeModel tempModel = mTree.getModel();
			if (!(tempModel instanceof CSVMetadataTreeModel))
			{
				System.err.println("I am expecting CSVMetadataTreeModel, but I received '" + tempModel == null ? "null" : tempModel.getClass().getName() + "'");
				return false;
			}

			int dropAction = e.getDropAction();
			CSVMetadataTreeModel treeModel = (CSVMetadataTreeModel) tempModel;
			isSuccess = treeModel.addChildren(targetNode, dragSourceObjectList, dropAction==DnDConstants.ACTION_COPY);
		}
		catch (Exception exp)
		{
			Log.logInfo(this, "Exception Caught by '" + this.getClass().getName() + "': " + exp.getClass().getName() + ";" + exp.getMessage());
			Log.logException(this, exp);
			isSuccess = false;
		}
		finally
		{
			return isSuccess;
		}
	}

}
/**
 * HISTORY      : $Log: not supported by cvs2svn $
 * HISTORY      : Revision 1.2  2008/06/09 19:53:52  phadkes
 * HISTORY      : New license text replaced for all .java files.
 * HISTORY      :
 * HISTORY      : Revision 1.1  2007/04/03 16:17:14  wangeug
 * HISTORY      : initial loading
 * HISTORY      :
 * HISTORY      : Revision 1.14  2006/08/02 18:44:21  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.13  2006/01/03 19:16:52  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.12  2006/01/03 18:56:24  jiangsc
 * HISTORY      : License Update
 * HISTORY      :
 * HISTORY      : Revision 1.11  2005/12/29 23:06:15  jiangsc
 * HISTORY      : Changed to latest project name.
 * HISTORY      :
 * HISTORY      : Revision 1.10  2005/12/29 15:39:05  chene
 * HISTORY      : Optimize imports
 * HISTORY      :
 * HISTORY      : Revision 1.9  2005/12/14 21:37:18  jiangsc
 * HISTORY      : Updated license information
 * HISTORY      :
 * HISTORY      : Revision 1.8  2005/11/29 16:23:56  jiangsc
 * HISTORY      : Updated License
 * HISTORY      :
 * HISTORY      : Revision 1.7  2005/10/26 18:12:29  jiangsc
 * HISTORY      : replaced printStackTrace() to Log.logException
 * HISTORY      :
 * HISTORY      : Revision 1.6  2005/10/25 22:00:43  jiangsc
 * HISTORY      : Re-arranged system output strings within UI packages.
 * HISTORY      :
 * HISTORY      : Revision 1.5  2005/10/24 19:08:40  jiangsc
 * HISTORY      : Enhanced drag and drop
 * HISTORY      :
 * HISTORY      : Revision 1.4  2005/08/04 18:06:28  jiangsc
 * HISTORY      : Updated class description in comments
 * HISTORY      :
 * HISTORY      : Revision 1.3  2005/07/22 20:53:13  jiangsc
 * HISTORY      : Structure change and added License and history anchors.
 * HISTORY      :
 * HISTORY      : Revision 1.2  2005/06/29 21:21:40  jiangsc
 * HISTORY      : More functionality.
 * HISTORY      :
 * HISTORY      : Revision 1.1  2005/06/24 19:53:07  jiangsc
 * HISTORY      : Save Point
 * HISTORY      :
 * HISTORY      : Revision 1.1  2005/06/23 14:30:06  jiangsc
 * HISTORY      : Updated CSVPanel implementation to support basic drag and drop.
 * HISTORY      :
 */


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

namespace Tests\Legacy\AlgoWeb\PODataLaravel\Facets\Models;

use AlgoWeb\PODataLaravel\Models\MetadataTrait;
use Illuminate\Database\Connection as Connection;
use Illuminate\Database\Eloquent\Model as Model;

class TestMonomorphicManyTarget extends Model
{
    use MetadataTrait {
        metadata as traitmetadata; // Need to alias the trait version of the method so we can call it and
        // not bury ourselves under a stack overflow and segfault
    }
    protected $metaArray;
    protected $connect;
    protected $grammar;
    protected $processor;

    public function __construct(array $meta = null, Connection $connect = null)
    {
        if (isset($meta)) {
            $this->metaArray = $meta;
        }
        if (isset($connect)) {
            $this->connect = $connect;
        } else {
            $this->processor = \Mockery::mock(\Illuminate\Database\Query\Processors\Processor::class)->makePartial();
            $this->grammar   = \Mockery::mock(\Illuminate\Database\Query\Grammars\Grammar::class)->makePartial();
            $connect         = \Mockery::mock(Connection::class)->makePartial();
            $connect->shouldReceive('getQueryGrammar')->andReturn($this->grammar);
            $connect->shouldReceive('getPostProcessor')->andReturn($this->processor);
            $this->connect = $connect;
        }
        parent::__construct();
    }

    public function getConnectionName()
    {
        return 'testconnection';
    }

    public function getConnection()
    {
        return $this->connect;
    }

    public function manyTarget()
    {
        return $this->belongsToMany(TestMonomorphicManySource::class, 'target_source', 'many_id', 'many_source');
    }

    public function metadata()
    {
        if (isset($this->metaArray)) {
            return $this->metaArray;
        }
        return $this->traitmetadata();
    }
}


text:
var webdriver = require('selenium-webdriver');
var chromedriver = require('chromedriver');
var path = require('path');
var _ = require('lodash');

function WebDriverEngine(config, logger) {
  this.config = config;
  this.logger = logger;
}

/*
 * Initialize the page
 */
WebDriverEngine.prototype.init = function(appUrl, initCallback, errorCallback, beforeInitCallback) {
  var _this = this;

  this.initializationCallback = initCallback;
  this.hasInitializationCallback = true;
  this.contentReadyTimer = null;

  process.env['PATH'] = path.dirname(chromedriver.path) + ':' + process.env['PATH'];

  this.driver = new webdriver.Builder().withCapabilities(
    webdriver.Capabilities.chrome()
    //webdriver.Capabilities.firefox()
  ).build();

  beforeInitCallback(function() {
    _this.driver.get(appUrl);

    // TODO: Bind console messages, set viewport size, etc
    _this.driver.executeScript(
      "window.isPrerender = true;" +

      "window.XContentReadyFlag = false;" +
      "document.addEventListener('XContentReady', function() {" +
        "window.XContentReadyFlag = true;" +
      "}, false);" +

      "window.jsErrors = [];" +
      "window.onerror = function(errorMessage) {" +
        "window.jsErrors.push(errorMessage);" +
      "};"
    );

    // Hack: the above event listener script that sets window.XContentReadyFlag is sometimes
    //       executed after the page has already loaded
    var _maxTries = 5;
    var _checkInterval = 100;

    _this.readyTimer = setInterval(function() {
      return _this.driver.executeScript(
        "return {" +
          "ready: window.XContentReadyFlag," +
          "errors: window.jsErrors" +
        "};"
      ).then(function(result) {
        if (result.errors.length) {
          errorCallback("Phantom encountered an error: " + result.errors.join());
        } else if (result.ready || (_this.hasInitializationCallback && _maxTries <= 0)) {
          _this.driver.executeScript("window.XContentReadyFlag = false;");
          _.bind(_this.onPageReady, _this)();
        } else if (_this.hasInitializationCallback) {
          _maxTries--;
        }
      });
    }, _checkInterval);
  });
};

/*
 * Load a route
 */
WebDriverEngine.prototype.loadRoute = function(page, callback) {
  var _this = this;

  this.currentPage = page;
  this.pageCallback = callback;
  this.hasPageCallback = true;

  clearTimeout(this.contentReadyTimer);

  this.driver.executeScript(
    "window.XContentReadyFlag = false;" +
    "window.prerenderTransitionEvent.url = '" + page.url + "';" +
    "window.document.dispatchEvent(window.prerenderTransitionEvent);"
  );
};

/*
 * Callback handler for when a page finishes rendering
 */
WebDriverEngine.prototype.onPageReady = function() {
  var _this = this;

  if (this.hasInitializationCallback) {
    this.hasInitializationCallback = false;
    this.initializationCallback();
  } else {
    this.contentReadyTimer = setTimeout(function() {
      _this.driver.getPageSource().then(function(html) {
        if (_this.hasPageCallback) {
          _this.hasPageCallback = false;
          _this.currentPage.statusCode = 200;
          _this.currentPage.html = html;
          _this.pageCallback(_this.currentPage);
        }
      });
    }, this.config.contentReadyDelay);
  }
};

/*
 * Destroy the webdriver process
 */
WebDriverEngine.prototype.shutdown = function() {
  clearInterval(this.readyTimer);
  clearTimeout(this.contentReadyTimer);

  if (this.driver) {
    this.driver.quit();
  }
};

module.exports = WebDriverEngine;


text:
Imports EpdIt.DBUtilities

<TestClass()>
Public Class NullableDateTimeUtilitiesTests

    <TestMethod>
    Public Sub GetNullableDateTime_FromValidString1()
        Dim result As Date? = GetNullableDateTime("2016-06-07")
        Assert.AreEqual(New Date(2016, 6, 7), result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromValidString2()
        Dim result As Date? = GetNullableDateTime("June 7, 2016")
        Assert.AreEqual(New Date(2016, 6, 7), result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromValidString3()
        Dim result As Date? = GetNullableDateTime("2016-06-07 08:00:00")
        Assert.AreEqual(New Date(2016, 6, 7, 8, 0, 0), result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromValidString4()
        Dim result As Date? = GetNullableDateTime("2016-06-07 14:00:00")
        Assert.AreEqual(New Date(2016, 6, 7, 14, 0, 0), result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromValidString5()
        Dim result As Date? = GetNullableDateTime("2016-06-07 2:00 pm")
        Assert.AreEqual(New Date(2016, 6, 7, 14, 0, 0), result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromDBNull()
        Dim result As Date? = GetNullableDateTime(DBNull.Value)
        Assert.AreEqual(Nothing, result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromNull()
        Dim result As Date? = GetNullableDateTime(Nothing)
        Assert.AreEqual(Nothing, result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromInvalidString()
        Dim result As Date? = GetNullableDateTime("test")
        Assert.AreEqual(Nothing, result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromBool_True()
        Dim result As Date? = GetNullableDateTime(True)
        Assert.AreEqual(Nothing, result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromBool_False()
        Dim result As Date? = GetNullableDateTime(False)
        Assert.AreEqual(Nothing, result)
    End Sub

    <TestMethod>
    Public Sub GetNullableDateTime_FromInteger()
        Dim result As Date? = GetNullableDateTime(12)
        Assert.AreEqual(Nothing, result)
    End Sub

End Class


text:
<?php

namespace UghAuthentication\Factory\Controller;

use UghAuthentication\Controller\LoginController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class LoginControllerFactory implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $formElementManager = $serviceLocator->getServiceLocator()->get('FormElementManager');
        $loginForm = $formElementManager->get('UghAuthentication\Form\Login');

        $moduleOptions = $serviceLocator->getServiceLocator()->get('UghAuthentication\Options\ModuleOptions');

        $controller = new LoginController($loginForm);
        $controller->setLoginRedirectRoute($moduleOptions->getLoginRedirectRoute());

        return $controller;
    }
}


text:
package i2c

import (
	"testing"
	"time"

	"github.com/hybridgroup/gobot/gobottest"
)

// --------- HELPERS
func initTestMPU6050Driver() (driver *MPU6050Driver) {
	driver, _ = initTestMPU6050DriverWithStubbedAdaptor()
	return
}

func initTestMPU6050DriverWithStubbedAdaptor() (*MPU6050Driver, *i2cTestAdaptor) {
	adaptor := newI2cTestAdaptor("adaptor")
	return NewMPU6050Driver(adaptor, "bot"), adaptor
}

// --------- TESTS

func TestNewMPU6050Driver(t *testing.T) {
	// Does it return a pointer to an instance of MPU6050Driver?
	var bm interface{} = NewMPU6050Driver(newI2cTestAdaptor("adaptor"), "bot")
	_, ok := bm.(*MPU6050Driver)
	if !ok {
		t.Errorf("NewMPU6050Driver() should have returned a *MPU6050Driver")
	}
}

func TestMPU6050Driver(t *testing.T) {
	mpu := initTestMPU6050Driver()
	gobottest.Assert(t, mpu.Name(), "bot")
	gobottest.Assert(t, mpu.Connection().Name(), "adaptor")
	gobottest.Assert(t, mpu.interval, 10*time.Millisecond)

	mpu = NewMPU6050Driver(newI2cTestAdaptor("adaptor"), "bot", 100*time.Millisecond)
	gobottest.Assert(t, mpu.interval, 100*time.Millisecond)
}

// Methods
func TestMPU6050DriverStart(t *testing.T) {
	mpu := initTestMPU6050Driver()

	gobottest.Assert(t, len(mpu.Start()), 0)
}

func TestMPU6050DriverHalt(t *testing.T) {
	mpu := initTestMPU6050Driver()

	gobottest.Assert(t, len(mpu.Halt()), 0)
}


text:
module Sortable
  module Rails
    VERSION = "0.0.2"
  end
end


text:
from swgpy.object import *

def create(kernel):
	result = Creature()

	result.template = "object/mobile/shared_dressed_rebel_brigadier_general_bith_male.iff"
	result.attribute_template_id = 9
	result.stfName("npc_name","bith_base_male")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package net.jueb.util4j.jvm;

import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import sun.management.VMManagement;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class VmUtil {
    static RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    static VMManagement vmManagement;

    static {
        try {
            Field jvm = runtime.getClass().getDeclaredField("jvm");
            jvm.setAccessible(true);
            vmManagement = (VMManagement) jvm.get(runtime);

        } catch (Exception e) {

        }
    }

    public static int getVmPid() {
        if (vmManagement != null) {
            try {
                Method pidMethod = vmManagement.getClass().getDeclaredMethod("getProcessId");
                if (!pidMethod.isAccessible()) {
                    pidMethod.setAccessible(true);
                }
                int pid = (Integer) pidMethod.invoke(vmManagement);
                return pid;
            } catch (Exception e) {
            }
        }
        String pid = ManagementFactory.getRuntimeMXBean().getName();
        int indexOf = pid.indexOf('@');
        if (indexOf > 0) {
            pid = pid.substring(0, indexOf);
        }
        return Integer.valueOf(pid);
    }

    public static VirtualMachine getVirtualMachine() throws IOException, AttachNotSupportedException {
        return VirtualMachine.attach(getVmPid() + "");
    }
}


text:
export const BEGIN_AJAX_CALL = 'BEGIN_AJAX_CALL';
export const AJAX_CALL_ERROR = 'AJAX_CALL_ERROR';

export const LOAD_COURSES_SUCCESS = 'LOAD_COURSES_SUCCESS';
export const CREATE_USER = 'CREATE_COURSE_SUCCESS';
export const UPDATE_COURSE_SUCCESS = 'UPDATE_COURSE_SUCCESS';

export const LOAD_AUTHORS_SUCCESS = 'LOAD_AUTHORS_SUCCESS';