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

var connect = "postgres://admhc:shc211521159796220@10.121.6.4:5432/hceventos";

module.exports = {
  BuscarUsuarios: function(req, res) {
  pg.connect(connect, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query('SELECT * FROM usuario ORDER BY nombre', function(err, result) {
       if(err) {
        return console.error('error running query');
      }
      return res.send(result.rows);
    });
  });
},

  RegistrarUsuario: function(req, res) {
  pg.connect(connect, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query("INSERT INTO usuario (nombre, email, password) VALUES ($1, $2, $3)",
      [req.body.nombre, req.body.email, req.body.password]);

      return res.sendStatus(200);
      //return res.Status(200).send({message:"Registro Exitoso"});
  });
},

  ModificarUsuario: function(req, res) {
  pg.connect(connect, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query("UPDATE usuario SET nombre= $1, email = $2, password = $3 WHERE id = $4",
      [req.body.nombre, req.body.email, req.body.password, req.params.id]);

      return res.sendStatus(200);
  });
},

EliminarUsuario: function(req, res) {
  pg.connect(connect, function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query("DELETE FROM usuario WHERE id = $1",
      [req.params.id]);

      return res.sendStatus(200);
  });
}
}


text:
import weakref
from abc import ABCMeta, abstractmethod

import torch

from pyro.ops.einsum import contract
from pyro.ops.einsum.adjoint import SAMPLE_SYMBOL, Backward
from pyro.util import ignore_jit_warnings

class Ring(object, metaclass=ABCMeta):
    """
    Abstract tensor ring class.

    Each tensor ring class has a notion of ``dims`` that can be sum-contracted
    out, and a notion of ``ordinal`` that represents a set of plate dimensions
    that can be broadcasted-up or product-contracted out.
    Implementations should cache intermediate results to be compatible with
    :func:`~opt_einsum.shared_intermediates`.

    Dims are characters (string or unicode).
    Ordinals are frozensets of characters.

    :param dict cache: an optional :func:`~opt_einsum.shared_intermediates`
        cache.
    """

    def __init__(self, cache=None):
        self._cache = {} if cache is None else cache

    def _hash_by_id(self, tensor):
        """
        Returns the id of a tensor and saves the tensor so that this id can be
        used as a key in the cache without risk of the id being recycled.
        """
        result = id(tensor)
        assert self._cache.setdefault(("tensor", result), tensor) is tensor
        return result

    @abstractmethod
    def sumproduct(self, terms, dims):
        """
        Multiply all ``terms`` together, then sum-contract out all ``dims``
        from the result.

        :param list terms: a list of tensors
        :param dims: an iterable of sum dims to contract
        """
        raise NotImplementedError

    @abstractmethod
    def product(self, term, ordinal):
        """
        Product-contract the given ``term`` along any plate dimensions
        present in given ``ordinal``.

        :param torch.Tensor term: the term to contract
        :param frozenset ordinal: an ordinal specifying plates to contract
        """
        raise NotImplementedError

    def broadcast(self, term, ordinal):
        """
        Broadcast the given ``term`` by expanding along any plate dimensions
        present in ``ordinal`` but not ``term``.

        :param torch.Tensor term: the term to expand
        :param frozenset ordinal: an ordinal specifying plates
        """
        dims = term._pyro_dims
        missing_dims = "".join(sorted(set(ordinal) - set(dims)))
        if missing_dims:
            key = "broadcast", self._hash_by_id(term), missing_dims
            if key in self._cache:
                term = self._cache[key]
            else:
                missing_shape = tuple(self._dim_to_size[dim] for dim in missing_dims)
                term = term.expand(missing_shape + term.shape)
                dims = missing_dims + dims
                self._cache[key] = term
                term._pyro_dims = dims
        return term

    @abstractmethod
    def inv(self, term):
        """
        Computes the reciprocal of a term, for use in inclusion-exclusion.

        :param torch.Tensor term: the term to invert
        """
        raise NotImplementedError

    def global_local(self, term, dims, ordinal):
        r"""
        Computes global and local terms for tensor message passing
        using inclusion-exclusion::

            term / sum(term, dims) * product(sum(term, dims), ordinal)
            \____________________/   \_______________________________/
                  local part                    global part

        :param torch.Tensor term: the term to contract
        :param dims: an iterable of sum dims to contract
        :param frozenset ordinal: an ordinal specifying plates to contract
        :return: a tuple ``(global_part, local_part)`` as defined above
        :rtype: tuple
        """
        assert dims, "dims was empty, use .product() instead"
        key = "global_local", self._hash_by_id(term), frozenset(dims), ordinal
        if key in self._cache:
            return self._cache[key]

        term_sum = self.sumproduct([term], dims)
        global_part = self.product(term_sum, ordinal)
        with ignore_jit_warnings():
            local_part = self.sumproduct([term, self.inv(term_sum)], set())
        assert sorted(local_part._pyro_dims) == sorted(term._pyro_dims)
        result = global_part, local_part
        self._cache[key] = result
        return result

class LinearRing(Ring):
    """
    Ring of sum-product operations in linear space.

    Tensor dimensions are packed; to read the name of a tensor, read the
    ``._pyro_dims`` attribute, which is a string of dimension names aligned
    with the tensor's shape.
    """

    _backend = "torch"

    def __init__(self, cache=None, dim_to_size=None):
        super().__init__(cache=cache)
        self._dim_to_size = {} if dim_to_size is None else dim_to_size

    def sumproduct(self, terms, dims):
        inputs = [term._pyro_dims for term in terms]
        output = "".join(sorted(set("".join(inputs)) - set(dims)))
        equation = ",".join(inputs) + "->" + output
        term = contract(equation, *terms, backend=self._backend)
        term._pyro_dims = output
        return term

    def product(self, term, ordinal):
        dims = term._pyro_dims
        for dim in sorted(ordinal, reverse=True):
            pos = dims.find(dim)
            if pos != -1:
                key = "product", self._hash_by_id(term), dim
                if key in self._cache:
                    term = self._cache[key]
                else:
                    term = term.prod(pos)
                    dims = dims.replace(dim, "")
                    self._cache[key] = term
                    term._pyro_dims = dims
        return term

    def inv(self, term):
        key = "inv", self._hash_by_id(term)
        if key in self._cache:
            return self._cache[key]

        result = term.reciprocal()
        result = result.clamp(
            max=torch.finfo(result.dtype).max
        )  # avoid nan due to inf / inf
        result._pyro_dims = term._pyro_dims
        self._cache[key] = result
        return result

class LogRing(Ring):
    """
    Ring of sum-product operations in log space.

    Tensor values are in log units, so ``sum`` is implemented as ``logsumexp``,
    and ``product`` is implemented as ``sum``.
    Tensor dimensions are packed; to read the name of a tensor, read the
    ``._pyro_dims`` attribute, which is a string of dimension names aligned
    with the tensor's shape.
    """

    _backend = "pyro.ops.einsum.torch_log"

    def __init__(self, cache=None, dim_to_size=None):
        super().__init__(cache=cache)
        self._dim_to_size = {} if dim_to_size is None else dim_to_size

    def sumproduct(self, terms, dims):
        inputs = [term._pyro_dims for term in terms]
        output = "".join(sorted(set("".join(inputs)) - set(dims)))
        equation = ",".join(inputs) + "->" + output
        term = contract(equation, *terms, backend=self._backend)
        term._pyro_dims = output
        return term

    def product(self, term, ordinal):
        dims = term._pyro_dims
        for dim in sorted(ordinal, reverse=True):
            pos = dims.find(dim)
            if pos != -1:
                key = "product", self._hash_by_id(term), dim
                if key in self._cache:
                    term = self._cache[key]
                else:
                    term = term.sum(pos)
                    dims = dims.replace(dim, "")
                    self._cache[key] = term
                    term._pyro_dims = dims
        return term

    def inv(self, term):
        key = "inv", self._hash_by_id(term)
        if key in self._cache:
            return self._cache[key]

        result = -term
        result = result.clamp(
            max=torch.finfo(result.dtype).max
        )  # avoid nan due to inf - inf
        result._pyro_dims = term._pyro_dims
        self._cache[key] = result
        return result

class _SampleProductBackward(Backward):
    """
    Backward-sample implementation of product.

    This is agnostic to sampler implementation, and hence can be used both by
    :class:`MapRing` (temperature 0 sampling) and :class:`SampleRing`
    (temperature 1 sampling).
    """

    def __init__(self, ring, term, ordinal):
        self.ring = ring
        self.term = term
        self.ordinal = ordinal

    def process(self, message):
        if message is not None:
            sample_dims = message._pyro_sample_dims
            message = self.ring.broadcast(message, self.ordinal)
            if message._pyro_dims.index(SAMPLE_SYMBOL) != 0:
                dims = SAMPLE_SYMBOL + message._pyro_dims.replace(SAMPLE_SYMBOL, "")
                message = message.permute(tuple(map(message._pyro_dims.find, dims)))
                message._pyro_dims = dims
                assert message.dim() == len(message._pyro_dims)
            message._pyro_sample_dims = sample_dims
            assert message.size(0) == len(message._pyro_sample_dims)
        yield self.term._pyro_backward, message

class MapRing(LogRing):
    """
    Ring of forward-maxsum backward-argmax operations.
    """

    _backend = "pyro.ops.einsum.torch_map"

    def product(self, term, ordinal):
        result = super().product(term, ordinal)
        if hasattr(term, "_pyro_backward"):
            result._pyro_backward = _SampleProductBackward(self, term, ordinal)
        return result

class SampleRing(LogRing):
    """
    Ring of forward-sumproduct backward-sample operations in log space.
    """

    _backend = "pyro.ops.einsum.torch_sample"

    def product(self, term, ordinal):
        result = super().product(term, ordinal)
        if hasattr(term, "_pyro_backward"):
            result._pyro_backward = _SampleProductBackward(self, term, ordinal)
        return result

class _MarginalProductBackward(Backward):
    """
    Backward-marginal implementation of product, using inclusion-exclusion.
    """

    def __init__(self, ring, term, ordinal, result):
        self.ring = ring
        self.term = term
        self.ordinal = ordinal
        self.result = weakref.ref(result)

    def process(self, message):
        ring = self.ring
        term = self.term
        result = self.result()
        factors = [result]
        if message is not None:
            message._pyro_dims = result._pyro_dims
            factors.append(message)
        if term._pyro_backward.is_leaf:
            product = ring.sumproduct(factors, set())
            message = ring.broadcast(product, self.ordinal)
        else:
            factors.append(ring.inv(term))
            message = ring.sumproduct(factors, set())
        yield term._pyro_backward, message

class MarginalRing(LogRing):
    """
    Ring of forward-sumproduct backward-marginal operations in log space.
    """

    _backend = "pyro.ops.einsum.torch_marginal"

    def product(self, term, ordinal):
        result = super().product(term, ordinal)
        if hasattr(term, "_pyro_backward"):
            result._pyro_backward = _MarginalProductBackward(
                self, term, ordinal, result
            )
        return result

BACKEND_TO_RING = {
    "torch": LinearRing,
    "pyro.ops.einsum.torch_log": LogRing,
    "pyro.ops.einsum.torch_map": MapRing,
    "pyro.ops.einsum.torch_sample": SampleRing,
    "pyro.ops.einsum.torch_marginal": MarginalRing,
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.mllib.tree

import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.model.TreeEnsembleModel
import org.apache.spark.util.StatCounter

import scala.collection.mutable

object EnsembleTestHelper {

  /**
   * Aggregates all values in data, and tests whether the empirical mean and stddev are within
   * epsilon of the expected values.
   * 聚合数据中的所有值,和测试均值和标准差期望值
   * @param data  Every element of the data should be an i.i.d. sample from some distribution.
   *  data 数据的每一个元素应该是一个独立同分布的样本分布
   */
  def testRandomArrays(
      data: Array[Array[Double]],
      numCols: Int,
      expectedMean: Double,
      expectedStddev: Double,
      //epsilon代收敛的阀值
      epsilon: Double) {
    val values = new mutable.ArrayBuffer[Double]()
    data.foreach { row =>
      assert(row.size == numCols)
      values ++= row
    }
    val stats = new StatCounter(values)
     //math.abs返回数的绝对值,mean,平均数
    assert(math.abs(stats.mean - expectedMean) < epsilon)
    //stdev 标准差
    assert(math.abs(stats.stdev - expectedStddev) < epsilon)
  }

  def validateClassifier(
      model: TreeEnsembleModel,
      input: Seq[LabeledPoint],
      requiredAccuracy: Double) {
    val predictions = input.map(x => model.predict(x.features))
    val numOffPredictions = predictions.zip(input).count { case (prediction, expected) =>
      prediction != expected.label
    }
    val accuracy = (input.length - numOffPredictions).toDouble / input.length
    assert(accuracy >= requiredAccuracy,
      s"validateClassifier calculated accuracy $accuracy but required $requiredAccuracy.")
  }

  /**
   * Validates a tree ensemble model for regression.
   * 验证回归的树集合模型
   */
  def validateRegressor(
      model: TreeEnsembleModel,
      input: Seq[LabeledPoint],
      required: Double,
      metricName: String = "mse") {
    val predictions = input.map(x => model.predict(x.features))
    val errors = predictions.zip(input.map(_.label)).map { case (prediction, label) =>
      label - prediction
    }
    val metric = metricName match {
      case "mse" =>
        errors.map(err => err * err).sum / errors.size
      case "mae" =>
        //MAE平均绝对误差是所有单个观测值与算术平均值的偏差的绝对值的平均
       //math.abs返回数的绝对值
        errors.map(math.abs).sum / errors.size
    }

    assert(metric <= required,
      s"validateRegressor calculated $metricName $metric but required $required.")
  }

  def generateOrderedLabeledPoints(numFeatures: Int, numInstances: Int): Array[LabeledPoint] = {
    val arr = new Array[LabeledPoint](numInstances)
    for (i <- 0 until numInstances) {
      val label = if (i < numInstances / 10) {
        0.0
      } else if (i < numInstances / 2) {
        1.0
      } else if (i < numInstances * 0.9) {
        0.0
      } else {
        1.0
      }
      val features = Array.fill[Double](numFeatures)(i.toDouble)
      arr(i) = new LabeledPoint(label, Vectors.dense(features))
    }
    arr
  }

}


text:
[![Build Status](https://travis-ci.org/chrisspang/bitmappy.svg?branch=master)](https://travis-ci.org/chrisspang/bitmappy)

## Installation (rvm)

Install ruby 2.0, create temporary gemset, etc:

    $ rvm install 2.0
    $ rvm use 2.0
    $ rvm gemset create testytest
    $ rvm gemset use testytest

    $ gem install bundler
    $ bundle

Run tests if you so desire:

    $ rake test

As desired, some combination of:

    $ rake build
    $ rake install

Then play with bitmappy:

```
$ bitmappy
> I 5 6
> L 2 3 A
> S
OOOOO
OOOOO
OAOOO
OOOOO
OOOOO
OOOOO
> F 3 3 J
> V 2 3 4 W
> H 3 4 2 Z
> S
JJJJJ
JJZZJ
JWJJJ
JWJJJ
JJJJJ
JJJJJ
> X
```

## Extra Feature

This version of the basic interactive bitmap editor has an exciting new feature.. UNDO!

Use the command 'U' command to roll back your last changes, all the way back to your first
bitmap creation ('I' command).  Use it once, use it forever (or until you run out of memory).

Example:

```
> I 10 10
> F 1 1 I
> H 1 10 1 A
> H 1 10 10 A
> V 1 1 10 A
> V 10 10 1 A
> H 3 8  3 B
> H 3 8 8 B
> V 3 3 8 B
> V 8 8 3 B
> F 5 5 X
> S
AAAAAAAAAA
AIIIIIIIIA
AIBBBBBBIA
AIBXXXXBIA
AIBXXXXBIA
AIBXXXXBIA
AIBXXXXBIA
AIBBBBBBIA
AIIIIIIIIA
AAAAAAAAAA
> C
```

 OOPS!

```
> S
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
OOOOOOOOOO
> U
> S
AAAAAAAAAA
AIIIIIIIIA
AIBBBBBBIA
AIBXXXXBIA
AIBXXXXBIA
AIBXXXXBIA
AIBXXXXBIA
AIBBBBBBIA
AIIIIIIIIA
AAAAAAAAAA
```

 YAY!

 You can keep going if you like:

```
> U
> U
> U
> U
> U
> S
AAAAAAAAAA
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AIIIIIIIII
AAAAAAAAAA
```

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    help = "Load sample store data for satchmo."

    def handle_noargs(self, **options):
        from satchmo_store.contact.models import (
            AddressBook,
            Contact,
            ContactOrganization,
            ContactOrganizationRole,
            ContactRole,
            Organization,
            PhoneNumber,
        )
        from product.models import (
            Category,
            OptionGroup,
            Option,
            Price,
            Product,
        )
        from product.modules.configurable.models import ConfigurableProduct

        from satchmo_store.shop.models import Config
        from django.conf import settings
        from l10n.models import Country
        from django.contrib.sites.models import Site
        from django.contrib.auth.models import User
        #idempotency test

        print "Checking for existing sample data."
        try:
            p = Product.objects.get(slug="dj-rocks")
            print "It looks like you already have loaded the sample store data, quitting."
            import sys
            sys.exit(1)
        except Product.DoesNotExist:
            pass

        print "Loading sample store data."

        #Load basic configuration information

        print "Creating site..."
        try:
            site = Site.objects.get(id=settings.SITE_ID)
            print "Using existing site #%i" % settings.SITE_ID
        except Site.DoesNotExist:
            print "Creating Example Store Site"
            site = Site(domain="localhost", name="Sample Store")
        site.domain = settings.SITE_DOMAIN
        site.name = settings.SITE_NAME
        site.save()
        store_country = Country.objects.get(iso3_code='USA')
        config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country)
        config.save()
        config.shipping_countries.add(store_country)
        config.save()
        print "Creating Customers..."
        # Import some customers

        customer = ContactRole.objects.get(pk='Customer')
        c1 = Contact(first_name="Chris", last_name="Smith", email="chris@aol.com", role=customer, notes="Really cool stuff")
        c1.save()
        p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home",primary=True)
        p1.save()
        c2 = Contact(first_name="John", last_name="Smith", email="abc@comcast.com", role=customer, notes="Second user")
        c2.save()
        p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work",primary=True)
        p2.save()
        # Import some addresses for these customers
        us = Country.objects.get(iso2_code='US');
        a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN",
                     postal_code="38138", country=us, is_default_shipping=True, contact=c1)
        a1.save()
        a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN",
                     postal_code="55082", country=us, is_default_shipping=True, contact=c2)
        a2.save()
        print "Creating Suppliers..."
        #Import some suppliers

        supplier = ContactOrganizationRole.objects.get(pk='Supplier')
        company = ContactOrganization.objects.get(pk='Company')
        contactsupplier = ContactRole.objects.get(pk='Supplier')
        org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier)
        org1.save()
        c4 = Contact(first_name="Fred", last_name="Jones", email="fj@rr.com",
            role=contactsupplier, organization=org1)
        c4.save()
        p4 = PhoneNumber(contact=c4,phone="800-188-7611", type="Work", primary=True)
        p4.save()
        p5 = PhoneNumber(contact=c4,phone="755-555-1111",type="Fax")
        p5.save()
        a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept",
            street2="918 Funky Town St", city="Fishkill",
             state="NJ", country=us, postal_code="19010")
        a3.save()
        #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200",
        #              city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="ron@rhinestone.com",
        #              notes="My main supplier")
        #s1.save()

        #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane",
        #    city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="sally@shirts.com",
        #              notes="Shirt Supplier")
        #s2.save()

        print "Creating Categories..."
        #Create some categories
        cat1 = Category(site=site, name="Shirts",slug="shirts",description="Women's Shirts")
        cat1.save()
        cat2 = Category(site=site, name="Short Sleeve",slug="shortsleeve",description="Short sleeve shirts", parent=cat1)
        cat2.save()
        cat3 = Category(site=site, name="Books",slug="book",description="Books")
        cat3.save()
        cat4 = Category(site=site, name="Fiction",slug="fiction",description="Fiction Books", parent=cat3)
        cat4.save()
        cat5 = Category(site=site, name="Science Fiction",slug="scifi",description="Science Fiction",parent=cat4)
        cat5.save()
        cat6 = Category(site=site, name="Non Fiction",slug="nonfiction",description="Non Fiction",parent=cat3)
        cat6.save()
        cat7 = Category(site=site, name="Software", slug="software")
        cat7.save()

        print "Creating products..."
        #Create some items
        i1 = Product(site=site, name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt",
                 active=True, featured=True)
        i1.save()
        p1 = Price(price="20.00", product=i1)
        p1.save()
        i1.category.add(cat1)
        i1.save()
        i2 = Product(site=site, name="Python Rocks shirt", slug="PY-Rocks",
            description="Really cool python shirt - One Size Fits All",
            active=True, featured=True)
        i2.save()
        p2 = Price(price="19.50", product=i2)
        p2.save()
        i2.category.add(cat2)
        i2.save()
        i3 = Product(site=site, name="A really neat book", slug="neat-book",
            description="A neat book.  You should buy it.",
            active=True, featured=True)
        i3.save()
        p3 = Price(price="5.00", product=i3)
        p3.save()
        i3.category.add(cat4)
        i3.save()
        i4 = Product(site=site, name="Robots Attack!", slug="robot-attack",
            description="Robots try to take over the world.",
            active=True, featured=True)
        i4.save()
        p4 = Price(price="7.99", product=i4)
        p4.save()
        i4.category.add(cat5)
        i4.save()

    #    i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
    #    i5.save()
    #    i5.category.add(cat7)
    #    i5.save()

        #Create an attribute set
        optSet1 = OptionGroup(site=site, name="sizes", sort_order=1)
        optSet2 = OptionGroup(site=site, name="colors", sort_order=2)
        optSet1.save()
        optSet2.save()

        optSet3 = OptionGroup(site=site, name="Book type", sort_order=1)
        optSet3.save()

        optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5)
        optSet4.save()

        optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1)
        optItem1a.save()
        optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1)
        optItem1b.save()
        optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1)
        optItem1c.save()

        optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2)
        optItem2a.save()
        optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2)
        optItem2b.save()
        optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2)
        optItem2c.save()

        optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3)
        optItem3a.save()
        optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3)
        optItem3b.save()
        optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3)
        optItem3c.save()

        optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1)
        optItem4a.save()
        optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2)
        optItem4b.save()

        #Add the option group to our items
        pg1 = ConfigurableProduct(product=i1)
        pg1.save()
        pg1.option_group.add(optSet1)
        pg1.save()
        pg1.option_group.add(optSet2)
        pg1.save()

        pg3 = ConfigurableProduct(product=i3)
        pg3.save()
        pg3.option_group.add(optSet3)
        pg3.save()

        pg4 = ConfigurableProduct(product=i4)
        pg4.save()
        pg4.option_group.add(optSet3)
        pg4.save()

    #    pg5 = ConfigurableProduct(product=i5)
    #    pg5.option_group.add(optSet4)
    #    pg5.save()

        print "Creating product variations..."
        #Create the required sub_items
        pg1.create_all_variations()
        pg3.create_all_variations()
        pg4.create_all_variations()
        #pg5.create_all_variations()

        #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
    #    pv1 = pg5.get_product_from_options([optItem4a])
    #    Price(product=pv1, price='5.00').save()
    #    Price(product=pv1, price='2.00', quantity='50.00').save()
    #    DownloadableProduct(product=pv1).save()

    #    pv2 = pg5.get_product_from_options([optItem4b])
    #    Price(product=pv2, price='1.00').save()
    #    DownloadableProduct(product=pv2).save()

        print "Create a test user..."
        #First see if our test user is still there, then use or create that user
        try:
            test_user = User.objects.get(username="csmith")
        except:
            test_user = User.objects.create_user('csmith', 'tester@testsite.com', 'test')
            test_user.save()
        c1.user = test_user
        c1.save()


text:
  Peyrelevade est
       un village
       situé dans le département de Corrèze en Limousin. Elle totalisait 838 habitants en 2008.

À coté de Peyrelevade sont situées les communes de
Chanteix à 6 km, 554 habitants,
Seilhac à 8 km, 1 765 habitants,
Saint-Clément à 6 km, 1 171 habitants,
Saint-Mexant localisée à 4 km, 1 051 habitants,
Saint-Germain-les-Vergnes localisée à 6 km, 916 habitants,
Tulle localisée à 4 km, 15 734 habitants,
 entre autres. De plus, Peyrelevade est située à seulement 20 km de Brive-la-Gaillarde.

La commune propose de nombreux  aménagements, elle propose entre autres un terrain de tennis, un parcours de golf, un terrain de sport et trois boucles de randonnée.

Le parc de logements, à Peyrelevade, se décomposait en 2011 en 74 appartements et 512 maisons soit
 un marché relativement équilibré.

Si vous envisagez de emmenager à Peyrelevade, vous pourrez facilement trouver une maison à vendre.

À Peyrelevade, la valeur moyenne à l'achat d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 160 € du m². À la location le prix moyen se situe à 0 € du m² par mois.


text:
package org.encuestame.persistence.domain;

import java.util.Date;

import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;

/**
 * Rate item (Like, Dislikes)
 * @author Morales Diana, Paola paolaATencuestame.org
 * @since September 13, 2011
 */
@Entity
@Indexed(index="access_rate")
//@Cacheable
//@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "access_rate")
public class AccessRate {

    /** **/
    private Long rateId;

    /** **/
    private TweetPoll tweetPoll;

    /** **/
    private Poll poll;

    /** **/
    private Survey survey;

    /** **/
    private Boolean rate;

    /** **/
    private UserAccount user;

    /** **/
    private Date updatedDate;

    /** **/
    private String ipAddress;

    /** {@link Comment} **/
    private Comment comments;

    /**
     * @return the tweetPollRateId
     */
    @Id
    @DocumentId
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "rateId", unique = true, nullable = false)
    public Long getRateId() {
        return rateId;
    }

    /**
     * @param tweetPollRateId
     *            the tweetPollRateId to set
     */
    public void setRateId(final Long rateId) {
        this.rateId = rateId;
    }

    /**
     * @return the tweetPoll
     */
    @ManyToOne(cascade = CascadeType.MERGE)
    public TweetPoll getTweetPoll() {
        return tweetPoll;
    }

    /**
     * @param tweetPoll
     *            the tweetPoll to set
     */
    public void setTweetPoll(TweetPoll tweetPoll) {
        this.tweetPoll = tweetPoll;
    }

    /**
     * @return the poll
     */
    @ManyToOne(cascade = CascadeType.MERGE)
    public Poll getPoll() {
        return poll;
    }

    /**
     * @param poll
     *            the poll to set
     */
    public void setPoll(final Poll poll) {
        this.poll = poll;
    }

    /**
     * @return the survey
     */
    @ManyToOne(cascade = CascadeType.MERGE)
    public Survey getSurvey() {
        return survey;
    }

    /**
     * @param survey
     *            the survey to set
     */
    public void setSurvey(final Survey survey) {
        this.survey = survey;
    }

    /**
     * @return the rate
     */
    @Column(name = "rate")
    public Boolean getRate() {
        return rate;
    }

    /**
     * @param rate
     *            the rate to set
     */
    public void setRate(Boolean rate) {
        this.rate = rate;
    }

    /**
     * @return the user
     */
    @ManyToOne(cascade = CascadeType.MERGE)
    public UserAccount getUser() {
        return user;
    }

    /**
     * @param user
     *            the user to set
     */
    public void setUser(UserAccount user) {
        this.user = user;
    }

    /**
     * @return the updatedDate
     */
    @Temporal(TemporalType.DATE)
    @Column(name = "created_at")
    public Date getUpdatedDate() {
        return updatedDate;
    }

    /**
     * @param updatedDate
     *            the updatedDate to set
     */
    public void setUpdatedDate(final Date updatedDate) {
        this.updatedDate = updatedDate;
    }

    /**
     * @return the ipAddress
     */
    @Field(index = Index.TOKENIZED, store = Store.YES)
    @Column(name = "ipAddress", nullable = false)
    public String getIpAddress() {
        return ipAddress;
    }

    /**
     * @param ipAddress
     *            the ipAddress to set
     */
    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    /**
     * @return the comments
     */
    @ManyToOne(cascade = CascadeType.MERGE)
    public Comment getComments() {
        return comments;
    }

    /**
     * @param comments the comments to set
     */
    public void setComments(final Comment comments) {
        this.comments = comments;
    }
}


text:
package org.mifos.ui.core.controller;

import java.io.Serializable;
import java.util.List;

import org.mifos.dto.screen.ListElement;

@SuppressWarnings("PMD")
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="SE_NO_SERIALVERSIONID", justification="required for spring web flow storage at a minimum - should disable at filter level and also for pmd")
public class OfficeHierarchyFormBean implements Serializable {

    private List<BranchOnlyHierarchyBean> branchOnlyOfficeHierarchy;
    private List<ListElement> nonBranches;

    public List<ListElement> getNonBranches() {
        return this.nonBranches;
    }

    public void setNonBranches(List<ListElement> nonBranches) {
        this.nonBranches = nonBranches;
    }

    public List<BranchOnlyHierarchyBean> getBranchOnlyOfficeHierarchy() {
        return this.branchOnlyOfficeHierarchy;
    }

    public void setBranchOnlyOfficeHierarchy(List<BranchOnlyHierarchyBean> branchOnlyOfficeHierarchy) {
        this.branchOnlyOfficeHierarchy = branchOnlyOfficeHierarchy;
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lostessence.server.component;

import com.artemis.Component;

/**
 * Amount of rotation in radians. Range is -Pi to Pi.
 *
 * @author simplyianm
 */
public class Rotation extends Component {
    private double rotation;

    public Rotation(double rotation) {
        this.rotation = rotation;
    }

    /**
     * @return the rotation
     */
    public double getRotation() {
        return rotation;
    }

    /**
     * @param rotation the rotation to set
     */
    public void setRotation(double rotation) {
        this.rotation = rotation;
    }
}


text:
package org.apache.struts2.portlet;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.portlet.PortletSession;

import junit.framework.TestCase;

import org.springframework.mock.web.portlet.MockPortletRequest;

/**
 * PortletSessionMapTest. Insert description.
 *
 */
public class PortletSessionMapTest extends TestCase {

    public void testPut() {

    	MockPortletRequest request = new MockPortletRequest();

        PortletSessionMap map = new PortletSessionMap(request);
        assertEquals("testValue1", map.put("testAttribute1", "testValue1"));
        assertEquals("testValue2", map.put("testAttribute2", "testValue2"));

        PortletSession session = request.getPortletSession();
        // Assert that the values has been propagated to the session
        assertEquals("testValue1", session.getAttribute("testAttribute1"));
        assertEquals("testValue2", session.getAttribute("testAttribute2"));
    }

    public void testGet() {
    	MockPortletRequest request = new MockPortletRequest();
    	PortletSession session = request.getPortletSession();
    	session.setAttribute("testAttribute1", "testValue1");
    	session.setAttribute("testAttribute2", "testValue2");
        PortletSessionMap map = new PortletSessionMap(request);
        Object val1 = map.get("testAttribute1");
        Object val2 = map.get("testAttribute2");
        // Assert that the values from the session is in the map
        assertEquals("testValue1", val1);
        assertEquals("testValue2", val2);
    }

    public void testClear() {
        MockPortletRequest req = new MockPortletRequest();
        PortletSession session = req.getPortletSession();
    	session.setAttribute("testAttribute1", "testValue1");
    	session.setAttribute("testAttribute2", "testValue2");

        PortletSessionMap map = new PortletSessionMap(req);
        map.clear();

        // Assert that there are no elements in the portlet session
        assertFalse(req.getPortletSession().getAttributeNames().hasMoreElements());
    }

    public void testRemove() {
    	MockPortletRequest request = new MockPortletRequest();
    	PortletSession session = request.getPortletSession();
    	session.setAttribute("testAttribute1", "testValue1");

        PortletSessionMap map = new PortletSessionMap(request);
        Object ret = map.remove("testAttribute1");
        // Assert that the element that was removed was returned and the key is no longer in the
        // portlet session
        assertEquals("testValue1", ret);
        assertNull(session.getAttribute("testAttribute1"));
    }

    public void testEntrySet() {
    	MockPortletRequest request = new MockPortletRequest();
    	PortletSession session = request.getPortletSession();
    	session.setAttribute("testAttribute1", "testValue1");
    	session.setAttribute("testAttribute2", "testValue2");

        PortletSessionMap map = new PortletSessionMap(request);
        Set entries = map.entrySet();

        assertEquals(2, entries.size());
        Iterator it = entries.iterator();
        Map.Entry entry = (Map.Entry)it.next();
        checkEntry(entry);
        entry = (Map.Entry)it.next();
        checkEntry(entry);

    }

	private void checkEntry(Map.Entry entry) {
		if(entry.getKey().equals("testAttribute1")) {
        	assertEquals("testValue1", entry.getValue());
        }
        else if(entry.getKey().equals("testAttribute2")) {
        	assertEquals("testValue2", entry.getValue());
        }
        else {
        	fail("Unexpected entry in etry set: " + entry);
        }
	}

}


text:
<?php
class Api_model extends CI_Model {

        public function __construct()
        {
                parent::__construct();
        }

        public function check_secret_key($secret_key)
        {
                $data=$this->db->get_where('api_app', array("secret_key"=>$secret_key),1)->result();
                return $data;
        }

        public function insert_log($secret_key,$url,$method,$function,$param,$msg)
        {
				$data["secret_key"]=$secret_key;
				$data["url"]=$url;
				$data["method"]=$method;
				$data["function"]=$function;
				$data["msg"]=$msg;
				$data["param"]=$param;
				$data["transaction_date"]=date("Y-m-d H:i:s");

                $this->db->insert('api_log', $data);
                if($this->db->affected_rows() > 0)
                {
                        return true;
                }
                else
                {
                        return false;
                }
        }

}


text:
//===------------------------- barrier.cpp ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include <__config>

#ifndef _LIBCPP_HAS_NO_THREADS

#include <barrier>
#include <thread>

_LIBCPP_BEGIN_NAMESPACE_STD

#if !defined(_LIBCPP_HAS_NO_TREE_BARRIER) && (_LIBCPP_STD_VER > 11)

class __barrier_algorithm_base {
public:
    struct alignas(64) /* naturally-align the heap state */ __state_t
    {
        struct {
            __atomic_base<__barrier_phase_t> __phase = ATOMIC_VAR_INIT(0);
        } __tickets[64];
    };

    ptrdiff_t&              __expected;
    unique_ptr<__state_t[]> __state;

    _LIBCPP_HIDDEN
    __barrier_algorithm_base(ptrdiff_t& __expected)
        : __expected(__expected)
    {
        size_t const __count = (__expected + 1) >> 1;
        __state = unique_ptr<__state_t[]>(new __state_t[__count]);
    }
    _LIBCPP_HIDDEN
    bool __arrive(__barrier_phase_t __old_phase)
    {
        __barrier_phase_t const __half_step = __old_phase + 1,
                                __full_step = __old_phase + 2;
        size_t __current_expected = __expected,
            __current = hash<thread::id>()(this_thread::get_id()) % ((__expected + 1) >> 1);
        for(int __round = 0;; ++__round) {
            if(__current_expected <= 1)
                return true;
            size_t const __end_node = ((__current_expected + 1) >> 1),
                         __last_node = __end_node - 1;
            for(;;++__current) {
                if(__current == __end_node)
                __current = 0;
                __barrier_phase_t expect = __old_phase;
                if(__current == __last_node && (__current_expected & 1))
                {
                    if(__state[__current].__tickets[__round].__phase.compare_exchange_strong(expect, __full_step, memory_order_acq_rel))
                        break;    // I'm 1 in 1, go to next __round
                }
                else if(__state[__current].__tickets[__round].__phase.compare_exchange_strong(expect, __half_step, memory_order_acq_rel))
                {
                    return false; // I'm 1 in 2, done with arrival
                }
                else if(expect == __half_step)
                {
                    if(__state[__current].__tickets[__round].__phase.compare_exchange_strong(expect, __full_step, memory_order_acq_rel))
                        break;    // I'm 2 in 2, go to next __round
                }
            }
            __current_expected = __last_node + 1;
            __current >>= 1;
        }
    }
};

_LIBCPP_EXPORTED_FROM_ABI
__barrier_algorithm_base * __construct_barrier_algorithm_base(ptrdiff_t& __expected)
{
    return new __barrier_algorithm_base(__expected);
}
_LIBCPP_EXPORTED_FROM_ABI
bool __arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier,
                                     __barrier_phase_t __old_phase)
{
    return __barrier->__arrive(__old_phase);
}
_LIBCPP_EXPORTED_FROM_ABI
void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier)
{
    delete __barrier;
}

#endif //!defined(_LIBCPP_HAS_NO_TREE_BARRIER) && (_LIBCPP_STD_VER >= 11)

_LIBCPP_END_NAMESPACE_STD

#endif //_LIBCPP_HAS_NO_THREADS


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/landing_page_background" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:layout_marginTop="96dp"
            android:orientation="vertical" >

            <com.p1.mobile.p1android.ui.widget.P1TextView
                style="@style/P1SmallTextLight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/apply_text" />

            <com.p1.mobile.p1android.ui.widget.P1EditText
                android:id="@+id/apply_firstname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="24dp"
                android:ems="10"
                android:hint="@string/apply_fistname"
                android:inputType="textPersonName"
                android:minHeight="48dp" />

            <com.p1.mobile.p1android.ui.widget.P1EditText
                android:id="@+id/apply_lastname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/apply_lastname"
                android:inputType="textPersonName"
                android:minHeight="48dp" />

            <com.p1.mobile.p1android.ui.widget.P1EditText
                android:id="@+id/apply_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/apply_email"
                android:inputType="textEmailAddress"
                android:minHeight="48dp" />

        </LinearLayout>
    </ScrollView>

    <com.p1.mobile.p1android.ui.widget.P1ActionBar
        android:id="@+id/login_actionbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </com.p1.mobile.p1android.ui.widget.P1ActionBar>

</FrameLayout>


text:
package com.hp.hpl.jena.datatypes.xsd.impl;

import com.hp.hpl.jena.datatypes.*;
import com.hp.hpl.jena.vocabulary.RDF;
//import com.hp.hpl.jena.rdf.arp.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.shared.BrokenException;
import java.io.*;

/**
 * Builtin data type to represent XMLLiteral (i.e. items created
 * by use of rdf:parsetype='literal'.
 *
 * @author Dave Reynolds
 * @version $Revision: 1.1 $ on $Date: 2009/06/29 08:55:58 $
 */
public class XMLLiteralType extends BaseDatatype implements RDFDatatype {
    /** Singleton instance */
    public static final RDFDatatype theXMLLiteralType = new XMLLiteralType(RDF.getURI() + "XMLLiteral");

    /**
     * Private constructor.
     */
    private XMLLiteralType(String uri) {
        super(uri);
    }

    /**
     * Convert a serialize a value of this datatype out
     * to lexical form.
     */
    @Override
    public String unparse(Object value) {
        return value.toString();
    }

    /**
     * Parse a lexical form of this datatype to a value
     * @throws DatatypeFormatException if the lexical form is not legal
     */
    @Override
    public Object parse(String lexicalForm) throws DatatypeFormatException {
        if ( !isValid(lexicalForm))
          throw new DatatypeFormatException("Bad rdf:XMLLiteral");
        return lexicalForm;
    }

    /**
     * Test whether the given string is a legal lexical form
     * of this datatype.
     */
    @Override
    public boolean isValid(final String lexicalForm) {
        return true; // in order to avoid using ARP
//        /*
//         * To check the lexical form we construct
//         * a dummy RDF/XML document and parse it with
//         * ARP. ARP performs an exclusive canonicalization,
//         * the dummy document has exactly one triple.
//         * If the lexicalForm is valid then the resulting
//         * literal found by ARP is unchanged.
//         * All other scenarios are either impossible
//         * or occur because the lexical form is invalid.
//         */
//        final boolean status[] = new boolean[]{false,false,false};
//        // status[0] true on error or other reason to know that this is not well-formed
//        // status[1] true once first triple found
//        // status[2] the result (good if status[1] and not status[0]).
//
//        ARP arp = new ARP();
//
//        arp.getHandlers().setErrorHandler(new ErrorHandler(){
//        	public void fatalError(SAXParseException e){
//        		status[0] = true;
//        	}
//			public void error(SAXParseException e){
//				status[0] = true;
//			}
//			public void warning(SAXParseException e){
//				status[0] = true;
//			}
//        });
//        arp.getHandlers().setStatementHandler(new StatementHandler(){
//        public void statement(AResource a, AResource b, ALiteral l){
//        	/* this method is invoked exactly once
//        	 * while parsing the dummy document.
//        	 * The l argument is in exclusive canonical XML and
//        	 * corresponds to where the lexical form has been
//        	 * in the dummy document. The lexical form is valid
//        	 * iff it is unchanged.
//        	 */
//        	if (status[1] || !l.isWellFormedXML()) {
//				status[0] = true;
//			}
//			//throw new BrokenException("plain literal in XMLLiteral code.");
//            status[1] = true;
//            status[2] = l.toString().equals(lexicalForm);
//        }
//		public void statement(AResource a, AResource b, AResource l){
//	      status[0] = true;
//	      //throw new BrokenException("resource valued RDF/XML in XMLLiteral code.");
//	    }
//        });
//        try {
//
//        arp.load(new StringReader(
//        "<rdf:RDF  xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n"
//        +"<rdf:Description><rdf:value rdf:parseType='Literal'>"
//        +lexicalForm+"</rdf:value>\n"
//        +"</rdf:Description></rdf:RDF>"
//        ));
//
//        }
//        catch (IOException ioe){
//           throw new BrokenException(ioe);
//        }
//        catch (SAXException s){
//        	return false;
//        }
//
//
//        return (!status[0])&&status[1]&&status[2];
    }

}

/*
    (c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


text:
class TSheets::Repos::CurrentUser < TSheets::Repository
  url "/current_user"
  model TSheets::Models::User
  actions :list
end


text:
'use strict';

/* globals window */

var test = require('tape');
var forEach = require('../');

test('forEach calls each iterator', function (t) {
    var count = 0;
    t.plan(4);
    forEach({ a: 1, b: 2 }, function (value, key) {
        if (count === 0) {
            t.equal(value, 1);
            t.equal(key, 'a');
        } else {
            t.equal(value, 2);
            t.equal(key, 'b');
        }
        count += 1;
    });
});

test('forEach calls iterator with correct this value', function (t) {
    var thisValue = {};

    t.plan(1);

    forEach([0], function () {
        t.equal(this, thisValue);
    }, thisValue);
});

test('second argument: iterator', function (t) {
    var arr = [];
    t['throws'](function () { forEach(arr); }, TypeError, 'undefined is not a function');
    t['throws'](function () { forEach(arr, null); }, TypeError, 'null is not a function');
    t['throws'](function () { forEach(arr, ''); }, TypeError, 'string is not a function');
    t['throws'](function () { forEach(arr, /a/); }, TypeError, 'regex is not a function');
    t['throws'](function () { forEach(arr, true); }, TypeError, 'true is not a function');
    t['throws'](function () { forEach(arr, false); }, TypeError, 'false is not a function');
    t['throws'](function () { forEach(arr, NaN); }, TypeError, 'NaN is not a function');
    t['throws'](function () { forEach(arr, 42); }, TypeError, '42 is not a function');
    t.doesNotThrow(function () { forEach(arr, function () {}); }, 'function is a function');
    t.doesNotThrow(function () { forEach(arr, setTimeout); }, 'setTimeout is a function');
    if (typeof window !== 'undefined') {
        t.doesNotThrow(function () { forEach(arr, window.alert); }, 'alert is a function');
    }
    t.end();
});

test('array', function (t) {
    var arr = [1, 2, 3];

    t.test('iterates over every item', function (st) {
        var index = 0;
        forEach(arr, function () { index += 1; });
        st.equal(index, arr.length, 'iterates ' + arr.length + ' times');
        st.end();
    });

    t.test('first iterator argument', function (st) {
        var index = 0;
        st.plan(arr.length);
        forEach(arr, function (item) {
            st.equal(arr[index], item, 'item ' + index + ' is passed as first argument');
            index += 1;
        });
        st.end();
    });

    t.test('second iterator argument', function (st) {
        var counter = 0;
        st.plan(arr.length);
        forEach(arr, function (item, index) {
            st.equal(counter, index, 'index ' + index + ' is passed as second argument');
            counter += 1;
        });
        st.end();
    });

    t.test('third iterator argument', function (st) {
        st.plan(arr.length);
        forEach(arr, function (item, index, array) {
            st.deepEqual(arr, array, 'array is passed as third argument');
        });
        st.end();
    });

    t.test('context argument', function (st) {
        var context = {};
        forEach([], function () {
            st.equal(this, context, '"this" is the passed context');
        }, context);
        st.end();
    });

    t.end();
});

test('object', function (t) {
    var obj = {
        a: 1,
        b: 2,
        c: 3
    };
    var keys = ['a', 'b', 'c'];

    var F = function F() {
        this.a = 1;
        this.b = 2;
    };
    F.prototype.c = 3;
    var fKeys = ['a', 'b'];

    t.test('iterates over every object literal key', function (st) {
        var counter = 0;
        forEach(obj, function () { counter += 1; });
        st.equal(counter, keys.length, 'iterated ' + counter + ' times');
        st.end();
    });

    t.test('iterates only over own keys', function (st) {
        var counter = 0;
        forEach(new F(), function () { counter += 1; });
        st.equal(counter, fKeys.length, 'iterated ' + fKeys.length + ' times');
        st.end();
    });

    t.test('first iterator argument', function (st) {
        var index = 0;
        st.plan(keys.length);
        forEach(obj, function (item) {
            st.equal(obj[keys[index]], item, 'item at key ' + keys[index] + ' is passed as first argument');
            index += 1;
        });
        st.end();
    });

    t.test('second iterator argument', function (st) {
        var counter = 0;
        st.plan(keys.length);
        forEach(obj, function (item, key) {
            st.equal(keys[counter], key, 'key ' + key + ' is passed as second argument');
            counter += 1;
        });
        st.end();
    });

    t.test('third iterator argument', function (st) {
        st.plan(keys.length);
        forEach(obj, function (item, key, object) {
            st.deepEqual(obj, object, 'object is passed as third argument');
        });
        st.end();
    });

    t.test('context argument', function (st) {
        var context = {};
        forEach({}, function () {
            st.equal(this, context, '"this" is the passed context');
        }, context);
        st.end();
    });

    t.end();
});

test('string', function (t) {
    var str = 'str';
    t.test('second iterator argument', function (st) {
        var counter = 0;
        st.plan((str.length * 2) + 1);
        forEach(str, function (item, index) {
            st.equal(counter, index, 'index ' + index + ' is passed as second argument');
            st.equal(str.charAt(index), item);
            counter += 1;
        });
        st.equal(counter, str.length, 'iterates ' + str.length + ' times');
        st.end();
    });
    t.end();
});


text:
namespace YuGiOh_PoC_Patcher
{
    partial class ImageWindow
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImageWindow));
            this.pictureBox1 = new YuGiOh_PoC_Patcher.PictureBoxWithInterpolationMode();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            //
            // pictureBox1
            //
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pictureBox1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(284, 261);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseClick);
            //
            // ImageWindow
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.pictureBox1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "ImageWindow";
            this.Text = "Image";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private PictureBoxWithInterpolationMode pictureBox1;
    }
}


text:
package de.tomgrill.gdxfirebase.core.analytics;

public class NullFirebaseAnalytics implements FirebaseAnalytics {
    @Override
    public void logEvent(String name, Bundle bundle) {

    }
}


text:
# Использование пре-процессоров

В Webpack все пре-процессоры должны быть применены с соответствующим загрузчиком. `vue-loader` позволяет вам использовать другие загрузчики Webpack для обработки секций компонентов Vue. Они будут автоматически вызваны для обработки секций на основе указанного атрибута `lang` у секции файла.

### CSS

Например, пусть в теге `<style>` будет использоваться SASS:

``` bash
npm install sass-loader node-sass --save-dev
```

``` html
<style lang="sass">
  /* используем SASS здесь */
</style>
```

В недрах, текстовое содержимое тега `<style>` будет сперва скомпилировано с помощью `sass-loader` перед передачей для дальнейшей обработки.

#### Особенность sass-loader

Вопреки тому, что он называется [*sass*-loader](https://github.com/jtangelder/sass-loader), по умолчанию парсится синтаксис *SCSS*. Если вы на самом деле хотите использовать синтаксис *SASS* с отступами, вам требуется настроить vue-loader для sass-loader соответственно.

```javascript
{
  test: /\.vue$/,
  loader: 'vue-loader',
  options: {
    loaders: {
      scss: 'vue-style-loader!css-loader!sass-loader', // <style lang="scss">
      sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // <style lang="sass">
    }
  }
}
```

Обратитесь к разделу [продвинутой конфигурации загрузчиков](./advanced.md) для получения дополнительной информации о том, как настраивать vue-loader.

#### Загрузка глобального файла настроек

Часто встречаются просьбы добавить возможность загружать файл настроек в каждом компоненте без необходимости явно импортировать его каждый раз, например для использования SCSS-переменных глобально во всех компонентах. Для этого нужно:

``` bash
npm install sass-resources-loader --save-dev
```

Затем добавить новое правило в Webpack:

``` js
{
  loader: 'sass-resources-loader',
  options: {
    resources: path.resolve(__dirname, '../src/style/_variables.scss')
  }
}
```

Например, если вы используете [vuejs-templates/webpack](https://github.com/vuejs-templates/webpack), измените файл `build/utils.js` таким образом:

``` js
scss: generateLoaders('sass').concat(
  {
    loader: 'sass-resources-loader',
    options: {
      resources: path.resolve(__dirname, '../src/style/_variables.scss')
    }
  }
),
```

В этот файл рекомендуется включать только переменные, примеси и т.п., чтобы предотвратить дублирование CSS в финальных скомпилированных файлах.

### JavaScript

Весь JavaScript внутри Vue компонентов обрабатывается `babel-loader` по умолчанию. При необходимости это можно изменить:

``` bash
npm install coffee-loader --save-dev
```

``` html
<script lang="coffee">
  # Пишем на coffeescript!
</script>
```

### Шаблоны

Обработка шаблонов выполняется несколько иначе, потому что большинство loader'ов шаблонов Webpack, например `pug-loader`, возвращают функцию шаблона вместо скомпилированного в строку HTML. Поэтому вместо использования `pug-loader`, можно просто установить оригинальный `pug`:

``` bash
npm install pug --save-dev
```

``` html
<template lang="pug">
div
  h1 Hello world!
</template>
```

> **Внимание:** При использовании `vue-loader@<8.2.0`, вам также необходимо установить `template-html-loader`.

### Непосредственное указание loader'ов

Вы можете указывать [опции для loader'ов Webpack](https://webpack.github.io/docs/loaders.html#introduction) в атрибуте `lang`:

``` html
<style lang="sass?outputStyle=expanded">
  /* используем SASS с расширенным выводом */
</style>
```

Обратите внимание, это сделает ваш компонент Vue зависимым от Webpack и несовместимым с Browserify и [vueify](https://github.com/vuejs/vueify). **Если вы планируете распространять ваш компонент Vue, избегайте использования этого синтаксиса.**


text:
// Copyright (c) 2009-2013 The Dacrs developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef DACRS_CHECKPOINTS_H_
#define DACRS_CHECKPOINTS_H_

#include <map>
#include <vector>

class CBlockIndex;
class uint256;

/** Block-chain checkpoints are compiled-in sanity checks.
 * They are updated every release or three.
 */
namespace Checkpoints {
// Returns true if block passes checkpoint checks
bool CheckBlock(int nHeight, const uint256& cHash);

// Return conservative estimate of total number of blocks, 0 if unknown
int GetTotalBlocksEstimate();

// Returns last CBlockIndex* in g_mapBlockIndex that is a checkpoint
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& g_mapBlockIndex);

double GuessVerificationProgress(CBlockIndex *pBlockIndex, bool bSigchecks = true);

bool AddCheckpoint(int nHeight, uint256 cHash);

bool GetCheckpointByHeight(const int nHeight, std::vector<int> &vnCheckPoints);

bool LoadCheckpoint();

void GetCheckpointMap(std::map<int, uint256> &mapCheckPoints);

extern bool g_bEnabled;
}

#endif


text:
export class InvalidTypeError extends Error {
  constructor() {
    super('Type provided is invalid.');
  }
}

export class InvalidPropertyError extends Error {
  constructor(message: string) {
    super(message);
  }
}

export class NoSchemaPropertiesError extends Error {
  constructor() {
    super('No schema properties found on class.');
  }
}

export class NoItemTypeProvidedError extends Error {
  constructor(target: any, key: string) {
    super(`Property: ${key} of ${target.constructor.name} should have options.items set.`);
  }
}

export class PropertyIsNotArrayError extends Error {
  constructor(target: any, key: string) {
    super(`Property: ${key} of ${target.constructor.name} is not an array.`);
  }
}

export class PropertyHasInvalidTypeError extends Error {
  constructor(target: any, key: string, typeName: string) {
    super(`Property: ${key} of ${target.constructor.name} cannot have type: ${typeName}.`);
  }
}

export class EnumEmptyError extends Error {
  constructor() {
    super('Enum has no values.');
  }
}


text:
//Problem 13. Check a Bit at Given Position

//Write a Boolean expression that returns if the bit at position p (counting from 0, starting from the right) in
//given integer number n, has value of 1.
//Examples:

//n	  binary representation of n	p	bit @ p == 1
//5	    00000000 00000101	        2	   true
//0	    00000000 00000000	        9	   false
//15	00000000 00001111	        1	   true
//5343	00010100 11011111	        7	   true
//62241	11110011 00100001	        11	   false

using System;

class CheckBitAtGivenPosition
{
	static void Main()
	{
		string task = "Problem 13. Check a Bit at Given Position\n\nWrite a Boolean expression that returns if the bit at position p (counting from 0, starting from the right) in given integer number n, has value of 1.\nExamples:\nn binary representation of n	p	bit @ p == 1\n5	00000000 00000101	2	true\n0	00000000 00000000	9	false\n15	00000000 00001111	1	true\n5343	00010100 11011111	7	true\n62241	11110011 00100001	11	false\n";
		string separator = new string('*', Console.WindowWidth);

		Console.WriteLine(task);
		Console.WriteLine(separator);

		Console.WriteLine("Enter number:");
		int number = int.Parse(Console.ReadLine());

		Console.WriteLine("Enter index:");
		byte index = byte.Parse(Console.ReadLine());

		bool isBitOne = (number & (1 << index)) != 0;

		string binaryNumber = Convert.ToString(number, 2).PadLeft(16, '0');

		Console.WriteLine("number: {0}\nbinary representation: {1}\nindex: {2}\nbit @ p == 1: {3}", number, binaryNumber, index, isBitOne);

	}
}


text:
using IuriiO.Apps.Avidoc.Services.DataContextServices;
using System;
using System.Collections.Generic;
using System.IO;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace IuriiO.Apps.Avidoc.Services.BackupServices
{
    public class BackupService : IBackupService
    {
        private const String DB_BACKUP_NAME = LibraryDataContext.DB_NAME + "_backup";

        private String localDbPath;

        public BackupService()
        {
            this.localDbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, LibraryDataContext.DB_FULL_NAME);
        }

        public async void BackupDatabase()
        {
            StorageFile localDbFile = await StorageFile.GetFileFromPathAsync(this.localDbPath);

            var picker = new FileSavePicker();
            picker.DefaultFileExtension = LibraryDataContext.DB_EXT;
            picker.SuggestedFileName = DB_BACKUP_NAME;
            picker.FileTypeChoices.Add("Backup", new List<string>() { LibraryDataContext.DB_EXT });
            picker.SuggestedStartLocation = PickerLocationId.Desktop;
            StorageFile target = await picker.PickSaveFileAsync();

            await localDbFile.CopyAndReplaceAsync(target);
        }

        public async void RestoreDatabase()
        {
            StorageFile localDbFile = await StorageFile.GetFileFromPathAsync(this.localDbPath);

            var filePicker = new FileOpenPicker();
            filePicker.SuggestedStartLocation = PickerLocationId.Desktop;
            filePicker.FileTypeFilter.Add(LibraryDataContext.DB_EXT);
            var src = await filePicker.PickSingleFileAsync();

            await src.CopyAndReplaceAsync(localDbFile);
        }
    }
}


text:
define([
    './_BaseDrawingElement'
  , './lib'
], function(
    Parent
  , lib
) {
    "use strict";

    var svgns = lib.svgns
      , setTransform = lib.setTransform
      , insertElement = lib.insertElement
      ;

    function Layout(doc, children, options) {
        this.options = options;
        this.leftSideBearing = 0;
        this.rightSideBearing = 0;
        this._children = children;
        this.element = doc.createElementNS(svgns, 'g');
        this._addChildren(children);
    }
    var _p = Layout.prototype = Object.create(Parent.prototype);
   _p.constructor = Layout;

    Object.defineProperty(_p, 'width', {
        get: function() {
            var i, l, width=0;
            for(i=0,l=this._children.length;i<l;i++) {
                if(this._children[i].noDimensions)
                    // don't consider these
                    continue;
                if(i > 0 && this.options.spacing)
                    width += this.options.spacing;
                width += this._children[i].width;
            }
            return width;
        }
      , enumerable: true
    });

    Object.defineProperty(_p, 'rawWidth', {
        get: function() {
            return this.width - this.leftSideBearing - this.rightSideBearing;
        }
    });

    _p.initDimensions = function() {
         var i, l, child, xadvance = 0;
         for(i=0,l=this._children.length;i<l;i++) {
            child = this._children[i];
            if(child.noDimensions)
                // don't consider these
                continue;
            child.initDimensions();
            setTransform(child.element, [1, 0, 0, 1, xadvance, 0]);
            if(this.options.spacing)
                xadvance += this.options.spacing;
            xadvance += child.width;
        }
        this.leftSideBearing = this._children[0].leftSideBearing;
        this.rightSideBearing = this._children[this._children.length-1].rightSideBearing;
    };

    _p._addChildren = function(children) {
        var i, l, child;
        if(!children.length) return;
        for(i=0,l=children.length;i<l;i++) {
            child = children[i];
            insertElement(this.element, child.element, child.options.insert);
        }
    };

    return Layout;
});


text:
"""
Web application for managing Bengfort finances.
"""

##########################################################################
## Imports
##########################################################################

from __future__ import absolute_import
from .version import get_version

##########################################################################
## Module Definition
##########################################################################

__version__ = get_version()


text:
void SetCustomTheme(Profile* profile, int theme_index) {
  test::ThemeServiceChangedWaiter waiter(
      ThemeServiceFactory::GetForProfile(profile));
  themes_helper::UseCustomTheme(profile, theme_index);
  waiter.WaitForThemeChanged();
}

ServerCountMatchStatusChecker::ServerCountMatchStatusChecker(
    syncer::ModelType type,
    size_t count)
    : type_(type), count_(count) {}

bool ServerCountMatchStatusChecker::IsExitConditionSatisfied(std::ostream* os) {
  size_t actual_count = fake_server()->GetSyncEntitiesByModelType(type_).size();
  *os << "Waiting for fake server entity count " << actual_count
      << " to match expected count " << count_ << " for type "
      << ModelTypeToDebugString(type_);
  return count_ == actual_count;
}

PassphraseRequiredChecker::PassphraseRequiredChecker(
    syncer::SyncServiceImpl* service)
    : SingleClientStatusChangeChecker(service) {}

bool PassphraseRequiredChecker::IsExitConditionSatisfied(std::ostream* os) {
  *os << "Passhrase Required";
  return service()->GetUserSettings()->IsPassphraseRequired();
}

PassphraseAcceptedChecker::PassphraseAcceptedChecker(
    syncer::SyncServiceImpl* service)
    : SingleClientStatusChangeChecker(service) {}

bool PassphraseAcceptedChecker::IsExitConditionSatisfied(std::ostream* os) {
  *os << "Passhrase Accepted";
  return !service()->GetUserSettings()->IsPassphraseRequired() &&
         service()->GetUserSettings()->IsUsingExplicitPassphrase();
}


text:
import logging

from asyncio import CancelledError
from itertools import count

from sanic.exceptions import NotFound
from sanic.request import Request
from sanic.response import HTTPResponse, json, text

# ------------------------------------------------------------ #
#  GET
# ------------------------------------------------------------ #

def test_middleware_request(app):
    results = []

    @app.middleware
    async def handler1(request):
        results.append(request)

    @app.route("/")
    async def handler2(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request

def test_middleware_request_as_convenience(app):
    results = []

    @app.on_request
    async def handler1(request):
        results.append(request)

    @app.on_request()
    async def handler2(request):
        results.append(request)

    @app.route("/")
    async def handler3(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request
    assert type(results[1]) is Request

def test_middleware_response(app):
    results = []

    @app.middleware("request")
    async def process_request(request):
        results.append(request)

    @app.middleware("response")
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    @app.route("/")
    async def handler(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse)

def test_middleware_response_as_convenience(app):
    results = []

    @app.on_request
    async def process_request(request):
        results.append(request)

    @app.on_response
    async def process_response_1(request, response):
        results.append(request)
        results.append(response)

    @app.on_response()
    async def process_response_2(request, response):
        results.append(request)
        results.append(response)

    @app.route("/")
    async def handler(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse)
    assert type(results[3]) is Request
    assert isinstance(results[4], HTTPResponse)

def test_middleware_response_as_convenience_called(app):
    results = []

    @app.on_request()
    async def process_request(request):
        results.append(request)

    @app.on_response()
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    @app.route("/")
    async def handler(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.text == "OK"
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse)

def test_middleware_response_exception(app):
    result = {"status_code": "middleware not run"}

    @app.middleware("response")
    async def process_response(request, response):
        result["status_code"] = response.status
        return response

    @app.exception(NotFound)
    async def error_handler(request, exception):
        return text("OK", exception.status_code)

    @app.route("/")
    async def handler(request):
        return text("FAIL")

    request, response = app.test_client.get("/page_not_found")
    assert response.text == "OK"
    assert result["status_code"] == 404

def test_middleware_response_raise_cancelled_error(app, caplog):
    app.config.RESPONSE_TIMEOUT = 1

    @app.middleware("response")
    async def process_response(request, response):
        raise CancelledError("CancelledError at response middleware")

    @app.get("/")
    def handler(request):
        return text("OK")

    with caplog.at_level(logging.ERROR):
        reqrequest, response = app.test_client.get("/")

        assert response.status == 503
        assert (
            "sanic.error",
            logging.ERROR,
            "Exception occurred while handling uri: 'http://127.0.0.1:42101/'",
        ) not in caplog.record_tuples

def test_middleware_response_raise_exception(app, caplog):
    @app.middleware("response")
    async def process_response(request, response):
        raise Exception("Exception at response middleware")

    app.route("/")(lambda x: x)
    with caplog.at_level(logging.ERROR):
        reqrequest, response = app.test_client.get("/fail")

    assert response.status == 404
    # 404 errors are not logged
    assert (
        "sanic.error",
        logging.ERROR,
        "Exception occurred while handling uri: 'http://127.0.0.1:42101/'",
    ) not in caplog.record_tuples
    # Middleware exception ignored but logged
    assert (
        "sanic.error",
        logging.ERROR,
        "Exception occurred in one of response middleware handlers",
    ) in caplog.record_tuples

def test_middleware_override_request(app):
    @app.middleware
    async def halt_request(request):
        return text("OK")

    @app.route("/")
    async def handler(request):
        return text("FAIL")

    _, response = app.test_client.get("/", gather_request=False)

    assert response.status == 200
    assert response.text == "OK"

def test_middleware_override_response(app):
    @app.middleware("response")
    async def process_response(request, response):
        return text("OK")

    @app.route("/")
    async def handler(request):
        return text("FAIL")

    request, response = app.test_client.get("/")

    assert response.status == 200
    assert response.text == "OK"

def test_middleware_order(app):
    order = []

    @app.middleware("request")
    async def request1(request):
        order.append(1)

    @app.middleware("request")
    async def request2(request):
        order.append(2)

    @app.middleware("request")
    async def request3(request):
        order.append(3)

    @app.middleware("response")
    async def response1(request, response):
        order.append(6)

    @app.middleware("response")
    async def response2(request, response):
        order.append(5)

    @app.middleware("response")
    async def response3(request, response):
        order.append(4)

    @app.route("/")
    async def handler(request):
        return text("OK")

    request, response = app.test_client.get("/")

    assert response.status == 200
    assert order == [1, 2, 3, 4, 5, 6]

def test_request_middleware_executes_once(app):
    i = count()

    @app.middleware("request")
    async def inc(request):
        nonlocal i
        next(i)

    @app.route("/")
    async def handler(request):
        await request.app._run_request_middleware(request)
        return text("OK")

    request, response = app.test_client.get("/")
    assert next(i) == 1

    request, response = app.test_client.get("/")
    assert next(i) == 3

def test_middleware_added_response(app):
    @app.on_response
    def display(_, response):
        response["foo"] = "bar"
        return json(response)

    @app.get("/")
    async def handler(request):
        return {}

    _, response = app.test_client.get("/")
    assert response.json["foo"] == "bar"

def test_middleware_return_response(app):
    response_middleware_run_count = 0
    request_middleware_run_count = 0

    @app.on_response
    def response(_, response):
        nonlocal response_middleware_run_count
        response_middleware_run_count += 1

    @app.on_request
    def request(_):
        nonlocal request_middleware_run_count
        request_middleware_run_count += 1

    @app.get("/")
    async def handler(request):
        resp1 = await request.respond()
        return resp1

    _, response = app.test_client.get("/")
    assert response_middleware_run_count == 1
    assert request_middleware_run_count == 1


text:
import datetime
import calendar

from django.shortcuts import render
from django.views.generic import TemplateView,RedirectView
from django.utils import dateparse,timezone

from .models import Calendar,MonthCache
from . import utils

# Create your views here.
class CalendarCssView(TemplateView):
    template_name = 'events/calendars.css'
    content_type = 'text/css'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['calendars'] = Calendar.objects.all()

        return context

class EventsView(TemplateView):
    template_name = 'events/index.html'

    year = None
    month = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        today = timezone.localtime(timezone.now()).date()
        try:
            self.year = int(self.kwargs['year'])
            self.month = int(self.kwargs['month'])
        except KeyError:
            self.year = today.year
            self.month = today.month

        current_month = datetime.date(self.year, self.month, 1)
        dates = calendar.Calendar(6).monthdatescalendar(current_month.year, current_month.month)

        events = {}
        gcals = Calendar.objects.all()
        for gcal in gcals:
            gdata = gcal.get_events(current_month)

            for event in gdata['items']:
                event['css_class'] = gcal.css_class
                try:
                    startdate = dateparse.parse_datetime(event['start']['dateTime'])
                    enddate = dateparse.parse_datetime(event['end']['dateTime'])

                    event['start_time'] = startdate.time()
                    event['end_time'] = enddate.time()

                    startdate = startdate.date()
                    enddate = enddate.date()
                except KeyError:
                    startdate = dateparse.parse_date(event['start']['date'])
                    enddate = dateparse.parse_date(event['end']['date'])

                event['start_date'] = startdate
                event['end_date'] = enddate

                try:
                    events[startdate.isoformat()].append(event)
                except KeyError:
                    events[startdate.isoformat()] = [event,]

        cal = []
        for week in dates:
            cal.append([])
            for date in week:
                isodate = date.isoformat()
                date_events = events.get(isodate, [])
                date_events.sort(key=utils.event_key)

                cal[-1].append({
                    'date': date,
                    'events': date_events,
                    })

        context['calendar'] = cal
        context['gcals'] = gcals
        context['current_month'] = current_month
        context['last_month'] = current_month - datetime.timedelta(days=1)
        context['next_month'] = current_month + datetime.timedelta(days=32)
        context['today'] = today

        return context


text:
class VotesController < Matterhorn::Base
  include Matterhorn::Resource
  include FakeAuth

  resource!
  belongs_to :post

  add_env :current_user

protected ######################################################################

  def resource
    get_resource_ivar || set_resource_ivar(end_of_association_chain.send(:votes).find_by(user: current_user))
  end

end


text:
package adept.kbapi;

import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;

import java.util.HashSet;
import java.util.Set;

import adept.common.KBID;
import adept.common.TemporalResolution;
import adept.common.TimexValue;
import adept.common.XSDDate;

/**
 * Class for representing Dates in the KB.
 *
 * Currently this implementation supports date strings in either Timex2 or
 * XSDDate format. Both formats will be available if conversion is possible.
 *
 * Dates are intended to be canonical within the KB; only one copy of a
 * particular date should ever exist.
 *
 * @author dkolas
 */
public class KBDate extends KBThing {

	/**
	 * The timex2 representation of the date
	 */
	private final String timexString;

	/**
	 * The XSDDate representation of the date
	 */
	private final Optional<String> xsdDateString;

	/**
	 * @param kb
	 * @param kbID
	 * @param provenances
	 * @param timexString
	 * @param xsdDateString
	 */
	protected KBDate(KB kb, KBID kbID, Optional<Set<KBProvenance>> provenances, String timexString,
			Optional<String> xsdDateString) {
		super(kb, kbID, provenances, timexString);
		this.timexString = timexString;
		this.xsdDateString = xsdDateString;
	}

	/**
	 * Get the timex2 representation of the date. This should always be
	 * available.
	 *
	 * @return
	 */
	public String getTimexString() {
		return timexString;
	}

	/**
	 * Get the XSDDate representation of the date. This will be available if the
	 * date was created with an XSDDate representation, or if the timex2 value
	 * could be successfully converted.
	 *
	 * Otherwise this method will return {@link Optional#absent()}
	 *
	 * @return
	 */
	public Optional<String> xsdDateString() {
		return xsdDateString;
	}

	/**
	 * Create an insertionBuilder based on a Timex string.
	 *
	 * Provenances can then be added.
	 *
	 * @param timexString
	 * @return
	 */
	public static InsertionBuilder timexInsertionBuilder(String timexString) {
		Preconditions.checkNotNull(timexString);
		return new InsertionBuilder(timexString, timexToXSD(timexString));
	}

	/**
	 * Private method for converting timex2 strings to XSDDate strings
	 *
	 * @param timexString
	 * @return
	 */
	public static Optional<String> timexToXSD(String timexString) {

		if (timexString.matches("\\d{4}-\\d{2}-\\d{2}(Z|((\\+|\\-)\\d{2}:\\d{2}))?")) {
			return Optional.of(timexString);
		} else {
			return Optional.absent();
		}
	}

	/**
	 * Create an insertionBuilder based on an XSDDate string.
	 *
	 * Provenances can then be added.
	 *
	 * @param xsdDateString
	 * @return
	 */
	public static InsertionBuilder xsdDateInsertionBuilder(String xsdDateString) {
		Preconditions.checkNotNull(xsdDateString);
		return new InsertionBuilder(xsdToTimex(xsdDateString), Optional.of(xsdDateString));
	}

	/**
	 * Private method for converting XSDDate strings to Timex strings
	 *
	 * @param xsdDateString
	 * @return
	 */
	public static String xsdToTimex(String xsdDateString) {
		return xsdDateString;
	}

	/**
	 * Create an insertion builder from a {@link TimexValue}.
	 *
	 * Any temporal resolutions in the provided list that are linked to the
	 * provided timexValue are used to add provenances to the builder.
	 *
	 * @param timexValue
	 * @param temporalResolutions
	 * @return the new InsertionBuilder
	 */
	public static InsertionBuilder timexInsertionBuilder(TimexValue timexValue,
			Set<TemporalResolution> temporalResolutions) {
		Preconditions.checkNotNull(timexValue);
		Preconditions.checkNotNull(temporalResolutions);
		InsertionBuilder builder = new InsertionBuilder(timexValue.asString(),
				timexToXSD(timexValue.asString()));
		for (TemporalResolution temporalResolution : temporalResolutions) {
			if (temporalResolution.getResolvedTemporalValue().equals(timexValue)) {
				builder.addProvenance(KBTextProvenance.builder(temporalResolution.getTimePhrase(),
						temporalResolution.getConfidence()));
			}
		}
		return builder;
	}

	/**
	 * Create an insertion builder from a {@link XSDDate}.
	 *
	 * Any temporal resolutions in the provided list that are linked to the
	 * provided xsdDate are used to add provenances to the builder.
	 *
	 * @param xsdDate
	 * @param temporalResolutions
	 * @return
	 */
	public static InsertionBuilder xsdDateInsertionBuilder(XSDDate xsdDate,
			Set<TemporalResolution> temporalResolutions) {
		Preconditions.checkNotNull(xsdDate);
		Preconditions.checkNotNull(temporalResolutions);
		InsertionBuilder builder = new InsertionBuilder(xsdToTimex(xsdDate.asString()),
				Optional.of(xsdDate.asString()));
		for (TemporalResolution temporalResolution : temporalResolutions) {
			if (temporalResolution.getResolvedTemporalValue().equals(xsdDate)) {
				builder.addProvenance(KBTextProvenance.builder(temporalResolution.getTimePhrase(),
						temporalResolution.getConfidence()));
			}
		}
		return builder;
	}

	/**
	 * Class for inserting KBDates into the KB.
	 *
	 * @author dkolas
	 */
	public static class InsertionBuilder extends
			KBPredicateArgument.InsertionBuilder<InsertionBuilder, KBDate> {

		private final String timexString;
		private final Optional<String> xsdDateString;

		public String getTimexDate() {
			return timexString;
		}

		public Optional<String> getXSDDate() {
			return xsdDateString;
		}

		/**
		 * Private constructor for the builder, to be called only by
		 * insertionBuilder methods.
		 *
		 * @param timexString
		 * @param xsdDateString
		 */
		private InsertionBuilder(String timexString, Optional<String> xsdDateString) {
			super();
			this.timexString = timexString;
			this.xsdDateString = xsdDateString;
		}

		/**
		 * Method to insert the contents of this builder into the KB.
		 *
		 * @param kb
		 * @return
		 *
		 */
		@Override
		public KBDate insert(KB kb) throws KBUpdateException {
			kb.insertDateValue(this);
			return build(kb, false);
		}

		protected KBDate build(KB kb, boolean deferProvenances) {
			Optional<Set<KBProvenance>> provenances = buildProvenances(deferProvenances);
			return new KBDate(kb, kbid, provenances, timexString, xsdDateString);
		}

		/**
		 *
		 * @return
		 *
		 * @see adept.kbapi.KBPredicateArgument.InsertionBuilder#me()
		 */
		@Override
		protected InsertionBuilder me() {
			return this;
		}
	}

	/**
	 * Get an update builder for this object.
	 *
	 * Only provenances are updatable.
	 *
	 * @return
	 *
	 */
	@Override
	public UpdateBuilder updateBuilder() {
		return new UpdateBuilder();
	}

	/**
	 * Class for updating a KBDate.
	 *
	 * Only provenances are updatable.
	 *
	 * @author dkolas
	 */
	public class UpdateBuilder extends KBPredicateArgument.UpdateBuilder<UpdateBuilder, KBDate> {

		@Override
		public KBDate update(KB kb) throws KBUpdateException {

			Set<KBProvenance> oldProvenances = null;
			try{
				oldProvenances = getProvenances();
				checkProvenancesToRemove();
			}catch(KBQueryException e){
				throw new KBUpdateException("Could not load provenances for original object",e);
			}
			kb.updateKBPredicateArgumentProvenances(this);
			Set<KBProvenance> provenances = new HashSet<KBProvenance>();
			for (KBProvenance.InsertionBuilder provenanceBuilder : getNewProvenances()) {
				provenances.add(provenanceBuilder.build());
			}
			for (KBProvenance kbProvenance : oldProvenances) {
				if (!getProvenancesToRemove().contains(kbProvenance)) {
					provenances.add(kbProvenance);
				}
			}
			return new KBDate(kb, getKBID(), Optional.of(provenances), getTimexString(),
					xsdDateString());
		}

		/**
		 *
		 * @return
		 *
		 * @see adept.kbapi.KBPredicateArgument.UpdateBuilder#me()
		 */
		@Override
		protected UpdateBuilder me() {
			return this;
		}

	}

	@Override
	public boolean equals(Object o) {
		if (null == o || (getClass() != o.getClass())) {
			return false;
		}
		KBDate that = (KBDate) o;
		return super.equals(that) && Objects.equal(that.timexString, this.timexString)
				&& Objects.equal(that.xsdDateString, this.xsdDateString);
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(super.hashCode(), timexString, xsdDateString);
	}
}


text:
a.multiSelect {
	background: #FFF url(../images/dropdown/dropdown.blue.png) right center no-repeat;
	border: solid 1px #ccc;
	padding-right: 20px;
	position: relative;
	cursor: default;
	text-decoration: none;
	display: -moz-inline-stack;
	display: inline-block;
	vertical-align: top;

	font-size: 10px;
	height: 27px;
    line-height: 27px;
    border-radius: 3px 3px 3px 3px;
    color: #808080;
}

a.multiSelect:link, a.multiSelect:visited, a.multiSelect:hover, a.multiSelect:active {
	color: black;
	text-decoration: none;
}

a.multiSelect span
{
	margin: 1px 0px 1px 3px;
	overflow: hidden;
	display: -moz-inline-stack;
	display: inline-block;
	white-space: nowrap;
}

a.multiSelect.hover {
	background-image: url(../images/dropdown/dropdown.blue.hover.png);
}

a.multiSelect.active,
a.multiSelect.focus {
	border: inset 1px #000;
}

a.multiSelect.active {
	background-image: url(../images/dropdown/dropdown.blue.active.png);
}

.multiSelectOptions {
	margin-top: -1px;
	overflow-y: auto;
	overflow-x: hidden;
	border: solid 1px #B2B2B2;
	background: #FFF;
	min-width: 120px;
}

.multiSelectOptions LABEL {
	padding: 0px 2px;
	display: block;
	white-space: nowrap;
}

.multiSelectOptions LABEL.optGroup
{
	font-weight: bold;
}

.multiSelectOptions .optGroupContainer LABEL
{
	padding-left: 10px;
}

.multiSelectOptions.optGroupHasCheckboxes .optGroupContainer LABEL
{
	padding-left: 18px;
}

.multiSelectOptions input{
	vertical-align: middle;
}

.multiSelectOptions LABEL.checked {
	background-color: #dce5f8;
}

.multiSelectOptions LABEL.selectAll {
	border-bottom: dotted 1px #CCC;
}

.multiSelectOptions LABEL.hover {
	background-color: #3399ff;
	color: white;
}


text:
<ion-header>
    <ion-toolbar>
        <ion-title>

{{ 'addon.mod_workshop.userplan' | translate }}

        </ion-title>
        <ion-buttons slot="end">
            <ion-button fill="clear" (click)="closeModal()" [attr.aria-label]="'core.close' | translate">
                <ion-icon name="fas-times" slot="icon-only" aria-hidden=true></ion-icon>
            </ion-button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>
<ion-content>
    <ion-list>
        <ng-container *ngFor="let phase of phases">
            <ion-item-divider [attr.aria-current]="workshopPhase == phase.code ? 'page' : 'false'">
                <ion-label>

{{ phase.title }}

                        {{ 'addon.mod_workshop.userplancurrentphase' | translate }}

                </ion-label>
            </ion-item-divider>
            <ion-item class="ion-text-wrap" *ngIf="phase.switchUrl" [href]="phase.switchUrl" detail="false">
                <ion-icon slot="start" name="fas-exchange-alt" aria-hidden="true"></ion-icon>
                <ion-label>

{{ 'addon.mod_workshop.switchphase' + phase.code | translate }}

                </ion-label>
                <ion-icon slot="end" name="fas-external-link-alt" aria-hidden="true"></ion-icon>
            </ion-item>
            <ion-item class="ion-text-wrap" *ngFor="let task of phase.tasks"
                [class.item-dimmed]="phase.code != workshopPhase || (task.code == 'submit' && !showSubmit)" (click)="runTask(task)"
                detail="false" button>
                <ion-icon slot="start" name="far-circle" *ngIf="task.completed == null"
                    [attr.aria-label]="'addon.mod_workshop.tasktodo' | translate"></ion-icon>
                <ion-icon slot="start" name="fas-times-circle" color="danger" *ngIf="task.completed == ''"
                    [attr.aria-label]="'addon.mod_workshop.taskfail' | translate"></ion-icon>
                <ion-icon slot="start" name="fas-info-circle" color="info" *ngIf="task.completed == 'info'"
                    [attr.aria-label]="'addon.mod_workshop.taskinfo' | translate"></ion-icon>
                <ion-icon slot="start" name="fas-check-circle" color="success" *ngIf="task.completed == '1'"
                    [attr.aria-label]="'addon.mod_workshop.taskdone' | translate"></ion-icon>
                <ion-label>

{{task.title}}

                </ion-label>
                <ion-icon slot="end" *ngIf="task.link && task.code != 'submit'" name="fas-external-link-alt" aria-hidden="true">
                </ion-icon>
            </ion-item>
        </ng-container>
    </ion-list>
</ion-content>