text:
namespace DbTransmogrifier.Dialects
{
    public interface ISqlDialect
    {
        string ExtractDatabaseName(string connectionString);
        void ClearAllPools();

        string DropAllConnections { get; }

        string CurrentVersion { get; }

        string DatabaseExists { get; }
        string CreateDatabase { get; }
        string DropDatabase { get; }

        string SchemaVersionTableExists { get; }
        string CreateSchemaVersionTable { get; }
        string DropSchemaVersionTable { get; }

        string InsertSchemaVersion { get; }
        string DeleteSchemaVersion { get; }

        string TearDown { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var tap = require("tap");
var test = tap.test;
var ArrayType;
var ArrayT;

test('load', function(t){
  console.log('#\n** Array');
  t.ok(ArrayType = require('../lib/array'), 'ArrayType loaded');
  t.ok(require('../'), 'reified loaded');
  t.end();
});

test('constructor properties', function(t){
	ArrayT = new ArrayType('Int8', 10);
  t.equal(typeof ArrayT, 'function', 'ctor is function');
  t.equal(ArrayT.name, 'Int8x10', 'named correctly');
  t.equal(ArrayT.bytes, 10, 'correct bytes');
  t.equal(ArrayT.__proto__, ArrayType.prototype, 'ctor inherits from ArrayType.prototype');
  t.equal(ArrayT.prototype.DataType, 'array', 'prototype is correct DataType');
  t.equal(ArrayT.count, 10, 'array is correct length');
  t.end();
});

test('instance creation', function(t){
	var Int8x10 = new ArrayT;
  t.equal(Int8x10.bytes, 10, 'correct bytes');
  t.equal(Int8x10.length, 10, 'correct length');
  t.similar(Object.keys(Int8x10), [], 'indices not initialized');
  Int8x10[5];
  t.similar(Object.keys(Int8x10), ['5'], 'accessing one index initializes only it');
  t.similar(Int8x10.reify(),[0,0,0,0,0,0,0,0,0,0], 'reifies to zero intialized values');
  t.similar(Object.keys(Int8x10), [0,1,2,3,4,5,6,7,8,9], 'all indices initialized after reify');
  Int8x10.fill(1)
  t.similar(Int8x10.reify(), [1,1,1,1,1,1,1,1,1,1], 'fill with single number');
  Int8x10.write([10,20,30,40,50])
  t.similar(Int8x10.reify(), [10,20,30,40,50,1,1,1,1,1], 'writing array with smaller size only writes given values');
  Int8x10._data[3] = 100;
  t.similar(Int8x10.reify(), [10,20,30,100,50,1,1,1,1,1], 'reflects buffer changes');
  var clone = Int8x10.clone();
  clone[1] = 14;
  t.similar(clone.reify(), Int8x10.reify(), 'clone points to same data');
  var copy = Int8x10.copy();
  t.similar(copy.reify(), Int8x10.reify(), 'copy starts out matching');
  copy[0] = 5;
  t.notSimilar(copy.reify(), Int8x10.reify(), 'and does not use same data');
  t.end();
});


text:
package org.broadinstitute.dsde.firecloud.service

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import org.broadinstitute.dsde.firecloud.dataaccess.AgoraDAO
import org.broadinstitute.dsde.firecloud.model.OrchMethodRepository.{AgoraPermission, FireCloudPermission}
import org.broadinstitute.dsde.firecloud.model.ModelJsonProtocol.impFireCloudPermission
import org.broadinstitute.dsde.firecloud.model.{RequestCompleteWithErrorReport, UserInfo}
import org.broadinstitute.dsde.firecloud.service.PerRequest.{PerRequestMessage, RequestComplete}
import org.broadinstitute.dsde.firecloud.{Application, FireCloudExceptionWithErrorReport}
import spray.json.DefaultJsonProtocol._

import scala.concurrent.{ExecutionContext, Future}

object NamespaceService {
  def constructor(app: Application)(userInfo: UserInfo)(implicit executionContext: ExecutionContext) =
    new NamespaceService(userInfo, app.agoraDAO)
}

class NamespaceService (protected val argUserInfo: UserInfo, val agoraDAO: AgoraDAO)(implicit protected val executionContext: ExecutionContext)
  extends SprayJsonSupport {

  implicit val userInfo = argUserInfo

  def getFireCloudPermissions(ns: String, entity: String): Future[PerRequestMessage] = {
    val agoraPermissions = agoraDAO.getNamespacePermissions(ns, entity)
    delegatePermissionsResponse(agoraPermissions)
  }

  def postFireCloudPermissions(ns: String, entity: String, permissions: List[FireCloudPermission]): Future[PerRequestMessage] = {
    val agoraPermissionsToPost = permissions map { permission => AgoraPermissionService.toAgoraPermission(permission) }
    val agoraPermissionsPosted = agoraDAO.postNamespacePermissions(ns, entity, agoraPermissionsToPost)
    delegatePermissionsResponse(agoraPermissionsPosted)
  }

  private def delegatePermissionsResponse(agoraPerms: Future[List[AgoraPermission]]): Future[PerRequestMessage] = {
    agoraPerms map {
      perms =>
        RequestComplete(OK, perms map AgoraPermissionService.toFireCloudPermission)
    } recover {
      case e: FireCloudExceptionWithErrorReport =>
//        RequestComplete(e.errorReport.statusCode.getOrElse(InternalServerError), e.errorReport)
        RequestComplete(e.errorReport.statusCode.getOrElse(InternalServerError))
      case e: Throwable =>
        RequestCompleteWithErrorReport(InternalServerError, e.getMessage)
    }
  }

}


text:
using Newtonsoft.Json;

namespace ifunction.KeenSDK.Core.AddOns
{
    /// <summary>
    /// Class UserAgentParser.
    /// </summary>
    public class UserAgentParser : EventAddOn
    {
        const string inputParameterName = "ua_string";

        /// <summary>
        /// Gets or sets the name of the input property.
        /// </summary>
        /// <value>The name of the input property.</value>
        [JsonIgnore]
        public string InputPropertyName
        {
            get
            {
                return this.InputParameters[inputParameterName];
            }
            set
            {
                this.InputParameters[inputParameterName] = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UserAgentParser" /> class.
        /// </summary>
        /// <param name="inputPropertyName">Name of the input property.</param>
        /// <param name="outputPropertyName">Name of the output property.</param>
        public UserAgentParser(string inputPropertyName = null, string outputPropertyName = null)
            : base("keen:ua_parser")
        {
            this.OutputPropertyName = outputPropertyName;
            this.InputParameters.Add(inputParameterName, inputPropertyName.ToSafeString());
        }
    }
}


text:
Are there any images that look unusual? List the file name of any unusual images for this night here, with description:

+ Several images in the "dark" section has few really bright spots.
+ Images in the "dark" section seem to have wavy string patterns.
+ `ey-uma-008R.fit` -- a small dash of light had appeared
+ `tres-3-002R.fit` -- looks like a satellite or plane had passed by

## Missing information?

Check these off if they are true:

- [x] No images are missing filter information (except BIAS and DARK, which need no filter).
- [x] No images are missing pointing information (RA/Dec and WCS)
- [x] No images are missing object names (only applies to science images)

## What, if anything, did you have to do to fix images on this night?

Nothing


text:
<div <?php echo $setting->getAttributesList(); ?>>
  <?php include NOPE_LIB_VIEWS_PATH . 'setting/box.php'; ?>
</div>


text:
using System.Xml.Linq;
using Skybrud.Essentials.Xml.Extensions;

namespace Skybrud.Social.Flickr.Models.Places {

    /// <summary>
    /// Class representing the response body as returned by the <c>flickr.places.getInfo</c> API method.
    /// </summary>
    /// <see>
    ///     <cref>https://www.flickr.com/services/api/flickr.places.getInfo.html</cref>
    /// </see>
    public class FlickrPlacesGetInfoResponseBody : FlickrResponseBody {

        #region Properties

        /// <summary>
        /// Gets a reference to an instance of <see cref="FlickrPlace"/> with information about the place.
        /// </summary>
        public FlickrPlace Place { get; }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance from the specified <paramref name="xml"/>.
        /// </summary>
        /// <param name="xml">The instance of <see cref="XElement"/> representing the object.</param>
        protected FlickrPlacesGetInfoResponseBody(XElement xml) : base(xml) {
            Place = xml.GetElement("place", FlickrPlace.Parse);
        }

        #endregion

        #region Static methods

        /// <summary>
        /// Gets an instance of <see cref="FlickrPlacesGetInfoResponseBody"/> from the specified <paramref name="xml"/>.
        /// </summary>
        /// <param name="xml">The instance of <see cref="XElement"/> to parse.</param>
        /// <returns>An instance of <see cref="FlickrPlacesGetInfoResponseBody"/>.</returns>
        public static FlickrPlacesGetInfoResponseBody Parse(XElement xml) {
            return xml == null ? null : new FlickrPlacesGetInfoResponseBody(xml);
        }

        #endregion

    }

}


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import qualified Network.Wai.Handler.Warp as Warp
import qualified Control.Concurrent as Con
import qualified Data.Map as M
import qualified Data.Configurator as DC
import qualified Data.Maybe as DMay
import qualified System.Environment as Env
import qualified Data.Char as C
import qualified Data.UUID.V4 as DU
import qualified Network.Wai.Middleware.Gzip as Gzip

import qualified Sanskell.Api as A
import qualified Sanskell.Types as ST
import qualified Sanskell.Server as SS

start :: ST.Config -> IO ()
start serverConfig = do
  uuid        <- DU.nextRandom
  nextJobId   <- Con.newMVar $ ST.JobId uuid
  jobResult   <- Con.newMVar M.empty
  pendingJobs <- Con.newMVar []
  jobChan     <- Con.newChan

  let server = ST.Server nextJobId jobResult pendingJobs jobChan serverConfig
  SS.startServer server

  let application = Gzip.gzip (Gzip.def { Gzip.gzipFiles = Gzip.GzipCompress}) $ A.app server
  Warp.run (ST.port serverConfig) application

main :: IO ()
main = do
  envFromEnv  <- Env.lookupEnv "AppEnv"

  let env = DMay.fromMaybe "dev" envFromEnv
      configFileName = "config/" ++ (map C.toLower env) ++ "/app.cfg"

  config     <- DC.load [ DC.Required configFileName ]
  appPortStr <- DC.lookup config "app.port"
  appRootUrl <- DC.lookup config "app.root-url"

  let appPort = DMay.fromMaybe 8034 (read <$> appPortStr)
      rootUrl = DMay.fromMaybe ("http://localhost:" ++ show appPort) appRootUrl
      serverConfig = ST.Config appPort (ST.URL rootUrl)

  putStrLn $ "Running server on " ++ (show rootUrl)

  start serverConfig


text:
package org.visallo.web;

import org.visallo.webster.Handler;
import org.visallo.webster.HandlerChain;
import org.visallo.webster.RequestResponseHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Sends the error code specified in the constructor for every request. This class is
 * meant to be used as an exception handler.
 */
public class ErrorCodeHandler implements RequestResponseHandler {
    private final int errorCode;

    public ErrorCodeHandler(int errorCode) {
        this.errorCode = errorCode;
    }

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HandlerChain handlerChain) throws Exception {
        httpServletResponse.sendError(this.errorCode);
    }
}


text:
namespace Bond
{

void ValidationPass::Analyze(TranslationUnit *translationUnitList)
{
	auto hasDefaultLabelElement = mHasDefaultLabel.Push(false);
	auto endsWithJumpElement = mEndsWithJump.Push(false);
	auto hasReturnElement = mHasReturn.Push(false);
	auto isInLoopElement = mIsInLoop.Push(false);
	auto isInSwitchElement = mIsInSwitch.Push(false);
	auto nextJumpTargetIdElement = mNextJumpTargetId.Push(0);
	auto switchJumpTargetIdElement = mSwitchJumpTargetId.Push(0);
	auto returnTypeElement = mReturnType.Push(nullptr);
	auto functionElement = mFunction.Push(nullptr);
	auto switchLabelListElement = mSwitchLabelList.Push(nullptr);
	SemanticAnalysisPass::Analyze(translationUnitList);
}

void ValidationPass::Visit(FunctionDefinition *functionDefinition)
{
	const TypeDescriptor *returnType = functionDefinition->GetPrototype()->GetReturnType();
	auto endsWithJumpElement = mEndsWithJump.Push(false);
	auto hasReturnElement = mHasReturn.Push(false);
	auto nextJumpTargetIdElement = mNextJumpTargetId.Push(0);
	auto switchJumpTargetIdElement = mSwitchJumpTargetId.Push(0);
	auto returnTypeElement = mReturnType.Push(returnType);
	auto functionElement = mFunction.Push(functionDefinition);
	SemanticAnalysisPass::Visit(functionDefinition);

	functionDefinition->SetNumReservedJumpTargetIds(nextJumpTargetIdElement);

	if (!returnType->IsVoidType() && !hasReturnElement && !functionDefinition->IsNative())
	{
		mErrorBuffer.PushError(CompilerError::NOT_ALL_PATHS_RETURN_A_VALUE, functionDefinition->GetName());
	}
}

void ValidationPass::Visit(FunctionPrototype *functionPrototype)
{
	const TypeDescriptor *typeDescriptor = functionPrototype->GetReturnType();
	if (!typeDescriptor->IsInstantiable())
	{
		mErrorBuffer.PushError(CompilerError::RETURN_OF_UNDEFINED_SIZE, functionPrototype->GetName(), typeDescriptor);
	}
	ParseNodeTraverser::Visit(functionPrototype);
}

void ValidationPass::Visit(Parameter *parameter)
{
	const TypeDescriptor *typeDescriptor = parameter->GetTypeDescriptor();
	if (!typeDescriptor->IsInstantiable())
	{
		mErrorBuffer.PushError(CompilerError::DECLARATION_OF_UNDEFINED_SIZE, parameter->GetName(), typeDescriptor);
	}
}

void ValidationPass::Visit(NamedInitializer *namedInitializer)
{
	TypeAndValue &tav = *namedInitializer->GetTypeAndValue();
	if ((namedInitializer->GetScope() == SCOPE_LOCAL) && tav.IsValueDefined() &&
	    tav.GetTypeDescriptor().IsPrimitiveType())
	{
		namedInitializer->SetElidable(true);
	}

	Initializer *initializer = namedInitializer->GetInitializer();

	if (initializer != nullptr)
	{
		const TypeDescriptor &typeDescriptor = tav.GetTypeDescriptor();
		ValidateInitializer(initializer, typeDescriptor);
	}

	ParseNodeTraverser::Visit(namedInitializer);
}

void ValidationPass::Visit(IfStatement *ifStatement)
{
	AssertReachableCode(ifStatement);
	mEndsWithJump.SetTop(false);
	Traverse(ifStatement->GetCondition());

	bool hasReturn = ifStatement->GetElseStatement() != nullptr;
	bool endsWithJump = hasReturn;
	{
		auto hasReturnElement = mHasReturn.Push(false);
		auto endsWithJumpElement = mEndsWithJump.Push(false);
		Traverse(ifStatement->GetThenStatement());
		hasReturn = hasReturn && hasReturnElement;
		endsWithJump = endsWithJump && endsWithJumpElement;
	}

	{
		auto hasReturnElement = mHasReturn.Push(false);
		auto endsWithJumpElement = mEndsWithJump.Push(false);
		Traverse(ifStatement->GetElseStatement());
		hasReturn = hasReturn && hasReturnElement;
		endsWithJump = endsWithJump && endsWithJumpElement;
	}
	mHasReturn.SetTop(mHasReturn.GetTop() || hasReturn);
	mEndsWithJump.SetTop(endsWithJump || hasReturn);
}

void ValidationPass::Visit(SwitchStatement *switchStatement)
{
	AssertReachableCode(switchStatement);
	auto isInSwitchElement = mIsInSwitch.Push(true);
	auto switchLabelListElement = mSwitchLabelList.Push(nullptr);
	mEndsWithJump.SetTop(false);
	Traverse(switchStatement->GetControl());

	bool hasReturn = true;
	SwitchSection *sectionList = switchStatement->GetSectionList();
	if (sectionList != nullptr)
	{
		auto hasDefaultLabelElement = mHasDefaultLabel.Push(false);
		while (sectionList != nullptr)
		{
			auto hasReturnElement = mHasReturn.Push(false);
			Traverse(sectionList);
			hasReturn = hasReturn && hasReturnElement;
			sectionList = NextNode(sectionList);
		}

		hasReturn = (hasReturn && hasDefaultLabelElement);
		mHasReturn.SetTop(mHasReturn.GetTop() || hasReturn);
	}

	mEndsWithJump.SetTop(hasReturn);
	switchStatement->SetResolvedLabelList(switchLabelListElement.GetValue());

	const ResolvedSwitchLabel *currLabel = switchLabelListElement.GetValue();
	uint32_t numMatches = 0;
	int32_t minMatch = BOND_INT_MAX;
	int32_t maxMatch = BOND_INT_MIN;
	while (currLabel != nullptr)
	{
		if (!currLabel->IsDefault())
		{
			++numMatches;
			minMatch = Min(minMatch, currLabel->GetMatch());
			maxMatch = Max(maxMatch, currLabel->GetMatch());
		}

		const ResolvedSwitchLabel *prevLabel = currLabel;
		currLabel = NextNode(currLabel);

		if ((currLabel != nullptr) && (*prevLabel == *currLabel))
		{
			if (currLabel->IsDefault())
			{
				mErrorBuffer.PushError(CompilerError::DUPLICATE_DEFAULT_IN_SWITCH, switchStatement->GetContextToken());
			}
			else
			{
				mErrorBuffer.PushErrorInt(CompilerError::DUPLICATE_CASE_IN_SWITCH, switchStatement->GetContextToken(), currLabel->GetMatch());
			}

			while ((currLabel != nullptr) && (*prevLabel == *currLabel))
			{
				prevLabel = currLabel;
				currLabel = NextNode(currLabel);
			}
		}
	}

	switchStatement->SetNumMatches(numMatches);
	switchStatement->SetMinMatch(minMatch);
	switchStatement->SetMaxMatch(maxMatch);
}

void ValidationPass::Visit(SwitchSection *switchSection)
{
	auto endsWithJumpElement = mEndsWithJump.Push(false);

	const size_t jumpTargetId = GetJumpTargetId();
	switchSection->SetJumpTargetId(jumpTargetId);
	auto switchJumpTargetIdElement = mSwitchJumpTargetId.Push(jumpTargetId);

	SemanticAnalysisPass::Visit(switchSection);

	if (!endsWithJumpElement)
	{
		mErrorBuffer.PushError(CompilerError::UNTERMINATED_SWITCH_SECTION, switchSection->GetLabelList()->GetContextToken());
	}
}

void ValidationPass::Visit(SwitchLabel *switchLabel)
{
	ParseNodeTraverser::Visit(switchLabel);

	ResolvedSwitchLabel &resolvedLabel = switchLabel->GetResolvedLabel();
	resolvedLabel.SetJumpTargetId(mSwitchJumpTargetId.GetTop());

	if (switchLabel->IsDefaultLabel())
	{
		resolvedLabel.SetIsDefault(true);
		mHasDefaultLabel.SetTop(true);
	}
	else
	{
		resolvedLabel.SetMatch(switchLabel->GetExpression()->GetTypeAndValue().GetIntValue());
	}

	auto switchLabelComparator = [](const ResolvedSwitchLabel &a, const ResolvedSwitchLabel &b)
		{
			if (a.IsDefault())
			{
				return !b.IsDefault();
			}
			return a.GetMatch() < b.GetMatch();
		};

	mSwitchLabelList.SetTop(InsertNode(mSwitchLabelList.GetTop(), &resolvedLabel, switchLabelComparator));
}

void ValidationPass::Visit(WhileStatement *whileStatement)
{
	AssertReachableCode(whileStatement);
	auto isInLoopElement = mIsInLoop.Push(true);
	mEndsWithJump.SetTop(false);
	auto endsWithJumpElement = mEndsWithJump.Push(false);
	ParseNodeTraverser::Visit(whileStatement);
}

void ValidationPass::Visit(ForStatement *forStatement)
{
	AssertReachableCode(forStatement);
	auto isInLoopElement = mIsInLoop.Push(true);
	mEndsWithJump.SetTop(false);
	auto endsWithJumpElement = mEndsWithJump.Push(false);
	SemanticAnalysisPass::Visit(forStatement);
}

void ValidationPass::Visit(JumpStatement *jumpStatement)
{
	AssertReachableCode(jumpStatement);
	ParseNodeTraverser::Visit(jumpStatement);

	bool endsWithJump = true;
	if (jumpStatement->IsBreak())
	{
		if (!mIsInLoop.GetTop() && !mIsInSwitch.GetTop())
		{
			mErrorBuffer.PushError(CompilerError::INVALID_BREAK, jumpStatement->GetContextToken());
			endsWithJump = false;
		}
	}
	else if (jumpStatement->IsContinue())
	{
		if (!mIsInLoop.GetTop())
		{
			mErrorBuffer.PushError(CompilerError::INVALID_CONTINUE, jumpStatement->GetContextToken());
			endsWithJump = false;
		}
	}
	else if (jumpStatement->IsReturn())
	{
		mHasReturn.SetTop(true);
		AssertAssignableTypes(
			jumpStatement->GetRhs()->GetTypeAndValue(),
			*mReturnType.GetTop(),
			jumpStatement->GetContextToken(),
			CompilerError::INVALID_RETURN_TYPE_CONVERSION,
			true);
	}
	mEndsWithJump.SetTop(mEndsWithJump.GetTop() || endsWithJump);
}

void ValidationPass::Visit(DeclarativeStatement *declarativeStatement)
{
	const TypeDescriptor *typeDescriptor = declarativeStatement->GetTypeDescriptor();
	if (!typeDescriptor->IsInstantiable())
	{
		mErrorBuffer.PushError(
			CompilerError::DECLARATION_OF_UNDEFINED_SIZE,
			declarativeStatement->GetNamedInitializerList()->GetName(),
			typeDescriptor);
	}
	AssertReachableCode(declarativeStatement);
	mEndsWithJump.SetTop(false);
	ParseNodeTraverser::Visit(declarativeStatement);
}

void ValidationPass::Visit(ExpressionStatement *expressionStatement)
{
	if (expressionStatement->GetExpression() != nullptr)
	{
		AssertReachableCode(expressionStatement);
	}
	mEndsWithJump.SetTop(false);
	ParseNodeTraverser::Visit(expressionStatement);
}

void ValidationPass::Visit(BinaryExpression *binaryExpression)
{
	const Token *op = binaryExpression->GetOperator();
	const TypeDescriptor &lhDescriptor = binaryExpression->GetLhs()->GetTypeDescriptor();
	switch (op->GetTokenType())
	{
		case Token::ASSIGN:
		{
			const TypeDescriptor &typeDescriptor = binaryExpression->GetTypeDescriptor();
			if (!typeDescriptor.IsInstantiable())
			{
				mErrorBuffer.PushError(
					CompilerError::ASSIGNMENT_OF_UNDEFINED_SIZE,
					binaryExpression->GetContextToken(),
					&typeDescriptor);
			}
			const TypeAndValue &rhTav = binaryExpression->GetRhs()->GetTypeAndValue();
			AssertAssignableTypes(rhTav, lhDescriptor, op, CompilerError::INVALID_TYPE_ASSIGNMENT);
		}
		break;
		case Token::ASSIGN_PLUS:
		case Token::ASSIGN_MINUS:
		case Token::OP_PLUS:
		case Token::OP_MINUS:
		{
			if (lhDescriptor.IsPointerType())
			{
				const TypeDescriptor parentType = lhDescriptor.GetDereferencedType();
				if (!parentType.IsInstantiable())
				{
					mErrorBuffer.PushError(
						CompilerError::POINTER_ARITHMETIC_OF_UNDEFINED_SIZE,
						binaryExpression->GetContextToken(),
						&lhDescriptor);
				}
			}
		}
		break;
		default:
			break;
	}
	ParseNodeTraverser::Visit(binaryExpression);
}

void ValidationPass::Visit(UnaryExpression *unaryExpression)
{
	const Token *op = unaryExpression->GetOperator();
	if (op->GetTokenType() == Token::OP_AMP)
	{
		IdentifierExpression *identifierExpression = CastNode<IdentifierExpression>(unaryExpression->GetRhs());
		if (identifierExpression != nullptr)
		{
			NamedInitializer *namedInitializer = CastNode<NamedInitializer>(identifierExpression->GetDefinition());
			if (namedInitializer != nullptr)
			{
				namedInitializer->SetElidable(false);
			}
		}
	}
	ParseNodeTraverser::Visit(unaryExpression);
}

void ValidationPass::Visit(ArraySubscriptExpression *arraySubscriptExpression)
{
	const TypeDescriptor &typeDescriptor = arraySubscriptExpression->GetTypeDescriptor();
	if (!typeDescriptor.IsInstantiable())
	{
		mErrorBuffer.PushError(
			CompilerError::POINTER_ARITHMETIC_OF_UNDEFINED_SIZE,
			arraySubscriptExpression->GetContextToken(),
			&arraySubscriptExpression->GetLhs()->GetTypeDescriptor());
	}
	ParseNodeTraverser::Visit(arraySubscriptExpression);
}

void ValidationPass::Visit(FunctionCallExpression *functionCallExpression)
{
	ParseNodeTraverser::Visit(functionCallExpression);

	const TypeDescriptor &lhDescriptor = functionCallExpression->GetLhs()->GetTypeDescriptor();
	const TypeSpecifier *lhSpecifier = lhDescriptor.GetTypeSpecifier();
	const FunctionDefinition *function = CastNode<FunctionDefinition>(lhSpecifier->GetDefinition());
	const FunctionPrototype *prototype = function->GetPrototype();
	const Parameter *paramList = prototype->GetParameterList();
	const Expression *argList = functionCallExpression->GetArgumentList();

	while ((paramList != nullptr) && (argList != nullptr))
	{
		const TypeDescriptor &paramDescriptor = *paramList->GetTypeDescriptor();
		const TypeAndValue &argTav = argList->GetTypeAndValue();
		AssertAssignableTypes(
			argTav,
			paramDescriptor,
			argList->GetContextToken(),
			CompilerError::INVALID_TYPE_ASSIGNMENT,
			true);
		paramList = NextNode(paramList);
		argList = NextNode(argList);
	}
}

void ValidationPass::ValidateInitializer(Initializer *initializer, const TypeDescriptor &typeDescriptor)
{
	const TypeDescriptor &descriptor = initializer->GetTypeDescriptor();
	const Expression *expression = initializer->GetExpression();
	Initializer *initializerList = initializer->GetInitializerList();

	if (descriptor.IsArrayType())
	{
		uint32_t numElements = typeDescriptor.GetLengthExpressionList()->GetTypeAndValue().GetUIntValue();
		const TypeDescriptor elementDescriptor = descriptor.GetDereferencedType();
		if (initializerList != nullptr)
		{
			while ((numElements > 0) && (initializerList != nullptr))
			{
				--numElements;
				ValidateInitializer(initializerList, elementDescriptor);
				initializerList = NextNode(initializerList);
			}

			if (initializerList != nullptr)
			{
				mErrorBuffer.PushError(
					CompilerError::TOO_MANY_INITIALIZERS,
					initializerList->GetContextToken(),
					&descriptor);
			}
		}
		else if (expression != nullptr)
		{
			const ConstantLiteralExpression *constantExpression = CastNode<ConstantLiteralExpression>(expression);
			const bool isStringInitializer =
				elementDescriptor.IsCharType() &&
				(constantExpression != nullptr) &&
				constantExpression->GetTypeDescriptor().IsStringType();

			if (isStringInitializer)
			{
				const uint32_t stringLength = uint32_t(constantExpression->GetValueToken()->GetStringLength() + 1);
				if (stringLength > numElements)
				{
					mErrorBuffer.PushError(
						CompilerError::TOO_MANY_INITIALIZERS,
						expression->GetContextToken(),
						&descriptor);
				}
			}
		}
	}
	else if (expression != nullptr)
	{
		AssertAssignableTypes(
			expression->GetTypeAndValue(),
			descriptor,
			expression->GetContextToken(),
			CompilerError::INVALID_TYPE_ASSIGNMENT,
			true);
	}
	else if (descriptor.IsStructType())
	{
		const TypeSpecifier *structSpecifier = descriptor.GetTypeSpecifier();
		const StructDeclaration *structDeclaration = CastNode<StructDeclaration>(structSpecifier->GetDefinition());
		const DeclarativeStatement *memberDeclarationList = structDeclaration->GetMemberVariableList();

		if (!structDeclaration->IsNative())
		{
			while ((memberDeclarationList != nullptr) && (initializerList != nullptr))
			{
				const TypeDescriptor *memberDescriptor = memberDeclarationList->GetTypeDescriptor();
				const NamedInitializer *nameList = memberDeclarationList->GetNamedInitializerList();
				while ((nameList != nullptr) && (initializerList != nullptr))
				{
					ValidateInitializer(initializerList, *memberDescriptor);
					nameList = NextNode(nameList);
					initializerList = NextNode(initializerList);
				}
				memberDeclarationList = NextNode(memberDeclarationList);
			}
		}
	}
}

void ValidationPass::AssertReachableCode(const ParseNode *node)
{
	if (mEndsWithJump.GetTop())
	{
		mErrorBuffer.PushError(CompilerError::UNREACHABLE_CODE, node->GetContextToken());
	}
}

size_t ValidationPass::GetJumpTargetId()
{
	const size_t targetId = mNextJumpTargetId.GetTop();
	mNextJumpTargetId.SetTop(targetId + 1);
	return targetId;
}

bool ValidationPass::AssertAssignableTypes(
	const TypeAndValue &fromTav,
	const TypeDescriptor &toType,
	const Token *context,
	CompilerError::Type errorType,
	bool ignoreConst)
{
	const TypeDescriptor &fromType = fromTav.GetTypeDescriptor();
	if (ignoreConst)
	{
		TypeDescriptor nonConstType = toType;
		nonConstType.ClearConst();
		nonConstType.SetUnaddressableLValue();
		if (!AreAssignableTypes(fromType, nonConstType))
		{
			mErrorBuffer.PushError(errorType, context, &fromType, &toType);
			return false;
		}
	}
	else
	{
		if (!AreAssignableTypes(fromType, toType))
		{
			mErrorBuffer.PushError(errorType, context, &fromType, &toType);
			return false;
		}
	}
	if (IsLossyConversion(fromTav, toType))
	{
		mErrorBuffer.PushError(CompilerError::LOSSY_CONVERSION, context, &fromType, &toType);
		return false;
	}
	return true;
}

}


text:
class Interpreter;
namespace ast
{
    // A statement
    class Statement
    {
    public:

        Statement();
        Statement(BaseNodePtr root) : m_root(std::move(root)) { }

        bool add(BaseNodePtr node);
        Value eval(Interpreter& ) const;

    private:

        BaseNodePtr m_root;
    };
}

#endif // STATEMENT_HPP


text:
<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'frzambra@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Formulario Contacto Web Sequía:  $name";
$email_body = "Este es un nuevo correo de la pagina web.\n\n"."Estos son los detalles:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>


text:
r"""
>>> from payflowpro.classes import (CreditCard, Amount, Profile,
...                                 Address, Tracking, Response, CustomerInfo)
>>> from payflowpro.client import PayflowProClient, find_classes_in_list, find_class_in_list

>>> PARTNER_ID = 'Paypal'
>>> VENDOR_ID = 'wiremine'
>>> USERNAME = None
>>> PASSWORD = 'twhtalmh2'

>>> client = PayflowProClient(partner=PARTNER_ID,
...                           vendor=VENDOR_ID,
...                           username=USERNAME,
...                           password=PASSWORD)

>>> credit_card = CreditCard(acct=5555555555554444, expdate="1212")

>>> responses, unconsumed_data = client.sale(credit_card,
...                                         Amount(amt=15, currency="AUD"),
...                                         extras=[Address(street="24285 Elm", zip="00382")])

>>> responses, unconsumed_data = client.authorization(credit_card, Amount(amt=13, currency="AUD"))

>>> transaction_id = responses[0].pnref

>>> responses, unconsumed_data = client.capture(transaction_id)

>>> client_inquiry = client.inquiry(original_pnref=transaction_id, extras=[Tracking(verbosity='M')])[0]

>>> profile = Profile(profilename='test_profile_002',
...                             start='07282008',
...                             term=0,
...                             payperiod='WEEK',
...                             desc="I'm just testing..."),

>>> responses, unconsumed_data = client.profile_add(profile=profile, credit_card=credit_card, amount=Amount(amt=30.00))

>>> responses, unconsumed_data = client.profile_modify(profile_id='RT0000000002', extras=[Profile(optionaltrx='S', optionaltrxamt=12.00),
...                                                     Address(street="123 Somewhere St", city='Sydney', state='NSW', zip="2060"),
...                                                     CustomerInfo(custcode='8675', email='test@example.com', firstname='Joe', lastname='Bloggs'),
...                                                     Tracking(comment1="Order #43",)])

>>> results, unconsumed_data = client.profile_inquiry(profile_id='RT0000000001', payment_history_only=True)
>>> recurring_payments = results[-1]

>>> responses, unconsumed_data = client.profile_inquiry(profile_id='RT0000000001')

>>> address = find_class_in_list(Address, responses)

>>> results, unconsumed_data = client.profile_cancel(profile_id='RT0000000001')

>>> results, unconsumed_data = client.profile_reactivate(profile_id='RT0000000001', extras=[Profile(start="07282008")])
"""

if __name__=="__main__":
    import doctest
    doctest.testmod()


text:
#include <aws/ssm/model/UpdateDocumentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::SSM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateDocumentRequest::UpdateDocumentRequest() :
    m_contentHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_documentVersionHasBeenSet(false)
{
}

Aws::String UpdateDocumentRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_contentHasBeenSet)
  {
   payload.WithString("Content", m_content);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_documentVersionHasBeenSet)
  {
   payload.WithString("DocumentVersion", m_documentVersion);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateDocumentRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonSSM.UpdateDocument"));
  return headers;

}


text:
"use strict";

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _defaults(subClass, superClass); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Selector = require('../selector');

var Placeholder = /*#__PURE__*/function (_Selector) {
  _inheritsLoose(Placeholder, _Selector);

  function Placeholder() {
    return _Selector.apply(this, arguments) || this;
  }

  var _proto = Placeholder.prototype;

  /**
   * Add old mozilla to possible prefixes
   */
  _proto.possible = function possible() {
    return _Selector.prototype.possible.call(this).concat(['-moz- old', '-ms- old']);
  }
  /**
   * Return different selectors depend on prefix
   */
  ;

  _proto.prefixed = function prefixed(prefix) {
    if (prefix === '-webkit-') {
      return '::-webkit-input-placeholder';
    }

    if (prefix === '-ms-') {
      return '::-ms-input-placeholder';
    }

    if (prefix === '-ms- old') {
      return ':-ms-input-placeholder';
    }

    if (prefix === '-moz- old') {
      return ':-moz-placeholder';
    }

    return "::" + prefix + "placeholder";
  };

  return Placeholder;
}(Selector);

_defineProperty(Placeholder, "names", ['::placeholder']);

module.exports = Placeholder;


text:
/**@
 * #Placeable
 * @category Grid
 * Utility component to easily place an entity in the grid
 */
Crafty.c("Placeable", {
    place: function(x, y) {
        this.x = x*Game.dimensions.tile;
        this.y = y*Game.dimensions.tile;
        return this;
    }
});

/**@
 * #Sizable
 * @category Grid
 * Utility component to set dimensions of a entity. Will also add category component
 * 'Vertical' or 'Horizontal' depending on height/width ratio.
 */
Crafty.c("Sizable", {
  size: function(w, h) {
    this.h = h*Game.dimensions.tile;
    this.w = w*Game.dimensions.tile;
    if (h>w)
      this.addComponent('Vertical');
    else
      this.addComponent('Horizontal');
    return this;
  }
});

Crafty.c('Title', {
  init: function() {
    this.requires('Text, DOM, Placeable');
    this.attr({w:500});
    this.textColor('goldenrod');
    this.place(15, Game.dimensions.height-6);
    this.text('Olympics RR');
    this.textFont({family:'impact', size:'32px'});
  }
});

Crafty.c('Olympics', {
  init: function() {
    this.count = 0;
    this.startSpeed = {x:30*Game.dimensions.tile, y:0};
    this.startPlacement = {x:15, y:35};
    this.winPoints = 15;
    this.maxSpeed = {x:{min:-60*Game.dimensions.tile, max:60*Game.dimensions.tile}, y:{min:-15*Game.dimensions.tile, max:15*Game.dimensions.tile}};
    this.speedIncrease = 1.08;
    this.bind('pointsChanged', this.onPointsChanged);
    this.bind('playerWin', this.onPlayerWin);
  },
  onPointsChanged: function(player) {

    if (player.points >= this.winPoints) {
      console.log('onPointAdded %o', player.playerId, player.points);
      Crafty.trigger('playerWin', player);
    }
  },
  onPlayerWin: function(player) {
    console.log(player.playerId + ' wins!');
    Crafty.pause();
  },
  setTitle: function(title) {
    if (Crafty('Title').length == 1) {
      Crafty('Title').get(0).text(title);
    } else {
      Crafty.e('Title')
        .text(title);
    }
    return this;
  },
  setBackground: function(color) {
    Crafty.background(color);
    return this;
  }
});

Crafty.c('Player', {
    init: function() {
        this.requires('Color');
        this.points = 0;
        this.playerId = 0;
    },
    setPaddle: function(paddle) {
        this.paddle = paddle;
        this.paddle.color(this.color());
        this.paddle.gamepadMultiway({
          analog: true,
          speed: 1000,
          gamepadIndex: this.playerId});
        this.paddle.unbind('GamepadAxisChange');
        if (this.paddle.has('Vertical')) {
          this.paddle.bind('GamepadAxisChange', Olympics.absoluteYAxisChange);
        } else if (this.paddle.has('Horizontal')) {
          this.paddle.bind('GamepadAxisChange', Olympics.absoluteXAxisChange);
        }
        return this;
    },
    setScoreboard: function(scoreboard) {
        this.scoreboard = scoreboard;
        this.scoreboard.textColor(this.color());
        return this;
    },
    addPoint: function() {
        this.points++;
        this.scoreboard.text(this.points);
        Crafty.trigger('pointsChanged', this);
    }
});

Crafty.c('Paddle', {
    init: function() {
        this.requires('2D, WebGL, Color, Multiway, GamepadMultiway, Solid, Placeable, Sizable');
        this.points = 0;
        this.vy=0;
    },

});

Crafty.c("Score", {
    init: function() {
        this.requires("DOM, 2D, Color, Text, Placeable");
        this.textFont({family: 'impact', size:'50px', type:'bold'})
    }
});

Crafty.c("Wall", {
    init: function() {
        this.requires("2D, WebGL, Color, Solid, Placeable, Sizable");
        this.color('powderblue');
    },
});

Crafty.c("Ball", {
    init: function() {
        this.requires("2D, WebGL, Color, Collision, Motion, Placeable, Sizable");
        this.size(1, 1);
        this.color('yellowgreen');
        this.vy = 0;
        this.vx = 200;
        this.hitPaddle = function hitPaddle(data) {console.log("ball hit Paddle")};
        this.hitWall = function hitWall(data) {console.log("ball hit wall")};
        this.leaveEast = function leaveEast() {console.log("Ball leaves east")};
        this.leaveWest = function leaveWest() {console.log("Ball leaves west")};
    }
});


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Vincent van Daal - All-round geek - tutorial</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

Vincent van Daal - All-round geek

Tutorials

Useful bits and bobs

Redis quick install on RHEL based distributions

                Published: Wed 13 November 2013

        <address class="vcard author">
                By                         Vincent van Daal
        </address>

In Tutorials.

tags: tutorial redis RHEL CentOS

This short tutorial sums up on how to compile / install Redis.
This instruction should generally work on any Redhat based distro :-)

I've tested this on CentOS 6.4.

Be sure to run these commands as root.
First make sure repo's and your packages are up-to-date:

sudo yum update

Install required prerequisites for compiling with the following command:

sudo yum install make gcc wget tcl

Download latest version of Redis and compile it:

cd /opt/
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make

Testing Redis (Recommended):

make test

Now run make install to copy the files to the correct location in /usr/local/bin/
(Thanks to Tassos for pointing this out)

make install

Start installation using the supplied script from Redis:

cd /opt/redis-stable/utils
./install_server.sh

Answer the questions asked, I recommend going with the default values for clarity sake but feel free to customize.

To start Redis:

Replace 6379 with the actual port that you have chosen during the installation.

service redis_6379 start

update.rc error when running the install_server.sh script

If you get an update.rc error from the installation script, which I encountered using Redis 2.6.16, edit the init script using your favourite text editor.
The location is /etc/init.d/ and the file name is redis_6379 (6379 is the port you have chosen earlier in the installation so this may differ from yours)

Replace "6379" in this example init script with the port you are using for Redis.

#/bin/sh
# chkconfig: 2345 95 20
# description: Init script for Redis on port 6379
#Configurations injected by install_server below....
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
PIDFILE=/var/run/redis_6379.pid
CONF="/etc/redis/6379.conf"
REDISPORT="6379"
###############

case "$1" in
start)
if [ -f $PIDFILE ]
then
echo "$PIDFILE exists, process is already running or crashed"
else
echo "Starting Redis server..."
$EXEC $CONF
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping ..."
$CLIEXEC -p $REDISPORT shutdown
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
;;
*)
echo "Please use start or stop as first argument"
;;
esac

And finish the fix with adding Redis at startup:

chkconfig --add redis_6379
chkconfig --level 345 redis_6379 on

This article was inspired by the Linode article https://library.linode.com/databases/redis/centos-5 and the official Redis installation instructions on http://redis.io/topics/quickstart

Other articles

My trip to Glasgow on 5 June 2013

                Published: Tue 04 June 2013

        <address class="vcard author">
                By                         Vincent van Daal
        </address>

In Useful bits and bobs.

tags: tutorial windows environment variables

Summary about my trip to Glasgow on 5 June 2013

                read more

Upgrading VMware ESXi to 5.1 without use of a depot or update center

                Published: Thu 14 February 2013

        <address class="vcard author">
                By                         Vincent van Daal
        </address>

In Tutorials.

tags: tutorial vmware esxi

Tutorial for upgrading VMware ESXi to 5.1 without use of a depot or update center

                read more

Windows global system environment variables

                Published: Sat 08 December 2012

        <address class="vcard author">
                By                         Vincent van Daal
        </address>

In Useful bits and bobs.

tags: tutorial windows environment variables

Some useful information about Windows global system environment variables

                read more

blogroll

Pelican

Python.org

Jinja2

You can modify those links in your config file

social

You can add links in your config file

Another social link

                <address id="about" class="vcard body">
                Proudly powered by Pelican, which takes great advantage of Python.
                </address>

The theme is by Smashing Magazine, thanks!


text:
from PIL import Image

img = Image.new('RGB', (225, 225), color='black')
img.save('../temp/black_square.png')


text:
import time
import os
BOT_NAME = 'ip_proxy'
ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SPIDER_MODULES = ['ip_proxy.spiders']
NEWSPIDER_MODULE = 'ip_proxy.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENTS = (
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36',
    'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
    'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
    'Mozilla/5.0 (Windows NT 6.1; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
    'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
    'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.1 Safari/605.1.15'
    )

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = True

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
#    'ip_proxy.middlewares.ip_proxy_spider.IpProxySpiderMiddleware': 543,
# }

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'ip_proxy.middlewares.ip_proxy_downloader.IpProxyDownloaderMiddleware': 543,
   'ip_proxy.middlewares.random_user_agent.RandomUserAgentMiddleware' : 542
}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'ip_proxy.pipelines.mysql_pipeline.MysqlPipeline': 300,
    'ip_proxy.pipelines.redis_pipeline.RedisPipeline': 299,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
LOG_LEVEL = 'INFO'
HTTPPROXY_AUTH_ENCODING = 'utf-8'


text:
#include <TestConfig.h>
#include <Lumino/Json/JsonDocument.h>

class Test_Json_JsonDocument : public ::testing::Test
{
protected:
	virtual void SetUp() {}
	virtual void TearDown() {}
};

//---------------------------------------------------------------------
TEST_F(Test_Json_JsonDocument, Basic)
{
	//const char* json = R"( { "hello" : "world", "t" : true , "f" : false, "n": null, "i":123, "pi": 3.1416, "a":[1, 2, 3, 4] } )";
	////String str = FileSystem::ReadAllText(LN_LOCALFILE("TestData/ReaderTest1.txt"), Encoding::GetSystemMultiByteEncoding());
	//tr::JsonDocument2 doc;

	//////ElapsedTimer t;
	//////t.Start();
	//doc.Parse(json);

	////printf("%d", t.GetElapsedTime());

	//printf("");
}

//---------------------------------------------------------------------
TEST_F(Test_Json_JsonDocument, Save)
{
	tr::JsonDocument2 doc;
	doc.AddMemberBool(_T("b1"), true);
	doc.AddMemberBool(_T("b2"), false);
	doc.AddMemberInt32(_T("i32"), 1);
	doc.AddMemberInt64(_T("i64"), 2147483648LL);
	doc.AddMemberFloat(_T("f"), 1.0f);
	doc.AddMemberDouble(_T("dbl"), 1.0);
	doc.AddMemberString(_T("str"), _T("test"));

	auto* ary = doc.AddMemberArray(_T("ary"));
	ary->AddBool(true);
	ary->AddInt32(200);

	auto* obj = doc.AddMemberObject(_T("obj"));
	obj->AddMemberInt32(_T("i32_2"), 100);

	auto* aryary = doc.AddMemberArray(_T("aryary"));
	aryary->AddArray()->AddInt32(111);
	aryary->AddArray()->AddInt32(222);

	auto* objary = doc.AddMemberArray(_T("objary"));
	objary->AddObject()->AddMemberInt32(_T("int32"), 300);
	objary->AddObject()->AddMemberString(_T("str1"), _T("test2"));

	doc.Save(TEMPFILE("json.txt"), tr::JsonFormatting::Indented);

	ASSERT_TRUE(TestHelper::EqualFiles(TEMPFILE("json.txt"), LN_LOCALFILE("TestData/Test_Json_JsonDocument_Save1.json")));

}

//---------------------------------------------------------------------
TEST_F(Test_Json_JsonDocument, Load)
{
	tr::JsonDocument2 doc;
	doc.Load(LN_LOCALFILE("TestData/Test_Json_JsonDocument_Save1.json"));
	doc.Save(TEMPFILE("json2.txt"), tr::JsonFormatting::Indented);
}


text:
from .helpers import *
from .behavior import trivia_behavior

DELAY = 20

async def premise(item):
    country, _ = item

    return dict(
        content='You have {} seconds to guess the name of the capital city of `{}`'
                    .format(DELAY, country),
    )

def resolve(item, answers):
    _, capital = item

    winner, message = Resolve.fastest(answers, capital.lower(), skill='geography')

    return winner, dict(content=message)

CapitalsTrivia = trivia_behavior(
    fetch   = Fetch.read_json('capitals.json'),
    pick    = Pick.random_collection,
    premise = premise,
    query   = Query.timed(DELAY),
    resolve = resolve,
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<tenant xmlns="http://docs.openstack.org/identity/api/v2.0"
        enabled="true" id="1234" name="ACME Corp">
    <description>A NEW description...</description>
</tenant>


text:
**Go to:**      [**Root TOC**](CM-Well.RootTOC.md)      [**Topic TOC**](ReleaseNotes.TOC.md)      [**Previous Topic**](ReleaseNotes.Dec.7.2016.md)     [**Next Topic**](ReleaseNotes.Jan.4.2016.md)

----

## Change Summary ##

### New Features ###

Feature/Link | Description
:-------------|:-----------
[SPARQL Trigger Processor Is Now an Internal CM-Well Agent](#hdr1) | The SPARQL Trigger Processor, which previously was an external utility of CM-Well, is now part of the CM-Well server and runs automatically.
[Alternative Syntax for "Create Consumer"](#hdr2) | Alternative syntax for "create consumer" API (uses POST instead of GET to enable long query values).
[Cache in SPARQL](#hdr3) | Cache added to SPARQL queries.

### Notable Bug Fixes ###
N/A

### Changes to API	 ###

Alternative syntax for "create consumer" API (uses POST instead of GET to enable long query values).

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

## Feature Descriptions ##

### SPARQL Trigger Processor Is Now an Internal CM-Well Agent ###

**Description:**

The SPARQL Trigger Processor, which previously was an external utility of CM-Well, is now part of the CM-Well server and runs automatically.

In addition, the agent has been enhanced to adjust its consumption rate dynamically according to local network conditions.

The YAML configuration file remains the same, except for the addition of the Boolean **active** flag, which you can use to enable or disable the specific configuration.

**Documentation:**
[Using the SPARQL Trigger Processor](Tools.UsingTheSPARQLTriggerProcessor.md)

----------

### Alternative Syntax for Create Consumer ###

**Description:**

Previously, the CM-Well API only supported a GET command for creating a consumer object (for bulk streaming of infotons). Now there is a new alternative syntax for creating a consumer, which uses POST instead of GET. The purpose of the new syntax is to avoid the length limitation that some clients impose on GET commands, in case the user needs to define a very long **qp** value. In the new syntax, the query parameters are passed as data rather than as part of the URL.

**Example:**

    curl -vX POST http://cm-well/permid.org?op=create-consumer -H "Content-Type:application/x-www-form-urlencoded" --data-binary "index-time=123456789&qp=\*type.rdf::http://permid.org/ontology/organization/Organization,\*type.rdf::http://ont.thomsonreuters.com/mdaas/Organization"

**Documentation:** [Create Consumer](API.Stream.CreateConsumer.md)

----------

### Cache in SPARQL ###

**Description:**

A cache has been added to the SPARQL query feature. Queries that recur within a short period of time return results from the cache instead of causing the query to be rerun. This is transparent to the user and improves performance of SPARQL queries.

**Documentation:** N/A.

----

**Go to:**      [**Root TOC**](CM-Well.RootTOC.md)      [**Topic TOC**](ReleaseNotes.TOC.md)      [**Previous Topic**](ReleaseNotes.Dec.7.2016.md)     [**Next Topic**](ReleaseNotes.Jan.4.2016.md)

----


text:
package com.kince.android.pulltozoomlistviewdemo;

import com.kince.android.pulltozoomlistview.PullToZoomListView;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity{

	private PullToZoomListView mListView;
	private String[] adapterData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mListView = (PullToZoomListView) findViewById(R.id.detail_list_view);
		mListView.setShadow(R.drawable.detail_pic_shadow);
		this.mListView.getHeaderView().setScaleType(
				ImageView.ScaleType.CENTER_CROP);

		adapterData = new String[] { "Activity", "Service", "View",
				"Intent", "BroadcastReceiver", "ADT", "Sqlite3", "HttpClient",
				"DDMS", "Android Studio", "Fragment", "Loader", "NDK",
				"Volley", "ListView", "ActionBar", "WindowManager", "Launcher",
				"App", "Lock", "Screen" };

		mListView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
				android.R.layout.simple_list_item_1, adapterData));
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if(position!=0){
					Toast.makeText(getApplicationContext(), adapterData[position-1]+"", 0).show();
				}

			}
		});

	}

}


text:
package uk.artdude.tweaks.twisted.common.gui.configuration;

import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import uk.artdude.tweaks.twisted.common.configuration.ConfigurationHelper;
import uk.artdude.tweaks.twisted.common.configuration.TTConfiguration;
import uk.artdude.tweaks.twisted.common.util.References;

import java.util.ArrayList;
import java.util.List;

public class TTConfigGUI extends GuiConfig {

    public TTConfigGUI(GuiScreen parent) {
        super(parent, getConfigElements(), References.modID, false, false, "Twisted Tweaks Configuration");
    }

    private static List<IConfigElement> getConfigElements() {
        // Set up our list to store the elements in.
        List<IConfigElement> list = new ArrayList<IConfigElement>();
        // Add our categories to the config GUI.
        list.add(configElement(ConfigurationHelper.CATEGORY_BLOCKS, "Blocks", "tweaks.twisted.config.blocks"));
        list.add(configElement(ConfigurationHelper.CATEGORY_ACIDRAIN, "Acid Rain", "tweaks.twisted.config.rain.acid"));
        list.add(configElement(ConfigurationHelper.CATEGORY_ACIDRAIN_EFFECTS, "Acid Rain Effects", "tweaks.twisted.config.rain.acid.effects"));
        list.add(configElement(ConfigurationHelper.CATEGORY_POTIONS, "Potions", "tweaks.twisted.config.rain.acid.potions"));
        list.add(configElement(ConfigurationHelper.CATEGORY_TWEAKS, " Game Tweaks", "tweaks.twisted.config.game.tweaks"));
        list.add(configElement(ConfigurationHelper.CATEGORY_ENCHANTMENTS, "Enchantments", "tweaks.twisted.config.enchantments"));
        list.add(configElement(ConfigurationHelper.CATEGORY_SETTINGS, "Settings", "tweaks.twisted.config.settings"));
        // Return the list back.
        return list;
    }

    private static IConfigElement configElement(String category, String name, String tooltip_key) {
        return new DummyConfigElement.DummyCategoryElement(name, tooltip_key,
                new ConfigElement(TTConfiguration.config.getCategory(category)).getChildElements());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="de.ub0r.android.eucookieconsent">

    <de.ub0r.android.eucookieconsent.EuCookieConsentView
            android:id="@+id/eucookieconsent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:textMessage="Your custom eu cookie consent text. %s"
            app:textLearnMore="more info"
            app:textGotIt="ok!"
            app:urlLeanMore="https://www.google.com/search?q=eu+cookie+consent"/>

    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sample text..\nbla bla..\n\nrestart app after reset"
            tools:ignore="HardcodedText"/>

    <Button
            android:id="@+id/reset_acknowledgement"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="reset acknowledgment"
            tools:ignore="HardcodedText"/>
</LinearLayout>


text:
package org.jkiss.dbeaver.ui.editors.sql.variables;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCScriptContext;
import org.jkiss.dbeaver.model.exec.DBCScriptContextListener;
import org.jkiss.dbeaver.model.sql.SQLScriptContext;
import org.jkiss.dbeaver.model.sql.registry.SQLQueryParameterRegistry;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.controls.ListContentProvider;
import org.jkiss.dbeaver.ui.controls.ProgressPageControl;
import org.jkiss.dbeaver.ui.controls.ViewerColumnController;
import org.jkiss.dbeaver.ui.editors.StringEditorInput;
import org.jkiss.dbeaver.ui.editors.SubEditorSite;
import org.jkiss.dbeaver.ui.editors.TextEditorUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditor;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.dbeaver.ui.navigator.NavigatorUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.CommonUtils;

import java.util.Arrays;
import java.util.List;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;

/**
 * SQLVariablesPanel
 */
public class SQLVariablesPanel extends Composite implements DBCScriptContextListener {

    static protected final Log log = Log.getLog(SQLVariablesPanel.class);

    private final SQLEditor mainEditor;
    private SQLEditorBase valueEditor;
    private TableViewer varsTable;
    private boolean showParameters;
    private boolean saveInProgress;
    private DBCScriptContext.VariableInfo curVariable;

    public SQLVariablesPanel(Composite parent, SQLEditor editor)
    {
        super(parent, SWT.NONE);
        this.mainEditor = editor;

        setLayout(new FillLayout());
    }

    private void createControls() {
        mainEditor.getGlobalScriptContext().addListener(this);
        addDisposeListener(e -> mainEditor.getGlobalScriptContext().removeListener(this));

        SashForm sash = new SashForm(this, SWT.VERTICAL);

        // Variables table
        {
            VariableListControl variableListControl = new VariableListControl(sash);
            variableListControl.createOrSubstituteProgressPanel(mainEditor.getSite());
        }

        // Editor
        {
            Composite editorGroup = UIUtils.createPlaceholder(sash, 1);

            UIUtils.createControlLabel(editorGroup, "Value");

            Composite editorPH = new Composite(editorGroup, SWT.NONE);
            GridData gd = new GridData(GridData.FILL_BOTH);
            gd.verticalIndent = 3;
            gd.horizontalSpan = 1;
            gd.minimumHeight = 100;
            gd.minimumWidth = 100;
            editorPH.setLayoutData(gd);
            editorPH.setLayout(new FillLayout());

            valueEditor = new SQLEditorBase() {
                @Nullable
                @Override
                public DBCExecutionContext getExecutionContext() {
                    return mainEditor.getExecutionContext();
                }

                @Override
                public void createPartControl(Composite parent) {
                    super.createPartControl(parent);
                    getAction(ITextEditorActionConstants.CONTEXT_PREFERENCES).setEnabled(false);
                }

                @Override
                public boolean isFoldingEnabled() {
                    return false;
                }
            };
            try {
                valueEditor.init(new SubEditorSite(mainEditor.getSite()),
                    new StringEditorInput("Variable value", "", true, GeneralUtils.getDefaultFileEncoding()));
            } catch (PartInitException e) {
                log.error(e);
            }
            valueEditor.createPartControl(editorPH);
            valueEditor.setWordWrap(true);
            valueEditor.reloadSyntaxRules();

            //valueEditor.getEditorControl().setEnabled(false);

            valueEditor.getEditorControlWrapper().setLayoutData(new GridData(GridData.FILL_BOTH));
            StyledText editorControl = valueEditor.getEditorControl();
            TextEditorUtils.enableHostEditorKeyBindingsSupport(mainEditor.getSite(), editorControl);
            if (editorControl != null) {
                editorControl.addFocusListener(new FocusAdapter() {
                    @Override
                    public void focusLost(FocusEvent e) {
                        saveVariableValue(editorControl);
                    }
                });
                //editorControl.addDisposeListener(e -> saveVariableValue(editorControl));
            }
        }

        sash.setWeights(new int[] { 600, 400 });
    }

    private void saveVariableValue(StyledText editorControl) {
        String varValue = editorControl.getText();

        if (curVariable != null) {
            saveInProgress = true;
            try {
                curVariable.value = varValue;
                mainEditor.getGlobalScriptContext().setVariable(
                    curVariable.name,
                    varValue);
                varsTable.refresh();
            } finally {
                saveInProgress = false;
            }
        }
    }

    private void editCurrentVariable() {
        ISelection selection = varsTable.getSelection();
        StyledText editorControl = valueEditor.getEditorControl();
        if (editorControl == null) {
            return;
        }
        if (!selection.isEmpty()) {
            //TableItem item = varsTable.getItem(selectionIndex);
            curVariable = (DBCScriptContext.VariableInfo) ((IStructuredSelection)selection).getFirstElement();

            StringEditorInput sqlInput = new StringEditorInput(
                "Variable " + curVariable.name,
                CommonUtils.toString(curVariable.value),
                false,
                GeneralUtils.DEFAULT_ENCODING
                );
            valueEditor.setInput(sqlInput);
            valueEditor.reloadSyntaxRules();
        }
    }

    public void refreshVariables() {
        if (varsTable == null) {
            createControls();
        }

        SQLScriptContext context = mainEditor.getGlobalScriptContext();

        //varsTable.removeAll();
        List<DBCScriptContext.VariableInfo> variables = context.getVariables();
        if (showParameters) {
            for (SQLQueryParameterRegistry.ParameterInfo param : SQLQueryParameterRegistry.getInstance().getAllParameters()) {
                if (context.hasVariable(param.name)) {
                    continue;
                }
                Object parameterValue = context.getParameterDefaultValue(param.name);
                if (parameterValue == null) {
                    parameterValue = param.value;
                }
                variables.add(new DBCScriptContext.VariableInfo(
                    param.name,
                    parameterValue,
                    DBCScriptContext.VariableType.PARAMETER));
            }
        }

        varsTable.setInput(variables);
        //UIUtils.packColumns(varsTable.getTable(), true);

        valueEditor.setInput(new StringEditorInput(
            "Variable",
            "",
            true,
            GeneralUtils.DEFAULT_ENCODING
        ));
        valueEditor.reloadSyntaxRules();
    }

    @Override
    public void variableChanged(ContextAction action, DBCScriptContext.VariableInfo variable) {
        if (saveInProgress) {
            return;
        }
        UIUtils.asyncExec(this::refreshVariables);
    }

    @Override
    public void parameterChanged(ContextAction action, String name, Object value) {
        if (saveInProgress) {
            return;
        }
        UIUtils.asyncExec(this::refreshVariables);
    }

    private class VariableListControl extends ProgressPageControl {

        private final ISearchExecutor searcher;
        private Action addAction;
        private Action deleteAction;

        public VariableListControl(Composite parent) {
            super(parent, SWT.SHEET);
            searcher = new ISearchExecutor() {
                @Override
                public boolean performSearch(String searchString, int options) {
                    try {
                        PatternFilter searchFilter = new PatternFilter() {
                            protected boolean isLeafMatch(Viewer viewer, Object element) {
                                DBCScriptContext.VariableInfo variable = (DBCScriptContext.VariableInfo) element;

                                return wordMatches(variable.name) || wordMatches(CommonUtils.toString(variable.value));
                            }
                        };
                        searchFilter.setPattern(searchString);
                            //(options & SEARCH_CASE_SENSITIVE) != 0);
                        varsTable.setFilters(new ViewerFilter[]{ searchFilter });
                        return true;
                    } catch (PatternSyntaxException e) {
                        log.error(e.getMessage());
                        return false;
                    }
                }

                @Override
                public void cancelSearch() {
                    varsTable.setFilters(new ViewerFilter[0]);
                }
            };

            varsTable = new TableViewer(this, SWT.MULTI | SWT.FULL_SELECTION);
            varsTable.getTable().setHeaderVisible(true);
            varsTable.getTable().setLinesVisible(true);
            varsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));

            ViewerColumnController columnController = new ViewerColumnController("sqlVariablesViewer", varsTable);

            varsTable.setContentProvider(new ListContentProvider());

            columnController.addColumn("Variable", "Variable or parameter name", SWT.LEFT, true, true, new ColumnLabelProvider() {
                @Override
                public String getText(Object element) {
                    return ((DBCScriptContext.VariableInfo) element).name;
                }
            });
            columnController.addColumn("Value", "Variable or parameter value", SWT.LEFT, true, true, new ColumnLabelProvider() {
                @Override
                public String getText(Object element) {
                    return CommonUtils.toString(((DBCScriptContext.VariableInfo) element).value);
                }
            });
            columnController.addColumn("Type", "Variable type", SWT.LEFT, true, true, new ColumnLabelProvider() {
                @Override
                public String getText(Object element) {
                    return ((DBCScriptContext.VariableInfo) element).type.getTitle();
                }
            });

            columnController.createColumns(true);

            varsTable.addSelectionChangedListener(event -> {
                if (deleteAction != null) {
                    Object varElement = event.getSelection().isEmpty() ?
                        null : ((IStructuredSelection) varsTable.getSelection()).getFirstElement();

                    deleteAction.setEnabled(
                        varElement instanceof DBCScriptContext.VariableInfo);
                    updateActions();
                }
                editCurrentVariable();
            });
            NavigatorUtils.createContextMenu(mainEditor.getSite(), varsTable, manager -> {} );
        }

        @Override
        protected ISearchExecutor getSearchRunner() {
            return searcher;
        }

        protected void addSearchAction(IContributionManager contributionManager) {
            contributionManager.add(new Action("Find variable", DBeaverIcons.getImageDescriptor(UIIcon.SEARCH)) {
                @Override
                public void run() {
                    performSearch(SearchType.NONE);
                }
            });
        }

        @Override
        protected void createSearchControls() {
            super.createSearchControls();
            Text textControl = getSearchTextControl();
            if (textControl != null) {
                TextEditorUtils.enableHostEditorKeyBindingsSupport(mainEditor.getSite(), textControl);
            }
        }

        @Override
        public void fillCustomActions(IContributionManager contributionManager) {
            super.fillCustomActions(contributionManager);

            addAction = new Action("Add variable", DBeaverIcons.getImageDescriptor(UIIcon.ADD)) {
                @Override
                public void run() {
                    AssignVariableAction action = new AssignVariableAction(mainEditor, "");
                    action.setEditable(true);
                    action.run();
                }
            };
            contributionManager.add(addAction);
            deleteAction = new Action("Delete variable", DBeaverIcons.getImageDescriptor(UIIcon.DELETE)) {
                @Override
                public void run() {
                    if (!varsTable.getSelection().isEmpty()) {
                        final StructuredSelection selection = (StructuredSelection) varsTable.getSelection();
                        List<String> varsList = Arrays.stream(selection.toArray()).map(el -> ((DBCScriptContext.VariableInfo) el).name).collect(Collectors.toList());
                        new RemoveVariablesAction(mainEditor, varsList).run();

                    }
                }
            };
            deleteAction.setEnabled(false);
            contributionManager.add(deleteAction);

            Action showParamsAction = new Action("Show parameters", Action.AS_CHECK_BOX) {
                @Override
                public void run() {
                    showParameters = !showParameters;
                    refreshVariables();
                }
            };
            showParamsAction.setChecked(showParameters);
            showParamsAction.setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.SQL_PARAMETER));
            showParamsAction.setDescription("Show query parameters");
            contributionManager.add(ActionUtils.makeActionContribution(showParamsAction, true));
        }
    }
}


text:
package marc.henrard.murisq.pricer.swaption;

import static com.opengamma.strata.basics.index.IborIndices.EUR_EURIBOR_3M;
import static com.opengamma.strata.product.swap.type.FixedIborSwapConventions.EUR_FIXED_1Y_EURIBOR_3M;
import static org.assertj.core.api.Assertions.assertThat;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

import org.assertj.core.data.Offset;
import org.junit.jupiter.api.Test;

import com.google.common.collect.ImmutableList;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.date.AdjustableDate;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.basics.date.DayCounts;
import com.opengamma.strata.basics.date.HolidayCalendar;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.pricer.model.HullWhiteOneFactorPiecewiseConstantParameters;
import com.opengamma.strata.pricer.model.HullWhiteOneFactorPiecewiseConstantParametersProvider;
import com.opengamma.strata.pricer.rate.ImmutableRatesProvider;
import com.opengamma.strata.pricer.swap.DiscountingSwapProductPricer;
import com.opengamma.strata.pricer.swaption.HullWhiteSwaptionPhysicalProductPricer;
import com.opengamma.strata.pricer.swaption.NormalSwaptionPhysicalProductPricer;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.common.LongShort;
import com.opengamma.strata.product.swap.ResolvedSwapTrade;
import com.opengamma.strata.product.swap.SwapPaymentPeriod;
import com.opengamma.strata.product.swap.SwapTrade;
import com.opengamma.strata.product.swaption.PhysicalSwaptionSettlement;
import com.opengamma.strata.product.swaption.ResolvedSwaption;
import com.opengamma.strata.product.swaption.Swaption;

import marc.henrard.murisq.basics.time.ScaledSecondTime;
import marc.henrard.murisq.basics.time.TimeMeasurement;
import marc.henrard.murisq.dataset.MulticurveEur20151120DataSet;
import marc.henrard.murisq.model.g2pp.G2ppPiecewiseConstantParameters;

/**
 * Tests {@link G2ppSwaptionPhysicalProductExplicitApproxPricer}.
 *
 * @author Marc Henrard
 */
public class G2ppSwaptionPhysicalProductExplicitApproxPricerTest {

  private static final ReferenceData REF_DATA = ReferenceData.standard();
  private static final HolidayCalendar EUTA_IMPL = REF_DATA.getValue(EUR_EURIBOR_3M.getFixingCalendar());

  private static final LocalDate VALUATION_DATE = LocalDate.of(2015, 11, 20);
  private static final ZoneId VALUATION_ZONE = ZoneId.of("Europe/London");
  private static final LocalTime VALUATION_TIME = LocalTime.of(10, 29);
  private static final ImmutableRatesProvider MULTICURVE_EUR =
      MulticurveEur20151120DataSet.MULTICURVE_EUR_EONIA_20151120;

  /* G2++ parameters */
  private static final Currency CURRENCY = Currency.EUR;
  private static final double CORRELATION = -0.50;
  private static final double KAPPA_1 = 0.02;
  private static final double KAPPA_2 = 0.20;
  private static final DoubleArray VOLATILITY_1_CST = DoubleArray.of(0.01d);
  private static final DoubleArray VOLATILITY_2_CST = DoubleArray.of(0.005d);
  private static final DoubleArray VOLATILITY_TIME_CST = DoubleArray.of();
  private static final TimeMeasurement TIME_MEASUREMENT = ScaledSecondTime.DEFAULT;
  private static final DayCount G2PP_DAYCOUNT = DayCounts.ACT_365F; // Used only for Implied Volatility computation
  private static final G2ppPiecewiseConstantParameters PARAMETERS =
      G2ppPiecewiseConstantParameters.builder()
      .currency(CURRENCY)
      .correlation(CORRELATION)
      .kappa1(KAPPA_1)
      .kappa2(KAPPA_2)
      .volatility1(VOLATILITY_1_CST)
      .volatility2(VOLATILITY_2_CST)
      .volatilityTime(VOLATILITY_TIME_CST)
      .valuationDate(VALUATION_DATE)
      .valuationTime(VALUATION_TIME)
      .valuationZone(VALUATION_ZONE)
      .timeMeasure(TIME_MEASUREMENT)
      .build();
  private static final G2ppPiecewiseConstantParameters PARAMETERS_G2PP_DEG_1 =
      G2ppPiecewiseConstantParameters.builder()
      .currency(CURRENCY)
      .correlation(CORRELATION)
      .kappa1(KAPPA_1)
      .kappa2(KAPPA_2)
      .volatility1(VOLATILITY_1_CST)
      .volatility2(DoubleArray.of(0.0d))
      .volatilityTime(VOLATILITY_TIME_CST)
      .valuationDate(VALUATION_DATE)
      .valuationTime(VALUATION_TIME)
      .valuationZone(VALUATION_ZONE)
      .timeMeasure(TIME_MEASUREMENT)
      .build();
  private static final G2ppPiecewiseConstantParameters PARAMETERS_G2PP_DEG_2 =
      G2ppPiecewiseConstantParameters.builder()
      .currency(CURRENCY)
      .correlation(CORRELATION)
      .kappa1(KAPPA_1)
      .kappa2(KAPPA_2)
      .volatility1(DoubleArray.of(0.0d))
      .volatility2(VOLATILITY_2_CST)
      .volatilityTime(VOLATILITY_TIME_CST)
      .valuationDate(VALUATION_DATE)
      .valuationTime(VALUATION_TIME)
      .valuationZone(VALUATION_ZONE)
      .timeMeasure(TIME_MEASUREMENT)
      .build();
  private static final DayCount HW_DAYCOUNT = DayCounts.ACT_365F;
  private static final HullWhiteOneFactorPiecewiseConstantParameters HW_PARAMETERS_1 =
      HullWhiteOneFactorPiecewiseConstantParameters.of(KAPPA_1, VOLATILITY_1_CST, DoubleArray.of());
  private static final HullWhiteOneFactorPiecewiseConstantParametersProvider PROVIDER_HW_1 =
      HullWhiteOneFactorPiecewiseConstantParametersProvider
      .of(HW_PARAMETERS_1, HW_DAYCOUNT, VALUATION_DATE, VALUATION_TIME, VALUATION_ZONE);
  private static final HullWhiteOneFactorPiecewiseConstantParameters HW_PARAMETERS_2 =
      HullWhiteOneFactorPiecewiseConstantParameters.of(KAPPA_2, VOLATILITY_2_CST, DoubleArray.of());
  private static final HullWhiteOneFactorPiecewiseConstantParametersProvider PROVIDER_HW_2 =
      HullWhiteOneFactorPiecewiseConstantParametersProvider
      .of(HW_PARAMETERS_2, HW_DAYCOUNT, VALUATION_DATE, VALUATION_TIME, VALUATION_ZONE);

  /* Swaption description */
  private static final double NOTIONAL = 1_000_000.0d;

  /* Pricers */
  private static final DiscountingSwapProductPricer PRICER_SWAP =
      DiscountingSwapProductPricer.DEFAULT;
  private static final G2ppSwaptionPhysicalProductExplicitApproxPricer PRICER_SWPT_G2PP_APPROX =
      G2ppSwaptionPhysicalProductExplicitApproxPricer.DEFAULT;
  private static final G2ppSwaptionPhysicalProductNumericalIntegration2DPricer PRICER_SWPT_G2PP_NI =
      G2ppSwaptionPhysicalProductNumericalIntegration2DPricer.DEFAULT;
  private static final NormalSwaptionPhysicalProductPricer PRICER_SWAPTION_BACHELIER =
      NormalSwaptionPhysicalProductPricer.DEFAULT;
  private static final HullWhiteSwaptionPhysicalProductPricer PRICER_SWAPTION_HW =
      HullWhiteSwaptionPhysicalProductPricer.DEFAULT;

  private static final Offset<Double> TOLERANCE_IV = Offset.offset(1.0E-5);

  /* Compare efficient approximation to Numerical integration 2D */
  @Test
  public void pv_approx_v_ni() {
    Period[] expiries = new Period[] {Period.ofMonths(6), Period.ofMonths(12), Period.ofMonths(60)};
    Tenor[] tenors = new Tenor[] {Tenor.TENOR_1Y, Tenor.TENOR_10Y};
    double[] moneyness = new double[] {-0.0050, 0, 0.0100};
    for (int loopexp = 0; loopexp < expiries.length; loopexp++) {
      LocalDate expiryDate = EUTA_IMPL.nextOrSame(VALUATION_DATE.plus(expiries[loopexp]));
      ResolvedSwapTrade swapMax = EUR_FIXED_1Y_EURIBOR_3M
          .createTrade(expiryDate, tenors[tenors.length - 1], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
      List<LocalDate> iborDates = new ArrayList<>();
      ImmutableList<SwapPaymentPeriod> iborLeg = swapMax.getProduct().getLegs().get(1).getPaymentPeriods();
      iborDates.add(iborLeg.get(0).getStartDate());
      for (SwapPaymentPeriod period : iborLeg) {
        iborDates.add(period.getEndDate());
      }
      for (int looptenor = 0; looptenor < tenors.length; looptenor++) {
        ResolvedSwapTrade swap0 = EUR_FIXED_1Y_EURIBOR_3M
            .createTrade(expiryDate, tenors[looptenor], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
        double parRate = PRICER_SWAP.parRate(swap0.getProduct(), MULTICURVE_EUR);
        for (int loopmoney = 0; loopmoney < moneyness.length; loopmoney++) {
          for (int loopPayRec = 0; loopPayRec < 2; loopPayRec++) {
            SwapTrade swap = EUR_FIXED_1Y_EURIBOR_3M
                .createTrade(expiryDate, tenors[looptenor],
                    (loopPayRec == 0) ? BuySell.BUY : BuySell.SELL, NOTIONAL, parRate + moneyness[loopmoney],
                    REF_DATA);
            double[] ivApprox = new double[2];
            for (int looplongshort = 0; looplongshort < 2; looplongshort++) {
              Swaption swaptionPayLong = Swaption.builder()
                  .expiryDate(AdjustableDate.of(expiryDate)).expiryTime(VALUATION_TIME).expiryZone(VALUATION_ZONE)
                  .longShort((looplongshort == 0) ? LongShort.LONG : LongShort.SHORT)
                  .swaptionSettlement(PhysicalSwaptionSettlement.DEFAULT)
                  .underlying(swap.getProduct()).build();
              ResolvedSwaption swaptionResolved = swaptionPayLong.resolve(REF_DATA);
              CurrencyAmount pvApprox =
                  PRICER_SWPT_G2PP_APPROX.presentValue(swaptionResolved, MULTICURVE_EUR, PARAMETERS);
              CurrencyAmount pvNi =
                  PRICER_SWPT_G2PP_NI.presentValue(swaptionResolved, MULTICURVE_EUR, PARAMETERS);
              assertThat(pvApprox.getCurrency()).isEqualTo(pvNi.getCurrency());
//              System.out
//                  .println(expiries[loopexp].toString() + tenors[looptenor] + moneyness[loopmoney] + ", " + pvApprox +
//                      ", " + pvNi + ", " + (pvNi.getAmount() - pvApprox.getAmount()));
              ivApprox[looplongshort] = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT,
                      pvApprox.getAmount());
              double ivNi = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT, pvNi.getAmount());
//              System.out
//                  .println(expiries[loopexp].toString() + tenors[looptenor] + moneyness[loopmoney]
//                      + ((loopPayRec == 0) ? BuySell.BUY : BuySell.SELL)
//                      + ((looplongshort == 0) ? LongShort.LONG : LongShort.SHORT)
//                      + ", " + ivApprox[looplongshort] +
//                      ", " + ivNi + ", " + (ivNi - ivApprox[looplongshort]));
              assertThat(ivApprox[looplongshort]).isEqualTo(ivNi, TOLERANCE_IV); // Compare implied volatilities
            } // end long/short
            assertThat(ivApprox[0]).isEqualTo(ivApprox[1], TOLERANCE_IV); // Long/short
          } // end pay/receive
        } // end loopmoney
      } // end looptenor
    } // end loopexp
  }

  /* Compare degenerated G2++ with Hull-White 1-factor */
  @Test
  public void pv_g2pp_v_hw() {
    Period[] expiries = new Period[] {Period.ofMonths(6), Period.ofMonths(12), Period.ofMonths(60)};
    Tenor[] tenors = new Tenor[] {Tenor.TENOR_1Y, Tenor.TENOR_10Y};
    double[] moneyness = new double[] {-0.0050, 0, 0.0100};
    for (int loopexp = 0; loopexp < expiries.length; loopexp++) {
      LocalDate expiryDate = EUTA_IMPL.nextOrSame(VALUATION_DATE.plus(expiries[loopexp]));
      ResolvedSwapTrade swapMax = EUR_FIXED_1Y_EURIBOR_3M
          .createTrade(expiryDate, tenors[tenors.length - 1], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
      List<LocalDate> iborDates = new ArrayList<>();
      ImmutableList<SwapPaymentPeriod> iborLeg = swapMax.getProduct().getLegs().get(1).getPaymentPeriods();
      iborDates.add(iborLeg.get(0).getStartDate());
      for (SwapPaymentPeriod period : iborLeg) {
        iborDates.add(period.getEndDate());
      }
      for (int looptenor = 0; looptenor < tenors.length; looptenor++) {
        ResolvedSwapTrade swap0 = EUR_FIXED_1Y_EURIBOR_3M
            .createTrade(expiryDate, tenors[looptenor], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
        double parRate = PRICER_SWAP.parRate(swap0.getProduct(), MULTICURVE_EUR);
        for (int loopmoney = 0; loopmoney < moneyness.length; loopmoney++) {
          for (int loopPayRec = 0; loopPayRec < 2; loopPayRec++) {
            SwapTrade swap = EUR_FIXED_1Y_EURIBOR_3M
                .createTrade(expiryDate, tenors[looptenor],
                    (loopPayRec == 0) ? BuySell.BUY : BuySell.SELL, NOTIONAL, parRate + moneyness[loopmoney],
                    REF_DATA);
            double[] ivG2pp1 = new double[2];
            for (int looplongshort = 0; looplongshort < 2; looplongshort++) {
              Swaption swaptionPayLong = Swaption.builder()
                  .expiryDate(AdjustableDate.of(expiryDate)).expiryTime(VALUATION_TIME).expiryZone(VALUATION_ZONE)
                  .longShort((looplongshort == 0) ? LongShort.LONG : LongShort.SHORT)
                  .swaptionSettlement(PhysicalSwaptionSettlement.DEFAULT)
                  .underlying(swap.getProduct()).build();
              ResolvedSwaption swaptionResolved = swaptionPayLong.resolve(REF_DATA);
              CurrencyAmount pvG2pp1 =
                  PRICER_SWPT_G2PP_APPROX.presentValue(swaptionResolved, MULTICURVE_EUR, PARAMETERS_G2PP_DEG_1);
              CurrencyAmount pvHw1 =
                  PRICER_SWAPTION_HW.presentValue(swaptionResolved, MULTICURVE_EUR, PROVIDER_HW_1);
              assertThat(pvG2pp1.getCurrency()).isEqualTo(pvHw1.getCurrency());
              ivG2pp1[looplongshort] = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT,
                      pvG2pp1.getAmount());
              double ivHw1 = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT, pvHw1.getAmount());
//              System.out
//                  .println(expiries[loopexp].toString() + tenors[looptenor] + moneyness[loopmoney]
//                      + ((loopPayRec == 0) ? BuySell.BUY : BuySell.SELL)
//                      + ((looplongshort == 0) ? LongShort.LONG : LongShort.SHORT)
//                      + ", " + ivG2pp1[looplongshort] +
//                      ", " + ivHw1 + ", " + (ivHw1 - ivG2pp1[looplongshort]));
              assertThat(ivG2pp1[looplongshort]).isEqualTo(ivHw1, TOLERANCE_IV); // Compare implied volatilities
              CurrencyAmount pvG2pp2 =
                  PRICER_SWPT_G2PP_APPROX.presentValue(swaptionResolved, MULTICURVE_EUR, PARAMETERS_G2PP_DEG_2);
              CurrencyAmount pvHw2 =
                  PRICER_SWAPTION_HW.presentValue(swaptionResolved, MULTICURVE_EUR, PROVIDER_HW_2);
              assertThat(pvG2pp2.getCurrency()).isEqualTo(pvHw2.getCurrency());
              double ivG2pp2 = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT, pvG2pp2.getAmount());
              double ivHw2 = PRICER_SWAPTION_BACHELIER
                  .impliedVolatilityFromPresentValue(swaptionResolved, MULTICURVE_EUR, G2PP_DAYCOUNT, pvHw2.getAmount());
              assertThat(ivG2pp2).isEqualTo(ivHw2, TOLERANCE_IV); // Compare implied volatilities
            } // end long/short
            assertThat(ivG2pp1[0]).isEqualTo(ivG2pp1[1], TOLERANCE_IV); // Long/short
          } // end pay/receive
        } // end loopmoney
      } // end looptenor
    } // end loopexp
  }

//@Ignore // Test performance. Does not run in the standard unit test.
//  @Test
//  public void performance() {
//    // Previous run results (1,800 swaptions): Approximation 50 ms / NI-2D 115,000 ms
//    long start, end;
//    int nbRep = 100;
//    int nbRep2 = 5;
//    Period[] expiries = new Period[] {Period.ofMonths(6), Period.ofMonths(12), Period.ofMonths(60)};
//    Tenor[] tenors = new Tenor[] {Tenor.TENOR_1Y, Tenor.TENOR_10Y};
//    double[] moneyness = new double[] {-0.0050, 0, 0.0100};
//    // Create instruments
//    ResolvedSwaption[][][] swaptionsResolved = new ResolvedSwaption[expiries.length][tenors.length][moneyness.length];
//    for (int loopexp = 0; loopexp < expiries.length; loopexp++) {
//      LocalDate expiryDate = EUTA_IMPL.nextOrSame(VALUATION_DATE.plus(expiries[loopexp]));
//      ResolvedSwapTrade swapMax = EUR_FIXED_1Y_EURIBOR_3M
//          .createTrade(expiryDate, tenors[tenors.length - 1], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
//      List<LocalDate> iborDates = new ArrayList<>();
//      ImmutableList<SwapPaymentPeriod> iborLeg = swapMax.getProduct().getLegs().get(1).getPaymentPeriods();
//      iborDates.add(iborLeg.get(0).getStartDate());
//      for (SwapPaymentPeriod period : iborLeg) {
//        iborDates.add(period.getEndDate());
//      }
//      for (int looptenor = 0; looptenor < tenors.length; looptenor++) {
//        ResolvedSwapTrade swap0 = EUR_FIXED_1Y_EURIBOR_3M
//            .createTrade(expiryDate, tenors[looptenor], BuySell.BUY, NOTIONAL, 0.0d, REF_DATA).resolve(REF_DATA);
//        double parRate = PRICER_SWAP.parRate(swap0.getProduct(), MULTICURVE_EUR);
//        for (int loopmoney = 0; loopmoney < moneyness.length; loopmoney++) {
//          SwapTrade swap = EUR_FIXED_1Y_EURIBOR_3M
//              .createTrade(expiryDate, tenors[looptenor], BuySell.BUY, NOTIONAL, parRate + moneyness[loopmoney],
//                  REF_DATA);
//          Swaption swaption = Swaption.builder()
//              .expiryDate(AdjustableDate.of(expiryDate)).expiryTime(VALUATION_TIME).expiryZone(VALUATION_ZONE)
//              .longShort(LongShort.LONG)
//              .swaptionSettlement(PhysicalSwaptionSettlement.DEFAULT)
//              .underlying(swap.getProduct()).build();
//          swaptionsResolved[loopexp][looptenor][loopmoney] = swaption.resolve(REF_DATA);
//        } // end loopmoney
//      } // end looptenor
//    } // end loopexp
//
//    // Approx
//    for (int j = 0; j < nbRep2; j++) {
//      start = System.currentTimeMillis();
//      double testLmm = 0.0;
//      for (int i = 0; i < nbRep; i++) {
//        for (int loopexp = 0; loopexp < expiries.length; loopexp++) {
//          for (int looptenor = 0; looptenor < tenors.length; looptenor++) {
//            for (int loopmoney = 0; loopmoney < moneyness.length; loopmoney++) {
//              CurrencyAmount pvApprox = PRICER_SWPT_G2PP_APPROX
//                  .presentValue(swaptionsResolved[loopexp][looptenor][loopmoney], MULTICURVE_EUR, PARAMETERS);
//              testLmm += pvApprox.getAmount();
//            } // end loopmoney
//          } // end looptenor
//        } // end loopexp
//      }
//      end = System.currentTimeMillis();
//      System.out.println("G2++ approx computation time: " + (end - start) + " ms. (" +
//          (nbRep * expiries.length * tenors.length * moneyness.length) + " computations) " + testLmm);
//
//      // NI-2D
//      start = System.currentTimeMillis();
//      double testHW = 0.0;
//      for (int i = 0; i < nbRep; i++) {
//        for (int loopexp = 0; loopexp < expiries.length; loopexp++) {
//          for (int looptenor = 0; looptenor < tenors.length; looptenor++) {
//            for (int loopmoney = 0; loopmoney < moneyness.length; loopmoney++) {
//              CurrencyAmount pvHw = PRICER_SWPT_G2PP_NI
//                  .presentValue(swaptionsResolved[loopexp][looptenor][loopmoney], MULTICURVE_EUR, PARAMETERS);
//              testHW += pvHw.getAmount();
//            } // end loopmoney
//          } // end looptenor
//        } // end loopexp
//      }
//      end = System.currentTimeMillis();
//      System.out.println("G2++ NI-2D computation time: " + (end - start) + " ms. (" +
//          (nbRep * expiries.length * tenors.length * moneyness.length) + " computations) " + testHW);
//    }
//  }

}


text:
var canvas_width;
var canvas_height;
var paper;

function initCanvas(container, width, height) {
	canvas_width = width;
	canvas_height = height;
	paper = Raphael(container, canvas_width, canvas_height);

}

function drawTurtle(data) {
	var moves = data["moves"];
	var angle = data["angle"];

	var middle_x = canvas_width / 2;
	var middle_y = canvas_height / 2;

	paper.clear();

	paper.circle(middle_x, middle_y, 5).attr({"fill": "green", "stroke": "green"});
	var x = middle_x;
	var y = middle_y;
	path = "M " + middle_x + " " + middle_y
	for (var move in moves) {
		x = x + moves[move][0];
		y = y + moves[move][1];
		path = path + "L " + x + " " + y;
	}
	paper.path(path).attr({"stroke-width": "3px","stroke": "green"});
	turtle = paper.image("static/turtle.png", x-16, y-16, 32, 32);
	turtle.rotate(angle);
}


text:
class CreateSpreeSuppliersTable < ActiveRecord::Migration
  def change
    create_table :spree_suppliers do |t|
      t.string :company, :null => false
      t.string :name
      t.string :address1
      t.string :address2
      t.string :city
      t.string :zipcode
      t.string :phone_number
      t.string :mobile_number
      t.string :email
      t.string :website
      t.references :state
      t.references :country
      t.timestamps
    end
  end
end


text:
<!DOCTYPE html>

  <title>codemade</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href='http://fonts.googleapis.com/css?family=Raleway:400,300,600' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Lobster+Two:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
  <link type="text/css" rel="stylesheet" href="site.css"/>

codemade

        René Viering

        Christian Kühl

Software-Developer

JavaScript, Node/IO, CQRS, Event Sourcing, Event Storming

        Caffeine - A simple coffee store web application, built with React, Flux, and Node.js.

        Github Repository, Demo

        Webmontag Kassel:

Session "ReactJS" (Slides)

Session "FLUX" (Slides)


text:
layout: model
title: English BertForTokenClassification Cased model (from Maaly)
author: John Snow Labs
name: bert_ner_body_site
date: 2022-08-02
tags: [bert, ner, open_source, en]
task: Named Entity Recognition
language: en
edition: Spark NLP 4.1.0
spark_version: 3.0
supported: true
annotator: BertForTokenClassification
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained BertForTokenClassification model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `body-site` is a English model originally trained by `Maaly`.

## Predicted Entities

`anatomy`

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/bert_ner_body_site_en_4.1.0_3.0_1659456011938.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = DocumentAssembler() \
        .setInputCol("text") \
        .setOutputCol("document")

sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")\
       .setInputCols(["document"])\
       .setOutputCol("sentence")

tokenizer = Tokenizer() \
    .setInputCols("sentence") \
    .setOutputCol("token")

tokenClassifier = BertForTokenClassification.pretrained("bert_ner_body_site","en") \
    .setInputCols(["sentence", "token"]) \
    .setOutputCol("ner")

pipeline = Pipeline(stages=[documentAssembler, sentenceDetector, tokenizer, tokenClassifier])

data = spark.createDataFrame([["PUT YOUR STRING HERE"]]).toDF("text")

result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new DocumentAssembler()
          .setInputCol("text")
          .setOutputCol("document")

val sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")
       .setInputCols(Array("document"))
       .setOutputCol("sentence")

val tokenizer = new Tokenizer()
    .setInputCols(Array("sentence"))
    .setOutputCol("token")

val tokenClassifier = BertForTokenClassification.pretrained("bert_ner_body_site","en")
    .setInputCols(Array("sentence", "token"))
    .setOutputCol("ner")

val pipeline = new Pipeline().setStages(Array(documentAssembler,sentenceDetector, tokenizer, tokenClassifier))

val data = Seq("PUT YOUR STRING HERE").toDF("text")

val result = pipeline.fit(data).transform(data)
```
</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|bert_ner_body_site|
|Compatibility:|Spark NLP 4.1.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document, token]|
|Output Labels:|[ner]|
|Language:|en|
|Size:|404.0 MB|
|Case sensitive:|true|
|Max sentence length:|128|

## References

- https://huggingface.co/Maaly/body-site
- https://gitlab.com/maaly7/emerald_metagenomics_annotations


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Stumps.Startup")]
[assembly: AssemblyDescription("Stumps Application")]
[assembly: AssemblyConfiguration("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ae9efa41-4aaa-4568-9611-7a9b03d13c47")]


text:
<?php

namespace Group4\ChallengeBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * VoteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VoteRepository extends EntityRepository
{

}