text:
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org>               //
//  available at http://getid3.sourceforge.net                 //
//            or http://www.getid3.org                         //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details                             //
/////////////////////////////////////////////////////////////////
//                                                             //
// module.archive.zip.php                                      //
// module for analyzing pkZip files                            //
// dependencies: NONE                                          //
//                                                            ///
/////////////////////////////////////////////////////////////////

class getid3_zip extends getid3_handler
{

	function Analyze() {
		$info = &$this->getid3->info;

		$info['fileformat']      = 'zip';
		$info['zip']['encoding'] = 'ISO-8859-1';
		$info['zip']['files']    = array();

		$info['zip']['compressed_size']   = 0;
		$info['zip']['uncompressed_size'] = 0;
		$info['zip']['entries_count']     = 0;

		if (!getid3_lib::intValueSupported($info['filesize'])) {
			$info['error'][] = 'File is larger than '.round(PHP_INT_MAX / 1073741824).'GB, not supported by PHP';
			return false;
		} else {
			$EOCDsearchData    = '';
			$EOCDsearchCounter = 0;
			while ($EOCDsearchCounter++ < 512) {

				fseek($this->getid3->fp, -128 * $EOCDsearchCounter, SEEK_END);
				$EOCDsearchData = fread($this->getid3->fp, 128).$EOCDsearchData;

				if (strstr($EOCDsearchData, 'PK'."\x05\x06")) {

					$EOCDposition = strpos($EOCDsearchData, 'PK'."\x05\x06");
					fseek($this->getid3->fp, (-128 * $EOCDsearchCounter) + $EOCDposition, SEEK_END);
					$info['zip']['end_central_directory'] = $this->ZIPparseEndOfCentralDirectory();

					fseek($this->getid3->fp, $info['zip']['end_central_directory']['directory_offset'], SEEK_SET);
					$info['zip']['entries_count'] = 0;
					while ($centraldirectoryentry = $this->ZIPparseCentralDirectory($this->getid3->fp)) {
						$info['zip']['central_directory'][] = $centraldirectoryentry;
						$info['zip']['entries_count']++;
						$info['zip']['compressed_size']   += $centraldirectoryentry['compressed_size'];
						$info['zip']['uncompressed_size'] += $centraldirectoryentry['uncompressed_size'];

						if ($centraldirectoryentry['uncompressed_size'] > 0) {
							$info['zip']['files'] = getid3_lib::array_merge_clobber($info['zip']['files'], getid3_lib::CreateDeepArray($centraldirectoryentry['filename'], '/', $centraldirectoryentry['uncompressed_size']));
						}
					}

					if ($info['zip']['entries_count'] == 0) {
						$info['error'][] = 'No Central Directory entries found (truncated file?)';
						return false;
					}

					if (!empty($info['zip']['end_central_directory']['comment'])) {
						$info['zip']['comments']['comment'][] = $info['zip']['end_central_directory']['comment'];
					}

					if (isset($info['zip']['central_directory'][0]['compression_method'])) {
						$info['zip']['compression_method'] = $info['zip']['central_directory'][0]['compression_method'];
					}
					if (isset($info['zip']['central_directory'][0]['flags']['compression_speed'])) {
						$info['zip']['compression_speed']  = $info['zip']['central_directory'][0]['flags']['compression_speed'];
					}
					if (isset($info['zip']['compression_method']) && ($info['zip']['compression_method'] == 'store') && !isset($info['zip']['compression_speed'])) {
						$info['zip']['compression_speed']  = 'store';
					}

					return true;

				}
			}
		}

		if ($this->getZIPentriesFilepointer()) {

			// central directory couldn't be found and/or parsed
			// scan through actual file data entries, recover as much as possible from probable trucated file
			if ($info['zip']['compressed_size'] > ($info['filesize'] - 46 - 22)) {
				$info['error'][] = 'Warning: Truncated file! - Total compressed file sizes ('.$info['zip']['compressed_size'].' bytes) is greater than filesize minus Central Directory and End Of Central Directory structures ('.($info['filesize'] - 46 - 22).' bytes)';
			}
			$info['error'][] = 'Cannot find End Of Central Directory - returned list of files in [zip][entries] array may not be complete';
			foreach ($info['zip']['entries'] as $key => $valuearray) {
				$info['zip']['files'][$valuearray['filename']] = $valuearray['uncompressed_size'];
			}
			return true;

		} else {

			unset($info['zip']);
			$info['fileformat'] = '';
			$info['error'][] = 'Cannot find End Of Central Directory (truncated file?)';
			return false;

		}
	}

	function getZIPHeaderFilepointerTopDown() {
		$info = &$this->getid3->info;

		$info['fileformat'] = 'zip';

		$info['zip']['compressed_size']   = 0;
		$info['zip']['uncompressed_size'] = 0;
		$info['zip']['entries_count']     = 0;

		rewind($this->getid3->fp);
		while ($fileentry = $this->ZIPparseLocalFileHeader()) {
			$info['zip']['entries'][] = $fileentry;
			$info['zip']['entries_count']++;
		}
		if ($info['zip']['entries_count'] == 0) {
			$info['error'][] = 'No Local File Header entries found';
			return false;
		}

		$info['zip']['entries_count']     = 0;
		while ($centraldirectoryentry = $this->ZIPparseCentralDirectory($this->getid3->fp)) {
			$info['zip']['central_directory'][] = $centraldirectoryentry;
			$info['zip']['entries_count']++;
			$info['zip']['compressed_size']   += $centraldirectoryentry['compressed_size'];
			$info['zip']['uncompressed_size'] += $centraldirectoryentry['uncompressed_size'];
		}
		if ($info['zip']['entries_count'] == 0) {
			$info['error'][] = 'No Central Directory entries found (truncated file?)';
			return false;
		}

		if ($EOCD = $this->ZIPparseEndOfCentralDirectory()) {
			$info['zip']['end_central_directory'] = $EOCD;
		} else {
			$info['error'][] = 'No End Of Central Directory entry found (truncated file?)';
			return false;
		}

		if (!empty($info['zip']['end_central_directory']['comment'])) {
			$info['zip']['comments']['comment'][] = $info['zip']['end_central_directory']['comment'];
		}

		return true;
	}

	function getZIPentriesFilepointer() {
		$info = &$this->getid3->info;

		$info['zip']['compressed_size']   = 0;
		$info['zip']['uncompressed_size'] = 0;
		$info['zip']['entries_count']     = 0;

		rewind($this->getid3->fp);
		while ($fileentry = $this->ZIPparseLocalFileHeader()) {
			$info['zip']['entries'][] = $fileentry;
			$info['zip']['entries_count']++;
			$info['zip']['compressed_size']   += $fileentry['compressed_size'];
			$info['zip']['uncompressed_size'] += $fileentry['uncompressed_size'];
		}
		if ($info['zip']['entries_count'] == 0) {
			$info['error'][] = 'No Local File Header entries found';
			return false;
		}

		return true;
	}

	function ZIPparseLocalFileHeader() {
		$LocalFileHeader['offset'] = ftell($this->getid3->fp);

		$ZIPlocalFileHeader = fread($this->getid3->fp, 30);

		$LocalFileHeader['raw']['signature']          = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  0, 4));
		if ($LocalFileHeader['raw']['signature'] != 0x04034B50) {
			// invalid Local File Header Signature
			fseek($this->getid3->fp, $LocalFileHeader['offset'], SEEK_SET); // seek back to where filepointer originally was so it can be handled properly
			return false;
		}
		$LocalFileHeader['raw']['extract_version']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  4, 2));
		$LocalFileHeader['raw']['general_flags']      = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  6, 2));
		$LocalFileHeader['raw']['compression_method'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  8, 2));
		$LocalFileHeader['raw']['last_mod_file_time'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 10, 2));
		$LocalFileHeader['raw']['last_mod_file_date'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 12, 2));
		$LocalFileHeader['raw']['crc_32']             = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 14, 4));
		$LocalFileHeader['raw']['compressed_size']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 18, 4));
		$LocalFileHeader['raw']['uncompressed_size']  = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 22, 4));
		$LocalFileHeader['raw']['filename_length']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 26, 2));
		$LocalFileHeader['raw']['extra_field_length'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 28, 2));

		$LocalFileHeader['extract_version']           = sprintf('%1.1f', $LocalFileHeader['raw']['extract_version'] / 10);
		$LocalFileHeader['host_os']                   = $this->ZIPversionOSLookup(($LocalFileHeader['raw']['extract_version'] & 0xFF00) >> 8);
		$LocalFileHeader['compression_method']        = $this->ZIPcompressionMethodLookup($LocalFileHeader['raw']['compression_method']);
		$LocalFileHeader['compressed_size']           = $LocalFileHeader['raw']['compressed_size'];
		$LocalFileHeader['uncompressed_size']         = $LocalFileHeader['raw']['uncompressed_size'];
		$LocalFileHeader['flags']                     = $this->ZIPparseGeneralPurposeFlags($LocalFileHeader['raw']['general_flags'], $LocalFileHeader['raw']['compression_method']);
		$LocalFileHeader['last_modified_timestamp']   = $this->DOStime2UNIXtime($LocalFileHeader['raw']['last_mod_file_date'], $LocalFileHeader['raw']['last_mod_file_time']);

		$FilenameExtrafieldLength = $LocalFileHeader['raw']['filename_length'] + $LocalFileHeader['raw']['extra_field_length'];
		if ($FilenameExtrafieldLength > 0) {
			$ZIPlocalFileHeader .= fread($this->getid3->fp, $FilenameExtrafieldLength);

			if ($LocalFileHeader['raw']['filename_length'] > 0) {
				$LocalFileHeader['filename']                = substr($ZIPlocalFileHeader, 30, $LocalFileHeader['raw']['filename_length']);
			}
			if ($LocalFileHeader['raw']['extra_field_length'] > 0) {
				$LocalFileHeader['raw']['extra_field_data'] = substr($ZIPlocalFileHeader, 30 + $LocalFileHeader['raw']['filename_length'], $LocalFileHeader['raw']['extra_field_length']);
			}
		}

		$LocalFileHeader['data_offset'] = ftell($this->getid3->fp);
		//$LocalFileHeader['compressed_data'] = fread($this->getid3->fp, $LocalFileHeader['raw']['compressed_size']);
		fseek($this->getid3->fp, $LocalFileHeader['raw']['compressed_size'], SEEK_CUR);

		if ($LocalFileHeader['flags']['data_descriptor_used']) {
			$DataDescriptor = fread($this->getid3->fp, 12);
			$LocalFileHeader['data_descriptor']['crc_32']            = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  0, 4));
			$LocalFileHeader['data_descriptor']['compressed_size']   = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  4, 4));
			$LocalFileHeader['data_descriptor']['uncompressed_size'] = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  8, 4));
		}

		return $LocalFileHeader;
	}

	function ZIPparseCentralDirectory() {
		$CentralDirectory['offset'] = ftell($this->getid3->fp);

		$ZIPcentralDirectory = fread($this->getid3->fp, 46);

		$CentralDirectory['raw']['signature']            = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  0, 4));
		if ($CentralDirectory['raw']['signature'] != 0x02014B50) {
			// invalid Central Directory Signature
			fseek($this->getid3->fp, $CentralDirectory['offset'], SEEK_SET); // seek back to where filepointer originally was so it can be handled properly
			return false;
		}
		$CentralDirectory['raw']['create_version']       = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  4, 2));
		$CentralDirectory['raw']['extract_version']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  6, 2));
		$CentralDirectory['raw']['general_flags']        = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  8, 2));
		$CentralDirectory['raw']['compression_method']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 10, 2));
		$CentralDirectory['raw']['last_mod_file_time']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 12, 2));
		$CentralDirectory['raw']['last_mod_file_date']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 14, 2));
		$CentralDirectory['raw']['crc_32']               = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 16, 4));
		$CentralDirectory['raw']['compressed_size']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 20, 4));
		$CentralDirectory['raw']['uncompressed_size']    = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 24, 4));
		$CentralDirectory['raw']['filename_length']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 28, 2));
		$CentralDirectory['raw']['extra_field_length']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 30, 2));
		$CentralDirectory['raw']['file_comment_length']  = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 32, 2));
		$CentralDirectory['raw']['disk_number_start']    = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 34, 2));
		$CentralDirectory['raw']['internal_file_attrib'] = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 36, 2));
		$CentralDirectory['raw']['external_file_attrib'] = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 38, 4));
		$CentralDirectory['raw']['local_header_offset']  = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 42, 4));

		$CentralDirectory['entry_offset']              = $CentralDirectory['raw']['local_header_offset'];
		$CentralDirectory['create_version']            = sprintf('%1.1f', $CentralDirectory['raw']['create_version'] / 10);
		$CentralDirectory['extract_version']           = sprintf('%1.1f', $CentralDirectory['raw']['extract_version'] / 10);
		$CentralDirectory['host_os']                   = $this->ZIPversionOSLookup(($CentralDirectory['raw']['extract_version'] & 0xFF00) >> 8);
		$CentralDirectory['compression_method']        = $this->ZIPcompressionMethodLookup($CentralDirectory['raw']['compression_method']);
		$CentralDirectory['compressed_size']           = $CentralDirectory['raw']['compressed_size'];
		$CentralDirectory['uncompressed_size']         = $CentralDirectory['raw']['uncompressed_size'];
		$CentralDirectory['flags']                     = $this->ZIPparseGeneralPurposeFlags($CentralDirectory['raw']['general_flags'], $CentralDirectory['raw']['compression_method']);
		$CentralDirectory['last_modified_timestamp']   = $this->DOStime2UNIXtime($CentralDirectory['raw']['last_mod_file_date'], $CentralDirectory['raw']['last_mod_file_time']);

		$FilenameExtrafieldCommentLength = $CentralDirectory['raw']['filename_length'] + $CentralDirectory['raw']['extra_field_length'] + $CentralDirectory['raw']['file_comment_length'];
		if ($FilenameExtrafieldCommentLength > 0) {
			$FilenameExtrafieldComment = fread($this->getid3->fp, $FilenameExtrafieldCommentLength);

			if ($CentralDirectory['raw']['filename_length'] > 0) {
				$CentralDirectory['filename']                  = substr($FilenameExtrafieldComment, 0, $CentralDirectory['raw']['filename_length']);
			}
			if ($CentralDirectory['raw']['extra_field_length'] > 0) {
				$CentralDirectory['raw']['extra_field_data']   = substr($FilenameExtrafieldComment, $CentralDirectory['raw']['filename_length'], $CentralDirectory['raw']['extra_field_length']);
			}
			if ($CentralDirectory['raw']['file_comment_length'] > 0) {
				$CentralDirectory['file_comment']              = substr($FilenameExtrafieldComment, $CentralDirectory['raw']['filename_length'] + $CentralDirectory['raw']['extra_field_length'], $CentralDirectory['raw']['file_comment_length']);
			}
		}

		return $CentralDirectory;
	}

	function ZIPparseEndOfCentralDirectory() {
		$EndOfCentralDirectory['offset'] = ftell($this->getid3->fp);

		$ZIPendOfCentralDirectory = fread($this->getid3->fp, 22);

		$EndOfCentralDirectory['signature']                   = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  0, 4));
		if ($EndOfCentralDirectory['signature'] != 0x06054B50) {
			// invalid End Of Central Directory Signature
			fseek($this->getid3->fp, $EndOfCentralDirectory['offset'], SEEK_SET); // seek back to where filepointer originally was so it can be handled properly
			return false;
		}
		$EndOfCentralDirectory['disk_number_current']         = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  4, 2));
		$EndOfCentralDirectory['disk_number_start_directory'] = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  6, 2));
		$EndOfCentralDirectory['directory_entries_this_disk'] = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  8, 2));
		$EndOfCentralDirectory['directory_entries_total']     = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 10, 2));
		$EndOfCentralDirectory['directory_size']              = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 12, 4));
		$EndOfCentralDirectory['directory_offset']            = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 16, 4));
		$EndOfCentralDirectory['comment_length']              = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 20, 2));

		if ($EndOfCentralDirectory['comment_length'] > 0) {
			$EndOfCentralDirectory['comment']                 = fread($this->getid3->fp, $EndOfCentralDirectory['comment_length']);
		}

		return $EndOfCentralDirectory;
	}

	static function ZIPparseGeneralPurposeFlags($flagbytes, $compressionmethod) {
		$ParsedFlags['encrypted'] = (bool) ($flagbytes & 0x0001);

		switch ($compressionmethod) {
			case 6:
				$ParsedFlags['dictionary_size']    = (($flagbytes & 0x0002) ? 8192 : 4096);
				$ParsedFlags['shannon_fano_trees'] = (($flagbytes & 0x0004) ? 3    : 2);
				break;

			case 8:
			case 9:
				switch (($flagbytes & 0x0006) >> 1) {
					case 0:
						$ParsedFlags['compression_speed'] = 'normal';
						break;
					case 1:
						$ParsedFlags['compression_speed'] = 'maximum';
						break;
					case 2:
						$ParsedFlags['compression_speed'] = 'fast';
						break;
					case 3:
						$ParsedFlags['compression_speed'] = 'superfast';
						break;
				}
				break;
		}
		$ParsedFlags['data_descriptor_used']       = (bool) ($flagbytes & 0x0008);

		return $ParsedFlags;
	}

	static function ZIPversionOSLookup($index) {
		static $ZIPversionOSLookup = array(
		0  => 'MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)',
		1  => 'Amiga',
		2  => 'OpenVMS',
		3  => 'Unix',
		4  => 'VM/CMS',
		5  => 'Atari ST',
		6  => 'OS/2 H.P.F.S.',
		7  => 'Macintosh',
		8  => 'Z-System',
		9  => 'CP/M',
		10 => 'Windows NTFS',
		11 => 'MVS',
		12 => 'VSE',
		13 => 'Acorn Risc',
		14 => 'VFAT',
		15 => 'Alternate MVS',
		16 => 'BeOS',
		17 => 'Tandem'
		);

		return (isset($ZIPversionOSLookup[$index]) ? $ZIPversionOSLookup[$index] : '[unknown]');
	}

	static function ZIPcompressionMethodLookup($index) {
		static $ZIPcompressionMethodLookup = array(
		0  => 'store',
		1  => 'shrink',
		2  => 'reduce-1',
		3  => 'reduce-2',
		4  => 'reduce-3',
		5  => 'reduce-4',
		6  => 'implode',
		7  => 'tokenize',
		8  => 'deflate',
		9  => 'deflate64',
		10 => 'PKWARE Date Compression Library Imploding'
		);

		return (isset($ZIPcompressionMethodLookup[$index]) ? $ZIPcompressionMethodLookup[$index] : '[unknown]');
	}

	static function DOStime2UNIXtime($DOSdate, $DOStime) {
		// wFatDate
		// Specifies the MS-DOS date. The date is a packed 16-bit value with the following format:
		// Bits      Contents
		// 0-4    Day of the month (1-31)
		// 5-8    Month (1 = January, 2 = February, and so on)
		// 9-15   Year offset from 1980 (add 1980 to get actual year)

		$UNIXday    =  ($DOSdate & 0x001F);
		$UNIXmonth  = (($DOSdate & 0x01E0) >> 5);
		$UNIXyear   = (($DOSdate & 0xFE00) >> 9) + 1980;

		// wFatTime
		// Specifies the MS-DOS time. The time is a packed 16-bit value with the following format:
		// Bits   Contents
		// 0-4    Second divided by 2
		// 5-10   Minute (0-59)
		// 11-15  Hour (0-23 on a 24-hour clock)

		$UNIXsecond =  ($DOStime & 0x001F) * 2;
		$UNIXminute = (($DOStime & 0x07E0) >> 5);
		$UNIXhour   = (($DOStime & 0xF800) >> 11);

		return gmmktime($UNIXhour, $UNIXminute, $UNIXsecond, $UNIXmonth, $UNIXday, $UNIXyear);
	}

}

?>


text:
package org.apereo.portal.layout;

import java.util.Enumeration;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import org.apereo.portal.PortalException;
import org.apereo.portal.layout.node.IUserLayoutNodeDescription;
import org.apereo.portal.layout.node.IUserLayoutNodeDescription.LayoutNodeType;
import org.w3c.dom.Document;

/**
 * An interface for abstracting operations performed on the user layout.
 */
public interface IUserLayoutManager {
    /** Represents a <folder> layout element */
    public static final String FOLDER = "folder";
    /** Represents <channel> layout element */
    public static final String CHANNEL = "channel";
    /** Represents <channel-header> layout element */
    public static final String CHANNEL_HEADER = "channel-header";
    /** Represents <parameter> layout element */
    public static final String PARAMETER = "parameter";
    /** Represents an ID element attribute */
    public static final String ID_ATTR = "ID";

    public static final QName ID_ATTR_NAME = new QName(ID_ATTR);

    /**
     * Gets a user layout (with appropriate markings).
     *
     * @return the user layout
     * @exception PortalException if an error occurs
     */
    public IUserLayout getUserLayout() throws PortalException;

    /** @return An XMLEventReader for the user's layout structure */
    public XMLEventReader getUserLayoutReader();

    /** Calls {@link #loadUserLayout(boolean)} passing false. */
    public void loadUserLayout() throws PortalException;

    /**
     * Signal manager to load a user layout.
     *
     * @param reload If true the reload will be forced, purging any cached data.
     * @throws PortalException PortalException if an error occurs
     */
    public void loadUserLayout(boolean reload) throws PortalException;

    /**
     * Signal manager to persist user layout to a database
     *
     * @exception PortalException if an error occurs
     */
    public void saveUserLayout() throws PortalException;

    /** @return The set of all channels the user is subscribed to */
    public Set<String> getAllSubscribedChannels();

    /**
     * Obtain a description of a node (channel or a folder) in a given user layout.
     *
     * @param nodeId a String channel subscribe id or folder id.
     * @return an UserLayoutNodeDescription value
     * @exception PortalException if an error occurs
     */
    public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException;

    /**
     * Add a new node to a current user layout.
     *
     * @param node an UserLayoutNodeDescription value of a node to be added (Id doesn't
     *     have to be set)
     * @param parentId a String id of a folder to which the new node (channel or
     *     folder) should be added.
     * @param nextSiblingId a String an id of a sibling node (channel or folder) prior
     *     to which the new node should be inserted.
     * @return an UserLayoutNodeDescription value with a newly determined Id.
     * @exception PortalException if an error occurs
     */
    public IUserLayoutNodeDescription addNode(
            IUserLayoutNodeDescription node, String parentId, String nextSiblingId)
            throws PortalException;

    /**
     * Move a node (channel or folder) from one location to another.
     *
     * @param nodeId a String value of a node Id.
     * @param parentId a String id of a folder to which the node should be moved.
     * @param nextSiblingId a String id of a sibling node (folder or channel) prior to
     *     which the node should be placed. (null to append at the end)
     * @return a boolean value noting if the operation was successful
     * @exception PortalException if an error occurs
     */
    public boolean moveNode(String nodeId, String parentId, String nextSiblingId)
            throws PortalException;

    /**
     * Delete a node (folder or a channel) from a user layout.
     *
     * @param nodeId a String id (channel subscribe id or folder id)
     * @return a boolean value noting if the operation was successful
     * @exception PortalException if an error occurs
     */
    public boolean deleteNode(String nodeId) throws PortalException;

    /**
     * Update a given node.
     *
     * @param node an UserLayoutNodeDescription value with a valid id.
     * @return a boolean value noting if the operation was successful
     * @exception PortalException if an error occurs
     */
    public boolean updateNode(IUserLayoutNodeDescription node) throws PortalException;

    /**
     * Test if a particular node can be added at a given location.
     *
     * @param node an UserLayoutNodeDescription value describing the node to be added.
     * @param parentId a String id of a parent to which the node to be added.
     * @param nextSiblingId a String id of a sibling prior to which the node to be
     *     inserted. (null to append at the end)
     * @return a boolean value
     * @exception PortalException if an error occurs
     */
    public boolean canAddNode(
            IUserLayoutNodeDescription node, String parentId, String nextSiblingId)
            throws PortalException;

    /**
     * Test if a particular node can be moved to a given location.
     *
     * @param nodeId a String id of a node to be moved.
     * @param parentId a String id of a parent to which the node to be moved.
     * @param nextSiblingId a String id of a sibling prior to which the node is to be
     *     inserted (null to append at the end)
     * @return a boolean value
     * @exception PortalException if an error occurs
     */
    public boolean canMoveNode(String nodeId, String parentId, String nextSiblingId)
            throws PortalException;

    /**
     * Tests if a particular node can be deleted.
     *
     * @param nodeId a String node id.
     * @return a boolean value
     * @exception PortalException if an error occurs
     */
    public boolean canDeleteNode(String nodeId) throws PortalException;

    /**
     * Test if a certain node can be updated.
     *
     * @param node a IUserLayoutNodeDescription node id.
     * @return a boolean value
     * @exception PortalException if an error occurs
     */
    public boolean canUpdateNode(IUserLayoutNodeDescription node) throws PortalException;

    /**
     * Ask manager to output markings at the locations where a given node can be added. The marks
     * will appear next time getUserLayout method is called.
     *
     * @param node an UserLayoutNodeDescription value or null to stop
     *     outputting add markings.
     * @exception PortalException if an error occurs
     */
    public void markAddTargets(IUserLayoutNodeDescription node) throws PortalException;

    /**
     * Ask manager to output markings at the locations where a given node can be moved. The marks
     * will appear next time getUserLayout method is called.
     *
     * @param nodeId a String value or null to stop outputting move
     *     markings.
     * @exception PortalException if an error occurs
     */
    public void markMoveTargets(String nodeId) throws PortalException;

    /**
     * Returns an Id of a parent user layout node. The user layout root node always has ID= {@link
     * IUserLayout#ROOT_NODE_NAME}
     *
     * @param nodeId a String value
     * @return a String value
     * @exception PortalException if an error occurs
     */
    public String getParentId(String nodeId) throws PortalException;

    /**
     * Returns a list of child node Ids for a given node.
     *
     * @param nodeId a String value
     * @return a List of String child node Ids.
     * @exception PortalException if an error occurs
     */
    public Enumeration<String> getChildIds(String nodeId) throws PortalException;

    /**
     * Determine an Id of a next sibling node.
     *
     * @param nodeId a String value
     * @return a String Id value of a next sibling node, or null if this
     *     is the last sibling.
     * @exception PortalException if an error occurs
     */
    public String getNextSiblingId(String nodeId) throws PortalException;

    /**
     * Determine an Id of a previous sibling node.
     *
     * @param nodeId a String value
     * @return a String Id value of a previous sibling node, or null if
     *     this is the first sibling.
     * @exception PortalException if an error occurs
     */
    public String getPreviousSiblingId(String nodeId) throws PortalException;

    /**
     * Return a cache key, uniquely corresponding to the composition and the structure of the user
     * layout.
     *
     * @return a String value
     * @exception PortalException if an error occurs
     */
    public String getCacheKey() throws PortalException;

    /**
     * @deprecated {@link #getUserLayout()} should be used instead. Direct manipulation of the DOM
     *     can cause caching problems and issues where the layout manager doesn't know about DOM
     *     changes. Read https://lists.wisc.edu/read/messages?id=2167043 for more information.
     */
    @Deprecated
    public Document getUserLayoutDOM() throws PortalException;

    /**
     * Returns a layout Id associated with this manager/
     *
     * @return an int layout Id value;
     */
    public int getLayoutId();

    /**
     * Returns a subscription id using the supplied functional name.
     *
     * @param fname the functional name to lookup
     * @return a String subscription id
     */
    public String getSubscribeId(String fname) throws PortalException;

    /**
     * Returns a subscription id using the supplied functional name if it exists under the specified
     * parent folder
     *
     * @param parentFolderId The id of the parent folder to look under
     * @param fname the functional name to lookup
     * @return a String subscription id, null if the fname does not exist under the
     *     specified folder id.
     */
    public String getSubscribeId(String parentFolderId, String fname);

    /**
     * Returns an id of the root folder.
     *
     * @return a String value
     */
    public String getRootFolderId();

    /**
     * Returns the depth of a node in the layout tree.
     *
     * @param nodeId a String value
     * @return a depth value
     * @exception PortalException if an error occurs
     */
    public int getDepth(String nodeId) throws PortalException;

    /**
     * A factory method to create an empty IUserLayoutNodeDescription instance
     *
     * @param nodeType a node type constant from IUserLayoutNodeDescription interface
     * @return an IUserLayoutNodeDescription instance
     * @exception PortalException if the error occurs.
     */
    public IUserLayoutNodeDescription createNodeDescription(LayoutNodeType nodeType)
            throws PortalException;
}

redpajama_set_name: RedPajamaGithub


text:
#import "CDVMailCore2.h"
#include <MailCore/MailCore.h>

@implementation CDVMailCore2

- (void)cordovaSendMail:(CDVInvokedUrlCommand*)command
{
	self.callbackId = command.callbackId;

	NSDictionary* options = command.arguments[0];

	NSString *fromName = [options objectForKey:@"fromName"];
	NSString *fromEmail = [options objectForKey:@"fromEmail"];
	NSString *toName = [options objectForKey:@"toName"];
	NSString *toEmail = [options objectForKey:@"toEmail"];
	NSString *replyEmail = [options objectForKey:@"replyEmail"];
	NSString *smtpServer = [options objectForKey:@"smtpServer"];
	int smtpPort = [[options objectForKey:@"smtpPort"] intValue];
	NSString *smtpUsername = [options objectForKey:@"smtpUserName"];
	NSString *smtpPassword = [options objectForKey:@"smtpPassword"];
	NSString *textSubject = [options objectForKey:@"textSubject"];
	NSString *textBody = [options objectForKey:@"textBody"];
	NSString *textAttachment = [options objectForKey:@"textAttachment"];
  bool connectionLogger = [[options objectForKey:@"connectionLogger"] boolValue];

	MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
	smtpSession.hostname = smtpServer;
	smtpSession.port = smtpPort;
	smtpSession.username = smtpUsername;
	smtpSession.password = smtpPassword;
	smtpSession.connectionType = MCOConnectionTypeTLS;

	MCOMessageBuilder * builder = [[MCOMessageBuilder alloc] init];
	[[builder header] setFrom:[MCOAddress addressWithDisplayName:fromName mailbox:fromEmail]];
//	[[builder header] setReplyTo:[MCOAddress addressWithMailbox:replyEmail]];

	NSMutableArray *to = [[NSMutableArray alloc] init];
	MCOAddress *newAddress = [MCOAddress addressWithDisplayName:toName mailbox:toEmail];
	[to addObject:newAddress];
	[[builder header] setTo:to];

	[[builder header] setSubject:textSubject];
	[builder setHTMLBody:textBody];

	if (textAttachment) {
		MCOAttachment *attachment = [MCOAttachment attachmentWithHTMLString:textAttachment];
		[builder addAttachment:attachment];
	}

	if (connectionLogger) {
    smtpSession.connectionLogger = ^(void * connectionID, MCOConnectionLogType type, NSData * data) {
      NSLog(@"smtp session[%li] %@", (long)type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
  }

	NSData * rfc822Data = [builder data];
	MCOSMTPSendOperation *sendOperation = [smtpSession sendOperationWithData:rfc822Data];
	[sendOperation start:^(NSError *error) {
		if(error) {
			NSLog(@"Error sending email: %@", error);

			CDVPluginResult *pluginResult = [
				CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]
			];

			[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
		} else {
			NSLog(@"Successfully sent email!");
			CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
			[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
		}
	}];
}

@end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
    public class NullableContextTests : CSharpTestBase
    {
        [InlineData("#nullable enable", NullableContextOptions.Disable, NullableContext.Enabled)]
        [InlineData("#nullable enable", NullableContextOptions.Annotations, NullableContext.Enabled)]
        [InlineData("#nullable enable", NullableContextOptions.Warnings, NullableContext.Enabled)]
        [InlineData("#nullable enable", NullableContextOptions.Enable, NullableContext.Enabled)]

        [InlineData("#nullable enable warnings", NullableContextOptions.Disable, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable enable warnings", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable enable warnings", NullableContextOptions.Annotations, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable enable warnings", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)]

        [InlineData("#nullable enable annotations", NullableContextOptions.Disable, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable enable annotations", NullableContextOptions.Warnings, NullableContext.Enabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable enable annotations", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable enable annotations", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.WarningsContextInherited)]

        [InlineData("#nullable disable", NullableContextOptions.Disable, NullableContext.Disabled)]
        [InlineData("#nullable disable", NullableContextOptions.Annotations, NullableContext.Disabled)]
        [InlineData("#nullable disable", NullableContextOptions.Warnings, NullableContext.Disabled)]
        [InlineData("#nullable disable", NullableContextOptions.Enable, NullableContext.Disabled)]

        [InlineData("#nullable disable warnings", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable disable warnings", NullableContextOptions.Warnings, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable disable warnings", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)]
        [InlineData("#nullable disable warnings", NullableContextOptions.Enable, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)]

        [InlineData("#nullable disable annotations", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable disable annotations", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable disable annotations", NullableContextOptions.Annotations, NullableContext.Disabled | NullableContext.WarningsContextInherited)]
        [InlineData("#nullable disable annotations", NullableContextOptions.Enable, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)]
        [Theory]
        public void NullableContextExplicitlySpecifiedAndRestoredInFile(string pragma, NullableContextOptions globalContext, NullableContext expectedContext)
        {
            var source = $@"
{pragma}
class C
{{
#nullable restore
    void M() {{}}
}}";

            var comp = CreateCompilation(source, options: WithNonNullTypes(globalContext));
            var syntaxTree = comp.SyntaxTrees[0];
            var model = comp.GetSemanticModel(syntaxTree);

            var classDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart;
            var methodDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().SpanStart;

            Assert.Equal(expectedContext, model.GetNullableContext(classDeclPosition));

            // The context at the start of the file should always be inherited and match the global context
            var restoredContext = ((NullableContext)globalContext) | NullableContext.ContextInherited;
            Assert.Equal(restoredContext, model.GetNullableContext(0));
            Assert.Equal(restoredContext, model.GetNullableContext(methodDeclPosition));
        }

        [Fact]
        public void NullableContextMultipleFiles()
        {
            var source1 = @"
#nullable enable
partial class C
{
    void M1() {};
}";

            var source2 = @"
partial class C
{
#nullable enable
    void M2();
}";

            var comp = CreateCompilation(new[] { source1, source2 }, options: WithNonNullTypesTrue());

            var syntaxTree1 = comp.SyntaxTrees[0];
            var model1 = comp.GetSemanticModel(syntaxTree1);
            var syntaxTree2 = comp.SyntaxTrees[1];
            var model2 = comp.GetSemanticModel(syntaxTree2);

            var classDecl1 = syntaxTree1.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart;
            var classDecl2 = syntaxTree2.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart;

            Assert.Equal(NullableContext.Enabled, model1.GetNullableContext(classDecl1));
            Assert.Equal(NullableContext.Enabled | NullableContext.ContextInherited, model2.GetNullableContext(classDecl2));
        }

        [Fact]
        public void NullableContextOptionsFlags()
        {
            Assert.True(NullableContextOptions.Enable.AnnotationsEnabled());
            Assert.True(NullableContextOptions.Enable.WarningsEnabled());

            Assert.True(NullableContextOptions.Annotations.AnnotationsEnabled());
            Assert.False(NullableContextOptions.Annotations.WarningsEnabled());

            Assert.False(NullableContextOptions.Warnings.AnnotationsEnabled());
            Assert.True(NullableContextOptions.Warnings.WarningsEnabled());

            Assert.False(NullableContextOptions.Disable.AnnotationsEnabled());
            Assert.False(NullableContextOptions.Disable.WarningsEnabled());
        }

        [Fact]
        public void NullableContextFlags()
        {
            AssertEnabledForInheritence(NullableContext.Disabled, warningsEnabled: false, annotationsEnabled: false);
            AssertEnabledForInheritence(NullableContext.WarningsEnabled, warningsEnabled: true, annotationsEnabled: false);
            AssertEnabledForInheritence(NullableContext.AnnotationsEnabled, warningsEnabled: false, annotationsEnabled: true);
            AssertEnabledForInheritence(NullableContext.Enabled, warningsEnabled: true, annotationsEnabled: true);

            void AssertEnabledForInheritence(NullableContext context, bool warningsEnabled, bool annotationsEnabled)
            {
                Assert.Equal(warningsEnabled, context.WarningsEnabled());
                Assert.Equal(annotationsEnabled, context.AnnotationsEnabled());
                Assert.False(context.WarningsInherited());
                Assert.False(context.AnnotationsInherited());

                var warningsInherited = context | NullableContext.WarningsContextInherited;
                Assert.Equal(warningsEnabled, warningsInherited.WarningsEnabled());
                Assert.Equal(annotationsEnabled, warningsInherited.AnnotationsEnabled());
                Assert.True(warningsInherited.WarningsInherited());
                Assert.False(warningsInherited.AnnotationsInherited());

                var annotationsInherited = context | NullableContext.AnnotationsContextInherited;
                Assert.Equal(warningsEnabled, annotationsInherited.WarningsEnabled());
                Assert.Equal(annotationsEnabled, annotationsInherited.AnnotationsEnabled());
                Assert.False(annotationsInherited.WarningsInherited());
                Assert.True(annotationsInherited.AnnotationsInherited());

                var contextInherited = context | NullableContext.ContextInherited;
                Assert.Equal(warningsEnabled, contextInherited.WarningsEnabled());
                Assert.Equal(annotationsEnabled, contextInherited.AnnotationsEnabled());
                Assert.True(contextInherited.WarningsInherited());
                Assert.True(contextInherited.AnnotationsInherited());
            }
        }
    }
}


text:
package com.badlogic.ashley.core;

/**
 * Interface for all Components. A Component is intended as a data holder and provides data to be processed in an
 * {@link EntitySystem}. But do as you wish.
 * @author Stefan Bachmann
 */
public interface Component {

}


text:
<?php

use yii\db\Migration;

/**
 * Handles the dropping of table `emailrecipients`.
 */
class m170216_200526_drop_emailrecipients_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->dropTable('{{%email_recipients}}');
    }

    /**
     * @inheritdoc
     */
    public function down()
    {

    }
}


text:
package org.apache.sqoop.connector;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.sqoop.common.SqoopException;
import org.apache.sqoop.connector.spi.SqoopConnector;
import org.apache.sqoop.core.ConfigurationConstants;
import org.apache.sqoop.repository.Repository;
import org.apache.sqoop.repository.RepositoryManager;
import org.apache.sqoop.repository.RepositoryTransaction;
import org.apache.sqoop.model.MConnector;

public final class ConnectorManager {

  /**
   * Logger object.
   */
  private static final Logger LOG = Logger.getLogger(ConnectorManager.class);

  /**
   * Private instance to singleton of this class.
   */
  private static ConnectorManager instance;

  /**
   * Create default object by default.
   *
   * Every Sqoop server application needs one so this should not be performance issue.
   */
  static {
    instance = new ConnectorManager();
  }

  /**
   * Return current instance.
   *
   * @return Current instance
   */
  public static ConnectorManager getInstance() {
    return instance;
  }

  /**
   * Allows to set instance in case that it's need.
   *
   * This method should not be normally used as the default instance should be sufficient. One target
   * user use case for this method are unit tests.
   *
   * @param newInstance New instance
   */
  public static void setInstance(ConnectorManager newInstance) {
    instance = newInstance;
  }

  // key: connector id, value: connector name
  private Map<Long, String> nameMap = new HashMap<Long, String>();

  // key: connector name, value: connector handler
  private Map<String, ConnectorHandler> handlerMap =
      new HashMap<String, ConnectorHandler>();

  public List<MConnector> getConnectorsMetadata() {
    List<MConnector> connectors = new LinkedList<MConnector>();
    for(ConnectorHandler handler : handlerMap.values()) {
      connectors.add(handler.getMetadata());
    }
    return connectors;
  }

  public Set<Long> getConnectorIds() {
    return nameMap.keySet();
  }

  public Map<Long, ResourceBundle> getResourceBundles(Locale locale) {
    Map<Long, ResourceBundle> bundles = new HashMap<Long, ResourceBundle>();
    for(ConnectorHandler handler : handlerMap.values()) {
      long id = handler.getMetadata().getPersistenceId();
      ResourceBundle bundle = handler.getConnector().getBundle(locale);
      bundles.put(id, bundle);
    }
    return bundles;
  }

  public ResourceBundle getResourceBundle(long connectorId,
                                                 Locale locale) {
    ConnectorHandler handler = handlerMap.get(nameMap.get(connectorId));
    return  handler.getConnector().getBundle(locale);
  }

  public MConnector getConnectorMetadata(long connectorId) {
    ConnectorHandler handler = handlerMap.get(nameMap.get(connectorId));
    if(handler == null) {
      return null;
    }

    return handler.getMetadata();
  }

  public SqoopConnector getConnector(long connectorId) {
    ConnectorHandler handler = handlerMap.get(nameMap.get(connectorId));
    return handler.getConnector();
  }

  public synchronized void initialize() {
    if (LOG.isTraceEnabled()) {
      LOG.trace("Begin connector manager initialization");
    }

    List<URL> connectorConfigs = new ArrayList<URL>();

    try {
      Enumeration<URL> appPathConfigs =
          ConnectorManager.class.getClassLoader().getResources(
              ConfigurationConstants.FILENAME_CONNECTOR_PROPERTIES);

      while (appPathConfigs.hasMoreElements()) {
        connectorConfigs.add(appPathConfigs.nextElement());
      }

      ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();

      if (ctxLoader != null) {
        Enumeration<URL> ctxPathConfigs = ctxLoader.getResources(
            ConfigurationConstants.FILENAME_CONNECTOR_PROPERTIES);

        while (ctxPathConfigs.hasMoreElements()) {
          URL configUrl = ctxPathConfigs.nextElement();
          if (!connectorConfigs.contains(configUrl)) {
            connectorConfigs.add(configUrl);
          }
        }
      }

      LOG.info("Connector config urls: " + connectorConfigs);

      if (connectorConfigs.size() == 0) {
        throw new SqoopException(ConnectorError.CONN_0002);
      }

      for (URL url : connectorConfigs) {
        ConnectorHandler handler = new ConnectorHandler(url);
        ConnectorHandler handlerOld =
            handlerMap.put(handler.getUniqueName(), handler);
        if (handlerOld != null) {
          throw new SqoopException(ConnectorError.CONN_0006,
              handler + ", " + handlerOld);
        }
      }
    } catch (IOException ex) {
      throw new SqoopException(ConnectorError.CONN_0001, ex);
    }

    registerConnectors();

    if (LOG.isInfoEnabled()) {
      LOG.info("Connectors loaded: " + handlerMap);
    }
  }

  private synchronized void registerConnectors() {
    Repository repository = RepositoryManager.getInstance().getRepository();

    RepositoryTransaction rtx = null;
    try {
      rtx = repository.getTransaction();
      rtx.begin();
      for (String name : handlerMap.keySet()) {
        ConnectorHandler handler = handlerMap.get(name);
        MConnector connectorMetadata = handler.getMetadata();
        MConnector registeredMetadata =
            repository.registerConnector(connectorMetadata);

        // Set registered metadata instead of connector metadata as they will
        // have filled persistent ids. We should be confident at this point that
        // there are no differences between those two structures.
        handler.setMetadata(registeredMetadata);

        String connectorName = handler.getUniqueName();
        if (!handler.getMetadata().hasPersistenceId()) {
          throw new SqoopException(ConnectorError.CONN_0010, connectorName);
        }
        nameMap.put(handler.getMetadata().getPersistenceId(), connectorName);
        LOG.debug("Registered connector: " + handler.getMetadata());
      }
      rtx.commit();
    } catch (Exception ex) {
      if (rtx != null) {
        rtx.rollback();
      }
      throw new SqoopException(ConnectorError.CONN_0007, ex);
    } finally {
      if (rtx != null) {
        rtx.close();
      }
    }
  }

  public synchronized void destroy() {
    // FIXME
  }
}


text:
class AsciicastProcessor

  def process(asciicast)
    AsciicastSnapshotUpdater.new.update(asciicast)
    AsciicastFramesFileUpdater.new.update(asciicast)
  end

end


text:
<?php
/**
 * Created by PhpStorm.
 * User: sgraupner
 * Date: 23/11/2016
 * Time: 10:26.
 */

namespace App\Model;

use Carbon\Carbon;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class DownloadVersion
{
    protected $fs = null;

    protected $path = '';

    protected $version = '';

    /**
     * @var Collection available files for the identifier and version
     */
    protected $files = null;

    public function __construct(Filesystem $fs, string $identifier, string $version)
    {
        $this->fs = $fs;
        $this->path = "downloads/{$identifier}/{$version}";
        $this->version = $version;

        if (!$fs->exists($this->path)) {
            throw new FileNotFoundException("No downloads available for identifier {$identifier}");
        }

        $this->files = collect($fs->files("downloads/{$identifier}/{$version}"))
            ->map(function ($filename) use ($fs) {
                return new Download($fs, $filename);
            });
    }

    /**
     * @return string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * @param string $version
     *
     * @return bool
     */
    public function isVersion(string $version)
    {
        return strcmp($this->version, $version) === 0;
    }

    /**
     * Return the number of days this download version exists.
     *
     * @return int
     */
    public function getAge()
    {
        $fileCTime = Carbon::createFromTimestamp(filectime(storage_path("app/{$this->path}")));

        return $fileCTime->diffInDays();
    }

    public function getFiles()
    {
        return $this->files;
    }

    /**
     * @param string $extension
     *
     * @throws FileNotFoundException
     *
     * @return Download
     */
    public function getFileForExtension(string $extension)
    {
        $file = $this->files->filter(function (Download $file) use ($extension) {
            return Str::endsWith($file->getFilename(), $extension);
        });

        if ($file->count() !== 1) {
            throw new FileNotFoundException("No file found for extension {$extension}");
        }

        return $file->first();
    }
}


text:
package visactor;

import java.io.Serializable;
import java.time.Instant;
import java.util.UUID;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * A simple base for visactor event abstraction that is presented by
 * (id, timestamp, source, target).
 *
 * @author Behrooz Nobakht
 * @since 1.0
 */
@XmlRootElement
public class Event implements Serializable {

	private static final long serialVersionUID = -6969088901063773872L;

	private String id = UUID.randomUUID().toString();
	private long timestamp = Instant.now().toEpochMilli();
	private String source;
	private String target;

	/**
	 * Ctor.
	 */
	public Event() {
	}

	/**
	 * @return the ID of the event
	 */
	public String getId() {
		return id;
	}

	/**
	 * @return the timestamp of the event
	 */
	public long getTimestamp() {
		return timestamp;
	}

	/**
	 * @return the source of the event
	 */
	public String getSource() {
		return source;
	}

	/**
	 * @return the target of the event
	 */
	public String getTarget() {
		return target;
	}

	/**
	 * @param id
	 *            the new ID
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @param timestamp
	 *            the new timestamp
	 */
	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}

	/**
	 * @param source
	 *            the new source
	 */
	public void setSource(String source) {
		this.source = source;
	}

	/**
	 * @param target
	 *            the new target
	 */
	public void setTarget(String target) {
		this.target = target;
	}

	/** {@inheritDoc} */
	@Override
	public int hashCode() {
		return getId().hashCode();
	}

	/** {@inheritDoc} */
	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj instanceof Event == false) {
			return false;
		}
		return hashCode() == obj.hashCode();
	}

	/** {@inheritDoc} */
	@Override
	public String toString() {
		return "(id=" + getId() + ", time=" + getTimestamp() + ", source=" + getSource()
				+ ", target=" + getTarget() + ")";
	}

}


text:
package en.com.beta.safetrip;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;

public class ConfigActivity extends PreferenceActivity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
	}

	public void selectOption(View view)
	{
		switch(view.getId())
		{
			case R.id.configs:
				startActivity(new Intent(this, ConfigActivity.class));
				break;
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using Lokad.Cqrs.TapeStorage;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;

namespace Lokad.Cqrs.AppendOnly
{
    /// <summary>
    /// <para>This is embedded append-only store implemented on top of cloud page blobs
    /// (for persisting data with one HTTP call).</para>
    /// <para>This store ensures that only one writer exists and writes to a given event store</para>
    /// </summary>
    public sealed class BlobAppendOnlyStore : IAppendOnlyStore
    {
        // Caches
        readonly CloudBlobContainer _container;

        readonly LockingInMemoryCache _cache = new LockingInMemoryCache();

        bool _closed;

        /// <summary>
        /// Currently open file
        /// </summary>
        AppendOnlyStream _currentWriter;

        public BlobAppendOnlyStore(CloudBlobContainer container)
        {
            _container = container;
        }

        public void Dispose()
        {
            if (!_closed)
                Close();
        }

        public void InitializeWriter()
        {
            CreateIfNotExists(_container, TimeSpan.FromSeconds(60));
            LoadCaches();
        }
        public void InitializeReader()
        {
            CreateIfNotExists(_container, TimeSpan.FromSeconds(60));
            LoadCaches();
        }

        int _pageSizeMultiplier = 1024 * 512;

        public void Append(string streamName, byte[] data, long expectedStreamVersion = -1)
        {
            // should be locked
            try
            {
                _cache.ConcurrentAppend(streamName, data, (streamVersion, storeVersion) =>
                {
                    EnsureWriterExists(storeVersion);
                    Persist(streamName, data, streamVersion);
                }, expectedStreamVersion);

            }
            catch (AppendOnlyStoreConcurrencyException)
            {
                //store is OK when AOSCE is thrown. This is client's problem
                // just bubble it upwards
                throw;
            }
            catch
            {
                // store probably corrupted. Close it and then rethrow exception
                // so that clien will have a chance to retry.
                Close();
                throw;
            }
        }

        public IEnumerable<DataWithKey> ReadRecords(string streamName, long afterVersion, int maxCount)
        {
            return _cache.ReadStream(streamName, afterVersion, maxCount);
        }

        public IEnumerable<DataWithKey> ReadRecords(long afterVersion, int maxCount)
        {
            return _cache.ReadAll(afterVersion, maxCount);

        }

        public void Close()
        {
            _closed = true;

            if (_currentWriter == null)
                return;

            var tmp = _currentWriter;
            _currentWriter = null;
            tmp.Dispose();
        }

        public void ResetStore()
        {
            Close();
            _cache.Clear(() =>
            {
                var blobs = _container.ListBlobs().OfType<CloudPageBlob>().Where(item => item.Uri.ToString().EndsWith(".dat"));

                blobs
                    .AsParallel().ForAll(i => i.DeleteIfExists());
            });
        }

        public long GetCurrentVersion()
        {
            return _cache.StoreVersion;
        }

        IEnumerable<StorageFrameDecoded> EnumerateHistory()
        {
            // cleanup old pending files
            // load indexes
            // build and save missing indexes
            var datFiles = _container
                .ListBlobs(new BlobRequestOptions()
                {
                    BlobListingDetails = BlobListingDetails.Metadata
                })
                .OrderBy(s => s.Uri.ToString())
                .OfType<CloudPageBlob>()
                .Where(s => s.Name.EndsWith(".dat"));

            foreach (var fileInfo in datFiles)
            {

                var bytes = fileInfo.DownloadByteArray();
                bool potentiallyNonTruncatedChunk = bytes.Length % _pageSizeMultiplier == 0;
                long lastValidPosition = 0;
                using (var stream = new MemoryStream(bytes))
                {
                    StorageFrameDecoded result;
                    while (StorageFramesEvil.TryReadFrame(stream, out result))
                    {
                        lastValidPosition = stream.Position;
                        yield return result;
                    }
                }
                var haveSomethingToTruncate = bytes.Length - lastValidPosition >= 512;
                if (potentiallyNonTruncatedChunk & haveSomethingToTruncate)
                {
                    TruncateBlob(lastValidPosition, fileInfo);
                }
            }
        }

        void TruncateBlob(long lastValidPosition, CloudPageBlob fileInfo)
        {
            var trunc = lastValidPosition;
            var remainder = lastValidPosition % 512;
            if (remainder > 0)
            {
                trunc += 512 - remainder;
            }
            Trace.WriteLine(string.Format("Truncating {0} to {1}", fileInfo.Name, trunc));
            _container.GetPageBlobReference(fileInfo.Name + ".bak").CopyFromBlob(fileInfo);
            SetLength(fileInfo, trunc);
        }

        static void SetLength(CloudPageBlob blob, long newLength, int timeout = 10000)
        {
            var credentials = blob.ServiceClient.Credentials;

            var requestUri = blob.Uri;
            if (credentials.NeedsTransformUri)
                requestUri = new Uri(credentials.TransformUri(requestUri.ToString()));

            var request = BlobRequest.SetProperties(requestUri, timeout, blob.Properties, null, newLength);
            request.Timeout = timeout;

            credentials.SignRequest(request);

            using (request.GetResponse()) { }
        }

        void LoadCaches()
        {
            _cache.LoadHistory(EnumerateHistory());
        }

        void Persist(string key, byte[] buffer, long commit)
        {
            var frame = StorageFramesEvil.EncodeFrame(key, buffer, commit);
            if (!_currentWriter.Fits(frame.Data.Length + frame.Hash.Length))
            {
                CloseWriter();
                EnsureWriterExists(_cache.StoreVersion);
            }

            _currentWriter.Write(frame.Data);
            _currentWriter.Write(frame.Hash);
            _currentWriter.Flush();
        }

        void CloseWriter()
        {
            _currentWriter.Dispose();
            _currentWriter = null;
        }

        void EnsureWriterExists(long version)
        {
            if (_currentWriter != null)
                return;

            var fileName = string.Format("{0:00000000}-{1:yyyy-MM-dd-HHmmss}.dat", version, DateTime.UtcNow);
            var blob = _container.GetPageBlobReference(fileName);
            blob.Create(_pageSizeMultiplier);

            _currentWriter = new AppendOnlyStream(512, (i, bytes) => blob.WritePages(bytes, i), _pageSizeMultiplier);
        }

        static void CreateIfNotExists(CloudBlobContainer container, TimeSpan timeout)
        {
            var sw = Stopwatch.StartNew();
            while (sw.Elapsed < timeout)
            {
                try
                {
                    container.CreateIfNotExist();
                    return;
                }
                catch (StorageClientException e)
                {
                    // container is being deleted
                    if (!(e.ErrorCode == StorageErrorCode.ResourceAlreadyExists && e.StatusCode == HttpStatusCode.Conflict))
                        throw;
                }
                Thread.Sleep(500);
            }

            throw new TimeoutException(string.Format("Can not create container within {0} seconds.", timeout.TotalSeconds));
        }
    }
}


text:
The goal of this policy is to create a restrictive environment for running the Cinched service.

The goal of the policy is:

* Remove write access to the library files and binaries used by Cinched (/usr/lib64/cinched, /usr/sbin/cinched)
* Restrict read/write access to Cinched's library and data files (/var/{lib,log}/cinched, /usr/sbin/cinched, /usr/lib64/cinched) to to a single security context, with a single entry point (/usr/sbin/cinched).

I have purposefully tried to limit the number of reference policy interfaces used in this policy to limit the possibility of accidentally granting more access to the system than what is necessary.

## Interfaces

* cinched_operator($role, $domain): Grants ability to execute binaries marked with ts_exec_t
* cinched_sysadmin($role): Grants ability to relabel some files into the secure domain.
* cinched_admin($role): Grants ability to relabel files into or out from all domains.

## Role mapping

I'm consuming the interfaces in the localuser policy.

Currently, only setfiles_t consumes the cinched_sysadmin inteface, and sysadm_t is consumes the cinched_operator interface.

No current mappings to the cinched_admin interface.


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Parquet.Data
{
   /// <summary>
   /// Represents a structure i.e. a container for other fields.
   /// </summary>
   public class StructField : Field, IEquatable<StructField>
   {
      private readonly List<Field> _fields = new List<Field>();

      /// <summary>
      /// Creates a new structure field
      /// </summary>
      /// <param name="name">Structure name</param>
      /// <param name="elements">List of elements</param>
      public StructField(string name, params Field[] elements) : this(name)
      {
         if(elements == null || elements.Length == 0)
         {
            throw new ArgumentException($"structure '{name}' requires at least one element");
         }

         //path for structures has no weirdnes, yay!

         foreach(Field field in elements)
         {
            _fields.Add(field);
         }

         Path = name;
         PathPrefix = null;
      }

      internal override string PathPrefix
      {
         set
         {
            Path = value.AddPath(Name);

            foreach(Field field in _fields)
            {
               field.PathPrefix = Path;
            }
         }
      }

      internal override void PropagateLevels(int parentRepetitionLevel, int parentDefinitionLevel)
      {
         //struct is a container, it doesn't have any levels

         foreach(Field f in Fields)
         {
            f.PropagateLevels(parentRepetitionLevel, parentDefinitionLevel);
         }
      }

      private StructField(string name) : base(name, SchemaType.Struct)
      {

      }

      internal static StructField CreateWithNoElements(string name)
      {
         return new StructField(name);
      }

      /// <summary>
      /// Elements of this structure
      /// </summary>
      public IReadOnlyList<Field> Fields => _fields;

      internal override void Assign(Field se)
      {
         _fields.Add(se);
      }

      /// <summary>
      ///
      /// </summary>
      /// <param name="other"></param>
      /// <returns></returns>
      public bool Equals(StructField other)
      {
         if (ReferenceEquals(null, other)) return false;
         if (ReferenceEquals(this, other)) return true;

         if (Name != other.Name) return false;
         if (Fields.Count != other.Fields.Count) return false;
         for(int i = 0; i < Fields.Count; i++)
         {
            if (!Fields[i].Equals(other.Fields[i])) return false;
         }

         return true;
      }

      /// <summary>
      ///
      /// </summary>
      /// <param name="obj"></param>
      /// <returns></returns>
      public override bool Equals(object obj)
      {
         if (ReferenceEquals(null, obj)) return false;
         if (ReferenceEquals(this, obj)) return true;
         if (obj.GetType() != GetType()) return false;

         return Equals((StructField)obj);
      }

      /// <summary>
      ///
      /// </summary>
      /// <returns></returns>
      public override int GetHashCode()
      {
         return Name.GetHashCode() *
            Fields.Aggregate(1, (current, f) => current * f.GetHashCode());
      }
   }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.rworsnop</groupId>
    <artifactId>vertx-concurrent</artifactId>
    <version>1.1-SNAPSHOT</version>

    <developers>
        <developer>
            <id>rworsnop</id>
            <name>Rob Worsnop</name>
            <email>rworsnop@gmail.com</email>
        </developer>
    </developers>

    <name>Vert.x Concurrent</name>
    <description>A selection of utilities from java.util.concurrent, in Vert.x-aware, non-blocking form</description>
    <url>https://github.com/rworsnop/vertx-concurrent</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:git://github.com:rworsnop/vertx-concurrent.git</connection>
        <developerConnection>scm:git:ssh://git@github.com:rworsnop/vertx-concurrent.git</developerConnection>
        <url>https://github.com/rworsnop/vertx-concurrent</url>
    </scm>

    <dependencies>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>3.5.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-rx-java</artifactId>
            <version>3.5.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-unit</artifactId>
            <version>3.5.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.6</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                     <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>2.4</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>2.10.3</version>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
    </distributionManagement>

</project>


text:
package org.mousephenotype.dcc.exportlibrary.xmlvalidationremoteclients.imits;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import org.apache.http.client.ClientProtocolException;
import org.json.simple.parser.ParseException;
import org.mousephenotype.dcc.exportlibrary.xmlvalidationdatastructure.external.imits.ImitsProductionCentre;
import org.mousephenotype.dcc.exportlibrary.xmlvalidationdatastructure.external.imits.MIPlan;
import org.mousephenotype.dcc.exportlibrary.xmlvalidationdatastructure.external.imits.MiPlans;
import org.mousephenotype.dcc.exportlibrary.xmlvalidationdatastructure.external.imits.PhenotypeAttempt;
import org.mousephenotype.dcc.exportlibrary.xmlvalidationdatastructure.external.imits.PhenotypeAttempts;
import org.slf4j.LoggerFactory;

public class ImitsOracle {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ImitsHTTPClient.class);
    private static final String JSON_FOLDER = "data/json/";
    private final ImitsHTTPClient imitsHTTPClient;
    private final ImitsParser imitsParser;

    static {
        if (!(new File(ImitsOracle.JSON_FOLDER).exists())) {
            new File(ImitsOracle.JSON_FOLDER).mkdirs();
        }
    }

    public ImitsOracle(String username, String password) {
        this.imitsHTTPClient = new ImitsHTTPClient(username, password);
        this.imitsParser = new ImitsParser();
    }

    public static String getPhenotypeAttemptFilename(ImitsProductionCentre imitsProductionCentre, String colonyID) {
        StringBuilder sb = new StringBuilder(JSON_FOLDER);
        if (imitsProductionCentre != null) {
            sb.append(imitsProductionCentre.name());
            sb.append("_");
        }
        sb.append(colonyID);
        sb.append(".json");
        return sb.toString();
    }

    public static String getMIPlanFilename(String miPlanID) {
        StringBuilder sb = new StringBuilder(JSON_FOLDER);
        sb.append("miplan_");
        sb.append(miPlanID);
        sb.append(".json");
        return sb.toString();
    }

    private MIPlan getMIPlan(String miPlanID) throws URISyntaxException, IOException, ClientProtocolException, NoSuchAlgorithmException, KeyManagementException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, FileNotFoundException, ParseException {
        URI uri = imitsHTTPClient.getMIPlanURIForMIPlanID(miPlanID);
        logger.trace("contacting imits to download miPlan {}", miPlanID);
        imitsHTTPClient.getData(uri, getMIPlanFilename(miPlanID), false);
        return this.loadMIPlan(miPlanID);
    }

    public MIPlan loadMIPlan(String miPlanID) throws FileNotFoundException, IOException, ParseException {
        MiPlans miPlans = imitsParser.getMiPlans(getMIPlanFilename(miPlanID));
        logger.trace("{} miplans found", miPlans.getMiPlan().size());
        if (miPlans.getMiPlan().size() > 1) {
            logger.warn("It should only return one attempt.");
        }
        if (miPlans.getMiPlan() != null && miPlans.getMiPlan().size() > 0) {
            return miPlans.getMiPlan().get(0);
        }
        return null;
    }

    public PhenotypeAttempt isInPhenotypeAttemptColonyName(ImitsProductionCentre imitsProductionCentre, String colonyID) throws URISyntaxException, IOException, ClientProtocolException, NoSuchAlgorithmException, KeyManagementException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, FileNotFoundException, ParseException {
        URI centreUri = imitsHTTPClient.getPhenotypeAttemptURIForProducionCentreAndColonyID(null, colonyID);
        logger.warn("uri = " + centreUri.toString());
        logger.trace("contacting imits for phenotype on {} {}", null, colonyID);
        imitsHTTPClient.getData(centreUri, getPhenotypeAttemptFilename(null, colonyID), false);
        logger.trace("parsing response stored in {}", getPhenotypeAttemptFilename(null, colonyID));
        String phenotypeAttemptFilename = getPhenotypeAttemptFilename(null, colonyID);
        PhenotypeAttempts phenotypeAttempts = imitsParser.getPhenotypeAttempts(phenotypeAttemptFilename);

        logger.trace("{} phenotype attempts found", phenotypeAttempts.getPhenotypeAttempt().size());
        if (phenotypeAttempts.getPhenotypeAttempt().size() > 1) {
            logger.warn("It should only return one attempt.");
        }

        PhenotypeAttempt phenotypeAttempt = null;

        if (phenotypeAttempts.getPhenotypeAttempt() != null && phenotypeAttempts.getPhenotypeAttempt().size() > 0) {
            phenotypeAttempt = phenotypeAttempts.getPhenotypeAttempt().get(0);
            MIPlan miPlan = this.getMIPlan(phenotypeAttempt.getMiPlanID().toString());
            if (miPlan != null && miPlan.getMarkerMGIaccessionID() != null) {
                phenotypeAttempt.getGenotypicInformation().setGeneMGIID(miPlan.getMarkerMGIaccessionID());
            }
        }
        return phenotypeAttempt;
    }

    public PhenotypeAttempt isInPhenotypeAttemptColonyNameOnly(String colonyID) throws URISyntaxException, IOException, ClientProtocolException, NoSuchAlgorithmException, KeyManagementException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, FileNotFoundException, ParseException {
        URI centreUri = imitsHTTPClient.getPhenotypeAttemptURIForColonyIDOnly(colonyID);
        System.out.println("uri = " + centreUri.toString());
        logger.trace("contacting imits for phenotype on {} {}", null, colonyID);
        imitsHTTPClient.getData(centreUri, getPhenotypeAttemptFilename(null, colonyID), false);
        logger.trace("parsing response stored in {}", getPhenotypeAttemptFilename(null, colonyID));
        System.out.println("file = " + getPhenotypeAttemptFilename(null, colonyID));
        PhenotypeAttempts phenotypeAttempts = imitsParser.getPhenotypeAttempts(getPhenotypeAttemptFilename(null, colonyID));

        logger.trace("{} phenotype attempts found", phenotypeAttempts.getPhenotypeAttempt().size());
        if (phenotypeAttempts.getPhenotypeAttempt().size() > 1) {
            logger.warn("It should only return one attempt.");
        }

        PhenotypeAttempt phenotypeAttempt = null;

        if (phenotypeAttempts.getPhenotypeAttempt() != null && phenotypeAttempts.getPhenotypeAttempt().size() > 0) {
            phenotypeAttempt = phenotypeAttempts.getPhenotypeAttempt().get(0);
            MIPlan miPlan = this.getMIPlan(phenotypeAttempt.getMiPlanID().toString());
            if (miPlan != null && miPlan.getMarkerMGIaccessionID() != null) {
                phenotypeAttempt.getGenotypicInformation().setGeneMGIID(miPlan.getMarkerMGIaccessionID());
            }
        }
        return phenotypeAttempt;
    }
}


text:
package org.elixirian.jsonstatham.json;

import static org.elixirian.kommonlee.util.Objects.*;

import org.elixirian.jsonstatham.annotation.Json;
import org.elixirian.jsonstatham.annotation.JsonField;
import org.elixirian.jsonstatham.annotation.ValueAccessor;

/**
 * <pre>
 *     ___  _____                                _____
 *    /   \/    /_________  ___ ____ __ ______  /    /   ______  ______
 *   /        / /  ___ \  \/  //___// //     / /    /   /  ___ \/  ___ \
 *  /        \ /  _____/\    //   //   __   / /    /___/  _____/  _____/
 * /____/\____\\_____/   \__//___//___/ /__/ /________/\_____/ \_____/
 * </pre>
 *
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-03-06)
 */
@Json
public class SubClassWithValueAccessorWithoutItsName extends SuperClassWithValueAccessorWithoutItsName
{
  @ValueAccessor
  @JsonField(name = "email")
  private String email;

  public SubClassWithValueAccessorWithoutItsName(final String name, final int number, final String email)
  {
    super(name, number);
    this.email = email;
  }

  /**
   * @return the email
   */
  public String getEmail()
  {
    return "My email address is " + email;
  }

  /**
   * @param email
   *          the email to set
   */
  public void setEmail(final String email)
  {
    this.email = email;
  }

  @Override
  public int hashCode()
  {
    return hash(super.hashCode(), email);
  }

  @Override
  public boolean equals(final Object subClassWithValueAccessorWithoutItsName)
  {
    if (identical(this, subClassWithValueAccessorWithoutItsName))
    {
      return true;
    }
    final SubClassWithValueAccessorWithoutItsName that =
      castIfInstanceOf(getClass(), subClassWithValueAccessorWithoutItsName);
    /* @formatter:off */
		return isNotNull(that) &&
						   (super.equals(subClassWithValueAccessorWithoutItsName) &&
								equal(this.email, that.email));
		/* @formatter:on */
  }

  @Override
  public String toString()
  {
    return toStringBuilder(this).value(super.toString())
        .newLine()
        .add("email", email)
        .toString();
  }
}


text:
<?php

namespace Ilios\AuthenticationBundle\Voter\Entity;

use Ilios\AuthenticationBundle\Voter\AbstractVoter;

use Ilios\CoreBundle\Entity\Manager\ProgramYearStewardManager;
use Ilios\CoreBundle\Entity\Manager\PermissionManager;
use Ilios\CoreBundle\Entity\ProgramYearInterface;
use Ilios\CoreBundle\Entity\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

/**
 * Class ProgramYearEntityVoter
 * @package Ilios\AuthenticationBundle\Voter
 */
class ProgramYearEntityVoter extends AbstractVoter
{
    /**
     * @var PermissionManager
     */
    protected $permissionManager;

    /**
     * @var ProgramYearStewardManager
     */
    protected $stewardManager;

    /**
     * @param PermissionManager $permissionManager
     * @param ProgramYearStewardManager $stewardManager
     */
    public function __construct(
        PermissionManager $permissionManager,
        ProgramYearStewardManager $stewardManager
    ) {
        $this->permissionManager = $permissionManager;
        $this->stewardManager = $stewardManager;
    }

    /**
     * {@inheritdoc}
     */
    protected function supports($attribute, $subject)
    {
        return $subject instanceof ProgramYearInterface && in_array($attribute, array(
            self::CREATE, self::VIEW, self::EDIT, self::DELETE
        ));
    }

    /**
     * @param string $attribute
     * @param ProgramYearInterface $programYear
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute($attribute, $programYear, TokenInterface $token)
    {
        $user = $token->getUser();
        if (!$user instanceof UserInterface) {
            return false;
        }

        switch ($attribute) {
            case self::VIEW:
                return $this->isViewGranted($programYear, $user);
                break;
            case self::CREATE:
            case self::EDIT:
            case self::DELETE:
                return $this->isWriteGranted($programYear, $user);
                break;
        }

        return false;
    }

    /**
     * @param ProgramYearInterface $programYear
     * @param UserInterface $user
     * @return bool
     */
    protected function isViewGranted($programYear, $user)
    {
        // do not enforce special views permissions.
        return true;
    }

    /**
     * @param ProgramYearInterface $programYear
     * @param UserInterface $user
     * @return bool
     */
    protected function isWriteGranted(ProgramYearInterface $programYear, $user)
    {
        // the given user is granted CREATE/EDIT/DELETE permissions on the given program year
        // when at least one of the following statements is true
        // 1. The user's primary school is the same as the parent program's owning school
        //    and the user has at least one of 'Course Director' and 'Developer' role.
        // 2. The user has WRITE permissions on the parent program's owning school
        //    and the user has at least one of 'Course Director' and 'Developer' role.
        // 3. The user's primary school matches at least one of the schools owning the
        //    program years' stewarding department,
        //    and the user has at least one of 'Course Director' and 'Developer' role.
        // 4. The user has WRITE permissions on the parent program.
        return (
            (
                $this->userHasRole($user, ['Course Director', 'Developer'])
                && (
                    $this->schoolsAreIdentical($programYear->getSchool(), $user->getSchool())
                    || $this->permissionManager->userHasWritePermissionToSchool(
                        $user,
                        $programYear->getSchool()->getId()
                    )
                    || $this->stewardManager->schoolIsStewardingProgramYear($user, $programYear)
                )
            )
            || $this->permissionManager->userHasWritePermissionToProgram($user, $programYear->getProgram())
        );
    }
}


text:
title: "exec"
description: "The exec command description and usage"
keywords: "command, container, run, execute"
---

<!-- This file is maintained within the docker/docker Github
     repository at https://github.com/docker/docker/. Make all
     pull requests against that repo. If you see this file in
     another repository, consider it read-only there, as it will
     periodically be overwritten by the definitive file. Pull
     requests which include edits to this file in other repositories
     will be rejected.
-->

# exec

```markdown
Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach         Detached mode: run command in the background
      --detach-keys    Override the key sequence for detaching a container
  -e, --env=[]         Set environment variables
      --help           Print usage
  -i, --interactive    Keep STDIN open even if not attached
      --privileged     Give extended privileges to the command
  -t, --tty            Allocate a pseudo-TTY
  -u, --user           Username or UID (format: <name|uid>[:<group|gid>])
```

## Description

The `docker exec` command runs a new command in a running container.

The command started using `docker exec` only runs while the container's primary
process (`PID 1`) is running, and it is not restarted if the container is
restarted.

COMMAND will run in the default directory of the container. It the
underlying image has a custom directory specified with the WORKDIR directive
in its Dockerfile, this will be used instead.

COMMAND should be an executable, a chained or a quoted command
will not work. Example: `docker exec -ti my_container "echo a && echo b"` will
not work, but `docker exec -ti my_container sh -c "echo a && echo b"` will.

## Examples

### Run `docker exec` on a running container

First, start a container.

```bash
$ docker run --name ubuntu_bash --rm -i -t ubuntu bash
```

This will create a container named `ubuntu_bash` and start a Bash session.

Next, execute a command on the container.

```bash
$ docker exec -d ubuntu_bash touch /tmp/execWorks
```

This will create a new file `/tmp/execWorks` inside the running container
`ubuntu_bash`, in the background.

Next, execute an interactive `bash` shell on the container.

```bash
$ docker exec -it ubuntu_bash bash
```

This will create a new Bash session in the container `ubuntu_bash`.

### Try to run `docker exec` on a paused container

If the container is paused, then the `docker exec` command will fail with an error:

```bash
$ docker pause test

test

$ docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                   PORTS               NAMES
1ae3b36715d2        ubuntu:latest       "bash"              17 seconds ago      Up 16 seconds (Paused)                       test

$ docker exec test ls

FATA[0000] Error response from daemon: Container test is paused, unpause the container before exec

$ echo $?
1
```