text:
package org.szegedi.spring.support;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * A factory of soft-reference pooled objects. While we are aware that pooling
 * <i>in general</i> is harmful on modern VMs, we do actually have use cases -
 * i.e. expensively initialized cryptographic transformers - that make sense to
 * pool.
 *
 * @author Attila Szegedi
 */
public abstract class SoftPooledFactory<T> {
    private final BlockingDeque<Reference<T>> pool = new LinkedBlockingDeque<>();

    public Reference<T> get() throws Exception {
        for (;;) {
            final Reference<T> ref = pool.pollLast();
            if (ref == null) {
                return new SoftReference<>(create());
            }
            final T obj = ref.get();
            if (obj != null) {
                return ref;
            }
        }
    }

    public void put(final Reference<T> ref) {
        pool.offerLast(ref);
    }

    protected abstract T create() throws Exception;
}


text:
/**
 * Created by senntyou on 2017/11/30.
 */

require('../../util/change_cwd_to')(__dirname + '/demo');

var projectConfig = require('./demo/lilacs.config');
projectConfig.skipNotExistingFiles = !0;
projectConfig.requireJsToTagLoad = !0;

projectConfig.filesMap = [];
projectConfig.filesMap[100] = {
    'require_js/index_2.html': 'require_js/index_new.html',
    'require_js/index_2.js': 'require_js/index_new.js'
};

require('../../util/exec')('lilacs dist require_js/* -e 100');

redpajama_set_name: RedPajamaGithub


text:
package com.opengamma.analytics.math.integration;

import org.apache.commons.lang.Validate;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.analysis.integration.SimpsonIntegrator;
import org.apache.commons.math.analysis.integration.UnivariateRealIntegrator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.analytics.math.MathException;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.util.wrapper.CommonsMathWrapper;

/**
 * Simpson's integration rule is a Newton-Cotes formula that approximates the function to be integrated with quadratic polynomials before performing the
 * integration. For a function $f(x)$, if three points $x_1$, $x_2$ and $x_3$ are equally spaced on the abscissa with $x_2 - x_1 = h$ then $$ \begin{align*}
 * \int^{x_3} _{x_1} f(x)dx \approx \frac{1}{3}h(f(x_1) + 4f(x_2) + f(x_3)) \end{align*} $$
 *

 * This class is a wrapper for the Commons
 * Math library implementation of Simpson integration.
 */
public class SimpsonIntegrator1D extends Integrator1D<Double, Double> {
  private static final Logger LOGGER = LoggerFactory.getLogger(SimpsonIntegrator1D.class);
  private final UnivariateRealIntegrator _integrator = new SimpsonIntegrator();

  /**
   * Simpson's integration method. Note that the Commons implementation fails if the lower bound is larger than the upper - in this case, the bounds are
   * reversed and the result negated.
   *
   * @param f
   *          The function to integrate, not null
   * @param lower
   *          The lower bound, not null
   * @param upper
   *          The upper bound, not null
   * @return The result of the integration
   */
  @Override
  public Double integrate(final Function1D<Double, Double> f, final Double lower, final Double upper) {
    Validate.notNull(f, "function");
    Validate.notNull(lower, "lower bound");
    Validate.notNull(upper, "upper bound");
    try {
      if (lower < upper) {
        return _integrator.integrate(CommonsMathWrapper.wrapUnivariate(f), lower, upper);
      }
      LOGGER.info("Upper bound was less than lower bound; swapping bounds and negating result");
      return -_integrator.integrate(CommonsMathWrapper.wrapUnivariate(f), upper, lower);
    } catch (final FunctionEvaluationException e) {
      throw new MathException(e);
    } catch (final org.apache.commons.math.ConvergenceException e) {
      throw new MathException(e);
    }
  }

}


text:
module PgStream
  class Processor
    CALLBACK_TYPES = [:before_execute, :during_execute, :after_execute]

    def initialize(stream)
      @stream = stream
      @callbacks = CALLBACK_TYPES.map do |type|
        [type, []]
      end.to_h
      @row_count = 0
    end

    def register(args)
      args.each do |type, function|
        if CALLBACK_TYPES.include?(type)
          @callbacks[type] << function
        else
          raise "#{type} is not an acceptable callback type. Types include #{CALLBACK_TYPES.join(', ')}"
        end
      end
      @callbacks
    end

    def execute
      @callbacks[:before_execute].each(&:call)
      @stream.each_row do |row|
        @row_count += 1
        @callbacks[:during_execute].each { |y| y.call(row, @row_count) }
      end
      @callbacks[:after_execute].each { |y| y.call(@row_count) }
      @row_count
    end
  end
end


text:
require "log4r"

require_relative "driver"
require_relative "plugin"

require "vagrant/util/platform"
require "vagrant/util/powershell"

module VagrantPlugins
  module HyperV
    class Provider < Vagrant.plugin("2", :provider)
      attr_reader :driver

      def self.usable?(raise_error=false)
        if !Vagrant::Util::Platform.windows?
          raise Errors::WindowsRequired
        end

        if !Vagrant::Util::Platform.windows_admin?
          raise Errors::AdminRequired
        end

        if !Vagrant::Util::PowerShell.available?
          raise Errors::PowerShellRequired
        end

        true
      rescue Errors::HyperVError
        raise if raise_error
        return false
      end

      def initialize(machine)
        @machine = machine

        # This method will load in our driver, so we call it now to
        # initialize it.
        machine_id_changed
      end

      def action(name)
        # Attempt to get the action method from the Action class if it
        # exists, otherwise return nil to show that we don't support the
        # given action.
        action_method = "action_#{name}"
        return Action.send(action_method) if Action.respond_to?(action_method)
        nil
      end

      def machine_id_changed
        @driver = Driver.new(@machine.id)
      end

      def state
        state_id = nil
        state_id = :not_created if !@machine.id

        if !state_id
          # Run a custom action we define called "read_state" which does
          # what it says. It puts the state in the `:machine_state_id`
          # key in the environment.
          env = @machine.action(:read_state)
          state_id = env[:machine_state_id]
        end

        # Get the short and long description
        short = state_id.to_s
        long  = ""

        # If we're not created, then specify the special ID flag
        if state_id == :not_created
          state_id = Vagrant::MachineState::NOT_CREATED_ID
        end

        # Return the MachineState object
        Vagrant::MachineState.new(state_id, short, long)
      end

      def to_s
        id = @machine.id.nil? ? "new" : @machine.id
        "Hyper-V (#{id})"
      end

      def ssh_info
        # We can only SSH into a running machine
        return nil if state.id != :running

        # Read the IP of the machine using Hyper-V APIs
        network = @driver.read_guest_ip
        return nil if !network["ip"]

        {
          host: network["ip"],
          port: 22,
        }
      end
    end
  end
end


text:
/** tbb - test bench BLE. */

#include "syscfg/syscfg.h"

#if MYNEWT_VAL(TESTBENCH_BLE)

#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "sysinit/sysinit.h"
#include "bsp/bsp.h"
#include "os/os.h"
#include "bsp/bsp.h"
#include "hal/hal_gpio.h"
#include "console/console.h"
#include "hal/hal_system.h"
#include "config/config.h"
#include "split/split.h"

/* BLE */
#include "nimble/ble.h"
#include "host/ble_hs.h"
#include "services/gap/ble_svc_gap.h"

#include "oic/oc_gatt.h"

#include "tbb.h"

static int tbb_gap_event(struct ble_gap_event *event, void *arg);

static struct log tbb_log;

/* tbb uses the first "peruser" log module. */
#define TBB_LOG_MODULE  (LOG_MODULE_PERUSER + 0)

/* Convenience macro for logging to the tbb module. */
#define TBB_LOG(lvl, ...) \
    LOG_ ## lvl(&tbb_log, TBB_LOG_MODULE, __VA_ARGS__)

void
tbb_print_addr(const void *addr)
{
    const uint8_t *u8p;

    u8p = addr;
    TBB_LOG(INFO, "%02x:%02x:%02x:%02x:%02x:%02x",
            u8p[5], u8p[4], u8p[3], u8p[2], u8p[1], u8p[0]);
}

/**
 * Logs information about a connection to the console.
 */
static void
tbb_print_conn_desc(struct ble_gap_conn_desc *desc)
{
    TBB_LOG(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
                desc->conn_handle, desc->our_ota_addr.type);
    tbb_print_addr(desc->our_ota_addr.val);
    TBB_LOG(INFO, " our_id_addr_type=%d our_id_addr=",
                desc->our_id_addr.type);
    tbb_print_addr(desc->our_id_addr.val);
    TBB_LOG(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
                desc->peer_ota_addr.type);
    tbb_print_addr(desc->peer_ota_addr.val);
    TBB_LOG(INFO, " peer_id_addr_type=%d peer_id_addr=",
                desc->peer_id_addr.type);
    tbb_print_addr(desc->peer_id_addr.val);
    TBB_LOG(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
                "encrypted=%d authenticated=%d bonded=%d\n",
                desc->conn_itvl, desc->conn_latency,
                desc->supervision_timeout,
                desc->sec_state.encrypted,
                desc->sec_state.authenticated,
                desc->sec_state.bonded);
}

/**
 * Enables advertising with the following parameters:
 *     o General discoverable mode.
 *     o Undirected connectable mode.
 */
static void
tbb_advertise(void)
{
    struct ble_gap_adv_params adv_params;
    struct ble_hs_adv_fields fields;
    const char *name;
    int rc;

    /**
     *  Set the advertisement data included in our advertisements:
     *     o Flags (indicates advertisement type and other general info).
     *     o Advertising tx power.
     *     o Device name.
     *     o 16-bit service UUIDs (alert notifications).
     */

    memset(&fields, 0, sizeof fields);

    /* Advertise two flags:
     *     o Discoverability in forthcoming advertisement (general)
     *     o BLE-only (BR/EDR unsupported).
     */
    fields.flags = BLE_HS_ADV_F_DISC_GEN |
                   BLE_HS_ADV_F_BREDR_UNSUP;

    /* Indicate that the TX power level field should be included; have the
     * stack fill this value automatically.  This is done by assiging the
     * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
     */
    fields.tx_pwr_lvl_is_present = 1;
    fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;

    name = ble_svc_gap_device_name();
    fields.name = (uint8_t *)name;
    fields.name_len = strlen(name);
    fields.name_is_complete = 1;

    fields.uuids16 = (ble_uuid16_t[]) {
        BLE_UUID16_INIT(OC_GATT_SEC_SVC_UUID)
    };
    fields.num_uuids16 = 1;
    fields.uuids16_is_complete = 1;

    rc = ble_gap_adv_set_fields(&fields);
    if (rc != 0) {
        TBB_LOG(ERROR, "error setting advertisement data; rc=%d\n", rc);
        return;
    }

    /* Begin advertising. */
    memset(&adv_params, 0, sizeof adv_params);
    adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
    adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
    rc = ble_gap_adv_start(BLE_OWN_ADDR_PUBLIC, NULL, BLE_HS_FOREVER,
                           &adv_params, tbb_gap_event, NULL);
    if (rc != 0) {
        TBB_LOG(ERROR, "error enabling advertisement; rc=%d\n", rc);
        return;
    }
}

/**
 * The nimble host executes this callback when a GAP event occurs.  The
 * application associates a GAP event callback with each connection that forms.
 * tbb uses the same callback for all connections.
 *
 * @param event                 The type of event being signalled.
 * @param ctxt                  Various information pertaining to the event.
 * @param arg                   Application-specified argument; unuesd by
 *                                  tbb.
 *
 * @return                      0 if the application successfully handled the
 *                                  event; nonzero on failure.  The semantics
 *                                  of the return code is specific to the
 *                                  particular GAP event being signalled.
 */
static int
tbb_gap_event(struct ble_gap_event *event, void *arg)
{
    struct ble_gap_conn_desc desc;
    int rc;

    switch (event->type) {
    case BLE_GAP_EVENT_CONNECT:
        /* A new connection was established or a connection attempt failed. */
        TBB_LOG(INFO, "connection %s; status=%d ",
                       event->connect.status == 0 ? "established" : "failed",
                       event->connect.status);
        if (event->connect.status == 0) {
            rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
            assert(rc == 0);
            tbb_print_conn_desc(&desc);
        }
        TBB_LOG(INFO, "\n");

        if (event->connect.status != 0) {
            /* Connection failed; resume advertising. */
            tbb_advertise();
        }
        return 0;

    case BLE_GAP_EVENT_DISCONNECT:
        TBB_LOG(INFO, "disconnect; reason=%d ", event->disconnect.reason);
        tbb_print_conn_desc(&event->disconnect.conn);
        TBB_LOG(INFO, "\n");

        /* Connection terminated; resume advertising. */
        tbb_advertise();
        return 0;

    case BLE_GAP_EVENT_CONN_UPDATE:
        /* The central has updated the connection parameters. */
        TBB_LOG(INFO, "connection updated; status=%d ",
                    event->conn_update.status);
        rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
        assert(rc == 0);
        tbb_print_conn_desc(&desc);
        TBB_LOG(INFO, "\n");
        return 0;

    case BLE_GAP_EVENT_ADV_COMPLETE:
        TBB_LOG(INFO, "advertise complete; reason=%d\n",
                event->adv_complete.reason);
        tbb_advertise();
        return 0;

    case BLE_GAP_EVENT_ENC_CHANGE:
        /* Encryption has been enabled or disabled for this connection. */
        TBB_LOG(INFO, "encryption change event; status=%d ",
                    event->enc_change.status);
        rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
        assert(rc == 0);
        tbb_print_conn_desc(&desc);
        TBB_LOG(INFO, "\n");
        return 0;

    case BLE_GAP_EVENT_SUBSCRIBE:
        TBB_LOG(INFO, "subscribe event; conn_handle=%d attr_handle=%d "
                          "reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
                    event->subscribe.conn_handle,
                    event->subscribe.attr_handle,
                    event->subscribe.reason,
                    event->subscribe.prev_notify,
                    event->subscribe.cur_notify,
                    event->subscribe.prev_indicate,
                    event->subscribe.cur_indicate);
        return 0;

    case BLE_GAP_EVENT_MTU:
        TBB_LOG(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
                    event->mtu.conn_handle,
                    event->mtu.channel_id,
                    event->mtu.value);
        return 0;
    }

    return 0;
}

static void
tbb_on_reset(int reason)
{
    TBB_LOG(ERROR, "Resetting state; reason=%d\n", reason);
}

static void
tbb_on_sync(void)
{
    /* Begin advertising. */
    tbb_advertise();
}

void
tbb_init(void)
{
    int rc;

    /* Initialize the tbb log. */
    log_register("tbb", &tbb_log, &log_console_handler, NULL,
                 LOG_SYSLEVEL);

    /* Initialize the NimBLE host configuration. */
    log_register("ble_hs", &ble_hs_log, &log_console_handler, NULL,
                 LOG_SYSLEVEL);
    ble_hs_cfg.reset_cb = tbb_on_reset;
    ble_hs_cfg.sync_cb = tbb_on_sync;

    /* Set the default device name. */
    rc = ble_svc_gap_device_name_set(MYNEWT_VAL(TESTBENCH_BLE_NAME));
    assert(rc == 0);
}

#endif


text:
static NSString *const APPLICATION_BUILD_VERSION = @"app_build_version";

@implementation HCPPluginInternalPreferences

#pragma mark Public API

+ (HCPPluginInternalPreferences *)defaultConfig {
    HCPPluginInternalPreferences *pluginConfig = [[HCPPluginInternalPreferences alloc] init];
    pluginConfig.appBuildVersion = [NSBundle applicationBuildVersion];

    return pluginConfig;
}

#pragma mark HCPJsonConvertable implementation

+ (instancetype)instanceFromJsonObject:(id)json {
    if (![json isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSDictionary *jsonObject = json;

    HCPPluginInternalPreferences *pluginConfig = [[HCPPluginInternalPreferences alloc] init];
    pluginConfig.appBuildVersion = [(NSNumber *)jsonObject[APPLICATION_BUILD_VERSION] integerValue];

    return pluginConfig;
}

- (id)toJson {
    NSMutableDictionary *jsonObject = [[NSMutableDictionary alloc] init];
    [jsonObject setObject:[NSNumber numberWithInteger:self.appBuildVersion] forKey:APPLICATION_BUILD_VERSION];

    return jsonObject;
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Q. Jl Fla Acad. Sci. 8(2): 187 (1945)

#### Original name
Inocybe fulviceps Murrill

### Remarks
null


text:
**Inactive Project:** I ended up not needing this for my related project. It's currently not being developed, pending further use for it.

onetimedownload
=========

[![Gem Version](https://img.shields.io/gem/v/onetimedownload.svg)](https://rubygems.org/gems/onetimedownload)
[![Code Climate](https://img.shields.io/codeclimate/github/akerl/onetimedownload.svg)](https://codeclimate.com/github/akerl/onetimedownload)
[![Coverage Status](https://img.shields.io/coveralls/akerl/onetimedownload.svg)](https://coveralls.io/r/akerl/onetimedownload)
[![Build Status](https://img.shields.io/travis/akerl/onetimedownload.svg)](https://travis-ci.org/akerl/onetimedownload)
[![MIT Licensed](https://img.shields.io/badge/license-MIT-green.svg)](https://tldrlegal.com/license/mit-license)

Simple tool for serving a file to a single recipient. Idea based on https://github.com/mikegrb/App-otfile.

## Usage

## Installation

    gem install onetimedownload

## License

onetimedownload is released under the MIT License. See the bundled LICENSE file for details.


text:
@echo off

if EXIST Built\build.ninja GOTO DoBuild
Make.pl

:DoBuild
pushd Built
ninja %*
popd


text:
package com.ibm.uk.hursley.perfharness.cmd;

import java.util.logging.Level;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQConnectionFactory;
import com.ibm.mq.jms.MQQueue;
import com.ibm.uk.hursley.perfharness.Config;
import com.ibm.uk.hursley.perfharness.ControlThread;
import com.ibm.uk.hursley.perfharness.Copyright;
import com.ibm.uk.hursley.perfharness.Log;

/**
 * Listens on an MQ Queue for commands calls super.processCommand to action
 * Replies to an MQ Queue with status/feedback
 *
 * NOTE: this is independent of the server under test. So if you
 * want to test WAS, this processor may still be valid if you want test control
 * through MQ
 *
 * To use: enable with -cmd_c MQCommandProcessor and provide parameters as described
 * in the properties file.
 *
 * The simplest way to send & receive messages is to use the WMQ sample applications
 * amqsput0 and amqsget0. Do something like:
 *
 * To send:
 * amqsput0 [qm] [q]
 * >REPORT -stats
 *
 * To receive:
 * amqsget0 [qm] [q]
 * <[stats]
 *
 * See Command class for supported commands
 *
 * @author fentono
 *
 */

@SuppressWarnings("deprecation")
public class MQCommandProcessor extends Command implements MessageListener {

	@SuppressWarnings("unused")
	private static final String c = Copyright.COPYRIGHT;

	// JMS interface classes
	protected ConnectionFactory cf = null;
	protected Connection connection = null;
	protected Session insession = null;
	protected Session outsession = null;
	protected MessageProducer messageProducer = null; //outbound
	protected MessageConsumer messageConsumer = null; //inbound
	protected Destination inQueue = null;
    protected Destination outQueue = null;
    protected Message outMessage = null;

    private Object mutexWaiting = null; // Lock for frozen/finished threads.

	/**
	 * Register our presence and look up any required parameters for this class.
	 *
	 * @see Config#registerSelf(Class)
	 */
	public static void registerConfig() {

		Config.registerSelf(MQCommandProcessor.class);

	}

	public MQCommandProcessor(ControlThread parent) {
		super(parent);

		buildJMSResource();

	}

	/**
	 * Apply vendor-specific settings for building up a connection factory to
	 * WMQ.
	 *
	 * @param cf
	 * @throws JMSException
	 */
	protected void configureMQConnectionFactory(MQConnectionFactory cf)
			throws JMSException {

		// always client bindings
		cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
		cf.setHostName(Config.parms.getString("cmd_jh"));
		cf.setPort(Config.parms.getInt("cmd_p"));
		cf.setChannel(Config.parms.getString("cmd_jc"));

		cf.setQueueManager(Config.parms.getString("cmd_jb"));

	}

	public final void buildJMSResource() {

		try {
			cf = new MQConnectionFactory();
			configureMQConnectionFactory((MQConnectionFactory) cf);
			connection = cf.createConnection();
			connection.start();

			insession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			outsession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			inQueue = new MQQueue(Config.parms.getString("cmd_inq"));
			outQueue = new MQQueue(Config.parms.getString("cmd_outq"));

			((MQQueue) outQueue).setTargetClient(JMSC.MQJMS_CLIENT_NONJMS_MQ);

			messageConsumer = insession.createConsumer(inQueue);
			messageProducer = outsession.createProducer(outQueue);

		} catch (JMSException e) {
			Log.logger.log(Level.SEVERE,
					"Error connecting Command Processor to WebSphereMQ", e);
			return;
		}

	}

	protected void destroyJMSResources(boolean reconnecting) {

		if (messageProducer != null) {
    		if ( !reconnecting ) Log.logger.log(Level.FINE, "Closing producer {0}",messageProducer );
            try {
                messageProducer.close();
            } catch (JMSException e) {
            } finally {
                messageProducer = null;
            }
        }

    	if (messageConsumer != null) {
    		if ( !reconnecting ) Log.logger.log(Level.FINE, "Closing consumer {0}",messageConsumer );
            try {
                messageConsumer.close();
            } catch (JMSException e) {
            } finally {
                messageConsumer = null;
            }
        }

    	if (insession != null) {
        	if ( !reconnecting ) Log.logger.log(Level.FINE, "Closing session {0}", insession );
            try {
                insession.close();
            } catch (JMSException e) {
            } finally {
                insession = null;
            }
        }

    	if (outsession != null) {
        	if ( !reconnecting ) Log.logger.log(Level.FINE, "Closing session {0}", outsession );
            try {
                outsession.close();
            } catch (JMSException e) {
            } finally {
                outsession = null;
            }
        }

        if (connection != null) {
        	if ( !reconnecting ) Log.logger.log(Level.FINE, "Closing connection {0}",connection );
            try {
                connection.close();
            } catch (JMSException e) {
            } finally {
                connection = null;
            }
        }

        if ( ! reconnecting ) {
        	inQueue = null;
        	outQueue = null;
        	cf = null;
        }
	}

	public final void run() {
		try {
			messageConsumer.setMessageListener(this);
			Log.logger.log( Level.FINE, "connected to command server & listening on {0}, responses to {1}",
					new Object[] {inQueue.toString(), outQueue.toString()});
			sendMessage("command server listening on " + inQueue.toString());
			waitForShutdownSignal();
		} catch (JMSException e) {
			// swallow
		} catch (InterruptedException e) {
			// swallow
		}
	}

	/**
	 * Causes the current thread to block until signalShutdown is called. This
	 * is used by WorkerThreads which are not actively polling the shutdown
	 * field.
	 *
	 * @throws InterruptedException
	 *             This is thrown if the thread is interrupted outside of the
	 *             expected shutdown period.
	 */
	protected void waitForShutdownSignal() throws InterruptedException {

		if (mutexWaiting == null) {
			mutexWaiting = new Object();
		}
		try {
			synchronized (mutexWaiting) {
				mutexWaiting.wait();
			}
		} catch (InterruptedException e) {
			if (!shutdown) {
				throw e;
			} // else swallowed
		}

	}

	// process incoming messages
	public void onMessage(Message m) {
		try {

			// convert the message to text
			String txt = ((TextMessage) m).getText();
			processMessage(txt);

		} catch(JMSException e) {
			Log.logger.log( Level.WARNING, "error processing message {0}", m.toString());
		}

	}

	// send outgoing messages
	@Override
	public final void sendMessage(String message) {

		if (id != null) {
			message = "id=" + id + "," + message;
		}

		try {
			if (message != null) {
				outMessage = outsession.createTextMessage(message);
			} else {
				outMessage = outsession.createTextMessage("null");
			}

			// send the message
			messageProducer.send(outMessage);

		} catch (JMSException e) {
			Log.logger.log( Level.WARNING, "error sending message to {0}: {1}", new Object[] {outQueue.toString(), e.getMessage()});
		}

	}
}


text:
if RubyIOC::Platform.windows?
	require "win32ole"
end

module RubyIOC
	module IOCItem
		class EventLogItem < RubyIOC::IOCTerm
			def get_type
				"EventLogItem"
			end

			def scan(indicator)
				if RubyIOC::Platform.windows?
					return search_windows_events(indicator)
				else
					puts "Not implemented on this platform yet"
				end
			end

			def search_windows_events(indicator)
				wmi = WIN32OLE.connect("winmgmts:{impersonationLevel=impersonate,(Security)}!\\")
				query = "Select * from Win32_NTLogEvent where "

				indicator.each { |i|
					case i[:search]
					when "EventLogItem/category"
						query += "CategoryString = '#{i[:content]}' "
					when "EventLogItem/categoryNum"
						query += "Category = #{i[:content]} "
					when "EventLogItem/genTime"
					when "EventLogItem/EID"
						query += "EventIdentifier = #{i[:content]} "
					when "EventLogItem/log"
						query += "LogFile = '#{i[:content]}' "
					when "EventLogItem/machine"
						query += "ComputerName = '#{i[:content]}' "
					when "EventLogItem/message"
						query += "Message like '%#{i[:content]}%' "
					when "EventLogItem/source"
						query += "SourceName = '#{i[:content]}' "
					when "EventLogItem/type"
						query += "Type = '#{i[:content]}' "
					when "EventLogItem/user"
						query += "User like '%#{i[:content]}%' "
					when "EventLogItem/writeTime"
					end
				}

				events = wmi.ExecQuery(query)
				events.each { |e|
					return true
				}
				return false
			end
		end

		class EventLogItemFactory < RubyIOC::IOCItem::IOCItemFactory
			def get_type
				"EventLogItem"
			end

			def create
				EventLogItem.instance
			end
		end

		EventLogItemFactory.add_factory(EventLogItemFactory)
	end
end


text:
package io.deepsense.models.workflows

import io.deepsense.commons.exception.FailureDescription
import io.deepsense.commons.models.Entity
import io.deepsense.graph.nodestate.{Draft, NodeStatus}

/**
  *
  * @param nodeStatus Status of the node
  * @param reports None means we have no knowledge about reports.
  *                Empty EntitiesMap means there is no reports.
  */
case class NodeState(nodeStatus: NodeStatus, reports: Option[EntitiesMap]) {

  def reportEntities(): Map[Entity.Id, EntitiesMap.Entry] = {
    reports.map(_.entities).getOrElse(Map())
  }

  def withoutReports: NodeState = copy(reports = None)

  def abort: NodeState = copy(nodeStatus = nodeStatus.abort)
  def enqueue: NodeState = copy(nodeStatus = nodeStatus.enqueue)
  def draft: NodeState = copy(nodeStatus = Draft(nodeStatus.results))
  def fail(failureDescription: FailureDescription): NodeState = {
    // failure means reseting reports
    copy(nodeStatus = nodeStatus.fail(failureDescription), Some(EntitiesMap()))
  }

  def isCompleted: Boolean = nodeStatus.isCompleted
  def isDraft: Boolean = nodeStatus.isDraft
  def isQueued: Boolean = nodeStatus.isQueued
  def isRunning: Boolean = nodeStatus.isRunning
  def isFailed: Boolean = nodeStatus.isFailed
  def isAborted: Boolean = nodeStatus.isAborted

  def finish(entitiesIds: Seq[Entity.Id], results: EntitiesMap): NodeState = {
    NodeState(nodeStatus.finish(entitiesIds), Some(results))
  }

  def start: NodeState = copy(nodeStatus = nodeStatus.start)
}

object NodeState {

  def draft: NodeState =
    NodeState(Draft(), Some(EntitiesMap()))
}


text:
            <?php
            use yii\helpers\Html;
            use yii\bootstrap\ActiveForm;
            use common\widgets\Tool;
            use yii\web;
            use yii\base;
            use unclead\widgets\MultipleInput;
            use vova07\fileapi\Widget;
            use yii\helpers\ArrayHelper;
            $admin_cur="brand";
            ?>
            <?=$this->render(\common\widgets\Variable::$layoutAdminLeftMenu_view,['admin_cur'=>$admin_cur]); ?>

            <?php
            $this->title='添加品牌';
            echo  Tool::setBreadcrumbs([['品牌管理',\common\widgets\Variable::$customerBrand_url],[$this->title]])
            ?>

                    <?php
                    $form = ActiveForm::begin([
                        'id' => 'add-seller-form',
                        'action'=>\common\widgets\Variable::$addBrand_url,
                        'method'=>'post'
                    ]);
                    ?>

                        <?= $form->field($model, 'name', ['options' => ['class' => 'form-group col-lg-6 paddingLeft']])->textInput()->label('品牌名称') ?>
                        <?=$form->field($model, 'sort', ['options' => ['class' => 'form-group col-lg-6 paddingLeft']])->textInput()->label('展示顺序');?>

                        <?=$form->field($model, 'parentId', ['options' => ['class' => 'form-group col-lg-3 paddingLeft']])->dropDownList(ArrayHelper::map($catModel,'id','name'), ['prompt' => '请选择所属客户分类'])->label('所属客户分类');?>

                    <?= $form->field($model, 'clogo')->label('品牌logo(灰色)')->widget('common\widgets\file_upload\FileUpload',[
                        'config'=>[]
                    ]) ?>
                    <?= $form->field($model, 'blogo')->label('品牌logo(彩色)')->widget('common\widgets\file_upload\FileUpload',[
                        'config'=>[]
                    ]) ?>
                    <?php
                    echo   $form->errorSummary($model,['header'=>false]);
                    ?>

                        <?= Html::submitButton('确定', ['class' => 'btn btn-primary', 'name' => 'add-seller-button','error'=>'ss']) ?>
                        <?= Html::resetButton('重置', ['class' => 'btn btn-primary', 'name' => 'reset-button','error'=>'ss']) ?>
                        <a class="btn-cancel" href="<?php echo \common\widgets\Variable::$customerBrand_url ;?>">返回

                    <?php ActiveForm::end(); ?>


text: [some link](#some-header)


text:
/*
 * SpiderMonkey wrapper to compress Javascript source files,
 * uses Dean Edwards (http://dean.edwards.name/packer/)
 *
 * Author: Diego Perini <diego.perini@gmail.com>
 *
 * Usage: fusecomp.js < input > output (uses stdin/stdout)
 *
 * Depends on correctly installed SpiderMonkey executable (js)
 *
 * Released under the Creative Commons license:
 * http://creativecommons.org/licenses/by/3.0/
 */

// import Dean Edwards project files
load("build/packer/base2.js");
load("build/packer/packer.js");

// read file from stdin
function _readFile(from) {
  var outstr = '', line = '';
  while ((line = readline()) != null) {
      outstr += line + '\x0a';
  }
  return outstr;
}

// read from input pack and send to output
(function minify() {
  // create new packer instance
  var packer = new Packer();
  // shrink!
  print(packer.pack(_readFile(), 0, 1, 1));
})();


text:
A simple starter project demonstrating on how to use capitalone public api to create an account.

### Usage
- Clone or fork this repository
- Make sure you have [node.js](https://nodejs.org/) installed version 5+
- Make sure you have NPM installed version 3+
- `WINDOWS ONLY` run `npm install -g webpack webpack-dev-server typings typescript` to install global dependencies
- run `npm install` to install dependencies
- `WINDOWS ONLY` run `npm run typings-install` to install typings
- run `npm start` to fire up dev server
- open browser to [`http://localhost:8001`](http://localhost:8001)

### Debug
Although the reference application doesn't write a formal log file, it does write all of the received JSON responses to the terminal window; you can use this information to match what you're seeing in the app's UI with the data the API is returning.
- ```DEBUG=http npm start``` : starts the app in debug mode where you can see the request/responses from the app to api

## Contributors
We welcome your interest in Capital One's Open Source Projects (the "Project"). Any Contributor to the Project must accept and sign a CLA indicating agreement to the license terms. Except for the license granted in this CLA to Capital One and to recipients of software distributed by Capital One, You reserve all right, title, and interest in and to your Contributions; this CLA does not impact your rights to use your own contributions for any other purpose.

##### [Link to CLA] (https://docs.google.com/forms/d/19LpBBjykHPox18vrZvBbZUcK6gQTj7qv1O5hCduAZFU/viewform)

This project adheres to the [Open Source Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code.

[code-of-conduct]: https://developer.capitalone.com/single/code-of-conduct/

### Contribution Guidelines
We encourage any contributions that align with the intent of this project and add more functionality or languages that other developers can make use of. To contribute to the project, please submit a PR for our review. Before contributing any source code, familiarize yourself with the Apache License 2.0 (LICENSE.txt), which controls the licensing for this project.


text:
<?php
/**
 * Created by PhpStorm.
 * User: Îôèñ
 * Date: 02.12.2015
 * Time: 15:00
 */

namespace backend\modules\request_type\models;

class RequestType extends \common\models\db\RequestType
{

}


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

namespace Microsoft.WindowsAzure.Management.Cmdlets
{
    using System;
    using System.Management.Automation;
    using Extensions;

    /// <summary>
    /// Selects a subscription from the previously imported ones.
    /// </summary>
    [Cmdlet(VerbsCommon.Select, "AzureSubscription", DefaultParameterSetName = "Set")]
    public class SelectAzureSubscriptionCommand : PSCmdlet
    {
        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the subscription.", ParameterSetName = "Set")]
        [ValidateNotNullOrEmpty]
        public string SubscriptionName { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "Specify to clear the current selection.", ParameterSetName = "Clear")]
        [ValidateNotNullOrEmpty]
        public SwitchParameter Clear { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Subscription data file.")]
        [ValidateNotNullOrEmpty]
        public string SubscriptionDataFile { get; set; }

        internal void SelectSubscriptionProcess(string parameterSetName, string subscriptionName, string subscriptionsDataFile)
        {
            switch (parameterSetName)
            {
                case "Set":
                    this.SetCurrentSubscription(
                        subscriptionName,
                        subscriptionsDataFile);
                    break;
                case "Clear":
                    this.ClearCurrentSubscription();
                    break;
            }
        }

        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();
                SelectSubscriptionProcess(
                    ParameterSetName,
                    SubscriptionName,
                    this.ResolvePath(SubscriptionDataFile));
            }
            catch (Exception exception)
            {
                WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
            }
        }
    }
}


text:
import {FocusMonitor} from '@angular/cdk/a11y';
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {
  AfterContentInit,
  Attribute,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  forwardRef,
  Input,
  OnDestroy,
  Output,
  ViewChild,
  ViewEncapsulation,
  Optional,
  Inject,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {
  CanColor, CanColorCtor,
  CanDisable, CanDisableCtor,
  CanDisableRipple, CanDisableRippleCtor,
  HasTabIndex, HasTabIndexCtor,
  mixinColor,
  mixinDisabled,
  mixinDisableRipple,
  mixinTabIndex,
} from '@angular/material/core';
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
import {
  MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS,
  MatSlideToggleDefaultOptions
} from './slide-toggle-config';

// Increasing integer for generating unique ids for slide-toggle components.
let nextUniqueId = 0;

/** @docs-private */
export const MAT_SLIDE_TOGGLE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => MatSlideToggle),
  multi: true
};

/** Change event object emitted by a MatSlideToggle. */
export class MatSlideToggleChange {
  constructor(
    /** The source MatSlideToggle of the event. */
    public source: MatSlideToggle,
    /** The new `checked` value of the MatSlideToggle. */
    public checked: boolean) { }
}

// Boilerplate for applying mixins to MatSlideToggle.
/** @docs-private */
class MatSlideToggleBase {
  constructor(public _elementRef: ElementRef) {}
}
const _MatSlideToggleMixinBase:
    HasTabIndexCtor &
    CanColorCtor &
    CanDisableRippleCtor &
    CanDisableCtor &
    typeof MatSlideToggleBase =
        mixinTabIndex(mixinColor(mixinDisableRipple(mixinDisabled(MatSlideToggleBase)), 'accent'));

/** Represents a slidable "switch" toggle that can be moved between on and off. */
@Component({
  selector: 'mat-slide-toggle',
  exportAs: 'matSlideToggle',
  host: {
    'class': 'mat-slide-toggle',
    '[id]': 'id',
    // Needs to be `-1` so it can still receive programmatic focus.
    '[attr.tabindex]': 'disabled ? null : -1',
    '[attr.aria-label]': 'null',
    '[attr.aria-labelledby]': 'null',
    '[class.mat-checked]': 'checked',
    '[class.mat-disabled]': 'disabled',
    '[class.mat-slide-toggle-label-before]': 'labelPosition == "before"',
    '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
  },
  templateUrl: 'slide-toggle.html',
  styleUrls: ['slide-toggle.css'],
  providers: [MAT_SLIDE_TOGGLE_VALUE_ACCESSOR],
  inputs: ['disabled', 'disableRipple', 'color', 'tabIndex'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestroy, AfterContentInit,
                                                                        ControlValueAccessor,
                                                                        CanDisable, CanColor,
                                                                        HasTabIndex,
                                                                        CanDisableRipple {
  private _onChange = (_: any) => {};
  private _onTouched = () => {};

  private _uniqueId: string = `mat-slide-toggle-${++nextUniqueId}`;
  private _required: boolean = false;
  private _checked: boolean = false;

  /** Reference to the thumb HTMLElement. */
  @ViewChild('thumbContainer') _thumbEl: ElementRef;

  /** Reference to the thumb bar HTMLElement. */
  @ViewChild('toggleBar') _thumbBarEl: ElementRef;

  /** Name value will be applied to the input element if present. */
  @Input() name: string | null = null;

  /** A unique id for the slide-toggle input. If none is supplied, it will be auto-generated. */
  @Input() id: string = this._uniqueId;

  /** Whether the label should appear after or before the slide-toggle. Defaults to 'after'. */
  @Input() labelPosition: 'before' | 'after' = 'after';

  /** Used to set the aria-label attribute on the underlying input element. */
  @Input('aria-label') ariaLabel: string | null = null;

  /** Used to set the aria-labelledby attribute on the underlying input element. */
  @Input('aria-labelledby') ariaLabelledby: string | null = null;

  /** Whether the slide-toggle is required. */
  @Input()
  get required(): boolean { return this._required; }
  set required(value) { this._required = coerceBooleanProperty(value); }

  /** Whether the slide-toggle element is checked or not. */
  @Input()
  get checked(): boolean { return this._checked; }
  set checked(value) {
    this._checked = coerceBooleanProperty(value);
    this._changeDetectorRef.markForCheck();
  }
  /** An event will be dispatched each time the slide-toggle changes its value. */
  @Output() readonly change: EventEmitter<MatSlideToggleChange> =
      new EventEmitter<MatSlideToggleChange>();

  /**
   * An event will be dispatched each time the slide-toggle input is toggled.
   * This event is always emitted when the user toggles the slide toggle, but this does not mean
   * the slide toggle's value has changed.
   */
  @Output() readonly toggleChange: EventEmitter<void> = new EventEmitter<void>();

  /** Returns the unique id for the visual hidden input. */
  get inputId(): string { return `${this.id || this._uniqueId}-input`; }

  /** Reference to the underlying input element. */
  @ViewChild('input') _inputElement: ElementRef<HTMLInputElement>;

  constructor(elementRef: ElementRef,
              private _focusMonitor: FocusMonitor,
              private _changeDetectorRef: ChangeDetectorRef,
              @Attribute('tabindex') tabIndex: string,
              @Inject(MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS)
                  public defaults: MatSlideToggleDefaultOptions,
              @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) {
    super(elementRef);
    this.tabIndex = parseInt(tabIndex) || 0;
  }

  ngAfterContentInit() {
    this._focusMonitor
      .monitor(this._elementRef, true)
      .subscribe(focusOrigin => {
        // Only forward focus manually when it was received programmatically or through the
        // keyboard. We should not do this for mouse/touch focus for two reasons:
        // 1. It can prevent clicks from landing in Chrome (see #18269).
        // 2. They're already handled by the wrapping `label` element.
        if (focusOrigin === 'keyboard' || focusOrigin === 'program') {
          this._inputElement.nativeElement.focus();
        } else if (!focusOrigin) {
          // When a focused element becomes disabled, the browser *immediately* fires a blur event.
          // Angular does not expect events to be raised during change detection, so any state
          // change (such as a form control's 'ng-touched') will cause a changed-after-checked
          // error. See https://github.com/angular/angular/issues/17793. To work around this,
          // we defer telling the form control it has been touched until the next tick.
          Promise.resolve().then(() => this._onTouched());
        }
      });
  }

  ngOnDestroy() {
    this._focusMonitor.stopMonitoring(this._elementRef);
  }

  /** Method being called whenever the underlying input emits a change event. */
  _onChangeEvent(event: Event) {
    // We always have to stop propagation on the change event.
    // Otherwise the change event, from the input element, will bubble up and
    // emit its event object to the component's `change` output.
    event.stopPropagation();
    this.toggleChange.emit();

    // When the slide toggle's config disables toggle change event by setting
    // `disableToggleValue: true`, the slide toggle's value does not change, and the
    // checked state of the underlying input needs to be changed back.
    if (this.defaults.disableToggleValue) {
      this._inputElement.nativeElement.checked = this.checked;
      return;
    }

    // Sync the value from the underlying input element with the component instance.
    this.checked = this._inputElement.nativeElement.checked;

    // Emit our custom change event only if the underlying input emitted one. This ensures that
    // there is no change event, when the checked state changes programmatically.
    this._emitChangeEvent();
  }

  /** Method being called whenever the slide-toggle has been clicked. */
  _onInputClick(event: Event) {
    // We have to stop propagation for click events on the visual hidden input element.
    // By default, when a user clicks on a label element, a generated click event will be
    // dispatched on the associated input element. Since we are using a label element as our
    // root container, the click event on the `slide-toggle` will be executed twice.
    // The real click event will bubble up, and the generated click event also tries to bubble up.
    // This will lead to multiple click events.
    // Preventing bubbling for the second event will solve that issue.
    event.stopPropagation();
  }

  /** Implemented as part of ControlValueAccessor. */
  writeValue(value: any): void {
    this.checked = !!value;
  }

  /** Implemented as part of ControlValueAccessor. */
  registerOnChange(fn: any): void {
    this._onChange = fn;
  }

  /** Implemented as part of ControlValueAccessor. */
  registerOnTouched(fn: any): void {
    this._onTouched = fn;
  }

  /** Implemented as a part of ControlValueAccessor. */
  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
    this._changeDetectorRef.markForCheck();
  }

  /** Focuses the slide-toggle. */
  focus(options?: FocusOptions): void {
    this._focusMonitor.focusVia(this._inputElement, 'keyboard', options);
  }

  /** Toggles the checked state of the slide-toggle. */
  toggle(): void {
    this.checked = !this.checked;
    this._onChange(this.checked);
  }

  /**
   * Emits a change event on the `change` output. Also notifies the FormControl about the change.
   */
  private _emitChangeEvent() {
    this._onChange(this.checked);
    this.change.emit(new MatSlideToggleChange(this, this.checked));
  }

  /** Method being called whenever the label text changes. */
  _onLabelTextChange() {
    // Since the event of the `cdkObserveContent` directive runs outside of the zone, the
    // slide-toggle component will be only marked for check, but no actual change detection runs
    // automatically. Instead of going back into the zone in order to trigger a change detection
    // which causes *all* components to be checked (if explicitly marked or not using OnPush),
    // we only trigger an explicit change detection for the slide-toggle view and its children.
    this._changeDetectorRef.detectChanges();
  }

  static ngAcceptInputType_required: BooleanInput;
  static ngAcceptInputType_checked: BooleanInput;
  static ngAcceptInputType_disabled: BooleanInput;
  static ngAcceptInputType_disableRipple: BooleanInput;
}


text:
require 'chewy/query/criteria'
require 'chewy/query/filters'
require 'chewy/query/loading'
require 'chewy/query/pagination'

module Chewy
  # Query allows you to create ES search requests with convenient
  # chainable DSL. Queries are lazy evaluated and might be merged.
  # The same DSL is used for whole index or individual types query build.
  #
  # @example
  #   UsersIndex.filter{ age < 42 }.query(text: {name: 'Alex'}).limit(20)
  #   UsersIndex::User.filter{ age < 42 }.query(text: {name: 'Alex'}).limit(20)
  #
  class Query
    include Enumerable
    include Loading
    include Pagination
    include Chewy::Search::Scoping

    DELEGATED_METHODS = %i[
      explain query_mode filter_mode post_filter_mode
      timeout limit offset highlight min_score rescore facets script_score
      boost_factor weight random_score field_value_factor decay aggregations
      suggest none strategy query filter post_filter boost_mode
      score_mode order reorder only types delete_all find total
      total_count total_entries unlimited script_fields track_scores preference
    ].to_set.freeze

    delegate :each, :count, :size, to: :_collection
    alias_method :to_ary, :to_a

    attr_reader :_indexes, :_types, :options, :criteria

    def initialize(*indexes_or_types_and_options)
      @options = indexes_or_types_and_options.extract_options!
      @_types = indexes_or_types_and_options.select { |klass| klass < Chewy::Type }
      @_indexes = indexes_or_types_and_options.select { |klass| klass < Chewy::Index }
      @_indexes |= @_types.map(&:index)
      @criteria = Criteria.new
    end

    # A compatibility layer with the new request DSL.
    def render
      _request
    end

    # Comparation with other query or collection
    # If other is collection - search request is executed and
    # result is used for comparation
    #
    # @example
    #   UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}) # => true
    #   UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}).to_a # => true
    #   UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Winnie'}) # => false
    #
    def ==(other)
      super || other.is_a?(self.class) ? other.criteria == criteria : other == to_a
    end

    # Adds `explain` parameter to search request.
    #
    # @example
    #   UsersIndex.filter(term: {name: 'Johny'}).explain
    #   UsersIndex.filter(term: {name: 'Johny'}).explain(true)
    #   UsersIndex.filter(term: {name: 'Johny'}).explain(false)
    #
    # Calling explain without any arguments sets explanation flag to true.
    # With `explain: true`, every result object has `_explanation`
    # method
    #
    # @example
    #   UsersIndex::User.filter(term: {name: 'Johny'}).explain.first._explanation # => {...}
    #
    def explain(value = nil)
      chain { criteria.update_request_options explain: (value.nil? ? true : value) }
    end

    # Adds `script_fields` parameter to search request.
    #
    # @example
    #  UsersIndex.script_fields(
    #    distance: {
    #      params: {
    #        lat: 37.569976,
    #        lon: -122.351591
    #      },
    #      script: "doc['coordinates'].distanceInMiles(lat, lon)"
    #    }
    #  )
    def script_fields(value)
      chain { criteria.update_script_fields(value) }
    end

    # Sets query compilation mode for search request.
    # Not used if only one filter for search is specified.
    # Possible values:
    #
    # * `:must`
    #   Default value. Query compiles into a bool `must` query.
    #
    # @example
    #     UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
    #       # => {body: {
    #              query: {bool: {must: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #            }}
    #
    # * `:should`
    #   Query compiles into a bool `should` query.
    #
    # @example
    #     UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(:should)
    #       # => {body: {
    #              query: {bool: {should: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #            }}
    #
    # * Any acceptable `minimum_should_match` value (1, '2', '75%')
    #   Query compiles into a bool `should` query with `minimum_should_match` set.
    #
    # @example
    #     UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode('50%')
    #       # => {body: {
    #              query: {bool: {
    #                should: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
    #                minimum_should_match: '50%'
    #              }}
    #            }}
    #
    # * `:dis_max`
    #   Query compiles into a `dis_max` query.
    #
    # @example
    #     UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(:dis_max)
    #       # => {body: {
    #              query: {dis_max: {queries: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #            }}
    #
    # * Any Float value (0.0, 0.7, 1.0)
    #   Query compiles into a `dis_max` query with `tie_breaker` option set.
    #
    # @example
    #     UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(0.7)
    #       # => {body: {
    #              query: {dis_max: {
    #                queries: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
    #                tie_breaker: 0.7
    #              }}
    #            }}
    #
    # Default value for `:query_mode` might be changed
    # with `Chewy.query_mode` config option.
    #
    # @example
    #   Chewy.query_mode = :dis_max
    #   Chewy.query_mode = '50%'
    #
    def query_mode(value)
      chain { criteria.update_options query_mode: value }
    end

    # Sets query compilation mode for search request.
    # Not used if only one filter for search is specified.
    # Possible values:
    #
    # * `:and`
    #   Default value. Filter compiles into an `and` filter.
    #
    # @example
    #     UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }
    #       # => {body: {query: {filtered: {
    #              query: {...},
    #              filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
    #            }}}}
    #
    # * `:or`
    #   Filter compiles into an `or` filter.
    #
    # @example
    #     UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:or)
    #       # => {body: {query: {filtered: {
    #              query: {...},
    #              filter: {or: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
    #            }}}}
    #
    # * `:must`
    #   Filter compiles into a bool `must` filter.
    #
    # @example
    #     UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:must)
    #       # => {body: {query: {filtered: {
    #              query: {...},
    #              filter: {bool: {must: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #            }}}}
    #
    # * `:should`
    #   Filter compiles into a bool `should` filter.
    #
    # @example
    #     UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:should)
    #       # => {body: {query: {filtered: {
    #              query: {...},
    #              filter: {bool: {should: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #            }}}}
    #
    # * Any acceptable `minimum_should_match` value (1, '2', '75%')
    #   Filter compiles into bool `should` filter with `minimum_should_match` set.
    #
    # @example
    #     UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode('50%')
    #       # => {body: {query: {filtered: {
    #              query: {...},
    #              filter: {bool: {
    #                should: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
    #                minimum_should_match: '50%'
    #              }}
    #            }}}}
    #
    # Default value for `:filter_mode` might be changed
    # with `Chewy.filter_mode` config option.
    #
    # @example
    #   Chewy.filter_mode = :should
    #   Chewy.filter_mode = '50%'
    #
    def filter_mode(value)
      chain { criteria.update_options filter_mode: value }
    end

    # Acts the same way as `filter_mode`, but used for `post_filter`.
    # Note that it fallbacks by default to `Chewy.filter_mode` if
    # `Chewy.post_filter_mode` is nil.
    #
    # @example
    #   UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode(:and)
    #   UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode(:should)
    #   UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode('50%')
    #
    def post_filter_mode(value)
      chain { criteria.update_options post_filter_mode: value }
    end

    # A search timeout, bounding the search request to be executed within the
    # specified time value and bail with the hits accumulated up to that point
    # when expired. Defaults to no timeout.
    #
    # By default, the coordinating node waits to receive a response from all
    # shards. If one node is having trouble, it could slow down the response to
    # all search requests.
    #
    # The timeout parameter tells the coordinating node how long it should wait
    # before giving up and just returning the results that it already has. It
    # can be better to return some results than none at all.
    #
    # The response to a search request will indicate whether the search timed
    # out and how many shards responded successfully:
    #
    # @example
    #   ...
    #   "timed_out":     true,
    #   "_shards": {
    #       "total":      5,
    #       "successful": 4,
    #       "failed":     1
    #   },
    #   ...
    #
    # The primary shard assigned to perform the index operation might not be
    # available when the index operation is executed. Some reasons for this
    # might be that the primary shard is currently recovering from a gateway or
    # undergoing relocation. By default, the index operation will wait on the
    # primary shard to become available for up to 1 minute before failing and
    # responding with an error. The timeout parameter can be used to explicitly
    # specify how long it waits.
    #
    # @example
    #   UsersIndex.timeout("5000ms")
    #
    # Timeout is not a circuit breaker.
    #
    # It should be noted that this timeout does not halt the execution of the
    # query, it merely tells the coordinating node to return the results
    # collected so far and to close the connection. In the background, other
    # shards may still be processing the query even though results have been
    # sent.
    #
    # Use the timeout because it is important to your SLA, not because you want
    # to abort the execution of long running queries.
    #
    def timeout(value)
      chain { criteria.update_request_options timeout: value }
    end

    # Sets elasticsearch `size` search request param
    # Default value is set in the elasticsearch and is 10.
    #
    # @example
    #  UsersIndex.filter{ name == 'Johny' }.limit(100)
    #     # => {body: {
    #            query: {...},
    #            size: 100
    #          }}
    #
    def limit(value = nil, &block)
      chain { criteria.update_request_options size: block || Integer(value) }
    end

    # Sets elasticsearch `from` search request param
    #
    # @example
    #  UsersIndex.filter{ name == 'Johny' }.offset(300)
    #     # => {body: {
    #            query: {...},
    #            from: 300
    #          }}
    #
    def offset(value = nil, &block)
      chain { criteria.update_request_options from: block || Integer(value) }
    end

    # Elasticsearch highlight query option support
    #
    # @example
    #   UsersIndex.query(...).highlight(fields: { ... })
    #
    def highlight(value)
      chain { criteria.update_request_options highlight: value }
    end

    # Elasticsearch rescore query option support
    #
    # @example
    #   UsersIndex.query(...).rescore(query: { ... })
    #
    def rescore(value)
      chain { criteria.update_request_options rescore: value }
    end

    # Elasticsearch minscore option support
    #
    # @example
    #   UsersIndex.query(...).min_score(0.5)
    #
    def min_score(value)
      chain { criteria.update_request_options min_score: value }
    end

    # Elasticsearch track_scores option support
    #
    # @example
    #   UsersIndex.query(...).track_scores(true)
    #
    def track_scores(value)
      chain { criteria.update_request_options track_scores: value }
    end

    # Adds facets section to the search request.
    # All the chained facets a merged and added to the
    # search request
    #
    # @example
    #   UsersIndex.facets(tags: {terms: {field: 'tags'}}).facets(ages: {terms: {field: 'age'}})
    #     # => {body: {
    #            query: {...},
    #            facets: {tags: {terms: {field: 'tags'}}, ages: {terms: {field: 'age'}}}
    #          }}
    #
    # If called parameterless - returns result facets from ES performing request.
    # Returns empty hash if no facets was requested or resulted.
    #
    def facets(params = nil)
      raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
      if params
        chain { criteria.update_facets params }
      else
        _response['facets'] || {}
      end
    end

    # Adds a script function to score the search request. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # @example
    #   UsersIndex.script_score("doc['boost'].value", params: { modifier: 2 })
    #       # => {body:
    #              query: {
    #                function_score: {
    #                  query: { ...},
    #                  functions: [{
    #                    script_score: {
    #                       script: "doc['boost'].value * modifier",
    #                       params: { modifier: 2 }
    #                     }
    #                    }
    #                  }]
    #                } } }
    def script_score(script, options = {})
      scoring = {script_score: {script: script}.merge(options)}
      chain { criteria.update_scores scoring }
    end

    # Adds a boost factor to the search request. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # This probably only makes sense if you specify a filter
    # for the boost factor as well
    #
    # @example
    #   UsersIndex.boost_factor(23, filter: { term: { foo: :bar} })
    #       # => {body:
    #              query: {
    #                function_score: {
    #                  query: { ...},
    #                  functions: [{
    #                    boost_factor: 23,
    #                    filter: { term: { foo: :bar } }
    #                  }]
    #                } } }
    def boost_factor(factor, options = {})
      scoring = options.merge(boost_factor: factor.to_i)
      chain { criteria.update_scores scoring }
    end

    # Add a weight scoring function to the search. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # This probably only makes sense if you specify a filter
    # for the weight as well.
    #
    # @example
    #   UsersIndex.weight(23, filter: { term: { foo: :bar} })
    #       # => {body:
    #              query: {
    #                function_score: {
    #                  query: { ...},
    #                  functions: [{
    #                    weight: 23,
    #                    filter: { term: { foo: :bar } }
    #                  }]
    #                } } }
    def weight(factor, options = {})
      scoring = options.merge(weight: factor.to_i)
      chain { criteria.update_scores scoring }
    end

    # Adds a random score to the search request. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # This probably only makes sense if you specify a filter
    # for the random score as well.
    #
    # If you do not pass in a seed value, Time.now will be used
    #
    # @example
    #   UsersIndex.random_score(23, filter: { foo: :bar})
    #       # => {body:
    #              query: {
    #                function_score: {
    #                  query: { ...},
    #                  functions: [{
    #                    random_score: { seed: 23 },
    #                    filter: { foo: :bar }
    #                  }]
    #                } } }
    def random_score(seed = Time.now, options = {})
      scoring = options.merge(random_score: {seed: seed.to_i})
      chain { criteria.update_scores scoring }
    end

    # Add a field value scoring to the search. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # This function is only available in Elasticsearch 1.2 and
    # greater
    #
    # @example
    #   UsersIndex.field_value_factor(
    #                {
    #                  field: :boost,
    #                  factor: 1.2,
    #                  modifier: :sqrt
    #                }, filter: { foo: :bar})
    #       # => {body:
    #              query: {
    #                function_score: {
    #                  query: { ...},
    #                  functions: [{
    #                    field_value_factor: {
    #                      field: :boost,
    #                      factor: 1.2,
    #                      modifier: :sqrt
    #                    },
    #                    filter: { foo: :bar }
    #                  }]
    #                } } }
    def field_value_factor(settings, options = {})
      scoring = options.merge(field_value_factor: settings)
      chain { criteria.update_scores scoring }
    end

    # Add a decay scoring to the search. All scores are
    # added to the search request and combinded according to
    # `boost_mode` and `score_mode`
    #
    # The parameters have default values, but those may not
    # be very useful for most applications.
    #
    # @example
    #   UsersIndex.decay(
    #                :gauss,
    #                :field,
    #                origin: '11, 12',
    #                scale: '2km',
    #                offset: '5km',
    #                decay: 0.4,
    #                filter: { foo: :bar})
    #       # => {body:
    #              query: {
    #                gauss: {
    #                  query: { ...},
    #                  functions: [{
    #                    gauss: {
    #                      field: {
    #                        origin: '11, 12',
    #                        scale: '2km',
    #                        offset: '5km',
    #                        decay: 0.4
    #                      }
    #                    },
    #                    filter: { foo: :bar }
    #                  }]
    #                } } }
    def decay(function, field, options = {})
      field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
      scoring = options.merge(function => {
        field => field_options
      })
      chain { criteria.update_scores scoring }
    end

    # Sets `preference` for request.
    # For instance, one can use `preference=_primary` to execute only on the primary shards.
    #
    # @example
    #   scope = UsersIndex.preference(:_primary)
    #
    def preference(value)
      chain { criteria.update_search_options preference: value }
    end

    # Sets elasticsearch `aggregations` search request param
    #
    # @example
    #  UsersIndex.filter{ name == 'Johny' }.aggregations(category_id: {terms: {field: 'category_ids'}})
    #     # => {body: {
    #            query: {...},
    #            aggregations: {
    #              terms: {
    #                field: 'category_ids'
    #              }
    #            }
    #          }}
    #
    def aggregations(params = nil)
      @_named_aggs ||= _build_named_aggs
      @_fully_qualified_named_aggs ||= _build_fqn_aggs
      if params
        params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
        params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
        chain { criteria.update_aggregations params }
      else
        _response['aggregations'] || {}
      end
    end
    alias_method :aggs, :aggregations

    # In this simplest of implementations each named aggregation must be uniquely named
    def _build_named_aggs
      named_aggs = {}
      @_indexes.each do |index|
        index.types.each do |type|
          type._agg_defs.each do |agg_name, prc|
            named_aggs[agg_name] = prc.call
          end
        end
      end
      named_aggs
    end

    def _build_fqn_aggs
      named_aggs = {}
      @_indexes.each do |index|
        named_aggs[index.to_s.downcase] ||= {}
        index.types.each do |type|
          named_aggs[index.to_s.downcase][type.to_s.downcase] ||= {}
          type._agg_defs.each do |agg_name, prc|
            named_aggs[index.to_s.downcase][type.to_s.downcase][agg_name.to_s.downcase] = prc.call
          end
        end
      end
      named_aggs
    end

    def _get_fully_qualified_named_agg(str)
      parts = str.scan(/\A(\S+)#(\S+)\.(\S+)\z/).first
      idx = "#{parts[0]}index"
      type = "#{idx}::#{parts[1]}"
      agg_name = parts[2]
      @_fully_qualified_named_aggs[idx][type][agg_name]
    end

    # Sets elasticsearch `suggest` search request param
    #
    # @example
    #  UsersIndex.suggest(name: {text: 'Joh', term: {field: 'name'}})
    #     # => {body: {
    #            query: {...},
    #            suggest: {
    #              text: 'Joh',
    #              term: {
    #                field: 'name'
    #              }
    #            }
    #          }}
    #
    def suggest(params = nil)
      if params
        chain { criteria.update_suggest params }
      else
        _response['suggest'] || {}
      end
    end

    # Marks the criteria as having zero documents. This scope  always returns empty array
    # without touching the elasticsearch server.
    # All the chained calls of methods don't affect the result
    #
    # @example
    #   UsersIndex.none.to_a
    #     # => []
    #   UsersIndex.query(text: {name: 'Johny'}).none.to_a
    #     # => []
    #   UsersIndex.none.query(text: {name: 'Johny'}).to_a
    #     # => []
    #
    def none
      chain { criteria.update_options none: true }
    end

    # Setups strategy for top-level filtered query
    #
    # @example
    #    UsersIndex.filter { name == 'Johny'}.strategy(:leap_frog)
    #     # => {body: {
    #            query: { filtered: {
    #              filter: { term: { name: 'Johny' } },
    #              strategy: 'leap_frog'
    #            } }
    #          }}
    #
    def strategy(value = nil)
      chain { criteria.update_options strategy: value }
    end

    # Adds one or more query to the search request
    # Internally queries are stored as an array
    # While the full query compilation this array compiles
    # according to `:query_mode` option value
    #
    # By default it joines inside `must` query
    # See `#query_mode` chainable method for more info.
    #
    # @example
    #   UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
    #   UsersIndex::User.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
    #     # => {body: {
    #            query: {bool: {must: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
    #          }}
    #
    # If only one query was specified, it will become a result
    # query as is, without joining.
    #
    # @example
    #   UsersIndex.query(text: {name: 'Johny'})
    #     # => {body: {
    #            query: {text: {name: 'Johny'}}
    #          }}
    #
    def query(params)
      chain { criteria.update_queries params }
    end

    # Adds one or more filter to the search request
    # Internally filters are stored as an array
    # While the full query compilation this array compiles
    # according to `:filter_mode` option value
    #
    # By default it joins inside `and` filter
    # See `#filter_mode` chainable method for more info.
    #
    # Also this method supports block DSL.
    # See `Chewy::Query::Filters` for more info.
    #
    # @example
    #   UsersIndex.filter(term: {name: 'Johny'}).filter(range: {age: {lte: 42}})
    #   UsersIndex::User.filter(term: {name: 'Johny'}).filter(range: {age: {lte: 42}})
    #   UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }
    #     # => {body: {query: {filtered: {
    #            query: {...},
    #            filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
    #          }}}}
    #
    # If only one filter was specified, it will become a result
    # filter as is, without joining.
    #
    # @example
    #   UsersIndex.filter(term: {name: 'Johny'})
    #     # => {body: {query: {filtered: {
    #            query: {...},
    #            filter: {term: {name: 'Johny'}}
    #          }}}}
    #
    def filter(params = nil, &block)
      params = Filters.new(&block).__render__ if block
      chain { criteria.update_filters params }
    end

    # Adds one or more post_filter to the search request
    # Internally post_filters are stored as an array
    # While the full query compilation this array compiles
    # according to `:post_filter_mode` option value
    #
    # By default it joins inside `and` filter
    # See `#post_filter_mode` chainable method for more info.
    #
    # Also this method supports block DSL.
    # See `Chewy::Query::Filters` for more info.
    #
    # @example
    #   UsersIndex.post_filter(term: {name: 'Johny'}).post_filter(range: {age: {lte: 42}})
    #   UsersIndex::User.post_filter(term: {name: 'Johny'}).post_filter(range: {age: {lte: 42}})
    #   UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }
    #     # => {body: {
    #            post_filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
    #          }}
    #
    # If only one post_filter was specified, it will become a result
    # post_filter as is, without joining.
    #
    # @example
    #   UsersIndex.post_filter(term: {name: 'Johny'})
    #     # => {body: {
    #            post_filter: {term: {name: 'Johny'}}
    #          }}
    #
    def post_filter(params = nil, &block)
      params = Filters.new(&block).__render__ if block
      chain { criteria.update_post_filters params }
    end

    # Sets the boost mode for custom scoring/boosting.
    # Not used if no score functions are specified
    # Possible values:
    #
    # * `:multiply`
    #   Default value. Query score and function result are multiplied.
    #
    # @example
    #     UsersIndex.boost_mode('multiply').script_score('doc['boost'].value')
    #       # => {body: {query: function_score: {
    #         query: {...},
    #         boost_mode: 'multiply',
    #         functions: [ ... ]
    #       }}}
    #
    # * `:replace`
    #   Only function result is used, query score is ignored.
    #
    # * `:sum`
    #   Query score and function score are added.
    #
    # * `:avg`
    #   Average of query and function score.
    #
    # * `:max`
    #   Max of query and function score.
    #
    # * `:min`
    #   Min of query and function score.
    #
    # Default value for `:boost_mode` might be changed
    # with `Chewy.score_mode` config option.
    def boost_mode(value)
      chain { criteria.update_options boost_mode: value }
    end

    # Sets the scoring mode for combining function scores/boosts
    # Not used if no score functions are specified.
    # Possible values:
    #
    # * `:multiply`
    #   Default value. Scores are multiplied.
    #
    # @example
    #     UsersIndex.score_mode('multiply').script_score('doc['boost'].value')
    #       # => {body: {query: function_score: {
    #         query: {...},
    #         score_mode: 'multiply',
    #         functions: [ ... ]
    #       }}}
    #
    # * `:sum`
    #   Scores are summed.
    #
    # * `:avg`
    #   Scores are averaged.
    #
    # * `:first`
    #   The first function that has a matching filter is applied.
    #
    # * `:max`
    #   Maximum score is used.
    #
    # * `:min`
    #   Minimum score is used
    #
    # Default value for `:score_mode` might be changed
    # with `Chewy.score_mode` config option.
    #
    # @example
    #   Chewy.score_mode = :first
    #
    def score_mode(value)
      chain { criteria.update_options score_mode: value }
    end

    # Sets search request sorting
    #
    # @example
    #   UsersIndex.order(:first_name, :last_name).order(age: :desc).order(price: {order: :asc, mode: :avg})
    #     # => {body: {
    #            query: {...},
    #            sort: ['first_name', 'last_name', {age: 'desc'}, {price: {order: 'asc', mode: 'avg'}}]
    #          }}
    #
    def order(*params)
      chain { criteria.update_sort params }
    end

    # Cleans up previous search sorting and sets the new one
    #
    # @example
    #   UsersIndex.order(:first_name, :last_name).order(age: :desc).reorder(price: {order: :asc, mode: :avg})
    #     # => {body: {
    #            query: {...},
    #            sort: [{price: {order: 'asc', mode: 'avg'}}]
    #          }}
    #
    def reorder(*params)
      chain { criteria.update_sort params, purge: true }
    end

    # Sets search request field list
    #
    # @example
    #   UsersIndex.only(:first_name, :last_name).only(:age)
    #     # => {body: {
    #            query: {...},
    #            fields: ['first_name', 'last_name', 'age']
    #          }}
    #
    def only(*params)
      chain { criteria.update_fields params }
    end

    # Cleans up previous search field list and sets the new one
    #
    # @example
    #   UsersIndex.only(:first_name, :last_name).only!(:age)
    #     # => {body: {
    #            query: {...},
    #            fields: ['age']
    #          }}
    #
    def only!(*params)
      chain { criteria.update_fields params, purge: true }
    end

    # Specify types participating in the search result
    # Works via `types` filter. Always merged with another filters
    # with the `and` filter.
    #
    # @example
    #   UsersIndex.types(:admin, :manager).filters{ name == 'Johny' }.filters{ age <= 42 }
    #     # => {body: {query: {filtered: {
    #            query: {...},
    #            filter: {and: [
    #              {or: [
    #                {type: {value: 'admin'}},
    #                {type: {value: 'manager'}}
    #              ]},
    #              {term: {name: 'Johny'}},
    #              {range: {age: {lte: 42}}}
    #            ]}
    #          }}}}
    #
    #   UsersIndex.types(:admin, :manager).filters{ name == 'Johny' }.filters{ age <= 42 }.filter_mode(:or)
    #     # => {body: {query: {filtered: {
    #            query: {...},
    #            filter: {and: [
    #              {or: [
    #                {type: {value: 'admin'}},
    #                {type: {value: 'manager'}}
    #              ]},
    #              {or: [
    #                {term: {name: 'Johny'}},
    #                {range: {age: {lte: 42}}}
    #              ]}
    #            ]}
    #          }}}}
    #
    def types(*params)
      chain { criteria.update_types params }
    end

    # Acts the same way as `types`, but cleans up previously set types
    #
    # @example
    #   UsersIndex.types(:admin).types!(:manager)
    #     # => {body: {query: {filtered: {
    #            query: {...},
    #            filter: {type: {value: 'manager'}}
    #          }}}}
    #
    def types!(*params)
      chain { criteria.update_types params, purge: true }
    end

    # Sets `search_type` for request.
    # For instance, one can use `search_type=count` to fetch only total count of documents or to fetch only aggregations without fetching documents.
    #
    # @example
    #   scope = UsersIndex.search_type(:count)
    #   scope.count == 0  # no documents actually fetched
    #   scope.total == 10 # but we know a total count of them
    #
    #   scope = UsersIndex.aggs(max_age: { max: { field: 'age' } }).search_type(:count)
    #   max_age = scope.aggs['max_age']['value']
    #
    def search_type(value)
      chain { criteria.update_search_options search_type: value }
    end

    # Merges two queries.
    # Merges all the values in criteria with the same rules as values added manually.
    #
    # @example
    #   scope1 = UsersIndex.filter{ name == 'Johny' }
    #   scope2 = UsersIndex.filter{ age <= 42 }
    #   scope3 = UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }
    #
    #   scope1.merge(scope2) == scope3 # => true
    #
    def merge(other)
      chain { criteria.merge!(other.criteria) }
    end

    # Deletes all documents matching a query.
    #
    # @example
    #   UsersIndex.delete_all
    #   UsersIndex.filter{ age <= 42 }.delete_all
    #   UsersIndex::User.delete_all
    #   UsersIndex::User.filter{ age <= 42 }.delete_all
    #
    def delete_all
      if Runtime.version >= '2.0'
        plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
        raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
      end

      request = chain { criteria.update_options simple: true }.send(:_request)

      ActiveSupport::Notifications.instrument 'delete_query.chewy',
        request: request, indexes: _indexes, types: _types,
        index: _indexes.one? ? _indexes.first : _indexes,
        type: _types.one? ? _types.first : _types do
          if Runtime.version >= '2.0'
            path = Elasticsearch::API::Utils.__pathify(
              Elasticsearch::API::Utils.__listify(request[:index]),
              Elasticsearch::API::Utils.__listify(request[:type]),
              '/_query'
            )
            Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
          else
            Chewy.client.delete_by_query(request)
          end
        end
    end

    # Find all documents matching a query.
    #
    # @example
    #   UsersIndex.find(42)
    #   UsersIndex.filter{ age <= 42 }.find(42)
    #   UsersIndex::User.find(42)
    #   UsersIndex::User.filter{ age <= 42 }.find(42)
    #
    # In all the previous examples find will return a single object.
    # To get a collection - pass an array of ids.
    #
    # @example
    #    UsersIndex::User.find(42, 7, 3) # array of objects with ids in [42, 7, 3]
    #    UsersIndex::User.find([8, 13])  # array of objects with ids in [8, 13]
    #    UsersIndex::User.find([42])     # array of the object with id == 42
    #
    def find(*ids)
      results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a

      raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
      ids.one? && !ids.first.is_a?(Array) ? results.first : results
    end

    # Returns true if there are at least one document that matches the query
    #
    # @example
    #   PlacesIndex.query(...).filter(...).exists?
    #
    def exists?
      search_type(:count).total > 0
    end

    # Sets limit to be equal to total documents count
    #
    # @example
    #  PlacesIndex.query(...).filter(...).unlimited
    #

    def unlimited
      count_query = search_type(:count)
      offset(0).limit { count_query.total }
    end

    # Returns request total time elapsed as reported by elasticsearch
    #
    # @example
    #   UsersIndex.query(...).filter(...).took
    #
    def took
      _response['took']
    end

    # Returns request timed_out as reported by elasticsearch
    #
    # The timed_out value tells us whether the query timed out or not.
    #
    # By default, search requests do not timeout. If low response times are more
    # important to you than complete results, you can specify a timeout as 10 or
    # "10ms" (10 milliseconds), or "1s" (1 second). See #timeout method.
    #
    # @example
    #   UsersIndex.query(...).filter(...).timed_out
    #
    def timed_out
      _response['timed_out']
    end

  protected

    def initialize_clone(origin)
      @criteria = origin.criteria.clone
      reset
    end

  private

    def chain(&block)
      clone.tap { |q| q.instance_exec(&block) }
    end

    def reset
      @_request, @_response, @_results, @_collection = nil
    end

    def _request
      @_request ||= begin
        request = criteria.request_body
        request[:index] = _indexes_hash.keys
        request[:type] = _types.map(&:type_name)
        request
      end
    end

    def _response
      @_response ||= ActiveSupport::Notifications.instrument 'search_query.chewy',
        request: _request, indexes: _indexes, types: _types,
        index: _indexes.one? ? _indexes.first : _indexes,
        type: _types.one? ? _types.first : _types do
        begin
          Chewy.client.search(_request)
        rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
          raise e if e.message !~ /IndexMissingException/ && e.message !~ /index_not_found_exception/
          {}
        end
      end
    end

    def _results
      @_results ||= (criteria.none? || _response == {} ? [] : _response['hits']['hits']).map do |hit|
        _derive_type(hit['_index'], hit['_type']).build(hit)
      end
    end

    def _collection
      @_collection ||= begin
        _load_objects! if criteria.options[:preload]
        if criteria.options[:preload] && criteria.options[:loaded_objects]
          _results.map(&:_object)
        else
          _results
        end
      end
    end

    def _derive_type(index, type)
      (@types_cache ||= {})[[index, type]] ||= _derive_index(index).type(type)
    end

    def _derive_index(index_name)
      (@derive_index ||= {})[index_name] ||= _indexes_hash[index_name] ||
        _indexes_hash[_indexes_hash.keys.sort_by(&:length).reverse.detect { |name| index_name.start_with?(name) }]
    end

    def _indexes_hash
      @_indexes_hash ||= _indexes.index_by(&:index_name)
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.beatific.daram.web.dao.DesignDao">

    <select id="listDesign" parameterType="org.beatific.daram.web.vo.dao.DashBoardVo" resultType="org.beatific.daram.web.vo.dao.DesignVo">
        /* DesignDao.listDesign */
       SELECT A.DESIGN_NAME designName
              , A.X_TAG xTag
              , A.Y_TAG yTag
              , A.DENOMINATION denomination
              , DECODE(B.DESIGN_NAME, NULL, 'false', 'true') selected
              ,  B.SORT
         FROM TB_DESIGN A,TB_DESIGN_PER_DASH_BOARD B
        WHERE B.DESIGN_NAME(+) = A.DESIGN_NAME
          AND B.DASH_BOARD_ID(+) = 1
        ORDER BY B.SORT
    </select>

    <select id="selectDashBoardPk" resultType="java.lang.Long">
       /* DesignDao.selectDashBoardPk */
       SELECT DASH_BOARD_SEQ.NEXTVAL
         FROM DUAL
    </select>

    <select id="listDesignByDashBoard" parameterType="org.beatific.daram.web.vo.dao.DashBoardVo" resultType="org.beatific.daram.web.vo.dao.DesignVo">
     /* DesignDao.listDesign */
       SELECT A.DESIGN_NAME designName
              , A.X_TAG xTag
              , A.Y_TAG yTag
              , A.DENOMINATION denomination
         FROM TB_DESIGN A, TB_DESIGN_PER_DASH_BOARD B
        WHERE A.DESIGN_NAME = B.DESIGN_NAME
          AND B.DASH_BOARD_ID = #{dashBoardId}
    </select>

    <select id="listDashBoard" parameterType="org.beatific.daram.web.vo.dao.DashBoardVo" resultType="org.beatific.daram.web.vo.dao.DashBoardVo">
        /* DesignDao.listDashBoard */
        SELECT DASH_BOARD_ID dashBoardId
               , DASH_BOARD_NAME dashBoardName
          FROM TB_DASH_BOARD
    </select>

    <insert id="insertDashBoard" parameterType="org.beatific.daram.web.vo.dao.DashBoardVo">
        /* DesignDao.insertDashBoard */
        INSERT INTO TB_DASH_BOARD
        (
            DASH_BOARD_ID
            , DASH_BOARD_NAME
            , CREATED_TIME
            , MODIFIED_TIME
        )
        VALUES(
            #{dashBoardId}
            , #{dashBoardName}
            , SYSTIMESTAMP
            , SYSTIMESTAMP
        )
    </insert>

    <delete id="deleteDashBoard" parameterType="org.beatific.daram.web.vo.dao.DashBoardVo">
        /* DesignDao.deleteDashBoard */
        DELETE
          FROM TB_DASH_BOARD
         WHERE DASH_BOARD_ID = #{dashBoardId}
    </delete>

    <insert id="insertDesignPerDashBoard" parameterType="org.beatific.daram.web.vo.dao.DesignPerDashBoardVo">
        /* DesignDao.insertDesignPerDashBoard */
        INSERT INTO TB_DESIGN_PER_DASH_BOARD
        (
            DASH_BOARD_ID
            , DESIGN_NAME
            , SORT
            , CREATED_TIME
            , MODIFIED_TIME
        )
        VALUES(
            #{dashBoardId}
            , #{designName}
            , #{sort}
            , SYSTIMESTAMP
            , SYSTIMESTAMP
        )
    </insert>

     <delete id="deleteDesignPerDashBoard" parameterType="org.beatific.daram.web.vo.dao.DesignPerDashBoardVo">
        /* DesignDao.deleteDesignPerDashBoard */
        DELETE
          FROM TB_DESIGN_PER_DASH_BOARD
         WHERE DASH_BOARD_ID = #{dashBoardId}
    </delete>

    <select id="listDesignPerDashBoard" parameterType="org.beatific.daram.web.vo.dao.DesignPerDashBoardVo" resultType="org.beatific.daram.web.vo.dao.DesignPerDashBoardVo">
        /* DesignDao.listDesignPerDashBoard */
        SELECT DASH_BOARD_ID dashBoardId
               , DESIGN_NAME designName
          FROM TB_DESIGN_PER_DASH_BOARD
         WHERE DASH_BOARD_ID = #{dashBoardId}
    </select>

    <select id="listMonitorGraphByDesign" parameterType="org.beatific.daram.web.vo.dao.MonitorGraphVo" resultType="org.beatific.daram.web.vo.dao.MonitorGraphVo">
        SELECT A.MONITOR_ID monitorId
               , A.MONITOR_TIME monitorTime
               , B.DESIGN_NAME designName
               , C.GRAPH_NAME graphName
               , C.Y_VALUE yValue
          FROM TB_MONITOR A, TB_MONITOR_DESIGN B, TB_MONITOR_GRAPH C
         WHERE A.MONITOR_ID = B.MONITOR_ID
           AND B.MONITOR_ID = C.MONITOR_ID
           AND B.DESIGN_NAME = C.DESIGN_NAME
           AND B.DESIGN_NAME = #{designName}
           <choose>
	           <when test="fromTime == null or  fromTime  == '' or toTime == null or toTime == ''">
	       AND A.MONITOR_TIME BETWEEN SYSTIMESTAMP - INTERVAL '1' hour AND SYSTIMESTAMP
	           </when>
	           <otherwise>
	       AND A.MONITOR_TIME BETWEEN TO_DATE(#{fromTime}, 'YYYYMMDDHH24') AND TO_DATE(#{toTime}, 'YYYYMMDDHH24')
	           </otherwise>
           </choose>
         ORDER BY monitorId
    </select>

    <select id="selectMonitorGraphByDesign" parameterType="org.beatific.daram.web.vo.dao.MonitorGraphVo" resultType="org.beatific.daram.web.vo.dao.MonitorGraphVo">
        SELECT MONITOR_ID monitorId
               , MONITOR_TIME monitorTime
               , DESIGN_NAME designName
               , GRAPH_NAME graphName
               , Y_VALUE yValue
          FROM (
        SELECT A.MONITOR_ID
               , A.MONITOR_TIME
               , B.DESIGN_NAME
               , C.GRAPH_NAME
               , C.Y_VALUE
          FROM TB_MONITOR A, TB_MONITOR_DESIGN B, TB_MONITOR_GRAPH C
         WHERE A.MONITOR_ID = B.MONITOR_ID
           AND B.MONITOR_ID = C.MONITOR_ID
           AND B.DESIGN_NAME = C.DESIGN_NAME
           AND B.DESIGN_NAME = #{designName}
         ORDER BY A.MONITOR_ID DESC )
          WHERE ROWNUM = 1

    </select>

</mapper>


text:
from __future__ import absolute_import
import weakref
from defcon.objects.base import BaseDictObject

class Kerning(BaseDictObject):

    """
    This object contains all of the kerning pairs in a font.

    **This object posts the following notifications:**

    ===================
    Name
    ===================
    Kerning.Changed
    Kerning.BeginUndo
    Kerning.EndUndo
    Kerning.BeginRedo
    Kerning.EndRedo
    Kerning.PairSet
    Kerning.PairDeleted
    Kerning.Cleared
    Kerning.Updated
    ====================

    This object behaves like a dict. For example, to get a list of all kerning pairs::

        pairs = kerning.keys()

    To get all pairs including the values::

        for (left, right), value in kerning.items():

    To get the value for a particular pair::

        value = kerning["a", "b"]

    To set the value for a particular pair::

        kerning["a", "b"] = 100

    And so on.

    **Note:** This object is not very smart in the way it handles zero values,
    exceptions, etc. This may change in the future.
    """

    changeNotificationName = "Kerning.Changed"
    beginUndoNotificationName = "Kerning.BeginUndo"
    endUndoNotificationName = "Kerning.EndUndo"
    beginRedoNotificationName = "Kerning.BeginRedo"
    endRedoNotificationName = "Kerning.EndRedo"
    setItemNotificationName = "Kerning.PairSet"
    deleteItemNotificationName = "Kerning.PairDeleted"
    clearNotificationName = "Kerning.Cleared"
    updateNotificationName = "Kerning.Updated"
    representationFactories = {}

    def __init__(self, font=None):
        self._font = None
        if font is not None:
            self._font = weakref.ref(font)
        super(Kerning, self).__init__()
        self.beginSelfNotificationObservation()

    # --------------
    # Parent Objects
    # --------------

    def getParent(self):
        return self.font

    def _get_font(self):
        if self._font is not None:
            return self._font()
        return None

    font = property(_get_font, doc="The :class:`Font` that this object belongs to.")

    # -------------
    # Pair Handling
    # -------------

    def get(self, pair, default=0):
        return super(Kerning, self).get(pair, default)

    # ------------------------
    # Notification Observation
    # ------------------------

    def endSelfNotificationObservation(self):
        super(Kerning, self).endSelfNotificationObservation()
        self._font = None

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


text:
/*
* IMX6X SOC devices
*
* This file contains names for all of the devices that may exists on any IMX6X
* processor variant (i.MX6 Quad, i.MX6 Dual, i.MX6 Solo). Specifically, these
* are the internal devices that are part of the IMX6X SOC and not board specific
* devices. Board specific devices are defined in a similarly named board specific file
*
* The names are added to the hwinfo section of the syspage (at the discretion of
* the startup writer) so that drivers can use hwi_find_device() to determine
* the existence of SOC device instances in a portable fashion and optionally
* retrieve device specific information like interrupt vectors, etc.
*
* Not all of the devices are on every processor so hwi_find_device() may return
* HWI_NULL_OFF if a device, or device instance (ie. unit) is not found.
*
*/

#ifndef __HWINFO_IMX61_H_INCLUDED
#define __HWINFO_IMX61_H_INCLUDED

#include <hw/sysinfo.h>

/*
 * =============================================================================
 *
 *                                B U S E S
 *
 * =============================================================================
*/
/* I2C - 1 interrupt */
#define IMX6_HWI_I2C						HWI_ITEM_BUS_I2C

/* USB */
#define IMX6_HWI_USB						HWI_ITEM_BUS_USB

/* SPI */
#define IMX6_HWI_SPI						HWI_ITEM_BUS_SPI

/*
 * =============================================================================
 *
 *                              D E V I C E S
 *
 * =============================================================================
*/
/* SDHC */
#define IMX6_HWI_SDHC						"sdhc"

/* DMA - multiple interrupts are assigned per available channel for each device */
#define IMX6_HWI_DMA						"dma"

/* FEC - interrupts are assigned */
#define IMX6_HWI_FEC						"FEC"  // "fec"
#define IMX6_HWI_LEGACY_FEC					"fec"  // "tsec"

/* DUART - 1 interrupt */
#define IMX6_HWI_UART						"uart"

/* Security - 1 interrupt per device */
#define IMX6_HWI_SECURITY					"security"

/* GPIO - 1 interrupt per device */
#define IMX6_HWI_GPIO						"gpio"

/* SSI BUS  */
#define IMX6_HWI_SSI						"ssi"

/* SDRAM  */
#define IMX6_HWI_SDRAM						"sdram"

/* Watchdog  */
#define IMX6_HWI_WDOG						"wdog"

/* MLB  */
#define IMX6_HWI_MLB						"mlb"

/* Graphics 2D  */
#define IMX6_HWI_GPU_2D						"gpu2d"

/* Graphics 3D  */
#define IMX6_HWI_GPU_3D						"gpu3d"

/* Image Processing Unit  */
#define IMX6_HWI_IPU						"ipu"

/* Video Processing Unit  */
#define IMX6_HWI_VPU						"vpu"

/* ESAI  */
#define IMX6_HWI_ESAI                                           "esai"

#endif  /* __HWINFO_IMX61_H_INCLUDED */

__SRCVERSION( "$URL: http://svn/product/tags/restricted/bsp/nto650/ti-omap4430-panda/latest/src/hardware/startup/lib/public/hw/hwinfo_imx6x.h $ $Rev: 655042 $" )