text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\DatePicker;
use app\models\User;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use kartik\widgets\Select2;
use kartik\widgets\TimePicker;
use yii\grid\GridView;

$this->title = 'ฟอร์มเลือกสมาชิก';
?>

        ฟอร์มเลือกสมาชิก

       <?php $form = ActiveForm::begin(['options'=>['class'=>'form-inline']]); ?>

                <?= $form->field($model, 'member_id')->widget(Select2::classname(), [
                    'language' => 'th',
                    'data' => ArrayHelper::map(User::find()->where(['status'=>'1'])->orderBy(['member_name'=>SORT_ASC])->all(),'id','member_name'),
                    'options' => ['placeholder' => '-- กรุณาเลือกสมาชิก --'],
                    'pluginOptions' => [
                        'allowClear' => true
                    ],
                ])->label(false); ?>

                <?= Html::submitButton(' เลือก' , ['class' => 'btn btn-primary']) ?>

        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                'user.member_name',
                'user.position.position_name',
                [
                    'attribute' => 'Action',
                    'format' => 'raw',
                    'value' => function($data){
                        return Html::a(' ลบ',Url::to(['official/delete-member-list','member_id'=>$data->member_id,'official_id'=>$data->official_id]),['class'=>'btn btn-sm btn-danger','onclick'=>"return confirm('คุณต้องการลบใช่หรือไม่ ? ')"]);
                    },
                    'contentOptions' => ['class'=>'text-center']
                ],
            ],
        ]); ?>

        <?php if(Yii::$app->session->hasFlash('success')) : ?>

                <button aria-hidden="true" data-dismiss="alert" class="close" type="button">
                    ×
                    Close
                </button>

<?=Yii::$app->session->getFlash('success')?>

        <?php endif; ?>

        <a href="<?=Url::to(['official/history-me-wait'])?>" class="btn btn-warning btn-block"> เสร็จสิ้นการเลือกสมาชิก


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.storage.network;

import androidx.annotation.NonNull;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.internal.StorageReferenceUri;

/** A network request that returns metadata on a gcs object. */
public class GetMetadataNetworkRequest extends NetworkRequest {
  public GetMetadataNetworkRequest(
      @NonNull StorageReferenceUri storageReferenceUri, @NonNull FirebaseApp app) {
    super(storageReferenceUri, app);
  }

  @Override
  @NonNull
  protected String getAction() {
    return GET;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p"

	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">

	<context:component-scan base-package="tw.com.fstop.spring, tw.com.fstop.app"/>

	<mvc:annotation-driven />

    <!-- 實際路徑 location 不可以 "/" 開頭 -->
	<mvc:resources mapping="/css/**" location="css/" />
	<mvc:resources mapping="/js/**" location="js/" />
	<mvc:resources mapping="/fonts/**" location="fonts/" />
	<mvc:resources mapping="/images/**" location="images/" />
	<mvc:resources mapping="/*.html" location="/" />

	<!-- site admin -->
	<mvc:resources mapping="/site/admin/login/css/**" location="site/admin/login/css/" />
	<mvc:resources mapping="/site/admin/login/js/**" location="site/admin/login/js/" />
	<mvc:resources mapping="/site/admin/login/fonts/**" location="site/admin/login/fonts/" />
	<mvc:resources mapping="/site/admin/login/images/**" location="site/admin/login/images/" />
	<mvc:resources mapping="/site/admin/login/*.html" location="site/admin/login/" />

	<mvc:resources mapping="/site/admin/main/**" location="site/admin/main/" />

<!--
    <bean name="htmlController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"/>
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/401-page.html">htmlController</prop>
                <prop key="/404-page.html">htmlController</prop>
                <prop key="/500-page.html">htmlController</prop>
            </props>
        </property>
    </bean>
 -->

	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

<!--  	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> -->

 	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="zh_TW"/>
        <property name="cookieName" value="locale-cookie"/>
        <property name="cookieMaxAge" value="3600"/>
    </bean>

	<mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="locale"/>
        </bean>

        <bean class="tw.com.fstop.spring.interceptor.AllInterceptor"/>

        <!--
        <mvc:interceptor>
        	<mvc:mapping path="/login.do"/>
        	<bean class="tw.com.fstop.app.srping.interceptor.LoginInterceptor"/>
    	</mvc:interceptor>
        -->

    </mvc:interceptors>

</beans>


text:
namespace falcon {
namespace _aux {

template <class Class, class T, bool IsReverse = false>
class circular_bit
{
public:
	typedef typename FALCON_BOOST_OR_STD_NAMESPACE::remove_cv<T>::type value_type;

private:
	typedef typename std::decay<value_type>::type unqualified_type;
	static const unqualified_type s_left = bit::left<unqualified_type>::value;
	static const unqualified_type s_right = bit::right<unqualified_type>::value;

private:
	value_type _mask;

public:
	circular_bit()
	: _mask(IsReverse ? s_right : s_left)
	{}

	circular_bit(const value_type& mask)
	: _mask(mask)
	{}

	circular_bit(const circular_bit& other)
	: _mask(other._mask)
	{}

	circular_bit& operator=(const circular_bit& other)
	{
		_mask == other._mask;
		return *this;
	}

	const value_type& operator*() const
	{ return _mask; }

	const value_type& get() const
	{ return _mask; }

private:
	void move(false_type)
	{
		if (_mask == s_left)
			_mask = s_right;
		else
			_mask = static_cast<T>(_mask << 1);
	}

	void move(true_type)
	{
		if (_mask == s_right)
			_mask = s_left;
		else
			_mask = static_cast<T>(_mask >> 1);
	}

public:
	Class& operator++()
	{
		move(integral_constant<bool, !IsReverse>());
		return static_cast<Class&>(*this);
	}

	Class operator++(int)
	{
		Class tmp(static_cast<Class&>(*this));
		return ++tmp;
	}

	Class& operator--()
	{
		move(integral_constant<bool, IsReverse>());
		return static_cast<Class&>(*this);
	}

	Class operator--(int)
	{
		Class tmp(static_cast<Class&>(*this));
		return --tmp;
	}

	FALCON_MEMBER_COMPARISON2_ALL_OPERATOR(circular_bit, _mask, other._mask)

	void reset()
	{ _mask = IsReverse ? s_right : s_left; }
};

}

template <class T>
class basic_circular_bit
: public _aux::circular_bit<basic_circular_bit<T>, T>
{
  typedef _aux::circular_bit<basic_circular_bit<T>, T> base_type;

public:
	typedef typename base_type::value_type value_type;

public:
	basic_circular_bit()
	: base_type()
	{}

	basic_circular_bit(const value_type& mask)
	: base_type(mask)
	{}
};

template <class T>
class basic_reverse_circular_bit
: public _aux::circular_bit<basic_reverse_circular_bit<T>, T, true>
{
  typedef _aux::circular_bit<basic_reverse_circular_bit<T>, T, true> base_type;

public:
	typedef typename base_type::value_type value_type;

public:
	basic_reverse_circular_bit()
	: base_type()
	{}

	basic_reverse_circular_bit(const value_type& mask)
	: base_type(mask)
	{}
};

typedef basic_circular_bit<unsigned> u_circular_bit;
typedef basic_reverse_circular_bit<unsigned> reverse_u_circular_bit;
typedef basic_circular_bit<unsigned long> ul_circular_bit;
typedef basic_reverse_circular_bit<unsigned long> reverse_ul_circular_bit;
#if __cplusplus >= 201103L
typedef basic_circular_bit<unsigned long long> ull_circular_bit;
typedef basic_reverse_circular_bit<unsigned long long> reverse_ull_circular_bit;
#endif

}

#endif


text:
import numpy as np

from bokeh.layouts import column, gridplot, row
from bokeh.plotting import figure, show

N = 1000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]

TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select"

def mkplot(xaxis="below", yaxis="left"):
    p = figure(width=300, height=300, tools=TOOLS, x_axis_location=xaxis, y_axis_location=yaxis)
    p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)
    return p

def mkgrid(plots, location):
    return gridplot(plots, width=300, height=300, toolbar_location=location)

l_al = mkgrid([[mkplot(), mkplot()], [mkplot(), mkplot()]], "above")
l_ar = mkgrid([[mkplot(), mkplot()], [mkplot(), mkplot()]], "below")
l_bl = mkgrid([[mkplot(), mkplot()], [mkplot(), mkplot()]], "left")
l_br = mkgrid([[mkplot(), mkplot()], [mkplot(), mkplot()]], "right")

layout = column(row(l_al, l_ar), row(l_bl, l_br))

show(layout)


text:
package com.sksamuel.elastic4s

import com.sksamuel.elastic4s.ElasticDsl._
import org.elasticsearch.action.WriteConsistencyLevel
import org.elasticsearch.action.bulk.BulkRequest
import org.elasticsearch.action.support.replication.ReplicationType
import org.elasticsearch.common.unit.TimeValue

/** @author Stephen Samuel */
trait BulkCompatibleDefinition

trait BulkDsl {
  this: IndexDsl =>
  def bulk(requests: BulkCompatibleDefinition*): BulkDefinition = new BulkDefinition(requests)
}

class BulkDefinition(requests: Seq[BulkCompatibleDefinition]) {

  def timeout(value: String): this.type = {
    _builder.timeout(value)
    this
  }

  def timeout(value: TimeValue): this.type = {
    _builder.timeout(value)
    this
  }

  def replicationType(replicationType: ReplicationType): this.type = {
    _builder.replicationType(replicationType)
    this
  }

  def refresh(refresh: Boolean): this.type = {
    _builder.refresh(refresh)
    this
  }

  def consistencyLevel(level: WriteConsistencyLevel): this.type = {
    _builder.consistencyLevel(level)
    this
  }

  val _builder = new BulkRequest()
  requests.foreach {
    case index: IndexDefinition => _builder.add(index.build)
    case delete: DeleteByIdDefinition => _builder.add(delete.build)
    case update: UpdateDefinition => _builder.add(update.build)
    case register: RegisterDefinition => _builder.add(register.build)
  }
}


text:
<?php
	/**
	 * copy file
	 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
	 * @link www.phpletter.com
	 * @since 22/May/2007
	 *
	 */

	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
    if(!osc_is_admin_user_logged_in()) { exit('Direct access is not allowed.'); };
	$error = "";
	$info = '';
	if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_COPY)
	{
		$error = SYS_DISABLED;
	}
	elseif(!isset($_POST['selectedDoc']) || !is_array($_POST['selectedDoc']) || sizeof($_POST['selectedDoc']) < 1)
	{
		$error = ERR_NOT_DOC_SELECTED_FOR_COPY;
	}
	elseif(empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath']))
	{
		$error = ERR_FOLDER_PATH_NOT_ALLOWED;
	}else
	{
		require_once(CLASS_SESSION_ACTION);
		$sessionAction = new SessionAction();
		$sessionAction->setAction($_POST['action_value']);
		$sessionAction->setFolder($_POST['currentFolderPath']);
		$sessionAction->set($_POST['selectedDoc']);
		$info = ',num:' . sizeof($_POST['selectedDoc']);
	}
	echo "{error:'" . $error .  "'\n" . $info . "}";
?>


text:
import {MultiAudioNode} from '../MultiAudioNode';

/**
 * The audio-effects delay class.
 * This class lets you add a delay effect.
 */
export class Delay extends MultiAudioNode {
    private _wet: number;
    private _speed: number;
    private _duration: number;

    constructor(audioContext: AudioContext) {
        super(audioContext);

        this.nodes = {
            inputGainNode: audioContext.createGain(), // Create the input and output nodes of the effect
            outputGainNode: audioContext.createGain(),
            wetGainNode: audioContext.createGain(), // Create the gain-node we'll use to controll the wetness of the delay
            durationGainNode: audioContext.createGain(), // Create the gain node we'll use to controll the duration of the delay
            delayNode: audioContext.createDelay() // Create the delay node
        };

        // Wire it all up
        this.nodes['inputGainNode'].connect(this.nodes['wetGainNode']);
        this.nodes['inputGainNode'].connect(this.nodes['delayNode']);
        this.nodes['durationGainNode'].connect(this.nodes['delayNode']);
        this.nodes['delayNode'].connect(this.nodes['durationGainNode']);
        this.nodes['delayNode'].connect(this.nodes['outputGainNode'])
        this.nodes['wetGainNode'].connect(this.nodes['outputGainNode'])

        // Set the input gain-node as the input-node.
        this.node = this.nodes['inputGainNode'];
        // Set the output gain-node as the output-node.
        this.output = this.nodes['outputGainNode'];

        // Set the default wetness to 1
        this.wet = 1;

        // Set the default speed to 1 second
        this.speed = 1;

        // Set the default duration to 0.4
        this.duration = 0.4;
    }

    /**
     * Getter for the effect's wetness
     * @return {number}
     */
    public get wet() : number|string {
        return this._wet;
    }

    /**
     * Setter for the effect's wetness
     * @param  {number|string} wetness
     */
    public set wet(wetness: number|string) {
        // Set the internal wetness value
        this._wet = parseFloat(<string>wetness);

        // Set the new value for the wetness controll gain-node
        (<GainNode>this.nodes['wetGainNode']).gain.value = this._wet;
    }

    /**
     * Getter for the effect's speed
     * @return {number}
     */
    public get speed() : number|string {
        return this._speed;
    }

    /**
     * Setter for the effect's speed
     * @param {number|string} speed
     */
    public set speed(speed: number|string) {
        // Set the internal speed value
        this._speed = parseFloat(<string>speed);

        // Set the delayTime value of the delay-node
        (<DelayNode>this.nodes['delayNode']).delayTime.value = this._speed;
    }

    /**
     * Getter for the effect's duration
     * @return {number}
     */
    public get duration() : number|string {
        return this._duration;
    }

    /**
     * Setter for the effect's duration
     * @param  {number|string} duration
     */
    public set duration(duration: number|string) {
        // Set the internal duration value
        this._duration = parseFloat(<string>duration);

        // Set the duration gain-node value
        (<GainNode>this.nodes['durationGainNode']).gain.value = this._duration;
    }
};


text:
'use strict';

(function() {
	// General test reports Controller Spec
	describe('General test reports Controller Tests', function() {
		// Initialize global variables
		var GeneralTestReportsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the General test reports controller.
			GeneralTestReportsController = $controller('GeneralTestReportsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one General test report object fetched from XHR', inject(function(GeneralTestReports) {
			// Create sample General test report using the General test reports service
			var sampleGeneralTestReport = new GeneralTestReports({
				name: 'New General test report'
			});

			// Create a sample General test reports array that includes the new General test report
			var sampleGeneralTestReports = [sampleGeneralTestReport];

			// Set GET response
			$httpBackend.expectGET('general-test-reports').respond(sampleGeneralTestReports);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.generalTestReports).toEqualData(sampleGeneralTestReports);
		}));

		it('$scope.findOne() should create an array with one General test report object fetched from XHR using a generalTestReportId URL parameter', inject(function(GeneralTestReports) {
			// Define a sample General test report object
			var sampleGeneralTestReport = new GeneralTestReports({
				name: 'New General test report'
			});

			// Set the URL parameter
			$stateParams.generalTestReportId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/general-test-reports\/([0-9a-fA-F]{24})$/).respond(sampleGeneralTestReport);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.generalTestReport).toEqualData(sampleGeneralTestReport);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(GeneralTestReports) {
			// Create a sample General test report object
			var sampleGeneralTestReportPostData = new GeneralTestReports({
				name: 'New General test report'
			});

			// Create a sample General test report response
			var sampleGeneralTestReportResponse = new GeneralTestReports({
				_id: '525cf20451979dea2c000001',
				name: 'New General test report'
			});

			// Fixture mock form input values
			scope.name = 'New General test report';

			// Set POST response
			$httpBackend.expectPOST('general-test-reports', sampleGeneralTestReportPostData).respond(sampleGeneralTestReportResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the General test report was created
			expect($location.path()).toBe('/general-test-reports/' + sampleGeneralTestReportResponse._id);
		}));

		it('$scope.update() should update a valid General test report', inject(function(GeneralTestReports) {
			// Define a sample General test report put data
			var sampleGeneralTestReportPutData = new GeneralTestReports({
				_id: '525cf20451979dea2c000001',
				name: 'New General test report'
			});

			// Mock General test report in scope
			scope.generalTestReport = sampleGeneralTestReportPutData;

			// Set PUT response
			$httpBackend.expectPUT(/general-test-reports\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/general-test-reports/' + sampleGeneralTestReportPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid generalTestReportId and remove the General test report from the scope', inject(function(GeneralTestReports) {
			// Create new General test report object
			var sampleGeneralTestReport = new GeneralTestReports({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new General test reports array and include the General test report
			scope.generalTestReports = [sampleGeneralTestReport];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/general-test-reports\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleGeneralTestReport);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.generalTestReports.length).toBe(0);
		}));
	});
}());


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\Core\Route\RoleAccessCheckTest.
 */

namespace Drupal\Tests\Core\Route;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\UserSession;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Access\RoleAccessCheck;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * @coversDefaultClass \Drupal\user\Access\RoleAccessCheck
 * @group Access
 * @group Route
 */
class RoleAccessCheckTest extends UnitTestCase {

  /**
   * Generates the test route collection.
   *
   * @return \Symfony\Component\Routing\RouteCollection
   *   Returns the test route collection.
   */
  protected function getTestRouteCollection() {
    $route_collection = new RouteCollection();
    $route_collection->add('role_test_1', new Route('/role_test_1',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_1',
      )
    ));
    $route_collection->add('role_test_2', new Route('/role_test_2',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_2',
      )
    ));
    $route_collection->add('role_test_3', new Route('/role_test_3',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_1,role_test_2',
      )
    ));
    // Ensure that trimming the values works on "OR" conjunctions.
    $route_collection->add('role_test_4', new Route('/role_test_4',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_1 , role_test_2',
      )
    ));
    $route_collection->add('role_test_5', new Route('/role_test_5',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_1+role_test_2',
      )
    ));
    // Ensure that trimming the values works on "AND" conjunctions.
    $route_collection->add('role_test_6', new Route('/role_test_6',
      array(
        '_controller' => '\Drupal\router_test\TestControllers::test1',
      ),
      array(
        '_role' => 'role_test_1 + role_test_2',
      )
    ));

    return $route_collection;
  }

  /**
   * Provides data for the role access test.
   *
   * @see \Drupal\Tests\Core\Route\RouterRoleTest::testRoleAccess
   */
  public function roleAccessProvider() {
    // Setup two different roles used in the test.
    $rid_1 = 'role_test_1';
    $rid_2 = 'role_test_2';

    // Setup one user with the first role, one with the second, one with both
    // and one final without any of these two roles.

    $account_1 = new UserSession(array(
      'uid' => 1,
      'roles' => array($rid_1),
    ));

    $account_2 = new UserSession(array(
      'uid' => 2,
      'roles' => array($rid_2),
    ));

    $account_12 = new UserSession(array(
      'uid' => 3,
      'roles' => array($rid_1, $rid_2),
    ));

    $account_none = new UserSession(array(
      'uid' => 1,
      'roles' => array(),
    ));

    // Setup expected values; specify which paths can be accessed by which user.
    return array(
      array('role_test_1', array($account_1, $account_12), array($account_2, $account_none)),
      array('role_test_2', array($account_2, $account_12), array($account_1, $account_none)),
      array('role_test_3', array($account_12), array($account_1, $account_2, $account_none)),
      array('role_test_4', array($account_12), array($account_1, $account_2, $account_none)),
      array('role_test_5', array($account_1, $account_2, $account_12), array()),
      array('role_test_6', array($account_1, $account_2, $account_12), array()),
    );
  }

  /**
   * Tests role requirements on routes.
   *
   * @param string $path
   *   The path to check access for.
   * @param array $grant_accounts
   *   A list of accounts which should have access to the given path.
   * @param array $deny_accounts
   *   A list of accounts which should not have access to the given path.
   *
   * @see \Drupal\Tests\Core\Route\RouterRoleTest::getTestRouteCollection
   * @see \Drupal\Tests\Core\Route\RouterRoleTest::roleAccessProvider
   *
   * @dataProvider roleAccessProvider
   */
  public function testRoleAccess($path, $grant_accounts, $deny_accounts) {
    $role_access_check = new RoleAccessCheck();
    $collection = $this->getTestRouteCollection();

    foreach ($grant_accounts as $account) {
      $message = sprintf('Access granted for user with the roles %s on path: %s', implode(', ', $account->getRoles()), $path);
      $this->assertEquals(AccessResult::allowed()->addCacheContexts(['user.roles']), $role_access_check->access($collection->get($path), $account), $message);
    }

    // Check all users which don't have access.
    foreach ($deny_accounts as $account) {
      $message = sprintf('Access denied for user %s with the roles %s on path: %s', $account->id(), implode(', ', $account->getRoles()), $path);
      $has_access = $role_access_check->access($collection->get($path), $account);
      $this->assertEquals(AccessResult::neutral()->addCacheContexts(['user.roles']), $has_access, $message);
    }
  }

}


text:
title: Switching to Vim
date: 21:19 06/30/2016
published: false
taxonomy:
    category: blog
    tag: [vim, tutorial, editor]
highlight:
    theme: monokai
---

Since starting in my new job, I've been hearing more and more about 'Vim' around the office and have been curious in trying it out. I've only recently made the 'switch' but I wanted to write about what I've learnt so far and how I've adapted it for my own purposes.

![term_into](vim.svg)

===

###What is Vim and why?

Vim ('vi' IMproved) for the unacquainted, is a text editor based on the command-line interface, and hence probably looks more akin to a terminal view than any GUI text-editor you've seen before. Don't let that put you off though because you're just a step away from one of the coolest and most versatile editors out there!

So why Vim and why now? For myself like most things, I was simply curious. Lately I've been keen on boosting my prowess inside the shell and creating shortcuts in my workflow. Discovering Vim was like finding something I'd been searching for all along.

! Please note that this is not another Vim tutorial - there's enough of those out there. Rather this is just someone else's first-hand experience of using Vim for the first time which may include something useful.

An editor inside the terminal is just the greatest thing and honestly I spend most of my time within iTerm nowadays since discovering Vim.

!!!! Actually, on that point you can use the `:.! [command]` to execute an external bash command and dump the output into Vim. For example `:.! date` would insert the current date into your open buffer within Vim.

###Where do I start & how do things work?

Firstly, I found this quick [video](https://www.youtube.com/watch?v=_NUO4JEtkDw) super useful and it's well worth the watch. It's even the first link when you search for 'Vim' on YouTube.

There's two critical points to take away from the video that vastly improve your Vim experience.

####Remap Caps Lock to ESC

You would not believe how vital this really is. When I started, the first thing I took to disliking was the use of the ESC key. It's simply too far out of the way and awkward to reach. So change that by remapping your needless Caps Lock with [this](https://pqrs.org/osx/karabiner/seil.html.en) handy tool.

####Speed up your Key Repeat

This is really handy, even if you're not interested in using Vim. Honestly, before changing my key repeats I had no idea how slow the default settings were. You can install [Karabiner](https://pqrs.org/osx/karabiner/) to modify the key repeats. The settings I've used and as recommended in the video are as follows:

+ Delay until Repeat: 400ms
+ Key Repeat: 25ms

####Steal a dotfile

This is a maybe. If you feel you'd learn more from doing things yourself then I recommend just going ahead and creating your own unique `~/.vimrc` and configuring things as you learn. Since I'm lazy and overconfident I went ahead and downloaded this really nice [vimrc](https://github.com/amix/vimrc) which has most things you'd probably want. However this really throws you in the deep-end and you have to spend time figuring out how things sit together. Not impossible though.

####Disable the arrow keys

You're not helping yourself by cheating. Keeping your hands firmly on the home-row is the one rule you must abide. I recommend disabling the arrow keys entirely by including the following in your `vimrc`:

`noremap <Up> <NOP>`
`noremap <Down> <NOP>`
`noremap <Left> <NOP>`
`noremap <Right> <NOP>`

###Some useful Vim commands

With just a few days of using Vim, I've already started to catalogue the most useful shortcuts I've picked up so far. Predictably enough, someone has already composed a very complete [list](http://rayninfo.co.uk/vimtips.html); compiled across nine years of using Vim.

Here are just a few of the most convienent I've adopted:

+ **ddp** moves the current line one row down
+ **%** finds and jumps to matching bracket highlighted
+ **dt,** deletes up until the next comma
+ **bye** yanks the current word
+ **.** the humble dot repeats the last modification
+ **'.** this jumps the cursor to the last modified line
+ **;** for the last f, t, F or T

There's also a bunch of shortcut commands I'm using with the mapleader `<leader>` which I've configured for `,` in my setup.

![vim_overview](vim_overview.png)

###Setting up FTP for Web Development - Case Study

As any typical programmer, the question you're always going to ask yourself before switching to a different environment is whether you can still perform the same tasks as you did in your previous editor. The only answer I've found for Vim is 'yes' and much more.

For instance, in my case I wanted to be able to FTP up to my website (a crucial requirement for anyone in web development) and sure enough, Vim had the right tool for the job.

Like any other editor Vim requires the necessary plugin for this new functionality - so called **vim-sync** which is available [here](https://github.com/eshion/vim-sync/) and allows for the automatic syncing of local and remote files within Vim.

!!! I later discovered that Vim actually has something called [netrw](http://www.vim.org/scripts/script.php?script_id=1075) which supports the reading and writing of files across networks, which many people seem to use for FTP.

With the previous download of Amix's vimrc, I already had [pathogen](https://github.com/tpope/vim-pathogen) installed and hence it was just a simple matter of booting up the terminal and running the following:

`
cd ~/.vim_runtime
`
`
git clone https://github.com/eshion/vim-sync/ sources_non_forked/vim-sync
`
!!! This command just clones the repo into a new folder name `vim-sync` inside the `sources_non_forked` directory.

The next step after install, according to the directions on the vim-sync Github page is to create a new executable `.sync` file in your project directory.

```bash
#!/bin/sh
if [ "upload" == $1 ];then
ncftpput -m -u login_name -p login_password -P 21 remote_host remote_path/$2 `dirname $0`/$2/$3
elif [ 'download' == $1 ];then
ncftpget -u login_name -p login_password -P 21 remote_host `dirname $0`/$2 remote_path/$2/$3
fi
```

Inside the new `.sync` file is where you write the **execute config** for your remote host - whether for rsync, FTP, SFTP .etc. Examples are provided inside the `.README`.

In the case of FTP, replace the following with your own details:

* login_name
* login_password
* remote_host
* remote_path

!!! Ignore the '$' numbers - they're variables necessary for the script, you'll see see them in the output when the file is executed

However, before you try running this script there's two more steps that are required - which are unfortunately absent from the `.README`.

Firstly, you're going to want to change the privileges for `.sync` before you can even try executing the file. Switch over to your terminal window and type the following to make it executable:

`
chmod +x .sync
`

![chmod](chmod.png)

Another semi-obvious thing (if you've even glanced at the script) is to install [ncftpget](http://www.ncftp.com/ncftp/doc/ncftpput.html) which is the internet file transfer program used by the script.

You can do this by installing it with HomeBrew:

`
brew install ncftp
`

![ncftp](ncftp_install.png)

After that quick setup, you should have a handy way of FTP'ing your files on the go.

If you prefer like me, you can remap the keys so `CTRL` + `u` uploads the open buffer and `CTRL` + `d` does the download.

The way to do this is to open up the `sources_non_forked` directory again and navigate to `sync.vim` for vim-sync.

Open the file and insert the following at the very bottom:

`
nnoremap <C-U> <ESC>:call SyncUploadFile()<CR>
`
`
nnoremap <C-D> <ESC>:call SyncDownloadFile()<CR>
`


text:
SHELL := /bin/bash

# The name of your project (the .ino file / folder name)
TARGET = firmware

# Path to your arduino installation
ARDUINOPATH ?= ../../arduino-1.6.9

# which board to target
# arduino:avr:uno for normal UNO.
# arduino:sam:arduino_due_x for Arduino DUE
BOARD = arduino:avr:uno

# Use PORT environment variable if it exists, otherwise use this.
PORT ?= /dev/ttyUSB0

# Additional flags to pass to the build & upload.
EXTRAFLAGS = --verbose-build

# Create path to the arduino executable.
ARDUINOEXEC = $(ARDUINOPATH)/arduino

all:
	$(ARDUINOEXEC) $(EXTRAFLAGS) --board $(BOARD) --port $(PORT) --upload $(TARGET).ino

clean:
	rm -f *.o *.d $(TARGET).elf $(TARGET).hex

libs:
	$(ARDUINOEXEC) --install-library IRremote:2.0.1


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>CreateEdificios</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/github.css" type="text/css" media="screen" />

            Class
            CreateEdificios

                <

                    ActiveRecord::Migration

db/migrate/20140524012205_create_edificios.rb

Methods

C

                change

Instance Public methods

              change()

            Link

                Source:
                show

# File db/migrate/20140524012205_create_edificios.rb, line 2
def change
  create_table :edificios do |t|
    t.integer :nivel, default: 0
    t.string :type

    t.datetime :fecha_actualizacion
    t.integer :proceso_id

    t.integer :orden

    t.integer :porcentaje_produccion, default: 100

    t.references :planeta, :luna, index: true
    t.timestamps
  end
end


text:
/**
 * This file contains the drag and drop manager class.
 *
 * Provides drag and drop functionality for blocks.
 *
 * @module moodle-core-blockdraganddrop
 */

/**
 * Constructs a new Block drag and drop manager.
 *
 * @namespace M.core.blockdraganddrop
 * @class Manager
 * @constructor
 * @extends M.core.dragdrop
 */
var MANAGER = function() {
    MANAGER.superclass.constructor.apply(this, arguments);
};
MANAGER.prototype = {

    /**
     * The skip block link from above the block being dragged while a drag is in progress.
     * Required by the M.core.dragdrop from whom this class extends.
     * @private
     * @property skipnodetop
     * @type Node
     * @default null
     */
    skipnodetop : null,

    /**
     * The skip block link from below the block being dragged while a drag is in progress.
     * Required by the M.core.dragdrop from whom this class extends.
     * @private
     * @property skipnodebottom
     * @type Node
     * @default null
     */
    skipnodebottom : null,

    /**
     * An associative object of regions and the
     * @property regionobjects
     * @type {Object} Primitive object mocking an associative array.
     * @type {BLOCKREGION} [regionname]* Each item uses the region name as the key with the value being
     *      an instance of the BLOCKREGION class.
     */
    regionobjects : {},

    /**
     * Called during the initialisation process of the object.
     * @method initializer
     */
    initializer : function() {
        Y.log('Initialising drag and drop for blocks.', 'info');
        var regionnames = this.get('regions'),
            i = 0,
            region,
            regionname,
            dragdelegation;

        // Evil required by M.core.dragdrop.
        this.groups = ['block'];
        this.samenodeclass = CSS.BLOCK;
        this.parentnodeclass = CSS.BLOCKREGION;

        // Add relevant classes and ID to 'content' block region on My Home page.
        var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
        if (myhomecontent.size() > 0) {
            var contentregion = myhomecontent.item(0);
            contentregion.addClass(CSS.BLOCKREGION);
            contentregion.set('id', CSS.REGIONCONTENT);
            contentregion.one('div').addClass(CSS.REGIONCONTENT);
        }

        for (i in regionnames) {
            regionname = regionnames[i];
            region = new BLOCKREGION({
                manager : this,
                region : regionname,
                node : Y.one('#block-region-'+regionname)
            });
            this.regionobjects[regionname] = region;

            // Setting blockregion as droptarget (the case when it is empty)
            // The region-post (the right one)
            // is very narrow, so add extra padding on the left to drop block on it.
            new Y.DD.Drop({
                node: region.get_droptarget(),
                groups: this.groups,
                padding: '40 240 40 240'
            });

            // Make each div element in the list of blocks draggable
            dragdelegation = new Y.DD.Delegate({
                container: region.get_droptarget(),
                nodes: '.'+CSS.BLOCK,
                target: true,
                handles: [SELECTOR.DRAGHANDLE],
                invalid: '.block-hider-hide, .block-hider-show, .moveto, .block_fake',
                dragConfig: {groups: this.groups}
            });
            dragdelegation.dd.plug(Y.Plugin.DDProxy, {
                // Don't move the node at the end of the drag
                moveOnEnd: false
            });
            dragdelegation.dd.plug(Y.Plugin.DDWinScroll);

            // On the DD Manager start operation, we enable all block regions so that they can be drop targets. This
            // must be done *before* drag:start but after dragging has been initialised.
            Y.DD.DDM.on('ddm:start', this.enable_all_regions, this);

            region.change_block_move_icons(this);
        }
        Y.log('Initialisation of drag and drop for blocks complete.', 'info');
    },

    /**
     * Returns the ID of the block the given node represents.
     * @method get_block_id
     * @param {Node} node
     * @returns {int} The blocks ID in the database.
     */
    get_block_id : function(node) {
        return Number(node.get('id').replace(/inst/i, ''));
    },

    /**
     * Returns the block region that the node is part of or belonging to.
     * @method get_block_region
     * @param {Y.Node} node
     * @returns {string} The region name.
     */
    get_block_region : function(node) {
        if (!node.test('[data-blockregion]')) {
            node = node.ancestor('[data-blockregion]');
        }
        return node.getData('blockregion');
    },

    /**
     * Returns the BLOCKREGION instance that represents the block region the given node is part of.
     * @method get_region_object
     * @param {Y.Node} node
     * @returns {BLOCKREGION}
     */
    get_region_object : function(node) {
        return this.regionobjects[this.get_block_region(node)];
    },

    /**
     * Enables all fo the regions so that they are all visible while dragging is occuring.
     *
     * @method enable_all_regions
     * @returns {undefined}
     */
    enable_all_regions : function() {
        var groups = Y.DD.DDM.activeDrag.get('groups');

        // As we're called by Y.DD.DDM, we can't be certain that the call
        // relates specifically to a block drag/drop operation. Test
        // whether the relevant group applies here.
        if (!groups || Y.Array.indexOf(groups, 'block') === -1) {
            return;
        }

        var i;
        for (i in this.regionobjects) {
            if (!this.regionobjects.hasOwnProperty(i)) {
                continue;
            }
            this.regionobjects[i].enable();
        }
    },

    /**
     * Disables enabled regions if they contain no blocks.
     * @method disable_regions_if_required
     * @returns {undefined}
     */
    disable_regions_if_required : function() {
        var i = 0;
        for (i in this.regionobjects) {
            this.regionobjects[i].disable_if_required();
        }
    },

    /**
     * Called by M.core.dragdrop.global_drag_start when dragging starts.
     * @method drag_start
     * @param {Event} e
     * @returns {undefined}
     */
    drag_start : function(e) {
        // Get our drag object
        var drag = e.target;

        // Store the parent node of original drag node (block)
        // we will need it later for show/hide empty regions

        // Determine skipnodes and store them
        if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
            this.skipnodetop = drag.get('node').previous();
        }
        if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
            this.skipnodebottom = drag.get('node').next();
        }
    },

    /**
     * Called by M.core.dragdrop.global_drop_over when something is dragged over a drop target.
     * @method drop_over
     * @param {Event} e
     * @returns {undefined}
     */
    drop_over : function(e) {
        // Get a reference to our drag and drop nodes
        var drag = e.drag.get('node');
        var drop = e.drop.get('node');

        // We need to fix the case when parent drop over event has determined
        // 'goingup' and appended the drag node after admin-block.
        if (drop.hasClass(CSS.REGIONCONTENT) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
            drop.prepend(drag);
        }
    },

    /**
     * Called by M.core.dragdrop.global_drop_end when a drop has been completed.
     * @method drop_end
     * @returns {undefined}
     */
    drop_end : function() {
        // Clear variables.
        this.skipnodetop = null;
        this.skipnodebottom = null;
        this.disable_regions_if_required();
    },

    /**
     * Called by M.core.dragdrop.global_drag_dropmiss when something has been dropped on a node that isn't contained by a drop target.
     * @method drag_dropmiss
     * @param {Event} e
     * @returns {undefined}
     */
    drag_dropmiss : function(e) {
        // Missed the target, but we assume the user intended to drop it
        // on the last ghost node location, e.drag and e.drop should be
        // prepared by global_drag_dropmiss parent so simulate drop_hit(e).
        this.drop_hit(e);
    },

    /**
     * Called by M.core.dragdrop.global_drag_hit when something has been dropped on a drop target.
     * @method drop_hit
     * @param {Event} e
     * @returns {undefined}
     */
    drop_hit : function(e) {
        // Get a reference to our drag node
        var dragnode = e.drag.get('node');
        var dropnode = e.drop.get('node');

        // Amend existing skipnodes
        if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
            // the one that belongs to block below move below
            dragnode.insert(dragnode.previous(), 'after');
        }
        // Move original skipnodes
        if (this.skipnodetop) {
            dragnode.insert(this.skipnodetop, 'before');
        }
        if (this.skipnodebottom) {
            dragnode.insert(this.skipnodebottom, 'after');
        }

        // Add lightbox if it not there
        var lightbox = M.util.add_lightbox(Y, dragnode);

        // Prepare request parameters
        var params = {
            sesskey : M.cfg.sesskey,
            courseid : this.get('courseid'),
            pagelayout : this.get('pagelayout'),
            pagetype : this.get('pagetype'),
            subpage : this.get('subpage'),
            contextid : this.get('contextid'),
            action : 'move',
            bui_moveid : this.get_block_id(dragnode),
            bui_newregion : this.get_block_region(dropnode)
        };

        if (this.get('cmid')) {
            params.cmid = this.get('cmid');
        }

        if (dragnode.next('.'+CSS.BLOCK) && !dragnode.next('.'+CSS.BLOCK).hasClass(CSS.BLOCKADMINBLOCK)) {
            params.bui_beforeid = this.get_block_id(dragnode.next('.'+CSS.BLOCK));
        }

        // Do AJAX request
        Y.io(M.cfg.wwwroot+AJAXURL, {
            method: 'POST',
            data: params,
            on: {
                start : function() {
                    lightbox.show();
                },
                success: function(tid, response) {
                    window.setTimeout(function() {
                        lightbox.hide();
                    }, 250);
                    try {
                        var responsetext = Y.JSON.parse(response.responseText);
                        if (responsetext.error) {
                            new M.core.ajaxException(responsetext);
                        }
                    } catch (e) {}
                },
                failure: function(tid, response) {
                    this.ajax_failure(response);
                    lightbox.hide();
                },
                complete : function() {
                    this.disable_regions_if_required();
                }
            },
            context:this
        });
    }
};
Y.extend(MANAGER, M.core.dragdrop, MANAGER.prototype, {
    NAME : 'core-blocks-dragdrop-manager',
    ATTRS : {
        /**
         * The Course ID if there is one.
         * @attribute courseid
         * @type int|null
         * @default null
         */
        courseid : {
            value : null
        },

        /**
         * The Course Module ID if there is one.
         * @attribute cmid
         * @type int|null
         * @default null
         */
        cmid : {
            value : null
        },

        /**
         * The Context ID.
         * @attribute contextid
         * @type int|null
         * @default null
         */
        contextid : {
            value : null
        },

        /**
         * The current page layout.
         * @attribute pagelayout
         * @type string|null
         * @default null
         */
        pagelayout : {
            value : null
        },

        /**
         * The page type string, should be used as the id for the body tag in the theme.
         * @attribute pagetype
         * @type string|null
         * @default null
         */
        pagetype : {
            value : null
        },

        /**
         * The subpage identifier, if any.
         * @attribute subpage
         * @type string|null
         * @default null
         */
        subpage : {
            value : null
        },

        /**
         * An array of block regions that are present on the page.
         * @attribute regions
         * @type array|null
         * @default Array[]
         */
        regions : {
            value : []
        }
    }
});


text:
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;

var UserSchema = new Schema({
	user_id: { type: String, index: true},
	name: {type: String},
	login: {type: String},
	accessToken:{type: String},
	refreshToken:{type: String}
});

var User = Mongoose.model('User', UserSchema);

module.exports = {
	User : User
}


text:
litecoin
========

LiteCoin, DogeCoin client written in Go


text:
<html>
<head>
	<title>Arcadia</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">

	<style type="text/css">
	body {
		background: #ccc;
		padding: 0;
		margin: 0;
	}

	#arcadia, #arcadia canvas {
		/*-webkit-touch-callout: none;*/
		/*-webkit-user-select: none;*/
		/*-moz-user-select: none;*/
		/*-ms-user-select: none;*/
		/*user-select: none;*/
		/*outline: none;*/
		-webkit-tap-highlight-color: rgba(255, 255, 255, 0);
	}
	</style>

	<script type="text/javascript" src="../../dist/arcadia.js"></script>

	<!-- scenes -->
	<script type="text/javascript" src="scenes/game.js"></script>
	<script type="text/javascript" src="scenes/title.js"></script>

	<!-- objects -->
	<script type="text/javascript" src="objects/player.js"></script>
	<script type="text/javascript" src="objects/enemy.js"></script>
	<script type="text/javascript" src="objects/player-bullet.js"></script>
	<script type="text/javascript" src="objects/enemy-bullet.js"></script>

	<script type="text/javascript">
		/* Instantiate game object */
		window.onload = function () {
			var game = new Arcadia.Game({
				width: 320,
				height: 568,
				scene: TitleScene,
				scaleToFit: true
			});
		};
	</script>
</head>
<body>

</body>
</html>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using System.Linq;
using System.Linq.Expressions;
using Marten.Exceptions;
using Marten.Services;
using Marten.Linq;
using Marten.Schema;
using Marten.Testing.Harness;

namespace Marten.Testing.Linq
{
	public class SimpleEqualsParserTests : IntegrationContext
	{
		public class QueryTarget
		{
			public int IntProp { get; set; }
			public long LongProp { get; set; }
			public decimal DecimalProp { get; set; }
			public bool BoolProp { get; set; }
			public Guid Id { get; set; }
			public DateTime DateTimeProp { get; set; }
			public DateTimeOffset DateTimeOffsetProp { get; set; }
		}

		[Fact]
		public void CanTranslateEqualsToQueries()
		{
			var queryTarget = new QueryTarget
			{
				IntProp = 1,
				LongProp = 2,
				DecimalProp = 1.1m,
				BoolProp = true,
				Id = Guid.NewGuid(),
				DateTimeProp = DateTime.UtcNow,
				DateTimeOffsetProp = DateTimeOffset.UtcNow
			};

			theSession.Store(queryTarget);

			theSession.SaveChanges();

			var itemFromDb = theSession.Query<QueryTarget>()
				.Where(x => x.IntProp.Equals(queryTarget.IntProp))
				.Where(x => x.LongProp.Equals(queryTarget.LongProp))
				.Where(x => x.DecimalProp.Equals(queryTarget.DecimalProp))
				.Where(x => x.BoolProp.Equals(queryTarget.BoolProp))
				.Where(x => x.Id.Equals(queryTarget.Id))
				.Where(x => x.DateTimeProp.Equals(queryTarget.DateTimeProp))
				.Where(x => x.DateTimeOffsetProp.Equals(queryTarget.DateTimeOffsetProp))
				.FirstOrDefault();

			Assert.NotNull(itemFromDb);
		}

		[Fact]
		public void ThrowsWhenValueNotConvertibleToComparandType()
		{
			var queryTarget = new QueryTarget
			{
				Id = System.Guid.NewGuid()
			};
			theSession.Store(queryTarget);

			theSession.SaveChanges();

			object notInt = "not int";

			Assert.Throws<BadLinqExpressionException>(() =>
			{
				theSession.Query<QueryTarget>()
					.Where(x => x.IntProp.Equals(notInt))
					.FirstOrDefault();
			});
		}

		public class TestData : IEnumerable<object[]>
		{
			private readonly List<object[]> _data = new List<object[]>
			{
				new object[] { Guid.NewGuid() },
				new object[] { 0 },
				new object[] { null },
				new object[] { false },
				new object[] { 32m },
				new object[] { 0L },
				new object[] { DateTime.UtcNow },
				new object[] { DateTimeOffset.UtcNow },
			};

			public IEnumerator<object[]> GetEnumerator()
			{
				return _data.GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		[Theory]
		[InlineData(PropertySearching.ContainmentOperator)]
		[InlineData(PropertySearching.JSON_Locator_Only)]
		public void EqualsGeneratesSameSqlAsEqualityOperatorWhenRegardlessOfPropertySearching(PropertySearching search)
		{
			StoreOptions(options =>
			{
				options.Schema.For<QueryTarget>().PropertySearching(search);
			});

			var queryTarget = new QueryTarget
			{
				IntProp = 1,
				LongProp = 2,
				DecimalProp = 1.1m,
				BoolProp = true,
				Id = Guid.NewGuid(),
				DateTimeProp = DateTime.UtcNow
			};

			var queryEquals = theSession.Query<QueryTarget>()
				.Where(x => x.IntProp.Equals(queryTarget.IntProp))
				.Where(x => x.LongProp.Equals(queryTarget.LongProp))
				.Where(x => x.DecimalProp.Equals(queryTarget.DecimalProp))
				.Where(x => x.BoolProp.Equals(queryTarget.BoolProp))
				.Where(x => x.Id.Equals(queryTarget.Id))
				.Where(x => x.DateTimeProp.Equals(queryTarget.DateTimeProp))
				.Where(x => x.DateTimeOffsetProp.Equals(queryTarget.DateTimeOffsetProp))
				.ToCommand().CommandText;

			var queryEqualOperator = theSession.Query<QueryTarget>()
				.Where(x => x.IntProp == queryTarget.IntProp)
				.Where(x => x.LongProp == queryTarget.LongProp)
				.Where(x => x.DecimalProp == queryTarget.DecimalProp)
				.Where(x => x.BoolProp == queryTarget.BoolProp)
				.Where(x => x.Id == queryTarget.Id)
				.Where(x => x.DateTimeProp == queryTarget.DateTimeProp)
				.Where(x => x.DateTimeOffsetProp == queryTarget.DateTimeOffsetProp)
				.ToCommand().CommandText;

			Assert.Equal(queryEqualOperator, queryEquals);
		}

		[Theory]
		[ClassData(typeof(TestData))]
		public void EqualsGeneratesSameSqlAsEqualityOperator(object value)
		{
			string queryEquals = null, queryEqualOperator = null;
			switch (value)
			{
				case int intValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.IntProp.Equals(intValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.IntProp == intValue).ToCommand().CommandText;
					break;
				case Guid guidValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.Id.Equals(guidValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.Id == guidValue).ToCommand().CommandText;
					break;
				case decimal decimalValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.DecimalProp.Equals(decimalValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.DecimalProp == decimalValue).ToCommand().CommandText;
					break;
				case long longValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.LongProp.Equals(longValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.LongProp == longValue).ToCommand().CommandText;
					break;
				case DateTime dateTimeValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.DateTimeProp.Equals(dateTimeValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.DateTimeProp == dateTimeValue).ToCommand().CommandText;
					break;
				case DateTimeOffset dateTimeOffsetValue:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.DateTimeOffsetProp.Equals(dateTimeOffsetValue)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
						.Where(x => x.DateTimeOffsetProp == dateTimeOffsetValue).ToCommand().CommandText;
					break;
				// Null
				default:
					queryEquals = theSession.Query<QueryTarget>()
						.Where(x => x.BoolProp.Equals(null)).ToCommand().CommandText;
					queryEqualOperator = theSession.Query<QueryTarget>()
#pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
						.Where(x => x.BoolProp == null).ToCommand().CommandText;
#pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
					break;
			}
			Assert.Equal(queryEqualOperator, queryEquals);
		}

		[Fact]
		public void CanUseEqualsInCompiledQuery()
		{
			var queryTarget = new QueryTarget
			{
				IntProp = 1,
				LongProp = 2,
				DecimalProp = 1.1m,
				BoolProp = true,
				Id = Guid.NewGuid()
			};

			theSession.Store(queryTarget);

			theSession.SaveChanges();

			var itemFromDb =
				theSession.Query(new CompiledQueryTarget() {IdProp = queryTarget.Id, IntProp = queryTarget.IntProp});

			Assert.NotNull(itemFromDb);
		}

		public class CompiledQueryTarget : ICompiledQuery<QueryTarget, QueryTarget>
		{
			public Guid IdProp { get; set; }
			public int IntProp { get; set; }

			public Expression<Func<IMartenQueryable<QueryTarget>, QueryTarget>> QueryIs()
			{
				return q => q.FirstOrDefault(x => x.IntProp.Equals(IntProp) && x.Id.Equals(IdProp));
			}
		}

        public SimpleEqualsParserTests(DefaultStoreFixture fixture) : base(fixture)
        {
        }
    }
}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.grid.internal.utils.configuration;

import com.google.common.annotations.VisibleForTesting;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.Expose;

import org.openqa.grid.common.exception.GridConfigurationException;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StandaloneConfiguration {
  public static final String DEFAULT_STANDALONE_CONFIG_FILE = "org/openqa/grid/common/defaults/DefaultStandalone.json";

  /*
   * IMPORTANT - Keep these constant values in sync with the ones specified in
   * 'defaults/DefaultStandalone.json'  -- if for no other reasons documentation & consistency.
   */

  /**
   * Default client timeout
   */
  @VisibleForTesting
  static final Integer DEFAULT_TIMEOUT = 1800;

  /**
   * Default browser timeout
   */
  @VisibleForTesting
  static final Integer DEFAULT_BROWSER_TIMEOUT = 0;

  /**
   * Default standalone role
   */
  @VisibleForTesting
  static final String DEFAULT_ROLE = "standalone";

  /**
   * Default standalone port
   */
  @VisibleForTesting
  static final Integer DEFAULT_PORT = 4444;

  /**
   * Default state of LogeLevel.FINE log output toggle
   */
  @VisibleForTesting
  static final Boolean DEFAULT_DEBUG_TOGGLE = false;

  /*
   * config parameters which do not serialize to json
   */
  @Expose( serialize = false )
  // initially defaults to false from boolean primitive type
  private boolean avoidProxy;

  @Expose( serialize = false )
  // initially defaults to false from boolean primitive type
  private boolean browserSideLog;

  @Expose( serialize = false )
  // initially defaults to false from boolean primitive type
  private boolean captureLogsOnQuit;

  /*
   * config parameters which serialize and deserialize to/from json
   */

  /**
   * Browser timeout. Default 0 (indefinite wait).
   */
  @Expose
  public Integer browserTimeout = DEFAULT_BROWSER_TIMEOUT;

  /**
   * Enable {@code LogLevel.FINE} log messages. Default {@code false}.
   */
  @Expose
  public Boolean debug = DEFAULT_DEBUG_TOGGLE;

  /**
   *   Max threads for Jetty. Defaults to {@code null}.
   */
  @Expose
  public Integer jettyMaxThreads;

  /**
   *   Filename to use for logging. Defaults to {@code null}.
   */
  @Expose
  public String log;

  /**
   * Port to bind to. Default determined by configuration type.
   */
  @Expose
  public Integer port = DEFAULT_PORT;

  /**
   * Server role. Default determined by configuration type.
   */
  @Expose
  public String role = DEFAULT_ROLE;

  /**
   * Client timeout. Default 1800 sec.
   */
  @Expose
  public Integer timeout = DEFAULT_TIMEOUT;

  /**
   * Creates a new configuration using the default values.
   */
  public StandaloneConfiguration() {
    // nothing to do.
  }

  /**
   * @param filePath node config json file to load configuration from
   */
  public static StandaloneConfiguration loadFromJSON(String filePath) {
    return loadFromJSON(loadJSONFromResourceOrFile(filePath));
  }

  /**
   * @param json JsonObject to load configuration from
   */
  public static StandaloneConfiguration loadFromJSON(JsonObject json) {
    try {
      GsonBuilder builder = new GsonBuilder();
      StandaloneConfiguration config =
        builder.excludeFieldsWithoutExposeAnnotation().create().fromJson(json, StandaloneConfiguration.class);
      return config;
    } catch (Throwable e) {
      throw new GridConfigurationException("Error with the JSON of the config : " + e.getMessage(),
                                           e);
    }
  }

  /**
   * copy another configuration's values into this one if they are set.
   */
  public void merge(StandaloneConfiguration other) {
    if (other == null) {
      return;
    }

    if (isMergeAble(other.browserTimeout, browserTimeout)) {
      browserTimeout = other.browserTimeout;
    }
    if (isMergeAble(other.jettyMaxThreads, jettyMaxThreads)) {
      jettyMaxThreads = other.jettyMaxThreads;
    }
    if (isMergeAble(other.timeout, timeout)) {
      timeout = other.timeout;
    }
    // role, port, log, debug, version, enablePassThrough, and help are not merged, they are only consumed by the
    // immediately running process and should never affect a remote
  }

  /**
   * Determines if one object can be merged onto another object. Checks for {@code null},
   * and empty (Collections & Maps) to make decision.
   *
   * @param other the object to merge. must be the same type as the 'target'
   * @param target the object to merge on to. must be the same type as the 'other'
   * @return whether the 'other' can be merged onto the 'target'
   */
  protected boolean isMergeAble(Object other, Object target) {
    // don't merge a null value
    if (other == null) {
      return false;
    } else {
      // allow any non-null value to merge over a null target.
      if (target == null) {
        return true;
      }
    }

    // we know we have two objects with value.. Make sure the types are the same and
    // perform additional checks.

    if (! target.getClass().getSuperclass().getTypeName()
        .equals(other.getClass().getSuperclass().getTypeName())) {
      return false;
    }

    if (target instanceof Collection) {
      return !((Collection<?>) other).isEmpty();
    }

    if (target instanceof Map) {
      return !((Map<?, ?>) other).isEmpty();
    }

    return true;
  }

  public String toString(String format) {
    StringBuilder sb = new StringBuilder();
    sb.append(toString(format, "browserTimeout", browserTimeout));
    sb.append(toString(format, "debug", debug));
    sb.append(toString(format, "jettyMaxThreads", jettyMaxThreads));
    sb.append(toString(format, "log", log));
    sb.append(toString(format, "port", port));
    sb.append(toString(format, "role", role));
    sb.append(toString(format, "timeout", timeout));
    return sb.toString();
  }

  @Override
  public String toString() {
    return toString(" -%1$s %2$s");
  }

  public StringBuilder toString(String format, String name, Object value) {
    StringBuilder sb = new StringBuilder();
    List<?> iterator;
    if (value instanceof List) {
      iterator = (List<?>)value;
    } else {
      iterator = Arrays.asList(value);
    }
    for (Object v : iterator) {
      if (v != null &&
          !(v instanceof Map && ((Map<?, ?>) v).isEmpty()) &&
          !(v instanceof Collection && ((Collection<?>) v).isEmpty())) {
        sb.append(String.format(format, name, v));
      }
    }
    return sb;
  }

  /**
   * Return a JsonElement representation of the configuration. Does not serialize nulls.
   */
  public JsonElement toJson() {
    GsonBuilder builder = new GsonBuilder();
    addJsonTypeAdapter(builder);
    //Note: it's important that nulls ARE NOT serialized, for backwards compatibility
    return builder.excludeFieldsWithoutExposeAnnotation().create().toJsonTree(this);
  }

  protected void addJsonTypeAdapter(GsonBuilder builder) {
    // no default implementation
  }

  /**
   * load a JSON file from the resource or file system.
   *
   * @param resource file or jar resource location
   * @return A JsonObject representing the passed resource argument.
   */
  protected static JsonObject loadJSONFromResourceOrFile(String resource) {
    try {
      return new JsonParser().parse(readFileOrResource(resource)).getAsJsonObject();
    } catch (JsonSyntaxException e) {
      throw new GridConfigurationException("Wrong format for the JSON input : " + e.getMessage(), e);
    }
  }

  private static String readFileOrResource(String resource) {
    Stream<Function<String, InputStream>> suppliers = Stream.of(
        (path) -> {
          try {
            return new FileInputStream(path);
          } catch (FileNotFoundException e) {
            return null;
          } },
        (path) -> Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("org/openqa/grid/common/" + path),
        (path) -> Thread.currentThread().getContextClassLoader().getResourceAsStream(path)
    );

    InputStream in = suppliers
        .map(supplier -> supplier.apply(resource))
        .filter(Objects::nonNull)
        .findFirst()
        .orElseThrow(() -> new RuntimeException(resource + " is not a valid resource."));

    try(BufferedReader buffreader = new BufferedReader(new InputStreamReader(in))) {
      return buffreader.lines().collect(Collectors.joining("\n"));
    } catch (IOException e) {
      throw new GridConfigurationException("Cannot read file or resource " + resource + ", " + e.getMessage(), e);
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}


text:
package com.eventprogramming.server.requests;

import org.json.simple.JSONObject;

import com.eventprogramming.constants.Constants;

public class CreateEventRequestHandler extends AbstractRequestHandler {

	@Override
	public String handleRequest(JSONObject payload) {
		try {
			String eventName = (String) payload.get(Constants.EVENT_NAME_KEYWORD);
			int isGreedy = ((Long) payload.get(Constants.GREEDY_KEYWORD)).intValue();
			String startDate = (String) payload.get(Constants.MIN_START_DATE_KEYWORD);
			String endDate = (String) payload.get(Constants.MAX_END_DATE_KEYWORD);
			int startHour = ((Long) payload.get(Constants.START_HOUR_KEYWORD)).intValue();
			int endHour = ((Long) payload.get(Constants.END_HOUR_KEYWORD)).intValue();
			int duration = ((Long) payload.get(Constants.DURATION_KEYWORD)).intValue();
			String username = (String) payload.get(Constants.USER_KEYWORD);
			String eventCode = String.valueOf(Math.abs(payload.toJSONString().hashCode()));

			return fSQLAccess.insertEvent(eventName, isGreedy, startDate, endDate, startHour, endHour, duration, username, eventCode);
		} catch (ClassCastException e) {
			e.printStackTrace();
		}

		return "ERROR";
	}

}


text:
"""Symbolic quantum and photonic circuit (SLH) algebra"""
import importlib

__all__ = ['init_algebra']

def init_algebra(*, default_hs_cls='LocalSpace'):
    """Initialize the algebra system

    Args:
        default_hs_cls (str): The name of the :class:`.LocalSpace` subclass
            that should be used when implicitly creating Hilbert spaces, e.g.
            in :class:`.OperatorSymbol`

    """
    from qnet.algebra.core.hilbert_space_algebra import LocalSpace
    from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
    default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls)
    if issubclass(default_hs_cls, LocalSpace):
        QuantumExpression._default_hs_cls = default_hs_cls
    else:
        raise TypeError("default_hs_cls must be a subclass of LocalSpace")
    # TODO: init_algebra should eventually control which rules QNET uses.


text:
[![Build Status](https://secure.travis-ci.org/peterbraden/node-opencv.png)](http://travis-ci.org/peterbraden/node-opencv)

[OpenCV](http://opencv.org) bindings for Node.js. OpenCV is
the defacto computer vision library - by interfacing with it natively in node,
we get powerful real time vision in js.

People are using node-opencv to fly control quadrocoptors, detect faces from
webcam images and annotate video streams. If you're using it for something
cool, I'd love to hear about it!

## Install

You'll need OpenCV 2.3.1 or newer installed before installing node-opencv.

Then:

```bash
$ npm install opencv
```

## Examples
Run the examples from the parent directory.

### Face Detection

```javascript
cv.readImage("./examples/files/mona.png", function(err, im){
  im.detectObject(cv.FACE_CASCADE, {}, function(err, faces){
    for (var i=0;i<faces.length; i++){
      var x = faces[i]
      im.ellipse(x.x + x.width/2, x.y + x.height/2, x.width/2, x.height/2);
    }
    im.save('./out.jpg');
  });
})
```

## API Documentation

### Matrix

The [matrix](http://opencv.jp/opencv-2svn_org/cpp/core_basic_structures.html#mat) is the most useful
base datastructure in OpenCV. Things like images are just matrices of pixels.

#### Creation

```javascript
new Matrix(rows, cols)
```

Or if you're thinking of a Matrix as an image:

```javascript
new Matrix(height, width)
```

Or you can use opencv to read in image files. Supported formats are in the OpenCV docs, but jpgs etc are supported.

```javascript
cv.readImage(filename, function(err, mat){
  ...
})

cv.readImage(buffer, function(err, mat){
  ...
})
```

If you need to pipe data into an image, you can use an ImageDataStream:

```javascript
var s = new cv.ImageDataStream()

s.on('load', function(matrix){
  ...
})

fs.createReadStream('./examples/files/mona.png').pipe(s);
```

If however, you have a series of images, and you wish to stream them into a
stream of Matrices, you can use an ImageStream. Thus:

```javascript
var s = new cv.ImageStream()

s.on('data', function(matrix){
   ...
})

ardrone.createPngStream().pipe(s);
```

Note: Each 'data' event into the ImageStream should be a complete image buffer.

#### Accessing Data

```javascript
var mat = new cv.Matrix.Eye(4,4); // Create identity matrix

mat.get(0,0) // 1

mat.row(0)  // [1,0,0,0]
mat.col(4)  // [0,0,0,1]
```

##### Save

```javascript
mat.save('./pic.jpg')
```

or:

```javascript
var buff = mat.toBuffer()
```

#### Image Processing

```javascript
im.convertGrayscale()
im.canny(5, 300)
im.houghLinesP()
```

#### Simple Drawing

```javascript
im.ellipse(x, y)
im.line([x1,y1], [x2, y2])
```

#### Object Detection

There is a shortcut method for
[Viola-Jones Haar Cascade](http://www.cognotics.com/opencv/servo_2007_series/part_2/sidebar.html) object
detection. This can be used for face detection etc.

```javascript
mat.detectObject(haar_cascade_xml, opts, function(err, matches){})
```

For convenience in face detection, cv.FACE_CASCADE is a cascade that can be used for frontal face detection.

Also:

```javascript
mat.goodFeaturesToTrack
```

#### Contours

```javascript
mat.findCountours
mat.drawContour
mat.drawAllContours
```

### Using Contours

`findContours` returns a `Contours` collection object, not a native array. This object provides
functions for accessing, computing with, and altering the contours contained in it.
See [relevant source code](src/Contours.cc) and [examples](examples/)

```javascript
var contours = im.findContours;

// Count of contours in the Contours object
contours.size();

// Count of corners(verticies) of contour `index`
contours.cornerCount(index);

// Access vertex data of contours
for(var c = 0; c < contours.size(); ++c) {
  console.log("Contour " + c);
  for(var i = 0; i < contours.cornerCount(c); ++i) {
    var point = contours.point(c, i);
    console.log("(" + point.x + "," + point.y + ")");
  }
}

// Computations of contour `index`
contours.area(index);
contours.arcLength(index, isClosed);
contours.boundingRect(index);
contours.minAreaRect(index);
contours.isConvex(index);
contours.fitEllipse(index);

// Destructively alter contour `index`
contours.approxPolyDP(index, epsilon, isClosed);
contours.convexHull(index, clockwise);
```

## MIT License
The library is distributed under the MIT License - if for some reason that
doesn't work for you please get in touch.


text:
/*
 * Sparta Software Co.
 * 2021
 */
package org.sparta.springwebutils.jdbc;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.util.ReflectionTestUtils;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Unit tests for class.
 *
 * @author Daniel Conde Diehl - Sparta Technology
 * <p>
 * History:
 * - Jan 18, 2017 - Daniel Conde Diehl
 * - Feb 02, 2017 - Daniel Conde Diehl - Adding tests for multiple rows issue.EmptyResultDataAccessException
 * - Oct 13, 2021 - Daniel Conde Diehl - Removing Jmockit as it is not compliant with latest JDKs
 */
@ExtendWith(MockitoExtension.class)
public class SpartaJdbcTemplateTest {

    private static final RowMapper<String> DEFAULT_ROW_MAPPER  = (rs, rowNum) -> rs.getString(1);

    private static final DataSource dataSource;
    private static final SpartaJdbcTemplate tested;
    static {
        final HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:h2:mem:");
        config.setUsername("sa");
        config.setPassword("");
        dataSource = new HikariDataSource(config);
        tested = new SpartaJdbcTemplate(dataSource);

        //Init database
        tested.execute("create table test ( id int, val varchar(2000))");
        tested.execute("insert into test values (1, 'test')");
        tested.execute("insert into test values (2, 'test 2')");
        tested.execute("insert into test values (3, null)");
    }

    @Test
    public void testInitWithJdbcDataSource() {
        final SpartaJdbcTemplate t1 = new SpartaJdbcTemplate(dataSource);
        final DataSource actual = (DataSource) ReflectionTestUtils.getField(t1, "dataSource");
        assertEquals(dataSource, actual);
    }

    @Test
    public void testInitWithJdbcDataSourceAndLazy() {
        final SpartaJdbcTemplate t1 = new SpartaJdbcTemplate(dataSource, true);
        final DataSource actual = (DataSource) ReflectionTestUtils.getField(t1, "dataSource");
        assertEquals(dataSource, actual);
        final Boolean lazy = (Boolean) ReflectionTestUtils.getField(t1, "lazyInit");
        assertEquals(Boolean.TRUE, lazy);
    }

    @Test
    public void testInitNoParameters() {
        new SpartaJdbcTemplate();
    }

    /* ***** BEGIN: TEST FOR SQL, CLASS *********** */
    @Test
    public void testQueryForOptionalObjectNull() {
        final String sql = "select val from test where id = 3";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalObjectWithValue() {
        final String sql = "select val from test where id = 1";
        final String expected = "test";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalObjectEmptyResultSet() {
        final String sql = "select val from test where id = -1";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalMultipleRows() {
        final String sql = "select val from test";

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, String.class));
    }
    /* ***** END: TEST FOR SQL, CLASS ******* */

    /* ***** BEGIN: TEST FOR SQL, CLASS, Args ******* */
    @Test
    public void testQueryForOptionalObjectArgsNull() {
        final String sql = "select val from test where id = ?";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class, 3);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalObjectArgsWithValue() {
        final String sql = "select val from test where id = ? or id = ?";
        final String expected = "test";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class, 1, -1);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalObjectArgsEmptyResultSet() {
        final String sql = "select val from test where id = ?";

        final Optional<String> actual = tested.queryForOptionalObject(sql, String.class, -1);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalArgsMultipleRows() {
        final String sql = "select val from test where id between ? and ? ";

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, String.class, 1, 10));
    }
    /* ***** END: TEST FOR SQL, CLASS, Args ******* */

    /* ***** BEGIN: TEST FOR SQL, Args, CLASS ******* */
    @Test
    public void testQueryForOptionalObjectArgsArrayNull() {
        final String sql = "select val from test where id = ?";

        final Optional<String> actual = tested.queryForOptionalObject(sql, new Object[]{3}, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalObjectArgsArrayWithValue() {
        final String sql = "select val from test where id = ? or id = ?";
        final String expected = "test";

        final Optional<String> actual = tested.queryForOptionalObject(sql, new Object[]{-1, 1}, String.class);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalObjectArgsArrayEmptyResultSet() {
        final String sql = "select val from test where id = ?";

        final Optional<String> actual = tested.queryForOptionalObject(sql, new Object[]{-1}, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalArgsArrayMultipleRows() {
        final String sql = "select val from test where id between ? and ? ";

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, new Object[]{1, 10}, String.class));
    }
    /* ***** END: TEST FOR SQL, Args, CLASS ******* */

    /* ***** BEGIN: TEST FOR SQL, Args, Types, CLASS ******* */
    @Test
    public void testQueryForOptionalObjectArgsArrayTypesNull() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{3};
        final int[] types = new int[]{Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalObjectArgsArrayTypesWithValue() {
        final String sql = "select val from test where id = ? or id = ?";
        final String expected = "test";
        final Object[] params = new Object[]{-1, 1};
        final int[] types = new int[]{Types.INTEGER, Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, String.class);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalObjectArgsArrayTypesEmptyResultSet() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};
        final int[] types = new int[]{Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, String.class);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalArgsArrayTypesMultipleRows() {
        final String sql = "select val from test where id between ? and ? ";
        final Object[] params = new Object[]{1, 10};
        final int[] types = new int[]{Types.INTEGER, Types.INTEGER};

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, params, types, String.class));
    }
    /* ***** END: TEST FOR SQL, Args, Types, CLASS ******* */

	/* ***** BEGIN: sql, rowMapper ***** */
    @Test
    public void testQueryForOptionalObject2Null() {
        final String sql = "select val from test where id = 3";

        final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER);
        assertFalse(actual.isPresent());
    }

	@Test
	public void testQueryForOptional2ObjectWithValue() {
		final String sql = "select val from test where id = 1";
		final String expected = "test";

		final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER);
		assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
	}

	@Test
	public void testQueryForOptional2ObjectEmptyResultSet() {
		final String sql = "select val from test where id = -1";

		final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER);
		assertFalse(actual.isPresent());
	}

	@Test
	public void testQueryForOptional2ObjectMultipleRows() {
		final String sql = "select val from test";

		assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER));
	}
	/* ***** END: sql, rowMapper ***** */

    /* ***** BEGIN: sql, params, types, rowMapper ***** */
    @Test
    public void testQueryForOptionalObjectRowMapperParamsTypesNull() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};
        final int[] types = new int[]{Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, DEFAULT_ROW_MAPPER);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsTypesObjectWithValue() {
        final String sql = "select val from test where id = ?";
        final String expected = "test";
        final Object[] params = new Object[]{1};
        final int[] types = new int[]{Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, DEFAULT_ROW_MAPPER);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalRowMapperParamsTypesObjectEmptyResultSet() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};
        final int[] types = new int[]{Types.INTEGER};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, types, DEFAULT_ROW_MAPPER);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsTypesObjectMultipleRows() {
        final String sql = "select val from test where id between ? and ?";
        final Object[] params = new Object[]{1, 10};
        final int[] types = new int[]{Types.INTEGER, Types.INTEGER};

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, params, types, DEFAULT_ROW_MAPPER));
    }
    /* ***** END: sql, params, types, rowMapper ***** */

    /* ***** BEGIN: sql, params, rowMapper ***** */
    @Test
    public void testQueryForOptionalObjectRowMapperParamsNull() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, DEFAULT_ROW_MAPPER);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsObjectWithValue() {
        final String sql = "select val from test where id = ?";
        final String expected = "test";
        final Object[] params = new Object[]{1};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, DEFAULT_ROW_MAPPER);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalRowMapperParamsObjectEmptyResultSet() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};

        final Optional<String> actual = tested.queryForOptionalObject(sql, params, DEFAULT_ROW_MAPPER);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsObjectMultipleRows() {
        final String sql = "select val from test where id between ? and ?";
        final Object[] params = new Object[]{1, 10};

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, params, DEFAULT_ROW_MAPPER));
    }
    /* ***** END: sql, rowMapper, params ***** */

    /* ***** BEGIN: sql, params, rowMapper ***** */
    @Test
    public void testQueryForOptionalObjectRowMapperParamsLastNull() {
        final String sql = "select val from test where id = ?";
        final Object[] params = new Object[]{-1};

        final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER, params);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsLastObjectWithValue() {
        final String sql = "select val from test where id = ?";
        final String expected = "test";

        final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER, 1);
        assertEquals(expected, actual.orElseThrow(() -> new AssertionError("Expected value but came empty")));
    }

    @Test
    public void testQueryForOptionalRowMapperParamsLastObjectEmptyResultSet() {
        final String sql = "select val from test where id = ?";

        final Optional<String> actual = tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER, -1);
        assertFalse(actual.isPresent());
    }

    @Test
    public void testQueryForOptionalRowMapperParamsLastObjectMultipleRows() {
        final String sql = "select val from test where id between ? and ?";

        assertThrows(IncorrectResultSizeDataAccessException.class, () -> tested.queryForOptionalObject(sql, DEFAULT_ROW_MAPPER, 1, 10));
    }
    /* ***** END: sql, rowMapper, params ***** */
}


text:
@interface NSString (MP)
-(NSURL *)mp_URL;
@end


text:
package org.onosproject.bgp.cli;

import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.bgp.controller.BgpCfg;
import org.onosproject.bgp.controller.BgpConnectPeer;
import org.onosproject.bgp.controller.BgpController;
import org.onosproject.bgp.controller.BgpPeerCfg;
import org.onosproject.cli.AbstractShellCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;
import java.util.TreeMap;

@Command(scope = "onos", name = "bgp", description = "lists configuration")
public class BgpConfiguration extends AbstractShellCommand {
    private static final Logger log = LoggerFactory.getLogger(BgpConfiguration.class);
    private static final String CONFIGURATION = "configuration";
    private static final String PEER = "peer";
    protected BgpController bgpController;
    protected BgpConnectPeer bgpConnectPeer;
    protected BgpPeerCfg bgpPeerCfg;
    protected BgpCfg bgpCfg;
    @Argument(index = 0, name = "name",
            description = "configuration" + "\n" + "peer",
            required = true, multiValued = false)
    String name = null;
    @Argument(index = 1, name = "peer",
            description = "peerIp",
            required = false, multiValued = false)
    String peer = null;

    @Override
    protected void execute() {
        switch (name) {
            case CONFIGURATION:
                displayBgpConfiguration();
                break;
            case PEER:
                displayBgpPeerConfiguration();
                break;
            default:
                System.out.print("Unknown command...!!");
                break;
        }
    }

    private void displayBgpConfiguration() {
        try {

            this.bgpController = get(BgpController.class);
            bgpCfg = bgpController.getConfig();
            print("RouterID = %s, ASNumber = %s, MaxSession = %s, HoldingTime = %s, LsCapabality = %s," +
                            " LargeAsCapabality = %s, FlowSpecCapabality = %s", bgpCfg.getRouterId(),
                    bgpCfg.getAsNumber(), bgpCfg.getMaxSession(), bgpCfg.getHoldTime(),
                    bgpCfg.getLsCapability(), bgpCfg.getLargeASCapability(), bgpCfg.flowSpecCapability());

        } catch (Exception e) {
            log.debug("Error occurred while displaying BGP configuration: {}", e.getMessage());
        }
    }

    private void displayBgpPeerConfiguration() {
        try {
            this.bgpController = get(BgpController.class);
            BgpCfg bgpCfg = bgpController.getConfig();
            if (bgpCfg == null) {
                return;
            }
            TreeMap<String, BgpPeerCfg> displayPeerTree = bgpCfg.getPeerTree();
            Set<String> peerKey = displayPeerTree.keySet();
            if (peer != null) {
                if (peerKey.size() > 0) {
                    for (String peerIdKey : peerKey) {
                        bgpPeerCfg = displayPeerTree.get(peerIdKey);
                        bgpConnectPeer = bgpPeerCfg.connectPeer();
                        if (peerIdKey.equals(peer)) {
                            print("PeerRouterID = %s, PeerHoldingTime = %s, ASNumber = %s, PeerState = %s," +
                                            " PeerPort = %s, ConnectRetryCounter = %s",
                                    peer, bgpPeerCfg.getHoldtime(), bgpPeerCfg.getAsNumber(),
                                    bgpPeerCfg.getState(), bgpConnectPeer.getPeerPort(),
                                    bgpConnectPeer.getConnectRetryCounter());
                        }
                    }
                }
            } else {
                if (peerKey.size() > 0) {
                    for (String peerIdKey : peerKey) {
                        bgpPeerCfg = displayPeerTree.get(peerIdKey);
                        bgpConnectPeer = bgpPeerCfg.connectPeer();
                        print("PeerRouterID = %s, PeerHoldingTime = %s, ASNumber = %s, PeerState = %s, PeerPort = %s," +
                                        " ConnectRetryCounter = %s",
                                bgpPeerCfg.getPeerRouterId(), bgpPeerCfg.getHoldtime(), bgpPeerCfg.getAsNumber(),
                                bgpPeerCfg.getState(), bgpConnectPeer.getPeerPort(),
                                bgpConnectPeer.getConnectRetryCounter());
                    }
                }

            }
        } catch (Exception e) {
            log.debug("Error occurred while displaying BGP peer configuration: {}", e.getMessage());
        }
    }

}


text:
package com.intellij.openapi.vcs.changes.ui;

public class ChangeListRemoteState {
  // true -> ok
  private final boolean[] myChangeStates;

  public ChangeListRemoteState(final int size) {
    myChangeStates = new boolean[size];
    for (int i = 0; i < myChangeStates.length; i++) {
      myChangeStates[i] = true;
    }
  }

  public void report(final int idx, final boolean state) {
    myChangeStates[idx] = state;
  }

  public boolean getState() {
    boolean result = true;
    for (boolean state : myChangeStates) {
      result &= state;
    }
    return result;
  }

  public static class Reporter {
    private final int myIdx;
    private final ChangeListRemoteState myState;

    public Reporter(int idx, ChangeListRemoteState state) {
      myIdx = idx;
      myState = state;
    }

    public void report(final boolean state) {
      myState.report(myIdx, state);
    }
  }
}