text:
import lasagne
from lasagne.layers import InputLayer
from lasagne.layers import Conv2DLayer as ConvLayer
from lasagne.layers import BatchNormLayer
from lasagne.layers import Pool2DLayer as PoolLayer
from lasagne.layers import NonlinearityLayer
from lasagne.layers import ElemwiseSumLayer
from lasagne.layers import DenseLayer
from lasagne.nonlinearities import rectify, softmax

def build_simple_block(incoming_layer, names,
                       num_filters, filter_size, stride, pad,
                       use_bias=False, nonlin=rectify):
    """Creates stacked Lasagne layers ConvLayer -> BN -> (ReLu)

    Parameters:
    ----------
    incoming_layer : instance of Lasagne layer
        Parent layer

    names : list of string
        Names of the layers in block

    num_filters : int
        Number of filters in convolution layer

    filter_size : int
        Size of filters in convolution layer

    stride : int
        Stride of convolution layer

    pad : int
        Padding of convolution layer

    use_bias : bool
        Whether to use bias in conlovution layer

    nonlin : function
        Nonlinearity type of Nonlinearity layer

    Returns
    -------
    tuple: (net, last_layer_name)
        net : dict
            Dictionary with stacked layers
        last_layer_name : string
            Last layer name
    """
    net = []
    net.append((
            names[0],
            ConvLayer(incoming_layer, num_filters, filter_size, stride, pad,
                      flip_filters=False, nonlinearity=None) if use_bias
            else ConvLayer(incoming_layer, num_filters, filter_size, stride, pad, b=None,
                           flip_filters=False, nonlinearity=None)
        ))

    net.append((
            names[1],
            BatchNormLayer(net[-1][1])
        ))
    if nonlin is not None:
        net.append((
            names[2],
            NonlinearityLayer(net[-1][1], nonlinearity=nonlin)
        ))

    return dict(net), net[-1][0]

def build_residual_block(incoming_layer, ratio_n_filter=1.0, ratio_size=1.0, has_left_branch=False,
                         upscale_factor=4, ix=''):
    """Creates two-branch residual block

    Parameters:
    ----------
    incoming_layer : instance of Lasagne layer
        Parent layer

    ratio_n_filter : float
        Scale factor of filter bank at the input of residual block

    ratio_size : float
        Scale factor of filter size

    has_left_branch : bool
        if True, then left branch contains simple block

    upscale_factor : float
        Scale factor of filter bank at the output of residual block

    ix : int
        Id of residual block

    Returns
    -------
    tuple: (net, last_layer_name)
        net : dict
            Dictionary with stacked layers
        last_layer_name : string
            Last layer name
    """
    simple_block_name_pattern = ['res%s_branch%i%s', 'bn%s_branch%i%s', 'res%s_branch%i%s_relu']

    net = {}

    # right branch
    net_tmp, last_layer_name = build_simple_block(
        incoming_layer, map(lambda s: s % (ix, 2, 'a'), simple_block_name_pattern),
        int(lasagne.layers.get_output_shape(incoming_layer)[1]*ratio_n_filter), 1, int(1.0/ratio_size), 0)
    net.update(net_tmp)

    net_tmp, last_layer_name = build_simple_block(
        net[last_layer_name], map(lambda s: s % (ix, 2, 'b'), simple_block_name_pattern),
        lasagne.layers.get_output_shape(net[last_layer_name])[1], 3, 1, 1)
    net.update(net_tmp)

    net_tmp, last_layer_name = build_simple_block(
        net[last_layer_name], map(lambda s: s % (ix, 2, 'c'), simple_block_name_pattern),
        lasagne.layers.get_output_shape(net[last_layer_name])[1]*upscale_factor, 1, 1, 0,
        nonlin=None)
    net.update(net_tmp)

    right_tail = net[last_layer_name]
    left_tail = incoming_layer

    # left branch
    if has_left_branch:
        net_tmp, last_layer_name = build_simple_block(
            incoming_layer, map(lambda s: s % (ix, 1, ''), simple_block_name_pattern),
            int(lasagne.layers.get_output_shape(incoming_layer)[1]*4*ratio_n_filter), 1, int(1.0/ratio_size), 0,
            nonlin=None)
        net.update(net_tmp)
        left_tail = net[last_layer_name]

    net['res%s' % ix] = ElemwiseSumLayer([left_tail, right_tail], coeffs=1)
    net['res%s_relu' % ix] = NonlinearityLayer(net['res%s' % ix], nonlinearity=rectify)

    return net, 'res%s_relu' % ix

def build_model():
    net = {}
    net['input'] = InputLayer((None, 3, 224, 224))
    sub_net, parent_layer_name = build_simple_block(
        net['input'], ['conv1', 'bn_conv1', 'conv1_relu'],
        64, 7, 2, 3, use_bias=True)
    net.update(sub_net)
    net['pool1'] = PoolLayer(net[parent_layer_name], pool_size=3, stride=2, pad=0, mode='max', ignore_border=False)
    block_size = list('abc')
    parent_layer_name = 'pool1'
    for c in block_size:
        if c == 'a':
            sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1, 1, True, 4, ix='2%s' % c)
        else:
            sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1.0/4, 1, False, 4, ix='2%s' % c)
        net.update(sub_net)

    block_size = list('abcd')
    for c in block_size:
        if c == 'a':
            sub_net, parent_layer_name = build_residual_block(
                net[parent_layer_name], 1.0/2, 1.0/2, True, 4, ix='3%s' % c)
        else:
            sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1.0/4, 1, False, 4, ix='3%s' % c)
        net.update(sub_net)

    block_size = list('abcdef')
    for c in block_size:
        if c == 'a':
            sub_net, parent_layer_name = build_residual_block(
                net[parent_layer_name], 1.0/2, 1.0/2, True, 4, ix='4%s' % c)
        else:
            sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1.0/4, 1, False, 4, ix='4%s' % c)
        net.update(sub_net)

    block_size = list('abc')
    for c in block_size:
        if c == 'a':
            sub_net, parent_layer_name = build_residual_block(
                net[parent_layer_name], 1.0/2, 1.0/2, True, 4, ix='5%s' % c)
        else:
            sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1.0/4, 1, False, 4, ix='5%s' % c)
        net.update(sub_net)
    net['pool5'] = PoolLayer(net[parent_layer_name], pool_size=7, stride=1, pad=0,
                             mode='average_exc_pad', ignore_border=False)
    net['fc1000'] = DenseLayer(net['pool5'], num_units=1000, nonlinearity=None)
    net['prob'] = NonlinearityLayer(net['fc1000'], nonlinearity=softmax)

    return net


text:
layout: post
date: '2016-02-09'
title: "Weddington Way Siri Tempo Sleeveless Short/Mini Aline/Princess"
category: Weddington Way
tags: [Weddington Way,Aline/Princess ,One shoulder,Short/Mini,Sleeveless]
---
### Weddington Way Siri Tempo
Just **$129.99**
###   Sleeveless Short/Mini Aline/Princess

BRANDS	Weddington Way

Silhouette	Aline/Princess

Neckline	One shoulder

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/weddington-way/17097-weddington-way-siri-tempo.html](https://www.readybrides.com/en/weddington-way/17097-weddington-way-siri-tempo.html)

redpajama_set_name: RedPajamaGithub


text:
namespace GafferArnold
{

/// \todo It's slightly awkward that this inherits from Shader, because
/// it inherits namePlug(), typePlug() and parametersPlug(), none of
/// which are needed. We should consider creating a fully abstract Shader
/// base class and renaming the current Shader class to StandardShader,
/// or defining an even more general Assignable base class which both
/// Shader and ArnoldDisplacement can inherit from.
class ArnoldDisplacement : public GafferScene::Shader
{

	public :

		ArnoldDisplacement( const std::string &name=defaultName<ArnoldDisplacement>() );
		virtual ~ArnoldDisplacement();

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferArnold::ArnoldDisplacement, ArnoldDisplacementTypeId, GafferScene::Shader );

		GafferScene::ShaderPlug *mapPlug();
		const GafferScene::ShaderPlug *mapPlug() const;

		Gaffer::FloatPlug *heightPlug();
		const Gaffer::FloatPlug *heightPlug() const;

		Gaffer::FloatPlug *paddingPlug();
		const Gaffer::FloatPlug *paddingPlug() const;

		Gaffer::FloatPlug *zeroValuePlug();
		const Gaffer::FloatPlug *zeroValuePlug() const;

		Gaffer::BoolPlug *autoBumpPlug();
		const Gaffer::BoolPlug *autoBumpPlug() const;

		Gaffer::Plug *outPlug();
		const Gaffer::Plug *outPlug() const;

		virtual void attributesHash( IECore::MurmurHash &h ) const;
		virtual IECore::ConstCompoundObjectPtr attributes() const;

	protected :

		virtual bool acceptsInput( const Gaffer::Plug *plug, const Gaffer::Plug *inputPlug ) const;

	private :

		static size_t g_firstPlugIndex;

};

IE_CORE_DECLAREPTR( ArnoldDisplacement )

} // namespace GafferArnold

#endif // GAFFERARNOLD_ARNOLDDISPLACEMENT_H


text:
#ifndef __FM_VECTOR_H__
#define __FM_VECTOR_H__

#include <memory>

#include "generic_type.h"
#include "bulk_operate.h"
#include "vec_store.h"
#include "mem_vec_store.h"

namespace fm
{

class bulk_operate;
class data_frame;
class agg_operate;
class dense_matrix;

class vector
{
	detail::vec_store::const_ptr store;

	bool verify_groupby(const gr_apply_operate<local_vec_store> &op) const;
protected:
	vector(detail::vec_store::const_ptr store) {
		this->store = store;
	}
public:
	typedef std::shared_ptr<vector> ptr;
	typedef std::shared_ptr<const vector> const_ptr;

	static ptr create(detail::vec_store::const_ptr store) {
		return ptr(new vector(store));
	}
	static ptr create(size_t length, const scalar_type &type, int num_nodes,
			bool in_mem, const set_vec_operate &op);

	~vector() {
	}

	const detail::vec_store &get_data() const {
		return *store;
	}

	detail::vec_store::const_ptr get_raw_store() const {
		return store;
	}

	template<class T>
	std::vector<T> conv2std() const {
		assert(is_type<T>());
		std::vector<T> ret(get_length());
		store->copy_to((char *) ret.data(), ret.size());
		return ret;
	}

	vector::ptr get(const std::vector<off_t> &offs) const;

	bool is_in_mem() const {
		return store->is_in_mem();
	}

	// Normally the entry size is the type size. But a vector may also
	// contains vectors, and the entry size is 0, which is no longer
	// the type size.
	size_t get_entry_size() const {
		return store->get_entry_size();
	}
	size_t get_length() const {
		return store->get_length();
	}

	template<class T>
	bool is_type() const {
		return store->get_type().get_type() == fm::get_type<T>();
	}

	const scalar_type &get_type() const {
		return store->get_type();
	}

	bool is_sorted() const {
		return store->is_sorted();
	}

	bool equals(const vector &vec) const;

	vector::ptr sort() const;
	std::shared_ptr<data_frame> sort_with_index() const;
	std::shared_ptr<dense_matrix> conv2mat(size_t nrow, size_t ncol,
			bool byrow) const;

	/*
	 * This is a general version of groupby. It requires sorting on the entire
	 * vector. If `with_val' is true, this method returns a data frame with two
	 * columns: the first column is a vector of unique values in the vector;
	 * the second column is a vector of vectors and contains the aggregation
	 * result for each unique value in the first column.
	 * If `with_val' is false, this method returns a data frame with only
	 * one column, which is a vector of vectors and contains the aggregation
	 * result for each unique value.
	 */
	std::shared_ptr<data_frame> groupby(
			const gr_apply_operate<local_vec_store> &op, bool with_val) const;
	/*
	 * This version of groupby runs aggregation on each group. It only needs
	 * to scan the vector once. If `with_val' is true, this method returns
	 * a data frame with two columns: the first column is a vector of unique
	 * values in the vector; the second column is a vector of aggregation
	 * result for each unique value in the first column.
	 * If `with_val' is false, this method returns a data frame with only
	 * one column, which contains the aggregation result for each unique value.
	 */
	std::shared_ptr<data_frame> groupby(
			std::shared_ptr<const agg_operate> op, bool with_val) const;

	vector::ptr sapply(bulk_uoperate::const_ptr op) const;
	scalar_variable::ptr aggregate(const bulk_operate &op) const;
	scalar_variable::ptr dot_prod(const vector &vec) const;

	template<class T>
	T max() const {
		const bulk_operate &max_op = *get_type().get_basic_ops().get_op(
				basic_ops::op_idx::MAX);
		scalar_variable::ptr res = aggregate(max_op);
		return *(T *) res->get_raw();
	}
	template<class T>
	T sum() const {
		const bulk_operate &sum_op = *get_type().get_basic_ops().get_op(
				basic_ops::op_idx::ADD);
		scalar_variable::ptr res = aggregate(sum_op);
		return *(T *) res->get_raw();
	}

	bool export2(FILE *f) const;
};

/*
 * Create a sequence of values in [start, end]. `end' is inclusive.
 */
template<class EntryType>
vector::ptr create_seq_vector(EntryType start, EntryType end, EntryType stride,
		int num_nodes = -1, bool in_mem = true)
{
	detail::vec_store::ptr store = detail::create_seq_vec_store(start, end, stride,
			num_nodes, in_mem);
	if (store == NULL)
		return vector::ptr();
	return vector::create(store);
}

/*
 * Create a vector filled with a constant value.
 */
template<class EntryType>
vector::ptr create_rep_vector(size_t length, EntryType initv,
		int num_nodes = -1, bool in_mem = true)
{
	detail::vec_store::ptr store = detail::create_rep_vec_store(length, initv,
			num_nodes, in_mem);
	if (store == NULL)
		return vector::ptr();
	return vector::create(store);
}

}

#endif


text:
package net.sourceforge.jwbf.mediawiki.actions.meta;

import java.util.Map;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.sourceforge.jwbf.core.actions.Get;
import net.sourceforge.jwbf.core.actions.util.HttpAction;
import net.sourceforge.jwbf.mapper.XmlElement;
import net.sourceforge.jwbf.mediawiki.ApiRequestBuilder;
import net.sourceforge.jwbf.mediawiki.MediaWiki;

/**
 * Gets details from the given MediaWiki installation like installed version.
 *
 * @author Thomas Stock
 * @see Siteinfo
 */
public class Siteinfo extends GetVersion {

  private final Get msg;
  private final Map<Integer, String> namespaces = Maps.newHashMap();
  private final Map<String, String> interwiki = Maps.newHashMap();

  public static final String GENERAL = "general";
  public static final String NAMESPACES = "namespaces";
  // : A list of all namespaces
  // # namespacealiases: A list of all namespace aliases
  // # specialpagealiases: A list of all special page aliases
  // # magicwords: A list of magic words and their aliases
  // # statistics: Site statistics à la Special:Statistics

  public static final String INTERWIKIMAP = "interwikimap";
  // : A list of all interwiki prefixes and where they go
  // # dbrepllag: Get information about the database server with the highest
  // replication lag
  // # usergroups: A list of all user groups and their permissions
  // # extensions: A list of extensions installed on the wiki
  // # fileextensions: A list of file extensions allowed to be uploaded
  // # rightsinfo: Get information about the license governing the wiki's
  // content

  /**
   * inits with parameters {@link #GENERAL}, {@link #NAMESPACES}, {@link #INTERWIKIMAP}.
   */
  public Siteinfo() {
    this(GENERAL, NAMESPACES, INTERWIKIMAP);
  }

  /**
   * @param types the, see {@link #GENERAL}, {@link #INTERWIKIMAP}, ...
   */
  public Siteinfo(String... types) {
    String result = MediaWiki.pipeJoined(types);
    msg = new ApiRequestBuilder() //
        .action("query") //
        .formatXml() //
        .param("meta", "siteinfo") //
        .param("siprop", MediaWiki.urlEncode(result)) //
        .buildGet();

  }

  /**
   * {@inheritDoc}
   */
  @Override
  public HttpAction getNextMessage() {
    return msg;
  }

  @Override
  protected void findContent(final XmlElement root) {
    super.findContent(root);
    for (XmlElement xmlElement : root.getChildren()) {
      if (xmlElement.getQualifiedName().equalsIgnoreCase("ns")) {
        Integer id = Integer.parseInt(xmlElement.getAttributeValue("id"));
        String name = xmlElement.getText();
        namespaces.put(id, name);

      } else if (xmlElement.getQualifiedName().equalsIgnoreCase("iw")) {
        if (xmlElement.hasAttribute("prefix")) {
          String prefix = xmlElement.getAttributeValue("prefix");
          String name = xmlElement.getAttributeValue("url");
          interwiki.put(prefix, name);
        }
      } else {
        findContent(xmlElement);
      }
    }
  }

  /**
   * @return of
   */
  public ImmutableMap<Integer, String> getNamespaces() {
    return ImmutableMap.copyOf(namespaces);
  }

  /**
   * @return of
   */
  public ImmutableMap<String, String> getInterwikis() {
    return ImmutableMap.copyOf(interwiki);
  }

}


text:
/* =============================================================
 * bootstrap-collapse.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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.
 * ============================================================ */

!function ($) {

  "use strict"; // jshint ;_;

 /* COLLAPSE PUBLIC CLASS DEFINITION
  * ================================ */

  var Collapse = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collapse.defaults, options)

    if (this.options.parent) {
      this.$parent = $(this.options.parent)
    }

    this.options.toggle && this.toggle()
  }

  Collapse.prototype = {

    constructor: Collapse

  , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
    }

  , show: function () {
      var dimension
        , scroll
        , actives
        , hasData

      if (this.transitioning || this.$element.hasClass('in')) return

      dimension = this.dimension()
      scroll = $.camelCase(['scroll', dimension].join('-'))
      actives = this.$parent && this.$parent.find('> .accordion-group > .in')

      if (actives && actives.length) {
        hasData = actives.data('collapse')
        if (hasData && hasData.transitioning) return
        actives.collapse('hide')
        hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0)
      this.transition('addClass', $.Event('show'), 'shown')
      $.support.transition && this.$element[dimension](this.$element[0][scroll])
    }

  , hide: function () {
      var dimension
      if (this.transitioning || !this.$element.hasClass('in')) return
      dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', $.Event('hide'), 'hidden')
      this.$element[dimension](0)
    }

  , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension](size || 'auto')
        [0].offsetWidth

      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')

      return this
    }

  , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
            if (startEvent.type == 'show') that.reset()
            that.transitioning = 0
            that.$element.trigger(completeEvent)
          }

      this.$element.trigger(startEvent)

      if (startEvent.isDefaultPrevented()) return

      this.transitioning = 1

      this.$element[method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
    }

  , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

  }

 /* COLLAPSE PLUGIN DEFINITION
  * ========================== */

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option)
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

  $.fn.collapse.Constructor = Collapse

 /* COLLAPSE NO CONFLICT
  * ==================== */

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }

 /* COLLAPSE DATA-API
  * ================= */

  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
    var $this = $(this), href
      , target = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
      , option = $(target).data('collapse') ? 'toggle' : $this.data()
    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
    $(target).collapse(option)
  })

}(window.jQuery);


text:
import * as React from 'react';

export interface ITabContentProps {
    for: string|number;
    visibleStyle?: object;
    isVisible?: boolean;
    renderActiveTabContentOnly?: boolean;
    disableInlineStyles?: boolean;
    className?: string;
    visibleClassName?: string;
    style?: string;
    displayName?: string;
    itemKey?:string;
}

export const styles = {
    hidden: {
      display: 'none',
    },
};

export default class TabContent extends React.Component<ITabContentProps, {}> {
    public static defaultProps = {
        displayName: 'TabContent'
    };

    public canRenderChildren() {
        return this.props.isVisible || !this.props.renderActiveTabContentOnly;
    }

    public render() {
        const visibleStyle = this.props.visibleStyle || {};
        const displayStyle = this.props.isVisible ? visibleStyle : styles.hidden;
        const disableInlineStyles = this.props.disableInlineStyles;
        const className = this.props.className;
        const visibleClassName =
          this.props.visibleClassName;
        const style = this.props.style;

        return (
          <div
            className={className}
            style={{...displayStyle } }
          >
            {this.canRenderChildren() && this.props.children}
          </div>
        );
      }
}


text:
class Simple_Rectangle;

class Snake_Piece
{
  public:
    enum Type
    {
      HEAD = 1,
      BODY = 2,
      TAIL = 3
    };
    Snake_Piece(Input::Direction direction, Type type, Simple_Rectangle *rectangle);
    ~Snake_Piece();
    void draw();
    float get_x();
    float get_y();
    Input::Direction get_direction();
    Type get_type();
    ALLEGRO_COLOR get_color();
    void set_x(float x);
    void set_y(float y);
    void set_direction(Input::Direction direction);
    void set_type(Type type);
    void set_color(ALLEGRO_COLOR color);
    void set_filled(bool filled);
  private:
    Input::Direction m_direction;
    Type m_type;
	Simple_Rectangle *m_rectangle;
};

#endif


text:
Transfigr.add(:textile) do
  after_activation do
    require 'redcloth'
  end

  def format!(opts = {})
    RedCloth.new(target).to_html
  end
end


text:
#ifndef SM_BOOST_NULL_DELETER_HPP
#define SM_BOOST_NULL_DELETER_HPP

namespace sm {

    struct null_deleter
    {
      template<typename T>
      void operator()(const T * ){}
    };

} // namespace sm

#endif /* SM_BOOST_NULL_DELETER_HPP */


text:
<?php

namespace ThirdEngine\PropelSOABundle\Controller;

use ThirdEngine\PropelSOABundle\Model;
use ThirdEngine\PropelSOABundle\Http\PropelSOASuccessResponse;
use ThirdEngine\PropelSOABundle\Interfaces\Collectionable;
use ThirdEngine\PropelSOABundle\Base\JoinTree;

use stdClass;
use DateTime;
use BasePeer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

abstract class ModelBasedServiceController extends ServiceController implements Collectionable
{
  /**
   * This stores the class info for the attached model classes.
   *
   * @var SymfonyClassInfo
   */
  protected $classInfo;

  /**
   * This property  is used for storing validation errors
   */
  protected $validationErrors;

  /**
   * This action will get data from the database out our resource.
   *
   * @param Request $request
   */
  public function getAction(Request $request)
  {
    $this->getJSONFromRequest($request);
    $this->setupClassInfo();

    $modelClass = $this->classInfo->getClassPath('model');
    $queryClass = $this->classInfo->getClassPath('query');
    $peerClass = $this->classInfo->getClassPath('peer');

    $query = $queryClass::create();

    // modify the query based on the posted data

    $queryDefinition = $this->getDataFromRequest($request);
    $this->joinTree = new JoinTree();

    if ($queryDefinition)
    {
      $this->addJoins($query, $queryDefinition);
      $this->addFilters($query, $queryDefinition);
    }

    $results = $query->find();

    // now, if we have linked data, we need to add that
    if ($queryDefinition && isset($queryDefinition->linkedData))
    {
      $results = $this->addLinkedData($results, $queryDefinition);
    }
    if (method_exists($this, 'afterGet'))
    {
      $results = $this->afterGet($results);
    }

    return $this->outputResultsAsJson($results);
  }

  /**
   * This method will populate our $classInfo object with information
   * about our related model.
   */
  abstract public function setupClassInfo();

  /**
   * This method will add any joins to the query.
   *
   * @param $query
   * @param $queryDefinition
   */
  protected function addJoins($query, $queryDefinition)
  {
    if (!$queryDefinition || !isset($queryDefinition->joins))
    {
      return;
    }

    $this->joinTree->buildFromPostedObjects($queryDefinition);
    $this->joinTree->correctNamespaces($query);
    $this->joinTree->addToQuery($query);
  }

  /**
   * This method will add any filters that were specified in the $_POST.
   *
   * @param $query
   * @param $queryDefinition
   */
  protected function addFilters($query, $queryDefinition)
  {
    if (!$queryDefinition || !isset($queryDefinition->filters))
    {
      return;
    }

    foreach ($queryDefinition->filters as $filterDefinition)
    {
      $methodName = 'add' . ucfirst($filterDefinition->filterType) . 'Filter';
      $this->$methodName($query, $filterDefinition);
    }
  }

  /**
   * This method will add linked data to results of a query.
   *
   * @param $results
   * @param $queryDefinition
   *
   * @return array
   */
  public function addLinkedData($results, $queryDefinition)
  {
    $this->setupClassInfo();
    $peerClass = $this->classInfo->getClassPath('peer');

//    $peer = new $peerClass();
//    $peer->prepopulateForLinkedData($results, $queryDefinition->linkedData);
//    $peer->populateLinkedData($results, $queryDefinition->linkedData);

    return $results;
  }

  /**
   * This method will print a result set as json.
   *
   * @param $results
   */
  protected function outputResultsAsJson($results, $status = 200)
  {
    $peerClass = $this->classInfo->getClassPath('peer');

    $finalResults = new stdClass();
    $finalResults->results = json_decode($this->joinTree->outputAsJSON($results));
    $finalResults->joinTree = $this->joinTree;

    return new PropelSOASuccessResponse($finalResults);
  }

  /**
   * This method will return the list of field names that should belong to an object
   * from this resource. For model-based resources, this will be the fields
   * available in the model.
   *
   * @return array
   */
  public function getFieldNames()
  {
    $this->setupClassInfo();
    $peerClass = $this->classInfo->getClassPath('peer');

    return $peerClass::getFieldNames();
  }

  /**
   * This method will return the list of linked data fields that can be joined in even
   * though they are not actual table relations.
   *
   * @return array
   */
  public function getLinkedDataFieldNames()
  {
    $this->setupClassInfo();
    $peerClass = $this->classInfo->getClassPath('peer');

    $peer = new $peerClass();
    return array_keys($peer->linkedData);
  }

  /**
   * This method will return the three class paths.
   *
   * @return array
   */
  protected function getClassPaths()
  {
    return [
      $this->classInfo->getClassPath('peer'),
      $this->classInfo->getClassPath('query'),
      $this->classInfo->getClassPath('model'),
    ];
  }

  /**
   * This action will save data to a record of our model.
   */
  public function postAction(Request $request)
  {
    $model = $this->getObjectFromRequest($request);

    // save the record and return the record's primary key
    if (method_exists($this, 'beforeSave'))
    {
      $this->beforeSave($model);
    }

    $model->save();

    if (method_exists($this, 'afterSave'))
    {
      $this->afterSave($model);
    }

    list($peerClass, $queryClass, $modelClass) = $this->getClassPaths();
    $query = new $queryClass();

    $pkFieldName = $this->getPrimaryKeyFieldName($query);
    $getPkMethod = 'get' . $pkFieldName;
    $returnData = ['pk' => $model->$getPkMethod()];

    $rawData = $request->getContent();
    $post = json_decode($rawData);

    return new PropelSOASuccessResponse($returnData, $this->isNewRecord($post, $pkFieldName)? 201 : 200);
  }

  /**
   * getObjectFromRequest - does all the setup necessary to allow the correct model to be used as associated
   * with the model based controller.
   *
   * @param Request $request
   *
   * @return mixed
   */
  protected function getObjectFromRequest(Request $request)
  {
    $this->setupClassInfo();
    list($peerClass, $queryClass, $modelClass) = $this->getClassPaths();

    $rawData = $request->getContent();
    $post = json_decode($rawData);

    // first, we need to be able to tell if a primary key was supplied. if so, we will update
    // a record, but if not, we will create a new record
    $query = new $queryClass();
    $pkFieldName = $this->getPrimaryKeyFieldName($query);

    // next, we will get a valid object that we will be able to use to update data for this record
    $model = $this->getWorkingModel($post, $query, $modelClass, $pkFieldName);
    $this->setModelPropertiesFromPost($post, $query, $model, $pkFieldName);

    return $model;
  }

  /**
   * This method will check the post and update the model values with corresponding post data.
   *
   * @param mixed $post
   * @param ModelCriteria $query
   * @param mixed $model
   * @param string $pkFieldName
   */
  protected function setModelPropertiesFromPost($post, $query, $model, $pkFieldName)
  {
    if (!is_object($post))
    {
      return;
    }

    foreach ($query->getTableMap()->getColumns() as $column)
    {
      $fieldName = $column->getPhpName();
      $setMethod = 'set' . $fieldName;

      if (!property_exists($post, $fieldName))
      {
        // this value was not passed in, so don't try to update it
        continue;
      }

      // we also need a special check for the primary key, since we do not want to
      // insert with setting a primary key value

      if ($pkFieldName == $fieldName && !$post->$fieldName)
      {
        continue;
      }

      $model->$setMethod($this->getModelPropertyValue($post, $fieldName, $column));
    }
  }

  /**
   * This method will return a value for a specified model property.
   *
   * @param mixed $post
   * @param string $fieldName
   * @param mixed $column
   *
   * @return mixed
   */
  protected function getModelPropertyValue($post, $fieldName, $column)
  {
    $value = $post->$fieldName;
    $dateTimeColumnTypes = array('TIMESTAMP', 'DATE');

    if (in_array($column->getType(), $dateTimeColumnTypes))
    {
      $value = strtoupper($value) == 'NOW' ? new DateTime() : new DateTime($value);
    }

    return $value;
  }

  /**
   * This method will return a new model object or the existing model based on db data. This will also
   * set the create date if there is a setter for it when we create a new record.
   *
   * @param mixed $post
   * @param ModelCriteria $query
   * @param string $modelClass
   * @param string $pkFieldName
   *
   * @return object
   */
  protected function getWorkingModel($post, $query, $modelClass, $pkFieldName)
  {
    $newRecord = $this->isNewRecord($post, $pkFieldName);
    $model = $newRecord ? new $modelClass() : $query->findPk($post->$pkFieldName);

    if ($newRecord && method_exists($model, 'setCreateDate'))
    {
      $model->setCreateDate(new DateTime());
    }

    return $model;
  }

  /**
   * This method will check to see if the posted data is meant to create a new record.
   *
   * @param mixed $post
   * @param string $pkFieldName
   *
   * @return bool
   */
  protected function isNewRecord($post, $pkFieldName)
  {
    return !isset($post->$pkFieldName) || !$post->$pkFieldName;
  }

  /**
   * This method will determine the primary key field name from a query object.
   *
   * @param ModelCriteria $query
   * @return string
   */
  protected function getPrimaryKeyFieldName($query)
  {
    $primaryKeyColumns = $query->getTableMap()->getPrimaryKeyColumns();
    $primaryKeyColumn = reset($primaryKeyColumns);

    return $primaryKeyColumn->getPhpName();
  }

  /**
   * This method will delete a record.
   */
  public function deleteAction(Request $request)
  {
    $this->setupClassInfo();

    $modelClass = $this->classInfo->getClassPath('model');
    $queryClass = $this->classInfo->getClassPath('query');
    $peerClass = $this->classInfo->getClassPath('peer');

    $pk = $request->get('recordId');

    $model = $queryClass::create()->findPk($pk);
    $model->delete();

    $returnData = array('pk' => $pk);
    return new PropelSOASuccessResponse($returnData);
  }

  /**
   * This method will add an equality filter to the query.
   *
   * @param $query
   * @param $filterDefinition
   */
  protected function addEqualFilter($query, $filterDefinition)
  {
    $filterMethod = 'filterBy' . $filterDefinition->field;
    $query->$filterMethod($filterDefinition->filterValue);
  }

  /**
   * This method will add an IN statement to the query.
   *
   * @param $query
   * @param $filterDefinition
   */
  protected function addInFilter($query, $filterDefinition)
  {
    $filterMethod = 'filterBy' . $filterDefinition->field;
    $query->$filterMethod($filterDefinition->filterValue);
  }
}


text:
package org.apache.ignite.ml.math.decompositions;

import java.io.Serializable;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.exceptions.NoDataException;
import org.apache.ignite.ml.math.exceptions.NullArgumentException;
import org.apache.ignite.ml.math.exceptions.SingularMatrixException;
import org.apache.ignite.ml.math.functions.Functions;
import org.apache.ignite.ml.math.util.MatrixUtil;

import static org.apache.ignite.ml.math.util.MatrixUtil.like;

/**
 * For an {@code m x n} matrix {@code A} with {@code m >= n}, the QR decomposition
 * is an {@code m x n} orthogonal matrix {@code Q} and an {@code n x n} upper
 * triangular matrix {@code R} so that {@code A = Q*R}.
 */
public class QRDSolver implements Serializable {
    /** */
    private final Matrix q;

    /** */
    private final Matrix r;

    /**
     * Constructs a new QR decomposition solver object.
     *
     * @param q An orthogonal matrix.
     * @param r An upper triangular matrix
     */
    public QRDSolver(Matrix q, Matrix r) {
        this.q = q;
        this.r = r;
    }

    /**
     * Least squares solution of {@code A*X = B}; {@code returns X}.
     *
     * @param mtx A matrix with as many rows as {@code A} and any number of cols.
     * @return {@code X<} that minimizes the two norm of {@code Q*R*X - B}.
     * @throws IllegalArgumentException if {@code B.rows() != A.rows()}.
     */
    public Matrix solve(Matrix mtx) {
        if (mtx.rowSize() != q.rowSize())
            throw new IllegalArgumentException("Matrix row dimensions must agree.");

        int cols = mtx.columnSize();
        Matrix x = like(r, r.columnSize(), cols);

        Matrix qt = q.transpose();
        Matrix y = qt.times(mtx);

        for (int k = Math.min(r.columnSize(), q.rowSize()) - 1; k >= 0; k--) {
            // X[k,] = Y[k,] / R[k,k], note that X[k,] starts with 0 so += is same as =
            x.viewRow(k).map(y.viewRow(k), Functions.plusMult(1 / r.get(k, k)));

            if (k == 0)
                continue;

            // Y[0:(k-1),] -= R[0:(k-1),k] * X[k,]
            Vector rCol = r.viewColumn(k).viewPart(0, k);

            for (int c = 0; c < cols; c++)
                y.viewColumn(c).viewPart(0, k).map(rCol, Functions.plusMult(-x.get(k, c)));
        }

        return x;
    }

    /**
     * Least squares solution of {@code A*X = B}; {@code returns X}.
     *
     * @param vec A vector with as many rows as {@code A}.
     * @return {@code X<} that minimizes the two norm of {@code Q*R*X - B}.
     * @throws IllegalArgumentException if {@code B.rows() != A.rows()}.
     */
    public Vector solve(Vector vec) {
        if (vec == null)
            throw new NullArgumentException();
        if (vec.size() == 0)
            throw new NoDataException();
        // TODO: IGNITE-5826, Should we copy here?

        Matrix res = solve(vec.likeMatrix(vec.size(), 1).assignColumn(0, vec));

        return vec.like(res.rowSize()).assign(res.viewColumn(0));
    }

    /**
     *
Compute the "hat" matrix.
     *

     *
The hat matrix is defined in terms of the design matrix X
     * by X(XTX)-1XT
     *

     *
The implementation here uses the QR decomposition to compute the
     * hat matrix as Q IpQT where Ip is the
     * p-dimensional identity matrix augmented by 0's.  This computational
     * formula is from "The Hat Matrix in Regression and ANOVA",
     * David C. Hoaglin and Roy E. Welsch,
     * The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
     *

     *
Data for the model must have been successfully loaded using one of
     * the {@code newSampleData} methods before invoking this method; otherwise
     * a {@code NullPointerException} will be thrown.

     *
     * @return the hat matrix
     * @throws NullPointerException unless method {@code newSampleData} has been called beforehand.
     */
    public Matrix calculateHat() {
        // Create augmented identity matrix
        // No try-catch or advertised NotStrictlyPositiveException - NPE above if n < 3
        Matrix augI = MatrixUtil.like(q, q.columnSize(), q.columnSize());

        int n = augI.columnSize();
        int p = r.columnSize();

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (i == j && i < p)
                    augI.setX(i, j, 1d);
                else
                    augI.setX(i, j, 0d);

        // Compute and return Hat matrix
        // No DME advertised - args valid if we get here
        return q.times(augI).times(q.transpose());
    }

    /**
     *
Calculates the variance-covariance matrix of the regression parameters.
     *

     *
Var(b) = (XTX)-1
     *

     *
Uses QR decomposition to reduce (XTX)-1
     * to (RTR)-1, with only the top p rows of
     * R included, where p = the length of the beta vector.

     *
     *
Data for the model must have been successfully loaded using one of
     * the {@code newSampleData} methods before invoking this method; otherwise
     * a {@code NullPointerException} will be thrown.

     *
     * @param p Size of the beta variance-covariance matrix
     * @return The beta variance-covariance matrix
     * @throws SingularMatrixException if the design matrix is singular
     * @throws NullPointerException if the data for the model have not been loaded
     */
    public Matrix calculateBetaVariance(int p) {
        Matrix rAug = MatrixUtil.copy(r.viewPart(0, p, 0, p));
        Matrix rInv = rAug.inverse();

        return rInv.times(rInv.transpose());
    }

    /** {@inheritDoc} */
    @Override public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        QRDSolver solver = (QRDSolver)o;

        return q.equals(solver.q) && r.equals(solver.r);
    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        int res = q.hashCode();
        res = 31 * res + r.hashCode();
        return res;
    }

    /**
     * Returns a rough string rendition of a QRD solver.
     */
    @Override public String toString() {
        return String.format("QRD Solver(%d x %d)", q.rowSize(), r.columnSize());
    }
}


text:
{- |
Copyright   :  (c) Andy Sonnenburg 2013
License     :  BSD3
Maintainer  :  andy22286@gmail.com
-}
module Data.Var
       ( module Data.Var.Class
       ) where

import Data.Var.Class


text:
#include "ecma-globals.h"

#if ENABLED (JERRY_ESNEXT)

#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"

#define BUILTIN_INC_HEADER_NAME "ecma-builtin-generator.inc.h"
#define BUILTIN_UNDERSCORED_ID generator
#include "ecma-builtin-internal-routines-template.inc.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmabuiltins
 * @{
 *
 * \addtogroup generator ECMA Generator object built-in
 * @{
 */

/**
 * @}
 * @}
 * @}
 */

#endif /* ENABLED (JERRY_ESNEXT) */


text:
package org.shypl.biser.csi.server;

import org.shypl.biser.csi.CommunicationLoggingUtils;
import org.shypl.biser.io.ByteArrayOutputData;
import org.shypl.biser.io.DataWriter;
import org.slf4j.Logger;

import java.util.Collection;

public abstract class GlobalMessage {
	private static final ThreadLocal<ByteArrayOutputData> threadLocalData = new ThreadLocal<ByteArrayOutputData>() {
		@Override
		protected ByteArrayOutputData initialValue() {
			return new ByteArrayOutputData();
		}
	};

	private final int    serviceId;
	private final String serviceName;
	private final int    methodId;
	private final String methodName;
	private       Logger logger;

	protected GlobalMessage(int serviceId, String serviceName, int methodId, String methodName) {
		this.serviceId = serviceId;
		this.serviceName = serviceName;
		this.methodId = methodId;
		this.methodName = methodName;
	}

	protected abstract void make(DataWriter writer);

	protected final void log() {
		CommunicationLoggingUtils.logGlobalServerCall(logger, serviceName, methodName);
	}

	protected final void log(Object arg) {
		CommunicationLoggingUtils.logGlobalServerCall(logger, serviceName, methodName, arg);
	}

	protected final void log(Object arg1, Object arg2) {
		CommunicationLoggingUtils.logGlobalServerCall(logger, serviceName, methodName, arg1, arg2);
	}

	protected final void log(Object... args) {
		CommunicationLoggingUtils.logGlobalServerCall(logger, serviceName, methodName, args);
	}

	void send(Collection<? extends AbstractClient> clients, Logger logger) {
		this.logger = logger;

		ByteArrayOutputData data = threadLocalData.get();
		data.clear();
		DataWriter writer = data.getWriter();

		writer.writeInt(0);
		writer.writeInt(serviceId);
		writer.writeInt(methodId);
		make(writer);

		byte[] bytes = data.getArray();

		for (AbstractClient client : clients) {
			client.sendMessage(bytes);
		}
	}
}


text:
import PaMonthTotals from "../paMonthTotals/paMonthTotals";
import { _ } from "underscore";
import dbPaDayTotals from "../../db/dbPaDayTotals";
import dbPaDetails from "../../db/dbPaDetails";
import dbPaMonthTotals from "../../db/dbPaMonthTotals";
import moment from "moment";

// Needed only once at start
const createNotExisting = async () => {
  const docs = await dbPaDetails.getAll();
  const disnt = _.uniq(docs, false, det =>
    moment.utc(det.DepositDate).format("DD-MM-YYYY")
  );
  for (let i = 0; i < disnt.length; i++) {
    const element = disnt[i];
    const doc = await dbPaDayTotals.getByDepositDate(element.DepositDate);
    const dateDetails = await dbPaDetails.getForDepositDate(
      element.DepositDate
    );
    let roomRent = 0;
    let waterCharges = 0;
    let electricityCharges = 0;
    let developmentFund = 0;
    let rutineHstlMaintnceCharges = 0;
    let miscellaneous = 0;
    let celebrationFund = 0;
    let total = 0;
    _.each(dateDetails, ndoc => {
      roomRent += ndoc.RoomRent;
      waterCharges += ndoc.WaterCharges;
      electricityCharges += ndoc.ElectricityCharges;
      developmentFund += ndoc.DevelopmentFund;
      rutineHstlMaintnceCharges += ndoc.RutineHstlMaintnceCharges;
      miscellaneous += ndoc.Miscellaneous;
      celebrationFund += ndoc.CelebrationFund;
      total += ndoc.Total;
    });
    if (doc === null) {
      const nDoc = await dbPaDayTotals.getDefault();
      nDoc.DepositDate = element.DepositDate;
      nDoc.DepositMonth = moment.utc(element.DepositDate).format("MMM, YYYY");
      nDoc.RoomRent = roomRent;
      nDoc.WaterCharges = waterCharges;
      nDoc.ElectricityCharges = electricityCharges;
      nDoc.DevelopmentFund = developmentFund;
      nDoc.RutineHstlMaintnceCharges = rutineHstlMaintnceCharges;
      nDoc.Miscellaneous = miscellaneous;
      nDoc.CelebrationFund = celebrationFund;
      nDoc.Total = total;
      await dbPaDayTotals.insert(nDoc);
    }
  }
};

const upsert = async depositDate => {
  const dets = await dbPaDetails.getForDepositDate(depositDate);
  const exist = await dbPaDayTotals.getByDepositDate(depositDate);
  let roomRent = 0;
  let waterCharges = 0;
  let electricityCharges = 0;
  let developmentFund = 0;
  let rutineHstlMaintnceCharges = 0;
  let miscellaneous = 0;
  let total = 0;
  _.each(dets, element => {
    roomRent += element.RoomRent;
    waterCharges += element.WaterCharges;
    electricityCharges += element.ElectricityCharges;
    developmentFund += element.DevelopmentFund;
    rutineHstlMaintnceCharges += element.RutineHstlMaintnceCharges;
    miscellaneous += element.Miscellaneous;
    total += element.Total;
  });
  if (exist) {
    exist.RoomRent = roomRent;
    exist.WaterCharges = waterCharges;
    exist.ElectricityCharges = electricityCharges;
    exist.DevelopmentFund = developmentFund;
    exist.RutineHstlMaintnceCharges = rutineHstlMaintnceCharges;
    exist.Miscellaneous = miscellaneous;
    exist.Total = total;
    if (exist.Total === 0 && dets.length === 0) {
      await dbPaDayTotals.remove(exist._id);
    } else if (exist.Total !== 0) {
      await dbPaDayTotals.update(exist);
    }
  } else {
    if (dets.length !== 0) {
      const det = await dbPaDayTotals.getDefault();
      det.DepositDate = depositDate;
      det.DepositMonth = moment.utc(depositDate).format("MMM, YYYY");
      det.RoomRent = roomRent;
      det.WaterCharges = waterCharges;
      det.ElectricityCharges = electricityCharges;
      det.DevelopmentFund = developmentFund;
      det.RutineHstlMaintnceCharges = rutineHstlMaintnceCharges;
      det.Miscellaneous = miscellaneous;
      det.Total = total;
      await dbPaDayTotals.insert(det);
    }
  }
  await PaMonthTotals.upsert(moment.utc(depositDate).format("MMM, YYYY"));
};

const getByPage = async args => {
  let skipVal = 0;
  if (parseInt(args.pageNo, 10) > 1) {
    skipVal = (parseInt(args.pageNo, 10) - 1) * 15;
  }
  const out = await dbPaDayTotals.getByPage(skipVal);
  const count = await dbPaDayTotals.paDayTotalsCount();
  return {
    dayTotals: out,
    count
  };
};

const removeByDate = async args => {
  const date = moment.utc(args.depositDate, "DD-MM-YYYY").toDate();
  await dbPaDayTotals.removeByDate(date);
  await dbPaDetails.removeByDate(date);
  await PaMonthTotals.upsert(moment.utc(date).format("MMM, YYYY"));
  return "PaDayTotal Removed";
};

const autoDeposit = async args => {
  await dbPaDayTotals.autoDeposit(args.id);
  const out = await dbPaDayTotals.getById(args.id);
  const docs = await dbPaDayTotals.getByDepositMonth(out.detail.DepositMonth);
  let deposit = 0;
  let excessDeposit = 0;
  _.each(docs, element => {
    deposit += element.Deposit;
    excessDeposit += excessDeposit;
  });
  await dbPaMonthTotals.updateMonthDeposit(
    out.detail.DepositMonth,
    deposit,
    excessDeposit
  );
  await PaMonthTotals.upsert(out.detail.DepositMonth);
  return "PaDayTotal AutoDeposited";
};

const getById = async args => {
  return await dbPaDayTotals.getById(args.detId);
};

const updatePaDayDeposits = async args => {
  const out = await dbPaDayTotals.getById(args.detId);
  const updated = await dbPaDayTotals.updatePaDayDeposits(
    args.detId,
    args.deposit
  );
  await PaMonthTotals.upsert(out.detail.DepositMonth);
  return updated;
};

const PaDayTotals = {
  createNotExisting,
  upsert,
  updatePaDayDeposits,
  getById,
  autoDeposit,
  removeByDate,
  getByPage
};

export default PaDayTotals;


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" id="btnWith" value="With Stop Propagation"/>
    <input type="button" id="btnWithout" value="Without"/>
    <script src="04%20Stop%20Propagation.js"></script>
</body>
</html>


text:
'use strict';

describe('Resources', function(){

  beforeEach(module('myApp'));

  it( 'tests PathHelper', inject(function(PathHelper) {
    expect( PathHelper.city.newsitems_path('ch') ).toEqual( 'travel-to/ch/newsitems' );
    expect( PathHelper.city.reports_path('ciity') ).toEqual( 'travel-to/ciity/reports' );
    expect( PathHelper.city_path('which city') ).toEqual( 'travel-to/which city' );
    expect( PathHelper.event_path('cityname', 'eventname') ).toEqual( 'cityname/events/show/eventname' );
    expect( PathHelper.gallery_path('g') ).toEqual( 'http://piousbox.com/en/galleries/show/g/0' );
    expect( PathHelper.partial('da') ).toEqual( '/partials/da.html' );
    expect( PathHelper.partial_compiled('daa') ).toEqual( '/en/daa' );
    expect( PathHelper.report_path( 'reportname', 'cityname' ) ).toEqual( 'cityname/reports/view/reportname' );
  }));

});


text:
( function( $ ) {
	var $body = $( 'body' );

	/**
	* Focus styles for menus.
	*
    */
	$( '.main-navigation' ).find( 'a' ).on( 'focus.argent blur.argent', function() {
		$( this ).parents().toggleClass( 'focus' );
	} );

	/**
    * Slick slideshow configuration
    *
    */
	function slickInit() {
		var $slider = $( '.slick-slider' );

		if ( $slider.length !== 0 ) {
			$slider.slick( {
				arrows		: false,
				dots		: true,
				infinite	: true,
				speed		: 300,
				slidesToShow: 1,
				centerMode	: true,
				variableWidth: true
			} );
		} else {
			return;
		}
		// Fade in the slideshow
		$( '.slick' ).fadeTo( 100, 1 );

		// Add next/prev navigation to the carousel
		$slider.on( 'click', function(e) {
			var clickXPosition = e.pageX - this.offsetLeft;

			// Go to the previous image if the click occurs in the left half of gallery,
			// or the next image if the click occurs in the right half.
			if (clickXPosition < $( window ).width() / 2 ) {
				$( this ).slick('slickPrev');
			} else {
				$( this ).slick('slickNext');
			}
			return false;
		});

        // Add classes to allow next/prev cursor styling
		$slider.on( 'mousemove', function(e){
			var mouseXPosition = e.pageX - this.offsetLeft;
			if (mouseXPosition < $( window ).width() / 2 ) {
				$( this ).removeClass( "right-arrow" );
				$( this ).addClass( "left-arrow" );
			} else {
				$( this ).removeClass( "left-arrow" );
				$( this ).addClass( "right-arrow" );
			}
		});
	}

	/*
	 * Add extra class to large images on pages and in single project view. Props to Intergalactic theme
	 */
	function outdentImages() {
		$( '.page-content img.size-full, .jetpack-portfolio.hentry .entry-content img.size-full' ).each( function() {
			var img = $( this ),
			    caption = $( this ).closest( 'figure' ),
				new_img = new Image();

				new_img.src = img.attr( 'src' );

				$( new_img ).load( function() {

					var img_width = new_img.width;
					if ( img_width >= 780 ) {
						$( img ).addClass( 'size-big' );
					}

				if ( caption.hasClass( 'wp-caption' ) && img_width >= 780 ) {
					caption.addClass( 'caption-big' );
				}
			} );
		} );
	}

	// Initialize Slick slideshow
	$( window ).load( function() {
		slickInit();
		outdentImages();
	});

} )( jQuery );


text:
from __future__ import print_function

import functools

import pytest
from jaraco.test import services

import pmxbot.util

def throws_exception(call, exceptions=[Exception]):
	"""
	Invoke the function and return True if it raises any of the
	exceptions provided. Otherwise, return False.
	"""
	try:
		call()
	except tuple(exceptions):
		return True
	except Exception:
		pass
	return False

def pytest_namespace():
	return dict(
		has_internet = pytest.mark.skipif('not pytest.config.has_internet'),
		has_wordnik = pytest.mark.skipif('not pytest.config.has_wordnik'),
	)

def pytest_configure(config):
	open_google = functools.partial(pmxbot.util.get_html,
		'http://www.google.com')
	config.has_internet = not throws_exception(open_google)
	config.has_wordnik = 'wordnik' in dir(pmxbot.util)

def pytest_addoption(parser):
	parser.addoption("--runslow", action="store_true",
		help="run slow tests")

def pytest_runtest_setup(item):
	if 'slow' in item.keywords and not item.config.getvalue("runslow"):
		pytest.skip("need --runslow option to run")

def mongodb_instance():
	try:
		import pymongo
		instance = services.MongoDBInstance()
		instance.log_root = ''
		instance.start()
		pymongo.Connection(instance.get_connect_hosts())
	except Exception:
		return None
	return instance

def pytest_funcarg__mongodb_uri(request):
	instance = request.cached_setup(setup=mongodb_instance, scope='session',
		teardown=lambda instance: instance.stop() if instance else None)
	if not instance:
		pytest.skip("MongoDB not available")
	return 'mongodb://' + ','.join(instance.get_connect_hosts())

@pytest.fixture(params=['mongodb', 'sqlite'])
def db_uri(request):
	if request.param == 'mongodb':
		return request.getfuncargvalue('mongodb_uri')
	return 'sqlite:pmxbot.sqlite'


text:
@interface SearchResultViewController ()

@end

@implementation SearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"搜索结果显示";
    self.customNavBarView.backgroundColor  = [CXUserDefaults instance].bgColor;

    QuestionCollectionViewCell *contentView = [[QuestionCollectionViewCell alloc] initWithFrame:CGRectZero];
    contentView.backgroundColor = CXWhiteColor;
    [contentView updateUIByQuestion:_question showRightAnswer:YES];
    [self.view addSubview:contentView];

    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.customNavBarView.mas_bottom);
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
/****************************************************************************************/
/*                                                                                */
/*                                       Pegasus                                        */
/*                                                                                */
/****************************************************************************************/

//! \file   GLExtensions.h
//! \author Karolyn Boulanger
//! \date   11th June 2013
//! \brief  Management of GL and WGL extensions, available throughout the engine
//!         to check if features are available before using them

#ifndef PEGASUS_RENDER_GLEXTENSIONS_H
#define PEGASUS_RENDER_GLEXTENSIONS_H

namespace Pegasus {
namespace Render {

//! Singleton that manages GL and WGL extensions, available throughout the engine
//! to check if features are available before using them
class GLExtensions
{
public:
    //! Definition of available OpenGL profiles
    enum Profile
    {
        PROFILE_NO_GL,      //!< No proper OpenGL support
        PROFILE_GL_3_3,     //!< GLSL 3.30, VS+GS+PS, samplers, floating point textures, instancing
        PROFILE_GL_4_3,     //!< GLSL 4.30, tessellation, compute shaders
        PROFILE_MAX
    };

    //! Constructor
    //! Initializes the extensions manager for OpenGL.
    //! Performs detection of the OpenGL version and the list of extensions available.
    GLExtensions();

    //! Destructor
    ~GLExtensions();

    //! Get the maximum profile handled by the GPU and the driver
    //! \return PROFILE_x constant representing the maximal profile handled by the GPU.
    //!         All the profiles with a lower version number are supported.
    Profile GetMaximumProfile() const;

    //! Test if a profile is supported by the GPU and the driver
    //! \param profile Profile to test, PROFILE_x constant
    //! \return True if the input profile is supported
    bool IsProfileSupported(Profile profile) const;

    //! Test if a OpenGL extension is supported
    //! \param name Full name of the extension, "GL_ARB_multitexture" for example
    //! \return True if the OpenGL extension is supported
    bool IsGLExtensionSupported(const char * name) const;

    //! Test if a WGL extension is supported
    //! \todo Make this function available only on Windows
    //! \param name Full name of the extension, "WGL_ARB_pbuffer" for example
    //! \return True if the WGL extension is supported
    bool IsWGLExtensionSupported(const char * name) const;

private:
    //! Test if a profile is a valid one
    //! \param profile Profile to test (PROFILE_x constant)
    //! \return True if the profile is valid (between PROFILE_NO_GL and PROFILE_MAX)
    bool IsProfileValid(Profile profile) const;

    static GLExtensions * sInstance; //!< Unique instance of the class
    bool mGLEWInitialized; //!< True when GLEW has been initialized properly
};

}   // namespace Render
}   // namespace Pegasus

#endif  // PEGASUS_RENDER_GLEXTENSIONS_H


text:
#ifndef VOXEL_TI_TINTINCDKCAMERAUVC_H
#define VOXEL_TI_TINTINCDKCAMERAUVC_H

#include <ToFTintinCamera.h>
#include <Downloader.h>
#include <TintinCDKCameraCommon.h>
#define TINTIN_CDK_VENDOR_ID 0x0451U
#define TINTIN_CDK_PRODUCT_UVC 0x9106U

#define PVDD "pvdd" // Illumination voltage
#define MIX_VOLTAGE "mix_volt" // Mixing voltage
#define TILLUM_SLAVE_ADDR "tillum_slv_addr"
#define LUMPED_DEAD_TIME "lumped_dead_time"
#define ILLUM_DC_CORR "illum_dc_corr"
#define ILLUM_DC_CORR_DIR "illum_dc_corr_dir"
#define DELAY_FB_CORR_MODE "delay_fb_corr_mode"
#define DELAY_FB_DC_CORR_MODE "delay_fb_dc_corr_mode"
#define COMP_VREF "comp_vref"

namespace Voxel
{

namespace TI
{

class TintinCDKCameraUVC: public ToFTintinCamera
{
protected:
  Ptr<Downloader> _downloader;

  bool _init();

  virtual bool _getFieldOfView(float &fovHalfAngle) const;
  virtual bool _getSupportedVideoModes(Vector<SupportedVideoMode> &supportedVideoModes) const;
  virtual bool _setStreamerFrameSize(const FrameSize &s);

  virtual bool _getMaximumVideoMode(VideoMode &videoMode) const;
  virtual bool _getMaximumFrameRate(FrameRate& frameRate, const FrameSize& forFrameSize) const;

  virtual bool _initStartParams();

public:
  TintinCDKCameraUVC(DevicePtr device);

  virtual ~TintinCDKCameraUVC() {}

};

}
}

#endif // VOXEL_TI_TINTINCDKCAMERA_H


text:
var fs = require('fs'),
    _ = require('underscore'),
    path = require('path'),
    Promise = require('bluebird'),
    logger = require('./logger'),
    request = require('request');

module.exports = {
    run: function (options) {
        return new Promise(function (resolve, reject) {
            var fileToStream = path.join(process.cwd(), '.demeteorized/bundle.zip');
            var fileSize = fs.statSync(fileToStream).size;

            var status = logger.newStream('Uploading zip...', fileSize);

            // Read the .zip file into the request
            fs.createReadStream(fileToStream)
                .pipe(status)
                .pipe(request
                    // PUT /api/zip/site/wwwroot -> body=bundle.zip
                    // https://github.com/projectkudu/kudu/wiki/REST-API#zip
                    .put('https://' + options.siteName + '.scm.azurewebsites.net/api/zip/site/wwwroot')
                    .auth(options.username, options.password, true))
                .on('error', function (err) {
                    logger.error('run-deploy', 'Error while uploading zip');
                    reject(err);
                })
                .on('end', function () {
                    logger.info('run-deploy', 'Successfully uploaded zip');
                    resolve();
                });
        })
    }
}


text:
const path = require('path');
// load the default config generator.
var genDefaultConfig = require('@kadira/storybook/dist/server/config/defaults/webpack.config.js');

// Export a function. Accept the base config as the only param.
module.exports = function(storybookBaseConfig, configType) {
  // configType has a value of 'DEVELOPMENT' or 'PRODUCTION'
  // You can change the configuration based on that.
  // 'PRODUCTION' is used when building the static version of storybook.
  // Make whatever fine-grained changes you need
  var config = genDefaultConfig(storybookBaseConfig, configType);

  config.module.loaders.push({
    test: /.scss$/,
    loaders: ["style", "css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]", "sass"],
    include: path.resolve(__dirname, '../')
  },
  {
    test: /\.tsx?$/,
    loaders: ["awesome-typescript-loader"],
    include: path.resolve(__dirname, '../')
  });

  config.resolve.extensions.push(".tsx")
  config.resolve.extensions.push(".ts")

  // Return the altered config
  return config;
};


text:
require "spec_helper"

describe Intercom::BaseCollectionProxy do
  let(:client) { Intercom::Client.new(token: 'token') }

  it "stops iterating if no starting after value" do
    client.expects(:get).with("/contacts", {}).returns(page_of_contacts(false))
    emails = []
    client.contacts.all.each { |contact| emails << contact.email }
    _(emails).must_equal %w[test1@example.com test2@example.com test3@example.com]
  end

  it "keeps iterating if starting after value" do
    client.expects(:get).with("/contacts", {}).returns(page_of_contacts(true))
    client.expects(:get).with('/contacts', { starting_after: "EnCrYpTeDsTrInG" }).returns(page_of_contacts(false))
    emails = []
    client.contacts.all.each { |contact| emails << contact.email }
    _(emails).must_equal %w[test1@example.com test2@example.com test3@example.com test1@example.com test2@example.com test3@example.com]
  end

  it "supports indexed array access" do
    client.expects(:get).with("/contacts", {}).returns(page_of_contacts(false))
    _(client.contacts.all[0].email).must_equal "test1@example.com"
  end

  it "supports map" do
    client.expects(:get).with("/contacts", {}).returns(page_of_contacts(false))
    emails = client.contacts.all.map { |contact| contact.email }
    _(emails).must_equal %w[test1@example.com test2@example.com test3@example.com]
  end

  it "keeps entire collection iterable after first iteration" do
    contacts = client.contacts.all
    emails_iter1 = []
    emails_iter2 = []
    expects_pagination = proc do
      client.expects(:get).with("/contacts", {}).returns(page_of_contacts(true))
      client.expects(:get).with("/contacts", { starting_after: "EnCrYpTeDsTrInG" }).returns(page_of_contacts(false))
    end

    expects_pagination.call
    contacts.each { |contact| emails_iter1 << contact.email }
    expects_pagination.call
    contacts.each { |contact| emails_iter2 << contact.email }
    _(emails_iter1).must_equal emails_iter2
  end
end


text:
package com.cinchapi.concourse.server.storage.temp;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;

import com.cinchapi.concourse.server.model.TObjectSorter;
import com.cinchapi.concourse.server.model.Value;
import com.cinchapi.concourse.server.storage.Action;
import com.cinchapi.concourse.server.storage.BaseStore;
import com.cinchapi.concourse.server.storage.PermanentStore;
import com.cinchapi.concourse.server.storage.db.Database;
import com.cinchapi.concourse.thrift.Operator;
import com.cinchapi.concourse.thrift.TObject;
import com.cinchapi.concourse.time.Time;
import com.cinchapi.concourse.util.MultimapViews;
import com.cinchapi.concourse.util.TMaps;
import com.cinchapi.concourse.util.TStrings;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import static com.google.common.collect.Maps.newLinkedHashMap;

/**
 * {@link Limbo} is a lightweight in-memory proxy store that is a suitable cache
 * or fast, albeit temporary, store for data that will eventually be persisted
 * to a {@link PermanentStore}.
 *

 * The store is designed to write data very quickly
 * at the expense of much slower read time. {@code Limbo} does
 * not index1 any of the data it stores, so reads are not as
 * efficient as they would normally be in the {@link Database}.
 *

 *

 * This class provides naive read implementations for the methods specified in
 * the {@link WritableStore} interface, but the subclass is free to override
 * those methods to provide smarter implementations of introduce concurrency
 * controls.
 *

 * 1 - All reads are O(n) because {@code Limbo} uses an
 * {@link #iterator()} to traverse the {@link Write} objects that it stores.
 *
 * @author Jeff Nelson
 */
@NotThreadSafe
public abstract class Limbo extends BaseStore implements Iterable<Write> {

    /**
     * Return {@code true} if {@code input} matches {@code operator} in relation
     * to {@code values}.
     *
     * @param input
     * @param operator
     * @param values
     * @return {@code true} if {@code input} matches
     */
    protected static boolean matches(Value input, Operator operator,
            TObject... values) {
        Value v1 = Value.wrap(values[0]);
        switch (operator) {
        case EQUALS:
            return v1.equals(input);
        case NOT_EQUALS:
            return !v1.equals(input);
        case GREATER_THAN:
            return v1.compareTo(input) < 0;
        case GREATER_THAN_OR_EQUALS:
            return v1.compareTo(input) <= 0;
        case LESS_THAN:
            return v1.compareTo(input) > 0;
        case LESS_THAN_OR_EQUALS:
            return v1.compareTo(input) >= 0;
        case BETWEEN:
            Preconditions.checkArgument(values.length > 1);
            Value v2 = Value.wrap(values[1]);
            return v1.compareTo(input) <= 0 && v2.compareTo(input) > 0;
        case REGEX:
            return input.getObject().toString()
                    .matches(v1.getObject().toString());
        case NOT_REGEX:
            return !input.getObject().toString()
                    .matches(v1.getObject().toString());
        default:
            throw new UnsupportedOperationException();
        }
    }

    /**
     * A Predicate that is used to filter out empty sets.
     */
    protected static final Predicate<Set<? extends Object>> emptySetFilter = new Predicate<Set<? extends Object>>() {

        @Override
        public boolean apply(@Nullable Set<? extends Object> input) {
            return !input.isEmpty();
        }

    };

    @Override
    public Map<Long, String> audit(long record) {
        Map<Long, String> audit = Maps.newTreeMap();
        for (Iterator<Write> it = iterator(); it.hasNext();) {
            Write write = it.next();
            if(write.getRecord().longValue() == record) {
                audit.put(write.getVersion(), write.toString());
            }
        }
        return audit;

    }

    @Override
    public Map<Long, String> audit(String key, long record) {
        Map<Long, String> audit = Maps.newTreeMap();
        for (Iterator<Write> it = iterator(); it.hasNext();) {
            Write write = it.next();
            if(write.getKey().toString().equals(key)
                    && write.getRecord().longValue() == record) {
                audit.put(write.getVersion(), write.toString());
            }
        }
        return audit;

    }

    @Override
    public Map<TObject, Set<Long>> browse(String key) {
        return browse(key, Time.NONE);
    }

    @Override
    public Map<TObject, Set<Long>> browse(String key, long timestamp) {
        Map<TObject, Set<Long>> context = Maps
                .newTreeMap(TObjectSorter.INSTANCE);
        return browse(key, timestamp, context);
    }

    /**
     * Calculate the browsable view of {@code key} at {@code timestamp} using
     * prior {@code context} as if it were also a part of the Buffer.
     *
     * @param key
     * @param timestamp
     * @param context
     * @return a possibly empty Map of data
     */
    public Map<TObject, Set<Long>> browse(String key, long timestamp,
            Map<TObject, Set<Long>> context) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write write = it.next();
                if(write.getKey().toString().equals(key)
                        && write.getVersion() <= timestamp) {
                    Set<Long> records = context.get(write.getValue()
                            .getTObject());
                    if(records == null) {
                        records = Sets.newLinkedHashSet();
                        context.put(write.getValue().getTObject(), records);
                    }
                    if(write.getType() == Action.ADD) {
                        records.add(write.getRecord().longValue());
                    }
                    else {
                        records.remove(write.getRecord().longValue());
                    }
                }
                else if(write.getVersion() > timestamp) {
                    break;
                }
                else {
                    continue;
                }
            }
        }
        return Maps.newTreeMap((SortedMap<TObject, Set<Long>>) Maps
                .filterValues(context, emptySetFilter));
    }

    @Override
    public boolean contains(long record) {
        for (Iterator<Write> it = iterator(); it.hasNext();) {
            Write write = it.next();
            if(write.getRecord().longValue() == record) {
                return true;
            }
        }
        return false;
    }

    /**
     * Calculate the description for {@code record} using prior {@code context}
     * as if it were also a part of the Buffer.
     *
     * @param record
     * @param timestamp
     * @param context
     * @return a possibly empty Set of keys
     */
    public Set<String> describe(long record, long timestamp,
            Map<String, Set<TObject>> context) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write write = it.next();
                if(write.getRecord().longValue() == record
                        && write.getVersion() <= timestamp) {
                    Set<TObject> values;
                    values = context.get(write.getKey().toString());
                    if(values == null) {
                        values = Sets.newHashSet();
                        context.put(write.getKey().toString(), values);
                    }
                    if(write.getType() == Action.ADD) {
                        values.add(write.getValue().getTObject());
                    }
                    else {
                        values.remove(write.getValue().getTObject());
                    }
                }
                else if(write.getVersion() > timestamp) {
                    break;
                }
                else {
                    continue;
                }
            }
        }
        return newLinkedHashMap(Maps.filterValues(context, emptySetFilter))
                .keySet();
    }

    /**
     * This is an implementation of the {@code findAndBrowse} routine that takes
     * in a prior {@code context}. Find and browse will return a mapping from
     * records that match a criteria (expressed as {@code key} filtered by
     * {@code operator} in relation to one or more {@code values}) to the set of
     * values that cause that record to match the criteria.
     *
     * @param context
     * @param timestamp
     * @param key
     * @param operator
     * @param values
     * @return the relevant data for the records that satisfy the find query
     */
    public Map<Long, Set<TObject>> explore(Map<Long, Set<TObject>> context,
            long timestamp, String key, Operator operator, TObject... values) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write write = it.next();
                long record = write.getRecord().longValue();
                if(write.getVersion() <= timestamp) {
                    if(write.getKey().toString().equals(key)
                            && matches(write.getValue(), operator, values)) {
                        if(write.getType() == Action.ADD) {
                            MultimapViews.put(context, record, write.getValue()
                                    .getTObject());
                        }
                        else {
                            MultimapViews.remove(context, record, write
                                    .getValue().getTObject());
                        }
                    }
                }
                else {
                    break;
                }
            }
        }
        return TMaps.asSortedMap(context);
    }

    /**
     * Return the number of milliseconds that this store desires any back to
     * back transport requests to pause in between.
     *
     * @return the pause time
     */
    public int getDesiredTransportSleepTimeInMs() {
        return 0;
    }

    /**
     * Insert {@code write} into the store without performing any
     * validity checks.
     *

     * This method is only safe to call from a context that performs
     * its own validity checks (i.e. a {@link BufferedStore}).
     *
     * @param write
     * @return {@code true}
     */
    public final boolean insert(Write write) {
        return insert(write, true);
    }

    /**
     * Insert {@code write} into the store without performing any
     * validity checks and specify whether a {@code sync} should occur
     * or not. By default, syncs are meaningless in {@link Limbo}, but some
     * implementations may wish to provide guarantees that the write will be
     * durably stored.
     *

     * This method is only safe to call from a context that performs
     * its own validity checks (i.e. a {@link BufferedStore}).
     *
     * @param write - The write to append
     * @param sync - a flag that controls whether this instance will make an
     *            attempt to durably persist the data to some backing store.
     *            Simply ignore this flag if the implementation does not support
     *            durability
     * @return {@code true}
     */
    public abstract boolean insert(Write write, boolean sync);

    /**
     * {@inheritDoc}
     *

     * NOTE: The subclass may override this method to
     * provide an iterator with granular locking functionality for increased
     * throughput.
     *

     */
    @Override
    public abstract Iterator<Write> iterator();

    @Override
    public Set<Long> search(String key, String query) {
        Map<Long, Set<Value>> rtv = Maps.newHashMap();
        String[] needle = TStrings.stripStopWordsAndTokenize(query
                .toLowerCase());
        if(needle.length > 0) {
            for (Iterator<Write> it = getSearchIterator(key); it.hasNext();) {
                Write write = it.next();
                Value value = write.getValue();
                long record = write.getRecord().longValue();
                if(isPossibleSearchMatch(key, write, value)) {
                    /*
                     * NOTE: It is not enough to merely check if the stored text
                     * contains the query because the Database does infix
                     * indexing/searching, which has some subtleties:
                     * 1. Stop words are removed from the both stored indices
                     * and the search query
                     * 2. A query and document are considered to match if the
                     * document contains a sequence of terms where each term or
                     * a substring of the term matches the term in the same
                     * relative position of the query.
                     */
                    // CON-10: compare lowercase for case insensitive search
                    String stored = (String) (value.getObject());
                    String[] haystack = TStrings
                            .stripStopWordsAndTokenize(stored.toLowerCase());
                    if(haystack.length > 0
                            && TStrings.isInfixSearchMatch(needle, haystack)) {
                        Set<Value> values = rtv.get(record);
                        if(values == null) {
                            values = Sets.newHashSet();
                            rtv.put(record, values);
                        }
                        if(write.getType() == Action.REMOVE) {
                            values.remove(value);
                        }
                        else {
                            values.add(value);
                        }

                    }
                }
            }
        }
        // FIXME sort search results based on frequency (see
        // SearchRecord#search())
        return newLinkedHashMap(Maps.filterValues(rtv, emptySetFilter))
                .keySet();
    }

    @Override
    public Map<String, Set<TObject>> select(long record) {
        return select(record, Time.NONE);
    }

    @Override
    public Map<String, Set<TObject>> select(long record, long timestamp) {
        Map<String, Set<TObject>> context = Maps
                .newTreeMap(new Comparator<String>() {

                    @Override
                    public int compare(String s1, String s2) {
                        return s1.compareToIgnoreCase(s2);
                    }

                });
        return select(record, timestamp, context);
    }

    /**
     * Calculate the browsable view of {@code record} at {@code timestamp} using
     * prior {@code context} as if it were also a part of the Buffer.
     *
     * @param key
     * @param timestamp
     * @param context
     * @return a possibly empty Map of data
     */
    public Map<String, Set<TObject>> select(long record, long timestamp,
            Map<String, Set<TObject>> context) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write write = it.next();
                if(write.getRecord().longValue() == record
                        && write.getVersion() <= timestamp) {
                    Set<TObject> values;
                    values = context.get(write.getKey().toString());
                    if(values == null) {
                        values = Sets.newHashSet();
                        context.put(write.getKey().toString(), values);
                    }
                    if(write.getType() == Action.ADD) {
                        values.add(write.getValue().getTObject());
                    }
                    else {
                        values.remove(write.getValue().getTObject());
                    }
                }
                else if(write.getVersion() > timestamp) {
                    break;
                }
                else {
                    continue;
                }
            }
        }
        return Maps.newTreeMap((SortedMap<String, Set<TObject>>) Maps
                .filterValues(context, emptySetFilter));
    }

    @Override
    public Set<TObject> select(String key, long record) {
        return select(key, record, Time.NONE);
    }

    @Override
    public Set<TObject> select(String key, long record, long timestamp) {
        return select(key, record, timestamp, Sets.<TObject> newLinkedHashSet());
    }

    /**
     * Fetch the values mapped from {@code key} in {@code record} at
     * {@code timestamp} using prior {@code context} as if it were also a part
     * of the Buffer.
     *
     * @param key
     * @param record
     * @param timestamp
     * @param context
     * @return the values
     */
    public Set<TObject> select(String key, long record, long timestamp,
            Set<TObject> context) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write write = it.next();
                if(write.getVersion() <= timestamp) {
                    if(key.equals(write.getKey().toString())
                            && record == write.getRecord().longValue()) {
                        if(write.getType() == Action.ADD) {
                            context.add(write.getValue().getTObject());
                        }
                        else {
                            context.remove(write.getValue().getTObject());
                        }
                    }
                }
                else {
                    break;
                }
            }
        }
        return context;
    }

    /**
     * If the implementation supports durable storage, this method guarantees
     * that all the data contained here-within is durably persisted. Otherwise,
     * this method is meaningless and returns immediately.
     */
    public void sync() {/* noop */}

    /**
     * Transport the content of this store to {@code destination}.
     *
     * @param destination
     */
    public final void transport(PermanentStore destination) {
        transport(destination, true);
    }

    /**
     * Transport the content of this store to {@code destination} with the
     * directive to {@code sync} or not. A sync guarantees that the transported
     * data is durably persisted within the {@link PermanentStore}.
     *
     * @param destination - the recipient store for the data
     * @param syncAfterEach - a flag that controls whether a call is always made
     *            to durably persist (i.e. fsync) in the {@code destination}
     *            after each write is transported
     */
    public void transport(PermanentStore destination, boolean syncAfterEach) {
        for (Iterator<Write> it = iterator(); it.hasNext();) {
            destination.accept(it.next(), syncAfterEach);
            it.remove();
        }
    }

    @Override
    public boolean verify(String key, TObject value, long record) {
        return verify(key, value, record, Time.NONE);
    }

    @Override
    public boolean verify(String key, TObject value, long record, long timestamp) {
        return verify(Write.notStorable(key, value, record), timestamp);
    }

    /**
     * Return {@code true} if {@code write} represents a data mapping that
     * currently exists using {@code exists} as prior context.
     *

     * This method is called from
     * {@link BufferedStore#verify(String, TObject, long)}.
     *

     *
     * @param write
     * @return {@code true} if {@code write} currently appears an odd number of
     *         times
     */
    public boolean verify(Write write, boolean exists) {
        return verify(write, Time.NONE, exists);
    }

    /**
     * Return {@code true} if {@code write} represents a data mapping that
     * exists at {@code timestamp}.
     *

     * This method is called from
     * {@link BufferedStore#verify(String, TObject, long, long)}.
     *

     *
     * @param write
     * @param timestamp
     * @return {@code true} if {@code write} appears an odd number of times at
     *         {@code timestamp}
     */
    public boolean verify(Write write, long timestamp) {
        return verify(write, timestamp, false);
    }

    /**
     * Return {@code true} if {@code write} represents a data mapping that
     * exists at {@code timestamp}, using {@code exists} as prior context.
     *

     * NOTE: ALL OTHER VERIFY METHODS DEFER TO THIS ONE.
     *

     *
     * @param write
     * @param timestamp
     * @param exists
     * @return {@code true} if {@code write} appears an odd number of times at
     *         {@code timestamp}
     */
    public boolean verify(Write write, long timestamp, boolean exists) {
        if(timestamp >= getOldestWriteTimstamp()) {
            for (Iterator<Write> it = iterator(); it.hasNext();) {
                Write stored = it.next();
                if(stored.getVersion() <= timestamp) {
                    if(stored.equals(write)) {
                        exists ^= true; // toggle boolean
                    }
                }
                else {
                    break;
                }
            }
        }
        return exists;
    }

    /**
     * Wait (block) until the Buffer has enough data to complete a transport.
     * This method should be called from the external service to avoid busy
     * waiting if continuously transporting data in the background.
     */
    public void waitUntilTransportable() {
        return; // do nothing because Limbo is assumed to always be
                // transportable. But the Buffer will override this method with
                // the appropriate conditions.
    }

    @Override
    protected Map<Long, Set<TObject>> doExplore(long timestamp, String key,
            Operator operator, TObject... values) {
        return explore(Maps.<Long, Set<TObject>> newLinkedHashMap(), timestamp,
                key, operator, values);
    }

    @Override
    protected Map<Long, Set<TObject>> doExplore(String key, Operator operator,
            TObject... values) {
        return explore(Time.NONE, key, operator, values);
    }

    /**
     * Return the timestamp for the oldest write available.
     *
     * @return {@code timestamp}
     */
    protected abstract long getOldestWriteTimstamp();

    /**
     * Return the iterator to use in the {@link #search(String, String)} method.
     *
     * @param key
     * @return the appropriate iterator to use for searching
     */
    protected abstract Iterator<Write> getSearchIterator(String key);

    /**
     * Allows the subclass to define some criteria for the search logic to
     * determine if {@code write} with {@code value} is a possible search match
     * for {@code key}.
     *

     * NOTE: This method should NOT check to see if
     * {@code write} is an true search match for {@code value} because that
     * logic is handled in the {@link #search(String, String)} method. The
     * purpose of this method is merely to help quickly eliminate writes that
     * can't possibly be a search match (i.e. because the write has a non-string
     * value or a different key).
     *

     *

     * NOTE: The {@link Buffer} uses this method to optimize
     * the check since the iterator it returns in
     * {@link #getSearchIterator(String)} already ensures that {@code write} has
     * the same key component as {@code key}.
     *

     *
     * @param key
     * @param write
     * @param value
     * @return {@code true} if the write is a possible search match
     */
    protected abstract boolean isPossibleSearchMatch(String key, Write write,
            Value value);

}


text:
<ion-view title="{{isMine ? 'lbl_mytrip': 'lbl_trip'| translate}}">
    <ion-nav-buttons side="right">

    </ion-nav-buttons>
    <ion-content>

                <leaflet event-broadcast="events" center="center" markers="markers" paths="pathLine" style="width: 100%; height: 200px;" ng-init="initMap()" id="tripMap"></leaflet>

                            {{driverInfo.dpName}}

                        <button class="button button-clear button-calm custom-button-calm" ng-click="showUser()">
                            {{'lbl_show_profile' | translate}}
                        </button>

{{mainCommunity.name}}

                    {{mainCommunity.name}}

                {{selectedTrip.when | date:travelDateFormat}}

                    {{'lbl_from' | translate | uppercase}}: {{selectedTrip.from.name}}

                    {{'lbl_to' | translate | uppercase}}: {{selectedTrip.to.name}}

                    {{'lbl_start_time' | translate}}: {{selectedTrip.route.startime | date:travelTimeFormat}}

                    {{'lbl_end_time' | translate}}: {{selectedTrip.route.endtime | date:travelTimeFormat}}

                {{'lbl_halfwaystops' | translate}}: {{(!!selectedTrip.intermediateStops ? 'lbl_halfwaystops_onrequest' : 'lbl_halfwaystops_none') | translate}}

                {{'lbl_recurrency' | translate}}: {{!!selectedTrip.recurrency ? dowString : 'lbl_recurrency_none' | translate}}

{{'lbl_passengers' | translate | uppercase}}

            {{'lbl_trip_rejected' | translate}}
            {{'lbl_trip_requested' | translate}}
            {{'lbl_trip_accepted' | translate}}

                <button class="button button-carpooling" ng-click="bookingAction()" ng-disabled="myBooking.accepted === -1 || myBooking.accepted === 0 || (myBooking.accepted === null && !!isPastTrip)">
                    {{'lbl_trip_ask' | translate | uppercase}}
                    {{'lbl_trip_rate' | translate | uppercase}}
                </button>

                <button class="button button-carpooling" ng-click="chatWithDriver()">
                    {{'lbl_driver_contact' | translate | uppercase}}
                </button>

 0">

{{'lbl_requests' | translate}}

            <ion-list ng-if="bookingCounters.booked > 0 && !isPastTrip">

{{booking.traveller.dpName}}

                        <button class="button button-clear button-calm custom-button-calm" ng-click="showPassenger(booking)">
                            {{'lbl_show_profile' | translate}}
                        </button>

                    <button class="button button-carpooling" ng-if="booking.accepted === 0" ng-click="reject(booking, (isRecurrencyEnabled() && !!selectedTrip.recurrentId))">

                    </button>
                    <button class="button" ng-class="{'button-carpooling': booking.accepted === 0, 'button-carpooling-inverse': booking.accepted === 1}" ng-click="positiveAction(booking)">

                    </button>

            </ion-list>

 0 && !!isPastTrip">{{'lbl_passengers_accepted' | translate}}

            <ion-list ng-if="pass_accepted.length > 0 && !!isPastTrip">

{{booking.traveller.dpName}}

                        <button class="button button-clear button-calm custom-button-calm" ng-click="showPassenger(booking)">
                            {{'lbl_show_profile' | translate}}
                        </button>

                    <button class="button button-carpooling" ng-click="chat(booking)">

                    </button>
                    <button class="button button-carpooling" ng-click="rate(booking)">

                    </button>

            </ion-list>

 0 && !!isPastTrip">{{'lbl_passengers_not_accepted' | translate}}

            <ion-list ng-if="pass_not_accepted.length > 0 && !!isPastTrip">

{{booking.traveller.dpName}}

                        <button class="button button-clear button-calm custom-button-calm" ng-click="showPassenger(booking)">
                            {{'lbl_show_profile' | translate}}
                        </button>

                    <button class="button button-carpooling" ng-click="chat(booking)">

                    </button>

            </ion-list>

    </ion-content>
</ion-view>