text:
/**
 * Controls' room
 */
package graphics.rooms.controlsMenu;

import graphics.effects.Button;
import graphics.effects.ControlButton;
import graphics.effects.PintableButton;
import graphics.rooms.Room;

import java.awt.Graphics;
import java.awt.event.KeyEvent;

import kuusisto.tinysound.Sound;
import logic.Input.KEY;
import logic.Sprite;
import logic.StatesMachine;
import logic.StatesMachine.STATE;
import sound.MusicRepository;

/**
 * @author Patricia Lazaro Tello (554309)
 * @author Jaime Ruiz-Borau Vizarraga (546751)
 */
public class Controls extends Room {

	private static final int PADDING_BORDER = 25;
	private static final int INTERBUTTON_BORDER = 25;

	public Button[][] menuButtons;
	public boolean selectingKey = false;
	private final int ROWS = 8;
	private final int COLUMNS = 2;
	private int selected;
	private int column;

	/**
	 * @param w
	 *            width
	 * @param h
	 *            height
	 * @param n
	 *            name
	 */
	public Controls(int w, int h, String n) {
		super(w, h, n);
	}

	@Override
	public void load() {
		ControlsRepository.load();

		this.background = ControlsRepository.background;

		createButtons();
		selected = 0;
		column = 0;
		select(0);

		setMusic(MusicRepository.menu, true);
	}

	/**
	 * Create some buttons
	 */
	private void createButtons() {
		menuButtons = new Button[ROWS][COLUMNS];

		// variables
		int _width = width / 2;
		int x = _width / 2;
		int x2 = x + _width / 2;
		int y = PADDING_BORDER;
		int i = 0;

		// UP button
		Sprite sprite = ControlsRepository.up;
		createOneButton(x, y, sprite, KEY.UP, i, 0, x2, i, 1, getKeyText(KEY.UP));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// DOWN button
		sprite = ControlsRepository.down;
		createOneButton(x, y, sprite, KEY.DOWN, i, 0, x2, i, 1, getKeyText(KEY.DOWN));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// LEFT button
		sprite = ControlsRepository.left;
		createOneButton(x, y, sprite, KEY.LEFT, i, 0, x2, i, 1, getKeyText(KEY.LEFT));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// RIGHT button
		sprite = ControlsRepository.right;
		createOneButton(x, y, sprite, KEY.RIGHT, i, 0, x2, i, 1, getKeyText(KEY.RIGHT));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// BOMB button
		sprite = ControlsRepository.bomb;
		createOneButton(x, y, sprite, KEY.BOMB, i, 0, x2, i, 1, getKeyText(KEY.BOMB));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// PAUSE button
		sprite = ControlsRepository.pause;
		createOneButton(x, y, sprite, KEY.PAUSE, i, 0, x2, i, 1, getKeyText(KEY.PAUSE));

		y = y + sprite.getHeight() + INTERBUTTON_BORDER;
		i++;

		// CONFIRM button
		sprite = ControlsRepository.confirm;
		createOneButton(x, y, sprite, KEY.CONFIRM, i, 0, x2, i, 1, getKeyText(KEY.CONFIRM));

		Sprite next = ControlsRepository.continueButton;
		y = this.height - PADDING_BORDER - next.getHeight() / 2;
		i++;

		menuButtons[i][0] = new Button(width / 2, y, this, next, new Runnable() {

			@Override
			public void run() {
				StatesMachine.goToRoom(STATE.MAIN_MENU, false);
			}
		});

		menuButtons[7][1] = menuButtons[7][0];
		addObjeto(menuButtons[7][0]);
	}

	/**
	 * @param x
	 *            x coordinate
	 * @param y
	 *            y coordinate
	 * @param sprite
	 *            sprite
	 * @param key
	 *            key attached to the button
	 * @param i1
	 *            first row index
	 * @param j1
	 *            first column index
	 * @param x2
	 *            second x coordinate
	 * @param i2
	 *            second row index
	 * @param j2
	 *            second column index
	 * @param text
	 *            text to paint
	 */
	private void createOneButton(int x, int y, Sprite sprite, KEY key, int i1, int j1, int x2, int i2, int j2,
			String text) {
		menuButtons[i1][j1] = new ControlButton(x, y + sprite.getHeight() / 2, this, sprite, key, new Runnable() {

			@Override
			public void run() {
				// Set new text to pintable
				ControlButton cb = ((ControlButton) menuButtons[i1][j1]);
				cb.setPintableText("...");
				cb.selecting = true;
			}
		});
		addObjeto(menuButtons[i1][j1]);

		menuButtons[i2][j2] = new PintableButton(x2, y + sprite.getHeight() / 2 - sprite.getCenterY(), this, text);
		addObjeto(menuButtons[i2][j2]);
		((ControlButton) menuButtons[i1][j1]).setPintable((PintableButton) menuButtons[i2][j2]);
	}

	/**
	 * Selects a button
	 *
	 * @param no
	 *            number of the selected button
	 */
	private void select(int no) {
		unselect();
		selected = no;
		menuButtons[no][column].select();
	}

	/**
	 * Deselects a button
	 */
	private void unselect() {
		for (int i = 0; i < menuButtons.length; i++) {
			for (int j = 0; j < menuButtons[i].length; j++) {
				if (menuButtons[i][j] != null) {
					menuButtons[i][j].unselect();
				}
			}
		}
	}

	/**
	 * Next button
	 */
	private void next() {
		int no = (selected + 1) % menuButtons.length;
		select(no);
	}

	/**
	 * Previous button
	 */
	private void previous() {
		int no = ((selected - 1) % menuButtons.length + menuButtons.length) % menuButtons.length;
		select(no);
	}

	/**
	 * Confirm the button
	 */
	private void confirm() {
		menuButtons[selected][column].confirm();
	}

	@Override
	public void drawBackground(Graphics g) {
		if (!loadComplete()) {
			return;
		}
		g.clearRect(0, 0, width, height);
		if (background != null) {
			g.drawImage(background.getSubsprites()[0], 0, 0, null);
		}
	}

	@Override
	public void step(KEY key, KEY direction) {
		super.step(key, direction);
		if (!loadComplete()) {
			return;
		}
		Sound sel = MusicRepository.select;
		if (!selectingKey) {
			switch (key) {
			case DOWN:
				next();
				sel.play();
				break;
			case UP:
				previous();
				sel.play();
				break;
			case RIGHT:
				break;
			case LEFT:
				break;
			case CONFIRM:
				confirm();
				break;
			default:
				break;
			}
		}
	}

	/**
	 * Get text from a key
	 *
	 * @param key
	 *            key to get the text from
	 * @return text attached to the key
	 */
	private String getKeyText(KEY key) {
		int code = StatesMachine.input.mapper.getCodeKey(key);
		String returned = ControlButton.defaultTextes(code);
		if (returned == null) {
			returned = KeyEvent.getKeyText(code);
		}
		return returned;
	}
}


text:
var rtp;

/**
 * Module dependecies
 */
var dgram = require('dgram'),
	ee = require('events').EventEmitter,
	net = require('net'),
	r = require('./readers.js'),
	xml = require('xml2js'),
	fs = require('fs'),
	udpPort = 41234,
	tempBuffer = null;

rtp = new ee();

var config = {
		port: 22222,
		host: '212.235.190.228',
		version: '1.10',
		byteOrder: 'BE',
		connected: false
};

rtp.parameters = null;

var	udp = dgram.createSocket('udp4', function(err, data){
		rtp.log('Dgram Socket created.', err, data);
	});

var tcp = new net.Socket();
tcp.setNoDelay(true);

/**
 * Config set function
 *
 * @param par config.parameter
 * @param value
 */
rtp.set = function(par, val){
	config[par] = val;
};

rtp.get = function(par){
	return config[par];
};

/**
 * Emit log event
 *
 * @author Andraz <andraz@easistent.com>
 *
 * @return {void}
 */
rtp.log = function () {
    var args = ['log'];
    for(var ii = 0; ii < arguments.length; ii++) {
        args.push(arguments[ii]);
    }

    rtp.emit.apply(rtp, args);
};

/**
 * Auto discover
 *
 * @param
 * @return
 */

rtp.discover = function(cb){
	var packet = new Buffer(10);
	packet.writeInt32LE(10, 0);
	packet.writeInt32LE(7, 4);
	packet.writeUInt16BE(udpPort, 8);
	udp.send(packet, 0, 10, 22226, '127.0.0.1', function(err, bytes){
		rtp.log('UDP Packet Sent', err, bytes);
	});
};

/**
 * Connect to QTM via TCP
 *
 * @param _p User defined port
 * @param _h User defined host
 * @return
 */

rtp.connect = function (_p, _h) {

	if (config.connected) {
		return;
	}

    rtp.log('RTP Connect');

	var port = _p || config.port;
		port++; // Default for LE
	var host = _h || config.host;

	// Set LE or BE
	if(config.byteOrder == 'BE') {
		port++;
    }

	tcp.connect(port, host, function () {
		rtp.log('RTP Connected');
	});
};

/**
 * Disconnect from QTM TCP
 *
 * @author Andraz <andraz@easistent.com>
 *
 * @return {void}
 */
rtp.disconnect = function () {
    rtp.log('RTP Disconnect');
    tcp.end();
    //rtp.emit('disconnected');
};

/**
 * Send Version Command
 *
 * @param _v String
 */

rtp.version = function (_v){
	var version = _v || config.version;
	rtp.command('Version ' + version);
};

/**
 * Send GetCurrentFrame Command
 *
 * @param _o String User defined options
 */

rtp.getCurrentFrame = function (_o){
	var options = _o || '3D';
	rtp.command('GetCurrentFrame ' + options);
};

/**
 * Send GetParameters Command
 *
 * @param _o String User defined options
 */
rtp.getParameters = function (_o){
	var options = _o || 'All';
	rtp.command('GetParameters ' + options);
};

/**
 * Send StreamFrames Command
 *
 * @param _o String User Defined Options
 */
rtp.streamFrames = function (_o){
	var options = _o || 'Frequency:50 3D';
	rtp.command('StreamFrames ' + options);
};

/**
 * Send command
 *
 * @param command String
 * @return
 */

rtp.command = function (command){
	var l = command.length + 8;
	var packet = new Buffer(l);
	packet.writeInt32BE(l, 0);
	packet.writeInt32BE(1, 4); // Command type = 1
	packet.write(command, 8, command.length, 'ASCII');
	tcp.write(packet, 'ASCII', function(){
		rtp.log('Command:    ', command);
	});
};

udp.on('message', function(msg, rinfo){
	var type = msg.readInt32LE(4);
	// Auto discover package
	if(type == 1){
		var port = msg.readUInt16BE(msg.length - 2);
		rtp.log('QTM discoverd on port ' + port);
		// Port -> Base port
		rtp.emit('discover', port);
	}
});

udp.on('error', function(err){
	rtp.log('UDP Error', err);
});

udp.bind(udpPort);

/**
 * Receive Package
 */
tcp.on('data', function(data){
	var self = this;
	var len = data.readInt32BE(0);
	var type = data.readInt32BE(4);
    var out;

	// Check Packet Size
	// TODO: Preveri tudi če je paket večji od len
	if(len != data.length){
		//rtp.log('VELIKOSTI SE NE UJEMAJO!!!!', type, len, data.length);
		if(tempBuffer === null){
			tempBuffer = data;
			return;
		}else{
			var _buf = new Buffer(tempBuffer.length + data.length);
			tempBuffer.copy(_buf);
			data.copy(_buf, tempBuffer.length);
			data = _buf;
			tempBuffer = null;
			// One more check
			len = data.readInt32BE(0);
			if(len != data.length){
				tempBuffer = data;
				return;
			}
			type = data.readInt32BE(4);
		}
	}

	// Error
	if (type === 0) {
		console.log('ERROR!!');
	// Command
	} else if (type === 1) {
		var res = data.toString('ASCII', 8, len-1);
		//res = res.slice(0, res.length-1);

		if (res === 'QTM RT Interface connected') {
			config.connected = true;
			rtp.emit('connect');
		} else if (res === 'Connection refused. Max number of clients reached') {
			rtp.emit('disconnected', res);
		} else {
			rtp.emit('command', res);
			rtp.log('Command Res:', res);

		}
	// XML Packet
	} else if (type === 2) {

		out = data.toString('ASCII', 8, len-1);
        var parser;

        //Write to file
        fs.writeFile('parameters.xml', out, 'ASCII', function (err) {
            if (err) {
                throw err;
            }
            rtp.log('XML\'s saved!');
            //rtp.emit('parameters');
        });

		parser = new xml.Parser(xml.defaults["0.1"]);
		parser.parseString(out, function (err, result) {
			rtp.log('XML\'s parsed!');
			if (err) throw err;
            rtp.parameters = result;
            rtp.emit('parameters', result);
        });
	// Data Packet
	} else if (type === 3) {
		out = r.readDataPacket(data);
		rtp.emit('data', out);
	// No More Data
	} else if (type === 4) {
		rtp.log('No More Data');
	// Events
	} else if (type === 6) {
		/*
		 * TODO: Če je klient stream-a ob RT Start automatsko začni stream
		 */
		out = r.readEventPacket(data);
		var events = [
            'Not Exist 0',
            'Connected',
            'Connection Closed',
            'Capture Started',
            'Capture Stopped',
            'Not Used',
            'Calibration Started',
            'Calibration Stopped',
            'RT From File Started',
            'RT From File Stopped',
            'Waiting for Trigger',
            'Camera Settings Changed',
            'QTM Shutting Down',
            'Capture Saved'
        ];
		rtp.emit('event', out);
		rtp.log('Event:', events[out]);
	} else {
		rtp.log('Unknown Response Type', type);
	}
});

tcp.on('error', function(err){
	rtp.log('TCP Error', err);
});

tcp.on('close', function(had_error) {
    rtp.log('TCP Close', had_error);
    rtp.emit('disconnected');
	//rtp.emit('connect', 'Problem connecting to QTM');
});

tcp.on('end', function(){
    rtp.log('TCP End');
    rtp.emit('disconnected');
});

// custom events listeners on RTP
rtp.on('disconnected', function () {
    if (config.connected === false) {
        return;
    }

    config.connected = false;
    rtp.log('RTP Disconnected');
});

module.exports = rtp;

redpajama_set_name: RedPajamaGithub


text:
import { join } from 'path';
import { ScriptTarget, ModuleKind, NewLineKind } from 'typescript';
import { uglifyJsFile } from './minify-sources';
import { createRollupBundle } from './rollup-helpers';
import { remapSourcemap } from './sourcemap-remap';
import { transpileFile } from './typescript-transpile';
import { buildConfig } from './build-config';

/** Directory where all bundles will be created in. */
const bundlesDir = join(buildConfig.outputDir, 'bundles');

/** Builds bundles for the primary entry-point w/ given entry file */
export async function buildPrimaryEntryPointBundles(entryFile: string, packageName: string) {
	return createBundlesForEntryPoint({
		entryFile,
		moduleName: `ng42.${packageName}`,
		fesm2015Dest: join(bundlesDir, `${packageName}.js`),
		fesm2014Dest: join(bundlesDir, `${packageName}.es5.js`),
		umdDest: join(bundlesDir, `${packageName}.umd.js`),
		umdMinDest: join(bundlesDir, `${packageName}.umd.min.js`),
	});
}

/** Builds bundles for a single secondary entry-point w/ given entry file */
export async function buildSecondaryEntryPointBundles(entryFile: string, packageName: string,
	entryPointName: string) {
	return createBundlesForEntryPoint({
		entryFile,
		moduleName: `ng42.${packageName}.${entryPointName}`,
		fesm2015Dest: join(bundlesDir, `${packageName}`, `${entryPointName}.js`),
		fesm2014Dest: join(bundlesDir, `${packageName}`, `${entryPointName}.es5.js`),
		umdDest: join(bundlesDir, `${packageName}-${entryPointName}.umd.js`),
		umdMinDest: join(bundlesDir, `${packageName}-${entryPointName}.umd.min.js`),
	});
}

/**
 * Creates the ES5, ES2015, and UMD bundles for the specified entry-point.
 * @param config Configuration that specifies the entry-point, module name, and output
 *     bundle paths.
 */
async function createBundlesForEntryPoint(config: BundlesConfig) {
	// Build FESM-2015 bundle file.
	await createRollupBundle({
		moduleName: config.moduleName,
		entry: config.entryFile,
		dest: config.fesm2015Dest,
		format: 'es',
	});

	await remapSourcemap(config.fesm2015Dest);

	// Downlevel FESM-2015 file to ES5.
	transpileFile(config.fesm2015Dest, config.fesm2014Dest, {
		importHelpers: true,
		target: ScriptTarget.ES5,
		module: ModuleKind.ES2015,
		allowJs: true,
		newLine: NewLineKind.LineFeed
	});

	await remapSourcemap(config.fesm2014Dest);

	// Create UMD bundle of FESM-2014 output.
	await createRollupBundle({
		moduleName: config.moduleName,
		entry: config.fesm2014Dest,
		dest: config.umdDest,
		format: 'umd'
	});

	await remapSourcemap(config.umdDest);

	// Create a minified UMD bundle using UglifyJS
	uglifyJsFile(config.umdDest, config.umdMinDest);

	await remapSourcemap(config.umdMinDest);
}

/** Configuration for creating library bundles. */
interface BundlesConfig {
	entryFile: string;
	moduleName: string;
	fesm2015Dest: string;
	fesm2014Dest: string;
	umdDest: string;
	umdMinDest: string;
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Storage.Models;

namespace Azure.ResourceManager.Storage
{
    /// <summary> The StorageAccounts service client. </summary>
    public partial class StorageAccountsOperations
    {
        private readonly ClientDiagnostics _clientDiagnostics;
        private readonly HttpPipeline _pipeline;
        internal StorageAccountsRestOperations RestClient { get; }
        /// <summary> Initializes a new instance of StorageAccountsOperations for mocking. </summary>
        protected StorageAccountsOperations()
        {
        }
        /// <summary> Initializes a new instance of StorageAccountsOperations. </summary>
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="subscriptionId"> The ID of the target subscription. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        internal StorageAccountsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2019-06-01")
        {
            RestClient = new StorageAccountsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint, apiVersion);
            _clientDiagnostics = clientDiagnostics;
            _pipeline = pipeline;
        }

        /// <summary> Checks that the storage account name is valid and is not already in use. </summary>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<CheckNameAvailabilityResult>> CheckNameAvailabilityAsync(StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.CheckNameAvailability");
            scope.Start();
            try
            {
                return await RestClient.CheckNameAvailabilityAsync(accountName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Checks that the storage account name is valid and is not already in use. </summary>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<CheckNameAvailabilityResult> CheckNameAvailability(StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.CheckNameAvailability");
            scope.Start();
            try
            {
                return RestClient.CheckNameAvailability(accountName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Deletes a storage account in Microsoft Azure. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> DeleteAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.Delete");
            scope.Start();
            try
            {
                return await RestClient.DeleteAsync(resourceGroupName, accountName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Deletes a storage account in Microsoft Azure. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response Delete(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.Delete");
            scope.Start();
            try
            {
                return RestClient.Delete(resourceGroupName, accountName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="expand"> May be used to expand the properties within account's properties. By default, data is not included when fetching properties. Currently we only support geoReplicationStats and blobRestoreStatus. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<StorageAccount>> GetPropertiesAsync(string resourceGroupName, string accountName, StorageAccountExpand? expand = null, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.GetProperties");
            scope.Start();
            try
            {
                return await RestClient.GetPropertiesAsync(resourceGroupName, accountName, expand, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="expand"> May be used to expand the properties within account's properties. By default, data is not included when fetching properties. Currently we only support geoReplicationStats and blobRestoreStatus. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<StorageAccount> GetProperties(string resourceGroupName, string accountName, StorageAccountExpand? expand = null, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.GetProperties");
            scope.Start();
            try
            {
                return RestClient.GetProperties(resourceGroupName, accountName, expand, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> The update operation can be used to update the SKU, encryption, access tier, or tags for a storage account. It can also be used to map the account to a custom domain. Only one custom domain is supported per storage account; the replacement/change of custom domain is not supported. In order to replace an old custom domain, the old value must be cleared/unregistered before a new value can be set. The update of multiple properties is supported. This call does not change the storage keys for the account. If you want to change the storage account keys, use the regenerate keys operation. The location and name of the storage account cannot be changed after creation. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for the updated account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<StorageAccount>> UpdateAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.Update");
            scope.Start();
            try
            {
                return await RestClient.UpdateAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> The update operation can be used to update the SKU, encryption, access tier, or tags for a storage account. It can also be used to map the account to a custom domain. Only one custom domain is supported per storage account; the replacement/change of custom domain is not supported. In order to replace an old custom domain, the old value must be cleared/unregistered before a new value can be set. The update of multiple properties is supported. This call does not change the storage keys for the account. If you want to change the storage account keys, use the regenerate keys operation. The location and name of the storage account cannot be changed after creation. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for the updated account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<StorageAccount> Update(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.Update");
            scope.Start();
            try
            {
                return RestClient.Update(resourceGroupName, accountName, parameters, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<StorageAccountListKeysResult>> ListKeysAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListKeys");
            scope.Start();
            try
            {
                return await RestClient.ListKeysAsync(resourceGroupName, accountName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<StorageAccountListKeysResult> ListKeys(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListKeys");
            scope.Start();
            try
            {
                return RestClient.ListKeys(resourceGroupName, accountName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Regenerates one of the access keys or Kerberos keys for the specified storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="regenerateKey"> Specifies name of the key which should be regenerated -- key1, key2, kerb1, kerb2. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<StorageAccountListKeysResult>> RegenerateKeyAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.RegenerateKey");
            scope.Start();
            try
            {
                return await RestClient.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Regenerates one of the access keys or Kerberos keys for the specified storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="regenerateKey"> Specifies name of the key which should be regenerated -- key1, key2, kerb1, kerb2. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<StorageAccountListKeysResult> RegenerateKey(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.RegenerateKey");
            scope.Start();
            try
            {
                return RestClient.RegenerateKey(resourceGroupName, accountName, regenerateKey, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List SAS credentials of a storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide to list SAS credentials for the storage account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<ListAccountSasResponse>> ListAccountSASAsync(string resourceGroupName, string accountName, AccountSasParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListAccountSAS");
            scope.Start();
            try
            {
                return await RestClient.ListAccountSASAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List SAS credentials of a storage account. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide to list SAS credentials for the storage account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<ListAccountSasResponse> ListAccountSAS(string resourceGroupName, string accountName, AccountSasParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListAccountSAS");
            scope.Start();
            try
            {
                return RestClient.ListAccountSAS(resourceGroupName, accountName, parameters, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List service SAS credentials of a specific resource. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide to list service SAS credentials. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<ListServiceSasResponse>> ListServiceSASAsync(string resourceGroupName, string accountName, ServiceSasParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListServiceSAS");
            scope.Start();
            try
            {
                return await RestClient.ListServiceSASAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> List service SAS credentials of a specific resource. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide to list service SAS credentials. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<ListServiceSasResponse> ListServiceSAS(string resourceGroupName, string accountName, ServiceSasParameters parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListServiceSAS");
            scope.Start();
            try
            {
                return RestClient.ListServiceSAS(resourceGroupName, accountName, parameters, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Revoke user delegation keys. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> RevokeUserDelegationKeysAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.RevokeUserDelegationKeys");
            scope.Start();
            try
            {
                return await RestClient.RevokeUserDelegationKeysAsync(resourceGroupName, accountName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Revoke user delegation keys. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response RevokeUserDelegationKeys(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.RevokeUserDelegationKeys");
            scope.Start();
            try
            {
                return RestClient.RevokeUserDelegationKeys(resourceGroupName, accountName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Lists all the storage accounts available under the subscription. Note that storage keys are not returned; use the ListKeys operation for this. </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual AsyncPageable<StorageAccount> ListAsync(CancellationToken cancellationToken = default)
        {
            async Task<Page<StorageAccount>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.List");
                scope.Start();
                try
                {
                    var response = await RestClient.ListAsync(cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<StorageAccount>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.List");
                scope.Start();
                try
                {
                    var response = await RestClient.ListNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary> Lists all the storage accounts available under the subscription. Note that storage keys are not returned; use the ListKeys operation for this. </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Pageable<StorageAccount> List(CancellationToken cancellationToken = default)
        {
            Page<StorageAccount> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.List");
                scope.Start();
                try
                {
                    var response = RestClient.List(cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<StorageAccount> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.List");
                scope.Start();
                try
                {
                    var response = RestClient.ListNextPage(nextLink, cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary> Lists all the storage accounts available under the given resource group. Note that storage keys are not returned; use the ListKeys operation for this. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception>
        public virtual AsyncPageable<StorageAccount> ListByResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }

            async Task<Page<StorageAccount>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListByResourceGroup");
                scope.Start();
                try
                {
                    var response = await RestClient.ListByResourceGroupAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
        }

        /// <summary> Lists all the storage accounts available under the given resource group. Note that storage keys are not returned; use the ListKeys operation for this. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception>
        public virtual Pageable<StorageAccount> ListByResourceGroup(string resourceGroupName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }

            Page<StorageAccount> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.ListByResourceGroup");
                scope.Start();
                try
                {
                    var response = RestClient.ListByResourceGroup(resourceGroupName, cancellationToken);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
        }

        /// <summary> Asynchronously creates a new storage account with the specified parameters. If an account is already created and a subsequent create request is issued with different properties, the account properties will be updated. If an account is already created and a subsequent create or update request is issued with the exact same set of properties, the request will succeed. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for the created account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, or <paramref name="parameters"/> is null. </exception>
        public virtual async Task<StorageAccountsCreateOperation> StartCreateAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartCreate");
            scope.Start();
            try
            {
                var originalResponse = await RestClient.CreateAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false);
                return new StorageAccountsCreateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateRequest(resourceGroupName, accountName, parameters).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Asynchronously creates a new storage account with the specified parameters. If an account is already created and a subsequent create request is issued with different properties, the account properties will be updated. If an account is already created and a subsequent create or update request is issued with the exact same set of properties, the request will succeed. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for the created account. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, or <paramref name="parameters"/> is null. </exception>
        public virtual StorageAccountsCreateOperation StartCreate(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartCreate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.Create(resourceGroupName, accountName, parameters, cancellationToken);
                return new StorageAccountsCreateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateRequest(resourceGroupName, accountName, parameters).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Failover request can be triggered for a storage account in case of availability issues. The failover occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception>
        public virtual async Task<StorageAccountsFailoverOperation> StartFailoverAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartFailover");
            scope.Start();
            try
            {
                var originalResponse = await RestClient.FailoverAsync(resourceGroupName, accountName, cancellationToken).ConfigureAwait(false);
                return new StorageAccountsFailoverOperation(_clientDiagnostics, _pipeline, RestClient.CreateFailoverRequest(resourceGroupName, accountName).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Failover request can be triggered for a storage account in case of availability issues. The failover occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="accountName"/> is null. </exception>
        public virtual StorageAccountsFailoverOperation StartFailover(string resourceGroupName, string accountName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartFailover");
            scope.Start();
            try
            {
                var originalResponse = RestClient.Failover(resourceGroupName, accountName, cancellationToken);
                return new StorageAccountsFailoverOperation(_clientDiagnostics, _pipeline, RestClient.CreateFailoverRequest(resourceGroupName, accountName).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Restore blobs in the specified blob ranges. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for restore blob ranges. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, or <paramref name="parameters"/> is null. </exception>
        public virtual async Task<StorageAccountsRestoreBlobRangesOperation> StartRestoreBlobRangesAsync(string resourceGroupName, string accountName, BlobRestoreParameters parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartRestoreBlobRanges");
            scope.Start();
            try
            {
                var originalResponse = await RestClient.RestoreBlobRangesAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false);
                return new StorageAccountsRestoreBlobRangesOperation(_clientDiagnostics, _pipeline, RestClient.CreateRestoreBlobRangesRequest(resourceGroupName, accountName, parameters).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Restore blobs in the specified blob ranges. </summary>
        /// <param name="resourceGroupName"> The name of the resource group within the user's subscription. The name is case insensitive. </param>
        /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param>
        /// <param name="parameters"> The parameters to provide for restore blob ranges. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, or <paramref name="parameters"/> is null. </exception>
        public virtual StorageAccountsRestoreBlobRangesOperation StartRestoreBlobRanges(string resourceGroupName, string accountName, BlobRestoreParameters parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var scope = _clientDiagnostics.CreateScope("StorageAccountsOperations.StartRestoreBlobRanges");
            scope.Start();
            try
            {
                var originalResponse = RestClient.RestoreBlobRanges(resourceGroupName, accountName, parameters, cancellationToken);
                return new StorageAccountsRestoreBlobRangesOperation(_clientDiagnostics, _pipeline, RestClient.CreateRestoreBlobRangesRequest(resourceGroupName, accountName, parameters).Request, originalResponse);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
@interface PaintViewController : UIViewController {

}

@end


text:
//TODO uncomment and write more tests
/* Tests for myprojects.js for My Projects in Dashboard */
/*global describe, it, expect, example, before, after, beforeEach, afterEach, mocha, sinon*/
'use strict';
var assert = require('chai').assert;

var $ = require('jquery');
var $osf = require('js/osfHelpers');
var fb = require('js/myProjects.js');
var m = require('mithril');

var LinkObject = fb.LinkObject;

describe('fileBrowser', function() {
    describe('LinkObject', function () {
        var collection;
        var tag;
        var name;
        var node;

        before(function () {
            collection = new LinkObject('collection', {
                path: 'users/me/nodes/',
                query: {'related_counts': 'children'},
                systemCollection: true
            }, 'All My Projects');
            tag = new LinkObject('tag', { tag : 'something', query : { 'related_counts' : true }}, 'Something Else');
            name = new LinkObject('name', { id : '8q36f', query : { 'related_counts' : true }}, 'Caner Uguz');
            node = new LinkObject('node', { id : 'qwerty'}, 'Node Title');
        });

        describe('#attributes', function () {
            it('should return an id of 1', function () {
                assert.equal(collection.id, 1);
            });
            it('should throw error when no arguments passed', function () {
                assert.throws(function(){ var missing = new LinkObject(); }, Error);
            });
        });
    });
});


text:
<?php

namespace Jalle19\Laravel\LostInterfaces\Http\Requests;

/**
 * Interface for form requests
 *
 * @package Jalle19\Laravel\LostInterfaces\Http\Requests
 */
interface FormRequest
{

    /**
     * Determine if the request passes the authorization check.
     *
     * @return bool
     */
    public function authorize();

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules();

}


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;

public class ContactDeletionTests extends TestBase {

  public void ensurePreconditions(){
    if (app.db().contacts().size()==0){
      app.goTo().ContactPage();
      app.contact().create(new ContactData().withFirstname("test_1").withLastname("test2"));
    }
  }

  @Test
  public void testContactDeletion(){
    Contacts before = app.db().contacts();
    ContactData deletedContact = before.iterator().next();
    app.contact().delete(deletedContact);
    Contacts after = app.db().contacts();
    assertEquals(after.size(), before.size()-1);
    assertThat(after, equalTo(before.without(deletedContact)));
    verifyContactListInUI();

  }

}


text:
<?php

namespace Tests\PHPCensor\Model\Base;

use PHPCensor\Model\Base\Environment;
use PHPCensor\StoreRegistry;
use PHPUnit\Framework\TestCase;

class EnvironmentTest extends TestCase
{
    protected StoreRegistry $storeRegistry;

    protected function setUp(): void
    {
        $configuration   = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();
        $databaseManager = $this
            ->getMockBuilder('PHPCensor\DatabaseManager')
            ->setConstructorArgs([$configuration])
            ->getMock();
        $this->storeRegistry = $this
            ->getMockBuilder('PHPCensor\StoreRegistry')
            ->setConstructorArgs([$databaseManager])
            ->getMock();
    }

    public function testConstruct()
    {
        $environment = new Environment($this->storeRegistry);

        self::assertInstanceOf('PHPCensor\Model', $environment);
        self::assertInstanceOf('PHPCensor\Model\Base\Environment', $environment);

        self::assertEquals([
            'id'         => null,
            'project_id' => null,
            'name'       => null,
            'branches'   => [],
        ], $environment->getDataArray());
    }

    public function testId()
    {
        $environment = new Environment($this->storeRegistry);

        $result = $environment->setId(100);
        self::assertEquals(true, $result);
        self::assertEquals(100, $environment->getId());

        $result = $environment->setId(100);
        self::assertEquals(false, $result);
    }

    public function testProjectId()
    {
        $environment = new Environment($this->storeRegistry);

        $result = $environment->setProjectId(200);
        self::assertEquals(true, $result);
        self::assertEquals(200, $environment->getProjectId());

        $result = $environment->setProjectId(200);
        self::assertEquals(false, $result);
    }

    public function testName()
    {
        $environment = new Environment($this->storeRegistry);

        $result = $environment->setName('name');
        self::assertEquals(true, $result);
        self::assertEquals('name', $environment->getName());

        $result = $environment->setName('name');
        self::assertEquals(false, $result);
    }

    public function testBranches()
    {
        $environment = new Environment($this->storeRegistry);

        $result = $environment->setBranches(['branch-1', 'branch-2']);
        self::assertEquals(true, $result);
        self::assertEquals(['branch-1', 'branch-2'], $environment->getBranches());

        $result = $environment->setBranches(['branch-1', 'branch-2']);
        self::assertEquals(false, $result);

        $environment = new Environment($this->storeRegistry, ['branches' => "branch-1\nbranch-2\nbranch-3\n\nbranch-4"]);
        self::assertEquals(['branch-1', 'branch-2', 'branch-3', 'branch-4'], $environment->getBranches());
    }
}


text:
#include "qcallsite_p.h"

#include "qcalltargetdescription_p.h"

QT_BEGIN_NAMESPACE

using namespace QPatternist;

CallTargetDescription::CallTargetDescription(const QXmlName &name) : m_name(name)
{
    Q_ASSERT(!m_name.isNull());
}

QXmlName CallTargetDescription::name() const
{
    return m_name;
}

void CallTargetDescription::checkArgumentsCircularity(CallTargetDescription::List &signList,
                                                      const Expression::Ptr callsite)
{
    /* Check the arguments. */
    const Expression::List ops(callsite->operands());
    const Expression::List::const_iterator end(ops.constEnd());
    Expression::List::const_iterator it(ops.constBegin());

    for(; it != end; ++it)
        checkCallsiteCircularity(signList, *it);
}

void CallTargetDescription::checkCallsiteCircularity(CallTargetDescription::List &signList,
                                                     const Expression::Ptr expr)
{
    Q_ASSERT(expr);

    if(expr->is(Expression::IDUserFunctionCallsite))
    {
        CallTargetDescription::List::const_iterator it(signList.constBegin());
        const CallTargetDescription::List::const_iterator end(signList.constEnd());
        CallSite *const callsite = static_cast<CallSite *>(expr.data());

        for(; it != end; ++it)
        {
            if(callsite->configureRecursion(*it))
            {
                /* A callsite inside the function body to the function. This user function
                 * is recursive if it's to the same function, in other words. Which it was
                 * if configureRecursion() returned true. */

                /* Now we continue and check the arguments of the callsite. That is, the arguments.
                 * This catches for instance local:foo(local:foo(3)). */
                checkArgumentsCircularity(signList, expr);
                return;
            }
        }
        /* Check the body of the function so this callsite isn't "indirectly" a
         * recursive call to the function we're checking. XQTS test case
         * default_namespace-011 is an example of this. */
        signList.append(callsite->callTargetDescription());
        checkCallsiteCircularity(signList, callsite->body());
    }

    checkArgumentsCircularity(signList, expr); /* We're done in this case. */
}

QT_END_NAMESPACE


text:
<?php

// autoload.php generated by Composer

require_once __DIR__ . '/../vendor/autoload.php';


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

 class Cadastrar extends CI_Controller {

     function __construct() {
         parent::__construct();
         $this->load->model('Igrejas_model', 'igrejas');

    }

    public function index() {
        $this->load->view('cadastrar');

    }

    public function Form_login() {
        $this->load->view('login');
    }

    public function cadastro($id = NULL) {
         if(null != $this->session->userdata('logado')){
         $this->db->where('ID', $id);
         $this->db->where('ativar',1);
        // if(NULL != $this->session->userdata('logado')){
         $data['igrejas'] = $this->igrejas->getIgrejas();
         $this->load->view('cadastro',$data);
            }

         else {
             redirect("login");

         }
    }

    public function agenda($id) {
        $this->load->model('Igrejas_model', 'agenda');
        $data['agenda'] = $this->agenda->getAgenda($id);
        $this->load->view('agenda', $data);
    }

    public function alterarPlano() {
        $this->load->view('alterar-plano');
    }

    public function alterarFoto() {
        $this->load->view('alterar-foto');
    }

    public function cadastroPastores() {
        $this->load->view('cadastro-pastores');
    }

    public function Adicionar() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('nome', 'Nome','required|min_length[5]');
        $this->form_validation->set_rules('email', 'E-mail', 'required|valid_email');
        if ($this->form_validation->run() == FALSE){
        $this->index();

        }
            else {
                $dados['denominacao_ID'] = $this->input->post("SELECT * FROM igreja WHERE denominacao_ID as denominacao");
                $dados['nome'] = $this->input->post('nome');
                $dados['cep'] = $this->input->post('cep');
                $dados['rua'] = $this->input->post('rua');
                $dados['bairro'] = $this->input->post('bairro');
                $dados['cidade_ID'] = $this->input->post('cidade_ID');
                $dados['cidade_ID'] = $this->input->post("SELECT * FROM igreja WHERE cidade_ID as uf");
                $dados['telefones'] = $this->input->post('telefones');
                $dados['responsavel'] = $this->input->post('responsavel');
                $dados['twitter'] = $this->input->post('twitter');
                $dados['facebook'] = $this->input->post('facebook');
                $dados['site'] = $this->input->post('site');
                $dados['email'] = $this->input->post('email');
                $dados['senha'] = $this->input->post('senha');

                if($this->db->insert('igrejas',$dados)){
                    echo "Dados Cadastrados com Sucesso!";
                    redirect('home');
                }
                else {
                    echo "Houve um erro ao processar seus dados";

                }

            }
    }

    public function Login(){
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'E-mail', 'required|valid_email');
        $this->form_validation->set_rules('senha', 'Senha','required|min_length[5]');
        if ($this->form_validation->run() == FALSE){
            $this->Form_login();
        }
        else{
            //$email = $this->input->post('email');
            //$senha = $this->input->post('senha');

            $this->db->where('email', $this->input->post('email'));
            $this->db->where('senha', $this->input->post('senha'));
            $igrejas = $this->db->get('igrejas')->result();
            $this->db->where('ativar',1);

            //$this->db->get('igrejas')->result();
           // echo $this->db->last_query(); //Use a função $this->db->last_query() para verificar a última consulta executada.
            //print_r($igrejas);
            //exit();
           if(count($igrejas)==1){
                $dadosSessao['igrejas'] = $igrejas[0];
                $dadosSessao['logado'] = TRUE;
                $this->session->set_userdata($dadosSessao);
                redirect(base_url("cadastro"));
            }
            else{
                $dadosSessao['igrejas'] = NULL;
                $dadosSessao['logado'] = FALSE;
                $this->session->set_userdata($dadosSessao);
                redirect(base_url("login"));
            }

        }

    }

    public function logout() {
        $dadosSessao['igrejas'] = NULL;
        $dadosSessao['logado'] = FALSE;
        $this->session->set_userdata($dadosSessao);
        redirect(base_url("login"));

    }

    public function editar_cadastro($id=NULL) {
        if(null != $this->session->userdata('logado')){
            $this->load->model('igrejas_model', 'igrejas');
            $this->db->where('md5(id)', $id);
            $this->db->where('id', $this->session->userdata('igrejas')->id);
            $data['cadastro'] = /*$this->igrejas->editar_cadastro($id); */ $this->db->get('igrejas')->result();
            if(count($data['cadastro']) == 1){
            $this->load->view('cadastro', $data);
            }
        }
            else {
                    redirect (base_url("login"));
        }
    }

    function salvar_alteracao_cadastro() {
        if(null != $this->session->userdata('logado')){
            $this->load->library('form_validation');
            $this->load->helper('form');
            $this->form_validation->set_rules('nome','required|min_lenght[5]');
            $this->form_validation->set_rules('email','required|valid_email');
            if ($this->form_validation->run() == FALSE){
		$this->cadastro($this->input->post('id'));
        }
        else {
            $dados['denominacao'] = $this->input->post('denominacao');
            $dados['nome'] = $this->input->post('nome');
            $dados['cep'] = $this->input->post('cep');
            $dados['rua'] = $this->input->post('rua');
            $dados['bairro'] = $this->input->post('bairro');
            $dados['cidade'] = $this->input->post('cidade');
            $dados['estado'] = $this->input->post('estado');
            $dados['numero'] = $this->input->post('numero');
            $dados['regiao'] = $this->input->post('regiao');
            $dados['telefone'] = $this->input->post('telefone');
            $dados['responsavel'] = $this->input->post('responsavel');
            $dados['twitter'] = $this->input->post('twitter');
            $dados['facebook'] = $this->input->post('facebook');
            $dados['site'] = $this->input->post('site');
            $dados['segunda'] = $this->input->post('segunda');
            $dados['terca'] = $this->input->post('terca');
            $dados['quarta'] = $this->input->post('quarta');
            $dados['quinta'] = $this->input->post('quinta');
            $dados['sexta'] = $this->input->post('sexta');
            $dados['sabado'] = $this->input->post('sabado');
            $dados['domingo'] = $this->input->post('domingo');
            $dados['email'] = $this->input->post('email');
            $dados['senha'] = $this->input->post('senha');
            $dados['ativar'] = 0;
            $this->db->query("INSERT INTO igrejas SELECT * FROM igrejas WHERE md5(id) = '".$this->input->post('id')."'");
            $this->db->where('md5(id)', $this->input->post('id'));
            if($this->db->update('igrejas',$dados)){
                echo "Dados alterados com sucesso!";

            }
            else {
                echo "Houve um erro ao processar a alteração";
            }
        }
    }

    }

}
?>


text:
/**
 * Created by yan on 16-1-8.
 */

import React from 'react';
import {render} from 'react-dom';
import CopyButton from './modules/CopyButton.jsx';

const textToBeCopied = "jellyfish";

render(

Example:

1. Click COPY Button

  <CopyButton data-clipboard-text={textToBeCopied}>Click to copy</CopyButton>

2. Paste below to check against {textToBeCopied}

  <textarea/>

, document.getElementById('root'));


text:
package org.kuali.kpme.tklm.api.leave.summary;

import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.kuali.kpme.core.api.calendar.entry.CalendarEntry;

import java.math.BigDecimal;
import java.util.List;

public interface LeaveSummaryService {
	public LeaveSummaryContract getLeaveSummary(String principalId, CalendarEntry calendarEntry) throws Exception;

	public List<LocalDateTime> getLeaveSummaryDates(CalendarEntry cal);

    public LeaveSummaryContract getLeaveSummaryAsOfDate(String principalId, LocalDate asOfDate);

    public LeaveSummaryContract getLeaveSummaryAsOfDateForAccrualCategory(String principalId, LocalDate asOfDate, String accrualCategory);

    public LeaveSummaryContract getLeaveSummaryAsOfDateWithoutFuture(String principalId, LocalDate asOfDate);

    public BigDecimal getLeaveBalanceForAccrCatUpToDate(String principalId, LocalDate startDate, LocalDate endDate, String accrualCategory, LocalDate usageEndDate);
}


text:
package handler

import (
	"github.com/micro/go-micro/errors"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/net/context"

	"github.com/dgrijalva/jwt-go"

	"github.com/dakstudios/auth-srv/db"
	auth "github.com/dakstudios/auth-srv/proto/auth"
)

const (
	jwtSecret = "some_secure_secret"
)

type userClaims struct {
	ID string `json:"id"`
	jwt.StandardClaims
}

type Auth struct{}

func (a *Auth) Authenticate(ctx context.Context, req *auth.AuthenticateRequest, res *auth.AuthenticateResponse) error {
	if len(req.Email) == 0 || len(req.Password) == 0 {
		return errors.BadRequest("srv.auth.Authenticate", "invalid_request")
	}

	user, err := db.FindUser(req.Email)
	if err != nil {
		return errors.InternalServerError("srv.auth.Authenticate", "server_error")
	}

	if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
		return errors.BadRequest("srv.auth.Authenticate", "access_denied")
	}

	claims := userClaims{
		user.Id,
		jwt.StandardClaims{
			ExpiresAt: 15000,
			Issuer:    "org.dakstudio.srv.auth",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signed, err := token.SignedString([]byte(jwtSecret))
	if err != nil {
		return errors.InternalServerError("srv.auth.Authenticate", "server_error")
	}

	res.Token = &auth.Token{Token: signed}

	return nil
}

func (a *Auth) Authorize(ctx context.Context, req *auth.AuthorizeRequest, res *auth.AuthorizeResponse) error {
	if len(req.Token.Token) == 0 || len(req.Permission) == 0 {
		return errors.BadRequest("srv.auth.Authenticate", "invalid_request")
	}

	token, err := jwt.ParseWithClaims(req.Token.Token, &userClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtSecret), nil
	})

	if !token.Valid {
		return errors.BadRequest("srv.auth.Authenticate", "access_denied")
	}

	claims, ok := token.Claims.(*userClaims)
	if !ok {
		return errors.InternalServerError("srv.auth.Authenticate", "server_error")
	}

	authorized, err := db.Authorize(claims.ID, req.Permission)
	if err != nil {
		return errors.InternalServerError("srv.auth.Authenticate", "server_error")
	}

	res.Authorized = authorized

	return nil
}


text:
package com.qualcomm.ftcrobotcontroller.opmodes.phresh;

import com.lasarobotics.library.controller.ButtonState;
import com.lasarobotics.library.controller.Controller;
import com.lasarobotics.library.drive.Tank;
import com.lasarobotics.library.util.MathUtil;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;

/**
 * Skunk (TM) Teleop
 */
public class Testing extends OpMode {

    DcMotor leftFront, rightFront, leftBack, rightBack,liftA,liftB,winch,intake;
    Servo leftHook,rightHook;
    Controller one,two;
    boolean hooked;
    boolean intakeBool;

    double DEADBAND = 0.05;

    @Override
    public void init() {
        leftFront = hardwareMap.dcMotor.get("rf");
        rightFront = hardwareMap.dcMotor.get("lf");
        leftBack = hardwareMap.dcMotor.get("rb");
        rightBack = hardwareMap.dcMotor.get("lb");
        winch = hardwareMap.dcMotor.get("winch");
        liftA = hardwareMap.dcMotor.get("liftA");
        liftB = hardwareMap.dcMotor.get("liftB");
        intake = hardwareMap.dcMotor.get("intake");

        leftHook = hardwareMap.servo.get("leftHook");
        rightHook = hardwareMap.servo.get("rightHook");

        rightFront.setDirection(DcMotor.Direction.REVERSE);
        rightBack.setDirection(DcMotor.Direction.REVERSE);

        one = new Controller(gamepad1);
        two = new Controller(gamepad2);

        leftHook.setPosition(0);
        rightHook.setPosition(1);
    }

    @Override
    public void loop() {
        one.update(gamepad1);
        two.update(gamepad2);

        telemetry.addData("Controller One Connected", one.isConnected());
        telemetry.addData("Controller Two Connected", two.isConnected());

        //Hooks
        if (one.x == ButtonState.PRESSED){
            hooked = !hooked;
        }
        if (hooked){
            leftHook.setPosition(1);
            rightHook.setPosition(0);
        }
        else {
            leftHook.setPosition(0);
            rightHook.setPosition(1);
        }

        //Winch
        winch.setPower(MathUtil.deadband(DEADBAND, two.right_stick_y));
        liftA.setPower(MathUtil.deadband(DEADBAND, -two.right_stick_y));

        //Lift
        liftB.setPower(MathUtil.deadband(DEADBAND, -two.left_stick_y));

        //Intake
        if (two.a == ButtonState.PRESSED){
            intakeBool = !intakeBool;
        }
        if (two.left_bumper == ButtonState.HELD || two.left_bumper == ButtonState.PRESSED){
            intake.setPower(-1);
        }
        else if(intakeBool) {
            intake.setPower(1);
        }
        else {
            intake.setPower(0);
        }

        Tank.motor4(leftFront, rightFront, leftBack, rightBack,
                MathUtil.deadband(DEADBAND, one.left_stick_y), MathUtil.deadband(DEADBAND, one.right_stick_y));
    }
}


text:
//package org.jasig.cas.ticket.support;

//import org.jasig.cas.ticket.ExpirationPolicy;
//import org.jasig.cas.ticket.TicketState;

/**
 * Ticket expiration policy based on a hard timeout from ticket creation time rather than the
 * "idle" timeout provided by {@link org.jasig.cas.ticket.support.TimeoutExpirationPolicy}.
 *
 * @author Andrew Feller
 * @version $Revision$ $Date$
 * @since 3.1.2
 */

namespace NCAS.jasig.ticket.support
{
    public class HardTimeoutExpirationPolicy : ExpirationPolicy
    {

        /** Unique Id for serialization. */
        private static long serialVersionUID = -1465997330804816888L;

        /** The time to kill in milliseconds. */
        private long timeToKillInMilliSeconds;

        public HardTimeoutExpirationPolicy(long timeToKillInMilliSeconds)
        {
            this.timeToKillInMilliSeconds = timeToKillInMilliSeconds;
        }

        public bool isExpired(TicketState ticketState)
        {
            return (ticketState == null)
                   || (System.DateTime.Now.Ticks - ticketState.getCreationTime() >= this.timeToKillInMilliSeconds);
        }
    }
}


text:
"""NormOptimiser for TensorFlow."""

from tensorflow.python.framework import ops
from tensorflow.python.ops import constant_op
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.training import optimizer
from tensorflow.python.training import training_ops

import tensorflow as tf

class AdamPlusOptimizer(optimizer.Optimizer):
    """Optimizer that implements the Adam algorithm.

    @@__init__
    """

    def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, pow=0.7,
                 use_locking=False, name="Norm"):
        """Construct a modified Adam optimizer.

        Implementation is based on: http://arxiv.org/pdf/1412.6980v7.pdf

        Initialization:

        ```
        m_0 <- 0 (Initialize initial 1st moment vector)
        v_0 <- 0 (Initialize initial 2nd moment vector)
        t <- 0 (Initialize timestep)
        ```

        The update rule for `variable` with gradient `g` uses an optimization
        described at the end of section2 of the paper:

        ```
        t <- t + 1
        lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)

        m_t <- beta1 * m_{t-1} + (1 - beta1) * g
        v_t <- beta2 * v_{t-1} + (1 - beta2) * g * g
        variable <- variable - lr_t * m_t / (sqrt(v_t) + epsilon)
        ```

        The default value of 1e-8 for epsilon might not be a good default in
        general. For example, when training an Inception network on ImageNet a
        current good choice is 1.0 or 0.1.

        Args:
          learning_rate: A Tensor or a floating point value.  The learning rate.
          beta1: A float value or a constant float tensor.
            The exponential decay rate for the 1st moment estimates.
          beta2: A float value or a constant float tensor.
            The exponential decay rate for the 2nd moment estimates.
          epsilon: A small constant for numerical stability.
          use_locking: If True use locks for update operations.
          name: Optional name for the operations created when applying gradients.
            Defaults to "Adam".
        """
        super(AdamPlusOptimizer, self).__init__(use_locking, name)
        self._lr = learning_rate
        self._beta1 = beta1
        self._beta2 = beta2
        self._epsilon = epsilon
        self._pow = pow

        # Tensor versions of the constructor arguments, created in _prepare().
        self._lr_t = None
        self._beta1_t = None
        self._beta2_t = None
        self._epsilon_t = None
        self._pow_t = None

        # Variables to accumulate the powers of the beta parameters.
        # Created in _create_slots when we know the variables to optimize.
        self._beta1_power = None
        self._beta2_power = None

        # Created in SparseApply if needed.
        self._updated_lr = None

    def _get_beta_accumulators(self):
        return self._beta1_power, self._beta2_power

    def _create_slots(self, var_list):
        # Create the beta1 and beta2 accumulators on the same device as the first
        # variable.
        if self._beta1_power is None:
            with ops.device(var_list[0].device):
                self._beta1_power = variables.Variable(self._beta1,
                                                       name="beta1_power",
                                                       trainable=False)
                self._beta2_power = variables.Variable(self._beta2,
                                                       name="beta2_power",
                                                       trainable=False)
        # Create slots for the first and second moments.
        for v in var_list:
            self._zeros_slot(v, "m", self._name)
            self._zeros_slot(v, "v", self._name)

    def _prepare(self):
        self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate")
        self._beta1_t = ops.convert_to_tensor(self._beta1, name="beta1")
        self._beta2_t = ops.convert_to_tensor(self._beta2, name="beta2")
        self._epsilon_t = ops.convert_to_tensor(self._epsilon, name="epsilon")
        self._pow_t = ops.convert_to_tensor(self._pow, name="pow")

    def _apply_dense(self, grad, var):
        lr = (self._lr_t *
              math_ops.sqrt(1 - self._beta2_power)
              / (1 - self._beta1_power))
        # m_t = beta1 * m + (1 - beta1) * g_t
        m = self.get_slot(var, "m")
        m_scaled_g_values = grad * (1 - self._beta1_t)
        m_t = m * self._beta1_t
        m_t = m_t + m_scaled_g_values
        # v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
        v = self.get_slot(var, "v")
        v_scaled_g_values = tf.pow(grad, 2) * (1 - self._beta2_t)
        v_t = v * self._beta2_t
        v_t = v_t + v_scaled_g_values
        v_sqrt = tf.pow(v_t, self._pow_t)
        var_update = state_ops.assign_sub(var,
                                          lr * m_t / (v_sqrt + self._epsilon_t),
                                          use_locking=self._use_locking)

        return control_flow_ops.group(*[var_update, m_t, v_t])

    def _apply_sparse(self, grad, var):
        lr = (self._lr_t *
              math_ops.sqrt(1 - self._beta2_power)
              / (1 - self._beta1_power))
        # m_t = beta1 * m + (1 - beta1) * g_t
        m = self.get_slot(var, "m")
        m_scaled_g_values = grad.values * (1 - self._beta1_t)
        m_t = state_ops.assign(m, m * self._beta1_t,
                               use_locking=self._use_locking)

        m_t = state_ops.scatter_add(m_t, grad.indices, m_scaled_g_values,
                                    use_locking=self._use_locking)
        # v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
        v = self.get_slot(var, "v")
        v_scaled_g_values = (grad.values * grad.values) * (1 - self._beta2_t)
        v_t = state_ops.assign(v, v * self._beta2_t, use_locking=self._use_locking)
        v_t = state_ops.scatter_add(v_t, grad.indices, v_scaled_g_values,
                                    use_locking=self._use_locking)
        v_sqrt = tf.pow(v_t, self._pow_t)
        var_update = state_ops.assign_sub(var,
                                          lr * m_t / (v_sqrt + self._epsilon_t),
                                          use_locking=self._use_locking)
        return control_flow_ops.group(*[var_update, m_t, v_t])

    def _finish(self, update_ops, name_scope):
        # Update the power accumulators.
        with ops.control_dependencies(update_ops):
            with ops.device(self._beta1_power.device):
                update_beta1 = self._beta1_power.assign(
                        self._beta1_power * self._beta1_t,
                        use_locking=self._use_locking)
                update_beta2 = self._beta2_power.assign(
                        self._beta2_power * self._beta2_t,
                        use_locking=self._use_locking)
        return control_flow_ops.group(*update_ops + [update_beta1, update_beta2],
                                      name=name_scope)

class AdamPlusCovOptimizer(optimizer.Optimizer):
    """Optimizer that implements the Adam algorithm.

    @@__init__
    """

    def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, pow=0.7,
                 use_locking=False, name="Norm"):
        """Construct a modified Adam optimizer.

        Implementation is based on: http://arxiv.org/pdf/1412.6980v7.pdf

        Initialization:

        ```
        m_0 <- 0 (Initialize initial 1st moment vector)
        v_0 <- 0 (Initialize initial 2nd moment vector)
        t <- 0 (Initialize timestep)
        ```

        The update rule for `variable` with gradient `g` uses an optimization
        described at the end of section2 of the paper:

        ```
        t <- t + 1
        lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)

        m_t <- beta1 * m_{t-1} + (1 - beta1) * g
        v_t <- beta2 * v_{t-1} + (1 - beta2) * g * g
        variable <- variable - lr_t * m_t / (sqrt(v_t) + epsilon)
        ```

        The default value of 1e-8 for epsilon might not be a good default in
        general. For example, when training an Inception network on ImageNet a
        current good choice is 1.0 or 0.1.

        Args:
          learning_rate: A Tensor or a floating point value.  The learning rate.
          beta1: A float value or a constant float tensor.
            The exponential decay rate for the 1st moment estimates.
          beta2: A float value or a constant float tensor.
            The exponential decay rate for the 2nd moment estimates.
          epsilon: A small constant for numerical stability.
          use_locking: If True use locks for update operations.
          name: Optional name for the operations created when applying gradients.
            Defaults to "Adam".
        """
        super(AdamPlusCovOptimizer, self).__init__(use_locking, name)
        self._lr = learning_rate
        self._beta1 = beta1
        self._beta2 = beta2
        self._epsilon = epsilon
        self._pow = pow

        # Tensor versions of the constructor arguments, created in _prepare().
        self._lr_t = None
        self._beta1_t = None
        self._beta2_t = None
        self._epsilon_t = None
        self._pow_t = None

        # Variables to accumulate the powers of the beta parameters.
        # Created in _create_slots when we know the variables to optimize.
        self._beta1_power = None
        self._beta2_power = None

        # Created in SparseApply if needed.
        self._updated_lr = None

    def _get_beta_accumulators(self):
        return self._beta1_power, self._beta2_power

    def _create_slots(self, var_list):
        # Create the beta1 and beta2 accumulators on the same device as the first
        # variable.
        if self._beta1_power is None:
            with ops.device(var_list[0].device):
                self._beta1_power = variables.Variable(self._beta1,
                                                       name="beta1_power",
                                                       trainable=False)
                self._beta2_power = variables.Variable(self._beta2,
                                                       name="beta2_power",
                                                       trainable=False)
        # Create slots for the first and second moments.
        for v in var_list:
            self._zeros_slot(v, "m", self._name)
            self._zeros_slot(v, "v", self._name)

    def _prepare(self):
        self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate")
        self._beta1_t = ops.convert_to_tensor(self._beta1, name="beta1")
        self._beta2_t = ops.convert_to_tensor(self._beta2, name="beta2")
        self._epsilon_t = ops.convert_to_tensor(self._epsilon, name="epsilon")
        self._pow_t = ops.convert_to_tensor(self._pow, name="pow")

    def _apply_dense(self, grad, var):
        lr = (self._lr_t *
              math_ops.sqrt(1 - self._beta2_power)
              / (1 - self._beta1_power))
        # m_t = beta1 * m + (1 - beta1) * g_t
        m = self.get_slot(var, "m")
        m_scaled_g_values = grad * (1 - self._beta1_t)
        m_t = m * self._beta1_t
        m_t = m_t + m_scaled_g_values
        # v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
        v = self.get_slot(var, "v")
        #######################################################################################
        v_scaled_g_values = tf.pow(grad - m_t, 2) * (1 - self._beta2_t)
        #######################################################################################
        v_t = v * self._beta2_t
        v_t = v_t + v_scaled_g_values
        v_sqrt = tf.pow(v_t, self._pow_t)
        var_update = state_ops.assign_sub(var,
                                          lr * m_t / (v_sqrt + self._epsilon_t),
                                          use_locking=self._use_locking)

        return control_flow_ops.group(*[var_update, m_t, v_t])

    def _apply_sparse(self, grad, var):
        lr = (self._lr_t *
              math_ops.sqrt(1 - self._beta2_power)
              / (1 - self._beta1_power))
        # m_t = beta1 * m + (1 - beta1) * g_t
        m = self.get_slot(var, "m")
        m_scaled_g_values = grad.values * (1 - self._beta1_t)
        m_t = state_ops.assign(m, m * self._beta1_t,
                               use_locking=self._use_locking)

        m_t = state_ops.scatter_add(m_t, grad.indices, m_scaled_g_values,
                                    use_locking=self._use_locking)
        # v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
        v = self.get_slot(var, "v")
        v_scaled_g_values = (grad.values * grad.values) * (1 - self._beta2_t)
        v_t = state_ops.assign(v, v * self._beta2_t, use_locking=self._use_locking)
        v_t = state_ops.scatter_add(v_t, grad.indices, v_scaled_g_values,
                                    use_locking=self._use_locking)
        v_sqrt = tf.pow(v_t, self._pow_t)
        var_update = state_ops.assign_sub(var,
                                          lr * m_t / (v_sqrt + self._epsilon_t),
                                          use_locking=self._use_locking)
        return control_flow_ops.group(*[var_update, m_t, v_t])

    def _finish(self, update_ops, name_scope):
        # Update the power accumulators.
        with ops.control_dependencies(update_ops):
            with ops.device(self._beta1_power.device):
                update_beta1 = self._beta1_power.assign(
                        self._beta1_power * self._beta1_t,
                        use_locking=self._use_locking)
                update_beta2 = self._beta2_power.assign(
                        self._beta2_power * self._beta2_t,
                        use_locking=self._use_locking)
        return control_flow_ops.group(*update_ops + [update_beta1, update_beta2],
                                      name=name_scope)