text: :root .alert-message, :root .btn { border-radius:0 \0; }

redpajama_set_name: RedPajamaGithub


text:
namespace dragonBones.phaser {
    export class Factory extends BaseFactory {
        protected _scene: Phaser.Scene;
        protected _dragonBones: DragonBones;

        constructor(dragonBones: DragonBones, scene: Phaser.Scene, dataParser?: DataParser) {
            super(dataParser);
            this._scene = scene;
            this._dragonBones = dragonBones;
        }

        protected _isSupportMesh(): boolean {
            return true;
        }

        protected _buildTextureAtlasData(textureAtlasData: display.TextureAtlasData, textureAtlas: Phaser.Textures.Texture): TextureAtlasData {
            if (textureAtlasData) {
                textureAtlasData.renderTexture = textureAtlas;
            } else
                textureAtlasData = BaseObject.borrowObject(display.TextureAtlasData);

            return textureAtlasData;
        }

        protected _buildArmature(dataPackage: BuildArmaturePackage): Armature {
            const armature = BaseObject.borrowObject(Armature);
            const armatureDisplay = new display.ArmatureDisplay(this._scene);

            armature.init(
                dataPackage.armature,
                armatureDisplay, armatureDisplay, this._dragonBones
            );

            return armature;
        }

        protected _buildSlot(dataPackage: BuildArmaturePackage, slotData: SlotData, armature: Armature): Slot {
            const slot = BaseObject.borrowObject(display.Slot);
            const rawDisplay = this._scene.dragonbone.createSlotDisplayPlaceholder();
            const meshDisplay = this._scene.dragonbone.createMeshDisplayPlaceholder();
            slot.init(slotData, armature, rawDisplay, meshDisplay);

            return slot;
        }

        // dragonBonesName must be assigned, or can't find in cache inside
        buildArmatureDisplay(armatureName: string, dragonBonesName: string, skinName: string = "", textureAtlasName: string = "", textureScale = 1.0): display.ArmatureDisplay {
            let armature: dragonBones.Armature;

            if (this.buildDragonBonesData(dragonBonesName, textureScale)) {
                armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName);
            }

            return armature.display as display.ArmatureDisplay;
        }

        buildDragonBonesData(dragonBonesName: string, textureScale = 1.0): DragonBonesData {
            let data = this._dragonBonesDataMap[dragonBonesName];
            if (!data) {
                const cache = this._scene.cache;
                const boneRawData: any = cache.custom.dragonbone.get(dragonBonesName);
                if (boneRawData) {
                    // parse raw data and add to cache map
                    data = this.parseDragonBonesData(boneRawData, dragonBonesName, textureScale);

                    const texture = this._scene.textures.get(dragonBonesName);
                    const json = cache.json.get(`${dragonBonesName}_atlasjson`);

                    this.parseTextureAtlasData(json, texture, texture.key, textureScale);
                }
            }
            return data;
        }

        /**
         * - A global sound event manager.
         * Sound events can be listened to uniformly from the manager.
         * @version DragonBones 4.5
         * @language en_US
         */
        public get soundEventManager(): display.ArmatureDisplay {
            return this._dragonBones.eventManager as display.ArmatureDisplay;
        }
    }
}


text:
/*
 * arch/arm/plat-orion/irq.c
 *
 * Marvell Orion SoC IRQ handling.
 *
 * This file is licensed under the terms of the GNU General Public
 * License version 2.  This program is licensed "as is" without any
 * warranty of any kind, whether express or implied.
 */

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/io.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/exception.h>
#include <plat/irq.h>
#include <plat/orion-gpio.h>
#include <mach/bridge-regs.h>

#ifdef CONFIG_MULTI_IRQ_HANDLER
/*
 * Compiling with both non-DT and DT support enabled, will
 * break asm irq handler used by non-DT boards. Therefore,
 * we provide a C-style irq handler even for non-DT boards,
 * if MULTI_IRQ_HANDLER is set.
 *
 * Notes:
 * - this is prepared for Kirkwood and Dove only, update
 *   accordingly if you add Orion5x or MV78x00.
 * - Orion5x uses different macro names and has only one
 *   set of CAUSE/MASK registers.
 * - MV78x00 uses the same macro names but has a third
 *   set of CAUSE/MASK registers.
 *
 */

static void __iomem *orion_irq_base = IRQ_VIRT_BASE;

asmlinkage void
__exception_irq_entry orion_legacy_handle_irq(struct pt_regs *regs)
{
	u32 stat;

	stat = readl_relaxed(orion_irq_base + IRQ_CAUSE_LOW_OFF);
	stat &= readl_relaxed(orion_irq_base + IRQ_MASK_LOW_OFF);
	if (stat) {
		unsigned int hwirq = __fls(stat);
		handle_IRQ(hwirq, regs);
		return;
	}
	stat = readl_relaxed(orion_irq_base + IRQ_CAUSE_HIGH_OFF);
	stat &= readl_relaxed(orion_irq_base + IRQ_MASK_HIGH_OFF);
	if (stat) {
		unsigned int hwirq = 32 + __fls(stat);
		handle_IRQ(hwirq, regs);
		return;
	}
}
#endif

void __init orion_irq_init(unsigned int irq_start, void __iomem *maskaddr)
{
	struct irq_chip_generic *gc;
	struct irq_chip_type *ct;

	/*
	 * Mask all interrupts initially.
	 */
	writel(0, maskaddr);

	gc = irq_alloc_generic_chip("orion_irq", 1, irq_start, maskaddr,
				    handle_level_irq);
	ct = gc->chip_types;
	ct->chip.irq_mask = irq_gc_mask_clr_bit;
	ct->chip.irq_unmask = irq_gc_mask_set_bit;
	irq_setup_generic_chip(gc, IRQ_MSK(32), IRQ_GC_INIT_MASK_CACHE,
			       IRQ_NOREQUEST, IRQ_LEVEL | IRQ_NOPROBE);

#ifdef CONFIG_MULTI_IRQ_HANDLER
	set_handle_irq(orion_legacy_handle_irq);
#endif
}

#ifdef CONFIG_OF
static int __init orion_add_irq_domain(struct device_node *np,
				       struct device_node *interrupt_parent)
{
	int i = 0;
	void __iomem *base;

	do {
		base = of_iomap(np, i);
		if (base) {
			orion_irq_init(i * 32, base + 0x04);
			i++;
		}
	} while (base);

	irq_domain_add_legacy(np, i * 32, 0, 0,
			      &irq_domain_simple_ops, NULL);
	return 0;
}

static const struct of_device_id orion_irq_match[] = {
	{ .compatible = "marvell,orion-intc",
	  .data = orion_add_irq_domain, },
	{},
};

void __init orion_dt_init_irq(void)
{
	of_irq_init(orion_irq_match);
}
#endif


text:
selected_army = {	status = false,
					subj = nil}

-- so heres how this works
-- every time a click happens, each gui element is checked to see if it should respond to the click
-- if so, it responds.
function selected_army.check( x, y, button)
	if button == "l" then
		local on_army = false
		for i = 1, #game.regiments do
			if x + land.display_x > game.regiments[i].loc[1] - 7 and x + land.display_x < game.regiments[i].loc[1] + 7 then
				if y + land.display_y + 25 > game.regiments[i].loc[2] - 16 and y + land.display_y - 25 < game.regiments[i].loc[2] + 16 then
					msg_area.update(false, "clicked "..game.regiments[i].name)
					selected_army.create(game.regiments[i])
					on_army = true
				end
			end
		end
		if not on_army then selected_army.destroy() end
	elseif button == "r" and selected_army.status then
		local from = 	{ math.floor( selected_army.subj.loc[1] / tile_width) + 1 , math.floor(selected_army.subj.loc[2] / tile_height) }
		local to = 		{ math.floor( (x + land.display_x) / tile_width) + 1, math.floor( ( y + land.display_y) / tile_height ) }
		-- holding down shift suppresses pathfinding
		if love.keyboard.isDown("rshift") or love.keyboard.isDown("lshift") then
			if not selected_army.subj.dest then
				selected_army.subj.dest = { to }
			else
				table.insert( selected_army.subj.dest, to )
			end
		else
			if not selected_army.subj.dest then
				selected_army.subj.dest = path.dijkstra( from, to )
			else
				if node.dist_euclid( selected_army.subj.dest[#selected_army.subj.dest], to) > 50 then
					selected_army.subj.dest = path.dijkstra( from, to )
				end
			end
		end
	end
end

function selected_army.create( s )
	selected_army.subj = s
	selected_army.status = true
end

function selected_army.destroy()
	selected_army.subj = nil
	selected_army.status = false
end

function selected_army.update()
	-- empty
end

function selected_army.draw()
	local temp = selected_army.subj
	if temp.loc[1] > land.display_x and temp.loc[1] < land.display_x + (display_w * tile_height) and temp.loc[2] > land.display_y and temp.loc[2] < land.display_y + ( tile_height * display_h) then
		love.graphics.setColor(0, 0, 0)
		love.graphics.rectangle("fill", temp.loc[1] - land.display_x + 10, temp.loc[2] - land.display_y - 60, 150, 70 )
		love.graphics.setColor(255, 255, 255)
		love.graphics.print(temp.name, temp.loc[1] - land.display_x + 15, temp.loc[2] - land.display_y - 55)
		love.graphics.print("Discipline: ", temp.loc[1] - land.display_x + 15, temp.loc[2] - land.display_y - 40)
		if temp.discipline > .8 then
			love.graphics.setColor(0, 255, 0)
		else
			love.graphics.setColor(255, 0, 0)
		end
		love.graphics.print(temp.discipline , temp.loc[1] - land.display_x + 80, temp.loc[2] - land.display_y - 40)
		love.graphics.setColor(255, 255, 255)
		love.graphics.print("Atk/Def: "..temp.attack.."/"..temp.defense, temp.loc[1] - land.display_x + 15, temp.loc[2] - land.display_y - 25)
		love.graphics.print(land.get_tile( temp.loc, true).t, temp.loc[1] - land.display_x + 15, temp.loc[2] - land.display_y - 10)
	end
end


text:
/* bb main containers */
body {
    margin: 0;
    font-family: Arial, Helvetica;
    font-size:16px;
	background: white;
    color: black;
    overflow-x: hidden;
}

div#pageTitle {
	background: black;
    width: auto;
}

div#pageTitle h1 {
	margin: 0;
	padding: 4px;
    width: auto;
    font-size: 16px;
    max-height: 16px;
    font-weight: normal;
    text-align: left;
    white-space: nowrap;
    color: white;
    font-weight: bold;
}

/*toolbar */
div#toolbar{
	border-bottom:1px solid lightgray;
	height: 25px;
	line-height: 25px;
	padding-left: 4px;
	width:100%;
}

div#toolbar .noButton {
    display:hidden;
}

/*content div styling*/
div#content h2 {
	font-size:15px;
	display:block;
	margin:4px;
}

div#content h2.groupTitle{
	background:black;
	height:14px;
	font-size:10px;
	padding:5px;
	border-bottom:1px solid lightgray;
}

div#content div.alert{
	color:red;
}

div#content div.warning{
	margin-left:4px;
}

div#content p{
	font-size:14px;
}

/* bb table styles */

div#content table {
    display:block;
	border:none;
	border-spacing:0;
    font-size: 80%;
    width:100%;
}

div#content table th {
	width:100%;
	display: block;
	border-bottom:1px solid #BBBBBB;
}

div#content table tr {
    width:100%;
}
div#content table tr td {
	margin:0;
    border-bottom:1px solid lightgray;
	height: 25px;
	line-height:25px;
}

div#content table tr td a {
	text-decoration: none;
	font-weight:bold;
	color:black;
	display:block;
	overflow: hidden;
}

div#content table tr td.recordLabel {
    width:100%;
}

div#content table tr td.itemLabel {
    width:50%;
    font-weight:bold;
}

div#content table tr td.itemValue {
    width:50%;
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Map Demo 4</title>
<link href="default.css" rel="stylesheet">

      <button onclick="toggleHeatmap()">Toggle Heatmap</button>
      <button onclick="changeGradient()">Change gradient</button>
      <button onclick="changeRadius()">Change radius</button>
      <button onclick="changeOpacity()">Change opacity</button>


text:
require 'pdq'

# Measured performance parameters

cpusPerServer = 4
emailThruput  = 2376 # emails per hour
scannerTime   = 6.0  # seconds per email

Pdq.Init("Spam Farm Model")

# Timebase is SECONDS ...

nstreams = Pdq.CreateOpen("Email", emailThruput/3600.0)
nnodes   = Pdq.CreateNode("spamCan", cpusPerServer, Pdq::MSQ)

Pdq.SetDemand("spamCan", "Email", scannerTime)

Pdq.Solve(Pdq::CANON)

Pdq.Report()


text:
package com.siyeh.igtest.style.redundant_implements;

import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;

class RedundantImplementsInspection extends ArrayList implements <warning descr="Redundant interface declaration 'List'">List</warning>, <warning descr="Redundant interface declaration 'Serializable'">Serializable</warning>{
}


text:
package com.wangsanshi.weather.entity;

import cn.bmob.v3.BmobObject;

public class FeedBack extends BmobObject {
    private String title;

    private String content;

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setContent(String content) {
        this.content = content;
    }
}


text:
package model.utilities.stats.processes;

import com.google.common.base.Objects;
import model.utilities.ActionOrder;
import model.utilities.pid.PIDController;
import model.utilities.stats.regression.SISORegression;

import java.math.RoundingMode;

/**
 *
Description

 *
 This really represents 1 step of the gradient descend. We try to minimize the
 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author carrknight
 * @version 2014-07-10
 * @see
 */
public class PIGradientDescent
{

    private final SISORegression systemRegression;

    private final PIDController originalController;

    private final double desiredTarget;

    private final int howManyStepsToSimulate;

    private final double derivativeStepSize; //.01?

    private final double maximizationStepSize;

    private final static double STEP_SIZE_LIMIT = .05;

    private final double covariants[];

    public PIGradientDescent(SISORegression systemRegression, PIDController originalController, double desiredTarget, double... covariants) {
        this(systemRegression,originalController,desiredTarget,100,.01,.0001,covariants);
    }

    public PIGradientDescent(SISORegression systemRegression, PIDController originalController, double desiredTarget, int howManyStepsToSimulate,
                             double derivativeStepSize, double maximizationStepSize, double... covariants) {
        this.systemRegression = systemRegression;
        this.originalController = originalController;
        this.desiredTarget = desiredTarget;
        this.howManyStepsToSimulate = howManyStepsToSimulate;
        this.derivativeStepSize = derivativeStepSize;
        this.maximizationStepSize = maximizationStepSize;
        this.covariants = covariants;
    }

    /**
     * computes ITAE of this pid controller with this process. The PID controller gets stepped on and is modified so supply a clone, not the original. Same thing for the dynamic process.
     * @param pid the pid controller to use
     * @param process the process that governs the outside world
     * @param desiredTarget the pid target
     * @param howManyStepsToSimulate how far into the future to simulate
     * @param covariants additional variable to feed the dynamic process  @return the integral time absolute error of this pid with this process
     */
    public static double computeITAE(PIDController pid, DynamicProcess process, float desiredTarget, int howManyStepsToSimulate,
                                     double... covariants)
    {
        double errorSum =0;
        for(int t=1; t<=howManyStepsToSimulate; t++)
        {
            float output = (float) Math.max(process.newStep(pid.getCurrentMV(),covariants),0);
            int speed = pid.getSpeed() + 1;
            if(t % (speed) == 0 )
                pid.adjust(desiredTarget,output,true,null,null, ActionOrder.DAWN);
            errorSum += t * Math.abs(output-desiredTarget);
        }

        return errorSum;

    }

    public PIDGains getNewGains()
    {

        double originalITAE = computeITAE(new PIDController(originalController),systemRegression.generateDynamicProcessImpliedByRegression(),
                (float) desiredTarget,howManyStepsToSimulate, covariants);
        //   System.out.println(originalITAE);

        /***
         *     .----------------.
         *    | .--------------. |
         *    | |   ______     | |
         *    | |  |_   __ \   | |
         *    | |    | |__) |  | |
         *    | |    |  ___/   | |
         *    | |   _| |_      | |
         *    | |  |_____|     | |
         *    | |              | |
         *    | '--------------' |
         *     '----------------'
         */
        PIDController pIncreasedPID = new PIDController(originalController); pIncreasedPID.setGains((float) (originalController.getProportionalGain()+derivativeStepSize),originalController.getIntegralGain(),originalController.getDerivativeGain());
        double pIncreasedITAE = computeITAE(pIncreasedPID,systemRegression.generateDynamicProcessImpliedByRegression(),
                (float) desiredTarget,howManyStepsToSimulate, covariants);
        PIDController pDecreasedPID = new PIDController(originalController); pDecreasedPID.setGains((float) (originalController.getProportionalGain()-derivativeStepSize),originalController.getIntegralGain(),originalController.getDerivativeGain());
        double pDecreasedITAE = computeITAE(pDecreasedPID,systemRegression.generateDynamicProcessImpliedByRegression(),
                (float) desiredTarget,howManyStepsToSimulate, covariants);
        double pDerivative = (pIncreasedITAE-pDecreasedITAE)/(2*derivativeStepSize);
        if(!Double.isFinite(pDerivative))
            pDerivative = 0;
        /***
         *     .----------------.
         *    | .--------------. |
         *    | |     _____    | |
         *    | |    |_   _|   | |
         *    | |      | |     | |
         *    | |      | |     | |
         *    | |     _| |_    | |
         *    | |    |_____|   | |
         *    | |              | |
         *    | '--------------' |
         *     '----------------'
         */
        PIDController iIncreasedPID = new PIDController(originalController); iIncreasedPID.setGains(originalController.getProportionalGain(),(float) (originalController.getIntegralGain()+derivativeStepSize),originalController.getDerivativeGain());
        double iIncreasedITAE = computeITAE(iIncreasedPID,systemRegression.generateDynamicProcessImpliedByRegression(),
                (float) desiredTarget,howManyStepsToSimulate, covariants);
        PIDController iDecreasedPID = new PIDController(originalController); iDecreasedPID.setGains(originalController.getProportionalGain(),(float) (originalController.getIntegralGain()-derivativeStepSize),originalController.getDerivativeGain());
        double iDecreasedITAE = computeITAE(iDecreasedPID,systemRegression.generateDynamicProcessImpliedByRegression(),
                (float) desiredTarget,howManyStepsToSimulate, covariants);
        double iDerivative = (iIncreasedITAE-iDecreasedITAE)/(2*derivativeStepSize);
        if(!Double.isFinite(iDerivative))
            iDerivative = 0;

        //return x + alpha * nablaX
        boolean tuneP = Math.abs(pDerivative) >= Math.abs(iDerivative);
        final double pStep = tuneP ?  Math.signum(pDerivative) * Math.min(Math.abs(maximizationStepSize * pDerivative), STEP_SIZE_LIMIT) : 0;
        final double iStep = tuneP ? 0 : Math.signum(iDerivative) * Math.min(Math.abs(maximizationStepSize * iDerivative), STEP_SIZE_LIMIT);
        return new PIDGains( (float)(originalController.getProportionalGain() - pStep),
                (float) (originalController.getIntegralGain() - iStep),
                originalController.getDerivativeGain());

    }

    public static class PIDGains{

        private final static RoundingMode rounder = RoundingMode.HALF_UP;

        private final float proportional;

        private final float integral;

        private final float derivative;

        public PIDGains(float proportional, float integral, float derivative) {
            this.proportional =  Math.max(proportional,0);
            this.integral = Math.max(integral,0);
            this.derivative = Math.max(derivative,0);
        }

        public float getProportional() {
            return proportional;
        }

        public float getIntegral() {
            return integral;
        }

        public float getDerivative() {
            return derivative;
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .add("proportional", proportional)
                    .add("integral", integral)
                    .add("derivative", derivative)
                    .toString();
        }
    }

}


text:
import { IFilter, matchesFuzzy, matchesFuzzy2 } from 'vs/base/common/filters';
import { IExpression, splitGlobAware, getEmptyExpression } from 'vs/base/common/glob';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { ResourceGlobMatcher } from 'vs/base/common/resources';

export class FilterOptions {

	static readonly _filter: IFilter = matchesFuzzy2;
	static readonly _messageFilter: IFilter = matchesFuzzy;

	readonly showWarnings: boolean = false;
	readonly showErrors: boolean = false;
	readonly showInfos: boolean = false;
	readonly textFilter: string = '';
	readonly excludesMatcher: ResourceGlobMatcher;
	readonly includesMatcher: ResourceGlobMatcher;

	constructor(readonly filter: string = '', filesExclude: { root: URI, expression: IExpression }[] | IExpression = [], showWarnings: boolean = false, showErrors: boolean = false, showInfos: boolean = false) {
		filter = filter.trim();
		this.showWarnings = showWarnings;
		this.showErrors = showErrors;
		this.showInfos = showInfos;

		const filesExcludeByRoot = Array.isArray(filesExclude) ? filesExclude : [];
		const excludesExpression: IExpression = Array.isArray(filesExclude) ? getEmptyExpression() : filesExclude;

		const includeExpression: IExpression = getEmptyExpression();
		if (filter) {
			const filters = splitGlobAware(filter, ',').map(s => s.trim()).filter(s => !!s.length);
			for (const f of filters) {
				if (strings.startsWith(f, '!')) {
					this.setPattern(excludesExpression, strings.ltrim(f, '!'));
				} else {
					this.setPattern(includeExpression, f);
					this.textFilter += ` ${f}`;
				}
			}
		}

		this.excludesMatcher = new ResourceGlobMatcher(excludesExpression, filesExcludeByRoot);
		this.includesMatcher = new ResourceGlobMatcher(includeExpression, []);
		this.textFilter = this.textFilter.trim();
	}

	private setPattern(expression: IExpression, pattern: string) {
		if (pattern[0] === '.') {
			pattern = '*' + pattern; // convert ".js" to "*.js"
		}
		expression[`**/${pattern}/**`] = true;
		expression[`**/${pattern}`] = true;
	}
}


text: __author__ = 'posborne'


text:
import { Config } from './config';
import * as util from './util';

/**
 * Cleans the top level dist folder. All npm-ready packages are created
 * in the dist folder.
 */
export function removeDistFolder(config: Config) {
  return util.exec('rimraf', ['./dist']);
}

/**
 * Uses the 'tsconfig-build.json' file in each package directory to produce
 * AOT and Closure compatible JavaScript
 */
export async function compilePackagesWithNgc(config: Config) {
  const pkgs = util.getTopLevelPackages(config);
  const storePkg = 'store';
  const restPkgs = pkgs.filter(name => name !== storePkg);
  const testPkgs = util.getTestingPackages(config);

  await _compilePackagesWithNgc(storePkg);
  await mapAsync(restPkgs, _compilePackagesWithNgc);
  await mapAsync(testPkgs, _compilePackagesWithNgc);
}

async function _compilePackagesWithNgc(pkg: string) {
  await util.exec('ngc', [`-p ./modules/${pkg}/tsconfig-build.json`]);

  /**
   * Test modules are treated differently because nested inside top-level.
   * This step removes the top-level package from testing modules from the
   * export statement.
   * Also changes the module name from 'index' to 'testing'
   * i.e. export * from './effects/testing/index' becomes './testing/testing';
   *
   * See https://github.com/ngrx/platform/issues/94
   */
  let [exportPath, moduleName] = /\/testing$/.test(pkg)
    ? [pkg.replace(/(.*\/)testing/i, 'testing'), 'testing']
    : [pkg, 'index'];

  const entryTypeDefinition = `export * from './${exportPath}/${moduleName}';`;
  const entryMetadata = `{"__symbolic":"module","version":3,"metadata":{},"exports":[{"from":"./${pkg}/index"}]}`;

  await Promise.all([
    util.writeFile(`./dist/packages/${pkg}.d.ts`, entryTypeDefinition),
    util.writeFile(`./dist/packages/${pkg}.metadata.json`, entryMetadata),
  ]);
}

/**
 * Uses Rollup to bundle the JavaScript into a single flat file called
 * a FESM (Flat Ecma Script Module)
 */
export async function bundleFesms(config: Config) {
  const pkgs = util.getAllPackages(config);

  await mapAsync(pkgs, async pkg => {
    const topLevelName = util.getTopLevelName(pkg);

    await util.exec('rollup', [
      `-i ./dist/packages/${pkg}/index.js`,
      `-o ./dist/${topLevelName}/${config.scope}/${pkg}.js`,
      `-f es`,
      `--sourcemap`,
    ]);

    await util.mapSources(`./dist/${topLevelName}/${config.scope}/${pkg}.js`);
  });
}

/**
 * Copies each FESM into a TS file then uses TypeScript to downlevel
 * the FESM into ES5 with ESM modules
 */
export async function downLevelFesmsToES5(config: Config) {
  const packages = util.getAllPackages(config);
  const tscArgs = ['--target es5', '--module es2015', '--noLib', '--sourceMap'];

  await mapAsync(packages, async pkg => {
    const topLevelName = util.getTopLevelName(pkg);

    const file = `./dist/${topLevelName}/${config.scope}/${pkg}.js`;
    const target = `./dist/${topLevelName}/${config.scope}/${pkg}.es5.ts`;

    await util.copy(file, target);
    await util.ignoreErrors(util.exec('tsc', [target, ...tscArgs]));
    await util.mapSources(target.replace('.ts', '.js'));
    await util.remove(target);
  });

  await util.removeRecursively(`./dist/**/*/${config.scope}/*.ts`);
}

/**
 * Re-runs Rollup on the downleveled ES5 to produce a UMD bundle
 */
export async function createUmdBundles(config: Config) {
  await mapAsync(util.getAllPackages(config), async pkg => {
    const topLevelName = util.getTopLevelName(pkg);
    const destinationName = util.getDestinationName(pkg);

    const rollupArgs = [`-c ./modules/${pkg}/rollup.config.js`, `--sourcemap`];

    await util.exec('rollup', rollupArgs);
    await util.mapSources(
      `./dist/${topLevelName}/bundles/${destinationName}.umd.js`
    );
  });
}

/**
 * Removes any leftover TypeScript files from previous compilation steps,
 * leaving any type definition files in place
 */
export async function cleanTypeScriptFiles(config: Config) {
  const tsFilesGlob = './dist/packages/**/*.ts';
  const dtsFilesFlob = './dist/packages/**/*.d.ts';
  const filesToRemove = await util.getListOfFiles(tsFilesGlob, dtsFilesFlob);

  await mapAsync(filesToRemove, util.remove);
}

/**
 * Renames the index files in each package to the name
 * of the package.
 */
export async function renamePackageEntryFiles(config: Config) {
  await mapAsync(util.getAllPackages(config), async pkg => {
    const bottomLevelName = util.getBottomLevelName(pkg);

    const files = await util.getListOfFiles(`./dist/packages/${pkg}/index.**`);

    await mapAsync(files, async file => {
      const target = file.replace('index', bottomLevelName);

      await util.copy(file, target);
      await util.remove(file);
    });
  });
}

/**
 * Removes any remaining source map files from running NGC
 */
export async function removeRemainingSourceMapFiles(config: Config) {
  const packages = util.getTopLevelPackages(config);

  await util.removeRecursively(
    `./dist/packages/?(${packages.join('|')})/**/*.map`
  );
}

/**
 * Copies the type definition files and NGC metadata files to
 * the root of the distribution
 */
export async function copyTypeDefinitionFiles(config: Config) {
  const packages = util.getTopLevelPackages(config);
  const files = await util.getListOfFiles(
    `./dist/packages/?(${packages.join('|')})/**/*.*`
  );

  await mapAsync(files, async file => {
    const target = file.replace('packages/', '');
    await util.copy(file, target);
  });

  await util.removeRecursively(`./dist/packages/?(${packages.join('|')})`);
}

/**
 * Creates minified copies of each UMD bundle
 */
export async function minifyUmdBundles(config: Config) {
  const uglifyArgs = ['-c', '-m', '--screw-ie8', '--comments'];

  await mapAsync(util.getAllPackages(config), async pkg => {
    const topLevelName = util.getTopLevelName(pkg);
    const destinationName = util.getDestinationName(pkg);
    const file = `./dist/${topLevelName}/bundles/${destinationName}.umd.js`;
    const out = `./dist/${topLevelName}/bundles/${destinationName}.umd.min.js`;

    return util.exec('uglifyjs', [
      ...uglifyArgs,
      `-o ${out}`,
      `--source-map ${out}.map`,
      `--source-map-include-sources ${file}`,
      `--in-source-map ${file}.map`,
    ]);
  });
}

/**
 * Copies the README.md, LICENSE, and package.json files into
 * each package
 */
export async function copyDocs(config: Config) {
  const packages = util.getTopLevelPackages(config);

  await mapAsync(packages, async pkg => {
    const source = `./modules/${pkg}`;
    const target = `./dist/${pkg}`;

    await Promise.all([
      util.copy(`${source}/README.md`, `${target}/README.md`),
      util.copy('./LICENSE', `${target}/LICENSE`),
    ]);
  });
}

export async function copyPackageJsonFiles(config: Config) {
  const packages = util.getAllPackages(config);

  await mapAsync(packages, async pkg => {
    const source = `./modules/${pkg}`;
    const target = `./dist/${pkg}`;

    await util.copy(`${source}/package.json`, `${target}/package.json`);
  });
}

/**
 * Removes the packages folder
 */
export async function removePackagesFolder(config: Config) {
  await util.removeRecursively('./dist/packages');
}

/**
 * Deploy build artifacts to repos
 */
export async function publishToRepo(config: Config) {
  for (let pkg of util.getTopLevelPackages(config)) {
    const SOURCE_DIR = `./dist/${pkg}`;
    const REPO_URL = `git@github.com:ngrx/${pkg}-builds.git`;
    const REPO_DIR = `./tmp/${pkg}`;
    const SHA = await util.git([`rev-parse HEAD`]);
    const SHORT_SHA = await util.git([`rev-parse --short HEAD`]);
    const COMMITTER_USER_NAME = await util.git([
      `--no-pager show -s --format='%cN' HEAD`,
    ]);
    const COMMITTER_USER_EMAIL = await util.git([
      `--no-pager show -s --format='%cE' HEAD`,
    ]);

    await util.cmd('rm -rf', [`${REPO_DIR}`]);
    await util.cmd('mkdir ', [`-p ${REPO_DIR}`]);
    await process.chdir(`${REPO_DIR}`);
    await util.git([`init`]);
    await util.git([`remote add origin ${REPO_URL}`]);
    await util.git(['fetch origin master --depth=1']);
    await util.git(['checkout origin/master']);
    await util.git(['checkout -b master']);
    await process.chdir('../../');
    await util.cmd('rm -rf', [`${REPO_DIR}/*`]);
    await util.git([`log --format="%h %s" -n 1 > ${REPO_DIR}/commit_message`]);
    await util.cmd('cp', [`-R ${SOURCE_DIR}/* ${REPO_DIR}/`]);
    await process.chdir(`${REPO_DIR}`);
    await util.git([`config user.name "${COMMITTER_USER_NAME}"`]);
    await util.git([`config user.email "${COMMITTER_USER_EMAIL}"`]);
    await util.git(['add --all']);
    await util.git([`commit -F commit_message`]);
    await util.cmd('rm', ['commit_message']);
    await util.git(['push origin master --force']);
    await process.chdir('../../');
  }
}

export function mapAsync<T>(
  list: T[],
  mapFn: (v: T, i: number) => Promise<any>
) {
  return Promise.all(list.map(mapFn));
}


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.internals.RecordContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * An in-memory LRU cache store similar to {@link MemoryLRUCache} but byte-based, not
 * record based
 *
 * @see org.apache.kafka.streams.state.Stores#create(String)
 */
public class ThreadCache {
    private static final Logger log = LoggerFactory.getLogger(ThreadCache.class);
    private final String name;
    private final long maxCacheSizeBytes;
    private final Map<String, NamedCache> caches = new HashMap<>();
    private final ThreadCacheMetrics metrics;

    // internal stats
    private long numPuts = 0;
    private long numGets = 0;
    private long numEvicts = 0;
    private long numFlushes = 0;

    public interface DirtyEntryFlushListener {
        void apply(final List<DirtyEntry> dirty);
    }

    public ThreadCache(long maxCacheSizeBytes) {
        this(null, maxCacheSizeBytes, null);
    }

    public ThreadCache(final String name, long maxCacheSizeBytes, final ThreadCacheMetrics metrics) {
        this.name = name;
        this.maxCacheSizeBytes = maxCacheSizeBytes;
        this.metrics = metrics != null ? metrics : new NullThreadCacheMetrics();
    }

    public long puts() {
        return numPuts;
    }

    public long gets() {
        return numGets;
    }

    public long evicts() {
        return numEvicts;
    }

    public long flushes() {
        return numFlushes;
    }

    /**
     * Add a listener that is called each time an entry is evicted from the cache or an explicit flush is called
     *
     * @param namespace
     * @param listener
     */
    public void addDirtyEntryFlushListener(final String namespace, DirtyEntryFlushListener listener) {
        final NamedCache cache = getOrCreateCache(namespace);
        cache.setListener(listener);
    }

    public void flush(final String namespace) {
        numFlushes++;

        final NamedCache cache = getCache(namespace);
        if (cache == null) {
            return;
        }
        cache.flush();

        log.debug("Thread {} cache stats on flush: #puts={}, #gets={}, #evicts={}, #flushes={}",
                  name, puts(), gets(), evicts(), flushes());
    }

    public LRUCacheEntry get(final String namespace, byte[] key) {
        numGets++;

        final NamedCache cache = getCache(namespace);
        if (cache == null) {
            return null;
        }
        return cache.get(Bytes.wrap(key));
    }

    public void put(final String namespace, byte[] key, LRUCacheEntry value) {
        numPuts++;
        final NamedCache cache = getOrCreateCache(namespace);
        cache.put(Bytes.wrap(key), value);
        maybeEvict(namespace);
    }

    public LRUCacheEntry putIfAbsent(final String namespace, byte[] key, LRUCacheEntry value) {
        final NamedCache cache = getOrCreateCache(namespace);

        final LRUCacheEntry result = cache.putIfAbsent(Bytes.wrap(key), value);
        maybeEvict(namespace);

        if (result == null) {
            numPuts++;
        }
        return result;
    }

    public void putAll(final String namespace, final List<KeyValue<byte[], LRUCacheEntry>> entries) {
        for (KeyValue<byte[], LRUCacheEntry> entry : entries) {
            put(namespace, entry.key, entry.value);
        }
    }

    public LRUCacheEntry delete(final String namespace, final byte[] key) {
        final NamedCache cache = getCache(namespace);
        if (cache == null) {
            return null;
        }

        return cache.delete(Bytes.wrap(key));
    }

    public MemoryLRUCacheBytesIterator range(final String namespace, final byte[] from, final byte[] to) {
        final NamedCache cache = getCache(namespace);
        if (cache == null) {
            return new MemoryLRUCacheBytesIterator(Collections.<Bytes>emptyIterator(), new NamedCache(namespace));
        }
        return new MemoryLRUCacheBytesIterator(cache.keyRange(cacheKey(from), cacheKey(to)), cache);
    }

    public MemoryLRUCacheBytesIterator all(final String namespace) {
        final NamedCache cache = getCache(namespace);
        if (cache == null) {
            return new MemoryLRUCacheBytesIterator(Collections.<Bytes>emptyIterator(), new NamedCache(namespace));
        }
        return new MemoryLRUCacheBytesIterator(cache.allKeys(), cache);
    }

    public long size() {
        long size = 0;
        for (NamedCache cache : caches.values()) {
            size += cache.size();
            if (isOverflowing(size)) {
                return Long.MAX_VALUE;
            }
        }

        if (isOverflowing(size)) {
            return Long.MAX_VALUE;
        }
        return size;
    }

    private boolean isOverflowing(final long size) {
        return size < 0;
    }

    long sizeBytes() {
        long sizeInBytes = 0;
        for (final NamedCache namedCache : caches.values()) {
            sizeInBytes += namedCache.sizeInBytes();
        }
        return sizeInBytes;
    }

    synchronized void close(final String namespace) {
        final NamedCache removed = caches.remove(namespace);
        if (removed != null) {
            removed.close();
        }
    }

    private void maybeEvict(final String namespace) {
        while (sizeBytes() > maxCacheSizeBytes) {
            final NamedCache cache = getOrCreateCache(namespace);
            // we abort here as the put on this cache may have triggered
            // a put on another cache. So even though the sizeInBytes() is
            // still > maxCacheSizeBytes there is nothing to evict from this
            // namespaced cache.
            if (cache.size() == 0) {
                return;
            }
            log.trace("Thread {} evicting cache {}", name, namespace);
            cache.evict();
            numEvicts++;
        }
    }

    private synchronized NamedCache getCache(final String namespace) {
        return caches.get(namespace);
    }

    private synchronized NamedCache getOrCreateCache(final String name) {
        NamedCache cache = caches.get(name);
        if (cache == null) {
            cache = new NamedCache(name, this.metrics);
            caches.put(name, cache);
        }
        return cache;
    }

    private Bytes cacheKey(final byte[] keyBytes) {
        return Bytes.wrap(keyBytes);
    }

    static class MemoryLRUCacheBytesIterator implements PeekingKeyValueIterator<byte[], LRUCacheEntry> {
        private final Iterator<Bytes> keys;
        private final NamedCache cache;
        private KeyValue<byte[], LRUCacheEntry> nextEntry;

        MemoryLRUCacheBytesIterator(final Iterator<Bytes> keys, final NamedCache cache) {
            this.keys = keys;
            this.cache = cache;
        }

        public byte[] peekNextKey() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return nextEntry.key;
        }

        KeyValue<byte[], LRUCacheEntry> peekNext() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return nextEntry;
        }

        @Override
        public boolean hasNext() {
            if (nextEntry != null) {
                return true;
            }

            while (keys.hasNext() && nextEntry == null) {
                internalNext();
            }

            return nextEntry != null;
        }

        @Override
        public KeyValue<byte[], LRUCacheEntry> next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            final KeyValue<byte[], LRUCacheEntry> result = nextEntry;
            nextEntry = null;
            return result;
        }

        private void internalNext() {
            Bytes cacheKey = keys.next();
            final LRUCacheEntry entry = cache.get(cacheKey);
            if (entry == null) {
                return;
            }

            nextEntry = new KeyValue<>(cacheKey.get(), entry);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("remove not supported by MemoryLRUCacheBytesIterator");
        }

        @Override
        public void close() {
            // do nothing
        }
    }

    public static class DirtyEntry {
        private final Bytes key;
        private final byte[] newValue;
        private final RecordContext recordContext;

        public DirtyEntry(final Bytes key, final byte[] newValue, final RecordContext recordContext) {
            this.key = key;
            this.newValue = newValue;
            this.recordContext = recordContext;
        }

        public Bytes key() {
            return key;
        }

        public byte[] newValue() {
            return newValue;
        }

        public RecordContext recordContext() {
            return recordContext;
        }
    }

    public static class NullThreadCacheMetrics implements ThreadCacheMetrics {
        @Override
        public Sensor addCacheSensor(String entityName, String operationName, String... tags) {
            return null;
        }

        @Override
        public void recordCacheSensor(Sensor sensor, double value) {
            // do nothing
        }

    }

}


text:
DOCUMENTATION = '''
---
module: pvol
author: "Travis Dixon (@thetrav)"
version_added: "0.1"
short_description: Manage LVM physical volumes
requirements: [ lvm2 ]
description:
    - Manage LVM physical volumes
options:
    device:
        required: true
        description:
            - Device to select (eg: /dev/sdb1)
    state:
        default: present
        choices: [ present, absent ]
        description:
            - Device to select (eg: /dev/sdb1)
'''

EXAMPLES = '''
# add a physical volume
- partition: device=/dev/sdb1
# remove a physical volume
- partition: device=/dev/sdb1 state=absent
'''

def read_fixed_width_table(table):
    titles = [title.strip() for title in table[0].split()]

    column_starts = [table[0].index(title) for title in titles]
    column_ends = [num - 1 for num in column_starts[1:]] + [len(table[0])]
    columns = zip(column_starts, column_ends)
    def record(line):
        values = [line[column[0]:column[1]].strip() for column in columns]
        return dict(zip(titles, values))
    return [ record(line) for line in table[1:] ]

class Lvm(object):
    def __init__(self, run_command):
        self.command_runner = run_command

    def run_command(self, cmd):
        rc, stdout, stderr = self.command_runner(cmd)
        if rc != 0:
            raise ValueError("{} {} {} {}".format(rc, stdout, stderr, cmd))
        return (stdout, stderr)

    def refresh(self):
        stdout, stderr = self.run_command("pvs")
        rows = read_fixed_width_table(stdout.split("\n"))
        self.volumes = [row['PV'] for row in rows]

    def set_volume(self, device):
        self.refresh()
        if device in self.volumes:
            return False
        stdout, stderr = self.run_command("pvcreate {}".format(device))
        self.refresh()
        return True

    def remove_volume(self, device):
        self.refresh()
        if device not in self.volumes:
            return False
        stdout, stderr = self.run_command("pvremove {}".format(device))
        self.refresh()
        return True

def main():
    module = AnsibleModule(
        argument_spec = dict(
            device=dict(required=True, type='str'),
            state=dict(default='present', choices=['present', 'absent'], type='str')
        ),
        supports_check_mode=True)
    def param(key):
        return module.params[key]

    result = {}

    lvm = Lvm(module.run_command)
    state = param('state')

    if state == 'present':
        result['changed'] = lvm.set_volume(param('device'))
    if state == 'absent':
        result['changed'] = lvm.remove_volume(param('device'))

    result['pvols'] = lvm.volumes
    module.exit_json(**result)

# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
    main()


text:
/**
 * NodeDraggable
 *
 * @author Joel Kniaz
 */
package gov.va.isaac.gui.querybuilder.node;

import gov.va.isaac.util.ObjectWithTemporaryUniqueId;

/**
 * NodeDraggable
 *
 * @author Joel Kniaz
 *
 */
public interface NodeDraggable extends ObjectWithTemporaryUniqueId {
	enum DragMode { NONE, COPY, MOVE }
	public default DragMode getDragMode() { return DragMode.MOVE; }
	public default NodeDraggable getItemToDrop() { return this; }
	public default String getNodeTypeName() { return getClass().getName().replaceAll(".*\\.", "").replaceAll(".*\\$", ""); }
	public default String getDescription() { return getNodeTypeName(); }
	public default boolean getIsValid() { return true; }
}


text:
namespace v8 {
namespace internal {
namespace compiler {

class BinaryOperationFeedback;
class CallFeedback;
class CompareOperationFeedback;
class ElementAccessFeedback;
class ForInFeedback;
class GlobalAccessFeedback;
class InstanceOfFeedback;
class LiteralFeedback;
class NamedAccessFeedback;
class RegExpLiteralFeedback;
class TemplateObjectFeedback;

class ProcessedFeedback : public ZoneObject {
 public:
  enum Kind {
    kInsufficient,
    kBinaryOperation,
    kCall,
    kCompareOperation,
    kElementAccess,
    kForIn,
    kGlobalAccess,
    kInstanceOf,
    kLiteral,
    kNamedAccess,
    kRegExpLiteral,
    kTemplateObject,
  };
  Kind kind() const { return kind_; }

  FeedbackSlotKind slot_kind() const { return slot_kind_; }
  bool IsInsufficient() const { return kind() == kInsufficient; }

  BinaryOperationFeedback const& AsBinaryOperation() const;
  CallFeedback const& AsCall() const;
  CompareOperationFeedback const& AsCompareOperation() const;
  ElementAccessFeedback const& AsElementAccess() const;
  ForInFeedback const& AsForIn() const;
  GlobalAccessFeedback const& AsGlobalAccess() const;
  InstanceOfFeedback const& AsInstanceOf() const;
  NamedAccessFeedback const& AsNamedAccess() const;
  LiteralFeedback const& AsLiteral() const;
  RegExpLiteralFeedback const& AsRegExpLiteral() const;
  TemplateObjectFeedback const& AsTemplateObject() const;

 protected:
  ProcessedFeedback(Kind kind, FeedbackSlotKind slot_kind);

 private:
  Kind const kind_;
  FeedbackSlotKind const slot_kind_;
};

class InsufficientFeedback final : public ProcessedFeedback {
 public:
  explicit InsufficientFeedback(FeedbackSlotKind slot_kind);
};

class GlobalAccessFeedback : public ProcessedFeedback {
 public:
  GlobalAccessFeedback(PropertyCellRef cell, FeedbackSlotKind slot_kind);
  GlobalAccessFeedback(ContextRef script_context, int slot_index,
                       bool immutable, FeedbackSlotKind slot_kind);
  explicit GlobalAccessFeedback(FeedbackSlotKind slot_kind);  // Megamorphic

  bool IsMegamorphic() const;

  bool IsPropertyCell() const;
  PropertyCellRef property_cell() const;

  bool IsScriptContextSlot() const;
  ContextRef script_context() const;
  int slot_index() const;
  bool immutable() const;

  base::Optional<ObjectRef> GetConstantHint() const;

 private:
  base::Optional<ObjectRef> const cell_or_context_;
  int const index_and_immutable_;
};

class KeyedAccessMode {
 public:
  static KeyedAccessMode FromNexus(FeedbackNexus const& nexus);

  AccessMode access_mode() const;
  bool IsLoad() const;
  bool IsStore() const;
  KeyedAccessLoadMode load_mode() const;
  KeyedAccessStoreMode store_mode() const;

 private:
  AccessMode const access_mode_;
  union LoadStoreMode {
    LoadStoreMode(KeyedAccessLoadMode load_mode);
    LoadStoreMode(KeyedAccessStoreMode store_mode);
    KeyedAccessLoadMode load_mode;
    KeyedAccessStoreMode store_mode;
  } const load_store_mode_;

  KeyedAccessMode(AccessMode access_mode, KeyedAccessLoadMode load_mode);
  KeyedAccessMode(AccessMode access_mode, KeyedAccessStoreMode store_mode);
};

class ElementAccessFeedback : public ProcessedFeedback {
 public:
  ElementAccessFeedback(Zone* zone, KeyedAccessMode const& keyed_mode,
                        FeedbackSlotKind slot_kind);

  KeyedAccessMode keyed_mode() const;

  // A transition group is a target and a possibly empty set of sources that can
  // transition to the target. It is represented as a non-empty vector with the
  // target at index 0.
  using TransitionGroup = ZoneVector<Handle<Map>>;
  ZoneVector<TransitionGroup> const& transition_groups() const;

  bool HasOnlyStringMaps(JSHeapBroker* broker) const;

  void AddGroup(TransitionGroup&& group);

  // Refine {this} by trying to restrict it to the maps in {inferred_maps}. A
  // transition group's target is kept iff it is in {inferred_maps} or if more
  // than one of its sources is in {inferred_maps}. Here's an (unrealistic)
  // example showing all the possible situations:
  //
  // inferred_maps = [a0, a2, c1, c2, d1, e0, e1]
  //
  // Groups before:                     Groups after:
  // [a0, a1, a2]                       [a0, a2]
  // [b0]
  // [c0, c1, c2, c3]                   [c0, c1, c2]
  // [d0, d1]                           [d1]
  // [e0, e1]                           [e0, e1]
  //
  ElementAccessFeedback const& Refine(
      ZoneVector<Handle<Map>> const& inferred_maps, Zone* zone) const;

 private:
  KeyedAccessMode const keyed_mode_;
  ZoneVector<TransitionGroup> transition_groups_;
};

class NamedAccessFeedback : public ProcessedFeedback {
 public:
  NamedAccessFeedback(NameRef const& name, ZoneVector<Handle<Map>> const& maps,
                      FeedbackSlotKind slot_kind);

  NameRef const& name() const { return name_; }
  ZoneVector<Handle<Map>> const& maps() const { return maps_; }

 private:
  NameRef const name_;
  ZoneVector<Handle<Map>> const maps_;
};

class CallFeedback : public ProcessedFeedback {
 public:
  CallFeedback(base::Optional<HeapObjectRef> target, float frequency,
               SpeculationMode mode, FeedbackSlotKind slot_kind)
      : ProcessedFeedback(kCall, slot_kind),
        target_(target),
        frequency_(frequency),
        mode_(mode) {}

  base::Optional<HeapObjectRef> target() const { return target_; }
  float frequency() const { return frequency_; }
  SpeculationMode speculation_mode() const { return mode_; }

 private:
  base::Optional<HeapObjectRef> const target_;
  float const frequency_;
  SpeculationMode const mode_;
};

template <class T, ProcessedFeedback::Kind K>
class SingleValueFeedback : public ProcessedFeedback {
 public:
  explicit SingleValueFeedback(T value, FeedbackSlotKind slot_kind)
      : ProcessedFeedback(K, slot_kind), value_(value) {
    DCHECK(
        (K == kBinaryOperation && slot_kind == FeedbackSlotKind::kBinaryOp) ||
        (K == kCompareOperation && slot_kind == FeedbackSlotKind::kCompareOp) ||
        (K == kForIn && slot_kind == FeedbackSlotKind::kForIn) ||
        (K == kInstanceOf && slot_kind == FeedbackSlotKind::kInstanceOf) ||
        ((K == kLiteral || K == kRegExpLiteral || K == kTemplateObject) &&
         slot_kind == FeedbackSlotKind::kLiteral));
  }

  T value() const { return value_; }

 private:
  T const value_;
};

class InstanceOfFeedback
    : public SingleValueFeedback<base::Optional<JSObjectRef>,
                                 ProcessedFeedback::kInstanceOf> {
  using SingleValueFeedback::SingleValueFeedback;
};

class LiteralFeedback
    : public SingleValueFeedback<AllocationSiteRef,
                                 ProcessedFeedback::kLiteral> {
  using SingleValueFeedback::SingleValueFeedback;
};

class RegExpLiteralFeedback
    : public SingleValueFeedback<JSRegExpRef,
                                 ProcessedFeedback::kRegExpLiteral> {
  using SingleValueFeedback::SingleValueFeedback;
};

class TemplateObjectFeedback
    : public SingleValueFeedback<JSArrayRef,
                                 ProcessedFeedback::kTemplateObject> {
  using SingleValueFeedback::SingleValueFeedback;
};

class BinaryOperationFeedback
    : public SingleValueFeedback<BinaryOperationHint,
                                 ProcessedFeedback::kBinaryOperation> {
  using SingleValueFeedback::SingleValueFeedback;
};

class CompareOperationFeedback
    : public SingleValueFeedback<CompareOperationHint,
                                 ProcessedFeedback::kCompareOperation> {
  using SingleValueFeedback::SingleValueFeedback;
};

class ForInFeedback
    : public SingleValueFeedback<ForInHint, ProcessedFeedback::kForIn> {
  using SingleValueFeedback::SingleValueFeedback;
};

}  // namespace compiler
}  // namespace internal
}  // namespace v8

#endif  // V8_COMPILER_PROCESSED_FEEDBACK_H_


text:
Music-Organiser
===============


text:
//
//  DDChattingModule.h
//  IOSDuoduo
//
//  Created by 独嘉 on 14-5-28.
//  Copyright (c) 2014年 dujia. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DDSessionEntity.h"
#import "DDUserEntity.h"
#define DD_PAGE_ITEM_COUNT                  10

typedef void(^DDReuestServiceCompletion)(DDUserEntity* user);
typedef void(^DDRequestGoodDetailCompletion)(NSDictionary* detail,NSError* error);
@class DDCommodity;
@class DDMessageEntity;
typedef void(^DDChatLoadMoreHistoryCompletion)(NSUInteger addcount, NSError* error);

@interface ChattingModule : NSObject
@property (nonatomic,retain)DDSessionEntity* sessionEntity;
@property (nonatomic,readonly)NSMutableArray* showingMessages;
@property (assign) NSInteger isGroup;
/**
 *  加载历史消息接口,这里会适时插入时间
 *
 *  @param completion 加载完成
 */
- (void)loadMoreHistoryCompletion:(DDChatLoadMoreHistoryCompletion)completion;

- (void)loadHostoryUntilCommodity:(DDMessageEntity*)message completion:(DDChatLoadMoreHistoryCompletion)completion;

- (float)messageHeight:(DDMessageEntity*)message;

- (void)addShowMessage:(DDMessageEntity*)message;
- (void)addShowMessages:(NSArray*)messages;
- (void)requestServicesWithShopID:(NSString*)shopID type:(int)type completion:(DDReuestServiceCompletion)completion;

- (void)requestGoodDetailWithGoodID:(NSString*)googID shopID:(NSString*)shopID completion:(DDRequestGoodDetailCompletion)completion;

- (void)updateSessionUpdateTime:(NSUInteger)time;
- (void)checkBlackList:(NSString *)bid userID:(NSString*)uid Block:(void(^)(bool isBlock))block;

- (void)clearChatData;
- (void)showMessagesAddCommodity:(DDMessageEntity*)message;
-(void)getCurrentUser:(void(^)(DDUserEntity *))block;
@end

@interface DDPromptEntity : NSObject
@property(nonatomic,retain)NSString* message;

@end


text:
#include <aws/appconfigdata/model/ResourceType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace AppConfigData
  {
    namespace Model
    {
      namespace ResourceTypeMapper
      {

        static const int Application_HASH = HashingUtils::HashString("Application");
        static const int ConfigurationProfile_HASH = HashingUtils::HashString("ConfigurationProfile");
        static const int Deployment_HASH = HashingUtils::HashString("Deployment");
        static const int Environment_HASH = HashingUtils::HashString("Environment");
        static const int Configuration_HASH = HashingUtils::HashString("Configuration");

        ResourceType GetResourceTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Application_HASH)
          {
            return ResourceType::Application;
          }
          else if (hashCode == ConfigurationProfile_HASH)
          {
            return ResourceType::ConfigurationProfile;
          }
          else if (hashCode == Deployment_HASH)
          {
            return ResourceType::Deployment;
          }
          else if (hashCode == Environment_HASH)
          {
            return ResourceType::Environment;
          }
          else if (hashCode == Configuration_HASH)
          {
            return ResourceType::Configuration;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ResourceType>(hashCode);
          }

          return ResourceType::NOT_SET;
        }

        Aws::String GetNameForResourceType(ResourceType enumValue)
        {
          switch(enumValue)
          {
          case ResourceType::Application:
            return "Application";
          case ResourceType::ConfigurationProfile:
            return "ConfigurationProfile";
          case ResourceType::Deployment:
            return "Deployment";
          case ResourceType::Environment:
            return "Environment";
          case ResourceType::Configuration:
            return "Configuration";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ResourceTypeMapper
    } // namespace Model
  } // namespace AppConfigData
} // namespace Aws


text:
package com.adobe.acs.commons.mcp.impl.processes;

import com.adobe.acs.commons.fam.ActionManager;
import com.adobe.acs.commons.mcp.ProcessDefinition;
import com.adobe.acs.commons.mcp.ProcessInstance;
import com.adobe.acs.commons.mcp.form.FormField;
import com.adobe.acs.commons.mcp.impl.ProcessInstanceImpl;
import com.adobe.acs.commons.util.visitors.TreeFilteringResourceVisitor;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;

/**
 * Removes archived process instances.
 */
public class ProcessCleanup extends ProcessDefinition {
    @FormField(
            name = "Age",
            description = "Minimum age (in days) to be considered for removal.",
            hint = "e.g. 7 will remove anything from a week ago or earlier",
            options = {"default=7"}
    )
    public int miniumumAge;

    @Override
    public void buildProcess(ProcessInstance instance, ResourceResolver rr) throws LoginException, RepositoryException {
        instance.defineAction("Remove old instances", rr, this::performCleanupActivity);
    }

    @Override
    public void storeReport(ProcessInstance instance, ResourceResolver rr) throws RepositoryException, PersistenceException {
        // No report, do nothing.
    }

    @Override
    public void init() throws RepositoryException {
        // No init needed, do nothing.
    }

    @SuppressWarnings("squid:S00112")
    private void performCleanupActivity(ActionManager manager) throws Exception {
        Calendar c = Calendar.getInstance();
        c.clear(Calendar.HOUR_OF_DAY);
        c.clear(Calendar.MINUTE);
        c.clear(Calendar.SECOND);
        c.add(Calendar.DATE, -miniumumAge); // minus 1 day
        manager.withResolver(rr->{
            TreeFilteringResourceVisitor visitor = new TreeFilteringResourceVisitor();
            visitor.setLeafVisitor((res,level)->{
                if (isCreatedDateBefore(res, c)) {
                    String path = res.getPath();
                    manager.deferredWithResolver(rr2->{
                        rr2.delete(rr2.getResource(path));
                    });
                }
            });
            visitor.accept(rr.getResource(ProcessInstanceImpl.BASE_PATH));
        });
    }

    private boolean isCreatedDateBefore(Resource res, Calendar threshold) {
        Date created = res.getValueMap().get(JcrConstants.JCR_CREATED, Date.class);
        Calendar createDate = Calendar.getInstance();
        createDate.setTime(created);
        return createDate.before(threshold);
    }
}


text:
// ----------------------------------------------------------------------
// This code is developed as part of the Java CoG Kit project
// The terms of the license can be found at http://www.cogkit.org/license
// This message may not be removed or altered.
// ----------------------------------------------------------------------

package org.globus.cog.abstraction.impl.execution.gt2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.globus.cog.abstraction.impl.common.task.SecurityContextImpl;
import org.globus.cog.abstraction.interfaces.Delegation;
import org.globus.cog.abstraction.interfaces.ServiceContact;
import org.globus.gsi.GlobusCredential;
import org.globus.gsi.gssapi.GlobusGSSCredentialImpl;
import org.globus.gsi.gssapi.auth.Authorization;
import org.globus.gsi.gssapi.auth.HostAuthorization;
import org.gridforum.jgss.ExtendedGSSManager;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;

public class GlobusSecurityContextImpl extends SecurityContextImpl implements Delegation {
    public static final Logger logger = Logger.getLogger(GlobusSecurityContextImpl.class);

    public static final int XML_ENCRYPTION = 1;
    public static final int XML_SIGNATURE = 2;

    public static final String PROXY_HOST_PATH_MAPPING_FILE = System.getProperty("user.home") +
        File.separator + ".globus" + File.separator + "proxy.mapping";

    public static final int DEFAULT_CREDENTIAL_REFRESH_INTERVAL = 30000;
    private static Map<String, GSSCredential> cachedCredentials = new HashMap<String, GSSCredential>();
    private static Map<String, Long> credentialTimes = new HashMap<String, Long>();

    private static Properties proxyPaths;

    public GlobusSecurityContextImpl() {
    }

    public GlobusSecurityContextImpl(String proxyPath) {
        if (proxyPath == null) {
            setCredentials(getDefaultCredentials());
        }
        else {
            setCredentials(loadProxyFromFile(proxyPath));
        }
    }

    public void setAuthorization(Authorization authorization) {
        setAttribute("authorization", authorization);
    }

    public Authorization getAuthorization() {
        Authorization authorization = (Authorization) getAttribute("authorization");
        if (authorization == null) {
            authorization = HostAuthorization.getInstance();
        }
        return authorization;
    }

    public void setXMLSec(int xml_security) {
        setAttribute("xml_security", new Integer(xml_security));
    }

    public int getXMLSec() {
        Integer value = (Integer) getAttribute("xml_security");
        if (value == null) {
            return GlobusSecurityContextImpl.XML_SIGNATURE;
        }
        return value.intValue();
    }

    public void setDelegation(int delegation) {
        setAttribute("delegation", new Integer(delegation));
    }

    public int getDelegation() {
        Integer value = (Integer) getAttribute("delegation");
        if (value == null) {
            return GlobusSecurityContextImpl.PARTIAL_DELEGATION;
        }
        return value.intValue();
    }

    public GSSCredential getDefaultCredentials() {
        return _getDefaultCredential(getServiceContact());
    }

    @Override
    public Object getCredentials() {
        Object credentials = super.getCredentials();
        if (credentials == null) {
            return getDefaultCredentials();
        }
        else {
            return credentials;
        }
    }

    public static GSSCredential _getDefaultCredential(ServiceContact serviceContact) {
        String host = null;
        if (serviceContact != null) {
            // null is OK
            host = serviceContact.getHost();
        }
        loadProxyPaths();
        synchronized (cachedCredentials) {
            GSSCredential cachedCredential = cachedCredentials.get(host);
            Long credentialTime = credentialTimes.get(host);
            long now = System.currentTimeMillis();
            if (cachedCredential == null || (now - credentialTime) > DEFAULT_CREDENTIAL_REFRESH_INTERVAL) {
                if (cachedCredential == null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("No cached credentials for " + host + ".");
                    }
                }
                else {
                    if (logger.isInfoEnabled()) {
                        logger.info("Credentials for " + host + " need refreshing.");
                    }
                }
                credentialTimes.put(host, now);
                cachedCredential = loadCredential(host);
                cachedCredentials.put(host, cachedCredential);
            }
            return cachedCredential;
        }
    }

    private static GSSCredential loadCredential(String host) {
        String proxyPath = null;

        if (host != null) {
            proxyPath = (String) proxyPaths.get(host);
        }

        if (proxyPath == null) {
            if (logger.isInfoEnabled()) {
                logger.info("No proxy mapping found for " + host + ". Loading default.");
            }
            return loadDefaultProxy();
        }
        else {
            if (logger.isInfoEnabled()) {
                logger.info("Proxy mapping found for " + host + ": " + proxyPath);
            }
            return loadProxyFromFile(proxyPath);
        }
    }

    private static GSSCredential loadProxyFromFile(String proxyPath) {
        try {
            GlobusCredential cred = new GlobusCredential(proxyPath);
            return new GlobusGSSCredentialImpl(cred, GSSCredential.INITIATE_AND_ACCEPT);
        }
        catch (Exception e) {
            throw new SecurityException(e);
        }
    }

    private static GSSCredential loadDefaultProxy() {
        GSSManager manager = ExtendedGSSManager.getInstance();
        try {
            return manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
        }
        catch (GSSException e) {
            throw new SecurityException(e);
        }
    }

    private static synchronized void loadProxyPaths() {
        if (proxyPaths == null) {
            proxyPaths = new Properties();
            try {
                proxyPaths.load(new FileInputStream(PROXY_HOST_PATH_MAPPING_FILE));
            }
            catch (FileNotFoundException e) {
                // no mapping
            }
            catch (IOException e) {
                logger.warn("Could not load host-proxy mapping file", e);
            }
        }
    }
}


text:
<?php

namespace frontend\modules\costs\models;

use Yii;

/**
 * This is the model class for table "categories_costs".
 *
 * @property integer $id
 * @property string $name
 */
class CategoriesCosts extends \yii\db\ActiveRecord
{
    public $createCategory;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'categories_costs';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['static', 'user_id'], 'integer'],
            [['name'], 'string', 'max' => 255],
            ['createCategory', 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Категорія',
        ];
    }

    public static function addOrCreate($name, $userId)
    {
        if (is_numeric($name)) {
            $model = new CategoryCostsUsers();
            $model->user_id = $userId;
            $model->category_id = $name;
            return $model;
        } else {
            $nameStrToLower = mb_strtolower($name, 'UTF-8');
            $model = new self();
            $model->name = $nameStrToLower;
            $model->user_id = $userId;
            $model->static = 0;
            return $model;
        }

    }

    public static function getNameCategoryById($id)
    {
        return self::findOne($id)->name;
    }

}


text:
/*
 * Date: September 1st 2014
 * Author: Yagnesh Shah
 * Twitter handle: @YagneshHShah
 * Organization: Moolya Software Testing Pvt Ltd
 * License Type: MIT
*/

//Aim: Reset password after logged-in

package webMainScripts.loginLogout;

import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.gjt.mm.mysql.Driver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import utils.SelectBrowser;
import utils.WebCommonMethods;
import webMethods.LoginLogoutMethods;

public class ResetPasswordAndLoginWithOldPassword extends SelectBrowser
{
	WebCommonMethods general;
	LoginLogoutMethods loginLogout;

	@BeforeMethod
    public void openTheBrowser() throws IOException
    {
    	WebDriver d = getBrowser();
	    loginLogout = PageFactory.initElements(d, LoginLogoutMethods.class);
	    general = PageFactory.initElements(d, WebCommonMethods.class);// initiating the driver and the .class file (the pageObject script)

	  	WebCommonMethods.openURL();
    }

	//validLogin test
	@Test(priority=1, groups={"loginlogout"})
	public void ResetPasswordAndLoginWithOldPasswordCheck() throws IOException, BiffException, InterruptedException
	{
		String[] users={"admin"};
		System.out.println("-----------------ResetPasswordAndLoginWithOldPasswordCheck started-----------------");
		for(int i=0; i<users.length; i++)
		{
			//reset password to new value
			LoginLogoutMethods.login(users[i]);
			LoginLogoutMethods.resetPasswordAndLoginWithOldPassword(users[i]);

			Cell[] record = WebCommonMethods.webReadExcel("validLogin",users[i]);  //sending userName, password
	  	  	//System.out.println("record: "+ record.length);
	        String username = record[0].getContents();
	        String password = record[2].getContents();
	        String profileName = record[3].getContents();
			LoginLogoutMethods.validLogin(username,password,profileName);
			LoginLogoutMethods.resetPasswordToOldValueAndLogin(users[i]);

//			Cell[] userNameRecord = WebCommonMethods.webReadExcel("validLogin", users[i]);
//			LoginLogoutMethods.validLogin(userNameRecord[0].getContents(), userNameRecord[2].getContents(), userNameRecord[3].getContents());
//			Thread.sleep(10000);
//			WebCommonMethods.callingImplicitSleep();
//
//			LoginLogoutMethods.resetPasswordToOldValueAndLogin(users[i]);
			//Thread.sleep(7000);
			//LoginLogoutMethods.logout();
		}
		System.out.println("-----------------ResetPasswordAndLoginWithOldPasswordCheck success-----------------");
	}

	@AfterMethod(alwaysRun=true)
    public void catchExceptions(ITestResult result) throws IOException
    {
    	String methodname = result.getName();
        if(!result.isSuccess()){
        	WebCommonMethods.screenshot(methodname);

        }
        WebCommonMethods.quit(); // Calling function close to quit browser instance
    }

}


text:
/*!
 * Module dependencies.
 */

var util = require('util'),
	super_ = require('../Type');

/**
 * URL FieldType Constructor
 * @extends Field
 * @api public
 */

function url(list, path, options) {
	this._nativeType = String;
	this._underscoreMethods = ['format'];
	this._formatUrl = options.format || removeProtocolPrefix;

	url.super_.call(this, list, path, options);
}

/*!
 * Inherit from Field
 */

util.inherits(url, super_);

/**
 * Formats the field value using either a supplied format function or default
 * which strips the leading protocol from the value for simpler display
 *
 * @api public
 */

url.prototype.format = function(item) {
	var url = (item.get(this.path) || '');
	return this._formatUrl(url);
};

/**
 * Remove the protocol prefix from url
 *
 * @api private
 */
function removeProtocolPrefix(url) {
	return url.replace(/^[a-zA-Z]+\:\/\//, '');
}

// TODO: Proper url validation

/*!
 * Export class
 */

exports = module.exports = url;


text:
package checklist

import org.scalatest._
import org.scalatest.freespec._
import org.scalatest.matchers.should._

class PathSpec extends AnyFreeSpec with Matchers {
  "path.pathString" - {
    "empty path" in {
      PNil.pathString should be("")
    }

    "single field" in {
      ("field" :: PNil).pathString should be("field")
    }

    "nested fields" in {
      ("foo" :: "bar" :: PNil).pathString should be("foo/bar")
    }

    "single index" in {
      (123 :: PNil).pathString should be("123")
    }

    "nested indices" in {
      (123 :: 456 :: PNil).pathString should be("123/456")
    }

    "interleaved fields and indices" in {
      ("a" :: "b" :: 3 :: "c" :: 4 :: 5 :: "d" :: PNil).pathString should be(
        "a/b/3/c/4/5/d"
      )
    }
  }
}


text:
import {AnimationMetadata, AnimationPlayer, AnimationTriggerMetadata} from '@angular/animations';
import {TriggerAst} from '../dsl/animation_ast';
import {buildAnimationAst} from '../dsl/animation_ast_builder';
import {AnimationTrigger, buildTrigger} from '../dsl/animation_trigger';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';

import {AnimationDriver} from './animation_driver';
import {parseTimelineCommand} from './shared';
import {TimelineAnimationEngine} from './timeline_animation_engine';
import {TransitionAnimationEngine} from './transition_animation_engine';

export class AnimationEngine {
  private _transitionEngine: TransitionAnimationEngine;
  private _timelineEngine: TimelineAnimationEngine;

  private _triggerCache: {[key: string]: AnimationTrigger} = {};

  // this method is designed to be overridden by the code that uses this engine
  public onRemovalComplete = (element: any, context: any) => {};

  constructor(driver: AnimationDriver, normalizer: AnimationStyleNormalizer) {
    this._transitionEngine = new TransitionAnimationEngine(driver, normalizer);
    this._timelineEngine = new TimelineAnimationEngine(driver, normalizer);

    this._transitionEngine.onRemovalComplete =
        (element: any, context: any) => { this.onRemovalComplete(element, context); }
  }

  registerTrigger(
      componentId: string, namespaceId: string, hostElement: any, name: string,
      metadata: AnimationTriggerMetadata): void {
    const cacheKey = componentId + '-' + name;
    let trigger = this._triggerCache[cacheKey];
    if (!trigger) {
      const errors: any[] = [];
      const ast = buildAnimationAst(metadata as AnimationMetadata, errors) as TriggerAst;
      if (errors.length) {
        throw new Error(
            `The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.join("\n - ")}`);
      }
      trigger = buildTrigger(name, ast);
      this._triggerCache[cacheKey] = trigger;
    }

    this._transitionEngine.register(namespaceId, hostElement, name, trigger);
  }

  destroy(namespaceId: string, context: any) {
    this._transitionEngine.destroy(namespaceId, context);
  }

  onInsert(namespaceId: string, element: any, parent: any, insertBefore: boolean): void {
    this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
  }

  onRemove(namespaceId: string, element: any, context: any): void {
    this._transitionEngine.removeNode(namespaceId, element, context);
  }

  setProperty(namespaceId: string, element: any, property: string, value: any): boolean {
    // @@property
    if (property.charAt(0) == '@') {
      const [id, action] = parseTimelineCommand(property);
      const args = value as any[];
      this._timelineEngine.command(id, element, action, args);
      return false;
    }
    return this._transitionEngine.trigger(namespaceId, element, property, value);
  }

  listen(
      namespaceId: string, element: any, eventName: string, eventPhase: string,
      callback: (event: any) => any): () => any {
    // @@listen
    if (eventName.charAt(0) == '@') {
      const [id, action] = parseTimelineCommand(eventName);
      return this._timelineEngine.listen(id, element, action, callback);
    }
    return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
  }

  flush(countId: number = -1): void { this._transitionEngine.flush(countId); }

  get players(): AnimationPlayer[] {
    return (this._transitionEngine.players as AnimationPlayer[])
        .concat(this._timelineEngine.players as AnimationPlayer[]);
  }

  whenRenderingDone(): Promise<any> { return this._transitionEngine.whenRenderingDone(); }
}


text:
Given(/^I enter my last name "(.*?)"$/) do |lastName|
    touch(query("* id:'last_initial'")[0])
    keyboard_enter_text(lastName)
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: guide > physics > collisionDetection </title>
  <meta name="revised" content="30-Aug-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  guide > physics > collisionDetection " />

  <link rel="stylesheet" href="../../../css/style.css" type="text/css" />

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

Collision Detection

Collision Events

collision

preCollision

postCollision

Collision Handling

Global Collision Handling

Local Collision Handling

Multi-Element Collisions

Collision Forces

Collision Filtering

categoryBits/maskBits

groupIndex

Ξ  ▸  guide  ▸  [physics][guide.physics]  ▸  collisionDetection

Collision Detection

This guide discusses how to handle collisions between physical objects, or ignore (filter) collisions between specific object sets.

Collision Events

Collision Handling

Multi-Element Collisions

Collision Forces

Collision Filtering

Collision Events

Physics engine collision events are exposed through the standard Corona event+listener model, with three event types:

collision

For general collision detection, you should listen for an event named "collision". The "collision" event includes phases for "began" and "ended", which signify the moments of initial contact and broken contact. If you do not implement a "collision" listener, this event will not fire.

preCollision

An event type that fires right before the objects start to interact. Depending on your game logic, you may wish to detect this event and conditionally override the collision.

For example, in a platform game, you may wish to construct "one-sided" platforms that the character can jump vertically through, but only in one direction. You might do this by comparing the character and platform position to see if the character is below the platform, and then using a short timer to make the isSensor body property temporarily true for the character object so that it passes through the platform. If you do not implement a "preCollision" listener, this event will not fire.

Note that "preCollision"" events are quite noisy, and may report many times per contact, which may affect performance. Therefore, you should only listen for these events if you need pre-collision warnings, and we also recommend that you use local listeners within the objects of interest, rather than listening globally to all "preCollision" events in the world.

postCollision

An event type that fires right after the objects have interacted. This is the only event in which the collision force is reported. See the Collision Forces section below for more on this topic. If you do not implement a "postCollision" listener, this event will not fire.

Propagation Rules

Collision events in Corona have a propagation model similar to touch events. You can use this to further optimize your game performance by limiting the number of events that are created. By default, a collision between two objects will fire a local event for the first object, then a local event for the second object, then a global event in the Runtime object (assuming all have active listeners enabled). However, you may only be interested in some of this information.

Any collision event handler that returns true will stop further propagation of that collision event, even if there are further listeners that would otherwise have received it. This allows you to further limit the number of events that are created and passed to the Lua side. While individual events are not very expensive, large numbers of them can affect overall performance, so limiting event propagation is a good practice.

Collision Handling

Collisions are reported between pairs of objects, and they can be detected either globally, using a Runtime listener, or locally within an object, using a table listener.

Important

Currently, the Box2D physics engine is liable to crash during a collision if Corona code attempts to modify objects still involved in the collision. This is because Box2D is still working out the iterated mathematics on these objects. Thus, you should never modify/create physics objects during a collision.

If you need to modify/create an object as a result of a collision, your collision handler should set a flag or add a time delay so the change can occur in the next application cycle or later, e.g. with timer.performWithDelay().

Global Collision Handling

When detected as a Runtime event, each collision event includes event.object1 and event.object2, which contain the table IDs of the two Corona display objects involved.

Because Corona display objects behave like Lua tables, you may freely add any arbitrary data to these tables, such as names, category designators, point values, or even stored functions, and then retrieve this data at collision time. For example, you may wish to store object names in an easily-accessible string format:

local crate1 = display.newImage( "crate.png", 100, 200 )
physics.addBody( crate1, { density = 1.0, friction = 0.3, bounce = 0.2 } )
crate1.myName = "first crate"

local crate2 = display.newImage( "crate.png", 100, 120 )
physics.addBody( crate2, { density = 1.0, friction = 0.3, bounce = 0.2 } )
crate2.myName = "second crate"

local function onCollision( event )

    if ( event.phase == "began" ) then

        print( "began: " .. event.object1.myName .. " and " .. event.object2.myName )

    elseif ( event.phase == "ended" ) then

        print( "ended: " .. event.object1.myName .. " and " .. event.object2.myName )

    end
end

Runtime:addEventListener( "collision", onCollision )

Local Collision Handling

When detected with a table listener within an object, each collision event includes a self table ID, representing the object itself, and event.other which contains the table ID of the other Corona display object involved in the collision. Again, you may wish to store each object's name in string format and retrieve it during the collision event:

local crate1 = display.newImage( "crate.png" )
physics.addBody( crate1, { density=3.0, friction=0.5, bounce=0.3 } )
crate1.myName = "first crate"

local crate2 = display.newImage( "crate.png" )
physics.addBody( crate2, { density=3.0, friction=0.5, bounce=0.3 } )
crate2.myName = "second crate"

local function onLocalCollision( self, event )

    if ( event.phase == "began" ) then

        print( self.myName .. ": collision began with " .. event.other.myName )

    elseif ( event.phase == "ended" ) then

        print( self.myName .. ": collision ended with " .. event.other.myName )

    end
end

crate1.collision = onLocalCollision
crate1:addEventListener( "collision", crate1 )

crate2.collision = onLocalCollision
crate2:addEventListener( "collision", crate2 )

Multi-Element Collisions

Collision events involving a multi-element body (see the Physics Bodies guide) also return the specific body part involved in the collision. This allows for more finely-tuned game logic: for example, you may decide that colliding with the nose of a rocket does more damage than colliding with its tailfins.

Body elements are identified by a numerical index, where the first element added to the body is given the number 1, the second one is number 2, the third is number 3, and so on.

For global collision events, two additional integer values are returned:

event.element1
event.element2

These numerical properties are equal to the index of the elements in object1 and object2 that were involved in the collision. For example, object1 might a rocket with three body elements: nose, body and tail. If the collision is with its tail, the value of event.element1 would be 3; if the collision is with its body, the value of event.element1 would be 2. Again, this number is simply determined by the order in which you declared the elements of the body during its construction.

When collisions involve single-element bodies, both of the above values will always be 1.

Similarly, local collision events (table listeners) return two additional values:

event.selfElement
event.otherElement

As above, these values will be 1 in the case of single-element bodies, and in multi-element bodies will range from 1 to the total number of elements in the body, numbered by the order in which the elements were added to the body.

Collision Forces

Once a collision has occurred, you can obtain the direct force of the collision, along with the sideways force between the two objects, which is effectively a frictional force. For example, you may have game objects that should be destroyed only if a collision is sufficiently forceful.

The direct force of the collision is reported within the "postCollision" event as event.force, and the frictional force is available as event.friction.

local function onPostCollision( event )

    if ( event.force > 1.0 ) then
        print( "Collision force: " .. event.force .. " Friction: " .. event.friction )
    end
end

Runtime:addEventListener( "postCollision", onPostCollision )

In the example above, very small forces are screened out. Also, a global listener is used here to simplify the example.

Since the "postCollision" event stream from the physics engine can be quite noisy (it registers a series of increasingly tiny forces as objects "settle"), you will probably want to choose your own threshold for ignoring some of it.

Technical Note: Box2D is actually reporting collision impulses, which are forces multiplied by the elapsed time of each world step, but since this time interval is always the same, this distinction can be ignored for the purposes of game logic.

Collision Filtering

By default, all bodies collide with all other bodies, but you may want to fine-tune this behavior. For example, in the classic arcade game Asteroids, none of the asteroids collide with other asteroids, but all of them collide with the player and with the enemy spaceships. There are two ways to accomplish this.

categoryBits/maskBits

First, you can assign categoryBits and maskBits to your objects via a "collision filter" definition, which is an optional table assigned during body construction. An object will only collide with other objects if their categoryBits are among its assigned maskBits. Normally, an object will only have one category bit assigned, but may have one or more mask bits depending on what other things it should collide with.

Update: see the helpful collision filter worksheet and discussion for help on determining the correct values.

In the example below, the red balloon has a maskBits value of 3, so it would collide with any objects in category bits 2 and 1, which in this case would include other red balloons (category bit 2) or the wall objects (category bit 1). Meanwhile, it will pass through any blue balloons (category bit 4), since bit 4 is not included in its maskBits value.

borderCollisionFilter = { categoryBits = 1, maskBits = 6 }
-- border collides with (4 and 2) only

borderBody = { friction=0.4, bounce=0.8, bodyType="static", filter=borderCollisionFilter }

local borderTop = display.newRect( 0, 0, 320, 1 )
physics.addBody( borderTop, borderBody )

local borderBottom = display.newRect( 0, 479, 320, 1 )
physics.addBody( borderBottom, borderBody )

local borderLeft = display.newRect( 0, 1, 1, 480 )
physics.addBody( borderLeft, borderBody )

local borderRight = display.newRect( 319, 1, 1, 480 )
physics.addBody( borderRight, borderBody )

local redCollisionFilter = { categoryBits = 2, maskBits = 3 }
-- red collides with (2 and 1) only

local blueCollisionFilter = { categoryBits = 4, maskBits = 5 }
-- blue collides with (4 and 1) only

local redBody = { density=0.2, friction=0, bounce=0.95, radius=43.0, filter=redCollisionFilter }
local blueBody = { density=0.2, friction=0, bounce=0.95, radius=43.0, filter=blueCollisionFilter }

redBalloon = display.newImage( "red_balloon.png" )
physics.addBody( redBalloon, redBody )

blueBalloon = display.newImage( "blue_balloon.png" )
physics.addBody( blueBalloon, blueBody )

groupIndex

The second method is to assign a groupIndex to each object, via the same filter definition shown above. This value can be a positive or negative integer, and may be a simpler way of specifying collision rules. Objects with the same positive groupIndex value will always collide with each other, and objects with the same negative groupIndex value will never collide with each other.

local greenCollisionFilter = { groupIndex = -2 }

If both groupIndex and collisionBits/maskBits are assigned to an object, the groupIndex has higher precedence.

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 30-Aug-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
DRIVER = driver
MOCK = driver_mock
UART_FILE=c_src/UART_receiver.c
UART_MOCK=c_src/UART_mock.c
CURDIR := $(shell pwd)
UART_OBJ=$(CURDIR)/priv/driver
UART_OBJ_MOCK=$(CURDIR)/priv/driver_mock

CC=gcc
FLAGS=-w -I.

all: priv driver driver_mock

priv:
	mkdir priv

driver: $(UART_FILE)
	$(CC) -lpthread -o $(UART_OBJ) $^ $(FLAGS)

driver_mock: $(UART_MOCK)
	$(CC) -lpthread -o $(UART_OBJ_MOCK) $^ $(FLAGS)

clean:
	@rm -f $(UART_OBJ) $(DRIVER)
	@rm -f $(UART_OBJ_MOCK) $(MOCK)


text:
'use strict';

require('es6-promise').polyfill();
var Mapper = require('./lib/mapper');
var cache = {};

function Factory(name) {
  if (!name) {
    name = Object.keys(cache)[0];
  }
  var mapper = cache[name];
  if (!mapper) {
    throw new Error('Mapper ' + name + ' is not exist');
  }
  return mapper;
}

/*
var opts = {
  adaptor:'',
  database: '',
  driver:{},
  pool:{},
  plugins: {
    pluginName: {
      provider: 'plugin',
      opts: {}
    }
  }
}
*/
Factory.create = function(mappers, opts) {
  opts.database = opts.database || opts.driver.database;
  var adaptor = require(opts.adaptor)(opts);
  var mapper = new Mapper(opts.database, adaptor);
  return new Promise(function(resolve, reject){
    mapper.build(mappers).then(function() {
      for (var key in opts.plugins) { // config plugins
        var pluginOpts = opts.plugins[key];
        mapper.plugin.set(key, require(pluginOpts.provider)(pluginOpts.opts || {}));
      }
      cache[opts.database] = mapper;
      resolve(mapper);
    }).catch(reject);
  });
};

module.exports = Factory;