text:
var Subgame = require('./Subgame.js');
var GLOBAL = require('../../global.js');
var EventSystem = require('../../pubsub.js');
var util = require('../../utils.js');
var ButtonPanel = require('../../objects/buttons/ButtonPanel.js');
var GeneralButton = require('../../objects/buttons/GeneralButton.js');
var TextButton = require('../../objects/buttons/TextButton.js');
var DraggableObject = require('../../objects/DraggableObject.js');
var ObjectPanel = require('../../objects/ObjectPanel');

module.exports = NumberGame;

/**
 * A superclass for games where you need to guess the correct number.
 * This class will set the .doInstructions, .doStartFunction and .doReturnFunction.
 * They will map to the functions that you should setup (see _setupFunctions).
 * See BeeFlightGame for inspiration of how you can use this class.
 *
 *
 * SETUP THESE IN THE SUBCLASS:
 * "this" object should have a property used when setting agent start position:
 *    this.pos: { agent: { start: { x, y }, scale: z } } }.
 *
 * NEVER DO ANY LOGICAL CHANGES IN THE INSTRUCTIONS!
 * instructionCount:       Method count.
 * instructionSteps:       Method incremental-steps.
 * instructionAdd:         Method addition.
 * instructionSubtract:    Method subtraction.
 * instructionAddSubtract: Method addition subtraction.
 *
 * startStop:  When round start without automatic "guessing". Used in count and incremental-steps method.
 * startBelow: When round start by guessing lower than target. Used in addition method.
 * startAbove: When round start by guessing higher than target. Used in subtraction method.
 * startThink: When round start by guessing something. Used in add/subt method.
 *
 * runNumber:  The function to run when a number has been chosen.
 *
 * returnToStart:            When returning to the start position on incorrect answer.
 * returnNone:               When the game stays at the incorrect answer position.
 * returnToPreviousIfHigher: When returning to previous value if the incorrect answer was too high.
 * returnToPreviousIfLower:  When returning to previous value if the incorrect answer was too low.
 *
 *
 * VARIABLES THE SUBCLASS CAN USE:
 * Number amount:        this.amount
 * Representation:       this.representation
 * The method:           this.method
 * The number to answer: this.currentNumber (updates automatically)
 *
 * FUNCTIONS THE SUBCLASS CAN USE:
 * Try a number: this.tryNumber(number) - when testing a guess against this.currentNumber
 *
 *
 * Typical game flow:
 * // the first mode, this.modeIntro, will be called automatically when assets are loaded and decoded.
 * this.nextRound();    // start next round (will automatically start next mode)
 * this.disable(false); // make it possible to interact with anything
 * this.tryNumber(x);   // try a number against the current one
 * this.nextRound();    // do this regardless if right or wrong,
 *                      // it takes care of mode switching and function calls for you
 * // Repeat last two functions until game is over.
 */
NumberGame.prototype = Object.create(Subgame.prototype);
NumberGame.prototype.constructor = NumberGame;
function NumberGame () {
	Subgame.call(this); // Call parent constructor.
}

/*
 * Phaser state function.
 * Publishes subgameStarted event.
 */
NumberGame.prototype.init = function (options) {
	Subgame.prototype.init.call(this, options);
	GeneralButton.prototype.buttonColor = this.buttonColor || GLOBAL.BUTTON_COLOR;
	DraggableObject.prototype.objectColor = this.objectColor || GLOBAL.BUTTON_COLOR;

	/* Public variables */
	//No need for different methods in MI, the methods system should be removed in the future at the moment set to one staticly
	this.method = GLOBAL.METHOD.addition;
	this.representation = options.representation;
	this.amount = 4; //Always wants 4 cookies in teh sharkGame

	/* The current number to answer */
	this.currentNumber = null;
	/* Stores the offset of the last try, can be used to judge last try */
	/* Ex: -1 means that last try was one less than currentNumber */
	this.lastTry = 0;
	/* This should be used to save the current position. */
	this.atValue = 0;
	/* This is used to add to the number of the button pushes. */
	/* This should be modified only when isRelative is set to true. */
	this.addToNumber = 0;

	// Setup gameplay differently depending on situation.
	this.isRelative = false;
	this._setupFunctions();

	/* Numbers for randomisation. */
	this._weighted = this.amount > 4 && this.method === GLOBAL.METHOD.count;
	this._numberMin = 1;
	this._numberMax = 9;
	if (this.method === GLOBAL.METHOD.addition) {
		this._numberMin++;
	}
	if (this.method === GLOBAL.METHOD.subtraction) {
		this._numberMax--;
	}

	// Agent is added to the game in the superclass, but we set it up here.
	this.agent.x = this.pos.agent.start.x;
	this.agent.y = this.pos.agent.start.y;
	this.agent.scale.set(this.pos.agent.scale);
	this.agent.visible = true;
	this.agent.addThought(this.representation[0], this.pos.agent.mirror || false);
	this.saidAgentWrong = false;

	var _this = this;
	this.agent.moveTo = {
		start: function () {
			if (_this.agent.x === _this.pos.agent.stop.x &&
				_this.agent.y === _this.pos.agent.stop.y) {
				return new TweenMax(_this.agent);
			}
			return _this.agent.move({ x: _this.pos.agent.stop.x, y: _this.pos.agent.stop.y }, 3);
		}
	};

	// Setup help button with correct instruction functions.
	this.helpButton = new TextButton(this.game, '?', {
		x: 75, y: 5, size: 56, fontSize: 30,
		color: GLOBAL.BUTTON_COLOR,
		doNotAdapt: true,
		onClick: function () {
			_this.disable(true);
			var t;
			if (_this.currentMode === GLOBAL.MODE.agentTry && !_this.saidAgentWrong) {
				t = _this.instructionYesNo();
			} else {
				t = _this.doInstructions();
			}
			t.addCallback(_this.disable, null, [false], true);
			t.skippable();
		}
	});
	this.helpButton.visible = false;
	this.hudGroup.add(this.helpButton);
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Private functions                              */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/**
 * Setup start and return functions.
 * Will map to the functions the subclass should overshadow (see bottom of this class).
 * The .doStartFunction is an easy way to call the appropriate start function.
 * The .doReturnFunction is an wasy way to call the appropriate return function when answer is incorrect.
 */
NumberGame.prototype._setupFunctions = function () {
	if (this.method === GLOBAL.METHOD.count) {
		this.doInstructions = this.instructionCount;
		this.doStartFunction = this.startStop;
		this.doReturnFunction = this.returnToStart;
	} else if (this.method === GLOBAL.METHOD.incrementalSteps) {
		this.doInstructions = this.instructionSteps;
		this.doStartFunction = this.startStop;
		this.doReturnFunction = this.returnNone;
	} else if (this.method === GLOBAL.METHOD.addition) {
		this.doInstructions = this.instructionAdd;
		this.doStartFunction = this.startBelow;
		this.doReturnFunction = this.returnToPreviousIfHigher;
		this.isRelative = true;
	} else if (this.method === GLOBAL.METHOD.subtraction) {
		this.doInstructions = this.instructionSubtract;
		this.doStartFunction = this.startAbove;
		this.doReturnFunction = this.returnToPreviousIfLower;
		this.isRelative = true;
	} else {
		this.doInstructions = this.instructionAddSubtract;
		this.doStartFunction = this.startThink;
		this.doReturnFunction = this.returnNone;
		this.isRelative = true;
	}
};

/** Change this.currentNumber to a new one (resets the tries). */
// TODO: Should we allow the same number again?
NumberGame.prototype._nextNumber = function () {
	// Weighted randomisation if applicable
	if (this._weighted && this.rnd.frac() < 0.2) {
		this.currentNumber = this.rnd.integerInRange(5, this._numberMax);
	} else {
		this.currentNumber = this.rnd.integerInRange(this._numberMin, this._numberMax);
	}
};

NumberGame.prototype._getRange = function () {
	if (this.method === GLOBAL.METHOD.addition) {
		return { min: 1, max: this.amount - this.addToNumber };
	} else if (this.method === GLOBAL.METHOD.subtraction) {
		return { min: 1 - this.addToNumber, max: -1 };
	} else if (this.method === GLOBAL.METHOD.additionSubtraction) {
		return { min: 1 - this.addToNumber, max: this.amount - this.addToNumber };
	} else {
		return { min: 1, max: this.amount };
	}
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Public functions                               */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/**
 * Try a number against this.currentNumber.
 * The offset of the last try is stored in this.lastTry.
 * Publishes tryNumber event.
 * @param {number} The number to try.
 * @param {number} The offset to the number (example if you start at 2).
 * @return {boolean} The offset of the last try (0 is correct, -x is too low, +x is too high).
 */
NumberGame.prototype.tryNumber = function (number, offset) {
	var sum = number + (offset || 0);
	this.lastTry = sum - this.currentNumber;
	EventSystem.publish(GLOBAL.EVENT.tryNumber, [sum, this.currentNumber, number, offset]);
	DraggableObject.prototype.setTry.call(this, this.lastTry); //Send the last try offset to draggable object for the visual feedback
	this._currentTries++;
	this._totalTries++;
	if (!this.lastTry) {
		this._counter.value++; // This will trigger next mode if we loop.
		this._nextNumber();
		this._totalCorrect++;
		this._currentTries = 0;
	}
	return this.lastTry;
};

/** Have the agent guess a number. */
NumberGame.prototype.agentGuess = function () {
	var t = new TimelineMax();
	t.addCallback(function () {
		this.agent.guessNumber(this.currentNumber - (this.isRelative ? this.addToNumber : 0), this._numberMin, this._numberMax);
	}, 0, null, this);
	t.add(this.agent.think());
	return t;
};

/**
 * Setup HUD buttons.
 * @param {Object} options - The options for the buttons
 *                           Supply like this: { buttons: {...}, yesnos: {...} }.
 *                           NOTE: .method and .onClick will be set in this function.
 */
NumberGame.prototype.setupButtons = function (options) {
	var _this = this;
	if (options.buttons) {
		options.buttons.method = this.method;
		options.buttons.onClick = function (number) { _this.pushNumber(number); };
		this.buttons = new ButtonPanel(this.game, this.amount, this.representation, options.buttons);
		this.buttons.visible = false;
		this.hudGroup.add(this.buttons);
	}

	if (options.yesnos) {
		options.yesnos.onClick = function (value) { _this.pushYesNo(value); };
		this.yesnos = new ButtonPanel(this.game, 2, GLOBAL.NUMBER_REPRESENTATION.yesno, options.yesnos);
		this.yesnos.visible = false;
		this.hudGroup.add(this.yesnos);
	}
};

/**
 * Setup drag and goal objects.
 * created in the same way as the buttons
 */
NumberGame.prototype.setUpDragObject = function(options){
	var _this = this;
	if(options.dragObject){
		options.dragObject.onClick = function (number) {_this.pushNumber(number);};
		this.dragObject = new ObjectPanel(this.game,this.amount, options.dragObject);
		this.dragObject.visible = false;
		this.hudGroup.add(this.dragObject);
	}

	if(options.goalObject){
		this.goalObject = new ObjectPanel(this.game,this.amount, options.goalObject);
		this.goalObject.visible = false;
		this.hudGroup.add(this.goalObject);
	}
	if(options.finalDragObject){
		options.finalDragObject.onClick = function(){_this.moveObject();};
		this.finalDragObject = new ObjectPanel(this.game, this.amount, options.finalDragObject);
		this.finalDragObject.visible = false;
		this.hudGroup.add(this.finalDragObject);
	}
};

/* Function to trigger when a button or object in the number panel is pushed/dropped.
 * if you want to trigger nextRound call it from within run Number*/
NumberGame.prototype.pushNumber = function (number) {
	this.saidAgentWrong = false;
	return this.runNumber(number);

};

/* Function triggered when a finalDragObject is drooped on the correct position*/
NumberGame.prototype.moveObject = function(){
	this.hideWinObject();
	return this.win().addCallback(this.nextRound, null, null, this);

};

/* Function to trigger when a button in the yes-no panel is pushed. */
NumberGame.prototype.pushYesNo = function (value) {
	if (!value) {
		this.saidAgentWrong = true;
		if (this.speech) {
			this.agent.say(this.agent.speech, 'wrongShow').play('wrongShow');
		}
		this.showNumbers();
	} else {
		this.yesButton = true;
		this.pushNumber(this.agent.lastGuess);
	}
};

/*Shows the drag object on win hides the goalObject*/
NumberGame.prototype.showWinObject = function(){
	this.disable(false);

	if(this.finalDragObject) {
		util.fade(this.finalDragObject, true);
	}
	if (this.dragObject) {
		util.fade(this.dragObject, false);
	}
	if (this.goalObject) {
		util.fade(this.goalObject, false);
	}
};

// Hides the finalDragObject
NumberGame.prototype.hideWinObject = function(){
	this.disable(false);
	if(this.finalDragObject) {
		util.fade(this.finalDragObject, false);
	}
};

// Shows teh goalObject
NumberGame.prototype.showGoalObject = function(){
	if(this.goalObject){
		if(this.isRelative){
			this.updateObjects();
		}
		util.fade(this.goalObject, true).eventCallback('onComplete', this.disable, false, this);
	}
};
/* Show the number panel, hide the yes/no panel and enable input. */
NumberGame.prototype.showNumbers = function () {
	this.disable(true);
	if (this.buttons) {
		this.buttons.reset();
		if (this.isRelative) {
			this.updateButtons();
		}
		util.fade(this.buttons, true).eventCallback('onComplete', this.disable, false, this);
	}

	if(this.dragObject){
		this.dragObject.reset();
		if(this.isRelative){
			this.updateObjects();
		}
		util.fade(this.dragObject, true).eventCallback('onComplete', this.disable, false, this);
	}
	if(this.goalObject){
		if(this.isRelative){
			this.updateObjects();
		}
		util.fade(this.goalObject, true).eventCallback('onComplete', this.disable, false, this);
	}

	if (this.yesnos) {
		util.fade(this.yesnos, false);
	}

	if (this.agent.visible) {
		util.fade(this.agent.thought, false);
		this.agent.eyesFollowPointer();
	}
};

/* Show the yes/no panel, hide the number panel and enable input. */
NumberGame.prototype.showYesnos = function () {
	this.disable(true);
	if (this.buttons) {
		util.fade(this.buttons, false);
	}
	if (this.yesnos) {
		this.yesnos.reset();
		util.fade(this.yesnos, true).eventCallback('onComplete', this.disable, false, this);
	}

	if (this.agent.visible) { this.agent.eyesFollowPointer(); }
};

/* Hide the number and yes/no panel. */
NumberGame.prototype.hideButtons = function () {
	this.disable(true);
	if (this.buttons) {
		util.fade(this.buttons, false);
	}
	if (this.yesnos) {
		util.fade(this.yesnos, false);
	}
	if (this.dragObject) {
		util.fade(this.dragObject, false);
	}
	if(this.goalObject){
		util.fade(this.goalObject, false);
	}

	if (this.agent.visible) { this.agent.eyesStopFollow(); }
};

/* Update the values of the button panel. */
NumberGame.prototype.updateButtons = function () {
	if (this.buttons) {
		var range = this._getRange();
		this.buttons.setRange(range.min, range.max);
	}
};

NumberGame.prototype.updateObjects = function(){
	var range = this._getRange();
	if(this.dragObject ){
		range = this._getRange();
		this.dragObject.setRange(range.min, range.max,this.currentNumber);
	}
	if(this.goalObject){
		range = this._getRange();
		this.goalObject.setRange(range.min,range.max, this.currentNumber);
	}

};

/* Update the relative value. */
NumberGame.prototype.updateRelative = function () {
	if (this.isRelative) {
		this.addToNumber = this.atValue;
	}
};
/*set relative true*/
NumberGame.prototype.setRelative = function (correct){
	if (correct === true){
		this.isRelative = true;
	}
	else {
		this.isRelative = false;
	}
};

/*Set relative false*/
NumberGame.prototype.setRelativefalse = function (){
	this.isRelative = true;
};

/* Instructions for the yes - no panel */
NumberGame.prototype.instructionYesNo = function () {
	var t = new TimelineMax();
	t.addSound(this.agent.speech, this.agent, 'willYouHelpMe');
	t.add(util.fade(this.yesnos, true), 0);
	t.addLabel('green', '+=0.7');
	t.addSound(this.agent.speech, this.agent, 'instructionGreen', 'green');
	t.add(this.yesnos.children[0].highlight(3), 'green');
	t.addLabel('red');
	t.addSound(this.agent.speech, this.agent, 'instructionRed', 'red');
	t.add(this.yesnos.children[1].highlight(3), 'red');
	return t;
};

/* Start the game. */
NumberGame.prototype.startGame = function () {
	this._nextNumber();
	this.helpButton.visible = true;

	Subgame.prototype.startGame.call(this);

	EventSystem.publish(GLOBAL.EVENT.numbergameStarted, [this.method, this.amount, this.representation]);
};

/* The following functions should be overshadowed in the game object. */
NumberGame.prototype.pos = { agent: { start: { x: 0, y: 0 }, scale: 1 } };
NumberGame.prototype.instructionCount = function () {};
NumberGame.prototype.instructionSteps = function () {};
NumberGame.prototype.instructionAdd = function () {};
NumberGame.prototype.instructionSubtract = function () {};
NumberGame.prototype.instructionAddSubtract = function () {};
NumberGame.prototype.startStop = function () {};
NumberGame.prototype.startBelow = function () {};
NumberGame.prototype.startAbove = function () {};
NumberGame.prototype.startThink = function () {};
NumberGame.prototype.returnToStart = function () {};
NumberGame.prototype.returnNone = function () {};
NumberGame.prototype.returnToPreviousIfHigher = function () {};
NumberGame.prototype.returnToPreviousIfLower = function () {};


text:
<?php

require_once __DIR__ . '/../bootstrap.php';

$loop = \React\EventLoop\Factory::create();
$scheduler = new \Rx\Scheduler\EventLoopScheduler($loop);

$source1 = \Rx\Observable::fromArray(range(0, 100));
$source2 = \Rx\Observable::fromArray(range(0, 100));

$source = $source1->combineLatest([$source2], function($value1, $value2){
    return "First: {$value1}, Second: {$value2}";
})->take(4);

$subscription = $source->subscribe($stdoutObserver, $scheduler);

$loop->run();

redpajama_set_name: RedPajamaGithub


text:
The documentation summary (or menu) disappeared.

## Why is the summary/menu hidden?
The menu is also hidden to reduce content redundancy.

## Why keeping the menu hidden instead of deleting it?
The menu is on the main page for those visitors who access this documentation through github ([see link](https://github.com/dotkernel/dotkernel/tree/master/docs))

## What does it look like?
We thought you might be curios what exactly disappeared so the menu will be presented below.

{% include menu.md %}

## [Back to documentation](README.md)


text:
#ifndef SKY_ENGINE_CORE_DOM_TEXT_H_
#define SKY_ENGINE_CORE_DOM_TEXT_H_

#include "sky/engine/core/dom/CharacterData.h"

namespace blink {

class ExceptionState;
class RenderText;

class Text : public CharacterData {
    DEFINE_WRAPPERTYPEINFO();
public:
    static const unsigned defaultLengthLimit = 1 << 16;

    static PassRefPtr<Text> create(Document&, const String&);
    static PassRefPtr<Text> createEditingText(Document&, const String&);

    RenderText* renderer() const;

    PassRefPtr<Text> splitText(unsigned offset, ExceptionState&);

    void recalcTextStyle(StyleRecalcChange);
    bool textRendererIsNeeded(const RenderStyle&, const RenderObject& parent);
    RenderText* createTextRenderer(RenderStyle*);
    void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);

    virtual void attach(const AttachContext& = AttachContext()) override final;

    virtual bool canContainRangeEndPoint() const override final { return true; }
    virtual NodeType nodeType() const override;

protected:
    Text(TreeScope& treeScope, const String& data, ConstructionType type)
        : CharacterData(treeScope, data, type)
    {
    }

private:
    virtual String nodeName() const override;
    virtual PassRefPtr<Node> cloneNode(bool deep = true) override final;

    bool isTextNode() const = delete; // This will catch anyone doing an unnecessary check.

    bool needsWhitespaceRenderer();

    virtual PassRefPtr<Text> cloneWithData(const String&);

#ifndef NDEBUG
    virtual void formatForDebugger(char* buffer, unsigned length) const override;
#endif
};

DEFINE_NODE_TYPE_CASTS(Text, isTextNode());

} // namespace blink

#endif  // SKY_ENGINE_CORE_DOM_TEXT_H_


text:
. include/common

test="dSIPRouter Started"

# Is service started
systemctl is-active --quiet dsiprouter; ret=$?

process_result "$test" $ret


text:
<module>

	<!-- WS Compiler: manually edited -->

	<!-- Inherit DefaultWidgetSet -->
	<inherits name="com.vaadin.DefaultWidgetSet" />

	<!-- Widget styles in public -directory -->
	<stylesheet src="VisibilityMap/styles.css"/>

</module>


text:
namespace fgui {
    export class PackageItem {
        public owner: UIPackage;

        public type: number;
        public objectType?: number;

        public id: string;
        public name: string;
        public width: number = 0;
        public height: number = 0;
        public file: string;
        public decoded?: boolean;
        public loading?: Array<Function>;
        public rawData?: ByteBuffer;

        public highResolution?: Array<string>;
        public branches?: Array<string>;

        //image
        public scale9Grid?: Laya.Rectangle;
        public scaleByTile?: boolean;
        public tileGridIndice?: number;
        public smoothing?: boolean;
        public texture?: Laya.Texture;
        public pixelHitTestData?: PixelHitTestData;

        //movieclip
        public interval?: number;
        public repeatDelay?: number;
        public swing?: boolean;
        public frames?: Frame[];

        //componenet
        public extensionType?: any;

        //font
        public bitmapFont?: BitmapFont;

        //skeleton
        public templet?: Laya.Templet;
        public skeletonAnchor?: Laya.Point;

        constructor() {
        }

        public load(): Object {
            return this.owner.getItemAsset(this);
        }

        public getBranch(): PackageItem {
            if (this.branches && this.owner._branchIndex != -1) {
                var itemId: string = this.branches[this.owner._branchIndex];
                if (itemId)
                    return this.owner.getItemById(itemId);
            }

            return this;
        }

        public getHighResolution(): PackageItem {
            if (this.highResolution && GRoot.contentScaleLevel > 0) {
                var itemId: string = this.highResolution[GRoot.contentScaleLevel - 1];
                if (itemId)
                    return this.owner.getItemById(itemId);
            }

            return this;
        }

        public toString(): string {
            return this.name;
        }
    }
}


text:
node.default['essentials']['help']['non-ess-in-help'] = true

# Hide plugins which do not give a permission.
# You can override a true value here for a single plugin by adding a permission to a user/group.
# The individual permission is: essentials.help.<plugin>, anyone with essentials.* or '*' will see all help regardless.
# You can use negative permissions to remove access to just a single plugins help if the following is enabled.
node.default['essentials']['help']['hide-permissionless-help'] = true


text:
using UnityEngine;
using VRTK;

public class Lamp : VRTK_InteractableObject
{
    public override void Grabbed(GameObject grabbingObject)
    {
        base.Grabbed(grabbingObject);
        ToggleKinematics(false);
    }

    public override void Ungrabbed(GameObject previousGrabbingObject)
    {
        base.Ungrabbed(previousGrabbingObject);
        ToggleKinematics(true);
    }

    private void ToggleKinematics(bool state)
    {
        foreach(Rigidbody rigid in transform.parent.GetComponentsInChildren<Rigidbody>())
        {
            rigid.isKinematic = state;
        }
    }
}


text:
package io.github.thankpoint.security.api.key;

import java.util.Set;

import io.github.thankpoint.security.api.key.asymmetric.SecurityAsymmetricKeyPair;
import io.github.thankpoint.security.api.key.symmetric.SecuritySymmetricKey;

/**
 * Interface for a {@link Set} of {@link SecurityKey}s that strictly belong together.
 *
 * @see SecuritySymmetricKey
 * @see SecurityAsymmetricKeyPair
 *
 * @author thks
 */
public interface SecurityKeySet {

  /**
   * @return the {@link Set} of {@link SecurityKey}s contained in this {@link SecurityKeySet}.
   */
  Set<? extends SecurityKey<?>> getKeys();

}


text:
@class QRCachedRunningApplication;
@protocol QRAppListPopoverDelegate;

@interface QRAppListPopover : NSPopover <NSPopoverDelegate>

@property (nonatomic, unsafe_unretained) IBOutlet NSObject<QRAppListPopoverDelegate> *appListDelegate;

@end

@protocol QRAppListPopoverDelegate <NSObject>

- (void)appListPopover:(QRAppListPopover *)popover selectedApp:(QRCachedRunningApplication *)app;

@end


text:
<body>

Support android.os classes to assist with development of applications for
android API level 4 or later.

</body>


text:
var interopUtils = require("./emscripten_interop_utils.js");

function EmscriptenIndoorsApi(emscriptenApiPointer, cwrap, emscriptenModule, emscriptenMemory) {

    var _emscriptenApiPointer = emscriptenApiPointer;
    var _emscriptenMemory = emscriptenMemory;

    var _indoorsApi_RegisterIndoorMapCallbacks = cwrap("indoorsApi_RegisterIndoorMapCallbacks", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number"]);
    var _indoorsApi_EnterIndoorMap = cwrap("indoorsApi_EnterIndoorMap", null, ["number", "string"]);
    var _indoorsApi_ExitIndoorMap = cwrap("indoorsApi_ExitIndoorMap", null, ["number"]);
    var _indoorsApi_HasActiveIndoorMap = cwrap("indoorsApi_HasActiveIndoorMap", "number", ["number"]);
    var _indoorsApi_GetActiveIndoorMapId = cwrap("indoorsApi_GetActiveIndoorMapId", "string", ["number"]);
    var _indoorsApi_GetActiveIndoorMapName = cwrap("indoorsApi_GetActiveIndoorMapName", "string", ["number"]);
    var _indoorsApi_GetActiveIndoorMapSourceVendor = cwrap("indoorsApi_GetActiveIndoorMapSourceVendor", "string", ["number"]);
    var _indoorsApi_GetActiveIndoorMapFloorCount = cwrap("indoorsApi_GetActiveIndoorMapFloorCount", "number", ["number"]);
    var _indoorsApi_GetActiveIndoorMapUserData = cwrap("indoorsApi_GetActiveIndoorMapUserData", "string", ["number"]);
    var _indoorsApi_GetSelectedFloorIndex = cwrap("indoorsApi_GetSelectedFloorIndex", "number", ["number"]);
    var _indoorsApi_SetSelectedFloorIndex = cwrap("indoorsApi_SetSelectedFloorIndex", "number", ["number", "number"]);
    var _indoorsApi_GetFloorName = cwrap("indoorsApi_GetFloorName", "string", ["number", "number"]);
    var _indoorsApi_GetFloorShortName = cwrap("indoorsApi_GetFloorShortName", "string", ["number", "number"]);
    var _indoorsApi_GetFloorNumber = cwrap("indoorsApi_GetFloorNumber", "number", ["number", "number"]);
    var _indoorsApi_GetFloorHeightAboveSeaLevel = cwrap("indoorsApi_GetFloorHeightAboveSeaLevel", "number", ["number", "number"]);

    var _indoorsApi_TryGetReadableNameBufferSize = cwrap("indoorsApi_TryGetReadableNameBufferSize", "number", ["number", "string", "number", "number"]);
    var _indoorsApi_TryGetReadableName = cwrap("indoorsApi_TryGetReadableName", "number", ["number", "string", "number", "number", "number"]);
    var _indoorsApi_TryGetFloorReadableNameBufferSize = cwrap("indoorsApi_TryGetFloorReadableNameBufferSize", "number", ["number", "string", "number", "number", "number"]);
    var _indoorsApi_TryGetFloorReadableName = cwrap("indoorsApi_TryGetFloorReadableName", "number", ["number", "string", "number", "number", "number", "number"]);
    var _indoorsApi_TryGetFloorShortNameBufferSize = cwrap("indoorsApi_TryGetFloorShortNameBufferSize", "number", ["number", "string", "number", "number", "number"]);
    var _indoorsApi_TryGetFloorShortName = cwrap("indoorsApi_TryGetFloorShortName", "number", ["number", "string", "number", "number", "number", "number"]);
    var _indoorsApi_SetBackgroundColor = cwrap("indoorsApi_SetBackgroundColor", null, ["number", "number"]);

    var _onIndoorMapEntered = null;
    var _onIndoorMapEnterFailed = null;
    var _onIndoorMapExited = null;
    var _onIndoorMapFloorChanged = null;
    var _onIndoorMapEntryMarkerAdded = null;
    var _onIndoorMapEntryMarkerRemoved = null;
    var _onIndoorMapLoaded = null;
    var _onIndoorMapUnloaded = null;

    var _indoorMapEnteredHandler = function() {
        if (_onIndoorMapEntered !== null) {
            _onIndoorMapEntered();
        }
    };

    var _indoorMapEntryFailedHandler = function() {
        if (_onIndoorMapEnterFailed !== null) {
            _onIndoorMapEnterFailed();
        }
    };

    var _indoorMapExitedHandler = function() {
        if (_onIndoorMapExited !== null) {
            _onIndoorMapExited();
        }
    };

    var _indoorMapFloorChangedHandler = function() {
        if (_onIndoorMapFloorChanged !== null) {
            _onIndoorMapFloorChanged();
        }
    };

    var _executeEntryMarkerCallback = function(callback, indoorMapIdPtr, indoorMapNamePtr, indoorMapLatLngPtr) {
        var indoorMapId = _emscriptenMemory.stringifyPointer(indoorMapIdPtr);
        var indoorMapName = _emscriptenMemory.stringifyPointer(indoorMapNamePtr);
        var latLngArray = _emscriptenMemory.readDoubles(indoorMapLatLngPtr, 3);
        var markerLatLng = L.latLng(latLngArray);
        callback(indoorMapId, indoorMapName, markerLatLng);
    };

    var _indoorMapEntryMarkerAddedHandler = function(indoorMapIdPtr, indoorMapNamePtr, indoorMapLatLngPtr) {
        if (_onIndoorMapEntryMarkerAdded !== null) {
            _executeEntryMarkerCallback(_onIndoorMapEntryMarkerAdded, indoorMapIdPtr, indoorMapNamePtr, indoorMapLatLngPtr);
        }
    };

    var _indoorMapEntryMarkerRemovedHandler = function(indoorMapIdPtr, indoorMapNamePtr, indoorMapLatLngPtr) {
        if (_onIndoorMapEntryMarkerRemoved !== null) {
            _executeEntryMarkerCallback(_onIndoorMapEntryMarkerRemoved, indoorMapIdPtr, indoorMapNamePtr, indoorMapLatLngPtr);
        }
    };

    var _indoorMapLoadedHandler = function(indoorMapIdPtr) {
        if (_onIndoorMapLoaded !== null) {
            var indoorMapId = _emscriptenMemory.stringifyPointer(indoorMapIdPtr);
            _onIndoorMapLoaded(indoorMapId);
        }
    };

    var _indoorMapUnloadedHandler = function(indoorMapIdPtr) {
        if (_onIndoorMapUnloaded !== null) {
            var indoorMapId = _emscriptenMemory.stringifyPointer(indoorMapIdPtr);
            _onIndoorMapUnloaded(indoorMapId);
        }
    };

    this.onInitialized = function() {
        _indoorsApi_RegisterIndoorMapCallbacks(
            _emscriptenApiPointer,
            emscriptenModule.addFunction(_indoorMapEnteredHandler),
            emscriptenModule.addFunction(_indoorMapEntryFailedHandler),
            emscriptenModule.addFunction(_indoorMapExitedHandler),
            emscriptenModule.addFunction(_indoorMapFloorChangedHandler),
            emscriptenModule.addFunction(_indoorMapEntryMarkerAddedHandler),
            emscriptenModule.addFunction(_indoorMapEntryMarkerRemovedHandler),
            emscriptenModule.addFunction(_indoorMapLoadedHandler),
            emscriptenModule.addFunction(_indoorMapUnloadedHandler)
        );
    };

    this.setNotificationCallbacks = function(
        indoorMapEnteredCallback,
        indoorMapEnterFailedCallback,
        indoorMapExitedCallback,
        indoorMapFloorChangedCallback,
        indoorMapEntryMarkerAddedCallback,
        indoorMapEntryMarkerRemovedCallback,
        indoorMapLoadedCallback,
        indoorMapUnloadedCallback
    ) {
        _onIndoorMapEntered = indoorMapEnteredCallback;
        _onIndoorMapEnterFailed = indoorMapEnterFailedCallback;
        _onIndoorMapExited = indoorMapExitedCallback;
        _onIndoorMapFloorChanged = indoorMapFloorChangedCallback;
        _onIndoorMapEntryMarkerAdded = indoorMapEntryMarkerAddedCallback;
        _onIndoorMapEntryMarkerRemoved = indoorMapEntryMarkerRemovedCallback;
        _onIndoorMapLoaded = indoorMapLoadedCallback;
        _onIndoorMapUnloaded = indoorMapUnloadedCallback;
    };

    this.enterIndoorMap = function(indoorMapId) {
        return _indoorsApi_EnterIndoorMap(_emscriptenApiPointer, indoorMapId);
    };

    this.exitIndoorMap = function() {
        _indoorsApi_ExitIndoorMap(_emscriptenApiPointer);
    };

    this.hasActiveIndoorMap = function() {
        return !!_indoorsApi_HasActiveIndoorMap(_emscriptenApiPointer);
    };

    this.getActiveIndoorMapId = function() {
        return _indoorsApi_GetActiveIndoorMapId(_emscriptenApiPointer);
    };

    this.getActiveIndoorMapName = function() {
        return _indoorsApi_GetActiveIndoorMapName(_emscriptenApiPointer);
    };

    this.getActiveIndoorMapSourceVendor = function() {
        return _indoorsApi_GetActiveIndoorMapSourceVendor(_emscriptenApiPointer);
    };

    this.getActiveIndoorMapFloorCount = function() {
        return _indoorsApi_GetActiveIndoorMapFloorCount(_emscriptenApiPointer);
    };

    this.getActiveIndoorMapUserData = function() {
        return _indoorsApi_GetActiveIndoorMapUserData(_emscriptenApiPointer);
    };

    this.getSelectedFloorIndex = function() {
        return _indoorsApi_GetSelectedFloorIndex(_emscriptenApiPointer);
    };

    this.setSelectedFloorIndex = function(floorIndex) {
        return !!_indoorsApi_SetSelectedFloorIndex(_emscriptenApiPointer, floorIndex);
    };

    this.getFloorName = function(floorIndex) {
        return _indoorsApi_GetFloorName(_emscriptenApiPointer, floorIndex);
    };

    this.getFloorShortName = function(floorIndex) {
        return _indoorsApi_GetFloorShortName(_emscriptenApiPointer, floorIndex);
    };

    this.getFloorNumber = function(floorIndex) {
        return _indoorsApi_GetFloorNumber(_emscriptenApiPointer, floorIndex);
    };

    this.getFloorHeightAboveSeaLevel = function(floorIndex) {
        return _indoorsApi_GetFloorHeightAboveSeaLevel(_emscriptenApiPointer, floorIndex);
    };

    this.tryGetReadableName = function(indoorMapId) {
        var bufferSizeBuf = _emscriptenMemory.createInt32Buffer(1);

        var success = _indoorsApi_TryGetReadableNameBufferSize(
            _emscriptenApiPointer,
            indoorMapId,
            indoorMapId.length,
            bufferSizeBuf.ptr
        );

        if (!success) {
            return null;
        }

        var bufferSize = _emscriptenMemory.consumeBufferToArray(bufferSizeBuf)[0];
        var stringBuffer = _emscriptenMemory.createInt8Buffer(bufferSize);

        success = _indoorsApi_TryGetReadableName(
            _emscriptenApiPointer,
            indoorMapId,
            indoorMapId.length,
            stringBuffer.ptr,
            bufferSize
        );

        if (!success) {
            return null;
        }

        var indoorMapReadableName = _emscriptenMemory.consumeUtf8BufferToString(stringBuffer);
        return indoorMapReadableName;
    };

    var _tryGetNativeIndoorMapFloorString = function(indoorMapId, indoorMapFloorId, nativeGetBufferSizeFunc, nativeGetStringFunc) {
        var bufferSizeBuf = _emscriptenMemory.createInt32Buffer(1);

        var success = nativeGetBufferSizeFunc(
            _emscriptenApiPointer,
            indoorMapId,
            indoorMapId.length,
            indoorMapFloorId,
            bufferSizeBuf.ptr
        );

        if (!success) {
            return null;
        }

        var bufferSize = _emscriptenMemory.consumeBufferToArray(bufferSizeBuf)[0];
        var stringBuffer = _emscriptenMemory.createInt8Buffer(bufferSize);

        success = nativeGetStringFunc(
            _emscriptenApiPointer,
            indoorMapId,
            indoorMapId.length,
            indoorMapFloorId,
            stringBuffer.ptr,
            bufferSize
        );

        if (!success) {
            return null;
        }

        var stringValue = _emscriptenMemory.consumeUtf8BufferToString(stringBuffer);
        return stringValue;
    };

    this.tryGetFloorReadableName = function(indoorMapId, indoorMapFloorId) {
        return _tryGetNativeIndoorMapFloorString(
            indoorMapId,
            indoorMapFloorId,
            _indoorsApi_TryGetFloorReadableNameBufferSize,
            _indoorsApi_TryGetFloorReadableName
        );
    };

    this.tryGetFloorShortName = function(indoorMapId, indoorMapFloorId) {
        return _tryGetNativeIndoorMapFloorString(
            indoorMapId,
            indoorMapFloorId,
            _indoorsApi_TryGetFloorShortNameBufferSize,
            _indoorsApi_TryGetFloorShortName
        );
    };

    this.setBackgroundColor = function(color) {
        var colorRGBA32 = interopUtils.colorToRgba32(color);
        _indoorsApi_SetBackgroundColor(_emscriptenApiPointer, colorRGBA32);
    };
}

module.exports = EmscriptenIndoorsApi;


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mpersonal extends CI_Model
{

    public $table = 'personal';
    public $id = 'id';
    public $order = 'DESC';

    function __construct()
    {
        parent::__construct();
    }

    // get all
    function get_all()
    {
        $this->db->order_by($this->id, $this->order);
        return $this->db->get($this->table)->result();
    }

}


text:
'use strict'

let EzGen = require('./ez-gen').EzGen

let ezGen = new EzGen()
ezGen.run()


text:
package org.innovateuk.ifs.finance.resource.cost;

import java.math.BigDecimal;

public class PreviousFunding extends BaseOtherFunding {

    public PreviousFunding() {
        this(null);
    }

    public PreviousFunding(Long targetId) {
        super(targetId);
    }

    public PreviousFunding(Long id, String otherPublicFunding, String fundingSource, String securedDate, BigDecimal fundingAmount, Long targetId) {
        super(id, otherPublicFunding, fundingSource, securedDate, fundingAmount, targetId);
    }

    @Override
    public FinanceRowType getCostType() {
        return FinanceRowType.PREVIOUS_FUNDING;
    }
}


text:
var Memcache = require('memcached');
var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.defaults = {
    host: '127.0.0.1',
    port: 11211
};

internals.testConnectionSettings = {
    timeout: 1000,
    idle: 1000,
    failures: 0,
    retries: 0,
    poolsize: 1
};

exports = module.exports = internals.Connection = function (options) {

    options = options || {};

    Hoek.assert(this.constructor === internals.Connection, 'Memcached cache client must be instantiated using new');
    Hoek.assert(!(options.location && (options.host || options.port)), 'Cannot specify both location and host/port when using memcached');

    this.settings = Hoek.applyToDefaults(internals.defaults, options);
    this.settings.location = this.settings.location || (this.settings.host + ':' + this.settings.port);
    delete this.settings.port;
    delete this.settings.host;

    this.client = null;
    return this;
};

internals.Connection.prototype.start = function (callback) {

    var self = this;
    if (this.client) {
        return callback();
    }

    var connect = function () {

        self.client = new Memcache(self.settings.location, self.settings);

        callback();
    };

    var testConnectionSettings = Hoek.applyToDefaults(internals.testConnectionSettings, {
        timeout: self.settings.timeout,
        idle: self.settings.idle
    });

    var testConnection = new Memcache(this.settings.location, testConnectionSettings);

    testConnection.get('foobar', function (err) {

        if (err) {
            testConnection.end();
            return callback(new Error('Failed opening memcached connection'));
        }

        connect();
    });
};

internals.Connection.prototype.stop = function () {

    if (this.client) {
        this.client.end();
        this.client = null;
    }
};

internals.Connection.prototype.isReady = function () {

    return (!!this.client);
};

internals.Connection.prototype.validateSegmentName = function (name) {

    if (!name) {
        return new Error('Empty string');
    }

    if (name.indexOf('\0') !== -1) {
        return new Error('Includes null character');
    }

    // https://github.com/memcached/memcached/blob/master/doc/protocol.txt#L47-49

    if (name.match(/\s/g)) {
        return new Error('Includes space character');
    }

    return null;
};

internals.Connection.prototype.get = function (key, callback) {

    if (!this.client) {
        return callback(new Error('Connection not started'));
    }

    this.client.get(this.generateKey(key), function (err, result) {

        if (err) {
            return callback(err);
        }

        if (!result) {
            return callback(null, null);
        }

        var envelope = null;
        try {
            envelope = JSON.parse(result);
        }
        catch (err) { }  // Handled by validation below

        if (!envelope) {
            return callback(new Error('Bad envelope content'));
        }

        if (!envelope.item ||
            !envelope.stored) {

            return callback(new Error('Incorrect envelope structure'));
        }

        return callback(null, envelope);
    });
};

internals.Connection.prototype.set = function (key, value, ttl, callback) {

    var self = this;

    if (!this.client) {
        return callback(new Error('Connection not started'));
    }

    var envelope = {
        item: value,
        stored: Date.now(),
        ttl: ttl
    };

    var cacheKey = this.generateKey(key);

    var stringifiedEnvelope = null;

    try {
        stringifiedEnvelope = JSON.stringify(envelope);
    }
    catch (err) {
        return callback(err);
    }

    var ttlSec = Math.max(1, Math.floor(ttl / 1000));
    this.client.set(cacheKey, stringifiedEnvelope, ttlSec, function (err) {

        if (err) {
            callback(err);
        } else {
            callback();
        }
    });
};

internals.Connection.prototype.drop = function (key, callback) {

    if (!this.client) {
        return callback(new Error('Connection not started'));
    }

    this.client.del(this.generateKey(key), function (err) {

        return callback(err);
    });
};

internals.Connection.prototype.generateKey = function (key) {

    return encodeURIComponent(this.settings.partition) + ':' + encodeURIComponent(key.segment) + ':' + encodeURIComponent(key.id);
};


text:
module Spree
  module Admin
    UsersController.class_eval do
      def active_deactive
        user = Spree::User.find(params[:id]) if params[:id]
        if user && user.is_active.present?
          user.update_attributes(is_active: false)
          flash[:notice] = Spree.t(:user_deactivated)
        else
          user.update_attributes(is_active: true)
          flash[:notice] = Spree.t(:user_activated)
        end
        redirect_to admin_users_path
      end
    end
  end
end


text:
use crate::architecture::Architecture;
use crate::error::*;
use crate::executor::successor::*;
use crate::executor::State;
use crate::il;
use crate::RC;

/// A driver for a concrete executor over Falcon IL.
#[derive(Debug, Clone)]
pub struct Driver {
    program: RC<il::Program>,
    location: il::ProgramLocation,
    state: State,
    architecture: RC<dyn Architecture>,
}

impl Driver {
    /// Create a new driver for concrete execution over Falcon IL.
    pub fn new(
        program: RC<il::Program>,
        location: il::ProgramLocation,
        state: State,
        architecture: RC<dyn Architecture>,
    ) -> Driver {
        Driver {
            program,
            location,
            state,
            architecture,
        }
    }

    /// Step forward over Falcon IL.
    pub fn step(self) -> Result<Driver> {
        let location = self.location.apply(&self.program)?;
        match *location.function_location() {
            il::RefFunctionLocation::Instruction(_, instruction) => {
                let successor = self.state.execute(instruction.operation())?;

                match successor.type_().clone() {
                    SuccessorType::FallThrough => {
                        let locations = location.forward()?;
                        if locations.len() == 1 {
                            Ok(Driver::new(
                                self.program.clone(),
                                locations[0].clone().into(),
                                successor.into(),
                                self.architecture,
                            ))
                        } else {
                            // every location should be an edge, and only one
                            // edge should be satisfiable
                            for location in locations {
                                if let il::RefFunctionLocation::Edge(edge) =
                                    *location.function_location()
                                {
                                    if successor
                                        .state()
                                        .symbolize_and_eval(
                                            edge.condition()
                                                .ok_or("Failed to get edge condition")?,
                                        )?
                                        .is_one()
                                    {
                                        return Ok(Driver::new(
                                            self.program.clone(),
                                            location.clone().into(),
                                            successor.into(),
                                            self.architecture,
                                        ));
                                    }
                                }
                            }
                            bail!("No valid successor location found on fall through");
                        }
                    }
                    SuccessorType::Branch(address) => {
                        match il::RefProgramLocation::from_address(&self.program, address) {
                            Some(location) => Ok(Driver::new(
                                self.program.clone(),
                                location.into(),
                                successor.into(),
                                self.architecture,
                            )),
                            None => {
                                let state: State = successor.into();
                                let function = self
                                    .architecture
                                    .translator()
                                    .translate_function(state.memory(), address)
                                    .unwrap_or_else(|e| {
                                        panic!(
                                            "Failed to lift function at 0x{:x}: {:?}",
                                            address, e
                                        )
                                    });
                                let mut program = self.program.clone();
                                RC::make_mut(&mut program).add_function(function);
                                let location: il::ProgramLocation =
                                    il::RefProgramLocation::from_address(&program, address)
                                        .ok_or("Failed to get location for newly lifted function")?
                                        .into();
                                Ok(Driver::new(program, location, state, self.architecture))
                            }
                        }
                    }
                    SuccessorType::Intrinsic(ref intrinsic) => {
                        bail!(format!(
                            "Intrinsic is unimplemented, {}",
                            intrinsic.instruction_str()
                        ));
                    }
                }
            }
            il::RefFunctionLocation::Edge(_) => {
                let locations = location.forward()?;
                Ok(Driver::new(
                    self.program.clone(),
                    locations[0].clone().into(),
                    self.state,
                    self.architecture,
                ))
            }
            il::RefFunctionLocation::EmptyBlock(_) => {
                let locations = location.forward()?;
                if locations.len() == 1 {
                    return Ok(Driver::new(
                        self.program.clone(),
                        locations[0].clone().into(),
                        self.state,
                        self.architecture,
                    ));
                } else {
                    for location in locations {
                        if let il::RefFunctionLocation::Edge(edge) = *location.function_location() {
                            if self
                                .state
                                .symbolize_and_eval(
                                    edge.condition().ok_or("Failed to get edge condition")?,
                                )?
                                .is_one()
                            {
                                return Ok(Driver::new(
                                    self.program.clone(),
                                    location.clone().into(),
                                    self.state,
                                    self.architecture,
                                ));
                            }
                        }
                    }
                }
                bail!("No valid location out of empty block");
            }
        }
    }

    /// Retrieve the Falcon IL program associated with this driver.
    pub fn program(&self) -> &il::Program {
        &self.program
    }

    /// If this driver is sitting on an instruction with an address, return
    /// that address.
    pub fn address(&self) -> Option<u64> {
        self.location
            .apply(&self.program)
            .expect("Failed to apply program location")
            .address()
    }

    /// Retrieve the `il::ProgramLocation` associated with this driver.
    pub fn location(&self) -> &il::ProgramLocation {
        &self.location
    }

    /// Retrieve the concrete `State` associated with this driver.
    pub fn state(&self) -> &State {
        &self.state
    }

    /// Retrieve a mutable reference to the `State` associated with this driver.
    pub fn state_mut(&mut self) -> &mut State {
        &mut self.state
    }
}


text:
namespace electron {

class TrayIcon {
 public:
  static TrayIcon* Create(base::Optional<UUID> guid);

#if defined(OS_WIN)
  using ImageType = HICON;
#else
  using ImageType = const gfx::Image&;
#endif

  virtual ~TrayIcon();

  // Sets the image associated with this status icon.
  virtual void SetImage(ImageType image) = 0;

  // Sets the image associated with this status icon when pressed.
  virtual void SetPressedImage(ImageType image);

  // Sets the hover text for this status icon. This is also used as the label
  // for the menu item which is created as a replacement for the status icon
  // click action on platforms that do not support custom click actions for the
  // status icon (e.g. Ubuntu Unity).
  virtual void SetToolTip(const std::string& tool_tip) = 0;

#if defined(OS_MAC)
  // Set/Get flag determining whether to ignore double click events.
  virtual void SetIgnoreDoubleClickEvents(bool ignore) = 0;
  virtual bool GetIgnoreDoubleClickEvents() = 0;

  struct TitleOptions {
    std::string font_type;
  };

  // Set/Get title displayed next to status icon in the status bar.
  virtual void SetTitle(const std::string& title,
                        const TitleOptions& options) = 0;
  virtual std::string GetTitle() = 0;
#endif

  enum class IconType { kNone, kInfo, kWarning, kError, kCustom };

  struct BalloonOptions {
    IconType icon_type = IconType::kCustom;
#if defined(OS_WIN)
    HICON icon = nullptr;
#else
    gfx::Image icon;
#endif
    std::u16string title;
    std::u16string content;
    bool large_icon = true;
    bool no_sound = false;
    bool respect_quiet_time = false;

    BalloonOptions();
  };

  // Displays a notification balloon with the specified contents.
  // Depending on the platform it might not appear by the icon tray.
  virtual void DisplayBalloon(const BalloonOptions& options);

  // Removes the notification balloon.
  virtual void RemoveBalloon();

  // Returns focus to the taskbar notification area.
  virtual void Focus();

  // Popups the menu.
  virtual void PopUpContextMenu(const gfx::Point& pos,
                                ElectronMenuModel* menu_model);

  virtual void CloseContextMenu();

  // Set the context menu for this icon.
  virtual void SetContextMenu(ElectronMenuModel* menu_model) = 0;

  // Returns the bounds of tray icon.
  virtual gfx::Rect GetBounds();

  void AddObserver(TrayIconObserver* obs) { observers_.AddObserver(obs); }
  void RemoveObserver(TrayIconObserver* obs) { observers_.RemoveObserver(obs); }

  void NotifyClicked(const gfx::Rect& = gfx::Rect(),
                     const gfx::Point& location = gfx::Point(),
                     int modifiers = 0);
  void NotifyDoubleClicked(const gfx::Rect& = gfx::Rect(), int modifiers = 0);
  void NotifyBalloonShow();
  void NotifyBalloonClicked();
  void NotifyBalloonClosed();
  void NotifyRightClicked(const gfx::Rect& bounds = gfx::Rect(),
                          int modifiers = 0);
  void NotifyDrop();
  void NotifyDropFiles(const std::vector<std::string>& files);
  void NotifyDropText(const std::string& text);
  void NotifyDragEntered();
  void NotifyDragExited();
  void NotifyDragEnded();
  void NotifyMouseUp(const gfx::Point& location = gfx::Point(),
                     int modifiers = 0);
  void NotifyMouseDown(const gfx::Point& location = gfx::Point(),
                       int modifiers = 0);
  void NotifyMouseEntered(const gfx::Point& location = gfx::Point(),
                          int modifiers = 0);
  void NotifyMouseExited(const gfx::Point& location = gfx::Point(),
                         int modifiers = 0);
  void NotifyMouseMoved(const gfx::Point& location = gfx::Point(),
                        int modifiers = 0);

 protected:
  TrayIcon();

 private:
  base::ObserverList<TrayIconObserver> observers_;

  DISALLOW_COPY_AND_ASSIGN(TrayIcon);
};

}  // namespace electron

#endif  // SHELL_BROWSER_UI_TRAY_ICON_H_


text:
package com.twitter.algebird.macros

import scala.language.experimental.{macros => sMacros}
import scala.reflect.macros.Context

/**
 * "Cubes" a case class or tuple, i.e. for a tuple of type
 * (T1, T2, ... , TN) generates all 2^N possible combinations of type
 * (Option[T1], Option[T2], ... , Option[TN]).
 *
 * This is useful for comparing some metric across all possible subsets.
 * For example, suppose we have a set of people represented as
 * case class Person(gender: String, age: Int, height: Double)
 * and we want to know the average height of
 *  - people, grouped by gender and age
 *  - people, grouped by only gender
 *  - people, grouped by only age
 *  - all people
 *
 * Then we could do
 * > import com.twitter.algebird.macros.Cuber.cuber
 * > val people: List[People]
 * > val averageHeights: Map[(Option[String], Option[Int]), Double] =
 * >   people.flatMap { p => cuber((p.gender, p.age)).map((_,p)) }
 * >     .groupBy(_._1)
 * >     .mapValues { xs => val heights = xs.map(_.height); heights.sum / heights.length }
 */
trait Cuber[I] {
  type K
  def apply(in: I): TraversableOnce[K]
}

object Cuber {
  implicit def cuber[T]: Cuber[T] = macro cuberImpl[T]

  def cuberImpl[T](c: Context)(implicit T: c.WeakTypeTag[T]): c.Expr[Cuber[T]] = {
    import c.universe._

    ensureCaseClass(c)

    val params = getParams(c)
    val arity = params.length
    if (arity > 22)
      c.abort(c.enclosingPosition, s"Cannot create Cuber for $T because it has more than 22 parameters.")
    if (arity == 0)
      c.abort(c.enclosingPosition, s"Cannot create Cuber for $T because it has no parameters.")

    val tupleName = {
      val types = getParamTypes(c)
      val optionTypes = types.map { t =>
        tq"_root_.scala.Option[$t]"
      }
      val tupleType = newTypeName(s"Tuple${arity}")
      tq"_root_.scala.$tupleType[..$optionTypes]"
    }

    val somes = params.zip(Stream.from(1)).map {
      case (param, index) =>
        val name = newTermName(s"some$index")
        q"val $name = _root_.scala.Some(in.$param)"
    }

    val options = (1 to arity).map { index =>
      val some = newTermName(s"some$index")
      q"if (((1 << ${index - 1}) & i) == 0) _root_.scala.None else $some"
    }

    val cuber = q"""
    new _root_.com.twitter.algebird.macros.Cuber[${T}] {
      type K = $tupleName
      def apply(in: ${T}): _root_.scala.Seq[K] = {
        ..$somes
        (0 until (1 << $arity)).map { i =>
          new K(..$options)
        }
      }
    }
    """
    c.Expr[Cuber[T]](cuber)
  }
}


text:
package org.apache.cassandra.db;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

import org.apache.cassandra.Util;

import org.junit.Test;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
import static junit.framework.Assert.assertEquals;

public class CompactionsTest extends CleanupHelper
{
    public static final String TABLE1 = "Keyspace1";
    public static final String TABLE2 = "Keyspace2";
    public static final InetAddress LOCAL = FBUtilities.getLocalAddress();

    @Test
    public void testCompactions() throws IOException, ExecutionException, InterruptedException
    {
        CompactionManager.instance.disableAutoCompaction();

        // this test does enough rows to force multiple block indexes to be used
        Table table = Table.open(TABLE1);
        ColumnFamilyStore store = table.getColumnFamilyStore("Standard1");

        final int ROWS_PER_SSTABLE = 10;
        Set<DecoratedKey> inserted = new HashSet<DecoratedKey>();
        for (int j = 0; j < (DatabaseDescriptor.getIndexInterval() * 3) / ROWS_PER_SSTABLE; j++) {
            for (int i = 0; i < ROWS_PER_SSTABLE; i++) {
                DecoratedKey key = Util.dk(String.valueOf(i % 2));
                RowMutation rm = new RowMutation(TABLE1, key.key);
                rm.add(new QueryPath("Standard1", null, ByteBufferUtil.bytes(String.valueOf(i / 2))), ByteBufferUtil.EMPTY_BYTE_BUFFER, j * ROWS_PER_SSTABLE + i);
                rm.apply();
                inserted.add(key);
            }
            store.forceBlockingFlush();
            assertEquals(inserted.toString(), inserted.size(), Util.getRangeSlice(store).size());
        }
        while (true)
        {
            Future<Integer> ft = CompactionManager.instance.submitMinorIfNeeded(store);
            if (ft.get() == 0)
                break;
        }
        if (store.getSSTables().size() > 1)
        {
            CompactionManager.instance.performMajor(store);
        }
        assertEquals(inserted.size(), Util.getRangeSlice(store).size());
    }

    @Test
    public void testGetBuckets()
    {
        List<Pair<String, Long>> pairs = new ArrayList<Pair<String, Long>>();
        String[] strings = { "a", "bbbb", "cccccccc", "cccccccc", "bbbb", "a" };
        for (String st : strings)
        {
            Pair<String, Long> pair = new Pair<String, Long>(st, new Long(st.length()));
            pairs.add(pair);
        }

        Set<List<String>> buckets = CompactionManager.getBuckets(pairs, 2);
        assertEquals(3, buckets.size());

        for (List<String> bucket : buckets)
        {
            assertEquals(2, bucket.size());
            assertEquals(bucket.get(0).length(), bucket.get(1).length());
            assertEquals(bucket.get(0).charAt(0), bucket.get(1).charAt(0));
        }

        pairs.clear();
        buckets.clear();

        String[] strings2 = { "aaa", "bbbbbbbb", "aaa", "bbbbbbbb", "bbbbbbbb", "aaa" };
        for (String st : strings2)
        {
            Pair<String, Long> pair = new Pair<String, Long>(st, new Long(st.length()));
            pairs.add(pair);
        }

        buckets = CompactionManager.getBuckets(pairs, 2);
        assertEquals(2, buckets.size());

        for (List<String> bucket : buckets)
        {
            assertEquals(3, bucket.size());
            assertEquals(bucket.get(0).charAt(0), bucket.get(1).charAt(0));
            assertEquals(bucket.get(1).charAt(0), bucket.get(2).charAt(0));
        }

        // Test the "min" functionality
        pairs.clear();
        buckets.clear();

        String[] strings3 = { "aaa", "bbbbbbbb", "aaa", "bbbbbbbb", "bbbbbbbb", "aaa" };
        for (String st : strings3)
        {
            Pair<String, Long> pair = new Pair<String, Long>(st, new Long(st.length()));
            pairs.add(pair);
        }

        buckets = CompactionManager.getBuckets(pairs, 10); // notice the min is 10
        assertEquals(1, buckets.size());
    }

}


text:
package org.cs3.pdt.console;

public class PDTConsolePredicates {

	private PDTConsolePredicates(){}

	// console server
	public static final String PDT_CURRENT_CONSOLE_SERVER = "pdt_console_server:pdt_current_console_server";
	public static final String PDT_START_CONSOLE_SERVER = "pdt_console_server:pdt_start_console_server";
	public static final String PDT_STOP_CONSOLE_SERVER = "pdt_console_server:pdt_stop_console_server";
	public static final String CONSOLE_THREAD_NAME = "pdt_console_server:console_thread_name";

}


text:
/**
 * @ngdoc service
 * @name umbraco.services.mediaTypeHelper
 * @description A helper service for the media types
 **/
function mediaTypeHelper(mediaTypeResource, $q) {

    var mediaTypeHelperService = {

        isFolderType: function(mediaEntity) {
            if (!mediaEntity) {
                throw "mediaEntity is null";
            }
            if (!mediaEntity.contentTypeAlias) {
                throw "mediaEntity.contentTypeAlias is null";
            }

            //if you create a media type, which has an alias that ends with ...Folder then its a folder: ex: "secureFolder", "bannerFolder", "Folder"
            //this is the exact same logic that is performed in MediaController.GetChildFolders
            return mediaEntity.contentTypeAlias.endsWith("Folder");
        },

        getAllowedImagetypes: function (mediaId){

            // Get All allowedTypes
            return mediaTypeResource.getAllowedTypes(mediaId)
                .then(function(types){

                    var allowedQ = types.map(function(type){
                        return mediaTypeResource.getById(type.id);
                    });

                    // Get full list
                    return $q.all(allowedQ).then(function(fullTypes){

                        // Find all the media types with an Image Cropper property editor
                        var filteredTypes = mediaTypeHelperService.getTypeWithEditor(fullTypes, ['Umbraco.ImageCropper']);

                        // If there is only one media type with an Image Cropper we will return this one
                        if(filteredTypes.length === 1) {
                            return filteredTypes;
                        // If there is more than one Image cropper, custom media types have been added, and we return all media types with and Image cropper or UploadField
                        } else {
                            return mediaTypeHelperService.getTypeWithEditor(fullTypes, ['Umbraco.ImageCropper', 'Umbraco.UploadField']);
                        }

                    });
            });
		},

        getTypeWithEditor: function (types, editors) {

            return types.filter(function (mediatype) {
                for (var i = 0; i < mediatype.groups.length; i++) {
                    var group = mediatype.groups[i];
                    for (var j = 0; j < group.properties.length; j++) {
                        var property = group.properties[j];
                        if( editors.indexOf(property.editor) !== -1 ) {
                            return mediatype;
                        }
                    }
                }
            });

        }

    };

    return mediaTypeHelperService;
}
angular.module('umbraco.services').factory('mediaTypeHelper', mediaTypeHelper);


text:
package container_with_most_water;

public class ContainerWithMostWater {

    public class Solution {
        public int maxArea(int[] height) {
            int maxArea = 0;
            int start = 0;
            int end = height.length - 1;
            while (start < end) {
                if (height[start] < height[end]) {
                    maxArea = Math.max(maxArea, (end - start) * height[start]);
                    start++;
                } else {
                    maxArea = Math.max(maxArea, (end - start) * height[end]);
                    end--;
                }
            }
            return maxArea;
        }
    }

    public static class UnitTest {

    }
}


text:
package org.cagrid.trust.tools;

import org.apache.commons.lang.StringUtils;
import org.cagrid.core.commandline.BaseCommandLine;
import org.cagrid.core.xml.XMLUtils;
import org.cagrid.gaards.pki.CertUtil;
import org.cagrid.trust.model.*;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Created by langella on 3/25/14.
 */
public class Bootstrapper extends BaseCommandLine {

    private static final String PROPERTIES_FILE = "src/main/resources/bootstrapper.properties";
    private static final String TRUST_SERVICE_DIR = "cagrid-trust";
    private static final String CERTIFICATES_DIR = "certificates";
    private static final String SYNC_DESCRIPTION_FILE = "sync-description.xml";
    private static final String TRUST_SERVICE_CFG = "cagrid.trust.service.cfg";

    private static final String TRUSTED_CA_PROMPT = "Please enter the location of a trust root certificate authority";
    private static final String TRUSTED_CA_PROPERTY = "cagrid.trust.ca.certificate.";

    private static final String TRUSTSTORE_FILE_NAME = "truststore.jks";
    private static final String TRUSTSTORE_LOCATION_PROPERTY_VALUE = "${karaf.base}/etc/" + TRUST_SERVICE_DIR + "/" + TRUSTSTORE_FILE_NAME;
    private static final String TRUSTSTORE_LOCATION_PROPERTY = "cagrid.trust.service.truststore.file";
    private static final String TRUSTSTORE_PASSWORD_PROMPT = "Please enter a password for the truststore";
    private static final String TRUSTSTORE_PASSWORD_PROPERTY = "cagrid.trust.service.truststore.password";

    private static final String GTS_URL_PROMPT = "Please enter the URL of the GTS you want the trust service to sync with";
    private static final String GTS_URL_PROPERTY = "cagrid.trust.service.gts.url";

    private static final String GTS_IDENTITY_PROMPT = "Please enter the identity of the GTS you want the trust service to sync with";
    private static final String GTS_IDENTITY_PROPERTY = "cagrid.trust.service.gts.identity";

    private static final String GTS_EXPIRATION_HOURS_PROMPT = "Please enter the number of hours a certificate authority should be trusted for without getting an update from the GTS";
    private static final String GTS_EXPIRATION_HOURS_PROPERTY = "cagrid.trust.service.gts.expiration.hours";

    private static final String GTS_EXPIRATION_MINUTES_PROMPT = "Please enter the number of minutes a certificate authority should be trusted for without getting an update from the GTS";
    private static final String GTS_EXPIRATION_MINUTES_PROPERTY = "cagrid.trust.service.gts.expiration.minutes";

    private static final String GTS_EXPIRATION_SECONDS_PROMPT = "Please enter the number of seconds a certificate authority should be trusted for without getting an update from the GTS";
    private static final String GTS_EXPIRATION_SECONDS_PROPERTY = "cagrid.trust.service.gts.expiration.seconds";

    private static final String GTS_NEXT_SYNC_PROMPT = "Please enter how often (milliseconds) the trust service should syn with the GTS";
    private static final String GTS_NEXT_SYNC_PROPERTY = "cagrid.trust.service.sync.repeat.interval";

    private static final String CONFIGURER_PROMPT = "Please specifiy a client configurer to use (truststoreClientConfigurer OR trustServiceClientConfigurer)";
    private static final String CONFIGURER_PROPERTY = "cagrid.trust.service.client.configurer";

    private List<X509Certificate> certificates;

    private File trustEtcDir;

    private Properties serviceProperties;

    public Bootstrapper(File propertiesFile) throws Exception {
        super(propertiesFile);

    }

    public Bootstrapper(Properties properties) throws Exception {
        super(properties);

    }

    public static void main(String[] args) {
        try {
            Bootstrapper main = new Bootstrapper(new File(PROPERTIES_FILE));
            main.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void execute() throws Exception {
        System.out.println("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
        System.out.println("*                Trust Service Bootstrapper                 *");
        System.out.println("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
        System.out.println("");
        serviceProperties = new Properties();
        trustEtcDir = new File(getServiceMixEtc().getAbsolutePath() + File.separator + TRUST_SERVICE_DIR);
        trustEtcDir.mkdirs();
        buildTrustList();
        createAndConfigureTruststore();
        writeTrustedCertificates();
        writeSyncDescription();

        String nextSync = getValue(GTS_NEXT_SYNC_PROMPT, GTS_NEXT_SYNC_PROPERTY);
        serviceProperties.setProperty(GTS_NEXT_SYNC_PROPERTY, nextSync);

        configureConfigurer();

        File config = new File(getServiceMixEtc(), TRUST_SERVICE_CFG);
        serviceProperties.store(new FileOutputStream(config), "Trust Service Configuration saved by bootstrapper on " + new Date());

    }

    private void configureConfigurer() {
        String configurer = getValue(CONFIGURER_PROMPT, CONFIGURER_PROPERTY);
        serviceProperties.setProperty(CONFIGURER_PROPERTY, configurer);
    }

    private void writeSyncDescription() {

        String gtsURL = getValue(GTS_URL_PROMPT, GTS_URL_PROPERTY);
        String gtsIdentity = getValue(GTS_IDENTITY_PROMPT, GTS_IDENTITY_PROPERTY);

        SyncDescription des = new SyncDescription();
        SyncDescriptor descriptor = new SyncDescriptor();
        des.getSyncDescriptors().add(descriptor);
        descriptor.setGTS(gtsURL);

        if (StringUtils.isBlank(gtsIdentity)) {
            descriptor.setPerformAuthorization(false);
        } else {
            descriptor.setPerformAuthorization(true);
            descriptor.setGTSIdentity(gtsIdentity);
        }

        Integer hours = Integer.valueOf(getValue(GTS_EXPIRATION_HOURS_PROMPT, GTS_EXPIRATION_HOURS_PROPERTY));
        Integer minutes = Integer.valueOf(getValue(GTS_EXPIRATION_MINUTES_PROMPT, GTS_EXPIRATION_MINUTES_PROPERTY));
        Integer seconds = Integer.valueOf(getValue(GTS_EXPIRATION_SECONDS_PROMPT, GTS_EXPIRATION_SECONDS_PROPERTY));
        Expiration expiration = new Expiration();
        expiration.setHours(hours);
        expiration.setMinutes(minutes);
        expiration.setSeconds(seconds);
        descriptor.setExpiration(expiration);

        TrustedAuthorityFilter f = new TrustedAuthorityFilter();
        f.setStatus(Status.TRUSTED);
        f.setLifetime(Lifetime.VALID);
        descriptor.getTrustedAuthorityFilters().add(f);

        ExcludedCAs excluded = new ExcludedCAs();

        for (X509Certificate cert : this.certificates) {
            excluded.getCASubjects().add(cert.getSubjectDN().getName());
        }

        des.setExcludedCAs(excluded);
        des.setDeleteInvalidFiles(false);
        des.setNextSync(BigInteger.valueOf(600));
        DateFilter df = new DateFilter();
        df.setMonth(1);
        df.setYear(0);
        df.setDay(0);
        des.setCacheSize(df);
        File syncDescription = new File(this.trustEtcDir.getAbsolutePath() + File.separator + SYNC_DESCRIPTION_FILE);
        try {
            XMLUtils.toXMLFile(des, syncDescription);
            System.out.println("Successfully wrote the sync description to " + syncDescription.getAbsolutePath() + ".");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

    }

    private void writeTrustedCertificates() {
        try {
            File dir = new File(this.trustEtcDir.getAbsolutePath() + File.separator + CERTIFICATES_DIR);
            dir.mkdirs();
            int count = 0;
            for (X509Certificate cert : this.certificates) {
                File caFile = new File(dir.getAbsolutePath() + File.separator + "trust-ca-" + count + ".cert");
                CertUtil.writeCertificate(cert, caFile);
                System.out.println("Successfully wrote the CA " + cert.getSubjectDN().getName() + " to " + caFile.getAbsolutePath() + ".");
                count = count + 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void createAndConfigureTruststore() {
        try {
            File f = new File(this.trustEtcDir.getAbsolutePath() + File.separator + TRUSTSTORE_FILE_NAME);
            KeyStore keyStore = KeyStore.getInstance("jks");
            keyStore.load(null);
            int count = 0;
            for (X509Certificate cert : this.certificates) {
                String alias = "trustca" + count;
                keyStore.setEntry(alias, new KeyStore.TrustedCertificateEntry(cert), null);
                count = count + 1;
                System.out.println("Added the CA " + cert.getSubjectDN().getName() + " to the truststore under the alias " + alias + ".");
            }
            String password = getValue(TRUSTSTORE_PASSWORD_PROMPT, TRUSTSTORE_PASSWORD_PROPERTY);
            FileOutputStream fos = new FileOutputStream(f);
            keyStore.store(fos, password.toCharArray());
            fos.close();

            serviceProperties.setProperty(TRUSTSTORE_LOCATION_PROPERTY, TRUSTSTORE_LOCATION_PROPERTY_VALUE);
            serviceProperties.setProperty(TRUSTSTORE_PASSWORD_PROPERTY, password);

            System.out.println("Truststore created at " + f.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void buildTrustList() {
        certificates = new ArrayList<X509Certificate>();
        int count = 0;
        boolean requestAnother = true;
        String property = TRUSTED_CA_PROPERTY + count;
        while (requestAnother) {

            String certLocation = getValue(TRUSTED_CA_PROMPT, property);
            try {
                X509Certificate cert = CertUtil.loadCertificate(new File(certLocation));
                System.out.println("Successfully loaded the certificate " + cert.getSubjectDN().getName() + " from the file " + certLocation + ".");
                this.certificates.add(cert);
                count = count + 1;
                property = TRUSTED_CA_PROPERTY + count;

                if (getProperties().getProperty(property) == null) {
                    requestAnother = getBooleanValue("Would you like to add another trust root certificate authority (true|false)?", "foo");
                }
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
    }

}


text:
require 'logger'
require 'rom/gateway'
require 'rfm'
require 'charlatan'
require 'yaml'

class Rfm::Layout
  # Strip out unnecessary output in Rfm::Layout#inspect
  def inspect
    "#<#{self.class.name}:#{self.object_id} @name=#{self.name} @database=#{database.name} @server=#{server.host_name} @loaded=#{@loaded}>"
  end
end

module ROM
  module FMP

    class Gateway < ROM::Gateway
      attr_reader :datasets, :database

      def initialize(*options)
        @database = Rfm.database(options[0].to_h.merge(FMRESULTSET_TEMPLATE).to_h)
        @datasets = Hash.new
      end

      def dataset(name)
        datasets[name.to_s] ||= Dataset.new(@database[name.to_s])
      end

      # This is required per lint specs
      alias_method :[], :dataset

      def dataset?(name)
        datasets.key?(name.to_s)
      end
    end

    class Dataset
      include ::Rfm::Scope

      DEFAULT_REQUEST_OPTIONS = {}

      # Dataset instance expects to hold Array of data in @data,
      # but it will also hold a FM Layout instance.
      # If any call to Dataset instance returns Array instance,
      # it will be wrapped in a new Dataset instance.
      include Charlatan.new(:data, kind: Array)
      attr_reader :layout, :data, :queries

      # Store layout, data, query in new dataset.
      def initialize(_layout, _data=[], _queries=[])
        @layout = _layout
        @queries = _queries
        #puts "DATASET NEW queries:#{@queries}"
        super(_data)
      end

      # Creates new dataset with current args and resultset. Not lazy.
      # This may not be how rom or sql uses 'where'. Find out more.
      def where(*args)
        #self.class.new(layout, layout.find(*args), args)
        get_results(:find, args)
      end

      # Creates new dataset with existing data & queries, plus new query
      def find(*args)
        #self.class.new(layout, data, (queries.dup << args))
        wrap_data(data, (queries.dup << args))
      end

      def any(options={})
        wrap_data(layout.any(options))
      end

      def all(options={})
        wrap_data(layout.all(DEFAULT_REQUEST_OPTIONS.merge(options)))
      end

      def count(*args)
        compiled_query = compile_query
        compiled_query ? layout.count(*compiled_query) : layout.total_count
      end

      def create(args={})
        get_results(:create, [args]) unless args.empty?
      end

      def update(record_id, args={})
        get_results(:edit, [record_id, args]) unless args.empty?
      end

      def delete(record_id)
        get_results(:delete, record_id)
      end

      # Triggers actual fm action.
      def to_a
        (data.nil? || data.empty?) ? call.data.to_a : data.to_a
      end

      # Triggers actual fm action.
      def each
        # passes block - if any - to upstream each.
        to_a.each(&Proc.new)
      end

      # Combines all queries, sends to FM, returns result in new dataset.
      def call
        compiled_query = compile_query
        wrap_data(compiled_query ? layout.find(*compiled_query) : layout.all(DEFAULT_REQUEST_OPTIONS))
      end

      # Mixes chained queries together into single query.
      # Now works with multiple-request queries (using new rfm scope feature).
      # Other ways: consider mixing multi-request queries with intersection: (result1 & result2),
      # or with the new scope feature: query1(scope:query2(scope:query3))
      def compile_query
        #puts "DATASET COMPILE self #{self}"
        #puts "DATASET COMPILE queries #{queries}"

        # Old way: works but doesn't handle fmp compound queries.
        #query.each_with_object([{},{}]){|x,o| o[0].merge!(x[0] || {}); o[1].merge!(x[1] || {})}

        # New way: handles compound queries. Reqires ginjo-rfm 3.0.11.
        return unless queries  # This should help introspecting dataset that results from record deletion. TODO: test this.
        queries.inject {|new_query,scope| apply_scope(new_query, scope)} ##puts "SCOPE INJECTION scope:#{scope} new_query:#{new_query}";
      end

      # Returns new dataset containing, data, layout, query.
      def wrap_data(_data=data, _queries=queries, _layout=layout)
        self.class.new(_layout, _data, _queries)
      end

      # Send method & query to layout, and wrap results in new dataset.
      def get_results(_method, query=queries, _layout=layout)
        wrap_data(_layout.send(_method, *query), query, _layout)
      end

    end # Dataset

    class Relation < ROM::Relation
      # we must configure adapter identifier here
      adapter :fmp

      forward :find, :all, :count, :create, :update, :delete
    end

  end # FMP
end # ROM


text:
/*!
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * @constructor
 */
function menu() {
    this.param = {};
}

menu.prototype =
{
    resetTimer: null,

    adaptSubMenuHeight: function() {
        var subNavHeight = $('.sfHover > ul').outerHeight();
        $('.nav_sep').height(subNavHeight);
    },

    overMainLI: function () {
        var $this = $(this);
        $this.siblings().removeClass('sfHover');
        $this.addClass('sfHover');
        menu.prototype.adaptSubMenuHeight();
        clearTimeout(menu.prototype.resetTimer);
    },

    outMainLI: function () {
        clearTimeout(menu.prototype.resetTimer);
        menu.prototype.resetTimer = setTimeout(function() {
            $('.Menu-tabList > .sfHover', this.menuNode).removeClass('sfHover');
            $('.Menu-tabList > .sfActive', this.menuNode).addClass('sfHover');
            menu.prototype.adaptSubMenuHeight();
        }, 2000);
    },

    onItemClick: function (e) {
        if (e.which === 2) {
            return;
        }
        $('.Menu--dashboard').trigger('piwikSwitchPage', this);
        broadcast.propagateAjax( $(this).attr('href').substr(1) );
        return false;
    },

    init: function () {
        this.menuNode = $('.Menu--dashboard');

        this.menuNode.find("li:has(ul),li#Searchmenu").hover(this.overMainLI, this.outMainLI);
        this.menuNode.find("li:has(ul),li#Searchmenu").focusin(this.overMainLI);

        // add id to all li menu to support menu identification.
        // for all sub menu we want to have a unique id based on their module and action
        // for main menu we want to add just the module as its id.
        this.menuNode.find('li').each(function () {
            var link = $(this).find('a');
            if (!link) {
                return;
            }
            var href = link.attr('href');
            if (!href) {
                return;
            }
            var url = href.substr(1);

            var module = broadcast.getValueFromUrl('module', url);
            var action = broadcast.getValueFromUrl('action', url);

            var moduleId = broadcast.getValueFromUrl("idGoal", url) || broadcast.getValueFromUrl("idDashboard", url);
            var main_menu = $(this).parent().hasClass('Menu-tabList') ? true : false;
            if (main_menu) {
                $(this).attr({id: module});
            }
            // if there's a idGoal or idDashboard, use this in the ID
            else if (moduleId != '') {
                $(this).attr({id: module + '_' + action + '_' + moduleId});
            }
            else {
                $(this).attr({id: module + '_' + action});
            }
        });

        this.menuNode.find('a.menuItem').click(this.onItemClick);

        menu.prototype.adaptSubMenuHeight();
    },

    activateMenu: function (module, action, id) {
        this.menuNode.find('li').removeClass('sfHover').removeClass('sfActive');
        var $li = this.getSubmenuID(module, id, action);
        var mainLi = $("#" + module);
        if (!mainLi.length) {
            mainLi = $li.parents('li');
        }

        mainLi.addClass('sfActive').addClass('sfHover');

        $li.addClass('sfHover');
    },

    // getting the right li is a little tricky since goals uses idGoal, and overview is index.
    getSubmenuID: function (module, id, action) {
        var $li = '';
        // So, if module is Goals, id is present, and action is not Index, must be one of the goals
        if ((module == 'Goals' || module == 'Ecommerce') && id != '' && (action != 'index')) {
            $li = $("#" + module + "_" + action + "_" + id);
            // if module is Dashboard and id is present, must be one of the dashboards
        } else if (module == 'Dashboard') {
            if (!id) id = 1;
            $li = $("#" + module + "_" + action + "_" + id);
        } else {
            $li = $("#" + module + "_" + action);
        }
        return $li;
    },

    loadFirstSection: function () {
        if (broadcast.isHashExists() == false) {
            $('li:first a:first', this.menuNode).click().addClass('sfHover').addClass('sfActive');
        }
    }
};


text:
title: "Go bindings for Soletta mainloop"
tags:
    - go
    - cgo
    - bindings
    - Soletta
    - GSoC2016
---

Once the structure of the go bindings package has been [established][1], it is time to start and write some actual code.

One of the first Soletta library components that needs to be tackled is the [Soletta mainloop][2]. Soletta enables asynchronous programming and it does so by
using a mainloop mechanism. This is similar to NodeJS' event loop. Basically it keeps an internal queue of events which is continously polled. The events can be generated internally, injected by other Soletta components (e.g. flow) or even by applications using Soletta (through the API).

The mainloop API is quite minimal. It allows users to start/stop Soletta, register idle/timeout callbacks, or even change the default mainloop implementation or provide additional event sources.

### Main functionality ###

The main functionality is provided by:

```c
sol_init(...)
sol_run(...)
sol_quit(...)
sol_shutdown(...)
```

Using cgo, the process of wrapping them is pretty straightforward, since these functions are directly exposed by Soletta. Just an example for ```sol_init```:

```go
//#include "soletta.h"
import "C"

func Init() bool {
    if C.sol_init() == 0 {
        return true
    }
    return false
}
```

```Init``` is just a wrapper, calling ```C.sol_init()```.

## Idle and Timeout ##

Binding ```sol_idle_add```, ```sol_idle_del```, ```sol_timeout_add```, ```sol_timeout_del``` is a bit more complicated, since it involves passing custom Go callbacks written by users
to the C library. I covered the details of the process [here][3].

As a remark, ```sol_timeout_add``` returns a handle, which can be passed to ```sol_timeout_del``` for removing the idler (same applies for sol_idle). I thought of 2 ways of achieving this in Go.
The first way is using something like this for wrapping ```sol_timeout_add```:

```go
func AddTimeout(cb *TimeoutCallback, data interface{}, timeout int)
```

The idea is that for deleting a previously registered timeout, the user would call ```DelTimeout``` with the same callback passed to ```AddTimeout```. This is doable, however it makes things quite complicated. On the one hand, the Go library will have to keep an internal mapping between user Go timeout callbacks and C timeout handles (the implementation of this may be more complex then you might think because of cgo). On the other hand, since parameters in Go are passed by value, the user would have to pass the pointer of the callback, otherwise the cases where the users registers the same Go callback twice can't be handled properly (same function registering still issues 2 different handles, but we can't map them to a single value). Now, passing pointers to functions in Go is pretty ugly (the way I managed to do it was by storing the function value into a variable and passing the address of the variable, since simply taking the address of a function resulted in syntax error), so I
chosed the second way.

The other way is the C way, which I wanted to avoid, but keeped in the end for simplicity. ```AddTimeout``` just returns the ```C.sol_timeout_add``` handle to the user, who can use the handle to delete the timeout at a later point. The handle is opaque to the user. A Go sample for this:

```go
func AddTimeout(cb TimeoutCallback, data interface{}, timeout int) interface{}

func RemoveTimeout(handle interface{}) {
    C.sol_timeout_del(handle.(*C.struct_sol_timeout))
}
```

## Mainloop source ##

Wrapping ```sol_mainloop_add_source``` is a similar case to adding timeouts and idlers, but on sterois. This time it is necessary to pass an entire struct with callbacks. I chose an interface for Go:

```go
type MainloopSource interface {
    Check(interface{}) bool
    Dispatch(interface{})
    Dispose(interface{})
    Prepare(interface{}) bool
}

func AddSource(source MainloopSource, data interface{}) interface{}
```

The user can pass any struct (or type) that implements this interface. ```AddSource``` will call into a C helper routine that will create a ```struct sol_mainloop_source_type *``` source with all
the necessary callback fields and call the Soletta ```sol_mainloop_add_source```.

The source removal mechanism is similar to timeout/idler, the user receives an opaque handler. However, the C helper routine does some memory allocations when creating the source, which need to be freed. To do so, I created a mapping between source handles and their corresponding allocations, which is consulted on ```DelSource```. The mapping also stores the data parameter passed to ```AddSource```, so it could be easily retrieved by ```GetSourceData```.

## Changing mainloop default implementation ##

This one is tough. I don't even know if wrapping it even makes sense, I have to put more thought on this and consult with my GSoC mentor.

Aside this, there are also some other things left to finish the bindings for Soletta mainloop, including writing documentation, examples, handling SOL_MAINLOOP_SOURCE_TYPE_API_VERSION, mainloop source ```get_next_timeout```.

The full code can be found on [github][4].

[1]: http://blog.digitalkid.me/go-package-for-soletta/
[2]: http://solettaproject.github.io/docs/c-api/group__Mainloop.html
[3]: http://blog.digitalkid.me/pass-go-callbacks-to-c/
[4]: https://github.com/kaspersky/go-soletta


text:
package network::fiberstore::snmp::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    $self->{modes} = {
        'cpu'             => 'network::fiberstore::snmp::mode::cpu',
        'hardware'        => 'network::fiberstore::snmp::mode::hardware',
        'interfaces'      => 'snmp_standard::mode::interfaces',
        'list-interfaces' => 'snmp_standard::mode::listinterfaces',
        'memory'          => 'network::fiberstore::snmp::mode::memory'
    };

    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check FiberStore in SNMP.

=cut


text:
Blockly.Blocks['ellipse'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("ellipse");
    this.appendValueInput("x")
        .setCheck("Number")
        .appendField("x");
    this.appendValueInput("y")
        .setCheck("Number")
        .appendField("y");
    this.appendValueInput("width")
        .setCheck("Number")
        .appendField("w");
    this.appendValueInput("height")
        .setCheck("Number")
        .appendField("h");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(165);
    this.setTooltip('Draws an ellipse to the screen. ');
    this.setHelpUrl('https://p5js.org/reference/#/p5/ellipse');
  }
};


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.
-->
<metainfo>
    <user>mapred</user>
    <comment>Non-relational distributed database and centralized service for configuration management & synchronization</comment>
    <version>0.94.6.1.3.0.0</version>

    <components>
        <component>
            <name>HBASE_MASTER</name>
            <category>MASTER</category>
        </component>

        <component>
            <name>HBASE_REGIONSERVER</name>
            <category>SLAVE</category>
        </component>

        <component>
            <name>HBASE_CLIENT</name>
            <category>CLIENT</category>
        </component>
    </components>

</metainfo>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Orleans.Analyzers {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Orleans.Analyzers.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The member "{0}" is marked as {1} and therefore cannot be serialized..
        /// </summary>
        internal static string AbstractOrStaticMembersCannotBeSerializedMessageFormat {
            get {
                return ResourceManager.GetString("AbstractOrStaticMembersCannotBeSerializedMessageFormat", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Members which are static or abstract cannot be serialized..
        /// </summary>
        internal static string AbstractOrStaticMembersCannotBeSerializedTitle {
            get {
                return ResourceManager.GetString("AbstractOrStaticMembersCannotBeSerializedTitle", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add the [GenerateSerializer] attribute..
        /// </summary>
        internal static string AddGenerateSerializerAttributeDescription {
            get {
                return ResourceManager.GetString("AddGenerateSerializerAttributeDescription", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add the [GenerateSerializer] attribute..
        /// </summary>
        internal static string AddGenerateSerializerAttributeMessageFormat {
            get {
                return ResourceManager.GetString("AddGenerateSerializerAttributeMessageFormat", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add the [GenerateSerializer] attribute..
        /// </summary>
        internal static string AddGenerateSerializerAttributesTitle {
            get {
                return ResourceManager.GetString("AddGenerateSerializerAttributesTitle", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add attributes to properties and fields to direct serializer generation..
        /// </summary>
        internal static string AddSerializationAttributesDescription {
            get {
                return ResourceManager.GetString("AddSerializationAttributesDescription", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add missing serialization attributes..
        /// </summary>
        internal static string AddSerializationAttributesMessageFormat {
            get {
                return ResourceManager.GetString("AddSerializationAttributesMessageFormat", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Add missing serialization attributes..
        /// </summary>
        internal static string AddSerializationAttributesTitle {
            get {
                return ResourceManager.GetString("AddSerializationAttributesTitle", resourceCulture);
            }
        }
    }
}