text:
<?php
App::uses('AppModel', 'Model');
App::uses('ModelBehavior', 'Model');
App::uses('CakeTime', 'Utility');
App::uses('DataTypeJugglingBehavior', 'DataTypeJuggling.Model' . DS . 'Behavior');

/**
 * Test Model
 *
 */
if (!class_exists('TestModel')) {
	class TestModel extends AppModel {}
}

/**
 * Data Type Juggling Behavior Test
 *
 * PHP 5
 *
 * Copyright (c) WizeHive, Inc. (http://www.wizehive.com)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @since       1.0
 * @package     DataTypeJuggling
 * @subpackage  DataTypeJuggling.Test.Case.Model.Behavior
 * @copyright   Copyright (c) WizeHive, Inc. (http://www.wizehive.com)
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 */
class DataTypeJugglingBehaviorTest extends CakeTestCase {

	/**
	 * Setup
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function setUp() {

		parent::setUp();

		$this->TestModel = $this->getMock('TestModel', array('getColumnType'));

		$this->DataTypeJuggling = new DataTypeJugglingBehavior();

		$this->DataTypeJuggling->setup($this->TestModel);

	}

	/**
	 * Tear Down
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function tearDown () {

		parent::tearDown();

		unset($this->DataTypeJuggling);

		unset($this->TestModel);

		ClassRegistry::flush();

	}

	/**
	 * Test Before Validate - Empty Data
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeValidateEmptyData() {

		$this->TestModel->data = array();

		$this->assertTrue($this->DataTypeJuggling->beforeValidate($this->TestModel));

		$this->assertEquals(array(), $this->TestModel->data);

	}

	/**
	 * Test Before Validate - Results
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeValidate() {

		$data = array(
			'is_active' => 'true',
			'name' => 'text',
			'is_bool' => '0',
			'is_null' => 'null'
		);

		$this->TestModel
			->expects($this->at(0))
			->method('getColumnType')
			->with('is_active')
			->will($this->returnValue('boolean'));

		$this->TestModel
			->expects($this->at(1))
			->method('getColumnType')
			->with('name')
			->will($this->returnValue('string'));

		$this->TestModel
			->expects($this->at(2))
			->method('getColumnType')
			->with('is_bool')
			->will($this->returnValue('boolean'));

		$this->TestModel->data[$this->TestModel->alias] = $data;

		$this->assertTrue($this->DataTypeJuggling->beforeValidate($this->TestModel));

		$expected = array(
			'is_active' => true,
			'name' => 'text',
			'is_bool' => false,
			'is_null' => null
		);

		$this->assertEquals($expected, $this->TestModel->data[$this->TestModel->alias]);

	}

	/**
	 * Test Before Save - Empty Data
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeSaveEmptyData() {

		$this->TestModel->data = array();

		$this->assertTrue($this->DataTypeJuggling->beforeSave($this->TestModel));

		$this->assertEquals(array(), $this->TestModel->data);

	}

	/**
	 * Test Before Save - Results
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeSave() {

		$data = array(
			'is_active' => 'true',
			'name' => 'text',
			'is_bool' => '0',
			'is_null' => 'null'
		);

		$this->TestModel
			->expects($this->at(0))
			->method('getColumnType')
			->with('is_active')
			->will($this->returnValue('boolean'));

		$this->TestModel
			->expects($this->at(1))
			->method('getColumnType')
			->with('name')
			->will($this->returnValue('string'));

		$this->TestModel
			->expects($this->at(2))
			->method('getColumnType')
			->with('is_bool')
			->will($this->returnValue('boolean'));

		$this->TestModel->data[$this->TestModel->alias] = $data;

		$this->assertTrue($this->DataTypeJuggling->beforeSave($this->TestModel));

		$expected = array(
			'is_active' => 1,
			'name' => 'text',
			'is_bool' => 0,
			'is_null' => null
		);

		$this->assertInternalType('integer', $this->TestModel->data[$this->TestModel->alias]['is_active']);
		$this->assertInternalType('string', $this->TestModel->data[$this->TestModel->alias]['name']);
		$this->assertInternalType('integer', $this->TestModel->data[$this->TestModel->alias]['is_bool']);

		$this->assertEquals($expected, $this->TestModel->data[$this->TestModel->alias]);

	}

	/**
	 * Test Before Find - With Parse Types Off
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeFindWithParseTypesOff() {

		$query = array(
			'conditions' => array(
				'User.id' => 1,
				'User.is_active' => 'true'
			)
		);

		$this->assertEquals(
			$query,
			$this->DataTypeJuggling->beforeFind($this->TestModel, $query)
		);

	}

	/**
	 * Test Before Find - Parse Types On
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testBeforeFindParseTypesOn() {

		$query = array(
			'conditions' => array(
				'User.id' => array(1, 2, 3),
				'User.is_active' => 'true'
			),
			'parseTypes' => true
		);

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with('is_active')
			->will($this->returnValue('boolean'));

		$result = $this->DataTypeJuggling->beforeFind($this->TestModel, $query);

		$expected = array(
			'conditions' => array(
				'User.id' => array(1, 2, 3),
				'User.is_active' => true
			),
			'parseTypes' => true
		);

		$this->assertEquals($expected, $result);

	}

	/**
	 * Test After Find - Not Primary
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindNotPrimary() {

		$data = array($this->TestModel->alias => array('field' => 'value'));

		$results = $this->DataTypeJuggling->afterFind($this->TestModel, $data, false);

		$this->assertEquals($data, $results);

	}

	/**
	 * Test After Find - Empty Data
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindEmptyData() {

		$data = array($this->TestModel->alias => array());

		$results = $this->DataTypeJuggling->afterFind($this->TestModel, $data, true);

		$this->assertEquals($data, $results);

	}

	/**
	 * Test After Find - Test Array Value
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindArrayValue() {

		$results = array(
			array(
				$this->TestModel->alias => array(
					'test_array' => array()
				)
			)
		);

		$this->assertEquals($results, $this->DataTypeJuggling->afterFind($this->TestModel, $results, true));

	}

	/**
	 * Test After Find - Test Null Value
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindNullValue() {

		$results = array(
			array(
				$this->TestModel->alias => array(
					'test_null' => null
				)
			)
		);

		$this->assertEquals($results, $this->DataTypeJuggling->afterFind($this->TestModel, $results, true));

	}

	/**
	 * Test After Find - Test Boolean Value
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindBooleanValue() {

		$results = array(
			array(
				$this->TestModel->alias => array(
					'test_boolean' => 1
				)
			)
		);

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with('test_boolean')
			->will($this->returnValue('boolean'));

		$expected = array(
			array(
				$this->TestModel->alias => array(
					'test_boolean' => true
				)
			)
		);

		$this->assertEquals(
			$expected,
			$this->DataTypeJuggling->afterFind($this->TestModel, $results, true)
		);

	}

	/**
	 * Test After Find - Test String Value
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindStringValue() {

		$results = array(
			array(
				$this->TestModel->alias => array(
					'test_string' => 'text'
				)
			)
		);

		$this->TestModel
			->expects($this->at(0))
			->method('getColumnType')
			->with('test_string')
			->will($this->returnValue('text'));

		$this->assertEquals(
			$results,
			$this->DataTypeJuggling->afterFind($this->TestModel, $results, true)
		);

	}

	/**
	 * Test After Find - Test Integer Value
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testAfterFindIntegerValue() {

		$results = array(
			array(
				$this->TestModel->alias => array(
					'test_numeric' => 100
				)
			)
		);

		$this->TestModel
			->expects($this->at(0))
			->method('getColumnType')
			->with('test_numeric')
			->will($this->returnValue('integer'));

		$this->assertEquals(
			$results,
			$this->DataTypeJuggling->afterFind($this->TestModel, $results, true)
		);

	}

	/**
	 * Test Convert Data Type - Empty Type
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertDataTypeEmptyType() {

		$data = 1;

		$type = null;

		$this->assertEquals(
			$data,
			$this->DataTypeJuggling->convertDataType($this->TestModel, $data, $type)
		);

	}

	/**
	 * Test Convert Data Type - Many Tests
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertDataType() {

		// Integers
		$this->assertEquals(1, $this->DataTypeJuggling->convertDataType($this->TestModel, '1', 'int'));
		$this->assertInternalType('integer', $this->DataTypeJuggling->convertDataType($this->TestModel, '1', 'int'));

		$this->assertNull($this->DataTypeJuggling->convertDataType($this->TestModel, null, 1));
		$this->assertInternalType('null', $this->DataTypeJuggling->convertDataType($this->TestModel, null, 'int'));

		$this->assertEquals(1, $this->DataTypeJuggling->convertDataType($this->TestModel, 1, 'int'));
		$this->assertInternalType('integer', $this->DataTypeJuggling->convertDataType($this->TestModel, 1, 'int'));

		$this->assertEquals(2, $this->DataTypeJuggling->convertDataType($this->TestModel, 2, 'integer'));
		$this->assertInternalType('integer', $this->DataTypeJuggling->convertDataType($this->TestModel, 2, 'integer'));

		// Booleans
		$this->assertEquals(true, $this->DataTypeJuggling->convertDataType($this->TestModel, 'true', 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, 'true', 'boolean'));

		$this->assertEquals(true, $this->DataTypeJuggling->convertDataType($this->TestModel, '1', 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, '1', 'boolean'));

		$this->assertEquals(true, $this->DataTypeJuggling->convertDataType($this->TestModel, 1, 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, 1, 'boolean'));

		$this->assertEquals(false, $this->DataTypeJuggling->convertDataType($this->TestModel, 9, 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, 9, 'boolean'));

		$this->assertEquals(false, $this->DataTypeJuggling->convertDataType($this->TestModel, 'false', 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, 'true', 'boolean'));

		$this->assertEquals(false, $this->DataTypeJuggling->convertDataType($this->TestModel, '0', 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, '1', 'boolean'));

		$this->assertEquals(false, $this->DataTypeJuggling->convertDataType($this->TestModel, 0, 'boolean'));
		$this->assertInternalType('boolean', $this->DataTypeJuggling->convertDataType($this->TestModel, 1, 'boolean'));

		// Strings
		$this->assertEquals(null, $this->DataTypeJuggling->convertDataType($this->TestModel, 0, 'string'));
		$this->assertInternalType('null', $this->DataTypeJuggling->convertDataType($this->TestModel, 0, 'string'));

		$this->assertEquals(null, $this->DataTypeJuggling->convertDataType($this->TestModel, false, 'string'));
		$this->assertInternalType('null', $this->DataTypeJuggling->convertDataType($this->TestModel, false, 'string'));

		$this->assertEquals(null, $this->DataTypeJuggling->convertDataType($this->TestModel, null, 'string'));
		$this->assertInternalType('null', $this->DataTypeJuggling->convertDataType($this->TestModel, null, 'string'));

		$this->assertEquals('test', $this->DataTypeJuggling->convertDataType($this->TestModel, 'test', 'string'));
		$this->assertInternalType('string', $this->DataTypeJuggling->convertDataType($this->TestModel, 'test', 'string'));

	}

	/**
	 * Test Is Boolean - Column Is Boolean
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsBooleanColumnIsBoolean() {

		$column = 'columnName';

		$type = 'boolean';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isBoolean($this->TestModel, $column));

	}

	/**
	 * Test Is Boolean - Column Is Other Type Than Boolean
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsBooleanColumnIsOtherThanBoolean() {

		$column = 'columnName';

		$type = 'other';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertFalse($this->DataTypeJuggling->isBoolean($this->TestModel, $column));

	}

	/**
	 * Test Is String - Column Is String
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsStringColumnString() {

		$column = 'columnName';

		$type = 'string';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isString($this->TestModel, $column));

	}

	/**
	 * Test Is String - Column Is Text
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsStringColumnIsText() {

		$column = 'columnName';

		$type = 'text';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isString($this->TestModel, $column));

	}

	/**
	 * Test Is String - Column Is Binary
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsStringColumnIsBinary() {

		$column = 'columnName';

		$type = 'binary';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isString($this->TestModel, $column));

	}

	/**
	 * Test Is String - Column Is Other Than String, Text or Binary
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsStringColumnIsOther() {

		$column = 'columnName';

		$type = 'other';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertFalse($this->DataTypeJuggling->isString($this->TestModel, $column));

	}

	/**
	 * Test Is Numeric - Column Is Integer
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsNumericColumnIsInteger() {

		$column = 'columnName';

		$type = 'integer';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isNumeric($this->TestModel, $column));

	}

	/**
	 * Test Is Numeric - Column Is Biginteger
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsNumericColumnIsBigInteger() {

		$column = 'columnName';

		$type = 'biginteger';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertTrue($this->DataTypeJuggling->isNumeric($this->TestModel, $column));

	}

	/**
	 * Test Is Numeric - Column Is Other Than Int or Bigint
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testIsNumericColumnIsOtherThanIntOrBigint() {

		$column = 'columnName';

		$type = 'other';

		$this->TestModel
			->expects($this->once())
			->method('getColumnType')
			->with($column)
			->will($this->returnValue($type));

		$this->assertFalse($this->DataTypeJuggling->isNumeric($this->TestModel, $column));

	}

	/**
	 * Test Convert To Boolean
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertToBoolean() {

		$tests = array('1', 1, 'true', true);

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToBoolean($this->TestModel, $test);
			$this->assertTrue($result);
			$this->assertInternalType('boolean', $result);
		}

		$tests = array(0, 2, null, '', array(), new stdClass);

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToBoolean($this->TestModel, $test);
			$this->assertFalse($result);
			$this->assertInternalType('boolean', $result);
		}

	}

	/**
	 * Test Convert To Integer
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertToInteger() {

		$tests = array('1', 'true', 1, true, 2, new stdClass);

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToInteger($this->TestModel, $test);
			$this->assertEquals(1, $result);
			$this->assertInternalType('integer', $result);
		}

		$tests = array('false', false, 0, null, '', array());

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToInteger($this->TestModel, $test);
			$this->assertEquals(0, $result);
			$this->assertInternalType('integer', $result);
		}

	}

	/**
	 * Test Convert To Integer Except Null
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertToIntegerExceptNull() {

		$test = null;

		$result = $this->DataTypeJuggling->convertToIntegerExceptNull($this->TestModel, $test);
		$this->assertEquals(null, $result);
		$this->assertInternalType('null', $result);

		$tests = array('1', 1, '2', 2);

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToIntegerExceptNull($this->TestModel, $test);
			$this->assertEquals($test, $result);
			$this->assertInternalType('integer', $result);
		}

		$tests = array('1', 'true', 1, '1.0', 1.0, true, new stdClass());

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToIntegerExceptNull($this->TestModel, $test);
			$this->assertEquals(1, $result);
			$this->assertInternalType('integer', $result);
		}

		$tests = array('false', false, 0, '0.01', 0.01, '', array());

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToIntegerExceptNull($this->TestModel, $test);
			$this->assertEquals(0, $result);
			$this->assertInternalType('integer', $result);
		}

	}

	/**
	 * Test Convert To String
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertToString() {

		$tests = array(0, '', false, null, array());

		foreach($tests as $test) {
			$result = $this->DataTypeJuggling->convertToString($this->TestModel, $test);
			$this->assertNull($result);
			$this->assertInternalType('null', $result);
		}

		$tests = array('test', '0', 1, 2, new stdClass);

		foreach($tests as $test) {
			$this->assertEquals($test, $this->DataTypeJuggling->convertToString($this->TestModel, $test));
		}

	}

	/**
	 * Test Convert To Null
	 *
	 * @author	Everton Yoshitani <everton@wizehive.com>
	 * @since	1.0
	 * @return	void
	 */
	public function testConvertToNull() {

		$result = $this->DataTypeJuggling->convertToNull($this->TestModel, null);
		$this->assertNull($result);
		$this->assertInternalType('null', $result);

		$result = $this->DataTypeJuggling->convertToNull($this->TestModel, '');
		$this->assertNull($result);
		$this->assertInternalType('null', $result);

		$result = $this->DataTypeJuggling->convertToNull($this->TestModel, 1);
		$this->assertEquals(1, $result);
		$this->assertInternalType('integer', $result);

		$result = $this->DataTypeJuggling->convertToNull($this->TestModel, true);
		$this->assertEquals(true, $result);
		$this->assertInternalType('boolean', $result);

		$result = $this->DataTypeJuggling->convertToNull($this->TestModel, 'test');
		$this->assertEquals('test', $result);
		$this->assertInternalType('string', $result);

	}

}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.1.3.9
description: >
  Throws a TypeError if `this` is a Set object.
info: >
  Map.prototype.set ( key , value )

  ...
  3. If M does not have a [[MapData]] internal slot, throw a TypeError
  exception.
  ...
features: [Set]
---*/

assert.throws(TypeError, function() {
  Map.prototype.set.call(new Set(), 1, 1);
});

assert.throws(TypeError, function() {
  var m = new Map();
  m.set.call(new Set(), 1, 1);
});

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

namespace OPS
{
namespace Stage
{

//  Constants and enums
static const wchar_t* ROOT_PATH_RELATIVE = L"../";
static const wchar_t* CONFIGS_ROOT_PATH_RELATIVE = L"conf";
static const wchar_t* SAMPLES_ROOT_PATH_RELATIVE = L"samples";

//  Classes

//  Functions declaration

//  Variables
static std::wstring g_stageRootPath;

//  Classes implementation

//  Global classes implementation

//  Functions implementation
std::wstring getStageRoot(void)
{
	if (g_stageRootPath.empty())
	{
		return IO::combinePath(getStartupPath(), ROOT_PATH_RELATIVE);
	}
	else
	{
		return g_stageRootPath;
	}
}

void setStageRoot(const wchar_t* rootPath)
{
	g_stageRootPath = rootPath;
}

wstring getStageConfigsRoot(void)
{
	return IO::combinePath(getStageRoot(), CONFIGS_ROOT_PATH_RELATIVE);
}

wstring getStageSamplesRoot(void)
{
	return IO::combinePath(getStageRoot(), SAMPLES_ROOT_PATH_RELATIVE);
}

//  Exit namespace
}
}


text:
CREATE OR REPLACE VIEW OSP$PROTOCOL_DOCUMENT_STATUS AS
    SELECT STATUS_CD, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER
    FROM PROTOCOL_ATTACHMENT_STATUS;

CREATE OR REPLACE VIEW OSP$PROTOCOL_DOCUMENT_TYPE AS
    SELECT t.TYPE_CD, t.DESCRIPTION, t.UPDATE_TIMESTAMP, t.UPDATE_USER, g.GROUP_CD
    FROM PROTOCOL_ATTACHMENT_TYPE t, PROTOCOL_ATTACHMENT_GROUP g, PROTOCOL_ATTACHMENT_TYPE_GROUP tg
    WHERE t.TYPE_CD = tg.TYPE_CD AND g.GROUP_CD = tg.GROUP_CD;

CREATE OR REPLACE VIEW OSP$PROTOCOL_DOCUMENTS AS
    SELECT p.PROTOCOL_NUMBER, p.SEQUENCE_NUMBER, pap.TYPE_CD, pap.DESCRIPTION, paf.FILE_NAME, paf.FILE_DATA,
    pap.UPDATE_TIMESTAMP, pap.UPDATE_USER, pap.VERSION_NUMBER, pap.STATUS_CD, pap.DOCUMENT_ID
    FROM PROTOCOL p, PROTOCOL_ATTACHMENT_PROTOCOL pap, PROTOCOL_ATTACHMENT_FILE paf
    WHERE p.PROTOCOL_ID = pap.PROTOCOL_ID AND pap.FILE_ID = paf.PA_FILE_ID;

ALTER TABLE PROTOCOL_ATTACHMENT_PERSONNEL DROP CONSTRAINT FK_PA_PERSONNEL_FILE;

ALTER TABLE PROTOCOL_ATTACHMENT_PERSONNEL
    ADD CONSTRAINT FK_PA_PERSONNEL_FILE
    FOREIGN KEY (FILE_ID)
    REFERENCES PROTOCOL_ATTACHMENT_FILE (PA_FILE_ID)
    ON DELETE CASCADE;

ALTER TABLE PROTOCOL_ATTACHMENT_PERSONNEL
    ADD CONSTRAINT FK_PA_PERSONNEL_PROTOCOL
    FOREIGN KEY (PROTOCOL_ID)
    REFERENCES PROTOCOL (PROTOCOL_ID);

ALTER TABLE PROTOCOL_ATTACHMENT_PERSONNEL
    ADD CONSTRAINT FK_PERSON
    FOREIGN KEY (PERSON_ID)
    REFERENCES PROTOCOL_PERSONS (PROTOCOL_PERSON_ID);

ALTER TABLE PROTOCOL_ATTACHMENT_PROTOCOL DROP CONSTRAINT FK_PA_PROTOCOL_FILE;

ALTER TABLE PROTOCOL_ATTACHMENT_PROTOCOL
    ADD CONSTRAINT FK_PA_PROTOCOL_FILE
    FOREIGN KEY (FILE_ID)
    REFERENCES PROTOCOL_ATTACHMENT_FILE (PA_FILE_ID)
    ON DELETE CASCADE;

ALTER TABLE PROTOCOL_ATTACHMENT_PROTOCOL
    ADD CONSTRAINT FK_PA_PROTOCOL
    FOREIGN KEY (PROTOCOL_ID)
    REFERENCES PROTOCOL (PROTOCOL_ID);


text:
package com.baidubce.services.iotdm.model;

import java.util.List;

import com.baidubce.model.AbstractBceResponse;

/**
 * Represent the response of get device access detail.
 */
public class DeviceAccessDetail extends AbstractBceResponse {

    private String protocol;
    private String deviceName;
    private String endpointName;
    private List<String> endpoints;
    private List<String> pubTopics;
    private List<String> subTopics;

    public String getProtocol() {
        return protocol;
    }
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    public String getEndpointName() {
        return endpointName;
    }
    public void setEndpointName(String endpointName) {
        this.endpointName = endpointName;
    }
    public List<String> getEndpoints() {
        return endpoints;
    }
    public void setEndpoints(List<String> endpoints) {
        this.endpoints = endpoints;
    }
    public List<String> getPubTopics() {
        return pubTopics;
    }
    public void setPubTopics(List<String> pubTopics) {
        this.pubTopics = pubTopics;
    }
    public List<String> getSubTopics() {
        return subTopics;
    }
    public void setSubTopics(List<String> subTopics) {
        this.subTopics = subTopics;
    }

}


text:
var Checker = require('../../../lib/checker');
var expect = require('chai').expect;

describe('rules/disallow-spaces-in-conditional-expression', function() {
    var checker;
    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
    });

    describe('afterTest', function() {
        beforeEach(function() {
            checker.configure({ disallowSpacesInConditionalExpression: { afterTest: true } });
        });

        it('should not report no space after test in Conditional Expression', function() {
            expect(checker.checkString('var x = a? b : c;')).to.have.no.errors();
        });

        it('should not report newline before question mark in Conditional Expression', function() {
            expect(checker.checkString('var x = a\n ? b : c;')).to.have.no.errors();
        });

        it('should report newline after question mark in Conditional Expression', function() {
            expect(checker.checkString('var x = a ?\n b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space after test in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space after test in Conditional Expression', function() {
            expect(checker.checkString('var x = a ?b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report no space after test in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = (a)? b : c;')).to.have.no.errors();
        });

        it('should report space after test in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = (a) ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });
    });

    describe('beforeConsequent', function() {
        beforeEach(function() {
            checker.configure({ disallowSpacesInConditionalExpression: { beforeConsequent: true } });
        });

        it('should not report no space before consequent in Conditional Expression', function() {
            expect(checker.checkString('var x = a ?b : c;')).to.have.no.errors();
        });

        it('should report newline before question mark in Conditional Expression', function() {
            expect(checker.checkString('var x = a\n ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report newline after question mark in Conditional Expression', function() {
            expect(checker.checkString('var x = a ?\n b : c;')).to.have.no.errors();
        });

        it('should report space before consequent in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space after test in Conditional Expression', function() {
            expect(checker.checkString('var x = a? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report no space before consequent in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a ?(b) : c;')).to.have.no.errors();
        });

        it('should report space after test for consequent in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a? (b) : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });
    });

    describe('afterConsequent', function() {
        beforeEach(function() {
            checker.configure({ disallowSpacesInConditionalExpression: { afterConsequent: true } });
        });

        it('should not report no space after consequent in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b: c;')).to.have.no.errors();
        });

        it('should not report newline before colon in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b\n : c;')).to.have.no.errors();
        });

        it('should report newline after colon in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b :\n c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space after consequent in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space after consequent in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b :c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report no space after consequent in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? (b): c;')).to.have.no.errors();
        });

        it('should report space after consequent in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? (b) : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });
    });

    describe('beforeAlternate', function() {
        beforeEach(function() {
            checker.configure({ disallowSpacesInConditionalExpression: { beforeAlternate: true } });
        });

        it('should not report no space before alternate in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b :c;')).to.have.no.errors();
        });

        it('should report newline before colon in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b\n : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report newline after colon in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b :\n c;')).to.have.no.errors();
        });

        it('should report space before alternate in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should report space before alternate in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b: c;'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });

        it('should not report no space before alternate in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b :(c);')).to.have.no.errors();
        });

        it('should report space before alternate in parens in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : (c);'))
              .to.have.one.validation.error.from('disallowSpacesInConditionalExpression');
        });
    });

    describe('true', function() {
        beforeEach(function() {
            checker.configure({ disallowSpacesInConditionalExpression: true });
        });

        it('should not report no spaces in Conditional Expression', function() {
            expect(checker.checkString('var x = a?b:c;')).to.have.no.errors();
        });

        it('should report all spaces in Conditional Expression', function() {
            expect(checker.checkString('var x = a ? b : c;')).to.have.error.count.equal(4);
        });

        it('should not report no spaces in recursive Conditional Expression', function() {
            expect(checker.checkString('var x = t1?c1t2?c2:a2:a1t3?c3:a3;')).to.have.no.errors();
        });

        it('should report all spaces in recursive Conditional Expression', function() {
            expect(checker.checkString('var x = t1 ? c1t2 ? c2 : a2 : a1t3 ? c3 : a3;')).to.have.error.count.equal(12);
        });
    });
});


text:
package com.hazelcast.simulator.wizard;

import com.hazelcast.simulator.utils.CommandLineExitException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.net.URL;

import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingDirectory;
import static com.hazelcast.simulator.utils.FileUtils.writeText;
import static com.hazelcast.simulator.utils.ReflectionUtils.invokePrivateConstructor;
import static com.hazelcast.simulator.wizard.WizardUtils.getJarDir;
import static com.hazelcast.simulator.wizard.WizardUtils.getProfileFile;
import static com.hazelcast.simulator.wizard.WizardUtils.getSimulatorPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class WizardUtilsTest {

    private File parent;

    @Before
    public void setUp() throws Exception {
        parent = new File("parent").getAbsoluteFile();
        ensureExistingDirectory(parent);
    }

    @After
    public void tearDown() throws Exception {
        deleteQuiet(parent);
    }

    @Test
    public void testConstructor() throws Exception {
        invokePrivateConstructor(WizardUtils.class);
    }

    @Test
    public void testGetSimulatorPath() {
        String simulatorPath = getSimulatorPath();

        assertNotNull(simulatorPath);
    }

    @Test
    public void testGetProfileFile_withBashrc() {
        File expectedFile = new File(parent, ".bashrc");
        writeText("# empty file", expectedFile);

        File actualFile = getProfileFile(parent.getPath());

        assertEquals(expectedFile.getPath(), actualFile.getPath());
    }

    @Test
    public void testGetProfileFile_withProfile() {
        File expectedFile = new File(parent, ".profile");
        writeText("# empty file", expectedFile);

        File actualFile = getProfileFile(parent.getPath());

        assertEquals(expectedFile.getPath(), actualFile.getPath());
    }

    @Test(expected = CommandLineExitException.class)
    public void testGetProfileFile_notFound() {
        getProfileFile(parent.getPath());
    }

    @Test
    public void testGetJarDir() {
        File jarDir = getJarDir(WizardUtils.class);

        assertNotNull(jarDir);
        assertTrue(jarDir.isDirectory());
    }

    @Test
    public void testGetFileFromUrl_fromJar() throws Exception {
        URL url = new URL("jar:file:/target/classes/simulator.jar!/WizardUtils.java");

        File file = WizardUtils.getFileFromUrl(url, "WizardUtils");

        assertNotNull(file);
        assertEquals("file:/target/classes/simulator.jar!/WizardUtils.java", file.getPath());
    }

    @Test
    public void testGetFileFromUrl_fromJarFile() throws Exception {
        URL url = new URL("file:/target/classes/simulator.jar");

        File file = WizardUtils.getFileFromUrl(url, "WizardUtils");

        assertNotNull(file);
        assertEquals("/target/classes", file.getPath());
    }

    @Test
    public void testGetFileFromUrl_fromClass() throws Exception {
        URL url = new URL("file:/target/classes/");

        File file = WizardUtils.getFileFromUrl(url, "WizardUtils");

        assertNotNull(file);
        assertEquals("/target/classes", file.getPath());
    }
}


text:
package org.jnosql.diana.couchbase.util;

import com.couchbase.client.java.CouchbaseCluster;

import java.util.Objects;

public final class CouchbaseClusterUtil {
    private CouchbaseClusterUtil() {
    }

    public static CouchbaseCluster getCouchbaseCluster(String database, CouchbaseCluster couchbaseCluster, String user, String password) {
        Objects.requireNonNull(database, "database is required");
        CouchbaseCluster authenticate = couchbaseCluster.authenticate(user, password);

       /*
        ClusterManager clusterManager = authenticate.clusterManager();
        List<BucketSettings> buckets = clusterManager.getBuckets();
        if(buckets.stream().noneMatch(b -> b.name().equals(database))) {
            BucketSettings bucketSettings =  DefaultBucketSettings.builder().name(database).quota(100);
            clusterManager.insertBucket(bucketSettings);
            Bucket bucket = authenticate.openBucket(database);
            bucket.query(N1qlQuery.simple("CREATE PRIMARY INDEX index_" + database + " on " + database));
            bucket.close();
        }*/
        return authenticate;
    }

}


text:
package org.txazo.test.runner;

import org.txazo.test.SuiteTest;
import org.txazo.test.annotation.Test;
import org.txazo.test.assertion.Assert;

/**
 * TestExecuorTest
 *
 * @author txazo
 * @email txazo1218@163.com
 * @since 22.05.2015
 */
public class TestExecuorTest extends SuiteTest {

    @Test
    public void testGetInstance() throws InstantiationException, IllegalAccessException {
        TestExecuorTest test1 = TestExecuor.getInstance(TestExecuorTest.class);
        TestExecuorTest test2 = TestExecuor.getInstance(TestExecuorTest.class);
        Assert.assertSame(test1, test2);
        Assert.assertSame(test1.getClass(), TestExecuorTest.class);
    }

}


text:
package attribute_test

import (
	"regexp"
	"testing"

	"github.com/stretchr/testify/require"

	"go.opentelemetry.io/otel/attribute"
)

type testCase struct {
	kvs []attribute.KeyValue

	keyRe *regexp.Regexp

	encoding string
	fullEnc  string
}

func expect(enc string, kvs ...attribute.KeyValue) testCase {
	return testCase{
		kvs:      kvs,
		encoding: enc,
	}
}

func expectFiltered(enc, filter, fullEnc string, kvs ...attribute.KeyValue) testCase {
	return testCase{
		kvs:      kvs,
		keyRe:    regexp.MustCompile(filter),
		encoding: enc,
		fullEnc:  fullEnc,
	}
}

func TestSetDedup(t *testing.T) {
	cases := []testCase{
		expect("A=B", attribute.String("A", "2"), attribute.String("A", "B")),
		expect("A=B", attribute.String("A", "2"), attribute.Int("A", 1), attribute.String("A", "B")),
		expect("A=B", attribute.String("A", "B"), attribute.String("A", "C"), attribute.String("A", "D"), attribute.String("A", "B")),

		expect("A=B,C=D", attribute.String("A", "1"), attribute.String("C", "D"), attribute.String("A", "B")),
		expect("A=B,C=D", attribute.String("A", "2"), attribute.String("A", "B"), attribute.String("C", "D")),
		expect("A=B,C=D", attribute.Float64("C", 1.2), attribute.String("A", "2"), attribute.String("A", "B"), attribute.String("C", "D")),
		expect("A=B,C=D", attribute.String("C", "D"), attribute.String("A", "B"), attribute.String("A", "C"), attribute.String("A", "D"), attribute.String("A", "B")),
		expect("A=B,C=D", attribute.String("A", "B"), attribute.String("C", "D"), attribute.String("A", "C"), attribute.String("A", "D"), attribute.String("A", "B")),
		expect("A=B,C=D", attribute.String("A", "B"), attribute.String("A", "C"), attribute.String("A", "D"), attribute.String("A", "B"), attribute.String("C", "D")),
	}
	enc := attribute.DefaultEncoder()

	s2d := map[string][]attribute.Distinct{}
	d2s := map[attribute.Distinct][]string{}

	for _, tc := range cases {
		cpy := make([]attribute.KeyValue, len(tc.kvs))
		copy(cpy, tc.kvs)
		sl := attribute.NewSet(cpy...)

		// Ensure that the input was reordered but no elements went missing.
		require.ElementsMatch(t, tc.kvs, cpy)

		str := sl.Encoded(enc)
		equ := sl.Equivalent()

		s2d[str] = append(s2d[str], equ)
		d2s[equ] = append(d2s[equ], str)

		require.Equal(t, tc.encoding, str)
	}

	for s, d := range s2d {
		// No other Distinct values are equal to this.
		for s2, d2 := range s2d {
			if s2 == s {
				continue
			}
			for _, elt := range d {
				for _, otherDistinct := range d2 {
					require.NotEqual(t, otherDistinct, elt)
				}
			}
		}
		for _, strings := range d2s {
			if strings[0] == s {
				continue
			}
			for _, otherString := range strings {
				require.NotEqual(t, otherString, s)
			}
		}
	}

	for d, s := range d2s {
		// No other Distinct values are equal to this.
		for d2, s2 := range d2s {
			if d2 == d {
				continue
			}
			for _, elt := range s {
				for _, otherDistinct := range s2 {
					require.NotEqual(t, otherDistinct, elt)
				}
			}
		}
		for _, distincts := range s2d {
			if distincts[0] == d {
				continue
			}
			for _, otherDistinct := range distincts {
				require.NotEqual(t, otherDistinct, d)
			}
		}
	}
}

func TestUniqueness(t *testing.T) {
	short := []attribute.KeyValue{
		attribute.String("A", "0"),
		attribute.String("B", "2"),
		attribute.String("A", "1"),
	}
	long := []attribute.KeyValue{
		attribute.String("B", "2"),
		attribute.String("C", "5"),
		attribute.String("B", "2"),
		attribute.String("C", "1"),
		attribute.String("A", "4"),
		attribute.String("C", "3"),
		attribute.String("A", "1"),
	}
	cases := []testCase{
		expectFiltered("A=1", "^A$", "B=2", short...),
		expectFiltered("B=2", "^B$", "A=1", short...),
		expectFiltered("A=1,B=2", "^A|B$", "", short...),
		expectFiltered("", "^C", "A=1,B=2", short...),

		expectFiltered("A=1,C=3", "A|C", "B=2", long...),
		expectFiltered("B=2,C=3", "C|B", "A=1", long...),
		expectFiltered("C=3", "C", "A=1,B=2", long...),
		expectFiltered("", "D", "A=1,B=2,C=3", long...),
	}
	enc := attribute.DefaultEncoder()

	for _, tc := range cases {
		cpy := make([]attribute.KeyValue, len(tc.kvs))
		copy(cpy, tc.kvs)
		distinct, uniq := attribute.NewSetWithFiltered(cpy, func(attr attribute.KeyValue) bool {
			return tc.keyRe.MatchString(string(attr.Key))
		})

		full := attribute.NewSet(uniq...)

		require.Equal(t, tc.encoding, distinct.Encoded(enc))
		require.Equal(t, tc.fullEnc, full.Encoded(enc))
	}
}

func TestLookup(t *testing.T) {
	set := attribute.NewSet(attribute.Int("C", 3), attribute.Int("A", 1), attribute.Int("B", 2))

	value, has := set.Value("C")
	require.True(t, has)
	require.Equal(t, int64(3), value.AsInt64())

	value, has = set.Value("B")
	require.True(t, has)
	require.Equal(t, int64(2), value.AsInt64())

	value, has = set.Value("A")
	require.True(t, has)
	require.Equal(t, int64(1), value.AsInt64())

	_, has = set.Value("D")
	require.False(t, has)
}


text:
using System;
using Captura.Models;
using Captura.Properties;

namespace Captura.Console
{
    class FakeSystemTray : ISystemTray
    {
        public void HideNotification() { }

        public void ShowScreenShotNotification(string FilePath)
        {
            System.Console.WriteLine($"{Resources.ScreenShotSaved}: {FilePath}");
        }

        public void ShowTextNotification(string Text, int Duration, Action OnClick)
        {
            System.Console.WriteLine(Text);
        }
    }
}


text:
package org.mockenize.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;

import lombok.Data;

@Data
public class RequestLogBean implements Serializable {

	private static final long serialVersionUID = 1L;

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

	private transient JsonNode body;
}


text:
package org.teraflopx.jsandboox.algorithm;

import static org.junit.Assert.assertEquals;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ArrayOperationsTest {

  @Test
  public void testQuickSort() {
    int[] data = new int[] {2, 8, 6, 4, 9, 5, 7, 3, 10, 1};
    ArrayOperations.quickSort(data);
  }

  @Test
  public void testPermutations() {
    ArrayOperations.findPermutations("abc");
  }

  @Test
  public void testMergeSort() {
    int[] data = new Random().ints().limit(100).toArray();
    ArrayOperations.mergeSort(data);
  }

  @Test
  public void testBinarySearchRecursive() {
    int[] data = new int[] {1, 2, 6, 7, 8, 12};

    long start = System.nanoTime();

    assertEquals(ArrayOperations.binarySearchRecursive(3, data, 0, data.length - 1), -1);
    for (int i = 0; i < data.length; i++)
      assertEquals(ArrayOperations.binarySearchRecursive(data[i], data, 0, data.length - 1), i);

    long end = System.nanoTime();
    System.out.println("Elapsed time (ms): " + TimeUnit.NANOSECONDS.toMillis(end - start));
  }

  @Test
  public void testBinarySearchLinear() {
    int[] data = new int[] {1, 2, 6, 7, 8, 12};

    long start = System.nanoTime();

    assertEquals(ArrayOperations.binarySearchLinear(3, data, 0, data.length - 1), -1);
    for (int i = 0; i < data.length; i++)
      assertEquals(ArrayOperations.binarySearchLinear(data[i], data, 0, data.length - 1), i);

    long end = System.nanoTime();
    System.out.println("Elapsed time (ms): " + TimeUnit.NANOSECONDS.toMillis(end - start));
  }
}


text:
Install mqtt client for **Ubuntu**:

```bash
sudo apt-get install mosquitto-clients
```
{: .copy-code}

Install cURL for **macOS**:

```bash
brew install mosquitto-clients
```
{: .copy-code}

{% if docsPrefix == 'paas/' %}

Replace $ACCESS_TOKEN with corresponding value.

```bash
mosquitto_pub -d -q 1 -h "mqtt.thingsboard.cloud" -p "1883" -t "v1/devices/me/telemetry" -u "$ACCESS_TOKEN" -m {"temperature":25}
```
{: .copy-code}

For example, $ACCESS_TOKEN is ABC123:

```bash
mosquitto_pub -d -q 1 -h "mqtt.thingsboard.cloud" -p "1883" -t "v1/devices/me/telemetry" -u "ABC123" -m {"temperature":25}
```
{: .copy-code}

{% else %}

Replace $THINGSBOARD_HOST_NAME and $ACCESS_TOKEN with corresponding values.

```bash
mosquitto_pub -d -q 1 -h "$THINGSBOARD_HOST_NAME" -p "1883" -t "v1/devices/me/telemetry" -u "$ACCESS_TOKEN" -m {"temperature":25}
```
{: .copy-code}

For example, $THINGSBOARD_HOST_NAME reference your local installation, $ACCESS_TOKEN is ABC123:

```bash
mosquitto_pub -d -q 1 -h "localhost" -p "1883" -t "v1/devices/me/telemetry" -u "ABC123" -m {"temperature":25}
```
{: .copy-code}

{% endif %}

Successful output should look similar to this one:

```text
Client mosqpub|xxx sending CONNECT
Client mosqpub|xxx received CONNACK
Client mosqpub|xxx sending PUBLISH (d0, q1, r0, m1, 'v1/devices/me/telemetry', ... (16 bytes))
Client mosqpub|xxx received PUBACK (Mid: 1)
Client mosqpub|xxx sending DISCONNECT
```

**Note:** Since ThingsBoard 3.2, you are able to use basic MQTT credentials (combination of client id, user name and password )
and customize **topic names** and **payload type** using Device Profile. See more info [here](/docs/user-guide/device-profiles/#mqtt-transport-type).


text:
package com.gizwits.framework.config;

// TODO: Auto-generated Javadoc
/**
 *
 * ClassName: Class JsonKeys.

 * Json对应字段表

 *
 * @author Lien
 */
public class JsonKeys {

	/** 产品名. */
	public final static String PRODUCT_NAME = "智能灯网关";

	/** 实体字段名,代表对应的项目. */
	public final static String KEY_ACTION = "entity0";

	/** 开关. */
	public final static String ON_OFF = "OnOff";

	/** 亮度. */
	public final static String LIGHTNESS = "Lightness";

	/** 开关所有灯 */
	public final static String ON_OFF_ALL = "OnOffAll";

}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (3 critical DevOps concepts we explored in 2020)
[#]: via: (https://opensource.com/article/20/12/devops)
[#]: author: (Dawn Parzych https://opensource.com/users/dawnparzych)

3 critical DevOps concepts we explored in 2020
======
In 2020, Opensource.com's top DevOps articles focused on testing,
software methodologies, and the most important part: the people
![Looking at a map][1]

Looking back through Opensource.com's articles about [DevOps][2] in 2020, there was a bit of something for everyone—from people starting the DevOps journey to seasoned DevOps veterans. The articles focused on testing, software methodologies, and DevOps' most important part: the people. Here are the top 10 DevOps articles of 2020.

### Test-driven development

Alex Bunardzic shared [many articles about testing][3] this year, and I narrowed the list down to the top three. If you are interested in testing (and I would argue that anybody involved in writing or supporting software should have at least a passing interest in testing), check out these articles.

In _[How to get started with test-driven development][4]_, Alex uses an analogy to describe the fundamentals of test-driven development (TDD) and explain dependencies and how to eliminate them for testing purposes.

If you're going to practice TDD, you need to understand how and when to write a unit test. Alex shares his best practices in [_Writing unit test after writing code considered harmful in test-driven development_][5].

Testing is about determining if code is working as designed, and [_What does it mean for code to "work"?_][6] explores how to define what working code looks like from the perspective of observable behavior.

### Software methodologies

People sometimes ask, "How does 'concept x' relate to DevOps?" Both [_DevOps vs. Agile: What's the difference?_][7] by Tonya Brown and [_How does kanban relate to DevOps_][8]_?_ by Willy-Peter Schaub address these questions head-on. Willy explains the four pivotal kanban practices then dives into how they are similar to DevOps. Tonya highlights similarities and differences between DevOps and agile. If you're starting out on your DevOps journey, these articles will help you understand how DevOps is similar to and different from your current practices.

And speaking of starting out, Sameer S Paradkar's article [_A beginner's guide to everything DevOps_][9] should be bookmarked and shared with anyone new to the practice. He covers everything from how DevOps addresses development and operations challenges, to the differences between traditional IT processes and DevOps, to understanding the DevOps lifecycle. To top it off, Sameer ends with a handy cheat sheet to open source DevOps tools.

### People

The people are the most important part of DevOps. They are the ones writing the software, supporting it, building automation, and so much more. Finding the right people is more important than implementing the right tools.

The right mindset is required to navigate DevOps. In [_10 tips for maintaining a DevOps mindset for distributed teams_][10], Willy-Peter Shaub shares how that mindset helps in the new era of remote work:

> "A healthy DevOps mindset navigates through different paths of continuous improvement wherein disruption, discipline, and guardrails are the norm. What no one anticipated is the radical disruption we are all experiencing due to the pandemic, and the impact it has on our DevOps and personal mindset, our workflows, and the ceremonies of kanban and agile teams."

This mindset is crucial as teams evolve how we collaborate, communicate, and deliver software for the remote world.

Yet, it's not the only thing you need to be successful in DevOps. Josh Atwell shared his list of key skills for DevOps success in [_How to be the right person for DevOps_][11]. It may come as a surprise, but none of the skills are related to programming languages or tools. Being the right person for DevOps requires communication, selflessness, and self-care, Josh says.

Even the right mindset and attitude won't make everything perfect; there will still be challenges. One of the challenges people face today is burnout. People are getting tired of being remote, and they are looking for things to return to "normal." In [_DevOps is a solution to burnout worth investing in_][12], I discuss how changing underlying processes and cultures can help reduce or prevent burnout.

Finally, if you're looking for a career change in 2021, consider the role of scrum master. Tonya Brown outlined a day in the life of a scrum master in [_What does a scrum master do?_][13] If you like removing impediments and coaching people on solving problems, this may be a role for you.

* * *

What DevOps topics are you interested in reading about? Please share your ideas in the comments, and if you have knowledge to share, please [consider writing about it for Opensource.com][14].

--------------------------------------------------------------------------------

via: https://opensource.com/article/20/12/devops

作者:[Dawn Parzych][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/dawnparzych
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/tips_map_guide_ebook_help_troubleshooting_lightbulb_520.png?itok=L0BQHgjr (Looking at a map)
[2]: https://opensource.com/resources/devops
[3]: https://opensource.com/users/alex-bunardzic
[4]: https://opensource.com/article/20/1/test-driven-development
[5]: https://opensource.com/article/20/2/automate-unit-tests
[6]: https://opensource.com/article/20/7/code-tdd
[7]: https://opensource.com/article/20/2/devops-vs-agile
[8]: https://opensource.com/article/20/4/kanban-devops
[9]: https://opensource.com/article/20/2/devops-beginners
[10]: https://opensource.com/article/20/6/devops-mindset
[11]: https://opensource.com/article/20/3/devops-relationships
[12]: https://opensource.com/article/20/1/devops-burnout-solution
[13]: https://opensource.com/article/20/7/scrum-master
[14]: https://opensource.com/how-submit-article


text:
import {initContext} from './utils';
import superagent from 'superagent';

module.exports = function run(context, req, res) {
  initContext(context);
  let platform = req.headers['x-requested-with'] == 'com.android.browser' ? 'android' : 'ios';
  let baseUrl = `https://packagerexponent.rnplay.org/js/${context.data.urlToken}`;
  let urlToken = context.data.urlToken.split("?")[0];
  console.log(context.data.urlToken)
  let unsignedManifest = {
    id: `@rnplay/${urlToken}`,
    name: 'RNApp',
    appKey: 'main',
    version: "1.0.0",
    description: "An app on Playground",
    sdkVersion: "10.0.0",
    iconUrl: "https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png",
    packagerOpts: {
      dev: false,
      minify: false,
    },
    loading: {
      hideExponentText: false,
      iconUrl: "https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png"
    },
    xde: true,
    developer: {
      tool: 'rnplay'
    },
    bundleUrl: `${baseUrl}/index.${platform}.bundle?platform=${platform}&dev=false&strict=false&minify=false&hot=false&includeAssetFileHashes=true`
  };

  let signingPayload = {
    body: unsignedManifest
  };

  let signingOptions = {
    serverSecret: context.data.exponentSecret,
    appId: context.data.urlToken,
  };

  let uriEncodedOptions = encodeURIComponent(JSON.stringify(signingOptions));

  superagent
    .post(`https://exp.host/--/api/signPlaygroundManifest/${uriEncodedOptions}`)
    .send(signingPayload)
    .set('Accept', 'application/json')
    .end((err, response) => {
      if (err) {
        console.log(err);
        res.writeHead(500, { 'Content-Type': 'text/plain'});
        res.end(err);
      }
      res.writeHead(200, { 'Content-Type': 'application/json'});
      res.end(response.body.response);
    });
};


text:
require('../../modules/es.reflect.define-property');
var path = require('../../internals/path');

module.exports = path.Reflect.defineProperty;


text:
package model

import (
	"encoding/json"
	"go-common/library/ecode"
)

// Response .
type Response struct {
	Code    int                    `json:"code"`
	Message string                 `json:"message"`
	Data    map[string]interface{} `json:"data"`
}

// Message .
func Message(raw map[string]interface{}, e error) (bs []byte) {
	res := &Response{
		Code:    ecode.Cause(e).Code(),
		Message: ecode.Cause(e).Message(),
		Data:    raw,
	}
	bs, _ = json.Marshal(res)
	return
}


text:
source "../../../cross_compilers.shlib"

### CONFIGURATION ###

# set whether of not to enable C++ support
ENABLE_CXX=0

# set binutils, gcc, newlib versions
BINUTILS_VERSION=2.19.1
GCC_VERSION=4.4.1
GMP_VERSION=4.3.1
MPFR_VERSION=2.4.1
NEWLIB_VERSION=1.17.0
NASM_VERSION=2.07
GDB_VERSION=6.8

# set CFLAGS
BINUTILS_CFLAGS=""
GCC_CFLAGS=""
GMP_CFLAGS=""
MPFR_CFLAGS="${GMP_CFLAGS}"
NEWLIB_CFLAGS=""
NEWLIB_CFLAGS_FOR_TARGET="-ffunction-sections -fdata-sections"
NASM_CFLAGS=""
GDB_CFLAGS=""

# target system
TARGET_SYSTEM=i686-elf

# finished cross-compiler root directory
CROSS_DIR=${CROSS_BASE}/x86

# set package names
BINUTILS_PACKAGE=binutils-${BINUTILS_VERSION}
GCC_PACKAGE=gcc-${GCC_VERSION}
GXX_PACKAGE=g++-${GCC_VERSION}
GMP_PACKAGE=gmp-${GMP_VERSION}
MPFR_PACKAGE=mpfr-${MPFR_VERSION}
NEWLIB_PACKAGE=newlib-${NEWLIB_VERSION}
NASM_PACKAGE=nasm-${NASM_VERSION}
GDB_PACKAGE=gdb-${GDB_VERSION}

# set download file names
BINUTILS_FILE=${BINUTILS_PACKAGE}.tar.bz2
GCC_FILE=gcc-core-${GCC_VERSION}.tar.bz2
GXX_FILE=gcc-g++-${GCC_VERSION}.tar.bz2
GMP_FILE=${GMP_PACKAGE}.tar.bz2
MPFR_FILE=${MPFR_PACKAGE}.tar.bz2
NEWLIB_FILE=${NEWLIB_PACKAGE}.tar.gz
NASM_FILE=${NASM_PACKAGE}.tar.bz2
GDB_FILE=${GDB_PACKAGE}.tar.bz2

# set download URLs
BINUTILS_URL="http://ftp.gnu.org/gnu/binutils/${BINUTILS_FILE}"
GCC_URL="http://ftp.gnu.org/gnu/gcc/${GCC_PACKAGE}/${GCC_FILE}"
GXX_URL="http://ftp.gnu.org/gnu/gcc/${GCC_PACKAGE}/${GXX_FILE}"
GMP_URL="ftp://ftp.gnu.org/gnu/gmp/${GMP_FILE}"
MPFR_URL="http://www.mpfr.org/mpfr-current/${MPFR_FILE}"
NEWLIB_URL="ftp://sources.redhat.com/pub/newlib/${NEWLIB_FILE}"
NASM_URL="http://www.nasm.us/pub/nasm/releasebuilds/${NASM_VERSION}/${NASM_FILE}"
GDB_URL="http://ftp.gnu.org/gnu/gdb/${GDB_FILE}"

### BUILD PROCESS ###
status "BUILDING OS X TO x86 CROSS COMPILER...."
check_prerequesites

# create some needed directories
status "Creating directories...."
# first check if they exist, then create them if they don't
cond_mkdir "${CROSS_DIR}"
cond_mkdir "${DL_DIR}"
cond_mkdir "${SRC_DIR}"
cond_mkdir "${BUILD_DIR}/${BINUTILS_PACKAGE}"
cond_mkdir "${BUILD_DIR}/${NEWLIB_PACKAGE}"
cond_mkdir "${BUILD_DIR}/${GDB_PACKAGE}"
cond_mkdir "${BUILD_DIR}/${GCC_PACKAGE}"
cond_mkdir "${BUILD_DIR}/${GCC_PACKAGE}-bootstrap"
cond_mkdir "${CROSS_DIR}/usr"

# download the needed packages
status "Downloading packages (if needed)...."
download "${BINUTILS_URL}"
download "${GCC_URL}"
if [ ${ENABLE_CXX} -ne 0 ]; then
	download "${GXX_URL}"
fi
download "${GMP_URL}"
download "${MPFR_URL}"
download "${NEWLIB_URL}"
download "${NASM_URL}"
download "${GDB_URL}"

# only extract binutils if needed
cond_extract "" "${BINUTILS_PACKAGE}" "${BINUTILS_FILE}"

# build binutils
status "Building ${BINUTILS_PACKAGE}...."
cd ${BUILD_DIR}/${BINUTILS_PACKAGE}
[ -f Makefile ] ||
	../../${SRC_DIR}/${BINUTILS_PACKAGE}/configure	\
						--prefix=${CROSS_DIR}		\
						--with-sysroot=${CROSS_DIR} \
						--target=${TARGET_SYSTEM}	\
						--with-gcc					\
						--with-gnu-as				\
						--with-gnu-ld				\
						--disable-nls				||
	abort "Failed to configure ${BINUTILS_PACKAGE}"
[ -f ld/ld-new ] || make CFLAGS="${BINUTILS_CFLAGS}" || abort "Failed to build ${BINUTILS_PACKAGE}"
[ -x ${CROSS_DIR}/bin/${TARGET_SYSTEM}-ld ] || make install || abort "Failed to install ${BINUTILS_PACKAGE}"
cd - > /dev/null

# only extract gmp if needed
cond_extract "" "${GMP_PACKAGE}" "${GMP_FILE}"

# only extract mpfr if needed
cond_extract "" "${MPFR_PACKAGE}" "${MPFR_FILE}"

# only extract newlib if not done
cond_extract "" "${NEWLIB_PACKAGE}" "${NEWLIB_FILE}"

# only copy newlib includes if not done
if [ ! -f "${CROSS_DIR}/usr/include/newlib.h" ]; then
	# copy newlib includes
	status "Copying ${NEWLIB_PACKAGE} include files...."
	cp -R ${SRC_DIR}/${NEWLIB_PACKAGE}/newlib/libc/include ${CROSS_DIR}/usr/ || abort "Failed to copy ${NEWLIB_PACKAGE} includes"
fi

# only extract gcc if not done
cond_extract "" "${GCC_PACKAGE}" "${GCC_FILE}"

# create library links
status "Creating numeric library links...."
cd ${SRC_DIR}/${GCC_PACKAGE}
ln -sf ../${GMP_PACKAGE} gmp || abort "Failed to create GMP link"
ln -sf ../${MPFR_PACKAGE} mpfr || abort "Failed to create MPFR link"
cd - > /dev/null

status "Building bootstrapping compiler...."
cd ${BUILD_DIR}/${GCC_PACKAGE}-bootstrap
[ -f Makefile ] ||
	../../${SRC_DIR}/${GCC_PACKAGE}/configure			\
						--prefix=${CROSS_DIR}			\
						--with-sysroot=${CROSS_DIR}		\
						--target=${TARGET_SYSTEM}		\
						--with-gcc						\
						--with-gnu-as					\
						--with-gnu-ld					\
						--disable-nls					\
						--enable-languages=c			\
						--with-newlib					\
						--disable-threads				\
						--disable-shared				\
						--without-headers				||
	abort "Failed to configure bootstrapping compiler"
[ -f "gcc/gcc" ] || make CFLAGS="${GCC_CFLAGS}" || abort "Failed to build bootstrapping compiler"
[ -x "${CROSS_DIR}/bin/${TARGET_SYSTEM}-gcc" ] || make install || abort "Failed to install bootstrapping compiler"
export PATH="${PATH}:${CROSS_DIR}/bin"
cd - > /dev/null

status "Building ${NEWLIB_PACKAGE}...."
cd ${BUILD_DIR}/${NEWLIB_PACKAGE}
[ -f Makefile ] ||
	../../${SRC_DIR}/${NEWLIB_PACKAGE}/configure			\
						--prefix=${CROSS_DIR}				\
						--target=${TARGET_SYSTEM}			\
						--with-gcc							\
						--with-gnu-as						\
						--with-gnu-ld						\
						--disable-newlib-supplied-syscalls	\
						--disable-shared					||
	abort "Failed to configure ${NEWLIB_PACKAGE}"
[ -f "${TARGET_SYSTEM}/newlib/libc.a" ] ||
	make CFLAGS="${NEWLIB_CFLAGS}" CFLAGS_FOR_TARGET="${NEWLIB_CFLAGS_FOR_TARGET}" ||
	abort "Failed to build ${NEWLIB_PACKAGE}"
[ -f "${CROSS_DIR}/${TARGET_SYSTEM}/lib/libc.a" ] || make install || abort "Failed to install ${NEWLIB_PACKAGE}"
cd - > /dev/null

status "Creating symbolic library links...."
if [ ! -L "${CROSS_DIR}/usr/lib/libc.a" ]; then
	mkdir -p ${CROSS_DIR}/usr/lib || abort "Failed to create ${CROSS_DIR}/usr/lib"
	ln -svf ${CROSS_DIR}/${TARGET_SYSTEM}/lib/*.a ${CROSS_DIR}/usr/lib || abort "Failed to create *.a links"
	ln -svf ${CROSS_DIR}/${TARGET_SYSTEM}/lib/*.o ${CROSS_DIR}/usr/lib || abort "Failed to create *.o links"
fi

if [ ${ENABLE_CXX} -ne 0 ]; then
	# only extract g++ if not done
	cond_extract "" "${GCC_PACKAGE}/libstdc++-v3" "${GXX_FILE}"

	# patch g++
	status "Patching libstdc++-v3...."
	cd ${SRC_DIR}/${GCC_PACKAGE}
	patch -p1 -N < ../../config-fix.patch || abort "Failed to patch 'libstdc++-v3'"
	cd - > /dev/null

	# build gcc/g++
	status "Building '${GCC_PACKAGE}'...."
	cd ${BUILD_DIR}/${GCC_PACKAGE}
	[ -f Makefile ] ||
		../../${SRC_DIR}/${GCC_PACKAGE}/configure		\
							--prefix=${CROSS_DIR}		\
							--with-sysroot=${CROSS_DIR} \
							--target=${TARGET_SYSTEM}	\
							--with-gcc					\
							--with-gnu-as				\
							--with-gnu-ld				\
							--disable-nls				\
							--enable-languages=c,c++	\
							--disable-threads			\
							--disable-shared			||
		abort "Failed to configure '${GCC_PACKAGE}'"
	[ -f "gcc/g++" ] || make CFLAGS="${GCC_CFLAGS}" || abort "Failed to build '${GCC_PACKAGE}'"
	[ -x "${CROSS_DIR}/bin/${TARGET_SYSTEM}-g++" ] || make install || abort "Failed to install '${GCC_PACKAGE}'"
else
	# build gcc
	status "Building '${GCC_PACKAGE}'...."
	cd ${BUILD_DIR}/${GCC_PACKAGE}
	[ -f Makefile ] ||
		../../${SRC_DIR}/${GCC_PACKAGE}/configure		\
							--prefix=${CROSS_DIR}		\
							--with-sysroot=${CROSS_DIR} \
							--target=${TARGET_SYSTEM}	\
							--with-gcc					\
							--with-gnu-as				\
							--with-gnu-ld				\
							--disable-nls				\
							--enable-languages=c		\
							--disable-threads			\
							--disable-shared			||
		abort "Failed to configure '${GCC_PACKAGE}'"
	[ -f "gcc/gcc" ] || make all-gcc CFLAGS="${GCC_CFLAGS}" || abort "Failed to build '${GCC_PACKAGE}'"
	make install-gcc || abort "Failed to install '${GCC_PACKAGE}'"
fi
cd - > /dev/null

# only extract nasm if not done
cond_extract "" "${NASM_PACKAGE}" "${NASM_FILE}"
[ -d "${BUILD_DIR}/${NASM_PACKAGE}" ] || mv ${SRC_DIR}/${NASM_PACKAGE} ${BUILD_DIR}/${NASM_PACKAGE} || abort "Failed to move ${NASM_PACKAGE} source"

# build nasm
status "Building '${NASM_PACKAGE}'...."
cd ${BUILD_DIR}/${NASM_PACKAGE}
[ -f Makefile ] || ./configure --prefix=${CROSS_DIR} || abort "Failed to configure '${NASM_PACKAGE}'"
[ -x "nasm" ] || make CFLAGS="${NASM_CFLAGS}" || abort "Failed to build '${NASM_PACKAGE}'"
[ -x "${CROSS_DIR}/bin/nasm" ] || make install || abort "Failed to install '${NASM_PACKAGE}'"
cd - > /dev/null

# only extract gdb if not done
cond_extract "" "${GDB_PACKAGE}" "${GDB_FILE}"

# build gdb
status "Building '${GDB_PACKAGE}'...."
cd ${BUILD_DIR}/${GDB_PACKAGE}
[ -f Makefile ] ||
	../../${SRC_DIR}/${GDB_PACKAGE}/configure		\
						--prefix=${CROSS_DIR}		\
						--with-sysroot=${CROSS_DIR} \
						--target=${TARGET_SYSTEM}	\
						--disable-nls				||
	abort "Failed to configure '${GDB_PACKAGE}'"
[ -f "gdb/gdb" ] || make CFLAGS="${GDB_CFLAGS}" || abort "Failed to build '${GDB_PACKAGE}'"
[ -x "${CROSS_DIR}/bin/${TARGET_SYSTEM}-gdb" ] || make install || abort "Failed to install '${GDB_PACKAGE}'"
cd - > /dev/null

# all done
success "OS X TO x86 CROSS COMPILER BUILT IN '${CROSS_DIR}'"
success "Total Size: "`du -hc ${CROSS_DIR} | grep 'total' | awk '{ print $1; }'`
exit 0


text:
package liquibase.util;

import liquibase.statement.DatabaseFunction;
import liquibase.statement.SequenceCurrentValueFunction;
import liquibase.statement.SequenceNextValueFunction;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class ObjectUtil {

	private static Map<Class<?>,Method[]>methodCache = new HashMap<Class<?>, Method[]>();

    public static Object getProperty(Object object, String propertyName) throws IllegalAccessException, InvocationTargetException {
        String methodName = "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1);
        Method[] methods = object.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName) && method.getParameterTypes().length == 0) {
                return method.invoke(object);
            }
        }
        throw new RuntimeException("Property not found: " + propertyName);
    }

    public static void setProperty(Object object, String propertyName, String propertyValue) throws IllegalAccessException, InvocationTargetException {
        String methodName = "set" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1);
        Method[] methods;

        methods = methodCache.get(object.getClass());

        if (methods == null) {
        	methods = object.getClass().getMethods();
        	methodCache.put(object.getClass(), methods);
        }

        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class<?> parameterType = method.getParameterTypes()[0];
                if (method.getParameterTypes().length == 1) {
                    if (parameterType.equals(Boolean.class) || parameterType.equals(boolean.class)) {
                        method.invoke(object, Boolean.valueOf(propertyValue));
                        return;
                    } else if (parameterType.equals(String.class)) {
                        method.invoke(object, propertyValue);
                        return;
                    } else if (parameterType.equals(Integer.class)) {
                        method.invoke(object, Integer.valueOf(propertyValue));
                        return;
                    } else if (parameterType.equals(Long.class)) {
                        method.invoke(object, Long.valueOf(propertyValue));
                        return;
                    } else if (parameterType.equals(BigInteger.class)) {
                        method.invoke(object, new BigInteger(propertyValue));
                        return;
                    } else if (parameterType.equals(DatabaseFunction.class)) {
                        method.invoke(object, new DatabaseFunction(propertyValue));
                        return;
                    } else if (parameterType.equals(SequenceNextValueFunction.class)) {
                        method.invoke(object, new SequenceNextValueFunction(propertyValue));
                        return;
                    } else if (parameterType.equals(SequenceCurrentValueFunction.class)) {
                        method.invoke(object, new SequenceCurrentValueFunction(propertyValue));
                        return;
                    }                }
            }
        }
        throw new RuntimeException("Property '" + propertyName+"' not found on object type "+object.getClass().getName());
    }
}


text:
#include <stdbool.h>
#include <string.h>
#include "indtext.h"

/** @file indtext.c  Maps text strings and indices of type INDTEXT_DATA */

#if !defined(__BORLANDC__) && !defined(_MSC_VER)
#include <ctype.h>
int stricmp(
    const char *s1,
    const char *s2)
{
    unsigned char c1, c2;

    do {
        c1 = (unsigned char) *s1;
        c2 = (unsigned char) *s2;
        c1 = (unsigned char) tolower(c1);
        c2 = (unsigned char) tolower(c2);
        s1++;
        s2++;
    } while ((c1 == c2) && (c1 != '\0'));

    return (int) c1 - c2;
}
#endif
#if defined(_MSC_VER)
#define stricmp _stricmp
#endif

bool indtext_by_string(
    INDTEXT_DATA * data_list,
    const char *search_name,
    unsigned *found_index)
{
    bool found = false;
    unsigned index = 0;

    if (data_list && search_name) {
        while (data_list->pString) {
            if (strcmp(data_list->pString, search_name) == 0) {
                index = data_list->index;
                found = true;
                break;
            }
            data_list++;
        }
    }

    if (found && found_index)
        *found_index = index;

    return found;
}

/* case insensitive version */
bool indtext_by_istring(
    INDTEXT_DATA * data_list,
    const char *search_name,
    unsigned *found_index)
{
    bool found = false;
    unsigned index = 0;

    if (data_list && search_name) {
        while (data_list->pString) {
            if (stricmp(data_list->pString, search_name) == 0) {
                index = data_list->index;
                found = true;
                break;
            }
            data_list++;
        }
    }

    if (found && found_index)
        *found_index = index;

    return found;
}

unsigned indtext_by_string_default(
    INDTEXT_DATA * data_list,
    const char *search_name,
    unsigned default_index)
{
    unsigned index = 0;

    if (!indtext_by_string(data_list, search_name, &index))
        index = default_index;

    return index;
}

unsigned indtext_by_istring_default(
    INDTEXT_DATA * data_list,
    const char *search_name,
    unsigned default_index)
{
    unsigned index = 0;

    if (!indtext_by_istring(data_list, search_name, &index))
        index = default_index;

    return index;
}

const char *indtext_by_index_default(
    INDTEXT_DATA * data_list,
    unsigned index,
    const char *default_string)
{
    const char *pString = NULL;

    if (data_list) {
        while (data_list->pString) {
            if (data_list->index == index) {
                pString = data_list->pString;
                break;
            }
            data_list++;
        }
    }

    return pString ? pString : default_string;
}

const char *indtext_by_index_split_default(
    INDTEXT_DATA * data_list,
    unsigned index,
    unsigned split_index,
    const char *before_split_default_name,
    const char *default_name)
{
    if (index < split_index)
        return indtext_by_index_default(data_list, index,
            before_split_default_name);
    else
        return indtext_by_index_default(data_list, index, default_name);
}

const char *indtext_by_index(
    INDTEXT_DATA * data_list,
    unsigned index)
{
    return indtext_by_index_default(data_list, index, NULL);
}

unsigned indtext_count(
    INDTEXT_DATA * data_list)
{
    unsigned count = 0; /* return value */

    if (data_list) {
        while (data_list->pString) {
            count++;
            data_list++;
        }
    }
    return count;
}

#ifdef TEST
#include <assert.h>
#include "ctest.h"

static INDTEXT_DATA data_list[] = {
    {1, "Joshua"},
    {2, "Mary"},
    {3, "Anna"},
    {4, "Christopher"},
    {5, "Patricia"},
    {0, NULL}
};

void testIndexText(
    Test * pTest)
{
    unsigned i; /*counter */
    const char *pString;
    unsigned index;
    bool valid;
    unsigned count = 0;

    for (i = 0; i < 10; i++) {
        pString = indtext_by_index(data_list, i);
        if (pString) {
            count++;
            valid = indtext_by_string(data_list, pString, &index);
            ct_test(pTest, valid == true);
            ct_test(pTest, index == i);
            ct_test(pTest, index == indtext_by_string_default(data_list,
                    pString, index));
        }
    }
    ct_test(pTest, indtext_count(data_list) == count);
    ct_test(pTest, indtext_by_string(data_list, "Harry", NULL) == false);
    ct_test(pTest, indtext_by_string(data_list, NULL, NULL) == false);
    ct_test(pTest, indtext_by_string(NULL, NULL, NULL) == false);
    ct_test(pTest, indtext_by_index(data_list, 0) == NULL);
    ct_test(pTest, indtext_by_index(data_list, 10) == NULL);
    ct_test(pTest, indtext_by_index(NULL, 10) == NULL);
    /* case insensitive versions */
    ct_test(pTest, indtext_by_istring(data_list, "JOSHUA", NULL) == true);
    ct_test(pTest, indtext_by_istring(data_list, "joshua", NULL) == true);
    valid = indtext_by_istring(data_list, "ANNA", &index);
    ct_test(pTest, index == indtext_by_istring_default(data_list, "ANNA",
            index));
}
#endif

#ifdef TEST_INDEX_TEXT
int main(
    void)
{
    Test *pTest;
    bool rc;

    pTest = ct_create("index text", NULL);

    /* individual tests */
    rc = ct_addTestFunction(pTest, testIndexText);
    assert(rc);

    ct_setStream(pTest, stdout);
    ct_run(pTest);
    (void) ct_report(pTest);

    ct_destroy(pTest);

    return 0;
}
#endif /* TEST_INDEX_TEXT */


text:
from django import forms
from django.forms.models import inlineformset_factory, modelformset_factory, BaseInlineFormSet, formset_factory
from django.forms.formsets import DELETION_FIELD_NAME
from django.contrib.auth.models import User

from zillions.models import Transaction, Primary_Category_Bucket, Primary_Category, Secondary_Category, Source_Category, Source, Budget, Rockleton

class TransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = '__all__'
        #fields = ['name', 'description', 'notes', 'workout_date', 'workout_plan']

#Multiple budget lines per secondary transaction enabling one for ed and one for julie
BudgetFormSet = inlineformset_factory(Secondary_Category, Budget, extra=1, can_delete=False, max_num=2, fields = '__all__')

class SelectFileForm(forms.Form):
    file = forms.FileField()

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

class RockletonForm(forms.ModelForm):
    class Meta:
        model = Rockleton
        exclude = ['user']

class TransferForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['source','secondary_category']

class BaseTransferForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['transaction_date','description','amount','ed_perc']


text:
[![Build Status](https://travis-ci.org/mechio/takana-client.svg?branch=master&style=flat)](https://travis-ci.org/mechio/takana-client)
[![npm version](https://badge.fury.io/js/takana-client.svg)](http://badge.fury.io/js/takana-client)
[![Dependency Status](https://david-dm.org/mechio/takana-client.svg?theme=shields.io)](https://david-dm.org/mechio/takana-client)
[![devDependency Status](https://david-dm.org/mechio/takana-client/dev-status.svg?theme=shields.io)](https://david-dm.org/mechio/takana-client#info=devDependencies)

This is the browser client for [takana](http://usetakana.com). It needs to be included inside your `<head>` tag of any page that you want to live update:

```html
<script type="text/javascript" src="http://localhost:48626/takana.js"></script>
<script type="text/javascript">
  takanaClient.run({
    host: 'localhost:48626' // optional, defaults to localhost:48626
  });
</script>
```

For more information about takana, please refer to the [takana repository](https://github.com/mechio/takana).


text:
import uuid

from nova import wsgi as base
from oslo.config import cfg

from auditlog.api.model import models
from auditlog.storage import impl_mongodb
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils

LOG = logging.getLogger(__name__)
cfg.CONF.import_opt('auditlog_connection', 'auditlog.storage',
                    group="database")

class AuditMiddleware(base.Middleware):
    """store POST/PUT/DELETE api request for audit."""

    def __init__(self, application, audit_methods='POST, PUT, DELETE'):

        super(AuditMiddleware, self).__init__(application)
        self._audit_methods = audit_methods.split(",")
        self.client = impl_mongodb.MongoDBStorage()
        self.connection = self.client.get_connection(cfg.CONF)

    def process_request(self, req):
        _need_audit = req.method in self._audit_methods
        if _need_audit:
            id = uuid.uuid4()
            user_id = req.headers.get('X-User-Id', 'unknown')
            tenant_id = req.headers.get('X-Tenant-Id', 'unknown')
            path = req.path
            try:
                rid = models.Resource.parse_url(path).rid
            except Exception:
                rid = None
            method = req.method
            status_code = None
            begin_at = self._format_time(timeutils.utcnow())
            end_at = None
            content = req.body
            self._log = models.AuditLog(id, user_id, tenant_id, rid, path,
                                        method, status_code, begin_at, end_at,
                                        content)
        else:
            self._log = None

    def process_response(self, response):
        if self._log is not None:
            self._log.status_code = response.status_int
            end_at = self._format_time(timeutils.utcnow())
            self._log.end_at = end_at
            self._store_log(self._log)
            self._log = None
        return response

    def _store_log(self, log):
        try:
            self.connection.create_auditlog(log)
        except Exception as e:
            LOG.error("Store audit log error : %s", e)

    def _format_time(self, time):
        formated_t = timeutils.strtime(time,
                                       '%Y-%m-%d %H:%M:%S')
        end = timeutils.parse_strtime(formated_t,
                                      '%Y-%m-%d %H:%M:%S')
        return end


text:
namespace media {

OffsetByteQueue::OffsetByteQueue() : buf_(nullptr), size_(0), head_(0) {}
OffsetByteQueue::~OffsetByteQueue() = default;

void OffsetByteQueue::Reset() {
  queue_.Reset();
  buf_ = nullptr;
  size_ = 0;
  head_ = 0;
}

void OffsetByteQueue::Push(const uint8_t* buf, int size) {
  queue_.Push(buf, size);
  Sync();
  DVLOG(4) << "Buffer pushed. head=" << head() << " tail=" << tail();
}

void OffsetByteQueue::Peek(const uint8_t** buf, int* size) {
  *buf = size_ > 0 ? buf_ : nullptr;
  *size = size_;
}

void OffsetByteQueue::Pop(int count) {
  queue_.Pop(count);
  head_ += count;
  Sync();
}

void OffsetByteQueue::PeekAt(int64_t offset, const uint8_t** buf, int* size) {
  DCHECK(offset >= head());
  if (offset < head() || offset >= tail()) {
    *buf = nullptr;
    *size = 0;
    return;
  }
  *buf = &buf_[offset - head()];
  *size = tail() - offset;
}

bool OffsetByteQueue::Trim(int64_t max_offset) {
  if (max_offset < head_) return true;
  if (max_offset > tail()) {
    Pop(size_);
    return false;
  }
  Pop(max_offset - head_);
  return true;
}

void OffsetByteQueue::Sync() {
  queue_.Peek(&buf_, &size_);
}

}  // namespace media


text:
package org.pac4j.saml.transport;

import net.shibboleth.utilities.java.support.codec.Base64Support;
import net.shibboleth.utilities.java.support.collection.Pair;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.net.URLBuilder;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.core.xml.util.XMLObjectSupport;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.encoder.AbstractMessageEncoder;
import org.opensaml.messaging.encoder.MessageEncodingException;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.common.binding.BindingException;
import org.opensaml.saml.common.binding.SAMLBindingSupport;
import org.opensaml.saml.common.messaging.SAMLMessageSecuritySupport;
import org.opensaml.saml.saml2.core.RequestAbstractType;
import org.opensaml.saml.saml2.core.StatusResponseType;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialSupport;
import org.opensaml.xmlsec.SignatureSigningParameters;
import org.opensaml.xmlsec.crypto.XMLSigningUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;

/**
 * Pac4j implementation extending directly the {@link AbstractMessageEncoder} as intermediate classes use the J2E HTTP response.
 * It's mostly a copy/paste of the source code of these intermediate opensaml classes.
 *
 * @author Misagh Moayyed
 * @since 1.8
 */
public class Pac4jHTTPRedirectDeflateEncoder extends AbstractMessageEncoder<SAMLObject> {

    private final static Logger log = LoggerFactory.getLogger(Pac4jHTTPPostEncoder.class);

    private final Pac4jSAMLResponse responseAdapter;
    private final boolean isAuthnRequestSigned;

    public Pac4jHTTPRedirectDeflateEncoder(final Pac4jSAMLResponse responseAdapter,
                                           final boolean isAuthnRequestSigned) {
        this.responseAdapter = responseAdapter;
        this.isAuthnRequestSigned = isAuthnRequestSigned;
    }

    @Override
    protected void doEncode() throws MessageEncodingException {
        final MessageContext messageContext = this.getMessageContext();
        final SAMLObject outboundMessage = (SAMLObject)messageContext.getMessage();
        final String endpointURL = this.getEndpointURL(messageContext).toString();

        if (!this.isAuthnRequestSigned) {
            this.removeSignature(outboundMessage);
        }

        final String encodedMessage = this.deflateAndBase64Encode(outboundMessage);
        final String redirectURL = this.buildRedirectURL(messageContext, endpointURL, encodedMessage);

        responseAdapter.init();
        responseAdapter.setRedirectUrl(redirectURL);
    }

    @Override
    protected void doInitialize() throws ComponentInitializationException {
        log.debug("Initialized {}", this.getClass().getSimpleName());
    }

    /**
     * Gets the response URL from the message context.
     *
     * @param messageContext current message context
     *
     * @return response URL from the message context
     *
     * @throws MessageEncodingException throw if no relying party endpoint is available
     */
    protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException {
        try {
            return SAMLBindingSupport.getEndpointURL(messageContext);
        } catch (BindingException e) {
            throw new MessageEncodingException("Could not obtain message endpoint URL", e);
        }
    }

    /**
     * Removes the signature from the protocol message.
     *
     * @param message current message context
     */
    protected void removeSignature(SAMLObject message) {
        if (message instanceof SignableSAMLObject) {
            final SignableSAMLObject signableMessage = (SignableSAMLObject) message;
            if (signableMessage.isSigned()) {
                log.debug("Removing SAML protocol message signature");
                signableMessage.setSignature(null);
            }
        }
    }

    /**
     * DEFLATE (RFC1951) compresses the given SAML message.
     *
     * @param message SAML message
     *
     * @return DEFLATE compressed message
     *
     * @throws MessageEncodingException thrown if there is a problem compressing the message
     */
    protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
        log.debug("Deflating and Base64 encoding SAML message");
        try {
            String messageStr = SerializeSupport.nodeToString(marshallMessage(message));
            log.trace("Output XML message: {}", messageStr);

            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            Deflater deflater = new Deflater(Deflater.DEFLATED, true);
            DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
            deflaterStream.write(messageStr.getBytes(StandardCharsets.UTF_8));
            deflaterStream.finish();

            return Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED);
        } catch (IOException e) {
            throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
        }
    }

    /**
     * Helper method that marshalls the given message.
     *
     * @param message message the marshall and serialize
     *
     * @return marshalled message
     *
     * @throws MessageEncodingException thrown if the give message can not be marshalled into its DOM representation
     */
    protected Element marshallMessage(XMLObject message) throws MessageEncodingException {
        log.debug("Marshalling message");

        try {
            return XMLObjectSupport.marshall(message);
        } catch (MarshallingException e) {
            throw new MessageEncodingException("Error marshalling message", e);
        }
    }

    /**
     * Builds the URL to redirect the client to.
     *
     * @param messageContext current message context
     * @param endpoint endpoint URL to send encoded message to
     * @param message Deflated and Base64 encoded message
     *
     * @return URL to redirect client to
     *
     * @throws MessageEncodingException thrown if the SAML message is neither a RequestAbstractType or Response
     */
    protected String buildRedirectURL(MessageContext<SAMLObject> messageContext, String endpoint, String message)
            throws MessageEncodingException {
        log.debug("Building URL to redirect client to");

        URLBuilder urlBuilder = null;
        try {
            urlBuilder = new URLBuilder(endpoint);
        } catch (MalformedURLException e) {
            throw new MessageEncodingException("Endpoint URL " + endpoint + " is not a valid URL", e);
        }

        List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
        queryParams.clear();

        SAMLObject outboundMessage = messageContext.getMessage();

        if (outboundMessage instanceof RequestAbstractType) {
            queryParams.add(new Pair<>("SAMLRequest", message));
        } else if (outboundMessage instanceof StatusResponseType) {
            queryParams.add(new Pair<>("SAMLResponse", message));
        } else {
            throw new MessageEncodingException(
                    "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
        }

        String relayState = SAMLBindingSupport.getRelayState(messageContext);
        if (SAMLBindingSupport.checkRelayState(relayState)) {
            queryParams.add(new Pair<>("RelayState", relayState));
        }

        SignatureSigningParameters signingParameters =
                SAMLMessageSecuritySupport.getContextSigningParameters(messageContext);
        if (signingParameters != null && signingParameters.getSigningCredential() != null) {
            String sigAlgURI =  getSignatureAlgorithmURI(signingParameters);
            Pair<String, String> sigAlg = new Pair<>("SigAlg", sigAlgURI);
            queryParams.add(sigAlg);
            String sigMaterial = urlBuilder.buildQueryString();

            queryParams.add(new Pair<>("Signature", generateSignature(
                    signingParameters.getSigningCredential(), sigAlgURI, sigMaterial)));
        } else {
            log.debug("No signing credential was supplied, skipping HTTP-Redirect DEFLATE signing");
        }

        return urlBuilder.buildURL();
    }

    /**
     * Gets the signature algorithm URI to use.
     *
     * @param signingParameters the signing parameters to use
     *
     * @return signature algorithm to use with the associated signing credential
     *
     * @throws MessageEncodingException thrown if the algorithm URI is not supplied explicitly and
     *          could not be derived from the supplied credential
     */
    protected String getSignatureAlgorithmURI(SignatureSigningParameters signingParameters)
            throws MessageEncodingException {

        if (signingParameters.getSignatureAlgorithm() != null) {
            return signingParameters.getSignatureAlgorithm();
        }

        throw new MessageEncodingException("The signing algorithm URI could not be determined");
    }

    /**
     * Generates the signature over the query string.
     *
     * @param signingCredential credential that will be used to sign query string
     * @param algorithmURI algorithm URI of the signing credential
     * @param queryString query string to be signed
     *
     * @return base64 encoded signature of query string
     *
     * @throws MessageEncodingException there is an error computing the signature
     */
    protected String generateSignature(Credential signingCredential, String algorithmURI, String queryString)
            throws MessageEncodingException {

        log.debug(String.format("Generating signature with key type '%s', algorithm URI '%s' over query string '%s'",
                CredentialSupport.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, queryString));

        String b64Signature = null;
        try {
            byte[] rawSignature =
                    XMLSigningUtil.signWithURI(signingCredential, algorithmURI, queryString.getBytes(StandardCharsets.UTF_8));
            b64Signature = Base64Support.encode(rawSignature, Base64Support.UNCHUNKED);
            log.debug("Generated digital signature value (base64-encoded) {}", b64Signature);
        } catch (final org.opensaml.security.SecurityException e) {
            throw new MessageEncodingException("Unable to sign URL query string", e);
        }

        return b64Signature;
    }
}


text:
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Preferences;
using Sample.Anim;
using Sample.Fragments;

namespace Sample
{
    [Activity(MainLauncher = true, Label = "SlidingMenu Demo", Theme = "@style/ExampleTheme")]
    public class ExampleListActivity : PreferenceActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetTitle(Resource.String.app_name);
            AddPreferencesFromResource(Resource.Xml.main);
        }

        public override bool OnPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)
        {
            Type cls = null;
            var title = preference.Title;

            if (title.Equals(GetString(Resource.String.properties)))
                cls = typeof(PropertiesActivity);
            else if (title.Equals(GetString(Resource.String.attach)))
                cls = typeof(AttachExample);
            else if (title.Equals(GetString(Resource.String.changing_fragments)))
                cls = typeof(FragmentChangeActivity);
            else if (title.Equals(GetString(Resource.String.left_and_right)))
                cls = typeof(LeftAndRightActivity);
            else if (title.Equals(GetString(Resource.String.responsive_ui)))
                cls = typeof(ResponsiveUIActivity);
            else if (title.Equals(GetString(Resource.String.viewpager)))
                cls = typeof(ViewPagerActivity);
            else if (title.Equals(GetString(Resource.String.title_bar_slide)))
                cls = typeof(SlidingTitleBar);
            else if (title.Equals(GetString(Resource.String.title_bar_content)))
                cls = typeof(SlidingContent);
            else if (title.Equals(GetString(Resource.String.anim_zoom)))
                cls = typeof(ZoomAnimation);
            else if (title.Equals(GetString(Resource.String.anim_scale)))
                cls = typeof(ScaleAnimation);
            else if (title.Equals(GetString(Resource.String.anim_slide)))
                cls = typeof(SlideAnimation);

            var intent = new Intent(this, cls);
            StartActivity(intent);
            return true;
        }
    }
}