text:
/**
 * @fileoverview Mock Clock implementation for working with setTimeout,
 * setInterval, clearTimeout and clearInterval within unit tests.
 *
 * Derived from jsUnitMockTimeout.js, contributed to JsUnit by
 * Pivotal Computer Systems, www.pivotalsf.com
 */

goog.setTestOnly('goog.testing.MockClock');
goog.provide('goog.testing.MockClock');

goog.require('goog.Disposable');
/** @suppress {extraRequire} */
goog.require('goog.Promise');
goog.require('goog.Thenable');
goog.require('goog.asserts');
goog.require('goog.async.nextTick');
goog.require('goog.async.run');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
goog.require('goog.testing.events.Event');

/**
 * Class for unit testing code that uses setTimeout and clearTimeout.
 *
 * NOTE: If you are using MockClock to test code that makes use of
 *       goog.fx.Animation, then you must either:
 *
 * 1. Install and dispose of the MockClock in setUpPage() and tearDownPage()
 *    respectively (rather than setUp()/tearDown()).
 *
 * or
 *
 * 2. Ensure that every test clears the animation queue by calling
 *    mockClock.tick(x) at the end of each test function (where `x` is large
 *    enough to complete all animations).
 *
 * Otherwise, if any animation is left pending at the time that
 * MockClock.dispose() is called, that will permanently prevent any future
 * animations from playing on the page.
 *
 * @param {boolean=} opt_autoInstall Install the MockClock at construction time.
 * @constructor
 * @extends {goog.Disposable}
 * @final
 */
goog.testing.MockClock = function(opt_autoInstall) {
  'use strict';
  goog.Disposable.call(this);
  /**
   * Reverse-order queue of timers to fire.
   *
   * The last item of the queue is popped off.  Insertion happens from the
   * right.  For example, the expiration times for each element of the queue
   * might be in the order 300, 200, 200.
   *
   * @type {?Array<!goog.testing.MockClock.QueueObjType_>}
   * @private
   */
  this.queue_ = [];

  /**
   * Set of timeouts that should be treated as cancelled.
   *
   * Rather than removing cancelled timers directly from the queue, this set
   * simply marks them as deleted so that they can be ignored when their
   * turn comes up.  The keys are the timeout keys that are cancelled, each
   * mapping to true.
   *
   * @private {?Object<number, boolean>}
   */
  this.deletedKeys_ = {};

  /**
   * Whether we should skip mocking Date.now().
   * @private {boolean}
   */
  this.unmockDateNow_ = false;

  if (opt_autoInstall) {
    this.install();
  }
};
goog.inherits(goog.testing.MockClock, goog.Disposable);

/**
 * @typedef {{
 *    timeoutKey: number, millis: number,
 *    runAtMillis: number, funcToCall: !Function, recurring: boolean}}
 * @private
 */
goog.testing.MockClock.QueueObjType_;

/**
 * Default wait timeout for mocking requestAnimationFrame (in milliseconds).
 *
 * @type {number}
 * @const
 */
goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT = 20;

/**
 * ID to use for next timeout.  Timeout IDs must never be reused, even across
 * MockClock instances.
 * @public {number}
 */
goog.testing.MockClock.nextId = Math.round(Math.random() * 10000);

/**
 * Count of the number of setTimeout/setInterval/etc. calls received by this
 * instance.
 * @type {number}
 * @private
 */
goog.testing.MockClock.prototype.timeoutsMade_ = 0;

/**
 * Count of the number of timeout/interval/etc. callbacks triggered by this
 * instance.
 * @type {number}
 * @private
 */
goog.testing.MockClock.prototype.callbacksTriggered_ = 0;

/**
 * PropertyReplacer instance which overwrites and resets setTimeout,
 * setInterval, etc. or null if the MockClock is not installed.
 * @type {?goog.testing.PropertyReplacer}
 * @private
 */
goog.testing.MockClock.prototype.replacer_ = null;

/**
 * The current simulated time in milliseconds.
 * @type {number}
 * @private
 */
goog.testing.MockClock.prototype.nowMillis_ = 0;

/**
 * Additional delay between the time a timeout was set to fire, and the time
 * it actually fires.  Useful for testing workarounds for this Firefox 2 bug:
 * https://bugzilla.mozilla.org/show_bug.cgi?id=291386
 * May be negative.
 * @type {number}
 * @private
 */
goog.testing.MockClock.prototype.timeoutDelay_ = 0;

/**
 * Whether the MockClock is allowed to use synchronous ticks.
 *
 * When this is true, MockClock will patch goog.async.run upon installation so
 * that GoogPromises can be resolved synchronously.
 * @type {boolean}
 * @private
 */
goog.testing.MockClock.prototype.isSynchronous_ = true;

/**
 * Creates an async-only MockClock that can only be ticked asynchronously.
 *
 * Async-only MockClocks rely on native Promise resolution instead of
 * patching async run behavior to force GoogPromise to resolve synchronously.
 * As a result, async MockClocks must be ticked with tickAsync() instead of
 * tick().
 *
 * Async-only MockClocks will always use the default async scheduler and will
 * never reset the async queue when uninstalled.
 *
 * @return {!goog.testing.MockClock}
 */
goog.testing.MockClock.createAsyncMockClock = function() {
  const clock = new goog.testing.MockClock();
  clock.isSynchronous_ = false;
  return clock;
};

/**
 * The real set timeout for reference.
 * @const @private {!Function}
 */
goog.testing.MockClock.REAL_SETTIMEOUT_ = goog.global.setTimeout;

/** @private {function():number} */
goog.testing.MockClock.prototype.oldGoogNow_;

/**
 * Installs the MockClock by overriding the global object's implementation of
 * setTimeout, setInterval, clearTimeout and clearInterval.
 */
goog.testing.MockClock.prototype.install = function() {
  'use strict';
  if (!this.replacer_) {
    if (goog.testing.MockClock.REAL_SETTIMEOUT_ !== goog.global.setTimeout) {
      if (typeof console !== 'undefined' && console.warn) {
        console.warn(
            'Non default setTimeout detected. ' +
            'Use of multiple MockClock instances or other clock mocking ' +
            'should be avoided due to unspecified behavior and ' +
            'the resulting fragility.');
      }
    }

    var r = this.replacer_ = new goog.testing.PropertyReplacer();
    r.set(goog.global, 'setTimeout', goog.bind(this.setTimeout_, this));
    r.set(goog.global, 'setInterval', goog.bind(this.setInterval_, this));
    r.set(goog.global, 'clearTimeout', goog.bind(this.clearTimeout_, this));
    r.set(goog.global, 'clearInterval', goog.bind(this.clearInterval_, this));
    if (!this.unmockDateNow_) {
      r.set(Date, 'now', goog.bind(this.getCurrentTime, this));
    }
    // goog.async.nextTick depends on various internal browser APIs
    // (setImmediate, MessageChannel, and setTimeout), but it's internal
    // implementation uses local caching which makes stubbing the browser
    // natives not feasible. Stub it directly instead.
    r.set(
        goog.async.nextTick, 'nextTickImpl',
        goog.bind(this.setImmediate_, this));
    // setImmediate is a deprecated API that does not exist in most browsers.
    // Set it in the browser supports it.
    // Preserve existing behavior of synchronous mock clocks to unconditionally
    // stub setImmediate.
    if (goog.global['setImmediate'] || this.isSynchronous_) {
      r.set(goog.global, 'setImmediate', goog.bind(this.setImmediate_, this));
    }

    if (this.isSynchronous_) {
      // goog.Promise uses goog.async.run. In order to be able to test
      // Promise-based code synchronously, we need to make sure that
      // goog.async.run uses nextTick instead of native browser Promises. Since
      // nextTick calls setImmediate, it will be synchronously executed the
      // next time the MockClock is ticked. Note that we test for the presence
      // of goog.async.run.forceNextTick to be resilient to the case where
      // tests replace goog.async.run directly.
      goog.async.run.forceNextTick &&
          goog.async.run.forceNextTick(goog.testing.MockClock.REAL_SETTIMEOUT_);
    } else {
      // Reset the scheduler in case a synchronous MockClock was previously
      // installed. Otherwise goog.Promise resolution and other work scheduled
      // with goog.async.run would be executed synchronously when ticking the
      // clock.
      goog.async.run.resetSchedulerForTest &&
          goog.async.run.resetSchedulerForTest();
    }

    // Replace the requestAnimationFrame functions.
    this.replaceRequestAnimationFrame_();

    // PropertyReplacer#set can't be called with renameable functions.
    this.oldGoogNow_ = goog.now;
    goog.now = goog.bind(this.getCurrentTime, this);
  }
};

/**
 * Unmocks the Date.now() function for tests that aren't expecting it to be
 * mocked. See b/141619890.
 * @deprecated
 */
goog.testing.MockClock.prototype.unmockDateNow = function() {
  'use strict';
  this.unmockDateNow_ = true;
  if (this.replacer_) {
    try {
      this.replacer_.restore(Date, 'now');
    } catch (e) {
      // Ignore error thrown if Date.now was not already mocked.
    }
  }
};

/**
 * Installs the mocks for requestAnimationFrame and cancelRequestAnimationFrame.
 * @private
 */
goog.testing.MockClock.prototype.replaceRequestAnimationFrame_ = function() {
  'use strict';
  var r = this.replacer_;
  var requestFuncs = [
    'requestAnimationFrame', 'webkitRequestAnimationFrame',
    'mozRequestAnimationFrame', 'oRequestAnimationFrame',
    'msRequestAnimationFrame'
  ];

  var cancelFuncs = [
    'cancelAnimationFrame', 'cancelRequestAnimationFrame',
    'webkitCancelRequestAnimationFrame', 'mozCancelRequestAnimationFrame',
    'oCancelRequestAnimationFrame', 'msCancelRequestAnimationFrame'
  ];

  for (var i = 0; i < requestFuncs.length; ++i) {
    if (goog.global && goog.global[requestFuncs[i]]) {
      r.set(
          goog.global, requestFuncs[i],
          goog.bind(this.requestAnimationFrame_, this));
    }
  }

  for (var i = 0; i < cancelFuncs.length; ++i) {
    if (goog.global && goog.global[cancelFuncs[i]]) {
      r.set(
          goog.global, cancelFuncs[i],
          goog.bind(this.cancelRequestAnimationFrame_, this));
    }
  }
};

/**
 * Removes the MockClock's hooks into the global object's functions and revert
 * to their original values.
 *
 * @param {boolean=} resetScheduler By default, a synchronous MockClock
 *     will not restore default goog.async behavior upon uninstallation and
 *     clear any pending async work. This can leave goog.Promises in a state
 *     where callbacks can never be executed. Set this flag to restore original
 *     scheduling behavior and retain the async queue. This argument is ignored
 *     for an async-only MockClock.
 */
goog.testing.MockClock.prototype.uninstall = function(resetScheduler) {
  'use strict';
  if (this.replacer_) {
    this.replacer_.reset();
    this.replacer_ = null;
    goog.now = this.oldGoogNow_;
  }

  if (this.isSynchronous_) {
    // Since async-only MockClock instances are always reset on installation,
    // they don't need to be reset when uninstalled.
    if (resetScheduler) {
      // Check for presence of resetScheduler in case users have replaced
      // goog.async.run.
      goog.async.run.resetSchedulerForTest &&
          goog.async.run.resetSchedulerForTest();
    } else {
      // If the overridden scheduler is not reset, then clear the work queue.
      // This prevents any pending goog.Promise resolution or other work
      // scheduled with goog.async.run from executing after uninstallation.
      this.resetAsyncQueue_();
    }
  }
};

/** @override */
goog.testing.MockClock.prototype.disposeInternal = function() {
  'use strict';
  this.uninstall();
  this.queue_ = null;
  this.deletedKeys_ = null;
  goog.testing.MockClock.superClass_.disposeInternal.call(this);
};

/**
 * Resets the MockClock, removing all timeouts that are scheduled and resets
 * the fake timer count.
 * @param {boolean=} retainAsyncQueue By default, a synchronous MockClock
 *     will clear any pending async work when reset. This can leave
 *     goog.Promises in a state where callbacks can never be executed. Set this
 *     flag to restore original scheduling behavior and retain the async queue.
 *     This argument is ignored for an async-only MockClock.
 */
goog.testing.MockClock.prototype.reset = function(retainAsyncQueue) {
  'use strict';
  this.queue_ = [];
  this.deletedKeys_ = {};
  this.nowMillis_ = 0;
  this.timeoutsMade_ = 0;
  this.callbacksTriggered_ = 0;
  this.timeoutDelay_ = 0;

  if (this.isSynchronous_ && !retainAsyncQueue) {
    // If the overridden scheduler is not intended to be reset, then clear the
    // work queue. This prevents any pending async work queue items from
    // executing after uninstallation.
    this.resetAsyncQueue_();
  }
};

/**
 * Resets the async queue when a synchronous MockClock resets.
 * @private
 */
goog.testing.MockClock.prototype.resetAsyncQueue_ = function() {
  'use strict';
  // Synchronous MockClock should reset the async queue so that pending tasks
  // are not executed the next time the call stack is emptied.
  goog.asserts.assert(
      this.isSynchronous_,
      'Async queue cannot be reset on async-only async MockClock.');

  goog.async.run.resetQueue();
};

/**
 * Sets the amount of time between when a timeout is scheduled to fire and when
 * it actually fires.
 * @param {number} delay The delay in milliseconds.  May be negative.
 */
goog.testing.MockClock.prototype.setTimeoutDelay = function(delay) {
  'use strict';
  this.timeoutDelay_ = delay;
};

/**
 * @return {number} delay The amount of time between when a timeout is
 *     scheduled to fire and when it actually fires, in milliseconds.  May
 *     be negative.
 */
goog.testing.MockClock.prototype.getTimeoutDelay = function() {
  'use strict';
  return this.timeoutDelay_;
};

/**
 * Increments the MockClock's time by a given number of milliseconds, running
 * any functions that are now overdue.
 * @param {number=} opt_millis Number of milliseconds to increment the counter.
 *     If not specified, clock ticks 1 millisecond.
 * @return {number} Current mock time in milliseconds.
 */
goog.testing.MockClock.prototype.tick = function(opt_millis) {
  'use strict';
  goog.asserts.assert(
      this.isSynchronous_,
      'Async MockClock does not support tick. Use tickAsync() instead.');
  if (typeof opt_millis != 'number') {
    opt_millis = 1;
  }
  if (opt_millis < 0) {
    throw new Error(
        'Time cannot go backwards (cannot tick by ' + opt_millis + ')');
  }
  var endTime = this.nowMillis_ + opt_millis;
  this.runFunctionsWithinRange_(endTime);
  // If a scheduled callback called tick() reentrantly, don't rewind time.
  this.nowMillis_ = Math.max(this.nowMillis_, endTime);
  return endTime;
};

/**
 * Takes a promise and then ticks the mock clock. If the promise successfully
 * resolves, returns the value produced by the promise. If the promise is
 * rejected, it throws the rejection as an exception. If the promise is not
 * resolved at all, throws an exception.
 * Also ticks the general clock by the specified amount.
 * Only works with goog.Thenable, hence goog.Promise. Does NOT work with native
 * browser promises.
 *
 * @param {!goog.Thenable<T>} promise A promise that should be resolved after
 *     the mockClock is ticked for the given opt_millis.
 * @param {number=} opt_millis Number of milliseconds to increment the counter.
 *     If not specified, clock ticks 1 millisecond.
 * @return {T}
 * @template T
 *
 * @deprecated Treating Promises as synchronous values is incompatible with
 *     native promises and async functions. More generally, this code relies on
 *     promises "pumped" by setTimeout which is not done in production code,
 *     even for goog.Promise and results unnatural timing between resolved
 *     promises callback and setTimeout/setInterval callbacks in tests.
 */
goog.testing.MockClock.prototype.tickPromise = function(promise, opt_millis) {
  'use strict';
  goog.asserts.assert(
      this.isSynchronous_, 'Async MockClock does not support tickPromise.');

  let value;
  let error;
  let resolved = false;
  promise.then(
      function(v) {
        'use strict';
        value = v;
        resolved = true;
      },
      function(e) {
        'use strict';
        error = e;
        resolved = true;
      });
  this.tick(opt_millis);
  if (!resolved) {
    throw new Error(
        'Promise was expected to be resolved after mock clock tick.');
  }
  if (error) {
    throw error;
  }
  return value;
};

/**
 * @return {number} The number of timeouts or intervals that have been
 * scheduled. A setInterval call is only counted once.
 */
goog.testing.MockClock.prototype.getTimeoutsMade = function() {
  'use strict';
  return this.timeoutsMade_;
};

/**
 * @return {number} The number of timeout or interval callbacks that have been
 * triggered. For setInterval, each callback is counted separately.
 */
goog.testing.MockClock.prototype.getCallbacksTriggered = function() {
  'use strict';
  return this.callbacksTriggered_;
};

/**
 * @return {number} The MockClock's current time in milliseconds.
 */
goog.testing.MockClock.prototype.getCurrentTime = function() {
  'use strict';
  return this.nowMillis_;
};

/**
 * @param {number} timeoutKey The timeout key.
 * @return {boolean} Whether the timer has been set and not cleared,
 *     independent of the timeout's expiration.  In other words, the timeout
 *     could have passed or could be scheduled for the future.  Either way,
 *     this function returns true or false depending only on whether the
 *     provided timeoutKey represents a timeout that has been set and not
 *     cleared.
 */
goog.testing.MockClock.prototype.isTimeoutSet = function(timeoutKey) {
  'use strict';
  return timeoutKey < goog.testing.MockClock.nextId &&
      timeoutKey >= goog.testing.MockClock.nextId - this.timeoutsMade_ &&
      !this.deletedKeys_[timeoutKey];
};

/**
 * Whether the MockClock is configured to run synchronously.
 *
 * This allows MockClock consumers to decide whether to tick synchronously or
 * asynchronously.
 * @return {boolean}
 */
goog.testing.MockClock.prototype.isSynchronous = function() {
  return this.isSynchronous_;
};

/**
 * Runs any function that is scheduled before a certain time.  Timeouts can
 * be made to fire early or late if timeoutDelay_ is non-0.
 * @param {number} endTime The latest time in the range, in milliseconds.
 * @private
 */
goog.testing.MockClock.prototype.runFunctionsWithinRange_ = function(endTime) {
  'use strict';
  // Repeatedly pop off the last item since the queue is always sorted.
  while (this.hasQueuedEntriesBefore_(endTime)) {
    this.runNextQueuedTimeout_();
  }
};

/**
 * Increments the MockClock's time by a given number of milliseconds, running
 * any functions that are now overdue.
 * @param {number=} millis Number of milliseconds to increment the counter.
 *     If not specified, clock ticks 1 millisecond.
 * @return {!Promise<number>} Current mock time in milliseconds.
 */
goog.testing.MockClock.prototype.tickAsync = async function(millis = 1) {
  if (millis < 0) {
    throw new Error(`Time cannot go backwards (cannot tick by ${millis})`);
  }
  const endTime = this.nowMillis_ + millis;
  await this.runFunctionsWithinRangeAsync_(endTime);
  // If a scheduled callback called tick() reentrantly, don't rewind time.
  this.nowMillis_ = Math.max(this.nowMillis_, endTime);
  return endTime;
};

/**
 * Asynchronously increments the MockClock's time by a given number of
 * milliseconds, returning the settled promise value.
 * @param {number} millis Number of milliseconds to increment the counter.
 * @param {!goog.Thenable<T>} promise A promise that should be resolved after
 *     the mockClock is ticked for the given opt_millis.
 * @return {!Promise<T>} Resolved promise value.
 * @throws {!goog.asserts.AssertionError} when the promise is not resolved after
 *     ticking.
 * @throws {*} when the promise is rejected.
 * @template T
 */
goog.testing.MockClock.prototype.tickAsyncMustSettlePromise =
    async function(millis, promise) {
  goog.asserts.assert(
      !this.isSynchronous_,
      'Synchronous MockClock does not support tickAsyncMustSettlePromise.');

  let settled = false;
  let value;
  let error;
  promise.then(
      (v) => {
        settled = true;
        value = v;
      },
      (e) => {
        settled = true;
        error = e;
      });
  await this.tickAsync(millis);
  goog.asserts.assert(
      settled, 'Promise was expected to be resolved after mock clock tick.');
  if (error !== undefined) {
    throw error;
  }
  return value;
};

/**
 * Instantly adjusts the clock's current time to a new timestamp. Unlike tick(),
 * this method skips over the intervening time, so that `setInterval()` calls or
 * recurring `setTimeout()`s will only run once.
 *
 * This mimics the behavior of setting the system clock, rather than waiting for
 * time to pass.
 *
 * CAUTION: This is an advanced feature.  Use this method to set the clock to be
 * a specific date, which is much faster than calling tick() with a large value.
 * This lets you test code against arbitrary dates.
 *
 * MOE:begin_strip
 * See go/mockclock-time-travel for how & why to use this method.
 * MOE:end_strip
 *
 * @param {!Date} newDate The new timestamp to set the clock to.
 * @return {!Promise}
 */
goog.testing.MockClock.prototype.doTimeWarpAsync = async function(newDate) {
  goog.asserts.assertInstanceof(
      newDate, Date,
      'doTimeWarpAsync() only accepts dates.  Use tickAsync() instead.');
  if (+newDate < this.nowMillis_) {
    throw new Error(`Time cannot go backwards (cannot time warp from ${
        new Date(this.nowMillis_)} to ${newDate})`);
  }
  // Adjust the clock before calling the functions, so that they schedule future
  // callbacks from the new time.
  this.nowMillis_ = +newDate;
  await this.runFunctionsWithinRangeAsync_(this.nowMillis_);
};

/**
 * Like runFunctionsWithinRange, but pauses to allow native promise callbacks to
 * run correctly.
 * @param {number} endTime The latest time in the range, in milliseconds.
 * @return {!Promise}
 * @private
 */
goog.testing.MockClock.prototype.runFunctionsWithinRangeAsync_ =
    async function(endTime) {
  'use strict';
  // Let native promises set timers before we start ticking.
  await goog.testing.MockClock.flushMicroTasks_();

  // Repeatedly pop off the last item since the queue is always sorted.
  while (this.hasQueuedEntriesBefore_(endTime)) {
    if (this.runNextQueuedTimeout_()) {
      await goog.testing.MockClock.flushMicroTasks_();
    }
  }
};

/**
 * Pauses asynchronously to run all promise callbacks in the microtask queue.
 *
 * This is optimized to be correct, but to also not be too slow in IE.  It waits
 * for up to 50 chained `then()` callbacks at once. Microtasks callbacks are run
 * in batches, so a series of `then()` callbacks scheduled at the same time will
 * run at once.  The loop is only necessary for to run very deep promise chains.
 *
 * Using `setTimeout()`, `setImmediate()`, or a polyfill would make this better,
 * but also makes it 15x slower in IE.  Without IE, setImmediate and polyfill is
 * best option.
 * @private
 */
goog.testing.MockClock.flushMicroTasks_ = async function() {
  'use strict';
  for (var i = 0; i < 50; i++) {
    await Promise.resolve();
  }
};

/**
 * @param {number} endTime The latest time in the range, in milliseconds.
 * @return {boolean}
 * @private
 */
goog.testing.MockClock.prototype.hasQueuedEntriesBefore_ = function(endTime) {
  'use strict';
  var adjustedEndTime = endTime - this.timeoutDelay_;
  return !!this.queue_ && !!this.queue_.length &&
      this.queue_[this.queue_.length - 1].runAtMillis <= adjustedEndTime;
};

/**
 * Runs the next timeout in the queue, advancing the clock.
 * @return {boolean} False if the timeout was cancelled (and nothing happened).
 * @private
 */
goog.testing.MockClock.prototype.runNextQueuedTimeout_ = function() {
  'use strict';
  var timeout = this.queue_.pop();

  if (timeout.timeoutKey in this.deletedKeys_) return false;

  // Only move time forwards.
  this.nowMillis_ =
      Math.max(this.nowMillis_, timeout.runAtMillis + this.timeoutDelay_);
  // Call timeout in global scope and pass the timeout key as the argument.
  this.callbacksTriggered_++;
  timeout.funcToCall.call(goog.global, timeout.timeoutKey);
  // In case the interval was cleared in the funcToCall
  if (timeout.recurring) {
    this.scheduleFunction_(
        timeout.timeoutKey, timeout.funcToCall, timeout.millis, true);
  }
  return true;
};

/**
 * Schedules a function to be run at a certain time.
 * @param {number} timeoutKey The timeout key.
 * @param {!Function} funcToCall The function to call.
 * @param {number} millis The number of milliseconds to call it in.
 * @param {boolean} recurring Whether to function call should recur.
 * @private
 */
goog.testing.MockClock.prototype.scheduleFunction_ = function(
    timeoutKey, funcToCall, millis, recurring) {
  'use strict';
  if (typeof funcToCall !== 'function') {
    // Early error for debuggability rather than dying in the next .tick()
    throw new TypeError(
        'The provided callback must be a function, not a ' + typeof funcToCall);
  }

  var /** !goog.testing.MockClock.QueueObjType_ */ timeout = {
    runAtMillis: this.nowMillis_ + millis,
    funcToCall: funcToCall,
    recurring: recurring,
    timeoutKey: timeoutKey,
    millis: millis
  };

  goog.testing.MockClock.insert_(timeout, goog.asserts.assert(this.queue_));
};

/**
 * Inserts a timer descriptor into a descending-order queue.
 *
 * Later-inserted duplicates appear at lower indices.  For example, the
 * asterisk in (5,4,*,3,2,1) would be the insertion point for 3.
 *
 * @param {!goog.testing.MockClock.QueueObjType_} timeout The timeout to insert,
 *     with numerical runAtMillis property.
 * @param {!Array<!goog.testing.MockClock.QueueObjType_>} queue The queue to
 *     insert into, with each element having a numerical runAtMillis property.
 * @private
 */
goog.testing.MockClock.insert_ = function(timeout, queue) {
  'use strict';
  // Although insertion of N items is quadratic, requiring goog.structs.Heap
  // from a unit test will make tests more prone to breakage.  Since unit
  // tests are normally small, scalability is not a primary issue.

  // Find an insertion point.  Since the queue is in reverse order (so we
  // can pop rather than unshift), and later timers with the same time stamp
  // should be executed later, we look for the element strictly greater than
  // the one we are inserting.

  for (var i = queue.length; i != 0; i--) {
    if (queue[i - 1].runAtMillis > timeout.runAtMillis) {
      break;
    }
    queue[i] = queue[i - 1];
  }

  queue[i] = timeout;
};

/**
 * Maximum 32-bit signed integer.
 *
 * Timeouts over this time return immediately in many browsers, due to integer
 * overflow.  Such known browsers include Firefox, Chrome, and Safari, but not
 * IE.
 *
 * @type {number}
 * @private
 */
goog.testing.MockClock.MAX_INT_ = 2147483647;

/**
 * Schedules a function to be called after `millis` milliseconds.
 * Mock implementation for setTimeout.
 * @param {!Function} funcToCall The function to call.
 * @param {number=} opt_millis The number of milliseconds to call it after.
 * @return {number} The number of timeouts created.
 * @private
 */
goog.testing.MockClock.prototype.setTimeout_ = function(
    funcToCall, opt_millis) {
  'use strict';
  var millis = opt_millis || 0;
  if (millis > goog.testing.MockClock.MAX_INT_) {
    throw new Error(
        'Bad timeout value: ' + millis + '.  Timeouts over MAX_INT ' +
        '(24.8 days) cause timeouts to be fired ' +
        'immediately in most browsers, except for IE.');
  }
  this.timeoutsMade_++;
  this.scheduleFunction_(
      goog.testing.MockClock.nextId, funcToCall, millis, false);
  return goog.testing.MockClock.nextId++;
};

/**
 * Schedules a function to be called every `millis` milliseconds.
 * Mock implementation for setInterval.
 * @param {!Function} funcToCall The function to call.
 * @param {number=} opt_millis The number of milliseconds between calls.
 * @return {number} The number of timeouts created.
 * @private
 */
goog.testing.MockClock.prototype.setInterval_ = function(
    funcToCall, opt_millis) {
  'use strict';
  var millis = opt_millis || 0;
  this.timeoutsMade_++;
  this.scheduleFunction_(
      goog.testing.MockClock.nextId, funcToCall, millis, true);
  return goog.testing.MockClock.nextId++;
};

/**
 * Schedules a function to be called when an animation frame is triggered.
 * Mock implementation for requestAnimationFrame.
 * @param {!Function} funcToCall The function to call.
 * @return {number} The number of timeouts created.
 * @private
 */
goog.testing.MockClock.prototype.requestAnimationFrame_ = function(funcToCall) {
  'use strict';
  return this.setTimeout_(goog.bind(function() {
    'use strict';
    if (funcToCall) {
      funcToCall(this.getCurrentTime());
    } else if (goog.global.mozRequestAnimationFrame) {
      var event = new goog.testing.events.Event('MozBeforePaint', goog.global);
      event['timeStamp'] = this.getCurrentTime();
      goog.testing.events.fireBrowserEvent(event);
    }
  }, this), goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT);
};

/**
 * Schedules a function to be called immediately after the current JS
 * execution.
 * Mock implementation for setImmediate.
 * @param {!Function} funcToCall The function to call.
 * @return {number} The number of timeouts created.
 * @private
 */
goog.testing.MockClock.prototype.setImmediate_ = function(funcToCall) {
  'use strict';
  return this.setTimeout_(funcToCall, 0);
};

/**
 * Clears a timeout.
 * Mock implementation for clearTimeout.
 * @param {number} timeoutKey The timeout key to clear.
 * @private
 */
goog.testing.MockClock.prototype.clearTimeout_ = function(timeoutKey) {
  'use strict';
  // Some common libraries register static state with timers.
  // This is bad. It leads to all sorts of crazy test problems where
  // 1) Test A sets up a new mock clock and a static timer.
  // 2) Test B sets up a new mock clock, but re-uses the static timer
  //    from Test A.
  // 3) A timeout key from test A gets cleared, breaking a timeout in
  //    Test B.
  //
  // For now, we just hackily fail silently if someone tries to clear a timeout
  // key before we've allocated it.
  // Ideally, we should throw an exception if we see this happening.
  if (this.isTimeoutSet(timeoutKey)) {
    this.deletedKeys_[timeoutKey] = true;
  }
};

/**
 * Clears an interval.
 * Mock implementation for clearInterval.
 * @param {number} timeoutKey The interval key to clear.
 * @private
 */
goog.testing.MockClock.prototype.clearInterval_ = function(timeoutKey) {
  'use strict';
  this.clearTimeout_(timeoutKey);
};

/**
 * Clears a requestAnimationFrame.
 * Mock implementation for cancelRequestAnimationFrame.
 * @param {number} timeoutKey The requestAnimationFrame key to clear.
 * @private
 */
goog.testing.MockClock.prototype.cancelRequestAnimationFrame_ = function(
    timeoutKey) {
  'use strict';
  this.clearTimeout_(timeoutKey);
};


text:
package org.osc.core.broker.service.policy;

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

import javax.persistence.EntityManager;

import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.management.Policy;
import org.osc.core.broker.service.ServiceDispatcher;
import org.osc.core.broker.service.api.ListVirtualSystemPolicyServiceApi;
import org.osc.core.broker.service.dto.PolicyDto;
import org.osc.core.broker.service.exceptions.VmidcBrokerValidationException;
import org.osc.core.broker.service.persistence.PolicyEntityMgr;
import org.osc.core.broker.service.persistence.VirtualSystemEntityMgr;
import org.osc.core.broker.service.request.BaseIdRequest;
import org.osc.core.broker.service.response.ListResponse;
import org.osgi.service.component.annotations.Component;

@Component
public class ListVirtualSystemPolicyService extends ServiceDispatcher<BaseIdRequest, ListResponse<PolicyDto>>
        implements ListVirtualSystemPolicyServiceApi {

    private VirtualSystem vs;

    @Override
    public ListResponse<PolicyDto> exec(BaseIdRequest daIdRequest, EntityManager em) throws Exception {

        validate(em, daIdRequest);

        // to do mapping
        List<PolicyDto> dtoList = new ArrayList<PolicyDto>();

        for(Policy policy : this.vs.getDomain().getPolicies()) {
            PolicyDto dto = new PolicyDto();
            PolicyEntityMgr.fromEntity(policy, dto);

            dtoList.add(dto);
        }

        ListResponse<PolicyDto> response = new ListResponse<PolicyDto>();
        response.setList(dtoList);

        return response;
    }

    protected void validate(EntityManager em, BaseIdRequest request) throws Exception {

        this.vs = VirtualSystemEntityMgr.findById(em, request.getId());

        if (this.vs == null) {
            throw new VmidcBrokerValidationException(
                    "Virtual System with Id: " + request.getId() + "  is not found.");
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef DEF_UNIFORM
#define DEF_UNIFORM

#include <iostream>
#include <map>
#include <string>
#define GLFW_INCLUDE_GLCOREARB
#include <GLFW/glfw3.h>
#include "texture.hpp"
#include "matrix4.hpp"
#include "vec3f.hpp"
#include "vec2f.hpp"

class Program;

typedef enum Uniform_Type {
    UNIFORM_BOOL, UNIFORM_INT, UNIFORM_FLOAT, UNIFORM_MAT4, UNIFORM_FLOAT3,
    UNIFORM_INT3, UNIFORM_FLOAT2, UNIFORM_INT2, UNIFORM_SAMPLER
} Uniform_Type;

typedef struct Program_Status {
    bool* binded;
    bool* uniform_sended;
} Program_Status;

class Uniform {
public:
    Uniform(std::string name,Uniform_Type type);
    void add_subscriber(bool *uniform_sended,GLuint program_id,bool *state);
    void add_texture(Texture **tex,Program *shaderprogram,int index);
    Uniform_Type get_type();
    void set_value(bool val);
    void set_value(int val);
    void set_value(float val);
    void set_value(Matrix4 &val);
    void set_value(Vec3f val);
    void set_value(Vec2f val);
    void set_value(Texture *tex);
    void send_value(GLuint program_id);
    std::string name();

private:
    void reset_bools();

    std::string uniform_name;
    Uniform_Type type;
    bool bval;
    int ival;
    float fval;
    Matrix4 mval;
    Vec3f f3val;
    Vec2f f2val;
    std::map<GLuint,Program_Status> programs_status; /* binded/not binded */
    std::map<GLuint,GLint> uniform_locations;
    std::map<Texture**,Program*> tex_pointers;
};

#endif


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Commande{

    void Do();

    void Undo();

}


text:
/* This file contains code for unified image loading from many
 * uncompressed  GIFs */
/********************************************************************/
/* Copyright (c) 2001 Sasha Vasko <sasha at aftercode.net>           */
/********************************************************************/
/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifdef _WIN32
#include "win32/config.h"
#else
#include "config.h"
#endif

/*#define LOCAL_DEBUG */
/*#define DO_CLOCKING */

#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#include <string.h>
#include <ctype.h>

#ifdef _WIN32
# include "win32/afterbase.h"
#else
# include "afterbase.h"
#endif
#ifdef HAVE_GIF
# ifdef HAVE_BUILTIN_UNGIF
#  include "libungif/gif_lib.h"
# else
#  include <gif_lib.h>
# endif
#endif

#include "asimage.h"
#include "ascmap.h"
#include "ungif.h"

#ifdef HAVE_GIF		/* GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF */

void
free_gif_saved_image( SavedImage *sp, Bool reusable )
{
	if( sp )
	{
		if (sp->ImageDesc.ColorMap)
	    	FreeMapObject(sp->ImageDesc.ColorMap);

		if (sp->RasterBits)
		    free((char *)sp->RasterBits);

		if (sp->ExtensionBlocks)
		    FreeExtension(sp);

		if( !reusable )
			free( sp );
	}
}

void
free_gif_saved_images( SavedImage *images, int count )
{
	if( images )
	{
		while ( --count >= 0 )
			free_gif_saved_image( &(images[count]), True );
		free( images );
	}
}

static void
append_gif_saved_image( SavedImage *src, SavedImage **ret, int *ret_images )
{
	*ret = realloc( *ret, sizeof( SavedImage )*((*ret_images)+1));
	memcpy( &((*ret)[*ret_images]), src, sizeof(SavedImage) );
	memset( src, 0x00, sizeof( SavedImage ) );
	++(*ret_images) ;
}

/* It appears that nobody has bloody debugged giflib with multiimage files where
 * subimages have private colormaps. So it bloody fucks everything up.
 * So we bloody have to cludge it to get something useful.
 * Oh The pain! The pain!
 */
int fread_gif( GifFileType *gif, GifByteType* buf, int len )
{
	int ret = fread( buf, 1, len, gif->UserData );
	return ret;
}

GifFileType*
open_gif_read( FILE *in_stream )
{
	return DGifOpen(in_stream, fread_gif);
}

int
get_gif_image_desc( GifFileType *gif, SavedImage *im )
{
	long start_pos, end_pos ;
	int status;

	start_pos = ftell(gif->UserData);
	status = DGifGetImageDesc( gif );
	end_pos = ftell(gif->UserData);
	if( status == GIF_OK )
	{
		int ext_count = im->ExtensionBlockCount ;
		ExtensionBlock	*ext_ptr = im->ExtensionBlocks ;

		im->ExtensionBlocks = NULL ;
		im->ExtensionBlockCount = 0 ;

		free_gif_saved_image( im, True );
		memset( im, 0x00, sizeof(SavedImage));

		im->ExtensionBlocks = ext_ptr ;
		im->ExtensionBlockCount = ext_count ;

		memcpy( &(im->ImageDesc), &(gif->Image), sizeof(GifImageDesc));
		if( gif->Image.ColorMap )
		{
			im->ImageDesc.ColorMap = MakeMapObject(gif->Image.ColorMap->ColorCount, NULL);
			fseek( gif->UserData, start_pos+9, SEEK_SET );
			fread( im->ImageDesc.ColorMap->Colors, 1, gif->Image.ColorMap->ColorCount*3, gif->UserData);
			fseek( gif->UserData, end_pos, SEEK_SET );
			gif->Image.ColorMap = NULL ;
 		}
	}
	return status;
}

int
get_gif_saved_images( GifFileType *gif, int subimage, SavedImage **ret, int *ret_images  )
{
    GifRecordType RecordType;
    GifByteType *ExtData;
    SavedImage temp_save;
	int curr_image = 0, ret_count = *ret_images ;
	int status = GIF_OK;

	memset( &temp_save, 0x00, sizeof( temp_save ) );
	do
	{
		if ( (status = DGifGetRecordType(gif, &RecordType)) == GIF_ERROR)
		{
			break;
		}
		switch (RecordType)
		{
	    	case IMAGE_DESC_RECORD_TYPE:
				if ((status = get_gif_image_desc(gif, &temp_save)) == GIF_OK)
				{
					int size = temp_save.ImageDesc.Width*temp_save.ImageDesc.Height ;
					temp_save.RasterBits = realloc( temp_save.RasterBits, size );
					status = DGifGetLine(gif, (unsigned char*)temp_save.RasterBits, size);
					if (status == GIF_OK)
					{
						if( curr_image == subimage || subimage < 0 )
						{
							append_gif_saved_image( &temp_save, ret, &(ret_count));
						}
					}
					++curr_image ;
				}
				break;

	    	case EXTENSION_RECORD_TYPE:
				status = DGifGetExtension(gif,&temp_save.Function,&ExtData);
				while (ExtData != NULL && status == GIF_OK )
				{
            		/* Create an extension block with our data */
            		if ((status = AddExtensionBlock(&temp_save, ExtData[0], (char*)&(ExtData[1]))) == GIF_OK)
				    	status = DGifGetExtensionNext(gif, &ExtData);
            		temp_save.Function = 0;
				}
				break;

	    	case TERMINATE_RECORD_TYPE:
				break;

	    	default:	/* Should be trapped by DGifGetRecordType */
				break;
		}
    }while( status == GIF_OK && RecordType != TERMINATE_RECORD_TYPE);

/*	if( status == GIF_OK && *ret == NULL )
		append_gif_saved_image( &temp_save, ret, &(ret_count));
	else
*/
	free_gif_saved_image( &temp_save, True );

	*ret_images = ret_count ;
    return status;
}

int
write_gif_saved_images( GifFileType *gif, SavedImage *images, unsigned int count )
{
	int status = GIF_OK;
	unsigned int i ;

	for( i = 0 ; i < count && status == GIF_OK; ++i )
	{
		register SavedImage	*sp = &images[i];
		int		SavedHeight = sp->ImageDesc.Height;
		int		SavedWidth = sp->ImageDesc.Width;
		ExtensionBlock	*ep;
		int y ;

#if 1
		if (sp->ExtensionBlocks)
        	for ( y = 0; y < sp->ExtensionBlockCount && status == GIF_OK; y++)
			{
            	ep = &sp->ExtensionBlocks[y];
            	status = EGifPutExtension(gif, (ep->Function != 0) ? ep->Function : '\0',
               							  ep->ByteCount, ep->Bytes);
			}
#endif
		if( status == GIF_OK )
		{
			status = EGifPutImageDesc(gif, sp->ImageDesc.Left, sp->ImageDesc.Top,
									  SavedWidth, SavedHeight, sp->ImageDesc.Interlace,
									  sp->ImageDesc.ColorMap );
			for (y = 0; y < SavedHeight && status == GIF_OK ; y++)
	    		status = EGifPutLine(gif, (unsigned char*)sp->RasterBits + y * SavedWidth, SavedWidth);
		}
	}
	return status;
}

#endif			/* GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF */


text:
[English](./README.md) | [繁中版](./README-tw.md) | [简中版](./README-zh.md) | [العربية](./README-ar.md) | [বাংলা](./README-bn.md) | [Deutsch](./README-de.md) | [Español](./README-es.md) | [فارسی](./README-fa.md) | [Français](./README-fr.md) | [हिंदी](./README-hi.md) | [Indonesia](./README-id.md) | [Italiano](./README-it.md) | [日本語](./README-ja.md) | [한국어](./README-ko.md) | [ລາວ](./README-lo.md) | [Македонски](./README-mk.md) | [മലയാളം](./README-ml.md) | [Монгол](./README-mn.md) | [Nederlands](./README-nl.md) | [Polski](./README-pl.md) | [Português (Brasil)](./README-pt_BR.md) | [Русский](./README-ru.md) | [ไทย](./README-th.md) | [Türkçe](./README-tr.md) | [Українська](./README-uk.md) | [Tiếng Việt](./README-vi.md)

# API λίστα ελέγχου ασφαλείας
Λίστα με τα πιο σημαντικά μέτρα ασφαλείας στον σχεδιασμό, έλεγχο, και την έκδοση του API σας.

---

## Επικύρωση ασφαλείας (Authentication)
- [ ] Μη χρησιμοποιήτε `Basic Auth`. Χρησιμοποιήστε standard authentication (π.χ. [JWT](https://jwt.io/), [OAuth](https://oauth.net/)).
- [ ] Μην προσπαθήσετε να επανεφεύρετε τον τροχό για `Authentication`, `token generation`, `password storage`. Χρησιμοποιήστε ήδη υπάρχων βιβλιοθήκες.
- [ ] Χρησιμοποιήστε `Max Retry` και jail features κατά τη σύνδεση (Login).
- [ ] Χρησιμοποιήστε κρυπτογράφηση (encryption) για όλα τα σημαντικά δεδομένα.

### JWT (JSON Web Token)
- [ ] Χρησιμοποιήστε τυχαίο περίπλοκο κλειδί (`JWT Secret`) για να γίνει αρκετά δύσκολο να αποκρυπτογραφηθεί με brute forcing.
- [ ] Μη χρησιμοποιήτε/αφαιρήτε τον αλγόριθμο απο το payload. Ο αλγόριθμος πρέπει να πραγματοποιήτε στο backend (`HS256` ή `RS256`).
- [ ] Κάντε το token να λήγει (token expiration) (`TTL`, `RTTL`) όσο πιο σύντομα γίνεται.
- [ ] Μη καταχωρείτε ευαίσθητα δεδομένα στο JWT payload, μπορεί να αποκρυπτογραφηθεί εύκολα [easily](https://jwt.io/#debugger-io).
- [ ] Αποφύγετε την αποθήκευση πάρα πολλών δεδομένων. JWT είναι συνήθως κοινόχρηστο σε headers και έχουν όριο μεγέθους.

## Πρόσβαση (Access)
- [ ] Περιορίστε τα αιτήματα (requests) (Throttling) για να αποφύγετε επιθέσεις DDoS / brute-force.
- [ ] Χρησιμοποιήστε HTTPS στο server side για να αποφύγετε επιθέσεις MITM (Man in the Middle Attack).
- [ ] Χρησιμοποιήστε `HSTS` κεφαλίδα (header) με SSL για να αποφύγετε SSL Strip επιθέσεις.
- [ ] Απενεργοποιήστε τις καταχωρίσεις directory.
- [ ] Για ιδιωτικά API, επιτρέπεται η πρόσβαση μόνο από IP/κεντρικούς στη λίστα επιτρεπόμενων.

## Authorization

### OAuth
- [ ] Πάντα να επαληθεύετε το `redirect_uri` στο server-side και επιτρέπετε μόνο whitelisted URLs.
- [ ] Πάντα να προσπαθήτε να ανταλλάσετε auth code και όχι tokens (μην επιτρέπετε `response_type=token`).
- [ ] Χρησιμοποιήστε `state` παράμετρο με τυχαίο περίπλοκο κλειδί (hash) για να αποτρέψετε CSRF κατα τη διάρκεια της OAuth authentication διαδικασίας.
- [ ] Ορίστε το προεπιλεγμένο πεδίο (default scope), και επικυρώστε τις παραμέτρους πεδίου (scope parameters) για κάθε εφαρμογή.

## Είσοδος δεδομένων (Input)
- [ ] Χρησιμοποιήστε την κατάλληλη HTTP μέθοδο σύμφωνα με τη λειτουργία που χρειάζεστε: `GET (read)`, `POST (create)`, `PUT/PATCH (replace/update)`, και `DELETE (για διαγραφή αρχείου)`, και απαντήστε με `405 Method Not Allowed` εάν η ζητούμενη μέθοδος δεν είναι κατάλληλη για την αιτούμενη εφαρμογή.
- [ ] Επικυρώστε `content-type` στη ζητούμενη Accept κεφαλίδα (Content Negotiation) για να επιτρέψετε μόνο το format που υποστηρίζετε (π.χ. `application/xml`, `application/json`, κτλ.) και απαντήστε με `406 Not Acceptable` εάν δεν το υποστηρίζετε.
- [ ] Επικυρώστε `content-type` δεδομένα που στέλνετε, με τον ίδιο τρόπο όπως τα δέχεστε (π.χ. `application/x-www-form-urlencoded`, `multipart/form-data`, `application/json`, κτλ.).
- [ ] Επικυρώστε την οποιαδήποτε είσοδο δεδομένων απο τους χρήστες, για να αποφύγετε τα κοινά κενά ασφαλείας (π.χ. `XSS`, `SQL-Injection`, `Remote Code Execution`, κτλ.).
- [ ] Μη χρησιμοποιήτε ευαίσθητα δεδομένα (`credentials`, `Passwords`, `security tokens`, ή `API keys`) στο URL, αλλά χρησιμοποιήστε τη κοινή Authorization κεφαλίδα (standard Authorization header).
- [ ] Χρησιμοποιήστε μόνο κρυπτογράφηση από την πλευρά του διακομιστή.
- [ ] Χρησιμοποιήστε API Gateway service για να ενεργοποιήσετε caching, Rate Limit policies (π.χ. `Quota`, `Spike Arrest`, ή `Concurrent Rate Limit`) και κάντε deploy APIs resources δυναμικά.

## Επεξεργασία (Processing)
- [ ] Ελέγξτε ότι όλα τα endpoints είναι προστατευμένα πίσω από επικύρωση ασφαλείας(authentication) για να αποφύγετε προβλήματα λανθασμένης επικύρωσης (broken authentication process).
- [ ] Μη χρησιμοποιήτε το ID των χρηστών. Χρησιμοποιήστε `/me/orders` αντί `/user/654321/orders`.
- [ ] Μη χρησιμοποιήτε την αυτόματη αύξηση των IDs. Χρησιμοποιήστε `UUID` αντι αυτου.
- [ ] Εάν επεργάζεστε XML αρχεία, σιγουρευτείτε ότι το entity parsing δεν είναι ενεργοποιημένο, για να αποφύγετε `XXE` (επίθεση XML external entity).
- [ ] Εάν επεργάζεστε XML αρχεία, σιγουρευτείτε ότι το entity expansion δεν είναι ενεργοποιημένο, για να αποφύγετε `Billion Laughs/XML bomb` δια μέσου exponential entity expansion επίθεσης.
- [ ] Χρησιμοποιήστε CDN για την φόρτωση αρχείων (file uploads).
- [ ] Εάν επεξεργάζεστε μεγάλο αριθμο δεδομένων, χρησιμοποιήστε Workers και Queues για να γίνετε η επεξεργασία στο background και να γίνεται η επιστροφή απάντησης πολύ πιο γρήγορα, αποφεύγοντας HTTP Blocking.
- [ ] Μην ξεχνάτε να απενεργοποιήσετε το DEBUG mode.
- [ ] Χρησιμοποιήστε μη εκτελέσιμες στοίβες όταν είναι διαθέσιμες.

## Αποστολή/Επιστροφή δεδομένων (Output)
- [ ] Αποστέλετε `X-Content-Type-Options: nosniff` κεφαλίδα (header).
- [ ] Αποστέλετε `X-Frame-Options: deny` κεφαλίδα (header).
- [ ] Αποστέλετε `Content-Security-Policy: default-src 'none'` κεφαλίδα (header).
- [ ] Αφαιρέστε fingerprinting κεφαλίδεs (headers) - `X-Powered-By`, `Server`, `X-AspNet-Version`, κτλ.
- [ ] Εξαναγκάστε το `content-type` να υπάρχει στην απάντηση (response), εάν η απάντηση είναι `application/json` τότε η απάντηση `content-type` πρέπει να είναι `application/json`.
- [ ] Μην επιστρέφετε ευαίσθητα δεδομένα, όπως: `credentials`, `Passwords`, ή `security tokens`.
- [ ] Επιστρέψτε τον κατάλληλο κωδικό κατάστασης σύμφωνα με τη διαδικασία που ολοκληρώθηκε. (π.χ. `200 OK`, `400 Bad Request`, `401 Unauthorized`, `405 Method Not Allowed`, κτλ.).

## CI & CD
- [ ] Ελέγξτε το σχεδιασμό και την κατάσταση της εφαρμογή σας με επαρκή κάλυψη τεστ Unit / integration.
- [ ] Χρησιμοποιήτε code review διαδικασίες και μη δέχεστε self-approval απο την ομάδα.
- [ ] Εξασφαλίστε ότι όλα τα στοιχέια των υπηρεσιών σας περνούν απο στατικό έλεγχο με AV software πριν τα αναρτήσετε στο production, συμπεριλαμβανομένου οποιασδήποτε εξωτερικής βιβλιοθήκης που μπορει να χρησιμοποιήτε.
- [ ] Εκτελείτε συνεχώς δοκιμές ασφαλείας (στατική/δυναμική ανάλυση) στον κώδικά σας.
- [ ] Ελέγξτε τις εξαρτήσεις σας (τόσο το λογισμικό όσο και το λειτουργικό σύστημα) για γνωστά τρωτά σημεία.
- [ ] Σχεδιάστε rollback διαδικασίες για deployments.

## Monitoring
- [ ] Use centralized logins for all services and components.
- [ ] Use agents to monitor all traffic, errors, requests, and responses.
- [ ] Use alerts for SMS, Slack, Email, Telegram, Kibana, Cloudwatch, etc.
- [ ] Ensure that you aren't logging any sensitive data like credit cards, passwords, PINs, etc.
- [ ] Use an IDS and/or IPS system to monitor your API requests and instances.

---

## Δείτε επίσης:
- [yosriady/api-development-tools](https://github.com/yosriady/api-development-tools) - Λίστα με χρήσιμες πληροφορίες για τον σχεδιασμό RESTful HTTP+JSON APIs.

---

# Συνεισφορά
Μη διστάσετε να συμβάλλετε με το να κάνετε forking αυτό το repository, κάνοντας αλλαγές και υποβάλλοντας pull requests. Για οποιεσδήποτε ερωτήσεις στείλτε μας ένα email στο `team@shieldfy.io`.


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace aoc.csharp._2017
{
    public class Day04 : ISolver
    {
        public (string Part1, string Part2) GetSolution(TextReader input)
        {
            return GetAnswer(input);
        }

        public static (string Part1, string Part2) GetAnswer(TextReader input)
        {
            var text = input.ReadToEnd();
            int part1 = CountValidPhrases(text);
            int part2 = CountValidPhrases2(text);
            return (part1.ToString(), part2.ToString());
        }

        public static int CountValidPhrases(string input)
        {
            int count = 0;
            using (var reader = new StringReader(input))
            {
                string? line;
                while ((line = reader.ReadLine()) != null)
                {
                    ISet<string> set = new HashSet<string>();
                    bool valid = true;
                    string[] split = line.Split(' ');
                    foreach (var word in split)
                    {
                        if (set.Contains(word))
                        {
                            valid = false;
                            break;
                        }
                        else
                        {
                            set.Add(word);
                        }
                    }
                    if (valid) count++;
                }
            }
            return count;
        }

        public static int CountValidPhrases2(string input)
        {
            int count = 0;
            using (var reader = new StringReader(input))
            {
                string? line;
                while ((line = reader.ReadLine()) != null)
                {
                    ISet<string> set = new HashSet<string>();
                    bool valid = true;
                    string[] split = line.Split(' ');
                    foreach (var word in split)
                    {
                        var orderedWord = new string(word.OrderBy(c => c).ToArray());
                        if (set.Contains(orderedWord))
                        {
                            valid = false;
                            break;
                        }
                        else
                        {
                            set.Add(orderedWord);
                        }
                    }
                    if (valid) count++;
                }
            }
            return count;
        }
    }
}


text:
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TemplateHaskell #-}

module System.Nemesis

(

  module System.Nemesis.DSL
, module System.Nemesis.Driver

)

where

import System.Nemesis.DSL
import System.Nemesis.Driver (run)


text:
using System;
using Stateflow.Workflow;

namespace LeadSample
{
	public class MailAction : IAction<string>
    {
		public void Execute(IWorkflow<string> workflow, StateChangeEventArgs<string> transition)
        {
            Console.WriteLine("Mail action executed: {0}. Context: {1}", workflow.GetType().Name, workflow.Context.GetType().Name);
        }
    }

	public class RejectAction : IAction<string>
	{
		public void Execute(IWorkflow<string> workflow, StateChangeEventArgs<string> transition)
		{
			Console.WriteLine("Rejected action");
		}
	}

}


text:
class RenameAttachmentSizeToAttachmentFileSize < ActiveRecord::Migration
  def change
    rename_column :spree_assets, :attachment_size, :attachment_file_size
  end
end


text:
using Halcyon.HAL.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace TestHalcyonApi.Models
{
    /// <summary>
    /// A simple test model.
    /// </summary>
    public class Thingy
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public Thingy()
        {

        }

        /// <summary>
        /// Id, it is important to fully name it here and in routes to avoid naming collisions.
        /// </summary>
        public int ThingyId { get; set; }

        /// <summary>
        /// Name, provides some test data.
        /// </summary>
        [MaxLength(25, ErrorMessage = "Name cannot be greater than 25 characters")]
        [Required(ErrorMessage = "You must include a name")]
        public String Name { get; set; }
    }
}


text:
'use strict';

require('./app')('playMusicModes');

//adjust for browser differences
navigator.getUserMedia = navigator.getUserMedia
    || navigator.webkitGetUserMedia
    || navigator.mozGetUserMedia;


text:
package org.apache.cassandra.locator;

import com.google.common.collect.Iterables;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.PartitionPosition;
import org.apache.cassandra.dht.AbstractBounds;

import java.util.function.Predicate;

public abstract class ReplicaPlan<E extends Endpoints<E>>
{
    protected final Keyspace keyspace;
    protected final ConsistencyLevel consistencyLevel;
    // The snapshot of the replication strategy when instantiating.
    // It could be different than the one fetched from Keyspace later, e.g. RS altered during the query.
    // Use the snapshot to calculate {@code blockFor} in order to have a consistent view of RS for the query.
    protected final AbstractReplicationStrategy replicationStrategy;

    // all nodes we will contact via any mechanism, including hints
    // i.e., for:
    //  - reads, only live natural replicas
    //      ==> live.natural().subList(0, blockFor + initial speculate)
    //  - writes, includes all full, and any pending replicas, (and only any necessary transient ones to make up the difference)
    //      ==> liveAndDown.natural().filter(isFull) ++ liveAndDown.pending() ++ live.natural.filter(isTransient, req)
    //  - paxos, includes all live replicas (natural+pending), for this DC if SERIAL_LOCAL
    //      ==> live.all()  (if consistencyLevel.isDCLocal(), then .filter(consistencyLevel.isLocal))
    private final E contacts;

    ReplicaPlan(Keyspace keyspace, AbstractReplicationStrategy replicationStrategy, ConsistencyLevel consistencyLevel, E contacts)
    {
        assert contacts != null;
        this.keyspace = keyspace;
        this.replicationStrategy = replicationStrategy;
        this.consistencyLevel = consistencyLevel;
        this.contacts = contacts;
    }

    public abstract int blockFor();

    public E contacts() { return contacts; }

    // TODO: should this semantically return true if we contain the endpoint, not the exact replica?
    public boolean contacts(Replica replica) { return contacts.contains(replica); }
    public Keyspace keyspace() { return keyspace; }
    public AbstractReplicationStrategy replicationStrategy() { return replicationStrategy; }
    public ConsistencyLevel consistencyLevel() { return consistencyLevel; }

    public static abstract class ForRead<E extends Endpoints<E>> extends ReplicaPlan<E>
    {
        // all nodes we *could* contacts; typically all natural replicas that are believed to be alive
        // we will consult this collection to find uncontacted nodes we might contact if we doubt we will meet consistency level
        private final E candidates;

        ForRead(Keyspace keyspace, AbstractReplicationStrategy replicationStrategy, ConsistencyLevel consistencyLevel, E candidates, E contacts)
        {
            super(keyspace, replicationStrategy, consistencyLevel, contacts);
            this.candidates = candidates;
        }

        public int blockFor() { return consistencyLevel.blockFor(replicationStrategy); }

        public E candidates() { return candidates; }

        public Replica firstUncontactedCandidate(Predicate<Replica> extraPredicate)
        {
            return Iterables.tryFind(candidates(), r -> extraPredicate.test(r) && !contacts(r)).orNull();
        }

        public Replica lookup(InetAddressAndPort endpoint)
        {
            return candidates().byEndpoint().get(endpoint);
        }

        public String toString()
        {
            return "ReplicaPlan.ForRead [ CL: " + consistencyLevel + " keyspace: " + keyspace + " candidates: " + candidates + " contacts: " + contacts() + " ]";
        }
    }

    public static class ForTokenRead extends ForRead<EndpointsForToken>
    {
        public ForTokenRead(Keyspace keyspace,
                            AbstractReplicationStrategy replicationStrategy,
                            ConsistencyLevel consistencyLevel,
                            EndpointsForToken candidates,
                            EndpointsForToken contacts)
        {
            super(keyspace, replicationStrategy, consistencyLevel, candidates, contacts);
        }

        ForTokenRead withContact(EndpointsForToken newContact)
        {
            return new ForTokenRead(keyspace, replicationStrategy, consistencyLevel, candidates(), newContact);
        }
    }

    public static class ForRangeRead extends ForRead<EndpointsForRange>
    {
        final AbstractBounds<PartitionPosition> range;
        final int vnodeCount;

        public ForRangeRead(Keyspace keyspace,
                            AbstractReplicationStrategy replicationStrategy,
                            ConsistencyLevel consistencyLevel,
                            AbstractBounds<PartitionPosition> range,
                            EndpointsForRange candidates,
                            EndpointsForRange contact,
                            int vnodeCount)
        {
            super(keyspace, replicationStrategy, consistencyLevel, candidates, contact);
            this.range = range;
            this.vnodeCount = vnodeCount;
        }

        public AbstractBounds<PartitionPosition> range() { return range; }

        /**
         * @return number of vnode ranges covered by the range
         */
        public int vnodeCount() { return vnodeCount; }

        ForRangeRead withContact(EndpointsForRange newContact)
        {
            return new ForRangeRead(keyspace, replicationStrategy, consistencyLevel, range, candidates(), newContact, vnodeCount);
        }
    }

    public static abstract class ForWrite<E extends Endpoints<E>> extends ReplicaPlan<E>
    {
        // TODO: this is only needed because of poor isolation of concerns elsewhere - we can remove it soon, and will do so in a follow-up patch
        final E pending;
        final E liveAndDown;
        final E live;

        ForWrite(Keyspace keyspace, AbstractReplicationStrategy replicationStrategy, ConsistencyLevel consistencyLevel, E pending, E liveAndDown, E live, E contact)
        {
            super(keyspace, replicationStrategy, consistencyLevel, contact);
            this.pending = pending;
            this.liveAndDown = liveAndDown;
            this.live = live;
        }

        public int blockFor() { return consistencyLevel.blockForWrite(replicationStrategy, pending()); }

        /** Replicas that a region of the ring is moving to; not yet ready to serve reads, but should receive writes */
        public E pending() { return pending; }
        /** Replicas that can participate in the write - this always includes all nodes (pending and natural) in all DCs, except for paxos LOCAL_QUORUM (which is local DC only) */
        public E liveAndDown() { return liveAndDown; }
        /** The live replicas present in liveAndDown, usually derived from FailureDetector.isReplicaAlive */
        public E live() { return live; }
        /** Calculate which live endpoints we could have contacted, but chose not to */
        public E liveUncontacted() { return live().filter(r -> !contacts(r)); }
        /** Test liveness, consistent with the upfront analysis done for this operation (i.e. test membership of live()) */
        public boolean isAlive(Replica replica) { return live.endpoints().contains(replica.endpoint()); }
        public Replica lookup(InetAddressAndPort endpoint)
        {
            return liveAndDown().byEndpoint().get(endpoint);
        }

        public String toString()
        {
            return "ReplicaPlan.ForWrite [ CL: " + consistencyLevel + " keyspace: " + keyspace + " liveAndDown: " + liveAndDown + " live: " + live + " contacts: " + contacts() +  " ]";
        }
    }

    public static class ForTokenWrite extends ForWrite<EndpointsForToken>
    {
        public ForTokenWrite(Keyspace keyspace, AbstractReplicationStrategy replicationStrategy, ConsistencyLevel consistencyLevel, EndpointsForToken pending, EndpointsForToken liveAndDown, EndpointsForToken live, EndpointsForToken contact)
        {
            super(keyspace, replicationStrategy, consistencyLevel, pending, liveAndDown, live, contact);
        }

        private ReplicaPlan.ForTokenWrite copy(ConsistencyLevel newConsistencyLevel, EndpointsForToken newContact)
        {
            return new ReplicaPlan.ForTokenWrite(keyspace, replicationStrategy, newConsistencyLevel, pending(), liveAndDown(), live(), newContact);
        }

        ForTokenWrite withConsistencyLevel(ConsistencyLevel newConsistencylevel) { return copy(newConsistencylevel, contacts()); }
        public ForTokenWrite withContact(EndpointsForToken newContact) { return copy(consistencyLevel, newContact); }
    }

    public static class ForPaxosWrite extends ForWrite<EndpointsForToken>
    {
        final int requiredParticipants;

        ForPaxosWrite(Keyspace keyspace, ConsistencyLevel consistencyLevel, EndpointsForToken pending, EndpointsForToken liveAndDown, EndpointsForToken live, EndpointsForToken contact, int requiredParticipants)
        {
            super(keyspace, keyspace.getReplicationStrategy(), consistencyLevel, pending, liveAndDown, live, contact);
            this.requiredParticipants = requiredParticipants;
        }

        public int requiredParticipants() { return requiredParticipants; }
    }

    /**
     * Used by AbstractReadExecutor, {Data,Digest}Resolver and ReadRepair to share a ReplicaPlan whose 'contacts' replicas
     * we progressively modify via various forms of speculation (initial speculation, rr-read and rr-write)
     *
     * The internal reference is not volatile, despite being shared between threads.  The initial reference provided to
     * the constructor should be visible by the normal process of sharing data between threads (i.e. executors, etc)
     * and any updates will either be seen or not seen, perhaps not promptly, but certainly not incompletely.
     * The contained ReplicaPlan has only final member properties, so it cannot be seen partially initialised.
     */
    public interface Shared<E extends Endpoints<E>, P extends ReplicaPlan<E>>
    {
        /**
         * add the provided replica to this shared plan, by updating the internal reference
         */
        public void addToContacts(Replica replica);
        /**
         * get the shared replica plan, non-volatile (so maybe stale) but no risk of partially initialised
         */
        public P get();
        /**
         * get the shared replica plan, non-volatile (so maybe stale) but no risk of partially initialised,
         * but replace its 'contacts' with those provided
         */
        public abstract P getWithContacts(E endpoints);
    }

    public static class SharedForTokenRead implements Shared<EndpointsForToken, ForTokenRead>
    {
        private ForTokenRead replicaPlan;
        SharedForTokenRead(ForTokenRead replicaPlan) { this.replicaPlan = replicaPlan; }
        public void addToContacts(Replica replica) { replicaPlan = replicaPlan.withContact(Endpoints.append(replicaPlan.contacts(), replica)); }
        public ForTokenRead get() { return replicaPlan; }
        public ForTokenRead getWithContacts(EndpointsForToken newContact) { return replicaPlan.withContact(newContact); }
    }

    public static class SharedForRangeRead implements Shared<EndpointsForRange, ForRangeRead>
    {
        private ForRangeRead replicaPlan;
        SharedForRangeRead(ForRangeRead replicaPlan) { this.replicaPlan = replicaPlan; }
        public void addToContacts(Replica replica) { replicaPlan = replicaPlan.withContact(Endpoints.append(replicaPlan.contacts(), replica)); }
        public ForRangeRead get() { return replicaPlan; }
        public ForRangeRead getWithContacts(EndpointsForRange newContact) { return replicaPlan.withContact(newContact); }
    }

    public static SharedForTokenRead shared(ForTokenRead replicaPlan) { return new SharedForTokenRead(replicaPlan); }
    public static SharedForRangeRead shared(ForRangeRead replicaPlan) { return new SharedForRangeRead(replicaPlan); }

}


text:
package holding.solution.ex10;
import static net.mindview.util.Print.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
class Rodent{
	Rodent() {
		print("Rodent init");
	}
	public void smile(){
		System.out.println("Rodent simle");
	}
}
class Mouse extends Rodent{
	Mouse() {
		print("Mouse init");
	}
	@Override
	public void smile(){
		System.out.println("Mouse smile");
	}
}
class Gerbil extends Rodent{
	Gerbil() {
		print("Gerbil init");
	}
	@Override
	public void smile(){
		System.out.println("Gerbil smile");
	}
}
class Hamster extends Rodent{
	Hamster() {
		print("Hamster init");
	}
	@Override
	public void smile(){
		System.out.println("Hamster smile");
	}
}

public class Ex10 {
	public static Rodent ro[] =  new Rodent[]{
			new Gerbil(),
			new Mouse(),
			new Hamster(),
		};

	public static void main(String[] args){

		List<Rodent> rodents = new ArrayList<Rodent>(Arrays.asList(ro));
		Iterator<Rodent> it = rodents.iterator();
		while(it.hasNext()){
			it.next().smile();
		}

	}
}


text:
from django.db import models

# Fields (Requirements)
from djangocms_text_ckeditor.fields import HTMLField

#Filer (Requirements)
from filer.fields.image import FilerImageField
from filer.fields.folder import FilerFolderField

# Taggit (Requirements)
from taggit.managers import TaggableManager

# Reverse
from django.core.urlresolvers import reverse

# I18N
from django.utils.translation import ugettext as _

class CategoryWork(models.Model):
    title = models.CharField(_('Title'), max_length=255)
    slug = models.SlugField()

    class Meta:
        verbose_name = _('Category')
        verbose_name_plural = _('Categories')

    def __str__(self):
        return self.title

class Work(models.Model):
    title = models.CharField(_('Title'), max_length=200)
    slug = models.SlugField()
    pub_date = models.DateTimeField(_('Published on'), auto_now_add=True)
    description = HTMLField(_('Work Description'))
    category = models.ForeignKey(CategoryWork, verbose_name=_('Category'))
    tags = TaggableManager()
    client = models.CharField(_('Client'), max_length=255, null=True, blank=True)
    location = models.CharField(_('Location'), max_length=255, null=True, blank=True)
    head_picture = FilerImageField(verbose_name=_("Head"))
    folder = FilerFolderField(verbose_name=_('Gallery Folder'), null=True, blank=True)

    class Meta:
        verbose_name = _('Work')
        verbose_name_plural = _('Works')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('work_detail', args=[self.slug])

    def get_next_work(self):
        try:
            next_work = Work.objects.get(pk=self.pk+1)
            return reverse('work_detail', args=[next_work.slug])
        except:
            return None

    def get_previous_work(self):
        try:
            previous_work = Work.objects.get(pk=self.pk-1)
            return reverse('work_detail', args=[previous_work.slug])
        except:
            return None


text:
package me.eddiep.minecraft.ls.system;

public class TimeUtils {
    public static String toFriendlyTime(long duration) {
        int minutes = (int) (duration / 60000), seconds = (int) ((duration / 1000) % 60);
        return minutes + " minute" + (minutes != 1 ? "s" : "") + " and " + seconds + " second" + (seconds != 1 ? "s" : "") + "!";
    }
}


text:
.sc-manuscript-view {
  flex-grow: 1;
}

.sc-manuscript-view {
  display: flex;
  flex-direction: row;
  height: 100%;
}

.sc-manuscript-view .se-toolbar-wrapper {
  z-index: 1000;
  padding: 4px;
  padding-bottom: 4px;
  box-shadow: var(--t-default-box-shadow);
}

.sc-manuscript-view.sm-compact .se-toolbar-wrapper {
  padding-left: 20px;
  padding-right: 20px;
}

.sc-manuscript-view .se-toolbar-wrapper .sc-toolbar {
  max-width: 980px; /* 760 - 50 for padding */
}

.sc-manuscript-view.sm-compact .se-toolbar-wrapper .sc-toolbar {
  margin: 0 auto;
  max-width: 710px;
}

.sc-manuscript-view > .se-context-pane {
  flex: 0 2 300px;
  border-left: var(--t-default-border);
  position: relative;
}

/* This seems to be obsolete
TODO: remove this if so
.sc-manuscript-view .sc-container-editor.sm-body {
  padding: 0;
  margin: 0 auto;
}
*/

.sc-manuscript-view .se-context-pane > .se-context-pane-content {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  overflow: auto;
}

.sc-manuscript-view > .se-main-section {
  flex: 1 1 600px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sc-manuscript-view > .se-main-section > .se-toolbar-wrapper {
  flex: 0 0 40px;
}

.sc-manuscript-view > .se-main-section > .se-content-section {
  flex: 1 1 0;
  display: flex;
  flex-direction: row;
}

.sc-manuscript-view > .se-main-section > .se-content-section > .se-toc-pane {
  flex: 0 0 250px;
  overflow: auto;
}

/* Do not display in compact mode to make more space for the rest */
.sc-manuscript-view.sm-compact > .se-main-section > .se-content-section > .se-toc-pane {
  display: none;
}

.sc-manuscript-view > .se-main-section > .se-content-section > .se-toc-pane.sm-hidden {
  display: none;
}

.sc-manuscript-view > .se-main-section > .se-content-section > .sc-scroll-pane {
  flex: 1 1 600px;
}

.sc-manuscript-view .se-main-section .sc-scroll-pane {
  position: relative;
}

.sc-manuscript-view .sc-container-editor:not(.sm-body):not(.sm-readonly) {
  border: var(--t-input-default-border);
  border-radius: var(--t-border-radius);
  padding: var(--t-input-padding);
  margin: var(--t-negative-input-padding);
}

.sc-manuscript-view .sc-container-editor:not(.sm-body):not(.sm-readonly):focus {
  border: var(--t-input-focus-border);
}

/* Add padding to each child except last one */
.sc-manuscript-view .sc-container-editor > * {
  margin: var(--t-text-spacing) 0;
}

.sc-manuscript-view .sc-container-editor > *:first-child {
  margin-top: 0 !important;
}

.sc-manuscript-view .sc-container-editor > *:last-child {
  margin-bottom: 0 !important;
}

.sc-manuscript-view .se-footer-pane {
  background: white;
  border-top: var(--t-default-border);
}


text:
var callbackQueue = [];
var isLoadingCompleted = false;
var isReady = false;

// Keeps track of how many events to wait for in addition to loading completing,
// before we're considered ready.
var readyHoldsCount = 0;

if (window.meteorExtraReadyHolds === undefined)
  window.meteorExtraReadyHolds = 0;

var holdReady =  function () {
  readyHoldsCount++;
}

var releaseReadyHold = function () {
  readyHoldsCount--;
  maybeReady();
}

var maybeReady = function () {
  if (isReady || !isLoadingCompleted || readyHoldsCount > 0 || window.meteorExtraReadyHolds > 0)
    return;

  isReady = true;

  // Run startup callbacks
  while (callbackQueue.length)
    (callbackQueue.shift())();

  if (Meteor.isCordova) {
    // Notify the WebAppLocalServer plugin that startup was completed successfully,
    // so we can roll back faulty versions if this doesn't happen
    WebAppLocalServer.startupDidComplete();
  }
};

var loadingCompleted = function () {
  if (!isLoadingCompleted) {
    isLoadingCompleted = true;
    maybeReady();
  }
}

if (Meteor.isCordova) {
  holdReady();
  document.addEventListener('deviceready', releaseReadyHold, false);
}

if (document.readyState === 'complete' || document.readyState === 'loaded') {
  // Loading has completed,
  // but allow other scripts the opportunity to hold ready
  window.setTimeout(loadingCompleted);
} else { // Attach event listeners to wait for loading to complete
  if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', loadingCompleted, false);
    window.addEventListener('load', loadingCompleted, false);
  } else { // Use IE event model for < IE9
    document.attachEvent('onreadystatechange', function () {
      if (document.readyState === "complete") {
        loadingCompleted();
      }
    });
    window.attachEvent('load', loadingCompleted);
  }
}

Meteor.holdReady = holdReady;
Meteor.releaseReadyHold = releaseReadyHold;
Meteor.maybeReady = maybeReady;
/**
 * @summary Run code when a client or a server starts.
 * @locus Anywhere
 * @param {Function} func A function to run on startup.
 */
Meteor.startup = function (callback) {
  // Fix for < IE9, see http://javascript.nwbox.com/IEContentLoaded/
  var doScroll = !document.addEventListener &&
    document.documentElement.doScroll;

  if (!doScroll || window !== top) {
    if (isReady)
      callback();
    else
      callbackQueue.push(callback);
  } else {
    try { doScroll('left'); }
    catch (error) {
      setTimeout(function () { Meteor.startup(callback); }, 50);
      return;
    };
    callback();
  }
};


text:
require 'net/http'
require 'json'

# Token Objects contains access and refresh token for
# Google API requests
class Token < ActiveRecord::Base
  belongs_to :user

  def self.from_omniauth auth, user
    Token.where(
      :provider => auth['provider'],
      :uid => auth['uid']
    ).first || self.create_with_omniauth(auth, user)
  end

  def self.create_with_omniauth auth, user
    create! do |token|
      token.provider = auth['provider'] || ''
      token.token = auth['credentials']['token'] || ''
      token.refresh_token = auth['credentials']['refresh_token'] || ''
      token.expires_at = Time.at(auth['credentials']['expires_at']) || ''
      token.uid = auth['uid'] || ''
      token.user = user
    end
  end

  # refresh token based on
  # https://www.twilio.com/blog/2014/09/gmail-api-oauth-rails.html

  def to_params
    {'refresh_token' => refresh_token,
    'client_id' => ENV['GOOGLE_KEY'],
    'client_secret' => ENV['GOOGLE_SECRET'],
    'grant_type' => 'refresh_token'}
  end

  def request_token_from_google
    url = URI('https://accounts.google.com/o/oauth2/token')
    Net::HTTP.post_form(url, self.to_params)
  end

  def refresh!
    response = request_token_from_google
    data = JSON.parse(response.body)
    update_attributes(
      token: data['access_token'],
      expires_at: (Time.now.getlocal + data['expires_in'])
    )
    data['access_token']
  end

  def expired?
    expires_at < Time.now.getlocal
  end

  def fresh_token
    if expired?
      refresh!
    else
      self.token
    end
  end
end


text:
/*Created by AlexCD on 11.04.2014*/

/**
 * Directive to add a custom swiping effect on element, a swiping effect that will work on windows mobile phones
 * @method customSwiping
 * @returns {{restrict: string, scope: {right: string, left: string}, link: link}}
 */
function customSwiping() {
    "use strict";
    return {
        restrict: 'E',
        scope: {
            right: '=',
            left: '='
        },
        link: function (scope, element) {
            var startCoord, endCoord, timer;

            /**
             * Retrieves pageX, pageY coordinates
             * @method getTouchCoordinates
             * @param event
             * @returns {{x: (Number|pageX|*), y: (Number|pageY|*)}}
             */
            function getTouchCoordinates(event) {
                var touch;
                if (event.type === 'mousedown' || event.type === 'mousemove') {
                    touch = event;
                } else {
                    if (event.touches) {
                        touch = event.touches[0];
                    } else {
                        touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0];
                    }
                }
                return {x: touch.pageX, y: touch.pageY};
            }

            /**
             * A swipe can be done 360 degrees. In this directive case, a swipe is executed when the angle has no more than 10 degrees.
             * So, to find the angle, trigonometry is used (tangent / arctangent functions)
             * @method getTheta
             * @returns {number}
             */
            function getTheta() {
                var dy, dx, theta;
                dy = endCoord.y - startCoord.y; //opposite cathetus
                dx = endCoord.x - startCoord.x; //adjacent cathetus

                //the angle
                theta = Math.atan2(dy, dx);
                theta *= 180 / Math.PI;

                //return the angle
                return Math.abs(theta);
            }

            /**
             * Each swipe uses specified callback
             * @method makeSwipe
             */
            function makeSwipe() {
                if (startCoord && endCoord) {
                    if ((startCoord.x - endCoord.x) < -10) {
                        if (scope.right) {
                            if (getTheta() >= 0 && getTheta() <= 10) {
                                scope.right();
                                scope.$apply();

                            }
                        }
                    } else if ((startCoord.x - endCoord.x) > 10) {
                        if (scope.left) {
                            if (getTheta() >= 170 && getTheta() <= 180) {
                                scope.left();
                                scope.$apply();
                            }
                        }
                    }
                }
            }

            function getStartCoord(e) {
                return getTouchCoordinates(e);
            }

            function getEndCoord(e) {
                return getTouchCoordinates(e);
            }

            function detectMouseEnd() {
                /*global window, clearTimeout*/
                if (timer) {
                    clearTimeout(timer);
                }
                timer = window.setTimeout(function () {
                    element.off('mousemove');
                    clearTimeout(timer);
                    makeSwipe();
                }, 50);
            }

            (function () {
                //For IE and desktops
                //Mouse events are used instead of pointer events. IE pointer events incorporate both mouse events and touch events but they will be prone to
                //changes as IE does this all the time. For instance IE10 uses MSPointerDown, MSPointerMove, MSPointerUp but these are deprecated and not used in IE11. IE11
                //uses pointerdown, pointermove, pointerup. Of course, conditions can be used but the idea is to keep the code as simple as possible, ignoring IE bliss.
                //So mouse events can be used instead.
                //Since mouseup event can create problems, a mouseend method will be used to track the end of swiping
                element.on('mousedown', function (e) {
                    startCoord = getStartCoord(e);

                    element.on('mousemove', function (e) {
                        endCoord = getEndCoord(e);
                        detectMouseEnd(e);
                    });

                });

                //For all other mobile browsers
                element.on('touchstart', function (e) {
                    startCoord = getStartCoord(e);
                });
                element.on('touchend', function (e) {
                    endCoord = getEndCoord(e);
                    makeSwipe();
                });

            }());

            scope.$on('$destroy', function () {
                element.off();
            });

        }
    };
}


text:
This document is for project maintainers who are doing versioning, releases, and publishing for the cardstack mono-repo.

## Updating package versions (with safeguards)

The versions of all packages in the mono-repo are updated at the same time, to the same version number.

1. Get the latest code on main: `git checkout main`, `git pull origin main`
2. Make sure your history is clean with `git status`
3. Look at the `git log` since the last release, and list anything significant in the `CHANGELOG.md`.
Determine whether the release should be a major (breaking), minor, or patch.
For breaking releases, include upgrade instructions in the changelog. Commit your changes.
4. Update all package versions, publish to npm, and push to GitHub with this command: `npx lerna publish --force-publish="*" --exact`
5. Check to see that the new version is on GitHub and on npm

## Updating packages yolo-style

If you are very confident in what you are doing, you can accomplish all of the above by running this command from an up-to-date version of `main`.

```sh
npx lerna publish --force-publish="*" --exact
```

## Pitfalls to look out for

- Always make sure you are publishing from an up-to-date copy of `main`. You don't want to publish stale code!
- New packages may need some additional configuration before they can be published
- If you have problems, check the version of lerna you are using. There may be new features in the lerna docs that are more recent than our version. Always use `npx` and not a globally installed version of lerna, for consistency.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using ColorMeCode.AppDomainHost.Core.Utilities;

namespace ColorMeCode.AppDomainHost.Core.Proxies
{
    public class ChildProxy:MarshalByRefObject,IDisposable
    {
        bool _disposed;
        ReferencedObject _referencedObject;
        SerializableObject _serializableObject;
        NonSerializableObject _nonSerializableObject;

        public ChildProxy()
        {
            _referencedObject = new ReferencedObject();
            _serializableObject = new SerializableObject();
            _nonSerializableObject = new NonSerializableObject();
        }

        public string WheraAmI()
        {
            return AppDomain.CurrentDomain.FriendlyName;
        }

        public void SetConsoleColor(int color)
        {
            ColoredOutput coloredOutput = new ColoredOutput(color);
            Console.SetOut(coloredOutput);
        }

        public ReferencedObject GetReferencedObject()
        {
            return _referencedObject;
        }

        public void SetReferencedObject(string value)
        {
            _referencedObject.Value = value;
            ShowReferencedObject();
        }

        public void ShowReferencedObject()
        {
            Console.WriteLine("Domain {0} ReferencedObject Value {1}", AppDomain.CurrentDomain.FriendlyName, _referencedObject.Value);
        }

        public SerializableObject GetSerializableObject()
        {
            return _serializableObject;
        }

        public void SetSerializableObject(string value)
        {
            _serializableObject.Value=value;
            ShowSerializableObject();
        }

        public void ShowSerializableObject()
        {
            Console.WriteLine("Domain {0} SerializableObject Value {1}", AppDomain.CurrentDomain.FriendlyName, _serializableObject.Value);
        }

        public NonSerializableObject GetNonSerializableObject()
        {
            return _nonSerializableObject;
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            RemotingServices.Disconnect(this);
            _disposed = true;
        }

        ~ChildProxy()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }
    }
}


text:
module Utils.CmdArgParser (Arguments (..),
                           Arg (..),
                           getArguments) where

-- this module defines a command line
-- argument parser

import Control.Applicative hiding (many)
import Control.Monad.Identity
import Data.List
import System.Environment (getArgs)
import System.Posix.Files (fileExist)
import Text.Parsec
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)

-- simple data type for representing arguments

data Arguments = Arguments [Arg] FilePath
                 deriving (Eq, Ord)

-- Arguments for controling the behavior of the
-- algorithm

data Arg = KindInfo            -- represented by --k
         | ClassInfo           -- represented by --c
         | InstInfo            -- represented by --i
         | AssumpInfo          -- represented by --a
         | Recomp              -- represented by --r
         | Make                -- enable multi module compilation
         | Help                -- shows help message
         deriving (Eq, Ord, Enum)

-- sample show instance for arguments

instance Show Arg where
    show KindInfo   = "--k"
    show ClassInfo  = "--c"
    show InstInfo   = "--i"
    show AssumpInfo = "--a"
    show Recomp     = "--r"
    show Make       = "--make"
    show Help       = "--h"

type Parser a = ParsecT String () Identity a

-- getting parameters

getArguments :: IO (Either String Arguments)
getArguments
    = do
        args <- getArgs
        let r = splitArgs args
        analysis r

analysis :: (Maybe [String], Maybe String) -> IO (Either String Arguments)
analysis (Nothing, Nothing)
    = return (Left "No input arguments.\nUsage: for information try --h option.")
analysis (Just x, Nothing)
    = if "--h" `elem` x then return (Left helpMessage)
        else return (Left "Incorrect usage. For more information try --h option.")
analysis (Nothing, Just f)
    = do
        b <- fileExist f
        if b then return (Right (Arguments [] f))
          else return (Left (concat ["The file:\n", f, "\ndoesn't exist."]))
analysis (Just as, Just f)
    = finish as f

finish :: [String] -> String -> IO (Either String Arguments)
finish ss s
    = do
        let ps = concat ss
            args = parser ps
        either (return . Left) (complete s) args

complete :: String -> [Arg] -> IO (Either String Arguments)
complete s args
    = do
        b <- fileExist s
        if b then return (Right (Arguments args s))
          else return (Left (concat ["The file:\n", s, "\ndoesn't exist."]))

parser :: String -> Either String [Arg]
parser s
    = case parse pargs "" s of
           Left _ -> Left "Incorrect usage. For more information try --h option."
           Right as -> Right as

-- parses very simple arguments

pargs :: Parser [Arg]
pargs
    = many (arg ps)
      where
        ps = map (\i -> (show i, i)) [KindInfo ..]
        arg = choice . map f
        f (s,k) = const k <$> try (symbol s)

-- lexer definition

lexer = P.makeTokenParser emptyDef
symbol = P.symbol lexer

-- some auxiliar functions

splitArgs :: [String] -> (Maybe [String], Maybe String)
splitArgs ss
    = case partition (\s -> (take 2 s) == "--") ss of
              ([],[x]) -> (Nothing, Just x)
              (ps,[x]) -> (Just ps, Just x)
              (ps,[])  -> (Just ps, Nothing)
              _        -> (Nothing, Nothing)

helpMessage :: String
helpMessage = "Usage:\nmain [options] file\n\n" ++
              "Options:\n--k: Show infered kinds\n"++
              "--c: Show infered class constraints\n" ++
              "--i: Show infered instance constraints\n" ++
              "--a: Show infered types (include data constructors)\n" ++
              "--r: Turn off recompilation checker\n" ++
              "--make : Enable multi-module processing\n" ++
              "--h: Show this message\n"


text:
package org.spoofax.jsglr2.integrationtest.features;

import java.util.stream.Stream;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;

public class PreferAvoidTest extends BaseTestWithSdf3ParseTables {

    public PreferAvoidTest() {
        super("prefer-avoid.sdf3");
    }

    @TestFactory public Stream<DynamicTest> testAvoid() {
        return testSuccessByExpansions("a x", "Avoid(amb([X2, X3]))");
    }

    @TestFactory public Stream<DynamicTest> testPrefer() {
        return testSuccessByExpansions("p x", "Prefer(X1)");
    }

}


text:
var grunt = require('../grunt').grunt();
var atCompiledTemplate = require('../contentProviders/ATCompiledTemplate');
var UglifyJS = require("uglify-js");
var uglifyJSContentProvider = require('../contentProviders/uglifyJS');

var ATValidateTemplates = function (cfg) {
    cfg = cfg || {};
    this.files = cfg.files || ['**/*'];
};

ATValidateTemplates.prototype.onWriteInputFile = function (packaging, outputFile, inputFile) {
    if (!inputFile.isMatch(this.files)) {
        return;
    }
    if (!atCompiledTemplate.getClassGeneratorFromLogicalPath(inputFile.logicalPath)) {
        return;
    }
    // make sure it is possible to get the template
    var res = atCompiledTemplate.getCompiledTemplate(inputFile);
    if (res == null) {
        grunt.log.error('ATValidateTemplates: could not compile template ' + inputFile.logicalPath.yellow);
        return;
    }
    try {
        // try to parse the template with the strict option:
        var ast = UglifyJS.parse(res, {
            strict : true,
            filename : inputFile.logicalPath
        });
        // as we have the ast, let's store it in case it is useful later:
        uglifyJSContentProvider.setAST(inputFile, ast);
    } catch (e) {
        grunt.log.error("JS validation failed in the compiled version of template " + inputFile.logicalPath.yellow +
                " (line " + e.line + ", column " + e.col + ") " + e.message.yellow);
    }
};

module.exports = ATValidateTemplates;


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.lookup_values_for_attribute.html">

Redirecting to fn.lookup_values_for_attribute.html...