text:
package pers.season.vml.statistics.texture;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat6;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.imgproc.Subdiv2D;

import pers.season.vml.util.ImUtils;
import pers.season.vml.util.Triangle;

public class TextureModel {

	public int delaunay[][];
	public Mat stdShape;
	public Mat meanX;
	public Mat U, S, e;
	public int X_SIZE, Z_SIZE;
	public int resolutionX, resolutionY;
	protected static ExecutorService threadPool = Executors
			.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

	protected TextureModel() {

	}

	public static TextureModel load(String dataPath, String U_name, String meanX_name, String e_name,
			String meanShape_name, String delaunay_name) {
		return load(ImUtils.loadMat(dataPath + U_name), ImUtils.loadMat(dataPath + meanX_name),
				ImUtils.loadMat(dataPath + e_name), ImUtils.loadMat(dataPath + meanShape_name),
				ImUtils.loadMat(dataPath + delaunay_name));
	}

	public static TextureModel load(Mat U, Mat meanX, Mat e, Mat meanShape, Mat delaunay) {
		TextureModel tm = new TextureModel();
		tm.U = U.clone();
		tm.meanX = meanX.clone();
		tm.e = e.clone();

		tm.stdShape = meanShape.clone();
		Mat delaunayMat = delaunay.clone();
		tm.delaunay = new int[delaunayMat.rows()][];
		for (int i = 0; i < delaunayMat.rows(); i++) {
			tm.delaunay[i] = new int[] { (int) delaunayMat.get(i, 0)[0], (int) delaunayMat.get(i, 1)[0],
					(int) delaunayMat.get(i, 2)[0] };

		}

		tm.X_SIZE = tm.U.rows();
		tm.Z_SIZE = tm.U.cols();

		Mat stdShapeX = new Mat(tm.stdShape.rows() / 2, 1, CvType.CV_32F);
		Mat stdShapeY = new Mat(tm.stdShape.rows() / 2, 1, CvType.CV_32F);
		for (int i = 0; i < tm.stdShape.rows() / 2; i++) {
			stdShapeX.put(i, 0, tm.stdShape.get(i * 2, 0)[0]);
			stdShapeY.put(i, 0, tm.stdShape.get(i * 2 + 1, 0)[0]);
		}
		MinMaxLocResult mmX = Core.minMaxLoc(stdShapeX);
		MinMaxLocResult mmY = Core.minMaxLoc(stdShapeY);
		tm.resolutionX = (int) Math.round(mmX.maxVal - mmX.minVal + 2);
		tm.resolutionY = (int) Math.round(mmY.maxVal - mmY.minVal + 2);

		System.out.println("TextureModel inited. " + tm.X_SIZE + " --> " + tm.Z_SIZE);
		return tm;

	}

	public void printTo(Mat Z, Mat dst, Mat shape) {
		Mat X = getXfromZ(Z).reshape(1, resolutionY);
		AffineTexture(X, stdShape, dst, shape, delaunay);
	}

	public Mat getZfromX(Mat X) {
		Mat result = new Mat();
		X = X.reshape(1, X_SIZE);
		Core.subtract(X, meanX, X);
		Core.gemm(U.t(), X, 1, new Mat(), 0, result);
		return result;
	}

	public Mat getXfromZ(Mat Z) {
		Mat X = new Mat();
		Core.gemm(U, Z, 1, new Mat(), 0, X);
		Core.add(X, meanX, X);
		return X;
	}

	public static int[][] createDelaunay(Rect roi, Mat pts) {
		DecimalFormat df = new DecimalFormat("#.0000");
		List<int[]> resultLst = new LinkedList<int[]>();
		ArrayList<String> pointIndexSearchLst = new ArrayList<String>();
		Subdiv2D sd = new Subdiv2D();

		sd.initDelaunay(roi);
		for (int i = 0; i < pts.rows() / 2; i++) {
			sd.insert(new Point(pts.get(i * 2, 0)[0], pts.get(i * 2 + 1, 0)[0]));
			pointIndexSearchLst.add(df.format(pts.get(i * 2, 0)[0]) + "," + df.format(pts.get(i * 2 + 1, 0)[0]));
		}
		MatOfFloat6 mof6 = new MatOfFloat6();
		sd.getTriangleList(mof6);
		for (int i = 0; i < mof6.rows(); i++) {
			double[] data = new double[6];
			data = mof6.get(i, 0);

			Point p1 = new Point(data[0], data[1]);
			Point p2 = new Point(data[2], data[3]);
			Point p3 = new Point(data[4], data[5]);
			if (!p1.inside(roi) || !p2.inside(roi) || !p3.inside(roi)) {
				continue;
			}
			int i1 = pointIndexSearchLst.indexOf(df.format(data[0]) + "," + df.format(data[1]));
			int i2 = pointIndexSearchLst.indexOf(df.format(data[2]) + "," + df.format(data[3]));
			int i3 = pointIndexSearchLst.indexOf(df.format(data[4]) + "," + df.format(data[5]));
			resultLst.add(new int[] { i1, i2, i3 });
		}

		int[][] result = new int[resultLst.size()][];
		resultLst.toArray(result);
		return result;
	}

	public static void AffineTexture(Mat srcpic, Mat srcpts, Mat dstpic, Mat dstpts, int[][] delaunay) {
		Semaphore sema = new Semaphore(0);
		if (dstpic.equals(srcpic))
			srcpic = srcpic.clone();
		for (int i = 0; i < delaunay.length; i++) {
			final int index = i;
			final Mat fSrcpic = srcpic;
			final Mat fDstpic = dstpic;
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					int x1i = delaunay[index][0] * 2;
					int y1i = delaunay[index][0] * 2 + 1;
					int x2i = delaunay[index][1] * 2;
					int y2i = delaunay[index][1] * 2 + 1;
					int x3i = delaunay[index][2] * 2;
					int y3i = delaunay[index][2] * 2 + 1;
					double x1 = srcpts.get(x1i, 0)[0];
					double y1 = srcpts.get(y1i, 0)[0];
					double x2 = srcpts.get(x2i, 0)[0];
					double y2 = srcpts.get(y2i, 0)[0];
					double x3 = srcpts.get(x3i, 0)[0];
					double y3 = srcpts.get(y3i, 0)[0];

					double nx1 = dstpts.get(x1i, 0)[0];
					double ny1 = dstpts.get(y1i, 0)[0];
					double nx2 = dstpts.get(x2i, 0)[0];
					double ny2 = dstpts.get(y2i, 0)[0];
					double nx3 = dstpts.get(x3i, 0)[0];
					double ny3 = dstpts.get(y3i, 0)[0];

					Triangle t = new Triangle(fSrcpic, x1, y1, x2, y2, x3, y3);
					t.shift(nx1, ny1, nx2, ny2, nx3, ny3);

					t.transTextureTo(fDstpic);
					sema.release();
				}

			});

		}

		try {
			sema.acquire(delaunay.length);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public Mat getNormFace(Mat pic, Mat pts) {

		float[] ptsdata = new float[pts.rows()];
		pts.get(0, 0, ptsdata);

		Mat result = Mat.zeros(new Size(resolutionX, resolutionY), pic.type());

		AffineTexture(pic, pts, result, stdShape, delaunay);

		return result;

	}

}


text:
<ion-view view-title="About">
    <ion-content>

Mobilea BV

{{ now | date : 'MMMM dd,yyyy' }}

                    Mobilea is an open platform where all kinds of products and services are combined together to enable elderly and handicapped people to be more self sufficient.

                    For more information visit our website http://www.mobilea.nl.

                    Like

                    Comment

                    Share

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

redpajama_set_name: RedPajamaGithub


text:
@import url('reset.css');
/* General Codrops Demo Style */
body{
	background:#1F1F1F url(../images/pattern.png) repeat top left;
	color:#fff;
	font-family: 'PT Sans Narrow', Arial, sans-serif;
	font-size:14px;
}
a{
	color:#ddd;
	text-decoration:none;
}
a:hover{
	color:#00c6e3;
}
.clr{
	clear:both;
}


text:
package com.bq.corbel.lib.token.serializer;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import com.bq.corbel.lib.token.TokenInfo;
import com.bq.corbel.lib.token.signer.TokenSigner;
import com.google.common.base.Joiner;

/**
 * @author Alexander De Leon
 *
 */
public class Base64TokenSerializer implements TokenSerializer {

	public static final String SEPARATOR = ".";
	public static final String SEPARATOR_REGEX = "\\.";

	@Override
	public String serialize(TokenInfo info, long expireTime, TokenSigner signer) {
		String token = Joiner.on(SEPARATOR).join(
				new String(Base64.getUrlEncoder().withoutPadding()
						.encode(info.serialize().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8),
				Long.toHexString(expireTime));

		return Joiner.on(SEPARATOR).join(token, signer.sign(token));
	}

}


text:
import { bindable, bindingMode, customElement, inlineView, viewResources } from "aurelia-framework";
import { InputWrapper } from "../forms/input-wrapper";
import { ListContainer } from "./list-container";
import { ListInput } from "./list-input";
import { ListMaker } from "./list-maker";
import view from "./ui-select.html";

@customElement("ui-select")
@viewResources(InputWrapper, ListInput, ListContainer)
@inlineView(view)
export class UISelect extends ListMaker {
  @bindable({ defaultBindingMode: bindingMode.twoWay })
  public value: AnyObject = undefined;
  @bindable({ defaultBindingMode: bindingMode.twoWay })
  public model: AnyObject = undefined;

  @bindable()
  public errors: string[];

  @bindable()
  public name: string = "";
  @bindable()
  public placeholder: string = "";

  @bindable()
  public labelProperty: string = "";
  @bindable()
  public valueProperty: string = "";
  @bindable()
  public groupProperty: string = "";
  @bindable()
  public query: ({ query }) => AnyObject[];
  @bindable()
  public options: AnyObject[];

  @bindable()
  public readonly: boolean = false;
  @bindable()
  public disabled: boolean = false;

  @bindable()
  public noOptionsText: string = "No Options";

  @bindable()
  public matcher: ({ option, value }) => boolean;

  constructor(protected element: Element) {
    super(element);
    this.dropHandle = "caret";
    this.multiple = element.hasAttribute("multiple");
    this.allowAny = element.hasAttribute("allow-any");

    this.template = this.element.querySelector("template");
  }

  protected attached(): void {
    this.dropEl.attachToViewport = isTrue(this.element.getAttribute("attach-to-viewport"));
    this.dropEl.closeOnClick = !this.multiple;
    this.dropEl.tether(this.element);
  }

  protected bind(): void {
    if (!isNull(this.model)) {
      if (this.multiple) {
        this.value = this.multiple
          ? this.model.map(o => o[this.valueProperty] || o)
          : this.model[this.labelProperty] || this.model;
      }
    }
    this.isGrouped = !!this.groupProperty;
    this.valueChanged();
  }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ChatRoomManager (android API)</title>
<meta name="date" content="2018-05-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cn.jpush.im.android.api

Class ChatRoomManager

java.lang.Object

cn.jpush.im.android.api.ChatRoomManager

public final class ChatRoomManager
extends java.lang.Object

聊天室管理相关接口类

Constructor Summary

Constructors

Constructor and Description

ChatRoomManager()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
enterChatRoom(long roomID,
             RequestCallback<Conversation> callback)

进入聊天室.

static void
getChatRoomInfos(java.util.Set<java.lang.Long> roomIDs,
                RequestCallback<java.util.List<ChatRoomInfo>> callback)

查询指定roomID的聊天室信息。

static void
getChatRoomListByApp(int start,
                    int count,
                    RequestCallback<java.util.List<ChatRoomInfo>> callback)

获取当前应用appkey所属下聊天室信息。

static void
getChatRoomListByUser(RequestCallback<java.util.List<ChatRoomInfo>> callback)

获取当前用户所加入的所有聊天室的信息。

static void
leaveChatRoom(long roomID,
             BasicCallback callback)

离开聊天室.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ChatRoomManager

public ChatRoomManager()

Method Detail

getChatRoomListByApp

public static void getChatRoomListByApp(int start,
                                        int count,
                                        RequestCallback<java.util.List<ChatRoomInfo>> callback)

获取当前应用appkey所属下聊天室信息。

Parameters:

start - 起始位置

count - 获取个数

callback - 接口回调

Since:

2.4.0

getChatRoomListByUser

public static void getChatRoomListByUser(RequestCallback<java.util.List<ChatRoomInfo>> callback)

获取当前用户所加入的所有聊天室的信息。

Parameters:

callback - 接口回调

Since:

2.4.0

getChatRoomInfos

public static void getChatRoomInfos(java.util.Set<java.lang.Long> roomIDs,
                                    RequestCallback<java.util.List<ChatRoomInfo>> callback)

查询指定roomID的聊天室信息。

Parameters:

roomIDs - 待查询的roomID集合

callback - 接口回调

Since:

2.4.0

enterChatRoom

public static void enterChatRoom(long roomID,
                                 RequestCallback<Conversation> callback)

进入聊天室.
 用户只有成功调用此接口之后,才能收到聊天室消息,以及在此聊天室中发言。
 成功进入聊天室之后,会将聊天室中最近若干条聊天记录同步到本地并以ChatRoomMessageEvent事件的形式通知到上层。

Parameters:

roomID - 聊天室的roomID

callback - 接口回调

Since:

2.4.0

leaveChatRoom

public static void leaveChatRoom(long roomID,
                                 BasicCallback callback)

离开聊天室.
 成功调用此接口之后,用户将能不在此聊天室收发消息。

Parameters:

roomID - 聊天室的roomID

callback - 接口回调

Since:

2.4.0

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module.exports = function(config) {
    config.set({
        basePath: '../',
        files: [
            'node_modules/babel-core/browser-polyfill.js',
            'localhistory/localhistory.min.js',
            'dist_dev/playbyplay.js',
            'test/utils.js',
            'test/tests/**/*.js'
        ],
        frameworks: ['mocha', 'chai-as-promised', 'chai-jquery', 'chai', 'jquery-2.1.0'],
        reporters: ['progress', 'coverage'],
        browsers: ['PhantomJS'],
        preprocessors: {
            'dist_dev/playbyplay.js': ['coverage'],
            'test/utils.js': ['babel'],
            'test/tests/**/*.js': ['babel']
        },
        babelPreprocessor: {
            options: {
                sourceMap: 'inline',
                optional: ['es7.asyncFunctions']
            },
            filename: function(file) {
                return file.originalPath.replace(/\.js$/, '.es5.js');
            },
            sourceFileName: function(file) {
                return file.originalPath;
            }
        },
        coverageReporter: {
            type: 'lcov',
            dir: 'test/coverage'
        }
    });
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<configentry>
    <keyword>MAXTIMEPOS</keyword>

    <scope>GLOBAL</scope>

    <anchor>GLOBAL_MAXTIMEPOS</anchor>

    <definition>MAXTIMEPOS

        <meta>x-pos</meta>

        <meta>y-pos</meta>
    </definition>

    <definition>MAXTIMEPOS

        <meta>x-pos</meta>

        <meta>y-pos</meta>

        <meta>formatstring</meta>
    </definition>

    <description xmlns="http://www.w3.org/1999/xhtml">

Specifies where to draw the 'newest data' timestamp on the map.

The data collection part of weathermap collects a timestamp for each piece of
        data, alongside the actual data. This is intended to signify the time that the
        data was actually valid
        - it would be the file modification date if it was a text file, or the current
        time if it was a live SNMP query. The minimum and maximum of these times are
        collated, and can be shown on the map with MINTIMEPOS and MAXTIMEPOS.

If no MAXTIMEPOS line is given, then the timestamp is not drawn.

You can optionally specify an additional parameter to change the text of the
        timestamp. This text can contain special tokens which are substituted with parts
        of the current time. The default timestamp text is
        <nobr><tt>Newest Data: %b %d %Y %H:%M:%S</tt></nobr>. The tokens used are those
        accepted by the PHP strftime function. For a full list see the
        PHP manual
        page.

You can control the font used to draw the timestamp with TIMEFONT, and the
        colour that it is drawn in, using TIMECOLOR.

    </description>

    <changes>
        <change version="0.96">Originally added MAXTIMEPOS
        </change>
    </changes>
</configentry>


text:
var space = new CanvasSpace( "cover", "#424855" ).display()
space.refresh( false );
space.clear("#424855");
space.ctx.lineCap = "round";

var form = new Form( space );

//// 2. Create Elements
var world = new ParticleSystem(); // a system to track the particles
space.add( world );

var follower = new Particle(); // particle gravitate toward the follower, which has a larger mass
follower.mass = 200;

// Custom Brush extending NoiseDashLine
function NoiseDashLineBrush() {
  NoiseDashLine.call( this, arguments );
  this.color = this.colors.black(.9);

  this._layer = 3 + Math.floor( Math.random()*5);
  this._mag = 0.5 + Math.random()*1.5;
  this._progress = Math.random()/100 + 0.002;
}
Util.extend( NoiseDashLineBrush, NoiseDashLine );

NoiseDashLineBrush.prototype.resetBrush = function() {
  this._layer = 3 + Math.floor( Math.random()*5);
  this._mag = 0.5 + Math.random()*1.5;
  this._progress = Math.random()/100 + 0.008;
};

NoiseDashLineBrush.prototype.draw = function( f ) {

  if (!f) f = this.form;

  if (!this.shouldDraw()) return;

  f.fill( false ).stroke( this.getColor() );

  var distRatio = (this.points.length < this.maxPoints/2) ? this.seedIndex/6 + 0.2 : (this.seedIndex+Math.random()+Math.random())/4 ;
  var smooth = 3;
  var layers = this._layer;
  var magnify = this._mag;
  var curveSegments = 1;
  var flatness = 0.57;

  this.noiseProgress +=  this._progress;
  var noiseFactors = {a: this.noiseProgress, b: this.noiseFactorIndex, c: this.noiseFactorLayer };
  f.noiseDashLine( this.points, this.noise, noiseFactors, this.flipSpeed, distRatio, smooth, this.maxDistance(), layers, magnify, curveSegments, flatness);

};

// set up lines
var darkcolor = {
  dark: "rgba(0,0,10,.02)",
  dark2: "rgba(0,0,10,.02)",
  light: "rgba(0,0,0,.01)",
  ligh2: "rgba(0,0,0,.01)"
};

var lightcolor = {
  dark: "rgba(255,255,255,.01)",
  dark2: "rgba(255,255,255,.01)",
  light: "rgba(255,255,255,.01)",
  ligh2: "rgba(255,255,255,.01)"
};

var line = new NoiseDashLineBrush().init( space );

line.noInput = true;
line.distanceThreshold = 50*50;
line.trace( true );
line.setColor( darkcolor, darkcolor );
line.resetBrush();
space.add( line );

var line2 = new NoiseChopLine().init( space );
line2.noInput = true;
line2.distanceThreshold = 50*50;
line2.trace( true );
line2.setColor( lightcolor, lightcolor );

var line3 = new GrowLine().init( space );
line3.noInput = true;
line3.distanceThreshold = 50*50;
line3.trace( true );
line3.setColor( lightcolor, lightcolor );

var lineB = line2;
space.add( lineB );

// A drawing Tip is a kind of Particle
var baseAge = 8000;

function Tip() {
  Particle.call( this, arguments );
  this.mass = 1;
  //baseAge -= 50;
  this.maxAge = Math.max( 2000, Math.random()*(10000 + baseAge) + 3000 + (baseAge/2) );
  this.age = 0;
}
Util.extend( Tip, Particle );

// animate this speckle
Tip.prototype.animate = function( time, frame, ctx ) {
  this.play(time, frame);
  this.age += frame;
};

// Particle use RK4 to integrate by default. Here we change it to Euler which is faster but less accurate.
Tip.prototype.integrate = function(t, dt) {
  return this.integrateEuler(t, dt);
};

// calculate the forces
Tip.prototype.forces = function( state, t ) {
  var brownian = new Vector( (Math.random()-Math.random())/7, (Math.random()-Math.random())/7 ); // random
  var g = Particle.force_gravitation( state, t, this, follower ); // follower gravity
  return {force: brownian.add(g.force)};
};

// Create a tip
var a = new Tip(space.size.x/2, space.size.y/2);
world.add( a );

// follower spins around the tip slowly
var ang = 0;
function orbit() {
  ang += Const.one_degree*1.2;
  follower.set( Math.cos(ang) * 60 + a.x, Math.sin(ang) * 60 + a.y );
}

// Redraw when out of bounds
function checkBounds() {

  var pxc = form.cc.getImageData(a.x, a.y, 1, 1).data;

  if (a.x <= 0 || a.x >= space.size.x || a.y <= 0 || a.y >= space.size.y || a.age >= a.maxAge || pxc[0] > 80 ) {
    world.remove(a);
    a = new Tip( space.size.x*Math.random(), space.size.x*Math.random() );

    world.add( a );

    darkcolor.dark2 = "rgba(0, 0, "+Math.floor(Math.random()*10+5)+", "+(Math.random()*0.015 + 0.01)+")";
    darkcolor.light2 = "rgba(0,0,0,0)";

    lightcolor.dark2 = "rgba(250, "+Math.floor(Math.random()*20+230)+","+Math.floor(Math.random()*20+230)+",0.02)";
    lightcolor.light2 = "rgba(0,0,0,0)";

    if (Math.random() < 0.3) {

      space.remove( lineB );
      lineB = line3;
      space.add( lineB );
    } else {
      space.remove( lineB );
      lineB = line2;
      space.add( lineB );
    }

    line.resetBrush();
  }
}

//// 3. Visualize, Animate, Interact
space.add({
  animate: function(time, fps, context) {

    checkBounds();
    orbit();

    form.fill(false).stroke();
    lineB.move( a.x, a.y );
    line.move(follower.x, follower.y);

  }
});

// 4. Start playing
space.play();


text:
package org.winterblade.minecraft.harmony.api.crafting.recipes;

import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.oredict.ShapedOreRecipe;
import org.winterblade.minecraft.harmony.api.crafting.RecipeInput;
import org.winterblade.minecraft.harmony.api.crafting.components.RecipeComponent;

import java.util.*;

/**
 * Created by Matt on 4/9/2016.
 */
public class ShapedComponentRecipe extends ShapedOreRecipe {
    private static final int MAX_CRAFT_GRID_WIDTH = 3;
    private static final int MAX_CRAFT_GRID_HEIGHT = 3;

    private final int width;
    private final int height;
    private final RecipeInput[] input;
    private final RecipeComponent output;
    private static final int CHAR_A = 65;

    public ShapedComponentRecipe(int width, int height, RecipeInput[] input, RecipeComponent output) {
        super(output.getItemStack(), itemStacksToOreRecipe(RecipeInput.getFacsimileItems(input), width, height));
        this.width = width;
        this.height = height;
        this.input = input;
        this.output = output;
    }

    private static Object[] itemStacksToOreRecipe(Object[] facsimileItems, int width, int height) {
        String[] lines = new String[height];
        Map<Character, Object> charmap = new HashMap<>();

        /**
         * Build out the recipe's pattern
         */
        int offset = 0;
        for(int y = 0; y < height; y++) {
            lines[y] = "";
            for(int x = 0; x < width; x++) {
                if(facsimileItems[offset] == null) {
                    lines[y] += " ";
                } else {
                    // This will produce increasing values of A, B, C, etc
                    char id = (char)(CHAR_A +offset);
                    lines[y] += id;
                    charmap.put(id, facsimileItems[offset]);
                }

                offset++;
            }
        }

        /**
         * Build out our arguments list...
         */
        List<Object> args = new ArrayList<>();
        args.add(false); // This will turn off mirroring.
        Collections.addAll(args, lines);
        for(Map.Entry<Character, Object> kv : charmap.entrySet()) {
            args.add(kv.getKey());
            args.add(kv.getValue());
        }
        return args.toArray();
    }

    @Override
    public boolean matches(InventoryCrafting inv, World worldIn) {
        for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++)
        {
            for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y)
            {
                if (checkMatch(inv, x, y))
                {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean checkMatch(InventoryCrafting inv, int startX, int startY)
    {
        boolean hasAtLeastOneMatcher = false;
        for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++)
        {
            for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++)
            {
                int subX = x - startX;
                int subY = y - startY;
                int pos = subX + subY * width;
                RecipeInput target = null;

                if (subX >= 0 && subY >= 0 && subX < width && subY < height)
                {
                    target = input[pos];
                }

                ItemStack slot = inv.getStackInRowAndColumn(x, y);

                // If we're null...
                if(RecipeInput.isNullOrEmpty(target)) {
                    // .. and we need to not be, bail:
                    if(slot != null) return false;
                    // Otherwise, don't run matchers
                    continue;
                }

                // If the slot is null, and it's not supposed to be...
                if(slot == null) return false;

                // Run matchers here...
                hasAtLeastOneMatcher = true;
                if(!target.matches(slot, inv, output.getItemStack())) return false;
            }
        }

        // Prevent bad recipes from being 'default':
        return hasAtLeastOneMatcher;
    }

    @Override
    public ItemStack getCraftingResult(InventoryCrafting inv) {
        return output.getItemStack().copy();
    }

    @Override
    public int getRecipeSize() {
        return input.length;
    }

    @Override
    public ItemStack getRecipeOutput() {
        return output.getItemStack();
    }

    @Override
    public ItemStack[] getRemainingItems(InventoryCrafting inv) {
        ItemStack[] ret = new ItemStack[inv.getSizeInventory()];
        RecipeInput target;

        // Lower right
        int left = 2;
        int top = 2;

        // Find the left/top of our recipe
        for(int y = 0; y <= inv.getHeight() - height; y++) {
            // We have to iterate every column, because there might be a null item in the upper left...
            for(int x = 0; x <= inv.getWidth(); x++) {
                ItemStack slot = inv.getStackInRowAndColumn(x, y);
                if(slot == null) continue;

                if(x < left) left = x;
                if(y < top) {
                    top = y;
                    // however, once we find that top item, we can break.
                    break;
                }
            }
        }

        int y2 = Math.min(inv.getHeight(), top+height);
        int x2 = Math.min(inv.getWidth(), left+width);

        int i = 0;
        for (int y = top; y < y2; y++) {
            for (int x = left; x < x2; x++) {
                // Make sure we have things to work with...
                if(i >= input.length) continue;
                target = input[i++];
                int invPos = x + (y * inv.getWidth());
                ItemStack slot = inv.getStackInSlot(invPos);
                if (slot == null) continue;

                // Transform it and roll out.
                ItemStack transformed = target.applyTransformers(slot.copy(), ForgeHooks.getCraftingPlayer());

                // Check if we're destroying the item or not...
                ret[invPos] = transformed != null && transformed.stackSize != 0
                        ? transformed
                        : ForgeHooks.getContainerItem(transformed);
            }
        }

        return ret;
    }
}


text:
package gobblin.metrics.metric.filter;

import static org.mockito.Mockito.mock;

import com.codahale.metrics.Metric;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Tests for {@link MetricNameRegexFilter}.
 */
@Test
public class MetricNameRegexFilterTest {

  @Test
  public void matchesTest() {
    MetricNameRegexFilter metricNameRegexFilter1 = new MetricNameRegexFilter(".*");
    Assert.assertTrue(metricNameRegexFilter1.matches("test1", mock(Metric.class)));
    Assert.assertTrue(metricNameRegexFilter1.matches("test2", mock(Metric.class)));
    Assert.assertTrue(metricNameRegexFilter1.matches("test3", mock(Metric.class)));

    MetricNameRegexFilter metricNameRegexFilter2 = new MetricNameRegexFilter("test1");
    Assert.assertTrue(metricNameRegexFilter2.matches("test1", mock(Metric.class)));
    Assert.assertFalse(metricNameRegexFilter2.matches("test2", mock(Metric.class)));
    Assert.assertFalse(metricNameRegexFilter2.matches("test3", mock(Metric.class)));
  }
}


text:
"""Test for gcs_to_bigquery_operator."""

import unittest
import mock

from  import gcs_to_bq_operator
from google.cloud import bigquery
from google.cloud import storage

_DATASET_ID = 'test_dataset'
_TABLE_ID = 'test_table'
_LOCATION = 'test_location'
_DIR_PREFIX = 'test_dir'
_EXCLUDE_PREFIX = 'test_exclude'
_FILE_NAME = _DIR_PREFIX + '/test_file'

class GCStoBQOperatorTest(unittest.TestCase):

  def setUp(self):
    super(GCStoBQOperatorTest, self).setUp()
    # Mock a GCS client that returns mock bucket with mock blob.
    self.mock_gcs_client = mock.create_autospec(storage.Client)
    self.mock_bucket = mock.create_autospec(storage.bucket.Bucket)
    self.mock_bucket.name = 'test_bucket'
    self.mock_gcs_client.get_bucket.return_value = self.mock_bucket
    self.mock_blob = mock.create_autospec(storage.blob.Blob)
    self.mock_blob.name = _FILE_NAME
    self.mock_blob.size = 100
    self.mock_bucket.list_blobs.return_value = [self.mock_blob]
    self.context = mock.MagicMock()
    # Mock BigQuery client that returns mock dataset with mock table reference.
    self.mock_bq_client = mock.create_autospec(bigquery.Client)
    self.mock_dataset_ref = self.mock_bq_client.dataset(_DATASET_ID)
    self.mock_table_ref = self.mock_dataset_ref.table(_TABLE_ID)
    self.mock_bq_client.dataset.return_value = self.mock_dataset_ref
    self.job_config = bigquery.LoadJobConfig()
    self.operator = gcs_to_bq_operator.GCStoBQOperator(
        task_id='test_task_id',
        bq_client=self.mock_bq_client,
        gcs_client=self.mock_gcs_client,
        job_config=self.job_config,
        dataset_id=_DATASET_ID,
        table_id=_TABLE_ID,
        gcs_bucket=self.mock_bucket.name,
        gcs_location=_LOCATION,
        exclude_prefix=_EXCLUDE_PREFIX,
        dir_prefix=_DIR_PREFIX)

  def test_filter_blobs(self):
    """Test for filtering Storage blobs."""
    expected_output = ['gs://{}/{}'.format(self.mock_bucket.name, _FILE_NAME)]
    blobs = self.operator.filter_blobs(_EXCLUDE_PREFIX, _DIR_PREFIX)
    self.assertEqual(blobs, expected_output)

  def test_load_table(self):
    """Test for loading data to BigQuery table."""
    self.operator.execute(self.context)
    blobs = self.operator.filter_blobs(_EXCLUDE_PREFIX, _DIR_PREFIX)
    self.mock_bq_client.load_table_from_uri.assert_called_once_with(
        blobs[0],
        self.mock_table_ref,
        location=_LOCATION,
        job_config=self.job_config)

if __name__ == '__main__':
  unittest.main()


text:
<?php

$dbParams = array(
    'database'  => 'shared',
    'username'  => 'root',
    'password'  => '',
    'hostname'  => 'localhost',
    // buffer_results - only for mysqli buffered queries, skip for others
    'options' => array('buffer_results' => true)
);

return array(
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => function ($sm) use ($dbParams) {
                $adapter = new BjyProfiler\Db\Adapter\ProfilingAdapter(array(
                    'driver'    => 'pdo',
                    'dsn'       => 'mysql:dbname='.$dbParams['database'].';host='.$dbParams['hostname'],
                    'database'  => $dbParams['database'],
                    'username'  => $dbParams['username'],
                    'password'  => $dbParams['password'],
                    'hostname'  => $dbParams['hostname'],
                ));

                if (php_sapi_name() == 'cli') {
                    $logger = new Zend\Log\Logger();
                    // write queries profiling info to stdout in CLI mode
                    $writer = new Zend\Log\Writer\Stream('php://output');
                    $logger->addWriter($writer, Zend\Log\Logger::DEBUG);
                    $adapter->setProfiler(new BjyProfiler\Db\Profiler\LoggingProfiler($logger));
                } else {
                    $adapter->setProfiler(new BjyProfiler\Db\Profiler\Profiler());
                }
                if (isset($dbParams['options']) && is_array($dbParams['options'])) {
                    $options = $dbParams['options'];
                } else {
                    $options = array();
                }
                $adapter->injectProfilingStatementPrototype($options);
                return $adapter;
            },
        ),
    ),
);


text:
namespace base {
class SequencedTaskRunner;
}  // namespace base

namespace policy {

class ConfigurationPolicyProvider;

namespace test_keys {

extern const char kKeyString[];
extern const char kKeyBoolean[];
extern const char kKeyInteger[];
extern const char kKeyStringList[];
extern const char kKeyDictionary[];

}  // namespace test_keys

class PolicyTestBase : public testing::Test {
 public:
  PolicyTestBase();
  PolicyTestBase(const PolicyTestBase&) = delete;
  PolicyTestBase& operator=(const PolicyTestBase&) = delete;
  ~PolicyTestBase() override;

  // testing::Test:
  void SetUp() override;
  void TearDown() override;

 protected:
  bool RegisterSchema(const PolicyNamespace& ns,
                      const std::string& schema);

  // Needs to be the first member
  base::test::TaskEnvironment task_environment_;
  SchemaRegistry schema_registry_;
};

// An interface for creating a test policy provider and creating a policy
// provider instance for testing. Used as the parameter to the abstract
// ConfigurationPolicyProviderTest below.
class PolicyProviderTestHarness {
 public:
  // |level|, |scope| and |source| are the level, scope and source of the
  // policies returned by the providers from CreateProvider().
  PolicyProviderTestHarness(PolicyLevel level,
                            PolicyScope scope,
                            PolicySource source);
  PolicyProviderTestHarness(const PolicyProviderTestHarness&) = delete;
  PolicyProviderTestHarness& operator=(const PolicyProviderTestHarness&) =
      delete;
  virtual ~PolicyProviderTestHarness();

  // Actions to run at gtest SetUp() time.
  virtual void SetUp() = 0;

  // Create a new policy provider.
  virtual ConfigurationPolicyProvider* CreateProvider(
      SchemaRegistry* registry,
      scoped_refptr<base::SequencedTaskRunner> task_runner) = 0;

  // Returns the policy level, scope and source set by the policy provider.
  PolicyLevel policy_level() const;
  PolicyScope policy_scope() const;
  PolicySource policy_source() const;

  // Helpers to configure the environment the policy provider reads from.
  virtual void InstallEmptyPolicy() = 0;
  virtual void InstallStringPolicy(const std::string& policy_name,
                                   const std::string& policy_value) = 0;
  virtual void InstallIntegerPolicy(const std::string& policy_name,
                                    int policy_value) = 0;
  virtual void InstallBooleanPolicy(const std::string& policy_name,
                                    bool policy_value) = 0;
  virtual void InstallStringListPolicy(const std::string& policy_name,
                                       const base::ListValue* policy_value) = 0;
  virtual void InstallDictionaryPolicy(
      const std::string& policy_name,
      const base::Value::Dict& policy_value) = 0;

  // Not every provider supports installing 3rd party policy. Those who do
  // should override this method; the default just makes the test fail.
  virtual void Install3rdPartyPolicy(const base::Value::Dict& policies);

 private:
  PolicyLevel level_;
  PolicyScope scope_;
  PolicySource source_;
};

// A factory method for creating a test harness.
typedef PolicyProviderTestHarness* (*CreatePolicyProviderTestHarness)();

// Abstract policy provider test. This is meant to be instantiated for each
// policy provider implementation, passing in a suitable harness factory
// function as the test parameter.
class ConfigurationPolicyProviderTest
    : public PolicyTestBase,
      public testing::WithParamInterface<CreatePolicyProviderTestHarness> {
 public:
  ConfigurationPolicyProviderTest(const ConfigurationPolicyProviderTest&) =
      delete;
  ConfigurationPolicyProviderTest& operator=(
      const ConfigurationPolicyProviderTest&) = delete;

 protected:
  ConfigurationPolicyProviderTest();
  ~ConfigurationPolicyProviderTest() override;

  void SetUp() override;
  void TearDown() override;

  // Installs a valid policy and checks whether the provider returns the
  // |expected_value|.
  void CheckValue(const char* policy_name,
                  const base::Value& expected_value,
                  base::OnceClosure install_value);

  std::unique_ptr<PolicyProviderTestHarness> test_harness_;
  std::unique_ptr<ConfigurationPolicyProvider> provider_;
};

// An extension of ConfigurationPolicyProviderTest that also tests loading of
// 3rd party policy. Policy provider implementations that support loading of
// 3rd party policy should also instantiate these tests.
class Configuration3rdPartyPolicyProviderTest
    : public ConfigurationPolicyProviderTest {
 public:
  Configuration3rdPartyPolicyProviderTest(
      const Configuration3rdPartyPolicyProviderTest&) = delete;
  Configuration3rdPartyPolicyProviderTest& operator=(
      const Configuration3rdPartyPolicyProviderTest&) = delete;

 protected:
  Configuration3rdPartyPolicyProviderTest();
  virtual ~Configuration3rdPartyPolicyProviderTest();
};

}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_COMMON_CONFIGURATION_POLICY_PROVIDER_TEST_H_


text:
using System.Collections.Generic;

public class PlayerData {

    public int playerID = 0;
    public List<Challenge> challenges;
    public float xPos = -7.37f; //X location of player
    public float yPos = 0; //Y location of player
    public PlayerCharacter character;
    public bool ritualCasting = false;

    public PlayerData(int playerID)
    {
        this.playerID = playerID;
        challenges = new List<Challenge>();
    }
}


text:
package br.com.wakim.index;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;

import br.com.wakim.index.dao.DataSet;
import br.com.wakim.index.dao.DataSetDAO;
import br.com.wakim.index.dao.DocumentDAO;

public class LuceneIndexer {

	private static final String FIELD = "contents";
	private static final FieldType fieldType;

	private static int currentTermPosition = 0;

	static {
		fieldType = new FieldType();

		fieldType.setStoreTermVectors(true);
		fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
		fieldType.setStored(true);
		fieldType.setIndexed(true);
		fieldType.setTokenized(true);
	}

	public static IndexWriter indexDocuments(IndexWriter indexWriter, List<String> documents) throws IOException {
		for(String document : documents) {
			Document d = new Document();
			Field field = new Field(FIELD, document, fieldType);
			d.add(field);
			indexWriter.addDocument(d);
		}

		return indexWriter;
	}

	public static void main(String args[]) {
		try {
			StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
			Directory dir = new RAMDirectory();
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
			IndexWriter indexWriter = new IndexWriter(dir, config);
			DocumentDAO docDao = new DocumentDAO();
			DataSetDAO setDao = new DataSetDAO();
			int dataSetId = 7;
			int documentsLength = 17036 / 4;

			HashMap<String, TermInfo> terms = new HashMap<String, TermInfo>();

			DataSet set = setDao.getDataSet(dataSetId);

			List<String> documents = docDao.getDocuments(dataSetId, documentsLength);

			indexDocuments(indexWriter, documents);

			indexWriter.commit();
			IndexReader reader = DirectoryReader.open(dir);

			int[][] TxD = getTermDocumentMatrix(reader, terms);

			indexWriter.close();
			reader.close();
			dir.close();

			documents = null;

			indexWriter = null;
			reader = null;
			dir = null;
			terms = null;

			System.gc();

			// Debug
//			for(int i = 0; i < TxD.length; ++i) {
//				for(int j = 0; j < TxD[i].length; ++j) {
//					System.out.print(TxD[i][j] + " ");
//				}
//
//				System.out.println();
//			}

			TermDocumentMatrixWriter writer =
				new TermDocumentMatrixWriter(set.name + "_" + TxD.length + "_" + TxD[0].length);
			writer.open();

			writer.write(TxD);

			writer.close();

			System.gc();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * retorna a matriz DxT, transposta da matriz TxD procurada.
	 * @param reader
	 * @param terms
	 * @return
	 * @throws IOException
	 */
	public static int[][] getTermDocumentMatrix(IndexReader reader, HashMap<String, TermInfo> terms) throws IOException {
		int[][] TxD = null;
		TermInfo info;

		String termString = null;
		Terms termsObject = null;
		TermsEnum it = null;
		BytesRef text = null;

		System.out.println("Num Docs: " + reader.numDocs());

		for(int i = 0; i < reader.numDocs(); ++i) {
			termsObject = reader.getTermVector(i, FIELD);

			if(termsObject == null) {
				continue;
			}
			it = termsObject.iterator(it);

			text = null;

			while((text = it.next()) != null) {
				termString = text.utf8ToString();

				if((info = terms.get(termString)) == null) {
					info = new TermInfo();
					info.docs = new int[reader.numDocs()];
					info.rowPosition = currentTermPosition++;
					info.term = termString;
					terms.put(termString, info);
				}

				info.docs[i] += (int) it.totalTermFreq();
			}
		}

		System.out.println(currentTermPosition + "_" + terms.size());

		TxD = new int[currentTermPosition][];

		for(TermInfo indexedInfo : terms.values()) {
			TxD[indexedInfo.rowPosition] = indexedInfo.docs;
		}

		return TxD;
	}
}


text:
#define _USE_MATH_DEFINES

#include <Windows.h>
#include "Game.h"
#include <gl\GL.h>
#include <gl\freeglut.h>
#include "RGBAColor.h"
#include "SpriteLayer.h"
#include "WallPlayer.h"

#include <math.h>
#include <iostream>

Game::Game() :
    window(800, 600, "Foul Kicker"), level(0)
{
    Layer* background = new Layer();
    background->addImage("resources/img/stadium.ptm");
    background->setX(0);
    background->setY(0);

    Image* bgImg = background->getImage();

    this->scene = new Image(*bgImg);
    this->bgCopy = bgImg;
    this->layers.push_back(background);

    Layer* goalkeeper = new Layer();
    goalkeeper->addImage("resources/img/goalkeeper1.ptm");
    goalkeeper->setX(399);
    goalkeeper->setY(208);

    this->layers.push_back(goalkeeper);

    /*
     * TODO: Level layout initialization should be in
     * another place. Maybe on a file later.
     */
    level.addPlayerOnWall(Position(270, 150));
    loadLevel(level);

    Level l(1);
    l.addPlayerOnWall(Position(490, 150));
    levels.push_back(l);

    Level l2(2);
    l2.addPlayerOnWall(Position(270, 150));
    l2.addPlayerOnWall(Position(320, 150));
    levels.push_back(l2);

    Level l3(3);
    l3.addPlayerOnWall(Position(440, 150));
    l3.addPlayerOnWall(Position(490, 150));
    levels.push_back(l3);

    Level l4(4);
    l4.addPlayerOnWall(Position(270, 150));
    l4.addPlayerOnWall(Position(320, 150));
    l4.addPlayerOnWall(Position(370, 150));
    levels.push_back(l4);

    Level l5(5);
    l5.addPlayerOnWall(Position(390, 150));
    l5.addPlayerOnWall(Position(440, 150));
    l5.addPlayerOnWall(Position(490, 150));
    levels.push_back(l5);

    // set initial speed of the ball
    ball.setSpeedX(0);
    ball.setSpeedY(0);

    ballLayer.setSprite(ball.getCurrentSprite());
    ballLayer.setX(400);
    ballLayer.setY(0);

    this->goalkeeperDirection = 1;

    currentTime = 1;

    this->run();
}

Game::~Game()
{
    delete this->scene;
    delete this->bgCopy;

    // Properly clean the vector
    while (!this->layers.empty()) {
        delete this->layers.back();
        this->layers.pop_back();
    }
}

bool Game::checkForCollision() {

	bool collision = false;

	Layer* goalkeeper = this->layers.at(1);

	// GoalKeeper collision
	if ((ballLayer.getY() >= goalkeeper->getY() && ballLayer.getY() < 215) &&
		(ballLayer.getX() >= goalkeeper->getX() && ballLayer.getX() <= goalkeeper->getX() + goalkeeper->getWidth())) {
		collision = true;
	}

	Layer wall = wallLayers.at(0);

	// WallLayer collision
	if (ballLayer.getY() == wall.getY() &&
		ballLayer.getX() >= wall.getX() &&
		ballLayer.getX() <= (wall.getX() + wall.getWidth() * (int)wallLayers.size())) {
		collision = true;
	}

	// GoalLine collision
	if (isBallOutOfPlay() && !hasCrossedGoalLine()) {
		collision = true;
	}

	// Sideline collision
	if (ballLayer.getX() > window.getWidth() || ballLayer.getX() < 0) {
		collision = true;
	}

	return collision;
}

int Game::animateBall(int time) {
    ballLayer.saveCurrentPosition();

	//ToDo:: Aplicar calculo de balistica
	if (currentAngleDirection > 0) {
		double v = ball.getSpeedY();
		double a = currentAngleDirection * M_PI / 180.0;
		double z = v * cos(a) * ++time;
		double temp = z / (v * cos(a));
		double w = z * tan(a) - 0.5 * 98 * (temp * temp);

		//ToDo:: Troca de Bola em Funcao do time por "v"
		if (ballLayer.getY() / 45 >= currentTime) {
			ball.nextBall();
			ballLayer.setSprite(ball.getCurrentSprite());
			currentTime++;
		}

		int posY = ballLayer.getY() + v;
		ballLayer.setX(400 + z);
		ballLayer.setY(posY);
	}

    Layer* goalkeeper = this->layers.at(1);

	/* Detectar gol
	 * Linha do Gol y@226
	 */
	if (checkForCollision()) {
		//Goal Defense
		prepare();
		Sleep(250);

		std::cout << "Goal Defense" << "\n";
		time = 0;
	}

	if (isBallOutOfPlay() && hasCrossedGoalLine()) {
		//Goal
		prepare();
		Sleep(250);

		goals++;
		std::cout << "Goal (" << goals << " / " << attempts << ")\n";
		time = 0;
		nextLevel();
	}

	boardMessage = "Goals: " + std::to_string(goals) + "\n" + "Attempts: " + std::to_string(attempts);

	/*
     * Trave Esquerda x@286
     * Trave Direita x@490
     */

    if (goalkeeper->getX() >= 490) {
        goalkeeperDirection = -1;
    } else {
        if (goalkeeper->getX() <= 286) {
            goalkeeperDirection = 1;
        }
    }

    goalkeeper->saveCurrentPosition();

    int goalkeeperPos = goalkeeper->getX();
    goalkeeperPos += 5 * goalkeeperDirection;
    goalkeeper->setX(goalkeeperPos);

    this->run();

    return time;
}

void Game::run() {
    if (!this->scene) {
        this->scene = new Image(this->window.getWidth(), this->window.getHeight());
    }

    int length = this->layers.size();

    for (int i = 1; i < length; i++) {
        drawLayer(layers.at(i));
    }

    for (unsigned i = 0; i < wallLayers.size(); i++) {
        drawLayer(&wallLayers.at(i));
    }

    drawLayer(&ballLayer);
}

void Game::drawLayer(Layer* layer) {
    Position* lastPos = layer->getLastPosition();

    /* TODO: Refactor it. This code probably should not be here.
     *
     * Redraw the part where the layer was located in the previous frame
     * so it deletes its trace.
     */
    if (lastPos) {
        int height = lastPos->getPosY() + lastPos->getHeight(),
            width = lastPos->getPosX() + lastPos->getWidth();

        for (int y = lastPos->getPosY(); y < height; y++) {
            if (y >= scene->getHeight()) break;
            if (y < 0) continue;

            for (int x = lastPos->getPosX(); x < width; x++) {
                if (x >= scene->getWidth()) break;
                if (x < 0) continue;

                unsigned pixel = this->bgCopy->getPixel(x, y);
                this->scene->setPixel(pixel, x, y);
            }
        }
    }

    layer->draw(this->scene, layer->getX(), layer->getY());
}

void Game::display(void) {
    glColor3f(255, 255, 0);

    glRasterPos2f(0, 0);

    glDrawPixels(scene->getWidth(), scene->getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, scene->getPixels());

    glRasterPos2f(370, 430);

    glutBitmapString(GLUT_BITMAP_HELVETICA_12, (const unsigned char*) boardMessage.c_str());

    glFlush();
}

void Game::loadLevel(Level newLevel) {
    std::cout << "Level " << level.getLevel() << "\n";

    while (!wallLayers.empty()) {
        wallLayers.pop_back();
    }

    for (int a = 0; a < newLevel.getNumberOfPlayersOnWall(); a++) {
        Layer player;
        player.setImage(wallPlayer.getImage());

        const Position* position = level.getPlayerPosition(a);

        if (position) {
            player.setX(position->getPosX());
            player.setY(position->getPosY());
        }

        wallLayers.push_back(player);
    }
}

bool Game::isBallOutOfPlay() {
	return ballLayer.getY() > 225;
}

bool Game::hasCrossedGoalLine() {
	return ballLayer.getX() >= 280 && ballLayer.getX() <= 520;
}

void Game::prepare() {
	ballLayer.setX(400);
	ballLayer.setY(0);
	ball.setSpeedX(0);
	ball.setSpeedY(2.0);
	currentAngleDirection = 0;

    currentTime = 1;
    ball.setCurrentBall(0);
    ballLayer.setSprite(ball.getCurrentSprite());
}

void Game::kick(int x, int y) {

	int diffY = window.getHeight() - y;

	int initialX = ballLayer.getX();
	int finalX = initialX + ballLayer.getWidth();

	int initialY = ballLayer.getY();
	int finalY = initialY + ballLayer.getHeight();

	int axisX = finalX - x;
	int axisY = finalY - abs(diffY);

	if (initialY == 0 &&
		(axisX >= 0 && axisX <= ballLayer.getWidth()) &&
		(axisY >= 0 && axisY <= ballLayer.getHeight())) {
		prepare();
		currentAngleDirection = abs(180 - axisX * 6);
		attempts++;
	}
}

bool Game::nextLevel() {
    if (levels.size() > 0) {
        Level l = levels.front();
        levels.erase(levels.begin());
        level = l;
        // draw background
        drawLayer(layers.at(0));
        loadLevel(l);
    } else {
        std::cout << "Out of levels\n";
        return false;
    }

    return true;
}


text:
package io.werval.runtime.routes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

import io.werval.api.exceptions.RouteNotFoundException;
import io.werval.api.http.RequestHeader;
import io.werval.api.routes.Route;
import io.werval.api.routes.Routes;
import io.werval.util.Iterables;

import static io.werval.util.Strings.NEWLINE;

/**
 * Instance of Routes.
 */
public class RoutesInstance
    extends ArrayList<Route>
    implements Routes
{
    private static final long serialVersionUID = 1L;

    public RoutesInstance( Route... routes )
    {
        this( Arrays.asList( routes ) );
    }

    public RoutesInstance( Iterable<Route> routes )
    {
        super();
        Iterables.addAll( this, routes );
    }

    @Override
    public Route route( RequestHeader requestHeader )
    {
        for( Route route : this )
        {
            if( route.satisfiedBy( requestHeader ) )
            {
                return route;
            }
        }
        throw new RouteNotFoundException( requestHeader.method(), requestHeader.uri() );
    }

    @Override
    public String toString()
    {
        int methodPadLen = 0, pathPadLen = 0;
        for( Route route : this )
        {
            if( route.httpMethod().name().length() > methodPadLen )
            {
                methodPadLen = route.httpMethod().name().length();
            }
            if( route.path().length() > pathPadLen )
            {
                pathPadLen = route.path().length();
            }
        }
        StringBuilder sb = new StringBuilder();
        for( Iterator<Route> it = iterator(); it.hasNext(); )
        {
            RouteInstance route = (RouteInstance) it.next();
            sb.append( route.toString( methodPadLen, pathPadLen, null ) );
            if( it.hasNext() )
            {
                sb.append( NEWLINE );
            }
        }
        return sb.toString();
    }
}


text:
namespace gfx {
class Size;
}

namespace ui {

class InputEventHandler;
class ServiceProviderImpl;
class SurfaceIdHandler;
class WindowCompositorFrameSinkBinding;
class WindowObserver;
class WindowSurface;
class WindowDropTarget;
class WindowTreeClient;
class WindowTreeClientPrivate;

namespace {
class OrderChangedNotifier;
}

// Defined in window_property.h (which we do not include)
template <typename T>
struct WindowProperty;

// Windows are owned by the WindowTreeClient. See WindowTreeClientDelegate for
// details on ownership.
//
// TODO(beng): Right now, you'll have to implement a WindowObserver to track
//             destruction and NULL any pointers you have.
//             Investigate some kind of smart pointer or weak pointer for these.
class Window {
 public:
  using Children = std::vector<Window*>;
  using EmbedCallback = base::Callback<void(bool)>;
  using PropertyDeallocator = void (*)(int64_t value);
  using SharedProperties = std::map<std::string, std::vector<uint8_t>>;

  // Destroys this window and all its children. Destruction is allowed for
  // windows that were created by this connection, or the roots. For windows
  // from other connections (except the roots), Destroy() does nothing. If the
  // destruction is allowed observers are notified and the Window is
  // immediately deleted.
  void Destroy();

  // Returns true if this client created and owns this window.
  bool WasCreatedByThisClient() const;

  WindowTreeClient* window_tree() { return client_; }

  // The local_id is provided for client code. The local_id is not set or
  // manipulated by mus. The default value is -1.
  void set_local_id(int id) { local_id_ = id; }
  int local_id() const { return local_id_; }

  int64_t display_id() const { return display_id_; }

  // Geometric disposition relative to parent window.
  const gfx::Rect& bounds() const { return bounds_; }
  void SetBounds(const gfx::Rect& bounds);

  // Geometric disposition relative to root window.
  gfx::Rect GetBoundsInRoot() const;

  const gfx::Insets& client_area() const { return client_area_; }
  const std::vector<gfx::Rect>& additional_client_areas() {
    return additional_client_areas_;
  }
  void SetClientArea(const gfx::Insets& new_client_area) {
    SetClientArea(new_client_area, std::vector<gfx::Rect>());
  }
  void SetClientArea(const gfx::Insets& new_client_area,
                     const std::vector<gfx::Rect>& additional_client_areas);

  // Mouse events outside the hit test mask do not hit the window. Returns null
  // if there is no mask.
  const gfx::Rect* hit_test_mask() const { return hit_test_mask_.get(); }
  void SetHitTestMask(const gfx::Rect& mask_rect);
  void ClearHitTestMask();

  // Visibility (also see IsDrawn()). When created windows are hidden.
  bool visible() const { return visible_; }
  void SetVisible(bool value);

  float opacity() const { return opacity_; }
  void SetOpacity(float opacity);

  // Cursors
  mojom::Cursor predefined_cursor() const { return cursor_id_; }
  void SetPredefinedCursor(ui::mojom::Cursor cursor_id);

  // A Window is drawn if the Window and all its ancestors are visible and the
  // Window is attached to the root.
  bool IsDrawn() const;

  std::unique_ptr<WindowCompositorFrameSink> RequestCompositorFrameSink(
      mojom::CompositorFrameSinkType type,
      scoped_refptr<cc::ContextProvider> context_provider);

  void AttachCompositorFrameSink(
      mojom::CompositorFrameSinkType type,
      std::unique_ptr<WindowCompositorFrameSinkBinding>
          compositor_frame_sink_binding);

  // The template-ized versions of the following methods rely on the presence
  // of a mojo::TypeConverter<const std::vector<uint8_t>, T>.
  // Sets a shared property on the window which is sent to the window server and
  // shared with other clients that can view this window.
  template <typename T>
  void SetSharedProperty(const std::string& name, const T& data);
  // Gets a shared property set on the window. The property must exist. Call
  // HasSharedProperty() before calling.
  template <typename T>
  T GetSharedProperty(const std::string& name) const;
  // Removes the shared property.
  void ClearSharedProperty(const std::string& name);
  bool HasSharedProperty(const std::string& name) const;

  // TODO(beng): Test only, should move to a helper.
  const SharedProperties& shared_properties() { return properties_; }

  // Sets the |value| of the given window |property|. Setting to the default
  // value (e.g., NULL) removes the property. The caller is responsible for the
  // lifetime of any object set as a property on the Window.
  //
  // These properties are not visible to the window server.
  template <typename T>
  void SetLocalProperty(const WindowProperty<T>* property, T value);

  // Returns the value of the given window |property|.  Returns the
  // property-specific default value if the property was not previously set.
  //
  // These properties are only visible in the current process and are not
  // shared with other mojo services.
  template <typename T>
  T GetLocalProperty(const WindowProperty<T>* property) const;

  // Sets the |property| to its default value. Useful for avoiding a cast when
  // setting to NULL.
  //
  // These properties are only visible in the current process and are not
  // shared with other mojo services.
  template <typename T>
  void ClearLocalProperty(const WindowProperty<T>* property);

  void set_input_event_handler(InputEventHandler* input_event_handler) {
    input_event_handler_ = input_event_handler;
  }

  void set_surface_id_handler(SurfaceIdHandler* surface_id_handler) {
    surface_id_handler_ = surface_id_handler;
  }

  // Observation.
  void AddObserver(WindowObserver* observer);
  void RemoveObserver(WindowObserver* observer);

  // Tree.
  Window* parent() { return parent_; }
  const Window* parent() const { return parent_; }

  Window* GetRoot() {
    return const_cast<Window*>(const_cast<const Window*>(this)->GetRoot());
  }
  const Window* GetRoot() const;

  void AddChild(Window* child);
  void RemoveChild(Window* child);
  const Children& children() const { return children_; }

  void Reorder(Window* relative, mojom::OrderDirection direction);
  void MoveToFront();
  void MoveToBack();

  // Returns true if |child| is this or a descendant of this.
  bool Contains(const Window* child) const;

  void AddTransientWindow(Window* transient_window);
  void RemoveTransientWindow(Window* transient_window);

  // TODO(fsamuel): Figure out if we want to refactor transient window
  // management into a separate class.
  // Transient tree.
  Window* transient_parent() { return transient_parent_; }
  const Window* transient_parent() const { return transient_parent_; }
  const Children& transient_children() const { return transient_children_; }

  void SetModal();
  bool is_modal() const { return is_modal_; }

  Window* GetChildByLocalId(int id);

  void SetTextInputState(mojo::TextInputStatePtr state);
  void SetImeVisibility(bool visible, mojo::TextInputStatePtr state);

  bool HasCapture() const;
  void SetCapture();
  void ReleaseCapture();

  // Focus. See WindowTreeClient::ClearFocus() to reset focus.
  void SetFocus();
  bool HasFocus() const;
  void SetCanFocus(bool can_focus);

  // Sets whether this window accepts drags. Passing a non-null |drop_target|
  // will enable acceptance of drops. Passing null will disable it.
  void SetCanAcceptDrops(WindowDropTarget* drop_target);
  WindowDropTarget* drop_target() { return drop_target_; }

  // Sets whether this window accepts events.
  void SetCanAcceptEvents(bool can_accept_events);

  // Embedding. See window_tree.mojom for details.
  void Embed(ui::mojom::WindowTreeClientPtr client, uint32_t flags = 0);

  // NOTE: callback is run synchronously if Embed() is not allowed on this
  // Window.
  void Embed(ui::mojom::WindowTreeClientPtr client,
             const EmbedCallback& callback,
             uint32_t flags = 0);

  // TODO(sky): this API is only applicable to the WindowManager. Move it
  // to a better place.
  void RequestClose();

  // Starts an inter-process drag and drop operation. When this finishes, will
  // return the tuple [success, action_taken] to |callback|, where action_taken
  // is one of the ui::mojom::kDropEffect constants in
  // window_tree_constants.mojom.
  void PerformDragDrop(
      const std::map<std::string, std::vector<uint8_t>>& drag_data,
      int drag_operation,
      const gfx::Point& cursor_location,
      const SkBitmap& bitmap,
      const base::Callback<void(bool, uint32_t)>& callback);

  // Cancels the in progress drag started with PerformDragDrop().
  void CancelDragDrop();

  // Tells the window manager to take control of moving the window. Returns
  // true if the move wasn't canceled.
  void PerformWindowMove(mojom::MoveLoopSource source,
                         const gfx::Point& cursor_location,
                         const base::Callback<void(bool)>& callback);

  // Tells the window manager to abort any current move initiated by
  // PerformWindowMove().
  void CancelWindowMove();

  // Returns an internal name, set by a client app when it creates a window.
  std::string GetName() const;

 protected:
  // This class is subclassed only by test classes that provide a public ctor.
  Window();
  ~Window();

 private:
  friend class WindowPrivate;
  friend class WindowTreeClient;
  friend class WindowTreeClientPrivate;

  Window(WindowTreeClient* client, Id id);

  // Used to identify this Window on the server. Clients can not change this
  // value.
  Id server_id() const { return server_id_; }

  // Applies a shared property change locally and forwards to the server. If
  // |data| is null, this property is deleted.
  void SetSharedPropertyInternal(const std::string& name,
                                 const std::vector<uint8_t>* data);
  // Called by the public {Set,Get,Clear}Property functions.
  int64_t SetLocalPropertyInternal(const void* key,
                                   const char* name,
                                   PropertyDeallocator deallocator,
                                   int64_t value,
                                   int64_t default_value);
  int64_t GetLocalPropertyInternal(const void* key,
                                   int64_t default_value) const;

  void LocalDestroy();
  void LocalAddChild(Window* child);
  void LocalRemoveChild(Window* child);
  void LocalAddTransientWindow(Window* transient_window);
  void LocalRemoveTransientWindow(Window* transient_window);
  void LocalSetModal();
  // Returns true if the order actually changed.
  bool LocalReorder(Window* relative, mojom::OrderDirection direction);
  void LocalSetBounds(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds);
  void LocalSetClientArea(
      const gfx::Insets& new_client_area,
      const std::vector<gfx::Rect>& additional_client_areas);
  void LocalSetParentDrawn(bool drawn);
  void LocalSetDisplay(int64_t display_id);
  void LocalSetVisible(bool visible);
  void LocalSetOpacity(float opacity);
  void LocalSetPredefinedCursor(mojom::Cursor cursor_id);
  void LocalSetSharedProperty(const std::string& name,
                              const std::vector<uint8_t>* data);
  void LocalSetSurfaceId(std::unique_ptr<SurfaceInfo> surface_info);

  // Notifies this winodw that its stacking position has changed.
  void NotifyWindowStackingChanged();
  // Methods implementing visibility change notifications. See WindowObserver
  // for more details.
  void NotifyWindowVisibilityChanged(Window* target, bool visible);
  // Notifies this window's observers. Returns false if |this| was deleted
  // during the call (by an observer), otherwise true.
  bool NotifyWindowVisibilityChangedAtReceiver(Window* target, bool visible);
  // Notifies this window and its child hierarchy. Returns false if |this| was
  // deleted during the call (by an observer), otherwise true.
  bool NotifyWindowVisibilityChangedDown(Window* target, bool visible);
  // Notifies this window and its parent hierarchy.
  void NotifyWindowVisibilityChangedUp(Window* target, bool visible);

  // Returns true if embed is allowed for this node. If embedding is allowed all
  // the children are removed.
  bool PrepareForEmbed();

  void RemoveTransientWindowImpl(Window* child);
  static void ReorderWithoutNotification(Window* window,
                                         Window* relative,
                                         mojom::OrderDirection direction);
  // Returns true if the order actually changed.
  static bool ReorderImpl(Window* window,
                          Window* relative,
                          mojom::OrderDirection direction,
                          OrderChangedNotifier* notifier);

  // Returns a pointer to the stacking target that can be used by
  // RestackTransientDescendants.
  static Window** GetStackingTarget(Window* window);

  WindowTreeClient* client_;
  Id server_id_;
  int local_id_ = -1;
  Window* parent_;
  Children children_;

  Window* stacking_target_;
  Window* transient_parent_;
  Children transient_children_;

  bool is_modal_;

  base::ObserverList<WindowObserver> observers_;
  InputEventHandler* input_event_handler_;
  SurfaceIdHandler* surface_id_handler_;

  gfx::Rect bounds_;
  gfx::Insets client_area_;
  std::vector<gfx::Rect> additional_client_areas_;
  std::unique_ptr<gfx::Rect> hit_test_mask_;

  bool visible_;
  float opacity_;
  int64_t display_id_;

  // The client supplied delegate that receives drag events for this
  // window (weak ptr).
  WindowDropTarget* drop_target_ = nullptr;

  // Whether this window can accept events. Initialized to true to
  // match ServerWindow.
  bool can_accept_events_ = true;

  mojom::Cursor cursor_id_;

  SharedProperties properties_;

  // Drawn state of our parent. This is only meaningful for root Windows, in
  // which the parent Window isn't exposed to the client.
  bool parent_drawn_;

  // Value struct to keep the name and deallocator for this property.
  // Key cannot be used for this purpose because it can be char* or
  // WindowProperty<>.
  struct Value {
    const char* name;
    int64_t value;
    PropertyDeallocator deallocator;
  };

  std::map<const void*, Value> prop_map_;

  std::unique_ptr<SurfaceInfo> surface_info_;

  DISALLOW_COPY_AND_ASSIGN(Window);
};

}  // namespace ui

#endif  // SERVICES_UI_PUBLIC_CPP_WINDOW_H_


text:
@interface PodsDummy_Pods_Marslink : NSObject
@end
@implementation PodsDummy_Pods_Marslink
@end


text:
echo $0 # Unquoted variable
var = 42 # Spaces around = in assignments
$foo=42 # $ in assignments

n=0 # Unused variable
if [[ n != 0 ]] # Constant test expressions, should be "$n"
then
echo this is incorrect
fi

PATH="$PATH:~/bin" # Includes tilde in path


text:
using FluentAssertions;

using KataNetHack.Console;
using KataNetHack.Console.PlayerSubsystem;
using KataNetHack.Console.Renderer;

using Xunit;

namespace KataNetHack.Tests
{
    public class RenderableFactoryTests
    {
        [Fact]
        public void CreateRenderable_Player_ReturnsExpectedRenderable()
        {
            var sut = new RenderableFactory();

            var player = new Player(new Location(3, 4));
            Renderable result = sut.CreateRenderable(player);

            result.Source.Should().BeSameAs(player);
            result.Representation.Should().Be(RenderableFactory.PLAYER_REPRESENTATION);
            result.ZIndex.Should().Be(RenderableFactory.PLAYER_ZINDEX);
        }
    }
}


text:
module Gitlab
  class SnippetSearchResults < SearchResults
    include SnippetsHelper

    attr_reader :limit_snippets

    def initialize(limit_snippets, query)
      @limit_snippets = limit_snippets
      @query = query
    end

    def objects(scope, page = nil)
      case scope
      when 'snippet_titles'
        snippet_titles.page(page).per(per_page)
      when 'snippet_blobs'
        snippet_blobs.page(page).per(per_page)
      else
        super
      end
    end

    def snippet_titles_count
      @snippet_titles_count ||= snippet_titles.count
    end

    def snippet_blobs_count
      @snippet_blobs_count ||= snippet_blobs.count
    end

    private

    def snippet_titles
      limit_snippets.search(query).order('updated_at DESC').includes(:author)
    end

    def snippet_blobs
      limit_snippets.search_code(query).order('updated_at DESC').includes(:author)
    end

    def default_scope
      'snippet_blobs'
    end
  end
end


text:
<!DOCTYPE html>

        <?php echo $common; ?>

            <?php echo $header; ?>
            <?php echo $sidebar; ?>

User Accounts

<a href="<?php echo base_url(); ?>auth_admin/dashboard">Dashboard

Users

                            <input type="hidden" alt="alert" class="img-responsive model_img" id="payment_added">
                            <input type="hidden" alt="alert" class="img-responsive model_img" id="payment_failed">
                            <input type="hidden" alt="alert" class="img-responsive model_img" id="user_approved_success">
                            <input type="hidden" alt="alert" class="img-responsive model_img" id="suspend_user_success">

                                            Username
                                            Email
                                            Mobile No.
                                            Earnings
                                            IP Address
                                            Last Login
                                            Email Verified ?
                                            Add Payment
                                            Payments
                                            Status
                                            Suspended
                                            Remove Session

                    <?php echo $footer; ?>

                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Payment

                        <form method="post" id="add_user_payment" enctype="multipart/form-data">

                                <input type="hidden" name="reseller_id" id="reseller_id">
                                <input type="hidden" name="edit_id" id="edit_id">

                                    Earnings:
                                    <input type="text" class="form-control" id="total_earnings" name="total_earnings" readonly="">

                                    Payment Date:
                                    <input type="text" class="form-control" id="payment_date" name='payment_date' placeholder="mm/dd/yyyy">

                                    Payment Mode:
                                    <select class="form-control" name="payment_mode" id="payment_mode">
                                        <option value="">Select Payment Mode</option>
                                        <option value="Cheque">Cheque</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Bitcoin">Bitcoin</option>
                                    </select>

                                    Amount:
                                    <input type="text" class="form-control" id="amount" name="amount" onblur="calculate_amount();">

                                    Tax :
                                    <select class="form-control" name="tax_method" id="tax_method" onchange="calculate_amount();">
                                        <option value="0">Expemted</option>
                                        <option value="15">15 %</option>
                                        <option value="10">10 %</option>
                                    </select>

                                    Net Amount:
                                    <input type="text" class="form-control" id="nettamount" name="nettamount" readonly="">

                                <input type="hidden" name="final_amount" id="final_amount">

                                    Description :
                                    <textarea class="form-control" id="payment_description" name="payment_description"></textarea>

                                <button type="submit" class="btn btn-danger waves-effect waves-light" name="submit_form" id="submit_form">Submit</button>

                        </form>

                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Payment History

                                            Payment Date
                                            Payment Mode
                                            Cheque No.
                                            Trasaction Id
                                            Amount
                                            Tax
                                            Net Amount
                                            Action

                            <button type="button" class="btn btn-danger waves-effect text-left" data-dismiss="modal">Close</button>

                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Approve User

                        <form method="post" id="approve_user">
                            <input type="hidden" name="approving_user" id="approving_user">

Are you sure want to activate this user

                                <button type="button" class="btn btn-info waves-effect" name="approve" id="approve" onclick="approve_user();">Submit</button>

                        </form>

                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Suspend User

                        <form method="post" id="suspend_user">
                            <input type="hidden" name="suspending_user" id="suspending_user">

                                <button type="button" class="btn btn-info waves-effect" name="suspend" id="suspend" onclick="suspend_user_confirm();">Submit</button>

                        </form>


text:
package onFailureIgnore;

import es.bsc.compss.api.COMPSs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class OnFailureIgnore {

    private static final String FILE_NAME = "/tmp/sharedDisk/onFailure1.txt";
    private static final String FILEOUT_NAME1 = "/tmp/sharedDisk/onFailureOut1.txt";
    private static final String FILEOUT_NAME2 = "/tmp/sharedDisk/onFailureOut2.txt";
    private static final int M = 5; // number of tasks to be executed

    public static void main(String[] args) {

        // Failure ignored behavior
        System.out.println("Init on failure : IGNORE FAILURE");
        try {
            onIgnoreFailureFileOutNotGenerated();
            onIgnoreFailure();
        } catch (numberException e) {
            catchException(e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void onIgnoreFailureFileOutNotGenerated() throws numberException {
        deleteFile(FILEOUT_NAME1);
        deleteFile(FILEOUT_NAME2);
        OnFailureIgnoreImpl.processOutParamIgnoreFailure(FILEOUT_NAME1, FILEOUT_NAME2);
        COMPSs.barrier();
    }

    // Ignore the task failure and continue with other tasks execution
    private static void onIgnoreFailure() throws Exception {

        // Create and write first number to file
        initFiles();
        writeFile();

        // Process file contents and if failed continue executing other tasks
        int i = 0;
        for (i = 0; i < M; i++) {
            OnFailureIgnoreImpl.processParamIgnoreFailure(FILE_NAME);
        }

        // Wait for all tasks to finish
        COMPSs.barrier();

        // Get the renamed file
        COMPSs.getFile(FILE_NAME);

        // Shell commands to execute to check contents of file
        ArrayList<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        commands.add(FILE_NAME);

        // ProcessBuilder start
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.redirectErrorStream(true);
        Process process = null;
        try {
            process = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read file content
        readContents(process);

        // Check result
        try {
            if (process.waitFor() != 0) {
                System.out.println("Error: Process cat return value different from 0");
                System.exit(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void readContents(Process process) throws Exception {
        // Read output of file
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        int count = 0;
        try {
            while ((line = br.readLine()) != null)
                if (!line.equals(previous)) {
                    previous = line;
                    out.append(line).append('\n');
                    count = count + 1;
                }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Exception if number of writers has not been correct
        if (count != 1) {
            throw new Exception("Incorrect number of writers " + count);
        }
    }

    private static void initFiles() {
        // Initialize the test file
        try {
            newFile(FILE_NAME);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeFile() throws numberException {
        // Write first number to file
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(FILE_NAME, false));
            writer.write(String.valueOf(1));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Function that creates a new empty file
    private static void newFile(String fileName) throws IOException {
        File file = new File(fileName);
        // Delete previous occurrences of the file
        if (file.exists()) {
            file.delete();
        }
        // Create the file and directories if required
        boolean createdFile = file.createNewFile();
        if (!createdFile) {
            throw new IOException("[ERROR] Cannot create test file");
        }
    }

    private static void deleteFile(String fileName) {
        File file = new File(fileName);
        // Delete previous occurrences of the file
        if (file.exists()) {
            file.delete();
        }
    }

    private static void catchException(numberException e) {
        System.out.println("exception caught!");
    }

}


text:
php-cli
=======

php command lind interface helper


text:
<?php

/**
 * OpenSRS Balance Class
 *
 * @category XMLRPC
 * @package  OpenSRS
 * @author   Lupo Montero <lupo@e-noise.com>
 * @license  http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @link     https://github.com/lupomontero/OpenSRS
 * @since    1.0
 */
class OpenSRS_Balance
{
    /**
     * A reference to the calling OpenSRS object
     *
     * @var OpenSRS
     */
    private $_openrsr;

    /**
     * Constructor
     *
     * @param OpenSRS $openrsr An OpenSRS object used to send the requests.
     *
     * @return void
     * @since  1.0
     */
    public function __construct(OpenSRS $openrsr)
    {
        $this->_openrsr = $openrsr;
    }

    /**
     * Get reseller's account balance.
     *
     * @return float Returns the total amount of money in the account.
     * @since  1.0
     */
    public function getBalance()
    {
        // Build request object
        $request = new OpenSRS_Request("balance", "get_balance");

        // Send request
        $response = $this->_openrsr->send($request);

        // Get response attributes
        $attr = $response->getAttributes();

        // Return balance as float
        return (float) $attr["balance"];
    }
}


text:
mkdir ~/.bintray/
FILE=$HOME/.bintray/.credentials
cat <<EOF >$FILE
realm = Bintray API Realm
host = api.bintray.com
user = $BINTRAY_USER
password = $BINTRAY_API_KEY
EOF

cd $TRAVIS_BUILD_DIR
pwd
sbt publish


text:
(this is removing files from stream and disk so it might not go very well with gulp plugin requirements, so it might get banned :) but I needed this functionality on one of the projects)

## Install

```bash
npm install --save-dev gulp-remove-files
```

## Example

```javascript
var gulp = require('gulp');
var removeFiles = require('gulp-remove-files');

gulp.task('clearHtml', function () {
  gulp.src('./public/*.html')
    .pipe(removeFiles());
});
```

## Options

None

## License

MIT © [Daniel Husar](https://github.com/danielhusar)


text:
MASTER_NODE=$1

echo " "
echo " "
echo "****************************"
echo "* Apache Spark Worker Node *"
echo "****************************"
echo " "

echo " "
echo "Environment Variables: "
echo " "
env

IP=$(ip -o -4 addr list eth0 | perl -n -e 'if (m{inet\s([\d\.]+)\/\d+\s}xms) { print $1 }')
echo " "
echo "WORKER_IP=$IP"
echo " "

#set listener for sigterm an other signals in order to de-register from master node.
function cleanup {
	echo "cleaning stuff..."
	/etc/remote-remove-slave.sh $MASTER_NODE $IP
	echo "done!"
}
trap cleanup SIGTERM TERM 15

## configure the hadoop and spark installations
echo " "
echo "Preparing Apache Spark..."
echo " "
sed s/HOSTNAME/$MASTER_NODE/ $HADOOP_PREFIX/etc/hadoop/core-site.xml.template > $HADOOP_PREFIX/etc/hadoop/core-site.xml
sed s/HOSTNAME/$MASTER_NODE/ $HADOOP_PREFIX/etc/hadoop/yarn-site.xml.template > $HADOOP_PREFIX/etc/hadoop/yarn-site.xml
sed "s/__MASTER__/$MASTER_NODE/;s/__HOSTNAME__/$HOSTNAME/;s/__LOCAL_IP__/$IP/" /tmp/spark-files/spark-env.sh.template > $SPARK_HOME/conf/spark-env.sh
sed s/HOSTNAME/$MASTER_NODE/ $SPARK_HOME/yarn-remote-client/core-site.xml.template > $SPARK_HOME/yarn-remote-client/core-site.xml
sed s/HOSTNAME/$MASTER_NODE/ $SPARK_HOME/yarn-remote-client/yarn-site.xml.template > $SPARK_HOME/yarn-remote-client/yarn-site.xml

echo " "
echo "Adding itself as a slave in Hadoop..."
echo " "
/etc/remote-add-slave.sh $MASTER_NODE $IP $HOSTNAME

echo " "
echo "Starting ssh service..."
echo " "
service ssh start

echo " "
echo "Starting Hadoop Datanode..."
echo " "
$HADOOP_PREFIX/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start datanode
sleep 5

echo " "
echo "Starting Spark Worker..."
echo " "
. $SPARK_HOME/conf/spark-env.sh
$SPARK_HOME/bin/spark-class org.apache.spark.deploy.worker.Worker $MASTER &

if [[ $2 == "-d" ]]; then
	wait
fi

if [[ $2 == "-bash" ]]; then
  /bin/bash
fi


text:
package io.datarouter.metric.counter;

import javax.inject.Singleton;

import io.datarouter.storage.file.Directory;

public interface CountDirectorySupplier{

	Directory getCountsBinaryDtoDirectory();

	@Singleton
	public class NoOpCountDirectorySupplier implements CountDirectorySupplier{

		@Override
		public Directory getCountsBinaryDtoDirectory(){
			throw new IllegalStateException();
		}

	}

}


text:
export * from './classes';
export * from './color-picker.directive';
export * from './color-picker.module';
export * from './color-picker.service';
export * from './highlight.directive';


text:
package de.cosmocode.palava.scope;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.google.common.annotations.Beta;
import com.google.inject.BindingAnnotation;

/**
 * A binding annotation for delegate {@link UnitOfWorkScope}s.
 *
 * @since 2.0
 * @author Willi Schoenborn
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({
    ElementType.METHOD,
    ElementType.PARAMETER
})
@BindingAnnotation
@Beta
public @interface Delegate {

}


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

import com.facebook.presto.operator.aggregation.state.NullableLongState;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.type.SqlType;

@AggregationFunction("sum")
public final class LongSumAggregation
{
    public static final InternalAggregationFunction LONG_SUM = new AggregationCompiler().generateAggregationFunction(LongSumAggregation.class);

    private LongSumAggregation() {}

    @InputFunction
    @IntermediateInputFunction
    public static void sum(NullableLongState state, @SqlType(StandardTypes.BIGINT) long value)
    {
        state.setNull(false);
        state.setLong(state.getLong() + value);
    }

    @OutputFunction(StandardTypes.BIGINT)
    public static void output(NullableLongState state, BlockBuilder out)
    {
        NullableLongState.write(BigintType.BIGINT, state, out);
    }
}