text:
import React, { Component } from 'react';
import '../stylesheets/components/simulator.css';

class ColorBlindnessView extends Component {

  componentWillMount() {
    const script1 = document.createElement("script");
    script1.src = "jsColorblindSimulator/panZoomImage.js";
    script1.async = true;
    document.body.appendChild(script1);

    const script2 = document.createElement("script");
    script2.src = "jsColorblindSimulator/hcirn_colorblind_simulation.js";
    script2.async = true;
    document.body.appendChild(script2);

    const script3 = document.createElement("script");
    script3.src = "jsColorblindSimulator/colorblind.js";
    script3.async = true;
    document.body.appendChild(script3);

    const script4 = document.createElement("script");
    script4.src = "jsColorblindSimulator/colorblindViewInterface.js";
    script4.async = true;
    document.body.appendChild(script4);
  };

  render(){
    var displayNone = {
      display: 'none'
    };
    var height100 = {
      height: '100%'
    };

    return (

Try the simulator!

            FILE UPLOAD
            <input type="file" id="fileInput"/>   Computing...

<input type="radio" name="colorblindType" value="Normal" id="defaultCheck"/> Normal

<input type="radio" name="colorblindType" value="Protanopia"/> Protanopia

<input type="radio" name="colorblindType" value="Protanomaly"/> Protanomaly

<input type="radio" name="colorblindType" value="Deuteranopia"/> Deuteranopia

<input type="radio" name="colorblindType" value="Deuteranomaly"/> Deuteranomaly

<input type="radio" name="colorblindType" value="Tritanopia"/> Tritanopia

<input type="radio" name="colorblindType" value="Tritanomaly"/> Tritanomaly

<input type="radio" name="colorblindType" value="Achromatopsia"/> Achromatopsia

<input type="radio" name="colorblindType" value="Achromatomaly"/> Achromatomaly

Drop your image to load it

            <canvas id="outCanvas">Your Browser does not support <canvas>.</canvas>

      );
  }
}

export default ColorBlindnessView;


text:
import * as glMatrix from "./common.js";

/**
 * 2 Dimensional Vector
 * @module vec2
 */

/**
 * Creates a new, empty vec2
 *
 * @returns {vec2} a new 2D vector
 */
export function create() {
  let out = new glMatrix.ARRAY_TYPE(2);
  out[0] = 0;
  out[1] = 0;
  return out;
}

/**
 * Creates a new vec2 initialized with values from an existing vector
 *
 * @param {vec2} a vector to clone
 * @returns {vec2} a new 2D vector
 */
export function clone(a) {
  let out = new glMatrix.ARRAY_TYPE(2);
  out[0] = a[0];
  out[1] = a[1];
  return out;
}

/**
 * Creates a new vec2 initialized with the given values
 *
 * @param {Number} x X component
 * @param {Number} y Y component
 * @returns {vec2} a new 2D vector
 */
export function fromValues(x, y) {
  let out = new glMatrix.ARRAY_TYPE(2);
  out[0] = x;
  out[1] = y;
  return out;
}

/**
 * Copy the values from one vec2 to another
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the source vector
 * @returns {vec2} out
 */
export function copy(out, a) {
  out[0] = a[0];
  out[1] = a[1];
  return out;
}

/**
 * Set the components of a vec2 to the given values
 *
 * @param {vec2} out the receiving vector
 * @param {Number} x X component
 * @param {Number} y Y component
 * @returns {vec2} out
 */
export function set(out, x, y) {
  out[0] = x;
  out[1] = y;
  return out;
}

/**
 * Adds two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function add(out, a, b) {
  out[0] = a[0] + b[0];
  out[1] = a[1] + b[1];
  return out;
}

/**
 * Subtracts vector b from vector a
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function subtract(out, a, b) {
  out[0] = a[0] - b[0];
  out[1] = a[1] - b[1];
  return out;
}

/**
 * Multiplies two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function multiply(out, a, b) {
  out[0] = a[0] * b[0];
  out[1] = a[1] * b[1];
  return out;
};

/**
 * Divides two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function divide(out, a, b) {
  out[0] = a[0] / b[0];
  out[1] = a[1] / b[1];
  return out;
};

/**
 * Math.ceil the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to ceil
 * @returns {vec2} out
 */
export function ceil(out, a) {
  out[0] = Math.ceil(a[0]);
  out[1] = Math.ceil(a[1]);
  return out;
};

/**
 * Math.floor the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to floor
 * @returns {vec2} out
 */
export function floor(out, a) {
  out[0] = Math.floor(a[0]);
  out[1] = Math.floor(a[1]);
  return out;
};

/**
 * Returns the minimum of two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function min(out, a, b) {
  out[0] = Math.min(a[0], b[0]);
  out[1] = Math.min(a[1], b[1]);
  return out;
};

/**
 * Returns the maximum of two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec2} out
 */
export function max(out, a, b) {
  out[0] = Math.max(a[0], b[0]);
  out[1] = Math.max(a[1], b[1]);
  return out;
};

/**
 * Math.round the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to round
 * @returns {vec2} out
 */
export function round (out, a) {
  out[0] = Math.round(a[0]);
  out[1] = Math.round(a[1]);
  return out;
};

/**
 * Scales a vec2 by a scalar number
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the vector to scale
 * @param {Number} b amount to scale the vector by
 * @returns {vec2} out
 */
export function scale(out, a, b) {
  out[0] = a[0] * b;
  out[1] = a[1] * b;
  return out;
};

/**
 * Adds two vec2's after scaling the second operand by a scalar value
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @param {Number} scale the amount to scale b by before adding
 * @returns {vec2} out
 */
export function scaleAndAdd(out, a, b, scale) {
  out[0] = a[0] + (b[0] * scale);
  out[1] = a[1] + (b[1] * scale);
  return out;
};

/**
 * Calculates the euclidian distance between two vec2's
 *
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {Number} distance between a and b
 */
export function distance(a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1];
  return Math.sqrt(x*x + y*y);
};

/**
 * Calculates the squared euclidian distance between two vec2's
 *
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {Number} squared distance between a and b
 */
export function squaredDistance(a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1];
  return x*x + y*y;
};

/**
 * Calculates the length of a vec2
 *
 * @param {vec2} a vector to calculate length of
 * @returns {Number} length of a
 */
export function length(a) {
  var x = a[0],
    y = a[1];
  return Math.sqrt(x*x + y*y);
};

/**
 * Calculates the squared length of a vec2
 *
 * @param {vec2} a vector to calculate squared length of
 * @returns {Number} squared length of a
 */
export function squaredLength (a) {
  var x = a[0],
    y = a[1];
  return x*x + y*y;
};

/**
 * Negates the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to negate
 * @returns {vec2} out
 */
export function negate(out, a) {
  out[0] = -a[0];
  out[1] = -a[1];
  return out;
};

/**
 * Returns the inverse of the components of a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to invert
 * @returns {vec2} out
 */
export function inverse(out, a) {
  out[0] = 1.0 / a[0];
  out[1] = 1.0 / a[1];
  return out;
};

/**
 * Normalize a vec2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a vector to normalize
 * @returns {vec2} out
 */
export function normalize(out, a) {
  var x = a[0],
    y = a[1];
  var len = x*x + y*y;
  if (len > 0) {
    //TODO: evaluate use of glm_invsqrt here?
    len = 1 / Math.sqrt(len);
    out[0] = a[0] * len;
    out[1] = a[1] * len;
  }
  return out;
};

/**
 * Calculates the dot product of two vec2's
 *
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {Number} dot product of a and b
 */
export function dot(a, b) {
  return a[0] * b[0] + a[1] * b[1];
};

/**
 * Computes the cross product of two vec2's
 * Note that the cross product must by definition produce a 3D vector
 *
 * @param {vec3} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @returns {vec3} out
 */
export function cross(out, a, b) {
  var z = a[0] * b[1] - a[1] * b[0];
  out[0] = out[1] = 0;
  out[2] = z;
  return out;
};

/**
 * Performs a linear interpolation between two vec2's
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the first operand
 * @param {vec2} b the second operand
 * @param {Number} t interpolation amount between the two inputs
 * @returns {vec2} out
 */
export function lerp(out, a, b, t) {
  var ax = a[0],
    ay = a[1];
  out[0] = ax + t * (b[0] - ax);
  out[1] = ay + t * (b[1] - ay);
  return out;
};

/**
 * Generates a random vector with the given scale
 *
 * @param {vec2} out the receiving vector
 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
 * @returns {vec2} out
 */
export function random(out, scale) {
  scale = scale || 1.0;
  var r = glMatrix.RANDOM() * 2.0 * Math.PI;
  out[0] = Math.cos(r) * scale;
  out[1] = Math.sin(r) * scale;
  return out;
};

/**
 * Transforms the vec2 with a mat2
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the vector to transform
 * @param {mat2} m matrix to transform with
 * @returns {vec2} out
 */
export function transformMat2(out, a, m) {
  var x = a[0],
    y = a[1];
  out[0] = m[0] * x + m[2] * y;
  out[1] = m[1] * x + m[3] * y;
  return out;
};

/**
 * Transforms the vec2 with a mat2d
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the vector to transform
 * @param {mat2d} m matrix to transform with
 * @returns {vec2} out
 */
export function transformMat2d(out, a, m) {
  var x = a[0],
    y = a[1];
  out[0] = m[0] * x + m[2] * y + m[4];
  out[1] = m[1] * x + m[3] * y + m[5];
  return out;
};

/**
 * Transforms the vec2 with a mat3
 * 3rd vector component is implicitly '1'
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the vector to transform
 * @param {mat3} m matrix to transform with
 * @returns {vec2} out
 */
export function transformMat3(out, a, m) {
  var x = a[0],
    y = a[1];
  out[0] = m[0] * x + m[3] * y + m[6];
  out[1] = m[1] * x + m[4] * y + m[7];
  return out;
};

/**
 * Transforms the vec2 with a mat4
 * 3rd vector component is implicitly '0'
 * 4th vector component is implicitly '1'
 *
 * @param {vec2} out the receiving vector
 * @param {vec2} a the vector to transform
 * @param {mat4} m matrix to transform with
 * @returns {vec2} out
 */
export function transformMat4(out, a, m) {
  let x = a[0];
  let y = a[1];
  out[0] = m[0] * x + m[4] * y + m[12];
  out[1] = m[1] * x + m[5] * y + m[13];
  return out;
}

/**
 * Returns a string representation of a vector
 *
 * @param {vec2} a vector to represent as a string
 * @returns {String} string representation of the vector
 */
export function str(a) {
  return 'vec2(' + a[0] + ', ' + a[1] + ')';
}

/**
 * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
 *
 * @param {vec2} a The first vector.
 * @param {vec2} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
export function exactEquals(a, b) {
  return a[0] === b[0] && a[1] === b[1];
}

/**
 * Returns whether or not the vectors have approximately the same elements in the same position.
 *
 * @param {vec2} a The first vector.
 * @param {vec2} b The second vector.
 * @returns {Boolean} True if the vectors are equal, false otherwise.
 */
export function equals(a, b) {
  let a0 = a[0], a1 = a[1];
  let b0 = b[0], b1 = b[1];
  return (Math.abs(a0 - b0) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
          Math.abs(a1 - b1) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a1), Math.abs(b1)));
}

/**
 * Alias for {@link vec2.length}
 * @function
 */
export const len = length;

/**
 * Alias for {@link vec2.subtract}
 * @function
 */
export const sub = subtract;

/**
 * Alias for {@link vec2.multiply}
 * @function
 */
export const mul = multiply;

/**
 * Alias for {@link vec2.divide}
 * @function
 */
export const div = divide;

/**
 * Alias for {@link vec2.distance}
 * @function
 */
export const dist = distance;

/**
 * Alias for {@link vec2.squaredDistance}
 * @function
 */
export const sqrDist = squaredDistance;

/**
 * Alias for {@link vec2.squaredLength}
 * @function
 */
export const sqrLen = squaredLength;

/**
 * Perform some operation over an array of vec2s.
 *
 * @param {Array} a the array of vectors to iterate over
 * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
 * @param {Number} offset Number of elements to skip at the beginning of the array
 * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
 * @param {Function} fn Function to call for each vector in the array
 * @param {Object} [arg] additional argument to pass to fn
 * @returns {Array} a
 * @function
 */
export const forEach = (function() {
  let vec = create();

  return function(a, stride, offset, count, fn, arg) {
    let i, l;
    if(!stride) {
      stride = 2;
    }

    if(!offset) {
      offset = 0;
    }

    if(count) {
      l = Math.min((count * stride) + offset, a.length);
    } else {
      l = a.length;
    }

    for(i = offset; i < l; i += stride) {
      vec[0] = a[i]; vec[1] = a[i+1];
      fn(vec, vec, arg);
      a[i] = vec[0]; a[i+1] = vec[1];
    }

    return a;
  };
})();

redpajama_set_name: RedPajamaGithub


text:
class GaiaOAuthFetcher;

namespace chromeos {

// WebUIMessageHandler implementation which handles events occurring on the
// page, such as the user pressing the signin button.
class EnterpriseOAuthEnrollmentScreenHandler
    : public BaseScreenHandler,
      public EnterpriseEnrollmentScreenActor,
      public GaiaOAuthConsumer,
      public BrowsingDataRemover::Observer {
 public:
  EnterpriseOAuthEnrollmentScreenHandler();
  virtual ~EnterpriseOAuthEnrollmentScreenHandler();

  // Implements WebUIMessageHandler:
  virtual void RegisterMessages() OVERRIDE;

  // Implements EnterpriseEnrollmentScreenActor:
  virtual void SetParameters(Controller* controller,
                             bool is_auto_enrollment,
                             const std::string& user) OVERRIDE;
  virtual void PrepareToShow() OVERRIDE;
  virtual void Show() OVERRIDE;
  virtual void Hide() OVERRIDE;
  virtual void FetchOAuthToken() OVERRIDE;
  virtual void ResetAuth(const base::Closure& callback) OVERRIDE;
  virtual void ShowSigninScreen() OVERRIDE;
  virtual void ShowEnrollmentSpinnerScreen() OVERRIDE;
  virtual void ShowLoginSpinnerScreen() OVERRIDE;
  virtual void ShowAuthError(const GoogleServiceAuthError& error) OVERRIDE;
  virtual void ShowEnrollmentStatus(policy::EnrollmentStatus status) OVERRIDE;
  virtual void ShowUIError(UIError error_code) OVERRIDE;
  virtual void SubmitTestCredentials(const std::string& email,
                                     const std::string& password) OVERRIDE;

  // Implements BaseScreenHandler:
  virtual void Initialize() OVERRIDE;
  virtual void GetLocalizedStrings(
      base::DictionaryValue* localized_strings) OVERRIDE;

  // Implements GaiaOAuthConsumer:
  virtual void OnGetOAuthTokenFailure(
      const GoogleServiceAuthError& error) OVERRIDE;
  virtual void OnOAuthGetAccessTokenSuccess(const std::string& token,
                                            const std::string& secret) OVERRIDE;
  virtual void OnOAuthGetAccessTokenFailure(
      const GoogleServiceAuthError& error) OVERRIDE;
  virtual void OnOAuthWrapBridgeSuccess(const std::string& service_scope,
                                        const std::string& token,
                                        const std::string& expires_in) OVERRIDE;
  virtual void OnOAuthWrapBridgeFailure(
      const std::string& service_scope,
      const GoogleServiceAuthError& error) OVERRIDE;
  virtual void OnUserInfoSuccess(const std::string& email) OVERRIDE;
  virtual void OnUserInfoFailure(const GoogleServiceAuthError& error) OVERRIDE;

  // Implements BrowsingDataRemover::Observer:
  virtual void OnBrowsingDataRemoverDone() OVERRIDE;

 private:
  // Handlers for WebUI messages.
  void HandleClose(const base::ListValue* args);
  void HandleCompleteLogin(const base::ListValue* args);
  void HandleRetry(const base::ListValue* args);

  // Shows a given enrollment step.
  void ShowStep(const char* step);

  // Display the given i18n resource as error message.
  void ShowError(int message_id, bool retry);

  // Display the given string as error message.
  void ShowErrorMessage(const std::string& message, bool retry);

  // Display the given i18n string as a progress message.
  void ShowWorking(int message_id);

  // Starts asynchronous token revocation requests if there are tokens present.
  void RevokeTokens();

  // Shows the screen.
  void DoShow();

  // Closes the screen. |back_to_signin| is true if the user should go back to
  // the sign-in screen when the enrollment screen is closed. Otherwise, a
  // pending sign-in will be resumed.
  void DoClose(bool back_to_signin);

  // Records |sample| as a UMA metric for auto-enrollment. This is a member
  // function for convenience.
  void UMAFailure(int sample);

  // Keeps the controller for this actor.
  Controller* controller_;

  bool show_on_init_;

  // Whether this is an auto-enrollment screen.
  bool is_auto_enrollment_;

  // Whether an enrollment attempt has failed.
  bool enrollment_failed_once_;

  // Username of the user signing in.
  std::string user_;

  // Credentials used for tests.
  std::string test_email_;
  std::string test_password_;

  // This intentionally lives here and not in the controller, since it needs to
  // execute requests in the context of the profile that displays the webui.
  scoped_ptr<GaiaOAuthFetcher> oauth_fetcher_;

  // Tokens currently held.
  std::string access_token_;
  std::string access_token_secret_;
  std::string wrap_token_;

  // The browsing data remover instance currently active, if any.
  BrowsingDataRemover* browsing_data_remover_;

  // The callbacks to invoke after browsing data has been cleared.
  std::vector<base::Closure> auth_reset_callbacks_;

  DISALLOW_COPY_AND_ASSIGN(EnterpriseOAuthEnrollmentScreenHandler);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_ENTERPRISE_OAUTH_ENROLLMENT_SCREEN_HANDLER_H_


text:
<?php

//DEFINIÇÃO DAS CONTANTES DO BANCO DE DADOS

define('HOST','localhost');
//define('USER','root');
//define('PASS','tnt789');
define('USER','sisnoc');
define('PASS','Sisjml');
define('DB','sisnoc');

//Função Para incluir automaticamente as classes.
function __autoload($Classe){

    $pasta = ['Conn'];
    $inPasta = FALSE;

    foreach ($pasta as $NomePasta):

        if(!$inPasta && file_exists(__DIR__.DIRECTORY_SEPARATOR.$NomePasta.DIRECTORY_SEPARATOR.$Classe.".class.php") && !is_dir(__DIR__.DIRECTORY_SEPARATOR.$NomePasta.DIRECTORY_SEPARATOR.$Classe.".class.php")):
            include_once (__DIR__.DIRECTORY_SEPARATOR.$NomePasta.DIRECTORY_SEPARATOR.$Classe.".class.php");
            $inPasta = true;
        endif;
    endforeach;

  if(!$inPasta):
      trigger_error("Não foi possível incluir {$Classe}.class.php", E_USER_ERROR);
  endif;

}


text:
import numpy as np
import pandas as pd
import gc
from rankit.Table import Table
from rankit.Ranker import MasseyRanker, KeenerRanker, ODRanker, MarkovRanker
from rankit.Merge import borda_count_merge

gc.enable()

avg = pd.read_csv('pair.avg.tsv', header=None, delimiter='\t', names=['item1', 'item2', 'score1', 'score2'], dtype={
    'item1': np.uint32,
    'item2': np.uint32,
    'score1': np.float32,
    'score2': np.float32
})

cdf = pd.read_csv('pair.cdf.tsv', header=None, delimiter='\t', names=['item1', 'item2', 'score1', 'score2'], dtype={
    'item1': np.uint32,
    'item2': np.uint32,
    'score1': np.float32,
    'score2': np.float32
})

prob = pd.read_csv('pair.prob.tsv', header=None, delimiter='\t', names=['item1', 'item2', 'score1', 'score2'], dtype={
    'item1': np.uint32,
    'item2': np.uint32,
    'score1': np.float32,
    'score2': np.float32
})

data = Table(avg, col = ['item1', 'item2', 'score1', 'score2'])
ranker = MasseyRanker()
masseyRank = ranker.rank(data)
keener = KeenerRanker()
keenerRank = keener.rank(data)
od = ODRanker()
odRank = od.rank(data)
markov = MarkovRanker()
markovRank = markov.rank(data)

data = Table(cdf, col = ['item1', 'item2', 'score1', 'score2'])
ranker = MasseyRanker()
masseyCdfRank = ranker.rank(data)
keener = KeenerRanker()
keenerCdfRank = keener.rank(data)
od = ODRanker()
odCdfRank = od.rank(data)
markov = MarkovRanker()
markovCdfRank = markov.rank(data)

data = Table(prob, col = ['item1', 'item2', 'score1', 'score2'])
ranker = MasseyRanker()
masseyProbRank = ranker.rank(data)
keener = KeenerRanker()
keenerProbRank = keener.rank(data)
od = ODRanker()
odProbRank = od.rank(data)
markov = MarkovRanker()
markovProbRank = markov.rank(data)

mergedRank = borda_count_merge([masseyRank, keenerRank, odRank, markovRank, masseyCdfRank,
keenerCdfRank, odCdfRank, markovCdfRank, masseyProbRank, keenerProbRank, odProbRank, markovProbRank])

subject = pd.read_csv("subject.tsv", delimiter='\t', dtype={
    'iid': 'uint32'
}, header=None, names=['iid', 'subjectname', 'rank'], engine='c')

table = mergedRank.merge(subject, left_on='name', right_on='iid', suffixes=('_custom', '_bangumi'))
table['rank_bangumi'] = table.rank_bangumi.astype('UInt32')
table.to_csv("customrank.csv", columns=['name', 'rank_custom', 'rank_bangumi', 'subjectname'], index=False, header=True)


text:
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
require('../common');
const assert = require('assert');
let i;

const N = 30;
const done = [];

function get_printer(timeout) {
  return function() {
    console.log(`Running from setTimeout ${timeout}`);
    done.push(timeout);
  };
}

process.nextTick(function() {
  console.log('Running from nextTick');
  done.push('nextTick');
});

for (i = 0; i < N; i += 1) {
  setTimeout(get_printer(i), i);
}

console.log('Running from main.');

process.on('exit', function() {
  assert.strictEqual(done[0], 'nextTick');
  /* Disabling this test. I don't think we can ensure the order
  for (i = 0; i < N; i += 1) {
    assert.strictEqual(i, done[i + 1]);
  }
  */
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="./testcase.xsl"?>
<test_definition>
  <suite name="webapi-nacl-xwalk-tests" category="Native Client">
    <set name="nacl" type="js">
      <testcase purpose="Check if the Sine Wave synthesizer example demonstrates playing sound" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Audio">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Audio.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the Core API example demonstrates the basic use of the Time and Callback functions" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Core">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Core.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the File IO example demonstrates saving, loading, and deleting files from the persistent file store" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_File_IO">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_File_IO.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the example demonstrates how to use the Gamepad API" type="compliance" status="designed" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Gamepad">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Gamepad.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the Graphics2D example demonstrates a simple flame effect" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Graphics2D">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Graphics2D.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the Graphics3D example demonstrates how to create a 3D cube that rotates" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Graphics3D">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Graphics3D.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the example shows how to handle input events" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Input_Event">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Input_Event.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the MediaStream Video example demonstrates how to capture video from a webcam" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_MediaStream_Video">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_MediaStream_Video.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the example shows how to change the mouse cursor" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Mouse_Cursor">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Mouse_Cursor.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the mouse movement is maintained even in tab and/or browser fullscreen" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Mouse_Lock">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Mouse_Lock.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the Network Monitor example demonstrates how to listen for changes to the status of the network interfaces" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Network_Monitor">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Network_Monitor.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the socket example demonstrates how to use the TCP and UDP socket API" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Socket">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Socket.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the URL Loader example demonstrates fetching an URL and then displaying its contents" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_URL_Loader">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_URL_Loader.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the VarArrayBuffer example demonstrates prompting the use for a file, then drawing a histogram representing the contents of the file to a 2D square" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Var_Array_Buffer">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Var_Array_Buffer.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the example shows how to use the pp::VarDictionary var type" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Var_Dictionary">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Var_Dictionary.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the Websocket example demonstrates how to use the Websocket API" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_Websocket">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_Websocket.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
      <testcase purpose="Check if the MediaStream Audio example demonstrates how to capture audio data from an audio input device" type="compliance" status="approved" component="WebAPI/TBD/Native Client" execution_type="manual" priority="P1" id="Nacl_api_MediaStream_Audio">
        <description>
          <test_script_entry>/opt/webapi-nacl-xwalk-tests/nacl/Nacl_api_MediaStream_Audio.html</test_script_entry>
        </description>
        <specs>
          <spec>
            <spec_assertion element_type="TBD" element_name="TBD" interface="TBD" specification="TBD" section="TBD" category="Native Client"/>
            <spec_url>TBD</spec_url>
            <spec_statement/>
          </spec>
        </specs>
      </testcase>
    </set>
  </suite>
</test_definition>


text:
import {h, Component} from 'preact';
import style from './style';

export default class NotFound extends Component {
	render() {
		return (

404

Page not found

		);
	}
}


text:
module TaskMother

  def exec_task(command = 'ls')
    args = Arguments.new([Argument.new("-la")].to_java(Argument))
    exec = ExecTask.new(command, args, "hero/ka/directory")
    exec.setCancelTask(ExecTask.new("echo", "'failing'", "oncancel_working_dir"))
    exec
  end

  def exec_task_without_on_cancel(command = 'ls')
    args = Arguments.new([Argument.new("-la")].to_java(Argument))
    exec = ExecTask.new(command, args, "hero/ka/directory")
    exec
  end

  def exec_task_with_ant_oncancel_task(command = 'ls')
    args = Arguments.new([Argument.new("-la")].to_java(Argument))
    exec = ExecTask.new(command, args, "hero/ka/directory")
    exec.setCancelTask(ant_task)
    exec
  end

  def fetch_task_with_exec_on_cancel_task(pipeline = 'pipeline', stage = 'stage', job = 'job', src_file = 'src', dest = 'dest')
    fetch = fetch_task(pipeline, stage, job, src_file, dest)
    fetch.setCancelTask(ExecTask.new("echo", "'failing'", "oncancel_working_dir"))
    fetch
  end

  def fetch_task(pipeline = 'pipeline', stage = 'stage', job = 'job', src_file = 'src', dest = 'dest')
    FetchTaskAdapter.new(FetchTask.new(CaseInsensitiveString.new(pipeline), CaseInsensitiveString.new(stage), CaseInsensitiveString.new(job), src_file, dest))
  end

  def fetch_external_task(pipeline = 'pipeline', stage = 'stage', job = 'job', artifact_id = 'docker')
    fetch_external = FetchTaskAdapter.new(FetchPluggableArtifactTask.new(CaseInsensitiveString.new(pipeline), CaseInsensitiveString.new(stage), CaseInsensitiveString.new(job), artifact_id))
    fetch_external.setCancelTask(ExecTask.new("echo", "'failing'", "oncancel_working_dir"))
    fetch_external
  end

  def simple_exec_task
    ExecTask.new("ls", "-la", "hero/ka/directory")
  end

  def simple_exec_task_with_args_list
    args = Arguments.new([Argument.new("-l"), Argument.new("-a")].to_java(Argument))
    ExecTask.new("ls", args, "hero/ka/directory")
  end

  def with_run_if(types, task)
    [types].flatten.each do |type|
      task.getConditions().add(type)
    end
    task
  end

  def ant_task file = "build.xml", target = "compile", working_dir = "default/wd"
    ant = AntTask.new
    ant.setTarget(target)
    ant.setBuildFile(file)
    ant.setWorkingDirectory(working_dir)
    ant
  end

  def nant_task file = "default.build", target = "compile", working_dir = "default/wd"
    nant = NantTask.new
    nant.setTarget(target)
    nant.setBuildFile(file)
    nant.setWorkingDirectory(working_dir)
    nant
  end

  def rake_task file = "rakefile", target = "default", working_dir = "default/wd"
    rake = RakeTask.new
    rake.setTarget(target)
    rake.setBuildFile(file)
    rake.setWorkingDirectory(working_dir)
    rake
  end

  def plugin_task plugin_id = "curl.plugin", configurations = []
    configuration = Configuration.new(configurations.to_java(ConfigurationProperty))
    PluggableTask.new(PluginConfiguration.new(plugin_id, "1.0"), configuration)
  end

  def simple_task_plugin_with_on_cancel_config plugin_id = "curl.plugin", configurations = []
    task_plugin = plugin_task plugin_id, configurations
    task_plugin.setCancelTask(simple_exec_task)
    task_plugin
  end

  def simple_task_with_pluggable_on_cancel_task
    task = rake_task
    task.setCancelTask(plugin_task)
    task
  end

  def task_with_on_cancel_task
    task = rake_task
    task.setCancelTask(rake_task)
    task
  end

  def vm_for task
    Spring.bean("taskViewService").getViewModel(task, 'new')
  end

  def set_up_registry
    descriptor = GoPluginDescriptor.builder.id("curl.plugin").version("1.0").build
    Spring.bean("defaultPluginRegistry").loadPlugin(GoPluginBundleDescriptor.new(descriptor))
  end

  def unload_all_from_registry
    Spring.bean("defaultPluginRegistry").clear()
  end

  class ApiTaskViewForTest
    include com.thoughtworks.go.plugin.api.task.TaskView

    def initialize(options = {:display_value => "test curl", :template => nil})
      @options = options
    end

    def displayValue()
      @options[:display_value]
    end

    def template()
      @options[:template]
    end
  end

  class ApiTaskForTest
    include com.thoughtworks.go.plugin.api.task.Task

    def initialize(options = {:display_value => "test curl", :template => nil})
      @options = options
    end

    def config()
      config = com.thoughtworks.go.plugin.api.task.TaskConfig.new()
      config.addProperty("Url")
      config
    end

    def executor()
    end

    def view()
      ApiTaskViewForTest.new @options
    end

    def validate(configuration)
    end
  end

  class StubTask
    include com.thoughtworks.go.plugin.api.task.Task

    def initialize()
      @config = com.thoughtworks.go.plugin.api.task.TaskConfig.new()
    end

    def config
      @config
    end

    def executor
    end

    def view
    end

    def validate(configuration)
    end
  end
end


text:
<?php

defined('_JEXEC') or die;

/**
 * $text  string  infotext to be displayed
 */
extract($displayData);

?>

<?php echo $text; ?>


text:
<?php

require_once "phplib/Dashboard.php";

$metrics = array(
"MemTotal", "MemFree", "Buffers", "Cached", "SwapCached", "Active", "Inactive", "Active(anon)",
"Inactive(anon)", "Active(file)", "Inactive(file)", "Unevictable", "Mlocked", "SwapTotal", "SwapFree",
"Dirty", "Writeback", "AnonPages", "Mapped", "Shmem", "Slab", "SReclaimable", "SUnreclaim", "KernelStack",
"PageTables", "NFS_Unstable", "Bounce", "WritebackTmp", "CommitLimit", "Committed_AS", "VmallocTotal", "VmallocUsed",
"VmallocChunk", "HardwareCorrupted", "AnonHugePages", "HugePages_Total", "HugePages_Free", "HugePages_Rsvd",
"HugePages_Surp", "Hugepagesize", "DirectMap4k", "DirectMap2M", "DirectMap1G"
);

$host = isset($_GET['host']) ? $_GET['host'] : null;

$title = "$host Meminfo Metrics";
$metric_graphs = array();

foreach ($metrics as $metric) {
   #$metric_name = "derivative(meminfo.$host.$metric)";
   $metric_name = "meminfo.$host.$metric";

   if (preg_match("/^SockStat/", $metric)) {
       $metric_name = "netstat.$host.tcpext.$metric";
   }

   $graph = array(
        'type'    => 'graphite',
        'title'   => $metric,
        'metrics' => array(
            $metric_name
        ),
        'width' => 300,
        'height' => 200,
   );
   array_push($metric_graphs, $graph);
}

$graphs = array(
    "$host meminfo " => $metric_graphs
);

$additional_controls = "<input type=\"hidden\" name=\"host\" value=\"$host\">";

$tabs = Dashboard::$NETWORK_TABS;
$tab_url = Dashboard::getTabUrl(__FILE__);

include "phplib/template.php";


text:
package controllers

import java.net.URL
import java.time.format.DateTimeFormatter
import java.util.UUID

import controllers.security.{AuthenticationAction, OptionalAuthenticationAction, UserAction}
import info.smart.models.owc100._
import javax.inject._
import models.ErrorResult
import models.owc.OwcContextDAO
import org.apache.commons.lang3.StringEscapeUtils
import play.api.libs.json._
import play.api.mvc.{Action, AnyContent}
import services.{EmailService, OwcCollectionsService, PortalConfig, UserService}

@Singleton
class CollectionsController @Inject()(portalConfig: PortalConfig,
                                      userService: UserService,
                                      emailService: EmailService,
                                      collectionsService: OwcCollectionsService,
                                      authenticationAction: AuthenticationAction,
                                      optionalAuthenticationAction: OptionalAuthenticationAction,
                                      userAction: UserAction)
  extends ConfiguredController(portalConfig) {

  /**
    * default actions composition
    */
  private val defaultAuthAction = authenticationAction andThen userAction

  /**
    * Gets all collections of relevance for a user (if logged in) and/or collection for ID if provided
    *
    * @param owcContextIdOption
    * @param keywords optional sequence of keywords (aka OwcCategory terms, not lable or scheme, only the terms are checked)
    * @return
    */
  def queryCollectionsForViewing(owcContextIdOption: Option[String], keywords: Seq[String]): Action[Unit] = optionalAuthenticationAction(parse.empty) {
    request =>
      val userOption = request.optionalSession.flatMap(session => userService.findUserByEmailAsString(session.email))

      val owcDocs = collectionsService.queryOwcContextsForUserAndIdForViewing(userOption, owcContextIdOption)
        .distinct
        .filter(owc => keywords.isEmpty || keywords.exists(p => findKeywordInContextDeep(owc, p)))

      val owcJsDocs = owcDocs.map {
        doc =>
          if (keywords.isEmpty) {
            doc.toJson
          } else {
            val score = calculateKeywordScore(doc, keywords)
            val owcJsWithScore = addScoreJsonTransform(doc.toJson, score)
            owcJsWithScore
          }
      }
      Ok(Json.obj("count" -> owcJsDocs.size, "collections" -> JsArray(owcJsDocs), "keywords" -> keywords))
  }

  def getCollections(owcContextIdOption: Option[String]): Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val owcJsDocs = collectionsService.getOwcContextsForUserAndId(request.user, owcContextIdOption)
        .map(doc => doc.toJson)
      Ok(Json.obj("count" -> owcJsDocs.size, "collections" -> JsArray(owcJsDocs)))
  }

  /**
    *
    * @return
    */
  def getPersonalDefaultCollection: Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val owcJsDocs = collectionsService.getUserDefaultOwcContext(request.user).map(doc => doc.toJson)
      owcJsDocs.fold {
        val error: ErrorResult = ErrorResult(s"Could not find user collection for '${request.user.email}' ", None)
        BadRequest(Json.toJson(error)).as(JSON)
      } {
        owcDocJs =>
          Ok(owcDocJs)
      }

  }

  def createNewCustomCollection: Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val owcJsDocs = collectionsService.createNewCustomCollection(request.user).map(doc => doc.toJson)
      owcJsDocs.fold {
        val error: ErrorResult = ErrorResult(s"Could not find user collection for '${request.user.email}' ", None)
        BadRequest(Json.toJson(error)).as(JSON)
      } {
        owcDocJs =>
          Ok(owcDocJs)
      }

  }

  /**
    * Returns a JSON array containing OwcLinks with all files uploaded by the current user
    *
    * @return
    */
  def getPersonalFilesFromDefaultCollection: Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val owcDataLinks = collectionsService.getOwcLinksForOwcAuthorOwnFiles(request.user).map(owcLink => owcLink.toJson)
      Ok(Json.obj("status" -> "OK", "datalinks" -> JsArray(owcDataLinks)))
  }

  /**
    * add collection AS IS, beware may quickly result in unique DB constraint violations and unwanted id URLs
    *
    * @return
    */
  def insertCollection: Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcContext] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("Collection could not be inserted",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcContext => {
          logger.trace(Json.prettyPrint(owcContext.toJson))
          // TODO mangle Context and Resource IDs
          val inserted = collectionsService.insertCollection(owcContext, request.user)
          inserted.fold {
            val error: ErrorResult = ErrorResult("Collection could not be inserted",
              Some("Database insert failed."))
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              Ok(Json.obj("message" -> "owcContext inserted", "document" -> theDoc.toJson))
            }
          }

        }
      )
  }

  /**
    * insert a new collection, but makes deep NewOf copy with refreshed IDs
    *
    * @return
    */
  def insertCopyOfCollection: Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcContext] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("Collection could not be inserted",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcContext => {
          logger.trace(Json.prettyPrint(owcContext.toJson))
          // TODO mangle Context and Resource IDs
          val idLink = new URL(s"${portalConfig.portalExternalBaseLink}/context/document/${UUID.randomUUID().toString}")
          val updatedResources = owcContext.resource.map {
            owcResource =>
              val idLink = new URL(s"${portalConfig.portalExternalBaseLink}/context/resource/${UUID.randomUUID().toString}")
              owcResource.newOf(idLink)
          }
          val refreshedCopyOfContext = OwcContextDAO.refreshedCopy(owcContext, idLink, Some(updatedResources))

          val inserted = collectionsService.insertCollection(refreshedCopyOfContext, request.user)
          inserted.fold {
            val error: ErrorResult = ErrorResult("Collection could not be inserted",
              Some("Database insert failed."))
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              Ok(Json.obj("message" -> "owcContext inserted", "document" -> theDoc.toJson))
            }
          }

        }
      )
  }

  /**
    *
    * @return
    */
  def updateCollection: Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcContext] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("Collection could not be updated",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcContext => {
          logger.trace(Json.prettyPrint(owcContext.toJson))
          val updated = collectionsService.updateCollection(owcContext, request.user)
          updated.fold {
            val error: ErrorResult = ErrorResult("Collection could not be updated",
              Some("Database insert failed."))
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              Ok(Json.obj("message" -> "owcContext updated", "document" -> theDoc.toJson))
            }
          }

        }
      )
  }

  /**
    * add resource AS IS to collection, beware may quickly result in unique DB constraint violations
    *
    * @param owcContextId
    * @return
    */
  def addResourceToCollection(owcContextId: String): Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcResource] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("Provided OwcResource not valid",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcResource => {
          logger.trace(Json.prettyPrint(owcResource.toJson))
          val collectionDoc = collectionsService.getOwcContextsForUserAndId(
            user = request.user, owcContextIdOption = Some(owcContextId)).headOption
          val updatedCollection = collectionDoc.map {
            o =>
              val updated = o.copy(resource = o.resource ++ Seq(owcResource))
              collectionsService.updateCollection(updated, request.user)
          }.getOrElse(None)
          updatedCollection.fold {
            val error: ErrorResult = ErrorResult("database update for resource failed", None)
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              Ok(Json.obj("message" -> "owcResource added to owcContext",
                "document" -> theDoc.toJson, "entry" -> owcResource.toJson))
            }
          }
        }
      )
  }

  /**
    * add resource to collection, but makes deep NewOf copy with refreshed IDs
    *
    * @param owcContextId
    * @return
    */
  def addCopyOfResourceToCollection(owcContextId: String): Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcResource] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("Provided OwcResource not valid",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcResource => {
          logger.trace(Json.prettyPrint(owcResource.toJson))
          val collectionDoc = collectionsService.getOwcContextsForUserAndId(
            user = request.user, owcContextIdOption = Some(owcContextId)).headOption
          val updatedCollection = collectionDoc.map {
            o =>
              val idLink = new URL(s"${portalConfig.portalExternalBaseLink}/context/resource/${UUID.randomUUID().toString}")
              val refreshedCopyOfResource = owcResource.newOf(idLink)
              val updated = o.copy(resource = o.resource ++ Seq(refreshedCopyOfResource))
              collectionsService.updateCollection(updated, request.user)
          }.getOrElse(None)
          updatedCollection.fold {
            val error: ErrorResult = ErrorResult("database update for resource failed", None)
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              Ok(Json.obj("message" -> "owcResource added to owcContext",
                "document" -> theDoc.toJson, "entry" -> owcResource.toJson))
            }
          }
        }
      )
  }

  /**
    *
    * @param owcContextId
    * @return
    */
  def replaceResourceInCollection(owcContextId: String): Action[JsValue] = defaultAuthAction(parse.json) {
    request =>
      request.body.validate[OwcResource] fold(
        errors => {
          logger.error(JsError.toJson(errors).toString())
          val error: ErrorResult = ErrorResult("replace resource failed",
            Some(StringEscapeUtils.escapeJson(errors.mkString("; "))))
          BadRequest(Json.toJson(error)).as(JSON)
        },
        owcResource => {
          logger.trace(Json.prettyPrint(owcResource.toJson))
          val collectionDoc = collectionsService.getOwcContextsForUserAndId(
            user = request.user, owcContextIdOption = Some(owcContextId)).headOption
          val updatedCollection = collectionDoc.map {
            o =>
              val newResources = o.resource.filterNot(r => r.id.equals(owcResource.id))
              val updated = o.copy(resource = newResources ++ Seq(owcResource))
              collectionsService.updateCollection(updated, request.user)
          }.getOrElse(None)
          updatedCollection.fold {
            val error: ErrorResult = ErrorResult("database update for resource failed", None)
            BadRequest(Json.toJson(error)).as(JSON)
          } {
            theDoc => {
              val resourceTest = theDoc.resource.find(r => r.id.equals(owcResource.id)).exists(
                tResource => tResource.equals(owcResource))
              if (resourceTest) {
                Ok(Json.obj("message" -> "owcResource replaced in owcContext",
                  "document" -> theDoc.toJson, "entry" -> owcResource.toJson))
              }
              else {
                val error: ErrorResult = ErrorResult("owcResource could not be replaced in owcContext", None)
                BadRequest(Json.toJson(error)).as(JSON)
              }
            }
          }
        }
      )
  }

  /**
    *
    * @param owcContextId
    * @param owcResourceId
    * @return
    */
  def deleteResourceFromCollection(owcContextId: String, owcResourceId: String): Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val collectionDoc = collectionsService.getOwcContextsForUserAndId(
        user = request.user, owcContextIdOption = Some(owcContextId)).headOption
      val updatedCollection = collectionDoc.map {
        o =>
          val newResources = o.resource.filterNot(r => r.id.toString.equals(owcResourceId))
          val updated = o.copy(resource = newResources)
          collectionsService.updateCollection(updated, request.user)
      }.getOrElse(None)
      updatedCollection.fold {
        val error: ErrorResult = ErrorResult("delete owcResource database update failed", None)
        BadRequest(Json.toJson(error)).as(JSON)
      } {
        theDoc => {
          val resourceTest = theDoc.resource.find(r => r.id.toString.equals(owcResourceId))
          if (resourceTest.isDefined) {
            val error: ErrorResult = ErrorResult("owcResource could not be removed from owcContext", None)
            BadRequest(Json.toJson(error)).as(JSON)
          }
          else {
            Ok(Json.obj("message" -> "owcResource removed from owcContext",
              "document" -> theDoc.toJson))
          }
        }
      }
  }

  /**
    *
    * @param owcContextId id of the OwcDoc
    * @return
    */
  def deleteCollection(owcContextId: String): Action[Unit] = defaultAuthAction(parse.empty) {
    request =>
      val collectionDoc = collectionsService.getOwcContextsForUserAndId(
        user = request.user, owcContextIdOption = Some(owcContextId)).headOption
      val deleted = collectionDoc.exists(o => collectionsService.deleteCollection(o, request.user))
      if (deleted) {
        //TODO SR general "response" JSON?
        Ok(Json.obj("message" -> "owcContext deleted", "document" -> owcContextId))
      }
      else {
        val error = ErrorResult("Deletion of OwcContext failed.", Some(s"DocumentId: ${owcContextId}"))
        BadRequest(Json.toJson(error)).as(JSON)
      }
  }

  /**
    * Creates a sitemap xml for publicly accessible records/collections and provides links via webgui access
    * https://support.google.com/webmasters/answer/75712?visit_id=1-636439946733108040-1790029023&rd=1
    *
    * @return
    */
  def generateSitemapFromPublicCollections: Action[AnyContent] = Action {

    val owcXmlElements: scala.collection.mutable.StringBuilder = new StringBuilder
    owcXmlElements.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
    owcXmlElements.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n")

    collectionsService.queryOwcContextsForUserAndIdForViewing(None, None).foreach {
      doc =>
        val docPart =
          s"""<url>
             |  <loc>${portalConfig.portalExternalBaseLink}/#${doc.id.getPath}</loc>
             |  <lastmod>${doc.updateDate.format(DateTimeFormatter.ISO_LOCAL_DATE)}</lastmod>
             |  <priority>1.0</priority>
             |</url>
          """.stripMargin
        owcXmlElements.append(docPart)
        doc.resource.foreach {
          res =>
            val resPart =
              s"""<url>
                 |  <loc>${portalConfig.portalExternalBaseLink}/#${res.id.getPath}</loc>
                 |  <lastmod>${doc.updateDate.format(DateTimeFormatter.ISO_LOCAL_DATE)}</lastmod>
                 |  <priority>1.0</priority>
                 |</url>
          """.stripMargin
            owcXmlElements.append(resPart)
        }
    }
    owcXmlElements.append("</urlset>\n")
    Ok(owcXmlElements.mkString).as("application/xml")
  }

  private def findKeywordInContext(owcContext: OwcContext, keyword: String): Boolean = {
    owcContext.keyword.exists(p => p.term.contentEquals(keyword))
  }

  private def findKeywordInContextDeep(owcContext: OwcContext, keyword: String): Boolean = {
    owcContext.keyword.exists(p => p.term.contentEquals(keyword)) ||
      owcContext.resource.exists(res => res.keyword.exists(p => p.term.contentEquals(keyword)))
  }

  private def addScoreJsonTransform(json: JsValue, searchScore: Double): JsValue = {
    val jsonTransformer1 = JsPath.read[JsObject].map(o => o ++ Json.obj("searchScore" -> JsNumber(searchScore)))
    json.transform(jsonTransformer1).get
  }

  private def calculateKeywordScore(owcContext: OwcContext, keywords: Seq[String]): Double = {
    val numQueryKeywords = if (keywords.nonEmpty) keywords.length else 1
    val numContextKeywords = if (owcContext.keyword.nonEmpty) owcContext.keyword.length else 1
    val kwSum = owcContext.resource.map(_.keyword.length).sum
    val numResourcesKeywords = if (kwSum > 0) kwSum else 1
    val directContextHits = keywords.map(kw => owcContext.keyword.count(p => p.term.contentEquals(kw))).sum
    val directResourceHits = keywords.map(
      kw => owcContext.resource.map(res => res.keyword.count(p => p.term.contentEquals(kw))).sum).sum

    val closeContextHits = keywords.map(kw => owcContext.keyword.count(p => p.term.contains(kw))).sum
    val closeResourceHits = keywords.map(
      kw => owcContext.resource.map(res => res.keyword.count(p => p.term.contains(kw))).sum).sum

    ( (directContextHits / numContextKeywords) +
      (closeContextHits * 0.3 / numContextKeywords) +
      (directResourceHits / numResourcesKeywords) +
      ((closeResourceHits / numResourcesKeywords) * 0.3)) / numQueryKeywords

  }

}