text:
function varargout = persubjectglms(mdm, opts)
% persubjectglms  - compute one GLM per subject
%
% FORMAT:       [glm1, glm2] = persubjectglms(mdm [, opts])
%
% Input fields:
%
%       mdm         MDM object (or filename) with at least 3 subjects
%       opts        optional settings
%        .cmbffx    combine outputs to one FFX GLM (default: true)
%        .cmbrfx    combine outputs to one RFX GLM (default: false)
%        .loadglms  load existing per-subject GLMs (default: false)
%        .outpatt   outfile pattern, default: '%M_%S_FFX.glm'
%        .subsel    subject selection (cell array with IDs)
%
% Output fields:
%
%       glm1, glm2  combined GLMs (order is FFX first if both are used)
%
% Note: additionally all fields to MDM::ComputeGLM are supported in opts.

% Version:  v0.9d
% Build:    14061709
% Date:     Jun-17 2014, 9:51 AM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

% Copyright (c) 2011, 2014, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% argument check
if nargin < 1 || ...
    isempty(mdm) || ...
   (~ischar(mdm) && ...
    (numel(mdm) ~= 1 || ...
     ~isxff(mdm, 'mdm')))
    error( ...
        'neuroelf:BadArgument', ...
        'Bad or missing argument.' ...
    );
end
if ischar(mdm)
    mdmf = mdm(:)';
    mdm = [];
else
    mdmf = '';
end
if nargin < 2 || ...
   ~isstruct(opts) || ...
    numel(opts) ~= 1
    opts = struct;
end
if isfield(opts, 'cmbrfx') && ...
   ~isfield(opts, 'cmbffx') && ...
    islogical(opts.cmbrfx) && ...
    numel(opts.cmbrfx) == 1 && ...
    opts.cmbrfx
    opts.cmbffx = false;
end
if ~isfield(opts, 'cmbffx') || ...
   ~islogical(opts.cmbffx) || ...
    numel(opts.cmbffx) ~= 1
    opts.cmbffx = true;
end
if ~isfield(opts, 'cmbrfx') || ...
   ~islogical(opts.cmbrfx) || ...
    numel(opts.cmbrfx) ~= 1
    opts.cmbrfx = false;
end
if ~isfield(opts, 'loadglms') || ...
   ~islogical(opts.loadglms) || ...
    numel(opts.loadglms) ~= 1
    opts.loadglms = false;
end
if ~isfield(opts, 'outpatt') || ...
   ~ischar(opts.outpatt)
    opts.outpatt = '%M_%S_FFX.glm';
elseif numel(opts.outpatt) < 6 || ...
    isempty(strfind(opts.outpatt(:)', '%S')) || ...
   ~strcmpi(lsqueeze(opts.outpatt(end-3:end))', '.glm') || ...
    sum(opts.outpatt(:)' == '%') > 2
    error( ...
        'neuroelf:BadArgument', ...
        'Invalid output filename pattern.' ...
    );
end
opts.outpatt = opts.outpatt(:)';
if ~isfield(opts, 'subsel') || ...
   ~iscell(opts.subsel) || ...
    isempty(opts.subsel) || ...
   ~ischar(opts.subsel{1}) || ...
    isempty(opts.subsel{1})
    opts.subsel = [];
end

% load MDM
if ~isempty(mdmf)
    try
        mdm = xff(mdmf);
        if ~isxff(mdm, 'mdm')
            error( ...
                'neuroelf:BadArgument', ...
                'Not an MDM file: %s.', ...
                mdmf ...
            );
        end
    catch ne_eo;
        if isxff(mdm)
            mdm.ClearObject;
        end
        rethrow(ne_eo);
    end
end
mdmc = getcont(mdm);

% patch pattern again
if ~isempty(strfind(opts.outpatt, '%M'))
    [mdmfp, mdmfn] = fileparts(mdm.FilenameOnDisk);
    if isempty(mdmfn)
        mdmfn = 'UNSAVED';
    elseif ~isempty(mdmfp)
        mdmfn = strrep(strrep([mdmfp '/' mdmfn], '\', '/'), '//', '/');
    end
    opts.outpatt = strrep(opts.outpatt, '%M', mdmfn);
    if sum(opts.outpatt == '%') ~= 1
        if ~isempty(mdmf)
            mdm.ClearObject;
        else
            setcont(mdm, mdmc);
        end
        error( ...
            'neuroelf:BadArgument', ...
            'Invalid output filename pattern.' ...
        );
    end
end

% subject selection
fsids = mdm.Subjects(true);
if ~isempty(opts.subsel)
    ksubs = (multimatch(fsids, opts.subsel(:)) > 0);
    if isfield(opts, 'motpars') && ...
        iscell(opts.motpars) && ...
        numel(opts.motpars) == size(mdm.XTC_RTC, 1)
        mdm.RunTimeVars.MotionParameters = lsqueeze(opts.motpars(ksubs));
        opts.motpars = true;
    elseif isfield(mdm.RunTimeVars, 'MotionParameters') && ...
        iscell(mdm.RunTimeVars.MotionParameters) && ...
        numel(mdm.RunTimeVars.MotionParameters) == size(mdm.XTC_RTC, 1)
        mdm.RunTimeVars.MotionParameters = ...
            lsqueeze(mdm.RunTimeVars.MotionParameters(ksubs));
    end
    mdm.XTC_RTC = mdm.XTC_RTC(ksubs, :);
    fsids = mdm.Subjects(true);
elseif isfield(opts, 'motpars') && ...
    iscell(opts.motpars) && ...
    numel(opts.motpars) == size(mdm.XTC_RTC, 1)
    mdm.RunTimeVars.MotionParameters = opts.motpars(:);
    opts.motpars = true;
end

% find subject IDs
sids = mdm.Subjects;
if numel(sids) < 3
    if ~isempty(mdmf)
        mdm.ClearObject;
    else
        setcont(mdm, mdmc);
    end
    error( ...
        'neuroelf:BadArgument', ...
        'MDM requires at least 3 subjects.' ...
    );
end

% settings
mdm.RFX_GLM = 0;
mdm.SeparatePredictors = 2;
mdm.NrOfStudies = size(mdm.XTC_RTC, 1);
nstudy = mdm.NrOfStudies;

% iterate over subjects
glms = cell(numel(sids), 1);
for sc = 1:numel(sids)

    % load only
    if opts.loadglms
        glms{sc} = strrep(opts.outpatt, '%S', sids{sc});
        if exist(glms{sc}, 'file') ~= 2
            if ~isempty(mdmf)
                mdm.ClearObject;
            else
                setcont(mdm, mdmc);
            end
            error( ...
                'neuroelf:BadArgument', ...
                'Cannot load GLM for subject %s.', ...
                sids{sc} ...
            );
        end
        continue;
    end

    % make a copy
    smdm = mdm.CopyObject;

    % match ID to list
    sidx = find(strcmpi(fsids, sids{sc}));

    % keep those entries
    smdm.XTC_RTC = mdm.XTC_RTC(sidx, :);
    if isfield(mdm.RunTimeVars, 'MotionParameters') && ...
        numel(mdm.RunTimeVars.MotionParameters) == nstudy
        smdm.RunTimeVars.MotionParameters = mdm.RunTimeVars.MotionParameters(sidx);
    end

    % compute and save GLM
    try
        glm = [];
        glm = smdm.ComputeGLM(opts);
        glm.SaveAs(strrep(opts.outpatt, '%S', sids{sc}));
        glm.SaveRunTimeVars;
        glms{sc} = glm.FilenameOnDisk;
        glm.ClearObject;
        smdm.ClearObject;
    catch ne_eo;
        if isxff(glm)
            glm.ClearObject;
        end
        smdm.ClearObject;
        if ~isempty(mdmf)
            mdm.ClearObject;
        else
            setcont(mdm, mdmc);
        end
        rethrow(ne_eo);
    end
end

% combine GLMs
if opts.cmbffx || ...
    opts.cmbrfx

    % load GLMs (with transio)
    for sc = 1:numel(glms)
        try
            glms{sc} = xff(glms{sc}, 't');
            if ~isxff(glms{sc}, 'glm') || ...
                glms{sc}.ProjectTypeRFX > 0
                error( ...
                    'neuroelf:BadGLMFile', ...
                    'Bad GLM file for subject %s.', ...
                    sids{sc} ...
                );
            end
            if opts.cmbffx && ...
                isfield(glms{sc}, 'SubjectSPMsn') && ...
                isstruct(glms{sc}.SubjectSPMsn) && ...
                numel(glms{sc}.SubjectSPMsn) == 1 && ...
               ~isempty(fieldnames(glms{sc}.SubjectSPMsn))
                error( ...
                    'neuroelf:BadCombination', ...
                    'Subject-GLMs with SPM-normalization cannot be FFX-combined.' ...
                );
            end
        catch ne_eo;
            clearxffobjects(glms);
            if ~isempty(mdmf)
                mdm.ClearObject;
            else
                setcont(mdm, mdmc);
            end
            rethrow(ne_eo);
        end
    end
end

% RFX
nss = numel(glms);
if opts.cmbrfx

    % try/catch
    try

        % make a copy of the first GLM
        rfx = bless(glms{1}.CopyObject, 1);

        % collect some data
        nrtp = 0;
        nrct = 0;
        nrcf = 0;
        msk = zeros(size(glms{1}.GLMData.MCorrSS));
        sts = cell(1, nss);
        prs = glms{1}.Predictor;
        pns = lsqueeze({prs(1:(glms{1}.NrOfPredictors - glms{1}.NrOfConfounds)).Name2});
        pns = regexprep(pns, '^Subject\s+(\w+)\:\s*', '');
        pnc = zeros(12, 0);
        for sc = 1:nss
            nrtp = nrtp + glms{sc}.NrOfTimePoints;
            nrct = nrct + glms{sc}.NrOfConfounds;
            nrcf = nrcf + numel(glms{sc}.NrOfConfoundsPerStudy);
            sts{sc} = glms{sc}.Study;
            prs = glms{sc}.Predictor;
            pnn = lsqueeze({prs(1:(glms{sc}.NrOfPredictors - glms{sc}.NrOfConfounds)).Name2});
            pnn = regexprep(pnn, '^Subject\s+(\w+)\:\s*', '');
            pns = uunion(pns, pnn);
            if size(pnc, 2) < numel(pns)
                for pc = (size(pnc, 2)+1):numel(pns)
                    pnc(:, pc) = prs(findfirst(strcmp(pnn, pns{pc}))).RGB(:);
                end
            end
            msk = msk + double(glms{sc}.GLMData.MCorrSS > 0);
        end
        sts = catstruct(sts{:});
        msk = (msk >= (0.75 * nss));
        ntp = (numel(pns) + 1) * nss;
        rfxspmsn = struct;
        rfxtrfpl = struct;

        % restructure
        rfx.ProjectTypeRFX = 1;
        rfx.NrOfSubjects = nss;
        rfx.NrOfSubjectPredictors = numel(pns) + 1;
        rfx.NrOfTimePoints = nrtp;
        rfx.NrOfPredictors = ntp;
        rfx.NrOfConfounds = nrct;
        rfx.NrOfStudies = numel(sts);
        rfx.NrOfStudiesWithConfounds = nrcf;
        rfx.NrOfConfoundsPerStudy = zeros(1, nrcf);
        rfx.SeparatePredictors = 2;
        rfx.NrOfVoxelsForBonfCorrection = sum(msk(:));
        rfx.CortexBasedStatisticsMaskFile = '';
        rfx.Study = sts;
        rfxPredictor = rfx.Predictor;
        rfxPredictor(ntp).Name1 = '';
        rfxPredictor = rfxPredictor(:);
        rfx.DesignMatrix = [];
        rfx.iXX = [];
        rfxGLMData.MultipleRegressionR = [];
        rfxGLMData.MCorrSS = [];
        rfxGLMData.BetaMaps = [];
        rfxGLMData.XY = [];
        rfxGLMData.TimeCourseMean = [];
        rfxGLMData.RFXGlobalMap = single(msk);
        rfxGLMData.Subject = repmat(struct('BetaMaps', ...
            repmat(single(0), [size(msk), numel(pns) + 1])), 1, nss);
        rfx.RunTimeVars.MotionParameters = cell(0, 1);

        % generate predictor array
        preds = emptystruct({'Name1', 'Name2', 'RGB'}, [numel(pns), 1]);
        for pc = 1:numel(pns)
            preds(pc).RGB = reshape(pnc(:, pc), 4, 3);
        end

        % iterate over subjects
        ts = 1;
        tp = 1;
        for sc = 1:nss

            % get subject ID
            ssts = glms{sc}.Study;
            sid = ssts(1).NameOfAnalyzedFile;
            [sidf, sid] = fileparts(sid);
            sid = regexprep(sid, '^([^_]+)_.*$', '$1');
            tsid = makelabel(sid);

            % RunTimeVars
            rtv = glms{sc}.RunTimeVars;

            % subject-related fields
            if isfield(rtv, 'MotionParameters') && ...
                iscell(rtv.MotionParameters) && ...
                numel(rtv.MotionParameters) == glms{sc}.NrOfStudies
                rfx.RunTimeVars.MotionParameters = [ ...
                    rfx.RunTimeVars.MotionParameters(:); rtv.MotionParameters(:)];
            end
            if isfield(rtv, 'SubjectSPMsn') && ...
                isstruct(rtv.SubjectSPMsn) && ...
                numel(rtv.SubjectSPMsn) == 1 && ...
                isfield(rtv.SubjectSPMsn, tsid)
                rfxspmsn.(tsid) = rtv.SubjectSPMsn.(tsid);
            end
            if isfield(rtv, 'SubjectTrfPlus') && ...
                isstruct(rtv.SubjectTrfPlus) && ...
                numel(rtv.SubjectTrfPlus) == 1 && ...
                isfield(rtv.SubjectTrfPlus, tsid)
                rfxtrfpl.(tsid) = rtv.SubjectTrfPlus.(tsid);
            end

            % fill in header fields
            nst = numel(ssts);
            rfx.NrOfConfoundsPerStudy(ts:ts+nst-1) = glms{sc}.NrOfConfoundsPerStudy;
            prs = glms{sc}.Predictor;
            pnn = lsqueeze({prs([1:(glms{sc}.NrOfPredictors - glms{sc}.NrOfConfounds), end]).Name2});
            pnn = regexprep(pnn, '^Subject\s+(\w+)\:\s*', '');
            pni = multimatch(pns, pnn);
            rfxPredictor(tp:tp+numel(pns)-1) = preds;
            for pc = 1:numel(pns)
                rfxPredictor(tp).Name1 = sprintf('Predictor: %d', tp);
                rfxPredictor(tp).Name2 = sprintf('Subject %s: %s', sid, pns{pc});

                % also fill in beta map?
                if pni(pc) > 0
                    rfxGLMData.Subject(sc).BetaMaps(:, :, :, pc) = ...
                        glms{sc}.GLMData.BetaMaps(:, :, :, pni(pc));
                end

                % increase counter
                tp = tp + 1;
            end

            % add constant predictor info
            rfxPredictor(ntp+sc-nss) = glms{sc}.Predictor(end);
            rfxPredictor(ntp+sc-nss).Name1 = sprintf('Predictor: %d', ntp+sc-nss);
            rfxPredictor(ntp+sc-nss).Name2 = sprintf('Subject %s: Constant', sid);

            % combine constant maps
            cprs = ~cellfun('isempty', regexpi(lsqueeze({prs.Name2}), '\s+constant$'));
            cmaps = glms{sc}.GLMData.BetaMaps(:, :, :, cprs);
            for stc = 1:numel(ssts)
                cmaps(:, :, :, stc) = ssts(stc).NrOfTimePoints .* cmaps(:, :, :, stc);
            end
            rfxGLMData.Subject(sc).BetaMaps(:, :, :, end) = ...
                (1 / sum(cat(1, ssts.NrOfTimePoints))) .* sum(cmaps, 4);

            % increase counter
            ts = ts + nst;
        end

        % store output
        rfx.Predictor = rfxPredictor;
        rfx.GLMData = rfxGLMData;
        if numel(rfx.RunTimeVars.MotionParameters) ~= numel(rfx.Study)
            rfx.RunTimeVars.MotionParameters = cell(0, 1);
        end
        if ~isempty(fieldnames(rfxspmsn))
            rfx.RunTimeVars.SubjectSPMsn = rfxspmsn;
        end
        if ~isempty(fieldnames(rfxtrfpl))
            rfx.RunTimeVars.SubjectTrfPlus = rfxtrfpl;
        end

        % clear temp data
        rfxGLMData(:) = [];

    % handle errors
    catch ne_eo;
        if ~isempty(mdmf)
            mdm.ClearObject;
        else
            setcont(mdm, mdmc);
        end
        clearxffobjects(glms);
        rfx.ClearObject;
        rethrow(ne_eo);
    end

    % where in output?
    if opts.cmbffx
        varargout{1} = [];
        varargout{2} = rfx;
    else
        varargout{1} = rfx;
    end
end

% FFX combination
if opts.cmbffx

    % try/catch
    try

        % always combine two at a time
        while numel(glms) > 1

            % iterate from the end
            for sc = numel(glms):-2:2

                % combine two GLMs
                nglm = glms{sc-1}.JoinFFX(glms{sc});

                % drop two old GLMs
                clearxffobjects(glms(sc-1:sc));

                % replace first one
                glms{sc-1} = nglm;

                % and remove second from list
                glms(sc) = [];
            end
        end

    % handle errors
    catch ne_eo;
        if ~isempty(mdmf)
            mdm.ClearObject;
        else
            setcont(mdm, mdmc);
        end
        clearxffobjects(glms);
        rethrow(ne_eo);
    end

    % set in output
    varargout{1} = bless(glms{1}.CopyObject, 1);
end

% clean up
if ~isempty(mdmf)
    mdm.ClearObject;
else
    setcont(mdm, mdmc);
end
clearxffobjects(glms);


text:
{% extends "name/base.html" %}
{% load name_extras %}
{% block title %}About{% endblock %}

{% block content %}

            {% include "name/introduction.html" %}

Two search modes are available.

Notice there are two modes of searching. The first mode is a traditional search which takes a query and a type, filtering records containing your query in either the authorized name field or the variant field. The second search method is more of an existence lookup of the authorized name. The user should request {% absolute_url "name:label" "name_string_here" %}. The API will then either return a 302 Found and redirect to the matching record, or a 404 Not Found.  This page will first address the 'traditional' search API, then the label API.

Search API

Let's dive right in! The following are various search examples using curl:

    $ curl "{% absolute_url "name:search-json" %}?q=joey+liechty"
    [
        {
            "URL": "{% absolute_url "name:detail" "nm0051457" %}",
            "id": "nm0051457",
            "name": "joey liechty",
            "type": "Personal"
        }
    ]

    $ curl "{% absolute_url "name:search-json" %}?q=abc&q_type=Organization&callback=foo"
    foo([
        {
            "URL": "{% url "name:detail" "nm0000063" %}",
            "id": "nm0000063",
            "name": "ABC Shop",
            "type": "Organization"
        }
    ])

    $ curl "{% absolute_url "name:search-json" %}?q_type=Software"
    [
        {
            "URL": "{% absolute_url "name:detail" "nm0051455" %}",
            "id": "nm0051455",
            "name": "Watson",
            "type": "Software"
        },
        {
            "URL": "{% absolute_url "name:detail" "nm0012345" %}",
            "id": "nm0012345",
            "name": "Software Foo",
            "type": "Software"
        },
        {
            "URL": "{% absolute_url "name:detail" "nm0043212" %}",
            "id": "nm0043212",
            "name": "123 SoftCom",
            "type": "Software"
        }
    ]

    $ curl "{% absolute_url "name:search-json" %}?q_type=Software,Organization"
    [
        {
            "URL": "{% absolute_url "name:detail" "nm0051455" %}",
            "id": "nm0051455",
            "name": "Watson",
            "type": "Software"
        },
        {
            "URL": "{% absolute_url "name:detail" "nm0012345" %}",
            "id": "nm0012345",
            "name": "Software Foo",
            "type": "Software"
        },
        {
            "URL": "{% absolute_url "name:detail" "nm0043212" %}",
            "id": "nm0043212",
            "name": "123 SoftCom",
            "type": "Software"
        },
        {
            "URL": "{% absolute_url "name:detail" "nm0000063" %}",
            "id": "nm0000063",
            "name": "ABC Shop",
            "type": "Organization"
        }
    ]

Search Return Codes

                200 OK response:

User gave a fully-formed search query which returns a list of results in JSON format.

                410 Gone response:

User gives a request for a record that had existed, but has since been deleted.

                404 Not Found response:

User gives a request for a record that does not exist.

                403 Forbidden response:

User gives a request for a record that exists, but is not public.

                302 Redirect response:

User requests a record which has been merged with another record.

How can I narrow my search?

Parameters hang off the end of a search request to narrow the results you get in your response and will get you closer to the name you are attempting to lookup.

            q: Optional - the text respresentation of the record name you want to search.

            q_type: Optional - the text representation of the record type. 5 types are available to filter the search, "Personal", "Organization", "Event", "Building", "Software".

            callback: Optional - the text representation of the jsonp callback wrapper.

Label API

The second method of searching is with the label API. The label API is essentially a quick way to determine if an authorized name exists in {{ name_app_title }}. The only two responses to this API are a 404 Not Found or a 302 Redirect.

    $ curl "{% absolute_url "name:label" "joey-not-here" %}"
    No matching term found - authoritative, or variant - for "joey-not-here"

    $ curl -I "{% absolute_url "name:label" "thisrecordisforsureinthedatabase" %}"
    HTTP/1.0 302 FOUND
    Date: Mon, 25 Feb 2013 22:33:19 GMT
    Server: WSGIServer/0.1 Python/2.7.3
    Content-Type: text/html; charset=utf-8
    Location: {% absolute_url "name:detail" "nm0000085" %}

Label Return Codes

                404 Not Found response:

User gives an authorized name that does not exist in the {{ name_app_title }} database.

                302 Redirect response:

User gives an authorized name that does exist in the {{ name_app_title }} database. The system redirects to the corresponding record.

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

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

include_once(realpath(__DIR__ . '/../../../models') . '/Base_model.php');

class Vendedor_Model extends Base_Model {

    public function __construct() {
        parent::__construct();
        $this->set_base_datos('default');
        $this->set_tabla('vendedores');
    }

    public function get_by_cedula($cedula) {
        $this->control_conexion();
        $this->conexion->where('cedula', $cedula);
        $cliente = $this->conexion->get($this->tabla)->result();
        $this->conexion->close();
        return $cliente;
    }

    public function get_all_by_estado($estado) {
        $this->control_conexion();
        $this->conexion->where('estado', $estado);
        $cliente = $this->conexion->get($this->tabla)->result();
        $this->conexion->close();
        return $cliente;
    }

}


text:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

function localInit() {
  var localInit = new express.Router();
  localInit.use(cors());
  localInit.use(bodyParser());

  // POST REST endpoint - note we use 'body-parser' middleware above to parse the request body in this route.
  // This can also be added in application.js
  // See: https://github.com/senchalabs/connect#middleware for a list of Express 4 middleware
  localInit.post('/', function(req, res) {
    console.log(new Date().toUTCString(), 'In mock init route POST / req.body=', req.body);
    // NOTE::
    // Replace below ip addresses with wifi ip to point a device at local machine

    // see http://expressjs.com/4x/api.html#res.json
    res.json({
      'apptitle': 'iss-local',
      'domain': 'iss.mtma',
      'firstTime': false,
      'hosts': {
        'debugCloudType': 'node',
        'debugCloudUrl': 'http://127.0.0.1:8001',
        'releaseCloudType': 'node',
        'releaseCloudUrl': 'http://127.0.0.1:8001'
      },
      'init': {
        'trackId': 'HOTVCyUGKVRvhoBe_WeN66si-'
      },
      'status': 'ok'
    });
  });

  return localInit;
}

module.exports = localInit;


text:
#!/usr/bin/env node
'use strict'

const argv = require('rasper')(process.argv.slice(2))

const pkg = require('./package.json')
const banner = require('./')

let options = {}

if (argv.v || argv.version) {
  console.log(pkg.version)
  process.exit(0)
}

if (argv.h || argv.help) {
  console.log(`
  Usage:

    $ banner-cli <files> [<options>]

  Options:

    -n, --name              Define project name
    -t, --tag               Define tag version
    -s, --site              Define homepage
    -a, --author            Define author
    -y, --year              Define year
    -l, --license           Define license
    -h, --help              Display help information
    -v, --version           Output version

  Examples:

    $ banner-cli dist/**/*.js
    $ banner-cli dist/**/*.css --author 'CJ Patoilo' --license MIT --site https://milligram.io
	`)
  process.exit(0)
}

if (argv.n && argv.n !== true) {
  options.name = argv.n
}

if (argv.name && argv.name !== true) {
  options.name = argv.name
}

if (argv.t && argv.t !== true) {
  options.tag = argv.t
}

if (argv.tag && argv.tag !== true) {
  options.tag = argv.tag
}

if (argv.s && argv.s !== true) {
  options.homepage = argv.s
}

if (argv.site && argv.site !== true) {
  options.homepage = argv.site
}

if (argv.l && argv.l !== true) {
  options.license = argv.l
}

if (argv.license && argv.license !== true) {
  options.license = argv.license
}

if (argv.a && argv.a !== true) {
  options.author = argv.a
}

if (argv.author && argv.author !== true) {
  options.author = argv.author
}

if (argv.year && argv.year !== true) {
  options.year = argv.year
}

if (argv.y && argv.y !== true) {
  options.year = argv.y
}

if (argv._[0]) {
  options.source = argv._[0]
  banner(options)
}


text:
import {assert} from '@ciscospark/test-helper-chai';
import Metrics, {config} from '../..';
import MockSpark from '@ciscospark/test-helper-mock-spark';
import sinon from '@ciscospark/test-helper-sinon';

describe(`plugin-metrics`, () => {
  describe(`Metrics`, () => {
    let spark;
    let metrics;
    const eventName = `test_event`;
    const mockPayload = {
      fields: {
        testField: 123
      },
      tags: {
        testTag: `tag value`
      },
      metricName: eventName,
      test: `this field should not be included in final payload`,
      type: `behavioral`
    };
    const transformedProps = {
      fields: {
        testField: 123
      },
      tags: {
        testTag: `tag value`
      },
      metricName: eventName,
      type: `behavioral`
    };
    const preLoginId = `1b90cf5e-27a6-41aa-a208-1f6eb6b9e6b6`;
    const preLoginProps = {
      metrics: [
        transformedProps
      ]
    };

    beforeEach(() => {
      spark = new MockSpark({
        children: {
          metrics: Metrics
        }
      });

      spark.config.metrics = config.metrics;
      metrics = spark.metrics;

      spark.request = function(options) {
        return Promise.resolve({
          statusCode: 204,
          body: undefined,
          options
        });
      };
      sinon.spy(spark, `request`);
      sinon.spy(metrics, `postPreLoginMetric`);
      sinon.spy(metrics, `aliasUser`);
    });

    describe(`#submit()`, () => {
      it(`submits a metric`, () => {
        return metrics.submit(`testMetric`)
          .then(() => {
            assert.calledOnce(spark.request);
            const req = spark.request.args[0][0];
            const metric = req.body.metrics[0];

            assert.property(metric, `key`);
            assert.property(metric, `version`);
            assert.property(metric, `appType`);
            assert.property(metric, `env`);
            assert.property(metric, `time`);
            assert.property(metric, `version`);

            assert.equal(metric.key, `testMetric`);
            assert.equal(metric.version, spark.version);
            assert.equal(metric.env, `TEST`);
          });
      });
    });

    describe(`#submitClientMetrics()`, () => {
      describe(`before login`, () => {
        it(`posts pre-login metric`, () => {
          metrics.submitClientMetrics(eventName, mockPayload, preLoginId);
          assert.calledWith(metrics.postPreLoginMetric, preLoginProps, preLoginId);
        });
      });
      describe(`after login`, () => {
        it(`submits a metric to clientmetrics`, () => {
          const testPayload = {
            tags: {success: true},
            fields: {perceivedDurationInMillis: 314}
          };
          return metrics.submitClientMetrics(`test`, testPayload)
            .then(() => {
              assert.calledOnce(spark.request);
              const req = spark.request.args[0][0];
              const metric = req.body.metrics[0];

              assert.property(metric, `metricName`);
              assert.property(metric, `tags`);
              assert.property(metric, `fields`);

              assert.equal(metric.metricName, `test`);
              assert.equal(metric.tags.success, true);
              assert.equal(metric.fields.perceivedDurationInMillis, 314);
            });
        });
      });
    });

    describe(`#postPreLoginMetric()`, () => {
      it(`returns an HttpResponse object`, () => {
        return metrics.postPreLoginMetric(preLoginProps, preLoginId)
          .then(() => {
            assert.calledOnce(spark.request);
            const req = spark.request.args[0][0];
            const metric = req.body.metrics[0];
            const headers = req.headers;

            assert.property(headers, `x-prelogin-userid`);
            assert.property(metric, `metricName`);
            assert.property(metric, `tags`);
            assert.property(metric, `fields`);

            assert.equal(metric.metricName, eventName);
            assert.equal(metric.tags.testTag, `tag value`);
            assert.equal(metric.fields.testField, 123);
          });
      });
    });

    describe(`#aliasUser()`, () => {
      it(`returns an HttpResponse object`, () => {
        return metrics.aliasUser(preLoginId)
          .then(() => {
            assert.calledOnce(spark.request);
            const req = spark.request.args[0][0];
            const params = req.qs;

            sinon.match(params, {alias: true});
          });
      });
    });
  });
});


text:
namespace System.Spatial
{
    using Microsoft.Data.Spatial;

    /// <summary>
    /// Class responsible for knowing how to create the Geography and Geometry builders for
    /// a particular implemenation of Spatial types
    /// </summary>
    public abstract class SpatialImplementation
    {
        /// <summary>Default Spatial Implementation.</summary>
        private static SpatialImplementation spatialImplementation = new DataServicesSpatialImplementation();

        /// <summary>
        /// Returns an instance of SpatialImplementation that is currently being used.
        /// </summary>
        public static SpatialImplementation CurrentImplementation
        {
            get
            {
                return spatialImplementation;
            }

            // Intended for use by tests only
            internal set
            {
                spatialImplementation = value;
            }
        }

        /// <summary>
        /// Property used to register Spatial operations implementation.
        /// </summary>
        public abstract SpatialOperations Operations
        {
            get;
            set;
        }

        /// <summary>
        /// Creates a SpatialBuilder for this implemenation
        /// </summary>
        /// <returns>The SpatialBuilder created.</returns>
        public abstract SpatialBuilder CreateBuilder();

        /// <summary>
        /// Creates a Formatter for Json Object
        /// </summary>
        /// <returns>The JsonObjectFormatter created</returns>
        public abstract GeoJsonObjectFormatter CreateGeoJsonObjectFormatter();

        /// <summary>
        /// Creates a GmlFormatter for this implementation
        /// </summary>
        /// <returns>The GmlFormatter created.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gml", Justification = "Gml is the common name for this format")]
        public abstract GmlFormatter CreateGmlFormatter();

        /// <summary>
        /// Creates a WellKnownTextSqlFormatter for this implementation
        /// </summary>
        /// <returns>The WellKnownTextSqlFormatter created.</returns>
        public abstract WellKnownTextSqlFormatter CreateWellKnownTextSqlFormatter();

        /// <summary>
        /// Creates a WellKnownTextSqlFormatter for this implementation
        /// </summary>
        /// <param name="allowOnlyTwoDimensions">Controls the writing and reading of the Z and M dimension</param>
        /// <returns>The WellKnownTextSqlFormatter created.</returns>
        public abstract WellKnownTextSqlFormatter CreateWellKnownTextSqlFormatter(bool allowOnlyTwoDimensions);

        /// <summary>
        /// Creates a spatial Validator
        /// </summary>
        /// <returns>The SpatialValidator created.</returns>
        public abstract SpatialPipeline CreateValidator();

        /// <summary>
        /// This method throws if the operations instance is null. It returns a non-null operations implementation.
        /// </summary>
        /// <returns>a SpatialOperations implementation.</returns>
        internal SpatialOperations VerifyAndGetNonNullOperations()
        {
            var operations = this.Operations;
            if (operations == null)
            {
                throw new NotImplementedException(Strings.SpatialImplementation_NoRegisteredOperations);
            }

            return operations;
        }
    }
}


text:
package com.github.robozonky.api.notifications;

public interface LoanDelinquent30DaysOrMoreEvent extends LoanDelinquentEvent {

}


text:
CFrontendContext::CFrontendContext(std::ostream &errors, CStringPool &pool)
    : m_pool(pool)
    , m_errors(errors)
{
}

CFrontendContext::~CFrontendContext()
{
}

std::string CFrontendContext::GetString(unsigned stringId) const
{
    return m_pool.GetString(stringId);
}

void CFrontendContext::PrintError(const std::string &message)const
{
    ++m_errorsCount;
    m_errors << "  Error: " << message << std::endl;
}

unsigned CFrontendContext::GetErrorsCount() const
{
    return m_errorsCount;
}


text:
package workbench.interfaces;

/**
 *
 * @author Thomas Kellerer
 */
public interface Committer
{
	/**
	 * The integer value that identifies the fact that no COMMIT statement
	 * at all should be written to the output file
	 */
	int NO_COMMIT_FLAG = Integer.MIN_VALUE;

	/**
	 * Define the interval when commits should be send to the DBMS
	 * @param interval the number of statement after which to commit. 0 means each statement
	 */
	void setCommitEvery(int interval);

	/**
	 * Never commit anything
	 */
	void commitNothing();

}


text:
Namespace.register("SFNamespace.SFBox");

var resetBoxField=function(){
    resetCheckToFields('input[name="SFBox-product_or_box"]', 'product', [
        '#SFBox-product_w',
        '#SFBox-product_d',
        '#SFBox-product_h',
        'input[name="SFBox-product_unit"]',
        '#SFBox-product_weight',
        '#SFBox-product_weight_unit'
        //'input[name="SFBox-product_weight_as_sample"]'
        ]);
    resetCheckToFields('input[name="SFBox-product_or_box"]', 'box', [
        '#SFBox-box_w',
        '#SFBox-box_d',
        '#SFBox-box_h',
        'input[name="SFBox-box_unit"]',
        ]);

    /*
    resetCheckToFields('input[name="SFBox-material_type"]', 'folding_cards', [
        'input[name="SFBox-folding_cards_type"]',
        '#SFBox-folding_cards_other',
        'input[name="SFBox-paper_thickness_type"]',
        '#SFBox-paper_thickness',
        'input[name="SFBox-paper_thickness_unit"]',
        '#SFBox-gramage_gsm'
        ]);
    resetCheckToFields('input[name="SFBox-material_type"]', 'corrugated', [
        '#SFBox-flute',
        'input[name="SFBox-flute_type"]',
        '#SFBox-bursting',
        '#SFBox-ect',
        '#SFBox-gramage',
        '#SFBox-flute_type_gsm'
        ]);
    resetCheckToFields('input[name="SFBox-material_type"]', 'other', '#SFBox-material_type_other_content');
    */
    resetCheckToFields('input[name="SFBox-top_closure"]', 'Other', '#SFBox-top_closure_other');
    resetCheckToFields('input[name="SFBox-top_locking"]', 'Other', '#SFBox-top_locking_other');
    resetCheckToFields('input[name="SFBox-bottom_closure"]', 'Other', '#SFBox-bottom_closure_other');
    resetCheckToFieldsNoteq('input[name="SFBox-bottom_closure"]', ['SLB','Auto','RSC','FOL','Open_Bottom'], "input[name='SFBox-bottom_locking']");
    resetCheckToFields('input[name="SFBox-bottom_locking"]', 'Other', '#SFBox-bottom_locking_other');
    resetCheckToFields('input[name="SFBox-insert"]', 'Yes', '#insert_material_tmp');
//resetAsSampleToFields('input[name="SFBox-product_weight_as_sample"]', ['#SFBox-product_w', '#SFBox-product_d', '#SFBox-product_h', 'input[name="SFBox-product_unit"]', '#SFBox-product_weight', 'input[name="SFBox-product_weight_unit"]'])
//resetCheckToFields('input[name="SFBox-window"]', ['Open'], ['#SFBox-window_size_w','#SFBox-window_size_h',"input[name='SFBox-window_size_unit']"]);
//resetCheckToFields('input[name="SFBox-window"]', 'No', ['#SFBox-pvc_thickness','#SFBox-pet_thickness','#SFBox-pp_thickness',"input[name='SFBox-window_with']"]);
//resetCheckToFields('input[name="SFBox-window"]', ['With'], ['#SFBox-window_size_w','#SFBox-window_size_h',"input[name='SFBox-window_size_unit']","input[name='SFBox-window_with']"]);
}

SFNamespace.SFBox.obj = {

    id   		 : "SFBox",

    title        : "Box",

    install 	 : function(){
        $('.datePicker').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: dateFormat
        });
        $(".numeric").numeric();
        validators.push(this);
        resetBoxField();
        $('input[name="SFBox-product_or_box"]').click(function(){
            resetBoxField()
        });
        /*
        $('input[name="SFBox-material_type"]').click(function(){
            resetBoxField()
        });
        */
        $('input[name="SFBox-top_closure"]').click(function(){
            resetBoxField()
        });
        $('input[name="SFBox-top_locking"]').click(function(){
            resetBoxField()
        });
        $('input[name="SFBox-bottom_closure"]').click(function(){
            resetBoxField()
        });
        $('input[name="SFBox-bottom_locking"]').click(function(){
            resetBoxField()
        });
        $('input[name="SFBox-insert"]').click(function(){
            resetBoxField()
        });
        $('input[name="SFBox-window_type"]').click(function(){
            resetBoxField()
        });
        $("input[name*='as_sample']").click(function(){
            resetBoxField()
        })
        $("input[name='SFBox-top_closure'],input[name='SFBox-top_locking']").click(function(){
            var v1 = $("input[name='SFBox-top_closure']:checked").val();
            var v2 = $("input[name='SFBox-top_locking']:checked").val();

            if(v1=="Standard" && v2=="No")
                $("#top_closure").attr("src","/images/sample/Standard Slit Lock.jpg");
            else if(v1=="Standard" && v2=="Yes")
                $("#top_closure").attr("src","/images/sample/Standard Slit Lock with Tongue Lock.jpg");
            else if(v1=="Friction" && v2=="No")
                $("#top_closure").attr("src","/images/sample/Friction Tuck.jpg");
            else if(v1=="Friction" && v2=="Yes")
                $("#top_closure").attr("src","/images/sample/Friction Tuck with Tongue Lock.jpg");
            else if(v1=="RSC"){
            	$("#top_closure").attr("src","/images/sample/RSC.jpg");
            }
            else if(v1=="FOL"){
            	$("#top_closure").attr("src","/images/sample/FOL.jpg");
            }
            else
                $("#top_closure").attr("src","/images/blank.png");
        });

        $("input[name='SFBox-bottom_closure'],input[name='SFBox-bottom_locking']").click(function(){
            var v1 = $("input[name='SFBox-bottom_closure']:checked");
            var v2 = $("input[name='SFBox-bottom_locking']:checked");

            if(v1.val()=="Standard" && v2.val()=="No")
                $("#bottom_closure").attr("src","/images/sample/Standard Slit Lock.jpg");
            if(v1.val()=="Standard" && v2.val()=="Yes")
                $("#bottom_closure").attr("src","/images/sample/Standard Slit Lock with Tongue Lock.jpg");
            if(v1.val()=="Friction" && v2.val()=="No")
                $("#bottom_closure").attr("src","/images/sample/Friction Tuck.jpg");
            if(v1.val()=="Friction" && v2.val()=="Yes")
                $("#bottom_closure").attr("src","/images/sample/Friction Tuck with Tongue Lock.jpg");

            if(!v1.val()||!v2.val()||v1.val()=='Other'||v2.val()=='Other'){
                $("#bottom_closure").attr("src","/images/blank.png");
            }
            if(v1.val()=='SLB'){
                $("#bottom_closure").attr("src","/images/sample/SLB.jpg");
            }
            if(v1.val()=='Auto'){
                $("#bottom_closure").attr("src","/images/sample/Auto Lock.jpg");
            }
            if(v1.val()=='RSC'){
                $("#bottom_closure").attr("src","/images/sample/RSC.jpg");
            }
            if(v1.val()=='FOL'){
                $("#bottom_closure").attr("src","/images/sample/FOL.jpg");
            }
            if(v1.val()=='Open_Bottom'){
                $("#bottom_closure").attr("src","/images/sample/Open.jpg");
            }
        });

    },

    uninstall 	 : function(){
        for(var i=0;i<validators.length;i++){
            if( this.id==validators[i].id ){
                validators.splice(i,1);
                break;
            }
        }
    },

    validation   : function(){
        var msg = [];
        //        if(!$("input[name='SFBox-presentation']:checked").val()){
        //
        //        }
        if( $("input[name='SFBox-presentation']:checked").length < 1 && $("input[name='SFBox-job_perpose']:checked").length < 1){
        	changeColorList([[[$("input[name='SFBox-presentation']"),$("input[name='SFBox-job_perpose']")],true]])
            msg.push("Task["+this.title+"]Please select the 'Job Purpose'.");
        }
        if(!$("input[name='SFBox-product_or_box']:checked").val()){
            changeColorList($("input[name='SFBox-product_or_box']"))
            msg.push("Task["+this.title+"]Please select the 'Product','Box' or 'As Sample' for the 'Job Purpose'.");
        }else if($("input[name='SFBox-product_or_box']:checked").val()=='product'){

                var checkBox = 0;
                if(!($('#SFBox-product_w').val() && $('#SFBox-product_d').val() && $('#SFBox-product_h').val() && $("input[name='SFBox-product_unit']:checked").val())){
                    //changeColorList([[[$('#SFBox-product_w'),$('#SFBox-product_d'),$('#SFBox-product_h'),$("input[name='SFBox-product_unit']")],true]])
                    msg.push("Task["+this.title+"]Please input Dimension 'Size' and 'Unit' for the 'Job Purpose: Product'.");
                    checkBox = 1;

                }
                if($("#SFBox-product_weight").val() && !$("#SFBox-product_weight_unit").val()){
                    msg.push("Task["+this.title+"]Please input Weight 'Unit' for the 'Job Purpose: Product'.");
                    checkBox = 1;
                }

                /*
                if(checkBox == 1){
                    changeColorList([[[[$('#SFBox-product_w'),$('#SFBox-product_d'),$('#SFBox-product_h'),$("input[name='SFBox-product_unit']"),$("#SFBox-product_weight"),$("#SFBox-product_weight_unit")],
                        $("input[name='SFBox-product_weight_as_sample'][value='Y']")
                        ],false]])
                }
                */
                if(checkBox == 1){
                    changeColorList([[[$('#SFBox-product_w'),$('#SFBox-product_d'),$('#SFBox-product_h'),$("input[name='SFBox-product_unit']"),$("#SFBox-product_weight"),$("#SFBox-product_weight_unit")],false],])
                }

        }else if($("input[name='SFBox-product_or_box']:checked").val()=='box'){
            if(!($('#SFBox-box_w').val() && $('#SFBox-box_d').val() && $('#SFBox-box_h').val() && $("input[name='SFBox-box_unit']:checked").val() && $("input[name='SFBox-box_size']:checked").val())){
                changeColorList([[[$('#SFBox-box_w'),$('#SFBox-box_d'),$('#SFBox-box_h'), $("input[name='SFBox-box_unit']"),$("input[name='SFBox-box_size']")],true]])
                msg.push("Task["+this.title+"]Please input Dimension 'Size' and 'Unit' for the 'Job Purpose: Box'.");
            }
        }

        /*
        if(!$("input[name='SFBox-material_type']:checked").val())
        {
            changeColorList($("input[name='SFBox-material_type']"))
            msg.push("Task["+this.title+"]Please select the 'Material'.");
        }
        else if($("input[name='SFBox-material_type']:checked").val()=='folding_cards'){
            if(!$("input[name='SFBox-folding_cards_type']:checked").val())
            {
                changeColorList($("input[name='SFBox-folding_cards_type']"))
                msg.push("Task["+this.title+"]Please select the option for the 'Folding Cards'.");
            }
            else if($("input[name='SFBox-folding_cards_type']:checked").val()=='Other' && !$('#SFBox-folding_cards_other').val())
            {
                changeColorList($('#SFBox-folding_cards_other'))
                msg.push("Task["+this.title+"]Please input the content if select the 'Folding Cards: Other'.");
            }
            if($("input[name='SFBox-paper_thickness_type']:checked").val()=='other' && !($('#SFBox-paper_thickness').val() && $("input[name='SFBox-paper_thickness_unit']:checked").val()) )
            {
                changeColorList([[[$('#SFBox-paper_thickness'),$("input[name='SFBox-paper_thickness_unit']")],true]])
                msg.push("Task["+this.title+"]Please input the content and select 'Unit' if select the 'Paper thickness'.");
            }
            if($("input[name='SFBox-paper_thickness_type']:checked").val()=='gramage' && !$('#SFBox-gramage_gsm').val())
            {
                changeColorList($('#SFBox-gramage_gsm'))
                msg.push("Task["+this.title+"]Please input the content if select the 'Grammage'.");
            }
        }else if($("input[name='SFBox-material_type']:checked").val()=='corrugated'){
            if(!$("input[name='SFBox-flute_type']:checked").val()||!$('#SFBox-flute').val())
            {
                changeColorList($('#SFBox-flute'))
                msg.push("Task["+this.title+"]Please input the content and select 'flut type' for the 'Corrugated'.");
            }
        }else if($("input[name='SFBox-material_type']:checked").val()=='other'){
            if(!$('#SFBox-material_type_other_content').val()){
                changeColorList($('#SFBox-material_type_other_content'))
                msg.push("Task["+this.title+"]Please input the content if select 'Material: Other'.");
            }
        }
        */

        //        if( $("input[name='SFBox-floding_cards']:checked").length < 1 && !$("#SFBox-corrugated").val() )
        //            msg.push("Tab["+this.title+"]Please select either 'Folding Cards' or 'Corrugate'.");
        //        else{
        //            if($("input[name='SFBox-floding_cards']:checked").val()){
        //                if(!$('#SFBox-grammage').val() && !$('#SFBox-paper_thickness').val())
        //                    msg.push("Tab["+this.title+"]Please input the 'Folding Cards: Paper thickness' or 'Folding Cards: Gramage'.");
        //                if($('#SFBox-paper_thickness').val() && !$("input[name='SFBox-paper_thickness_unit']:checked").val())
        //                    msg.push("Tab["+this.title+"]Please select 'Unit' for the 'Folding Cards: Paper thickness'.");
        //            }
        //            if($("#SFBox-corrugated").val()){
        //                if(!$("input[name='SFBox-flute']:checked").val())
        //                    msg.push("Tab["+this.title+"]Please select 'Kraft Top' or 'Mottle White Top' or 'CCNB Top' for the 'Corrugate'.");
        //            }
        //        }
        //

        if($(".material_widget[value!='']").length < 1){
            msg.push("Task["+this.title+"]Please add the 'Material'.");
        }

        if( $("input[name='SFBox-top_closure']:checked").length < 1 )
        {
            changeColorList($("input[name='SFBox-top_closure']"))
            msg.push("Task["+this.title+"]Please fill in the 'Top Closure'.");
        }
        else if($("input[name='SFBox-top_closure']:checked").val()=='Other'&&!$('#SFBox-top_closure_other').val())
        {
            changeColorList($('#SFBox-top_closure_other'))
            msg.push("Task["+this.title+"]Please input the content if select the 'Top Closure: Other'.");
        }

        if( $("input[name='SFBox-top_locking']:checked").length < 1 && !( $("input[name='SFBox-top_closure'][value='RSC']:checked").length ==1 || $("input[name='SFBox-top_closure'][value='FOL']:checked").length ==1))
        {
            changeColorList($("input[name='SFBox-top_locking']"))
            msg.push("Task["+this.title+"]Please fill in the 'Top Locking'.");
        }
        else if($("input[name='SFBox-top_locking']:checked").val()=='Other'&&!$('#SFBox-top_locking_other').val())
        {
            changeColorList($('#SFBox-top_locking_other'))
            msg.push("Task["+this.title+"]Please input the content if select the 'Top Locking: Other'.");
        }

        if( $("input[name='SFBox-bottom_closure']:checked").length < 1 ){
            changeColorList($("input[name='SFBox-bottom_closure']"))
            msg.push("Task["+this.title+"]Please fill in the 'Bottom Closure'.");
        }
        else if($("input[name='SFBox-bottom_closure']:checked").val()=='Other'&&!$('#SFBox-bottom_closure_other').val())
        {
            changeColorList($('#SFBox-bottom_closure_other'))
            msg.push("Task["+this.title+"]Please input the content if select the 'Bottom Closure: Other'.");
        }

        if( $("input[name='SFBox-bottom_locking']:checked").length < 1 && !($("input[name='SFBox-bottom_closure'][value='Auto']:checked").length == 1 || $("input[name='SFBox-bottom_closure'][value='SLB']:checked").length == 1|| $("input[name='SFBox-bottom_closure'][value='Open_Bottom']:checked").length == 1|| $("input[name='SFBox-bottom_closure'][value='FOL']:checked").length == 1|| $("input[name='SFBox-bottom_closure'][value='RSC']:checked").length == 1) ){
            changeColorList($("input[name='SFBox-bottom_locking']"))
            //changeColorList([[[$("input[name='SFBox-bottom_closure'][value='Auto']"),$("input[name='SFBox-bottom_closure'][value='SLB']")],false]])
            msg.push("Task["+this.title+"]Please fill in the 'Bottom Locking'.");
        }
        else if($("input[name='SFBox-bottom_locking']:checked").val()=='Other'&&!$('#SFBox-bottom_locking_other').val())
        {
            changeColorList($('#SFBox-bottom_locking_other'))
            msg.push("Task["+this.title+"]Please input the content if select the 'Bottom Locking: Other'.");
        }

        if( $("input[name='SFBox-insert']:checked").length < 1 )
        {
            changeColorList($("input[name='SFBox-insert']"))
            msg.push("Task["+this.title+"]Please fill in the 'Insert'.");
        }
        else if($("input[name='SFBox-insert']:checked").val()=='Yes' && !$('#SFBox-insert_material').val())
        {
            changeColorList($('#insert_material_tmp'));
            msg.push("Task["+this.title+"]Please input 'Material' for the 'Insert: Yes'.");
        }

        if( $("input[name='SFBox-loading']:checked").length < 1 )
        {
            changeColorList($("input[name='SFBox-loading']"))
            msg.push("Task["+this.title+"]Please select in the 'Top Loading/Side Loading'.");
        }

        if( $("input[name='SFBox-window_type']:checked").length < 1 )
        {
            changeColorList($("input[name='SFBox-window_type']"))
            msg.push("Task["+this.title+"]Please select in the 'Open Window/No Window/Window with'.");
        }
        else if($("input[name='SFBox-window_type']:checked").val()=='With'){
            if(!$("input[name='SFBox-window_with']:checked").val())
            {
                changeColorList($("input[name='SFBox-window_with']"))
                msg.push("Task["+this.title+"]Please select option if select 'Insert: Window with'.");
            }
            else if($("input[name='SFBox-window_with']:checked").val()=='PVC' && !$('#SFBox-pvc_thickness').val())
            {
                changeColorList($('#SFBox-pvc_thickness'))
                msg.push("Task["+this.title+"]Please input 'Thickness' for the 'Insert: Window with PVC'.");
            }
            else if($("input[name='SFBox-window_with']:checked").val()=='PET' && !$('#SFBox-pet_thickness').val())
            {
                changeColorList($('#SFBox-pet_thickness'))
                msg.push("Task["+this.title+"]Please input 'Thickness' for the 'Insert: Window with PET'.");
            }
            else if($("input[name='SFBox-window_with']:checked").val()=='PP' && !$('#SFBox-pp_thickness').val())
            {
                changeColorList($('#SFBox-pp_thickness'))
                msg.push("Task["+this.title+"]Please input 'Thickness' for the 'Insert: Window with PP'.");
            }
        }

        if( $("input[name='SFBox-window_type'][value='With']:checked").length == 1
        		&& !(
        				($("#SFBox-window_size_w").val()
        				&& $("#SFBox-window_size_h").val()
        				&& $("input[name='SFBox-window_size_unit']:checked").length>=1
        				&& $("input[name='SFBox-window_with']:checked").length>=1
        				)
        				||
        				$("input[name='SFBox-suggested_by_pd_team']:checked").length>=1
        			)
        	){
            changeColorList([[[$("#SFBox-window_size_w"),$("#SFBox-window_size_h"),$("input[name='SFBox-window_size_unit']"),$("input[name='SFBox-suggested_by_pd_team']")],true]])
            msg.push("Task["+this.title+"]Please input  and 'Window Size' and 'Unit' and options(PVC or PET or PP or Other)  if select 'Window with'.");
        }
        if($("input[name='SFBox-window_type'][value='Open']:checked").length == 1 && !($("#SFBox-window_size_w").val() && $("#SFBox-window_size_h").val() && $("input[name='SFBox-window_size_unit']:checked").length>=1 || $("input[name='SFBox-suggested_by_pd_team']:checked").length>0)){
            changeColorList([[[$("#SFBox-window_size_w"),$("#SFBox-window_size_h"),$("input[name='SFBox-window_size_unit']")],true]])
            msg.push("Task["+this.title+"]Please input 'Window Size' and 'Unit' or select 'Window Size: Suggested by PD Team' if select 'Open Window'.");
        }
        //
        //        if( $("input[name='SFBox-flute']:checked").length < 1 )
        //            msg.push("Tab["+this.title+"]Please select the 'Kraft Top/Mottle White Top/CCNB Top'.");

        if( !$("#SFBox-expected_date").val() )
        {
            changeColorList($("#SFBox-expected_date"))
            msg.push("Task["+this.title+"]Please input the 'Expected date/time'.");
        }

        //jsonify the material info into the hidden field
		var jsonvals = new Array();
		$(".material_widget").each(function(){
		    if($(this).val()){
		        jsonvals.push($(this).attr("ref"));
		    }
		});
		$("#SFBox-material_widgets").val("[" + jsonvals.join(",") + "]");

        return msg;
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _Mod = require("../Mod");

class CopyWebpackPlugin extends _Mod.Plugin {}

exports.default = CopyWebpackPlugin;
;
module.exports = exports.default;


text:
package org.locationtech.geomesa.jobs.index
import com.twitter.scalding._
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io.Text
import org.geotools.data.DataStoreFinder
import org.locationtech.geomesa.accumulo.data.AccumuloDataStoreFactory.params._
import org.locationtech.geomesa.accumulo.data.AccumuloFeatureWriter.FeatureToWrite
import org.locationtech.geomesa.accumulo.data._
import org.locationtech.geomesa.accumulo.data.tables.{AttributeTable, AttributeTableV5}
import org.locationtech.geomesa.accumulo.index._
import org.locationtech.geomesa.features.SimpleFeatureSerializers
import org.locationtech.geomesa.jobs.GeoMesaBaseJob
import org.locationtech.geomesa.jobs.scalding.ConnectionParams._
import org.locationtech.geomesa.jobs.scalding._
import org.locationtech.geomesa.utils.geotools.RichAttributeDescriptors.RichAttributeDescriptor
import org.locationtech.geomesa.utils.geotools.RichSimpleFeatureType.RichSimpleFeatureType
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.locationtech.geomesa.utils.stats.IndexCoverage
import org.locationtech.geomesa.utils.stats.IndexCoverage.IndexCoverage
import org.opengis.feature.`type`.AttributeDescriptor

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.util.Try

class AttributeIndexJob(args: Args) extends GeoMesaBaseJob(args) {

  val feature = args(FEATURE_IN)
  val dsParams = toDataStoreInParams(args)

  // add a comma-split to allow comma-separated values
  val attributes = args.list(AttributeIndexJob.ATTRIBUTES_TO_INDEX).flatMap(_.split(","))
  val coverage = args.optional(AttributeIndexJob.INDEX_COVERAGE)
      .flatMap(c => Try(IndexCoverage.withName(c)).toOption)
      .getOrElse(IndexCoverage.JOIN)

  val input = GeoMesaInputOptions(dsParams, feature)

  // non-serializable resources - need to be lazy and transient so they are available to each mapper
  @transient lazy val ds = DataStoreFinder.getDataStore(dsParams.asJava).asInstanceOf[AccumuloDataStore]
  @transient lazy val sft = {
    val sft = ds.getSchema(feature)
    if (sft != null) {
      // set the coverage for each descriptor so that we write out the ones we want to index and not others
      sft.getAttributeDescriptors.foreach { d =>
        d.setIndexCoverage(if (attributes.contains(d.getLocalName)) coverage else IndexCoverage.NONE)
      }
    }
    sft
  }
  @transient lazy val writer =
    if (sft.getSchemaVersion < 6) AttributeTableV5.writer(sft) else AttributeTable.writer(sft)
  @transient lazy val encoding = ds.getFeatureEncoding(sft)
  @transient lazy val featureEncoder = SimpleFeatureSerializers(sft, encoding)
  @transient lazy val indexValueEncoder = IndexValueEncoder(sft)
  @transient lazy val visibilities = ds.writeVisibilities

  // validation
  {
    require(sft != null, s"The feature '$feature' does not exist in the input data store")
    val valid = sft.getAttributeDescriptors.map(_.getLocalName)
    attributes.foreach(a => assert(valid.contains(a), s"Attribute '$a' does not exist in feature $feature"))
  }

  val output = {
    val attributeTable = ds.getTableName(feature, AttributeTable)
    val instance = dsParams(instanceIdParam.getName)
    val zoos = dsParams(zookeepersParam.getName)
    val user = dsParams(userParam.getName)
    val pwd = dsParams(passwordParam.getName)
    AccumuloOutputOptions(instance, zoos, user, pwd, attributeTable, createTable = true)
  }

  // scalding job
  TypedPipe.from(GeoMesaSource(input)).flatMap { case (id, sf) =>
    writer(new FeatureToWrite(sf, visibilities, featureEncoder, indexValueEncoder)).map((null: Text, _))
  }.write(AccumuloSource(output))

  override def afterJobTasks() = {
    // schedule a table compaction to clean up the table
    ds.connector.tableOperations().compact(output.table, null, null, true, false)
    // update the metadata
    // reload the sft, as we nulled out the index flags earlier
    val sft = ds.getSchema(feature)
    def wasIndexed(ad: AttributeDescriptor) = attributes.contains(ad.getLocalName)
    sft.getAttributeDescriptors.filter(wasIndexed).foreach(_.setIndexCoverage(coverage))
    val updatedSpec = SimpleFeatureTypes.encodeType(sft)
    ds.updateIndexedAttributes(feature, updatedSpec)
  }
}

object AttributeIndexJob {

  val ATTRIBUTES_TO_INDEX = "geomesa.index.attributes"
  val INDEX_COVERAGE      = "geomesa.index.coverage"

  def runJob(conf: Configuration,
             dsParams: Map[String, String],
             feature: String,
             attributes: List[String],
             indexCoverage: IndexCoverage = IndexCoverage.JOIN) = {
    val args = Seq(FEATURE_IN -> List(feature),
                   ATTRIBUTES_TO_INDEX -> attributes,
                   INDEX_COVERAGE -> List(indexCoverage.toString)).toMap ++ toInArgs(dsParams)
    val instantiateJob = (args: Args) => new AttributeIndexJob(args)
    GeoMesaBaseJob.runJob(conf, args, instantiateJob)
  }
}


text:
using namespace ofp;

TEST(queue, test) {
  QueueBuilder queue;

  queue.setQueueId(0x11111111);
  queue.setPort(0x22222222);

  PropertyList props;
  props.add(QueuePropertyMinRate{34});
  props.add(QueuePropertyMaxRate{100});
  queue.setProperties(props.toRange());

  QueueList list;
  list.add(queue);

  for (auto &iter : list) {
    EXPECT_EQ(0x11111111, iter.queueId());
    EXPECT_EQ(0x22222222, iter.port());

    EXPECT_EQ(34, iter.properties().value<QueuePropertyMinRate>());
    EXPECT_EQ(100, iter.properties().value<QueuePropertyMaxRate>());
    EXPECT_EQ(2, iter.properties().itemCount());
  }

  EXPECT_EQ(0x30, list.size());
  EXPECT_HEX(
      "111111112222222200300000000000000001001000000000002200000000000000020010"
      "000000000064000000000000",
      list.data(), list.size());
}

TEST(queue, queuepropertyexperimenter) {
  {
    PropertyList props;
    props.add(QueuePropertyExperimenter{0x1234, {"foo", 3}});

    EXPECT_EQ(24, props.size());
    EXPECT_HEX("FFFF0013000000000000123400000000666F6F0000000000", props.data(),
               props.size());
  }

  {
    PropertyList props;
    props.add(QueuePropertyExperimenter{0x12345678, {}});

    EXPECT_EQ(16, props.size());
    EXPECT_HEX("FFFF0010000000001234567800000000", props.data(), props.size());
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Fl. Pl. South Africa 20: t. 779. 1940

#### Original name
null

### Remarks
null


text:
using namespace ild;

std::pair<float, float> Math::RotatePoint(const std::pair<float, float> & point, const std::pair<float, float> & origin, float theta)
{
    float xPos = std::cos(theta) * (point.first - origin.first) - std::sin(theta) * (point.second - origin.second) + origin.first;
    float yPos = std::sin(theta) * (point.first - origin.first) + std::cos(theta) * (point.second - origin.second) + origin.second;

    return std::pair<float,float>(xPos,yPos);
}

Math::Vector2 Math::GetEdge(const Point2 & vertexA, const Point2 & vertexB)
{
    return Vector2(vertexA.first - vertexB.first, vertexA.second - vertexB.second);
}

Math::Vector2 Math::GetNormal(const Vector2 & edge)
{
    return Vector2(-edge.second, edge.first);
}

float Math::Dot(const Math::Vector2 & a, const Math::Vector2 & b)
{
    return a.first * b.first + a.second * b.second;
}

Math::Projection2 Math::GetProjection(const Vertices2 & shapeA, const Vector2 & normal)
{
    auto max = -INFINITY;
    auto min = INFINITY;

    for(auto & point : shapeA)
    {
        auto dot = Dot(point, normal);
        max = fmax(max, dot);
        min = fmin(min, dot);
    }

    return Projection2(min, max);
}

bool Math::Intersect(const Projection2 & a, const Projection2 & b)
{
    return !(a.first > b.second || b.first > a.second);
}

float Math::FixMagnitude(const Math::Projection2 & a, const Math::Projection2 & b)
{
    if(a.first >= b.second || b.first > a.second)
    {
        return 0;
    }

    float left = b.first - a.second;  // negative
    float right = b.second - a.first; //positive

    return fabs(left) > fabs(right) ? right : left;
}

Math::Point2 Math::Normalize(const Math::Point2 & vector)
{
    float magnitude = sqrt(vector.first * vector.first + vector.second * vector.second);
    return Point2(vector.first / magnitude, vector.second / magnitude);
}

//Only test the axis's defined by shapeA
static bool TestShapeAxis(const Math::Vertices2 & shapeA, const Math::Vertices2 & shapeB)
{
    using namespace Math;
    for(auto i = 0u; i < shapeA.size(); i++)
    {
        auto endIndex = i + 1 >= shapeA.size() ? 0 : i + 1;
        auto edge = GetEdge(shapeA[i], shapeA[endIndex]);
        auto normal = GetNormal(edge);

        auto projectionA = GetProjection(shapeA, normal);
        auto projectionB = GetProjection(shapeB, normal);

        if(!Intersect(projectionA, projectionB))
        {
            return false;
        }
    }
    return true;
}

Math::CollisionFix Math::GetFixVector(const Math::Vertices2 & shapeA, const Math::Vertices2 & shapeB)
{
    using namespace Math;
    float min = INFINITY;
    Point2 normalOfMin;
    for(auto i = 0u; i < shapeA.size(); i++)
    {
        auto endIndex = i + 1 >= shapeA.size() ? 0 : i + 1;
        auto edge = GetEdge(shapeA[i], shapeA[endIndex]);
        auto normal = Normalize(GetNormal(edge));

        auto projectionA = GetProjection(shapeA, normal);
        auto projectionB = GetProjection(shapeB, normal);

        auto fix = FixMagnitude(projectionA, projectionB);

        if(fabs(fix) < fabs(min))
        {
            min = fix;
            normalOfMin = normal;
        }

        if (min == 0) {
            break;
        }
    }
    return Math::CollisionFix {normalOfMin, min};
}

bool Math::Collide(const Vertices2 & shapeA, const Vertices2 & shapeB)
{
    return TestShapeAxis(shapeA,shapeB) && TestShapeAxis(shapeB,shapeA);
}

bool Math::Collide(const Vertices2 & shapeA, const Vertices2 & shapeB, CollisionFix & collisionFix)
{
    CollisionFix fixA = GetFixVector(shapeA, shapeB);
    CollisionFix fixB = GetFixVector(shapeB, shapeA);

    fixB.magnitude *= -1;

    collisionFix = fabs(fixA.magnitude) <= fabs(fixB.magnitude) ? fixA : fixB;

    if (collisionFix.magnitude < 0)
    {
        collisionFix.magnitude *= -1;
        collisionFix.normal.first *= -1;
        collisionFix.normal.second *= -1;
    }

    return collisionFix.magnitude != 0;
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bd.ac.seu.iptools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;

/**
 *
 * @author kmhasan
 */
public class MainUIController implements Initializable {

    @FXML
    private Label statusLabel;
    @FXML
    private AnchorPane leftPane;
    @FXML
    private AnchorPane rightPane;
    private BufferedImage inputImage;
    private BufferedImage outputImage;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        inputImage = null;
        outputImage = null;
    }

    @FXML
    private void handleFileOpenAction(ActionEvent event) {
        try {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showOpenDialog(null);
            BufferedImage bufferedImage = ImageIO.read(file);
            inputImage = bufferedImage;
            if (bufferedImage != null) {
                outputImage = null;
            }
            statusLabel.setText("Opened " + file.getName() + " [" + bufferedImage.getWidth() + "x" + bufferedImage.getHeight() + "]");

            displayImage(inputImage, leftPane);
        } catch (IOException ex) {
            Logger.getLogger(MainUIController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    private void handleFileSaveAction(ActionEvent event) {
        try {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showSaveDialog(null);
            String format = file.getName().substring(file.getName().indexOf(".") + 1);
            ImageIO.write(outputImage, format, file);
            statusLabel.setText("Saving to " + file.getName() + " format: " + format);
        } catch (IOException ex) {
            Logger.getLogger(MainUIController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private BufferedImage toBufferedImage(double grayPixels[][]) {
        BufferedImage image = new BufferedImage(grayPixels[0].length, grayPixels.length, BufferedImage.TYPE_3BYTE_BGR);
        for (int r = 0; r < grayPixels.length; r++) {
            for (int c = 0; c < grayPixels[r].length; c++) {
                int value = (int) grayPixels[r][c];
                value = (value << 0) | (value << 8) | (value << 16);
                image.setRGB(c, r, value);
            }
        }
        return image;
    }

    private BufferedImage toBufferedImage(int grayPixels[][]) {
        BufferedImage image = new BufferedImage(grayPixels[0].length, grayPixels.length, BufferedImage.TYPE_3BYTE_BGR);
        for (int r = 0; r < grayPixels.length; r++) {
            for (int c = 0; c < grayPixels[r].length; c++) {
                int value = grayPixels[r][c];
                value = (value << 0) | (value << 8) | (value << 16);
                image.setRGB(c, r, value);
            }
        }
        return image;
    }

    private BufferedImage toGrayScale(BufferedImage rgbImage) {
        BufferedImage grayImage = new BufferedImage(rgbImage.getWidth(), rgbImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        for (int c = 0; c < rgbImage.getWidth(); c++) {
            for (int r = 0; r < rgbImage.getHeight(); r++) {
                int rgb = rgbImage.getRGB(c, r);
                int rr = (rgb >> 16) & 0xFF;
                int gg = (rgb >> 8) & 0xFF;
                int bb = (rgb >> 0) & 0xFF;

                int intensity = (int) (rr * 0.72 + gg * 0.21 + bb * 0.07);

                rgb = (intensity << 16) | (intensity << 8) | intensity;
                grayImage.setRGB(c, r, rgb);
            }
        }

        return grayImage;
    }

    private double[][] toGrayScaleArray(BufferedImage rgbImage) {
        double pixels[][] = new double[rgbImage.getHeight()][rgbImage.getWidth()];
        for (int c = 0; c < rgbImage.getWidth(); c++) {
            for (int r = 0; r < rgbImage.getHeight(); r++) {
                int rgb = rgbImage.getRGB(c, r);
                int rr = (rgb >> 16) & 0xFF;
                int gg = (rgb >> 8) & 0xFF;
                int bb = (rgb >> 0) & 0xFF;

                double intensity = rr * 0.72 + gg * 0.21 + bb * 0.07;
                pixels[r][c] = intensity;
            }
        }

        return pixels;
    }

    public BufferedImage otsusThreshold(BufferedImage grayscaleImage) {
        BufferedImage binaryImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        int frequency[] = new int[256];
        double p[] = new double[frequency.length];
        double P1[] = new double[frequency.length];
        double m[] = new double[frequency.length];
        double sB[] = new double[frequency.length]; // sigma square B 10.3-17
        double mG;
        int M = binaryImage.getWidth();
        int N = binaryImage.getHeight();

        for (int r = 0; r < grayscaleImage.getHeight(); r++) {
            for (int c = 0; c < grayscaleImage.getWidth(); c++) {
                int intensity = grayscaleImage.getRGB(c, r) & 0xFF;
                frequency[intensity]++;
            }
        }
        System.out.println("Histogram done");

        // Step 1, 2 and 3
        for (int i = 0; i < frequency.length; i++) {
            p[i] = ((double) frequency[i]) / (M * N);
            if (i == 0) {
                P1[i] = p[i];
                m[i] = i * p[i];
            } else {
                P1[i] = P1[i - 1] + p[i];
                m[i] = m[i - 1] + i * p[i];
            }
        }
        System.out.println("Cumulative sums done");

        // step 4
        mG = m[m.length - 1];
        double highestVariance = Double.MIN_VALUE;
        int bestK = -1;
        for (int k = 0; k < frequency.length; k++) {
            double numerator = mG * P1[k] - m[k];
            double denominator = P1[k] * (1 - P1[k]);
            sB[k] = numerator * numerator / denominator;
            if (sB[k] > highestVariance) {
                highestVariance = sB[k];
                bestK = k;
            }
        }
        System.out.println("Calculated best K");

        int threshold = bestK;
        for (int r = 0; r < grayscaleImage.getHeight(); r++) {
            for (int c = 0; c < grayscaleImage.getWidth(); c++) {
                int intensity = grayscaleImage.getRGB(c, r) & 0xFF;
                if (intensity < threshold) {
                    binaryImage.setRGB(c, r, 0);
                } else {
                    binaryImage.setRGB(c, r, (0xFF << 16 | 0xFF << 8 | 0xFF));
                }
            }
        }
        System.out.println("Applied threshold");
        return binaryImage;
    }

    private BufferedImage myThreshold(BufferedImage grayscaleImage, int threshold) {
        BufferedImage binaryImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        int M = binaryImage.getWidth();
        int N = binaryImage.getHeight();

        for (int r = 0; r < grayscaleImage.getHeight(); r++) {
            for (int c = 0; c < grayscaleImage.getWidth(); c++) {
                int intensity = grayscaleImage.getRGB(c, r) & 0xFF;
                if (intensity < threshold) {
                    binaryImage.setRGB(c, r, 0);
                } else {
                    binaryImage.setRGB(c, r, (0xFF << 16 | 0xFF << 8 | 0xFF));
                }
            }
        }
        return binaryImage;
    }

    @FXML
    private void handleRGBtoGrayscaleAction(ActionEvent event) {
        outputImage = toGrayScale(inputImage);
        displayImage(outputImage, rightPane);
    }

    @FXML
    private void handleRotateClockwiseAction(ActionEvent event) {
        outputImage = new BufferedImage(inputImage.getHeight(), inputImage.getWidth(), inputImage.getType());
        for (int c = 0; c < inputImage.getWidth(); c++) {
            for (int r = 0; r < inputImage.getHeight(); r++) {
                int rgb = inputImage.getRGB(c, r);
                outputImage.setRGB(inputImage.getHeight() - 1 - r, c, rgb);
            }
        }
        displayImage(outputImage, rightPane);
    }

    private void displayImage(BufferedImage bufferedImage, AnchorPane anchorPane) {
        Image image = SwingFXUtils.toFXImage(bufferedImage, null);
        ImageView imageView = new ImageView(image);
        anchorPane.getChildren().removeAll();
        anchorPane.getChildren().add(imageView);
    }

    private double[][] applyKernelArray(double grayPixels[][], int kernel[][]) {
        double outputPixels[][] = new double[grayPixels.length][grayPixels[0].length];

        int offset = kernel.length / 2;
        int kernelSum = 0;
        for (int r = 0; r < kernel.length; r++) {
            for (int c = 0; c < kernel[r].length; c++) {
                kernelSum += Math.abs(kernel[r][c]);
            }
        }

        for (int c = offset; c < grayPixels[0].length - offset; c++) {
            for (int r = offset; r < grayPixels.length - offset; r++) {
                double sum = 0;
                for (int dx = -offset; dx <= +offset; dx++) {
                    for (int dy = -offset; dy <= +offset; dy++) {
                        sum += kernel[dy + offset][dx + offset] * grayPixels[r + dy][c + dx];
                    }
                }

                sum /= kernelSum;
                outputPixels[r][c] = sum;
            }
        }

        return outputPixels;
    }

    private BufferedImage applyKernel(BufferedImage image, int kernel[][]) {
        BufferedImage outputImage;
        outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());

        int offset = kernel.length / 2;
        int kernelSum = 0;
        for (int r = 0; r < kernel.length; r++) {
            for (int c = 0; c < kernel[r].length; c++) {
                kernelSum += Math.abs(kernel[r][c]);
            }
        }

        for (int c = offset; c < inputImage.getWidth() - offset; c++) {
            for (int r = offset; r < inputImage.getHeight() - offset; r++) {
                int sumRed = 0;
                int sumGreen = 0;
                int sumBlue = 0;
                for (int dx = -offset; dx <= +offset; dx++) {
                    for (int dy = -offset; dy <= +offset; dy++) {
                        int newc = c + dx;
                        int newr = r + dy;

                        int newrgb = inputImage.getRGB(newc, newr);
                        int newrr = (newrgb >> 16) & 0xFF;
                        int newgg = (newrgb >> 8) & 0xFF;
                        int newbb = (newrgb >> 0) & 0xFF;

                        int multipliedValue;
                        multipliedValue = kernel[dy + offset][dx + offset] * newrr;
                        sumRed += multipliedValue;
                        multipliedValue = kernel[dy + offset][dx + offset] * newgg;
                        sumGreen += multipliedValue;
                        multipliedValue = kernel[dy + offset][dx + offset] * newbb;
                        sumBlue += multipliedValue;
                    }
                }

                sumRed /= kernelSum;
                sumGreen /= kernelSum;
                sumBlue /= kernelSum;

                if (sumRed < 0) {
                    sumRed = 0;
                }
                if (sumRed > 255) {
                    sumRed = 255;
                }
                if (sumGreen < 0) {
                    sumGreen = 0;
                }
                if (sumGreen > 255) {
                    sumGreen = 255;
                }
                if (sumBlue < 0) {
                    sumBlue = 0;
                }
                if (sumBlue > 255) {
                    sumBlue = 255;
                }

                int rgb = (sumRed << 16) | (sumGreen << 8) | (sumBlue);
                outputImage.setRGB(c, r, rgb);
            }
        }

        return outputImage;
    }

    @FXML
    private void handleBoxBlurAction(ActionEvent event) {
        // Implemented by Kazi Fazle Azim Rabi
        System.out.println("inside");

        outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());

        int blurKernel[][] = {
            {+1, +2, +1},
            {+2, +4, +2},
            {+1, +2, +1}
        };

        int offset = blurKernel.length / 2;

        for (int c = offset; c < inputImage.getWidth() - offset; c++) {
            for (int r = offset; r < inputImage.getHeight() - offset; r++) {
                int sumRed = 0;
                int sumGreen = 0;
                int sumBlue = 0;
                for (int dx = -offset; dx <= +offset; dx++) {
                    for (int dy = -offset; dy <= +offset; dy++) {
                        int newc = c + dx;
                        int newr = r + dy;

                        int newrgb = inputImage.getRGB(newc, newr);
                        int newrr = (newrgb >> 16) & 0xFF;
                        int newgg = (newrgb >> 8) & 0xFF;
                        int newbb = (newrgb >> 0) & 0xFF;

                        int multipliedValue;
                        multipliedValue = blurKernel[dy + offset][dx + offset] * newrr;
                        sumRed += multipliedValue;
                        multipliedValue = blurKernel[dy + offset][dx + offset] * newgg;
                        sumGreen += multipliedValue;
                        multipliedValue = blurKernel[dy + offset][dx + offset] * newbb;
                        sumBlue += multipliedValue;
                    }
                }
                int rgb = (sumRed << 16) | (sumGreen << 8) | (sumBlue);
                outputImage.setRGB(c, r, rgb);
                // DIVIDE the sum values by 9
                // pack the new RGBs into one integer
                // put the integer in the new image
            }
        }
        System.out.println("done");
        displayImage(outputImage, rightPane);
    }

    @FXML
    private void handleCannyAction(ActionEvent event) {
        // kernels
        int gaussianKernel[][] = {
            {1, 2, 1},
            {2, 4, 2},
            {1, 2, 1}
        };
        int sobelGx[][] = {
            {-1, 0, +1},
            {-2, 0, +2},
            {-1, 0, +1}
        };
        int sobelGy[][] = {
            {-1, -2, -1},
            {0, 0, 0},
            {+1, +2, +1}
        };

        double grayPixels[][] = null;
        double blurPixels[][] = null;
        double gx[][] = null;
        double gy[][] = null;
        double gn[][] = null;
        int gnh[][] = null;
        int gnl[][] = null;
        int output[][] = null;
        double M[][] = null;
        double alpha[][] = null;
        double tl; // low threshold
        double th; // high threshold

        // step 0
        // RGB -> Gray Scale
        grayPixels = toGrayScaleArray(inputImage);

        // step 1
        // Smooth the input image with a Gaussian filter
        blurPixels = applyKernelArray(grayPixels, gaussianKernel);

        // step 2
        // Calculate gradient vector components
        gx = applyKernelArray(blurPixels, sobelGx);
        gy = applyKernelArray(blurPixels, sobelGy);

        // step 2 and 3
        // Calculate non maxima suppressed image
        M = new double[gx.length][gx[0].length];
        alpha = new double[gx.length][gx[0].length];
        gn = new double[gx.length][gx[0].length];
        gnl = new int[gx.length][gx[0].length];
        gnh = new int[gx.length][gx[0].length];
        output = new int[gx.length][gx[0].length];
        double minM = Double.MAX_VALUE;
        double maxM = Double.MIN_VALUE;
        for (int r = 1; r < gx.length - 1; r++) {
            for (int c = 1; c < gx[0].length - 1; c++) {
                M[r][c] = Math.sqrt(gx[r][c] * gx[r][c] + gy[r][c] * gy[r][c]);
                alpha[r][c] = Math.atan(gy[r][c] / gx[r][c]);
                if (gx[r][c] != 0.0) {
                    if (alpha[r][c] < 0) {
                        alpha[r][c] += Math.PI / 2;
                    }
                } else {
                    alpha[r][c] = Math.PI / 2;
                }
                minM = Math.min(minM, M[r][c]);
                maxM = Math.max(maxM, M[r][c]);
                if ((alpha[r][c] >= -Math.PI / 8 * 1 && alpha[r][c] < Math.PI / 8 * 1)
                        || (alpha[r][c] >= Math.PI / 8 * 7 && alpha[r][c] < Math.PI / 8 * 9)) {
                    if (M[r][c] < M[r][c - 1] || M[r][c] < M[r][c + 1]) {
                        gn[r][c] = 0;
                    } else {
                        gn[r][c] = M[r][c];
                    }
                } else if (alpha[r][c] >= Math.PI / 8 * 1 && alpha[r][c] < Math.PI / 8 * 3) {
                    if (M[r][c] < M[r - 1][c + 1] || M[r][c] < M[r + 1][c - 1]) {
                        gn[r][c] = 0;
                    } else {
                        gn[r][c] = M[r][c];
                    }
                } else if (alpha[r][c] >= Math.PI / 8 * 3 && alpha[r][c] < Math.PI / 8 * 5) {
                    if (M[r][c] < M[r - 1][c] || M[r][c] < M[r + 1][c]) {
                        gn[r][c] = 0;
                    } else {
                        gn[r][c] = M[r][c];
                    }
                } else if (alpha[r][c] >= Math.PI / 8 * 5 && alpha[r][c] < Math.PI / 8 * 7) {
                    if (M[r][c] < M[r - 1][c - 1] || M[r][c] < M[r + 1][c + 1]) {
                        gn[r][c] = 0;
                    } else {
                        gn[r][c] = M[r][c];
                    }
                } else {
                    ;
                }
            }
        }

//        tl = minM + (maxM - minM) / 4.0;
//        th = minM + (maxM - minM) / 4.0 * 3.0;
        // need to add slider so that users can pick tl and th values
        tl = 5;
        th = 20;

        for (int r = 1; r < gn.length - 1; r++) {
            for (int c = 1; c < gn[0].length - 1; c++) {
                if (gn[r][c] > tl) {
                    gnl[r][c] = 0xFF;
                } else {
                    gnl[r][c] = 0;
                }
                if (gn[r][c] > th) {
                    gnh[r][c] = 0xFF;
                } else {
                    gnh[r][c] = 0;
                }

                // connectivity analysis
                for (int dr = -1; dr <= +1; dr++) {
                    for (int dc = -1; dc <= +1; dc++) {
                        if (gnh[r][c] > 0) {
                            output[r][c] = 255;
                            if (gnl[r + dr][c + dc] > 0)
                                output[r][c] = 255;
                        }
                    }
                }
            }
        }

        outputImage = toBufferedImage(output);
        statusLabel.setText(String.format("M %.2f %.2f Thresholds %.2f %.2f", minM, maxM, tl, th));
        /*
        BufferedImage gx = applyKernel(outputImage, sobelGx);
        BufferedImage gy = applyKernel(outputImage, sobelGy);

        calculateMagnitude(M, alpha, gx, gy);
         */
        //displayImage(inputImage, leftPane);
        displayImage(outputImage, rightPane);
    }

    /*
    @FXML
    private void handleCannyAction(ActionEvent event) {
        // kernels
        int gaussianKernel[][] = {
            {1, 2, 1},
            {2, 4, 2},
            {1, 2, 1}
        };
        int sobelGx[][] = {
            {-1, 0, +1},
            {-2, 0, +2},
            {-1, 0, +1}
        };
        int sobelGy[][] = {
            {-1, -2, -1},
            {0, 0, 0},
            {+1, +2, +1}
        };
        BufferedImage M = null;
        double alpha[][] = null;

        outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());
        // step 0
        // RGB -> Gray Scale
        outputImage = toGrayScale(outputImage);

        // step 1
        // Smooth the input image with a Gaussian filter
        outputImage = applyKernel(outputImage, gaussianKernel);

        BufferedImage gx = applyKernel(outputImage, sobelGx);
        BufferedImage gy = applyKernel(outputImage, sobelGy);

        calculateMagnitude(M, alpha, gx, gy);
    }
     */
    private void calculateMagnitude(BufferedImage M, double[][] alpha, BufferedImage gx, BufferedImage gy) {
        M = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());
        alpha = new double[inputImage.getHeight()][inputImage.getWidth()];

        for (int c = 0; c < inputImage.getWidth(); c++) {
            for (int r = 0; r < inputImage.getHeight(); r++) {
                int valueGx = gx.getRGB(c, r) & 0xFF;
                int valueGy = gy.getRGB(c, r) & 0xFF;
                int valueM = (int) (Math.sqrt(valueGx * valueGx + valueGy * valueGy));
                if (valueM > 255) {
                    valueM = 255;
                }
                valueM = (valueM << 16) | (valueM << 8) | (valueM << 0);
                M.setRGB(c, r, valueM);
            }
        }
        M = myThreshold(M, 1);
        System.out.println("Displaying M");
        displayImage(M, rightPane);
    }

    @FXML
    private void handleTestOpAction(ActionEvent event) {
        double pixels[][] = toGrayScaleArray(inputImage);
        BufferedImage image = toBufferedImage(pixels);
        displayImage(image, rightPane);
    }
}


text:
package us.dot.its.jpo.ode.plugin.j2735;

import us.dot.its.jpo.ode.plugin.asn1.Asn1Object;

public class J2735SpeedandHeadingandThrottleConfidence extends Asn1Object {
	private static final long serialVersionUID = 1L;

	public J2735HeadingConfidence heading;
	public J2735SpeedConfidence speed;
	public J2735ThrottleConfidence throttle;

}


text:
package net.sf.plugfy.sample;

/**
 * a sample return type
 *
 * @author hendrik
 * @param <T> type
 */
public class SampleReturn<T> {
    // empty
}


text:
define({
//Body
	loadingInfo: "Betöltés...",
	emptyInfo: "Nincsenek megjelenítendő elemek",
	loadFailInfo: "Az adatokat nem sikerült betölteni!",
	loadMore: "Továbbiak betöltése",
	loadMoreLoading: "Betöltés...",
	loadPrevious: "Előző betöltése",
	loadPreviousLoading: "Betöltés...",

//FilterBar
	"clearFilterDialogTitle": "Szűrő törlése",
	"filterDefDialogTitle": "Szűrő",
	"defaultRuleTitle": "Szabály",
	"ruleTitleTemplate": "${ruleNumber}. szabály",
	"noFilterApplied": "Nincs alkalmazott szűrő.",
	"defineFilter": "Szűrő meghatározása",
	"conditionEqual": "egyenlő",
	"conditionNotEqual": "nem egyenlő",
	"conditionLess": "kisebb",
	"conditionLessEqual": "kisebb vagy egyenlő",
	"conditionGreater": "nagyobb",
	"conditionGreaterEqual": "nagyobb vagy egyenlő",
	"conditionContain": "tartalmaz",
	"conditionIs": "azonos",
	"conditionStartWith": "következővel kezdődik",
	"conditionEndWith": "következőre végződik",
	"conditionNotContain": "nem tartalmaz",
	"conditionIsNot": "nem azonos",
	"conditionNotStartWith": "nem a következővel kezdődik",
	"conditionNotEndWith": "nem a következőre végződik",
	"conditionBefore": "előtt",
	"conditionAfter": "után",
	"conditionRange": "tartomány",
	"conditionIsEmpty": "üres",
	"all": "mind",
	"any": "bármely",
	"relationAll": "minden szabály",
	"waiRelAll": "Az összes következő szabálynak megfelel:",
	"relationAny": "bármely szabály",
	"waiRelAny": "Bármely következő szabálynak megfelel:",
	"relationMsgFront": "Egyeztetés",
	"relationMsgTail": "",
	"and": "és",
	"or": "vagy",
	"addRuleButton": "Szabály hozzáadása",
	"waiAddRuleButton": "Új szabály hozzáadása",
	"removeRuleButton": "Szabály eltávolítása",
	"waiRemoveRuleButtonTemplate": "${0} szabály eltávolítása",
	"addRuleButton": "Szűrőszabály hozzáadása",
	"cancelButton": "Mégse",
	"waiCancelButton": "Párbeszédablak bezárása",
	"clearButton": "Törlés",
	"waiClearButton": "A szűrő törlése",
	"filterButton": "Szűrő",
	"waiFilterButton": "Szűrő elküldése",
	"columnSelectLabel": "Oszlop:",
	"waiColumnSelectTemplate": "A(z) ${0} szabály oszlopa",
	"conditionSelectLabel": "Feltétel:",
	"waiConditionSelectTemplate": "A(z) ${0} szabály feltétele",
	"valueBoxLabel": "Érték:",
	"waiValueBoxTemplate": "Adjon meg értéket a(z) ${0} szabály szűréséhez",
	"rangeTo": "vég",
	"rangeTemplate": "kezdet: ${0}, vég: ${1}",
	"statusTipHeaderColumn": "Oszlop",
	"statusTipHeaderCondition": "Szabályok",
	"statusTipTitle": "Szűrősáv",
	"statusTipMsg": "Kattintson ide a szűrősávon a(z) ${0} értékeire végzett szűréshez.",
	"anycolumn": "bármely oszlop",
	"statusTipTitleNoFilter": "Szűrősáv",
	"statusTipTitleHasFilter": "Szűrő",
	"statusTipRelPre": "Egyeztetés",
	"statusTipRelPost": "szabályokkal.",
	"statusTipHeaderAll": "Egyeztetés az összes szabállyal.",
	"statusTipHeaderAny": "Egyeztetés bármely szabállyal.",
	"defaultItemsName": "elem",
	"filterBarMsgHasFilterTemplate": "${0} / ${1} ${2} megjelenítve.",
	"filterBarMsgNoFilterTemplate": "Nincs alkalmazott szűrő",
	"filterBarDefButton": "Szűrő meghatározása",
	"waiFilterBarDefButton": "Táblázat szűrése",
	"a11yFilterBarDefButton": "Szűrés...",
	"filterBarClearButton": "Szűrő törlése",
	"waiFilterBarClearButton": "A szűrő törlése",
	"closeFilterBarBtn": "Szűrősáv bezárása",
	"clearFilterMsg": "Ez a művelet eltávolítja a szűrőt és minden elérhető rekordot megjelenít.",
	"anyColumnOption": "Bármely oszlop",
	"trueLabel": "Igaz",
	"falseLabel": "Hamis",
	"radioTrueLabel": "Igaz érték",
	"radioFalseLabel": "Hamis érték",
	"beginTimeRangeLabel": "Időtartomány-érték kezdete",
	"endTimeRangeLabel": "Időtartomány-érték vége",
	"beginDateRangeLabel": "Dátumtartomány-érték kezdete",
	"endDateRangeLabel": "Dátumtartomány-érték vége",
	"startsWithExpr": "${0}*",

//NestedSort
	singleSort: "Egyszeri rendezés",
	nestedSort: "Beágyazott rendezés",
	ascending: "Kattintson ide a növekvő sorrend szerinti rendezéshez",
	descending: "Kattintson ide a csökkenő sorrend szerinti rendezéshez",
	sortingState: "${0} - ${1}",
	unsorted: "Ne rendezze ezt az oszlopot",
	waiSingleSortLabel: "${0} - ${1} szerint van rendezve. Válassza ki a(z) ${2} szerinti rendezéshez",
	waiNestedSortLabel:"${0} - ${1} szerint van beágyazott módon rendezve. Válassza ki a(z) ${2} szerinti beágyazott rendezéshez",

//PaginationBar
	pagerWai: 'Lapozó',

	pageIndex: '${0}',
	pageIndexTitle: '${0}. oldal',

	firstPageTitle: 'Első oldal',
	prevPageTitle: 'Előző oldal',
	nextPageTitle: 'Következő oldal',
	lastPageTitle: 'Utolsó oldal',

	pageSize: '${0}',
	pageSizeTitle: '${0} elem oldalanként',
	pageSizeAll: 'Összes',
	pageSizeAllTitle: 'Összes elem',

	description: '${0} - ${1} / ${2} elem.',
	descriptionEmpty: 'A rács üres.',

	summary: 'Összesen: ${0}',
	summaryWithSelection: 'Összesen: ${0}, kiválasztva: ${1}',

	gotoBtnTitle: 'Ugrás egy adott oldalra',

	gotoDialogTitle: 'Ugrás oldalra',
	gotoDialogMainMsg: 'Adja meg az oldalszámot:',
	gotoDialogPageCount: '(${0} oldal)',
	gotoDialogOKBtn: 'Ugrás',
	gotoDialogCancelBtn: 'Mégse',
	// for drop down pagination bar
	pageLabel: 'Oldal',
	pageSizeLabel: 'Sorok',

//QuickFilter
	filterLabel: 'Szűrő',
	clearButtonTitle: 'Szűrő törlése',
	buildFilterMenuLabel: '… összeépítés-szűrő',
	apply: 'Szűrő alkalmazása',

//Sort
	helpMsg: '${0} - Kattintson ide a rendezéshez, vagy használja a Ctrl-kattintás kombinációt a rendezéshez hozzáadáshoz',
	singleHelpMsg: '${0} - Kattintson ide a rendezéshez',
	priorityOrder: 'rendezési prioritás: ${0}',

//SummaryBar
	summaryTotal: 'Összesen: ${0}',
	summarySelected: 'Kiválasztva: ${0}',
	summaryRange: 'Tartomány: ${0}-${1}',	//need translation

//Other
	indirectSelectAll: "Az összes kijelöléséhez nyomja meg a SZÓKÖZ gombot.",	//need translation
	indirectDeselectAll: "Az összes kijelölésének megszüntetéséhez nyomja meg a SZÓKÖZ gombot.",	//need translation
	treeExpanded: "A Control + balra mutató nyíl gombbal összehúzhatja ezt a sort.",	//need translation
	treeCollapsed: "A Control + jobbra mutató nyíl gombbal kibonthatja ezt a sort."	//need translation
});


text:
package griffon.pivot.support.adapters;

import groovy.lang.Closure;

/**
 * @author Andres Almiray
 */
public class MenuAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.MenuListener {
    private Closure activeItemChanged;
    private Closure sectionInserted;
    private Closure sectionsRemoved;

    public Closure getActiveItemChanged() {
        return this.activeItemChanged;
    }

    public Closure getSectionInserted() {
        return this.sectionInserted;
    }

    public Closure getSectionsRemoved() {
        return this.sectionsRemoved;
    }

    public void setActiveItemChanged(Closure activeItemChanged) {
        this.activeItemChanged = activeItemChanged;
        if (this.activeItemChanged != null) {
            this.activeItemChanged.setDelegate(this);
            this.activeItemChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
        }
    }

    public void setSectionInserted(Closure sectionInserted) {
        this.sectionInserted = sectionInserted;
        if (this.sectionInserted != null) {
            this.sectionInserted.setDelegate(this);
            this.sectionInserted.setResolveStrategy(Closure.DELEGATE_FIRST);
        }
    }

    public void setSectionsRemoved(Closure sectionsRemoved) {
        this.sectionsRemoved = sectionsRemoved;
        if (this.sectionsRemoved != null) {
            this.sectionsRemoved.setDelegate(this);
            this.sectionsRemoved.setResolveStrategy(Closure.DELEGATE_FIRST);
        }
    }

    public void activeItemChanged(org.apache.pivot.wtk.Menu arg0, org.apache.pivot.wtk.Menu.Item arg1) {
        if (activeItemChanged != null) {
            activeItemChanged.call(arg0, arg1);
        }
    }

    public void sectionInserted(org.apache.pivot.wtk.Menu arg0, int arg1) {
        if (sectionInserted != null) {
            sectionInserted.call(arg0, arg1);
        }
    }

    public void sectionsRemoved(org.apache.pivot.wtk.Menu arg0, int arg1, org.apache.pivot.collections.Sequence arg2) {
        if (sectionsRemoved != null) {
            sectionsRemoved.call(arg0, arg1, arg2);
        }
    }

}


text:
package StringAndArray;

import java.util.*;

/**
 *
 * @author Quang Vu
 * Purpose: the solver rotate an array of n-elements at k-steps
 * EXP: n = 7, k = 3
 * [1,2,3,4,5,6,7] ---------> [5,6,7,1,2,3,4]
 *
 */
public class Solver {

   public static void main(String[] args) {
     // Read in user input and initialize the original array
     Scanner scanner = new Scanner(System.in);
     System.out.println("Please enter the number of an array:");
     int n = scanner.nextInt();
     System.out.println("Please enter the number of steps:");
     int k = scanner.nextInt();

     int[] originalArray = new int[n];
     int num = 1;
     for(int i = 0; i < originalArray.length; i++){
        originalArray[i] = num;
        num++;
     }

     /*
      * Rotating mechanism:
      * Add element at index (k+1) from the original array to the rotated array
      * and increment k until k is not bigger than the original array's length
      *
      * Add the rest to the rotated array from index 0 of original array
      */
     int[] rotatedArray = new int[n];
     int index = 0;
     k++;
     for(int j = 0; j < originalArray.length; j++){
        if(!(k >= originalArray.length)){
           rotatedArray[j] = originalArray[k];
           k++;
        }
        else{
           rotatedArray[j] = originalArray[index];
           index++;
        }
     }
     System.out.println(Arrays.toString(rotatedArray));
   }

}


text:
package actors

import akka.actor.{Actor, ActorRef, ActorLogging, Props}
import play.api.mvc.WebSocket.FrameFormatter
import play.api.libs.json.{__, Format, Writes, Reads, Json, JsError}
import akka.event.Logging
import play.api.libs.json._
import cc.mewa.channels.ChannelManagerActor
import cc.mewa.channels.ChannelActor
import cc.mewa.api.Protocol._
import akka.actor.PoisonPill

object HttpEventActor {
  def props(channel: String, password: String, device: String) = Props(new HttpEventActor(channel, password, device))

  case class SendEvent(eventId: String, content: String)
}

/**
 * Http event actor implementation
 */
class HttpEventActor(channel: String, password: String, device: String) extends Actor with ActorLogging {

  import HttpEventActor.SendEvent

  def receive: Actor.Receive = {

    case SendEvent(id, content) =>
      val manager = context.actorSelection("/user/channel-manager")
      manager ! ChannelManagerActor.GetChannel(channel, device, password)
      context.become(receiveEvent(id, content))
  }

  def receiveEvent(id: String, content: String): Actor.Receive = {

    case ChannelManagerActor.ChannelFound(channel) =>
      channel ! ChannelActor.Event(device, id, content, "")
      self ! PoisonPill

    case _ => self ! PoisonPill
  }
}