text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* WriteRecordCommand.cs -- create or update many records
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: moderate
 *
 * TODO determine max MFN
 */

#region Using directives

using AM;
using AM.Collections;
using AM.Logging;

using CodeJam;

using JetBrains.Annotations;

using ManagedIrbis.ImportExport;

using MoonSharp.Interpreter;

#endregion

namespace ManagedIrbis.Infrastructure.Commands
{
    /// <summary>
    /// Create or update many records simultaneously.
    /// </summary>
    [PublicAPI]
    [MoonSharpUserData]
    public sealed class WriteRecordsCommand
        : AbstractCommand
    {
        #region Properties

        /// <summary>
        /// Need actualize?
        /// </summary>
        public bool Actualize { get; set; }

        /// <summary>
        /// Need lock?
        /// </summary>
        public bool Lock { get; set; }

        /// <summary>
        /// Records to write.
        /// </summary>
        [NotNull]
        public NonNullCollection<RecordReference> References
        {
            get { return _references; }
        }

        #endregion

        #region Construction

        /// <summary>
        /// Constructor.
        /// </summary>
        public WriteRecordsCommand
            (
                [NotNull] IIrbisConnection connection
            )
            : base(connection)
        {
            _references = new NonNullCollection<RecordReference>();
        }

        #endregion

        #region Private members

        private readonly NonNullCollection<RecordReference> _references;

        #endregion

        #region Public methods

        #endregion

        #region AbstractCommand members

        /// <inheritdoc cref="AbstractCommand.CreateQuery" />
        public override ClientQuery CreateQuery()
        {
            ClientQuery result = base.CreateQuery();
            result.CommandCode = CommandCode.SaveRecordGroup;

            if (References.Count == 0)
            {
                Log.Error
                    (
                        "WriteRecordsCommand::CreateQuery: "
                        + "no records given"
                    );

                throw new IrbisNetworkException("no records given");
            }

            if (References.Count >= IrbisConstants.MaxPostings)
            {
                Log.Error
                    (
                        "WriteRecordsCommand::CreateQuery: "
                        + "too many records"
                    );

                throw new IrbisNetworkException("too many records");
            }

            result
                .Add(Lock)
                .Add(Actualize);

            foreach (RecordReference reference in References)
            {
                if (ReferenceEquals(reference.Record, null))
                {
                    Log.Error
                        (
                            "WriteRecordsCommand::CreateQuery: "
                            + "record is null"
                        );

                    throw new IrbisException("record is null");
                }

                if (ReferenceEquals(reference.Database, null))
                {
                    reference.Database = reference.Record.Database;
                }

                if (ReferenceEquals(reference.Database, null))
                {
                    Log.Error
                    (
                        "WriteRecordsCommand::CreateQuery: "
                        + "database not set"
                    );

                    throw new IrbisException("database not set");
                }

                if (string.IsNullOrEmpty(reference.Record.Database))
                {
                    reference.Record.Database = reference.Database;
                }

                result.Add(reference);
            }

            return result;
        }

        /// <inheritdoc cref="AbstractCommand.Execute" />
        public override ServerResponse Execute
            (
                ClientQuery query
            )
        {
            Code.NotNull(query, "query");

            ServerResponse result = base.Execute(query);

            result.GetReturnCode();

            // ReSharper disable AssignNullToNotNullAttribute
            // ReSharper disable PossibleNullReferenceException
            // ReSharper disable ForCanBeConvertedToForeach
            for (int i = 0; i < References.Count; i++)
            {
                ProtocolText.ParseResponseForWriteRecords
                    (
                        result,
                        References[i].Record
                    );

                References[i].Mfn = References[i].Record.Mfn;
            }
            // ReSharper restore ForCanBeConvertedToForeach
            // ReSharper restore PossibleNullReferenceException
            // ReSharper restore AssignNullToNotNullAttribute

            return result;
        }

        #endregion

        #region IVerifiable members

        /// <inheritdoc cref="IVerifiable.Verify" />
        public override bool Verify
            (
                bool throwOnError
            )
        {
            Verifier<WriteRecordsCommand> verifier
                = new Verifier<WriteRecordsCommand>
                    (
                        this,
                        throwOnError
                    );

            verifier
                .Assert
                (
                    References.Count < IrbisConstants.MaxPostings,
                    "References.Count"
                );

            foreach (RecordReference reference in References)
            {
                // TODO fix reference.Verify for WriteRecordCommand
                // reference.Verify(throwOnError);
                verifier.NotNull(reference.Record, "record");
            }

            return verifier.Result;
        }

        #endregion
    }
}


text:
from .application import application
from .controllers import *

redpajama_set_name: RedPajamaGithub


text:
title: PapljTokenElementTypes.ABRACK_L - aesi-intellij
---

[aesi-intellij](../../index.html) / [org.metaborg.paplj.psi](../index.html) / [PapljTokenElementTypes](index.html) / [ABRACK_L](.)

# ABRACK_L

`@JvmField val ABRACK_L: IElementType`


text:
namespace TAO_PEGTL_NAMESPACE
{
   template< typename NewState >
   struct change_state
      : maybe_nothing
   {
      template< typename Rule,
                apply_mode A,
                rewind_mode M,
                template< typename... >
                class Action,
                template< typename... >
                class Control,
                typename ParseInput,
                typename... States >
      [[nodiscard]] static bool match( ParseInput& in, States&&... st )
      {
         NewState s( static_cast< const ParseInput& >( in ), st... );
         if( TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, s ) ) {
            if constexpr( A == apply_mode::action ) {
               Action< Rule >::success( static_cast< const ParseInput& >( in ), s, st... );
            }
            return true;
         }
         return false;
      }

      template< typename ParseInput,
                typename... States >
      static void success( const ParseInput& in, NewState& s, States&&... st ) noexcept( noexcept( s.success( in, st... ) ) )
      {
         s.success( in, st... );
      }
   };

}  // namespace TAO_PEGTL_NAMESPACE

#endif


text:
<!DOCTYPE html>

	<title>Authorizing APIs</title>

API: <select type="text" id="apiName"></select>

Client ID: <input type="text" id="clientId" />

Client Secret: <input type="text" id="clientSecret"  />

	<input type="button" id="buttonSubmit" value="Submit" />

Authenticating on APIs

This page will allow to authenticate on any APIs whose handlers are subclasses of the AssistantHandlerWithAuthCode class.

You need to create your own Client IDs and Secrets in the APIs.

When creating your client ID and secret make sure to set the redirect URI to redirect uri

Some examples where you can create these:

Spotify

Google APIs - click on Create Credentials->OAuth client Id->Web Application


text:
package com.alibaba.otter.shared.arbitrate.impl.setl;

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

import org.I0Itec.zkclient.exception.ZkException;
import org.I0Itec.zkclient.exception.ZkNoNodeException;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.alibaba.otter.shared.arbitrate.exception.ArbitrateException;
import com.alibaba.otter.shared.arbitrate.impl.ArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.helper.RemedyIndexComparator;
import com.alibaba.otter.shared.arbitrate.impl.setl.helper.StagePathUtils;
import com.alibaba.otter.shared.arbitrate.impl.setl.monitor.PermitMonitor;
import com.alibaba.otter.shared.arbitrate.impl.zookeeper.ZooKeeperClient;
import com.alibaba.otter.shared.arbitrate.model.RemedyIndexEventData;
import com.alibaba.otter.shared.arbitrate.model.SyncStatusEventData;
import com.alibaba.otter.shared.common.utils.JsonUtils;
import com.alibaba.otter.shared.common.utils.zookeeper.ZkClientx;

/**
 * 为setl提供辅助工具的event事件
 *
 * @author jianghang 2011-10-18 上午10:17:18
 * @version 4.0.0
 */
public class ToolArbitrateEvent implements ArbitrateEvent {

    private static final Logger logger    = LoggerFactory.getLogger(ToolArbitrateEvent.class);
    private ZkClientx           zookeeper = ZooKeeperClient.getInstance();

    /**
     * 阻塞等待授权通过
     *
     * @param pipelineId
     * @throws InterruptedException
     */
    public void waitForPermit(Long pipelineId) throws InterruptedException {
        Assert.notNull(pipelineId);

        PermitMonitor permitMonitor = ArbitrateFactory.getInstance(pipelineId, PermitMonitor.class);
        permitMonitor.waitForPermit();// 阻塞等待授权
    }

    /**
     * 提供数据接口获取对应pipeline上的状态
     */
    public SyncStatusEventData fetch(Long pipelineId) {
        String path = StagePathUtils.getPipeline(pipelineId);
        try {
            byte[] bytes = zookeeper.readData(path);
            if (bytes == null || bytes.length == 0) {
                SyncStatusEventData evnetData = new SyncStatusEventData();
                evnetData.setPipelineId(pipelineId);
                return evnetData;
            } else {
                return JsonUtils.unmarshalFromByte(bytes, SyncStatusEventData.class);
            }
        } catch (ZkException e) {
            // 没有节点返回空
            throw new ArbitrateException("fetch_SyncStatus", pipelineId.toString(), e);
        }
    }

    /**
     * 提供数据接口更新对应的pipeline上的状态
     */
    public void single(SyncStatusEventData syncStatus) {
        String path = StagePathUtils.getPipeline(syncStatus.getPipelineId());
        try {
            byte[] bytes = JsonUtils.marshalToByte(syncStatus);
            zookeeper.writeData(path, bytes);
            logger.info("## single status : " + syncStatus);
        } catch (ZkException e) {
            throw new ArbitrateException("single_SyncStatus", syncStatus.getPipelineId().toString(), e);
        }
    }

    /**
     * 添加一个index节点
     */
    public void addRemedyIndex(RemedyIndexEventData data) {
        String path = StagePathUtils.getRemedyRoot(data.getPipelineId());
        try {
            zookeeper.create(path + "/" + RemedyIndexEventData.formatNodeName(data), new byte[] {},
                             CreateMode.PERSISTENT);
        } catch (ZkNodeExistsException e) {
            // ignore
        } catch (ZkException e) {
            throw new ArbitrateException("addRemedyIndex", data.getPipelineId().toString(), e);
        }
    }

    /**
     * 删除一个index节点
     */
    public void removeRemedyIndex(RemedyIndexEventData data) {
        String path = StagePathUtils.getRemedyRoot(data.getPipelineId());
        try {
            zookeeper.delete(path + "/" + RemedyIndexEventData.formatNodeName(data));
        } catch (ZkNoNodeException e) {
            // ignore
        } catch (ZkException e) {
            throw new ArbitrateException("removeRemedyIndex", data.getPipelineId().toString(), e);
        }
    }

    /**
     * 查询当前的remedy index记录
     */
    public List<RemedyIndexEventData> listRemedyIndexs(Long pipelineId) {
        String path = StagePathUtils.getRemedyRoot(pipelineId);
        List<RemedyIndexEventData> datas = new ArrayList<RemedyIndexEventData>();
        try {
            List<String> nodes = zookeeper.getChildren(path);
            for (String node : nodes) {
                RemedyIndexEventData data = RemedyIndexEventData.parseNodeName(node);
                data.setPipelineId(pipelineId);
                datas.add(data);
            }
        } catch (ZkException e) {
            throw new ArbitrateException("listRemedyIndexs", pipelineId.toString(), e);
        }

        Collections.sort(datas, new RemedyIndexComparator()); // 做一下排序
        return datas;
    }

    /**
     * 释放对应的pipeline资源,是个同步调用
     */
    public void release(Long pipelineId) {
        ArbitrateFactory.destory(pipelineId);
    }

    public void release() {
        ArbitrateFactory.destory();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scripty.MsBuild
{
	class Utils
	{
		private const char QUOTE_CHAR = '"';

		static void SkipBlanks(ref int index, string csvString)
		{
			while (index < csvString.Length &&
				csvString[index] == ' ')
				index++;
		}

		public static List<string> AsList(string csvString, IEnumerable<char> separators = null, char escapeChar = '\\', bool skipBlanks = true)
		{
			HashSet<char> seps;
			if (separators == null)
			{
				seps = new HashSet<char>();
				seps.Add(';');
			}
			else
				seps = new HashSet<char>(separators);

			bool quoteCharIsSame = escapeChar == QUOTE_CHAR;

				var list = new List<string>();
				bool markOn = false;
				csvString = skipBlanks ? csvString.Trim() : csvString;
				if (csvString.Length == 0)
					return list;
				int index = 0;
				StringBuilder s = new StringBuilder();
				bool ending = false;

				if (skipBlanks) SkipBlanks(ref index, csvString);

				bool inEscape = false;

				while (index < csvString.Length && !ending)
				{
					if (!inEscape && csvString[index] == QUOTE_CHAR)
					{
						// start quoted item
						if (!markOn && s.Length == 0)
							markOn = true;
						else
							// last quote
							if (index == csvString.Length - 1)
						{
							list.Add(s.ToString());
							s.Length = 0;
							markOn = false;
							ending = true;
						}
						else
						{   // part of item ?
							if (markOn)
							{
								// next quote mark for literal char
								if (quoteCharIsSame && csvString[index + 1] == '"')
								{
									s.Append('"');
									index++;
								}
								else
									// end quoted item
									markOn = false;
							}
							// not marked, is literal char
							else
								s.Append(QUOTE_CHAR);
						}
					}
					else if (!markOn && csvString[index] == '\r')
					{
						// ignore cr
					}
					else if (!markOn && csvString[index] == '\n')
					{
						ending = true; break; // end of line
					}
					else
					{
						// check separator
						if (seps.Contains(csvString[index]))
						{
							// delimiter is part of string
							if (markOn)
								s.Append(csvString[index]);
							else
							{
								list.Add(s.ToString());
								s.Length = 0;
								markOn = false;
								index++; // after ;
								if (skipBlanks) SkipBlanks(ref index, csvString);
								continue; // don't jump to increment index
							}
						}
						else if (markOn && !inEscape && csvString[index] == escapeChar)
						{
							inEscape = true;
						}
						else
						{
							inEscape = false;
							s.Append(csvString[index]);
						}
					}
					index++;
				}

				// if line ends without Delimiter
				if (s.Length > 0)
					list.Add(s.ToString());
				return list;
			}
	}
}


text:
<?php

class Profile extends \HXPHP\System\Model
{
	static function table_name()
	{
		return 'profiles';
	}

  //Relacionamnetos 1:1 entre as tabelas
  static $belongs_to = array(
    array('pattern', 'foreign_key' => 'profile_id', 'class_name' => 'Pattern'),
    array('opportunity', 'foreign_key' => 'profile_id', 'class_name' => 'Opportunity')
  );

  //Relacionamnetos 1:n entre as tabelas
  static $has_many = array(
    array('definitions')
  );

  public static function backProfile($idProfile)
  {
    $respostaspl = Pattern::find_by_profile_id($idProfile);
    $pesos = array();

    for ($i=1; $i < 16 ; $i++) {
      $questao = 'answer_' . $i; //concatena a expresão com o contador, para formar o campo
      $valor = $respostaspl->$questao; //recupera a opção do Analista na Patterns
      $quesito = Parameter::find_by_id($i); //Recupera o Atributo (Idioma, Experiencia...)
      $weigths = $quesito->weight_id; //ID do Atributo a ser recuperado o peso
      $pesosRecuperados = Weight::find_by_id($weigths);//Recupera os Pesos do Atributo
      $opcao = 'option_' . $valor; //Concatena a expressao com a Opcao Selecionada p/Usuario
      $pesos[$i-1] = $pesosRecuperados->$opcao; //Array com os Pesos do Analista
    }
    return $pesos;
  }

  public static function backUserWeights($idUser){
    $respostasusuario = Answer::find_by_user_id($idUser);
    $pesos_usuario = array();

    for ($i=1; $i < 16 ; $i++) {
      $questao = 'question_' . $i; //concatena a expresão com o contador, para formar o campo
      $valor = $respostasusuario->$questao; //recupera a opção selecionada pelo Usuario na Answers
      $quesito = Parameter::find_by_id($i); //Recupera o Atributo (Idioma, Experiencia...)
      $weigths = $quesito->weight_id; //ID do Atributo a ser recuperado o peso
      $pesosRecuperados = Weight::find_by_id($weigths);//Recupera os Pesos do Atributo
      $opcaoUser = 'option_' . $valor; //Concatena a expressao com a Opcao Selecionada p/Usuario
      $pesos_usuario[$i-1] = $pesosRecuperados->$opcaoUser; //Array com os Pesos do Usuario
    }
    return $pesos_usuario;
  }

  public static function backChargeWeights($idAttribute){
    $atributosVaga = Attribute::find_by_id($idAttribute);
    $pesos_vaga = array();

    for ($i=1; $i < 16 ; $i++) {
      $atributo = 'attribute_' . $i; //concatena a expresão com o contador, para formar o campo
      $valor = $atributosVaga->$atributo; //recupera a opção selecionada pelo Usuario na Answers
      $quesito = Parameter::find_by_id($i); //Recupera o Atributo (Idioma, Experiencia...)
      $weigths = $quesito->weight_id; //ID do Atributo a ser recuperado o peso
      $pesosRecuperados = Weight::find_by_id($weigths);//Recupera os Pesos do Atributo
      $opcaoUser = 'option_' . $valor; //Concatena a expressao com a Opcao Selecionada p/Usuario
      $pesos_vaga[$i-1] = $pesosRecuperados->$opcaoUser; //Array com os Pesos do Usuario
    }
    return $pesos_vaga;
  }

  public static function calculoPesos($peso, $pesoProfile, $pesoUsuario)
  {
    return $valor = ($peso * abs ($pesoProfile - $pesoUsuario)**2);
  }

  public static function calculoFinal($pesos_usuario, $pesos_analista)
  {
   $calcularPesos = 0.0000;
    for ($i=0; $i < 15; $i++) {
      $idParameter = Parameter::find_by_id($i+1);
      $pesoDominio = $idParameter->heft;
      $pesoU = $pesos_usuario[$i];
      $pesoA = $pesos_analista[$i];
      $valor = self::calculoPesos($pesoDominio, $pesoU, $pesoA);
      $calcularPesos = $calcularPesos + $valor;
    }
    $calcularPesos = ($calcularPesos**(1/2));
    return $calcularPesos;
  }

   public static function defineProfile($pesos_usuario)
   {
    $profilesAll = Profile::all();//Recuper Perfis Padrões (Junior, Pleno e Sênior)
    $ctr = array();
    $ctr[0] = 0.00;

      foreach ($profilesAll as $profile) {
         $type = $profile->type;
         $pesos = self::backProfile($type);
         $callBack = self::calculoFinal($pesos_usuario, $pesos);

         if($callBack == 0){ //Verfica se Cálculo Retorna Desvio Padrão 0.00
           $ctr[0] = $callBack;//caso desvio 0.00 já define o perfil
           $ctr[1] = $type;
           break;//Interrompe a análise e retorna $ctr (Desvio Padrão e Tipo Perfil)
         }
         if ($ctr[0] == 0.00) { //Primeiro verificação atribui os parametros
           $ctr[0] = $callBack;
           $ctr[1] = $type;
         }
         else if ($callBack <= $ctr[0]) { //Verifica se Desvio é < que atual armazenado
           $ctr[0] = $callBack; //Desvio Padrão
           $ctr[1] = $type; //Tipo de Perfil (1,2,3)
         }
      }
      return $ctr;
   }

   public static function recalculateProfile($id_usuario)
   {
      $callbackObj = new \stdClass;// Cria classe vazia
      $callbackObj->profile = null;// Propriedade user da classe null
      $callbackObj->status = false;// Propriedade Status da Classe False
      $callbackObj->errors = array();// Array padrão de erros vazio

      $pesos_backUser = Profile::backUserWeights($id_usuario);
      if (!$pesos_backUser) {
         array_push($callbackObj->errors, 'Oops! Não foi possível recuperar os parametros de cálculo do Perfil Informado. Por favor, revise informações e tente novamente');
         return $callbackObj;
      }

      $controle = Profile::defineProfile($pesos_backUser);
      if (!$controle) {
         array_push($callbackObj->errors, 'Oops! Não foi possível realizar o cálculo de definição do Perfil Informado. Por favor, revise informações e tente novamente');
         return $callbackObj;
      }

      $atualizarDefinition = Definition::atualizar($controle, $id_usuario);
      if ($atualizarDefinition) {
         $callbackObj->definition = $atualizarDefinition;
         $callbackObj->status = true;
         return $callbackObj;
      }

      $errors = $atualizarDefinition->errors->get_raw_errors();
      foreach ($errors as $field => $message) {
         array_push($callbackObj->errors, $message[0]);
      }
      return $callbackObj;
   }
}


text:
using OperationResult.Tags;

namespace OperationResult
{
    /// <summary>
    /// Status of operation (without Value and Error fields)
    /// </summary>
    public struct Status
    {
        private readonly bool _isSuccess;

        public bool IsSuccess => _isSuccess;
        public bool IsError => !_isSuccess;

        private Status(bool isSuccess)
        {
            _isSuccess = isSuccess;
        }

        public static implicit operator bool(Status status)
        {
            return status._isSuccess;
        }

        private static Status SuccessStatus = new Status(true);

        public static implicit operator Status(SuccessTag tag)
        {
            return SuccessStatus;
        }

        private static Status ErrorStatus = new Status(false);

        public static implicit operator Status(ErrorTag tag)
        {
            return ErrorStatus;
        }
    }

    /// <summary>
    /// Status of operation (without Value but with Error field)
    /// </summary>
    /// <typeparam name="TError">Type of Error field</typeparam>
    public struct Status<TError>
    {
        private readonly bool _isSuccess;

        public readonly TError Error;

        public bool IsSuccess => _isSuccess;
        public bool IsError => !_isSuccess;

        private Status(bool isSuccess)
        {
            _isSuccess = isSuccess;
            Error = default(TError);
        }

        private Status(TError error)
        {
            _isSuccess = false;
            Error = error;
        }

        public static implicit operator bool(Status<TError> status)
        {
            return status._isSuccess;
        }

        private static Status<TError> SuccessStatus = new Status<TError>(true);

        public static implicit operator Status<TError>(SuccessTag tag)
        {
            return SuccessStatus;
        }

        public static implicit operator Status<TError>(ErrorTag<TError> tag)
        {
            return new Status<TError>(tag.Error);
        }
    }

    /// <summary>
    /// Status of operation (without Value but with different Errors)
    /// </summary>
    /// <typeparam name="TError1">Type of first Error</typeparam>
    /// <typeparam name="TError2">Type of second Error</typeparam>
    public struct Status<TError1, TError2>
    {
        private readonly bool _isSuccess;

        public readonly object Error;

        public bool IsSuccess => _isSuccess;
        public bool IsError => !_isSuccess;

        public bool HasError<TError>() => Error is TError;
        public TError GetError<TError>() => (TError)Error;

        private Status(bool isSuccess)
        {
            _isSuccess = isSuccess;
            Error = null;
        }

        private Status(object error)
        {
            _isSuccess = false;
            Error = error;
        }

        public static implicit operator bool(Status<TError1, TError2> status)
        {
            return status._isSuccess;
        }

        private static Status<TError1, TError2> SuccessStatus = new Status<TError1, TError2>(true);

        public static implicit operator Status<TError1, TError2>(SuccessTag tag)
        {
            return SuccessStatus;
        }

        public static implicit operator Status<TError1, TError2>(ErrorTag<TError1> tag)
        {
            return new Status<TError1, TError2>(tag.Error);
        }

        public static implicit operator Status<TError1, TError2>(ErrorTag<TError2> tag)
        {
            return new Status<TError1, TError2>(tag.Error);
        }
    }

    /// <summary>
    /// Status of operation (without Value but with different Errors)
    /// </summary>
    /// <typeparam name="TError1">Type of first Error</typeparam>
    /// <typeparam name="TError2">Type of second Error</typeparam>
    /// <typeparam name="TError3">Type of third Error</typeparam>
    public struct Status<TError1, TError2, TError3>
    {
        private readonly bool _isSuccess;

        public readonly object Error;

        public bool IsSuccess => _isSuccess;
        public bool IsError => !_isSuccess;

        public bool HasError<TError>() => Error is TError;
        public TError GetError<TError>() => (TError)Error;

        private Status(bool isSuccess)
        {
            _isSuccess = isSuccess;
            Error = null;
        }

        private Status(object error)
        {
            _isSuccess = false;
            Error = error;
        }

        public static implicit operator bool(Status<TError1, TError2, TError3> status)
        {
            return status._isSuccess;
        }

        private static Status<TError1, TError2, TError3> SuccessStatus = new Status<TError1, TError2, TError3>(true);

        public static implicit operator Status<TError1, TError2, TError3>(SuccessTag tag)
        {
            return SuccessStatus;
        }

        public static implicit operator Status<TError1, TError2, TError3>(ErrorTag<TError1> tag)
        {
            return new Status<TError1, TError2, TError3>(tag.Error);
        }

        public static implicit operator Status<TError1, TError2, TError3>(ErrorTag<TError2> tag)
        {
            return new Status<TError1, TError2, TError3>(tag.Error);
        }

        public static implicit operator Status<TError1, TError2, TError3>(ErrorTag<TError3> tag)
        {
            return new Status<TError1, TError2, TError3>(tag.Error);
        }
    }
}


text:
#import <UIKit/UIKit.h>

#import "TrackerAppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([TrackerAppDelegate class]));
    }
}


text:
class HistoriesController < ApplicationController
  before_filter :login_required

  def add
    @goal = current_user.goals.find(params[:id])
    unless request.post?
      @history = @goal.histories.new :history_at => Time.now.strftime("%m/%d/%Y"), :style => 2
      return render :layout => false
    end
    @history = History.new params[:history]
    @history.before_number = @goal.current
    if params[:history][:style] == "1"
      @goal.current = params[:history][:number]
    else
      @goal.current += params[:history][:number].to_f
    end
    @history.after_number = @goal.current
    @goal.histories << @history
    @goal.save
    return render :layout => false, :text => "history added."
  end
end


text:
package org.finra.datagenerator.scaffolding.spark

import gremlin.scala._
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer
import org.apache.tinkerpop.gremlin.spark.process.computer.SparkGraphComputer
import org.finra.datagenerator.scaffolding.graph.{GraphFactoryService, GraphService}
import org.springframework.beans.factory.annotation.{Autowired, Value}
import org.springframework.stereotype.Service

/**
  * Created by dkopel on 9/20/16.
  */
trait SparkGraphService extends GraphService {
    lazy override val compute: GraphComputer = graph.compute(classOf[SparkGraphComputer])
}

@Service
class SparkGraphFactoryService @Autowired()(@Value("${spark.master:local[4]}") override val host: String) extends GraphFactoryService {

    override def existingGraph(location: String): GraphService = {
        new SparkGraphService {
            override val graph: ScalaGraph = SparkGraphConfiguration(host, Option.empty, Option(location)).graph
        }
    }

    override def newGraph(location: Option[String]=Option.empty): GraphService = {
        new SparkGraphService {
            override val graph: ScalaGraph = SparkGraphConfiguration(host, location).graph
        }
    }
}


text:
var TopologyAPI = {

    query: function(gremlinQuery) {
      return $.ajax({
        dataType: "json",
        url: '/api/topology',
        data: JSON.stringify({"GremlinQuery": gremlinQuery}),
        contentType: "application/json; charset=utf-8",
        method: 'POST',
      })
      .then(function(data) {
        // Result can be [Node] or [[Node, Node]]
        if (data.length > 0 && data[0] instanceof Array)
          data = data[0];
        return data;
      });
    }
};


text:
module Origen
  class Value
    # Handles a value represented by a string of hex character(s) [0-9, a-f, x, X, z, Z]
    #
    # This is
    #
    # * x when all the bits in a nibble are x
    # * X when some of the bits in a nibble are x, though the exact bit-level values are not known
    # * z when all the bits in a nibble are z
    # * Z when some of the bits in a nibble are z, though the exact bit-level values are not known
    #
    # Capital hex numbers will be accepted when defining the value, but they will be converted
    # to lower case
    class HexStrVal
      attr_reader :val, :size

      def initialize(value, options)
        @val = clean(value)
        if options[:size]
          @size = options[:size]
          # Trim any nibbles that are out of range...
          @val = val.split(//).last(size_in_nibbles).join
        else
          @size = (val.size * 4)
        end
      end

      def numeric?
        !!(val =~ /^[0-9a-f]+$/)
      end

      def to_i
        if numeric?
          val.to_i(16) & size.bit_mask
        end
      end

      def to_s
        "h#{val}"
      end

      # Returns the value of the given bit.
      # Return nil if out of range, otherwise 0, 1 or an X or Z object
      def [](index)
        unless index > (size - 1)
          if numeric?
            to_i[index]
          else
            # Get the nibble in question and re-align the index, if the bit falls in a numeric
            # part of the string we can still resolve to an integer
            nibble = nibble_of(index)
            nibble = val[val.size - 1 - nibble]
            if nibble.downcase == 'x'
              X.new
            elsif nibble.downcase == 'z'
              Z.new
            else
              nibble.to_i[index % 4]
            end
          end
        end
      end

      private

      def nibble_of(bit_number)
        bit_number / 4
      end

      # Rounds up to the nearest whole nibble
      def size_in_nibbles
        adder = size % 4 == 0 ? 0 : 1
        (size / 4) + adder
      end

      def clean(val)
        val = val.to_s.strip.to_s[1..-1]
        if valid?(val)
          if val =~ /[A-F]/
            val = val.gsub('A', 'a')
            val = val.gsub('B', 'b')
            val = val.gsub('C', 'c')
            val = val.gsub('D', 'd')
            val = val.gsub('E', 'e')
            val = val.gsub('F', 'f')
          end
          val.gsub('_', '')
        end
      end

      def valid?(val)
        if val =~ /^[0-9a-fA-F_xXzZ]+$/
          true
        else
          fail Origen::SyntaxError, 'Hex string values can only contain: 0-9, a-f, A-F, _, x, X, z, Z'
        end
      end
    end
  end
end


text:
Ext.define('OPF.core.component.form.SearchComboBox', {
    extend: 'OPF.core.component.form.FieldContainer',
    alias: ['widget.opf-searchcombo'],

    layout: 'anchor',

    name: null,          //association.name + '_' + associationModel.idProperty,
    fieldLabel: null,    //association.displayName || OPF.getSimpleClassName(association.model),
    subFieldLabel: null, //association.displayDescription,
    multiSelect: true,

    readOnly: false,

    model: null,
    validator: null,

    constructor: function(cfg) {
        cfg = cfg || {};
        this.addEvents(
            'onBeforeStoreLoad'
        );
        OPF.core.component.form.SearchComboBox.superclass.constructor.call(this, cfg);
    },

    initComponent: function() {
        var me = this;

        this.initializedModel = Ext.create(this.model);

        this.selectedItemsStore = Ext.create('Ext.data.Store', {
            model: this.model
        });

        var tpl;
        var searchFields;
        if (OPF.isNotEmpty(this.initializedModel.self.template)) {
            tpl = this.initializedModel.self.template.join('');
            searchFields = this.getFieldsFromTemplate();
        } else {
            tpl = '{' + this.initializedModel.displayProperty + '}';
            var field = me.findModelField(this.initializedModel, this.initializedModel.displayProperty);
            searchFields = [field];
        }
        var selectedItemTpl = new Ext.XTemplate(
//            '
',
            	'
',
                    '<tpl for=".">',
                        '
',
                            '
',
                                tpl,
                            '
',

                            '<tpl if="this.allowToDelete()">',
                                '

',
                            '</tpl>',

                        '
',
                    '</tpl>',
                '
',
//            '
'
            {
                disableFormats: true,
                // member functions:
                allowToDelete: function(){
                   return !me.readOnly;
                }
            }
        );

        this.selectedItemsView = Ext.create('Ext.view.View', {
            store: this.selectedItemsStore,
            tpl: selectedItemTpl,
            itemSelector: 'li.item-wrap',
            readOnly: this.readOnly,
            listeners: {
                itemclick: function (view, record, el, i, e) {
                    if (e.getTarget('.x-boxselect-item-close')) {
                        me.removeSelectSearchedItem(record);
                    }
                }
            }
        });

        this.searchComboStore = Ext.create('Ext.data.Store', {
            model: this.model,
            proxy: {
                type: 'ajax',
                url : this.initializedModel.self.restSuffixUrl + '/advanced-search',
                reader: {
                    type: 'json',
                    root: 'data'
                },
                startParam: 'offset',
                limitParam: 'limit'
            },
            pageSize: 10,
            autoLoad: false,
            listeners: {
                beforeload: function(store) {
                    var searchTerm = me.searchCombo.getRawValue();
                    me.fireEvent('onBeforeStoreLoad', me, store, searchTerm);
                }
            }
        });

        var comboValidator = OPF.isNotEmpty(this.validator) && Ext.isFunction(this.validator) ? this.validator : null;
        var searchComboConfig = {
            store: this.searchComboStore,
            excludeStore: this.selectedItemsStore,
            cls: 'opf-combo-field',
            anchor: '100%',
            valueField: this.initializedModel.idProperty,
            displayField: this.initializedModel.displayProperty,
            searchFields: searchFields,
            queryMode: 'remote',
            queryCaching: false,
            typeAhead: true,
            typeAheadDelay: 250,
            getParams: this.getParams,
            forceSelection: false,
            triggerAction: 'query',
            minChars: 0,
//            multiSelect: this.multiSelect,
            pageSize: 10,
            listeners: {
                select: this.selectSearchedItem,
                scope: this
            },
            listConfig: {
                loadingText: 'Searching...',
                emptyText: 'No matching items found.',
                getInnerTpl: function() {
                    return tpl;
                }
            },
            hidden: this.readOnly,
            validator: comboValidator
        };

        this.searchCombo = Ext.create('OPF.core.component.form.ComboBox', searchComboConfig);

        this.items = [
            this.selectedItemsView,
            this.searchCombo
        ];

        me.callParent();
    },

    getParams: function (queryString) {
        var me = this;

        var excludeIds = [];
        var excludeRecords = this.excludeStore.getRange();
        Ext.each(excludeRecords, function(excludeRecord) {
            excludeIds.push(excludeRecord.get(me.valueField));
        });

        var queryParameters = [];
        Ext.each(this.searchFields, function(searchField) {
            if (searchField.type.type == 'string') {
                var queryParam = [];
                if (OPF.isNotBlank(queryString)) {
                    queryParam.push({
                        field: searchField.name,
                        operation: 'LIKE',
                        value: queryString
                    });
                    if (excludeIds.length > 0) {
                        queryParam.push({
                            field: me.valueField,
                            operation: 'NOTIN',
                            value: excludeIds
                        });
                    }
                    queryParameters.push(queryParam);
                }
            }
        });

        if (queryParameters.length == 0 && excludeIds.length > 0) {
            queryParameters.push([
                {
                    field: me.valueField,
                    operation: 'NOTIN',
                    value: excludeIds
                }
            ])
        }

        return {
            queryParameters: Ext.encode(queryParameters)
        };
    },

    selectSearchedItem: function(combo, records, eOpts) {
        var me = this;
        Ext.Array.each(records, function(record) {
            if (!me.multiSelect) {
                me.selectedItemsStore.removeAll();
            }
            me.selectedItemsStore.add(record);
        });
        combo.clearValue();
    },

    removeSelectSearchedItem: function(record) {
        this.selectedItemsStore.remove(record);
    },

    getValue: function() {
        var me = this;
        var values = [];
        var records = this.selectedItemsStore.getRange();
        Ext.Array.each(records, function(record) {
            values.push(record.get(me.initializedModel.idProperty));
        });
        return values;
    },

    getSubmitValue: function(){
        return this.getValue();
    },

    getSubmitData: function(){
        var me = this,
        data = null;
        if (!me.disabled && me.submitValue && !me.isFileUpload()) {
            data = {};
            data[me.getName()] = me.getSubmitValue();
        }
        return data;
    },

    setValue: function(records) {
        this.selectedItemsStore.removeAll();
        if (records) {
            this.selectedItemsStore.add(records);
        }
    },

    setReadOnly: function(readOnly) {
        var me = this,
            old = me.readOnly;

        if (readOnly != old) {
            me.readOnly = readOnly;
            this.searchCombo.setVisible(!readOnly);
            this.selectedItemsView.readOnly = readOnly;
            this.selectedItemsView.refresh();
        }
    },

//    private methods
    getFieldsFromTemplate: function() {
        var me = this;

        var template = this.initializedModel.self.template[0];
        var fields = [];
        var matches = template.match(/\{[\w\.]+\}/gi);
        Ext.each(matches, function(match) {
            var fieldName = match.substring(1, match.length - 1);
            var field = me.findModelField(me.initializedModel, fieldName);
            if (OPF.isNotEmpty(field)) {
                fields.push(field);
            }
        });
        return fields;
    },

    findModelField: function(model, fieldName) {
        var foundField = null;
        Ext.each(model.fields.items, function(field) {
            if (field.name == fieldName) {
                foundField = field;
            }
        });
        return foundField;
    }

});


text:
/* min-width has been changed from 450px to 320px */
@media all and (min-width: 320px){
	.ui-controlgroup-label { vertical-align: top; display: inline-block;  width: 20%;  margin: 0 2% 0 0;  }
	.ui-controlgroup-controls { width: 60%; display: inline-block; }
}

/* min-width has been changed from 450px to 320px */
@media all and (min-width: 320px){
	.ui-field-contain { border-width: 0; padding: 0; margin: 1em 0; }
}

/* min-width has been changed from 450px to 320px */
@media all and (min-width: 320px){
	label.ui-select { display: inline-block;  width: 20%;  margin: 0 2% 0 0; }
	.ui-select { width: 60%; display: inline-block; }
}

/* min-width has been changed from 450px to 320px */
@media all and (min-width: 320px){
	label.ui-input-text  { vertical-align: top; display: inline-block;  width: 20%;  margin: 0 2% 0 0 }
	input.ui-input-text,
	textarea.ui-input-text,
	.ui-input-search { width: 60%; display: inline-block; }
	.ui-input-search { width: 50%; }
	.ui-input-search input.ui-input-text { width: 98%; /*echos rule from above*/ }
}

/* fields placement fix, because min-width has been changed from 450px to 320px */
@media all and (min-width: 320px){
    .ui-controlgroup-controls,
    .ui-select,
    input.ui-input-text,
    textarea.ui-input-text,
    .ui-input-search { margin-left: 20px; }
}

/* fix for https://www.pivotaltracker.com/story/show/19794687 */
@media all and (min-width: 320px){
    .ui-content ul li div.itemLabel {
        float: left;  /* float the label left, rather than floating the item right */
        width: 40%;   /* A width MUST be specified when floating. */
    }

    .ui-content ul li div.itemValue {
        width: 60%;
        float: none;            /* Un-do the default float */
        word-wrap: break-word;  /* breaks-up long strings with no spaces */
    }
}


text:
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />


text:
using namespace physx;
extern physx::PxPhysics*    gPhysics;
extern physx::PxScene*      gScene;
extern physx::PxMaterial*   gMaterial;

namespace FishEngine
{
	void Collider::Start()
	{
		//m_physxShape = gPhysics->createShape(PxSphereGeometry(m_radius), *gMaterial);
		CreatePhysicsShape();
		auto rigidbody = gameObject()->GetComponent<Rigidbody>();
		if (rigidbody == nullptr)
		{
			//PxRigidStatic* rigidStatic = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial);
			const auto& t = transform();
			auto p = t->position();
			auto q = t->rotation();
			auto rigidStatic = PxCreateStatic(*gPhysics, PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)), *m_physxShape);
			gScene->addActor(*rigidStatic);
		}
//        else {
//            rigidbody->Initialize(m_physxShape);
//        }
	}
}


text:
module MyForeignLib.Hello (sayHi) where

import MyForeignLib.SomeBindings
import MyForeignLib.AnotherVal

foreign export ccall sayHi :: IO ()

-- | Say hi!
sayHi :: IO ()
sayHi = putStrLn $
     "Hi from a foreign library! Foo has value " ++ show valueOfFoo
  ++ " and anotherVal has value " ++ show anotherVal


text:
import createLib from '../../shared/lib';

const mocks = {
    player: {
        getAudio             : () => Promise.resolve({}),
        play                 : () => Promise.resolve({}),
        pause                : () => Promise.resolve({}),
        stop                 : () => Promise.resolve({}),
        setMetadata          : () => Promise.resolve({}),
        setVolume            : () => Promise.resolve({}),
        mute                 : () => Promise.resolve({}),
        unmute               : () => Promise.resolve({}),
        setPlaybackRate      : () => Promise.resolve({}),
        setCurrentTime       : () => Promise.resolve({}),
        getCurrentTime       : () => Promise.resolve({})
    }
};

const lib = createLib(mocks);

export default lib;


text:
package org.jboss.resteasy.test.providers.jackson.resource;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.lang.reflect.Proxy;

@Path("/")
public class ProxyWithGenericReturnTypeJacksonResource {
    @Produces("text/plain")
    @Path("test")
    public ProxyWithGenericReturnTypeJacksonSubResourceSubIntf resourceLocator() {
        Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.class},
                new ProxyWithGenericReturnTypeJacksonInvocationHandler());

        return ProxyWithGenericReturnTypeJacksonSubResourceSubIntf.class.cast(proxy);
    }
}


text:
namespace Microsoft.Azure.Management.Batch.Fluent.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for AutoUserScope.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum AutoUserScope
    {
        [EnumMember(Value = "Task")]
        Task,
        [EnumMember(Value = "Pool")]
        Pool
    }
    internal static class AutoUserScopeEnumExtension
    {
        internal static string ToSerializedValue(this AutoUserScope? value)
        {
            return value == null ? null : ((AutoUserScope)value).ToSerializedValue();
        }

        internal static string ToSerializedValue(this AutoUserScope value)
        {
            switch( value )
            {
                case AutoUserScope.Task:
                    return "Task";
                case AutoUserScope.Pool:
                    return "Pool";
            }
            return null;
        }

        internal static AutoUserScope? ParseAutoUserScope(this string value)
        {
            switch( value )
            {
                case "Task":
                    return AutoUserScope.Task;
                case "Pool":
                    return AutoUserScope.Pool;
            }
            return null;
        }
    }
}


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
    /// <summary>
    /// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifctransportelementtypeenum.htm
    /// </summary>
    public enum IfcTransportElementTypeEnum {ELEVATOR,ESCALATOR,MOVINGWALKWAY,CRANEWAY,LIFTINGGEAR,USERDEFINED,NOTDEFINED}
}


text:
'use strict';

const { wrapError } = require('db-errors');

const { raw } = require('./RawBuilder');
const { createModifier } = require('../utils/createModifier');
const { ValidationErrorType } = require('../model/ValidationError');
const { isObject, isString, isFunction, last, flatten } = require('../utils/objectUtils');
const { RelationExpression, DuplicateRelationError } = require('./RelationExpression');
const { assertIdNotUndefined } = require('../utils/assert');

const { Selection } = require('./operations/select/Selection');

const { QueryBuilderContext } = require('./QueryBuilderContext');
const { QueryBuilderBase } = require('./QueryBuilderBase');

const { FindOperation } = require('./operations/FindOperation');
const { DeleteOperation } = require('./operations/DeleteOperation');
const { UpdateOperation } = require('./operations/UpdateOperation');
const { InsertOperation } = require('./operations/InsertOperation');
const { RelateOperation } = require('./operations/RelateOperation');
const { UnrelateOperation } = require('./operations/UnrelateOperation');

const { JoinEagerOperation } = require('./operations/eager/JoinEagerOperation');
const { NaiveEagerOperation } = require('./operations/eager/NaiveEagerOperation');
const { WhereInEagerOperation } = require('./operations/eager/WhereInEagerOperation');

const { InsertGraphAndFetchOperation } = require('./operations/InsertGraphAndFetchOperation');
const { UpsertGraphAndFetchOperation } = require('./operations/UpsertGraphAndFetchOperation');
const { InsertAndFetchOperation } = require('./operations/InsertAndFetchOperation');
const { UpdateAndFetchOperation } = require('./operations/UpdateAndFetchOperation');
const { JoinRelatedOperation } = require('./operations/JoinRelatedOperation');
const { OnBuildKnexOperation } = require('./operations/OnBuildKnexOperation');
const { InsertGraphOperation } = require('./operations/InsertGraphOperation');
const { UpsertGraphOperation } = require('./operations/UpsertGraphOperation');
const { RunBeforeOperation } = require('./operations/RunBeforeOperation');
const { RunAfterOperation } = require('./operations/RunAfterOperation');
const { FindByIdOperation } = require('./operations/FindByIdOperation');
const { FindByIdsOperation } = require('./operations/FindByIdsOperation');
const { OnBuildOperation } = require('./operations/OnBuildOperation');
const { OnErrorOperation } = require('./operations/OnErrorOperation');
const { SelectOperation } = require('./operations/select/SelectOperation');
const { EagerOperation } = require('./operations/eager/EagerOperation');
const { RangeOperation } = require('./operations/RangeOperation');
const { FirstOperation } = require('./operations/FirstOperation');
const { FromOperation } = require('./operations/FromOperation');
const { KnexOperation } = require('./operations/KnexOperation');

class QueryBuilder extends QueryBuilderBase {
  static init(self, modelClass) {
    super.init(self, modelClass);

    self._resultModelClass = null;
    self._explicitRejectValue = null;
    self._explicitResolveValue = null;
    self._modifiers = {};

    self._allowedGraphExpression = null;
    self._findOperationOptions = modelClass.defaultFindOptions;
    self._relatedQueryFor = null;

    self._findOperationFactory = findOperationFactory;
    self._insertOperationFactory = insertOperationFactory;
    self._updateOperationFactory = updateOperationFactory;
    self._patchOperationFactory = patchOperationFactory;
    self._relateOperationFactory = relateOperationFactory;
    self._unrelateOperationFactory = unrelateOperationFactory;
    self._deleteOperationFactory = deleteOperationFactory;
  }

  static get QueryBuilderContext() {
    return QueryBuilderContext;
  }

  static parseRelationExpression(expr) {
    return RelationExpression.create(expr).toPojo();
  }

  tableNameFor(modelClassOrTableName, newTableName) {
    return super.tableNameFor(getTableName(modelClassOrTableName), newTableName);
  }

  tableName(newTableName) {
    return this.tableNameFor(this.modelClass().getTableName(), newTableName);
  }

  tableRef() {
    return this.tableRefFor(this.modelClass().getTableName());
  }

  aliasFor(modelClassOrTableName, alias) {
    return super.aliasFor(getTableName(modelClassOrTableName), alias);
  }

  alias(alias) {
    return this.aliasFor(this.modelClass().getTableName(), alias);
  }

  fullIdColumnFor(modelClass) {
    const tableName = this.tableRefFor(modelClass);
    const idColumn = modelClass.getIdColumn();

    if (Array.isArray(idColumn)) {
      return idColumn.map((col) => `${tableName}.${col}`);
    } else {
      return `${tableName}.${idColumn}`;
    }
  }

  fullIdColumn() {
    return this.fullIdColumnFor(this.modelClass());
  }

  modifiers(modifiers) {
    if (arguments.length === 0) {
      return { ...this._modifiers };
    } else {
      this._modifiers = { ...this._modifiers, ...modifiers };
      return this;
    }
  }

  modify(modifier, ...args) {
    if (!modifier) {
      return this;
    }

    modifier = createModifier({
      modifier,
      modelClass: this.modelClass(),
      modifiers: this._modifiers,
    });

    modifier(this, ...args);
    return this;
  }

  reject(error) {
    this._explicitRejectValue = error;
    return this;
  }

  resolve(value) {
    this._explicitResolveValue = value;
    return this;
  }

  isExplicitlyResolvedOrRejected() {
    return !!(this._explicitRejectValue || this._explicitResolveValue);
  }

  isExecutable() {
    return !this.isExplicitlyResolvedOrRejected() && !findQueryExecutorOperation(this);
  }

  findOperationFactory(factory) {
    this._findOperationFactory = factory;
    return this;
  }

  insertOperationFactory(factory) {
    this._insertOperationFactory = factory;
    return this;
  }

  updateOperationFactory(factory) {
    this._updateOperationFactory = factory;
    return this;
  }

  patchOperationFactory(factory) {
    this._patchOperationFactory = factory;
    return this;
  }

  deleteOperationFactory(factory) {
    this._deleteOperationFactory = factory;
    return this;
  }

  relateOperationFactory(factory) {
    this._relateOperationFactory = factory;
    return this;
  }

  unrelateOperationFactory(factory) {
    this._unrelateOperationFactory = factory;
    return this;
  }

  withGraphFetched(exp, options = {}) {
    return this._withGraph(exp, options, getWhereInEagerAlgorithm(this));
  }

  withGraphJoined(exp, options = {}) {
    return this._withGraph(exp, options, getJoinEagerAlgorithm(this));
  }

  _withGraph(exp, options, algorithm) {
    const eagerOp = ensureEagerOperation(this, algorithm);
    const parsedExp = parseRelationExpression(this.modelClass(), exp);

    eagerOp.expression = eagerOp.expression.merge(parsedExp);
    eagerOp.graphOptions = { ...eagerOp.graphOptions, ...options };

    checkEager(this);
    return this;
  }

  allowGraph(exp) {
    const currentExpr = this._allowedGraphExpression || RelationExpression.create();

    this._allowedGraphExpression = currentExpr.merge(
      parseRelationExpression(this.modelClass(), exp)
    );

    checkEager(this);
    return this;
  }

  allowedGraphExpression() {
    return this._allowedGraphExpression;
  }

  graphExpressionObject() {
    const eagerOp = this.findOperation(EagerOperation);

    if (eagerOp && !eagerOp.expression.isEmpty) {
      return eagerOp.expression.toPojo();
    } else {
      return null;
    }
  }

  graphModifiersAtPath() {
    const eagerOp = this.findOperation(EagerOperation);

    if (eagerOp && !eagerOp.expression.isEmpty) {
      return eagerOp.modifiersAtPath.map((it) => Object.assign({}, it));
    } else {
      return [];
    }
  }

  modifyGraph(path, modifier) {
    const eagerOp = ensureEagerOperation(this);
    eagerOp.modifiersAtPath.push({ path, modifier });
    return this;
  }

  findOptions(opt) {
    if (arguments.length !== 0) {
      this._findOperationOptions = Object.assign({}, this._findOperationOptions, opt);
      return this;
    } else {
      return this._findOperationOptions;
    }
  }

  resultModelClass() {
    return this._resultModelClass || this.modelClass();
  }

  isFind() {
    return !(
      this.isInsert() ||
      this.isUpdate() ||
      this.isDelete() ||
      this.isRelate() ||
      this.isUnrelate()
    );
  }

  isInsert() {
    return this.has(InsertOperation);
  }

  isUpdate() {
    return this.has(UpdateOperation);
  }

  isDelete() {
    return this.has(DeleteOperation);
  }

  isRelate() {
    return this.has(RelateOperation);
  }

  isUnrelate() {
    return this.has(UnrelateOperation);
  }

  hasWheres() {
    const queryWithoutGraph = this.clone().clearWithGraph();
    return prebuildQuery(queryWithoutGraph).has(QueryBuilderBase.WhereSelector);
  }

  hasSelects() {
    return this.has(QueryBuilderBase.SelectSelector);
  }

  hasWithGraph() {
    const eagerOp = this.findOperation(EagerOperation);
    return !!eagerOp && !eagerOp.expression.isEmpty;
  }

  isSelectAll() {
    if (this._operations.length === 0) {
      return true;
    }

    const tableRef = this.tableRef();
    const tableName = this.tableName();

    return this.everyOperation((op) => {
      if (op.constructor === SelectOperation) {
        // SelectOperations with zero selections are the ones that only have
        // raw items or other non-trivial selections.
        return (
          op.selections.length > 0 &&
          op.selections.every((select) => {
            return (!select.table || select.table === tableRef) && select.column === '*';
          })
        );
      } else if (op.constructor === FromOperation) {
        return op.table === tableName;
      } else if (op.name === 'as' || op.is(FindOperation)) {
        return true;
      } else {
        return false;
      }
    });
  }

  toString() {
    return '[object QueryBuilder]';
  }

  clone() {
    const builder = this.emptyInstance();

    // Call the super class's clone implementation.
    this.baseCloneInto(builder);

    builder._resultModelClass = this._resultModelClass;

    builder._explicitRejectValue = this._explicitRejectValue;
    builder._explicitResolveValue = this._explicitResolveValue;
    builder._modifiers = { ...this._modifiers };

    builder._allowedGraphExpression = this._allowedGraphExpression;
    builder._findOperationOptions = this._findOperationOptions;
    builder._relatedQueryFor = this._relatedQueryFor;

    return builder;
  }

  emptyInstance() {
    const builder = new this.constructor(this.modelClass());

    builder._findOperationFactory = this._findOperationFactory;
    builder._insertOperationFactory = this._insertOperationFactory;
    builder._updateOperationFactory = this._updateOperationFactory;
    builder._patchOperationFactory = this._patchOperationFactory;
    builder._relateOperationFactory = this._relateOperationFactory;
    builder._unrelateOperationFactory = this._unrelateOperationFactory;
    builder._deleteOperationFactory = this._deleteOperationFactory;
    builder._relatedQueryFor = this._relatedQueryFor;

    return builder;
  }

  clearWithGraph() {
    this.clear(EagerOperation);
    return this;
  }

  clearWithGraphFetched() {
    this.clear(WhereInEagerOperation);
    return this;
  }

  clearAllowGraph() {
    this._allowedGraphExpression = null;
    return this;
  }

  clearModifiers() {
    this._modifiers = {};
    return this;
  }

  clearReject() {
    this._explicitRejectValue = null;
    return this;
  }

  clearResolve() {
    this._explicitResolveValue = null;
    return this;
  }

  castTo(modelClass) {
    this._resultModelClass = modelClass || null;
    return this;
  }

  then(...args) {
    const promise = this.execute();
    return promise.then(...args);
  }

  catch(...args) {
    const promise = this.execute();
    return promise.catch(...args);
  }

  async resultSize() {
    const knex = this.knex();
    const builder = this.clone().clear(/orderBy|offset|limit/);

    const countQuery = knex.count('* as count').from((knexBuilder) => {
      builder.toKnexQuery(knexBuilder).as('temp');
    });

    if (this.internalOptions().debug) {
      countQuery.debug();
    }

    const result = await countQuery;
    return result[0] && result[0].count ? parseInt(result[0].count) : 0;
  }

  toKnexQuery(knexBuilder = this.knex().queryBuilder()) {
    const prebuiltQuery = prebuildQuery(this.clone());
    return buildKnexQuery(prebuiltQuery, knexBuilder);
  }

  async execute() {
    // Take a clone so that we don't modify this instance during execution.
    const builder = this.clone();

    try {
      await beforeExecute(builder);
      const result = await doExecute(builder);
      return await afterExecute(builder, result);
    } catch (error) {
      return await handleExecuteError(builder, error);
    }
  }

  throwIfNotFound(data = {}) {
    return this.runAfter((result) => {
      if (
        (Array.isArray(result) && result.length === 0) ||
        result === null ||
        result === undefined ||
        result === 0
      ) {
        throw this.modelClass().createNotFoundError(this.context(), data);
      } else {
        return result;
      }
    });
  }

  findSelection(selection, explicit = false) {
    let noSelectStatements = true;
    let selectionInstance = null;

    this.forEachOperation(true, (op) => {
      if (op.constructor === SelectOperation) {
        selectionInstance = op.findSelection(this, selection);
        noSelectStatements = false;

        if (selectionInstance) {
          return false;
        }
      }
    });

    if (selectionInstance) {
      return selectionInstance;
    }

    if (noSelectStatements && !explicit) {
      const selectAll = new Selection(this.tableRef(), '*');

      if (Selection.doesSelect(this, selectAll, selection)) {
        return selectAll;
      } else {
        return null;
      }
    } else {
      return null;
    }
  }

  findAllSelections() {
    let allSelections = [];

    this.forEachOperation(true, (op) => {
      if (op.constructor === SelectOperation) {
        allSelections = allSelections.concat(op.selections);
      }
    });

    return allSelections;
  }

  hasSelection(selection, explicit) {
    return this.findSelection(selection, explicit) !== null;
  }

  hasSelectionAs(selection, alias, explicit) {
    selection = Selection.create(selection);
    const foundSelection = this.findSelection(selection, explicit);

    if (foundSelection === null) {
      return false;
    } else {
      if (foundSelection.column === '*') {
        // * selects the columns with their column names as aliases.
        return selection.column === alias;
      } else {
        return foundSelection.name === alias;
      }
    }
  }

  traverse(modelClass, traverser) {
    if (typeof traverser === 'undefined') {
      traverser = modelClass;
      modelClass = null;
    }

    return this.runAfter((result) => {
      this.resultModelClass().traverse(modelClass, result, traverser);
      return result;
    });
  }

  page(page, pageSize) {
    return this.range(+page * +pageSize, (+page + 1) * +pageSize - 1);
  }

  columnInfo({ table = null } = {}) {
    table = table || this.tableName();

    const knex = this.knex();
    const tableParts = table.split('.');
    const columnInfoQuery = knex(last(tableParts)).columnInfo();
    const schema = this.internalOptions().schema;

    if (schema) {
      columnInfoQuery.withSchema(schema);
    } else if (tableParts.length > 1) {
      columnInfoQuery.withSchema(tableParts[0]);
    }

    if (this.internalOptions().debug) {
      columnInfoQuery.debug();
    }

    return columnInfoQuery;
  }

  withSchema(schema) {
    this.internalOptions().schema = schema;
    this.internalContext().onBuild.push((builder) => {
      if (!builder.has(/withSchema/)) {
        // Need to push this operation to the front because knex doesn't use the
        // schema for operations called before `withSchema`.
        builder.addOperationToFront(new KnexOperation('withSchema'), [schema]);
      }
    });

    return this;
  }

  debug /* istanbul ignore next */() {
    this.internalOptions().debug = true;
    this.internalContext().onBuild.push((builder) => {
      builder.addOperation(new KnexOperation('debug'), []);
    });

    return this;
  }

  insert(modelsOrObjects) {
    return writeOperation(this, () => {
      const insertOperation = this._insertOperationFactory(this);

      this.addOperation(insertOperation, [modelsOrObjects]);
    });
  }

  insertAndFetch(modelsOrObjects) {
    return writeOperation(this, () => {
      const insertOperation = this._insertOperationFactory(this);

      const insertAndFetchOperation = new InsertAndFetchOperation('insertAndFetch', {
        delegate: insertOperation,
      });

      this.addOperation(insertAndFetchOperation, [modelsOrObjects]);
    });
  }

  insertGraph(modelsOrObjects, opt) {
    return writeOperation(this, () => {
      const insertOperation = this._insertOperationFactory(this);

      const insertGraphOperation = new InsertGraphOperation('insertGraph', {
        delegate: insertOperation,
        opt,
      });

      this.addOperation(insertGraphOperation, [modelsOrObjects]);
    });
  }

  insertGraphAndFetch(modelsOrObjects, opt) {
    return writeOperation(this, () => {
      const insertOperation = this._insertOperationFactory(this);

      const insertGraphOperation = new InsertGraphOperation('insertGraph', {
        delegate: insertOperation,
        opt,
      });

      const insertGraphAndFetchOperation = new InsertGraphAndFetchOperation('insertGraphAndFetch', {
        delegate: insertGraphOperation,
      });

      return this.addOperation(insertGraphAndFetchOperation, [modelsOrObjects]);
    });
  }

  update(modelOrObject) {
    return writeOperation(this, () => {
      const updateOperation = this._updateOperationFactory(this);

      this.addOperation(updateOperation, [modelOrObject]);
    });
  }

  updateAndFetch(modelOrObject) {
    return writeOperation(this, () => {
      const updateOperation = this._updateOperationFactory(this);

      if (!(updateOperation.instance instanceof this.modelClass())) {
        throw new Error('updateAndFetch can only be called for instance operations');
      }

      const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
        delegate: updateOperation,
      });

      // patchOperation is an instance update operation that already adds the
      // required "where id = $" clause.
      updateAndFetch.skipIdWhere = true;

      this.addOperation(updateAndFetch, [updateOperation.instance.$id(), modelOrObject]);
    });
  }

  updateAndFetchById(id, modelOrObject) {
    return writeOperation(this, () => {
      const updateOperation = this._updateOperationFactory(this);

      const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
        delegate: updateOperation,
      });

      this.addOperation(updateAndFetch, [id, modelOrObject]);
    });
  }

  upsertGraph(modelsOrObjects, upsertOptions) {
    return writeOperation(this, () => {
      const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
        upsertOptions,
      });

      this.addOperation(upsertGraphOperation, [modelsOrObjects]);
    });
  }

  upsertGraphAndFetch(modelsOrObjects, upsertOptions) {
    return writeOperation(this, () => {
      const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
        upsertOptions,
      });

      const upsertGraphAndFetchOperation = new UpsertGraphAndFetchOperation('upsertGraphAndFetch', {
        delegate: upsertGraphOperation,
      });

      return this.addOperation(upsertGraphAndFetchOperation, [modelsOrObjects]);
    });
  }

  patch(modelOrObject) {
    return writeOperation(this, () => {
      const patchOperation = this._patchOperationFactory(this);

      this.addOperation(patchOperation, [modelOrObject]);
    });
  }

  patchAndFetch(modelOrObject) {
    return writeOperation(this, () => {
      const patchOperation = this._patchOperationFactory(this);

      if (!(patchOperation.instance instanceof this.modelClass())) {
        throw new Error('patchAndFetch can only be called for instance operations');
      }

      const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
        delegate: patchOperation,
      });

      // patchOperation is an instance update operation that already adds the
      // required "where id = $" clause.
      patchAndFetch.skipIdWhere = true;

      this.addOperation(patchAndFetch, [patchOperation.instance.$id(), modelOrObject]);
    });
  }

  patchAndFetchById(id, modelOrObject) {
    return writeOperation(this, () => {
      const patchOperation = this._patchOperationFactory(this);

      const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
        delegate: patchOperation,
      });

      this.addOperation(patchAndFetch, [id, modelOrObject]);
    });
  }

  delete(...args) {
    return writeOperation(this, () => {
      if (args.length) {
        throw new Error(
          `Don't pass arguments to delete(). You should use it like this: delete().where('foo', 'bar').andWhere(...)`
        );
      }

      const deleteOperation = this._deleteOperationFactory(this);
      this.addOperation(deleteOperation, args);
    });
  }

  del(...args) {
    return this.delete(...args);
  }

  relate(...args) {
    return writeOperation(this, () => {
      const relateOperation = this._relateOperationFactory(this);

      this.addOperation(relateOperation, args);
    });
  }

  unrelate(...args) {
    return writeOperation(this, () => {
      if (args.length) {
        throw new Error(
          `Don't pass arguments to unrelate(). You should use it like this: unrelate().where('foo', 'bar').andWhere(...)`
        );
      }

      const unrelateOperation = this._unrelateOperationFactory(this);
      this.addOperation(unrelateOperation, args);
    });
  }

  increment(propertyName, howMuch) {
    const columnName = this.modelClass().propertyNameToColumnName(propertyName);

    return this.patch({
      [columnName]: raw('?? + ?', [columnName, howMuch]),
    });
  }

  decrement(propertyName, howMuch) {
    const columnName = this.modelClass().propertyNameToColumnName(propertyName);

    return this.patch({
      [columnName]: raw('?? - ?', [columnName, howMuch]),
    });
  }

  findOne(...args) {
    return this.where.apply(this, args).first();
  }

  range(...args) {
    return this.clear(RangeOperation).addOperation(new RangeOperation('range'), args);
  }

  first(...args) {
    return this.addOperation(new FirstOperation('first'), args);
  }

  joinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'innerJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  innerJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'innerJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  outerJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'outerJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  fullOuterJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'fullOuterJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  leftJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'leftJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  leftOuterJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'leftOuterJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  rightJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'rightJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  rightOuterJoinRelated(expression, options) {
    ensureJoinRelatedOperation(this, 'rightOuterJoin').addCall({
      expression,
      options,
    });

    return this;
  }

  deleteById(id) {
    return this.findById(id)
      .delete()
      .runBefore((_, builder) => {
        if (!builder.internalOptions().skipUndefined) {
          assertIdNotUndefined(id, `undefined was passed to deleteById`);
        }
      });
  }

  findById(...args) {
    return this.addOperation(new FindByIdOperation('findById'), args).first();
  }

  findByIds(...args) {
    return this.addOperation(new FindByIdsOperation('findByIds'), args);
  }

  runBefore(...args) {
    return this.addOperation(new RunBeforeOperation('runBefore'), args);
  }

  onBuild(...args) {
    return this.addOperation(new OnBuildOperation('onBuild'), args);
  }

  onBuildKnex(...args) {
    return this.addOperation(new OnBuildKnexOperation('onBuildKnex'), args);
  }

  runAfter(...args) {
    return this.addOperation(new RunAfterOperation('runAfter'), args);
  }

  onError(...args) {
    return this.addOperation(new OnErrorOperation('onError'), args);
  }

  from(...args) {
    return this.addOperation(new FromOperation('from'), args);
  }

  table(...args) {
    return this.addOperation(new FromOperation('table'), args);
  }

  for(relatedQueryFor) {
    if (arguments.length === 0) {
      return this._relatedQueryFor;
    } else {
      this._relatedQueryFor = relatedQueryFor;
      return this;
    }
  }
}

Object.defineProperties(QueryBuilder.prototype, {
  isObjectionQueryBuilder: {
    enumerable: false,
    writable: false,
    value: true,
  },
});

function getTableName(modelClassOrTableName) {
  if (isString(modelClassOrTableName)) {
    return modelClassOrTableName;
  } else {
    return modelClassOrTableName.getTableName();
  }
}

function ensureEagerOperation(builder, algorithm = null) {
  const modelClass = builder.modelClass();
  const defaultGraphOptions = modelClass.getDefaultGraphOptions();
  const eagerOp = builder.findOperation(EagerOperation);

  if (algorithm) {
    const EagerOperationClass = getOperationClassForEagerAlgorithm(builder, algorithm);

    if (eagerOp instanceof EagerOperationClass) {
      return eagerOp;
    } else {
      const newEagerOp = new EagerOperationClass('eager', {
        defaultGraphOptions,
      });

      if (eagerOp) {
        newEagerOp.cloneFrom(eagerOp);
      }

      builder.clear(EagerOperation);
      builder.addOperation(newEagerOp);

      return newEagerOp;
    }
  } else {
    if (eagerOp) {
      return eagerOp;
    } else {
      const EagerOperationClass = getOperationClassForEagerAlgorithm(
        builder,
        getWhereInEagerAlgorithm(builder)
      );

      const newEagerOp = new EagerOperationClass('eager', {
        defaultGraphOptions,
      });

      builder.addOperation(newEagerOp);

      return newEagerOp;
    }
  }
}

function getWhereInEagerAlgorithm(builder) {
  return builder.modelClass().WhereInEagerAlgorithm;
}

function getJoinEagerAlgorithm(builder) {
  return builder.modelClass().JoinEagerAlgorithm;
}

function getNaiveEagerAlgorithm(builder) {
  return builder.modelClass().NaiveEagerAlgorithm;
}

function getOperationClassForEagerAlgorithm(builder, algorithm) {
  if (algorithm === getJoinEagerAlgorithm(builder)) {
    return JoinEagerOperation;
  } else if (algorithm === getNaiveEagerAlgorithm(builder)) {
    return NaiveEagerOperation;
  } else {
    return WhereInEagerOperation;
  }
}

function parseRelationExpression(modelClass, exp) {
  try {
    return RelationExpression.create(exp);
  } catch (err) {
    if (err instanceof DuplicateRelationError) {
      throw modelClass.createValidationError({
        type: ValidationErrorType.RelationExpression,
        message: `Duplicate relation name "${err.relationName}" in relation expression "${exp}". For example, use "${err.relationName}.[foo, bar]" instead of "[${err.relationName}.foo, ${err.relationName}.bar]".`,
      });
    } else {
      throw modelClass.createValidationError({
        type: ValidationErrorType.RelationExpression,
        message: `Invalid relation expression "${exp}"`,
      });
    }
  }
}

function checkEager(builder) {
  const eagerOp = builder.findOperation(EagerOperation);

  if (!eagerOp) {
    return;
  }

  const expr = eagerOp.expression;
  const allowedExpr = builder.allowedGraphExpression();

  if (expr.numChildren > 0 && allowedExpr && !allowedExpr.isSubExpression(expr)) {
    const modelClass = builder.modelClass();

    builder.reject(
      modelClass.createValidationError({
        type: ValidationErrorType.UnallowedRelation,
        message: 'eager expression not allowed',
      })
    );
  }
}

function findQueryExecutorOperation(builder) {
  return builder.findOperation((op) => op.hasQueryExecutor());
}

function beforeExecute(builder) {
  let promise = Promise.resolve();

  builder = addImplicitOperations(builder);

  // Resolve all before hooks before building and executing the query
  // and the rest of the hooks.
  promise = chainOperationHooks(promise, builder, 'onBefore1');

  promise = chainHooks(promise, builder, builder.context().runBefore);
  promise = chainHooks(promise, builder, builder.internalContext().runBefore);

  promise = chainOperationHooks(promise, builder, 'onBefore2');
  promise = chainOperationHooks(promise, builder, 'onBefore3');

  return promise;
}

function doExecute(builder) {
  let promise = Promise.resolve();

  builder = callOnBuildHooks(builder);
  const queryExecutorOperation = findQueryExecutorOperation(builder);

  const explicitRejectValue = builder._explicitRejectValue;
  const explicitResolveValue = builder._explicitResolveValue;

  if (explicitRejectValue !== null) {
    promise = Promise.reject(explicitRejectValue);
  } else if (explicitResolveValue !== null) {
    promise = Promise.resolve(explicitResolveValue);
  } else if (queryExecutorOperation !== null) {
    promise = Promise.resolve(queryExecutorOperation.queryExecutor(builder));
  } else {
    promise = Promise.resolve(buildKnexQuery(builder));

    promise = chainOperationHooks(promise, builder, 'onRawResult');
    promise = promise.then((result) => createModels(result, builder));
  }

  return promise;
}

function afterExecute(builder, result) {
  let promise = Promise.resolve(result);

  promise = chainOperationHooks(promise, builder, 'onAfter1');
  promise = chainOperationHooks(promise, builder, 'onAfter2');

  promise = chainHooks(promise, builder, builder.context().runAfter);
  promise = chainHooks(promise, builder, builder.internalContext().runAfter);

  promise = chainOperationHooks(promise, builder, 'onAfter3');

  return promise;
}

function handleExecuteError(builder, err) {
  let promise = Promise.reject(wrapError(err));

  builder.forEachOperation(true, (op) => {
    if (op.hasOnError()) {
      promise = promise.catch((err) =>
        builder.callAsyncOperationMethod(op, 'onError', [builder, err])
      );
    }
  });

  return promise;
}

function chainOperationHooks(promise, builder, hookName) {
  return promise.then((result) => {
    let promise = Promise.resolve(result);

    builder.forEachOperation(true, (op) => {
      if (op.hasHook(hookName)) {
        promise = promise.then((result) =>
          builder.callAsyncOperationMethod(op, hookName, [builder, result])
        );
      }
    });

    return promise;
  });
}

function ensureJoinRelatedOperation(builder, joinOperation) {
  const opName = joinOperation + 'Relation';
  let op = builder.findOperation(opName);

  if (!op) {
    op = new JoinRelatedOperation(opName, { joinOperation });
    builder.addOperation(op);
  }

  return op;
}

function prebuildQuery(builder) {
  builder = addImplicitOperations(builder);
  builder = callOnBuildHooks(builder);

  const queryExecutorOperation = findQueryExecutorOperation(builder);

  if (queryExecutorOperation) {
    return prebuildQuery(queryExecutorOperation.queryExecutor(builder));
  } else {
    return builder;
  }
}

function addImplicitOperations(builder) {
  if (builder.isFind()) {
    // If no write operations have been called at this point this query is a
    // find query and we need to call the custom find implementation.
    addFindOperation(builder);
  }

  if (builder.hasWithGraph()) {
    moveEagerOperationToEnd(builder);
  }

  return builder;
}

function addFindOperation(builder) {
  if (!builder.has(FindOperation)) {
    const operation = builder._findOperationFactory(builder);
    builder.addOperationToFront(operation, []);
  }
}

function moveEagerOperationToEnd(builder) {
  const eagerOp = builder.findOperation(EagerOperation);

  builder.clear(EagerOperation);
  builder.addOperation(eagerOp);
}

function callOnBuildHooks(builder) {
  callOnBuildFuncs(builder, builder.context().onBuild);
  callOnBuildFuncs(builder, builder.internalContext().onBuild);

  builder.executeOnBuild();
  return builder;
}

function callOnBuildFuncs(builder, func) {
  if (isFunction(func)) {
    func.call(builder, builder);
  } else if (Array.isArray(func)) {
    func.forEach((func) => callOnBuildFuncs(builder, func));
  }
}

function buildKnexQuery(builder, knexBuilder = builder.knex().queryBuilder()) {
  knexBuilder = builder.executeOnBuildKnex(knexBuilder);

  const fromOperation = builder.findLastOperation(QueryBuilderBase.FromSelector);
  const hasSelects = builder.has(QueryBuilderBase.SelectSelector);

  if (!builder.isPartial()) {
    // Set the table only if it hasn't been explicitly set yet.
    if (!fromOperation) {
      knexBuilder = setDefaultTable(builder, knexBuilder);
    }

    // Only add `table.*` select if there are no explicit selects
    // and `from` is a table name and not a subquery.
    if (!hasSelects && (!fromOperation || fromOperation.table)) {
      knexBuilder = setDefaultSelect(builder, knexBuilder);
    }
  }

  return knexBuilder;
}

function setDefaultTable(builder, knexBuilder) {
  const table = builder.tableName();
  const tableRef = builder.tableRef();

  if (table === tableRef) {
    return knexBuilder.table(table);
  } else {
    return knexBuilder.table(`${table} as ${tableRef}`);
  }
}

function setDefaultSelect(builder, knexBuilder) {
  const tableRef = builder.tableRef();

  return knexBuilder.select(`${tableRef}.*`);
}

async function chainHooks(promise, builder, func) {
  return promise.then((result) => {
    let promise = Promise.resolve(result);

    if (isFunction(func)) {
      promise = promise.then((result) => func.call(builder, result, builder));
    } else if (Array.isArray(func)) {
      func.forEach((func) => {
        promise = chainHooks(promise, builder, func);
      });
    }

    return promise;
  });
}

function createModels(result, builder) {
  const modelClass = builder.resultModelClass();

  if (result === null || result === undefined) {
    return null;
  }

  if (Array.isArray(result)) {
    if (result.length && shouldBeConvertedToModel(result[0], modelClass)) {
      for (let i = 0, l = result.length; i < l; ++i) {
        result[i] = modelClass.fromDatabaseJson(result[i]);
      }
    }
  } else if (shouldBeConvertedToModel(result, modelClass)) {
    result = modelClass.fromDatabaseJson(result);
  }

  return result;
}

function shouldBeConvertedToModel(obj, modelClass) {
  return isObject(obj) && !(obj instanceof modelClass);
}

function writeOperation(builder, cb) {
  if (!builder.isFind()) {
    return builder.reject(
      new Error(
        'Double call to a write method. ' +
          'You can only call one of the write methods ' +
          '(insert, update, patch, delete, relate, unrelate, increment, decrement) ' +
          'and only once per query builder.'
      )
    );
  }

  try {
    cb();
    return builder;
  } catch (err) {
    return builder.reject(err);
  }
}

function findOperationFactory() {
  return new FindOperation('find');
}

function insertOperationFactory() {
  return new InsertOperation('insert');
}

function updateOperationFactory() {
  return new UpdateOperation('update');
}

function patchOperationFactory() {
  return new UpdateOperation('patch', {
    modelOptions: { patch: true },
  });
}

function relateOperationFactory() {
  return new RelateOperation('relate', {});
}

function unrelateOperationFactory() {
  return new UnrelateOperation('unrelate', {});
}

function deleteOperationFactory() {
  return new DeleteOperation('delete');
}

module.exports = {
  QueryBuilder,
};


text:
<?php
/**
 * Blog sidebar
 *
 * @package Blog
 */

// fetch & display latest comments
if ($vars['page'] == 'all') {
	echo elgg_view('page/elements/comments_block', array(
		'subtypes' => 'blog',
	));
} elseif ($vars['page'] == 'owner') {
	echo elgg_view('page/elements/comments_block', array(
		'subtypes' => 'blog',
		'owner_guid' => elgg_get_page_owner_guid(),
	));
}

// only users can have archives at present
if ($vars['page'] == 'owner' || $vars['page'] == 'group') {
	echo elgg_view('blog/sidebar/archives', $vars);
}

if ($vars['page'] != 'friends') {
	echo elgg_view('page/elements/tagcloud_block', array(
		'subtypes' => 'blog',
		'owner_guid' => elgg_get_page_owner_guid(),
	));
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/vmmigration/v1/vmmigration.proto

package com.google.cloud.vmmigration.v1;

public interface ListSourcesResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.vmmigration.v1.ListSourcesResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Output only. The list of sources response.
   *

   *
   *
   * repeated .google.cloud.vmmigration.v1.Source sources = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  java.util.List<com.google.cloud.vmmigration.v1.Source> getSourcesList();
  /**
   *
   *
   *

   * Output only. The list of sources response.
   *

   *
   *
   * repeated .google.cloud.vmmigration.v1.Source sources = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  com.google.cloud.vmmigration.v1.Source getSources(int index);
  /**
   *
   *
   *

   * Output only. The list of sources response.
   *

   *
   *
   * repeated .google.cloud.vmmigration.v1.Source sources = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  int getSourcesCount();
  /**
   *
   *
   *

   * Output only. The list of sources response.
   *

   *
   *
   * repeated .google.cloud.vmmigration.v1.Source sources = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  java.util.List<? extends com.google.cloud.vmmigration.v1.SourceOrBuilder>
      getSourcesOrBuilderList();
  /**
   *
   *
   *

   * Output only. The list of sources response.
   *

   *
   *
   * repeated .google.cloud.vmmigration.v1.Source sources = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   */
  com.google.cloud.vmmigration.v1.SourceOrBuilder getSourcesOrBuilder(int index);

  /**
   *
   *
   *

   * Output only. A token, which can be sent as `page_token` to retrieve the
   * next page. If this field is omitted, there are no subsequent pages.
   *

   *
   * string next_page_token = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * Output only. A token, which can be sent as `page_token` to retrieve the
   * next page. If this field is omitted, there are no subsequent pages.
   *

   *
   * string next_page_token = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();

  /**
   *
   *
   *

   * Output only. Locations that could not be reached.
   *

   *
   * repeated string unreachable = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @return A list containing the unreachable.
   */
  java.util.List<java.lang.String> getUnreachableList();
  /**
   *
   *
   *

   * Output only. Locations that could not be reached.
   *

   *
   * repeated string unreachable = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @return The count of unreachable.
   */
  int getUnreachableCount();
  /**
   *
   *
   *

   * Output only. Locations that could not be reached.
   *

   *
   * repeated string unreachable = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @param index The index of the element to return.
   * @return The unreachable at the given index.
   */
  java.lang.String getUnreachable(int index);
  /**
   *
   *
   *

   * Output only. Locations that could not be reached.
   *

   *
   * repeated string unreachable = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
   *
   * @param index The index of the value to return.
   * @return The bytes of the unreachable at the given index.
   */
  com.google.protobuf.ByteString getUnreachableBytes(int index);
}


text:
package io.virtdata.libbasics.shared.from_long.to_long;

import io.virtdata.annotations.Categories;
import io.virtdata.annotations.Category;
import io.virtdata.annotations.Example;
import io.virtdata.annotations.ThreadSafeMapper;

import java.util.function.LongUnaryOperator;

/**
 * Combine multiple LongUnaryOperators into a single function.
 */
@Categories(Category.functional)
@ThreadSafeMapper
public class LongFlow implements LongUnaryOperator {

    private final LongUnaryOperator[] ops;

    @Example({"StringFlow(Add(3),Mul(6))","Create an integer operator which adds 3 and multiplies the result by 6"})
    public LongFlow(LongUnaryOperator... ops) {
        this.ops = ops;
    }

    @Override
    public long applyAsLong(long operand) {
        long value = operand;
        for (LongUnaryOperator op : ops) {
            value = op.applyAsLong(value);
        }
        return value;
    }
}


text:
cask :v1 => 'paye-tools' do
  version '15.0.15048.300'
  sha256 '11199be757ef71fa123c13bb69685d234a814958713d27a475616c6e587de2ee'

  url "https://www.gov.uk/government/uploads/uploaded/hmrc/payetools-rti-#{version}-osx.zip"
  name 'Basic PAYE Tools'
  homepage 'http://www.hmrc.gov.uk/payerti/payroll/bpt/paye-tools.htm'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  installer :script => "payetools-rti-#{version}-osx.app/Contents/MacOS/osx-intel",
            :args => [ '--mode', 'unattended' ]

  uninstall :quit => 'uk.gov.hmrc.bptrti'
end


text:
package play.db.jpa;

import play.*;
import play.libs.F;
import play.mvc.Http;

import javax.persistence.*;

/**
 * JPA Helpers.
 */
public class JPA {

    // Only used when there's no HTTP context
    static ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<EntityManager>();

    /**
     * Create a default JPAApi with the given persistence unit configuration.
     * Automatically initialise the JPA entity manager factories.
     */
    public static JPAApi createFor(String name, String unitName) {
        return new DefaultJPAApi(DefaultJPAConfig.of(name, unitName)).start();
    }

    /**
     * Create a default JPAApi with name "default" and the given unit name.
     * Automatically initialise the JPA entity manager factories.
     */
    public static JPAApi createFor(String unitName) {
        return new DefaultJPAApi(DefaultJPAConfig.of("default", unitName)).start();
    }

    /**
     * Get the JPA api for the current play application.
     */
    public static JPAApi jpaApi() {
        Application app = Play.application();
        if (app == null) {
            throw new RuntimeException("No application running");
        }
        return app.injector().instanceOf(JPAApi.class);
    }

    /**
     * Get the EntityManager for specified persistence unit for this thread.
     */
    public static EntityManager em(String key) {
        EntityManager em = jpaApi().em(key);
        if (em == null) {
            throw new RuntimeException("No JPA EntityManagerFactory configured for name [" + key + "]");
        }

        return em;
    }

    /**
     * Get the default EntityManager for this thread.
     */
    public static EntityManager em() {
        Http.Context context = Http.Context.current.get();
        if (context != null) {
            EntityManager em = (EntityManager) context.args.get("currentEntityManager");
            if (em == null) {
                throw new RuntimeException("No EntityManager bound to this thread. Try to annotate your action method with @play.db.jpa.Transactional");
            }
            return em;
        }
        // Not a web request
        EntityManager em = currentEntityManager.get();
        if(em == null) {
            throw new RuntimeException("No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread.");
        }
        return em;
    }

    /**
     * Bind an EntityManager to the current thread.
     */
    public static void bindForCurrentThread(EntityManager em) {
        Http.Context context = Http.Context.current.get();
        if (context != null) {
            if (em == null) {
                context.args.remove("currentEntityManager");
            } else {
                context.args.put("currentEntityManager", em);
            }
        } else {
            currentEntityManager.set(em);
        }
    }

    /**
     * Run a block of code in a JPA transaction.
     *
     * @param block Block of code to execute.
     */
    public static <T> T withTransaction(play.libs.F.Function0<T> block) throws Throwable {
        return jpaApi().withTransaction(block);
    }

    /**
     * Run a block of asynchronous code in a JPA transaction.
     *
     * @param block Block of code to execute.
     *
     * @deprecated This may cause deadlocks
     */
    @Deprecated
    public static <T> F.Promise<T> withTransactionAsync(play.libs.F.Function0<F.Promise<T>> block) throws Throwable {
        return jpaApi().withTransactionAsync(block);
    }

    /**
     * Run a block of code in a JPA transaction.
     *
     * @param block Block of code to execute.
     */
    public static void withTransaction(final play.libs.F.Callback0 block) {
        jpaApi().withTransaction(block);
    }

    /**
     * Run a block of code in a JPA transaction.
     *
     * @param name The persistence unit name
     * @param readOnly Is the transaction read-only?
     * @param block Block of code to execute.
     */
    public static <T> T withTransaction(String name, boolean readOnly, play.libs.F.Function0<T> block) throws Throwable {
        return jpaApi().withTransaction(name, readOnly, block);
    }

    /**
     * Run a block of asynchronous code in a JPA transaction.
     *
     * @param name The persistence unit name
     * @param readOnly Is the transaction read-only?
     * @param block Block of code to execute.
     *
     * @deprecated This may cause deadlocks
     */
    @Deprecated
    public static <T> F.Promise<T> withTransactionAsync(String name, boolean readOnly, play.libs.F.Function0<F.Promise<T>> block) throws Throwable {
        return jpaApi().withTransactionAsync(name, readOnly, block);
    }
}


text:
select department_id,sum(salary) from employees group by department_id;
update employees set salary=salary+10 where department_id=20;
commit;
select department_id,sum(salary) from employees group by department_id;
update employees set salary=salary+10 where department_id=60;
commit;
select department_id,sum(salary) from employees group by department_id;


text:
package org.dcache.nfs.status;

import org.dcache.nfs.ChimeraNFSException;
import static org.dcache.nfs.nfsstat.*;

public class BackChanBusyException extends ChimeraNFSException {

    private static final long serialVersionUID = 5438779958538246183L;

    public BackChanBusyException() {
        super(NFSERR_BACK_CHAN_BUSY);
    }

    public BackChanBusyException(String msg) {
        super(NFSERR_BACK_CHAN_BUSY, msg);
    }
}


text:
namespace Nz
{
	SocketPollerImpl::SocketPollerImpl()
	{
		m_handle = epoll_create1(0);
	}

	SocketPollerImpl::~SocketPollerImpl()
	{
		close(m_handle);
	}

	void SocketPollerImpl::Clear()
	{
		m_readyToReadSockets.clear();
		m_readyToWriteSockets.clear();
		m_sockets.clear();
	}

	bool SocketPollerImpl::IsReadyToRead(SocketHandle socket) const
	{
		return m_readyToReadSockets.count(socket) != 0;
	}

	bool SocketPollerImpl::IsReadyToWrite(SocketHandle socket) const
	{
		return m_readyToWriteSockets.count(socket) != 0;
	}

	bool SocketPollerImpl::IsRegistered(SocketHandle socket) const
	{
		return m_sockets.count(socket) != 0;
	}

	bool SocketPollerImpl::RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags)
	{
		NazaraAssert(!IsRegistered(socket), "Socket is already registered");

		epoll_event entry;
		std::memset(&entry, 0, sizeof(epoll_event));

		entry.data.fd = socket;

		if (eventFlags & SocketPollEvent::Read)
			entry.events |= EPOLLIN;

		if (eventFlags & SocketPollEvent::Write)
			entry.events |= EPOLLOUT;

		if (epoll_ctl(m_handle, EPOLL_CTL_ADD, socket, &entry) != 0)
		{
			NazaraError("Failed to add socket to epoll structure (errno " + NumberToString(errno) + ": " + Error::GetLastSystemError() + ')');
			return false;
		}

		m_sockets.insert(socket);

		return true;
	}

	void SocketPollerImpl::UnregisterSocket(SocketHandle socket)
	{
		NazaraAssert(IsRegistered(socket), "Socket is not registered");

		m_readyToReadSockets.erase(socket);
		m_readyToWriteSockets.erase(socket);
		m_sockets.erase(socket);

		if (epoll_ctl(m_handle, EPOLL_CTL_DEL, socket, nullptr) != 0)
			NazaraWarning("An error occured while removing socket from epoll structure (errno " + NumberToString(errno) + ": " + Error::GetLastSystemError() + ')');
	}

	unsigned int SocketPollerImpl::Wait(int msTimeout, SocketError* error)
	{
		int activeSockets;

		// Reset status of sockets
		m_events.resize(m_sockets.size());
		std::memset(m_events.data(), 0, m_events.size() * sizeof(epoll_event));

		activeSockets = epoll_wait(m_handle, m_events.data(), static_cast<int>(m_events.size()), static_cast<int>(msTimeout));
		if (activeSockets == -1)
		{
			if (error)
				*error = SocketImpl::TranslateErrorToSocketError(errno);

			return 0;
		}

		m_readyToReadSockets.clear();
		m_readyToWriteSockets.clear();
		if (activeSockets > 0)
		{
			int socketCount = activeSockets;
			for (int i = 0; i < socketCount; ++i)
			{
				if (m_events[i].events & (EPOLLIN | EPOLLOUT | EPOLLHUP | EPOLLERR))
				{
					if (m_events[i].events & (EPOLLIN | EPOLLHUP | EPOLLERR))
						m_readyToReadSockets.insert(m_events[i].data.fd);

					if (m_events[i].events & (EPOLLOUT | EPOLLERR))
						m_readyToWriteSockets.insert(m_events[i].data.fd);
				}
				else
				{
					NazaraWarning("Descriptor " + NumberToString(m_events[i].data.fd) + " was returned by epoll without EPOLLIN nor EPOLLOUT flags (events: 0x" + NumberToString(m_events[i].events, 16) + ')');
					activeSockets--;
				}
			}
		}

		if (error)
			*error = SocketError::NoError;

		return activeSockets;
	}
}