text:
class InvitationsController < ApplicationController

  before_filter :only => :create do |controller|
    controller.ensure_logged_in "you_must_log_in_to_invite_new_user"
  end

  before_filter :users_can_invite_new_users, :only => :create

  def create
    @invitation = Invitation.new(params[:invitation])
    if @invitation.save
      notice = [:notice, "invitation_sent"]
      Delayed::Job.enqueue(InvitationCreatedJob.new(@invitation.id, request.host))
    else
      notice = [:error, "invitation_could_not_be_sent"]
    end
    respond_to do |format|
      format.html {
        flash[notice[0]] = notice[1]
        redirect_to root
      }
      format.js {
        flash.now[notice[0]] = notice[1]
        render :layout => false
      }
    end
  end

  private

  def users_can_invite_new_users
    unless @current_community.users_can_invite_new_users
      flash[:error] = "inviting_new_users_is_not_allowed_in_this_community"
      redirect_to root and return
    end
  end

end


text:
Checks if new BIOS updates for a list of Dell laptops
scrapes http://downloads.dell.com/published/pages/ for bios versions.
Alert if new version is found for a watched laptop

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace backend\controllers;

use Yii;
use yii\data\Pagination;
use yii\filters\AccessControl;
use common\models\EmailLog;
use common\extensions\Util;

class EmailLogController extends BackendController {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['actions' => ['index'], 'allow' => true, 'roles' => ['@']]
                ],
            ],
        ];
    }

    public function actionIndex() {
        $var['keyword'] = Util::filterStringRelace(Yii::$app->request->get('keyword'));
        $var['status'] = (int) Yii::$app->request->get('status');
        $var['start_time'] = Yii::$app->request->get('start_time');
        $var['end_time'] = Yii::$app->request->get('end_time');
        $var['pagesize'] = (int) Yii::$app->request->get('pagesize', 10);

        $data = EmailLog::find();

        if ($var['keyword']) {
            $data->orFilterWhere(['like', 'c_email', $var['keyword']]);
            $data->orFilterWhere(['like', 'c_name', $var['keyword']]);
        }

        if ($var['status']) {
            $data->andWhere(['c_status' => $var['status']]);
        }

        if ($var['start_time'] && empty($var['end_time'])) {
            $data->andWhere(['>=', 'c_create_time', strtotime($var['start_time'])]);
        } elseif (empty($var['start_time']) && $var['end_time']) {
            $data->andWhere(['<=', 'c_create_time', strtotime($var['end_time']) + 86400]);
        } elseif ($var['start_time'] && $var['end_time'] && $var['start_time'] < $var['end_time']) {
            $data->andWhere(['>=', 'c_create_time', strtotime($var['start_time'])]);
            $data->andWhere(['<=', 'c_create_time', strtotime($var['end_time']) + 86400]);
        } elseif ($var['start_time'] && $var['end_time'] && $var['start_time'] > $var['end_time']) {//谁的日期大就当做结束日期,相反就是开始日期
            $data->andWhere(['>=', 'c_create_time', strtotime($var['end_time'])]);
            $data->andWhere(['<=', 'c_create_time', strtotime($var['start_time']) + 86400]);
        } elseif ($var['start_time'] && $var['start_time'] == $var['end_time']) {
            $data->andWhere(['>=', 'c_create_time', strtotime($var['start_time'])]);
            $data->andWhere(['<=', 'c_create_time', strtotime($var['start_time']) + 86400]);
        }
        $var['pages'] = new Pagination(['totalCount' => $data->count(), 'pageSize' => $var['pagesize'], 'defaultPageSize' => $var['pagesize']]);
        $var['list'] = $data->offset($var['pages']->offset)->orderby(['c_id' => SORT_DESC])->limit($var['pages']->limit)->all();
        return $this->render('index', $var);
    }

}


text:
using System;
using System.Text;
using GSF.IO.Unmanaged;

namespace GSF.Snap.Tree
{
    public abstract class TreeNodeRandomizerBase<TKey, TValue>
        where TKey : class, new()
        where TValue : class, new()
    {
        public abstract void Reset(int maxCount);
        public abstract void Next();
        public abstract void GetRandom(int index, TKey key, TValue value);
        public abstract void GetInSequence(int index, TKey key, TValue value);
    }

    public class LeafNodeTest
    {
        private const int Max = 1000000;

        public static void TestNode<TKey, TValue>(SortedTreeNodeBase<TKey, TValue> node, TreeNodeRandomizerBase<TKey, TValue> randomizer, int count)
            where TKey : SnapTypeBase<TKey>, new()
            where TValue : SnapTypeBase<TValue>, new()
        {
            int Max = count;
            uint rootKey = 0;
            byte rootLevel = 0;

            uint nextKeyIndex = 2;
            bool hasChanged = false;
            Func<uint> getNextKey = () =>
            {
                nextKeyIndex++;
                return nextKeyIndex - 1;
            };

            StringBuilder sb = new StringBuilder();

            using (BinaryStream bs = new BinaryStream())
            {
                const int pageSize = 512;
                SparseIndex<TKey> sparse = new SparseIndex<TKey>();
                sparse.Initialize(bs, pageSize, getNextKey, 0, 1);
                node.Initialize(bs, pageSize, getNextKey, sparse);
                node.CreateEmptyNode(1);

                TKey key = new TKey();
                TKey key2 = new TKey();
                TValue value = new TValue();
                TValue value2 = new TValue();

                randomizer.Reset(Max);
                for (int x = 0; x < Max; x++)
                {
                    randomizer.Next();
                    //Add the next point
                    randomizer.GetRandom(x, key, value);

                    //node.WriteNodeData(sb);

                    if (!node.TryInsert(key, value))
                        throw new Exception();

                    //node.WriteNodeData(sb);
                    //File.WriteAllText("c:\\temp\\temp.log", sb.ToString());

                    //Check if all points exist
                    for (int y = 0; y <= x; y++)
                    {
                        randomizer.GetRandom(y, key, value);
                        if (!node.TryGet(key, value2))
                            throw new Exception();
                        if (!value.IsEqualTo(value2))
                            throw new Exception();
                    }

                    //Check if scanner works.
                    SortedTreeScannerBase<TKey, TValue> scanner = node.CreateTreeScanner();
                    scanner.SeekToStart();
                    for (int y = 0; y <= x; y++)
                    {
                        randomizer.GetInSequence(y, key, value);
                        if (!scanner.Read(key2, value2))
                            throw new Exception();
                        if (!key.IsEqualTo(key2))
                            throw new Exception();
                        if (!value.IsEqualTo(value2))
                            throw new Exception();
                    }
                    if (scanner.Read(key2, value2))
                        throw new Exception();
                }

                node = node;
            }
        }

        internal static void TestSpeed<TKey, TValue>(SortedTreeNodeBase<TKey, TValue> nodeInitializer, TreeNodeRandomizerBase<TKey, TValue> randomizer, int count, int pageSize)
            where TKey : SnapTypeBase<TKey>, new()
            where TValue : SnapTypeBase<TValue>, new()
        {
            int Max = count;

            uint nextKeyIndex = 2;
            Func<uint> getNextKey = () =>
            {
                nextKeyIndex++;
                return nextKeyIndex - 1;
            };

            using (BinaryStream bs = new BinaryStream())
            {
                randomizer.Reset(Max);
                for (int x = 0; x < Max; x++)
                {
                    randomizer.Next();
                }

                TKey key = new TKey();
                TValue value = new TValue();
                SortedTreeNodeBase<TKey, TValue> node = null;

                System.Console.WriteLine(StepTimer.Time(count, (sw) =>
                {
                    nextKeyIndex = 2;
                    node = nodeInitializer.Clone(0);
                    SparseIndex<TKey> sparse = new SparseIndex<TKey>();
                    sparse.Initialize(bs, pageSize, getNextKey, 0, 1);
                    node.Initialize(bs, pageSize, getNextKey, sparse);
                    node.CreateEmptyNode(1);
                    sw.Start();
                    for (int x = 0; x < Max; x++)
                    {
                        //Add the next point
                        randomizer.GetRandom(x, key, value);

                        if (!node.TryInsert(key, value))
                            throw new Exception();
                    }
                    sw.Stop();
                }));

                System.Console.WriteLine(StepTimer.Time(count, () =>
                {
                    for (int x = 0; x < Max; x++)
                    {
                        //Add the next point
                        randomizer.GetRandom(x, key, value);

                        if (!node.TryGet(key, value))
                            throw new Exception();
                    }
                }));

                System.Console.WriteLine(StepTimer.Time(count, () =>
                {
                    SortedTreeScannerBase<TKey, TValue> scanner = node.CreateTreeScanner();
                    scanner.SeekToStart();
                    while (scanner.Read(key, value))
                        ;
                }));

                node = node;
            }
        }
    }
}


text:
name: Constructors
hidecode: true
description: >

  - Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!
  - Methods can return `this` to help with method chaining.

  ```javascript
    function Jedi() {
      console.log("new jedi");
    }

    // good
    Jedi.prototype.fight = function fight() {
      console.log("fighting");
    };

    Jedi.prototype.block = function block() {
      console.log("blocking");
    };
  ```

  **[⬆ back to top](#table-of-contents)**

---


text:
'use strict';
const common = require('../common.js');

const bench = common.createBenchmark(main, {
  pieces: [1, 4, 16],
  pieceSize: [1, 16, 256],
  withTotalLength: [0, 1],
  n: [1024]
});

function main(conf) {
  const n = +conf.n;
  const size = +conf.pieceSize;
  const pieces = +conf.pieces;

  const list = new Array(pieces);
  list.fill(Buffer.allocUnsafe(size));

  const totalLength = conf.withTotalLength ? pieces * size : undefined;

  bench.start();
  for (var i = 0; i < n * 1024; i++) {
    Buffer.concat(list, totalLength);
  }
  bench.end(n);
}


text:
<resources>
        <string name="title_activity_login">Sign in</string>

    <!-- Strings related to login -->
    <string name="prompt_email">Email</string>
    <string name="prompt_password">Password</string>

    <string name="action_sign_in_register">Sign in</string>
    <string name="action_sign_in_short">Sign in</string>
    <string name="action_sign_in_google">Sign in with Google</string>
    <string name="action_sign_in_facebook">Facebook</string>
    <string name="action_sign_in_twitter">Twitter</string>

    <string name="action_forgot_password">Recover lost password</string>

    <string name="login_progress_signing_in">Signing in…</string>

    <string name="error_invalid_email">This email address is invalid</string>
    <string name="error_invalid_password">This password is too short</string>
    <string name="error_incorrect_password">This password is incorrect</string>
    <string name="error_field_required">This field is required</string>

    <string name="toast_wrong_credentials">Wrong combination of user email and password.</string>
</resources>


text:
"""Count different ratios of nucleotides in a sequence
"""
from joblib import Parallel, delayed
import sys
import math
import glob
import numpy
import os

__author__ = "Titouan Laessle"
__copyright__ = "Copyright 2017 Titouan Laessle"
__license__ = "MIT"

# Species abbreviation:
species = str(sys.argv[2])
# Wanted window size:
window_size = int(sys.argv[3])
# Sample size:
sample_size = int(sys.argv[4])
# Wanted number of threads at the same time:
n_threads = int(sys.argv[5])
# Output file:
output = str(sys.argv[6])

###
# Extract all the path of files matching a certain pattern in a directory
###
def extract_path(files_directory, pattern):
    return glob.glob(files_directory + pattern)

###
# Check if parent directory is present, if not create it
###
def checking_parent(file_path):
    # We don't need the file name, so will take everything but the last part
    parent_directories = '/'.join(file_path.split('/')[0:(len(file_path.split('/')) - 1)])
    # As we uses parallel, we ended up we one thread doesn't seeing the directory, attempting
    # creating it, while another just did the same -> error "The file already exist", and stopped everything...
    try:
        if not os.path.exists(parent_directories):
            os.makedirs(parent_directories)
    except:
        pass

###
# Compute the k-mer Frequencies using the Chaos Game Representation (FCGR)
# Inputs:
#   - k_size : k-mer size
#   - CGR :
#       - Either a file (string)
#       - Or a set a of coordinates (list) obtained through CGR_coordinates function
#   - outfile : path to the output file, which will contain the FCGR
#           Note: if empty, will return the FCGR instead of writing a file.
# Output:
#   - Either a file, where each k-mer frequencies are separated by \t
#   - Or the k-mer frequencies stocked ias a list
###
def FCGR_from_CGR(k_size, CGR, outfile):
    #####################
    # 1)  Fetch the coordinates and compute all the boundaries of the grid (for a certain k-mer size)
    #####################

    # If CGR is a string, it must be a path leading to a file containing all the coordinates
    if isinstance(CGR, str):
        x_coord = []
        y_coord = []
        with open(CGR, 'r') as CGR_file:
            for each_coord in CGR_file:
                x_coord.append(float(each_coord.split()[0]))
                y_coord.append(float(each_coord.split()[1]))
        coordinates = [x_coord, y_coord]
    # Else it's a Python list of coordinates
    else:
        coordinates = CGR
    # We take out the k_size-1 first coordinates, are these are the coordinates of words smaller than our
    # wanted k-mer size, and would add small errors later on when counting the frequencies
    for each_xy in [0, 1]:
        coordinates[each_xy] = coordinates[each_xy][k_size - 1::]

    # Now compute the different grid starting boundaries
    # Make sure the decimals are precise enough
    decimals = int(math.pow(10, k_size + 2))
    # Calculate the number of different k-mer we will compute (= number of grid we divide the CGR with)
    grid_size = int(math.pow(4, k_size))
    # Compute all the possible starting coordinates of all these grids
    start_coord_ranges = range(0, int(decimals), int(decimals / math.sqrt(grid_size)))

    #####################
    # 2)  After sorting the x coordinates, go one coordinates at a time, and check if it is a starting boundary
    #####################
    # For x coordinates:
    sort_x = sorted(coordinates[0])
    x_boundaries = []
    which_boundary = 0

    # We can go one sorted x coordinate at a time now:
    for each_coordinates in range(len(sort_x)):
        # If we are a the last coordinate, we must mark any remaining boundaries as empty, and we can stop here (break)
        if each_coordinates == len(sort_x) - 1:
            x_boundaries.append(each_coordinates)
            while len(x_boundaries) != len(start_coord_ranges) + 1:
                x_boundaries.append('empty')
            break
        # First, we see if the i coordinates is a "boundary" of a grid
        # (if bigger/outside of the i grid (represented by 'which_boundary'))
        if sort_x[each_coordinates] >= start_coord_ranges[which_boundary] / decimals:
            # If we are just before the last grid, we cannot have problem of empty grid left (see next if):
            if which_boundary == len(start_coord_ranges) - 1:
                x_boundaries.append(each_coordinates)
                which_boundary += 1
            # In some cases, the i coordinates is not only bigger than the i boundary, but also of i+1
            # (and even the next, so on and so on). In this case, we know that the i boundary
            # does not contain any coordinates ('empty'), and that we can go to the next boundary (which_boundary +1)
            elif sort_x[each_coordinates] >= start_coord_ranges[which_boundary + 1] / decimals:
                while not which_boundary == len(start_coord_ranges) - 1 \
                        and sort_x[each_coordinates] >= start_coord_ranges[which_boundary + 1] / decimals:
                    x_boundaries.append('empty')
                    which_boundary += 1
                x_boundaries.append(each_coordinates)
                which_boundary += 1
            # If not at the before-last grid, or if only bigger to i grid, it is the boundary of the i grid.
            # We then note where we are in the index, and go for the next starting boundary (which_boundary +1)
            else:
                x_boundaries.append(each_coordinates)
                which_boundary += 1
            # If we ended up being at the last grid, the last boundary is simply the last element
            # and we can stop here (break)
            if which_boundary == len(start_coord_ranges):
                x_boundaries.append(len(sort_x))
                break

    #####################
    # 3)  Quite similar step is done for each y coordinates corresponding to each x grids
    #####################
    # We will need the order of indices of x coordinates to do the same operations on y:
    numpy_x = numpy.array(coordinates[0])
    numpy_y = numpy.array(coordinates[1])
    sort_index_x = numpy.argsort(numpy_x)
    y_boundaries = []

    # Can go one starting boundary of grids of x at a time:
    # Note, we don't go for the -1 one, as it is not really a grid, but simply the ultimate grid's ending boundary
    for each_column in range(len(x_boundaries) - 1):
        y_boundaries.append([])

        # We will compute the y boundaries differently depending on whether the x column is empty or not:
        if not x_boundaries[each_column] == 'empty':
            # For each column of grids, we can sort the y of the sorted x, and do the same steps as before
            # First, we must find all the y corresponding to the x in the right grid:

            # In case we are at the last column
            if each_column == len(x_boundaries) - 1:
                corresponding_x_indexes = [x_boundaries[each_column], len(sort_x)]

            # Now in cases next column is an empty column, need the first non-empty one to know the corresponding x
            next_column = each_column + 1
            if x_boundaries[next_column] == 'empty':
                while True:
                    # In cases we have only empty columns left,
                    if next_column == len(x_boundaries) - 1:
                        corresponding_x_indexes = [x_boundaries[each_column], len(sort_x)]
                        break
                    # Else we must find which is the next non-empty
                    if x_boundaries[next_column] == 'empty':
                        next_column += 1
                    else:
                        corresponding_x_indexes = [x_boundaries[each_column], x_boundaries[next_column]]
                        break
            # Otherwise, it's simply the x between the boundaries
            else:
                corresponding_x_indexes = [x_boundaries[each_column], x_boundaries[next_column]]

            # Now that we have the corresponding x indexes, we can find the y of these corresponding x, sort them
            # and do the same operation that was performed on x before
            each_column_y = numpy_y[sort_index_x[corresponding_x_indexes[0]:corresponding_x_indexes[1]]]
            sort_y = numpy.sort(each_column_y)
            which_boundary = 0
            # Now do the same operation (see comments for the x coordinates operation)
            # Note, we do not place the last coordinate break at the beginning here,
            # as it would impede with counting later on.
            for each_coordinates in range(len(sort_y)):
                if sort_y[each_coordinates] >= start_coord_ranges[which_boundary] / decimals:
                    # Penultimate grid
                    if which_boundary == len(start_coord_ranges) - 1:
                        y_boundaries[each_column].append(each_coordinates)
                        which_boundary += 1
                    # Empty grid later on:
                    elif sort_y[each_coordinates] >= start_coord_ranges[which_boundary + 1] / decimals:
                        while not which_boundary == len(start_coord_ranges) - 1 \
                                and sort_y[each_coordinates] >= start_coord_ranges[which_boundary + 1] / decimals:
                            y_boundaries[each_column].append('empty')
                            which_boundary += 1
                        y_boundaries[each_column].append(each_coordinates)
                        which_boundary += 1
                    # Any not special grid
                    else:
                        y_boundaries[each_column].append(each_coordinates)
                        which_boundary += 1
                    # Ultimate grid:
                    if which_boundary == len(start_coord_ranges):
                        y_boundaries[each_column].append(len(sort_y))
                        break
                # If we are at the last coordinate
                if each_coordinates == len(sort_y) - 1:
                    y_boundaries[each_column].append(len(sort_y))
                    while len(y_boundaries[each_column]) != len(start_coord_ranges) + 1:
                        y_boundaries[each_column].append('empty')
                    break

        # Else, the whole column is empty, and must be marked as such:
        else:
            while len(y_boundaries[each_column]) != len(start_coord_ranges) + 1:
                y_boundaries[each_column].append('empty')

    #####################
    # 4)  Using only these y starting boundaries (indexes of y), we can count
    # how many coordinates there is in each boundary
    #####################
    FCGR = []
    # We know use the y boundaries to count the frequencies:
    for each_column in range(len(y_boundaries)):
        for each_kmer in range(len(y_boundaries[each_column]) - 1):
            # next_kmer will help us know which boundary we will use to compare to our actual kmer
            next_kmer = each_kmer + 1
            # If empty, this mean there is no counts for this kmer.
            if y_boundaries[each_column][each_kmer] == 'empty':
                FCGR.append(0)
            # As we subtract, we must have a non-empty index to compare with:
            elif y_boundaries[each_column][each_kmer + 1] == 'empty':
                find_non_empty = True
                while y_boundaries[each_column][next_kmer] == 'empty':
                    # If the ultimate kmer is also empty it simply means that each_kmer was the last boundary
                    if next_kmer == len(start_coord_ranges):
                        FCGR.append(0)
                        find_non_empty = False
                        break
                    # Else, we must keep on searching for the next which is not empty
                    else:
                        next_kmer += 1
                # If we find non-empty boundaries in the next kmers, can use it to count the number of kmer in grid i
                # Note that we add +1 to the index, as we are not as a starting position
                if find_non_empty:
                    # Note: Python start indexing at 0.
                    # To easily count using subtraction we must add +1 to the next index to get the real index.
                    FCGR.append((y_boundaries[each_column][next_kmer]) - y_boundaries[each_column][each_kmer])
            # Else can simply use the next kmer index to count the number of coordinates in the grid
            else:
                FCGR.append((y_boundaries[each_column][next_kmer]) - y_boundaries[each_column][each_kmer])

    # If outfile is non-empty, write the output
    if outfile:
        checking_parent(outfile)
        with open(outfile, 'w') as file:
            for each_count in FCGR:
                file.write(str(each_count) + '\t')
            file.write('\n')
        return FCGR
    # If no 2nd argument was given, outfile is empty (= considered False)
    else:
        return FCGR

###
# Compute various nucleotide ratios using CGRs
# Input:
#   - CGR : Path to the file containing the coordinates of a CGR
#   - window_size
###
def ratios (CGR, window_size):
    FCGR = FCGR_from_CGR(1, CGR, '')

    nA = FCGR[0]
    nC = FCGR[1]
    nT = FCGR[2]
    nG = FCGR[3]

    ratio_A = nA / window_size * 100
    ratio_C = nC / window_size * 100
    ratio_T = nT / window_size * 100
    ratio_G = nG / window_size * 100
    ratio_AG = (nA + nG) / window_size * 100
    ratio_CG = (nC + nG) / window_size * 100
    ratio_TG = (nT + nG) / window_size * 100

    every_ratio = [ratio_A, ratio_C, ratio_T, ratio_G, ratio_AG, ratio_CG, ratio_TG]
    return(every_ratio)

checking_parent(output)
# Opening concatenated file on top level, to avoid rewriting at each record
with open(output, 'w') as outfile:
    # Write column headers
    header = '\t'.join(['record','A','C','T','G','AG','CG', 'TG'])
    outfile.write(header + '\t' + '\n')     # + '\t' to keep same number of column

    # Path to CGR directory
    CGR_directory = '/'.join(['../files/CGRs', '_'.join([str(window_size), str(sample_size)]), species])
    # Get all the different CGRs files path
    all_records = extract_path(CGR_directory + '/', '*')
    # Maintain the initial order of sampling
    all_records.sort(key=lambda r: int(r.split('_')[-1]))

    # Parallel computation for every region:
    every_ratio = Parallel(n_jobs=n_threads)(delayed(ratios)
                                             (all_records[each_region], window_size)
                                             for each_region in range(len(all_records)))

    # Take all the records names from the file paths
    record_names = list()
    for each_record in all_records:
        file_name = os.path.basename(each_record).split('_')
        record_names.append('_'.join([file_name[0], file_name[1], file_name[2]]))

    # Write each region's genomic signature in a single file:
    for each_region in range(len(every_ratio)):
        outfile.write(record_names[each_region] + '\t')
        for each_count in every_ratio[each_region]:
            outfile.write(str(each_count) + '\t')
        outfile.write('\n')


text:
<?php
namespace Rost\Mvc\Controller;

use Rost\Mvc\Dispatcher\DispatcherState;
use Rost\Http\Request;
use Rost\Http\Response;
use Rost\Http\RedirectResponse;

/**
* This is a required base class for all controllers which should to be
* dispatchable by the StandardDispatcher. In addition it has shortcut
* methods to run common operations.
*/
abstract class StandardController
{
	/**
	* @var DispatcherState
	*/
	protected $dispatcherState;

	/**
	* Sets a dispatcher state.
	*
	* @param DispatcherState $dispatcherState
	*/
	function SetDispatcherState(DispatcherState $dispatcherState)
	{
		$this->dispatcherState = $dispatcherState;
	}

	/**
	* Returns Request instance.
	*
	* @return Request
	*/
	protected function GetRequest()
	{
		return $this->dispatcherState->request;
	}

	/**
	* Renders a template and returns Response object with the rendered content.
	*
	* @param string $template
	* @param mixed[] $variables
	* @return Response
	*/
	protected function Render($template, $variables = [])
	{
		$templateManager = $this->dispatcherState->templateManager;
		$templateManager->SetGlobalVariables($variables);
		$content = $templateManager->Render($template);

		return new Response($content);
	}

	/**
	* Returns a named parameter from the matched route.
	* Returns the default value if there is no parameter with the given name.
	*
	* @param string $name
	* @param mixed $default
	* @return mixed
	*/
	protected function GetRouteParameter($name, $default = null)
	{
		return $this->dispatcherState->routeParameters->Get($name, $default);
	}

	/**
	* Returns a named POST parameter.
	* Returns the default value if there is no parameter with the given name.
	*
	* @param string $name
	* @param mixed $default
	* @return mixed
	*/
	protected function GetPostParameter($name, $default = null)
	{
		$request = $this->GetRequest();
		return $request->GetPostParameters()->Get($name, $default);
	}

	/**
	* Returns a named parameter from the URL query.
	* Returns the default value if there is no parameter with the given name.
	*
	* @param string $name
	* @param mixed $default
	* @return mixed
	*/
	protected function GetQueryParameter($name, $default = null)
	{
		$request = $this->GetRequest();
		return $request->GetQueryParameters()->Get($name, $default);
	}

	/**
	* Generates URL by the given route name and parameters.
	*
	* @param string $routeName
	* @param string[] $parameters
	* @return string
	*/
	protected function Url($routeName, $parameters = [])
	{
		return $this->dispatcherState->router->Assemble($routeName, $parameters);
	}

	/**
	* Returns the initialized RedirectResponce object.
	*
	* @param string $url
	* @param int $statusCode The HTTP status code.
	* @return RedirectResponse
	*/
	protected function Redirect($url, $statusCode = 301)
	{
		return new RedirectResponse($url, $statusCode);
	}

	/**
	* Returns the initialized RedirectResponce object.
	*
	* @param string $routeName
	* @param string[] $parameters
	* @param int $statusCode The HTTP status code.
	* @return RedirectResponse
	*/
	protected function RedirectToRoute($routeName, $parameters = [], $statusCode = 301)
	{
		$url = $this->Url($routeName, $parameters);
		return $this->Redirect($url, $statusCode);
	}
}


text:
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset.h"
#include "tensorflow/core/util/batch_util.h"

namespace tensorflow {

namespace {

// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following op.

class BatchDatasetOp : public UnaryDatasetOpKernel {
 public:
  explicit BatchDatasetOp(OpKernelConstruction* ctx)
      : UnaryDatasetOpKernel(ctx) {}

  void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
                   DatasetBase** output) override {
    int64 batch_size = 0;
    OP_REQUIRES_OK(ctx,
                   ParseScalarArgument<int64>(ctx, "batch_size", &batch_size));
    OP_REQUIRES(
        ctx, batch_size > 0,
        errors::InvalidArgument("Batch size must be greater than zero."));

    *output = new Dataset(ctx, batch_size, input);
  }

 private:
  class Dataset : public GraphDatasetBase {
   public:
    Dataset(OpKernelContext* ctx, int64 batch_size, const DatasetBase* input)
        : GraphDatasetBase(ctx), batch_size_(batch_size), input_(input) {
      input_->Ref();

      // NOTE(mrry): Currently we implement "batch up to" semantics. If
      // we could tell statically that the input dataset is infinite,
      // then we could always report `batch_size` as the 0th dimension.
      const auto& input_shapes = input_->output_shapes();
      output_shapes_.reserve(input_shapes.size());
      for (const auto& input_shape : input_shapes) {
        output_shapes_.emplace_back(
            PartialTensorShape({-1}).Concatenate(input_shape));
      }
    }

    ~Dataset() override { input_->Unref(); }

    std::unique_ptr<IteratorBase> MakeIteratorInternal(
        const string& prefix) const override {
      return std::unique_ptr<IteratorBase>(new Iterator(
          Iterator::Params{this, strings::StrCat(prefix, "::Batch")}));
    }

    const DataTypeVector& output_dtypes() const override {
      return input_->output_dtypes();
    }

    const std::vector<PartialTensorShape>& output_shapes() const override {
      return output_shapes_;
    }

    string DebugString() const override {
      return strings::StrCat("BatchDatasetOp(", batch_size_, ")::Dataset");
    }

   protected:
    Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
                              Node** output) const override {
      Node* input_graph_node = nullptr;
      TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
      Node* batch_size = nullptr;
      TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size));
      TF_RETURN_IF_ERROR(
          b->AddDataset(this, {input_graph_node, batch_size}, output));
      return Status::OK();
    }

   private:
    class Iterator : public DatasetIterator<Dataset> {
     public:
      explicit Iterator(const Params& params)
          : DatasetIterator<Dataset>(params) {}

      Status Initialize(IteratorContext* ctx) override {
        return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_);
      }

      Status GetNextInternal(IteratorContext* ctx,
                             std::vector<Tensor>* out_tensors,
                             bool* end_of_sequence) override {
        // Each row of `batch_elements` is a tuple of tensors from the
        // input iterator.
        std::vector<std::vector<Tensor>> batch_elements;
        {
          mutex_lock l(mu_);
          if (!input_impl_) {
            *end_of_sequence = true;
            return Status::OK();
          }
          batch_elements.reserve(dataset()->batch_size_);
          *end_of_sequence = false;
          for (int i = 0; i < dataset()->batch_size_ && !*end_of_sequence;
               ++i) {
            std::vector<Tensor> batch_element_tuple;
            TF_RETURN_IF_ERROR(input_impl_->GetNext(ctx, &batch_element_tuple,
                                                    end_of_sequence));
            if (!*end_of_sequence) {
              batch_elements.emplace_back(std::move(batch_element_tuple));
            } else {
              input_impl_.reset();
            }
          }
        }

        if (batch_elements.empty()) {
          DCHECK(*end_of_sequence);
          return Status::OK();
        }

        // Copy the retrieved batch elements into one output tensor
        // per tuple component.
        // NOTE(mrry): If the input or output sizes are statically
        // known, we could potentially read the input values in-place
        // into their respective slice locations. This would require a
        // different GetNext() overload that supports zero-copy, and might
        // make sense in an optimization pass.
        const size_t num_tuple_components = batch_elements[0].size();
        const int64 num_batch_elements = batch_elements.size();
        for (size_t component_index = 0; component_index < num_tuple_components;
             ++component_index) {
          const Tensor& first_element = batch_elements[0][component_index];
          TensorShape batch_component_shape({num_batch_elements});
          batch_component_shape.AppendShape(first_element.shape());
          Tensor batch_component(ctx->allocator({}), first_element.dtype(),
                                 batch_component_shape);
          // Build the output tuple component by copying one slice
          // from each input element in the batch.
          for (size_t i = 0; i < num_batch_elements; ++i) {
            if (batch_elements[i][component_index].shape() !=
                first_element.shape()) {
              return errors::InvalidArgument(
                  "Cannot batch tensors with different shapes in component ",
                  component_index, ". First element had shape ",
                  first_element.shape().DebugString(), " and element ", i,
                  " had shape ",
                  batch_elements[i][component_index].shape().DebugString(),
                  ".");
            }
            TF_RETURN_IF_ERROR(batch_util::CopyElementToSlice(
                std::move(batch_elements[i][component_index]), &batch_component,
                i));
          }
          out_tensors->emplace_back(std::move(batch_component));
        }
        *end_of_sequence = false;
        return Status::OK();
      }

     protected:
      Status SaveInternal(IteratorStateWriter* writer) override {
        mutex_lock l(mu_);
        if (!input_impl_) {
          TF_RETURN_IF_ERROR(
              writer->WriteScalar(full_name("input_impl_empty"), ""));
        } else {
          TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
        }
        return Status::OK();
      }

      Status RestoreInternal(IteratorContext* ctx,
                             IteratorStateReader* reader) override {
        mutex_lock l(mu_);
        if (!reader->Contains(full_name("input_impl_empty"))) {
          TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
        } else {
          input_impl_.reset();
        }
        return Status::OK();
      }

     private:
      mutex mu_;
      std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_);
    };

    const int64 batch_size_;
    const DatasetBase* const input_;
    std::vector<PartialTensorShape> output_shapes_;
  };
};

REGISTER_KERNEL_BUILDER(Name("BatchDataset").Device(DEVICE_CPU),
                        BatchDatasetOp);

}  // namespace

}  // namespace tensorflow


text:
alias update="bu && sudo softwareupdate -ia && nu && gu && pipu && hash -r"
### Midnight Commander with xoria
alias mc="mc -x -S xoria256.ini"
### Code dir
hash -d code=$HOME/code


text:
Usage
=====

Scribble provides an embedded LDAP server than can be started, stopped and configured as a test rule to provide a LDAP
conforming server to test your LDAP code.

The LDAP Rules use the embeddable directory service and server of the Apache Directory Project.

Rules
-----
The LDAP server can be created and configured using a builder.

### io.inkstand.scribble.rules.ldap.Directory

The Directory rule provides the directory structure that can be access via the LDAP API of the Apache Directory project
without having to connect to an LDAP server. The rule can be configured to serve pre-defined content.

To create the rule, use the following

    @Rule
    public Directory directory = Scribble.newDirectory().build();

#### Importing LDIF

To prepare the directory with content from an LDIF file, make the following call while constructing the directory.

    private final URL ldif = YourTest.class.getResource("test.ldif");

    @Rule
    public final Directory directory = Scribble.newDirectory()
                                               .withPartition("test", "cn=test")
                                               .importLdif(ldif)
                                               .build();

To import content from the LDIF, the root entry in the LDIF file must be present as a partition in the directory.
The rule itself will use in-memory partitions. Each partition must have an ID and a context DN.

You may specify only one LDIF to be imported during rule application (setup), but you may import additional LDIF files
and create additional partition from within the test or test-setup methods.

    @Before
    public void setup() throws Exception {
        directory.addPartition("test2", "cn=test2");
        directory.importLdif(ldif.openStream());
    }

#### Access Control and Anonymous Access

Per default, the directory has no access control enabled, allowing every user to modify existing entries. This suits the
most test cases fine, as the typical use case is read-only access to LDAP services. Anonymous access is allowed as well.

To change these settings, you may invoked the according methods during rule creation:

    //enable access control
    @Rule
    public final Directory directory = Scribble.newDirectory().accessControlEnabled().build();

    //disable anonymous access
    @Rule
    public final Directory directory = Scribble.newDirectory().anonymousAccessDisabled().build();

You may not change these settings once the rule is applied.

Defaults:

- Access Control is disabled
- Anonymous Access is enabled

### io.inkstand.scribble.rules.ldap.DirectoryServer

The DirectoryServer rule is a wrapper for the Directory serving it's content on a TCP port using the LDAP protocol.
It's best suited for writing tests for code that has to connect and interact directly with an LDAP server. The builder
for the rule allows to set the port and hostname.

    @Rule
    public final DirectoryServer ldapServer = Scribble.newDirectoryServer()
                                                      .onListenAddress("localhost")
                                                      .onPort(389)
                                                      .build();

Default Values:

- listen address: localhost
- port: 10389

If you are not sure, whether the default port 10389 is available on your tests server, you can instruct the rule to
select an arbitrary available port:

    @Rule
    public final DirectoryServer ldapServer = Scribble.newDirectoryServer().onAvailablePort().build();

You may retrieve the generated port using the getTcpPort() method on the rule.

#### Access to DirectoryService via API

To access the DirectoryService, i.e. for adding content to it, you may invoke

    DirectoryService directory = ldapServer.getDirectoryService();

Which will give you direct access to the Apache Directory Service API.

#### Initialization with Content

If you want to initialize the directory server with specific content, you have to configure the underlying Directory
rule first and then configure the server rule. But you can do it just in one line, for example:

    @Rule
    public final DirectoryServer ldapServer = Scribble.newDirectory()
                                                      .withPartition("test", "cn=test")
                                                      .importLdif(ldifURL)
                                                      .accessControlEnabled()
                                                      .aroundDirectoryServer()
                                                      .onAvailablePort().build();

Which will create an access-control-enabled ldap service on an available TCP port with a partition on the context
DN "cn=test" with content from an external LDIF file.

The "aroundDirectoryServer()" may seem semantically a bit odd, but the Directory rule has to be created first and then
been assigned to the server. From a JUnit RuleChain perspective the rule that has to be initialized first is wrapped
around the rule that is initialized next.

Troubleshooting
---------------

### Duplicate Schemas

When using Scribble's embedded LDAP server in the same module with the ApacheDS client API, the following error may
occur:

    Caused by: org.apache.directory.api.ldap.schema.extractor.UniqueResourceException: Problem locating LDIF file in schema repository
    Multiple copies of resource named 'schema/ou=schema/cn=apachedns/ou=syntaxes.ldif' located on classpath at urls
        jar:file:/E:/mvnrepository/org/apache/directory/api/api-ldap-schema-data/1.0.0-M31/api-ldap-schema-data-1.0.0-M31.jar!/schema/ou%3dschema/cn%3dapachedns/ou%3dsyntaxes.ldif
        jar:file:/E:/mvnrepository/org/apache/directory/server/apacheds-all/2.0.0-M20/apacheds-all-2.0.0-M20.jar!/schema/ou%3dschema/cn%3dapachedns/ou%3dsyntaxes.ldif

The reason is, that the ApacheDS server (which is a dependency of Scribble) as well was the Client API have both
the api-ldap-schema-data embedded.

So this module have to be excluded from the dependencies. Instead of using the *-all artifact, you should add the
client-api dependency instead - which is sufficient for the most cases - and exclude the schema data module
pom.xml with basic LDAP client api

    <dependency>
        <groupId>org.apache.directory.api</groupId>
        <artifactId>api-ldap-client-api</artifactId>
        <version>1.0.0-M31</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.directory.api</groupId>
                <artifactId>api-ldap-schema-data</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

At the moment, there is no way to exclude this jar from the Scribble module, as scribble uses the server's *-all
artifact.


text:
/* eslint-env mocha */
////////////////////////////////////////////////////////////////////////////////
// REQUIRES : BEGIN
////////////////////////////////////////////////////////////////////////////////

import { assert } from 'chai';

import CASTS from '../src/casts';
import { Type, CAST_ERROR } from '../src/enums';

const { STRING, STRING_NET, NUMBER, DATE, BOOLEAN, FUNCTION } = Type;

////////////////////////////////////////////////////////////////////////////////
// REQUIRES : END
////////////////////////////////////////////////////////////////////////////////

describe('casts:', function () {

  describe('STRING:', function () {

    it('should cast to string if it is possible', function () {
      assert.equal(CASTS[STRING]('string '), 'string ');
      // eslint-disable-next-line no-new-wrappers
      assert.equal(CASTS[STRING](new String('string')), 'string');
      assert.equal(CASTS[STRING](3.2), '3.2');
      assert.equal(CASTS[STRING](true), 'true');
    });

    it('should return error object if unable to cast', function () {
      assert.strictEqual(CASTS[STRING](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[STRING]({}), CAST_ERROR);
      assert.strictEqual(CASTS[STRING]([]), CAST_ERROR);
    });

  });

  describe('STRING_NET:', function () {

    it('should return undefined is string is empty or whitespace-only', function () {
      assert.equal(CASTS[STRING_NET](''), undefined);
      assert.equal(CASTS[STRING_NET](' '), undefined);
      assert.equal(CASTS[STRING_NET]('\t'), undefined);
    });

    it('should cast to string if it is possible', function () {
      assert.equal(CASTS[STRING_NET]('string '), 'string');
      // eslint-disable-next-line no-new-wrappers
      assert.equal(CASTS[STRING_NET](new String(' string')), 'string');
      assert.equal(CASTS[STRING_NET](3.2), '3.2');
      assert.equal(CASTS[STRING_NET](true), 'true');
    });

    it('should return error object if unable to cast', function () {
      assert.strictEqual(CASTS[STRING_NET](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[STRING_NET]({}), CAST_ERROR);
      assert.strictEqual(CASTS[STRING_NET]([]), CAST_ERROR);
    });

  });

  describe('NUMBER:', function () {

    it('should cast to number if it is possible', function () {
      assert.equal(CASTS[NUMBER](' 3.2 '), 3.2);
      assert.equal(CASTS[NUMBER](3.2), 3.2);
    });

    it('should return error object if unable to cast', function () {
      assert.strictEqual(CASTS[NUMBER](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[NUMBER]([]), CAST_ERROR);
      assert.strictEqual(CASTS[NUMBER]({}), CAST_ERROR);
      assert.strictEqual(CASTS[NUMBER]('fdsa32'), CAST_ERROR);
    });

  });

  describe('DATE:', function () {

    it('should cast to date if it is possible', function () {
      assert.deepEqual(CASTS[DATE](-366580080000), new Date(-366580080000));
      assert.deepEqual(CASTS[DATE](' -366580080000 '), new Date(-366580080000));
      assert.deepEqual(CASTS[DATE](' 21 May 1958 10:12 GMT+0600').getTime(),
                       new Date(-366580080000).getTime());
      assert.instanceOf(CASTS[DATE]('2112/3/23 '), Date);
    });

    it('should return error object if unable to cast', function () {
      assert.strictEqual(CASTS[DATE](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[DATE]([]), CAST_ERROR);
      assert.strictEqual(CASTS[DATE]({}), CAST_ERROR);
      assert.strictEqual(CASTS[DATE]('21May195810:12'), CAST_ERROR);
      assert.strictEqual(CASTS[DATE]('2sf2/3/23'), CAST_ERROR);
    });

  });

  describe('FUNCTION:', function () {

    it('should return value if value is a function', function () {
      const f = () => {};
      assert.strictEqual(CASTS[FUNCTION](f), f);
    });

    it('should return error object if value is not a function', function () {
      assert.strictEqual(CASTS[FUNCTION](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[FUNCTION]([]), CAST_ERROR);
      assert.strictEqual(CASTS[FUNCTION]({}), CAST_ERROR);
      assert.strictEqual(CASTS[FUNCTION]('21May195810:12'), CAST_ERROR);
      assert.strictEqual(CASTS[FUNCTION](15), CAST_ERROR);
    });

  });

  describe('BOOLEAN:', function () {

    it('should cast to boolean if it is possible', function () {
      assert.equal(CASTS[BOOLEAN](true), true);
      assert.equal(CASTS[BOOLEAN]('true'), true);
      assert.equal(CASTS[BOOLEAN](' TrUe  '), true);
      assert.equal(CASTS[BOOLEAN]('t '), true);
      assert.equal(CASTS[BOOLEAN]('1'), true);
      assert.equal(CASTS[BOOLEAN](1), true);
      assert.equal(CASTS[BOOLEAN](false), false);
      assert.equal(CASTS[BOOLEAN]('false'), false);
      assert.equal(CASTS[BOOLEAN](' fAlSe  '), false);
      assert.equal(CASTS[BOOLEAN]('f'), false);
      assert.equal(CASTS[BOOLEAN]('0'), false);
      assert.equal(CASTS[BOOLEAN](0), false);
    });

    it('should return error object if unable to cast', function () {
      assert.strictEqual(CASTS[BOOLEAN](undefined), CAST_ERROR);
      assert.strictEqual(CASTS[BOOLEAN](45), CAST_ERROR);
      assert.strictEqual(CASTS[BOOLEAN]([]), CAST_ERROR);
      assert.strictEqual(CASTS[BOOLEAN]({}), CAST_ERROR);
      assert.strictEqual(CASTS[BOOLEAN]('fdsa32'), CAST_ERROR);
    });

  });

});


text:
var express = require('express');

var app = express();

app.set('view engine', 'pug');

app.use(express.static('public'));

app.get('/', function (req, res) {
  res.render('index', { title:'Platzigram' });
})
app.get('/signup', function (req, res) {
  res.render('index', { title:'Platzigram-signup' });
})
app.get('/signin', function (req, res) {
  res.render('index', { title:'Platzigram-signin' });
})

app.listen(3000, function (err) {
  if (err) return console.log('Hubo un error'), process.exit(1);

  console.log('Platzigram escuchando en el puerto 3000');
})


text:
using System;

using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
    internal class SecP256R1FieldElement
        : ECFieldElement
    {
        public static readonly BigInteger Q = SecP256R1Curve.q;

        protected internal readonly uint[] x;

        public SecP256R1FieldElement(BigInteger x)
        {
            if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0)
                throw new ArgumentException("value invalid for SecP256R1FieldElement", "x");

            this.x = SecP256R1Field.FromBigInteger(x);
        }

        public SecP256R1FieldElement()
        {
            this.x = Nat256.Create();
        }

        protected internal SecP256R1FieldElement(uint[] x)
        {
            this.x = x;
        }

        public override bool IsZero
        {
            get { return Nat256.IsZero(x); }
        }

        public override bool IsOne
        {
            get { return Nat256.IsOne(x); }
        }

        public override bool TestBitZero()
        {
            return Nat256.GetBit(x, 0) == 1;
        }

        public override BigInteger ToBigInteger()
        {
            return Nat256.ToBigInteger(x);
        }

        public override string FieldName
        {
            get { return "SecP256R1Field"; }
        }

        public override int FieldSize
        {
            get { return Q.BitLength; }
        }

        public override ECFieldElement Add(ECFieldElement b)
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.Add(x, ((SecP256R1FieldElement)b).x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement AddOne()
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.AddOne(x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Subtract(ECFieldElement b)
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.Subtract(x, ((SecP256R1FieldElement)b).x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Multiply(ECFieldElement b)
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.Multiply(x, ((SecP256R1FieldElement)b).x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Divide(ECFieldElement b)
        {
            //return Multiply(b.Invert());
            uint[] z = Nat256.Create();
            Mod.Invert(SecP256R1Field.P, ((SecP256R1FieldElement)b).x, z);
            SecP256R1Field.Multiply(z, x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Negate()
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.Negate(x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Square()
        {
            uint[] z = Nat256.Create();
            SecP256R1Field.Square(x, z);
            return new SecP256R1FieldElement(z);
        }

        public override ECFieldElement Invert()
        {
            //return new SecP256R1FieldElement(ToBigInteger().ModInverse(Q));
            uint[] z = Nat256.Create();
            Mod.Invert(SecP256R1Field.P, x, z);
            return new SecP256R1FieldElement(z);
        }

        /**
         * return a sqrt root - the routine verifies that the calculation returns the right value - if
         * none exists it returns null.
         */
        public override ECFieldElement Sqrt()
        {
            // Raise this element to the exponent 2^254 - 2^222 + 2^190 + 2^94

            uint[] x1 = this.x;
            if (Nat256.IsZero(x1) || Nat256.IsOne(x1))
                return this;

            uint[] t1 = Nat256.Create();
            uint[] t2 = Nat256.Create();

            SecP256R1Field.Square(x1, t1);
            SecP256R1Field.Multiply(t1, x1, t1);

            SecP256R1Field.SquareN(t1, 2, t2);
            SecP256R1Field.Multiply(t2, t1, t2);

            SecP256R1Field.SquareN(t2, 4, t1);
            SecP256R1Field.Multiply(t1, t2, t1);

            SecP256R1Field.SquareN(t1, 8, t2);
            SecP256R1Field.Multiply(t2, t1, t2);

            SecP256R1Field.SquareN(t2, 16, t1);
            SecP256R1Field.Multiply(t1, t2, t1);

            SecP256R1Field.SquareN(t1, 32, t1);
            SecP256R1Field.Multiply(t1, x1, t1);

            SecP256R1Field.SquareN(t1, 96, t1);
            SecP256R1Field.Multiply(t1, x1, t1);

            SecP256R1Field.SquareN(t1, 94, t1);
            SecP256R1Field.Multiply(t1, t1, t2);

            return Nat256.Eq(x1, t2) ? new SecP256R1FieldElement(t1) : null;
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as SecP256R1FieldElement);
        }

        public override bool Equals(ECFieldElement other)
        {
            return Equals(other as SecP256R1FieldElement);
        }

        public virtual bool Equals(SecP256R1FieldElement other)
        {
            if (this == other)
                return true;
            if (null == other)
                return false;
            return Nat256.Eq(x, other.x);
        }

        public override int GetHashCode()
        {
            return Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 8);
        }
    }
}


text:
layout: category
section-type: category
title: people
---
## Category


text:
package org.eclipse.rdf4j.spin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.query.impl.MapBindingSet;
import org.eclipse.rdf4j.query.parser.ParsedBooleanQuery;
import org.eclipse.rdf4j.query.parser.ParsedGraphQuery;
import org.eclipse.rdf4j.query.parser.ParsedOperation;
import org.eclipse.rdf4j.query.parser.ParsedTupleQuery;
import org.eclipse.rdf4j.query.parser.ParsedUpdate;

import com.google.common.base.Joiner;

/**
 * Class to represent a SPIN template.
 */
public class Template {

	private final IRI IRI;

	private ParsedOperation parsedOp;

	private final List<Argument> arguments = new ArrayList<>(4);

	public Template(IRI IRI) {
		this.IRI = IRI;
	}

	public IRI getUri() {
		return IRI;
	}

	public void setParsedOperation(ParsedOperation op) {
		this.parsedOp = op;
	}

	public ParsedOperation getParsedOperation() {
		return parsedOp;
	}

	public void addArgument(Argument arg) {
		arguments.add(arg);
	}

	public List<Argument> getArguments() {
		return arguments;
	}

	public ParsedOperation call(Map<IRI, Value> argValues) throws MalformedSpinException {
		MapBindingSet args = new MapBindingSet();
		for (Argument arg : arguments) {
			IRI argPred = arg.getPredicate();
			Value argValue = argValues.get(argPred);
			if (argValue == null && !arg.isOptional()) {
				throw new MalformedSpinException("Missing value for template argument: " + argPred);
			}
			if (argValue == null) {
				argValue = arg.getDefaultValue();
			}
			if (argValue != null) {
				args.addBinding(argPred.getLocalName(), argValue);
			}
		}

		ParsedOperation callOp;
		if (parsedOp instanceof ParsedBooleanQuery) {
			callOp = new ParsedBooleanTemplate(this, args);
		} else if (parsedOp instanceof ParsedTupleQuery) {
			callOp = new ParsedTupleTemplate(this, args);
		} else if (parsedOp instanceof ParsedGraphQuery) {
			callOp = new ParsedGraphTemplate(this, args);
		} else if (parsedOp instanceof ParsedUpdate) {
			callOp = new ParsedUpdateTemplate(this, args);
		} else {
			throw new AssertionError("Unrecognised ParsedOperation: " + parsedOp.getClass());
		}
		return callOp;
	}

	@Override
	public String toString() {
		return IRI + "(" + Joiner.on(", ").join(arguments) + ")";
	}
}


text:
#ifndef LB2_SAMPLE_H_
#define LB2_SAMPLE_H_

#include <cmath>
#include <limits>

using sample_t = int16_t;  // For flexibility. May change to a float type if needed.

static_assert(std::is_integral<sample_t>::value,
        "FULL_SAMPLE_SCALE assumes sample values are of integer type");
// FIXME: Would we plan to use floats, the maximum value will be 1.0.
constexpr double FULL_SAMPLE_SCALE = std::numeric_limits<sample_t>::max() + 1;

inline double convertSampleType(sample_t s) {
    static_assert(std::numeric_limits<sample_t>::is_signed, "sample value is assumed to be signed");
    return s / FULL_SAMPLE_SCALE;
}

inline sample_t convertSampleType(double d) {
    return std::trunc(d * FULL_SAMPLE_SCALE);
}

#endif  // LB2_SAMPLE_H_


text:
package org.pentaho.runtime.test.i18n;

/**
 * Created by bryan on 8/21/15.
 */
public interface MessageGetter {
  String getMessage( String key, String... parameters );
}


text:
require 'thread'

require 'concurrent/dereferenceable'
require 'concurrent/observable'
require 'concurrent/options_parser'
require 'concurrent/utility/timeout'
require 'concurrent/logging'

module Concurrent

  # {include:file:doc/agent.md}
  #
  # @!attribute [r] timeout
  #   @return [Fixnum] the maximum number of seconds before an update is cancelled
  class Agent
    include Dereferenceable
    include Concurrent::Observable
    include Logging

    attr_reader :timeout, :task_executor, :operation_executor

    # Initialize a new Agent with the given initial value and provided options.
    #
    # @param [Object] initial the initial value
    # @param [Hash] opts the options used to define the behavior at update and deref
    #
    # @option opts [Boolean] :operation (false) when `true` will execute the future on the global
    #   operation pool (for long-running operations), when `false` will execute the future on the
    #   global task pool (for short-running tasks)
    # @option opts [object] :executor when provided will run all operations on
    #   this executor rather than the global thread pool (overrides :operation)
    #
    # @option opts [String] :dup_on_deref (false) call `#dup` before returning the data
    # @option opts [String] :freeze_on_deref (false) call `#freeze` before returning the data
    # @option opts [String] :copy_on_deref (nil) call the given `Proc` passing the internal value and
    #   returning the value returned from the proc
    def initialize(initial, opts = {})
      @value                = initial
      @rescuers             = []
      @validator            = Proc.new { |result| true }
      self.observers        = CopyOnWriteObserverSet.new
      @serialized_execution = SerializedExecution.new
      @task_executor        = OptionsParser.get_task_executor_from(opts)
      @operation_executor   = OptionsParser.get_operation_executor_from(opts)
      init_mutex
      set_deref_options(opts)
    end

    # Specifies a block operation to be performed when an update operation raises
    # an exception. Rescue blocks will be checked in order they were added. The first
    # block for which the raised exception "is-a" subclass of the given `clazz` will
    # be called. If no `clazz` is given the block will match any caught exception.
    # This behavior is intended to be identical to Ruby's `begin/rescue/end` behavior.
    # Any number of rescue handlers can be added. If no rescue handlers are added then
    # caught exceptions will be suppressed.
    #
    # @param [Exception] clazz the class of exception to catch
    # @yield the block to be called when a matching exception is caught
    # @yieldparam [StandardError] ex the caught exception
    #
    # @example
    #   score = Concurrent::Agent.new(0).
    #             rescue(NoMethodError){|ex| puts "Bam!" }.
    #             rescue(ArgumentError){|ex| puts "Pow!" }.
    #             rescue{|ex| puts "Boom!" }
    #
    #   score << proc{|current| raise ArgumentError }
    #   sleep(0.1)
    #   #=> puts "Pow!"
    def rescue(clazz = StandardError, &block)
      unless block.nil?
        mutex.synchronize do
          @rescuers << Rescuer.new(clazz, block)
        end
      end
      self
    end
    alias_method :catch, :rescue
    alias_method :on_error, :rescue

    # A block operation to be performed after every update to validate if the new
    # value is valid. If the new value is not valid then the current value is not
    # updated. If no validator is provided then all updates are considered valid.
    #
    # @yield the block to be called after every update operation to determine if
    #   the result is valid
    # @yieldparam [Object] value the result of the last update operation
    # @yieldreturn [Boolean] true if the value is valid else false
    def validate(&block)

      unless block.nil?
        begin
          mutex.lock
          @validator = block
        ensure
          mutex.unlock
        end
      end
      self
    end
    alias_method :validates, :validate
    alias_method :validate_with, :validate
    alias_method :validates_with, :validate

    # Update the current value with the result of the given block operation,
    # block should not do blocking calls, use #post_off for blocking calls
    #
    # @yield the operation to be performed with the current value in order to calculate
    #   the new value
    # @yieldparam [Object] value the current value
    # @yieldreturn [Object] the new value
    # @return [true, nil] nil when no block is given
    def post(&block)
      post_on(@task_executor, &block)
    end

    # Update the current value with the result of the given block operation,
    # block can do blocking calls
    #
    # @param [Fixnum, nil] timeout maximum number of seconds before an update is cancelled
    #
    # @yield the operation to be performed with the current value in order to calculate
    #   the new value
    # @yieldparam [Object] value the current value
    # @yieldreturn [Object] the new value
    # @return [true, nil] nil when no block is given
    def post_off(timeout = nil, &block)
      block = if timeout
                lambda { |value| Concurrent::timeout(timeout) { block.call(value) } }
              else
                block
              end
      post_on(@operation_executor, &block)
    end

    # Update the current value with the result of the given block operation,
    # block should not do blocking calls, use #post_off for blocking calls
    #
    # @yield the operation to be performed with the current value in order to calculate
    #   the new value
    # @yieldparam [Object] value the current value
    # @yieldreturn [Object] the new value
    def <<(block)
      post(&block)
      self
    end

    # Waits/blocks until all the updates sent before this call are done.
    #
    # @param [Numeric] timeout the maximum time in second to wait.
    # @return [Boolean] false on timeout, true otherwise
    def await(timeout = nil)
      done = Event.new
      post { |val| done.set; val }
      done.wait timeout
    end

    private

    def post_on(executor, &block)
      return nil if block.nil?
      @serialized_execution.post(executor) { work(&block) }
      true
    end

    # @!visibility private
    Rescuer = Struct.new(:clazz, :block) # :nodoc:

    # @!visibility private
    def try_rescue(ex) # :nodoc:
      rescuer = mutex.synchronize do
        @rescuers.find { |r| ex.is_a?(r.clazz) }
      end
      rescuer.block.call(ex) if rescuer
    rescue Exception => ex
      # suppress
      log DEBUG, ex
    end

    # @!visibility private
    def work(&handler) # :nodoc:
      validator, value = mutex.synchronize { [@validator, @value] }

      begin
        result = handler.call(value)
        valid  = validator.call(result)
      rescue Exception => ex
        exception = ex
      end

      begin
        mutex.lock
        should_notify = if !exception && valid
                          @value = result
                          true
                        end
      ensure
        mutex.unlock
      end

      if should_notify
        time = Time.now
        observers.notify_observers { [time, self.value] }
      end

      try_rescue(exception)
    end
  end
end


text:
Entriy to [One hour game jam](http://onehourgamejam.com/).
[Profile link](http://onehourgamejam.com/?page=author&author=carlmartus).

## #99 (Wind) - "Tornado surfer"
![Tornado surfer](99/logo.png)

A tornado has appeared! Time to show what a bad ass you are! Dust off your
skateboard and start riding up in the tornado. Just make sure you don't hit any
of the debries flying around in there. The longer you last in there, the more
score you get.

CONTROLS: Left/Right - Steer

 * [Play in browser](http://martus.se/onehourgamejam/99/wind.html)
 * [Source code](99/)


text:
@interface MediaFullScreenViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) Media *media;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) UITapGestureRecognizer *doubleTap;

@end

@implementation MediaFullScreenViewController

- (void) viewDidLoad {
    [super viewDidLoad];

    self.scrollView = [UIScrollView new];
    self.scrollView.delegate = self;
    self.scrollView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.scrollView];

    self.imageView = [UIImageView new];
    self.imageView.image = self.media.image;

    [self.scrollView addSubview:self.imageView];

    self.scrollView.contentSize = self.media.image.size;

    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFired:)];

    self.doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapFired:)];
    self.doubleTap.numberOfTapsRequired = 2;

    [self.tap requireGestureRecognizerToFail:self.doubleTap];

    [self.scrollView addGestureRecognizer:self.tap];
    [self.scrollView addGestureRecognizer:self.doubleTap];
}

- (void) viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    self.scrollView.frame = self.view.bounds;

    CGSize scrollViewFrameSize = self.scrollView.frame.size;
    CGSize scrollViewContentSize = self.scrollView.contentSize;

    CGFloat scaleWidth = scrollViewFrameSize.width / scrollViewContentSize.width;
    CGFloat scaleHeight = scrollViewFrameSize.height / scrollViewContentSize.height;
    CGFloat minScale = MIN(scaleWidth, scaleHeight);

    self.scrollView.minimumZoomScale = minScale;
    self.scrollView.maximumZoomScale = 1;
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self centerScrollView];
}

- (instancetype) initWithMedia:(Media *)media {
    self = [super init];

    if (self) {
        self.media = media;
    }

    return self;
}

- (void) centerScrollView {
    [self.imageView sizeToFit];

    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect contentsFrame = self.imageView.frame;

    if (contentsFrame.size.width < boundsSize.width) {
        contentsFrame.origin.x = (boundsSize.width - CGRectGetWidth(contentsFrame)) / 2;
    } else {
        contentsFrame.origin.x = 0;
    }

    if (contentsFrame.size.height < boundsSize.height) {
        contentsFrame.origin.y = (boundsSize.height - CGRectGetHeight(contentsFrame)) / 2;
    } else {
        contentsFrame.origin.y = 0;
    }

    self.imageView.frame = contentsFrame;
}

#pragma mark - UIScrollViewDelegate

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

- (void) scrollViewDidZoom:(UIScrollView *)scrollView {
    [self centerScrollView];
}

#pragma mark - Gesture Recognizers

- (void) tapFired:(UITapGestureRecognizer *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) doubleTapFired:(UITapGestureRecognizer *)sender {
    if (self.scrollView.zoomScale == self.scrollView.minimumZoomScale) {
        // #8
        CGPoint locationPoint = [sender locationInView:self.imageView];

        CGSize scrollViewSize = self.scrollView.bounds.size;

        CGFloat width = scrollViewSize.width / self.scrollView.maximumZoomScale;
        CGFloat height = scrollViewSize.height / self.scrollView.maximumZoomScale;
        CGFloat x = locationPoint.x - (width / 2);
        CGFloat y = locationPoint.y - (height / 2);

        [self.scrollView zoomToRect:CGRectMake(x, y, width, height) animated:YES];
    } else {
        // #9
        [self.scrollView setZoomScale:self.scrollView.minimumZoomScale animated:YES];
    }
}

@end


text:
namespace google {
namespace jwt_verify {

StructUtils::StructUtils(const ::google::protobuf::Struct& struct_pb)
    : struct_pb_(struct_pb) {}

StructUtils::FindResult StructUtils::GetString(const std::string& name,
                                               std::string* str_value) {
  const ::google::protobuf::Value* found;
  FindResult result = GetValue(name, found);
  if (result != OK) {
    return result;
  }
  if (found->kind_case() != google::protobuf::Value::kStringValue) {
    return WRONG_TYPE;
  }
  *str_value = found->string_value();
  return OK;
}

StructUtils::FindResult StructUtils::GetDouble(const std::string& name,
                                               double* double_value) {
  const ::google::protobuf::Value* found;
  FindResult result = GetValue(name, found);
  if (result != OK) {
    return result;
  }
  if (found->kind_case() != google::protobuf::Value::kNumberValue) {
    return WRONG_TYPE;
  }
  *double_value = found->number_value();
  return OK;
}

StructUtils::FindResult StructUtils::GetUInt64(const std::string& name,
                                               uint64_t* int_value) {
  double double_value;
  FindResult result = GetDouble(name, &double_value);
  if (result != OK) {
    return result;
  }
  if (double_value < 0 ||
      double_value >=
          static_cast<double>(std::numeric_limits<uint64_t>::max())) {
    return OUT_OF_RANGE;
  }
  *int_value = static_cast<uint64_t>(double_value);
  return OK;
}

StructUtils::FindResult StructUtils::GetBoolean(const std::string& name,
                                                bool* bool_value) {
  const ::google::protobuf::Value* found;
  FindResult result = GetValue(name, found);
  if (result != OK) {
    return result;
  }
  if (found->kind_case() != google::protobuf::Value::kBoolValue) {
    return WRONG_TYPE;
  }
  *bool_value = found->bool_value();
  return OK;
}

StructUtils::FindResult StructUtils::GetStringList(
    const std::string& name, std::vector<std::string>* list) {
  const ::google::protobuf::Value* found;
  FindResult result = GetValue(name, found);
  if (result != OK) {
    return result;
  }
  if (found->kind_case() == google::protobuf::Value::kStringValue) {
    list->push_back(found->string_value());
    return OK;
  }
  if (found->kind_case() == google::protobuf::Value::kListValue) {
    for (const auto& v : found->list_value().values()) {
      if (v.kind_case() != google::protobuf::Value::kStringValue) {
        return WRONG_TYPE;
      }
      list->push_back(v.string_value());
    }
    return OK;
  }
  return WRONG_TYPE;
}

StructUtils::FindResult StructUtils::GetValue(
    const std::string& nested_names, const google::protobuf::Value*& found) {
  const std::vector<absl::string_view> name_vector =
      absl::StrSplit(nested_names, '.');

  const google::protobuf::Struct* current_struct = &struct_pb_;
  for (int i = 0; i < name_vector.size(); ++i) {
    const auto& fields = current_struct->fields();
    const auto it = fields.find(std::string(name_vector[i]));
    if (it == fields.end()) {
      return MISSING;
    }
    if (i == name_vector.size() - 1) {
      found = &it->second;
      return OK;
    }
    if (it->second.kind_case() != google::protobuf::Value::kStructValue) {
      return WRONG_TYPE;
    }
    current_struct = &it->second.struct_value();
  }
  return MISSING;
}

}  // namespace jwt_verify
}  // namespace google


text:
package com.strategicgains.repoexpress.adapter;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.strategicgains.repoexpress.domain.Identifier;
import com.strategicgains.repoexpress.exception.InvalidObjectIdException;

/**
 * @author toddf
 * @since Oct 25, 2011
 */
public class StringToIntegerIdAdapterTest
{
	@Test(expected=InvalidObjectIdException.class)
	public void shouldThrowExceptionOnInvalidId()
	{
		Identifiers.INTEGER.parse("invalid");
	}

	@Test(expected=InvalidObjectIdException.class)
	public void shouldHandleNull()
	{
		Identifiers.INTEGER.parse(null);
	}

	@Test
	public void shouldParseIdentifier()
	{
		String stringValue = "655";
		Identifier objectId = Identifiers.INTEGER.parse(stringValue);
		Identifier expected = new Identifier(Integer.valueOf(stringValue));
		assertEquals(expected, objectId);
		assertEquals(stringValue, Identifiers.INTEGER.format(objectId));
	}
}


text:
HMPUTILS ;SLC/AGP,ASMR/ASF,JC-HMP utilities ;Jan 20, 2017 17:18:18
 ;;2.0;ENTERPRISE HEALTH MANAGEMENT PLATFORM;**1,2,3**;Sep 01, 2011;Build 15
 ;Per VA Directive 6402, this routine should not be modified.
 ;
 Q  ; no entry from top
 ;DE6644, 7 September 2016, updated comments, corrected variables in stack, optimized code
 ;
 ; integration agreements:
 ;
 ; External References          DBIA#
 ; -------------------          -----
 ; XLFCRC                        3156
 ; XLFDT                        10103
 ; XLFUTL                        2622
 ; XUPARAM                       2541
 ;
 ;
 ;
CHKSP(HMPFHMP) ; ^XTMP check before patient subscription starts to cache   *BEGIN*S68-PJH
 ; HMPFHMP - server name
 N HMPOK S HMPOK=0
 F  D  Q:HMPOK
 . I $$GETMAX>$$GETSIZE("estimate",HMPFHMP) S HMPOK=1 D STATUS^HMPMETA(HMPOK,HMPFHMP) Q  ; set DISK USAGE STATUS to 'WITHIN LIMIT' and continue, US8228
 . D STATUS^HMPMETA(HMPOK,HMPFHMP) H $$GETSECS^HMPDJFSP  ; DISK USAGE STATUS is 'EXCEEDED LIMIT' and wait, US8228
 Q  ;  *END*S68-PJH
 ;
SETERROR(RESULT,ERROR,EXTERROR,DATA) ; -- error text for JSON
 N CNT,TEMP,HMPTEMP,XCNT
 S HMPTEMP="HMPXTEMP ERRORS"
 I '$D(^XTMP(HMPTEMP,0)) S ^XTMP(HMPTEMP,0)=$$FMADD^XLFDT(DT,7)_U_DT_U_"HMP ERROR GLOBAL"
 S RESULT("success")="false"
 I $D(DATA) S XCNT=$O(^XTMP(HMPTEMP,""),-1)+1 M ^XTMP(HMPTEMP,XCNT,"ERROR")=DATA
 I $D(ERROR) D SETERRTX(.TEMP,.ERROR) S RESULT("error","code")=TEMP
 I +$G(XCNT)>0 S RESULT("error","code")=$G(RESULT("error","code"))_" See ^XTMP("_HMPTEMP_","_XCNT_",DATA) for data"
 I $D(EXTERROR) D SETERRTX(.TEMP,.EXTERROR) I TEMP'="" S RESULT("error","message")=TEMP
 ;
 Q
 ;
SETERRTX(TEMP,ERROR) ; concatenate errors from ERROR array, put CR, LF between them
 S TEMP="",CNT=0  ; CNT, TEMP from SETERROR
 F  S CNT=$O(ERROR(CNT)) Q:CNT'>0  S TEMP=$S(TEMP'="":TEMP=TEMP_$C(13,10)_ERROR(CNT),1:ERROR(CNT))
 Q
 ;
 ;
SETTEXT(X,VALUE) ; -- format word processing text
 N FIRST,I,LINE
 S FIRST=1
 S I=0 F  S I=$O(@X@(I)) Q:I<1  D
 .S LINE=$S($D(@X@(I,0)):@X@(I,0),1:@X@(I))
 .; FIRST=1 S @VALUE@(I)=LINE,FIRST=0 Q
 .S @VALUE@(I)=LINE_$C(13)_$C(10)
 Q
 ;
 ;
SPLITVAL(NODE,ARRAY) ; -- split a value into a list
 N CNT,NAME,VALUE,FIELD
 S NAME="" F  S NAME=$O(ARRAY(NAME)) Q:NAME=""  D
 .S CNT=+ARRAY(NAME)
 .S VALUE=$P($G(NODE),U,CNT)
 .I NAME="Code" S FIELD=$P(ARRAY(NAME),U,2) S VALUE=$$SETVURN(FIELD,VALUE)
 .S ARRAY(NAME)=VALUE
 Q
 ;
 ;
SETPROV(NODE,PROV) ; -- providers
 S PROV("providerUid")=$$SETUID("user",,+NODE),PROV("providerName")=$P(NODE,U,2) Q
 ;
SETUID(DOMAIN,PAT,ID,ADDDATA) ; function, UID string
 N RESULT,SYS
 S SYS=$S($D(HMPSYS):HMPSYS,1:$$SYS^HMPUTILS)
 S RESULT="urn:va:"_DOMAIN_":"_SYS_":"_$S($G(PAT):PAT_":",1:"")_ID
 I $L($G(ADDDATA)) S RESULT=RESULT_":"_ADDDATA
 Q RESULT
 ;
 ;
SETFCURN(DOMAIN,FACILITY,VALUE) ; function, create facility URN
 Q "urn:va:"_DOMAIN_":"_FACILITY_":"_VALUE
 ;
 ;
SETVURN(DOMAIN,VALUE) ; function, create VA urn
 Q "urn:va:"_DOMAIN_":"_VALUE
 ;
SYS(NAME) ; -- return hashed system name from HMP SYSTEM NAME parameter, or calculate from NAME parameter if it exists
 ; DE4463 4/22/2016 CK - changed HMP routines to all call this function
 ;  SYS^HMPUTILS returns a 4 digit hashed site, padded with leading zeros
 N SYS
 S SYS=$$GET^XPAR("SYS","HMP SYSTEM NAME")
 I '$L($G(NAME)),'$L(SYS) Q $$SYS($$KSP^XUPARAM("WHERE"))       ; r2.0 install workaround: if no parameter AND no HMP SYSTEM NAME, then calculate and return using domain name
 I '$L($G(NAME)) Q SYS                                        ; else return HMP SYSTEM NAME parameter
 Q $TR($J($$BASE^XLFUTL($$CRC16^XLFCRC(NAME),10,16),4)," ",0) ; else calculate from parameter
 ;
 ;
SETNCS(CODESET,VALUE) ; -- create national codeset URN
 Q "urn:"_CODESET_":"_VALUE
 ;
JSONDT(X) ; function, convert FileMan date-time to HL7 date-time for JSON
 N HL7DT,T,Y
 ;DE3116, 12 April 2016 function updated to handle FM date problems
 ; T indicates that a time was included
 S T=0 I $E(X,8)=".",$E(X,6,7) S T=1  ; if there's a time it must be a precise date
 S Y=$S(T:X,1:X\1)  ; strip time if imprecise date
 I T,($E(Y,9,10)>23)!($E(Y,11,12)>59)!($E(Y,13,14)>59) S Y=$$FMADD^XLFDT(Y,0,0,0,0) ;DE3116 ASF 04/09/16 allows for hrs >24 and mins >60
 S HL7DT=$$FMTHL7^HMPSTMP(Y)  ; DE5016
 S:T HL7DT=$E(HL7DT_"000000",1,14)  ; if time passed, result must be 14 chars.
 Q HL7DT
 ;
 ;
FACILITY(X,Y) ; -- add facility info to array for JSON
 ;  X=STATION NUMBER^STATION NAME
 ;  Y=Variable array name
 ; >D FACILITY^HMPUTILS("500^CAMP MASTER","LAB")
 ;
 S @Y@("facilityCode")=$P(X,"^")
 S @Y@("facilityName")=$P(X,"^",2)
 Q
 ;
 ;
VERSRV()   ; function, Return server version of option name
 N HMPLST,VAL
 D FIND^DIC(19,"",1,"X","HMP UI CONTEXT",1,,,,"HMPLST")
 S VAL=$G(HMPLST("DILIST","ID",1,1))
 Q $$UP^XLFSTR($P(VAL,"version ",2))
 ;
 ;
VERCMP(CUR,VAL) ; Returns 1 if CUR<VAL, -1 if CUR>VAL, 0 if equal
 N CURMAJOR,CURMINOR,CURSNAP,VALMAJOR,VALMINOR,VALSNAP
 S CURMAJOR=$P(CUR,"-"),CURMINOR=$P(CUR,"-",2),CURSNAP=$E($P(CUR,"-",3),1,4)="SNAP"
 S VALMAJOR=$P(VAL,"-"),VALMINOR=$P(VAL,"-",2),VALSNAP=$E($P(VAL,"-",3),1,4)="SNAP"
 I $E(VALMINOR)="P" S VALMINOR=$E(VALMINOR,2,99)     ; "P"ilot versions (old)
 I $E(CURMINOR)="P" S CURMINOR=$E(VALMINOR,2,99)
 I $E(VALMINOR)="S" S VALMINOR=$E(VALMINOR,2,99)*10  ; "S"print versions
 I $E(CURMINOR)="S" S CURMINOR=$E(CURMINOR,2,99)*10
 Q:VALMAJOR>CURMAJOR 1   Q:VALMAJOR<CURMAJOR -1  ; compare major versions
 Q:VALMINOR>CURMINOR 1   Q:VALMINOR<CURMINOR -1  ; compare minor versions
 Q:(CURSNAP&'VALSNAP) 1  Q:(VALSNAP&'CURSNAP) -1 ; "SNAPSHOT" < released
 Q 0
 ;
 ;
WDWH() ; What kind of data exist?, DE6644, 7 September 2016
 ; HMPA   = loop counter
 ; HMPB   = node information
 ; HMPOPD = 1 if operational data exists, 0 otherwise
 ; HMPPAT = 1 if patient data exist, 0 otherwise
 ; HMPRET = return variable - 0 if no data exist
 ;                            1 if ONLY patient data exist
 ;                            2 if ONLY operational data exist
 ;                            3 if BOTH patient and operational data exist
 N HMPA,HMPB,HMPOPD,HMPPAT,HMPRET
 S (HMPOPD,HMPPAT,HMPRET)=0,HMPA="HMPFX"
 ; iterate through HMP* data only
 F  S HMPA=$O(^XTMP(HMPA)) Q:'($E(HMPA,1,3)="HMP")  D  Q:HMPOD&HMPPAT  ; no need to continue if both flags set
 . S HMPB=$P(HMPA,"~",3) I HMPB="OPD" S HMPOPD=1 Q  ; operational data
 . S:HMPB=+HMPB HMPPAT=1  ; patient data
 I HMPPAT,'HMPOPD S HMPRET=1  ; ONLY patient data
 I 'HMPPAT,HMPOPD S HMPRET=2  ; ONLY operational data
 I HMPPAT,HMPOPD S HMPRET=3   ; patient & operational data
 Q HMPRET
 ;
NODATA(A) ; boolean function, is there any patient data for stream in A?; JD - 2/23/15
 ; Returns 1 if there is no patient data, 0 Otherwise, DE6644, 7 September 2016
 ; HMPA = Loop counter
 ; HMPF = Flag indicating data found
 N HMPA,HMPF
 S HMPF=0,HMPA=""
 F  S HMPA=$O(^XTMP(A,0,"count",HMPA)) Q:HMPF!(HMPA="")  S:+$G(^XTMP(A,0,"count",HMPA))>0 HMPF=1
 Q 'HMPF  ; return opposite of flag
 ;
GETSIZE(HMPMODE,HMPSRVN) ; function, returns aggregate extract size for extracts waiting to be sent to HMP servers
 ; returns: total size ^ object count
 ; HMPMODE = estimate - use estimated domain average sizes (default)
 ;           actual - walk though object nodes to calculate using $LENGTH
 ; HMPSRVN = name of HMP server [optional - defaults to all HMP servers]
 ; DE7401, move function here, 20 January 2017
 ; loop through extracts for server(s)
 N BATCH,DOMAIN,L,OBJCNT,OBJS,OBJSIZES,ROOT,TASK,TOTAL
 S HMPMODE=$G(HMPMODE,"estimate")  ; default to estimate
 S:'("^estimate^actual^")[U_HMPMODE_U HMPMODE="estimate"  ; valid mode check
 I HMPMODE="estimate" D GETLST^XPAR(.OBJSIZES,"PKG","HMP DOMAIN SIZES","I")  ; domain sizes needed for estimate
 ; object counter, total, root node, batch to check, L is length of ROOT for loop exit
 S (OBJCNT,TOTAL)=0,ROOT="HMPFX~"_$S($G(HMPSRVN)]"":HMPSRVN_"~",1:""),BATCH=ROOT,L=$L(ROOT)
 F  S BATCH=$O(^XTMP(BATCH)) Q:$E(BATCH,1,L)'=ROOT  D
 . S TASK=0 F  S TASK=$O(^XTMP(BATCH,TASK)) Q:'TASK  S DOMAIN="" F  S DOMAIN=$O(^XTMP(BATCH,TASK,DOMAIN)) Q:DOMAIN=""  D
 ..  S OBJS=+$O(^XTMP(BATCH,TASK,DOMAIN," "),-1),OBJCNT=OBJCNT+OBJS
 ..  I HMPMODE="estimate" S TOTAL=TOTAL+(OBJS*$G(OBJSIZES($P(DOMAIN,"#")),1000)) Q  ; use domain sizes for estimate & quit
 ..  S TOTAL=TOTAL+$$WALK(BATCH,TASK,DOMAIN)  ; fall through for actual
 Q TOTAL_"^"_OBJCNT
 ;
WALK(BATCH,TASK,DOMAIN) ; function, walk through domain objects in task to get actual size
 N NODE,OBJ,SIZE
 S (OBJ,SIZE)=0
 F  S OBJ=$O(^XTMP(BATCH,TASK,DOMAIN,OBJ)) Q:'OBJ  D
 . S NODE=0 F  S NODE=$O(^XTMP(BATCH,TASK,DOMAIN,OBJ,NODE)) Q:'NODE  S SIZE=SIZE+$L(^(NODE))
 Q SIZE  ; return size in bytes
 ;
GETMAX() ; function, return the max allowable aggregate extract size in bytes
 ;
 N HMPLIM S HMPLIM=$$GET^XPAR("SYS","HMP EXTRACT DISK SIZE LIMIT")*1000000
 Q $S(HMPLIM>999999:HMPLIM,1:20000000)  ; if not set to 1 million minimum, return 20mb characters
 ;


text:
package org.mvel2.ast;

import org.mvel2.compiler.ExecutableStatement;
import org.mvel2.integration.VariableResolverFactory;

/**
 * @author Christopher Brock
 */
public class IndexedDeclTypedVarNode extends ASTNode implements Assignment {
    private int register;

    public IndexedDeclTypedVarNode(int register, Class type) {
        this.egressType = type;
        this.register = register;
    }

    public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
        factory.createIndexedVariable(register, null, egressType);
        return ctx;
    }

    public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
        factory.createIndexedVariable(register, null, egressType);
        return null;
    }

    public String getAssignmentVar() {
        return null;
    }

    public char[] getExpression() {
        return new char[0];
    }

    public boolean isAssignment() {
        return true;
    }

    public boolean isNewDeclaration() {
        return true;
    }

    public void setValueStatement(ExecutableStatement stmt) {
        throw new RuntimeException("illegal operation");
    }
}