text:
#include "dm-cache-policy.h"
#include "dm.h"

#include <linux/hash.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>

/*----------------------------------------------------------------*/

#define DM_MSG_PREFIX "cache cleaner"

/* Cache entry struct. */
struct wb_cache_entry {
	struct list_head list;
	struct hlist_node hlist;

	dm_oblock_t oblock;
	dm_cblock_t cblock;
	bool dirty:1;
	bool pending:1;
};

struct hash {
	struct hlist_head *table;
	dm_block_t hash_bits;
	unsigned nr_buckets;
};

struct policy {
	struct dm_cache_policy policy;
	spinlock_t lock;

	struct list_head free;
	struct list_head clean;
	struct list_head clean_pending;
	struct list_head dirty;

	/*
	 * We know exactly how many cblocks will be needed,
	 * so we can allocate them up front.
	 */
	dm_cblock_t cache_size, nr_cblocks_allocated;
	struct wb_cache_entry *cblocks;
	struct hash chash;
};

/*----------------------------------------------------------------------------*/

/*
 * Low-level functions.
 */
static unsigned next_power(unsigned n, unsigned min)
{
	return roundup_pow_of_two(max(n, min));
}

static struct policy *to_policy(struct dm_cache_policy *p)
{
	return container_of(p, struct policy, policy);
}

static struct list_head *list_pop(struct list_head *q)
{
	struct list_head *r = q->next;

	list_del(r);

	return r;
}

/*----------------------------------------------------------------------------*/

/* Allocate/free various resources. */
static int alloc_hash(struct hash *hash, unsigned elts)
{
	hash->nr_buckets = next_power(elts >> 4, 16);
	hash->hash_bits = ffs(hash->nr_buckets) - 1;
	hash->table = vzalloc(sizeof(*hash->table) * hash->nr_buckets);

	return hash->table ? 0 : -ENOMEM;
}

static void free_hash(struct hash *hash)
{
	vfree(hash->table);
}

static int alloc_cache_blocks_with_hash(struct policy *p, dm_cblock_t cache_size)
{
	int r = -ENOMEM;

	p->cblocks = vzalloc(sizeof(*p->cblocks) * from_cblock(cache_size));
	if (p->cblocks) {
		unsigned u = from_cblock(cache_size);

		while (u--)
			list_add(&p->cblocks[u].list, &p->free);

		p->nr_cblocks_allocated = 0;

		/* Cache entries hash. */
		r = alloc_hash(&p->chash, from_cblock(cache_size));
		if (r)
			vfree(p->cblocks);
	}

	return r;
}

static void free_cache_blocks_and_hash(struct policy *p)
{
	free_hash(&p->chash);
	vfree(p->cblocks);
}

static struct wb_cache_entry *alloc_cache_entry(struct policy *p)
{
	struct wb_cache_entry *e;

	BUG_ON(from_cblock(p->nr_cblocks_allocated) >= from_cblock(p->cache_size));

	e = list_entry(list_pop(&p->free), struct wb_cache_entry, list);
	p->nr_cblocks_allocated = to_cblock(from_cblock(p->nr_cblocks_allocated) + 1);

	return e;
}

/*----------------------------------------------------------------------------*/

/* Hash functions (lookup, insert, remove). */
static struct wb_cache_entry *lookup_cache_entry(struct policy *p, dm_oblock_t oblock)
{
	struct hash *hash = &p->chash;
	unsigned h = hash_64(from_oblock(oblock), hash->hash_bits);
	struct wb_cache_entry *cur;
	struct hlist_head *bucket = &hash->table[h];

	hlist_for_each_entry(cur, bucket, hlist) {
		if (cur->oblock == oblock) {
			/* Move upfront bucket for faster access. */
			hlist_del(&cur->hlist);
			hlist_add_head(&cur->hlist, bucket);
			return cur;
		}
	}

	return NULL;
}

static void insert_cache_hash_entry(struct policy *p, struct wb_cache_entry *e)
{
	unsigned h = hash_64(from_oblock(e->oblock), p->chash.hash_bits);

	hlist_add_head(&e->hlist, &p->chash.table[h]);
}

static void remove_cache_hash_entry(struct wb_cache_entry *e)
{
	hlist_del(&e->hlist);
}

/* Public interface (see dm-cache-policy.h */
static int wb_map(struct dm_cache_policy *pe, dm_oblock_t oblock,
		  bool can_block, bool can_migrate, bool discarded_oblock,
		  struct bio *bio, struct policy_result *result)
{
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;
	unsigned long flags;

	result->op = POLICY_MISS;

	if (can_block)
		spin_lock_irqsave(&p->lock, flags);

	else if (!spin_trylock_irqsave(&p->lock, flags))
		return -EWOULDBLOCK;

	e = lookup_cache_entry(p, oblock);
	if (e) {
		result->op = POLICY_HIT;
		result->cblock = e->cblock;

	}

	spin_unlock_irqrestore(&p->lock, flags);

	return 0;
}

static int wb_lookup(struct dm_cache_policy *pe, dm_oblock_t oblock, dm_cblock_t *cblock)
{
	int r;
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;
	unsigned long flags;

	if (!spin_trylock_irqsave(&p->lock, flags))
		return -EWOULDBLOCK;

	e = lookup_cache_entry(p, oblock);
	if (e) {
		*cblock = e->cblock;
		r = 0;

	} else
		r = -ENOENT;

	spin_unlock_irqrestore(&p->lock, flags);

	return r;
}

static void __set_clear_dirty(struct dm_cache_policy *pe, dm_oblock_t oblock, bool set)
{
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;

	e = lookup_cache_entry(p, oblock);
	BUG_ON(!e);

	if (set) {
		if (!e->dirty) {
			e->dirty = true;
			list_move(&e->list, &p->dirty);
		}

	} else {
		if (e->dirty) {
			e->pending = false;
			e->dirty = false;
			list_move(&e->list, &p->clean);
		}
	}
}

static void wb_set_dirty(struct dm_cache_policy *pe, dm_oblock_t oblock)
{
	struct policy *p = to_policy(pe);
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);
	__set_clear_dirty(pe, oblock, true);
	spin_unlock_irqrestore(&p->lock, flags);
}

static void wb_clear_dirty(struct dm_cache_policy *pe, dm_oblock_t oblock)
{
	struct policy *p = to_policy(pe);
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);
	__set_clear_dirty(pe, oblock, false);
	spin_unlock_irqrestore(&p->lock, flags);
}

static void add_cache_entry(struct policy *p, struct wb_cache_entry *e)
{
	insert_cache_hash_entry(p, e);
	if (e->dirty)
		list_add(&e->list, &p->dirty);
	else
		list_add(&e->list, &p->clean);
}

static int wb_load_mapping(struct dm_cache_policy *pe,
			   dm_oblock_t oblock, dm_cblock_t cblock,
			   uint32_t hint, bool hint_valid)
{
	int r;
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e = alloc_cache_entry(p);

	if (e) {
		e->cblock = cblock;
		e->oblock = oblock;
		e->dirty = false; /* blocks default to clean */
		add_cache_entry(p, e);
		r = 0;

	} else
		r = -ENOMEM;

	return r;
}

static void wb_destroy(struct dm_cache_policy *pe)
{
	struct policy *p = to_policy(pe);

	free_cache_blocks_and_hash(p);
	kfree(p);
}

static struct wb_cache_entry *__wb_force_remove_mapping(struct policy *p, dm_oblock_t oblock)
{
	struct wb_cache_entry *r = lookup_cache_entry(p, oblock);

	BUG_ON(!r);

	remove_cache_hash_entry(r);
	list_del(&r->list);

	return r;
}

static void wb_remove_mapping(struct dm_cache_policy *pe, dm_oblock_t oblock)
{
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);
	e = __wb_force_remove_mapping(p, oblock);
	list_add_tail(&e->list, &p->free);
	BUG_ON(!from_cblock(p->nr_cblocks_allocated));
	p->nr_cblocks_allocated = to_cblock(from_cblock(p->nr_cblocks_allocated) - 1);
	spin_unlock_irqrestore(&p->lock, flags);
}

static void wb_force_mapping(struct dm_cache_policy *pe,
				dm_oblock_t current_oblock, dm_oblock_t oblock)
{
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);
	e = __wb_force_remove_mapping(p, current_oblock);
	e->oblock = oblock;
	add_cache_entry(p, e);
	spin_unlock_irqrestore(&p->lock, flags);
}

static struct wb_cache_entry *get_next_dirty_entry(struct policy *p)
{
	struct list_head *l;
	struct wb_cache_entry *r;

	if (list_empty(&p->dirty))
		return NULL;

	l = list_pop(&p->dirty);
	r = container_of(l, struct wb_cache_entry, list);
	list_add(l, &p->clean_pending);

	return r;
}

static int wb_writeback_work(struct dm_cache_policy *pe,
			     dm_oblock_t *oblock,
			     dm_cblock_t *cblock)
{
	int r = -ENOENT;
	struct policy *p = to_policy(pe);
	struct wb_cache_entry *e;
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);

	e = get_next_dirty_entry(p);
	if (e) {
		*oblock = e->oblock;
		*cblock = e->cblock;
		r = 0;
	}

	spin_unlock_irqrestore(&p->lock, flags);

	return r;
}

static dm_cblock_t wb_residency(struct dm_cache_policy *pe)
{
	return to_policy(pe)->nr_cblocks_allocated;
}

/* Init the policy plugin interface function pointers. */
static void init_policy_functions(struct policy *p)
{
	p->policy.destroy = wb_destroy;
	p->policy.map = wb_map;
	p->policy.lookup = wb_lookup;
	p->policy.set_dirty = wb_set_dirty;
	p->policy.clear_dirty = wb_clear_dirty;
	p->policy.load_mapping = wb_load_mapping;
	p->policy.walk_mappings = NULL;
	p->policy.remove_mapping = wb_remove_mapping;
	p->policy.writeback_work = wb_writeback_work;
	p->policy.force_mapping = wb_force_mapping;
	p->policy.residency = wb_residency;
	p->policy.tick = NULL;
}

static struct dm_cache_policy *wb_create(dm_cblock_t cache_size,
					 sector_t origin_size,
					 sector_t cache_block_size)
{
	int r;
	struct policy *p = kzalloc(sizeof(*p), GFP_KERNEL);

	if (!p)
		return NULL;

	init_policy_functions(p);
	INIT_LIST_HEAD(&p->free);
	INIT_LIST_HEAD(&p->clean);
	INIT_LIST_HEAD(&p->clean_pending);
	INIT_LIST_HEAD(&p->dirty);

	p->cache_size = cache_size;
	spin_lock_init(&p->lock);

	/* Allocate cache entry structs and add them to free list. */
	r = alloc_cache_blocks_with_hash(p, cache_size);
	if (!r)
		return &p->policy;

	kfree(p);

	return NULL;
}
/*----------------------------------------------------------------------------*/

static struct dm_cache_policy_type wb_policy_type = {
	.name = "cleaner",
	.version = {1, 0, 0},
	.hint_size = 0,
	.owner = THIS_MODULE,
	.create = wb_create
};

static int __init wb_init(void)
{
	int r = dm_cache_policy_register(&wb_policy_type);

	if (r < 0)
		DMERR("register failed %d", r);
	else
		DMINFO("version %u.%u.%u loaded",
		       wb_policy_type.version[0],
		       wb_policy_type.version[1],
		       wb_policy_type.version[2]);

	return r;
}

static void __exit wb_exit(void)
{
	dm_cache_policy_unregister(&wb_policy_type);
}

module_init(wb_init);
module_exit(wb_exit);

MODULE_AUTHOR("Heinz Mauelshagen <dm-devel@redhat.com>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("cleaner cache policy");


text:
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder";
import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer";
import { PokerCommandHeader } from "../../core/data/PokerCommandHeader";
import { SrvEnableIncrementalTourAwardingCommand } from "../commands/SrvEnableIncrementalTourAwardingCommand";

export class SrvEnableIncrementalTourAwardingCommandSerializer {
	public static serialize(buffer: ArrayBufferBuilder, command: SrvEnableIncrementalTourAwardingCommand ): void {
		buffer.pointer += PokerCommandHeader.HEADER_SIZE_BYTES;

		PokerCommandHeaderSerializer.serialize(buffer, command.header);
	}

	public static deserialize(buffer: ArrayBufferBuilder, command: SrvEnableIncrementalTourAwardingCommand ): void {
		PokerCommandHeaderSerializer.deserialize(buffer, command.header);

	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

  Copyright 2003 - 2015 The eFaps Team

  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.

  Author:          The eFaps Team
  Revision:        $Rev: 6511 $
  Last Changed:    $Date: 2011-05-11 16:52:44 -0500 (Wed, 11 May 2011) $
  Last Changed By: $Author: jan@moxter.net $

-->
<ui-form xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>7af40c0b-20bb-4af2-9bab-5eeee6c9e32b</uuid>
    <file-application>eFapsApp-TimeReport</file-application>
    <file-revision>$Rev: 6511 $</file-revision>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>TimeReport_EmployeeTimeCardCreate4ProjectForm</name>
        <field character="Group" name="dategroup">
            <property name="GroupCount">2</property>
            <property name="ModeCreate">READONLY</property>
        </field>
        <field name="date">
            <property name="Columns">12</property>
            <property name="ModeCreate">EDITABLE</property>
            <property name="ModeEdit">EDITABLE</property>
            <property name="ModeSearch">EDITABLE</property>
            <property name="Attribute">Date</property>
            <property name="Required">true</property>
            <trigger program="org.efaps.esjp.common.uiform.Field"
                method="getDefault4DateFieldValue"
                name="TimeReport_EmployeeTimeCardCreate4ProjectForm.date.UI_FIELD_VALUE"
                event="UI_FIELD_VALUE">
                <property name="withDayOfMonth">1</property>
            </trigger>
        </field>
        <field name="dueDate">
            <property name="Columns">12</property>
            <property name="ModeCreate">EDITABLE</property>
            <property name="ModeEdit">EDITABLE</property>
            <property name="ModeSearch">EDITABLE</property>
            <property name="Attribute">DueDate</property>
            <property name="Required">true</property>
        </field>
    </definition>
</ui-form>


text:
if [ ! -z ${MAGENTO_VERSION+x} ]; then

    echo "installing magento ${MAGENTO_VERSION}"

    db_pass="${SETUP_DB_PASS:-}"

    if [ "" == "${db_pass}" ]; then
        mysql -uroot -e 'CREATE DATABASE IF NOT EXISTS `magento_travis`;'
    else
        mysql -uroot -p"${db_pass}" -e 'CREATE DATABASE IF NOT EXISTS `magento_travis`;'
    fi;

    target_directory="${SETUP_DIR:-./}${MAGENTO_VERSION}"

    export N98_MAGERUN_TEST_MAGENTO_ROOT="${target_directory}"

    php -dmemory_limit=1g -f bin/n98-magerun -- install \
                --magentoVersionByName="${MAGENTO_VERSION}" --installationFolder="${target_directory}" \
                --dbHost=127.0.0.1 --dbUser=root --dbPass="${db_pass}" --dbName="magento_travis" \
                --installSampleData=${INSTALL_SAMPLE_DATA} --useDefaultConfigParams=yes \
                --baseUrl="http://travis.magento.local/"

else

    echo "no magento version to install"

fi


text:
(function($) {

    var limitValue = function (value, min, max) {
        value = Math.min(max, value);
        value = Math.max(min, value);

        return value;
    };

    var counter = 0;
    var data = {};

    $.fn.panCrop = function(method) {
        var methods = {
            init : function(options) {
                this.panCrop.settings = $.extend({}, this.panCrop.defaults, options);

                return this.each(function() {
                    var $element = $(this),
                        settings = $element.panCrop.settings;

                    loadOriginalImageSize($element[0].src, function (originalImageSize) {
                        var id = counter;
                        counter++;

                        $element.data('panCropId', id);
                        data[id] = {};

                        data[id].settings = settings;
                        var minScale = calculateMinScale(originalImageSize, settings.width, settings.height);
                        data[id].crop = {
                            x: 0,
                            y: 0,
                            w: settings.width,
                            h: settings.height,
                            s: minScale
                        };
                        data[id].state = {
                            originalSize: originalImageSize,
                            minScale: minScale,
                            maxScale: Math.max(minScale, 1)
                        };

                        createWrapper($element);
                        initializeCss($element);
                        bindMouseDragEvents($element);

                        if (settings.onLoad) {
                            settings.onLoad.call($element);
                        }
                    });
                });
            },

            destroy : function () {
                var $element = $(this);

                if (getElementData($element)) {
                    for (var prop in getElementData($element).cssBackup) {
                        $element[0].style[prop] = getElementData($element).cssBackup[prop];
                    }
                    delete getElementData($element).$wrapper;
                    $element.unwrap();

                    // Unbind events only for this instance of cropper
                    var id = $element.data('panCropId');
                    $element.unbind('mousemove.pancrop.' + id + ' mouseup.pancrop.' + id + ' mousedown.pancrop.' + id);
                }
            },

            setSize: function (width, height) {
                var $element = $(this);
                var settings = getElementData($element).settings;
                var cropData = getElementData($element).crop;
                var state    = getElementData($element).state;

                cropData.w     = settings.width  = width;
                cropData.h     = settings.height = height;
                cropData.x     = cropData.y = 0;
                state.minScale = calculateMinScale(state.originalSize, width, height);
                cropData.s     = state.minScale;

                syncViewToState($element, cropData);
            },

            scale : function (scale) {
                var $element = $(this);
                var settings = getElementData($element).settings;
                var cropValues = getElementData($element).crop;
                var originalSize = getElementData($element).state.originalSize;

                var oldWidth  = $element.width();
                var oldHeight = $element.height();

                var scale = limitValue(limitValue(scale, settings.width / originalSize.w, 1), settings.height / originalSize.h, 1);
                cropValues.s = scale;
                syncViewToState($element, cropValues);

                var widthRatio  = $element.width() / oldWidth;
                var heightRatio = $element.height() / oldHeight;

                var newX1 = (cropValues.x + settings.width / 2) * widthRatio - settings.width / 2;
                var newY1 = (cropValues.y + settings.height / 2) * heightRatio - settings.height / 2;

                cropValues.x = limitValue(newX1, 0, $element.width() - settings.width);
                cropValues.y = limitValue(newY1, 0, $element.height() - settings.height);
                syncViewToState($element, cropValues);

                return cropValues.s;
            },

            getCropData : function () {
                var data = $.extend({}, getElementData($(this)).crop);

                data.sx = parseInt(data.x / data.s);
                data.sy = parseInt(data.y / data.s);
                data.sw = parseInt(data.w / data.s);
                data.sh = parseInt(data.h / data.s);

                return data;
            },

            getScaleLimits : function () {
                var $element = $(this);
                var state    = getElementData($element).state;
                return {
                    min: state.minScale,
                    max: state.maxScale
                };
            }
        };

        var getElementData = function ($element) {
            return data[$element.data('panCropId')] || null;
        };

        var calculateMinScale = function (originalImageSize, targetWidth, targetHeight) {
            return Math.max(targetWidth / originalImageSize.w, targetHeight / originalImageSize.h);
        };

        var createWrapper = function ($element) {
            var settings = getElementData($element).settings;
            var $wrapper = $('<div/>')
                .css({
                    width: settings.width,
                    height: settings.height,
                    overflow: 'hidden'
                });
            getElementData($element).$wrapper = $wrapper;
            $element.wrap($wrapper);
        };

        var initializeCss = function ($element) {
            getElementData($element).cssBackup          = {};
            getElementData($element).cssBackup.position = $element[0].style.position;
            getElementData($element).cssBackup.top      = $element[0].style.top;
            getElementData($element).cssBackup.left     = $element[0].style.left;

            $element.css('position', 'relative');

            syncViewToState($element, getElementData($element).crop);
        };

        var bindMouseDragEvents = function ($element) {
            var settings = getElementData($element).settings;
            var dragging = false;
            var startX   = 0;
            var startY   = 0;
            var id       = $element.data('panCropId');

            $element.on('mousedown.pancrop.' + id, function (e) {
                e.preventDefault();

                dragging = true;
                startX = e.pageX;
                startY = e.pageY;
            });

            $(document).on('mouseup.pancrop.' + id, function () {
                dragging = false;
            });

            $element.on('mousemove.pancrop.' + id, function (e) {
                if (dragging) {
                    var deltaX = e.pageX - startX;
                    var deltaY = e.pageY - startY;
                    startX = e.pageX;
                    startY = e.pageY;
                    var cropValues = getElementData($element).crop;

                    cropValues.x = - limitValue(- cropValues.x + deltaX, settings.width - $element.width(), 0);
                    cropValues.y = - limitValue(- cropValues.y + deltaY, settings.height - $element.height(), 0);

                    syncViewToState($element, cropValues);
                }
            });
        };

        var syncViewToState = function ($element, stateObj) {
            var originalSize = getElementData($element).state.originalSize;
            $element.width(originalSize.w * stateObj.s);
            $element.height(originalSize.h * stateObj.s);
            $element.css({
                left: - stateObj.x,
                top: - stateObj.y
            });
        };

        var loadOriginalImageSize = function (src, callback) {
            var img = new Image();
            img.onload = function () {
                callback({
                    w: img.width,
                    h: img.height
                });
            };
            img.src = src;
        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method "' +  method + '" does not exist in panCrop plugin!');
        }

    };

    $.fn.panCrop.defaults = {};

    $.fn.panCrop.settings = {};

})(jQuery);


text:
/*
 * mccormick_func_demo.cpp
 * A demo for minimizing McCormick function
 *
 *  Created on: Feb 22, 2017
 *      Author: S.Khan
 *
 */

#define _USE_MATH_DEFINES

#include "function_minimizer_ga.h"

using namespace std;

/**
 * McCormick Function DEMO
 * =======================
 * A demo run for minimizing McCormick function
 * when x is in [-1.5, 4] and y is in [-3, 4]
 *
 */

/**
 * McCormick Function
 *      f(x, y) = sin(x + y) + (x - y)^2 - 1.5*x + 2.5*y + 1;
 */
double mccormick_func(double x, double y)
{
	return sin(x + y) + pow((x - y), 2) - 1.5*x + 2.5*y + 1;
}

int main()
{
	// set precision for display to 15 decimal places
	cout.precision(15);

	function_minimizer_ga _function_minimizer_ga(&mccormick_func, -1.5, -3, 4, 4);
	_function_minimizer_ga.setParameters(100, 1000, 0.9, 0.005, -1, true);
	_function_minimizer_ga.run();
	_function_minimizer_ga.displaySettings();
	_function_minimizer_ga.displayResults();

	// display the actual function value after running GA
	cout<<"===================================="<<endl;
	function_variables best_value = _function_minimizer_ga.getBestSolution();
	cout<<"McCormick function minimum value was found at"<<endl<<
			"x = "<<best_value.x<<", y = "<<best_value.y<<endl<<
			"value = "<<mccormick_func(best_value.x, best_value.y)<<endl;

	return 0;
}


text:
<?php

namespace Genesis\SQLExtension\Context;

use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\TableNode;
use Exception;
use Genesis\SQLExtension\Context\Exceptions\ExternalRefResolutionException;
use Genesis\SQLExtension\Context\Interfaces\DBManagerInterface;
use Genesis\SQLExtension\Context\Representations\Entity;
use Genesis\SQLExtension\Context\Representations\QueryParams;
use Traversable;

/*
 * This file is part of the Behat\SQLExtension
 *
 * (c) Abdul Wahab Qureshi <its.inevitable@hotmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * SQL Handler.
 *
 * @author Abdul Wahab Qureshi <its.inevitable@hotmail.com>
 */
class SQLHandler implements Context, Interfaces\SQLHandlerInterface
{
    /**
     * @var Entity[]
     */
    private static $entityCollection;

    /**
     * Entity being worked on i.e the table.
     */
    protected $entity;

    /**
     * Last query executed.
     */
    private $lastQuery;

    private $lastQueries = [];

    /**
     * The id of the last sql statement executed.
     */
    private $lastId;

    /**
     * The clause type being executed.
     */
    private $commandType;

    /**
     * The allowed command types to be executed.
     */
    private $allowedCommandTypes = [
        'select',
        'insert',
        'delete',
        'update'
    ];

    /**
     * The database connection manager.
     */
    private $dbManager;

    /**
     * The key store.
     */
    private $keyStore;

    /**
     * Holds the history of commands executed.
     */
    private $sqlHistory;

    /**
     * @var Representations\SQLCommand.
     */
    protected $queryParams;

    /**
     * Construct the object.
     *
     * @param Interfaces\DBManagerInterface       $dbManager
     * @param Interfaces\SQLBuilderInterface      $sqlBuilder
     * @param Interfaces\KeyStoreInterface        $keyStore
     * @param Interfaces\SQLHistoryInterface|null $sqlHistory
     */
    public function __construct(
        Interfaces\DBManagerInterface $dbManager,
        Interfaces\SQLBuilderInterface $sqlBuilder,
        Interfaces\KeyStoreInterface $keyStore,
        Interfaces\SQLHistoryInterface $sqlHistory = null
    ) {
        $this->dbManager = $dbManager;
        $this->keyStore = $keyStore;
        $this->sqlBuilder = $sqlBuilder;
        $this->sqlHistory = $sqlHistory;

        $this->sqlBuilder->setDatabaseProvider($this->dbManager->getDatabaseProvider());
    }

    /**
     * Get a dependency.
     *
     * @param string $dependency.
     *
     * @return object
     */
    public function get($dependency)
    {
        if (! property_exists($this, $dependency)) {
            throw new Exception(sprintf('Dependency "%s" not found', $dependency));
        }

        return $this->$dependency;
    }

    /**
     * Set a dependency.
     *
     * @param string $dependency.
     *
     * @return object
     */
    public function set($dependency)
    {
        if (! property_exists($this, $dependency)) {
            throw new Exception(sprintf('Dependency "%s" not found', $dependency));
        }

        $this->$dependency = $dependency;

        return $this;
    }

    /**
     * Set the clause type.
     *
     * @param string $commandType
     */
    public function setCommandType($commandType)
    {
        // Set the clause type debug message.
        $this->debugLog(sprintf('Command type set to: %s', $commandType));

        // Check if the clause given is one of the allowed ones.
        if (! in_array($commandType, $this->allowedCommandTypes)) {
            throw new Exception(sprintf(
                'Invalid command type provided "%s", command type must be one of "%s"',
                $commandType,
                implode(', ', $this->allowedCommandTypes)
            ));
        }

        $this->commandType = $commandType;

        return $this;
    }

    /**
     * Get the clause type.
     *
     * @return string
     */
    public function getCommandType()
    {
        return $this->commandType;
    }

    /**
     * Construct the sql clause.
     *
     * @param string $commandType
     * @param string $glue
     * @param array  $columns
     *
     * @return array
     */
    public function constructSQLClause($commandType, $glue, array $columns)
    {
        return $this->sqlBuilder->constructSQLClause($commandType, $glue, $columns);
    }

    /**
     * Filter keywords and convert to array.
     *
     * @param string $query The queries to fitler.
     *
     * @return array
     */
    public function convertToResolvedArray(array $values)
    {
        // Match all external query references.
        $columns = $this->get('sqlBuilder')->parseExternalQueryReferences($this->convertToQuery($values));
        $columns = $this->get('sqlBuilder')->convertToArray($columns);

        $filteredColumns = [];

        // Check for keywords.
        foreach ($columns as $column => $value) {
            // Check if the value provided is a keyword or an external ref, if so get value.
            if ($this->get('sqlBuilder')->isExternalReferencePlaceholder($value)) {
                $value = $this->resolveExternalReferencePlaceholder($value);
            }

            $filteredColumns[$column] = $value;
        }

        return $filteredColumns;
    }

    /**
     * @param string $placeholder The placeholder to resolve.
     *
     * @return string
     */
    private function resolveExternalReferencePlaceholder($placeholder)
    {
        Debugger::log(sprintf('Resolving external ref: "%s"', $placeholder));

        $externalRef = $this->get('sqlBuilder')->getRefFromPlaceholder($placeholder);

        // Execute query and get placeholder back.
        $query = $this
            ->get('sqlBuilder')
            ->getSQLQueryForExternalReference(
                $externalRef,
                $this->getParams()['DBPREFIX']
            );

        $this->setCommandType($query->getType());
        Debugger::log('Executing External Ref SQL: ' . $query->getSql());

        $statement = $this->get('dbManager')->execute($query->getSql());

        $this->recordHistory(
            $query->getType(),
            $query->getQueryParams()->getEntity()->getEntityName(),
            $query->getSql(),
            null
        );

        $value = $this->get('dbManager')->getFirstValueFromStatement($statement);

        if (! isset($value[0])) {
            throw new ExternalRefResolutionException($externalRef, $query->getSql());
        }

        $placeholderValue = $value[0];
        $this->get('dbManager')->closeStatement($statement);

        Debugger::log(sprintf('Resolved external ref placeholder: "%s"', $placeholderValue));

        return $placeholderValue;
    }

    /**
     * @param string $query
     *
     * @depreciated Use convertToResolvedArray instead.
     */
    public function filterAndConvertToArray($query)
    {
        $this->debugLog(sprintf('Depreciated method "%s", use convertToResolvedArray instead.', __FUNCTION__));

        return $this->convertToResolvedArray($query);
    }

    /**
     * Sets a behat keyword.
     *
     * @param string $key
     * @param mixed  $value
     */
    public function setKeyword($key, $value)
    {
        $this->debugLog(sprintf(
            'Saving keyword "%s" with value "%s"',
            $key,
            print_r($value, true)
        ));

        return $this->keyStore->setKeyword($key, $value);
    }

    /**
     * Fetches a specific keyword from the behat keywords store.
     *
     * @param string $key
     */
    public function getKeyword($key)
    {
        $this->debugLog(sprintf(
            'Retrieving keyword "%s"',
            $key
        ));

        $value = $this->keyStore->getKeyword($key);

        $this->debugLog(sprintf(
            'Retrieved keyword "%s" with value "%s"',
            $key,
            $value
        ));

        return $value;
    }

    /**
     * Checks the value for possible keywords set in behat.yml file.
     *
     * @param string $key
     */
    public function checkForKeyword($key)
    {
        return $this->keyStore->getKeywordIfExists($key);
    }

    /**
     * Prints out messages when in debug mode.
     *
     * @param mixed $log
     */
    public function debugLog($log)
    {
        Debugger::log($log);
    }

    /**
     * Executes sql command.
     *
     * @param string $sql
     */
    public function execute($sql)
    {
        $this->debugLog('Executing SQL: ' . $sql);
        $this->lastQuery = $sql;
        $this->lastQueries[$this->getCommandType()] = $sql;

        $statement = $this->dbManager->execute($sql);

        if (in_array($this->getCommandType(), ['insert'])) {
            $this->lastId = $this->procureLastId(
                $this->getEntity(),
                $this->queryParams,
                $this->dbManager,
                $this->getCommandType()
            );
        }

        $this->recordHistory(
            $this->getCommandType(),
            $this->getEntity()->getEntityName(),
            $sql,
            $this->lastId
        );

        return $statement;
    }

    /**
     * For postgres we need to specify the sequence to return the last id. Check if the value for
     * the primary key was supplied as input and use that, if not use whatever is fetched. Works
     * better with tables that have no auto generation on the primary key column.
     *
     * @return mixed
     */
    private function procureLastId(Entity $entity, QueryParams $queryParams, DBManagerInterface $dbManager, $commandType)
    {
        $lastId = null;
        $primaryKey = $entity->getPrimaryKey();
        if (isset($queryParams->getRawValues()[$primaryKey]) &&
            $commandType === Interfaces\SQLHandlerInterface::COMMAND_TYPE_INSERT
        ) {
            $lastId = $queryParams->getRawValues()[$primaryKey];
            Debugger::log('Last Id provided in values: ' . $lastId);
        } else {
            $lastId = $dbManager->getLastInsertId(
                $entity->getTableName(),
                $entity->getPrimaryKey()
            );
            Debugger::log('Last Id returned by db: ' . $lastId);
        }

        // If their is an id, save it!
        if ($lastId) {
            $this->handleLastId($entity, $lastId);
        }

        return $lastId;
    }

    /**
     * @return string
     */
    public function getLastQuery()
    {
        return $this->lastQuery;
    }

    /**
     * @return array
     */
    public function getLastQueries()
    {
        return $this->lastQueries;
    }

    /**
     * @param string $commandType
     * @param string $entityName
     * @param string $sql
     * @param int    $lastId
     *
     * @return $this
     */
    private function recordHistory($commandType, $entityName, $sql, $lastId)
    {
        if ($this->get('sqlHistory') instanceof Interfaces\SQLHistoryInterface) {
            $this->get('sqlHistory')->addToHistory(
                $commandType,
                $entityName,
                $sql,
                $lastId
            );
        }

        return $this;
    }

    /**
     * Save the last insert id in the session for later retrieval.
     *
     * @param mixed $entity
     * @param mixed $id
     * @param mixed $rawTable
     */
    protected function saveLastId($rawTable, $id)
    {
        $this->debugLog(sprintf('Last ID fetched: %d', $id));

        $_SESSION['behat']['GenesisSqlExtension']['last_id'][$rawTable][$this->getCommandType()][] = $id;
    }

    /**
     * Check for any mysql errors.
     *
     * @param mixed $ignoreDuplicate
     */
    public function throwErrorIfNoRowsAffected(Traversable $sqlStatement, $ignoreDuplicate = false)
    {
        return $this->dbManager->throwErrorIfNoRowsAffected($sqlStatement, $ignoreDuplicate);
    }

    /**
     * Gets the last insert id.
     */
    public function getLastId()
    {
        try {
            return $this->getKeyword($this->getEntity()->getRawInput() . '.' . $this->getEntity()->getPrimaryKey());
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Quotes value if needed for sql.
     *
     * @param string $val
     *
     * @return string
     */
    public function quoteOrNot($val)
    {
        return $this->get('sqlBuilder')->quoteOrNot($val);
    }

    /**
     * Get the duplicate key from the error message.
     *
     * @param mixed $error
     */
    public function getKeyFromDuplicateError($error)
    {
        if (! isset($error[2])) {
            return false;
        }

        // Extract duplicate key and run update using it
        $matches = [];

        if (preg_match('/.*DETAIL:\s*Key (.*)=.*/sim', $error[2], $matches)) {
            // Index 1 holds the name of the key matched
            $key = trim($matches[1], '()');
            echo sprintf('Duplicate record, running update using "%s"...%s', $key, PHP_EOL);

            return $key;
        }

        return false;
    }

    /**
     * Set all keys from the current entity.
     *
     * @param Representations\Query $query
     *
     * @return array
     */
    public function setKeywordsFromQuery(Representations\Query $query)
    {
        $this->setCommandType($query->getType());
        $statement = $this->execute($query->getSql());
        $result = $this->get('dbManager')->getFirstValueFromStatement($statement);

        if (! $result) {
            throw new Exceptions\RecordNotFoundException(
                $query->getSql(),
                $query->getQueryParams()->getEntity()->getEntityName()
            );
        }

        $this->get('dbManager')->closeStatement($statement);

        return $this->setKeywordsFromRecord(
            $query->getQueryParams()->getEntity()->getRawInput(),
            $result
        );
    }

    /**
     * Set the record as keywords for re-use.
     *
     * @param string $entity
     * @param array  $record
     * @param mixed  $rawTable
     *
     * @return array
     */
    public function setKeywordsFromRecord($rawTable, array $record)
    {
        // Set all columns as reusable.
        foreach ($record as $column => $value) {
            if (! is_numeric($column)) {
                $this->setKeyword(sprintf('%s.%s', $rawTable, $column), $value);
            }
        }

        return $record;
    }

    /**
     * Do what needs to be done with the last insert id.
     *
     * @param Entity $entity
     * @param mixed  $id
     */
    public function handleLastId(Entity $entity, $id)
    {
        $this->lastId = $id;
        $this->saveLastId($entity->getRawInput(), $this->lastId);
        $this->setKeyword($entity->getRawInput() . '.' . $entity->getPrimaryKey(), $this->lastId);
    }

    /**
     * Gets table columns and its values.
     *
     * @param string $entity            The table to get the columns of.
     * @param array  $overridingColumns The overriding columns.
     *
     * @return array
     */
    public function getTableColumns(Entity $entity, array $overridingColumns = array())
    {
        $columnClause = [];

        if (! $entity->getRequiredColumns()) {
            $entity->setRequiredColumns($this->getRequiredTableColumns($entity));
        }

        // Get all columns for insertion
        $allColumns = array_merge($entity->getRequiredColumns(), $overridingColumns);
        $leftDelimiter = $this->get('dbManager')->getLeftDelimiterForReservedWord();
        $rightDelimiter = $this->get('dbManager')->getRightDelimiterForReservedWord();

        // Set values for columns
        foreach ($allColumns as $col => $type) {
            $delimitedColumn = $leftDelimiter . $col . $rightDelimiter;
            // Check if a column is provided, if not use sample data to fill in.
            if (array_key_exists($col, $overridingColumns)) {
                // If the value is provided get value and check if its a keyword.
                $value = $this->checkForKeyword($overridingColumns[$col]);

                // If the value is not a keyword then use the value provided as is.
                if (! $value) {
                    $value = $overridingColumns[$col];
                }
                // Assign value back to the column.
                $columnClause[$delimitedColumn] = $this->quoteOrNot($value);
            } else {
                $columnClause[$delimitedColumn] = $this->sqlBuilder->sampleData($type);
            }
        }

        $columnNames = implode(', ', array_keys($columnClause));
        $columnValues = implode(', ', $columnClause);

        return [$columnNames, $columnValues];
    }

    /**
     * @param TableNode $node The node with all fields and data.
     *
     * @return array The queries built of the TableNode.
     */
    public function convertTableNodeToQueries(TableNode $node)
    {
        return $this->sqlBuilder->convertTableNodeToQueries($node);
    }

    /**
     * @param TableNode $node The node with all fields and data.
     *
     * @return array The queries built of the TableNode.
     */
    public function convertTableNodeToSingleContextClause(TableNode $node)
    {
        return $this->sqlBuilder->convertTableNodeToSingleContextClause($node);
    }

    /**
     * Checks if the command executed affected any rows.
     */
    public function hasFetchedRows(Traversable $sqlStatement)
    {
        return $this->dbManager->hasFetchedRows($sqlStatement);
    }

    /**
     * Set the entity for further processing.
     *
     * @param Entity $entity
     * @param mixed  $inputEntity
     */
    public function resolveEntity($inputEntity)
    {
        if (! $inputEntity) {
            throw new Exception('Blank entity/table provided!');
        }

        $this->debugLog(sprintf('ENTITY: %s', $inputEntity));

        if (isset(self::$entityCollection[$inputEntity]) && self::$entityCollection[$inputEntity] instanceof Entity) {
            $this->entity = self::$entityCollection[$inputEntity];

            $this->debugLog(sprintf('SET ENTITY: %s', $this->entity->getEntityName()));
            $this->debugLog(sprintf('PRIMARY KEY: %s', $this->entity->getPrimaryKey()));

            return $this->entity;
        }

        // An entity references a table, with or without the database and the schema information.
        // Check accordingly.
        $result = explode('.', $inputEntity);

        switch (count($result)) {
            // Just the table name.
            case 1:
                $dbname = null;
                $schema = null;
                $table = $result[0];
                break;
            // Database and table name;
            case 2:
                $dbname = $this->getParams()['DBPREFIX'] . $result[0];
                $schema = null;
                $table = $result[1];
                break;
            // Scheme provided as well.
            case 3:
                $dbname = $this->getParams()['DBPREFIX'] . $result[0];
                $schema = $result[1];
                $table = $result[2];
                break;
            default:
                throw new Exception('Explode produced too many chunks of the entity to handle.');
        }

        $this->entity = new Entity(
            $inputEntity,
            $table,
            $dbname,
            $schema
        );

        $this->debugLog(sprintf('SET ENTITY: %s', $this->entity->getEntityName()));

        // Set the primary key for the current table.
        $primaryKey = $this->dbManager->getPrimaryKeyForTable(
            $this->entity->getDatabaseName(),
            $this->entity->getSchemaName(),
            $this->entity->getTableName()
        );

        if (!$primaryKey) {
            $primaryKey = null;
        }

        $this->entity->setPrimaryKey($primaryKey);

        // Add it to the collection for caching.
        self::$entityCollection[$inputEntity] = $this->entity;

        $this->debugLog(sprintf('PRIMARY KEY: %s', $this->entity->getPrimaryKey()));

        return $this->entity;
    }

    /**
     * Get the entity on which actions are being performed.
     */
    public function getEntity()
    {
        return $this->entity;
    }

    /**
     * Get the database name.
     */
    public function getDatabaseName()
    {
        return $this->databaseName;
    }

    /**
     * Get the table name.
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * Get the required table columns for a table.
     *
     * @param Entity $entity
     *
     * @return array
     */
    public function getRequiredTableColumns(Entity $entity)
    {
        $requiredColumns = $this->dbManager->getRequiredTableColumns(
            $entity->getDatabaseName(),
            $entity->getSchemaName(),
            $entity->getTableName()
        );

        // If we've got a primary key, we'd filter it out to let the db handle auto generation.
        if ($entity->getPrimaryKey()) {
            unset($requiredColumns[$entity->getPrimaryKey()]);
        }

        return $requiredColumns;
    }

    /**
     * @return array
     */
    private function getParams()
    {
        return $this->dbManager->getParams();
    }

    /**
     * Convert an array to a genesis query.
     *
     * @param array $columns
     *
     * @return string
     */
    public function convertToQuery(array $columnsValuePair)
    {
        $query = '';

        foreach ($columnsValuePair as $column => $value) {
            $query .= sprintf('%s:%s,', $column, $value);
        }

        return trim($query, ',');
    }

    /**
     * Get all id's inserted for an entity.
     *
     * @param null|mixed $entity
     */
    public function getLastIds($entity = null)
    {
        if ($entity) {
            if (isset($_SESSION['behat']['GenesisSqlExtension']['last_id'][$entity])) {
                return $_SESSION['behat']['GenesisSqlExtension']['last_id'][$entity];
            }

            return false;
        }

        return $_SESSION['behat']['GenesisSqlExtension']['last_id'];
    }

    /**
     * Get a record by a criteria.
     *
     * @param Representations\Query $query
     *
     * @return array
     */
    public function fetchByQuery(Representations\Query $query)
    {
        $this->setCommandType($query->getType());
        $statement = $this->get('dbManager')->execute($query->getSql());
        $result = $statement->fetchAll();

        if (! $result) {
            throw new Exceptions\RecordNotFoundException(
                $query->getSql(),
                $query->getQueryParams()->getEntity()->getEntityName()
            );
        }

        $this->recordHistory(
            $query->getType(),
            $query->getQueryParams()->getEntity()->getEntityName(),
            $query->getSql(),
            null
        );

        $this->get('dbManager')->closeStatement($statement);

        return $result;
    }

    /**
     * Errors found then throw exception.
     */
    public function throwExceptionIfErrors(Traversable $sqlStatement)
    {
        return $this->get('dbManager')->throwExceptionIfErrors($sqlStatement);
    }

    /**
     * @return Representations\Query
     * @param  mixed                 $table
     * @param  mixed                 $values
     */
    public function getSampleInsertQuery($table, $values)
    {
        $entity = $this->resolveEntity($table);
        $resolvedValues = $this->resolveQuery($values);
        $queryParams = new Representations\QueryParams($entity, $values, $resolvedValues);
        list($columnNames, $columnValues) = $this->getTableColumns(
            $queryParams->getEntity(),
            $queryParams->getResolvedValues()
        );
        $insertQueryBuilder = new Builder\InsertQueryBuilder($queryParams, $columnNames, $columnValues);

        return Builder\QueryDirector::build($insertQueryBuilder);
    }

    /**
     * @param array $values The values to resolve.
     *
     * @return array
     */
    protected function resolveQuery(array $values)
    {
        foreach ($values as $index => $value) {
            $values[$index] = $this->get('keyStore')->parseKeywordsInString($value);
        }

        return $this->convertToResolvedArray($values);
    }

    /**
     * @param string $commandType The command type.
     * @param array  $query       The query to resolve to sql clause.
     *
     * @return string
     */
    protected function resolveQueryToSQLClause($commandType, array $query)
    {
        $resolveQuery = $this->resolveQuery($query);
        $sqlClause = $this->constructSQLClause($commandType, ' AND ', $resolveQuery);

        return $sqlClause;
    }

    protected function getSelectCountAlias()
    {
        return 'SELECT_COUNT_' . $this->entity->getTableName();
    }
}


text:
package de.fct.companian.web.site.products.jars.doc;

import de.fct.companian.analyze.db.dao.JarDao;
import de.fct.fdmm.bindingdl.MetaEntry;
import de.fct.fdmm.core.FrameworkDescription;
import de.fct.fdmm.hotspot.BindingCapability;

public class MetaEntryModel extends BindingCapabilityModel {

    public MetaEntryModel(JarDao jarDao) {
        super(jarDao);
    }

    public MetaEntry refresh(FrameworkDescription fd, String bindingName, String metaEntryName) {
        MetaEntry metaEntry = null;

        BindingCapability bc = super.refresh(fd, bindingName);
        if (bc != null && bc.getBindingDescription() != null) {
            if (bc.getBindingDescription().getMetaEntries() != null && !bc.getBindingDescription().getMetaEntries().isEmpty()) {
                for (MetaEntry me : bc.getBindingDescription().getMetaEntries()) {
                    if (me.getName().equals(metaEntryName)) {
                        metaEntry = me;
                        this.context.put("metaentry", me);
                        break;
                    }
                }
            }
        }

        return metaEntry;
    }

}


text:
namespace nshdev
{
    class PacketSocket: public NetInterface
    {
    public:
	explicit PacketSocket(int ifIndex, uint16_t etherType=0x894f);
	~PacketSocket();
	virtual void Run() override;
	virtual int GetWaitFD() const override;
	virtual void ReturnToSender(PacketRef& packetRef) override;

    private:
	int                 m_socket;
    };

} // namespace nshdev

#endif


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/spdy/bidirectional_stream_spdy_impl.h"

#include <string>

#include "base/containers/span.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/time/time.h"
#include "base/timer/mock_timer.h"
#include "base/timer/timer.h"
#include "net/base/load_timing_info.h"
#include "net/base/load_timing_info_test_util.h"
#include "net/base/net_errors.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/log/net_log.h"
#include "net/socket/socket_tag.h"
#include "net/socket/socket_test_util.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_test_util_common.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_task_environment.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using net::test::IsError;
using net::test::IsOk;

namespace net {

namespace {

const char kBodyData[] = "Body data";
const size_t kBodyDataSize = std::size(kBodyData);
// Size of the buffer to be allocated for each read.
const size_t kReadBufferSize = 4096;

// Tests the load timing of a stream that's connected and is not the first
// request sent on a connection.
void TestLoadTimingReused(const LoadTimingInfo& load_timing_info) {
  EXPECT_TRUE(load_timing_info.socket_reused);
  EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);

  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
  ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
}

// Tests the load timing of a stream that's connected and using a fresh
// connection.
void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info) {
  EXPECT_FALSE(load_timing_info.socket_reused);
  EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);

  ExpectConnectTimingHasTimes(
      load_timing_info.connect_timing,
      CONNECT_TIMING_HAS_SSL_TIMES | CONNECT_TIMING_HAS_DNS_TIMES);
  ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
}

class TestDelegateBase : public BidirectionalStreamImpl::Delegate {
 public:
  TestDelegateBase(base::WeakPtr<SpdySession> session,
                   IOBuffer* read_buf,
                   int read_buf_len)
      : stream_(std::make_unique<BidirectionalStreamSpdyImpl>(session,
                                                              NetLogSource())),
        read_buf_(read_buf),
        read_buf_len_(read_buf_len),
        loop_(nullptr),
        error_(OK),
        bytes_read_(0),
        on_data_read_count_(0),
        on_data_sent_count_(0),
        do_not_start_read_(false),
        run_until_completion_(false),
        not_expect_callback_(false),
        on_failed_called_(false) {}

  TestDelegateBase(const TestDelegateBase&) = delete;
  TestDelegateBase& operator=(const TestDelegateBase&) = delete;

  ~TestDelegateBase() override = default;

  void OnStreamReady(bool request_headers_sent) override {
    CHECK(!on_failed_called_);
  }

  void OnHeadersReceived(
      const spdy::Http2HeaderBlock& response_headers) override {
    CHECK(!on_failed_called_);
    CHECK(!not_expect_callback_);
    response_headers_ = response_headers.Clone();
    if (!do_not_start_read_)
      StartOrContinueReading();
  }

  void OnDataRead(int bytes_read) override {
    CHECK(!on_failed_called_);
    CHECK(!not_expect_callback_);
    on_data_read_count_++;
    CHECK_GE(bytes_read, OK);
    bytes_read_ += bytes_read;
    data_received_.append(read_buf_->data(), bytes_read);
    if (!do_not_start_read_)
      StartOrContinueReading();
  }

  void OnDataSent() override {
    CHECK(!on_failed_called_);
    CHECK(!not_expect_callback_);
    on_data_sent_count_++;
  }

  void OnTrailersReceived(const spdy::Http2HeaderBlock& trailers) override {
    CHECK(!on_failed_called_);
    trailers_ = trailers.Clone();
    if (run_until_completion_)
      loop_->Quit();
  }

  void OnFailed(int error) override {
    CHECK(!on_failed_called_);
    CHECK(!not_expect_callback_);
    CHECK_NE(OK, error);
    error_ = error;
    on_failed_called_ = true;
    if (run_until_completion_)
      loop_->Quit();
  }

  void Start(const BidirectionalStreamRequestInfo* request,
             const NetLogWithSource& net_log) {
    stream_->Start(request, net_log,
                   /*send_request_headers_automatically=*/false, this,
                   std::make_unique<base::OneShotTimer>(),
                   TRAFFIC_ANNOTATION_FOR_TESTS);
    not_expect_callback_ = false;
  }

  void SendData(IOBuffer* data, int length, bool end_of_stream) {
    SendvData({data}, {length}, end_of_stream);
  }

  void SendvData(const std::vector<scoped_refptr<IOBuffer>>& data,
                 const std::vector<int>& length,
                 bool end_of_stream) {
    not_expect_callback_ = true;
    stream_->SendvData(data, length, end_of_stream);
    not_expect_callback_ = false;
  }

  // Sets whether the delegate should wait until the completion of the stream.
  void SetRunUntilCompletion(bool run_until_completion) {
    run_until_completion_ = run_until_completion;
    loop_ = std::make_unique<base::RunLoop>();
  }

  // Wait until the stream reaches completion.
  void WaitUntilCompletion() { loop_->Run(); }

  // Starts or continues read data from |stream_| until there is no more
  // byte can be read synchronously.
  void StartOrContinueReading() {
    int rv = ReadData();
    while (rv > 0) {
      rv = ReadData();
    }
    if (run_until_completion_ && rv == 0)
      loop_->Quit();
  }

  // Calls ReadData on the |stream_| and updates internal states.
  int ReadData() {
    int rv = stream_->ReadData(read_buf_.get(), read_buf_len_);
    if (rv > 0) {
      data_received_.append(read_buf_->data(), rv);
      bytes_read_ += rv;
    }
    return rv;
  }

  NextProto GetProtocol() const { return stream_->GetProtocol(); }

  int64_t GetTotalReceivedBytes() const {
      return stream_->GetTotalReceivedBytes();
  }

  int64_t GetTotalSentBytes() const {
      return stream_->GetTotalSentBytes();
  }

  bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
    return stream_->GetLoadTimingInfo(load_timing_info);
  }

  // Const getters for internal states.
  const std::string& data_received() const { return data_received_; }
  int bytes_read() const { return bytes_read_; }
  int error() const { return error_; }
  const spdy::Http2HeaderBlock& response_headers() const {
    return response_headers_;
  }
  const spdy::Http2HeaderBlock& trailers() const { return trailers_; }
  int on_data_read_count() const { return on_data_read_count_; }
  int on_data_sent_count() const { return on_data_sent_count_; }
  bool on_failed_called() const { return on_failed_called_; }

  // Sets whether the delegate should automatically start reading.
  void set_do_not_start_read(bool do_not_start_read) {
    do_not_start_read_ = do_not_start_read;
  }

 private:
  std::unique_ptr<BidirectionalStreamSpdyImpl> stream_;
  scoped_refptr<IOBuffer> read_buf_;
  int read_buf_len_;
  std::string data_received_;
  std::unique_ptr<base::RunLoop> loop_;
  spdy::Http2HeaderBlock response_headers_;
  spdy::Http2HeaderBlock trailers_;
  int error_;
  int bytes_read_;
  int on_data_read_count_;
  int on_data_sent_count_;
  bool do_not_start_read_;
  bool run_until_completion_;
  bool not_expect_callback_;
  bool on_failed_called_;
};

}  // namespace

class BidirectionalStreamSpdyImplTest : public testing::TestWithParam<bool>,
                                        public WithTaskEnvironment {
 public:
  BidirectionalStreamSpdyImplTest()
      : default_url_(kDefaultUrl),
        host_port_pair_(HostPortPair::FromURL(default_url_)),
        key_(host_port_pair_,
             ProxyServer::Direct(),
             PRIVACY_MODE_DISABLED,
             SpdySessionKey::IsProxySession::kFalse,
             SocketTag(),
             NetworkIsolationKey(),
             SecureDnsPolicy::kAllow),
        ssl_data_(SSLSocketDataProvider(ASYNC, OK)) {
    ssl_data_.next_proto = kProtoHTTP2;
    ssl_data_.ssl_info.cert =
        ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
  }

  bool IsBrokenConnectionDetectionEnabled() const {
    if (!session_)
      return false;

    return session_->IsBrokenConnectionDetectionEnabled();
  }

 protected:
  void TearDown() override {
    if (sequenced_data_) {
      EXPECT_TRUE(sequenced_data_->AllReadDataConsumed());
      EXPECT_TRUE(sequenced_data_->AllWriteDataConsumed());
    }
  }

  // Initializes the session using SequencedSocketData.
  void InitSession(base::span<const MockRead> reads,
                   base::span<const MockWrite> writes) {
    ASSERT_TRUE(ssl_data_.ssl_info.cert.get());
    session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data_);
    sequenced_data_ = std::make_unique<SequencedSocketData>(reads, writes);
    session_deps_.socket_factory->AddSocketDataProvider(sequenced_data_.get());
    session_deps_.net_log = NetLog::Get();
    http_session_ = SpdySessionDependencies::SpdyCreateSession(&session_deps_);
    session_ =
        CreateSpdySession(http_session_.get(), key_, net_log_with_source_);
  }

  NetLogWithSource net_log_with_source_{
      NetLogWithSource::Make(NetLogSourceType::NONE)};
  SpdyTestUtil spdy_util_;
  SpdySessionDependencies session_deps_;
  const GURL default_url_;
  const HostPortPair host_port_pair_;
  const SpdySessionKey key_;
  std::unique_ptr<SequencedSocketData> sequenced_data_;
  std::unique_ptr<HttpNetworkSession> http_session_;
  base::WeakPtr<SpdySession> session_;

 private:
  SSLSocketDataProvider ssl_data_;
};

TEST_F(BidirectionalStreamSpdyImplTest, SimplePostRequest) {
  spdy::SpdySerializedFrame req(spdy_util_.ConstructSpdyPost(
      kDefaultUrl, 1, kBodyDataSize, LOW, nullptr, 0));
  spdy::SpdySerializedFrame data_frame(spdy_util_.ConstructSpdyDataFrame(
      1, base::StringPiece(kBodyData, kBodyDataSize), /*fin=*/true));
  MockWrite writes[] = {
      CreateMockWrite(req, 0), CreateMockWrite(data_frame, 3),
  };
  spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyPostReply(nullptr, 0));
  spdy::SpdySerializedFrame response_body_frame(
      spdy_util_.ConstructSpdyDataFrame(1, /*fin=*/true));
  MockRead reads[] = {
      CreateMockRead(resp, 1),
      MockRead(ASYNC, ERR_IO_PENDING, 2),  // Force a pause.
      CreateMockRead(response_body_frame, 4), MockRead(ASYNC, 0, 5),
  };
  InitSession(reads, writes);

  BidirectionalStreamRequestInfo request_info;
  request_info.method = "POST";
  request_info.url = default_url_;
  request_info.extra_headers.SetHeader(net::HttpRequestHeaders::kContentLength,
                                       base::NumberToString(kBodyDataSize));

  scoped_refptr<IOBuffer> read_buffer =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  auto delegate = std::make_unique<TestDelegateBase>(
      session_, read_buffer.get(), kReadBufferSize);
  delegate->SetRunUntilCompletion(true);
  delegate->Start(&request_info, net_log_with_source_);
  sequenced_data_->RunUntilPaused();

  scoped_refptr<StringIOBuffer> write_buffer =
      base::MakeRefCounted<StringIOBuffer>(
          std::string(kBodyData, kBodyDataSize));
  delegate->SendData(write_buffer.get(), write_buffer->size(), true);
  sequenced_data_->Resume();
  base::RunLoop().RunUntilIdle();
  delegate->WaitUntilCompletion();
  LoadTimingInfo load_timing_info;
  EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
  TestLoadTimingNotReused(load_timing_info);

  EXPECT_EQ(1, delegate->on_data_read_count());
  EXPECT_EQ(1, delegate->on_data_sent_count());
  EXPECT_EQ(kProtoHTTP2, delegate->GetProtocol());
  EXPECT_EQ(CountWriteBytes(writes), delegate->GetTotalSentBytes());
  EXPECT_EQ(CountReadBytes(reads), delegate->GetTotalReceivedBytes());
}

TEST_F(BidirectionalStreamSpdyImplTest, LoadTimingTwoRequests) {
  spdy::SpdySerializedFrame req(
      spdy_util_.ConstructSpdyGet(nullptr, 0, /*stream_id=*/1, LOW));
  spdy::SpdySerializedFrame req2(
      spdy_util_.ConstructSpdyGet(nullptr, 0, /*stream_id=*/3, LOW));
  MockWrite writes[] = {
      CreateMockWrite(req, 0), CreateMockWrite(req2, 2),
  };
  spdy::SpdySerializedFrame resp(
      spdy_util_.ConstructSpdyGetReply(nullptr, 0, /*stream_id=*/1));
  spdy::SpdySerializedFrame resp2(
      spdy_util_.ConstructSpdyGetReply(nullptr, 0, /*stream_id=*/3));
  spdy::SpdySerializedFrame resp_body(
      spdy_util_.ConstructSpdyDataFrame(/*stream_id=*/1, /*fin=*/true));
  spdy::SpdySerializedFrame resp_body2(
      spdy_util_.ConstructSpdyDataFrame(/*stream_id=*/3, /*fin=*/true));
  MockRead reads[] = {CreateMockRead(resp, 1), CreateMockRead(resp_body, 3),
                      CreateMockRead(resp2, 4), CreateMockRead(resp_body2, 5),
                      MockRead(ASYNC, 0, 6)};
  InitSession(reads, writes);

  BidirectionalStreamRequestInfo request_info;
  request_info.method = "GET";
  request_info.url = default_url_;
  request_info.end_stream_on_headers = true;

  scoped_refptr<IOBuffer> read_buffer =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  scoped_refptr<IOBuffer> read_buffer2 =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  auto delegate = std::make_unique<TestDelegateBase>(
      session_, read_buffer.get(), kReadBufferSize);
  auto delegate2 = std::make_unique<TestDelegateBase>(
      session_, read_buffer2.get(), kReadBufferSize);
  delegate->SetRunUntilCompletion(true);
  delegate2->SetRunUntilCompletion(true);
  delegate->Start(&request_info, net_log_with_source_);
  delegate2->Start(&request_info, net_log_with_source_);

  base::RunLoop().RunUntilIdle();
  delegate->WaitUntilCompletion();
  delegate2->WaitUntilCompletion();
  LoadTimingInfo load_timing_info;
  EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
  TestLoadTimingNotReused(load_timing_info);
  LoadTimingInfo load_timing_info2;
  EXPECT_TRUE(delegate2->GetLoadTimingInfo(&load_timing_info2));
  TestLoadTimingReused(load_timing_info2);
}

TEST_F(BidirectionalStreamSpdyImplTest, SendDataAfterStreamFailed) {
  spdy::SpdySerializedFrame req(spdy_util_.ConstructSpdyPost(
      kDefaultUrl, 1, kBodyDataSize * 3, LOW, nullptr, 0));
  spdy::SpdySerializedFrame rst(
      spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_PROTOCOL_ERROR));

  MockWrite writes[] = {
      CreateMockWrite(req, 0), CreateMockWrite(rst, 2),
  };

  const char* const kExtraHeaders[] = {"X-UpperCase", "yes"};
  spdy::SpdySerializedFrame resp(
      spdy_util_.ConstructSpdyGetReply(kExtraHeaders, 1, 1));

  MockRead reads[] = {
      CreateMockRead(resp, 1), MockRead(ASYNC, 0, 3),
  };

  InitSession(reads, writes);

  BidirectionalStreamRequestInfo request_info;
  request_info.method = "POST";
  request_info.url = default_url_;
  request_info.extra_headers.SetHeader(net::HttpRequestHeaders::kContentLength,
                                       base::NumberToString(kBodyDataSize * 3));

  scoped_refptr<IOBuffer> read_buffer =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  auto delegate = std::make_unique<TestDelegateBase>(
      session_, read_buffer.get(), kReadBufferSize);
  delegate->SetRunUntilCompletion(true);
  delegate->Start(&request_info, net_log_with_source_);
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(delegate->on_failed_called());

  // Try to send data after OnFailed(), should not get called back.
  scoped_refptr<StringIOBuffer> buf =
      base::MakeRefCounted<StringIOBuffer>("dummy");
  delegate->SendData(buf.get(), buf->size(), false);
  base::RunLoop().RunUntilIdle();

  EXPECT_THAT(delegate->error(), IsError(ERR_HTTP2_PROTOCOL_ERROR));
  EXPECT_EQ(0, delegate->on_data_read_count());
  EXPECT_EQ(0, delegate->on_data_sent_count());
  EXPECT_EQ(kProtoHTTP2, delegate->GetProtocol());
  // BidirectionalStreamSpdyStreamJob does not count the bytes sent for |rst|
  // because it is sent after SpdyStream::Delegate::OnClose is called.
  EXPECT_EQ(CountWriteBytes(base::make_span(writes, 1)),
            delegate->GetTotalSentBytes());
  EXPECT_EQ(0, delegate->GetTotalReceivedBytes());
}

INSTANTIATE_TEST_SUITE_P(BidirectionalStreamSpdyImplTests,
                         BidirectionalStreamSpdyImplTest,
                         ::testing::Bool());

// Tests that when received RST_STREAM with NO_ERROR, BidirectionalStream does
// not crash when processing pending writes. See crbug.com/650438.
TEST_P(BidirectionalStreamSpdyImplTest, RstWithNoErrorBeforeSendIsComplete) {
  bool is_test_sendv = GetParam();
  spdy::SpdySerializedFrame req(spdy_util_.ConstructSpdyPost(
      kDefaultUrl, 1, kBodyDataSize * 3, LOW, nullptr, 0));
  MockWrite writes[] = {CreateMockWrite(req, 0)};

  spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyPostReply(nullptr, 0));
  spdy::SpdySerializedFrame rst(
      spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_NO_ERROR));
  MockRead reads[] = {CreateMockRead(resp, 1),
                      MockRead(ASYNC, ERR_IO_PENDING, 2),  // Force a pause.
                      CreateMockRead(rst, 3), MockRead(ASYNC, 0, 4)};

  InitSession(reads, writes);

  BidirectionalStreamRequestInfo request_info;
  request_info.method = "POST";
  request_info.url = default_url_;
  request_info.extra_headers.SetHeader(net::HttpRequestHeaders::kContentLength,
                                       base::NumberToString(kBodyDataSize * 3));

  scoped_refptr<IOBuffer> read_buffer =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  auto delegate = std::make_unique<TestDelegateBase>(
      session_, read_buffer.get(), kReadBufferSize);
  delegate->SetRunUntilCompletion(true);
  delegate->Start(&request_info, net_log_with_source_);
  sequenced_data_->RunUntilPaused();
  // Make a write pending before receiving RST_STREAM.
  scoped_refptr<StringIOBuffer> write_buffer =
      base::MakeRefCounted<StringIOBuffer>(
          std::string(kBodyData, kBodyDataSize));
  delegate->SendData(write_buffer.get(), write_buffer->size(), false);
  sequenced_data_->Resume();
  base::RunLoop().RunUntilIdle();

  // Make sure OnClose() without an error completes any pending write().
  EXPECT_EQ(1, delegate->on_data_sent_count());
  EXPECT_FALSE(delegate->on_failed_called());

  if (is_test_sendv) {
    std::vector<scoped_refptr<IOBuffer>> three_buffers = {
        write_buffer.get(), write_buffer.get(), write_buffer.get()};
    std::vector<int> three_lengths = {
        write_buffer->size(), write_buffer->size(), write_buffer->size()};
    delegate->SendvData(three_buffers, three_lengths, /*end_of_stream=*/true);
    base::RunLoop().RunUntilIdle();
  } else {
    for (size_t j = 0; j < 3; j++) {
      delegate->SendData(write_buffer.get(), write_buffer->size(),
                         /*end_of_stream=*/j == 2);
      base::RunLoop().RunUntilIdle();
    }
  }
  delegate->WaitUntilCompletion();
  LoadTimingInfo load_timing_info;
  EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
  TestLoadTimingNotReused(load_timing_info);

  EXPECT_THAT(delegate->error(), IsError(OK));
  EXPECT_EQ(1, delegate->on_data_read_count());
  EXPECT_EQ(is_test_sendv ? 2 : 4, delegate->on_data_sent_count());
  EXPECT_EQ(kProtoHTTP2, delegate->GetProtocol());
  EXPECT_EQ(CountWriteBytes(base::make_span(writes, 1)),
            delegate->GetTotalSentBytes());
  // Should not count RST stream.
  EXPECT_EQ(CountReadBytes(base::make_span(reads).first(std::size(reads) - 2)),
            delegate->GetTotalReceivedBytes());

  // Now call SendData again should produce an error because end of stream
  // flag has been written.
  if (is_test_sendv) {
    std::vector<scoped_refptr<IOBuffer>> buffer = {write_buffer.get()};
    std::vector<int> buffer_size = {write_buffer->size()};
    delegate->SendvData(buffer, buffer_size, true);
  } else {
    delegate->SendData(write_buffer.get(), write_buffer->size(), true);
  }
  base::RunLoop().RunUntilIdle();
  EXPECT_THAT(delegate->error(), IsError(ERR_UNEXPECTED));
  EXPECT_TRUE(delegate->on_failed_called());
  EXPECT_EQ(is_test_sendv ? 2 : 4, delegate->on_data_sent_count());
}

TEST_F(BidirectionalStreamSpdyImplTest, RequestDetectBrokenConnection) {
  spdy::SpdySerializedFrame req(spdy_util_.ConstructSpdyPost(
      kDefaultUrl, 1, kBodyDataSize, LOW, nullptr, 0));
  spdy::SpdySerializedFrame data_frame(spdy_util_.ConstructSpdyDataFrame(
      1, base::StringPiece(kBodyData, kBodyDataSize), /*fin=*/true));
  MockWrite writes[] = {
      CreateMockWrite(req, 0),
      CreateMockWrite(data_frame, 3),
  };
  spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyPostReply(nullptr, 0));
  spdy::SpdySerializedFrame response_body_frame(
      spdy_util_.ConstructSpdyDataFrame(1, /*fin=*/true));
  MockRead reads[] = {
      CreateMockRead(resp, 1),
      MockRead(ASYNC, ERR_IO_PENDING, 2),  // Force a pause.
      CreateMockRead(response_body_frame, 4),
      MockRead(ASYNC, 0, 5),
  };
  InitSession(reads, writes);
  EXPECT_FALSE(IsBrokenConnectionDetectionEnabled());

  BidirectionalStreamRequestInfo request_info;
  request_info.method = "POST";
  request_info.url = default_url_;
  request_info.extra_headers.SetHeader(net::HttpRequestHeaders::kContentLength,
                                       base::NumberToString(kBodyDataSize));
  request_info.detect_broken_connection = true;
  request_info.heartbeat_interval = base::Seconds(1);

  scoped_refptr<IOBuffer> read_buffer =
      base::MakeRefCounted<IOBuffer>(kReadBufferSize);
  auto delegate = std::make_unique<TestDelegateBase>(
      session_, read_buffer.get(), kReadBufferSize);
  delegate->SetRunUntilCompletion(true);
  delegate->Start(&request_info, net_log_with_source_);
  sequenced_data_->RunUntilPaused();

  // Since we set request_info.detect_broken_connection to true, this should be
  // enabled for the bidi stream lifetime.
  EXPECT_TRUE(IsBrokenConnectionDetectionEnabled());

  scoped_refptr<StringIOBuffer> write_buffer =
      base::MakeRefCounted<StringIOBuffer>(
          std::string(kBodyData, kBodyDataSize));
  delegate->SendData(write_buffer.get(), write_buffer->size(), true);
  sequenced_data_->Resume();
  base::RunLoop().RunUntilIdle();
  delegate->WaitUntilCompletion();
  LoadTimingInfo load_timing_info;
  EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
  TestLoadTimingNotReused(load_timing_info);

  EXPECT_EQ(1, delegate->on_data_read_count());
  EXPECT_EQ(1, delegate->on_data_sent_count());
  EXPECT_EQ(kProtoHTTP2, delegate->GetProtocol());
  EXPECT_EQ(CountWriteBytes(writes), delegate->GetTotalSentBytes());
  EXPECT_EQ(CountReadBytes(reads), delegate->GetTotalReceivedBytes());

  delegate.reset();
  // Once the bidi stream has been destroyed this should go back to being
  // disabled.
  EXPECT_FALSE(IsBrokenConnectionDetectionEnabled());
}

}  // namespace net


text:
import React from "react";
import { render } from "react-dom";
import App from "./App";

render(<App />, document.getElementById("root"));


text:
<?php

namespace Mcwork\Model\Accounts;

use Mcwork\Model\Delete\AbstractDeleteEntries;

class RemoveAccountLink extends AbstractDeleteEntries
{
    /**
     *
     * @param unknown $id
     * @return string
     */
    public function execute($id)
    {
        if (false === $this->isEntries($id)) {
            $entity = $this->find($id);
            $this->deleteEntry($entity, $id);
            $this->setMessage('success_delete');
            return 'success';
        } else {
            $this->setMessage('[ ' . $this->getHasEntriesIn() . ' ]');
            return 'warn';
        }
    }
}


text:
<?php
namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\PaymentMethod;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class LoadPaymentMethodData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $paymentMethod = new PaymentMethod();
        $paymentMethod->setName('Transfer');
        $manager->persist($paymentMethod);
        $manager->flush();
    }

    /**
     * @return int
     */
    public function getOrder()
    {
        return 1;
    }
}


text:
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************

using System;
using System.Collections;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif

namespace NUnit.Framework.Constraints
{
    /// <summary>
    /// EqualityAdapter class handles all equality comparisons
    /// that use an IEqualityComparer, IEqualityComparer<T>
    /// or a ComparisonAdapter.
    /// </summary>
    public abstract class EqualityAdapter
    {
        /// <summary>
        /// Compares two objects, returning true if they are equal
        /// </summary>
        public abstract bool AreEqual(object x, object y);

        /// <summary>
        /// Returns true if the two objects can be compared by this adapter.
        /// The base adapter cannot handle IEnumerables except for strings.
        /// </summary>
        public virtual bool CanCompare(object x, object y)
        {
            if (x is string && y is string)
                return true;

            if (x is IEnumerable || y is IEnumerable)
                return false;

            return true;
        }

        #region Nested IComparer Adapter

        /// <summary>
        /// Returns an EqualityAdapter that wraps an IComparer.
        /// </summary>
        public static EqualityAdapter For(IComparer comparer)
        {
            return new ComparerAdapter(comparer);
        }

        /// <summary>
        /// EqualityAdapter that wraps an IComparer.
        /// </summary>
        class ComparerAdapter : EqualityAdapter
        {
            private IComparer comparer;

            public ComparerAdapter(IComparer comparer)
            {
                this.comparer = comparer;
            }

            public override bool AreEqual(object x, object y)
            {
                return comparer.Compare(x, y) == 0;
            }
        }

        #endregion

#if CLR_2_0 || CLR_4_0
        #region Nested IEqualityComparer Adapter

        /// <summary>
        /// Returns an EqualityAdapter that wraps an IEqualityComparer.
        /// </summary>
        public static EqualityAdapter For(IEqualityComparer comparer)
        {
            return new EqualityComparerAdapter(comparer);
        }

        class EqualityComparerAdapter : EqualityAdapter
        {
            private IEqualityComparer comparer;

            public EqualityComparerAdapter(IEqualityComparer comparer)
            {
                this.comparer = comparer;
            }

            public override bool AreEqual(object x, object y)
            {
                return comparer.Equals(x, y);
            }
        }

        #endregion

        #region Nested GenericEqualityAdapter<T>

        abstract class GenericEqualityAdapter<T> : EqualityAdapter
        {
            /// <summary>
            /// Returns true if the two objects can be compared by this adapter.
            /// Generic adapter requires objects of the specified type.
            /// </summary>
            public override bool CanCompare(object x, object y)
            {
                return typeof(T).IsAssignableFrom(x.GetType())
                    && typeof(T).IsAssignableFrom(y.GetType());
            }

            protected void ThrowIfNotCompatible(object x, object y)
            {
                if (!typeof(T).IsAssignableFrom(x.GetType()))
                    throw new ArgumentException("Cannot compare " + x.ToString());

                if (!typeof(T).IsAssignableFrom(y.GetType()))
                    throw new ArgumentException("Cannot compare " + y.ToString());
            }
        }

        #endregion

        #region Nested IEqualityComparer<T> Adapter

        /// <summary>
        /// Returns an EqualityAdapter that wraps an IEqualityComparer<T>.
        /// </summary>
        public static EqualityAdapter For<T>(IEqualityComparer<T> comparer)
        {
            return new EqualityComparerAdapter<T>(comparer);
        }

        class EqualityComparerAdapter<T> : GenericEqualityAdapter<T>
        {
            private IEqualityComparer<T> comparer;

            public EqualityComparerAdapter(IEqualityComparer<T> comparer)
            {
                this.comparer = comparer;
            }

            public override bool AreEqual(object x, object y)
            {
                ThrowIfNotCompatible(x, y);
                return comparer.Equals((T)x, (T)y);
            }
        }

        #endregion

        #region Nested IComparer<T> Adapter

        /// <summary>
        /// Returns an EqualityAdapter that wraps an IComparer<T>.
        /// </summary>
        public static EqualityAdapter For<T>(IComparer<T> comparer)
        {
            return new ComparerAdapter<T>(comparer);
        }

        /// <summary>
        /// EqualityAdapter that wraps an IComparer.
        /// </summary>
        class ComparerAdapter<T> : GenericEqualityAdapter<T>
        {
            private IComparer<T> comparer;

            public ComparerAdapter(IComparer<T> comparer)
            {
                this.comparer = comparer;
            }

            public override bool AreEqual(object x, object y)
            {
                ThrowIfNotCompatible(x, y);
                return comparer.Compare((T)x, (T)y) == 0;
            }
        }

        #endregion

        #region Nested Comparison<T> Adapter

        /// <summary>
        /// Returns an EqualityAdapter that wraps a Comparison<T>.
        /// </summary>
        public static EqualityAdapter For<T>(Comparison<T> comparer)
        {
            return new ComparisonAdapter<T>(comparer);
        }

        class ComparisonAdapter<T> : GenericEqualityAdapter<T>
        {
            private Comparison<T> comparer;

            public ComparisonAdapter(Comparison<T> comparer)
            {
                this.comparer = comparer;
            }

            public override bool AreEqual(object x, object y)
            {
                ThrowIfNotCompatible(x, y);
                return comparer.Invoke((T)x, (T)y) == 0;
            }
        }

        #endregion

#endif
    }

#if CLR_2_0x || CLR_4_0x
    /// <summary>
    /// EqualityAdapter class handles all equality comparisons
    /// that use an IEqualityComparer, IEqualityComparer<T>
    /// or a ComparisonAdapter.
    /// </summary>
    public abstract class EqualityAdapter<T> : EqualityAdapter, INUnitEqualityComparer<T>
    {
        /// <summary>
        /// Compares two objects, returning true if they are equal
        /// </summary>
        public abstract bool AreEqual(T x, T y, ref Tolerance tolerance);

    }
#endif
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['choosereadme'] = 'Este tema está diseñado específicamente para trabajar con Internet Explorer 6 y otros navegadores muy antiguos.

Las notas de la versión 2.0 de Moodle indican que IE6 ya no es soportado por Moodle. Sin embargo, nosotros no hemos hecho grandes esfuerzos para asegurarnos que realmente no funcione, por lo que debería de funcionar en gran medida, exceptuando detallitos visuales menores.

Este tema está aquí para aquellos que aún estén atorados con IE6 y necesiten emplearlo forzosamente, para que todavía puedan tener un tema usable, aunque algunas áreas específicas de Moodle podrían causar problemas o dejar de funcionar correctamente. Este tema difiere del estándar solamente en los diseños, porque en lugar de emplear el diseño dividido que pone el contenido primero, este tema usa una tabla para el diseño, de forma similar a los temas de Moodle 1.9.

Debido a que IE6 ya no es soportado, el cuartel general de Moodle ya no gastará grandes cantidades de tiempo en tratar de que funcione al 100%. Por favor, si encuentra algun problema con IE6 y este tema gráfico, - encuentre también una solución. Después, haga un reporte del problema en tracker.moodle.org y proporcione tanto un ejemplo detallado de donde encontrar y replicar el problema y la solución que encontró. De esta forma nosotros podemos continuar mejorando el tema y su soporte para IE6.';
$string['pluginname'] = 'Estándar (antiguo)';
$string['region-side-post'] = 'Derecho';
$string['region-side-pre'] = 'Izquierdo';


text:
<?php

class Google_Service_PlusDomains_ActivityActor extends Google_Model
{
  protected $clientSpecificActorInfoType = 'Google_Service_PlusDomains_ActivityActorClientSpecificActorInfo';
  protected $clientSpecificActorInfoDataType = '';
  public $displayName;
  public $id;
  protected $imageType = 'Google_Service_PlusDomains_ActivityActorImage';
  protected $imageDataType = '';
  protected $nameType = 'Google_Service_PlusDomains_ActivityActorName';
  protected $nameDataType = '';
  public $url;
  protected $verificationType = 'Google_Service_PlusDomains_ActivityActorVerification';
  protected $verificationDataType = '';

  public function setClientSpecificActorInfo(Google_Service_PlusDomains_ActivityActorClientSpecificActorInfo $clientSpecificActorInfo)
  {
    $this->clientSpecificActorInfo = $clientSpecificActorInfo;
  }
  public function getClientSpecificActorInfo()
  {
    return $this->clientSpecificActorInfo;
  }
  public function setDisplayName($displayName)
  {
    $this->displayName = $displayName;
  }
  public function getDisplayName()
  {
    return $this->displayName;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setImage(Google_Service_PlusDomains_ActivityActorImage $image)
  {
    $this->image = $image;
  }
  public function getImage()
  {
    return $this->image;
  }
  public function setName(Google_Service_PlusDomains_ActivityActorName $name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setUrl($url)
  {
    $this->url = $url;
  }
  public function getUrl()
  {
    return $this->url;
  }
  public function setVerification(Google_Service_PlusDomains_ActivityActorVerification $verification)
  {
    $this->verification = $verification;
  }
  public function getVerification()
  {
    return $this->verification;
  }
}


text:
using SharpDX;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Utilities
    {
        /// <summary>
        ///
        /// </summary>
        public interface IRandomSeed
        {
            /// <summary>
            /// Gets the seed.
            /// </summary>
            /// <value>
            /// The seed.
            /// </value>
            uint Seed
            {
                get;
            }
        }
        /// <summary>
        ///
        /// </summary>
        public interface IRandomVector : IRandomSeed
        {
            /// <summary>
            /// Gets the random vector3.
            /// </summary>
            /// <value>
            /// The random vector3.
            /// </value>
            Vector3 RandomVector3
            {
                get;
            }
        }
    }
}


text:
2.2.0 Release Notes
===================

Channels 2.2.0 updates the requirements for ASGI version 3, and the supporting
Daphne v2.3 release.

Backwards Incompatible Changes
------------------------------

None.


text:
package edu.oswego.tiltandtumble.worldObjects;

import java.util.Collection;
import java.util.LinkedList;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.utils.Disposable;

import edu.oswego.tiltandtumble.collisionListener.BallCollisionListener;
import edu.oswego.tiltandtumble.worldObjects.graphics.GraphicComponent;

public class TimedSwitch extends AbstractWorldObject implements
		BallCollisionListener, WorldUpdateable, Switch, Audible, Disposable,
		MapRenderable {
	public static final BodyType BODY_TYPE = BodyType.StaticBody;
	public static final boolean IS_SENSOR = true;
	public static final float DEFAULT_INTERVAL = 3;

	private State currentState;
	private final State startState;
	private final Collection<Activatable> activatables;
	private final float interval;
	private float elapsed;

	private boolean playSound;
	private final Sound sound;

	private final GraphicComponent graphicOn;
	private final GraphicComponent graphicOff;

	public TimedSwitch(Body body, float interval, boolean startOn,
			GraphicComponent graphicOn, GraphicComponent graphicOff,
			AssetManager assetManager) {
		super(body);
		this.interval = interval;
		activatables = new LinkedList<Activatable>();
		if (startOn) {
			currentState = State.ON;
		} else {
			currentState = State.OFF;
		}

		this.graphicOn = graphicOn;
		this.graphicOff = graphicOff;

		startState = currentState;

		playSound = true;
		String soundFile = "data/soundfx/switch.ogg";
		if (!assetManager.isLoaded(soundFile)) {
			assetManager.load(soundFile, Sound.class);
			assetManager.finishLoading();
		}
		sound = assetManager.get(soundFile, Sound.class);
	}

	@Override
	public void addActivatable(Activatable a) {
		if (startState == State.ON) {
			a.activate();
		} else {
			a.deactivate();
		}
		activatables.add(a);
	}

	@Override
	public void handleBeginCollision(Contact contact, Ball ball) {
		currentState.start(this);
	}

	@Override
	public void handleEndCollision(Contact contact, Ball ball) {
	}

	@Override
	public void drawBeforeBall(float delta, SpriteBatch batch) {
		currentState.draw(this, delta, batch);
	}

	@Override
	public void drawAfterBall(float delta, SpriteBatch batch) {
	}

	@Override
	public void update(float delta) {
		currentState.update(this, delta);
	}

	@Override
	public void setPlaySound(boolean value) {
		playSound = value;
	}

	@Override
	public void playSound() {
		if (playSound) {
			sound.play();
		}
	}

	@Override
	public void endSound() {
		sound.stop();
	}

	@Override
	public void dispose() {
		graphicOff.dispose();
		graphicOn.dispose();
	}

	private void changeState(State state) {
		currentState = state;
	}

	private static enum State {
		TIMER {
			@Override
			public void update(TimedSwitch s, float delta) {
				s.elapsed += delta;
				if (s.elapsed >= s.interval) {
					s.changeState(s.startState);
					s.elapsed = 0;
					s.startState.toggle(s);
				}
			}

			@Override
			public void draw(TimedSwitch s, float delta, SpriteBatch batch) {
				if (s.startState == ON) {
					s.graphicOff.draw(delta, batch);
				} else {
					s.graphicOn.draw(delta, batch);
				}
			}
		},
		ON {
			@Override
			public void start(TimedSwitch s) {
				s.playSound();
				s.changeState(TIMER);
				toggle(s);
			}

			@Override
			public void toggle(TimedSwitch s) {
				for (Activatable a : s.activatables) {
					a.deactivate();
				}
			}

			@Override
			public void draw(TimedSwitch s, float delta, SpriteBatch batch) {
				s.graphicOn.draw(delta, batch);
			}
		},
		OFF {
			@Override
			public void start(TimedSwitch s) {
				s.playSound();
				s.changeState(TIMER);
				toggle(s);
			}

			@Override
			public void toggle(TimedSwitch s) {
				for (Activatable a : s.activatables) {
					a.activate();
				}
			}

			@Override
			public void draw(TimedSwitch s, float delta, SpriteBatch batch) {
				s.graphicOff.draw(delta, batch);
			}
		};

		public void start(TimedSwitch s) {}
		public void update(TimedSwitch s, float delta) {}
		protected void toggle(TimedSwitch s) {}
		public void draw(TimedSwitch s, float delta, SpriteBatch batch) {}
	}
}


text:
"""Module containing classes to connect to Simian as a Mac client."""

import logging
import os
import os.path
import subprocess
from simian.client import client
from simian.mac.common import hw

MUNKI_CONFIG_PLIST = '/Library/Preferences/ManagedInstalls.plist'

class Error(Exception):
  """Base Error class."""

class BaseSimianClient(object):
  """Base client features in all Mac clients."""

  def GetSystemRootCACertChain(self):
    """Load certificate chain from system.

    Returns:
      str, all X509 root ca certs, or '' if none can be found
    """
    certs = client.SimianClient.GetSystemRootCACertChain(self)
    if certs != '':
      return certs

    try:
      argv = [
          '/usr/bin/security',
          'find-certificate', '-a',
          '-p', '/System/Library/Keychains/SystemRootCertificates.keychain'
      ]
      logging.debug('GetSystemRootCACertChain: Executing %s', argv)
      p = subprocess.Popen(
        argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      (stdout, stderr) = p.communicate()
      rc = p.wait()
    except OSError:
      return ''

    if rc == 0:
      logging.debug(
          'GetSystemRootCACertChain: returning %d bytes', len(stdout))
      return stdout
    else:
      return ''

  def _GetSystemProfile(self):
    """Get hardware profile.

    Returns:
      dict from hw.SystemProfile.GetProfile
    Raises:
      hw.SystemProfilerError: error fetching and parsing System Profiler output.
    """
    sp = hw.SystemProfile(include_only=['network', 'system'])
    profile = sp.GetProfile()
    return profile

class SimianAuthClient(BaseSimianClient, client.SimianAuthClient):
  """Client perform authentication steps with Simian server."""

  def __init__(self, uuid, **kwargs):
    self.uuid = uuid
    client.SimianAuthClient.__init__(self, root_ok=True, **kwargs)

  def _GetPuppetSslDetails(self, cert_fname=None, interactive_user=False):
    """Get Puppet SSL details.

    Args:
      cert_fname: str, optiona, certificate filename.
      interactive_user: bool, optional, default False,
        True if the client user an interactive user who can be prompted
        for auth.
    Returns:
      dict = {
          'cert': str, X509 format client certificate in PEM format,
          'ca_cert': str, X509 format CA certificate in PEM format,
          'priv_key': str, X509 format private key in PEM format,
          'cn': str, commonName of this client's certificate
      }
      or {} if the details cannot be read.
    """
    logging.debug('SimianAuthClient._GetPuppetSslDetails')
    if not cert_fname:
      try:
        facts = self.GetFacter()
      except client.FacterError:
        # don't give up, facter fails from time to time.
        facts = {}
      cert_name = facts.get('certname', None)
      logging.debug('Certname from facter: "%s"', cert_name)
      if not cert_name:
        logging.warning('Certname was not found in facter!')
      cert_fname = '%s.pem' % cert_name
    return super(SimianAuthClient, self)._GetPuppetSslDetails(
        cert_fname=cert_fname, interactive_user=interactive_user)