text:
package dotty.tools
package dotc
package core

import Types._, Contexts._, Symbols._
import Decorators._
import config.Config
import config.Printers._
import collection.mutable

/** Methods for adding constraints and solving them.
 *
 * What goes into a Constraint as opposed to a ConstrainHandler?
 *
 * Constraint code is purely functional: Operations get constraints and produce new ones.
 * Constraint code does not have access to a type-comparer. Anything regarding lubs and glbs has to be done
 * elsewhere.
 *
 * By comparison: Constraint handlers are parts of type comparers and can use their functionality.
 * Constraint handlers update the current constraint as a side effect.
 */
trait ConstraintHandling {

  implicit val ctx: Context

  protected def isSubType(tp1: Type, tp2: Type): Boolean
  protected def isSameType(tp1: Type, tp2: Type): Boolean

  val state: TyperState
  import state.constraint

  private var addConstraintInvocations = 0

  /** If the constraint is frozen we cannot add new bounds to the constraint. */
  protected var frozenConstraint = false

  private def addOneBound(param: PolyParam, bound: Type, isUpper: Boolean): Boolean =
    !constraint.contains(param) || {
      def occursIn(bound: Type): Boolean = {
        val b = bound.dealias
        (b eq param) || {
          b match {
            case b: AndOrType => occursIn(b.tp1) || occursIn(b.tp2)
            case b: TypeVar => occursIn(b.origin)
            case _ => false
          }
        }
      }
      if (Config.checkConstraintsSeparated)
        assert(!occursIn(bound), s"$param occurs in $bound")
      val c1 = constraint.narrowBound(param, bound, isUpper)
      (c1 eq constraint) || {
        constraint = c1
        val TypeBounds(lo, hi) = constraint.entry(param)
        isSubType(lo, hi)
      }
    }

  protected def addUpperBound(param: PolyParam, bound: Type): Boolean = {
    def description = i"constraint $param <: $bound to\n$constraint"
    if (bound.isRef(defn.NothingClass) && ctx.typerState.isGlobalCommittable) {
      def msg = s"!!! instantiated to Nothing: $param, constraint = ${constraint.show}"
      if (Config.failOnInstantiationToNothing) assert(false, msg)
      else ctx.log(msg)
    }
    constr.println(i"adding $description")
    val lower = constraint.lower(param)
    val res =
      addOneBound(param, bound, isUpper = true) &&
      lower.forall(addOneBound(_, bound, isUpper = true))
    constr.println(i"added $description = $res")
    res
  }

  protected def addLowerBound(param: PolyParam, bound: Type): Boolean = {
    def description = i"constraint $param >: $bound to\n$constraint"
    constr.println(i"adding $description")
    val upper = constraint.upper(param)
    val res =
      addOneBound(param, bound, isUpper = false) &&
      upper.forall(addOneBound(_, bound, isUpper = false))
    constr.println(i"added $description = $res")
    res
  }

  protected def addLess(p1: PolyParam, p2: PolyParam): Boolean = {
    def description = i"ordering $p1 <: $p2 to\n$constraint"
    val res =
      if (constraint.isLess(p2, p1)) unify(p2, p1)
      else {
        val down1 = p1 :: constraint.exclusiveLower(p1, p2)
        val up2 = p2 :: constraint.exclusiveUpper(p2, p1)
        val lo1 = constraint.nonParamBounds(p1).lo
        val hi2 = constraint.nonParamBounds(p2).hi
        constr.println(i"adding $description down1 = $down1, up2 = $up2")
        constraint = constraint.addLess(p1, p2)
        down1.forall(addOneBound(_, hi2, isUpper = true)) &&
        up2.forall(addOneBound(_, lo1, isUpper = false))
      }
    constr.println(i"added $description = $res")
    res
  }

  /** Make p2 = p1, transfer all bounds of p2 to p1
   *  @pre  less(p1)(p2)
   */
  private def unify(p1: PolyParam, p2: PolyParam): Boolean = {
    constr.println(s"unifying $p1 $p2")
    assert(constraint.isLess(p1, p2))
    val down = constraint.exclusiveLower(p2, p1)
    val up = constraint.exclusiveUpper(p1, p2)
    constraint = constraint.unify(p1, p2)
    val bounds = constraint.nonParamBounds(p1)
    val lo = bounds.lo
    val hi = bounds.hi
    isSubType(lo, hi) &&
    down.forall(addOneBound(_, hi, isUpper = true)) &&
    up.forall(addOneBound(_, lo, isUpper = false))
  }

  final def isSubTypeWhenFrozen(tp1: Type, tp2: Type): Boolean = {
    val saved = frozenConstraint
    frozenConstraint = true
    try isSubType(tp1, tp2)
    finally frozenConstraint = saved
  }

  final def isSameTypeWhenFrozen(tp1: Type, tp2: Type): Boolean = {
    val saved = frozenConstraint
    frozenConstraint = true
    try isSameType(tp1, tp2)
    finally frozenConstraint = saved
  }

  /** Test whether the lower bounds of all parameters in this
   *  constraint are a solution to the constraint.
   */
  protected final def isSatisfiable: Boolean =
    constraint.forallParams { param =>
      val TypeBounds(lo, hi) = constraint.entry(param)
      isSubType(lo, hi) || {
        ctx.log(i"sub fail $lo <:< $hi")
        false
      }
    }

  /** Solve constraint set for given type parameter `param`.
   *  If `fromBelow` is true the parameter is approximated by its lower bound,
   *  otherwise it is approximated by its upper bound. However, any occurrences
   *  of the parameter in a refinement somewhere in the bound are removed.
   *  (Such occurrences can arise for F-bounded types).
   *  The constraint is left unchanged.
   *  @return the instantiating type
   *  @pre `param` is in the constraint's domain.
   */
  final def approximation(param: PolyParam, fromBelow: Boolean): Type = {
    val avoidParam = new TypeMap {
      override def stopAtStatic = true
      def apply(tp: Type) = mapOver {
        tp match {
          case tp: RefinedType if param occursIn tp.refinedInfo => tp.parent
          case _ => tp
        }
      }
    }
    val bound = if (fromBelow) constraint.fullLowerBound(param) else constraint.fullUpperBound(param)
    val inst = avoidParam(bound)
    typr.println(s"approx ${param.show}, from below = $fromBelow, bound = ${bound.show}, inst = ${inst.show}")
    inst
  }

  /** Constraint `c1` subsumes constraint `c2`, if under `c2` as constraint we have
   *  for all poly params `p` defined in `c2` as `p >: L2 <: U2`:
   *
   *     c1 defines p with bounds p >: L1 <: U1, and
   *     L2 <: L1, and
   *     U1 <: U2
   *
   *  Both `c1` and `c2` are required to derive from constraint `pre`, possibly
   *  narrowing it with further bounds.
   */
  protected final def subsumes(c1: Constraint, c2: Constraint, pre: Constraint): Boolean =
    if (c2 eq pre) true
    else if (c1 eq pre) false
    else {
      val saved = constraint
      try
        c2.forallParams(p =>
          c1.contains(p) &&
          c2.upper(p).forall(c1.isLess(p, _)) &&
          isSubTypeWhenFrozen(c1.nonParamBounds(p), c2.nonParamBounds(p)))
      finally constraint = saved
    }

  /** The current bounds of type parameter `param` */
  final def bounds(param: PolyParam): TypeBounds = constraint.entry(param) match {
    case bounds: TypeBounds => bounds
    case _ => param.binder.paramBounds(param.paramNum)
  }

  /** Add polytype `pt`, possibly with type variables `tvars`, to current constraint
   *  and propagate all bounds.
   *  @param tvars   See Constraint#add
   */
  def addToConstraint(pt: PolyType, tvars: List[TypeVar]): Unit =
    assert {
      checkPropagated(i"initialized $pt") {
        constraint = constraint.add(pt, tvars)
        pt.paramNames.indices.forall { i =>
          val param = PolyParam(pt, i)
          val bounds = constraint.nonParamBounds(param)
          val lower = constraint.lower(param)
          val upper = constraint.upper(param)
          if (lower.nonEmpty && !bounds.lo.isRef(defn.NothingClass) ||
            upper.nonEmpty && !bounds.hi.isRef(defn.AnyClass)) constr.println(i"INIT*** $pt")
          lower.forall(addOneBound(_, bounds.hi, isUpper = true)) &&
            upper.forall(addOneBound(_, bounds.lo, isUpper = false))
        }
      }
    }

  /** Can `param` be constrained with new bounds? */
  final def canConstrain(param: PolyParam): Boolean =
    !frozenConstraint && (constraint contains param)

  /** Add constraint `param <: bound` if `fromBelow` is false, `param >: bound` otherwise.
   *  `bound` is assumed to be in normalized form, as specified in `firstTry` and
   *  `secondTry` of `TypeComparer`. In particular, it should not be an alias type,
   *  lazy ref, typevar, wildcard type, error type. In addition, upper bounds may
   *  not be AndTypes and lower bounds may not be OrTypes. This is assured by the
   *  way isSubType is organized.
   */
  protected def addConstraint(param: PolyParam, bound: Type, fromBelow: Boolean): Boolean = {
    def description = i"constr $param ${if (fromBelow) ">:" else "<:"} $bound:\n$constraint"
    //checkPropagated(s"adding $description")(true) // DEBUG in case following fails
    checkPropagated(s"added $description") {
      addConstraintInvocations += 1

      def addParamBound(bound: PolyParam) =
        if (fromBelow) addLess(bound, param) else addLess(param, bound)

      /** Drop all constrained parameters that occur at the toplevel in `bound` and
       *  handle them by `addLess` calls.
       *  The preconditions make sure that such parameters occur only
       *  in one of two ways:
       *
       *  1.
       *
       *    P <: Ts1 | ... | Tsm   (m > 0)
       *    Tsi = T1 & ... Tn      (n >= 0)
       *    Some of the Ti are constrained parameters
       *
       *  2.
       *
       *    Ts1 & ... & Tsm <: P   (m > 0)
       *    Tsi = T1 | ... | Tn    (n >= 0)
       *    Some of the Ti are constrained parameters
       *
       *  In each case we cannot leave the parameter in place,
       *  because that would risk making a parameter later a subtype or supertype
       *  of a bound where the parameter occurs again at toplevel, which leads to cycles
       *  in the subtyping test. So we intentionally narrow the constraint by
       *  recording an isLess relationship instead (even though this is not implied
       *  by the bound).
       *
       *  Narrowing a constraint is better than widening it, because narrowing leads
       *  to incompleteness (which we face anyway, see for instance eitherIsSubType)
       *  but widening leads to unsoundness.
       *
       *  A test case that demonstrates the problem is i864.scala.
       *  Turn Config.checkConstraintsSeparated on to get an accurate diagnostic
       *  of the cycle when it is created.
       *
       *  @return The pruned type if all `addLess` calls succeed, `NoType` otherwise.
       */
      def prune(bound: Type): Type = bound match {
        case bound: AndOrType =>
          val p1 = prune(bound.tp1)
          val p2 = prune(bound.tp2)
          if (p1.exists && p2.exists) bound.derivedAndOrType(p1, p2)
          else NoType
        case bound: TypeVar if constraint contains bound.origin =>
          prune(bound.underlying)
        case bound: PolyParam if constraint contains bound =>
          if (!addParamBound(bound)) NoType
          else if (fromBelow) defn.NothingType
          else defn.AnyType
        case _ =>
          bound
      }

      try bound match {
        case bound: PolyParam if constraint contains bound =>
          addParamBound(bound)
        case _ =>
          val pbound = prune(bound)
          pbound.exists && (
            if (fromBelow) addLowerBound(param, pbound) else addUpperBound(param, pbound))
      }
      finally addConstraintInvocations -= 1
    }
  }

  /** Instantiate `param` to `tp` if the constraint stays satisfiable */
  protected def tryInstantiate(param: PolyParam, tp: Type): Boolean = {
    val saved = constraint
    constraint =
      if (addConstraint(param, tp, fromBelow = true) &&
          addConstraint(param, tp, fromBelow = false)) constraint.replace(param, tp)
      else saved
    constraint ne saved
  }

  /** Check that constraint is fully propagated. See comment in Config.checkConstraintsPropagated */
  def checkPropagated(msg: => String)(result: Boolean): Boolean = {
    if (Config.checkConstraintsPropagated && result && addConstraintInvocations == 0) {
      val saved = frozenConstraint
      frozenConstraint = true
      for (p <- constraint.domainParams) {
        def check(cond: => Boolean, q: PolyParam, ordering: String, explanation: String): Unit =
          assert(cond, i"propagation failure for $p $ordering $q: $explanation\n$msg")
        for (u <- constraint.upper(p))
          check(bounds(p).hi <:< bounds(u).hi, u, "<:", "upper bound not propagated")
        for (l <- constraint.lower(p)) {
          check(bounds(l).lo <:< bounds(p).hi, l, ">:", "lower bound not propagated")
          check(constraint.isLess(l, p), l, ">:", "reverse ordering (<:) missing")
        }
      }
      frozenConstraint = saved
    }
    result
  }
}


text:
package org.assertj.core.internal;

import static org.assertj.core.configuration.ConfigurationProvider.CONFIGURATION_PROVIDER;
import static org.assertj.core.util.IterableUtil.isNullOrEmpty;

import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * Implements {@link ComparisonStrategy} contract with a comparison strategy based on a {@link Comparator}.
 *
 * @author Joel Costigliola
 */
public class ComparatorBasedComparisonStrategy extends AbstractComparisonStrategy {

  static final int NOT_EQUAL = -1;

  // A raw type is necessary because we can't make assumptions on object to be compared.
  @SuppressWarnings("rawtypes")
  private final Comparator comparator;

  // Comparator description used in assertion messages.
  private final String comparatorDescription;

  /**
   * Creates a new {@link ComparatorBasedComparisonStrategy} specifying the comparison strategy with given
   * comparator.
   *
   * @param comparator the comparison strategy to use.
   */
  public ComparatorBasedComparisonStrategy(@SuppressWarnings("rawtypes") Comparator comparator) {
    this(comparator, null);

  }

  /**
   * Creates a new {@link ComparatorBasedComparisonStrategy} specifying the comparison strategy with given
   * comparator and comparator description
   *
   * @param comparator the comparison strategy to use.
   * @param comparatorDescription the comparator description to use in assertion messages.
   */
  public ComparatorBasedComparisonStrategy(@SuppressWarnings("rawtypes") Comparator comparator,
                                           String comparatorDescription) {
    this.comparator = comparator;
    this.comparatorDescription = comparatorDescription;
  }

  /**
   * Creates a new {@link ComparatorBasedComparisonStrategy} specifying the comparison strategy with given
   * {@link DescribableComparator}.
   *
   * @param comparator the comparator to use in the comparison strategy.
   */
  public ComparatorBasedComparisonStrategy(DescribableComparator<?> comparator) {
    this(comparator, comparator.description());
  }

  /**
   * Returns true if given {@link Iterable} contains given value according to {@link #comparator}, false otherwise.

   * If given {@link Iterable} is null or empty, return false.
   *
   * @param iterable the {@link Iterable} to search value in
   * @param value the object to look for in given {@link Iterable}
   * @return true if given {@link Iterable} contains given value according to {@link #comparator}, false otherwise.
   */
  @Override
  @SuppressWarnings("unchecked")
  public boolean iterableContains(Iterable<?> iterable, Object value) {
    if (isNullOrEmpty(iterable)) return false;
    for (Object element : iterable) {
      // avoid comparison when objects are the same or both null
      if (element == value) return true;
      // both objects are not null => if one is then the other is not => compare next element with value
      if (value == null || element == null) continue;
      if (comparator.compare(element, value) == 0) return true;
    }
    return false;
  }

  /**
   * Look for given value in given {@link Iterable} according to the {@link Comparator}, if value is found it is removed
   * from it.

   * Does nothing if given {@link Iterable} is null (meaning no exception thrown).
   *
   * @param iterable the {@link Iterable} we want remove value from
   * @param value object to remove from given {@link Iterable}
   */
  @Override
  @SuppressWarnings("unchecked")
  public void iterableRemoves(Iterable<?> iterable, Object value) {
    if (iterable == null) return;
    // Avoid O(N^2) complexity of serial removal from an iterator of collections like ArrayList
    if (iterable instanceof Collection) {
      ((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0);
    } else {
      Iterator<?> iterator = iterable.iterator();
      while (iterator.hasNext()) {
        if (comparator.compare(iterator.next(), value) == 0) {
          iterator.remove();
        }
      }
    }
  }

  @Override
  @SuppressWarnings("unchecked")
  public void iterablesRemoveFirst(Iterable<?> iterable, Object value) {
    if (iterable == null) return;
    Iterator<?> iterator = iterable.iterator();
    while (iterator.hasNext()) {
      if (comparator.compare(iterator.next(), value) == 0) {
        iterator.remove();
        return;
      }
    }
  }

  /**
   * Returns true if actual and other are equal according to {@link #comparator}, false otherwise.

   * Handles the cases where one of the parameter is null so that internal {@link #comparator} does not have too.
   *
   * @param actual the object to compare to other
   * @param other the object to compare to actual
   * @return true if actual and other are equal according to {@link #comparator}, false otherwise.
   */
  @Override
  @SuppressWarnings("unchecked")
  public boolean areEqual(Object actual, Object other) {
    // we don't check actual or expected for null, this should be done by the comparator, the rationale being that a
    // comparator might consider null to be equals to some special value (like blank String and null)
    return comparator.compare(actual, other) == 0;
  }

  /**
   * Returns any duplicate elements from the given {@link Iterable} according to {@link #comparator}.
   *
   * @param iterable the given {@link Iterable} we want to extract duplicate elements.
   * @return an {@link Iterable} containing the duplicate elements of the given one. If no duplicates are found, an
   *         empty {@link Iterable} is returned.
   */
  // overridden to write javadoc.
  @Override
  public Iterable<?> duplicatesFrom(Iterable<?> iterable) {
    return super.duplicatesFrom(iterable);
  }

  @SuppressWarnings("unchecked")
  @Override
  protected Set<Object> newSetUsingComparisonStrategy() {
    return new TreeSet<>(comparator);
  }

  @Override
  public String asText() {
    return "when comparing values using " + toString();
  }

  @Override
  public String toString() {
    return CONFIGURATION_PROVIDER.representation().toStringOf(this);
  }

  public Comparator<?> getComparator() {
    return comparator;
  }

  public String getComparatorDescription() {
    return comparatorDescription;
  }

  @Override
  @SuppressWarnings("unchecked")
  public boolean stringStartsWith(String string, String prefix) {
    if (string.length() < prefix.length()) return false;
    String stringPrefix = string.substring(0, prefix.length());
    return comparator.compare(stringPrefix, prefix) == 0;
  }

  @Override
  @SuppressWarnings("unchecked")
  public boolean stringEndsWith(String string, String suffix) {
    if (string.length() < suffix.length()) return false;
    String stringSuffix = string.substring(string.length() - suffix.length());
    return comparator.compare(stringSuffix, suffix) == 0;
  }

  @Override
  public boolean stringContains(String string, String sequence) {
    int sequenceLength = sequence.length();
    for (int i = 0; i < string.length(); i++) {
      String subString = string.substring(i);
      if (subString.length() < sequenceLength) return false;
      if (stringStartsWith(subString, sequence)) return true;
    }
    return false;
  }

  @Override
  @SuppressWarnings("unchecked")
  public boolean isGreaterThan(Object actual, Object other) {
    return comparator.compare(actual, other) > 0;
  }

  @Override
  public boolean isStandard() {
    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
require('dotenv/config')

const jalla = require('jalla')
const mount = require('koa-mount')
const mongoose = require('mongoose')
const compose = require('koa-compose')
const router = require('./lib/router')
const lang = require('./lib/middleware/lang')

const app = jalla('index.js', {
  serve: process.env.NODE_ENV !== 'development',
  css: 'index.css',
  skip: [
    require.resolve('moment'),
    require.resolve('mapbox-gl'),
    require.resolve('highcharts')
  ]
})
app.keys = [process.env.BRFENERGI_SESSION_SECRET]
app.proxy = true

app.on('error', console.error)

if (process.env.BRFENERGI_USER && process.env.BRFENERGI_PASS) {
  app.use(require('koa-basic-auth')({
    name: process.env.BRFENERGI_USER,
    pass: process.env.BRFENERGI_PASS
  }))
}

app.use(require('@koa/cors')())
app.use(require('koa-session')(app))
app.use(require('koa-methodoverride')('_method'))
app.use(require('./lib/middleware/health'))
app.use(require('./lib/middleware/geoip'))
app.use(require('./lib/middleware/error'))
app.use(require('./lib/middleware/auth')())
app.use(require('./lib/middleware/prismic'))

app.use(async function (ctx, next) {
  ctx.set('Access-Control-Allow-Origin', process.env.FORUM_URL)
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  if (!ctx.response.get('Cache-Control')) {
    ctx.set('Cache-Control', 'no-cache, max-age=0')
  }
  return next()
})

const routes = compose([router.routes(), router.allowedMethods()])
app.use(mount('/en', compose([lang('en'), routes])))
app.use(routes)

mongoose.Promise = Promise
mongoose.connect(process.env.MONGO_URL, {
  useUnifiedTopology: true,
  useNewUrlParser: true,
  useCreateIndex: true
}).then(() => {
  app.listen(process.env.PORT || 8080)
}, err => {
  app.emit('error', err)
  process.exit(1)
})


text:
<template name="home">

            Restaurants

{{> preloader}}

</template>


text:
var AppRouter = Backbone.Router.extend({

	routes:{
		"":"home",
		"contact":"contact",
		"employees/:id":"employeeDetails"
	},

	initialize:function () {
		this.headerView = new HeaderView();
		$('.header').html(this.headerView.render().el);

		// Close the search dropdown on click anywhere in the UI
		$('body').click(function () {
			$('.dropdown').removeClass("open");
		});
	},

	home:function () {
		// Since the home view never changes, we instantiate it and render it only once
		if (!this.homeView) {
			this.homeView = new HomeView();
			this.homeView.render();
		}
		$('#content').html(this.homeView.el);
	},

	contact:function () {
		if (!this.contactView) {
			this.contactView = new ContactView();
			this.contactView.render();
		}
		$('#content').html(this.contactView.el);
	},

	employeeDetails:function (id) {
		var employee = new Employee({_id:id});
		employee.fetch({
			success:function (data) {
				// Note that we could also 'recycle' the same instance of EmployeeFullView
				// instead of creating new instances
				$('#content').html(new EmployeeFullView({model:data}).render().el);
			}
		});
	}

});

Backbone.Model.prototype.idAttribute = '_id';
tpl.loadTemplates(['home', 'contact', 'header', 'employee-full', 'employee-details', 'employee-list-item'],
	function () {
		app = new AppRouter();
		Backbone.history.start();
	});


text:
ABRAID-MP
=========
http://seeg.zoo.ox.ac.uk/themes/infectious-disease-atlas

[![Build Status](https://travis-ci.org/SEEG-Oxford/ABRAID-MP.svg?branch=master)](https://travis-ci.org/SEEG-Oxford/ABRAID-MP)

The Atlas of Baseline Risk Assessment for Infectious Disease (ABRAID) is an automated mapping platform (MP). The essence of the project is to create a system that automatically generates spatially comprehensive, iteratively improving, evidence-based maps of disease risk at the global scale. They will be continuously updated in response to new occurrence data collection. The concept is outlined in more detail in Hay et al. (2013).


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "DTD/xhtml1-strict.dtd">

    <title>pynprcalc.calc.main : API documentation</title>

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="apidocs.css" />

            pynprcalc API Documentation

      <button onclick="togglePrivate()" class="btn btn-link">Toggle Private API</button>

pynprcalc.calc.main module documentation

          Part of pynprcalc.calc

Corazón de la caluladora.

La calculadora tiene un *stack* (que es una cola LIFO, lo último que entra es lo
primero que sale). Trabaja con *float*.

Los números se ponen en el *stack*. Los comandos sacan cero o más números del
*stack*, hacen una operación con ellos y ponen el resultado en el *stack*.

Por ejemplo al comienzo el *stack* contiene varios números, los últimos números
están abajo.

::

    5
    6
    2
    4

Al usar el comando ``+``, el se toman los últimos dos números del *stack* y se
coloca su suma::

    5
    6
    6

    Class
    Stack

Implementación de un *stack*.

    Class
    Calc

Calculadora en sí.

      <address>
        API Documentation for pynprcalc, generated by pydoctor at 2017-06-18 11:43:43.
      </address>


text:
<?php

class Core_Model_SiteLogo
{
    public static function getFileName()
    {
        $db = Zend_Registry::get('db');
        $logoPath = $db->fetchOne("SELECT logo FROM organization_details");
        if (!$logoPath) {
            $logoPath = PUBLIC_PATH . "/files/logo/binary-vibes-bizsense-default.png";
        }
        return $logoPath;
    }

    public static function getLogoForDocumentsFileName()
    {
        $db = Zend_Registry::get('db');
        $logoPath = $db->fetchOne("SELECT logo_for_documents FROM organization_details");
        if (!$logoPath) {
            $logoPath = APPLICATION_PATH . "/data/logo/binary-vibes-bizsense-default-documents.png";
        }
        return $logoPath;
    }

}


text:
<?php

namespace app\models;

use Yii;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/**
 * This is the model class for table "tbl_atlet_pakaian_peralatan".
 *
 * @property integer $peralatan_id
 * @property integer $atlet_id
 * @property string $jenis_sukan
 * @property string $saiz
 * @property string $jenama
 * @property string $warna
 */
class AtletPakaianPeralatan extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_atlet_pakaian_peralatan';
    }

    public function behaviors()
    {
        return [
            [
                'class' => \yii\behaviors\BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'created',
                'updatedAtAttribute' => 'updated',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['atlet_id', 'tarikh_serahan', 'peralatan','jenis_sukan', 'jenama'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['atlet_id'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['jenis_sukan'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['model'], 'string', 'max' => 50, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['peralatan', 'jenama'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['saiz', 'warna'], 'string', 'max' => 10, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['jenis_sukan','model','peralatan', 'jenama','saiz', 'warna'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'peralatan_id' => GeneralLabel::peralatan_id,
            'atlet_id' => GeneralLabel::atlet_id,
            'jenis_sukan' => GeneralLabel::jenis_sukan,
            'peralatan' => GeneralLabel::nama_peralatan,
            'saiz' => GeneralLabel::saiz,
            'jenama' => GeneralLabel::jenama,
            'model' => GeneralLabel::model,
            'warna' => GeneralLabel::warna,
            'tarikh_serahan' => GeneralLabel::tarikh_serahan,

        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefSukan(){
        return $this->hasOne(RefSukan::className(), ['id' => 'jenis_sukan']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefJenamaPeralatan(){
        return $this->hasOne(RefJenamaPeralatan::className(), ['id' => 'jenama']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefPeralatanPinjaman(){
        return $this->hasOne(RefPeralatanPinjaman::className(), ['id' => 'peralatan']);
    }
}


text:
<?php

/**
 * Skeleton subclass for performing query and update operations on the 'rol' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.feetcent_feetcenter
 */
class RolQuery extends BaseRolQuery
{
}


text:
package com.xinfan.wxshop.business.entity;

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

public class GoodsLimitExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public GoodsLimitExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andGoodsIdIsNull() {
            addCriterion("goods_id is null");
            return (Criteria) this;
        }

        public Criteria andGoodsIdIsNotNull() {
            addCriterion("goods_id is not null");
            return (Criteria) this;
        }

        public Criteria andGoodsIdEqualTo(Integer value) {
            addCriterion("goods_id =", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdNotEqualTo(Integer value) {
            addCriterion("goods_id <>", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdGreaterThan(Integer value) {
            addCriterion("goods_id >", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("goods_id >=", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdLessThan(Integer value) {
            addCriterion("goods_id <", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdLessThanOrEqualTo(Integer value) {
            addCriterion("goods_id <=", value, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdIn(List<Integer> values) {
            addCriterion("goods_id in", values, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdNotIn(List<Integer> values) {
            addCriterion("goods_id not in", values, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdBetween(Integer value1, Integer value2) {
            addCriterion("goods_id between", value1, value2, "goodsId");
            return (Criteria) this;
        }

        public Criteria andGoodsIdNotBetween(Integer value1, Integer value2) {
            addCriterion("goods_id not between", value1, value2, "goodsId");
            return (Criteria) this;
        }

        public Criteria andTotalAmountIsNull() {
            addCriterion("total_amount is null");
            return (Criteria) this;
        }

        public Criteria andTotalAmountIsNotNull() {
            addCriterion("total_amount is not null");
            return (Criteria) this;
        }

        public Criteria andTotalAmountEqualTo(Integer value) {
            addCriterion("total_amount =", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountNotEqualTo(Integer value) {
            addCriterion("total_amount <>", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountGreaterThan(Integer value) {
            addCriterion("total_amount >", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountGreaterThanOrEqualTo(Integer value) {
            addCriterion("total_amount >=", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountLessThan(Integer value) {
            addCriterion("total_amount <", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountLessThanOrEqualTo(Integer value) {
            addCriterion("total_amount <=", value, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountIn(List<Integer> values) {
            addCriterion("total_amount in", values, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountNotIn(List<Integer> values) {
            addCriterion("total_amount not in", values, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountBetween(Integer value1, Integer value2) {
            addCriterion("total_amount between", value1, value2, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andTotalAmountNotBetween(Integer value1, Integer value2) {
            addCriterion("total_amount not between", value1, value2, "totalAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountIsNull() {
            addCriterion("sell_amount is null");
            return (Criteria) this;
        }

        public Criteria andSellAmountIsNotNull() {
            addCriterion("sell_amount is not null");
            return (Criteria) this;
        }

        public Criteria andSellAmountEqualTo(Integer value) {
            addCriterion("sell_amount =", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountNotEqualTo(Integer value) {
            addCriterion("sell_amount <>", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountGreaterThan(Integer value) {
            addCriterion("sell_amount >", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountGreaterThanOrEqualTo(Integer value) {
            addCriterion("sell_amount >=", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountLessThan(Integer value) {
            addCriterion("sell_amount <", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountLessThanOrEqualTo(Integer value) {
            addCriterion("sell_amount <=", value, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountIn(List<Integer> values) {
            addCriterion("sell_amount in", values, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountNotIn(List<Integer> values) {
            addCriterion("sell_amount not in", values, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountBetween(Integer value1, Integer value2) {
            addCriterion("sell_amount between", value1, value2, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andSellAmountNotBetween(Integer value1, Integer value2) {
            addCriterion("sell_amount not between", value1, value2, "sellAmount");
            return (Criteria) this;
        }

        public Criteria andBuyLimitIsNull() {
            addCriterion("buy_limit is null");
            return (Criteria) this;
        }

        public Criteria andBuyLimitIsNotNull() {
            addCriterion("buy_limit is not null");
            return (Criteria) this;
        }

        public Criteria andBuyLimitEqualTo(Integer value) {
            addCriterion("buy_limit =", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitNotEqualTo(Integer value) {
            addCriterion("buy_limit <>", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitGreaterThan(Integer value) {
            addCriterion("buy_limit >", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitGreaterThanOrEqualTo(Integer value) {
            addCriterion("buy_limit >=", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitLessThan(Integer value) {
            addCriterion("buy_limit <", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitLessThanOrEqualTo(Integer value) {
            addCriterion("buy_limit <=", value, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitIn(List<Integer> values) {
            addCriterion("buy_limit in", values, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitNotIn(List<Integer> values) {
            addCriterion("buy_limit not in", values, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitBetween(Integer value1, Integer value2) {
            addCriterion("buy_limit between", value1, value2, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andBuyLimitNotBetween(Integer value1, Integer value2) {
            addCriterion("buy_limit not between", value1, value2, "buyLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitIsNull() {
            addCriterion("time_limit is null");
            return (Criteria) this;
        }

        public Criteria andTimeLimitIsNotNull() {
            addCriterion("time_limit is not null");
            return (Criteria) this;
        }

        public Criteria andTimeLimitEqualTo(Date value) {
            addCriterion("time_limit =", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitNotEqualTo(Date value) {
            addCriterion("time_limit <>", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitGreaterThan(Date value) {
            addCriterion("time_limit >", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitGreaterThanOrEqualTo(Date value) {
            addCriterion("time_limit >=", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitLessThan(Date value) {
            addCriterion("time_limit <", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitLessThanOrEqualTo(Date value) {
            addCriterion("time_limit <=", value, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitIn(List<Date> values) {
            addCriterion("time_limit in", values, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitNotIn(List<Date> values) {
            addCriterion("time_limit not in", values, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitBetween(Date value1, Date value2) {
            addCriterion("time_limit between", value1, value2, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andTimeLimitNotBetween(Date value1, Date value2) {
            addCriterion("time_limit not between", value1, value2, "timeLimit");
            return (Criteria) this;
        }

        public Criteria andLimitTypeIsNull() {
            addCriterion("limit_type is null");
            return (Criteria) this;
        }

        public Criteria andLimitTypeIsNotNull() {
            addCriterion("limit_type is not null");
            return (Criteria) this;
        }

        public Criteria andLimitTypeEqualTo(Integer value) {
            addCriterion("limit_type =", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeNotEqualTo(Integer value) {
            addCriterion("limit_type <>", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeGreaterThan(Integer value) {
            addCriterion("limit_type >", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeGreaterThanOrEqualTo(Integer value) {
            addCriterion("limit_type >=", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeLessThan(Integer value) {
            addCriterion("limit_type <", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeLessThanOrEqualTo(Integer value) {
            addCriterion("limit_type <=", value, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeIn(List<Integer> values) {
            addCriterion("limit_type in", values, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeNotIn(List<Integer> values) {
            addCriterion("limit_type not in", values, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeBetween(Integer value1, Integer value2) {
            addCriterion("limit_type between", value1, value2, "limitType");
            return (Criteria) this;
        }

        public Criteria andLimitTypeNotBetween(Integer value1, Integer value2) {
            addCriterion("limit_type not between", value1, value2, "limitType");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}


text:
"""Test objects in module."""

import pytest

from sphinxcontrib.versioning.lib import Config

def test_config():
    """Test Config."""
    config = Config()
    config.update(dict(invert=True, overflow=('-D', 'key=value'), root_ref='master', verbose=1))

    # Verify values.
    assert config.banner_main_ref == 'master'
    assert config.greatest_tag is False
    assert config.invert is True
    assert config.overflow == ('-D', 'key=value')
    assert config.root_ref == 'master'
    assert config.verbose == 1
    assert repr(config) == ("<sphinxcontrib.versioning.lib.Config "
                            "_program_state={}, verbose=1, root_ref='master', overflow=('-D', 'key=value')>")

    # Verify iter.
    actual = sorted(config)
    expected = [
        ('banner_greatest_tag', False),
        ('banner_main_ref', 'master'),
        ('banner_recent_tag', False),
        ('chdir', None),
        ('git_root', None),
        ('greatest_tag', False),
        ('grm_exclude', tuple()),
        ('invert', True),
        ('local_conf', None),
        ('no_colors', False),
        ('no_local_conf', False),
        ('overflow', ('-D', 'key=value')),
        ('priority', None),
        ('push_remote', 'origin'),
        ('recent_tag', False),
        ('root_ref', 'master'),
        ('show_banner', False),
        ('sort', tuple()),
        ('verbose', 1),
        ('whitelist_branches', tuple()),
        ('whitelist_tags', tuple()),
    ]
    assert actual == expected

    # Verify contains, setitem, and pop.
    assert getattr(config, '_program_state') == dict()
    assert 'key' not in config
    config['key'] = 'value'
    assert getattr(config, '_program_state') == dict(key='value')
    assert 'key' in config
    assert config.pop('key') == 'value'
    assert getattr(config, '_program_state') == dict()
    assert 'key' not in config
    assert config.pop('key', 'nope') == 'nope'
    assert getattr(config, '_program_state') == dict()
    assert 'key' not in config

    # Test exceptions.
    with pytest.raises(AttributeError) as exc:
        config.update(dict(unknown=True))
    assert exc.value.args[0] == "'Config' object has no attribute 'unknown'"
    with pytest.raises(AttributeError) as exc:
        config.update(dict(_program_state=dict(key=True)))
    assert exc.value.args[0] == "'Config' object does not support item assignment on '_program_state'"
    with pytest.raises(AttributeError) as exc:
        config.update(dict(invert=False))
    assert exc.value.args[0] == "'Config' object does not support item re-assignment on 'invert'"


text:
$(function() {

    //Will hold the promise returned by AJAX call.
    var requestPromise;

    $('#makeRequest').click(function () {
        writeMessage('--------------------------------------------------');
        writeMessage('starting request');

        //Make an ajax request...this is a demo so we know it will take 10 seconds to respond
        // $.ajax returns a jQuery Promise.
        requestPromise = $.ajax({
            url: '/home/DelayService',
            type: 'POST'
        });

        writeMessage('done making the request.  Waiting for something to happen...');

        //Attach an event handler to the promise
        writeMessage('attach an event handler to the promise. Will run when the promise is resolved');
        requestPromise.done(function (data) {
            writeMessage('server says: ' + data.status);
        });

    });

    $('#attachToRequest').click(function() {

        //Attach another handler when the button is clicked.  But this will only work if the request has been made already.
        writeMessage('attach a different event handler to the promise.');
        requestPromise.done(function (data) {
            writeMessage('secret code is: ' + data.secretCode);
        });

    });
});

//Function to write messages to the message window
function writeMessage(message) {
    /// Write a message to the screen
    /// <param name="message" type="String">Message to display</param>

    var now = (new Date()).toTimeString().substring(0, 8);
    $('#messages').append('
' + now + ' ' + message + '
');
}


text:
define([
        'gettext', 'underscore', 'backbone'
    ], function (gettext, _, Backbone) {

        var UserModel = Backbone.Model.extend({
        	idAttribute: 'id',
        });
        return UserModel;
});


text:
package core.webui.server.handlers.internals.menu;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.nio.protocol.HttpAsyncExchange;
import org.apache.http.protocol.HttpContext;

import core.webui.server.handlers.AbstractSingleMethodHttpHandler;
import core.webui.webcommon.HttpServerUtilities;

public class MenuImportTaskActionHandler extends AbstractSingleMethodHttpHandler {

	public MenuImportTaskActionHandler() {
		super(AbstractSingleMethodHttpHandler.POST_METHOD);
	}

	@Override
	protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
		Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
		if (params == null) {
			return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get POST parameters.");
		}
		String path = params.get("path");
		if (path == null) {
			return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path must be provided.");
		}
		if (!Files.isRegularFile(Paths.get(path))) {
			return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path '" + path + "' is not a file.");
		}

		backEndHolder.importTasks(new File(path));
		return emptySuccessResponse(exchange);
	}
}


text:
<?php

/**
 * @package     Doctrine
 * @subpackage  Import
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @version     $Revision: 5801 $
 * @link        www.phpdoctrine.org
 * @since       1.0
 */
class Doctrine_Import_Sqlite extends Doctrine_Import
{
    /**
     * lists all databases
     *
     * @return array
     */
    public function listDatabases()
    {

    }

    /**
     * lists all availible database functions
     *
     * @return array
     */
    public function listFunctions()
    {

    }

    /**
     * lists all database triggers
     *
     * @param string|null $database
     * @return array
     */
    public function listTriggers($database = null)
    {

    }

    /**
     * lists all database sequences
     *
     * @param string|null $database
     * @return array
     */
    public function listSequences($database = null)
    {
        $query      = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
        $tableNames = $this->conn->fetchColumn($query);

        $result = array();
        foreach ($tableNames as $tableName) {
            if ($sqn = $this->conn->fixSequenceName($tableName, true)) {
                $result[] = $sqn;
            }
        }
        if ($this->conn->getAttribute(Doctrine::ATTR_PORTABILITY) & Doctrine::PORTABILITY_FIX_CASE) {
            $result = array_map(($this->conn->getAttribute(Doctrine::ATTR_FIELD_CASE) == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
        }
        return $result;
    }

    /**
     * lists table constraints
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableConstraints($table)
    {
        $table = $this->conn->quote($table, 'text');

        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";

        if ($this->conn->getAttribute(Doctrine::ATTR_PORTABILITY) & Doctrine::PORTABILITY_FIX_CASE) {
            $query .= 'LOWER(tbl_name) = ' . strtolower($table);
        } else {
            $query .= 'tbl_name = ' . $table;
        }
        $query  .= ' AND sql NOT NULL ORDER BY name';
        $indexes = $this->conn->fetchColumn($query);

        $result = array();
        foreach ($indexes as $sql) {
            if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {
                $index = $this->conn->formatter->fixIndexName($tmp[1]);
                if ( ! empty($index)) {
                    $result[$index] = true;
                }
            }
        }

        if ($this->conn->getAttribute(Doctrine::ATTR_PORTABILITY) & Doctrine::PORTABILITY_FIX_CASE) {
            $result = array_change_key_case($result, $this->conn->getAttribute(Doctrine::ATTR_FIELD_CASE));
        }
        return array_keys($result);
    }

    /**
     * lists table constraints
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableColumns($table)
    {
        $sql    = 'PRAGMA table_info(' . $table . ')';
        $result = $this->conn->fetchAll($sql);

        $description = array();
        $columns     = array();
        foreach ($result as $key => $val) {
            $val = array_change_key_case($val, CASE_LOWER);
            $decl = $this->conn->dataDict->getPortableDeclaration($val);

            $description = array(
                    'name'      => $val['name'],
                    'ntype'     => $val['type'],
                    'type'      => $decl['type'][0],
                    'alltypes'  => $decl['type'],
                    'notnull'   => (bool) $val['notnull'],
                    'default'   => $val['dflt_value'],
                    'primary'   => (bool) $val['pk'],
                    'length'    => null,
                    'scale'     => null,
                    'precision' => null,
                    'unsigned'  => null,
                    );
            $columns[$val['name']] = $description;
        }
        return $columns;
    }

    /**
     * lists table constraints
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableIndexes($table)
    {
        $sql  = 'PRAGMA index_list(' . $table . ')';
        return $this->conn->fetchColumn($sql);
   }
    /**
     * lists tables
     *
     * @param string|null $database
     * @return array
     */
    public function listTables($database = null)
    {
        $sql = "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' "
             . "UNION ALL SELECT name FROM sqlite_temp_master "
             . "WHERE type = 'table' ORDER BY name";

        return $this->conn->fetchColumn($sql);
    }

    /**
     * lists table triggers
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableTriggers($table)
    {

    }

    /**
     * lists table views
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableViews($table)
    {
        $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
        $views = $db->fetchAll($query);

        $result = array();
        foreach ($views as $row) {
            if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {
                if ( ! empty($row['name'])) {
                    $result[$row['name']] = true;
                }
            }
        }
        return $result;
    }

    /**
     * lists database users
     *
     * @return array
     */
    public function listUsers()
    {

    }

    /**
     * lists database views
     *
     * @param string|null $database
     * @return array
     */
    public function listViews($database = null)
    {
        $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";

        return $this->conn->fetchColumn($query);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Tweetinvi.Models;

namespace Tweetinvi.Parameters
{
    ///
    /// For more information visit : https://dev.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
    ///
    public interface IPublishTweetParameters : ICustomRequestParameters, ITweetModeParameter
    {
        ///
        /// Message to publish as a tweet
        ///
        string Text { get; set; }

        ///
        /// The ID of an existing status that the update is in reply to.
        ///
        long? InReplyToTweetId { get; set; }

        ///
        /// Quote a specific tweet
        ///
        ITweet QuotedTweet { get; set; }

        ///
        /// An existing status that the update is in reply to.
        ///
        ITweetIdentifier InReplyToTweet { get; set; }

        ///
        /// In order for a URL to not be counted in the status body of an extended Tweet, provide a URL as a Tweet attachment.
        /// This URL must be a Tweet permalink, or Direct Message deep link.
        /// Arbitrary, non-Twitter URLs must remain in the status text.
        /// URLs passed to the attachment_url parameter not matching either a Tweet permalink or
        /// Direct Message deep link will fail at Tweet creation and cause an exception.
        ///
        string QuotedTweetUrl { get; set; }

        ///
        /// A place in the world.
        ///
        string PlaceId { get; set; }

        ///
        /// Coordinates indicating the position from where the tweet has been published.
        ///
        ICoordinates Coordinates { get; set; }

        ///
        /// Whether or not to put a pin on the exact coordinates a tweet has been sent from.
        ///
        bool? DisplayExactCoordinates { get; set; }

        ///
        /// A list of media_ids to associate with the Tweet. You may include up to 4 photos or 1 animated GIF or 1 video in a Tweet.
        ///
        List<long> MediaIds { get; set; }

        ///
        /// A list of media (uploaded or not) that need to be displayed within the tweet.
        ///
        List<IMedia> Medias { get; set; }

        ///
        /// Whether this Tweet will be published with any media attached
        ///
        bool HasMedia { get; }

        ///
        /// If you upload Tweet media that might be considered sensitive content such as
        /// nudity, violence, or medical procedures, you should set this value to true.
        ///
        bool? PossiblySensitive { get; set; }

        ///
        /// If set to true, the creator property (IUser) will only contain the id.
        ///
        bool? TrimUser { get; set; }

        ///
        /// Twitter will auto-populate the @mentions in the extended tweet prefix from the Tweet
        /// being replied to, plus a mention of the screen name that posted the Tweet being replied to.
        /// i.e. This auto-populates a "reply all".
        /// Must be used with InReplyToTweetId or InReplyToTweet.
        /// Use ExcludeReplyUserIds to specify accounts to not mention in the prefix.
        /// Also note that there can be a maximum of 50 mentions in the prefix, any more will error.
        ///
        bool? AutoPopulateReplyMetadata { get; set; }

        ///
        /// Twitter User IDs to not include in the auto-populated extended Tweet prefix.
        /// Cannot exclude the User who is directly being replied to, only the additional mentions.
        /// Must be used with AutoPopulateReplyMetadata.
        ///
        IEnumerable<long> ExcludeReplyUserIds { get; set; }

        ///
        /// Associate an ads card with the Tweet using the card_uri value from any ads card response.
        ///
        string CardUri { get; set; }
    }

    /// <inheritdoc/>
    public class PublishTweetParameters : CustomRequestParameters, IPublishTweetParameters
    {
        public PublishTweetParameters()
        {
        }

        public PublishTweetParameters(string text)
        {
            Text = text;
        }

        public PublishTweetParameters(IPublishTweetParameters source) : base(source)
        {
            if (source == null)
            {
                return;
            }

            Text = source.Text;
            InReplyToTweet = source.InReplyToTweet;
            QuotedTweet = source.QuotedTweet;

            if (InReplyToTweet == null)
            {
                InReplyToTweetId = source.InReplyToTweetId;
            }

            MediaIds = source.MediaIds?.ToList();
            Medias = source.Medias?.ToList();
            PlaceId = source.PlaceId;
            Coordinates = source.Coordinates;
            DisplayExactCoordinates = source.DisplayExactCoordinates;
            PossiblySensitive = source.PossiblySensitive;
            TrimUser = source.TrimUser;
            AutoPopulateReplyMetadata = source.AutoPopulateReplyMetadata;
            ExcludeReplyUserIds = source.ExcludeReplyUserIds;
            TweetMode = source.TweetMode;
        }

        /// <inheritdoc/>
        public string Text { get; set; }

        /// <inheritdoc/>
        public ITweetIdentifier InReplyToTweet { get; set; }

        /// <inheritdoc/>
        public string QuotedTweetUrl { get; set; }

        /// <inheritdoc/>
        public ITweet QuotedTweet { get; set; }

        /// <inheritdoc/>
        public long? InReplyToTweetId
        {
            get => InReplyToTweet?.Id;
            set => InReplyToTweet = value != null ? new TweetIdentifier((long)value) : null;
        }

        /// <inheritdoc/>
        public List<long> MediaIds { get; set; } = new List<long>();
        /// <inheritdoc/>
        public List<IMedia> Medias { get; set; } = new List<IMedia>();
        /// <inheritdoc/>
        public bool HasMedia => MediaIds?.Count > 0 || Medias?.Count > 0;
        /// <inheritdoc/>
        public string PlaceId { get; set; }
        /// <inheritdoc/>
        public ICoordinates Coordinates { get; set; }
        /// <inheritdoc/>
        public bool? DisplayExactCoordinates { get; set; }
        /// <inheritdoc/>
        public bool? PossiblySensitive { get; set; }
        /// <inheritdoc/>
        public bool? TrimUser { get; set; }
        /// <inheritdoc/>
        public bool? AutoPopulateReplyMetadata { get; set; }
        /// <inheritdoc/>
        public IEnumerable<long> ExcludeReplyUserIds { get; set; }
        /// <inheritdoc/>
        public string CardUri { get; set; }
        /// <inheritdoc/>
        public TweetMode? TweetMode { get; set; }
    }
}


text:
#import "FCompoundHash.h"
#import "FChildrenNode.h"
#import "FLeafNode.h"
#import "FSnapshotUtilities.h"
#import "FStringUtilities.h"

@interface FCompoundHashBuilder ()

@property(nonatomic, strong) FCompoundHashSplitStrategy splitStrategy;

@property(nonatomic, strong) NSMutableArray *currentPaths;
@property(nonatomic, strong) NSMutableArray *currentHashes;

@end

@implementation FCompoundHashBuilder {

    // NOTE: We use the existence of this to know if we've started building a
    // range (i.e. encountered a leaf node).
    NSMutableString *optHashValueBuilder;

    // The current path as a stack. This is used in combination with
    // currentPathDepth to simultaneously store the last leaf node path. The
    // depth is changed when descending and ascending, at the same time the
    // current key is set for the current depth. Because the keys are left
    // unchanged for ascending the path will also contain the path of the last
    // visited leaf node (using lastLeafDepth elements)
    NSMutableArray *currentPath;
    NSInteger lastLeafDepth;
    NSInteger currentPathDepth;

    BOOL needsComma;
}

- (instancetype)initWithSplitStrategy:(FCompoundHashSplitStrategy)strategy {
    self = [super init];
    if (self != nil) {
        self->_splitStrategy = strategy;
        self->optHashValueBuilder = nil;
        self->currentPath = [NSMutableArray array];
        self->lastLeafDepth = -1;
        self->currentPathDepth = 0;
        self->needsComma = YES;
        self->_currentPaths = [NSMutableArray array];
        self->_currentHashes = [NSMutableArray array];
    }
    return self;
}

- (BOOL)isBuildingRange {
    return self->optHashValueBuilder != nil;
}

- (NSUInteger)currentHashLength {
    return self->optHashValueBuilder.length;
}

- (FPath *)currentPath {
    return [self currentPathWithDepth:self->currentPathDepth];
}

- (FPath *)currentPathWithDepth:(NSInteger)depth {
    NSArray *pieces =
        [self->currentPath subarrayWithRange:NSMakeRange(0, depth)];
    return [[FPath alloc] initWithPieces:pieces andPieceNum:0];
}

- (void)enumerateCurrentPathToDepth:(NSInteger)depth
                          withBlock:(void (^)(NSString *key))block {
    for (NSInteger i = 0; i < depth; i++) {
        block(self->currentPath[i]);
    }
}

- (void)appendKey:(NSString *)key toString:(NSMutableString *)string {
    [FSnapshotUtilities appendHashV2RepresentationForString:key
                                                   toString:string];
}

- (void)ensureRange {
    if (![self isBuildingRange]) {
        optHashValueBuilder = [NSMutableString string];
        [optHashValueBuilder appendString:@"("];
        [self
            enumerateCurrentPathToDepth:self->currentPathDepth
                              withBlock:^(NSString *key) {
                                [self appendKey:key
                                       toString:self->optHashValueBuilder];
                                [self->optHashValueBuilder appendString:@":("];
                              }];
        self->needsComma = NO;
    }
}

- (void)processLeaf:(FLeafNode *)leafNode {
    [self ensureRange];

    self->lastLeafDepth = self->currentPathDepth;
    [FSnapshotUtilities
        appendHashRepresentationForLeafNode:leafNode
                                   toString:self->optHashValueBuilder
                                hashVersion:FDataHashVersionV2];
    self->needsComma = YES;
    if (self.splitStrategy(self)) {
        [self endRange];
    }
}

- (void)startChild:(NSString *)key {
    [self ensureRange];

    if (self->needsComma) {
        [self->optHashValueBuilder appendString:@","];
    }
    [self appendKey:key toString:self->optHashValueBuilder];
    [self->optHashValueBuilder appendString:@":("];
    if (self->currentPathDepth == currentPath.count) {
        [self->currentPath addObject:key];
    } else {
        self->currentPath[self->currentPathDepth] = key;
    }
    self->currentPathDepth++;
    self->needsComma = NO;
}

- (void)endChild {
    self->currentPathDepth--;
    if ([self isBuildingRange]) {
        [self->optHashValueBuilder appendString:@")"];
    }
    self->needsComma = YES;
}

- (void)finishHashing {
    NSAssert(self->currentPathDepth == 0,
             @"Can't finish hashing in the middle of processing a child");
    if ([self isBuildingRange]) {
        [self endRange];
    }

    // Always close with the empty hash for the remaining range to allow simple
    // appending
    [self.currentHashes addObject:@""];
}

- (void)endRange {
    NSAssert([self isBuildingRange],
             @"Can't end range without starting a range!");
    // Add closing parenthesis for current depth
    for (NSUInteger i = 0; i < currentPathDepth; i++) {
        [self->optHashValueBuilder appendString:@")"];
    }
    [self->optHashValueBuilder appendString:@")"];

    FPath *lastLeafPath = [self currentPathWithDepth:self->lastLeafDepth];
    NSString *hash =
        [FStringUtilities base64EncodedSha1:self->optHashValueBuilder];
    [self.currentHashes addObject:hash];
    [self.currentPaths addObject:lastLeafPath];

    self->optHashValueBuilder = nil;
}

@end

@interface FCompoundHash ()

@property(nonatomic, strong, readwrite) NSArray *posts;
@property(nonatomic, strong, readwrite) NSArray *hashes;

@end

@implementation FCompoundHash

- (id)initWithPosts:(NSArray *)posts hashes:(NSArray *)hashes {
    self = [super init];
    if (self != nil) {
        if (posts.count != hashes.count - 1) {
            [NSException raise:NSInvalidArgumentException
                        format:@"Number of posts need to be n-1 for n hashes "
                               @"in FCompoundHash"];
        }
        self.posts = posts;
        self.hashes = hashes;
    }
    return self;
}

+ (FCompoundHashSplitStrategy)simpleSizeSplitStrategyForNode:(id<FNode>)node {
    NSUInteger estimatedSize =
        [FSnapshotUtilities estimateSerializedNodeSize:node];

    // Splits for
    // 1k -> 512 (2 parts)
    // 5k -> 715 (7 parts)
    // 100k -> 3.2k (32 parts)
    // 500k -> 7k (71 parts)
    // 5M -> 23k (228 parts)
    NSUInteger splitThreshold = MAX(512, (NSUInteger)sqrt(estimatedSize * 100));

    return ^BOOL(FCompoundHashBuilder *builder) {
      // Never split on priorities
      return [builder currentHashLength] > splitThreshold &&
             ![[[builder currentPath] getBack] isEqualToString:@".priority"];
    };
}

+ (FCompoundHash *)fromNode:(id<FNode>)node {
    return [FCompoundHash
             fromNode:node
        splitStrategy:[FCompoundHash simpleSizeSplitStrategyForNode:node]];
}

+ (FCompoundHash *)fromNode:(id<FNode>)node
              splitStrategy:(FCompoundHashSplitStrategy)strategy {
    if ([node isEmpty]) {
        return [[FCompoundHash alloc] initWithPosts:@[] hashes:@[ @"" ]];
    } else {
        FCompoundHashBuilder *builder =
            [[FCompoundHashBuilder alloc] initWithSplitStrategy:strategy];
        [FCompoundHash processNode:node builder:builder];
        [builder finishHashing];
        return [[FCompoundHash alloc] initWithPosts:builder.currentPaths
                                             hashes:builder.currentHashes];
    }
}

+ (void)processNode:(id<FNode>)node builder:(FCompoundHashBuilder *)builder {
    if ([node isLeafNode]) {
        [builder processLeaf:node];
    } else {
        NSAssert(![node isEmpty], @"Can't calculate hash on empty node!");
        FChildrenNode *childrenNode = (FChildrenNode *)node;
        [childrenNode enumerateChildrenAndPriorityUsingBlock:^(
                          NSString *key, id<FNode> node, BOOL *stop) {
          [builder startChild:key];
          [self processNode:node builder:builder];
          [builder endChild];
        }];
    }
}

@end


text:
namespace query_tiles {

// TileService that can cache API calls before the underlying |tile_service_| is
// initialized. After a successful initialization of |tile_service_|, all cached
// API calls will be invoked in sequence. If failed to initialize, cached API
// calls will be invoked with empty data.
class InitAwareTileService : public TileService {
 public:
  explicit InitAwareTileService(
      std::unique_ptr<InitializableTileService> tile_service);
  ~InitAwareTileService() override;

 private:
  // TileService implementation.
  void GetQueryTiles(GetTilesCallback callback) override;
  void GetTile(const std::string& tile_id, TileCallback callback) override;
  void StartFetchForTiles(bool is_from_reduced_mode,
                          BackgroundTaskFinishedCallback callback) override;
  void CancelTask() override;

  void OnTileServiceInitialized(bool success);
  void MaybeCacheApiCall(base::OnceClosure api_call);

  // Returns whether |tile_service_| is successfully initialized.
  bool IsReady() const;

  // Returns whether |tile_service_| is failed to initialize.
  bool IsFailed() const;

  std::unique_ptr<InitializableTileService> tile_service_;
  std::deque<base::OnceClosure> cached_api_calls_;

  // The initialization result of |tile_service_|.
  base::Optional<bool> init_success_;

  base::WeakPtrFactory<InitAwareTileService> weak_ptr_factory_{this};
};

}  // namespace query_tiles

#endif  // COMPONENTS_QUERY_TILES_INTERNAL_INIT_AWARE_TILE_SERVICE_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/background3x">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1150px"
        android:background="@mipmap/whitebox_halfcirle3x"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_marginTop="100px"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:src="@mipmap/logo3x"/>

        <LinearLayout
            android:layout_width="300dp"
            android:orientation="vertical"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center"
            android:layout_marginTop="150px">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/username"
                android:layout_marginTop="25px"
                android:hint="用户名"
                android:background="@mipmap/orangebox3x"
                android:gravity="center"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25px"
                android:id="@+id/password"
                android:inputType="textPassword"
                android:background="@mipmap/orangebox3x"
                android:hint="密码"
                android:gravity="center"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"
                android:layout_marginTop="100px"
                android:textSize="20dp"
                android:id="@+id/login"
                android:text="登录"/>

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="70px">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/forgetpassword"
                android:text="忘记密码?"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="70px"
                android:background="@null"
                android:autoLink="all"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/regist"
                android:layout_alignParentRight="true"
                android:background="@null"
                android:layout_marginRight="70px"
                android:text="注册"/>
        </RelativeLayout>

        <ImageView
            android:layout_width="40px"
            android:layout_height="40px"
            android:src="@mipmap/cross3x"
            android:layout_marginTop="20px"
            android:layout_gravity="center"/>

    </LinearLayout>

</LinearLayout>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Organization Schema
 */
var OrganizationSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Organization name',
		trim: true
	},
  owner:{
    type:Schema.ObjectId,
    ref:'Employee'
  },
  members:[
    {
      type:Schema.ObjectId,
      ref:'Employee'
    }
  ],
  projects:[
    {
      type:Schema.ObjectId,
      ref:'Project'
    }
  ],
  totalHeadCount:{
    type:Number,
    default:0
  },
  billableHeadCount:{
    type:Number,
    default:0
  },
  benchHeadCount:{
    type:Number,
    default:0
  },
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Organization', OrganizationSchema);


text:
pub type SERVICETYPE = ::ULONG;
STRUCT!{struct FLOWSPEC {
    TokenRate: ::ULONG,
    TokenBucketSize: ::ULONG,
    PeakBandwidth: ::ULONG,
    Latency: ::ULONG,
    DelayVariation: ::ULONG,
    ServiceType: SERVICETYPE,
    MaxSduSize: ::ULONG,
    MinimumPolicedSize: ::ULONG,
}}
pub type PFLOWSPEC = *mut FLOWSPEC;
pub type LPFLOWSPEC = *mut FLOWSPEC;


text:
#ifdef USE_TI_UILISTVIEW

#import "TiUIView.h"
#import "TiUIListViewProxy.h"

@interface TiUIListView : TiUIView <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, UIGestureRecognizerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, TiScrolling, TiProxyObserver >

#pragma mark - Private APIs

@property (nonatomic, readonly) UITableView *tableView;
@property (nonatomic, readonly) BOOL isSearchActive;

- (void)updateSearchResults:(id)unused;
- (void)setDictTemplates_:(id)args;
- (void)setContentInsets_:(id)value withObject:(id)props;
- (void)deselectAll:(BOOL)animated;
- (void)updateIndicesForVisibleRows;

+ (UITableViewRowAnimation)animationStyleForProperties:(NSDictionary*)properties;

@end

#endif


text:
package org.cytoscape.rest.service;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.times;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import org.cytoscape.ci.model.CIError;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.rest.internal.commands.resources.CommandResource;
import org.cytoscape.rest.internal.resource.AppsResource;
import org.cytoscape.rest.internal.resource.CyRESTCommandSwagger;
import org.cytoscape.view.model.CyNetworkView;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.models.parameters.QueryParameter;

public class CyRESTCommandSwaggerTest extends SwaggerResourceTest
{
	private ObjectMapper mapper = new ObjectMapper();

	@Test
	public void resourceURITest() {
		CyRESTCommandSwagger resource = new CyRESTCommandSwagger();
		assertEquals("commands:swagger", resource.getResourceURI());
	}

	@Override
	protected Application configure() {
		return new ResourceConfig(CyRESTCommandSwagger.class);
	}

	/**
	 * Test to ensure that the base networks remain unaltered after fetching the command swagger.
	 */
	@Test
	public void maintainsBaseTestNetworks() {
		Set<CyNetwork> networks = networkManager.getNetworkSet();
		assertEquals(2, networks.size());
		when(cyApplicationManager.getCurrentNetwork()).thenReturn(network);
		when(cyApplicationManager.getCurrentNetworkView()).thenReturn(view);
		verify(viewManager, times(0)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(0)).destroyNetworkView(any(CyNetworkView.class));
		target("/v1/commands/swagger.json").request().get();
		verify(viewManager, times(0)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(0)).destroyNetworkView(any(CyNetworkView.class));
		networks = networkManager.getNetworkSet();
		assertEquals(2, networks.size());
	}

	/**
	 * Test to ensure that when no networks or views are present, the command swagger can be fetched.
	 */
	@Test
	public void maintainsZeroNetworks() {

		Set<CyNetwork> networks = networkManager.getNetworkSet();
		for (CyNetwork network : networks) { networkManager.destroyNetwork(network); }
		networks = networkManager.getNetworkSet();
		assertEquals(0, networks.size());
		verify(viewManager, times(0)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(0)).destroyNetworkView(any(CyNetworkView.class));
		when(cyApplicationManager.getCurrentNetwork()).thenReturn(null);
		when(cyApplicationManager.getCurrentNetworkView()).thenReturn(null);
		target("/v1/commands/swagger.json").request().get();

		verify(viewManager, times(1)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(1)).destroyNetworkView(any(CyNetworkView.class));

		networks = networkManager.getNetworkSet();
		assertEquals(0, networks.size());

	}

	/**
	 * Test to ensure that when a network or networks with no current or view are present, the command swagger can be fetched.
	 */
	@Test
	public void maintainsOneNetworkZeroViews() {

		Set<CyNetwork> networks = networkManager.getNetworkSet();

		assertEquals(2, networks.size());
		verify(viewManager, times(0)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(0)).destroyNetworkView(any(CyNetworkView.class));
		when(cyApplicationManager.getCurrentNetwork()).thenReturn(network);
		when(cyApplicationManager.getCurrentNetworkView()).thenReturn(null);
		target("/v1/commands/swagger.json").request().get();

		verify(viewManager, times(1)).addNetworkView(any(CyNetworkView.class), anyBoolean());
		verify(viewManager, times(1)).destroyNetworkView(any(CyNetworkView.class));

		networks = networkManager.getNetworkSet();
		assertEquals(2, networks.size());

		networks = networkManager.getNetworkSet();
	}

	@Test
	public void hasValidSwaggerConfig() throws Exception {

		Response response = target("/v1/commands/swagger.json").request().get();
		String result = response.readEntity(String.class);
		assertNotNull(result);

		//System.out.println("CyREST Command Swagger exists at /v1/commands/swagger.json");
		System.out.println(result);

		final JsonNode root = mapper.readTree(result);

		swaggerConfigTest(root);

		JsonNode pathsNode = root.get("paths");
		assertTrue(pathsNode.has("/v1/commands/" + DUMMY_NAMESPACE + "/" + DUMMY_COMMAND));
		assertTrue(pathsNode.has("/v1/commands/" + DUMMY_NAMESPACE + "/" + DUMMY_MULTI_TASK_COMMAND));
		assertTrue(pathsNode.has("/v1/commands/" + DUMMY_NAMESPACE + "/" + DUMMY_APPEND_TASK_COMMAND));

	}

	@Test
	public void isDefinitionNullOnInit() {
		CyRESTCommandSwagger cyRESTCommandSwagger = new CyRESTCommandSwagger();
		assertTrue(cyRESTCommandSwagger.isSwaggerDefinitionNull());
	}

	@Test
	public void isIntJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, int.class);
		verify(parameter).setType("integer");
		verify(parameter).setFormat("int32");
	}

	@Test
	public void isLongJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, long.class);
		verify(parameter).setType("integer");
		verify(parameter).setFormat("int64");
	}

	@Test
	public void isFloatJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, float.class);
		verify(parameter).setType("number");
		verify(parameter).setFormat("int32");
	}

	@Test
	public void isDoubleJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, double.class);
		verify(parameter).setType("number");
		verify(parameter).setFormat("int64");
	}

	@Test
	public void isStringJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, String.class);
		verify(parameter).setType("string");
	}

	@Test
	public void isByteJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, byte.class);
		verify(parameter).setType("string");
		verify(parameter).setFormat("byte");
	}

	@Test
	public void isBooleanJSONTypeCorrect() {
		QueryParameter parameter = mock(QueryParameter.class);
		CyRESTCommandSwagger.setParameterTypeAndFormatFromClass(parameter, boolean.class);
		verify(parameter).setType("boolean");
	}

	@Test
	public void detectsNullExampleJSON() throws JsonParseException, JsonMappingException, IOException {
		String exampleJSON = "{\"value_f\": null}";
		JsonNode jsonNode = mapper.readValue(CommandResource.getJSONResponse(Arrays.asList(new String[]{exampleJSON}), new ArrayList<CIError>(), null), JsonNode.class);
		assertTrue(CyRESTCommandSwagger.containsNull(jsonNode));
	}

	@Test
	public void detectsNestedNullExampleJSON() throws JsonParseException, JsonMappingException, IOException {
		String exampleJSON ="{ \"data\": { \"subnode\" : null } }";
		JsonNode jsonNode = mapper.readValue(CommandResource.getJSONResponse(Arrays.asList(new String[]{exampleJSON}), new ArrayList<CIError>(), null), JsonNode.class);
		assertTrue(CyRESTCommandSwagger.containsNull(jsonNode));
	}

	@Test
	public void passesValidExampleJSON() throws JsonParseException, JsonMappingException, IOException {
		String exampleJSON = "{ \"data\": { \"subnode\" : \"hodor\" } }";
		JsonNode jsonNode = mapper.readValue(CommandResource.getJSONResponse(Arrays.asList(new String[]{exampleJSON}), new ArrayList<CIError>(), null), JsonNode.class);
		assertFalse(CyRESTCommandSwagger.containsNull(jsonNode));
	}
}


text:
namespace flu
{
    DisplayMesh::DisplayMesh() : Mesh()
    {

    }

    bool DisplayMesh::operator==(const DisplayMesh & other) const
    {
        return _positionTriangles == other._positionTriangles && _colorTriangles == other._colorTriangles && _uvTriangles == other._uvTriangles;
    }

    bool DisplayMesh::operator!=(const DisplayMesh & other) const
    {
        return !(*this == other);
    }

    void DisplayMesh::add(const Triangle<V3<double> > & position,const Triangle<Color> & color,const Triangle<V2<double> > & uv)
    {
        _positionTriangles.push_back(position);
        _colorTriangles.push_back(color);
        _uvTriangles.push_back(uv);
    }

    Triangle<Color> DisplayMesh::getColor(const int index) const
    {
        try
        {
            return _colorTriangles.at(index);
        }
        catch (OutOfBoundsException)
        {
            throw OutOfBoundsException("Color triangle out of bounds");
        }
    }

    Triangle<V2<double> > DisplayMesh::getUV(const int index) const
    {
        try
        {
            return _uvTriangles.at(index);
        }
        catch (OutOfBoundsException)
        {
            throw OutOfBoundsException("UV triangle out of bounds");
        }
    }
}


text:
package com.xlythe.textmanager.text.service;

import android.app.IntentService;
import android.content.Intent;
import android.telephony.TelephonyManager;

import com.xlythe.textmanager.text.Text;
import com.xlythe.textmanager.text.TextManager;
import com.xlythe.textmanager.text.util.MessageUtils;

public class HeadlessSmsSendService extends IntentService {

    public HeadlessSmsSendService() {
        super(HeadlessSmsSendService.class.getSimpleName());
        setIntentRedelivery(true);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        if (!TelephonyManager.ACTION_RESPOND_VIA_MESSAGE.equals(action)) {
            return;
        }

        Text text = MessageUtils.parse(this, intent);
        if (text != null) {
            TextManager.getInstance(this).send(text);
        }
    }
}


text:
<?php
include 'php/mysql_conn.php';
include 'fun.inc.php';
include 'fun.dataTable.php';

$row = @mysql_query ( "SELECT * FROM `info` WHERE `ID` = '" . $_SESSION ['userID'] . "' " );
if (! $result = @mysql_fetch_array ( $row )) {
	echo "";
	exit ();
}else{
	$Permit = $result['Permission'];
	if( $Permit != 5){
		echo "";
		exit ();
	}
}

$rslRiv = @mysql_query ( "SELECT No,Name FROM river WHERE 1" );
$num = mysql_num_rows ( $rslRiv );
$rslMatch = @mysql_query ( "SELECT * FROM `competition` WHERE 1" );
$numMatchAll = mysql_num_rows ( $rslMatch );
$rslMatch = @mysql_query ( "SELECT * FROM `competition` WHERE matchDate < now()" );
$numMatch = mysql_num_rows ( $rslMatch );

$rslAll = mysql_query ( "SELECT competition.matchID, river.Name, competition.difficulty, competition.price,
	competition.maxPeople, competition.status, competition.matchDate FROM competition, river WHERE river.No = competition.riverID");
$numAll = mysql_num_rows ( $rslAll );
?>
<!DOCTYPE HTML>

	<title>亞洲泛舟網</title>
	<meta charset="UTF-8">

	<?php topNavBarLogin(201);?>

			 賽事管理

		  總賽事
		  <input type="text" class="form-control" placeholder="Total Race"
		  aria-describedby="basic-addon1" value="<?php echo $numMatchAll;?>">
		  已完成賽事
		  <input type="text" class="form-control" placeholder="Complete Race"
		  aria-describedby="basic-addon1" value="<?php echo $numMatch;?>">

		<form action="mag.race.php" method="post">

					河流
					難度
					費用
					最大人數
					活動日期

					<select name="riverID" class="form-control">
						<option value="">River</option>
						<?php for($i = 0; $i < $num; $i ++) {
							$rowRiv = mysql_fetch_row ( $rslRiv );
							echo "<option value=". $rowRiv[0] .">".$rowRiv[0].".".$rowRiv[1]."</option>";
						}?>
					</select>
					<input type="number" class="form-control" placeholder="Difficulty" name="diff" min="1" required>
					<input type="number" class="form-control" placeholder="Price" name="price" min="0" required>
					<input type="number" class="form-control" placeholder="Max people" name="maxP" min="1" required>
					<input type="number" class="form-control" placeholder="After N day" name="afterDate" min="0" required>
					<input type="submit" class="btn btn-success" name="sure" value="新增">

		</form>

	<?php
	if(isset($_POST['sure'])){
		$riverID = preg_replace("/[\'\"]+/" , '' ,$_POST['riverID']);
		$diff = preg_replace("/[\'\"]+/" , '' ,$_POST['diff']);
		$price = preg_replace("/[\'\"]+/" , '' ,$_POST['price']);
		$maxP = preg_replace("/[\'\"]+/" , '' ,$_POST['maxP']);
		$aDay =  preg_replace("/[\'\"]+/" , '' ,$_POST['afterDate']);
		// INSERT INTO `competition` ( `riverID`, `difficulty`, `price`, `maxPeople`, `matchDate` )
		// VALUES ( '8', '6', '5', '20', ADDDATE( CURRENT_DATE(), INTERVAL 4 DAY ) )
		$sqlAddRiver = "INSERT INTO `competition` (`riverID`, `difficulty`, `price`, `maxPeople`, `matchDate`)
		VALUES ('$riverID','$diff','$price','$maxP',ADDDATE( CURRENT_DATE(),INTERVAL '$aDay' DAY ))";
		if(@mysql_query($sqlAddRiver)){
			echo "";
		}else{
			echo "";
		}
	}
	?>

				MatchID
				River
				Diff.
				Price
				MaxP
				Cur.P
				Date
				Status

			<?php
			for($i = 0; $i < $numAll ; $i ++) {
				$rows = @mysql_fetch_array ( $rslAll );
				$rsCount = @mysql_query ( "SELECT COUNT(*) FROM `game` WHERE game.matchID = '" . $rows ['matchID'] . "' " );
				$count = @mysql_fetch_row ( $rsCount ); // <<<報名人數
				echo '

					' . $rows ['matchID'] . '
					' . $rows ['Name'] . '
					LV.' . $rows ['difficulty'] . '
					' . $rows ['price'] . '萬
					' . $rows ['maxPeople'] . '
					' . $count [0] . '
					' . $rows ['matchDate'] . '
					' . $rows ['status'] . '

';
				//<button type="button" class="btn btn-success">修改</button>
			}
			?>


text:
//=======================================
//	ProcMan.c
//=======================================
//	Process Manager
//
//  Interacts with the MLFQ to handle
//	starting/stoping/pausing of processes.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

#include "List.h"
#include "MLFQ.h"
#include "ProcMan.h"
#include "Proc.h"

ProcInfo* lastProc;

void _SuspendProc(ProcInfo* proc)
// Suspends a process by sending a SIGTSTP
{
	proc->status = PROCSUSPENDED;

	if(proc->pid)
	{
		kill(proc->pid,SIGTSTP);
	}
}

void _WakeProc(ProcInfo* proc)
// Resumes a process by sending a SIGCONT
{
	proc->status = PROCRUNNING;

	if(proc->pid)
		kill(proc->pid,SIGCONT);
}

void _StartProc(ProcInfo* proc)
// Stats a new process using fork.
// The new process then executes the ProcFunc() function
{
	int retVal = 0;
	retVal = fork();

	if(retVal < 0)
		printf("\nError starting process %d", proc->num);
	if(retVal == 0)
	// If child, execute the proc function
	{
		ProcFunc(proc);
	}
	else
	// If parent
	{
		// Store the PID and mark the process as running
		proc->pid = retVal;
		proc->status = PROCRUNNING;
	}
}

int _isProcAlive(ProcInfo* proc)
// Checks if the process is still alive.
// This can be used to see if the process was terminated due to some external reasons
{
	if(proc->pid)
	{
		if(kill(proc->pid,0) == 0)
			return 1;
	}
	else
		return 0;
}

void _KillProc(ProcInfo * proc)
// Terminates a process by sending a SIGINT
{
	if(proc->pid)
	{
		kill(proc->pid,SIGINT);

		// Mark the process as not running.
		proc->pid = 0;
		proc->status = PROCNOTRUNNING;
	}
}

PROCERR ProcManRun(int timeStep)
// This function retrieves the next process to execute from the MLFQ and decides what to do with the previous process
// After this decision, it suspends or terminates the previous process and then resumes or starts the new process
{
	ProcInfo* nextProc = NULL;
	int procKilled = 0;

	// If the last executing process is done executing or is dead due to external reasons
	// kill it and remove it from the scheduling queue
	if(lastProc && ( !lastProc->cpuTime || !_isProcAlive(lastProc)))
	{
		_KillProc(lastProc);
		lastProc->cpuTime = 0;
		procKilled = 1;
	}

	// Get the next process to execute from the MLFQ
	nextProc = MLFQGetNextProc(lastProc,timeStep);

	if(procKilled)
	// If the last process was killed, mark it as null
	{
		procKilled = 0;
		lastProc = NULL;
	}

	// Delete all processes returned from the MLFQ that are dead due to external reasons
	while( nextProc && nextProc->pid && !_isProcAlive(nextProc))
	{
		_KillProc(nextProc);
		nextProc->cpuTime = 0;
		nextProc = MLFQGetNextProc(nextProc,timeStep);
	}

	// At this point, we have found a valid process to execute (if nextproc is not NULL)
	// or we have determined that we must wait this quantum (if nextproc is NULL)
	if(nextProc)
	{
		if(lastProc)
		// If the next process to execute is the same as the last process
		// do nothing. Let the same process continue executing. Only decrement the cpu time.
		{
			if(nextProc == lastProc)
			{
				nextProc->cpuTime--;
				return PROCMANSUCCESS;
			}
			else
			{
				// If the last process is different from the next process and if the last process
				// was already started, suspend it.
				if(lastProc->pid)
					_SuspendProc(lastProc);
			}
		}

		// If the last process was already started some time ago, resume it. Otherwise, start it.
		if(nextProc->pid)
			_WakeProc(nextProc);
		else
			_StartProc(nextProc);

		// Update the last process and decrement the cpu time.
		lastProc = nextProc;
		nextProc->cpuTime --;
		return PROCMANSUCCESS;
	}
	else
	{
		if(MLFQIsJobQEmpty() == MLFQJOBQEMPTY)
			return PROCMANALLDONE;
		else
			return PROCMANWAITING;
	}
}

Node* ProcManLinkNode(Node* node)
// This is required for generic use of the linked list to store the process structures
{
	ProcInfo* procInfo;
	if(!node || !(node->data))
		return NULL;

	procInfo = (ProcInfo*) node->data;

	procInfo->node = node;

	return node;
}


text:
import { Reducer as ReduxReducer } from 'redux';

import { Action, TypedAction } from './action';

export interface Reducer<State> extends ReduxReducer<State> {
    (state?: State, action?: Action<any>): State;
}

export type SubReducer<State, ActionMap, Type extends keyof ActionMap> = (
    state: State,
    payload: ActionMap[Type],
    action: TypedAction<Type, ActionMap[Type]>
) => State;