text:
<?php
App::uses('Upload.Upload', 'Model/Behavior');
App::uses('Folder', 'Utility');

class TestUpload extends CakeTestModel {

	public $useTable = 'uploads';

	public $actsAs = array(
		'Upload.Upload' => array(
			'photo' => array(
				'thumbnailMethod' => '_bad_thumbnail_method_',
				'pathMethod' => '_bad_path_method_',
			)
		)
	);

}

class TestUploadTwo extends CakeTestModel {

	public $useTable = 'uploads';

	public $actsAs = array(
		'Upload.Upload' => array(
			'photo' => array(
				'fields' => array(
					'type' => 'type',
					'dir' => 'dir'
				),
				'mimetypes' => array(
					'image/png',
					'image/jpeg',
					'image/gif'
				),
				'thumbnailSizes' => array(
					'thumb' => '80h'
				)
			)
		)
	);

}

class UploadBehaviorTest extends CakeTestCase {

	public $fixtures = array('plugin.upload.upload');

	public $TestUpload = null;

	public $MockUpload = null;

	public $data = array();

	public $currentTestMethod;

/**
 * Start Test callback
 *
 * @param string $method Test method that is about to be executed
 * @return void
 */
	public function startTest($method) {
		$this->TestUpload = ClassRegistry::init('TestUpload');
		$this->TestUploadTwo = ClassRegistry::init('TestUploadTwo');
		$this->currentTestMethod = $method;
		$this->data['test_empty'] = array(
			'photo' => ''
		);
		$this->data['test_ok'] = array(
			'photo' => array(
				'name' => 'Photo.png',
				'tmp_name' => 'Photo.png',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/png',
				'size' => 8192,
				'error' => UPLOAD_ERR_OK,
			)
		);
		$this->data['test_ok_bmp'] = array(
			'photo' => array(
				'name' => 'Photo.bmp',
				'tmp_name' => 'Photo.bmp',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/bmp',
				'size' => 8192,
				'error' => UPLOAD_ERR_OK,
			)
		);
		$this->data['test_update'] = array(
			'id' => 1,
			'photo' => array(
				'name' => 'NewPhoto.png',
				'tmp_name' => 'PhotoTmp.png',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/png',
				'size' => 8192,
				'error' => UPLOAD_ERR_OK,
			)
		);
		$this->data['test_update_other_field'] = array(
			'id' => 1,
			'other_field' => 'test',
			'photo' => array()
		);
		$this->data['test_update_other_field_without_photo_set'] = array(
			'id' => 1,
			'other_field' => 'test',
		);
		$this->data['test_remove'] = array(
			'photo' => array(
				'remove' => true,
			)
		);
	}

/**
 * Setup a MockUpload model with an attached behavior
 *
 * @param array $methods array of methods to mock
 * @return void
 */
	public function mockUpload($methods = array()) {
		if (!is_array($methods)) {
			$methods = (array)$methods;
		}
		if (empty($methods)) {
			$methods = array('handleUploadedFile', 'unlink', '_getMimeType', '_createThumbnails');
		}
		$this->MockUpload = $this->getMock('UploadBehavior', $methods);

		$this->MockUpload->setup($this->TestUpload, $this->TestUpload->actsAs['Upload.Upload']);
		$this->TestUpload->Behaviors->set('Upload', $this->MockUpload);

		$this->MockUpload->setup($this->TestUploadTwo, $this->TestUploadTwo->actsAs['Upload.Upload']);
		$this->TestUploadTwo->Behaviors->set('Upload', $this->MockUpload);
	}

/**
 * Call a protected method on an object
 *
 * @param Object $object object
 * @param string $name method to call
 * @param array $args arguments to pass to the method
 * @return mixed
 */
	public function protectedMethodCall($obj, $name, array $args) {
		$class = new \ReflectionClass($obj);
		$method = $class->getMethod($name);
		$method->setAccessible(true);
		return $method->invokeArgs($obj, $args);
	}

/**
 * Called when a test case method has been executed
 *
 * @param string $method Test method that was executed.
 * @return void
 */
	public function endTest($method) {
		$folder = new Folder(TMP);
		$folder->delete(ROOT . DS . APP_DIR . DS . 'webroot' . DS . 'files' . DS . 'test_upload');
		$folder->delete(ROOT . DS . APP_DIR . DS . 'tmp' . DS . 'tests' . DS . 'path');
		Classregistry::flush();
		unset($this->TestUpload);
		unset($this->TestUploadTwo);
	}

	public function testSetup() {
		$this->mockUpload(array('handleUploadedFile', 'unlink'));
		$this->assertEquals('_resizeImagick', $this->MockUpload->settings['TestUpload']['photo']['thumbnailMethod']);
		$this->assertEquals('_getPathPrimaryKey', $this->MockUpload->settings['TestUpload']['photo']['pathMethod']);
	}

	public function testUploadSettings() {
		$this->mockUpload(array('handleUploadedFile', 'unlink'));
		$this->assertEquals('_resizeImagick', $this->MockUpload->settings['TestUpload']['photo']['thumbnailMethod']);
		$this->assertEquals('_getPathPrimaryKey', $this->MockUpload->settings['TestUpload']['photo']['pathMethod']);

		$this->TestUpload->uploadSettings('photo', 'thumbnailMethod', '_resizePhp');
		$this->assertEquals('_resizePhp', $this->MockUpload->settings['TestUpload']['photo']['thumbnailMethod']);
		$this->assertEquals('_getPathPrimaryKey', $this->MockUpload->settings['TestUpload']['photo']['pathMethod']);

		$this->TestUpload->uploadSettings('photo', array(
			'thumbnailMethod' => '_resizeImagick',
			'pathMethod' => '_getPathFlat',
		));
		$this->assertEquals('_resizeImagick', $this->MockUpload->settings['TestUpload']['photo']['thumbnailMethod']);
		$this->assertEquals('_getPathFlat', $this->MockUpload->settings['TestUpload']['photo']['pathMethod']);

		$this->TestUpload->uploadSettings('photo', array('pathMethod', 'thumbnailQuality'), array('_getPathPrimaryKey', 100));
		$this->assertEquals('_resizeImagick', $this->MockUpload->settings['TestUpload']['photo']['thumbnailMethod']);
		$this->assertEquals('_getPathPrimaryKey', $this->MockUpload->settings['TestUpload']['photo']['pathMethod']);
		$this->assertEquals(100, $this->MockUpload->settings['TestUpload']['photo']['thumbnailQuality']);
	}

	public function testFileSize() {
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$result = $this->TestUpload->save($this->data['test_ok']);
		$this->assertInternalType('array', $result);
		$newRecord = $this->TestUpload->findById($this->TestUpload->id);
		$this->assertEquals($this->data['test_ok']['photo']['size'], $newRecord['TestUpload']['size']);
	}

	public function testEmptyUpload() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->MockUpload->expects($this->never())->method('unlink');
		$result = $this->TestUpload->save($this->data['test_empty']);
		$this->assertInternalType('array', $result);

		$id = $this->TestUpload->id;
		$newRecord = $this->TestUpload->findById($id);
		$expectedRecord = array(
			'TestUpload' => array(
				'id' => $id,
				'photo' => null,
				'dir' => null,
				'type' => null,
				'size' => null,
				'other_field' => null
			)
		);

		$this->assertEquals($expectedRecord, $newRecord);
	}

	public function testSimpleUpload() {
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->MockUpload->expects($this->never())->method('unlink');
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->with(
			$this->TestUpload,
			'photo',
			$this->data['test_ok']['photo']['tmp_name'],
			$this->MockUpload->settings['TestUpload']['photo']['path'] . 3 . DS . $this->data['test_ok']['photo']['name']
		);
		$result = $this->TestUpload->save($this->data['test_ok']);
		$this->assertInternalType('array', $result);

		$id = $this->TestUpload->id;
		$newRecord = $this->TestUpload->findById($id);
		$expectedRecord = array(
			'TestUpload' => array(
				'id' => $id,
				'photo' => 'Photo.png',
				'dir' => 3,
				'type' => 'image/png',
				'size' => 8192,
				'other_field' => null
			)
		);

		$this->assertEquals($expectedRecord, $newRecord);
	}

/**
 * Tests Upload::save creates a new Upload record including
 * an upload of an PNG image file using the Upload.Upload behavior
 * with the default path and pathMethod (primaryKey)
 *
 * @return void
 **/
	public function testSaveSuccessPngDefaultPathAndPathMethod() {
		$this->mockUpload();
		$nextId = (1 + $this->TestUploadTwo->field('id', array(), array('TestUploadTwo.id' => 'DESC')));
		$destinationDir = APP . 'webroot' . DS . 'files' . DS . 'test_upload_two' . DS . 'photo' . DS . $nextId . DS;

		$Upload = array(
			'TestUploadTwo' => array(
				'photo' => array(
					'name' => 'image-png.png',
					'type' => 'image/png',
					'tmp_name' => 'image-png-tmp.png',
					'error' => UPLOAD_ERR_OK,
					'size' => 8123,
				)
			)
		);

		$this->MockUpload->expects($this->never())
			->method('unlink');

		$this->MockUpload->expects($this->once())
			->method('handleUploadedFile')
			->with(
					$this->equalTo($this->TestUploadTwo),
					$this->equalTo('photo'),
					$this->equalTo('image-png-tmp.png'),
					$this->equalTo($destinationDir . 'image-png.png')
			)
			->will($this->returnValue(true));

		$this->MockUpload->expects($this->once())
			->method('_createThumbnails')
			->with(
					$this->isInstanceOf('TestUploadTwo'),
					$this->equalTo('photo'),
					$this->equalTo($destinationDir),
					$this->equalTo($destinationDir)
			)
			->will($this->returnValue(true));

		$this->assertTrue(false !== $this->TestUploadTwo->save($Upload));
		$this->assertSame(array(), array_keys($this->TestUploadTwo->validationErrors));

		$this->assertSame('image-png.png', $this->TestUploadTwo->field('photo', array('TestUploadTwo.id' => $nextId)));
		$this->assertSame('image/png', $this->TestUploadTwo->field('type', array('TestUploadTwo.id' => $nextId)));
		$this->assertSame((string)$nextId, $this->TestUploadTwo->field('dir', array('TestUploadTwo.id' => $nextId)));
	}

	public function testSaveDirEscaped() {
		$this->TestUpload->actsAs['Upload.Upload']['photo']['pathMethod'] = 'random';
		$this->mockUpload(array('handleUploadedFile', 'unlink', '_getMimeType', '_createThumbnails', '_getPathRandom'));

		$DS = '\\';
		$randomPath = '01' . $DS . '02' . $DS . '03';

		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->MockUpload->expects($this->once())->method('_getPathRandom')->will($this->returnValue($randomPath));

		$result = $this->TestUpload->save($this->data['test_ok']);
		$this->assertInternalType('array', $result);
		$newRecord = $this->TestUpload->findById($this->TestUpload->id);

		$this->assertSame($randomPath, $newRecord['TestUpload']['dir']);
	}

	public function testDeleteOnUpdate() {
		$this->TestUpload->actsAs['Upload.Upload']['photo']['deleteOnUpdate'] = true;
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->MockUpload->expects($this->once())->method('unlink')->will($this->returnValue(true));

		$existingRecord = $this->TestUpload->findById($this->data['test_update']['id']);
		$this->MockUpload->expects($this->once())->method('unlink')->with(
			$this->MockUpload->settings['TestUpload']['photo']['path'] . $existingRecord['TestUpload']['dir'] . DS . $existingRecord['TestUpload']['photo']
		);
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->with(
			$this->TestUpload,
			'photo',
			$this->data['test_update']['photo']['tmp_name'],
			$this->MockUpload->settings['TestUpload']['photo']['path'] . $this->data['test_update']['id'] . DS . $this->data['test_update']['photo']['name']
		);
		$result = $this->TestUpload->save($this->data['test_update']);
		$this->assertInternalType('array', $result);
	}

	public function testDeleteOnUpdateWithoutNewUpload() {
		$this->TestUpload->actsAs['Upload.Upload']['photo']['deleteOnUpdate'] = true;
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');
		$this->MockUpload->expects($this->never())->method('handleUploadedFile');
		$result = $this->TestUpload->save($this->data['test_update_other_field']);
		$this->assertInternalType('array', $result);
		$newRecord = $this->TestUpload->findById($this->TestUpload->id);
		$this->assertEquals($this->data['test_update_other_field']['other_field'], $newRecord['TestUpload']['other_field']);
	}

	public function testUpdateWithoutNewUpload() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');
		$this->MockUpload->expects($this->never())->method('handleUploadedFile');
		$result = $this->TestUpload->save($this->data['test_update_other_field']);
		$this->assertInternalType('array', $result);
		$newRecord = $this->TestUpload->findById($this->TestUpload->id);
		$this->assertEquals($this->data['test_update_other_field']['other_field'], $newRecord['TestUpload']['other_field']);
	}

	public function testUpdateWithoutNewUploadWithoutFieldSet() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');
		$this->MockUpload->expects($this->never())->method('handleUploadedFile');
		$result = $this->TestUpload->save($this->data['test_update_other_field_without_photo_set']);
		$this->assertInternalType('array', $result);
		$newRecord = $this->TestUpload->findById($this->TestUpload->id);
		$this->assertEquals($this->data['test_update_other_field_without_photo_set']['other_field'], $newRecord['TestUpload']['other_field']);
	}

	public function testRuntimeConfigIsResetBetweenSaves() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');

		// We'll save the record twice using the same model instance,
		// but handleUploadedFile should only be called once, on the first save.
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->TestUpload->save($this->data['test_update']);
		$runtime = $this->TestUpload->Behaviors->Upload->runtime;
		$this->assertInternalType('array', $runtime['TestUpload']['photo']);

		$this->TestUpload->read(null, $this->data['test_update']['id']);

		// intentionally don't pass an uploaded file in save data
		$this->TestUpload->save();
		$runtime = $this->TestUpload->Behaviors->Upload->runtime;
		$this->assertFalse(isset($runtime['TestUpload']['photo']));
	}

	public function testUnlinkFileOnDelete() {
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('unlink')->will($this->returnValue(true));
		$existingRecord = $this->TestUpload->findById($this->data['test_update']['id']);
		$this->MockUpload->expects($this->once())->method('unlink')->with(
			$this->MockUpload->settings['TestUpload']['photo']['path'] . $existingRecord['TestUpload']['dir'] . DS . $existingRecord['TestUpload']['photo']
		);
		$result = $this->TestUpload->delete($this->data['test_update']['id']);
		$this->assertTrue($result);
		$this->assertEmpty($this->TestUpload->findById($this->data['test_update']['id']));
	}

	public function testKeepFilesOnDelete() {
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(true));
		$this->MockUpload->expects($this->never())->method('unlink');
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->with(
			$this->TestUpload,
			'photo',
			$this->data['test_ok']['photo']['tmp_name'],
			$this->MockUpload->settings['TestUpload']['photo']['path'] . 3 . DS . $this->data['test_ok']['photo']['name']
		);
		$result = $this->TestUpload->save($this->data['test_ok']);
		$this->assertInternalType('array', $result);
		$id = $this->TestUpload->id;

		$existingRecord = $this->TestUpload->findById($id);
		$this->TestUpload->uploadSettings('photo', 'keepFilesOnDelete', true);
		$this->MockUpload->expects($this->never())->method('unlink');

		$result = $this->TestUpload->delete($id);
		$this->assertTrue($result);
		$this->assertEmpty($this->TestUpload->findById($id));
	}

	public function testDeleteFileOnTrueRemoveSave() {
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('unlink')->will($this->returnValue(true));

		$data = array(
			'id' => 1,
			'photo' => array(
				'remove' => true
			)
		);

		$existingRecord = $this->TestUpload->findById($data['id']);
		$this->MockUpload->expects($this->once())->method('unlink')->with(
			$this->MockUpload->settings['TestUpload']['photo']['path'] . $existingRecord['TestUpload']['dir'] . DS . $existingRecord['TestUpload']['photo']
		);
		$result = $this->TestUpload->save($data);
		$this->assertInternalType('array', $result);
	}

	public function testKeepFileOnFalseRemoveSave() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');

		$data = array(
			'id' => 1,
			'photo' => array(
				'remove' => false
			)
		);

		$existingRecord = $this->TestUpload->findById($data['id']);
		$result = $this->TestUpload->save($data);
		$this->assertInternalType('array', $result);
	}

	public function testKeepFileOnNullRemoveSave() {
		$this->mockUpload();
		$this->MockUpload->expects($this->never())->method('unlink');

		$data = array(
			'id' => 1,
			'photo' => array(
				'remove' => null
			)
		);

		$existingRecord = $this->TestUpload->findById($data['id']);
		$result = $this->TestUpload->save($data);
		$this->assertInternalType('array', $result);
	}

/**
 * Test file move exception
 *
 * @return void
 * @expectedException UploadException
 **/
	public function testMoveFileExecption() {
		$this->mockUpload(array('handleUploadedFile'));
		$this->MockUpload->expects($this->once())->method('handleUploadedFile')->will($this->returnValue(false));
		$result = $this->TestUpload->save($this->data['test_ok']);
	}

/**
 * Test validation rules
 *
 * @param string $rule rule to test
 * @param array $data validation data
 * @param array $record record to test
 * @return void
 * @dataProvider providerTestValidationRules
 **/
	public function testValidationRules($rule, $data, $record = array()) {
		$this->TestUpload->validate = array(
			'photo' => array(
				$rule => array(
					'rule' => $rule,
					'message' => $rule
				),
			)
		);

		$data = array_merge(array(
			'photo' => array_merge(array(
				'tmp_name' => 'Photo.png',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/png',
				'size' => 8192,
			), $data
		), $record));

		$this->__testInvalidValidationRule($rule, $data);
		$this->__testOkAndRemoveCasesValidate();
	}

	public function providerTestValidationRules() {
		return array(
			array('isUnderPhpSizeLimit', array('error' => UPLOAD_ERR_INI_SIZE)),
			array('isUnderFormSizeLimit', array('error' => UPLOAD_ERR_FORM_SIZE)),
			array('isCompletedUpload', array('error' => UPLOAD_ERR_PARTIAL)),
			array('isFileUpload', array('error' => UPLOAD_ERR_NO_FILE)),
			array('isFileUploadOrHasExistingValue', array('error' => UPLOAD_ERR_NO_FILE), array('id' => 2)),
			array('isFileUploadOrHasExistingValue', array('error' => UPLOAD_ERR_NO_FILE), array('id' => '')),
			array('isFileUploadOrHasExistingValue', array('error' => UPLOAD_ERR_NO_FILE)),
		);
	}

/**
 * Test ignorable validation rules
 *
 * @param string $rule rule to test
 * @param array $data validation data
 * @param array $record record to test
 * @return void
 * @dataProvider providerTestIgnorableValidationRules
 **/
	public function testIgnorableValidationRules($rule, $data, $record = array()) {
		$this->TestUpload->validate = array(
			'photo' => array(
				$rule => array(
					'rule' => $rule,
					'message' => $rule
				),
			)
		);

		$data = array_merge(array(
			'photo' => array_merge(array(
				'tmp_name' => 'Photo.png',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/png',
				'size' => 8192,
			), $data
		), $record));
		$this->__testInvalidValidationRule($rule, $data);

		$this->TestUpload->validate = array('photo' => array(
			$rule => array('rule' => array($rule, false),
		)));
		$data = array('photo' => array('error' => UPLOAD_ERR_NO_FILE));
		$this->__testSkipValidationRule($rule, $data);
		$this->__testOkAndRemoveCasesValidate();
	}

	public function providerTestIgnorableValidationRules() {
		return array(
			array('tempDirExists', array('error' => UPLOAD_ERR_NO_TMP_DIR)),
			array('isSuccessfulWrite', array('error' => UPLOAD_ERR_CANT_WRITE)),
			array('noPhpExtensionErrors', array('error' => UPLOAD_ERR_EXTENSION)),
		);
	}

/**
 * Test changing configuration when running validation rules
 *
 * @param string $rule rule to test
 * @return void
 * @dataProvider providerTestChangeConfigurationValidationRules
 **/
	public function testChangeConfigurationValidationRules($rule) {
		$this->TestUpload->validate = array(
			'photo' => array(
				$rule => array(
					'rule' => $rule,
					'message' => $rule
				),
			)
		);

		$this->__testInvalidValidationRule($rule, $this->data['test_ok']);

		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo' => array(
				'path' => TMP
			)
		));

		$this->__testOkCaseValidates();
		$this->__testRemoveCaseValidates();
	}

	public function providerTestChangeConfigurationValidationRules() {
		return array(
			array('isWritable'),
			array('isValidDir'),
		);
	}

/**
 * This simulates the case where we are uploading no file
 * to an existing record, which DOES have an existing value.
 *
 * @return void
 **/
	public function testIsFileUploadOrHasExistingValueEditingWithExistingValue() {
		$this->TestUpload->validate = array(
			'photo' => array(
				'isFileUploadOrHasExistingValue' => array(
					'rule' => 'isFileUploadOrHasExistingValue',
					'message' => 'isFileUploadOrHasExistingValue'
				),
			)
		);

		// Fixture record #1 has an existing value.
		$data = array(
			'id' => 1,
			'photo' => array(
				'tmp_name' => 'Photo.png',
				'dir' => '/tmp/php/file.tmp',
				'type' => 'image/png',
				'size' => 8192,
				'error' => UPLOAD_ERR_NO_FILE,
			)
		);
		$this->TestUpload->set($data);
		$this->assertTrue($this->TestUpload->validates());
		$this->assertEquals(0, count($this->TestUpload->validationErrors));

		$this->__testOkAndRemoveCasesValidate();
	}

	public function testIsValidMimeType() {
		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo' => array(
				'mimetypes' => array('image/bmp', 'image/jpeg')
			)
		));

		$this->TestUpload->validate = array(
			'photo' => array(
				'isValidMimeType' => array(
					'rule' => 'isValidMimeType',
					'message' => 'isValidMimeType'
				),
			)
		);

		$this->__testInvalidValidationRule('isValidMimeType', $this->data['test_ok']);

		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo' => array(
				'mimetypes' => array('image/png', 'image/jpeg')
			)
		));

		$this->__testOkAndRemoveCasesValidate();

		$this->TestUpload->validate = array(
			'photo' => array(
				'isValidMimeType' => array(
					'rule' => array('isValidMimeType', 'image/png'),
					'message' => 'isValidMimeType',
				),
			)
		);

		$this->__testOkCaseValidates();

		$this->TestUpload->validate = array('photo' => array(
			'isValidMimeType' => array('rule' => array('isValidMimeType', 'image/png', false),
		)));
		$data = array('photo' => array('error' => UPLOAD_ERR_NO_FILE));
		$this->__testSkipValidationRule('isValidMimeType', $data);
	}

	public function testIsValidExtension() {
		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo' => array(
				'extensions' => array('jpeg', 'bmp')
			)
		));

		$this->TestUpload->validate = array(
			'photo' => array(
				'isValidExtension' => array(
					'rule' => 'isValidExtension',
					'message' => 'isValidExtension'
				),
			)
		);

		$this->__testInvalidValidationRule('isValidExtension', $this->data['test_ok']);

		$this->TestUpload->set($this->data['test_ok_bmp']);
		$this->assertTrue($this->TestUpload->validates());
		$this->assertEquals(0, count($this->TestUpload->validationErrors));

		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo'
		));

		$this->TestUpload->validate['photo']['isValidExtension']['rule'] = array('isValidExtension', 'jpg');
		$this->__testInvalidValidationRule('isValidExtension', $this->data['test_ok']);

		$this->TestUpload->validate['photo']['isValidExtension']['rule'] = array('isValidExtension', array('jpg'));
		$this->__testInvalidValidationRule('isValidExtension', $this->data['test_ok']);

		$this->TestUpload->validate['photo']['isValidExtension']['rule'] = array('isValidExtension', array('jpg', 'bmp'));
		$this->__testInvalidValidationRule('isValidExtension', $this->data['test_ok']);

		$this->TestUpload->validate['photo']['isValidExtension']['rule'] = array('isValidExtension', array('jpg', 'bmp', 'png'));
		$this->__testOkCaseValidates();

		$this->TestUpload->validate = array(
			'photo' => array(
				'isFileUpload' => array(
					'rule' => 'isFileUpload',
					'message' => 'isFileUpload'
				),
				'isValidExtension' => array(
					'rule' => array('isValidExtension', array('jpg')),
					'message' => 'isValidExtension'
				),
			)
		);

		$this->__testInvalidValidationRule('isValidExtension', $this->data['test_ok']);

		$data = $this->data['test_ok'];
		$data['photo']['name'] = 'Photo.jpeg';
		$this->__testInvalidValidationRule('isValidExtension', $data);

		$this->__testRemoveCaseValidates();

		$this->TestUpload->validate = array('photo' => array(
			'isValidExtension' => array('rule' => array('isValidExtension', array('jpeg', 'bmp'), false),
		)));
		$data = array('photo' => array('error' => UPLOAD_ERR_NO_FILE));
		$this->__testSkipValidationRule('isValidExtension', $data);
	}

	public function testIsImage() {
		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'photo' => array(
				'mimetypes' => array('image/bmp', 'image/jpeg')
			)
		));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isImage', array(
			'image/bmp'
		));
		$this->assertTrue($result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isImage', array(
			'image/jpeg'
		));
		$this->assertTrue($result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isImage', array(
			'application/zip'
		));
		$this->assertFalse($result);
	}

	public function testIsMedia() {
		$this->TestUpload->Behaviors->detach('Upload.Upload');
		$this->TestUpload->Behaviors->attach('Upload.Upload', array(
			'pdf_file' => array(
				'mimetypes' => array('application/pdf', 'application/postscript')
			)
		));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isMedia', array(
			'application/pdf'
		));
		$this->assertTrue($result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isMedia', array(
			'application/postscript'
		));
		$this->assertTrue($result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isMedia', array(
			'application/zip'
		));
		$this->assertFalse($result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_isMedia', array(
			'image/jpeg'
		));
		$this->assertFalse($result);
	}

	public function testGetPathFlat() {
		$basePath = 'tests' . DS . 'path' . DS . 'flat' . DS;
		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_getPathFlat', array(
			$this->TestUpload, 'photo', TMP . $basePath
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(0, strlen($result));
	}

	public function testGetPathPrimaryKey() {
		$this->TestUpload->id = 5;
		$basePath = 'tests' . DS . 'path' . DS . 'primaryKey' . DS;
		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_getPathPrimaryKey', array(
			$this->TestUpload, 'photo', TMP . $basePath
		));

		$this->assertInternalType('integer', $result);
		$this->assertEquals(1, strlen($result));
		$this->assertEquals($result, $this->TestUpload->id);
		$this->assertTrue(is_dir(TMP . $basePath . $result));
	}

	public function testGetPathRandom() {
		$basePath = 'tests' . DS . 'path' . DS . 'random' . DS;
		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_getPathRandom', array(
			$this->TestUpload, 'photo', TMP . $basePath
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(8, strlen($result));
		$this->assertTrue(is_dir(TMP . $basePath . $result));
	}

	public function testGetPathRandomCombined() {
		$this->TestUpload->id = 5;
		$basePath = 'tests' . DS . 'path' . DS . 'random' . DS;
		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_getPathRandomCombined', array(
			$this->TestUpload, 'photo', TMP . $basePath
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(9 + strlen($this->TestUpload->id), strlen($result));
		$this->assertEquals(substr($result, 0, strlen($this->TestUpload->id)), $this->TestUpload->id);
		$this->assertTrue(is_dir(TMP . $basePath . $result));
	}

	public function testReplacePath() {
		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_path', array(
			$this->TestUpload, 'photo', array('path' => 'webroot{DS}files/{model}\\{field}{DS}')
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(WWW_ROOT . 'files' . DIRECTORY_SEPARATOR . 'test_upload' . DIRECTORY_SEPARATOR . 'photo' . DIRECTORY_SEPARATOR, $result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_path', array(
			$this->TestUpload, 'photo', array('path' => 'webroot{DS}files//{size}/{model}\\{field}{DS}{geometry}///')
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(WWW_ROOT . 'files' . DIRECTORY_SEPARATOR . '{size}' . DIRECTORY_SEPARATOR . 'test_upload' . DIRECTORY_SEPARATOR . 'photo' . DIRECTORY_SEPARATOR . '{geometry}' . DIRECTORY_SEPARATOR, $result);

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_path', array(
			$this->TestUpload, 'photo', array('isThumbnail' => false, 'path' => 'webroot{DS}files//{size}/{model}\\\\{field}{DS}{geometry}///')
		));

		$this->assertInternalType('string', $result);
		$this->assertEquals(WWW_ROOT . 'files' . DIRECTORY_SEPARATOR . 'test_upload' . DIRECTORY_SEPARATOR . 'photo' . DIRECTORY_SEPARATOR, $result);
	}

	public function testPrepareFilesForDeletion() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => 'dir'
				)
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('image/png'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'dir' => '1', 'photo' => 'Photo.png')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));

		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));
	}

	public function testPrepareFilesForDeletionWithoutDirDataFieldWithPrimaryKeyPathMethod() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'pathMethod' => 'primaryKey',
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => false
				)
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('image/png'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'photo' => 'Photo.png')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));
		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));

		$basePath	= $this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']['path'];
		$primaryKey = 1;
		$this->assertEquals($result['TestUpload'][0], sprintf('%s%d' . DS . 'Photo.png', $basePath, $primaryKey));
		$this->assertEquals($result['TestUpload'][1], sprintf('%s%d' . DS . 'xvga_Photo.png', $basePath, $primaryKey));
		$this->assertEquals($result['TestUpload'][2], sprintf('%s%d' . DS . 'vga_Photo.png', $basePath, $primaryKey));
		$this->assertEquals($result['TestUpload'][3], sprintf('%s%d' . DS . 'thumb_Photo.png', $basePath, $primaryKey));
	}

	public function testPrepareFilesForDeletionWithoutDirDataFieldWithFlagPathMethod() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'pathMethod' => 'flat',
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => false
				)
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('image/png'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'photo' => 'Photo.png')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));

		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));

		$basePath	= $this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']['path'];
		$primaryKey = 1;
		$this->assertEquals($result['TestUpload'][0], sprintf('%sPhoto.png', $basePath));
		$this->assertEquals($result['TestUpload'][1], sprintf('%sxvga_Photo.png', $basePath));
		$this->assertEquals($result['TestUpload'][2], sprintf('%svga_Photo.png', $basePath));
		$this->assertEquals($result['TestUpload'][3], sprintf('%sthumb_Photo.png', $basePath));
	}

	public function testPrepareFilesForDeletionWithThumbnailType() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => 'dir'
				),
				'thumbnailType' => 'jpg'
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('image/png'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'dir' => '1', 'photo' => 'Photo.png')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));

		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));
	}

	public function testPrepareFilesForDeletionWithMediaFileAndFalseThumbnailType() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => 'dir'
				),
				'thumbnailType' => false
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('application/pdf'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'dir' => '1', 'photo' => 'Photo.pdf')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));

		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));
	}

	public function testPrepareFilesForDeletionWithMediaFile() {
		$this->TestUpload->actsAs['Upload.Upload'] = array(
			'photo' => array(
				'thumbnailSizes' => array(
					'xvga' => '1024x768',
					'vga' => '640x480',
					'thumb' => '80x80'
				),
				'fields' => array(
					'dir' => 'dir'
				)
			)
		);
		$this->mockUpload();
		$this->MockUpload->expects($this->once())->method('_getMimeType')->will($this->returnValue('application/pdf'));

		$result = $this->protectedMethodCall($this->TestUpload->Behaviors->Upload, '_prepareFilesForDeletion', array(
			$this->TestUpload, 'photo',
			array('TestUpload' => array('id' => 1, 'dir' => '1', 'photo' => 'Photo.pdf')),
			$this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo']
		));

		$this->assertInternalType('array', $result);
		$this->assertEquals(1, count($result));
		$this->assertEquals(4, count($result['TestUpload']));
	}

	private function __testOkAndRemoveCasesValidate() {
		$this->__testOkCaseValidates();
		$this->__testRemoveCaseValidates();
	}

	private function __testValidates($data) {
		$this->TestUpload->set($data);
		$this->assertTrue($this->TestUpload->validates());
		$this->assertEquals(0, count($this->TestUpload->validationErrors));
	}

	private function __testOkCaseValidates() {
		$this->__testValidates($this->data['test_ok']);
	}

	private function __testRemoveCaseValidates() {
		$this->TestUpload->set($this->data['test_remove']);
		$this->assertTrue($this->TestUpload->validates());
		$this->assertEquals(0, count($this->TestUpload->validationErrors));
	}

	private function __testSkipValidationRule($ruleName, $data) {
		$this->TestUpload->set($data);
		$this->assertTrue($this->TestUpload->validates());
		$this->assertEquals(0, count($this->TestUpload->validationErrors));
	}

	private function __testInvalidValidationRule($ruleName, $data) {
		$this->TestUpload->set($data);
		$this->assertFalse($this->TestUpload->validates());
		$this->assertEquals(1, count($this->TestUpload->validationErrors));
		$this->assertEquals($ruleName, current($this->TestUpload->validationErrors['photo']));
	}

}


text:
package com.kotcrab.vis.editor.module.editor;

import com.google.common.eventbus.Subscribe;
import com.kotcrab.vis.editor.event.EventBusExceptionEvent;
import com.kotcrab.vis.editor.module.EventBusSubscriber;
import com.kotcrab.vis.editor.ui.toast.DetailsToast;

/** @author Kotcrab */
@EventBusSubscriber
public class EventBusExceptionMonitorModule extends EditorModule {
	private ToastModule toastModule;

	@Subscribe
	public void handleEventBusException (EventBusExceptionEvent event) {
		toastModule.show(new DetailsToast("Internal exception occurred", event.exception));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.rekognition.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.rekognition.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * SunglassesMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SunglassesMarshaller {

    private static final MarshallingInfo<Boolean> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Value").build();
    private static final MarshallingInfo<Float> CONFIDENCE_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Confidence").build();

    private static final SunglassesMarshaller instance = new SunglassesMarshaller();

    public static SunglassesMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Sunglasses sunglasses, ProtocolMarshaller protocolMarshaller) {

        if (sunglasses == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(sunglasses.getValue(), VALUE_BINDING);
            protocolMarshaller.marshall(sunglasses.getConfidence(), CONFIDENCE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements. See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership. The ASF licenses this file
  to you 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

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied. See the License for the
  specific language governing permissions and limitations
  under the License.

-->
<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>

  <artifactId>odata-fit</artifactId>
  <packaging>war</packaging>
  <name>${project.artifactId}</name>

  <parent>
    <groupId>org.apache.olingo</groupId>
    <artifactId>odata-parent</artifactId>
    <version>4.3.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
  </parent>

  <properties>
    <cobertura.skip>true</cobertura.skip>
    <!-- exclude proxy tests by default -->
    <exclude.regex>.*proxy.*</exclude.regex>
  </properties>

  <profiles>
    <profile>
      <id>build.fast</id>
      <properties>
        <pmd.skip>true</pmd.skip>
        <rat.skip>true</rat.skip>
        <checkstyle.skip>true</checkstyle.skip>
        <exclude.regex>.*(proxy|client).*</exclude.regex>
      </properties>
    </profile>
    <profile>
      <id>build.quality</id>
      <properties>
        <cobertura.skip>false</cobertura.skip>
        <!-- nothing excluded -->
        <exclude.regex></exclude.regex>
      </properties>
    </profile>
  </profiles>

  <dependencies>
    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-commons-core</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-client-core</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-client-proxy</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- REST services CXF -->
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-javamail_1.4_spec</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-client</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-security-oauth2</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
    </dependency>
    <!-- /REST services CXF -->

    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-logging-log4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jasper</artifactId>
      <exclusions>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.esigate</groupId>
      <artifactId>esigate-core</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${sl4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-vfs2</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-server-tecsvc</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-simple</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>target/maven-shared-archive-resources</directory>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <includes>
            <include>**/*ITCase.java</include>
            <include>**/*Test.java</include>
          </includes>
          <excludes>
            <exclude>%regex[${exclude.regex}]</exclude>
          </excludes>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.8</version>
        <executions>
          <execution>
            <id>unpack-dependencies</id>
            <phase>compile</phase>
            <!--<phase>package</phase>-->
            <goals>
              <goal>unpack-dependencies</goal>
            </goals>
            <configuration>
              <skip>${cobertura.skip}</skip>
              <includeGroupIds>${project.groupId}</includeGroupIds>
              <outputDirectory>${project.build.directory}/classes</outputDirectory>
              <overWriteReleases>true</overWriteReleases>
              <overWriteSnapshots>true</overWriteSnapshots>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <configuration>
          <skip>${cobertura.skip}</skip>
          <instrumentation>
            <excludes>
              <exclude>org/apache/olingo/**/tecsvc/**/*.class</exclude>
              <exclude>org/apache/olingo/**/fit/**/*.class</exclude>
              <exclude>org/apache/olingo/**/testutil/**/*.class</exclude>
            </excludes>
          </instrumentation>
          <check/>
          <aggregate>true</aggregate>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/*ITCase.java</exclude>
          </excludes>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>org.apache.olingo.fit.server.TomcatTestServer</mainClass>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <inherited>true</inherited>
        <executions>
          <execution>
            <id>compile</id>
            <phase>process-classes</phase>
            <goals>
              <goal>exploded</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <webResources>
            <resource>
              <directory>${project.build.outputDirectory}</directory>
              <!--<includes>
                <include>META-INF/DEPENDENCIES*</include>
              </includes>-->
            </resource>
          </webResources>

          <packagingExcludes>WEB-INF/classes/esigate.properties,WEB-INF/classes/META-INF/LICENSE*,WEB-INF/classes/META-INF/DEPENDENCIES*</packagingExcludes>
        </configuration>
      </plugin>

    </plugins>

  </build>
</project>


text:
package uk.co.matbooth.calameo.impl;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

import uk.co.matbooth.calameo.CalameoClient;
import uk.co.matbooth.calameo.CalameoConfig;
import uk.co.matbooth.calameo.CalameoException;
import uk.co.matbooth.calameo.ItemList;
import uk.co.matbooth.calameo.Publication;
import uk.co.matbooth.calameo.Session;
import uk.co.matbooth.calameo.SingleDrm;
import uk.co.matbooth.calameo.Subscriber;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;

public class CalameoClientImpl implements CalameoClient {
  private final Log log = LogFactory.getLog(CalameoClientImpl.class);

  private CalameoConfig config;

  public CalameoClientImpl(final CalameoConfig config) {
    this.config = config;
  }

  @Override
  public CalameoConfig getConfig() {
    if (config == null) {
      config = new CalameoConfigImpl();
    }
    return config;
  }

  /*
   * Publications
   */

  @Override
  public ItemList<Publication> getPublicationList(final int start, final int step) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.fetchSubscriptionBooks");
    params.put("start", Integer.toString(start));
    params.put("step", Integer.toString(step));
    PublicationListResponse response = executeRequest(PublicationListResponse.class, params);
    return response.getContent();
  }

  @Override
  public Publication getPublication(final String bookId) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.getBookInfos");
    params.put("book_id", bookId);
    PublicationResponse response = executeRequest(PublicationResponse.class, params);
    return response.getContent();
  }

  /*
   * Subscribers
   */

  @Override
  public ItemList<Subscriber> getSubscriberList(final int start, final int step) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.fetchSubscriptionSubscribers");
    params.put("start", Integer.toString(start));
    params.put("step", Integer.toString(step));
    SubscriberListResponse response = executeRequest(SubscriberListResponse.class, params);
    return response.getContent();
  }

  @Override
  public Subscriber getSubscriber(final String login) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.getSubscriberInfos");
    params.put("login", login);
    SubscriberResponse response = executeRequest(SubscriberResponse.class, params);
    return response.getContent();
  }

  @Override
  public void activateSubscriber(final String login) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.activateSubscriber");
    params.put("login", login);
    executeRequest(VoidResponse.class, params);
  }

  @Override
  public void deactivateSubscriber(final String login) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.deactivateSubscriber");
    params.put("login", login);
    executeRequest(VoidResponse.class, params);
  }

  @Override
  public Subscriber addSubscriber(final String login, final String password, final String firstName,
      final String lastName, final String email, final boolean isActive, final String extras) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.addSubscriber");
    params.put("login", login);
    params.put("password", password);
    params.put("firstname", firstName);
    params.put("lastname", lastName);
    params.put("email", email);
    params.put("is_active", isActive ? "1" : "0");
    params.put("extras", extras);
    SubscriberResponse response = executeRequest(SubscriberResponse.class, params);
    return response.getContent();
  }

  @Override
  public Subscriber updateSubscriber(final String login, final String newLogin, final String password,
      final String firstName, final String lastName, final String email, final boolean isActive, final String extras)
      throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.updateSubscriber");
    params.put("login", login);
    params.put("new_login", newLogin);
    params.put("password", password);
    params.put("firstname", firstName);
    params.put("lastname", lastName);
    params.put("email", email);
    params.put("is_active", isActive ? "1" : "0");
    params.put("extras", extras);
    SubscriberResponse response = executeRequest(SubscriberResponse.class, params);
    return response.getContent();
  }

  @Override
  public void deleteSubscriber(final String login) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.deleteSubscriber");
    params.put("login", login);
    executeRequest(VoidResponse.class, params);
  }

  /*
   * Subscriber Single DRMs
   */

  @Override
  public ItemList<SingleDrm> getSubscriberSingleDrmList(final String login, final int start, final int step)
      throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.fetchSubscriberDRMSingles");
    params.put("login", login);
    params.put("start", Integer.toString(start));
    params.put("step", Integer.toString(step));
    SingleDrmListResponse response = executeRequest(SingleDrmListResponse.class, params);
    return response.getContent();
  };

  @Override
  public SingleDrm addSubscriberSingleDrm(final String login, final String bookId, final String extras)
      throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.addSubscriberDRMSingle");
    params.put("login", login);
    params.put("book_id", bookId);
    params.put("extras", extras);
    SingleDrmResponse response = executeRequest(SingleDrmResponse.class, params);
    return response.getContent();
  }

  /*
   * Subscriber Sessions
   */

  @Override
  public Session authSubscriberSession(final String login) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.authSubscriberSession");
    params.put("login", login);
    SessionResponse response = executeRequest(SessionResponse.class, params);
    return response.getContent();
  }

  @Override
  public Session checkSubscriberSession(final String sessionId) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.checkSubscriberSession");
    params.put("session_id", sessionId);
    SessionResponse response = executeRequest(SessionResponse.class, params);
    return response.getContent();
  }

  @Override
  public void deleteSubscriberSession(final String sessionId) throws CalameoException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("action", "API.deleteSubscriberSession");
    params.put("session_id", sessionId);
    executeRequest(SessionResponse.class, params);
  }

  /**
   * Internal method that actually does the work of making the request to Calaméo and
   * parsing the response.
   *
   * @param responseType
   *          the class of type T that the response is expected to be
   * @param params
   *          a map of key/value pairs to be sent to Calaméo as query parameters
   * @return the response object of type T, whose class was specified in the responseType
   *         argument
   * @throws CalameoException
   *           if there was an error communicating with Calaméo
   */
  private <T extends Response<?>> T executeRequest(final Class<T> responseType, final Map<String, String> params)
      throws CalameoException {
    HttpClient client = null;
    HttpGet get = null;
    InputStreamReader entity = null;
    try {
      // Generate signed params
      Map<String, String> p = new HashMap<String, String>(params);
      p.put("apikey", getConfig().getKey());
      p.put("expires", Long.toString(new Date().getTime() + getConfig().getExpires()));
      p.put("output", "JSON");
      p.put("subscription_id", getConfig().getSubscription());
      Set<String> keys = new TreeSet<String>(p.keySet());
      StringBuilder input = new StringBuilder(getConfig().getSecret());
      for (String key : keys) {
        input.append(key);
        input.append(p.get(key));
      }
      p.put("signature", DigestUtils.md5Hex(input.toString()));
      // Configure HTTP client
      client = new DefaultHttpClient();
      // Configure GET request
      URIBuilder uri = new URIBuilder(getConfig().getEndpoint());
      for (String key : p.keySet()) {
        uri.addParameter(key, p.get(key));
      }
      get = new HttpGet(uri.build());
      log.debug("Request URI: " + get.getURI());
      // Execute request and parse response
      HttpResponse response = client.execute(get);
      entity = new InputStreamReader(response.getEntity().getContent());
      JsonElement parsed = new JsonParser().parse(entity);
      JsonElement responseJson = parsed.getAsJsonObject().get("response");
      T r = new Gson().fromJson(responseJson, responseType);
      log.debug("Response Object: " + r);
      // Return response or throw an error
      if ("error".equals(r.getStatus())) {
        CalameoException e = new CalameoException(r.getError().getCode(), r.getError().getMessage());
        log.error(e.getMessage());
        throw e;
      } else {
        return r;
      }
    } catch (IOException e) {
      log.error(e.getMessage());
      throw new CalameoException(e);
    } catch (URISyntaxException e) {
      log.error(e.getMessage());
      throw new CalameoException(e);
    } catch (JsonParseException e) {
      log.error(e.getMessage());
      throw new CalameoException(e);
    } finally {
      if (entity != null) {
        try {
          entity.close();
        } catch (IOException e) {
          log.warn(e.getMessage());
        }
      }
      if (get != null) {
        get.releaseConnection();
      }
      if (client != null) {
        client.getConnectionManager().shutdown();
      }
    }
  }
}


text:
title: FREAK
playwright: Anna Jordan
season: In House
season_sort: 30
period: Autumn
venue: New Theatre
date_start: 2016-11-02
date_end: 2016-11-05

cast:
- role: Leah
  name: Kate O'Gorman
- role: Georgie
  name: Lara Cowler

crew:
- role: Director
  name: Niamh Caines
- role: Producer
  name: Lydia Smith
- role: Technical Director
  name: Jess Donn
- role: Lighting Designer
  name: Darcey Graham
- role: Sound Designer
  name: Joanne Blunt
- role: Technical Operator
  name: Adam Humphries
- role: Technical Operator
  name: Tom Proffitt
- role: Technical Operator
  name: Hannah Burne
- role: Technical Operator
  name: Joseph Heil
- role: Technical Operator
  name: Joe Strickland
- role: Poster Designer
  name: Harry Bradley
- role: Trailer Production
  name: Gus Herbert

prod_shots: kfzbzK

assets:
  - type: poster
    image: hMsFKmw
  - type: trailer
    video: 38V5wQ4
    title: Show Trailer
  - type: backstage
    video: KcLtJX4
    title: Backstage At

links:
  - type: Review
    href: http://www.hercampus.com/school/nottingham/review-freak-nottingham-new-theatre
    snapshot: shsaN
    publisher: HerCampus
    author: Charlotte Hegley
    title: "Review: Freak at Nottingham New Theatre"
    date: 2016-11-05
    rating: 4/5
    quote: "An excellent drama presentation of modern teenage expectations of sex compared almost too closely to the consequences of adult desire."
  - type: Review
    href: http://www.impactnottingham.com/2016/11/freak-nnt/
    snapshot: 1LotF
    publisher: Impact
    author: Shanai Momi
    title: "Freak @ NNT"
    date: 2016-11-04
    rating: 8/10
    quote: "Together, these two actresses complement one another tremendously, making them an easy partnership for the audience to resonate with."
  - type: Review
    href: http://kevcastletheatrereviews.blogspot.co.uk/2016/11/freak-by-anna-jordan.html
    snapshot: NKoBz
    publisher: Kev Castle Reviews
    title: "\"Freak\" by Anna Jordan"
    date: 2016-11-03
    quote: "\"Freak\" is a powerful piece of drama and a great start to Nottingham New Theatre's new season, it will make you think, it will make you laugh and hopefully it will get you talking as well, and if you're quite truthful with yourself, it may make you change your attitude towards how you treat people, both male and female attitudes that is."

---

Georgie is thirty with dirty secrets. She drinks in her room and hides from the world. Leah is fifteen with teenage dreams. She practises her cum face and Veets. A lot. All-meat, all sex, all-vulnerable, all-powerful. There's a first time for everything…Isn't there? Anna Jordan's witty, entwining monologues combine to ask what sexual empowerment looks like in this day and age. 'Freak' is a full-on, unabashed exploration of the expectations placed upon and ultimately adopted by women in an age where it is possible to receive a high-definition sex education before having your first kiss.


text:
package org.visallo.core.model.properties.types;

import org.vertexium.Metadata;
import org.vertexium.Property;
import org.vertexium.Visibility;
import org.vertexium.mutation.ExistingElementMutation;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class MetadataVisalloProperty<TRaw, TGraph> {
    private final String metadataKey;

    protected MetadataVisalloProperty(String metadataKey) {
        this.metadataKey = metadataKey;
    }

    /**
     * Convert the raw value to an appropriate value for storage
     * in Vertexium.
     */
    public abstract TGraph wrap(final TRaw value);

    /**
     * Convert the Vertexium value to its original raw type.
     */
    public abstract TRaw unwrap(final Object value);

    public String getMetadataKey() {
        return metadataKey;
    }

    public TRaw getMetadataValue(Metadata metadata) {
        return unwrap(metadata.getValue(getMetadataKey()));
    }

    public Collection<TRaw> getMetadataValues(Metadata metadata) {
        return metadata.getValues(getMetadataKey()).stream().map(this::unwrap).collect(Collectors.toList());
    }

    public TRaw getMetadataValueOrDefault(Metadata metadata, TRaw defaultValue) {
        Object value = metadata.getValue(getMetadataKey());
        if (value == null) {
            return defaultValue;
        }
        return unwrap(value);
    }

    public TRaw getMetadataValue(Metadata metadata, TRaw defaultValue) {
        if (metadata.getEntry(getMetadataKey()) == null) {
            return defaultValue;
        }
        return unwrap(metadata.getValue(getMetadataKey()));
    }

    public TRaw getMetadataValue(Map<String, Object> metadata) {
        //noinspection unchecked
        return (TRaw) metadata.get(getMetadataKey());
    }

    public TRaw getMetadataValue(Property property) {
        return getMetadataValue(property.getMetadata());
    }

    public void setMetadata(Metadata metadata, TRaw value, Visibility visibility) {
        metadata.add(getMetadataKey(), wrap(value), visibility);
    }

    public void setMetadata(PropertyMetadata metadata, TRaw value, Visibility visibility) {
        metadata.add(getMetadataKey(), wrap(value), visibility);
    }

    public void setMetadata(ExistingElementMutation m, Property property, TRaw value, Visibility visibility) {
        m.setPropertyMetadata(property, getMetadataKey(), wrap(value), visibility);
    }
}


text:
Thank you for considering Shaderc development!  Please make sure you review
[`CONTRIBUTING.md`](CONTRIBUTING.md) for important preliminary info.

## Building

Instructions for first-time building can be found in [`README.md`](README.md).
Incremental build after a source change can be done using `ninja` (or
`cmake --build`) and `ctest` exactly as in the first-time procedure.

## Code reviews

(Terminology: we consider everyone with write access to our GitHub repo a
project _member_.)

All submissions, including submissions by project members, require review.  We
use GitHub pull requests to facilitate the review process.  A submission may be
accepted by any project member (other than the submitter), who will then squash
the changes into a single commit and cherry-pick them into the repository.

Before accepting, there may be some review feedback prompting changes in the
submission.  You should expect reviewers to strictly insist on the
[commenting](https://google.github.io/styleguide/cppguide.html#Comments)
guidelines -- in particular, every file, class, method, data member, and global
will require a comment.  Reviewers will also expect to see test coverage for
every code change.  _How much_ coverage will be a judgment call on a
case-by-case basis, balancing the required effort against the incremental
benefit.  Coverage will be expected.  As a matter of development philosophy,
we will strive to engineer the code to make writing tests easy.

## Coding style

For our C++ files, we use the
[Google C++ style guide](https://google.github.io/styleguide/cppguide.html).
(Conveniently, the formatting rules it specifies can be achieved using
`clang-format -style=google`.)

For our Python files, we use the
[Google Python style guide](https://google.github.io/styleguide/pyguide.html).

## Supported platforms

We expect Shaderc to always build and test successfully on the platforms listed
below.  Please keep that in mind when offering contributions.  This list will
likely grow over time.

| Platform | Build Status |
|:--------:|:------------:|
| Android (ARMv7)  | Not Automated |
| Linux (x86_64)   | [![Linux Build Status](https://travis-ci.org/google/shaderc.svg)](https://travis-ci.org/google/shaderc "Linux Build Status") |
| Mac OS X | [![Mac Build Status](https://travis-ci.org/google/shaderc.svg)](https://travis-ci.org/google/shaderc "Mac Build Status") |
| Windows (x86_64) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/g6c372blna7vnk1l?svg=true)](https://ci.appveyor.com/project/dneto0/shaderc "Windows Build Status") |


text:
> HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It was finalized, and published, on 28 October 2014 by the World Wide Web Consortium (W3C).[2][3] This is the fifth revision of the HTML standard since the inception of the World Wide Web. The previous version, HTML 4, was standardized in 1997.

> Its core aims are to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers, etc.). - [HTML5 - Wikipedia](https://en.wikipedia.org/wiki/HTML5)

- [Apprentice](apprentice.md)
- [Journeyman](journeyman.md)
- [Master](master.md)

-----

*Is this page missing something? Submit a PR and review it with a master in this category*


text:
require 'spec_helper'
require 'guignol/models/instance'

describe Guignol::Models::Instance do
  subject { described_class.new(name, options) }

  let(:name) { "foobar" }
  let(:options) {{
    :uuid => '948DB8E9-A356-4F66-8857-165FBDF5A71F'
  }}

  describe '#initialize' do
    it 'should require :uuid' do
      options.delete :uuid
      expect { subject }.to raise_error
    end

    it 'should require a name' do
      name.replace ""
      expect { subject }.to raise_error
    end

    it 'should pass with minimal options' do
      expect { subject }.to_not raise_error
    end

    it 'parses ERB in user data' do
      options[:foo] = 'bar'
      options[:user_data] = "foo=<%= foo %>,<%= name %>"
      subject.options[:user_data].should == 'foo=bar,foobar'
    end
  end

  describe '#create' do
    it 'set server tags' do
      expected_tags = {'Name' => name, 'UUID' => options[:uuid]}

      subject.connection.should_receive(:create_tags)
        .with(anything, {'Domain' => nil}.merge(expected_tags))
        .and_return(double(:status => 200))

      subject.create
    end

    it "configures DNS properly" do
      subject.should_receive(:update_dns)
      subject.create
    end

    it 'should pass with minimal options' do
      expect { subject.create }.to_not raise_error
    end

    it 'does not break when providing an availibity zone' do
      instance = described_class.new(name, options.merge(:availability_zone => 'eu-west-1c'))
      expect { instance.create }.to_not raise_error
    end

    it 'does not break when providing a root ebs size' do
      instance = described_class.new(name, options.merge(:root_ebs_size => 30))
      expect { instance.create }.to_not raise_error
    end

    it 'does not allow an availability zone that does not match the region' do
      instance = described_class.new(name, options.merge(:availability_zone => 'us-west-1a'))
      expect { instance.create }.to raise_error('availability zone us-west-1a is not in the defined region eu-west-1')
    end

    it 'does not allow a non numeric root ebs size' do
      instance = described_class.new(name, options.merge(:root_ebs_size => 'foobar'))
      expect { instance.create }.to raise_error
    end

    it 'requires existing volumes to live in a given availability zone'
    it 'reuses existing volumes'
    it 'fails when existing volumes are in different zones'

    it 'starts up the server'
  end

  describe "#id" do
    it "returns nil when there is no 'subject' (server)" do
      instance = Guignol::Models::Instance.new(name, options)
      instance.stub(:subject).and_return(nil)

      instance.id.should be_nil
    end

    it "returns the id when 'subject' has no id" do
      instance = Guignol::Models::Instance.new(name, options)
      instance.stub(:subject).and_return(double)

      instance.id.should be_nil
    end

    it "returns the id when 'subject' exists and has an id" do
      instance = Guignol::Models::Instance.new(name, options)
      instance.stub(:subject).and_return(double(:id => 'i-123456'))

      instance.id.should == 'i-123456'
    end
  end

  describe '#start' do

    it 'returns when the server does not exist' do
      instance = Guignol::Models::Instance.new(name, options)
      instance.stub(:subject).and_return(nil)

      instance.start.should be_nil
    end

    it 'returns with a server marked as "running"'
  end

  describe '#destroy' do
    it 'should pass with minimal options' do
      expect { subject.destroy }.to_not raise_error
    end
  end
end


text:
package com.evolveum.midpoint.testing.selenide.tests.basictests;

import static com.codeborne.selenide.Condition.*;

import com.codeborne.selenide.SelenideElement;
import com.evolveum.midpoint.testing.selenide.tests.AbstractSelenideTest;
import org.openqa.selenium.By;
import org.testng.annotations.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.codeborne.selenide.Selectors.byAttribute;
import static com.codeborne.selenide.Selectors.byText;
import static com.codeborne.selenide.Selectors.byValue;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.close;

/**
 * Created by Kate on 22.08.2015.
 */
public class RoleTests extends AbstractSelenideTest {
    //role fields
    public static final String ROLE_NAME_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:0:property:values:0:value:valueContainer:input:input";
    public static final String ROLE_DISPLAY_NAME_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:1:property:values:0:value:valueContainer:input:input";
    public static final String ROLE_DESCRIPTION_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:2:property:values:0:value:valueContainer:input:input";
    public static final String ROLE_TYPE_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:15:property:values:0:value:valueContainer:input:input";
    public static final String ROLE_IDENTIFIER_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:3:property:values:0:value:valueContainer:input:input";
    public static final String ROLE_RISK_LEVEL_FIELD = "tabPanel:panel:focusForm:body:containers:0:container:properties:12:property:values:0:value:valueContainer:input:input";
    //role values
    public static final String ROLE_NAME_VALUE = "TestRole";
    public static final String ROLE_DISPLAY_NAME_VALUE = "RoleDisplayName";
    public static final String ROLE_DESCRIPTION_VALUE = "RoleDescription";
    public static final String ROLE_TYPE_VALUE = "RoleType";
    public static final String ROLE_IDENTIFIER_VALUE = "RoleIdentifier";
    public static final String ROLE_RISK_LEVEL_VALUE = "RoleRiskLevel";

    private Map<String, String> roleAttributes = new HashMap<>();

    @Test(priority = 0)
    public void test001createRoleTest(){
        close();
        login();
        //click Roles menu
        $(By.partialLinkText("Roles")).shouldBe(visible).click();
        //click New role menu item
        $(By.partialLinkText("New role")).shouldBe(visible).click();
        //set new role attributes
        roleAttributes.put(ROLE_NAME_FIELD, ROLE_NAME_VALUE);
        roleAttributes.put(ROLE_DISPLAY_NAME_FIELD, ROLE_DISPLAY_NAME_VALUE);
        roleAttributes.put(ROLE_DESCRIPTION_FIELD, ROLE_DESCRIPTION_VALUE);
        roleAttributes.put(ROLE_TYPE_FIELD, ROLE_TYPE_VALUE);
        roleAttributes.put(ROLE_IDENTIFIER_FIELD, ROLE_IDENTIFIER_VALUE);
        roleAttributes.put(ROLE_RISK_LEVEL_FIELD, ROLE_RISK_LEVEL_VALUE);
        setFieldValues(roleAttributes);
        //click Save button
        $(By.linkText("Save")).shouldBe(visible).click();
        //check if Success message appears
        $(byText("Success")).shouldBe(visible);
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE)).shouldBe(visible).click();
        //check role attributes are filled in with correct values
        checkObjectAttributesValues(roleAttributes);

    }

    @Test(priority = 1, dependsOnMethods = {"test001createRoleTest"})
    public void test002updateRoleTest(){
        //click Roles menu
//        $(By.partialLinkText("Roles")).shouldBe(visible).click(); // clicked in previous test
        //click List roles menu item
        $(By.partialLinkText("List roles")).shouldBe(visible).click();
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE)).shouldBe(visible).click();
        //update role attributes values
        Set<String> attributeFielldNames = roleAttributes.keySet();
        Map<String, String> roleAttributesUpdated = new HashMap<>();
        for (String attributeFieldName : attributeFielldNames){
            roleAttributesUpdated.put(attributeFieldName, roleAttributes.get(attributeFieldName) + UPDATED_VALUE);
        }
        setFieldValues(roleAttributesUpdated);
        //click Save button
        $(By.linkText("Save")).shouldBe(visible).click();
        //check if Success message appears
        $(byText("Success")).shouldBe(visible);
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE + UPDATED_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE  + UPDATED_VALUE)).shouldBe(visible).click();
        //check role attributes are filled in with correct values
        checkObjectAttributesValues(roleAttributesUpdated);
    }

    @Test (priority = 2, dependsOnMethods = {"test001createRoleTest"})
    public void test003deleteRoleTest(){
        //click Roles menu
//        $(By.partialLinkText("Roles")).shouldBe(visible).click(); // clicked in previous test
        //click List roles menu item
        $(By.partialLinkText("List roles")).shouldBe(visible).click();
        //search for created role
        searchForElement(ROLE_NAME_VALUE + UPDATED_VALUE);
        //select found role checkbox
        $(byAttribute("type", "checkbox")).shouldBe(visible).click();
        //click on the menu icon in the upper right corner of the roles list
        $(By.className("cog")).find(By.className("caret")).shouldBe(visible).click();
        //click Delete menu item
        $(By.linkText("Delete")).shouldBe(visible).click();
        //click Yes button in the Confirm delete window
        $(By.linkText("Yes")).shouldBe(visible).click();
        //check if success message appears after role deletion
        $(byText("The role(s) have been successfully deleted.")).shouldBe(visible);
    }

}


text:
<?php

namespace Ekyna\Bundle\OrderBundle\Service;

use Ekyna\Component\Sale\Order\OrderInterface;
use Ekyna\Component\Sale\Order\OrderItemInterface;
use Ekyna\Component\Sale\Payment\PaymentStates;
use Ekyna\Component\Sale\Tax\TaxAmount;
use Ekyna\Component\Sale\Tax\TaxesAmounts;

/**
 * Class Calculator
 * @package Ekyna\Bundle\OrderBundle\Service
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class Calculator implements CalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculateOrderItemTotal(OrderItemInterface $item, $ati = false)
    {
        $total = $item->getPrice() * $item->getQuantity();
        if ($ati && null !== $tax = $item->getTax()) {
            $total *= 1 + $tax->getRate();
        }
        return $total;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderItemsTotal(OrderInterface $order, $ati = false)
    {
        $total = 0;
        foreach ($order->getItems() as $item) {
            $total += $this->calculateOrderItemTotal($item, $ati);
        }
        return $total;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderShipmentTotal(OrderInterface $order, $ati = false)
    {
        return 0; /* TODO */
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderTotal(OrderInterface $order, $ati = false)
    {
        return $this->calculateOrderItemsTotal($order, $ati)
             + $this->calculateOrderShipmentTotal($order, $ati);
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderItemTaxAmount(OrderItemInterface $item)
    {
        if (null !== $tax = $item->getTax()) {
            return new TaxAmount(
                $item->getTax(),
                $this->calculateOrderItemTotal($item, true) - $this->calculateOrderItemTotal($item)
            );
        }
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderTaxesAmounts(OrderInterface $order)
    {
        $taxesAmounts = new TaxesAmounts();
        foreach ($order->getItems() as $item) {
            if (null !== $taxAmount = $this->calculateOrderItemTaxAmount($item)) {
                $taxesAmounts->addTaxAmount($taxAmount);
            }
        }
        return $taxesAmounts;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderItemTotalWeight(OrderItemInterface $item)
    {
        return $item->getWeight() * $item->getQuantity();
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderTotalWeight(OrderInterface $order)
    {
        $total = 0;
        foreach ($order->getItems() as $item) {
            $total += $this->calculateOrderItemTotalWeight($item);
        }
        return $total;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderItemsCount(OrderInterface $order)
    {
        $count = 0;
        foreach ($order->getItems() as $item) {
            $count += $item->getQuantity();
        }
        return $count;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderPaidTotal(OrderInterface $order)
    {
        $total = 0;
        foreach ($order->getPayments() as $payment) {
            if (in_array($payment->getState(), [PaymentStates::STATE_AUTHORIZED, PaymentStates::STATE_CAPTURED])) {
                $total += $payment->getAmount();
            }
        }
        return $total;
    }

    /**
     * {@inheritdoc}
     */
    public function calculateOrderRemainingTotal(OrderInterface $order)
    {
        $amount = $this->calculateOrderTotal($order, true) - $this->calculateOrderPaidTotal($order);
        if (0 > $amount) {
            $amount = 0;
        }
        return $amount;
    }

    /**
     * {@inheritdoc}
     */
    public function updateTotals(OrderInterface $order)
    {
        // TODO: Adjustments / Shipping
        $order
            ->setItemsCount($this->calculateOrderItemsCount($order))
            ->setTotalWeight($this->calculateOrderTotalWeight($order))
            ->setNetTotal($this->calculateOrderTotal($order))
            ->setAtiTotal($this->calculateOrderTotal($order, true))
        ;
    }
}


text:
<!--
  Copyright 2014 - 2022 Blazebit.

  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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

   <servers>
      <server>
         <id>sonatype-nexus-snapshots</id>
         <username>${env.SONATYPE_USERNAME}</username>
         <password>${env.SONATYPE_PASSWORD}</password>
      </server>
   </servers>

   <profiles>
      <profile>
         <id>blazebit-release</id>
         <repositories>
            <repository>
               <id>sonatype-nexus-snapshots</id>
               <name>Sonatype Nexus Snapshots</name>
               <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
            </repository>
         </repositories>
      </profile>
   </profiles>

</settings>


text:
<?php

namespace	cs\modules\Home;
use			cs\Index,
			cs\Page,
			cs\User;
$User	= User::instance();
if ($User->guest()) {
	error_code(403);
	return;
}
$Index	= Index::instance();
if (!isset($Index->route_ids[0], $_POST['confirmation_code'])) {
	error_code(400);
	return;
}
$Goods		= Goods::instance();
$added_by	= array_column($Goods->unconfirmed($User->id), 'id');
if (!in_array($Index->route_ids[0], $added_by)) {
	error_code(403);
	return;
}
$driver = Volunteers::instance()->get_driver_by_code($_POST['confirmation_code']);
if (!$driver) {
	error_code(404);
	Page::instance()->error('Водія з таким кодом не знайдено');
	return;
}
if (!$Goods->set_driver($Index->route_ids[0], $driver['id'])) {
	error_code(500);
}


text:
@implementation UserDetailTableViewCell

- (void)dealloc {
    [keyLabel release];
    [valueLabel release];
    [super dealloc];
}

- (void)setKeyText:(NSString *)text
{
    keyLabel.text = text;
}

- (void)setValueText:(NSString *)text
{
    valueLabel.text = text;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    if (self.selectionStyle != UITableViewCellSelectionStyleNone) {
        keyLabel.textColor =
            selected ? [UIColor whiteColor] : [UIColor codeWatchLabelColor];
        valueLabel.textColor =
            selected ? [UIColor whiteColor] : [UIColor blackColor];
    }
}

@end


text:
phpqa container
===============

This Dockerfile was inspired by the [docker-phpqa](https://github.com/herdphp/docker-phpqa) project,
borrowing their original file so we can make some customizations. Once the project stabilizes we will
review for being able to just pull upstream and work with their images.

# Starting a container

docker build -it bitcoinconsensusbuild .
docker run -it -v /path/to/output:/usr/src/php/lcov_html -v /path/to/bitcoinconsensus-php/bitcoinconsensus:/usr/src/php/ext/bitcoinconsensus --name s1 bitcoinconsensusbuild


text:
<?php

$ch = curl_init();

$url = 'http://localhost/lines/index.php?';
//Edit your options as needed
$url .= http_build_query(array(
            'dir' => dirname(__DIR__),
            'options' => array(
                'ignoreFolders' => explode(', ', '.svn, backups, db, nbproject, assets, commands, data, extensions, messages, runtime, tests'),
                'ignoreFiles' => explode(', ', 'index-test.php, jquery-1.5.js, jquery-1.5.min.js, yiic.php'),
                'extensions' => explode(', ', 'php, js'),
                'whitespace' => false, //Whether to count blank lines
                'comments' => false, //Wheter to count comments
            ),
        ));

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$output = curl_exec($ch);
echo $output;

curl_close($ch);
?>


text:
define(function(require) {
	require("$UI/system/components/justep/common/res");
	var justep = require("$UI/system/lib/justep");
	var url = require.normalizeName("./progress");
	var ComponentConfig = require("./progress.config");
	var Progress = justep.BindComponent.extend({
		getConfig : function() {
			return ComponentConfig;
		},

		constructor : function(options) {
			this.valuenow = '';
			this.valuemax = 100;
			this.textVisible = true;
			this.callParent(options);
		},

		init: function(value, bindingContext){
			this.callParent(value, bindingContext);
		},

		propertyChangedHandler : function(key, oldVal, value) {
			this.callParent(key, oldVal, value);
			if(key == "valuenow"){
				var progress = Math.round((parseFloat(value||0)*100.0)/this.valuemax);
				$(">.progress-bar",this.$domNode).css("width",progress+"%");
				var eData = { source : this, valuenow : this.value, progress : progress+"%" };
				this.fireEvent('onRender', eData);
				$(">.progress-bar>span",this.$domNode).html(eData.progress);
			}else if(key == 'textVisible'){
				$(">.progress-bar>span",this.$domNode)["false" == (""+value)?"addClass":"removeClass"]("sr-only");
			}
		}
	});

	justep.Component.register(url, Progress);
	return Progress;
});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AppCampus.SignboardApi.Models.QueryModels
{
    /// <summary>
    /// The Diagnostic Input Model
    /// </summary>
    public class DiagnosticInputModel
    {
        /// <summary>
        /// The Date of the diagnostic
        /// </summary>
        [Required]
        public DateTime DiagnosticDate { get; set; }

        /// <summary>
        /// The Software version installed on the Signboard
        /// </summary>
        [Required]
        public string SoftwareVersion { get; set; }

        /// <summary>
        /// The List of Metrics and values
        /// </summary>
        public List<DiagnosticMetricInputModel> Metrics { get; set; }

        /// <summary>
        /// The object containing the Health states of the screen
        /// </summary>
        public SignboardHealthModel SignboardHealth { get; set; }

    }
}


text:
It allows to add easily and quickly RESTful API to your nodejs app, to be used with MongoDB.

It is based on https://github.com/tdegrunt/mongodb-rest.

## Install and setting

* install library `npm install restful-mongo`
* create a config file in the root of your project, whose content is like this:

```

module.exports = {
	db: {
		username: '',
		password:'',
		host: 'localhost',
		port: 27017
	},
	"flavor": "nounderscore",
	"debug": true
}

```

* add routers to your app in app.js files

```
var app = express();
,	config=require('./config.js')
,	restfulMongo=require('../../index.js');

restfulMongo.configure(app, config );

```

Installation and configuration is completed.

## Documentation

### GET method

To get all resources contained in a collection, use the following url:

* `/api/database_name/collection_name`

To get a single resource, append _id value to the prevouos url, like the following:

* `/api/database_name/collection_name/_id`

GET method supports the following parameters:

* sort: to sort the results, for example `?sort=-_id,name` sort the results by _id field, in descending order, and then by name, in ascending order
* fields: to apply projection to the results, for example `?fields=name,_id` returns an array of objects with only 2 fields: name and _id
* query: to query specific objects, you can specify condition on evenry single object dirrectly as parameters, separated by comma. For example `?name=giovanni,age=18` returns only objects that has 'giovanni' as name and '18' as age. You can specify more complex query too. See below documentation about comples query

### POST method
### PUT method
### DELETE method


text:
package com.soomla.store.domain;

import com.soomla.store.StoreUtils;
import com.soomla.store.data.JSONConsts;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class represents an item in the Market.
 * Every PurchasableVirtualItem with PurchaseType of PurchaseWithMarket has an instance of this class which is a
 * representation of the same currency pack as an item on the Market.
 */
public class MarketItem {

    /** Constructor
     *
     * @param mProductId is the Id of the current item in Google Play.
     * @param mManaged is the Managed type of the current item in Google Play.
     * @param mPrice is the actual $$ cost of the current item in Google Play.
     */
    public MarketItem(String mProductId, Managed mManaged, double mPrice) {
        this.mProductId = mProductId;
        this.mManaged = mManaged;
        this.mPrice = mPrice;
    }

    /** Constructor
     *
     * Generates an instance of {@link MarketItem} from a JSONObject.
     * @param jsonObject is a JSONObject representation of the wanted {@link MarketItem}.
     * @throws JSONException
     */
    public MarketItem(JSONObject jsonObject) throws JSONException {
        if (jsonObject.has(JSONConsts.MARKETITEM_MANAGED)) {
            this.mManaged = Managed.values()[jsonObject.getInt(JSONConsts.MARKETITEM_MANAGED)];
        } else {
            this.mManaged = Managed.UNMANAGED;
        }
        if (jsonObject.has(JSONConsts.MARKETITEM_ANDROID_ID)) {
            this.mProductId = jsonObject.getString(JSONConsts.MARKETITEM_ANDROID_ID);
        } else {
            this.mProductId = jsonObject.getString(JSONConsts.MARKETITEM_PRODUCT_ID);
        }
        this.mPrice = jsonObject.getDouble(JSONConsts.MARKETITEM_PRICE);
    }

    public JSONObject toJSONObject(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(JSONConsts.MARKETITEM_MANAGED, mManaged.ordinal());
            jsonObject.put(JSONConsts.MARKETITEM_ANDROID_ID, mProductId);
            jsonObject.put(JSONConsts.MARKETITEM_PRICE, new Double(mPrice));
        } catch (JSONException e) {
            StoreUtils.LogError(TAG, "An error occured while generating JSON object.");
        }

        return jsonObject;
    }

    /** Getters **/

    public String getProductId() {
        return mProductId;
    }

    public Managed getManaged() {
        return mManaged;
    }

    public void setManaged(Managed managed) {
        this.mManaged = managed;
    }

    public double getPrice() {
        return mPrice;
    }

    public String getMarketPrice() {
        return mMarketPrice;
    }

    public String getMarketTitle() {
        return mMarketTitle;
    }

    public String getMarketDescription() {
        return mMarketDescription;
    }

    /** Setters**/

    public void setMarketPrice(String mMarketPrice) {
        this.mMarketPrice = mMarketPrice;
    }

    public void setMarketTitle(String mMarketTitle) {
        this.mMarketTitle = mMarketTitle;
    }

    public void setMarketDescription(String mMarketDescription) {
        this.mMarketDescription = mMarketDescription;
    }

    /** Private members **/

    /**
     * Each product in the catalog can be MANAGED, UNMANAGED, or SUBSCRIPTION.  MANAGED
     * means that the product can be purchased only once per user (such as a new
     * level in a game). The purchase is remembered by Android Market and
     * can be restored if this application is uninstalled and then
     * re-installed. UNMANAGED is used for products that can be used up and
     * purchased multiple times (such as poker chips). It is up to the
     * application to keep track of UNMANAGED products for the user.
     * SUBSCRIPTION is just like MANAGED except that the user gets charged monthly
     * or yearly.
     */
    public static enum Managed { MANAGED, UNMANAGED, SUBSCRIPTION }

    private Managed mManaged;
    /**
     *  The Id of this VirtualGood in Google Market
    */

    private static final String TAG = "SOOMLA MarketItem";

    private String mProductId;
    private double mPrice;

    private String mMarketPrice;
    private String mMarketTitle;
    private String mMarketDescription;
}


text:
require 'abstract_unit'
require 'fixtures/reference_type'
require 'fixtures/reference_code'

class CompositeArraysTest < ActiveSupport::TestCase

  def test_new_primary_keys
    keys = CompositePrimaryKeys::CompositeKeys.new
    assert_not_nil keys
    assert_equal '', keys.to_s
    assert_equal '', "#{keys}"
  end

  def test_initialize_primary_keys
    keys = CompositePrimaryKeys::CompositeKeys.new([1,2,3])
    assert_not_nil keys
    assert_equal '1,2,3', keys.to_s
    assert_equal '1,2,3', "#{keys}"
  end

  def test_to_composite_keys
    keys = [1,2,3].to_composite_keys
    assert_equal CompositePrimaryKeys::CompositeKeys, keys.class
    assert_equal '1,2,3', keys.to_s
  end

  def test_new_ids
    keys = CompositePrimaryKeys::CompositeIds.new
    assert_not_nil keys
    assert_equal '', keys.to_s
    assert_equal '', "#{keys}"
  end

  def test_initialize_ids
    keys = CompositePrimaryKeys::CompositeIds.new([1,2,3])
    assert_not_nil keys
    assert_equal '1,2,3', keys.to_s
    assert_equal '1,2,3', "#{keys}"
  end

  def test_to_composite_ids
    keys = [1,2,3].to_composite_ids
    assert_equal CompositePrimaryKeys::CompositeIds, keys.class
    assert_equal '1,2,3', keys.to_s
  end

  def test_flatten
    keys = [CompositePrimaryKeys::CompositeIds.new([1,2,3]), CompositePrimaryKeys::CompositeIds.new([4,5,6])]
    assert_equal 6, keys.flatten.size
  end
end