text:
<?php

	namespace Bricks\Custom\Twentysteps\AlexaBrick\AlexaBundle\Joblet;

	use JMS\DiExtraBundle\Annotation as DI;

	use Bricks\Infrastructure\CoreBrick\CoreBundle\Joblet\AbstractJoblet;
	use Bricks\Infrastructure\CoreBrick\CoreBundle\Joblet\Joblet as JobletInterface;
	use Bricks\Infrastructure\CoreBrick\CoreBundle\Annotations\Joblet;

	use Bricks\Custom\Twentysteps\AlexaBrick\AlexaBundle\Shell\AlexaShell;

	/**
	 * @DI\Service("bricks_custom_twentysteps_alexa_joblet_push")
	 * @DI\Tag("monolog.logger", attributes = {"channel" = "bricks.custom.twentysteps_alexas.joblet.push"})
	 * @DI\Tag("twentysteps.bricks.joblet", attributes = {"alias" = "push"})
	 *
	 * @Joblet(
	 *		scope="project",
	 *      actor="alexa",
	 *      pods={"job"},
	 *		queue="bricks_custom_twentysteps_alexa_push",
	 *		priority="normal",
	 *		interval="PT1M"
	 * )
	 **/
	class PushJoblet extends AbstractJoblet implements JobletInterface {

		/**
		 * @DI\InjectParams({
		 *     "core" = @Di\Inject("core"),
		 *     "brickShell" = @Di\Inject("twentysteps_alexa"),
		 *     "logger" = @Di\Inject("logger"),
		 *     "stopwatch" = @Di\Inject("debug.stopwatch", required=false)
		 * })
		 */
		public function __construct($core, $brickShell, $logger, $stopwatch=null) {
			parent::__construct($core, $brickShell, $logger, $stopwatch);
		}

		public function run($jobId) {
			/** @var AlexaShell $shell */
			$shell = $this->getBrickShell();
			return array('status' => 'success','result' => $shell->getAlexaModule()->processPush());
		}

	}


text:
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  def index
    @products = Product.all
  end

  # GET /products/1
  def show
  end

  # GET /products/new
  def new
    @product = Product.new
  end

  # GET /products/1/edit
  def edit
  end

  # POST /products
  def create
    @product = Product.new(product_params)

    if @product.save
      redirect_to @product, notice: 'Product was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /products/1
  def update
    if @product.update(product_params)
      redirect_to @product, notice: 'Product was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /products/1
  def destroy
    @product.destroy
    redirect_to products_url, notice: 'Product was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def product_params
      params.require(:product).permit(:sku, :title, :price, :active, :description)
    end
end

redpajama_set_name: RedPajamaGithub


text:
import logging
from typing import Dict, Union

from .base import BaseNode
from ..sdo import SdoServer, SdoAbortedError
from ..pdo import PDO, TPDO, RPDO
from ..nmt import NmtSlave
from ..emcy import EmcyProducer
from .. import objectdictionary

logger = logging.getLogger(__name__)

class LocalNode(BaseNode):

    def __init__(
        self,
        node_id: int,
        object_dictionary: Union[objectdictionary.ObjectDictionary, str],
    ):
        super(LocalNode, self).__init__(node_id, object_dictionary)

        self.data_store: Dict[int, Dict[int, bytes]] = {}
        self._read_callbacks = []
        self._write_callbacks = []

        self.sdo = SdoServer(0x600 + self.id, 0x580 + self.id, self)
        self.tpdo = TPDO(self)
        self.rpdo = RPDO(self)
        self.pdo = PDO(self, self.rpdo, self.tpdo)
        self.nmt = NmtSlave(self.id, self)
        # Let self.nmt handle writes for 0x1017
        self.add_write_callback(self.nmt.on_write)
        self.emcy = EmcyProducer(0x80 + self.id)

    def associate_network(self, network):
        self.network = network
        self.sdo.network = network
        self.tpdo.network = network
        self.rpdo.network = network
        self.nmt.network = network
        self.emcy.network = network
        network.subscribe(self.sdo.rx_cobid, self.sdo.on_request)
        network.subscribe(0, self.nmt.on_command)

    def remove_network(self):
        self.network.unsubscribe(self.sdo.rx_cobid, self.sdo.on_request)
        self.network.unsubscribe(0, self.nmt.on_command)
        self.network = None
        self.sdo.network = None
        self.tpdo.network = None
        self.rpdo.network = None
        self.nmt.network = None
        self.emcy.network = None

    def add_read_callback(self, callback):
        self._read_callbacks.append(callback)

    def add_write_callback(self, callback):
        self._write_callbacks.append(callback)

    def get_data(
        self, index: int, subindex: int, check_readable: bool = False
    ) -> bytes:
        obj = self._find_object(index, subindex)

        if check_readable and not obj.readable:
            raise SdoAbortedError(0x06010001)

        # Try callback
        for callback in self._read_callbacks:
            result = callback(index=index, subindex=subindex, od=obj)
            if result is not None:
                return obj.encode_raw(result)

        # Try stored data
        try:
            return self.data_store[index][subindex]
        except KeyError:
            # Try ParameterValue in EDS
            if obj.value is not None:
                return obj.encode_raw(obj.value)
            # Try default value
            if obj.default is not None:
                return obj.encode_raw(obj.default)

        # Resource not available
        logger.info("Resource unavailable for 0x%X:%d", index, subindex)
        raise SdoAbortedError(0x060A0023)

    def set_data(
        self,
        index: int,
        subindex: int,
        data: bytes,
        check_writable: bool = False,
    ) -> None:
        obj = self._find_object(index, subindex)

        if check_writable and not obj.writable:
            raise SdoAbortedError(0x06010002)

        # Try callbacks
        for callback in self._write_callbacks:
            callback(index=index, subindex=subindex, od=obj, data=data)

        # Store data
        self.data_store.setdefault(index, {})
        self.data_store[index][subindex] = bytes(data)

    def _find_object(self, index, subindex):
        if index not in self.object_dictionary:
            # Index does not exist
            raise SdoAbortedError(0x06020000)
        obj = self.object_dictionary[index]
        if not isinstance(obj, objectdictionary.Variable):
            # Group or array
            if subindex not in obj:
                # Subindex does not exist
                raise SdoAbortedError(0x06090011)
            obj = obj[subindex]
        return obj


text:
'use strict'

const BPromise = require('bluebird')
const { expect } = require('chai')
const sinon = require('sinon')

const subject = require('../get-project').execute
require('../../../test/init-api')
const octopus = require('../../octopus-deploy')
const createProject = require('../../../test/mocks/project')

describe('commands/get-project', () => {
  const project = createProject()

  afterEach(() => {
    octopus.projects.find.restore()
  })

  describe('when the project has required dependencies', () => {
    it('returns the project', () => {
      sinon.stub(octopus.projects, 'find').callsFake(() => BPromise.resolve(project))

      return subject(project.id).then(actual => {
        expect(actual).to.eql(project)
        return expect(octopus.projects.find).to.be.calledWith(project.id)
      })
    })
  })

  describe('when the project is missing a variable set', () => {
    it('rejects with an error', () => {
      const invalidProject = Object.assign({}, project, { variableSetId: null })
      sinon.stub(octopus.projects, 'find').callsFake(() => BPromise.resolve(invalidProject))

      return subject(project.id).catch(err => {
        expect(err.message).to.be.eql(`VariableSetId is not set on project '${project.id}'`)
      })
    })
  })

  describe('when the project is missing a deployment process', () => {
    it('rejects with an error', () => {
      const invalidProject = Object.assign({}, project, { deploymentProcessId: null })
      sinon.stub(octopus.projects, 'find').callsFake(() => BPromise.resolve(invalidProject))

      return subject(project.id).catch(err => {
        expect(err.message).to.eql(`DeploymentProcessId is not set on project '${project.id}'`)
      })
    })
  })
})


text:
sleeptime=30

#Google DNS is a good choice for host and it's anycasted to
#a nearby server.  You may want to modify this though based
#on your location
host="8.8.8.8"

#How many pings are we going to send
number="20"

#How long are we going to wait between pings
#Keep in mind only superusers (root) can use a time
#value of 200ms or less!!
wait="0.25"

#Prepare to start the loop and warn the user
echo "Press [CTRL+C] to stop..."
while :
do

	#Lets ping the host!
	results=$(ping -c $number -i $wait -q $host)

	#We need to get ONLY lines 4 and 5 from the results
	#The rest isn't needed for ourpurposes
	counter=0
	while read -r line; do
		((counter++))
		if [ $counter = 4 ]
		then
			line4="$line"
		fi
		if [ $counter = 5 ]
		then
			line5="$line"
		fi
	done <<< "$results"

	echo "$line4"
	echo "$line5"

	#Parse out the 2 lines
	#First we need to get the packet loss
	IFS=',' read -ra arrline4 <<< "$line4" #Split the line based on a ,
	loss=${arrline4[2]} #Get just the 3rd element containing the loss
	IFS='%' read -ra lossnumber <<< "$loss" #Split the thrid element based on a %
	lossnumber=$(echo $lossnumber | xargs) #Remove the leading whitespace

	#Now lets get the min/avg/max/mdev
	IFS=' = ' read -ra arrline5 <<< "$line5" #Split the lines based on a =
	numbers=${arrline5[2]} #Get the right side containing the actual numbers
	IFS='/' read -ra numbersarray <<< "$numbers" #Break out all the numbers based on a /
	#Get the individual values from the array
	min=${numbersarray[0]}
	avg=${numbersarray[1]}
	max=${numbersarray[2]}
	mdev=${numbersarray[3]}

	#Write the data to the database
	curl -i -XPOST 'http://localhost:8086/write?db=home' --data-binary "ping,host=8.8.8.8,measurement=loss value=$lossnumber"
	curl -i -XPOST 'http://localhost:8086/write?db=home' --data-binary "ping,host=8.8.8.8,measurement=min value=$min"
	curl -i -XPOST 'http://localhost:8086/write?db=home' --data-binary "ping,host=8.8.8.8,measurement=avg value=$avg"
	curl -i -XPOST 'http://localhost:8086/write?db=home' --data-binary "ping,host=8.8.8.8,measurement=max value=$max"
	curl -i -XPOST 'http://localhost:8086/write?db=home' --data-binary "ping,host=8.8.8.8,measurement=mdev value=$mdev"

	#Wait for a bit before checking again
	sleep "$sleeptime"

done


text:
package com.inin.analytics.elasticsearch.index.routing;

import java.util.HashMap;
import java.util.Map;

import com.google.common.base.Preconditions;
import com.inin.analytics.elasticsearch.index.rotation.ElasticSearchIndexMetadata;
import com.inin.analytics.elasticsearch.util.MurmurHash;

/**
 * This routing strategy for elasticsearch. Read up on what routing does here
 * http://www.elasticsearch.org/blog/customizing-your-document-routing/
 *
 * Perhaps you have 10 shards per index and you don't wish to query every shard
 * every time you do a search against an org. A simple sharding strategy would
 * put all the data for 1 org on 1 shard using consistant hashing on orgId. However that
 * has the potential to hotspot some shards if an org with a lot of data comes
 * through.
 *
 * This attempts to alleviate that by making the # subset of shards configurable. EG
 * numShards = 10, numShardsPerOrg = 3, all of an org's data will be split to one of
 * 3 shards. Which one of the 3 is determined by hashing the conversationId.
 *
 * Note: DO NOT CHANGE THIS CLASS. It's immutable once it's been used to generate ES indexes
 * so changing it affects data routing and will make data appear unavailable b/c its looking
 * in the wrong shard. The correct thing to do is to make a newer version of this class,
 * say ElasticsearchRoutingStrategyV2 and see to it that the hadoop jobs to rebuild
 * the ES indexes not only use it, but update zookeeper with which implementation
 * indexes were built with. That way you can evolve the routing strategy without breaking
 * anything.
 *
 * @author drew
 *
 */
public class ElasticsearchRoutingStrategyV1 implements ElasticsearchRoutingStrategy, java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private int numShardsPerOrg;
	private int numShards;
	private Map<Integer, Integer> shardToRout = new HashMap<>();

	/**
	 * Adapted from DjbHashFunction & PlainOperationRouting in Elasticsearch. This is the default hashing
	 * Algorithm for doc routing. We need this to reverse engineer routing strings that rout to
	 * the shard we want.
	 *
	 * @param value
	 * @return
	 */
	public int hash(String value) {
		long hash = 5381;
		for (int i = 0; i < value.length(); i++) {
			hash = ((hash << 5) + hash) + value.charAt(i);
		}

		return Math.abs((int) hash % numShards);
	}

	public void init() {
		Integer x = 0;
		while(shardToRout.size() < numShards) {
			Integer hash = hash(x.toString());
			if(shardToRout.get(x) == null) {
				shardToRout.put(x, hash);
			}
			x++;
		}
	}

	public ElasticsearchRoutingStrategyV1() {

	}

	@Override
	public void configure(ElasticSearchIndexMetadata rotatedIndexMetadata) {
		Preconditions.checkNotNull(rotatedIndexMetadata.getNumShardsPerOrg(), "Num shards per org must not be null with " + this.getClass().getSimpleName());
		Preconditions.checkNotNull(rotatedIndexMetadata.getNumShards(), "Num shards must not be null with " + this.getClass().getSimpleName());
		this.numShardsPerOrg = rotatedIndexMetadata.getNumShardsPerOrg();
		this.numShards = rotatedIndexMetadata.getNumShards();
		init();
	}

	@Override
	public int getNumShardsPerOrg() {
		return numShardsPerOrg;
	}

	@Override
	public int getNumShards() {
		return numShards;
	}

	public Map<Integer, Integer> getShardToRout() {
		return shardToRout;
	}

	/**
	 * For an orgId & convId, get the shard routing for a document.
	 *
	 * Note: ES re-hashes routing values so shard 1 wont necessarily mean
	 * your data ends up in shard 1. However, if you realize that
	 * then you're in a bad place.
	 *
	 *
	 * @param orgId
	 * @param convId
	 * @param numShards
	 * @param numShardsPerOrg
	 * @return
	 */

	@Override
	public String getRoutingHash(String orgId, String convId) {
		Preconditions.checkArgument(numShards >= numShardsPerOrg, "Misconfigured, numShards must be >= numShardsPerOrg");
		int orgIdHash = getOrgIdHash(orgId, numShards);
		int convIdHash = Math.abs(MurmurHash.getInstance().hash(convId.getBytes(), 0)) % numShardsPerOrg;

		int shard = orgIdHash + convIdHash;
		while(shard >= numShards) {
			shard -= numShards;
		}

		return shardToRout.get(shard).toString();
	}

	/**
	 * When searching data for an Org, you may desire to only search the shards
	 * which hold data for that Org. This gives you a list of possible shard routings.
	 *
	 * @param orgId
	 * @param numShards
	 * @param numShardsPerOrg
	 * @return
	 */
	@Override
	public String[] getPossibleRoutingHashes(String orgId) {
		int orgIdHash = getOrgIdHash(orgId, numShards);
		String[] possibleShards = new String[numShardsPerOrg];
		for(int x = 0; x < numShardsPerOrg; x ++) {
			int shard = orgIdHash + x;
			while(shard >= numShards) {
				shard -= numShards;
			}
			possibleShards[x] = shardToRout.get(shard).toString();
		}
		return possibleShards;
	}

	private int getOrgIdHash(String orgId, int numShards) {
		return Math.abs(MurmurHash.getInstance().hash(orgId.getBytes(), 0)) % numShards;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + numShards;
		result = prime * result + numShardsPerOrg;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ElasticsearchRoutingStrategyV1 other = (ElasticsearchRoutingStrategyV1) obj;
		if (numShards != other.numShards)
			return false;
		if (numShardsPerOrg != other.numShardsPerOrg)
			return false;
		return true;
	}

    @Override
    public String toString() {
        return "ElasticsearchRoutingStrategyV1 [numShardsPerOrg=" + numShardsPerOrg + ", numShards=" + numShards
                + ", shardToRout=" + shardToRout + "]";
    }

}


text:
The top-level [win](configuration.md#Configuration-win) key contains set of options instructing electron-builder on how it should build Windows targets. These options applicable for any Windows target.

* target = `nsis` String | [TargetConfiguration](/configuration/target.md#targetconfiguration) - The target package type: list of `nsis`, `nsis-web` (Web installer), `portable` (portable app without installation), `appx`, `msi`, `squirrel`, `7z`, `zip`, `tar.xz`, `tar.lz`, `tar.gz`, `tar.bz2`, `dir`. AppX package can be built only on Windows 10.

  To use Squirrel.Windows please install `electron-builder-squirrel-windows` dependency.

  For `portable` app, `PORTABLE_EXECUTABLE_DIR` env is set (dir where portable executable located).
* icon = `build/icon.ico` String - The path to application icon.
* legalTrademarks String - The trademarks and registered trademarks.

---

* signingHashAlgorithms = `['sha1', 'sha256']` Array<"sha1" | "sha256"> - Array of signing algorithms used. For AppX `sha256` is always used.
* sign String | (configuration: CustomWindowsSignTaskConfiguration) => Promise - The custom function (or path to file or module id) to sign Windows executable.
* certificateFile String - The path to the *.pfx certificate you want to sign with. Please use it only if you cannot use env variable `CSC_LINK` (`WIN_CSC_LINK`) for some reason. Please see [Code Signing](../code-signing.md).
* certificatePassword String - The password to the certificate provided in `certificateFile`. Please use it only if you cannot use env variable `CSC_KEY_PASSWORD` (`WIN_CSC_KEY_PASSWORD`) for some reason. Please see [Code Signing](../code-signing.md).
* certificateSubjectName String - The name of the subject of the signing certificate. Required only for EV Code Signing and works only on Windows (or on macOS if [Parallels Desktop](https://www.parallels.com/products/desktop/) Windows 10 virtual machines exits).
* certificateSha1 String - The SHA1 hash of the signing certificate. The SHA1 hash is commonly specified when multiple certificates satisfy the criteria specified by the remaining switches. Works only on Windows (or on macOS if [Parallels Desktop](https://www.parallels.com/products/desktop/) Windows 10 virtual machines exits).
* additionalCertificateFile String - The path to an additional certificate file you want to add to the signature block.
* rfc3161TimeStampServer = `http://timestamp.comodoca.com/rfc3161` String - The URL of the RFC 3161 time stamp server.
* timeStampServer = `http://timestamp.verisign.com/scripts/timstamp.dll` String - The URL of the time stamp server.

---

* publisherName String | Array<String> - [The publisher name](https://github.com/electron-userland/electron-builder/issues/1187#issuecomment-278972073), exactly as in your code signed certificate. Several names can be provided. Defaults to common name from your code signing certificate.
* verifyUpdateCodeSignature = `true` Boolean - Whether to verify the signature of an available update before installation. The [publisher name](#publisherName) will be used for the signature verification.
* requestedExecutionLevel = `asInvoker` "asInvoker" | "highestAvailable" | "requireAdministrator" - The [security level](https://msdn.microsoft.com/en-us/library/6ad1fshk.aspx#Anchor_9) at which the application requests to be executed. Cannot be specified per target, allowed only in the `win`.

---

## Common Questions
#### How do delegate code signing?

Use [sign](#WindowsConfiguration-sign) option.

```json
"win": {
  "sign": "./customSign.js"
}
```

File `customSign.js` in the project root directory:
```js
exports.default = async function(configuration) {
  // your custom code
}
```

#### How do create Parallels Windows 10 Virtual Machine?

You don't need to have Windows 10 license. Free is provided (expire after 90 days, but it is not a problem because no additional setup is required).

1. Open Parallels Desktop.
2. File -> New.
3. Select "Modern.IE" in the "Free Systems".
4. Continue, Continue, Accept software license agreement.
5. Select "Microsoft Edge on Windows 10".
6. The next steps are general, see [Installing Windows on your Mac using Parallels Desktop](http://kb.parallels.com/4729) from "Step 6: Specify a name and location".

Parallels Windows 10 VM will be used automatically to build AppX on macOS. No need even start VM — it will be started automatically on demand and suspended after build. No need to specify VM — it will be detected automatically (first Windows 10 VM will be used).

#### How do create VirtualBox Windows 10 Virtual Machine?

If you are not on macOS or don't want to buy [Parallels Desktop](https://www.parallels.com/products/desktop/), you can use free [VirtualBox](https://www.virtualbox.org/wiki/Downloads).

1. Open [Download virtual machines](https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/).
2. Select "MSEdge on Win10 (x64) Stable".
3. Select "VirtualBox" platform.
4. Download. See [installation instructions](https://az792536.vo.msecnd.net/vms/release_notes_license_terms_8_1_15.pdf).

The password to your VM is `Passw0rd!`.

VirtualBox is not supported by electron-builder for now, so, you need to setup build environment on Windows if you want to use VirtualBox to build AppX (and other Windows-only tasks).


text:
export { mod, average, rand };

/* The % operator doesn't properly mod negative numbers. This does */
function mod(n, m) {
	return ((n % m) + m) % m;
}

/* Returns the average of the numbers in the array */
function average(arr) {
	let ret = 0;

	for (let i = 0, l = arr.length; i < l; i++)
		ret += arr[i];

	if (arr.length !== 0)
		ret /= arr.length;

	return ret;
}

/* Returns a random integer between min (included) and max (included) */
function rand(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}


text:
using System.ComponentModel;
using System.Runtime.Serialization;

namespace ChargeBee.Models.Enums
{
    public enum OperationEnum
    {

        [EnumMember(Value = "Unknown Enum")]
        UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
                dotnet-client version incompatibility. We suggest you to upgrade to the latest version */

        [EnumMember(Value = "create")]
         Create,

        [EnumMember(Value = "update")]
         Update,

        [EnumMember(Value = "delete")]
         Delete,

    }
}


text:
import Line = require('./line')
class Chapter{
    private _id: string;
    private _header: string;
    private _lines: Line[];

    constructor(header, paragraphs){
        this._header = header;
        this._lines = paragraphs;
    }

    get id(): string{
        return this._id;
    }

    set id(value){
        this._id = value;
    }

    get header(): string{
        return this._header;
    }

    set header(value){
        this._header = value;
    }

    get paragraphs(): Line[] {
        return this._lines;
    }

    set paragraphs(value){
        this._lines = value;
    }
}

export = Chapter;


text:
package com.orionplatform.math.function.fourvariables;

import com.orionplatform.core.abstraction.OrionService;
import com.orionplatform.math.function.FunctionRules;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.AddFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.AddValuesOfFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.DivideFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.GetSumOfSquaresOfFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.MultiplyFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.MultiplyValuesOfFunctions4x1Task;
import com.orionplatform.math.function.fourvariables.tasks.arithmetics.SubtractFunctions4x1Task;
import com.orionplatform.math.number.ANumber;
import com.orionplatform.math.number.precision.Precision;

public class Function4x1ArithmeticService extends OrionService
{
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getDouble(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).doubleGET());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getHalf(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).halfGET());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getSquare(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).squareGET());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    @SuppressWarnings({"unchecked"})
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getSumOfSquares(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber>... functions)
    {
        return GetSumOfSquaresOfFunctions4x1Task.run(functions);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getSquareRoot(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        return getSquareRoot(f, Precision.precision);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getSquareRoot(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, int precision)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> ((ANumber)f.run(x, y, z, w)).getSquareRoot(precision));
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getNthRoot(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, int n)
    {
        return getNthRoot(f, n, Precision.precision);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getNthRoot(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, int n, int precision)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> ((ANumber)f.run(x, y, z, w)).getNthRoot(n, precision));
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    @SuppressWarnings("unchecked")
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> add(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, ANumber x)
    {
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x1, y1, z1, w1) -> x);
        return add(f, Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func));
    }

    public static synchronized ANumber add(ANumber x, ANumber y, ANumber z, ANumber w, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber>[] functions)
    {
        return AddValuesOfFunctions4x1Task.run(x, y, z, w, functions);
    }

    @SuppressWarnings({"unchecked"})
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> add(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber>... functions)
    {
        return AddFunctions4x1Task.run(f, functions);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> subtract(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, ANumber x)
    {
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x1, y1, z1, w1) -> x);
        return subtract(f, Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func));
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> subtract(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> g)
    {
        return SubtractFunctions4x1Task.run(f, g);
    }

    @SuppressWarnings("unchecked")
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> multiply(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, ANumber x)
    {
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x1, y1, z1, w1) -> x);
        return multiply(f, Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func));
    }

    public static synchronized ANumber multiply(ANumber x, ANumber y, ANumber z, ANumber w, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber>[] functions)
    {
        return MultiplyValuesOfFunctions4x1Task.run(x, y, z, w, functions);
    }

    @SuppressWarnings({"unchecked"})
    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> multiply(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber>... functions)
    {
        return MultiplyFunctions4x1Task.run(f, functions);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> divide(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, ANumber x)
    {
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x1, y1, z1, w1) -> x);
        return divide(f, Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func));
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> divide(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> g)
    {
        return DivideFunctions4x1Task.run(f, g);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> negate(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).negateGET());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> reciprocate(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).reciprocateGET());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> exponentiate(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f, ANumber exponent)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).exponentiateGET(exponent));
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }

    public static synchronized Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> getAbsoluteValue(Function4x1<ANumber, ANumber, ANumber, ANumber, ANumber> f)
    {
        FunctionRules.isValid(f);
        Function4x1IF<ANumber, ANumber, ANumber, ANumber, ANumber> func = ((x, y, z, w) -> f.run(x, y, z, w).getAbsoluteValue());
        return Function4x1.<ANumber, ANumber, ANumber, ANumber, ANumber>of(func);
    }
}


text:
import PVMidi as M

M.process(force=True)


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

package com.google.api.ads.adwords.awreporting.server.kratu;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import com.google.api.ads.adwords.awreporting.model.entities.Report;
import com.google.api.ads.adwords.awreporting.model.entities.ReportAccount;
import com.google.api.ads.adwords.awreporting.model.entities.ReportAd;
import com.google.api.ads.adwords.awreporting.model.entities.ReportAdGroup;
import com.google.api.ads.adwords.awreporting.model.entities.ReportCampaign;
import com.google.api.ads.adwords.awreporting.model.entities.ReportKeyword;
import com.google.api.ads.adwords.awreporting.model.entities.ReportPlaceholderFeedItem;
import com.google.api.ads.adwords.awreporting.model.util.DateUtil;
import com.google.api.ads.adwords.awreporting.server.entities.Account;
import com.google.api.ads.adwords.awreporting.server.entities.Kratu;
import com.google.api.ads.adwords.awreporting.server.util.StorageHelper;
import com.google.api.client.util.Lists;
import com.google.common.collect.ImmutableList;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Test case for the {@code KratuCompute} class.
 *
 * @author jtoledo@google.com (Julian Toledo)
 */
public class KratuComputeTest {

  private static final RoundingMode ROUNDING = RoundingMode.HALF_UP;
  private static final int SCALE = 2;

  private final List<Kratu> dailyKratus = Lists.newArrayList();

  private final Calendar day1 = Calendar.getInstance();
  private final Calendar day1LastMinute = Calendar.getInstance();

  private final Calendar day2 = Calendar.getInstance();

  private Kratu kratu1;
  private Kratu kratu2;

  private Account account;

  @Mock
  private StorageHelper storageHelper;

  @Captor
  ArgumentCaptor<Class<? extends Report>> classReportCaptor;

  @Before
  public <R extends Report> void setUp() {

    day1.setTime(DateUtil.parseDateTime("20140601").toDate());
    day1.set(Calendar.HOUR_OF_DAY, 0);
    day1.set(Calendar.MINUTE, 0);
    day1.set(Calendar.SECOND, 0);

    day1LastMinute.setTime(DateUtil.parseDateTime("20140601").toDate());
    day1LastMinute.set(Calendar.HOUR_OF_DAY, 23);
    day1LastMinute.set(Calendar.MINUTE, 59);
    day1LastMinute.set(Calendar.SECOND, 59);

    day2.setTime(DateUtil.parseDateTime("20140602").toDate());
    day2.set(Calendar.HOUR_OF_DAY, 0);
    day2.set(Calendar.MINUTE, 0);
    day2.set(Calendar.SECOND, 0);

    account = new Account();
    account.setCurrencyCode("EUR");
    account.setDateTimeZone("Europe/Paris");
    account.setId("777");
    account.setName("Account1");

    kratu1 = new Kratu(123L, account, day1.getTime());
    kratu2 = new Kratu(123L, account, day2.getTime());
    kratu1.setAccountActive("Yes");
    kratu1.setAccountSuspended(false);
    kratu1.setAverageCpcDisplay(new BigDecimal(1L));
    kratu1.setAverageCpcSearch(new BigDecimal(2L));
    kratu1.setAverageCpmDisplay(new BigDecimal(3L));
    kratu1.setAverageCpmSearch(new BigDecimal(4L));
    kratu1.setAveragePositionDisplay(new BigDecimal(5L));
    kratu1.setAveragePositionSearch(new BigDecimal(6L));
    kratu1.setConversions(7L);
    kratu1.setCtrDisplay(new BigDecimal(8L));
    kratu1.setCtrSearch(new BigDecimal(9L));
    kratu1.setElegibleImpressionsDisplay(new BigDecimal(10L));
    kratu1.setElegibleImpressionsSearch(new BigDecimal(11L));
    kratu1.setImpressionsDisplay(12L);
    kratu1.setImpressionsSearch(13L);
    kratu1.setLostImpressionsDueToBidAdRankDisplay(new BigDecimal(14L));
    kratu1.setLostImpressionsDueToBidAdRankSearch(new BigDecimal(15L));
    kratu1.setLostImpressionsDueToBudgetDisplay(new BigDecimal(16L));
    kratu1.setLostImpressionsDueToBudgetSearch(new BigDecimal(17L));
    kratu1.setNumberOfActiveAdGroups(new BigDecimal(18L));
    kratu1.setNumberOfActiveAds(new BigDecimal(19L));
    kratu1.setNumberOfActiveAverageQualityScoreKeywords(new BigDecimal(20L));
    kratu1.setNumberOfActiveBroadMatchingKeywords(new BigDecimal(21L));
    kratu1.setNumberOfActiveCampaigns(new BigDecimal(22L));
    kratu1.setNumberOfActiveExactMatchingKeywords(new BigDecimal(23L));
    kratu1.setNumberOfActiveGoodQualityScoreKeywords(new BigDecimal(24L));
    kratu1.setNumberOfActivePhraseMatchingKeywords(new BigDecimal(25L));
    kratu1.setNumberOfActivePoorQualityScoreKeywords(new BigDecimal(26L));
    kratu1.setNumberOfAdGroupNegativeActiveKeywords(new BigDecimal(27L));
    kratu1.setNumberOfAdgroupsWithoneActiveAd(new BigDecimal(28L));
    kratu1.setNumberOfAdgroupsWithTwoActiveAds(new BigDecimal(29L));
    kratu1.setNumberOfCampaignNegativeActiveKeywords(new BigDecimal(30L));
    kratu1.setNumberOfCampaignsWithCallExtensionEnabled(new BigDecimal(31L));
    kratu1.setNumberOfCampaignsWithLocationExtensionEnabled(new BigDecimal(32L));
    kratu1.setNumberOfCampaignsWithSiteLinksEnabled(new BigDecimal(33L));
    kratu1.setNumberOfDisapprovedAds(new BigDecimal(34L));
    kratu1.setNumberOfNegativeActiveKeywords(new BigDecimal(35L));
    kratu1.setNumberOfPositiveActiveKeywords(new BigDecimal(36L));
    kratu1.setSpend(new BigDecimal(37L));
    kratu1.setSumBudget(new BigDecimal(38L));
    kratu1.setTotalClicksDisplay(39L);
    kratu1.setTotalClicksSearch(40L);
    kratu1.setWeightedAverageKeywordPosition(new BigDecimal(41L));
    kratu1.setWeightedAverageQualityScore(new BigDecimal(42L));

    kratu2.setAccountActive("Yes");
    kratu2.setAccountSuspended(false);
    kratu2.setAverageCpcDisplay(new BigDecimal(99.99));
    kratu2.setAverageCpcSearch(new BigDecimal(199.99));
    kratu2.setAverageCpmDisplay(new BigDecimal(299.99));
    kratu2.setAverageCpmSearch(new BigDecimal(399.99));
    kratu2.setAveragePositionDisplay(new BigDecimal(99.99));
    kratu2.setAveragePositionSearch(new BigDecimal(99.99));
    kratu2.setConversions(33L);
    kratu2.setCtrDisplay(new BigDecimal(99.99));
    kratu2.setCtrSearch(new BigDecimal(99.99));
    kratu2.setElegibleImpressionsDisplay(new BigDecimal(99.99));
    kratu2.setElegibleImpressionsSearch(new BigDecimal(99.99));
    kratu2.setImpressionsDisplay(3000L);
    kratu2.setImpressionsSearch(5000L);
    kratu2.setLostImpressionsDueToBidAdRankDisplay(new BigDecimal(99.99));
    kratu2.setLostImpressionsDueToBidAdRankSearch(new BigDecimal(99.99));
    kratu2.setLostImpressionsDueToBudgetDisplay(new BigDecimal(99.99));
    kratu2.setLostImpressionsDueToBudgetSearch(new BigDecimal(99.99));
    kratu2.setNumberOfActiveAdGroups(new BigDecimal(99.99));
    kratu2.setNumberOfActiveAds(new BigDecimal(99.99));
    kratu2.setNumberOfActiveAverageQualityScoreKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfActiveBroadMatchingKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfActiveCampaigns(new BigDecimal(99.99));
    kratu2.setNumberOfActiveExactMatchingKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfActiveGoodQualityScoreKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfActivePhraseMatchingKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfActivePoorQualityScoreKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfAdGroupNegativeActiveKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfAdgroupsWithoneActiveAd(new BigDecimal(99.99));
    kratu2.setNumberOfAdgroupsWithTwoActiveAds(new BigDecimal(99.99));
    kratu2.setNumberOfCampaignNegativeActiveKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfCampaignsWithCallExtensionEnabled(new BigDecimal(99.99));
    kratu2.setNumberOfCampaignsWithLocationExtensionEnabled(new BigDecimal(99.99));
    kratu2.setNumberOfCampaignsWithSiteLinksEnabled(new BigDecimal(99.99));
    kratu2.setNumberOfDisapprovedAds(new BigDecimal(99.99));
    kratu2.setNumberOfNegativeActiveKeywords(new BigDecimal(99.99));
    kratu2.setNumberOfPositiveActiveKeywords(new BigDecimal(99.99));
    kratu2.setSpend(new BigDecimal(99.99));
    kratu2.setSumBudget(new BigDecimal(99.99));
    kratu2.setTotalClicksDisplay(60L);
    kratu2.setTotalClicksSearch(888L);
    kratu2.setWeightedAverageKeywordPosition(new BigDecimal(99.99));
    kratu2.setWeightedAverageQualityScore(new BigDecimal(99.99));

    dailyKratus.add(kratu1);
    dailyKratus.add(kratu2);

    MockitoAnnotations.initMocks(this);

    Mockito.doAnswer(new Answer<List<? extends Report>>() {
      @Override
      public List<? extends Report> answer(InvocationOnMock invocation) throws Throwable {

        if (invocation.getArguments()[0].equals(ReportAccount.class)) {
          ReportAccount reportAccount =  new ReportAccount();
          reportAccount.setCost(new BigDecimal(9.99));
          reportAccount.setConvertedClicks(100L);
          return ImmutableList.of(reportAccount);
        } else {
          return Lists.newArrayList();
        }

      }
    }).when(storageHelper)
        .getReportByAccountId(Mockito.<Class<? extends Report>>anyObject(), Mockito.any(Long.class),Mockito.any(Date.class), Mockito.any(Date.class));

  }

  /*
   * Test for createKratuSummary
   */
  @Test
  public void test_createKratuSummary() {

    Kratu kratuSummarized = KratuCompute.createKratuSummary(dailyKratus, day1.getTime(), day2.getTime());

    // From Account
    assertEquals(kratuSummarized.getTopAccountId(), new Long(123));
    assertEquals(kratuSummarized.getAccountName(), "Account1");
    assertEquals(kratuSummarized.getExternalCustomerId(), new Long(777));
    assertEquals(kratuSummarized.getCurrencyCode(), "EUR");
    assertEquals(kratuSummarized.getDateTimeZone(), "Europe/Paris");
    assertEquals(kratuSummarized.getAccountSuspended(), false);

    // General
    assertEquals(kratuSummarized.getSpend(), kratu1.getSpend().add(kratu2.getSpend()).setScale(SCALE, ROUNDING));
    assertEquals(kratuSummarized.getSumBudget(), kratu1.getSumBudget().add(kratu2.getSumBudget()));
    assertEquals(kratuSummarized.getConversions(), new Long(kratu1.getConversions() + kratu2.getConversions()));
    assertEquals(kratuSummarized.getAccountActive(), "Yes");

    // Search Info
    assertEquals(kratuSummarized.getTotalClicksSearch(),
        new Long(kratu1.getTotalClicksSearch() + kratu2.getTotalClicksSearch()));

    assertEquals(kratuSummarized.getImpressionsSearch(),
        new Long(kratu1.getImpressionsSearch() + kratu2.getImpressionsSearch()));

    assertEquals(kratuSummarized.getElegibleImpressionsSearch(),
        kratu1.getElegibleImpressionsSearch().add(kratu2.getElegibleImpressionsSearch()));

    assertEquals(kratuSummarized.getLostImpressionsDueToBudgetSearch(),
        kratu1.getLostImpressionsDueToBudgetSearch().add(kratu2.getLostImpressionsDueToBudgetSearch()));

    assertEquals(kratuSummarized.getLostImpressionsDueToBidAdRankSearch(),
        kratu1.getLostImpressionsDueToBidAdRankSearch().add(kratu2.getLostImpressionsDueToBidAdRankSearch()));

    assertEquals(kratuSummarized.getCtrSearch(),
        dailyAverage(kratu1.getCtrSearch(), kratu2.getCtrSearch()));

    assertEquals(kratuSummarized.getAverageCpcSearch(),
        dailyAverage(kratu1.getAverageCpcSearch(), kratu2.getAverageCpcSearch()));

    assertEquals(kratuSummarized.getAverageCpmSearch(),
        dailyAverage(kratu1.getAverageCpmSearch(), kratu2.getAverageCpmSearch()));

    assertEquals(kratuSummarized.getAveragePositionSearch(),
        dailyAverage(kratu1.getAveragePositionSearch(), kratu2.getAveragePositionSearch()));

    // Display Info
    assertEquals(kratuSummarized.getTotalClicksDisplay(),
        new Long(kratu1.getTotalClicksDisplay() + kratu2.getTotalClicksDisplay()));

    assertEquals(kratuSummarized.getImpressionsDisplay(),
        new Long(kratu1.getImpressionsDisplay() + kratu2.getImpressionsDisplay()));

    assertEquals(kratuSummarized.getElegibleImpressionsDisplay(),
        kratu1.getElegibleImpressionsDisplay().add(kratu2.getElegibleImpressionsDisplay()));

    assertEquals(kratuSummarized.getLostImpressionsDueToBudgetDisplay(),
        kratu1.getLostImpressionsDueToBudgetDisplay().add(kratu2.getLostImpressionsDueToBudgetDisplay()));

    assertEquals(kratuSummarized.getLostImpressionsDueToBidAdRankDisplay(),
        kratu1.getLostImpressionsDueToBidAdRankDisplay().add(kratu2.getLostImpressionsDueToBidAdRankDisplay()));

    assertEquals(kratuSummarized.getCtrDisplay(),
        dailyAverage(kratu1.getCtrDisplay(), kratu2.getCtrDisplay()));

    assertEquals(kratuSummarized.getAverageCpcDisplay(),
        dailyAverage(kratu1.getAverageCpcDisplay(), kratu2.getAverageCpcDisplay()));

    assertEquals(kratuSummarized.getAverageCpmDisplay(),
        dailyAverage(kratu1.getAverageCpmDisplay(), kratu2.getAverageCpmDisplay()));

    assertEquals(kratuSummarized.getAveragePositionDisplay(),
        dailyAverage(kratu1.getAveragePositionDisplay(), kratu2.getAveragePositionDisplay()));

    // Structural Info
    assertEquals(kratuSummarized.getNumberOfActiveCampaigns(),
        dailyAverage(kratu1.getNumberOfActiveCampaigns(), kratu2.getNumberOfActiveCampaigns()));

    assertEquals(kratuSummarized.getNumberOfActiveAdGroups(),
        dailyAverage(kratu1.getNumberOfActiveAdGroups(), kratu2.getNumberOfActiveAdGroups()));

    assertEquals(kratuSummarized.getNumberOfActiveAds(),
        dailyAverage(kratu1.getNumberOfActiveAds(), kratu2.getNumberOfActiveAds()));

    assertEquals(kratuSummarized.getNumberOfPositiveActiveKeywords(),
        dailyAverage(kratu1.getNumberOfPositiveActiveKeywords(), kratu2.getNumberOfPositiveActiveKeywords()));

    assertEquals(kratuSummarized.getNumberOfActiveBroadMatchingKeywords(),
        dailyAverage(kratu1.getNumberOfActiveBroadMatchingKeywords(), kratu2.getNumberOfActiveBroadMatchingKeywords()));

    assertEquals(kratuSummarized.getNumberOfActivePhraseMatchingKeywords(),
        dailyAverage(kratu1.getNumberOfActivePhraseMatchingKeywords(), kratu2.getNumberOfActivePhraseMatchingKeywords()));

    assertEquals(kratuSummarized.getNumberOfAdGroupNegativeActiveKeywords(),
        dailyAverage(kratu1.getNumberOfAdGroupNegativeActiveKeywords(), kratu2.getNumberOfAdGroupNegativeActiveKeywords()));

    assertEquals(kratuSummarized.getNumberOfActiveGoodQualityScoreKeywords(),
        dailyAverage(kratu1.getNumberOfActiveGoodQualityScoreKeywords(), kratu2.getNumberOfActiveGoodQualityScoreKeywords()));

    assertEquals(kratuSummarized.getNumberOfActiveAverageQualityScoreKeywords(),
        dailyAverage(kratu1.getNumberOfActiveAverageQualityScoreKeywords(), kratu2.getNumberOfActiveAverageQualityScoreKeywords()));

    assertEquals(kratuSummarized.getNumberOfActivePoorQualityScoreKeywords(),
        dailyAverage(kratu1.getNumberOfActivePoorQualityScoreKeywords(), kratu2.getNumberOfActivePoorQualityScoreKeywords()));

    assertEquals(kratuSummarized.getNumberOfCampaignsWithCallExtensionEnabled(),
        dailyAverage(kratu1.getNumberOfCampaignsWithCallExtensionEnabled(), kratu2.getNumberOfCampaignsWithCallExtensionEnabled()));

    assertEquals(kratuSummarized.getNumberOfCampaignsWithLocationExtensionEnabled(),
        dailyAverage(kratu1.getNumberOfCampaignsWithLocationExtensionEnabled(), kratu2.getNumberOfCampaignsWithLocationExtensionEnabled()));

    assertEquals(kratuSummarized.getNumberOfCampaignsWithSiteLinksEnabled(),
        dailyAverage(kratu1.getNumberOfCampaignsWithSiteLinksEnabled(), kratu2.getNumberOfCampaignsWithSiteLinksEnabled()));

    assertEquals(kratuSummarized.getNumberOfAdgroupsWithoneActiveAd(),
        dailyAverage(kratu1.getNumberOfAdgroupsWithoneActiveAd(), kratu2.getNumberOfAdgroupsWithoneActiveAd()));

    assertEquals(kratuSummarized.getNumberOfAdgroupsWithTwoActiveAds(),
        dailyAverage(kratu1.getNumberOfAdgroupsWithTwoActiveAds(), kratu2.getNumberOfAdgroupsWithTwoActiveAds()));

    assertEquals(kratuSummarized.getNumberOfDisapprovedAds(),
        dailyAverage(kratu1.getNumberOfDisapprovedAds(), kratu2.getNumberOfDisapprovedAds()));

    assertEquals(kratuSummarized.getWeightedAverageKeywordPosition(),
        dailyAverage(kratu1.getWeightedAverageKeywordPosition(), kratu2.getWeightedAverageKeywordPosition()));

    assertEquals(kratuSummarized.getWeightedAverageQualityScore(),
        dailyAverage(kratu1.getWeightedAverageQualityScore(), kratu2.getWeightedAverageQualityScore()));
  }

  /*
   * Test for createDailyKratuFromDB
   */
  @Test
  public void test_createDailyKratuFromDB() {

    KratuCompute.createDailyKratuFromDB(storageHelper, 1L, account, day1.getTime());

    ArgumentCaptor<Long> accountIdCaptor = ArgumentCaptor.forClass(Long.class);
    ArgumentCaptor<Date> date1Captor = ArgumentCaptor.forClass(Date.class);
    ArgumentCaptor<Date> date2Captor = ArgumentCaptor.forClass(Date.class);

    verify(storageHelper, times(6)).getReportByAccountId(
        classReportCaptor.capture(), accountIdCaptor.capture(), date1Captor.capture(), date2Captor.capture());

    List<Class<? extends Report>> classes = classReportCaptor.getAllValues();
    assertEquals(classes.get(0), ReportAccount.class);
    assertEquals(classes.get(1), ReportCampaign.class);
    assertEquals(classes.get(2), ReportAdGroup.class);
    assertEquals(classes.get(3), ReportAd.class);
    assertEquals(classes.get(4), ReportKeyword.class);
    assertEquals(classes.get(5), ReportPlaceholderFeedItem.class);

    List<Long> accountIds = accountIdCaptor.getAllValues();
    assertEquals(accountIds.get(0), new Long(777));
    assertEquals(accountIds.get(1), new Long(777));
    assertEquals(accountIds.get(2), new Long(777));
    assertEquals(accountIds.get(3), new Long(777));
    assertEquals(accountIds.get(4), new Long(777));
    assertEquals(accountIds.get(5), new Long(777));

    List<Date> date1Captors = date1Captor.getAllValues();
    assertEquals(date1Captors.get(0), day1.getTime());
    assertEquals(date1Captors.get(1), day1.getTime());
    assertEquals(date1Captors.get(2), day1.getTime());
    assertEquals(date1Captors.get(3), day1.getTime());
    assertEquals(date1Captors.get(4), day1.getTime());
    assertEquals(date1Captors.get(5), day1.getTime());

    List<Date> date2Captors = date2Captor.getAllValues();
    assertEquals(date2Captors.get(0), day1LastMinute.getTime());
    assertEquals(date2Captors.get(1), day1LastMinute.getTime());
    assertEquals(date2Captors.get(2), day1LastMinute.getTime());
    assertEquals(date2Captors.get(3), day1LastMinute.getTime());
    assertEquals(date2Captors.get(4), day1LastMinute.getTime());
    assertEquals(date2Captors.get(5), day1LastMinute.getTime());
  }

  private BigDecimal dailyAverage(BigDecimal bigDecimal1, BigDecimal bigDecimal2) {
    BigDecimal daysInRange = new BigDecimal(2);
    return bigDecimal1.divide(daysInRange, SCALE, ROUNDING).add(bigDecimal2.divide(daysInRange, SCALE, ROUNDING));
  }
}


text:
'use strict';

(function() {

class MainController {

  constructor($http) {
    this.$http = $http;
    this.awesomeThings = [];

    $http.get('/api/things').then(response => {
      this.awesomeThings = response.data;
    });
  }

  addThing() {
    if (this.newThing) {
      this.$http.post('/api/things', { name: this.newThing });
      this.newThing = '';
    }
  }

  deleteThing(thing) {
    this.$http.delete('/api/things/' + thing._id);
  }
}

angular.module('meanStackWeatherDemoApp')
  .controller('MainController', MainController);

})();


text:
package pipeline

import (
	"io"

	"gopkg.in/vmihailenco/msgpack.v2"
)

type MsgPackDeserializer struct {
	constructor func() Emitter
	decoder     *msgpack.Decoder
	hasNext     bool
	lastError   error
}

func (m *MsgPackDeserializer) HasNext() bool {
	return m.hasNext
}

func (m *MsgPackDeserializer) Error() error {
	return m.lastError
}

func (m *MsgPackDeserializer) Next() Emitter {
	e := m.constructor()
	m.lastError = m.decoder.Decode(e)
	if m.lastError != nil {
		m.hasNext = false
	}
	return e
}

func NewMsgPackDeserializer(fn func() Emitter) DeserializerFunc {

	return func(r io.Reader) Deserializer {

		// Create a new decoder
		decoder := msgpack.NewDecoder(r)

		return &MsgPackDeserializer{
			constructor: fn,
			decoder:     decoder,
			hasNext:     true,
			lastError:   nil,
		}

	}

}


text:
'use strict';

export default function (fn) {
    if (typeof window !== 'undefined' && !('requestAnimationFrame' in window)) {
        return fn;
    }

    let id = null;

    return (...args) => {
        if (id !== null) {
            cancelAnimationFrame(id);
        }

        id = requestAnimationFrame(() => {
            fn(...args);
            id = null;
        });
    };
}


text:
/**
 * nagTriagr, free and open source forever
 * https://github.com/mirokuratczyk/nagTriagr
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

import React, {
  AppRegistry,
  NavigatorIOS,
  ActivityIndicatorIOS,
  Component,
  TouchableHighlight,
  Image,
  ListView,
  StyleSheet,
  Text,
  TextInput,
  View,
  AlertIOS
} from 'react-native';

var UsernameBar = require('UsernameBar');
var PasswordBar = require('PasswordBar');
var ServernameBar = require('ServernameBar');
var t = require('tcomb-form-native');
var base64 = require('base-64');
var Accordion = require('react-native-accordion');

var HTTP_HEALTH_URL = '/nagios/cgi-bin/statusjson.cgi?query=servicelist&details=true&dateformat=%25T'
var Form = t.form.Form;
const SERVICE_CRITICAL = 16;
const SERVICE_UNKNOWN = 8;
const SERVICE_OK = 2;

var Servername = t.refinement(t.String, function (n) {
  /* stub for check later */
  return true;
});

var LoginInfo = t.struct({
  server: Servername,
  username: t.String,
  password: t.String,
  /*rememberMe: t.Boolean // to implement */
});

var options = {
  fields: {
    server: {
      autoCorrect: false,
      autoCapitalize: "none",
      placeholder: "example.com",
      label: "Server",
      error: "Expecting format https://x.y or http://x.y or example.com"
    },
    username: {
      autoCorrect: false,
      autoCapitalize: "none",
      placeholder: "username",
      label: "Username"
    },
    password: {
      password: true,
      secureTextEntry: true,
      placeholder: 'password',
      label: 'Password',
    },
  }
};

class nagTriagr extends Component {
  constructor(props) {
      super(props);
      this.renderStatusPage = this.renderStatusPage.bind(this);
      this.fetchNagiosData = this.fetchNagiosData.bind(this);
      this.returnToAuthScreen = this.returnToAuthScreen.bind(this);
      this.login = this.login.bind(this);

      this.state = {
        nagiosListData: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2,
        sectionHeaderHasChanged : (s1, s2) => s1 !== s2}),
        nagiosData: {},
        loaded: false,
        isLoading: true,
        username: "",
        password: "",
        serverUrl: "",
        authSubmitted: false,
        statusLoaded: false,
      };
  }

  componentDidMount() {
    this.setState({loaded:true, isLoading:false});
  }

  onPress() {
    // call getValue() to get the values of the form
    var value = this.refs.form.getValue();
    if (value) { // if validation fails, value will be null
      console.log(value); // value here is an instance of Person
      this.setState({
        username: value.username,
        password: value.password,
        serverUrl: value.server,
      });
      this.login();
    }
  }

  onChange(value) {
    /*stub*/
  }

  onInputChange(event) {
    /*stub*/
  }

  render() {
    if(!this.state.loaded) { // check if authed
      return this.renderLoadingView();
    }

    if (!this.state.authSubmitted) {
      return this.renderAuthScreen();
    } else if (this.state.authSubmitted && this.state.statusLoaded) {
      return this.renderStatusPage(this.state.nagiosData.localhost);
    } else if (this.state.authSubmitted && this.state.statusLoaded==false) {
      return this.renderLoadingView();
    }
  }

  login() {
    console.log("Attemping login with " + this.state.username + this.state.password + this.state.serverUrl);
    if (this.state.username && this.state.password && this.state.serverUrl) {
      this.setState({authSubmitted: true});
      this.fetchNagiosData();
      console.log("Username,password and servername submitted, ready to fetch data from server");
    }
  }

  /* invalidate auth. information */
  returnToAuthScreen() {
    this.setState({
        username:"",
        password:"",
        serverUrl:"",
        statusLoaded:false,
        authSubmitted: false,
    });
  }

  renderLoadingView() {
    return (
      <View style={styles.loadingContainer}>
        <Text>
          Loading...
        </Text>
      </View>
    );
  }

  renderAuthScreen() {
    return (
      <View style={styles.mainContainer}>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarTitle}>nagTriagr</Text>
        </View>
        <View style={styles.container}>
          {/* display */}
          <Form
            ref="form"
            type={LoginInfo}
            options={options}
            value={this.props.value}
            onChange={this.props.onChange}
          />
          <TouchableHighlight style={styles.button} onPress={this.onPress.bind(this)} underlayColor='#99d9f4'>
            <Text style={styles.buttonText}>Login</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  renderStatusPage(host) {
    return (
      <View style={styles.mainContainer}>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton} onPress={this.fetchNagiosData}>refresh</Text>
          <Text style={styles.toolbarTitle}>nagiosTriagr</Text>
          <Text style={styles.toolbarButton} onPress={this.returnToAuthScreen}>new</Text>
        </View>
        <View style={styles.content}>
          <ListView
            dataSource={this.state.nagiosListData}
            renderSectionHeader={this.renderHostName.bind(this)}
            renderRow={this.renderHost}
            style={styles.listView}
          />
          <Text>
            Last snapshot at {this.state.nagiosData.result.query_time}
          </Text>
        </View>
      </View>
    );
  }

  renderHostName(host,hostname) {
    if (hostname == "localhost") {
      hostname = this.state.serverUrl;
    }
    return (
      <Text style={styles.hostName}>{hostname}</Text>
    );
  }

  iPress() {
    console.log("PRESSED");
  }

  renderHost(host) {
    var rows = [];
    var status = "OK";
    var styleSheet = styles.pluginOutputOK;

    if (host.status == SERVICE_CRITICAL) {
      console.warn(host.host_name + ": " + host.description + " is critical.")
      status = "CRITICAL";
      styleSheet = styles.pluginOutputCRITICAL;
    } else if (host.status == SERVICE_UNKNOWN) {
      console.warn(host.host_name + ": " + host.description + " is unknown.")
      status = "UNKNOWN";
    }

    rows.push(<Text key={host.description} style={styleSheet}>{host.description}</Text>);
    rows.push(<Text key={host.status} style={styleSheet}>{status}</Text>);
    var content = (
      <View>
        <Text style={styles.pluginOutput}>{host.plugin_output}</Text>
      </View>
    );

    var header = (
      <View style={styles.rightContainer}>
        {rows}
      </View>
    );

    return (
      <Accordion
        header={header}
        content={content}
        easing="easeOutCubic"
      />
    );
  }

  fetchNagiosData() {
    console.log("Fetching data");
    /* probably should sanitize input here */
    var url = "";
    if (this.state.serverUrl.match("http://") || this.state.serverUrl.match("https://")) {
      url = this.state.serverUrl + HTTP_HEALTH_URL;
    } else {
      url = "https://" + this.state.serverUrl + HTTP_HEALTH_URL;
    }

    console.log("Attempting connection with " + url);
    fetch(url, {
      method:'GET',
      headers: {
        'Authorization':'Basic '+base64.encode(this.state.username+":"+this.state.password),
      },
    })
      .then((response) => response.json()) //.text
      .then((responseData)=> {
        console.log(responseData.data.servicelist);
        this.setState({
            nagiosListData: this.state.nagiosListData.cloneWithRowsAndSections(responseData.data.servicelist),
            nagiosData: responseData,
            statusLoaded:true,
        });
      }) //.done
      .catch((error) => {
        console.warn("Could not connect to server, please try again");
        this.setState({
          statusLoaded: false,
          authSubmitted: false,
        })
      });
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    backgroundColor: '#F5FCFF',
    flex: 1,
  },
  content:{
    backgroundColor: '#F5FCFF',
    alignItems: 'stretch',
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  rightContainer: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#e6f7ff',
  },
  listView: {
    backgroundColor: '#F5FCFF',
  },
  toolbar:{
    backgroundColor:'#81c04d',
    paddingTop:30,
    paddingBottom:10,
    flexDirection:'row'
  },
  toolbarButton:{
    width: 50,
    color:'#fff',
    textAlign:'center'
  },
  toolbarTitle:{
    color:'#fff',
    textAlign:'center',
    fontWeight:'bold',
    flex:1
  },
  container: {
    justifyContent: 'center',
    marginTop: 50,
    padding: 20,
  },
  pluginOutput: {
    textAlign: 'left',
    backgroundColor: '#ccffff',
    fontSize: 14,
    flex: 1,
    paddingLeft: 8,
  },
  pluginOutputOK: {
    fontSize: 8,
    borderColor: 'black',
    borderWidth: 0.5,
    textAlign: 'left',
    backgroundColor: '#00e600',
    fontSize: 14,
    flex: 1,
    paddingLeft: 8,
  },
  pluginOutputCRITICAL: {
    fontSize: 8,
    borderColor: 'black',
    borderWidth: 0.5,
    textAlign: 'left',
    backgroundColor: '#ff9933',
    fontSize: 14,
    flex: 1,
    paddingLeft: 8,
  },
  hostName: {
    height: 36,
    borderColor: 'black',
    borderWidth: 0.5,
    paddingTop: 8,
    backgroundColor: '#48BBEC',
    fontSize: 18,
    color: 'white',
    textAlign: 'center',
    textDecorationStyle: 'solid',
    letterSpacing: 2,
    textShadowColor: 'black',
    flex:1,
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

AppRegistry.registerComponent('nagTriagr', () => nagTriagr);


text:
#ifndef MEDIA_ENGINE_VP8_ENCODER_SIMULCAST_PROXY_H_
#define MEDIA_ENGINE_VP8_ENCODER_SIMULCAST_PROXY_H_

#include <memory>
#include <vector>

#include BOSS_WEBRTC_U_api__video_codecs__sdp_video_format_h //original-code:"api/video_codecs/sdp_video_format.h"
#include BOSS_WEBRTC_U_api__video_codecs__video_encoder_factory_h //original-code:"api/video_codecs/video_encoder_factory.h"
#include BOSS_WEBRTC_U_modules__video_coding__codecs__vp8__include__vp8_h //original-code:"modules/video_coding/codecs/vp8/include/vp8.h"

namespace webrtc {

// This class provides fallback to SimulcastEncoderAdapter if default VP8Encoder
// doesn't support simulcast for provided settings.
class VP8EncoderSimulcastProxy : public VP8Encoder {
 public:
  VP8EncoderSimulcastProxy(VideoEncoderFactory* factory,
                           const SdpVideoFormat& format);
  // Deprecated. Remove once all clients use constructor with both factory and
  // SdpVideoFormat;
  explicit VP8EncoderSimulcastProxy(VideoEncoderFactory* factory);

  ~VP8EncoderSimulcastProxy() override;

  // Implements VideoEncoder.
  int Release() override;
  int InitEncode(const VideoCodec* inst,
                 int number_of_cores,
                 size_t max_payload_size) override;
  int Encode(const VideoFrame& input_image,
             const CodecSpecificInfo* codec_specific_info,
             const std::vector<FrameType>* frame_types) override;
  int RegisterEncodeCompleteCallback(EncodedImageCallback* callback) override;
  int SetChannelParameters(uint32_t packet_loss, int64_t rtt) override;
  int SetRateAllocation(const VideoBitrateAllocation& bitrate,
                        uint32_t new_framerate) override;

  VideoEncoder::ScalingSettings GetScalingSettings() const override;

  bool SupportsNativeHandle() const override;
  const char* ImplementationName() const override;

 private:
  VideoEncoderFactory* const factory_;
  SdpVideoFormat video_format_;
  std::unique_ptr<VideoEncoder> encoder_;
  EncodedImageCallback* callback_;
};

}  // namespace webrtc

#endif  // MEDIA_ENGINE_VP8_ENCODER_SIMULCAST_PROXY_H_


text:
@if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild" set msbuildpath=%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin
@if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild" set msbuildpath=%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin
@if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild" set msbuildpath=%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin

nuget.exe restore %~dp0\..\src\IoT.sln
REM dotnet restore %~dp0\..\src

"%msbuildpath%\msbuild" %~dp0\..\src\Iot.Admin.Application\Iot.Admin.Application.sfproj /t:Package /p:Platform=x64
"%msbuildpath%\msbuild" %~dp0\..\src\Iot.Ingestion.Application\Iot.Ingestion.Application.sfproj /t:Package /p:Platform=x64
"%msbuildpath%\msbuild" %~dp0\..\src\Iot.Tenant.Application\Iot.Tenant.Application.sfproj /t:Package /p:Platform=x64


text:
<?php

namespace Crate\DBAL\Driver\PDOCrate;

use Crate\DBAL\Platforms\CratePlatform1;
use Crate\DBAL\Platforms\CratePlatform;
use Crate\DBAL\Platforms\CratePlatform4;
use Crate\DBAL\Schema\CrateSchemaManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\VersionAwarePlatformDriver;

class Driver implements \Doctrine\DBAL\Driver, VersionAwarePlatformDriver
{
    const VERSION = '3.0.0';
    const NAME = 'crate';

    private const VERSION_057 = '0.57.0';
    private const VERSION_4 = '4.0.0';

    /**
     * {@inheritDoc}
     * @return PDOConnection The database connection.
     */
    public function connect(array $params, $username = null, $password = null, array $driverOptions = array())
    {
        return new PDOConnection($this->constructPdoDsn($params), $username, $password, $driverOptions);
    }

    /**
     * Constructs the Crate PDO DSN.
     *
     * @return string The DSN.
     */
    private function constructPdoDsn(array $params)
    {
        $dsn = self::NAME . ':';
        if (isset($params['host']) && $params['host'] != '') {
            $dsn .= $params['host'];
        } else {
            $dsn .= 'localhost';
        }
        $dsn .= ':' . (isset($params['port']) ? $params['port'] : '4200');

        return $dsn;
    }

    /**
     * {@inheritDoc}
     */
    public function getDatabasePlatform()
    {
        return new CratePlatform();
    }

    /**
     * {@inheritDoc}
     */
    public function getSchemaManager(Connection $conn)
    {
        return new CrateSchemaManager($conn);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return self::NAME;
    }

    /**
     * {@inheritDoc}
     */
    public function getDatabase(Connection $conn)
    {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public function createDatabasePlatformForVersion($version)
    {
        if (version_compare($version, self::VERSION_057, "<")) {
            return new CratePlatform();
        } elseif (version_compare($version, self::VERSION_4, "<")) {
            return new CratePlatform1();
        } else {
            return new CratePlatform4();
        }
    }
}


text:
Suppose your website http(s)://foo.com (note: "foo.com" can be "localhost") is running PHP. Here is how you use SVAuth:

* Create a directory or a virtual directory on foo.com called ```/SVAuth```;
* Unzip the zip file of the "SVAuth-adapter" zip file into a folder;
* Open ```adapter_config/adapter_config.json```. You will see the following:
```
{
  "WebAppSettings": {
    "hostname": "localhost",
    "scheme": "http",
    "port": "80",
    "platform": {
      "name": "php"
    }
  },

  "AgentSettings": {
    "scheme": "https",
    "port": "3020",
    "agentScope": "*",
    "agentHostname": "authjs.westus.cloudapp.azure.com"
  }
}
```
* Modify the ```WebAppSettings``` section to match your website platform;
* Copy the ```adapters``` folder into the ```/SVAuth``` directory on your website;
* Visit http(s)://foo.com/SVAuth/adapters/php/AllInOne.php, you should see [**a page like this**](http://authjs.westus.cloudapp.azure.com/SVAuth/adapters/php/AllInOne.php), and should be able to click on the buttons to sign in.

## Integrate with your web application

* If your PHP page ```x.php``` wants to initiate a ```Facebook``` login, it simply redirects the browser to http(s)://foo.com/SVAuth/adapters/php/start.php?provider=```Facebook```;
* SVAuth will set the user data into the following session variables in your session. Your application code takes the data from there. That's it.
```
Session["SVAuth_UserID"]=436436434635643
Session["SVAuth_FullName"]=John Doe
Session["SVAuth_Email"]=johndoe@abcd.com
Session["SVAuth_Authority"]=Facebook.com
```

#### Other web languages and SSO services
In this README description, "php" can be replaced by the following:
```php```,```aspx```.

"Facebook" can be replaced by ```Facebook```, ```Microsoft```, ```MicrosoftAzureAD```, ```Google```, ```Yahoo```, ```LinkedIn```, ```Weibo```.

#### Customize the landing URL

By default, SVAuth will redirect the browser back to ```x.php``` when the login is done. If you want the user to land on a different page ```y.php```, ```x.php``` should set the "LandingUrl" cookie to be the full URL of ```y.php```. This can be implemented in PHP as follows:
```
setcookie("LandingUrl", "http(s)://foo.com/y.php", 0 ,"/");
```


text:
#ifndef SkColorFilterShader_DEFINED
#define SkColorFilterShader_DEFINED

#include "src/core/SkColorFilterBase.h"
#include "src/shaders/SkShaderBase.h"

class SkArenaAlloc;

class SkColorFilterShader : public SkShaderBase {
public:
    SkColorFilterShader(sk_sp<SkShader> shader, float alpha, sk_sp<SkColorFilter> filter);

#if SK_SUPPORT_GPU
    std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const override;
#endif

private:
    bool isOpaque() const override;
    void flatten(SkWriteBuffer&) const override;
    bool onAppendStages(const SkStageRec&) const override;

    skvm::Color onProgram(skvm::Builder*, skvm::Coord device, skvm::Coord local, skvm::Color paint,
                          const SkMatrixProvider&, const SkMatrix* localM, const SkColorInfo& dst,
                          skvm::Uniforms* uniforms, SkArenaAlloc*) const override;

    SK_FLATTENABLE_HOOKS(SkColorFilterShader)

    sk_sp<SkShader>          fShader;
    sk_sp<SkColorFilterBase> fFilter;
    float                    fAlpha;

    using INHERITED = SkShaderBase;
};

#endif


text:
"use strict";

function Configuration () {
}

function getEnv (name, defaultValue) {
	name = name.toUpperCase();

	return name in process.env ? process.env[name] : defaultValue;
}

Configuration.prototype.database = {
	url : getEnv.bind(
		null,
		"influxdb_url",
		"http://localhost:8086/db/lurker/series?u=lurker&p=test"
	)
};

Configuration.prototype.github = {
	client : {
		id     : getEnv.bind(null, "github_client_id", null),
		secret : getEnv.bind(null, "github_client_secret", null)
	},

	organization : getEnv.bind(null, "github_organization", null),
	secret       : getEnv.bind(null, "github_secret", null)
};

Configuration.prototype.server = {
	hostname : getEnv.bind(null, "host", null),
	secret   : getEnv.bind(null, "cookie_password", null),
	url      : getEnv.bind(null, "base_url", null),

	port     : function () {
		return Number(getEnv("port", 0));
	}
};

module.exports = Configuration;


text:
describe('makeSelectToolsSortOptionsDomain', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});


text:
@interface STKEventsNavigationController ()

@end

@implementation STKEventsNavigationController

- (UIViewController *)childViewControllerForStatusBarHidden {
    return self.topViewController;
}

- (UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

@end


text:
package kubeyaml

import (
	"bytes"
	"strings"
)

const (
	yamlSeparator = "---\n"
)

// Split the given yaml doc if it's multipart document.
func Split(yamlText []byte) [][]byte {
	parts := bytes.Split(yamlText, []byte(yamlSeparator))
	var result [][]byte
	for _, p := range parts {
		if len(p) != 0 {
			result = append(result, p)
		}
	}
	return result
}

// SplitString splits the given yaml doc if it's multipart document.
func SplitString(yamlText string) []string {
	parts := strings.Split(yamlText, yamlSeparator)
	var result []string
	for _, p := range parts {
		if len(p) != 0 {
			result = append(result, p)
		}
	}
	return result
}

// Join the given yaml parts into a single multipart document.
func Join(parts ...[]byte) []byte {
	var b bytes.Buffer

	var lastIsNewLine bool
	for _, p := range parts {
		if len(p) == 0 {
			continue
		}
		if b.Len() != 0 {
			if !lastIsNewLine {
				_, _ = b.WriteString("\n")
			}
			b.WriteString(yamlSeparator)
		}
		_, _ = b.Write(p)
		s := string(p)
		lastIsNewLine = s[len(s)-1] == '\n'
	}

	return b.Bytes()
}

// JoinString joins the given yaml parts into a single multipart document.
func JoinString(parts ...string) string {
	var st strings.Builder

	var lastIsNewLine bool
	for _, p := range parts {
		if len(p) == 0 {
			continue
		}
		if st.Len() != 0 {
			if !lastIsNewLine {
				_, _ = st.WriteString("\n")
			}
			st.WriteString(yamlSeparator)
		}
		_, _ = st.WriteString(p)
		lastIsNewLine = p[len(p)-1] == '\n'
	}

	return st.String()
}


text:
module Spree
  class Order < Spree::Base
    module StoreCredit
      def add_store_credit_payments
        payments.store_credits.where(state: 'checkout').map(&:invalidate!)

        remaining_total = outstanding_balance

        if user && user.store_credits.any?
          payment_method = Spree::PaymentMethod::StoreCredit.available.first
          raise "Store credit payment method could not be found" unless payment_method

          user.store_credits.order_by_priority.each do |credit|
            break if remaining_total.zero?
            next if credit.amount_remaining.zero?

            amount_to_take = store_credit_amount(credit, remaining_total)
            create_store_credit_payment(payment_method, credit, amount_to_take)
            remaining_total -= amount_to_take
          end
        end
      end

      def covered_by_store_credit?
        return false unless user
        user.total_available_store_credit >= total
      end
      alias_method :covered_by_store_credit, :covered_by_store_credit?

      def total_available_store_credit
        return 0.0 unless user
        user.total_available_store_credit
      end

      def could_use_store_credit?
        total_available_store_credit > 0
      end

      def order_total_after_store_credit
        total - total_applicable_store_credit
      end

      def total_applicable_store_credit
        if payment? || confirm? || complete?
          total_applied_store_credit
        else
          [total, (user.try(:total_available_store_credit) || 0.0)].min
        end
      end

      def total_applied_store_credit
        payments.store_credits.valid.sum(:amount)
      end

      def using_store_credit?
        total_applied_store_credit > 0
      end

      def display_total_applicable_store_credit
        Spree::Money.new(-total_applicable_store_credit, currency: currency)
      end

      def display_total_applied_store_credit
        Spree::Money.new(-total_applied_store_credit, currency: currency)
      end

      def display_order_total_after_store_credit
        Spree::Money.new(order_total_after_store_credit, currency: currency)
      end

      def display_total_available_store_credit
        Spree::Money.new(total_available_store_credit, currency: currency)
      end

      def display_store_credit_remaining_after_capture
        Spree::Money.new(total_available_store_credit - total_applicable_store_credit, currency: currency)
      end

      private

      def create_store_credit_payment(payment_method, credit, amount)
        payments.create!(
          source: credit,
          payment_method: payment_method,
          amount: amount,
          state: 'checkout',
          response_code: credit.generate_authorization_code
        )
      end

      def store_credit_amount(credit, total)
        [credit.amount_remaining, total].min
      end
    end
  end
end


text:
Tutorial
--------

For loops are very similar to for loops in C, They are defined like this:

    for( [variable to count iterations] ; [conditions checked for] ; [code to execute every loop])
    {

    }

E.G:

    int i;

    for( i = 0; i < 10; i++)
    {

    }

This would loop until i is no longer less than ten, increasing i by one each time.
However unlike C, C# does allow you to declare the variable you are using as to count iterations in the for loop:

    for( int i = 0; i < 10; i++)

For loops are used to allow you to repeat sections of code a fixed, or variable amount of times.
This allows you to make your code more compact and clean.

There are several statements you can use to control a loop:

    break;

This allows you to exit a loop without finishing the loop.

E.G

    for(int i = 0; i < 16; i++)
    {

        if(i == 12)
        {
            break;
        }
    }

Exit the loop when i is 12, not when the loop would usually finish

    continue;

This allows you to skip straight to the next iteration

    for(int i = 0; i < 16; i++)
    {

        if(i % 2 == 1)
        {
            continue;
        }

        Console.WriteLine(i);

    }

Print only the even numbers by skipping the interations where i is odd.

Exercise
--------

Print the value of variable X to the screen N number of times

Tutorial Code
-------------

    using System;

    public class Functions
    {
        public static void Main()
        {
            string x = "Hi";
            int n = 10;

            // write for loop here
        }

    }

Expected Output
---------------

    Hi
    Hi
    Hi
    Hi
    Hi
    Hi
    Hi
    Hi
    Hi
    Hi

Solution
--------

    using System;

    public class Functions
    {
        public static void Main()
        {
            string x = "Hi";
            int n = 10;

            for( int i = 0; i < n; i++)
            {
                Console.WriteLine(x);
            }
        }

    }


text:
package main

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"strings"
)

var domainFlag = flag.String("radio_domain", "http://ws.radiothermostat.com", "Don't include the path component")
var port = flag.String("port", ":8080", "The port the proxy should listen on.")

var reverseProxy *httputil.ReverseProxy

type LoggedResponseWriter struct {
	http.ResponseWriter
}

func (w LoggedResponseWriter) WriteHeader(status int) {
	log.Println("responded:", status, w.Header())
	w.ResponseWriter.WriteHeader(status)
}

func (w LoggedResponseWriter) Write(msg []byte) (int, error) {
	log.Printf("response[%d]: %s\n", len(msg), hex.EncodeToString(msg))
	return w.ResponseWriter.Write(msg)
}

type CT_post struct {
	Uuid      string `json:"uuid"`
	FormatVer string `json:"format_ver"`
	EIV       string `json:"eiv"`
}

type Chain struct {
	Cause error
	msg   string
}

func (c *Chain) Error() string {
	return fmt.Sprintf("%s caused by %q", c.msg, c.Cause)
}

func NewChain(msg string, cause error) *Chain {
	return &Chain{cause, msg}
}

func req_printer(req *http.Request) error {
	dump, err := httputil.DumpRequest(req, true)

	if err != nil {
		return NewChain("unable to read request", err)
	}

	i := bytes.IndexByte(dump, byte('}')) + 1
	if i <= 0 {
		return errors.New("unable to find end of json")
	}

	english := string(dump[:i])
	payload := dump[i:]
	log.Println("request:\n", english)
	log.Printf("Payload[%d]: %s\n", len(payload), hex.EncodeToString(payload))

	j := strings.Index(english, "{")
	if j < 0 {
		return errors.New("unable to find start of json")
	}

	json_payload := dump[j:i]

	post := &CT_post{}
	err = json.Unmarshal(json_payload, post)
	if err != nil {
		return NewChain("bad json", err)
	}

	log.Printf("json payload: %s", string(json_payload))
	log.Printf("EIV: %q", post.EIV)
	return nil
}

func handler(rw http.ResponseWriter, req *http.Request) {

	err := req_printer(req)
	if err != nil {
		log.Print(err)
	}

	w := LoggedResponseWriter{rw}
	reverseProxy.ServeHTTP(w, req)
}

func main() {
	url, err := url.ParseRequestURI(*domainFlag)
	if err != nil {
		log.Fatalf("failed to parse url '%s': %s", *domainFlag, err)
	}
	reverseProxy = httputil.NewSingleHostReverseProxy(url)

	http.HandleFunc("/", handler)
	log.Println("Start serving on port", *port)
	http.ListenAndServe(*port, nil)
	os.Exit(0)
}


text:
@interface OCMBlockCaller : NSObject
{
	void (^block)(NSInvocation *);
}

- (id)initWithCallBlock:(void (^)(NSInvocation *))theBlock;

- (void)handleInvocation:(NSInvocation *)anInvocation;

@end

#endif


text:
PersianDatePicker
=========

An Android DatePicker for Persian Calendar

![ScreenShot](http://smartlab.ir/wp-content/uploads/2014/09/android-persian-date-picker-guide-output.png)
![ScreenShot](http://smartlab.ir/wp-content/uploads/2014/09/android-persian-date-picker-guide-output-with-month-names.png)

Usage:
---

  - Add as an Android Library Project:
   - Add this line to root layout element:

xmlns:persianDatePicker="http://schemas.android.com/apk/res-auto"

   - Add PersianDatePicker view:

<ir.smartlab.persindatepicker.PersianDatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

  - Add Source and other required things to your Project:
   - Copy all sources to your source tree.
   - Copy /res/layout/sl_persian_date_picker.xml to your /res/layout folder.
   - Add this to your /res/values/attrs.xml:

<declare-styleable name="PersianDatePicker">
        <attr name="minYear" format="integer" />
        <attr name="maxYear" format="integer" />
        <attr name="selectedYear" format="integer" />
        <attr name="selectedMonth" format="integer" />
        <attr name="selectedDay" format="integer" />
        <attr name="displayMonthNames" format="boolean" />
        <attr name="yearRange" format="integer" />
    </declare-styleable>

Params:
---
 - minYear: Min value for year in the picker. Default is current Hijri Shamsi (Jalali) year - yearRange(default is 10).
 - maxYear: Max value for year in the picker. Default is current Hijri Shamsi (Jalali) year + yearRange(default is 10).
 - yearRange: If you set a selected year, available years in picker will be from (selectedYear - yearRange) to (selectedYear + yearRange). Default value is 10.
 - selectedYear: Selected year that PersianDatePicker starts with. Default is the current Hijri Shamsi (Jalali) year.
 - selectedMonth: Selected month that PersianDatePicker starts with. Default is the current Hijri Shamsi (Jalali) year's month.
 - selectedDay: Selected day of month that PersianDatePicker starts with. Default is the current Hijri Shamsi (Jalali) month's day.
 - displayMonthNames: If set to true, months names are displayed, otherwise their number will be shown.
 - displayDescription: If set to true, a TextView below datepicker will show the selected date with more details.

Examples:
---
   - Display a PersianDatePicker with current Hijri Shamsi (Jalali) values:

<ir.smartlab.persindatepicker.PersianDatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

   - Display a PersianDatePicker with selected Hijri Shamsi (Jalali) date:

<ir.smartlab.persindatepicker.PersianDatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:selectedYear="1390"
        app:selectedMonth="5"
        app:selectedDay="15" />

   - Display a PersianDatePicker that shows month names:

<ir.smartlab.persindatepicker.PersianDatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:displayMonthNames="true" />

   - Display a PersianDatePicker that shows years between 1350 and 1450:

<ir.smartlab.persindatepicker.PersianDatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:maxYear="1450"
        app:minYear="1350" />

Java Examples:
---
- You can set a java.util.Date object to PersianDatePpicker in java code:

persianDatePicker.setDisplayDate(new Date());

- you can also set a ir.smartlab.persindatepicker.util.PersianCalendar object:

PersianCalendar persianCalendar = new PersianCalendar();
persianCalendar.setPersianDate(1393, 6, 28);
persianDatePicker.setDisplayPersianDate(persianCalendar);

- You can get displayed date in java.util.Date or ir.smartlab.persindatepicker.util.PersianCalendar:

Date d = persianDatePicker.getDisplayDate();
// OR
PersianCalendar pCal = persianDatePicker.getDisplayPersianDate();

Leap Year:
---
In Hijri Shamsi some years are leap year, so the last month of year is 30 days (not 29 days). PersianDatePicker take cares of leap years. This means that users will never pick a wrong date.

To Do:
---
* Support Persian digits as an option
* Support typeface settings

Credits:
---
PersianDatepicker is heavily based on AOSP (https://source.android.com) and persian-calendar (https://github.com/mortezaadi/persian-calendar).

Version
----
1.0

License
----
Apache License Version 2.0


text:
module Capistrano
  module Nodeenv
    VERSION = "0.0.5"
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.puppycrawl.tools.checkstyle.checks.metrics (checkstyle 5.6 API)</title>
<meta name="date" content="2012-09-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.puppycrawl.tools.checkstyle.checks.metrics

Contains the Metrics checks that are
 bundled with the main distribution.

See: Description

Class Summary

Class
Description

AbstractClassCouplingCheck

Base class for coupling calculation.

AbstractComplexityCheck

Base class for checks the calculate complexity based around methods.

BooleanExpressionComplexityCheck

Restricts nested boolean operators (&&, ||, &, | and ^) to
 a specified depth (default = 3).

ClassDataAbstractionCouplingCheck

This metric measures the number of instantiations of other classes
 within the given class.

ClassFanOutComplexityCheck

The number of other classes a given class relies on.

CyclomaticComplexityCheck

Checks cyclomatic complexity against a specified limit.

JavaNCSSCheck

This check calculates the Non Commenting Source Statements (NCSS) metric for
 java source files and methods.

NPathComplexityCheck

Checks the npath complexity against a specified limit (default = 200).

Package com.puppycrawl.tools.checkstyle.checks.metrics Description

Contains the Metrics checks that are
 bundled with the main distribution.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2001-2012. All Rights Reserved.


text:
@interface FeRippleButton : UIButton
// Ripple Over Bound
@property (assign, nonatomic) BOOL rippleOverBound;

// Ripple Color
@property (strong, nonatomic) UIColor *rippleColor;

// Ripple Background Color
@property (strong, nonatomic) UIColor *rippleBackgroundColor;

// Shadow Radius
@property (assign, nonatomic) CGFloat shadowRippleRadius;

// Enable
@property (assign, nonatomic) BOOL shadowRippleEnable;

// TrackTouch
@property (assign, nonatomic) BOOL trackTouchLocation;

-(id) initWithFrame:(CGRect)frame;
@end


text:
class CreatePars < ActiveRecord::Migration[5.0]
  def change
    Tournament.all.each do |t|
      Par.create(tournament: t)
    end
  end
end


text:
$(function () {
	window.near_me = false;
	$('#form1').on('submit', function (e) {
		//stop page refresh
		e.preventDefault();
		var inputs = $('#form1 :input');
		var values = {};

		inputs.each(function() {
			values[this.name] = $(this).val();
		});

		var keyword = values['food-type'];
		var searchBusinessArray = {};
		var businessDetails = {};
		var dublin = new google.maps.LatLng(53.350140,-6.266155);

		var map = new google.maps.Map(document.getElementById('google-map-results'), {
			center: dublin,
			zoom: 15
		});

		var request = {
			location: dublin,
			radius: '500',
			query: 'restaurant'
		};

		var service = new google.maps.places.PlacesService(map);
		service.textSearch(request, callback);

		function callback(results, status) {
			searchBusinessArray = results;
			var randomPlaceId = results[Math.floor(Math.random()*results.length)]['place_id'];
			var placeRequest = { placeId: randomPlaceId };
			service.getDetails(placeRequest, getDetails);
		}

		function getDetails(results, status) {
			var randomPlace = results;
			businessDetails = {
				'name': randomPlace['name'] || '',
				'opening_hours': randomPlace['opening_hours']['weekday_text'] || '',
				'rating': randomPlace['rating'] || '',
				'map_url': randomPlace['url'] || '',
				'address': randomPlace['formatted_address'] || '',
				'phone': randomPlace['formatted_phone_number'] || '',
				'website': randomPlace['website'] || ''
			}

			document.getElementById("search-business-name").innerHTML = businessDetails['name'];
			document.getElementById("search-food-type").innerHTML = keyword;
			document.getElementById("search-address").innerHTML = businessDetails['address'];
			document.getElementById("search-phone").innerHTML = businessDetails['phone'];
			document.getElementById("search-website").innerHTML = businessDetails['website'];
			$("#search-website").attr("href", businessDetails['website']);
			$("#search-map").attr("src", businessDetails['map_url']+'&ie=UTF8&output=embed');
			document.getElementById("search-rating").innerHTML = businessDetails['rating'];
			document.getElementById("search-opening-hours").innerHTML = businessDetails['opening_hours'];
			$('#portfolioModalSearch').modal('toggle');
		}
	});
	//When user clicks "near me" this brings them to food type thumbnails and sets their location in the background using showPosition()
	$('.choice1 a').click(function(e) {
		document.getElementById('load').style.visibility="visible";
		window.near_me = true;
		navigator.geolocation.getCurrentPosition(showPosition);
		$('html, body').animate({
		        scrollTop: $('#food-thumbnails').offset().top
		}, 2500);

		function showPosition(position) {
			window.lat = position.coords.latitude;
			window.long = position.coords.longitude;
			document.getElementById('load').style.visibility="hidden";
			console.log(position.coords.latitude, position.coords.longitude);
		}
	});
	$(".choice2").click(function(event) {
	    $('.choice2').html("<input type='text' id='test' placeholder='Enter Location' onclick='initialize()' />");
	    $('#test').focus();
	    event.stopPropagation();
	});
	$('.choice3 a').click(function(e) {
		$('html, body').animate({
		        scrollTop: $('#food-thumbnails').offset().top
		}, 2500);
	});
	$('.food-type-thumbnail').click(function (e) {
		e.preventDefault();
		var type = $(this).data('type');
		var href = $(this).attr('href');

		//if user chooses "near me"
		if (window.near_me === true) {
			//gets user's location
			var loc = new google.maps.LatLng(window.lat,window.long);
			// var loc = new google.maps.LatLng(53.3980234,-6.2352455);
			var area = new google.maps.Map(document.getElementById('google-map-results'), {
				center: loc,
				zoom: 15
			});
			var req = {
				location: loc,
				radius: '1000',
				type: 'restaurant',
				keyword: type
			};
			var serv = new google.maps.places.PlacesService(area);
			//GOOGLE API QUERY based on req outlined above
			window.check = 0;
			serv.nearbySearch(req, callback);

			//function that results are passed through from api query
			function callback(results, status) {
				//if restaurants in db are in their area
				if (status != 'ZERO_RESULTS') {
					//grabs a random reference id from the results of google api call
					var randomId = results[Math.floor(Math.random()*results.length)]['id'];
					var id = randomId;

					$.ajax({
						//Sends food type and id in real time to Restaurants model using config.php file
				     	url: 'index.php/near_ajax/'+type+'/'+id,
				     	context: this,
				     	success: function(data)
				    	{
				    		//Restaurants model returns the database info for that reference id

				    		var restaurant = JSON.parse(data);
				    		if (restaurant.length == 0) {
				    			console.log('undefined');
				    			window.check++;
				    			window.check < 5 ? serv.nearbySearch(req, callback) : alert("Oops, we don't have any "+type+" restaurants near you! Try again!");
				    		} else {
				    			var reference = restaurant['slug'];
				    			//build the dynamic url with the restaurant slug
				    			var goTo = href + '/' + reference;
				    			//go to that restaurant landing page
								window.location = goTo;
				    		}
				     	},
				     	error: function(jqXHR, exception)
				     	{
				     		console.log('oops, nothing near you');
				     	}
				    });
				    return false;
				} else {
					//no restaurants from db are in their area
					alert("Oops, we don't have any restaurants near you! Try again!");
					//remove the near me setting and return results from anywhere if they click again
					window.near_me = false;
				}
			}
		} else {
			//if user chooses anywhere
			$.ajax({
				//Sends ONLY food type in real time to Restaurants model using config.php file
		     	url: 'index.php/test_ajax/'+type,
		     	context: this,
		     	success: function(data)
		    	{
		    		//returns db data for a restaurant related to that food type
		    		var restaurant = JSON.parse(data);
		    		var reference = restaurant['slug'];
					var goTo = href + '/' + reference;
					window.location = goTo;
		     	},
		     	error: function(jqXHR, exception)
		     	{
		     		console.log('oops, nothing near you');
		     	}
		    });
		}

	});
	//sets which navbar tab is active
	$('.header-button').click(function(e) {
		$('.header-button').removeClass('active');
	    $(this).addClass('active');
	});
	$(window).scroll(function() {
		//checks if user scroll is near the top
		//if so it removes white background from navbar
		//hides navbar background when the user arrives on page so map can be seen in full
		if ($(window).scrollTop() < 10) {
			$('.navbar .navbar-collapse').removeClass('white');
			$('.header-button').removeClass('blue');
			$('#navbar-logo').attr('src', document.location.origin+'/assets/img/logo/wsiewhite.png');
		} else {
			//puts in white background for navbar as user scrolls down
			$('.navbar .navbar-collapse').addClass('white');
			$('.header-button').addClass('blue');
			$('#navbar-logo').attr('src', document.location.origin+'/assets/img/logo/wsieblue.png');
		}
    });
});