text:
//  Copyright (c) 2005, Regents of the University of California
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//    * Redistributions of source code must retain the above copyright notice,
//  this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright
//  notice, this list of conditions and the following disclaimer in the
//  documentation and/or other materials provided with the distribution.
//    * Neither the name of the University of California, San Diego (UCSD) nor
//  the names of its contributors may be used to endorse or promote products
//  derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
//  FILE
//  SRBContainer.java  -  edu.sdsc.grid.io.srb.SRBContainer
//
//  CLASS HIERARCHY
//  java.lang.Object
//      |
//      +-.GeneralFile
//              |
//              +-.RemoteFile
//                    |
//                    +-.SRBFile
//                          |
//                          +-.SRBContainer
//
//  PRINCIPAL AUTHOR
//  Lucas Gilbert, SDSC/UCSD
//
//
package edu.sdsc.grid.io.srb;

import edu.sdsc.grid.io.*;
import edu.sdsc.grid.io.local.*;

import java.io.IOException;
import java.util.Date;
import java.util.Vector;
import java.net.URI;

//import java.io.FilenameFilter;
//import java.io.FileFilter;
//import java.util.Iterator;

/**
 * An abstract representation of a container on the SRB. A container is a way to
 * put together a lot of small files into one larger file to improve
 * performance. This works very well with resources that include tapes (such as
 * HPSS). The whole container is retrieved from tape, cached on SRB disk, and
 * then multiple files can be quickly read and written on the container copy on
 * disk. The SRB handles the book-keeping for the container.
 *

 * SRBContainer subclasses SRBFile and have certain similarities with SRB
 * directories/collections, the logical groupings of files on the SRB.
 * Containers represent a physical grouping of files on a particular SRB
 * resource. Containers can be placed anywhere on the SRB the user has write
 * privileges.
 *

 *
 * @author Lucas Gilbert, San Diego Supercomputer Center
 * @since JARGON1.0
 * @see edu.sdsc.grid.io.srb.SRBFile
 */
public class SRBContainer extends SRBFile {
	// ----------------------------------------------------------------------
	// Constants
	// ----------------------------------------------------------------------
	/**
	 * The default maximum container size, in bytes. i.e. 209715200.
	 */
	final static int DEFAULT_CONTAINER_SIZE = 209715200;

	/**
	 * Synchronize all containers in a container family.
	 */
	// public static final String ALL_SYNC =
	// "synchronize all containers in family";

	/**
	 * Delete the cache copy once the copies have been synchronized.
	 */
	public static final String PURGE_SYNC = "synchronize then purge cache";

	/**
	 * Delete the cache copy once the copies have been synchronized.
	 */
	public static final String PRIMARY_SYNC = "synchronize primary copy";

	// ----------------------------------------------------------------------
	// Fields
	// ----------------------------------------------------------------------
	/**
	 * The maximum size, in bytes, this container can hold.
	 */
	long containerMaxSize = DEFAULT_CONTAINER_SIZE;

	// ----------------------------------------------------------------------
	// Constructors and Destructors
	// ----------------------------------------------------------------------
	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *
	 * @param fileSystem
	 *            The connection to the SRB
	 * @param filePath
	 *            The pathname string
	 */
	public SRBContainer(SRBFileSystem fileSystem, String filePath) {
		super(fileSystem, filePath);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *
	 * @param fileSystem
	 *            The connection to the SRB
	 * @param filePath
	 *            A pathname string
	 * @param containerMaxSize
	 *            The size of the container, in bytes
	 */
	public SRBContainer(SRBFileSystem fileSystem, String filePath,
			long containerMaxSize) {
		super(fileSystem, filePath);

		setContainerMaxSize(containerMaxSize);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *

	 * If parent is null then the new
	 * SRBContainer instance is created as if by invoking the
	 * single-argument SRBContainer constructor on the given
	 * child pathname string.
	 *

	 * Otherwise the parent abstract pathname is taken to denote a directory,
	 * and the child pathname string is taken to denote the container name. If
	 * the child pathname string is absolute then it is converted
	 * into a relative pathname in a SRB pathname. If parent is the empty string
	 * then the new SRBContainer instance is created by converting
	 * child into an abstract pathname and resolving the result
	 * against the SRB default container directory. Otherwise each pathname
	 * string is converted into an abstract pathname and the child
	 * abstract pathname is resolved against the parent.
	 *

	 *
	 * @param parent
	 *            The parent abstract pathname
	 * @param child
	 *            The child pathname string
	 */
	public SRBContainer(SRBFile parent, String child) {
		super(parent, child);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *

	 * If parent is null then the new
	 * SRBContainer instance is created as if by invoking the
	 * single-argument SRBContainer constructor on the given
	 * child pathname string.
	 *

	 * Otherwise the parent abstract pathname is taken to denote a directory,
	 * and the child pathname string is taken to denote the container name. If
	 * the child pathname string is absolute then it is converted
	 * into a relative pathname in a SRB pathname. If parent is the empty string
	 * then the new SRBContainer instance is created by converting
	 * child into an abstract pathname and resolving the result
	 * against the SRB default container directory. Otherwise each pathname
	 * string is converted into an abstract pathname and the child
	 * abstract pathname is resolved against the parent.
	 *

	 *
	 * @param parent
	 *            The parent abstract pathname
	 * @param child
	 *            The child pathname string
	 * @param containerMaxSize
	 *            The size of the container, in bytes
	 */
	public SRBContainer(SRBFile parent, String child, long containerMaxSize) {
		super(parent, child);

		setContainerMaxSize(containerMaxSize);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *

	 * If parent is null then the new
	 * SRBContainer instance is created as if by invoking the
	 * single-argument SRBContainer constructor on the given
	 * child pathname string.
	 *

	 * Otherwise the parent abstract pathname is taken to denote a directory,
	 * and the child pathname string is taken to denote the container name. If
	 * the child pathname string is absolute then it is converted
	 * into a relative pathname in a SRB pathname. If parent is the empty string
	 * then the new SRBContainer instance is created by converting
	 * child into an abstract pathname and resolving the result
	 * against the SRB default container directory. Otherwise each pathname
	 * string is converted into an abstract pathname and the child
	 * abstract pathname is resolved against the parent.
	 *

	 *
	 * @param fileSystem
	 *            The connection to the SRB
	 * @param parent
	 *            The parent pathname string
	 * @param child
	 *            The child pathname string
	 */
	public SRBContainer(SRBFileSystem fileSystem, String parent, String child) {
		super(fileSystem, parent, child);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * pathname string into an abstract pathname.
	 *

	 * If parent is null then the new
	 * SRBContainer instance is created as if by invoking the
	 * single-argument SRBContainer constructor on the given
	 * child pathname string.
	 *

	 * Otherwise the parent abstract pathname is taken to denote a directory,
	 * and the child pathname string is taken to denote the container name. If
	 * the child pathname string is absolute then it is converted
	 * into a relative pathname in a SRB pathname. If parent is the empty string
	 * then the new SRBContainer instance is created by converting
	 * child into an abstract pathname and resolving the result
	 * against the SRB default container directory. Otherwise each pathname
	 * string is converted into an abstract pathname and the child
	 * abstract pathname is resolved against the parent.
	 *

	 *
	 * @param fileSystem
	 *            The connection to the SRB
	 * @param parent
	 *            The parent pathname string
	 * @param child
	 *            The child pathname string
	 * @param containerMaxSize
	 *            The size of the container, in bytes
	 */
	public SRBContainer(SRBFileSystem fileSystem, String parent, String child,
			long containerMaxSize) {
		super(fileSystem, parent, child);

		setContainerMaxSize(containerMaxSize);
	}

	/**
	 * Creates a new SRBContainer instance by converting the given
	 * uri string into an abstract pathname.
	 *

	 *
	 * @param fileSystem
	 *            The connection to the SRB
	 * @param uri
	 *            The uri pathname string
	 * @param containerMaxSize
	 *            The size of the container, in bytes
	 * @throws IOException
	 *             If an IOException occurs.
	 */
	public SRBContainer(URI uri) throws IOException {
		super(uri);

		setContainerMaxSize(containerMaxSize);
	}

	/**
	 * Finalizes the object by explicitly letting go of each of its internally
	 * held values.
	 *

	 */
	/*
	 * protected void finalize( ) throws Throwable { super.finalize(); }
	 */

	// ----------------------------------------------------------------------
	// Setters and Getters
	// ----------------------------------------------------------------------
	/**
	 * Sets the container size of this SRBContainer object, in bytes. The max
	 * size of a container cannot be changed if the container already exists on
	 * the SRB.
	 *

	 * Currently, containers cannot have a max size over 2GB, though they will
	 * accept files larger than 2GB. If the container runs out of space it will
	 * be renamed to a new container plus some random digits and a new container
	 * will be created.

	 * eg. container foo will be renamed foo.1234 and a new foo container will
	 * be created.
	 *
	 * @throws IllegalArgumentException
	 *             If the containerMaxSize is less than zero.
	 */
	public void setContainerMaxSize(long containerMaxSize) {
		if (containerMaxSize < 0)
			throw new IllegalArgumentException();
		this.containerMaxSize = containerMaxSize;
	}

	/**
	 * @return the size of this SRBContainer, in bytes.
	 */
	public long getContainerMaxSize() {
		try {
			MetaDataRecordList[] rl = query(SRBMetaDataSet.CONTAINER_MAX_SIZE);
			if (rl != null) {
				return Long.parseLong(rl[0].getValue(
						SRBMetaDataSet.CONTAINER_MAX_SIZE).toString());
			}
		} catch (IOException e) {
			// container doesn't exist
		}

		return 0;
	}

	/**
	 * @return resource the physical resource where this SRBFile is stored.
	 *
	 * @throws IOException
	 *             If an IOException occurs.
	 */
	public String getResource() throws IOException {
		MetaDataRecordList[] rl = query(SRBMetaDataSet.RESOURCE_NAME);
		if (rl != null) {
			return rl[0].getValue(SRBMetaDataSet.RESOURCE_NAME).toString();
		}

		return null;
	}

	/**
	 * @return dataType The dataType string of this SRBFile.
	 *
	 * @throws IOException
	 *             If an IOException occurs.
	 */
	public String getDataType() throws IOException {
		MetaDataRecordList[] rl = query(SRBMetaDataSet.FILE_TYPE_NAME);
		if (rl != null) {
			return rl[0].getValue(SRBMetaDataSet.FILE_TYPE_NAME).toString();
		}

		return null;
	}

	// ----------------------------------------------------------------------
	// SRBContainer Methods
	// ----------------------------------------------------------------------
	/**
	 * Adds the named file to this container. Note, files already on the SRB
	 * cannot be added to a container. One reason being a name conflict will
	 * occur.
	 */
	public void include(GeneralFile file) throws IOException {
		if (!exists()) {
			createNewFile();
		}

		int fd = srbFileSystem.srbObjCreate(catalogType, file.getName()
				+ "&CONTAINER=" + getAbsolutePath(), dataType, resource, file
				.getParent(), "", file.length());

		byte inputBuffer[] = new byte[BUFFER_MAX_SIZE];
		long length = file.length();
		GeneralRandomAccessFile in = FileFactory.newRandomAccessFile(file, "r");
		if (length > BUFFER_MAX_SIZE) {
			do {
				in.read(inputBuffer);
				srbFileSystem.srbObjWrite(fd, inputBuffer, inputBuffer.length);
				length -= BUFFER_MAX_SIZE;
			} while (length > BUFFER_MAX_SIZE);
		}
		inputBuffer = new byte[(int) length];
		in.read(inputBuffer);
		srbFileSystem.srbObjWrite(fd, inputBuffer, inputBuffer.length);

		in.close();
		srbFileSystem.srbObjClose(fd);
	}

	// ----------------------------------------------------------------------
	// GeneralFile Methods
	// ----------------------------------------------------------------------
	public MetaDataRecordList[] query(MetaDataSelect[] selects)
			throws IOException {
		return query(selects, SRBFileSystem.DEFAULT_RECORDS_WANTED);
	}

	public MetaDataRecordList[] query(MetaDataSelect[] selects,
			int recordsWanted) throws IOException {
		MetaDataCondition iConditions[] = { MetaDataSet.newCondition(
				SRBMetaDataSet.CONTAINER_NAME, MetaDataCondition.EQUAL,
				getAbsolutePath()) };

		return srbFileSystem.query(iConditions, selects, recordsWanted);
	}

	public void copyTo(GeneralFile file, boolean forceOverwrite,
			boolean bulkCopy) throws IOException {
		String list[] = list();
		GeneralFile temp;

		if (!file.exists()) {
			file.mkdir();
		} else if (file.isFile()) {
			throw new IllegalArgumentException(
					"The destination cannot be a file.");
		}

		if (file instanceof SRBContainer) {
			for (int i = 0; i < list.length; i++) {
				((SRBContainer) file).include(new SRBFile(srbFileSystem,
						list[i]));
			}
		} else {
			for (int i = 0; i < list.length; i++) {
				temp = FileFactory.newFile(this, list[i]);
				temp.copyTo(FileFactory.newFile(file, temp.getName()));
			}
		}
	}

	public void copyFrom(GeneralFile file, boolean forceOverwrite,
			boolean bulkCopy) throws IOException {
		String list[] = file.list();

		if (!exists()) {
			createNewFile();
		}

		if (file.isFile()) {
			include(file);
		} else {
			for (int i = 0; i < list.length; i++) {
				include(FileFactory.newFile(file, list[i]));
			}
		}
	}

	// ----------------------------------------------------------------------
	// RemoteFile and SRBFile Methods
	// ----------------------------------------------------------------------
	/**
	 * @deprecated Superseded by copyFrom( GeneralFile ). This single new method
	 *             replaces all the other older copyFrom...() methods. It
	 *             functions in the same manner as those old methods, but can
	 *             except any GeneralFile. It also fixes some bugs in those
	 *             methods.
	 */
	public void copyFromLocal(LocalFile localFile) throws IOException {
		if (localFile.isDirectory()) {
			copyFrom(localFile, false, false);
		}

		throw new UnsupportedOperationException(
				"Cannot use copyFromLocal for containers");
	}

	/**
	 * @deprecated Superseded by copyFrom( GeneralFile ). This single new method
	 *             replaces all the other older copyFrom...() methods. It
	 *             functions in the same manner as those old methods, but can
	 *             except any GeneralFile. It also fixes some bugs in those
	 *             methods.
	 */
	public void copyFromLocal(String localFilePath) throws IOException {
		LocalFile localFile = new LocalFile(localFilePath);
		if (localFile.isDirectory()) {
			copyFrom(localFile, false, false);
		}

		throw new UnsupportedOperationException(
				"Cannot use copyFromLocal for containers");
	}

	/**
	 * Copies the SRB container to the local file system, as if it were a
	 * directory. The local file must be a directory. If the local file does not
	 * exist, a new one will be created.
	 *

	 *
	 * @deprecated Superseded by copyFrom( GeneralFile ). This single new method
	 *             replaces all the other older copyFrom...() methods. It
	 *             functions in the same manner as those old methods, but can
	 *             except any GeneralFile. It also fixes some bugs in those
	 *             methods.
	 * @param localFile
	 *            The file to receive the data
	 * @throws NullPointerException
	 *             If localFile is null.
	 */
	public void copyToLocal(LocalFile localFile) throws IOException {
		copyTo(localFile, false, false);
	}

	/**
	 * Copies the SRB container to the local file system, as if it were a
	 * directory. If the local file does not exist, a new one will be created.
	 *

	 *
	 * @deprecated Superseded by copyFrom( GeneralFile ). This single new method
	 *             replaces all the other older copyFrom...() methods. It
	 *             functions in the same manner as those old methods, but can
	 *             except any GeneralFile. It also fixes some bugs in those
	 *             methods.
	 * @param localFile
	 *            The file to be copied
	 * @throws NullPointerException
	 *             If localFile is null.
	 */
	public void copyToLocal(String localFilePath) throws IOException {
		copyTo(new LocalFile(localFilePath), false, false);
	}

	/**
	 * Copies this file to a new location on the server. If the
	 * remoteFile does not exist, one will be created. Otherwise
	 * this SRB file is appended to the end of the remote file.
	 *

	 * Copying a container to a new logical space would be an unusual action.
	 * Replicate is better.
	 *
	 * @deprecated Superseded by copyFrom( GeneralFile ). This single new method
	 *             replaces all the other older copyFrom...() methods. It
	 *             functions in the same manner as those old methods, but can
	 *             except any GeneralFile. It also fixes some bugs in those
	 *             methods.
	 * @param remoteFile
	 *            The local file to receive the data.
	 * @throws ClassCastException
	 *             - if the argument is not a SRBFile object.
	 * @throws NullPointerException
	 *             If remoteFile is null.
	 */
	public void copyToRemote(RemoteFile remoteFile) throws IOException,
			ClassCastException {
		copyTo(remoteFile);
	}

	/**
	 * Get the permissions of the current user for this SRBContainer: write,
	 * read, all, annotate or null.
	 *

	 *
	 * @throws IOException
	 *             If an IOException occurs.
	 */
	public String getPermissions() throws IOException {
		MetaDataRecordList[] rl = null;
		String userName = srbFileSystem.getUserName();
		String userDomain = srbFileSystem.getDomainName();

		MetaDataCondition conditions[] = {
				MetaDataSet.newCondition(SRBMetaDataSet.USER_NAME,
						MetaDataCondition.EQUAL, userName),
				MetaDataSet.newCondition(SRBMetaDataSet.USER_DOMAIN,
						MetaDataCondition.EQUAL, userDomain), };
		MetaDataSelect selects[] = {
				MetaDataSet.newSelection(UserMetaData.USER_NAME),
				MetaDataSet.newSelection(SRBMetaDataSet.USER_DOMAIN),
				MetaDataSet.newSelection(SRBMetaDataSet.ACCESS_CONSTRAINT), };
		rl = query(conditions, selects);

		if (rl != null) {
			for (int i = 0; i < rl.length; i++) {
				if (rl[i].getValue(SRBMetaDataSet.USER_NAME).equals(userName)
						&& rl[i].getValue(SRBMetaDataSet.USER_DOMAIN).equals(
								userDomain)) {
					return rl[i].getValue(SRBMetaDataSet.ACCESS_CONSTRAINT)
							.toString();
				}
			}
		}

		return null;
	}

	/**
	 * Gets all the non null permissions of all SRB users for this SRBContainer:
	 * write, read, all, annotate or null.
	 *

	 *
	 * @throws IOException
	 *             If an IOException occurs.
	 */
	public MetaDataRecordList[] getPermissions(boolean allUsers)
			throws IOException {
		return query(GeneralMetaData.ACCESS_CONSTRAINT);
	}

	/**
	 * Replicates this container to a new resource. Each replicant will
	 * increment its replication number by 1 from the last replication.
	 *

	 *
	 * @param newResource
	 *            The storage resource name of the new copy.
	 */
	public void replicate(String newResource) throws IOException {
		srbFileSystem.srbReplContainer(catalogType, getPath(), newResource);
	}

	/**
	 * Sync a container. With backup() you can sync the permanant replica with
	 * the temporary replica. The default is to synchronize all archival
	 * resources. Syncronization types can also be either
	 * PURGE_SYNC or PRIMARY_SYNC
	 *
	 * @param syncType
	 *            synchronization type, see PURGE_SYNC and PRIMARY_SYNC. default
	 *            value is to synchronize all archival resources.
	 */
	public void backup(String syncType) throws IOException {
		int syncFlag = 0;
		String path = getAbsolutePath();

		// purge the cache copies after sync is done.
		// PURGE_FLAG = 1
		if (syncType == PURGE_SYNC) {
			syncFlag = 1;
		}
		// Synchronize to the primary archival resource
		// only. The default is to synchronize all archival resources.
		// PRIMARY_FLAG = 2
		else if (syncType == PRIMARY_SYNC) {
			syncFlag = 2;
		}
		// The default is to synchronize all archival resources.
		else {
			path += ".*";
		}

		srbFileSystem.srbSyncContainer(catalogType, path, syncFlag);
	}

	/**
	 * Loads the local files on to the SRB in this container in the
	 * srbDirectory.
	 */
	void bulkLoad(LocalFile[] files) throws IOException {
		/*
		 * which container or resource, get size and MaxSize of container open
		 * container or temp file for upload create two 8MB byte buffers create
		 * new threads main thread starts loading local files into buffer -one
		 * buffer gets filled well the other buffer is used in transfer also
		 * loads myResultStruct (upto 300 files)
		 * -somehow->dataName,collectionName,offset -once full create
		 * registration thread make sure not to overflow container
		 *
		 * only one transfer thread waits on buffer to have data -main gives
		 * signal check enough space, otherwise create new container uses
		 * regular srbobjwrite udates status and wait again
		 *
		 * upto 4 registration threads
		 */

		int MAX_REGISTRATION_THREADS = 4;

		long maxSize = -1;
		long containerOffset = 0;

		// Two buffers are used switching back and forth
		// from loading to transfering files
		byte[] buffer1 = new byte[BULK_LOAD_BUFFER_SIZE];
		byte[] buffer2 = new byte[BULK_LOAD_BUFFER_SIZE];

		// the file to receive the data
		GeneralRandomAccessFile raf = new SRBRandomAccessFile(this, "rw");

		// one transfer thread
		Thread loadThread = null;
		LoadThread load = null;

		// if this object isn't a dir, make it one.
		mkdir();

		RegistrationThread[] registration = new RegistrationThread[MAX_REGISTRATION_THREADS];
		for (int i = 0; i < MAX_REGISTRATION_THREADS; i++) {
			registration[i] = new RegistrationThread(srbFileSystem,
					catalogType, getAbsolutePath());
		}
		Thread[] registrationThreads = new Thread[MAX_REGISTRATION_THREADS];
		for (int i = 0; i < MAX_REGISTRATION_THREADS; i++) {
			registrationThreads[i] = new Thread(registration[i]);
		}

		load = new LoadThread(raf, buffer1, buffer2);
		loadThread = new Thread(load);
		loadThread.start();

		// Now start copying
		for (int i = 0; i < files.length; i++) {
			loadBuffer(files[i], load, this, registrationThreads, registration,
					null);
		}

		// make sure the load buffers have finished loading all the files
		if ((useBuffer == 0) || (useBuffer == 1)) {
			load.buffer1Length = bufferPos;
		} else if (useBuffer == 2) {
			load.buffer2Length = bufferPos;
		}

		load.writeBuffer1 = true;
		while (load.writeBuffer1) {
			// wait?
		}
		load.writeBuffer2 = true;

		// end thread stuff
		load.keepLoading = false;
		raf.close();
		try {
			if (loadThread.isAlive()) {
				loadThread.join();
			}
			for (int i = 0; i < MAX_REGISTRATION_THREADS; i++) {
				registration[i].forceRegister();
			}
			for (int i = 0; i < MAX_REGISTRATION_THREADS; i++) {
				if (registrationThreads[i] != null) {
				}
			}
		} catch (InterruptedException e) {

		}
	}

	int bufferPos = 0;
	int useBuffer = 0;
	int numRegistrationThreads = 0;

	// file currently being loaded into the buffer
	private void loadBuffer(GeneralFile file, LoadThread load,
			SRBFile tempFile, Thread[] registrationThreads,
			RegistrationThread[] registration, String topLevelFile)
			throws IOException {
		if (file == null) {
			return;
		}

		if (file.isDirectory()) {
			if (topLevelFile == null) {
				topLevelFile = file.getName();
			} else {
				topLevelFile += separator + file.getName();
			}

			GeneralFile[] files = file.listFiles();
			if (files == null)
				return;

			for (int i = 0; i < files.length; i++) {
				loadBuffer(files[i], load, tempFile, registrationThreads,
						registration, topLevelFile);
			}
		} else {
			GeneralRandomAccessFile readFile = null;
			try {
				readFile = FileFactory.newRandomAccessFile(file, "r");
			} catch (SecurityException e) {
				return;
			}
			long toRead = file.length();
			int temp = 0;

			while (toRead > 0) {
				// load the buffer that is not being transferred
				// this if, or something else is cutting up the transfer
				// so the buffer2 isn't always getting sent.
				// it should switch back and forth.
				while ((load.writeBuffer1 && load.writeBuffer2)
						|| (load.writeBuffer1 && (useBuffer == 1))
						|| (load.writeBuffer2 && (useBuffer == 2))) {
					// just wait
				}

				// warning, had problems went I limit the BULK_LOAD_BUFFER_SIZE
				// to something small
				// it would occasionally not upload buffer2
				if ((useBuffer == 0) || (useBuffer == 1)) {
					if ((toRead + bufferPos) < BULK_LOAD_BUFFER_SIZE) {
						// read [the last of] this file into this buffer
						temp = readFile.read(load.buffer1, bufferPos,
								(int) toRead);
						bufferPos += temp;
						toRead -= temp;
					} else if (bufferPos < BULK_LOAD_BUFFER_SIZE) {
						// fill this buffer
						temp = readFile.read(load.buffer1, bufferPos,
								BULK_LOAD_BUFFER_SIZE - bufferPos);
						bufferPos += temp;
						toRead -= temp;

						// signal to the load thread, and reset local variables
						load.buffer1Length = bufferPos;
						load.writeBuffer1 = true;
						useBuffer = 2;
						bufferPos = 0;

						// if possible, load the remainder of the file into the
						// other buffer
						if (toRead < BULK_LOAD_BUFFER_SIZE) {
							temp = readFile.read(load.buffer2, bufferPos,
									(int) toRead);
							bufferPos += temp;
							toRead -= temp;
						}
					} else {
						// buffer is full, signal and reset
						load.buffer1Length = bufferPos;
						load.writeBuffer1 = true;
						useBuffer = 2;
						bufferPos = 0;

						// if possible, load the remainder of the file into the
						// other buffer
						if (toRead < BULK_LOAD_BUFFER_SIZE) {
							temp = readFile.read(load.buffer2, bufferPos,
									(int) toRead);
							bufferPos += temp;
							toRead -= temp;
						}
					}
				}

				if (useBuffer == 2) {
					if ((toRead + bufferPos) < BULK_LOAD_BUFFER_SIZE) {
						// read [the last of] this file into this buffer
						temp = readFile.read(load.buffer2, bufferPos,
								(int) toRead);
						bufferPos += temp;
						toRead -= temp;
					} else if (bufferPos < BULK_LOAD_BUFFER_SIZE) {
						// fill this buffer
						temp = readFile.read(load.buffer2, bufferPos,
								BULK_LOAD_BUFFER_SIZE - bufferPos);
						bufferPos += temp;
						toRead -= temp;

						// signal to the load thread, and reset local variables
						load.buffer2Length = bufferPos;
						load.writeBuffer2 = true;
						useBuffer = 1;
						bufferPos = 0;

						// if possible, load the remainder of the file into the
						// other buffer
						if (toRead < BULK_LOAD_BUFFER_SIZE) {
							temp = readFile.read(load.buffer1, bufferPos,
									(int) toRead);
							bufferPos += temp;
							toRead -= temp;
						}
					} else {
						load.buffer2Length = bufferPos;
						load.writeBuffer2 = true;
						useBuffer = 1;
						bufferPos = 0;

						// if possible, load the remainder of the file into the
						// other buffer
						if (toRead < BULK_LOAD_BUFFER_SIZE) {
							temp = readFile.read(load.buffer1, bufferPos,
									(int) toRead);
							bufferPos += temp;
							toRead -= temp;
						}
					}
				}
			}
			readFile.close();

			filesReadyToRegister++;

			if (topLevelFile == null) {
				registration[numRegistrationThreads % 4].addFile(file, "");
			} else {
				registration[numRegistrationThreads % 4].addFile(file,
						topLevelFile);
			}

			if ((((filesReadyToRegister % 10) == 0))
					&& (numRegistrationThreads < 4)) {
				if (!registrationThreads[numRegistrationThreads].isAlive()) {
					registrationThreads[numRegistrationThreads].start();
				}
				numRegistrationThreads++;
			}
		}
	}

	class LoadThread implements Runnable {
		GeneralRandomAccessFile out;
		byte[] buffer1;
		byte[] buffer2;
		boolean writeBuffer1 = false;
		boolean writeBuffer2 = false;
		int buffer1Length = 0;
		int buffer2Length = 0;
		boolean keepLoading = true;

		LoadThread(GeneralRandomAccessFile out, byte[] buffer1, byte[] buffer2) {
			this.out = out;
			this.buffer1 = buffer1;
			this.buffer2 = buffer2;
		}

		public void run() {
			while (keepLoading) {
				sendBuffer();
			}
		}

		void sendBuffer() {
			try {
				if (writeBuffer1) {
					out.write(buffer1, 0, buffer1Length);
					writeBuffer1 = false;
				}

				if (writeBuffer2) {
					out.write(buffer2, 0, buffer2Length);
					writeBuffer2 = false;
				}
			} catch (IOException e) {
			}
		}
	}

	// keep track of which files have been registered
	int registeredFiles = 0;
	// and which still need to be.
	int filesReadyToRegister = 0;

	int registrationOffset = 0;

	class RegistrationThread implements Runnable {
		SRBFileSystem fileSystem;
		int catalogType;

		// directory to load into on the SRB
		String bloadFilePath;

		// loop until false
		boolean keepLoading = false;

		boolean newFiles = false;

		Vector files = new Vector();
		Vector paths = new Vector();

		RegistrationThread(SRBFileSystem fileSystem, int catType,
				String bloadFilePath) throws IOException {
			this.fileSystem = fileSystem;
			this.catalogType = catalogType;
			this.bloadFilePath = bloadFilePath;
		}

		void addFile(GeneralFile file, String relativePath) {
			files.add(file);
			paths.add(relativePath);
			newFiles = true;
		}

		public void run() {
			keepLoading = true;
			while (keepLoading) {
				register();
			}
		}

		// get the files that are ready to be registered
		SRBMetaDataRecordList[] getFileRegistry() throws IOException {
			SRBMetaDataRecordList rl = null;
			SRBMetaDataRecordList[] recordLists = new SRBMetaDataRecordList[files
					.size()];

			GeneralFile tempFile = null, tempFile2 = null;
			String tempName = null, tempName2 = null;

			String fileName = null;
			String dirName = null;
			long size = 0;

			// create the registry for the files loaded so far.
			for (int i = 0; i < recordLists.length; i++) {
				tempFile = (GeneralFile) files.get(i);
				fileName = tempFile.getName();
				registrationOffset += size;// I hope the reg threads always
				// run in order...
				size = tempFile.length();
				dirName = (String) paths.get(i);
				if (dirName != "")
					dirName = getAbsolutePath() + separator + dirName;
				else
					dirName = getAbsolutePath();

				rl = new SRBMetaDataRecordList(SRBMetaDataSet
						.getField(SRBMetaDataSet.FILE_NAME), fileName);
				rl.addRecord(SRBMetaDataSet
						.getField(SRBMetaDataSet.DIRECTORY_NAME), dirName);
				rl
						.addRecord(
								SRBMetaDataSet.getField(SRBMetaDataSet.SIZE),
								size);
				rl.addRecord(SRBMetaDataSet.getField(SRBMetaDataSet.OFFSET),
						registrationOffset);

				recordLists[i - registeredFiles] = rl;
			}

			for (int i = 0; i < recordLists.length; i++) {
				try {// HACK
					files.remove(0);
					paths.remove(0);
				} catch (ArrayIndexOutOfBoundsException e) {
					break;
				}
			}

			return recordLists;
		}

		void register() {
			try {
				if (!newFiles)
					return;
				if (files.size() < 5)
					return;
				fileSystem.srbBulkLoad(catalogType, bloadFilePath,
						getFileRegistry());
			} catch (IOException e) {
			}
		}

		void forceRegister() {
			if (!newFiles)
				return;

			try {
				fileSystem.srbBulkLoad(catalogType, bloadFilePath,
						getFileRegistry());
			} catch (IOException e) {
			}
		}
	}

	/**
	 * Tests whether the application can read from the container denoted by this
	 * abstract pathname.
	 *
	 * @return true if and only if the container specified by this
	 *         abstract pathname exists and can be read; otherwise
	 *         false.
	 */
	public boolean canRead() {
		try {
			if (exists()) {
				MetaDataRecordList[] rl = query(SRBMetaDataSet.ACCESS_CONSTRAINT);
				if (rl != null) {
					if (rl[0].getStringValue(0).equals("all")
							|| rl[0].getStringValue(0).equals("read")) {
						return true;
					}
				}
			}
		} catch (IOException e) {
		}

		return false;
	}

	/**
	 * Tests whether the application can modify to the container denoted by this
	 * abstract pathname.
	 *
	 * @return true if and only if the container system actually
	 *         contains a file denoted by this abstract pathname and
	 *         the application is allowed to write to the container; otherwise
	 *         false.
	 */
	public boolean canWrite() {
		try {
			if (exists()) {
				MetaDataRecordList[] rl = query(SRBMetaDataSet.ACCESS_CONSTRAINT);
				if (rl != null) {
					if (rl[0].getStringValue(0).equals("all")
							|| rl[0].getStringValue(0).equals("write")) {
						return true;
					}
				}
			}
		} catch (IOException e) {
		}

		return false;
	}

	/**
	 * Compares two containers lexicographically.
	 *
	 * @param pathname
	 *            The container to be compared to this abstract pathname
	 *
	 * @return Zero if the argument is equal to this container, a value less
	 *         than zero if this container is lexicographically less than the
	 *         argument, or a value greater than zero if this container is
	 *         lexicographically greater than the argument
	 */
	public int compareTo(GeneralFile pathname) {
		return getAbsolutePath().compareTo(
				((SRBContainer) pathname).getAbsolutePath());
	}

	/**
	 * Compares this container to another object. If the other object is an
	 * container, then this function behaves like {@link
   * #compareTo(GeneralFile)}
	 * . Otherwise, it throws a ClassCastException, since
	 * containers can only be compared to containers.
	 *
	 * @param o
	 *            The Object to be compared to this abstract
	 *            pathname
	 *
	 * @return If the argument is an container, returns zero if the argument is
	 *         equal to this container, a value less than zero if this container
	 *         is lexicographically less than the argument, or a value greater
	 *         than zero if this container is lexicographically greater than the
	 *         argument
	 *

	 * @throws ClassCastException
	 *             - if the argument is not an container
	 */
	public int compareTo(Object o) throws ClassCastException {
		return compareTo((SRBContainer) o);
	}

	/**
	 * Atomically creates a new, empty container named by this abstract pathname
	 * if and only if a container with this name does not yet exist.
	 */
	public boolean createNewFile() {
		try {
			if (!exists()) {
				srbFileSystem
						.srbContainerCreate(catalogType, getAbsolutePath(),
								dataType, resource, containerMaxSize);
				return true;
			}
		} catch (IOException e) {
			// don't do anything.
		}

		return false;
	}

	/**
	 * Creates an empty file in the default temporary-file directory, using the
	 * given prefix and suffix to generate its name. Invoking this method is
	 * equivalent to invoking {@link #createTempFile(java.lang.String,
   * java.lang.String, edu.sdsc.grid.io.GeneralFile)
   * createTempFile(prefix, suffix, null)}
	 * .
	 *
	 * @param prefix
	 *            The prefix string to be used in generating the file's name;
	 *            must be at least three characters long
	 *
	 * @param suffix
	 *            The suffix string to be used in generating the file's name;
	 *            may be null, in which case the suffix
	 *            ".tmp" will be used
	 *
	 * @return An abstract pathname denoting a newly-created empty file
	 *
	 * @throws IllegalArgumentException
	 *             If the prefix argument contains fewer than three
	 *             characters
	 *
	 * @throws IOException
	 *             If a file could not be created
	 */
	public static GeneralFile createTempFile(String prefix, String suffix)
			throws IOException, IllegalArgumentException {
		return createTempFile(prefix, suffix, null);
	}

	/**
	 *

	 * Creates a new empty file in the specified directory, using the given
	 * prefix and suffix strings to generate its name. If this method returns
	 * successfully then it is guaranteed that:
	 *
	 *

	 *
The file denoted by the returned abstract pathname did not exist
	 * before this method was invoked, and
	 *
Neither this method nor any of its variants will return the same
	 * abstract pathname again in the current invocation of the virtual machine.
	 *

	 *
	 * This method provides only part of a temporary-file facility. To arrange
	 * for a file created by this method to be deleted automatically, use the
	 * {@link #deleteOnExit} method.
	 *
	 *

	 * The prefix argument must be at least three characters long.
	 * It is recommended that the prefix be a short, meaningful string such as
	 * "hjb" or "mail". The suffix
	 * argument may be null, in which case the suffix
	 * ".tmp" will be used.
	 *
	 *

	 * To create the new file, the prefix and the suffix may first be adjusted
	 * to fit the limitations of the underlying platform. If the prefix is too
	 * long then it will be truncated, but its first three characters will
	 * always be preserved. If the suffix is too long then it too will be
	 * truncated, but if it begins with a period character ('.')
	 * then the period and the first three characters following it will always
	 * be preserved. Once these adjustments have been made the name of the new
	 * file will be generated by concatenating the prefix, five or more
	 * internally-generated characters, and the suffix.
	 *
	 *

	 * If the directory argument is null then the SRB
	 * default temporary-file directory will be used. The default temporary-file
	 * directory is specified by the system property java.io.tmpdir
	 * . On UNIX systems the default value of this property is typically
	 * "/tmp" or "/var/tmp"; on Microsoft Windows
	 * systems it is typically "c:\\temp". A different value may be
	 * given to this system property when the Java virtual machine is invoked,
	 * but programmatic changes to this property are not guaranteed to have any
	 * effect upon the the temporary directory used by this method.
	 *
	 * @param prefix
	 *            The prefix string to be used in generating the file's name;
	 *            must be at least three characters long
	 *
	 * @param suffix
	 *            The suffix string to be used in generating the file's name;
	 *            may be null, in which case the suffix
	 *            ".tmp" will be used
	 *
	 * @param directory
	 *            The directory in which the file is to be created, or
	 *            null if the default temporary-file directory is
	 *            to be used
	 *
	 * @return An abstract pathname denoting a newly-created empty file
	 *
	 * @throws IllegalArgumentException
	 *             If the prefix argument contains fewer than three
	 *             characters
	 *
	 * @throws IOException
	 *             If a file could not be created
	 */
	public static GeneralFile createTempFile(String prefix, String suffix,
			GeneralFile directory) throws IOException, IllegalArgumentException {
		if (prefix == null)
			throw new NullPointerException();
		if (prefix.length() < 3)
			throw new IllegalArgumentException("Prefix string too short");

		if (suffix == null)
			suffix = ".tmp";

		if (directory == null) {
			SRBFileSystem fs = new SRBFileSystem();
			directory = new SRBContainer(fs, "");
		}

		SRBContainer temp = new SRBContainer((SRBFile) directory, prefix
				+ suffix);
		if (temp.exists()) {
			throw new IOException();
		}
		temp.createNewFile();
		return temp;
	}

	/**
	 * Deletes the container denoted by this SRBContainer. The container must be
	 * empty in order to be deleted.
	 */
	public boolean delete() {
		return delete(false);
	}

	/**
	 * Deletes the file or directory denoted by this abstract pathname. If this
	 * pathname denotes a directory, then the directory must be empty in order
	 * to be deleted.
	 *
	 * @return true if and only if the file or directory is
	 *         successfully deleted; false otherwise
	 */
	public boolean delete(boolean force) {
		try {
			if (exists()) {
				srbFileSystem.srbRmContainer(catalogType, getAbsolutePath(),
						true);
				return true;
			}
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	/**
	 * Tests this abstract pathname for equality with the given object. Returns
	 * true if and only if the argument is not null
	 * and is an abstract pathname that denotes the same container as this
	 * abstract pathname.
	 *
	 * @param obj
	 *            The object to be compared with this abstract pathname
	 *
	 * @return true if and only if the objects are the same;
	 *         false otherwise
	 */
	public boolean equals(Object obj) {
		try {
			SRBContainer temp = (SRBContainer) obj;

			return getAbsolutePath().equals(temp.getAbsolutePath());
		} catch (ClassCastException e) {
			// ignore
		}

		return false;
	}

	/**
	 * Tests whether the container denoted by this abstract pathname exists.
	 *
	 * @return true if and only if the container denoted by this
	 *         abstract pathname exists; false otherwise
	 */
	public boolean exists() {
		try {
			MetaDataRecordList[] rl = null;
			int operator = MetaDataCondition.EQUAL;

			// if it is a file
			MetaDataCondition conditions[] = { MetaDataSet.newCondition(
					SRBMetaDataSet.CONTAINER_NAME, operator, getAbsolutePath()) };
			MetaDataSelect selects[] = { MetaDataSet
					.newSelection(SRBMetaDataSet.CONTAINER_NAME) };

			rl = srbFileSystem.query(conditions, selects, 3);

			if (rl != null)
				return true;
		} catch (IOException e) {
			// don't do anything
		}

		return false;
	}

	/**
	 * Returns the absolute form of this abstract pathname. Equivalent to
	 * new SRBContainer(this.{@link #getFileSystem}(),
   * this.{@link #getAbsolutePath}()).
	 *
	 * @return The absolute abstract pathname denoting the same container as
	 *         this abstract pathname
	 */
	public GeneralFile getAbsoluteFile() {
		return new SRBContainer(srbFileSystem, getAbsolutePath());
	}

	/**
	 * Returns the canonical form of this abstract pathname. Equivalent to
	 * new SRBContainer(this.{@link #getCanonicalPath}()).
	 *
	 * @return The canonical pathname string denoting the same container as this
	 *         abstract pathname
	 *
	 * @throws IOException
	 *             If an I/O error occurs, which is possible because the
	 *             construction of the canonical pathname may require filesystem
	 *             queries
	 */
	public GeneralFile getCanonicalFile() {
		return new SRBContainer(srbFileSystem, getAbsolutePath());
	}

	/**
	 * Returns the abstract pathname of this abstract pathname's parent, or
	 * null if this pathname does not name a parent directory.
	 *
	 *

	 * The parent of an abstract pathname consists of the pathname's
	 * prefix, if any, and each name in the pathname's name sequence except for
	 * the last. If the name sequence is empty then the pathname does not name a
	 * parent directory.
	 *
	 * @return The abstract pathname of the parent directory named by this
	 *         abstract pathname, or null if this pathname does not
	 *         name a parent
	 */
	public GeneralFile getParentFile() {
		return new SRBContainer(srbFileSystem, getParent());
	}

	/**
	 * Tests whether the object denoted by this abstract pathname is a
	 * container.
	 *
	 * @return true if and only if the file denoted by this
	 *         abstract pathname exists and is a container;
	 *         false otherwise
	 */
	public boolean isContainer() {
		if (exists())
			return true;

		return false;
	}

	/**
	 * Tests whether the file denoted by this abstract pathname is a directory.
	 *
	 * @return true if and only if the file denoted by this
	 *         abstract pathname exists and is a directory;
	 *         false otherwise
	 */
	public boolean isDirectory() {
		return false;
	}

	/**
	 * Tests whether the file denoted by this abstract pathname is a normal
	 * file. A file is normal if it is not a directory or a container.
	 * Any non-directory or other subclass of SRBFile, such as a SRBContainer,
	 * file created by a Java application is guaranteed to be a normal file.
	 *
	 * @return true if and only if the file denoted by this
	 *         abstract pathname exists and is a normal file;
	 *         false otherwise
	 */
	public boolean isFile() {
		return false;
	}

	/**
	 * Tests whether the file named by this abstract pathname is a hidden file.
	 *
	 * @return true if and only if the file denoted by this
	 *         abstract pathname is hidden.
	 */
	public boolean isHidden() {
		return false;// SRB files can't be hidden?
	}

	/**
	 * Returns the time that the file denoted by this abstract pathname was last
	 * modified.
	 *
	 * @return A long value representing the time the file was last
	 *         modified, measured in milliseconds since the epoch (00:00:00 GMT,
	 *         January 1, 1970), or 0L if the file does not exist
	 *         or if an I/O error occurs
	 */
	public long lastModified() {
		try {
			MetaDataRecordList[] rl = query(SRBMetaDataSet.MODIFICATION_DATE);// wrong
			// attribute,
			// need
			// epoch
			// long
			if (rl != null) {
				return Long.parseLong(rl[0].getValue(
						SRBMetaDataSet.MODIFICATION_DATE).toString());
			}
		} catch (IOException e) {
			return 0;
		}

		return 0;
	}

	/**
	 * Returns the length of the container denoted by this abstract pathname.
	 * The return value is unspecified if this pathname denotes a directory.
	 * This is the actual amount of data in the container, use
	 * getContainerMaxSize() to get the maximum amount of data the container can
	 * hold.
	 *
	 * @return The length, in bytes, of the container denoted by this abstract
	 *         pathname, or 0L if the container does not exist
	 */
	public long length() {
		try {
			MetaDataRecordList[] rl = query(SRBMetaDataSet.CONTAINER_SIZE);
			if (rl != null) {
				return Long.parseLong(rl[0].getValue(
						SRBMetaDataSet.CONTAINER_SIZE).toString());
			}
		} catch (IOException e) {
			return 0;
		}

		return 0;
	}

	/**
	 * Returns an array of strings naming the files and directories in the
	 * container denoted by this abstract pathname.
	 *

	 * There is no guarantee that the name strings in the resulting array will
	 * appear in any specific order; they are not, in particular, guaranteed to
	 * appear in alphabetical order.
	 *
	 * @return An array of strings naming the files and directories in the
	 *         container denoted by this abstract pathname. The array will be
	 *         empty if the directory is empty. Returns null if this abstract
	 *         pathname does not denote a directory, or if an I/O error occurs.
	 */
	public String[] list() {
		String list[] = {};
		String fileName, containerName = getName();

		try {
			MetaDataRecordList[] rl = query(SRBMetaDataSet.FILE_NAME);

			if (rl != null) {
				list = new String[rl.length - 1];

				for (int i = 0, j = 0; i < rl.length; i++) {
					fileName = rl[i].getStringValue(0);
					if (!fileName.equals(containerName)) {
						list[j] = fileName;
						j++;
					}
				}
			}
		} catch (IOException e) {
			return null;
		}

		return list;
	}

	/**
	 * Creates the container named by this abstract pathname. Same as calling
	 * the createNewFile method.
	 */
	public boolean mkdir() {
		return createNewFile();
	}

	/**
	 * Renames the container denoted by this abstract pathname.
	 *
	 * @param dest
	 *            The new abstract pathname for the named container
	 *
	 * @throws IllegalArgumentException
	 *             If parameter dest is not a SRBFile.
	 */
	public boolean renameTo(GeneralFile dest) {
		try {
			if (exists()) {
				srbFileSystem.srbModifyDataset(catalogType, getName(),
						getParent(), resource, null, dest.getName(), null,
						SRBMetaDataSet.D_CHANGE_DNAME);
				return true;
			}
		} catch (IOException e) {
			// ignore
		}
		return false;
	}
}


text:
<?php
/**
 * Tests for Hostingcheck_View class.
 *
 * @author Peter Decuyper <peter@serial-graphics.be>
 */
class Hostingcheck_View_TestCase extends PHPUnit_Framework_TestCase
{
    /**
     * Test the constructor.
     *
     * @expectedException Exception
     * @expectedExceptionMessage View scripts path "/fake/path" is not valid.
     */
    public function testConstructorWithFaultPath()
    {
        new Hostingcheck_View('/fake/path');
    }

    /**
     * Test the method to render a single view script.
     */
    public function testRender()
    {
        $path = __DIR__ . '/../Views';
        $view = new Hostingcheck_View($path);

        $vars = array('foo' => 'TEST 123');
        $output = $view->render('script', $vars);
        $this->assertEquals('
TEST 123
', $output);
    }

    /**
     * Test the method to render a view script within a template file.
     */
    public function testRenderTemplate()
    {
        $path = __DIR__ . '/../Views';
        $view = new Hostingcheck_View($path, 'template');

        $vars = array('foo' => 'TEST 123');
        $output = $view->renderTemplate('script', $vars);
        $this->assertEquals('

TEST 123

', $output);

        $output = $view->renderTemplate('script', $vars, 'template-custom');
        $this->assertEquals('

TEST 123

', $output);
    }

    /**
     * Test the __call() magic method run helper plugins.
     */
    public function testExistingHelper()
    {
        $path = __DIR__ . '/../Views';
        $view = new Hostingcheck_View($path, 'template');

        $result = new Hostingcheck_Result_Failure();
        $this->assertEquals('failure', $view->resultCssClass($result));
    }
}

redpajama_set_name: RedPajamaGithub


text:
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT!

package fallk.jfunktion;

/**
 * Represents a function that accepts two arguments, a double and a short, and produces a
 * result.  This is the {@code double} and {@code short}-consuming primitive specialization for
 * {@link java.util.function.BiFunction}.
 *
 * @param <R> the type of the result of the function
 *
 * @see java.util.function.BiFunction
 */
@FunctionalInterface
public interface DoubleShortFunction<R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param v1 the {@code double} argument
     * @param v2 the {@code short} argument
     * @return the function result
     */
    R apply(double v1, short v2);
}


text:
"""
parser.http.bsouplxml.etree module (imdb.parser.http package).

This module adapts the beautifulsoup interface to lxml.etree module.

Copyright 2008 H. Turgut Uyar <uyar@tekir.org>
          2008 Davide Alberani <da@erlug.linux.it>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

import _bsoup as BeautifulSoup
from _bsoup import Tag as Element

import bsoupxpath

# Not directly used by IMDbPY, but do not remove: it's used by IMDbPYKit,
# for example.
def fromstring(xml_string):
    """Return a DOM representation of the string."""
    # We try to not use BeautifulSoup.BeautifulStoneSoup.XML_ENTITIES,
    # for convertEntities.
    return BeautifulSoup.BeautifulStoneSoup(xml_string,
                        convertEntities=None).findChild(True)

def tostring(element, encoding=None, pretty_print=False):
    """Return a string or unicode representation of an element."""
    if encoding is unicode:
        encoding = None
    # For BeautifulSoup 3.1
    #encArgs = {'prettyPrint': pretty_print}
    #if encoding is not None:
    #    encArgs['encoding'] = encoding
    #return element.encode(**encArgs)
    return element.__str__(encoding, pretty_print)

def setattribute(tag, name, value):
    tag[name] = value

def xpath(node, expr):
    """Apply an xpath expression to a node. Return a list of nodes."""
    #path = bsoupxpath.Path(expr)
    path = bsoupxpath.get_path(expr)
    return path.apply(node)

# XXX: monkey patching the beautifulsoup tag class
class _EverythingIsNestable(dict):
    """"Fake that every tag is nestable."""
    def get(self, key, *args, **kwds):
        return []

BeautifulSoup.BeautifulStoneSoup.NESTABLE_TAGS = _EverythingIsNestable()
BeautifulSoup.Tag.tag = property(fget=lambda self: self.name)
BeautifulSoup.Tag.attrib = property(fget=lambda self: self)
BeautifulSoup.Tag.text = property(fget=lambda self: self.string)
BeautifulSoup.Tag.set = setattribute
BeautifulSoup.Tag.getparent = lambda self: self.parent
BeautifulSoup.Tag.drop_tree = BeautifulSoup.Tag.extract
BeautifulSoup.Tag.xpath = xpath

# TODO: setting the text attribute for tags


text:
using namespace std;

static ossimTrace traceDebug ("ossimOrthoImageMosaic:debug");

RTTI_DEF1(ossimOrthoImageMosaic, "ossimOrthoImageMosaic", ossimImageMosaic);

//**************************************************************************************************
//
//**************************************************************************************************
ossimOrthoImageMosaic::ossimOrthoImageMosaic()
   :ossimImageMosaic()
{
   m_Delta.makeNan();
   m_UpperLeftTie.makeNan();
}

//**************************************************************************************************
//
//**************************************************************************************************
ossimOrthoImageMosaic::ossimOrthoImageMosaic(ossimConnectableObject::ConnectableObjectList& inputSources)
   :ossimImageMosaic(inputSources)
{
   m_Delta.makeNan();
   m_UpperLeftTie.makeNan();
}

//**************************************************************************************************
//
//**************************************************************************************************
ossimOrthoImageMosaic::~ossimOrthoImageMosaic()
{
}

//**************************************************************************************************
//
//**************************************************************************************************
ossim_uint32 ossimOrthoImageMosaic::getNumberOfOverlappingImages(const ossimIrect& rect,
                                                                 ossim_uint32 resLevel)const
{
   ossim_uint32 result = 0;
   for(ossim_uint32 i = 0; i < m_InputTiePoints.size(); ++i)
   {
      ossimImageSource* interface = PTR_CAST(ossimImageSource,
                                                      getInput(i));
      if(interface&&
         !m_InputTiePoints[i].hasNans())
      {
         ossimIrect tempRect = getRelativeRect(i, resLevel);

         if(!tempRect.hasNans())
         {
            if(tempRect.intersects(rect))
            {
               ++result;
            }
         }
      }
   }

   return 0;
}

//**************************************************************************************************
//
//**************************************************************************************************
void ossimOrthoImageMosaic::getOverlappingImages(std::vector<ossim_uint32>& result,
                                                 const ossimIrect& rect,
                                                 ossim_uint32 resLevel)const
{
   result.clear();
   for(ossim_uint32 i = 0; i < m_InputTiePoints.size(); ++i)
   {
      ossimImageSource* interface = PTR_CAST(ossimImageSource,
                                                      getInput(i));
      if(interface&&
         !m_InputTiePoints[i].hasNans())
      {
         ossimIrect tempRect = getRelativeRect(i, resLevel);

         if(!tempRect.hasNans())
         {
            if(tempRect.intersects(rect))
            {
               result.push_back(i);
            }
         }
      }
   }
}

//**************************************************************************************************
// Returns the image geometry for the complete mosaic
//**************************************************************************************************
ossimRefPtr<ossimImageGeometry> ossimOrthoImageMosaic::getImageGeometry()
{
   if ( !m_Geometry.valid() )
   {
      // The geometry (projection) associated with this mosaic is necessarily the same for all
      // single-image objects feeding into this combiner, So we will copy the first image source's
      // geometry, and modify our copy to reflect the mosaic-specific items.
      ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0));
      if(interface)
      {
         ossimRefPtr<ossimImageGeometry> inputGeom = interface->getImageGeometry();
         if ( inputGeom.valid() )
         {
            m_Geometry = new ossimImageGeometry(*inputGeom);
            updateGeometry();
         }
      }
   }
   return m_Geometry;
}

//**************************************************************************************************
//! If this object is maintaining an ossimImageGeometry, this method needs to be called after
//! each time the contents of the mosaic changes.
//**************************************************************************************************
void ossimOrthoImageMosaic::updateGeometry()
{
   if (!m_Geometry.valid())
      return;

   ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, m_Geometry->getProjection());
   if (mapProj)
   {
      if(m_Units == "degrees")
      {
         mapProj->setDecimalDegreesPerPixel(m_Delta);
         mapProj->setUlGpt(ossimGpt(m_UpperLeftTie.y, m_UpperLeftTie.x, 0.0,
                                    mapProj->origin().datum()));
      }
      else if(m_Units == "meters")
      {
         mapProj->setMetersPerPixel(m_Delta);
         mapProj->setUlEastingNorthing(m_UpperLeftTie);
      }
   }
}

//**************************************************************************************************
//
//**************************************************************************************************
ossimIrect ossimOrthoImageMosaic::getBoundingRect(ossim_uint32 resLevel) const
{
   ossimDpt decimation;

   decimation.makeNan();

   ossimImageSource* interface = PTR_CAST(ossimImageSource,
                                                   getInput(0));
   if(interface)
   {
      interface->getDecimationFactor(resLevel,
                                     decimation);
   }
   if(decimation.hasNans())
   {
      return m_BoundingRect;
   }
   return m_BoundingRect*decimation;
}

//**************************************************************************************************
//
//**************************************************************************************************
void ossimOrthoImageMosaic::initialize()
{
   m_InputTiePoints.clear();
   m_Delta.makeNan();
   m_UpperLeftTie.makeNan();

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimOrthoImageMosaic::initialize() DEBUG: Entered..."
         << "Number of inputs = " << getNumberOfInputs()
         << std::endl;
   }
   if(getNumberOfInputs())
   {
      m_InputTiePoints.resize(getNumberOfInputs());
      for(ossim_uint32 i = 0; i < getNumberOfInputs(); ++i)
      {
         ossimImageSource *interface = PTR_CAST(ossimImageSource, getInput(i));
         m_InputTiePoints[i].makeNan();
         if(interface)
         {
            ossimRefPtr<ossimImageGeometry> geom = interface->getImageGeometry();
            if( geom.valid() )
            {
               const ossimMapProjection* mapPrj = PTR_CAST(ossimMapProjection, geom->getProjection());
               if(mapPrj)
               {
                  if(!mapPrj->isGeographic())
                  {
                     m_Units = "meters";
                     m_Delta = mapPrj->getMetersPerPixel();
                  }
                  else
                  {
                     m_Units = "degrees";
                     m_Delta = mapPrj->getDecimalDegreesPerPixel();
                  }
                  if(m_Units == "degrees")
                  {
                     m_InputTiePoints[i].x = mapPrj->getUlGpt().lond();
                     m_InputTiePoints[i].y = mapPrj->getUlGpt().latd();
                  }
                  else if(m_Units == "meters")
                  {
                     m_InputTiePoints[i].x = mapPrj->getUlEastingNorthing().x;;
                     m_InputTiePoints[i].y = mapPrj->getUlEastingNorthing().y;
                  }

                  if(traceDebug())
                  {
                     ossimNotify(ossimNotifyLevel_DEBUG)
                        << "tie points for input " << i << " = "
                        << m_InputTiePoints[i] << std::endl;
                  }

               }
            }
            if(!m_InputTiePoints[i].hasNans())
            {
               if(m_UpperLeftTie.hasNans())
               {
                  m_UpperLeftTie = m_InputTiePoints[i];
               }
               else if(!m_InputTiePoints[i].hasNans())
               {
                  if(m_Units == "meters")
                  {
                     m_UpperLeftTie.x = std::min(m_UpperLeftTie.x, m_InputTiePoints[i].x);
                     m_UpperLeftTie.y = std::max(m_UpperLeftTie.y, m_InputTiePoints[i].y);
                  }
                  else
                  {
                     m_UpperLeftTie.lon = std::min(m_UpperLeftTie.lon, m_InputTiePoints[i].lon);
                     m_UpperLeftTie.lat = std::max(m_UpperLeftTie.lat, m_InputTiePoints[i].lat);
                  }
               }
            }
         }
         else
         {
            m_InputTiePoints[i].makeNan();
//            CLOG << "Input " << i << " will not be used since no ortho information exists" << endl;
         }
      }
   }

   computeBoundingRect();
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "m_UpperLeftTie = " << m_UpperLeftTie << std::endl
         << "delta per pixel = " << m_Delta        << std::endl
         << "bounding rect   = " << m_BoundingRect << std::endl;
   }
   ossimImageMosaic::initialize();

   // Finally, update the geometry (if there was one already defined), to reflect the change in input
   updateGeometry();

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoImageMosaic::initialize() DEBUG: Leaving..." << std::endl;
   }
}

//**************************************************************************************************
//
//**************************************************************************************************
ossimRefPtr<ossimImageData> ossimOrthoImageMosaic::getNextTile(ossim_uint32& returnedIdx,
                                                               const ossimIrect& origin,
                                                               ossim_uint32 resLevel)
{
   const char *MODULE="ossimOrthoImageMosaic::getNextTile";

   ossim_uint32 size = getNumberOfInputs();

   if(theCurrentIndex >= size)
   {
      return ossimRefPtr<ossimImageData>();
   }

   ossimImageSource* temp = NULL;
   ossimRefPtr<ossimImageData> result;
   ossimDataObjectStatus status = OSSIM_NULL;

   do
   {
      temp = PTR_CAST(ossimImageSource, getInput(theCurrentIndex));
      if(temp)
      {
         ossimIrect relRect = getRelativeRect(theCurrentIndex, resLevel);

         if(traceDebug())
         {
            CLOG << "Rel rect for input " << theCurrentIndex
                 << " = " << relRect
                 << "\nRes level:  " << resLevel
                 << endl;
         }

         if(origin.intersects(relRect))
         {
            // get the rect relative to the input rect
            //
            ossimIrect shiftedRect = origin + (ossimIpt(-relRect.ul().x,
                                                        -relRect.ul().y));

            // request that tile from the input space.
            result = temp->getTile(shiftedRect, resLevel);

            // now change the origin to the output origin.
            if (result.valid())
            {
               result->setOrigin(origin.ul());

               status = result->getDataObjectStatus();

               if((status == OSSIM_NULL)||(status == OSSIM_EMPTY))
               {
                  result = NULL;
               }
            }
         }
         else
         {
            result = NULL;
         }
      }

      // Go to next source.
      ++theCurrentIndex;

   } while(!result.valid() && (theCurrentIndex<size));

   returnedIdx = theCurrentIndex;
   if(result.valid())
   {
      --returnedIdx;
   }
   return result;
}

//**************************************************************************************************
//
//**************************************************************************************************
void ossimOrthoImageMosaic::computeBoundingRect(ossim_uint32 resLevel)
{
   const char* MODULE = "ossimOrthoImageMosaic::computeBoundingRect";

   m_BoundingRect.makeNan();

   for(ossim_uint32 i = 0; i < m_InputTiePoints.size(); ++ i)
   {
      ossimIrect shiftedRect = getRelativeRect(i, resLevel);

      if(traceDebug())
      {
         CLOG << "bounding rect for input " << (i+1)
              << ":" << shiftedRect << endl;
      }
      if(!shiftedRect.hasNans())
      {
         if(m_BoundingRect.hasNans())
         {
            m_BoundingRect = shiftedRect;
         }
         else
         {
            m_BoundingRect = m_BoundingRect.combine(shiftedRect);
         }
      }
   }
}

//**************************************************************************************************
//
//**************************************************************************************************
ossimIrect ossimOrthoImageMosaic::getRelativeRect(ossim_uint32 index,
                                                  ossim_uint32 resLevel)const
{
   ossimIrect result;
   ossimImageSource* interface = PTR_CAST(ossimImageSource,
                                                   getInput(index));
   result.makeNan();
   if(interface&&
      !m_InputTiePoints[index].hasNans())
   {
      ossimIrect inputRect = interface->getBoundingRect();
      result = inputRect;

      if(!inputRect.hasNans())
      {
         ossimDpt shift = (m_InputTiePoints[index] - m_UpperLeftTie);

         shift.x/= m_Delta.x;
         shift.y/=-m_Delta.y;

	 result = result + shift;
         if(!resLevel)
         {
            return result;
         }
 	 ossimDpt decimation;
 	 interface->getDecimationFactor(resLevel, decimation);
	 if(!decimation.hasNans())
         {
            result = result * decimation;
         }
      }
   }

   return result;
}


text:
/* jshint node: true,esversion: 9, -W014, -W033 */
/* eslint-disable new-cap */
'use strict'

const xmlbuilder = require('xmlbuilder')

module.exports = class deviceLinkHub {
  constructor (platform, accessory, devicesInHB) {
    // Set up variables from the platform
    this.consts = platform.consts
    this.devicesInHB = devicesInHB
    this.funcs = platform.funcs
    this.hapChar = platform.api.hap.Characteristic
    this.hapErr = platform.api.hap.HapStatusError
    this.hapServ = platform.api.hap.Service
    this.lang = platform.lang
    this.log = platform.log
    this.platform = platform

    // Set up variables from the accessory
    this.accessory = accessory
    this.enableLogging = accessory.context.enableLogging
    this.enableDebugLogging = accessory.context.enableDebugLogging
    this.name = accessory.displayName
  }

  receiveDeviceUpdate (deviceId, attribute) {
    // Find the accessory to which this relates
    this.devicesInHB.forEach(accessory => {
      if (
        accessory.context.serialNumber === deviceId &&
        accessory.control &&
        accessory.control.receiveDeviceUpdate
      ) {
        accessory.control.receiveDeviceUpdate(attribute)
      }
    })
  }

  async sendDeviceUpdate (deviceId, capability, value) {
    // Generate the XML to send
    const deviceStatusList = xmlbuilder
      .create('DeviceStatus', {
        version: '1.0',
        encoding: 'utf-8'
      })
      .ele({
        IsGroupAction: deviceId.length === 10 ? 'YES' : 'NO',
        DeviceID: deviceId,
        CapabilityID: capability,
        CapabilityValue: value
      })
      .end()

    // Send the update
    return await this.platform.httpClient.sendDeviceUpdate(
      this.accessory,
      'urn:Belkin:service:bridge:1',
      'SetDeviceStatus',
      {
        DeviceStatusList: { '#text': deviceStatusList }
      }
    )
  }

  async requestDeviceUpdate (deviceId) {
    return await this.platform.httpClient.sendDeviceUpdate(
      this.accessory,
      'urn:Belkin:service:bridge:1',
      'GetDeviceStatus',
      {
        DeviceIDs: deviceId
      }
    )
  }
}


text:
<?php
namespace inklabs\kommerce\ActionHandler\Attachment;

use inklabs\kommerce\Action\Attachment\MarkAttachmentNotVisibleCommand;
use inklabs\kommerce\EntityRepository\AttachmentRepositoryInterface;
use inklabs\kommerce\Lib\Authorization\AuthorizationContextInterface;
use inklabs\kommerce\Lib\Command\CommandHandlerInterface;

final class MarkAttachmentNotVisibleHandler implements CommandHandlerInterface
{
    /** @var MarkAttachmentNotVisibleCommand */
    private $command;

    /** @var AttachmentRepositoryInterface */
    private $attachmentRepository;

    public function __construct(
        MarkAttachmentNotVisibleCommand $command,
        AttachmentRepositoryInterface $attachmentRepository
    ) {
        $this->command = $command;
        $this->attachmentRepository = $attachmentRepository;
    }

    public function verifyAuthorization(AuthorizationContextInterface $authorizationContext): void
    {
        $authorizationContext->verifyIsAdmin();
    }

    public function handle()
    {
        $attachment = $this->attachmentRepository->findOneById(
            $this->command->getAttachmentId()
        );
        $attachment->setNotVisible();

        $this->attachmentRepository->update($attachment);
    }
}


text:
package edu.umass.ciir.galagotools.fns;

import edu.umass.ciir.galagotools.fns.AppFnRunner;
import edu.umass.ciir.galagotools.galago.GalagoUtil;
import edu.umass.ciir.galagotools.utils.IO;
import edu.umass.ciir.jasmine.tupleflow.NameFieldText;
import org.lemurproject.galago.core.index.disk.DiskIndex;
import org.lemurproject.galago.core.parse.Document;
import org.lemurproject.galago.tupleflow.Processor;
import org.lemurproject.galago.tupleflow.Sorter;
import org.lemurproject.galago.tupleflow.error.IncompatibleProcessorException;
import org.lemurproject.galago.utility.Parameters;
import org.lemurproject.galago.utility.tools.AppFunction;

import java.io.IOException;
import java.io.PrintStream;

/**
 * @author jfoley
 */
public class MergeTextIndices extends AppFunction {
  @Override
  public String getName() {
    return "merge-text-indices";
  }

  @Override
  public String getHelpString() {
    return makeHelpStr(
        "input", "map of indices to merge; e.g. --input/asr=asr.galago --input/ocr=ocr.galago",
        "output", "json per line documents to write out"
    );
  }

  public static class NFTDocumentWriter implements NameFieldText.NameFieldOrder.ShreddedProcessor {
    String name;
    String field;
    StringBuilder text;
    PrintStream out;

    public NFTDocumentWriter(String output) throws IOException {
      this.out = IO.printStream(output);
    }

    @Override
    public void processName(String name) throws IOException {
      flush();
      this.name = name;
      this.text = new StringBuilder();
    }

    @Override
    public void processField(String field) throws IOException {
      this.field = field;
    }

    @Override
    public void processTuple(String text) throws IOException {
      this.text.append("<").append(field).append(">\n")
        .append(text)
        .append("\n</").append(field).append(">\n");
    }

    public void flush() {
      if(name == null || text.length() == 0) {
        return;
      }
      Parameters doc = Parameters.create();
      doc.put("text", text.toString());
      doc.put("name", name);
      out.println(doc.toString());
    }

    @Override
    public void close() throws IOException {
      flush();
      out.close();
    }
  }

  @Override
  public void run(Parameters argp, PrintStream stdout) throws Exception {
    Parameters inputs = argp.getMap("input");

    // tiny pipeline
    try (Processor<NameFieldText> writer = textAggregator(argp.getString("output"))) {
      for (String kind : inputs.keySet()) {
        for (Document doc : GalagoUtil.documentIterable(new DiskIndex(inputs.getString(kind)), Document.DocumentComponents.JustText)) {
          NameFieldText nft = new NameFieldText();
          nft.name = doc.name;
          nft.field = kind;
          nft.text = doc.text;
          writer.process(nft);
        }
      }
    } // close pipeline
    System.err.println("# Done!");
  }

  public static Processor<NameFieldText> textAggregator(String outputFile) throws IOException, IncompatibleProcessorException {
    Sorter<NameFieldText> sorter = new Sorter<>(new NameFieldText.NameFieldOrder());
    sorter.setProcessor(new NameFieldText.NameFieldOrder.TupleShredder(new NFTDocumentWriter(outputFile)));
    return sorter;
  }
}


text:
/* global $ */

$(function () {
    'use strict';

    // layout-specific JS can go here.
    function layoutButton() {
        /* mobile nav button */
        $('#page-header .nav-btn').click(function (event) {
            event.preventDefault();
            var $nav = $('#page-header nav ul');
            $nav.toggleClass('active');
        });
    }
    layoutButton();

    function halos() {
        var haloElements = [];
        var $container = $('.header-bg-fx');

        var haloData = [
            { class: 'halo-2018 halo-orange', x: 815, y: 171, s: 147 },
            { class: 'halo-2018 halo-green', x: 531, y: 6, s: 218 },
            { class: 'halo-2018 halo-blue', x: 202, y: 87, s: 257 },
            { class: 'halo-2018 halo-purple', x: -8, y: -17, s: 220 },
        ];

        haloData.forEach(function(cd) {
            // var src = IMAGE_BASE_PATH + cd.src;
            var $halo = $('<div class="' + cd.class + '"/>');
            $halo.css('left', cd.x / 2);
            $halo.css('top', cd.y / 2);
            $halo.css('width', cd.s / 2);
            $halo.css('height', cd.s / 2);
            $container.append($halo);
            haloElements.push($halo);
        });

        document.addEventListener('mouseover', function() {
            haloElements.forEach(function(haloElement, index) {
                var val = Math.sin(new Date().valueOf() / 1000 + index);
                haloElement.css('opacity', val * 0.5 + 0.5);
            });
        }, 500);
    }
    halos();

    function backgrounds() {
        var bgElements = [
            '.layer-cyan',
            '.layer-green',
            '.layer-purple',
            '.layer-yellow'
        ].map(function(selector) {
            return $(selector);
        });

        // minimum delay between animations
        var DELAY = 2500;
        // track whether the user is interacting with the page or not
        var interacting = false;

        function update() {
            if(!interacting) {
                return;
            }
            interacting = false;
            // Using the clock for this keeps the look consistent when navigating.
            var x = new Date().valueOf() / 2000;
            bgElements.forEach(function(bgElement, index) {
                bgElement.css('opacity', 0.5 + 0.5 * Math.sin((x + index) * Math.PI / 4));
            });
        }

        function onInteraction() {
            interacting = true;
        }

        document.addEventListener('mouseover', onInteraction);
        document.addEventListener('mousedown', onInteraction);
        document.addEventListener('keydown', onInteraction);

        // Start the 2 s animation every 2+ s.
        // The transitions sometimes glitch on Firefox if the opacity
        // target value changes mid-transition.
        // The gap isn't too noticeable, especially with ease-in-out.
        setInterval(update, DELAY);
        update();
    }
    backgrounds();
});


text:
class EnchantmentInstance
{
public:
	int type;
	int level;
public:
	EnchantmentInstance(int, int);
	EnchantmentInstance();
public:
	void setEnchantType(int);
	void setEnchantLevel(int);
	int getEnchantType() const;
	int getEnchantLevel() const;
};


text:
At its simplest, this is a class that can be used to simply and easily read lines one at a time from a file.  However, it also offers the ability to tail a file (ie. wait for more data to be written to the file).

## Basic Example
An example of how to use the class is as follows:

BDFileTailer *tailer = [[BDFileTailer alloc] initWithURL:url];
NSString *line = [tailer readLine];
while (line != nil) {
	NSLog(@"Line:  %@", line);
	line = [self.tailer readLine];
}

It will continue to read lines from the file, until there are no more.  At this point, it will return a `nil`.  By default, the `NSString` objects returned will be encoded using the UTF8 encoding.

After each line, you can query the `tailer` object for one of two useful properties:

* `lastLineNumber` - The line number of the last-read line. Note that this is a 1-based index.
* `lastLineFileOffset` - The raw file offset of the start of the last-read line.  This is a 0-based index.

### Configuring Behaviour
There are several properties that can be set that will modify the way `BDFileTailer` works.

* `bufferSize` - To assist with performance, `BDFileTailer` uses an internal buffer to read data from the input file.  The default size if 4096, but it can be overridden using this property.
* `lineEndIndicator` - Allows you to define how *line-end* is recognized.  The following options are supported:
	* `BDFileTailerLineEndAuto` - Will match CR, or CRLF (this is the default)
	* `BDFileTailerLineEndOnlyCR` - A lone CR signifies line-end
	* `BDFileTailerLineEndOnlyLF` -  A lone LF signifies line-end
	* `BDFileTailerLineEndCRLF` - Needs both CR and LF for line-end
* `shouldStripLineEnds` - By default, the trailing line-end character(s) are faithfully returned as part of the returned line.  By setting this property to `YES`, the line-ends will be trimmed off.
* `encodings` - An array of `NSStringEncoding` enums that will be used to try and encode the raw data into a string.  For every line read, each encoding is attempted in succession, and the first that is able to successfully encode into an `NSString` will be used.

## Tailing a File
In addition to the properties defined above, there are two properties that can be used to enable tailing as can be seen in the example below:

BDFileTailer *tailer = [[BDFileTailer alloc] initWithURL:url];
tailer.shouldTail = YES;
tailer.tailFrequency = 1.0;
NSString *line = [tailer readLine];

When `shouldTail` is set to `YES`, calls to `readLine` or `readLineAsData` will block indefinitely until there is no more data in the file.  The `tailFrequency` property controls how often the file will be rechecked for more data (the default is every second).

To stop tailing, the `[BDFileTailer stopTailing]` method must be called on a secondary thread.

**Note:** Do not tail on the main thread, otherwise the UI thread will be blocked while waiting for more input.  It is recommended to run the tail on a background thread using gcd, `NSTask`, or any of the other many background techniques.

## Following File Renames
There are many processes (such as Apache) that start writing to a particular file and once the file exceeds a certain size or date the file is closed, renamed, and a new file is renamed with the same name as the original.

If the `shouldFollowRename` property is set, `BDFileTailer` will read any remaining lines from the renamed file, and then open the new file and start reading lines from that file.

## License
BDFileTailer is licensed under the MIT License.

	Copyright (c) 2013 Craig Edwards

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.


text:
package etcd

import (
	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/generic"
	etcdgeneric "github.com/GoogleCloudPlatform/kubernetes/pkg/registry/generic/etcd"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"

	"github.com/openshift/origin/pkg/oauth/api"
	"github.com/openshift/origin/pkg/oauth/registry/oauthclientauthorization"
)

// rest implements a RESTStorage for oauth client authorizations against etcd
type REST struct {
	etcdgeneric.Etcd
}

const EtcdPrefix = "/oauth/clientauthorizations"

// NewREST returns a RESTStorage object that will work against oauth clients
func NewREST(h tools.EtcdHelper) *REST {
	store := &etcdgeneric.Etcd{
		NewFunc:     func() runtime.Object { return &api.OAuthClientAuthorization{} },
		NewListFunc: func() runtime.Object { return &api.OAuthClientAuthorizationList{} },
		KeyRootFunc: func(ctx kapi.Context) string {
			// TODO: JTL: switch to NoNamespaceKeyRootFunc after rebase
			return EtcdPrefix
		},
		KeyFunc: func(ctx kapi.Context, name string) (string, error) {
			return etcdgeneric.NoNamespaceKeyFunc(ctx, EtcdPrefix, name)
		},
		ObjectNameFunc: func(obj runtime.Object) (string, error) {
			return obj.(*api.OAuthClientAuthorization).Name, nil
		},
		PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher {
			return oauthclientauthorization.Matcher(label, field)
		},
		EndpointName: "oauthclientauthorizations",

		Helper: h,
	}

	store.CreateStrategy = oauthclientauthorization.Strategy
	store.UpdateStrategy = oauthclientauthorization.Strategy

	return &REST{*store}
}


text:
/*
 *
 * AccountEditor
 *
 */

import { FC } from 'react'

import { buildLog } from '@/utils/logger'
import { bond } from '@/utils/mobx'
import { closeDrawer } from '@/utils/helper'

import SubmitButton from '@/widgets/Buttons/SubmitButton'
import Tooltip from '@/widgets/Tooltip'
import { Divider, SpaceGrow, Br } from '@/widgets/Common'
import OSSUploader from '@/widgets/OSSUploader'

import SexInputer from './SexInputer'
import SocialInputer from './SocialInputer'

import type { TStore } from './store'

import {
  Wrapper,
  AvatarPic,
  FormsWrapper,
  Section,
  RowSection,
  LoginSection,
  LoginDesc,
  GithubIcon,
  Label,
  SexLabel,
  Input,
  TextareaInput,
  Footer,
} from './styles'

import { useInit, inputOnChange, onUpdate } from './logic'

/* eslint-disable-next-line */
const log = buildLog('C:AccountEditor')

type TProps = {
  accountEditor?: TStore
}

const AccountEditorContainer: FC<TProps> = ({ accountEditor: store }) => {
  useInit(store)

  const { login, fromGithub, submitState, editData } = store
  const { profile } = editData

  return (
    <Wrapper className="normal-form">
      <OSSUploader onUploadDone={(url) => inputOnChange(url, 'avatar')}>
        {profile.avatar && <AvatarPic src={profile.avatar} />}
      </OSSUploader>

      <FormsWrapper>
        <LoginSection>
          登入名称
          <LoginDesc>{login}</LoginDesc>
          <SpaceGrow />
          {fromGithub && (
            <Tooltip content="使用 Github 登入" placement="bottom-end">
              <GithubIcon />
            </Tooltip>
          )}
        </LoginSection>

          我的昵称
          <Input
            value={profile.nickname}
            placeholder="// 我的昵称"
            onChange={(e) => inputOnChange(e, 'nickname')}
          />

          一句话介绍
          <Input
            value={profile.shortbio}
            placeholder="// 示例:工作@团队"
            onChange={(e) => inputOnChange(e, 'shortbio')}
          />

        <RowSection>
          <SexLabel>性别</SexLabel>
          <SexInputer value={profile.sex} />
        </RowSection>

          关于我
          <TextareaInput
            value={profile.bio}
            placeholder="// 更多介绍"
            behavior="textarea"
            onChange={(e) => inputOnChange(e, 'bio')}
          />

        <Divider top={0} bottom={30} />
        <SocialInputer editData={editData} />
        <Divider bottom={30} />

          <SubmitButton
            submitState={submitState}
            okText="更 新"
            onPublish={onUpdate}
            onCancel={closeDrawer}
            withCancel
          />

      </FormsWrapper>
    </Wrapper>
  )
}

export default bond(AccountEditorContainer, 'accountEditor') as FC<TProps>


text:
namespace blink {

class WebNodeTest : public testing::Test {
protected:
    Document& document() { return m_pageHolder->document(); }

private:
    void SetUp() override;

    OwnPtr<DummyPageHolder> m_pageHolder;
};

void WebNodeTest::SetUp()
{
    m_pageHolder = DummyPageHolder::create(IntSize(800, 600));
}

TEST_F(WebNodeTest, GetElementsByHTMLTagName)
{
    document().documentElement()->setInnerHTML("<svg xmlns='http://www.w3.org/2000/svg'></svg>", ASSERT_NO_EXCEPTION);
    WebNode node(document().documentElement());
    // WebNode::getElementsByHTMLTagName returns only HTML elements.
    WebElementCollection collection = node.getElementsByHTMLTagName("label");
    EXPECT_EQ(1u, collection.length());
    EXPECT_TRUE(collection.firstItem().hasHTMLTagName("label"));
    // The argument should be lower-case.
    collection = node.getElementsByHTMLTagName("LABEL");
    EXPECT_EQ(0u, collection.length());
}

} // namespace blink


text:
package com.intellij.platform.renameProject;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

/**
 * @author lene
 */
public class RenameProjectAction extends DumbAwareAction {

  public RenameProjectAction() {
    super(RefactoringBundle.lazyMessage("rename.project.action.title"),
          RefactoringBundle.lazyMessage("renames.project"), null);
  }

  private static final Logger LOG = Logger.getInstance(RenameProjectAction.class);

  @Override
  public void update(@NotNull AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    e.getPresentation().setEnabled(project != null && !project.isDefault());
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    LOG.assertTrue(project instanceof ProjectEx);
    final Module[] modules = ModuleManager.getInstance(project).getModules();
    final Module module = ContainerUtil.find(modules, module1 -> project.getName().equals(module1.getName()));
    Messages.showInputDialog(project, RefactoringBundle.message("enter.new.project.name"), RefactoringBundle.message("rename.project"),
                             Messages.getQuestionIcon(),
                             project.getName(),
                             new RenameProjectHandler.MyInputValidator((ProjectEx)project, module));
  }
}


text:
package com.twelvemonkeys.lang;

/**
 * MostUnfortunateException
 *

 *
 * @author Harald Kuhr
 * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java#1 $
 */
class MostUnfortunateException extends RuntimeException {
    public MostUnfortunateException() {
        this("Most unfortunate.");
    }

    public MostUnfortunateException(Throwable pCause) {
        this(pCause.getMessage(), pCause);
    }

    public MostUnfortunateException(String pMessage, Throwable pCause) {
        this(pMessage);
        initCause(pCause);
    }

    public MostUnfortunateException(String pMessage) {
        super("A most unfortunate exception has occured: " + pMessage);
    }
}


text:
// Copyright © Microsoft Open Technologies, Inc.
//
// All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.

package com.microsoft.aad.adal;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

/**
 * Extended result to store more info Queries will be performed over this item
 * not the key.
 */
public class TokenCacheItem implements Serializable {

    /**
     * Serial version.
     */
    private static final long serialVersionUID = 1L;

    private static final String TAG = "TokenCacheItem";

    private UserInfo mUserInfo;

    private String mResource;

    private String mAuthority;

    private String mClientId;

    private String mAccessToken;

    private String mRefreshtoken;

    private String mRawIdToken;

    /**
     * This time is GMT.
     */
    private Date mExpiresOn;

    private boolean mIsMultiResourceRefreshToken;

    private String mTenantId;

    /**
     * Construct default cache item.
     */
    public TokenCacheItem() {

    }

    TokenCacheItem(final AuthenticationRequest request, final AuthenticationResult result,
            boolean storeMultiResourceRefreshToken) {
        if (request != null) {
            mAuthority = request.getAuthority();
            mClientId = request.getClientId();
            if (!storeMultiResourceRefreshToken) {
                // Cache item will not store resource info for Multi Resource
                // Refresh Token
                mResource = request.getResource();
            }
        }

        if (result != null) {
            mRefreshtoken = result.getRefreshToken();
            mExpiresOn = result.getExpiresOn();
            mIsMultiResourceRefreshToken = storeMultiResourceRefreshToken;
            mTenantId = result.getTenantId();
            mUserInfo = result.getUserInfo();
            mRawIdToken = result.getIdToken();
            if (!storeMultiResourceRefreshToken) {
                // Cache item will not store accesstoken for Multi
                // Resource Refresh Token
                mAccessToken = result.getAccessToken();
            }
        }
    }

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public void setUserInfo(UserInfo info) {
        this.mUserInfo = info;
    }

    public String getResource() {
        return mResource;
    }

    public void setResource(String resource) {
        this.mResource = resource;
    }

    public String getAuthority() {
        return mAuthority;
    }

    public void setAuthority(String authority) {
        this.mAuthority = authority;
    }

    public String getClientId() {
        return mClientId;
    }

    public void setClientId(String clientId) {
        this.mClientId = clientId;
    }

    public String getAccessToken() {
        return mAccessToken;
    }

    public void setAccessToken(String accessToken) {
        this.mAccessToken = accessToken;
    }

    public String getRefreshToken() {
        return mRefreshtoken;
    }

    public void setRefreshToken(String refreshToken) {
        this.mRefreshtoken = refreshToken;
    }

    public Date getExpiresOn() {
        return mExpiresOn;
    }

    public void setExpiresOn(Date expiresOn) {
        this.mExpiresOn = expiresOn;
    }

    public boolean getIsMultiResourceRefreshToken() {
        return mIsMultiResourceRefreshToken;
    }

    public void setIsMultiResourceRefreshToken(boolean isMultiResourceRefreshToken) {
        this.mIsMultiResourceRefreshToken = isMultiResourceRefreshToken;
    }

    public String getTenantId() {
        return mTenantId;
    }

    public void setTenantId(String tenantId) {
        this.mTenantId = tenantId;
    }

    public String getRawIdToken() {
        return mRawIdToken;
    }

    public void setRawIdToken(String rawIdToken) {
        this.mRawIdToken = rawIdToken;
    }

    /**
     * Checks expiration time.
     *
     * @return true if expired
     */
    public static boolean isTokenExpired(Date expiresOn) {
        Calendar calendarWithBuffer = Calendar.getInstance();
        calendarWithBuffer.add(Calendar.SECOND,
                AuthenticationSettings.INSTANCE.getExpirationBuffer());
        Date validity = calendarWithBuffer.getTime();
        Logger.v(TAG, "expiresOn:" + expiresOn + " timeWithBuffer:" + calendarWithBuffer.getTime()
                + " Buffer:" + AuthenticationSettings.INSTANCE.getExpirationBuffer());

        if (expiresOn != null && expiresOn.before(validity)) {
            return true;
        }

        return false;
    }
}


text:
'use strict';
var DEBUG = true;

/* App Module */
var myApplicationModule = myApplicationModule || angular.module('myApplicationModule', [
    'uiGmapgoogle-maps',
    'geolocation',
    'ngRoute',
    'ui.bootstrap',
    'PegelAlarm',
    'myControllers'
]);

myApplicationModule.config(function ($routeProvider) {
    $routeProvider.when('/home',
    {
      templateUrl:    'view/home.html',
    });

    $routeProvider.when('/contact',
    {
      templateUrl:    'view/contact.html',
    });
    $routeProvider.otherwise(
    {
      redirectTo:     '/home'
    });
});
myApplicationModule.config(function(uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
        key: 'AIzaSyCbfQaCBu2uOqS49CHqIqhp4lZ1s_X3bFI',
        v: '3.20', //defaults to latest 3.X anyhow
        libraries: 'weather,geometry,visualization'
    });
});

// myApplicationModule.directive('contentfill', function ($window) {
//     return {
//         restrict: 'A',
//         link: function (scope, elem, attrs) {
//             var winHeight = $window.innerHeight;
//             var otherElements = 170 + 30;
//             elem.css('height', winHeight - otherElements + 'px');
//         }
//     };
// });


text:
Rails.application.routes.draw do

  mount ColorboxRails::Engine => "/colorbox-rails"
end