text:
import { hslToRgb, rgbToHsl } from '../lib/hsl.js'

/**
 * A sprite that can be drawn on a 2D canvas.
 * @constructor
 * @param {string|HTMLImageElement|HTMLCanvasElement|Sprite} filename File to load, a graphical element that's already
 * loaded, or another Sprite.
 * @param {string=} filter Filter function to convert the sprite, for example Sprite.turnSolidColored('black')
 * @param {string|HTMLImageElement|HTMLCanvasElement=} fallback Fallback file to load or a graphical element that's
 * already loaded.
 */
const Sprite = function(filename, /* Optional */ filter, fallback) {
    this.filename = filename;
    this.bakeableFilepath = null;
    this.missing = false;
    this.fallback = fallback;
    this.filter = filter;
    Sprite.createdCount++;
    this.loadedListeners = [];
    this.implementsGameutilsSprite = true;
    this._reload();
};

Sprite.prototype.addLoadedListener = function(callback) {
    if (this.loaded) {
        callback();
    }
    else {
        this.loadedListeners.push(callback);
    }
};

Sprite.prototype._callLoadedListeners = function() {
    for (var i = 0; i < this.loadedListeners.length; ++i) {
        this.loadedListeners[i]();
    }
};

/**
 * Reload the Sprite.
 * @protected
 */
Sprite.prototype._reload = function() {
    if (typeof this.filename != typeof '') {
        this.img = this.filename;
        if (this.img instanceof Sprite) {
            var that = this;
            this.img.addLoadedListener(function() {
                that.filename = that.img.img;
                that._reload();
            });
            return;
        }
        this.loaded = true;
        Sprite.loadedCount++;
        this.width = this.img.width;
        this.height = this.img.height;
        if (this.filter !== undefined) {
            this.filter(this);
        }
        this._callLoadedListeners();
    } else {
        var isDataOrHTTP = this.filename.substring(0, 5) === 'data:' ||
                           this.filename.substring(0, 5) === 'http:' ||
                           this.filename.substring(0, 6) === 'https:';
        if (!isDataOrHTTP && Sprite.atlas !== null && Sprite.atlas.hasSpriteImg(Sprite.gfxPath + this.filename)) {
            var that = this;
            this.bakeableFilepath = Sprite.gfxPath + that.filename;
            Sprite.bakeableSpritePaths.push(this.bakeableFilepath);
            Sprite.atlas.img.addLoadedListener(function() {
                that.filename = Sprite.atlas.getSpriteImg(that.bakeableFilepath);
                that._reload();
            });
            return;
        } else {
            this.img = document.createElement('img');
            if (isDataOrHTTP) {
                this.img.src = this.filename;
            } else {
                this.bakeableFilepath = Sprite.gfxPath + this.filename;
                this.img.src = this.bakeableFilepath;
                Sprite.bakeableSpritePaths.push(this.bakeableFilepath);
            }
            var that = this;
            this.loaded = false;
            this.img.onload = function() {
                that.loaded = true;
                Sprite.loadedCount++;
                that.width = that.img.width;
                that.height = that.img.height;
                if (that.filter !== undefined) {
                    that.filter(that);
                }
                that._callLoadedListeners();
            };
            this.img.onerror = function() {
                if (that.fallback) {
                    that.filename = that.fallback;
                    that.fallback = undefined;
                    that._reload();
                    return;
                }
                that.loaded = true;
                that.missing = true;
                if (Sprite.requireAllSpritesLoaded) {
                    console.log('Loading sprite failed ' + that.img.src);
                } else {
                    Sprite.loadedCount++;
                }
                that.img = Sprite.getMissingImg(that.filename);
                that.width = that.img.width;
                that.height = that.img.height;
                that._callLoadedListeners();
            };
        }
    }
};

/**
 * @param {string} filename
 * @return {HTMLCanvasElement} Canvas element with the text "Missing: <filename>"
 */
Sprite.getMissingImg = function(filename) {
    var img = document.createElement('canvas');
    img.width = 150;
    img.height = 20;
    var ctx = img.getContext('2d');
    ctx.textBaseline = 'top';
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.fillStyle = '#000';
    ctx.fillText('Missing: ' + filename, 0, 0);
    return img;
};

/**
 * Path for graphics files. Set this before creating any Sprite objects.
 */
Sprite.gfxPath = 'assets/gfx/';

/**
 * Whether to require that all constructed sprites load their images succesfully. Can be convenient to set to false for
 * game jam type events, should set to true to target Cordova.
 */
Sprite.requireAllSpritesLoaded = false;

/**
 * Baked atlas to load sprites from instead of loading them from relative filenames. SpriteAtlas.
 */
Sprite.atlas = null;

/**
 * List of the paths of all bakeable sprites.
 */
Sprite.bakeableSpritePaths = [];

/**
 * Filter for turning the sprite solid colored.
 */
Sprite.turnSolidColored = function(solidColor) {
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = solidColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = 'destination-in';
        sprite.draw(ctx, 0, 0);
        sprite.img = canvas;
    };
};

/**
 * Filter for generating a different hued variation of the sprite.
 */
Sprite.varyHue = function(options) {
    var defaults = {
        minHue: 0,
        maxHue: 1,
        hueChange: 0
    };
    for(var key in defaults) {
        if(!options.hasOwnProperty(key)) {
            options[key] = defaults[key];
        }
    }
    while (options.hueChange < 0) {
        options.hueChange += 1;
    }
    while (options.hueChange > 1) {
        options.hueChange -= 1;
    }
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        sprite.draw(ctx, 0, 0);
        try {
            var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
        } catch (e) {
            if (e.name == 'SecurityError') {
                if (!Sprite.reportedSecurityError) {
                    Sprite.reportedSecurityError = true;
                    console.log(e.message);
                }
                return;
            }
        }
        for (var i = 0; i < data.data.length; i += 4) {
            var r = data.data[i];
            var g = data.data[i + 1];
            var b = data.data[i + 2];
            var hsl = rgbToHsl(r, g, b);
            if (hsl[0] >= options.minHue && hsl[0] <= options.maxHue) {
                hsl[0] += options.hueChange;
                if (hsl[0] > 1.0) {
                    hsl[0] -= 1.0;
                }
                var rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
                data.data[i] = rgb[0];
                data.data[i + 1] = rgb[1];
                data.data[i + 2] = rgb[2];
            }
        }
        ctx.putImageData(data, 0, 0);
        sprite.img = canvas;
    };
};

/**
 * Filter for generating a variation of the Sprite with colors replaced with others.
 * @param {Object} paletteMap A mapping from RGB source color values to target values. Source colors should be strings
 * in "R, G, B" format. Target colors should be arrays [R, G, B]. In both cases the scale is 0-255.
 * @param {number=} tolerance Tolerance for detecting source colors.
 */
Sprite.repalette = function(paletteMap, tolerance) {
    if (tolerance === undefined) {
        tolerance = 10;
    }
    var palette = [];
    for (var key in paletteMap) {
        if (paletteMap.hasOwnProperty(key)) {
            var sourceRgb = key.split(', ');
            palette.push({
                r: sourceRgb[0],
                g: sourceRgb[1],
                b: sourceRgb[2],
                target: paletteMap[key]
            });
        }
    }
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        sprite.draw(ctx, 0, 0);
        var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < data.data.length; i += 4) {
            var r = data.data[i];
            var g = data.data[i + 1];
            var b = data.data[i + 2];
            for (var j = 0; j < palette.length; ++j) {
                if (Math.abs(r - palette[j].r) < tolerance &&
                    Math.abs(g - palette[j].g) < tolerance &&
                    Math.abs(b - palette[j].b) < tolerance)
                {
                    var rgb = palette[j].target;
                    data.data[i] = rgb[0];
                    data.data[i + 1] = rgb[1];
                    data.data[i + 2] = rgb[2];
                }
            }
        }
        ctx.putImageData(data, 0, 0);
        sprite.img = canvas;
    };
};

Sprite.reportedSecurityError = false;

/**
 * How many Sprite objects have been created.
 */
Sprite.createdCount = 0;
/**
 * How many Sprite objects have been fully loaded.
 */
Sprite.loadedCount = 0;

/**
 * @return {number} Amount of Sprite objects that have been fully loaded per amount that has been created.
 * Name specified as string to support Closure compiler together with loadingbar.js.
 */
Sprite['loadedFraction'] = function() {
    if (Sprite.createdCount === 0) {
        return 1.0;
    }
    return Sprite.loadedCount / Sprite.createdCount;
};

/**
 * Draw this to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} leftX X coordinate of the left edge.
 * @param {number} topY Y coordinate of the top edge.
 */
Sprite.prototype.draw = function(ctx, leftX, topY) {
    if (this.loaded) {
        ctx.drawImage(this.img, leftX, topY);
    }
};

/**
 * Draw this to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} leftX X coordinate of the left edge.
 * @param {number} topY Y coordinate of the top edge.
 * @param {number} sx X coordinate of the left edge in the source image.
 * @param {number} sy Y coordinate of the top edge in the source image.
 * @param {number} sWidth Width of the subrectangle in the source image.
 * @param {number} sHeight Height of the subrectangle in the source image.
 */
Sprite.prototype.drawCropped = function(ctx, leftX, topY, sx, sy, sWidth, sHeight) {
    if (this.loaded && sWidth > 0 && sHeight > 0) {
        ctx.drawImage(this.img, sx, sy, sWidth, sHeight, leftX, topY, sWidth, sHeight);
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scale Scale to scale the sprite with (relative to its center).
 */
Sprite.prototype.drawRotated = function(ctx, centerX, centerY, angleRadians, /* optional */ scale) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scale === undefined) {
        scale = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scale, scale);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scaleX Scale to scale the sprite with along the x axis (relative to its center).
 * @param {number} scaleY Scale to scale the sprite with along the y axis (relative to its center).
 */
Sprite.prototype.drawRotatedNonUniform = function(ctx, centerX, centerY, angleRadians, scaleX, scaleY) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scaleX === undefined) {
        scaleX = 1.0;
    }
    if (scaleY === undefined) {
        scaleY = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scaleX, scaleY);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite centered on the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvas = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height * 0.5, 0, scale);
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Fill the canvas horizontally with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasHorizontallyFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = ctx.canvas.width / this.width;
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Just here to make Sprite and AnimatedSpriteInstance interchangeable.
 */
Sprite.prototype.update = function() {
};

export { Sprite }


text:
package com.github.scaronthesky.eternalwinterwars.model.units.bluntarmamentbehaviour;

public class GoodDefense implements BluntArmamentBehaviour {

	@Override
	public int defend() {
		return 3;
	}

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.botservice.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.botservice.fluent.models.BotChannelInner;
import com.azure.resourcemanager.botservice.models.RegenerateKeysChannelName;
import com.azure.resourcemanager.botservice.models.SiteInfo;

/** An instance of this class provides access to all the operations defined in DirectLinesClient. */
public interface DirectLinesClient {
    /**
     * Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService resource.
     *
     * @param resourceGroupName The name of the Bot resource group in the user subscription.
     * @param resourceName The name of the Bot resource.
     * @param channelName The name of the Channel resource for which keys are to be regenerated.
     * @param parameters The parameters to provide for the created bot.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return bot channel resource definition.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    BotChannelInner regenerateKeys(
        String resourceGroupName, String resourceName, RegenerateKeysChannelName channelName, SiteInfo parameters);

    /**
     * Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService resource.
     *
     * @param resourceGroupName The name of the Bot resource group in the user subscription.
     * @param resourceName The name of the Bot resource.
     * @param channelName The name of the Channel resource for which keys are to be regenerated.
     * @param parameters The parameters to provide for the created bot.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return bot channel resource definition along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<BotChannelInner> regenerateKeysWithResponse(
        String resourceGroupName,
        String resourceName,
        RegenerateKeysChannelName channelName,
        SiteInfo parameters,
        Context context);
}


text:
Replace with ugly alert(), confirm(), and prompt() with bootstrap modals.

## Requirements

 * [jQuery](http://jquery.com)
 * [Bootstrap 2.0.0+](http://twitter.github.com/bootstrap)

## Usage

After jQuery and Bootstrap includes:

	<script src="path/to/bootstrap-dialogs.js"></script>

### Alert

    $.alert('Hello World!', function () {
		console.log('"OK" has been pressed');
	});

### Confirm

    $.confirm('Say hello?', function (response) {
		if (response) {
			console.log('"OK" has been pressed');
		}
		else {
			console.log('"Cancel" has been pressed');
		}
	});

### Prompt

    $.prompt('Who are you?', function (response) {
		console.log('User has entered: ' + response);
	});

With a default value for the input

    $.prompt('Who are you?', 'John Smith', function (response) {
		console.log('User has entered: ' + response);
	});

## Todo

* Minify it

## License

[The MIT license](http://opensource.org/licenses/MIT)


text:
package org.spongepowered.api.data.type;

import org.spongepowered.api.util.generator.dummy.DummyObjectProvider;

/**
 * An enumeration of known vanilla {@link SkeletonType}s.
 */
public final class SkeletonTypes {

    // SORTFIELDS:ON

    public static final SkeletonType NORMAL = DummyObjectProvider.createFor(SkeletonType.class, "NORMAL");

    public static final SkeletonType STRAY = DummyObjectProvider.createFor(SkeletonType.class, "STRAY");

    public static final SkeletonType WITHER = DummyObjectProvider.createFor(SkeletonType.class, "WITHER");

    // SORTFIELDS:OFF

    private SkeletonTypes() {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2019 Google LLC
  ~
  ~ 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
  ~
  ~     https://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.
-->
<resources>

    <string name="playstore_tagline">دستیار شما برای پیمایش I/O، چه به‌صورت حضوری شرکت داشته باشید چه از راه دور.</string>

    <string name="playstore_change">به‌روزرسانی‌شده برای Google I/O 2018\n• رزرو صندلی برای رویدادها جلوتر از زما‌ن‌بندی\n• مطالعه اطلاعات مهم درباره «رویداد»، جزئیات «سفر» و سوالات متداول.</string>
    <string name="playstore_required_permissions">مجوزهای لازم</string>
    <string name="playstore_optional_permissions">مجوزهای اختیاری</string>
    <string name="playstore_permission_location_information">اطلاعات مکان: برای نشان دادن نقشه محل برگزاری در اطراف مکان کاربر نیاز است.</string>
</resources>


text:
using Microsoft.Deployment.WindowsInstaller;
using System.Linq;
using WixSharp;
using WixSharp.CommonTasks;
using WixSharp.Controls;

public class EmptyDialogSetup
{
    public static void Build()
    {
        var project = new Project("CustomDialogTest",
                          new Dir(@"%ProgramFiles%\My Company\My Product",
                              new File("setup.exe")));

        //Injects CLR dialog EmptyDialog between MSI dialogs InsallDirDlg and VerifyReadyDlg.
        //Passes custom action ShowCustomDialog for instantiating and popping up the CLR dialog.

        project.InjectClrDialog("ShowCustomDialog", NativeDialogs.InstallDirDlg, NativeDialogs.VerifyReadyDlg)
               .RemoveDialogsBetween(NativeDialogs.WelcomeDlg, NativeDialogs.InstallDirDlg);

        project.Actions.OfType<ManagedAction>()
                       .Single()
                       .AddRefAssembly(typeof(ExternalAsm.Utils).Assembly.Location);

        //or as the next commented code line
        //project.DefaultRefAssemblies.Add(typeof(ExternalAsm.Utils).Assembly.Location);

        Compiler.PreserveTempFiles = true;
        Compiler.BuildMsi(project);
    }

    [CustomAction]
    public static ActionResult ShowCustomDialog(Session session)
    {
        return WixCLRDialog.ShowAsMsiDialog(new EmptyDialog(session));
    }
}


text:
using namespace OpenZWave;

enum AlarmCmd
{
	AlarmCmd_Get	= 0x04,
	AlarmCmd_Report = 0x05
};

enum
{
	AlarmIndex_Type = 0,
	AlarmIndex_Level
};

//-----------------------------------------------------------------------------
// <Alarm::RequestState>
// Request current state from the device
//-----------------------------------------------------------------------------
bool Alarm::RequestState
(
	uint32 const _requestFlags,
	uint8 const _instance,
	Driver::MsgQueue const _queue
)
{
	if( _requestFlags & RequestFlag_Dynamic )
	{
		return RequestValue( _requestFlags, 0, _instance, _queue );
	}

	return false;
}

//-----------------------------------------------------------------------------
// <Alarm::RequestValue>
// Request current value from the device
//-----------------------------------------------------------------------------
bool Alarm::RequestValue
(
	uint32 const _requestFlags,
	uint8 const _dummy1,	// = 0 (not used)
	uint8 const _instance,
	Driver::MsgQueue const _queue
)
{
	if( IsGetSupported() )
	{
		Msg* msg = new Msg( "AlarmCmd_Get", GetNodeId(), REQUEST, FUNC_ID_ZW_SEND_DATA, true, true, FUNC_ID_APPLICATION_COMMAND_HANDLER, GetCommandClassId() );
		msg->SetInstance( this, _instance );
		msg->Append( GetNodeId() );
		msg->Append( 2 );
		msg->Append( GetCommandClassId() );
		msg->Append( AlarmCmd_Get );
		msg->Append( GetDriver()->GetTransmitOptions() );
		GetDriver()->SendMsg( msg, _queue );
		return true;
	} else {
		Log::Write(  LogLevel_Info, GetNodeId(), "AlarmCmd_Get Not Supported on this node");
	}
	return false;
}

//-----------------------------------------------------------------------------
// <Alarm::HandleMsg>
// Handle a message from the Z-Wave network
//-----------------------------------------------------------------------------
bool Alarm::HandleMsg
(
	uint8 const* _data,
	uint32 const _length,
	uint32 const _instance	// = 1
)
{
	if (AlarmCmd_Report == (AlarmCmd)_data[0])
	{
		// We have received a report from the Z-Wave device
		Log::Write( LogLevel_Info, GetNodeId(), "Received Alarm report: type=%d, level=%d", _data[1], _data[2] );

		ValueByte* value;
		if( (value = static_cast<ValueByte*>( GetValue( _instance, AlarmIndex_Type ) )) )
		{
			value->OnValueRefreshed( _data[1] );
			value->Release();
		}
		if( (value = static_cast<ValueByte*>( GetValue( _instance, AlarmIndex_Level ) )) )
		{
			value->OnValueRefreshed( _data[2] );
			value->Release();
		}
		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// <Alarm::CreateVars>
// Create the values managed by this command class
//-----------------------------------------------------------------------------
void Alarm::CreateVars
(
	uint8 const _instance
)
{
	if( Node* node = GetNodeUnsafe() )
	{
	  	node->CreateValueByte( ValueID::ValueGenre_User, GetCommandClassId(), _instance, AlarmIndex_Type, "Alarm Type", "", true, false, 0, 0 );
		node->CreateValueByte( ValueID::ValueGenre_User, GetCommandClassId(), _instance, AlarmIndex_Level, "Alarm Level", "", true, false, 0, 0 );
	}
}


text:
package org.luaj.vm2.lib.jse;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.RandomAccessFile;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.IoLib;
import org.luaj.vm2.lib.LibFunction;

/**
 * Subclass of {@link IoLib} and therefore {@link LibFunction} which implements
 * the lua standard {@code io} library for the JSE platform.
 *

 * It uses RandomAccessFile to implement seek on files.
 *

 * Typically, this library is included as part of a call to
 * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
 *
 *

 * {
 * 	@code
 * 	Globals globals = JsePlatform.standardGlobals();
 * 	globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
 * }
 *

 *

 * For special cases where the smallest possible footprint is desired, a minimal
 * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
 * using code such as:
 *
 *

 * {
 * 	@code
 * 	Globals globals = new Globals();
 * 	globals.load(new JseBaseLib());
 * 	globals.load(new PackageLib());
 * 	globals.load(new JseIoLib());
 * 	globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
 * }
 *

 *

 * However, other libraries such as MathLib are not loaded in this
 * case.
 *

 * This has been implemented to match as closely as possible the behavior in the
 * corresponding library in C.
 *
 * @see LibFunction
 * @see org.luaj.vm2.lib.jse.JsePlatform
 * @see org.luaj.vm2.lib.jme.JmePlatform
 * @see IoLib
 * @see org.luaj.vm2.lib.jme.JmeIoLib
 * @see Lua 5.2 I/O Lib
 *      Reference
 */
public class JseIoLib extends IoLib {

	@Override
	protected File wrapStdin() throws IOException {
		return new StdinFile();
	}

	@Override
	protected File wrapStdout() throws IOException {
		return new StdoutFile(FTYPE_STDOUT);
	}

	@Override
	protected File wrapStderr() throws IOException {
		return new StdoutFile(FTYPE_STDERR);
	}

	@Override
	protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode,
		boolean binaryMode) throws IOException {
		RandomAccessFile f = new RandomAccessFile(filename, readMode? "r": "rw");
		if (appendMode) {
			f.seek(f.length());
		} else {
			if (!readMode)
				f.setLength(0);
		}
		return new FileImpl(f);
	}

	@Override
	protected File openProgram(String prog, String mode) throws IOException {
		final Process p = Runtime.getRuntime().exec(prog);
		return "w".equals(mode)? new FileImpl(p.getOutputStream()): new FileImpl(p.getInputStream());
	}

	@Override
	protected File tmpFile() throws IOException {
		java.io.File f = java.io.File.createTempFile(".luaj", "bin");
		f.deleteOnExit();
		return new FileImpl(new RandomAccessFile(f, "rw"));
	}

	private static void notimplemented() {
		throw new LuaError("not implemented");
	}

	private final class FileImpl extends File {
		private final RandomAccessFile file;
		private final InputStream      is;
		private final OutputStream     os;
		private boolean                closed   = false;
		private boolean                nobuffer = false;

		private FileImpl(RandomAccessFile file, InputStream is, OutputStream os) {
			this.file = file;
			this.is = is != null? is.markSupported()? is: new BufferedInputStream(is): null;
			this.os = os;
		}

		private FileImpl(RandomAccessFile f) {
			this(f, null, null);
		}

		private FileImpl(InputStream i) {
			this(null, i, null);
		}

		private FileImpl(OutputStream o) {
			this(null, null, o);
		}

		@Override
		public String tojstring() {
			return "file (" + (this.closed? "closed": String.valueOf(this.hashCode())) + ")";
		}

		@Override
		public boolean isstdfile() {
			return file == null;
		}

		@Override
		public void close() throws IOException {
			closed = true;
			if (file != null) {
				file.close();
			}
		}

		@Override
		public void flush() throws IOException {
			if (os != null)
				os.flush();
		}

		@Override
		public void write(LuaString s) throws IOException {
			if (os != null)
				os.write(s.m_bytes, s.m_offset, s.m_length);
			else if (file != null)
				file.write(s.m_bytes, s.m_offset, s.m_length);
			else
				notimplemented();
			if (nobuffer)
				flush();
		}

		@Override
		public boolean isclosed() {
			return closed;
		}

		@Override
		public int seek(String option, int pos) throws IOException {
			if (file != null) {
				if ("set".equals(option)) {
					file.seek(pos);
				} else if ("end".equals(option)) {
					file.seek(file.length()+pos);
				} else {
					file.seek(file.getFilePointer()+pos);
				}
				return (int) file.getFilePointer();
			}
			notimplemented();
			return 0;
		}

		@Override
		public void setvbuf(String mode, int size) {
			nobuffer = "no".equals(mode);
		}

		// get length remaining to read
		@Override
		public int remaining() throws IOException {
			return file != null? (int) (file.length()-file.getFilePointer()): -1;
		}

		// peek ahead one character
		@Override
		public int peek() throws IOException {
			if (is != null) {
				is.mark(1);
				int c = is.read();
				is.reset();
				return c;
			} else if (file != null) {
				long fp = file.getFilePointer();
				int c = file.read();
				file.seek(fp);
				return c;
			}
			notimplemented();
			return 0;
		}

		// return char if read, -1 if eof, throw IOException on other exception
		@Override
		public int read() throws IOException {
			if (is != null)
				return is.read();
			else if (file != null) {
				return file.read();
			}
			notimplemented();
			return 0;
		}

		// return number of bytes read if positive, -1 if eof, throws IOException
		@Override
		public int read(byte[] bytes, int offset, int length) throws IOException {
			if (file != null) {
				return file.read(bytes, offset, length);
			} else if (is != null) {
				return is.read(bytes, offset, length);
			} else {
				notimplemented();
			}
			return length;
		}
	}

	private final class StdoutFile extends File {
		private final int file_type;

		private StdoutFile(int file_type) {
			this.file_type = file_type;
		}

		@Override
		public String tojstring() {
			return "file (" + this.hashCode() + ")";
		}

		private PrintStream getPrintStream() { return file_type == FTYPE_STDERR? globals.STDERR: globals.STDOUT; }

		@Override
		public void write(LuaString string) throws IOException {
			getPrintStream().write(string.m_bytes, string.m_offset, string.m_length);
		}

		@Override
		public void flush() throws IOException {
			getPrintStream().flush();
		}

		@Override
		public boolean isstdfile() {
			return true;
		}

		@Override
		public void close() throws IOException {
			// do not close std files.
		}

		@Override
		public boolean isclosed() {
			return false;
		}

		@Override
		public int seek(String option, int bytecount) throws IOException {
			return 0;
		}

		@Override
		public void setvbuf(String mode, int size) {
		}

		@Override
		public int remaining() throws IOException {
			return 0;
		}

		@Override
		public int peek() throws IOException, EOFException {
			return 0;
		}

		@Override
		public int read() throws IOException, EOFException {
			return 0;
		}

		@Override
		public int read(byte[] bytes, int offset, int length) throws IOException {
			return 0;
		}
	}

	private final class StdinFile extends File {
		private StdinFile() {
		}

		@Override
		public String tojstring() {
			return "file (" + this.hashCode() + ")";
		}

		@Override
		public void write(LuaString string) throws IOException {
		}

		@Override
		public void flush() throws IOException {
		}

		@Override
		public boolean isstdfile() {
			return true;
		}

		@Override
		public void close() throws IOException {
			// do not close std files.
		}

		@Override
		public boolean isclosed() {
			return false;
		}

		@Override
		public int seek(String option, int bytecount) throws IOException {
			return 0;
		}

		@Override
		public void setvbuf(String mode, int size) {
		}

		@Override
		public int remaining() throws IOException {
			return -1;
		}

		@Override
		public int peek() throws IOException, EOFException {
			globals.STDIN.mark(1);
			int c = globals.STDIN.read();
			globals.STDIN.reset();
			return c;
		}

		@Override
		public int read() throws IOException, EOFException {
			return globals.STDIN.read();
		}

		@Override
		public int read(byte[] bytes, int offset, int length) throws IOException {
			return globals.STDIN.read(bytes, offset, length);
		}
	}
}


text:
<?php
require_once("../support/config.php");

if(!AllowUser(array(1,2))){
        redirect("index.php");
    }

$employees=array();
//var_dump($_GET);
if(!empty($_GET['employees_id'])){
    if($_GET['employees_id']=='NULL' && AllowUser(array(1))){
        $employees=$con->myQuery("SELECT id,code,CONCAT(last_name,', ',first_name,' ',middle_name) as employee FROM employees WHERE is_deleted=0 AND is_terminated=0")->fetchAll(PDO::FETCH_ASSOC);
    }else{
        if(AllowUser(array(1))){
            if(is_numeric($_GET['employees_id'])){
            $employees=$con->myQuery("SELECT id,code,CONCAT(last_name,', ',first_name,' ',middle_name) as employee FROM employees WHERE is_deleted=0 AND is_terminated=0 AND id=?",array($_GET['employees_id']))->fetchAll(PDO::FETCH_ASSOC);
            }
        }
        else{
            $employees=$con->myQuery("SELECT id,code,CONCAT(last_name,', ',first_name,' ',middle_name) as employee FROM employees WHERE is_deleted=0 AND is_terminated=0 AND id=?",array($_SESSION[WEBAPP]['user']['employee_id']))->fetchAll(PDO::FETCH_ASSOC);
        }
    }
}
else{
		if(AllowUser(array(1))){
			$employees=$con->myQuery("SELECT id,code,CONCAT(last_name,', ',first_name,' ',middle_name) as employee FROM employees WHERE is_deleted=0 AND is_terminated=0")->fetchAll(PDO::FETCH_ASSOC);
		}
		else{

        $employees=$con->myQuery("SELECT id,code,CONCAT(last_name,', ',first_name,' ',middle_name) as employee FROM employees WHERE is_deleted=0 AND is_terminated=0 AND id=?",array($_SESSION[WEBAPP]['user']['employee_id']))->fetchAll(PDO::FETCH_ASSOC);
		}
}

//$limit=$_GET['length'];
try {
    $date_start=new DateTime($_GET['date_from']);
    $date_end=new DateTime($_GET['date_to']);
    $period = new DatePeriod(
         $date_start,
         new DateInterval('P1D'),
         $date_end
    );

    $data=array();
    $index=count($data);

    foreach ($employees as $employee) {
        $use_ot=array();
        foreach ($period as $key => $date) {
            $data[$index]['code']=$employee['code'];
            $data[$index]['code']=$employee['code'];
            $data[$index]['employee']=$employee['employee'];
            $data[$index]['ot']=0;
            $data[$index]['date']=$date->format("Y-m-d");
            $data[$index]['status']='Regular Day';

            $time_ins=$con->myQuery("SELECT in_time,out_time,id,note FROM `attendance` WHERE employees_id=? AND DATE(in_time)=? ORDER BY in_time ASC LIMIT 1",array($employee['id'],$date->format("Y-m-d")))->fetch(PDO::FETCH_ASSOC);
            $time_outs=$con->myQuery("SELECT in_time,out_time,id,note FROM `attendance` WHERE employees_id=? AND DATE(in_time)=? ORDER BY out_time DESC LIMIT 1",array($employee['id'],$date->format("Y-m-d")))->fetch(PDO::FETCH_ASSOC);

            $data[$index]['in_time']=!empty($time_ins['in_time'])?$time_ins['in_time']:'';
            $data[$index]['out_time']=!empty($time_outs['out_time'])?$time_outs['out_time']:'';
            $data[$index]['note']=(!empty($time_ins['note'])?"Time in: ".$time_ins['note']:''). (!empty($time_outs['note'])?" Time out: ".$time_outs['note']:'');

            $leaves=$con->myQuery("SELECT id,remark FROM `employees_leaves` WHERE employee_id=? AND ? BETWEEN date_start AND date_end AND status='Approved'",array($employee['id'],$date->format("Y-m-d")))->fetch(PDO::FETCH_ASSOC);
            if(!empty($leaves)){

                $data[$index]['status']=$leaves['remark']=="L"?"Leave":"Leave Without Pay";
            }

            $ots=$con->myQuery("SELECT id,no_hours FROM employees_ot WHERE employees_id=? AND ? BETWEEN date(date_from) AND date(date_to) AND status='Approved'".(!empty($use_ot)?" AND id NOT IN (".implode(",",$use_ot) .")":''),array($employee['id'],$date->format("Y-m-d")))->fetchAll(PDO::FETCH_ASSOC);

            foreach ($ots as $key => $ot) {
                $data[$index]['ot']+=$ot['no_hours'];
                $use_ot[]=$ot['id'];
            }

            $obs=$con->myQuery("SELECT COUNT(id) FROM employees_ob WHERE employees_id=? AND ? BETWEEN date(date_from) AND date(date_to) AND status='Approved'",array($employee['id'],$date->format("Y-m-d")))->fetchColumn();
            if(!empty($obs)){
                $data[$index]['status']='Official Business';
            }
            //echo $date->format("Y-m-d");
            $index++;
        }
    }

} catch (Exception $e) {
    //echo $e;
    $data=array();
}

echo json_encode($data);
die;
$bindings=jp_bind($bindings);
$complete_query="SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", SSP::pluck($columns, 'db'))."`,`employees_id`
             FROM `attendance` {$where} {$order} {$limit}";
            // echo $complete_query;
             //var_dump($bindings);
$data=$con->myQuery($complete_query,$bindings)->fetchAll();
$recordsFiltered=$con->myQuery("SELECT FOUND_ROWS();")->fetchColumn();

$recordsTotal=$con->myQuery("SELECT COUNT(id) FROM `attendance` {$where};",$bindings)->fetchColumn();

$json['draw']=isset ( $request['draw'] ) ?intval( $request['draw'] ) :0;
$json['recordsTotal']=$recordsFiltered;
$json['recordsFiltered']=$recordsFiltered;
$json['data']=SSP::data_output($columns,$data);

echo json_encode($json);
die;


text:
Small library to extract peaks from an array of audio samples or a webaudio AudioBuffer.

[![npm](https://img.shields.io/npm/dm/webaudio-peaks.svg)](https://www.npmjs.com/package/webaudio-peaks)

## Installation

`npm install webaudio-peaks --save`

## Basic Usage

```javascript
var extractPeaks = require("webaudio-peaks");

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
//decode an ArrayBuffer into an AudioBuffer
audioCtx.decodeAudioData(audioData, function (decodedData) {
  //calculate peaks from an AudioBuffer
  var peaks = extractPeaks(decodedData, 10000, true);
});
```

### extractPeaks(source, samplesPerPixel, isMono, cueIn, cueOut, bits)
function to extract peaks from a TypedArray, or AudioBuffer

**Params**

- source `TypedArray|AudioBuffer` - A source of audio samples.
- samplesPerPixel `number` - Number of samples used to calculate a single peak.
- isMono `boolean` - Combine all channels into one array of peaks or not.
- cueIn `number` - Sample to begin at. The offset is inclusive.
- cueOut `number` - Sample to end at. The offset is exclusive.
- bits `(8|16|32)` - Resolution of calculated peaks.

**Returns**: `object`

```javascript
{
  length: `number`; //Number of calculated peaks,
  //Computed peak data, length ==  #channels or 1 if isMono == true
  //Each entry of type `Int{bits}Array`
  data: `Array`;
  bits: `(8|16|32)`; //Resolution of calculated peaks.
}
```

## License

[MIT License](http://doge.mit-license.org)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NHibernate.Caches.Redis
{
    public delegate void RedisCacheEventHandler<TEventArgs>(RedisCache sender, TEventArgs e);
}


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

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>amStock Example</title>
		<link rel="stylesheet" href="../amcharts/style.css"	type="text/css">


text:
package org.rakam.kume.util;

import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;

public class FutureUtil {
    public static class MultipleFutureListener<V> {
        final int expected;
        CompletableFuture<V> f;
        private int current = 0;
        private V val;

        public MultipleFutureListener(int expected) {
            this.expected = expected;
            if(expected > 0)
                f = new CompletableFuture<>();
            else
                f = CompletableFuture.completedFuture(null);
        }

        public static MultipleFutureListener from(Stream<CompletableFuture> stream) {
            MultipleFutureListener l = new MultipleFutureListener((int) stream.count());
            stream.forEach(f -> f.thenAccept((v) -> {
                l.current++;
                l.val = v;
                l.runIfDone();
            }));
            return l;
        }

        public CompletableFuture<V> get() {
            return f;
        }

        public void increment() {
            current++;
            runIfDone();
        }

        private void runIfDone() {
            if (current >= expected)
                f.complete(val);
        }

        public void listen(CompletableFuture<V> f) {
            f.thenAccept((v) -> {
                current++;
                // detect inconsistency
                val = v;
                runIfDone();
            });
        }
    }
}


text:
(function () {
    'use strict';
    var controllerId = 'branches';
    angular.module('app').controller(controllerId, ['common', 'datacontext', 'bootstrap.dialog','$location', branches]);

    function branches(common, datacontext, dialog, $location) {
        var getLogFn = common.logger.getLogFn;
        var logError = getLogFn(controllerId, "error");
        var logSuccess = getLogFn(controllerId, "success");
        common.hideNavi();
        var removeItem = breeze.core.arrayRemoveItem;
        var vm = this;
        vm.busyMessage = 'Please wait ...';
        vm.isBusy = false;
        vm.spinnerOptions = {
            radius: 40,
            lines: 7,
            length: 0,
            width: 30,
            speed: 1.7,
            corners: 1.0,
            trail: 100,
            color: '#F58A00'
        };

        vm.title = 'Branches';
        vm.sort = {
            sortingOrder: 'BranchDisplayName',
            reverse: false
        };
        vm.branchesCount = 0;
        vm.branchesFilteredCount = 0;
        vm.items = [];
        vm.paging = {
            currentPage: 1,
            maxPagesToShow: 5,
            pageSize: 10
        };
        vm.pageChanged = pageChanged;

        Object.defineProperty(vm.paging, "pageCount", {
            get: function () {
                return Math.floor(vm.branchesFilteredCount / vm.paging.pageSize) + 1;
            }
        });

        function pageChanged(e) {
            e && (vm.paging.currentPage = e, activate());
        }

        vm.sort_by = function (newSortingOrder) {
            var sort = vm.sort;

            if (sort.sortingOrder == newSortingOrder) {
                sort.reverse = !sort.reverse;
            }

            sort.sortingOrder = newSortingOrder;
        };

        vm.selectedCls = function (column) {

            if (column == vm.sort.sortingOrder) {
                return ('fa fa-chevron-' + ((vm.sort.reverse) ? 'down' : 'up'));
            }
            else {
                return 'fa fa-sort';
            }
        };

        vm.editBranche = function (e) {
            e && e.Id && $location.path("/branches/" + e.Id);
        }

        vm.removeBranch = function (item) {
            return dialog.deleteDialog(item.BranchDisplayName).then(function() {
                toggleSpinner(true);
                return datacontext.removeBranch(item).done(function (result) {
                    var scope = angular.element($("#branches-view")).scope();
                    if (result.Succeeded) {
                        scope.$apply(function () {
                            removeItem(vm.items, item);
                            logSuccess(result.Message);
                            scope.vm.isBusy = false;
                        });
                    } else {
                        vm.resultDialog("Error", result.Message);
                    }
                }).always(function () {
                    toggleSpinner(false);
                });
            }).catch(function (e) { });
        }

        vm.createNew = function() {
            $location.path("/newbranch");
        }

        activate();

        function activate() {
            common.activateController([getBranches()], controllerId)
                .then(function () { });
        }

        function getBranches() {
            return datacontext.getBranches(vm.paging.currentPage - 1, vm.paging.pageSize).then(function (data) {
                return vm.items = data.results, vm.branchesCount = data.inlineCount, vm.branchesFilteredCount = data.inlineCount;
            }).fail(queryFailed);
        }

        function toggleSpinner(on) { vm.isBusy = on; }
        vm.resultDialog = function (title, message) {
            return dialog.resultDialog(title, message, "OK").then(function () { }).catch(function (e) { });
        }

        function queryFailed(error) {
            toggleSpinner(false);
            logError(error.message, "Query failed", true);
        }
    }
})();


text:
class BaseQuery
  include Mongoid::Document
  store_in collection: 'queries'

  field :title, type: String
  field :description, type: String
  field :filter, type: String
  field :map, type: String
  field :reduce, type: String
  field :query_structure, type: Hash

  field :generated, type: Boolean

  validates_presence_of :title

end


text:
package cmd

import (
	"io"
	"os"

	"github.com/spf13/cobra"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
	cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
)

func NewCmdApiVersions(f *cmdutil.Factory, out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use: "api-versions",
		// apiversions is deprecated.
		Aliases: []string{"apiversions"},
		Short:   "Print available API versions.",
		Run: func(cmd *cobra.Command, args []string) {
			err := RunApiVersions(f, out)
			cmdutil.CheckErr(err)
		},
	}
	return cmd
}

func RunApiVersions(f *cmdutil.Factory, out io.Writer) error {
	if os.Args[1] == "apiversions" {
		printDeprecationWarning("api-versions", "apiversions")
	}

	client, err := f.Client()
	if err != nil {
		return err
	}

	kubectl.GetApiVersions(out, client)
	return nil
}


text:
<?php
namespace TYPO3\CMS\Rtehtmlarea\Extension;

use TYPO3\CMS\Rtehtmlarea\RteHtmlAreaApi;

/**
 * Undo Redo plugin for htmlArea RTE
 */
class UndoRedo extends RteHtmlAreaApi
{
    /**
     * The name of the plugin registered by the extension
     *
     * @var string
     */
    protected $pluginName = 'UndoRedo';

    /**
     * The comma-separated list of button names that the registered plugin is adding to the htmlArea RTE toolbar
     *
     * @var string
     */
    protected $pluginButtons = 'undo,redo';

    /**
     * The name-converting array, converting the button names used in the RTE PageTSConfing to the button id's used by the JS scripts
     *
     * @var array
     */
    protected $convertToolbarForHtmlAreaArray = [
        'undo' => 'Undo',
        'redo' => 'Redo'
    ];

    /**
     * Return JS configuration of the htmlArea plugins registered by the extension
     *
     * @return string JS configuration for registered plugins
     */
    public function buildJavascriptConfiguration()
    {
        return '';
    }
}


text: Source code for the LSMaker iOS app.


text:
// sample-metadata:
//  title: Creates a user-managed instance configuration.
//  usage: node instance-config-create <INSTANCE_CONFIG_ID> <BASE_INSTANCE_CONFIG_ID> <PROJECT_ID>

'use strict';

function main(
  instanceConfigId = 'custom-my-instance-config',
  baseInstanceConfigId = 'my-base-instance-config',
  projectId = 'my-project-id'
) {
  // [START spanner_create_instance_config]

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const instanceConfigId = 'custom-my-instance-config-id'
  // const baseInstanceConfigId = 'my-base-instance-config-id';
  // const projectId = 'my-project-id';

  // Imports the Google Cloud client library
  const {Spanner} = require('@google-cloud/spanner');

  // Creates a client
  const spanner = new Spanner({
    projectId: projectId,
  });
  async function createInstanceConfig() {
    // Creates a new instance config
    const instanceConfig = spanner.instanceConfig(instanceConfigId);
    try {
      const [baseInstanceConfig] = await spanner.getInstanceConfig(
        baseInstanceConfigId
      );
      console.log(`Creating instance config ${instanceConfig.formattedName_}.`);
      const [, operation] = await instanceConfig.create({
        displayName: instanceConfigId,
        baseConfig: baseInstanceConfig.name,
        replicas: baseInstanceConfig.replicas.concat(
          baseInstanceConfig.optionalReplicas[0]
        ),
      });
      console.log(
        `Waiting for create operation for ${instanceConfig.id} to complete...`
      );
      await operation.promise();
      console.log(`Created instance config ${instanceConfigId}.`);
    } catch (err) {
      console.error(
        'ERROR: Creating instance config ',
        instanceConfigId,
        ' failed with error message ',
        err
      );
    }
  }
  createInstanceConfig();
  // [END spanner_create_instance_config]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
package custom.view;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import xyz.anmai.easybill.R;

public class GalleryAdapter extends
        RecyclerView.Adapter<GalleryAdapter.ViewHolder>
{
    /**
     * ItemClick的回调接口
     * @author anmai
     */
    public interface OnItemClickLitener
    {
        void onItemClick(View view, int position);
    }

    private OnItemClickLitener mOnItemClickLitener;

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener)
    {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    private LayoutInflater mInflater;
    private TreeMap<Integer, String> mDatas;

    public GalleryAdapter(Context context, TreeMap<Integer, String> datats)
    {
        mInflater = LayoutInflater.from(context);
        mDatas = datats;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        public ViewHolder(View arg0)
        {
            super(arg0);
        }

        ImageView mImg;
        TextView mTxt;
    }

    @Override
    public int getItemCount()
    {
        return mDatas.size();
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
    {
        View view = mInflater.inflate(R.layout.category_recyclerview_item,
                viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);

        viewHolder.mImg = (ImageView) view
                .findViewById(R.id.id_index_gallery_item_image);
        viewHolder.mTxt = (TextView) view
                .findViewById(R.id.id_index_gallery_item_text);
        return viewHolder;
    }

    /**
     * 设置值
     */
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i)
    {
        viewHolder.mImg.setImageResource((int) mDatas.keySet().toArray()[i]);
        viewHolder.mTxt.setText((String)mDatas.values().toArray()[i]);

        //如果设置了回调,则设置点击事件
        if (mOnItemClickLitener != null)
        {
            viewHolder.itemView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    mOnItemClickLitener.onItemClick(viewHolder.itemView, i);
                }
            });

        }
    }

}


text:
namespace ui {

// TableColumn -----------------------------------------------------------------

TableColumn::TableColumn()
    : id(0),
      title(),
      alignment(LEFT),
      width(-1),
      percent(),
      min_visible_width(0),
      sortable(false) {
}

TableColumn::TableColumn(int id, Alignment alignment, int width, float percent)
    : id(id),
      title(l10n_util::GetStringUTF16(id)),
      alignment(alignment),
      width(width),
      percent(percent),
      min_visible_width(0),
      sortable(false) {
}

// TableModel -----------------------------------------------------------------

// Used for sorting.
static icu::Collator* collator = NULL;

gfx::ImageSkia TableModel::GetIcon(int row) {
  return gfx::ImageSkia();
}

string16 TableModel::GetTooltip(int row) {
  return string16();
}

bool TableModel::ShouldIndent(int row) {
  return false;
}

bool TableModel::HasGroups() {
  return false;
}

TableModel::Groups TableModel::GetGroups() {
  // If you override HasGroups to return true, you must override this as
  // well.
  NOTREACHED();
  return std::vector<Group>();
}

int TableModel::GetGroupID(int row) {
  // If you override HasGroups to return true, you must override this as
  // well.
  NOTREACHED();
  return 0;
}

int TableModel::CompareValues(int row1, int row2, int column_id) {
  DCHECK(row1 >= 0 && row1 < RowCount() &&
         row2 >= 0 && row2 < RowCount());
  string16 value1 = GetText(row1, column_id);
  string16 value2 = GetText(row2, column_id);
  icu::Collator* collator = GetCollator();

  if (collator)
    return base::i18n::CompareString16WithCollator(collator, value1, value2);

  NOTREACHED();
  return 0;
}

void TableModel::ClearCollator() {
  delete collator;
  collator = NULL;
}

icu::Collator* TableModel::GetCollator() {
  if (!collator) {
    UErrorCode create_status = U_ZERO_ERROR;
    collator = icu::Collator::createInstance(create_status);
    if (!U_SUCCESS(create_status)) {
      collator = NULL;
      NOTREACHED();
    }
  }
  return collator;
}

}  // namespace ui


text:
package org.ovirt.engine.core.dao.gluster;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeOptionEntity;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.BaseDAODbFacade;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class GlusterOptionDaoDbFacadeImpl extends BaseDAODbFacade implements GlusterOptionDao {
    private static final ParameterizedRowMapper<GlusterVolumeOptionEntity> optionRowMapper = new VolumeOptionRowMapper();

    @Override
    public void save(GlusterVolumeOptionEntity option) {
        getCallsHandler().executeModification("InsertGlusterVolumeOption", createVolumeOptionParams(option));
    }

    @Override
    public void updateVolumeOption(Guid optionId, String optionValue) {
        getCallsHandler().executeModification("UpdateGlusterVolumeOption",
                getCustomMapSqlParameterSource()
                        .addValue("id", optionId)
                        .addValue("option_val", optionValue));
    }

    @Override
    public void removeVolumeOption(Guid optionId) {
        getCallsHandler().executeModification("DeleteGlusterVolumeOption",
                getCustomMapSqlParameterSource().addValue("id", optionId));
    }

    @Override
    public GlusterVolumeOptionEntity getById(Guid id) {
        return getCallsHandler().executeRead(
                "GetGlusterOptionById", optionRowMapper,
                getCustomMapSqlParameterSource().addValue("id", id));
    }

    @Override
    public List<GlusterVolumeOptionEntity> getOptionsOfVolume(Guid volumeId) {
        return getCallsHandler().executeReadList(
                "GetOptionsByGlusterVolumeGuid", optionRowMapper,
                getCustomMapSqlParameterSource().addValue("volume_id", volumeId));
    }

    private MapSqlParameterSource createVolumeOptionParams(GlusterVolumeOptionEntity option) {
        return getCustomMapSqlParameterSource()
                .addValue("id", option.getId())
                .addValue("volume_id", option.getVolumeId())
                .addValue("option_key", option.getKey())
                .addValue("option_val", option.getValue());
    }

    private static final class VolumeOptionRowMapper implements ParameterizedRowMapper<GlusterVolumeOptionEntity> {
        @Override
        public GlusterVolumeOptionEntity mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            GlusterVolumeOptionEntity option = new GlusterVolumeOptionEntity();
            option.setId(Guid.createGuidFromString(rs.getString("id")));
            option.setVolumeId(Guid.createGuidFromString(rs.getString("volume_id")));
            option.setKey(rs.getString("option_key"));
            option.setValue(rs.getString("option_val"));
            return option;
        }
    }
}


text:
speech-to-text-wavenet supports `Docker` to make it easy to running through [Docker](http://www.docker.com/).

## Installing and using Docker

For general information about Docker, see [the Docker site](https://docs.docker.com/installation/).

## Download speech-to-text-wavenet docker images

Get speech-to-text-wavenet docker image

```
docker pull buriburisuri/speech-to-text-wavenet
```

## Running speech-to-text-wavenet container for shell console

Run speech-to-text-wavenet container

```
docker run -it buriburisuri/speech-to-text-wavenet
```

## Testing speech-to-text-wavenet container

Run recognition example in the '/root/speech-to-text-wavenet'(aka '~/') directory.

```
python recognize.py --file asset/data/LibriSpeech/test-clean/1089/134686/1089-134686-0000.flac
```

# Author

Namju Kim (namju.kim@kakaocorp.com) at KakaoBrain Corp.


text: Cordova GTM Plugin


text:
<!DOCTYPE html>

First

Second

Third


text:
echo
====

Experiment with Django and the Echo Nest API

Author: Walter Gillett

Details:

This is my first Django application, written in a couple of afternoons to learn some Django and experiment with the
Echo Nest music API (see http://developer.echonest.com/docs/v4/index.html). This is NOT a full app, it's just an
exploratory finger bending exercise.

Notes:

* "Artist" is the only model object, with just a "name" field
* Uses MySQL for persistent storage
* Has one main page that lists artists
* Each artist has a "bio" button next to it. Click on the "bio" button to get the artist biography, using a
    jQuery AJAX call that fills in the right side of the page with the first artist biography that is found.
* Has a minimal unit test for the model and the view. Ideally there would be a test for the JavaScript as well.
* Calling Echo Nest APIs requires an API key. Since API keys are personal, my API key is not checked in here, rather
    it's defined externally as an environment variable (ECHO_NEST_API_KEY).


text:
<?php

namespace AppBundle\Factory\Common\Choices\Enum;

use AppBundle\Entity\Main\BenchmarkField;
use AppBundle\Factory\Common\Choices\Base\TwigChoicesFactory;

class BenchmarkFieldBetterThanTypesFactory extends TwigChoicesFactory {

	public function __construct() {
		$this->items['label.benchmarkField.betterThanType.none'] = BenchmarkField::NONE_BETTER_THAN_TYPE;
		$this->items['label.benchmarkField.betterThanType.lesserThan'] = BenchmarkField::LT_BETTER_THAN_TYPE;
		$this->items['label.benchmarkField.betterThanType.greaterThan'] = BenchmarkField::GT_BETTER_THAN_TYPE;
	}

	protected function getTwigFunctionName() {
		return 'benchmarkFieldBetterThanTypeName';
	}
}


text:
(function(plugin) {
	var chicago = window.Chicago || {
		utils: {
			now: Date.now || function() {
				return new Date().getTime();
			},
			uid: function(prefix) {
				return(prefix || "id") + chicago.utils.now() + "RAND" + Math.ceil(Math.random() * 1e5);
			},
			is: {
				number: function(obj) {
					return !isNaN(parseFloat(obj)) && isFinite(obj);
				},
				fn: function(obj) {
					return typeof obj === "function";
				},
				object: function(obj) {
					return Object.prototype.toString.call(obj) === "[object Object]";
				}
			},
			debounce: function(fn, wait, immediate) {
				var timeout;
				return function() {
					var context = this,
						args = arguments,
						later = function() {
							timeout = null;
							if(!immediate) {
								fn.apply(context, args);
							}
						},
						callNow = immediate && !timeout;
					if(timeout) {
						clearTimeout(timeout);
					}
					timeout = setTimeout(later, wait);
					if(callNow) {
						fn.apply(context, args);
					}
				};
			}
		},
		$: window.jQuery || null
	};
	if(typeof define === "function" && define.amd) {
		define("chicago", function() {
			chicago.load = function(res, req, onload, config) {
				var resources = res.split(","),
					load = [];
				var base = (config.config && config.config.chicago && config.config.chicago.base ? config.config.chicago.base : "").replace(/\/+$/g, "");
				if(!base) {
					throw new Error("Please define base path to jQuery scrollend in the requirejs config.");
				}
				var i = 0;
				while(i < resources.length) {
					var resource = resources[i].replace(/\./g, "/");
					load.push(base + "/" + resource);
					i += 1;
				}
				req(load, function() {
					onload(chicago);
				});
			};
			return chicago;
		});
	}
	if(window && window.jQuery) {
		return plugin(chicago, window, window.document);
	} else {
		if(!window.jQuery) {
			throw new Error("jQuery scrollend requires jQuery");
		}
	}
})(function(_c, win, doc) {
	_c.$win = _c.$(win);
	_c.$doc = _c.$(doc);
	if(!_c.events) {
		_c.events = {};
	}
	_c.events.scrollend = {
		defaults: {
			delay: 150
		},
		setup: function(data) {
			var args = arguments,
				options = {
					delay: _c.$.event.special.scrollend.defaults.delay
				},
				fn;
			if(_c.utils.is.fn(args[0])) {
				fn = args[0];
			} else {
				if(_c.utils.is.number(args[0])) {
					options.delay = args[0];
				} else {
					if(_c.utils.is.object(args[0])) {
						options = _c.$.extend({}, options, args[0]);
					}
				}
			}
			var uid = _c.utils.uid("scrollend"),
				_data = _c.$.extend({
					delay: _c.$.event.special.scrollend.defaults.delay
				}, options),
				timer = null,
				scrolling = false,
				handler = function(e) {
					if(timer) {
						clearTimeout(timer);
					} else {
						e.type = "scrollend.chicago.dom";
						_c.$(e.target).trigger("scrollend", e);
					}
					timer = setTimeout(function() {
						timer = null;
					}, _data.delay);
				};
			_c.$(this).data("chicago.event.scrollend.uid", uid);
			return _c.$(this).on("scroll", _c.utils.debounce(handler, 100)).data(uid, handler);
		},
		teardown: function() {
			var uid = _c.$(this).data("chicago.event.scrollend.uid");
			_c.$(this).off("scroll", _c.$(this).data(uid));
			_c.$(this).removeData(uid);
			return _c.$(this).removeData("chicago.event.scrollend.uid");
		}
	};
	(function() {
		_c.$.event.special.scrollend = _c.events.scrollend;
		_c.$.fn.scrollend = function(options, callback) {
			return this.each(function() {
				_c.$(this).on("scrollend", options, callback);
			});
		};
	})();
});


text:
import React,{Component} from 'react';

export default  class InlineList extends Component{

render(){

    let listNodes=this.props.data.map(function(item){

        let {captionField,keyField,linkUrl}=this.props;
        let link=linkUrl.replace(':key',item[keyField]);
        return (

                    {item[captionField]}

);

    }.bind(this));

    return (

			{listNodes}

		);

}

}


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Model\CartDiscount;

use Commercetools\Core\Model\Common\Context;
use Commercetools\Core\Model\Common\Reference;

/**
 * @package Commercetools\Core\Model\CartDiscount
 * @ramlTestIgnoreFields('key')
 * @link https://docs.commercetools.com/http-api-types.html#reference-types
 * @link https://docs.commercetools.com/http-api-projects-cartDiscounts.html#cartdiscount
 * @method string getTypeId()
 * @method CartDiscountReference setTypeId(string $typeId = null)
 * @method string getId()
 * @method CartDiscountReference setId(string $id = null)
 * @method CartDiscount getObj()
 * @method CartDiscountReference setObj(CartDiscount $obj = null)
 * @method string getKey()
 * @method CartDiscountReference setKey(string $key = null)
 */
class CartDiscountReference extends Reference
{
    const TYPE_CART_DISCOUNT = 'cart-discount';
    const TYPE_CLASS = CartDiscount::class;

    /**
     * @param $id
     * @param Context|callable $context
     * @return CartDiscountReference
     */
    public static function ofId($id, $context = null)
    {
        return static::ofTypeAndId(static::TYPE_CART_DISCOUNT, $id, $context);
    }
}


text:
package com.kendanware.onegui.core.control;

import com.kendanware.onegui.core.Container;
import com.kendanware.onegui.core.Control;

/**
 *
 * @author Daniel Johansson, Kendanware
 * @author Kenny Colliander Nordin, Kendanware
 *
 * @since 0.0.1
 */
public class TextControl extends Control {
    public TextControl(final Container parent) {
        super(parent);
    }

    public TextControl(final Container parent, final String id) {
        super(parent, id);
    }

    private String text;

    public String getText() {
        return this.text;
    }

    public void setText(final String text) {
        this.text = text;
    }
}


text:
package org.apache.flink.table.dataformat;

import org.apache.flink.table.dataformat.vector.ArrayColumnVector;
import org.apache.flink.table.dataformat.vector.BooleanColumnVector;
import org.apache.flink.table.dataformat.vector.ByteColumnVector;
import org.apache.flink.table.dataformat.vector.BytesColumnVector;
import org.apache.flink.table.dataformat.vector.ColumnVector;
import org.apache.flink.table.dataformat.vector.DecimalColumnVector;
import org.apache.flink.table.dataformat.vector.DoubleColumnVector;
import org.apache.flink.table.dataformat.vector.FloatColumnVector;
import org.apache.flink.table.dataformat.vector.IntColumnVector;
import org.apache.flink.table.dataformat.vector.LongColumnVector;
import org.apache.flink.table.dataformat.vector.ShortColumnVector;
import org.apache.flink.table.dataformat.vector.TimestampColumnVector;

import java.util.Arrays;

/**
 * Columnar array to support access to vector column data.
 */
public final class ColumnarArray implements BaseArray {

	private final ColumnVector data;
	private final int offset;
	private final int numElements;

	public ColumnarArray(ColumnVector data, int offset, int numElements) {
		this.data = data;
		this.offset = offset;
		this.numElements = numElements;
	}

	@Override
	public int numElements() {
		return numElements;
	}

	@Override
	public boolean isNullAt(int pos) {
		return data.isNullAt(offset + pos);
	}

	@Override
	public void setNullAt(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public boolean getBoolean(int ordinal) {
		return ((BooleanColumnVector) data).getBoolean(offset + ordinal);
	}

	@Override
	public byte getByte(int ordinal) {
		return ((ByteColumnVector) data).getByte(offset + ordinal);
	}

	@Override
	public short getShort(int ordinal) {
		return ((ShortColumnVector) data).getShort(offset + ordinal);
	}

	@Override
	public int getInt(int ordinal) {
		return ((IntColumnVector) data).getInt(offset + ordinal);
	}

	@Override
	public long getLong(int ordinal) {
		return ((LongColumnVector) data).getLong(offset + ordinal);
	}

	@Override
	public float getFloat(int ordinal) {
		return ((FloatColumnVector) data).getFloat(offset + ordinal);
	}

	@Override
	public double getDouble(int ordinal) {
		return ((DoubleColumnVector) data).getDouble(offset + ordinal);
	}

	@Override
	public BinaryString getString(int ordinal) {
		BytesColumnVector.Bytes byteArray = getByteArray(ordinal);
		return BinaryString.fromBytes(byteArray.data, byteArray.offset, byteArray.len);
	}

	@Override
	public Decimal getDecimal(int ordinal, int precision, int scale) {
		return ((DecimalColumnVector) data).getDecimal(offset + ordinal, precision, scale);
	}

	@Override
	public SqlTimestamp getTimestamp(int ordinal, int precision) {
		return ((TimestampColumnVector) data).getTimestamp(offset + ordinal, precision);
	}

	@Override
	public <T> BinaryGeneric<T> getGeneric(int ordinal) {
		throw new UnsupportedOperationException("GenericType is not supported.");
	}

	@Override
	public byte[] getBinary(int ordinal) {
		BytesColumnVector.Bytes byteArray = getByteArray(ordinal);
		if (byteArray.len == byteArray.data.length) {
			return byteArray.data;
		} else {
			return Arrays.copyOfRange(byteArray.data, byteArray.offset, byteArray.len);
		}
	}

	@Override
	public BaseArray getArray(int ordinal) {
		return ((ArrayColumnVector) data).getArray(offset + ordinal);
	}

	@Override
	public BaseMap getMap(int ordinal) {
		throw new UnsupportedOperationException("Map is not supported.");
	}

	@Override
	public BaseRow getRow(int ordinal, int numFields) {
		throw new UnsupportedOperationException("Row is not supported.");
	}

	@Override
	public void setBoolean(int ordinal, boolean value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setByte(int ordinal, byte value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setShort(int ordinal, short value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setInt(int ordinal, int value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setLong(int ordinal, long value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setFloat(int ordinal, float value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setDouble(int ordinal, double value) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setDecimal(int i, Decimal value, int precision) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setTimestamp(int ordinal, SqlTimestamp value, int precision) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNotNullAt(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullLong(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullInt(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullBoolean(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullByte(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullShort(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullFloat(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public void setNullDouble(int pos) {
		throw new UnsupportedOperationException("Not support the operation!");
	}

	@Override
	public boolean[] toBooleanArray() {
		boolean[] res = new boolean[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getBoolean(i);
		}
		return res;
	}

	@Override
	public byte[] toByteArray() {
		byte[] res = new byte[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getByte(i);
		}
		return res;
	}

	@Override
	public short[] toShortArray() {
		short[] res = new short[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getShort(i);
		}
		return res;
	}

	@Override
	public int[] toIntArray() {
		int[] res = new int[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getInt(i);
		}
		return res;
	}

	@Override
	public long[] toLongArray() {
		long[] res = new long[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getLong(i);
		}
		return res;
	}

	@Override
	public float[] toFloatArray() {
		float[] res = new float[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getFloat(i);
		}
		return res;
	}

	@Override
	public double[] toDoubleArray() {
		double[] res = new double[numElements];
		for (int i = 0; i < numElements; i++) {
			res[i] = getDouble(i);
		}
		return res;
	}

	private BytesColumnVector.Bytes getByteArray(int ordinal) {
		return ((BytesColumnVector) data).getBytes(offset + ordinal);
	}
}


text:
package com.jsyn.examples;

import com.jsyn.JSyn;
import com.jsyn.Synthesizer;
import com.jsyn.unitgen.LineOut;
import com.jsyn.unitgen.SineOscillator;
import com.jsyn.unitgen.UnitOscillator;

/**
 * Play a tone using a JSyn oscillator.
 *
 * @author Phil Burk (C) 2010 Mobileer Inc
 */
public class PlayTone {
    Synthesizer synth;
    UnitOscillator osc;
    LineOut lineOut;

    private void test() {

        // Create a context for the synthesizer.
        synth = JSyn.createSynthesizer();

        // Start synthesizer using default stereo output at 44100 Hz.
        synth.start();

        // Add a tone generator.
        synth.add(osc = new SineOscillator());
        // Add a stereo audio output unit.
        synth.add(lineOut = new LineOut());

        // Connect the oscillator to both channels of the output.
        osc.output.connect(0, lineOut.input, 0);
        osc.output.connect(0, lineOut.input, 1);

        // Set the frequency and amplitude for the sine wave.
        osc.frequency.set(345.0);
        osc.amplitude.set(0.6);

        // We only need to start the LineOut. It will pull data from the
        // oscillator.
        lineOut.start();

        System.out.println("You should now be hearing a sine wave. ---------");

        // Sleep while the sound is generated in the background.
        try {
            double time = synth.getCurrentTime();
            System.out.println("time = " + time);
            // Sleep for a few seconds.
            synth.sleepUntil(time + 4.0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Stop playing. -------------------");
        // Stop everything.
        synth.stop();
    }

    public static void main(String[] args) {
        new PlayTone().test();
    }
}


text:
<?php

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/Interface.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Cache_Backend_ExtendedInterface extends Zend_Cache_Backend_Interface
{

    /**
     * Return an array of stored cache ids
     *
     * @return array array of stored cache ids (string)
     */
    public function getIds();

    /**
     * Return an array of stored tags
     *
     * @return array array of stored tags (string)
     */
    public function getTags();

    /**
     * Return an array of stored cache ids which match given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of matching cache ids (string)
     */
    public function getIdsMatchingTags($tags = array());

    /**
     * Return an array of stored cache ids which don't match given tags
     *
     * In case of multiple tags, a logical OR is made between tags
     *
     * @param array $tags array of tags
     * @return array array of not matching cache ids (string)
     */
    public function getIdsNotMatchingTags($tags = array());

    /**
     * Return an array of stored cache ids which match any given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of any matching cache ids (string)
     */
    public function getIdsMatchingAnyTags($tags = array());

    /**
     * Return the filling percentage of the backend storage
     *
     * @return int integer between 0 and 100
     */
    public function getFillingPercentage();

    /**
     * Return an array of metadatas for the given cache id
     *
     * The array must include these keys :
     * - expire : the expire timestamp
     * - tags : a string array of tags
     * - mtime : timestamp of last modification time
     *
     * @param string $id cache id
     * @return array array of metadatas (false if the cache id is not found)
     */
    public function getMetadatas($id);

    /**
     * Give (if possible) an extra lifetime to the given cache id
     *
     * @param string $id cache id
     * @param int $extraLifetime
     * @return boolean true if ok
     */
    public function touch($id, $extraLifetime);

    /**
     * Return an associative array of capabilities (booleans) of the backend
     *
     * The array must include these keys :
     * - automatic_cleaning (is automating cleaning necessary)
     * - tags (are tags supported)
     * - expired_read (is it possible to read expired cache records
     *                 (for doNotTestCacheValidity option for example))
     * - priority does the backend deal with priority when saving
     * - infinite_lifetime (is infinite lifetime can work with this backend)
     * - get_list (is it possible to get the list of cache ids and the complete list of tags)
     *
     * @return array associative of with capabilities
     */
    public function getCapabilities();

}


text:
describe ThrottlePolicy::Violation do
  violation   = ThrottlePolicy::Violation
  rule        = ThrottlePolicy::Rule
  time_period = ThrottlePolicy::TimePeriod

  it 'is comparable' do
    smaller     = violation.new(rule.new(time_period.new(1.minute), 10))
    bigger      = violation.new(rule.new(time_period.new(1.day),    10))
    medium      = violation.new(rule.new(time_period.new(1.hour),   10))
    violations  = [medium, smaller, bigger]
    result      = violations.sort
    expect(result.first).to be(smaller)
    expect(result.last).to  be(bigger)
  end
end


text:
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * Created by hajarboulhdir on 02/10/2016.
 */
public class Point3DTest {
    Point3D p;
    @BeforeMethod
    public void setUp() throws Exception {
    p=new Point3D(0.0,0.0,0.0);
    }

    @AfterMethod
    public void tearDown() throws Exception {

    }

    @Test
    public void testTranslate() throws Exception {
        p.translate(2, 3, 4);
        assertEquals(p.getX(), 2.0);
        assertEquals(p.getY(), 3.0);
        assertEquals(p.getZ(), 4.0);
    }

    @Test
    public void testIsOrigin() throws Exception {
        assertEquals(p.isOrigin(),true);
    }

    @Test
    public void testDistance() throws Exception {
        p=new Point3D(2.0,2.0,3.0);
        assertEquals(p.distance(p),Math.sqrt(8.0));
    }

}


text:
#undef G_DISABLE_ASSERT
#undef G_LOG_DOMAIN

#include <errno.h>
#include <glib.h>
#ifdef G_OS_UNIX
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>

#ifdef G_OS_WIN32
#include <fcntl.h>		/* For _O_BINARY used by pipe() macro */
#include <io.h>			/* for _pipe() */
#endif

#define ITERS 10000
#define INCREMENT 10
#define NTHREADS 4
#define NCRAWLERS 4
#define CRAWLER_TIMEOUT_RANGE 40
#define RECURSER_TIMEOUT 50

/* The partial ordering between the context array mutex and
 * crawler array mutex is that the crawler array mutex cannot
 * be locked while the context array mutex is locked
 */
GPtrArray *context_array;
GMutex *context_array_mutex;
GCond *context_array_cond;

GMainLoop *main_loop;

G_LOCK_DEFINE_STATIC (crawler_array_lock);
GPtrArray *crawler_array;

typedef struct _AddrData AddrData;
typedef struct _TestData TestData;

struct _AddrData
{
  GMainLoop *loop;
  GIOChannel *dest;
  gint count;
};

struct _TestData
{
  gint current_val;
  gint iters;
  GIOChannel *in;
};

static void cleanup_crawlers (GMainContext *context);

gboolean
read_all (GIOChannel *channel, char *buf, gsize len)
{
  gsize bytes_read = 0;
  gsize count;
  GIOError err;

  while (bytes_read < len)
    {
      err = g_io_channel_read (channel, buf + bytes_read, len - bytes_read, &count);
      if (err)
	{
	  if (err != G_IO_ERROR_AGAIN)
	    return FALSE;
	}
      else if (count == 0)
	return FALSE;

      bytes_read += count;
    }

  return TRUE;
}

gboolean
write_all (GIOChannel *channel, char *buf, gsize len)
{
  gsize bytes_written = 0;
  gsize count;
  GIOError err;

  while (bytes_written < len)
    {
      err = g_io_channel_write (channel, buf + bytes_written, len - bytes_written, &count);
      if (err && err != G_IO_ERROR_AGAIN)
	return FALSE;

      bytes_written += count;
    }

  return TRUE;
}

gboolean
adder_callback (GIOChannel   *source,
		GIOCondition  condition,
		gpointer      data)
{
  char buf1[32];
  char buf2[32];

  char result[32];

  AddrData *addr_data = data;

  if (!read_all (source, buf1, 32) ||
      !read_all (source, buf2, 32))
    {
      g_main_loop_quit (addr_data->loop);
      return FALSE;
    }

  sprintf (result, "%d", atoi(buf1) + atoi(buf2));
  write_all (addr_data->dest, result, 32);

  return TRUE;
}

gboolean
timeout_callback (gpointer data)
{
  AddrData *addr_data = data;

  addr_data->count++;

  return TRUE;
}

gpointer
adder_thread (gpointer data)
{
  GMainContext *context;
  GSource *adder_source;
  GSource *timeout_source;

  GIOChannel **channels = data;
  AddrData addr_data;

  context = g_main_context_new ();

  g_mutex_lock (context_array_mutex);

  g_ptr_array_add (context_array, context);

  if (context_array->len == NTHREADS)
    g_cond_broadcast (context_array_cond);

  g_mutex_unlock (context_array_mutex);

  addr_data.dest = channels[1];
  addr_data.loop = g_main_loop_new (context, FALSE);
  addr_data.count = 0;

  adder_source = g_io_create_watch (channels[0], G_IO_IN | G_IO_HUP);
  g_source_set_callback (adder_source, (GSourceFunc)adder_callback, &addr_data, NULL);
  g_source_attach (adder_source, context);
  g_source_unref (adder_source);

  timeout_source = g_timeout_source_new (10);
  g_source_set_callback (timeout_source, (GSourceFunc)timeout_callback, &addr_data, NULL);
  g_source_set_priority (timeout_source, G_PRIORITY_HIGH);
  g_source_attach (timeout_source, context);
  g_source_unref (timeout_source);

  g_main_loop_run (addr_data.loop);

  g_io_channel_unref (channels[0]);
  g_io_channel_unref (channels[1]);

  g_free (channels);

  g_main_loop_unref (addr_data.loop);

#ifdef VERBOSE
  g_print ("Timeout run %d times\n", addr_data.count);
#endif

  g_mutex_lock (context_array_mutex);
  g_ptr_array_remove (context_array, context);
  if (context_array->len == 0)
    g_main_loop_quit (main_loop);
  g_mutex_unlock (context_array_mutex);

  cleanup_crawlers (context);

  return NULL;
}

void
io_pipe (GIOChannel **channels)
{
  gint fds[2];

  if (pipe(fds) < 0)
    {
      g_warning ("Cannot create pipe %s\n", g_strerror (errno));
      exit (1);
    }

  channels[0] = g_io_channel_unix_new (fds[0]);
  channels[1] = g_io_channel_unix_new (fds[1]);

  g_io_channel_set_close_on_unref (channels[0], TRUE);
  g_io_channel_set_close_on_unref (channels[1], TRUE);
}

void
do_add (GIOChannel *in, gint a, gint b)
{
  char buf1[32];
  char buf2[32];

  sprintf (buf1, "%d", a);
  sprintf (buf2, "%d", b);

  write_all (in, buf1, 32);
  write_all (in, buf2, 32);
}

gboolean
adder_response (GIOChannel   *source,
		GIOCondition  condition,
		gpointer      data)
{
  char result[32];
  TestData *test_data = data;

  if (!read_all (source, result, 32))
    return FALSE;

  test_data->current_val = atoi (result);
  test_data->iters--;

  if (test_data->iters == 0)
    {
      if (test_data->current_val != ITERS * INCREMENT)
	{
	  g_print ("Addition failed: %d != %d\n",
		   test_data->current_val, ITERS * INCREMENT);
	  exit (1);
	}

      g_io_channel_unref (source);
      g_io_channel_unref (test_data->in);

      g_free (test_data);

      return FALSE;
    }

  do_add (test_data->in, test_data->current_val, INCREMENT);

  return TRUE;
}

void
create_adder_thread (void)
{
  GError *err = NULL;
  TestData *test_data;

  GIOChannel *in_channels[2];
  GIOChannel *out_channels[2];

  GIOChannel **sub_channels;

  sub_channels = g_new (GIOChannel *, 2);

  io_pipe (in_channels);
  io_pipe (out_channels);

  sub_channels[0] = in_channels[0];
  sub_channels[1] = out_channels[1];

  g_thread_create (adder_thread, sub_channels, FALSE, &err);

  if (err)
    {
      g_warning ("Cannot create thread: %s", err->message);
      exit (1);
    }

  test_data = g_new (TestData, 1);
  test_data->in = in_channels[1];
  test_data->current_val = 0;
  test_data->iters = ITERS;

  g_io_add_watch (out_channels[0], G_IO_IN | G_IO_HUP,
		  adder_response, test_data);

  do_add (test_data->in, test_data->current_val, INCREMENT);
}

static void create_crawler (void);

static void
remove_crawler (void)
{
  GSource *other_source;

  if (crawler_array->len > 0)
    {
      other_source = crawler_array->pdata[g_random_int_range (0, crawler_array->len)];
      g_source_destroy (other_source);
      g_assert (g_ptr_array_remove_fast (crawler_array, other_source));
    }
}

static gint
crawler_callback (gpointer data)
{
  GSource *source = data;

  G_LOCK (crawler_array_lock);

  if (!g_ptr_array_remove_fast (crawler_array, source))
    remove_crawler();

  remove_crawler();
  G_UNLOCK (crawler_array_lock);

  create_crawler();
  create_crawler();

  return FALSE;
}

static void
create_crawler (void)
{
  GSource *source = g_timeout_source_new (g_random_int_range (0, CRAWLER_TIMEOUT_RANGE));
  g_source_set_callback (source, (GSourceFunc)crawler_callback, source, NULL);

  G_LOCK (crawler_array_lock);
  g_ptr_array_add (crawler_array, source);

  g_mutex_lock (context_array_mutex);
  g_source_attach (source, context_array->pdata[g_random_int_range (0, context_array->len)]);
  g_source_unref (source);
  g_mutex_unlock (context_array_mutex);

  G_UNLOCK (crawler_array_lock);
}

static void
cleanup_crawlers (GMainContext *context)
{
  gint i;

  G_LOCK (crawler_array_lock);
  for (i=0; i < crawler_array->len; i++)
    {
      if (g_source_get_context (crawler_array->pdata[i]) == context)
	{
	  g_source_destroy (g_ptr_array_remove_index (crawler_array, i));
	  i--;
	}
    }
  G_UNLOCK (crawler_array_lock);
}

static gboolean
recurser_idle (gpointer data)
{
  GMainContext *context = data;
  gint i;

  for (i = 0; i < 10; i++)
    g_main_context_iteration (context, FALSE);

  return FALSE;
}

static gboolean
recurser_start (gpointer data)
{
  GMainContext *context;
  GSource *source;

  g_mutex_lock (context_array_mutex);
  context = context_array->pdata[g_random_int_range (0, context_array->len)];
  source = g_idle_source_new ();
  g_source_set_callback (source, recurser_idle, context, NULL);
  g_source_attach (source, context);
  g_source_unref (source);
  g_mutex_unlock (context_array_mutex);

  return TRUE;
}

int
main (int   argc,
      char *argv[])
{
  /* Only run the test, if threads are enabled and a default thread
     implementation is available */
#if defined(G_THREADS_ENABLED) && ! defined(G_THREADS_IMPL_NONE)
  gint i;

  g_thread_init (NULL);

  context_array = g_ptr_array_new ();
  context_array_mutex = g_mutex_new ();
  context_array_cond = g_cond_new ();

  crawler_array = g_ptr_array_new ();

  main_loop = g_main_loop_new (NULL, FALSE);

  for (i = 0; i < NTHREADS; i++)
    create_adder_thread ();

  /* Wait for all threads to start
   */
  g_mutex_lock (context_array_mutex);

  if (context_array->len < NTHREADS)
    g_cond_wait (context_array_cond, context_array_mutex);

  g_mutex_unlock (context_array_mutex);

  for (i = 0; i < NCRAWLERS; i++)
    create_crawler ();

  g_timeout_add (RECURSER_TIMEOUT, recurser_start, NULL);

  g_main_loop_run (main_loop);
  g_main_loop_unref (main_loop);

#endif
  return 0;
}


text:
Release 0.5.3
==================================

Client-mode changes
------------------

* All commands support ``-H, --header KEY=VALUE`` option to add a custom HTTP header.

* client.properties can include ``header.<KEY> = <VALUE>`` lines where ``<KEY>`` is HTTP header name and ``<VALUE>`` is its value.

Server-mode changes
------------------

* Added ``/api/version`` endpoint.

* Added ``Authenticator`` interface so that applications can overwrite authentication mechanism.

* Replaced ``ServerModule.bindAuthInterceptor`` with ``bindAuthenticator`` which improves type-safety.

Release Date
------------------
2016-03-31


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_STATISTIC_MANAGER_BEGIN

/// <summary>
/// Indicates the type of statistic change event.
/// </summary>
public enum class StatisticEventType
{
    /// <summary>
    /// A local user has been added
    /// </summary>
    LocalUserAdded = xbox::services::stats::manager::stat_event_type::local_user_added,

    /// <summary>
    /// A local user has been removed
    /// </summary>
    LocalUserRemoved = xbox::services::stats::manager::stat_event_type::local_user_removed,

    /// <summary>
    /// stat has been updated
    /// </summary>
    StatisticUpdateComplete = xbox::services::stats::manager::stat_event_type::stat_update_complete,

    /// <summary>
    /// cast event args to leaderboard_result_event_args
    /// </summary>
    GetLeaderboardComplete = xbox::services::stats::manager::stat_event_type::get_leaderboard_complete
};

NAMESPACE_MICROSOFT_XBOX_SERVICES_STATISTIC_MANAGER_END