text:
<?php

namespace muka\OsmParser\Event;

use Symfony\Component\EventDispatcher\Event;

class OsmParserItemEvent extends Event {

    private $currentItem;
    private $currentType;
    private $osmParser;

    public function __construct($currentType, $currentItem, \muka\OsmParser\OsmParser $osmParser)
    {
        $this->currentType = $currentType;
        $this->currentItem = $currentItem;
        $this->osmParser = $osmParser;
    }

    public function getItem()
    {
        return $this->currentItem;
    }

    public function getType()
    {
        return $this->currentType;
    }

    public function getParser()
    {
        return $this->osmParser;
    }

}


text:
[//]: # "This README.md file is auto-generated, all changes to this file will be lost."
[//]: # "To regenerate it, use `python -m synthtool`."
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# [Access Approval: Node.js Samples](https://github.com/googleapis/google-cloud-node)

[![Open in Cloud Shell][shell_img]][shell_link]

## Table of Contents

* [Before you begin](#before-you-begin)
* [Samples](#samples)
  * [Access_approval.approve_approval_request](#access_approval.approve_approval_request)
  * [Access_approval.delete_access_approval_settings](#access_approval.delete_access_approval_settings)
  * [Access_approval.dismiss_approval_request](#access_approval.dismiss_approval_request)
  * [Access_approval.get_access_approval_service_account](#access_approval.get_access_approval_service_account)
  * [Access_approval.get_access_approval_settings](#access_approval.get_access_approval_settings)
  * [Access_approval.get_approval_request](#access_approval.get_approval_request)
  * [Access_approval.invalidate_approval_request](#access_approval.invalidate_approval_request)
  * [Access_approval.list_approval_requests](#access_approval.list_approval_requests)
  * [Access_approval.update_access_approval_settings](#access_approval.update_access_approval_settings)
  * [Quickstart](#quickstart)
  * [Quickstart](#quickstart)

## Before you begin

Before running the samples, make sure you've followed the steps outlined in
[Using the client library](https://github.com/googleapis/google-cloud-node#using-the-client-library).

`cd samples`

`npm install`

`cd ..`

## Samples

### Access_approval.approve_approval_request

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.approve_approval_request.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.approve_approval_request.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.approve_approval_request.js`

-----

### Access_approval.delete_access_approval_settings

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.delete_access_approval_settings.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.delete_access_approval_settings.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.delete_access_approval_settings.js`

-----

### Access_approval.dismiss_approval_request

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.dismiss_approval_request.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.dismiss_approval_request.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.dismiss_approval_request.js`

-----

### Access_approval.get_access_approval_service_account

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_service_account.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_service_account.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_service_account.js`

-----

### Access_approval.get_access_approval_settings

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_settings.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_settings.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_access_approval_settings.js`

-----

### Access_approval.get_approval_request

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_approval_request.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_approval_request.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.get_approval_request.js`

-----

### Access_approval.invalidate_approval_request

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.invalidate_approval_request.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.invalidate_approval_request.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.invalidate_approval_request.js`

-----

### Access_approval.list_approval_requests

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.list_approval_requests.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.list_approval_requests.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.list_approval_requests.js`

-----

### Access_approval.update_access_approval_settings

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/generated/v1/access_approval.update_access_approval_settings.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/generated/v1/access_approval.update_access_approval_settings.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/generated/v1/access_approval.update_access_approval_settings.js`

-----

### Quickstart

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/quickstart.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/quickstart.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/quickstart.js`

-----

### Quickstart

View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-accessapproval/samples/test/quickstart.js).

[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-accessapproval/samples/test/quickstart.js,samples/README.md)

__Usage:__

`node packages/google-cloud-accessapproval/samples/test/quickstart.js`

[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=samples/README.md
[product-docs]: https://cloud.google.com/cloud-provider-access-management/access-approval/docs

redpajama_set_name: RedPajamaGithub


text:
set -eo pipefail

if [[ -z "$CREDENTIALS" ]]; then
  # if CREDENTIALS are explicitly set, assume we're testing locally
  # and don't set NPM_CONFIG_PREFIX.
  export NPM_CONFIG_PREFIX=${HOME}/.npm-global
  export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin"
  cd $(dirname $0)/../..
fi

npm install
npm install --no-save @google-cloud/cloud-rad@^0.2.5
npx @google-cloud/cloud-rad


text:
<?php $this->pageTitle = Yii::app()->getModule('yupe')->siteDescription; ?>

<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider' => $dataProvider,
    'itemView'     => '_view',
    'template'     => "{items}\n{pager}",
)); ?>

<?php $this->widget('application.modules.social.widgets.ysc.yandex.YandexShareApi'); ?>


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection.parallel

import scala.collection.generic.Signalling
import scala.collection.generic.DelegatedSignalling
import scala.collection.generic.IdleSignalling
import scala.collection.mutable.Builder
import scala.collection.GenTraversableOnce
import scala.collection.parallel.immutable.repetition

private[collection] trait RemainsIterator[+T] extends Iterator[T] {
  /** The number of elements this iterator has yet to iterate.
   *  This method doesn't change the state of the iterator.
   */
  def remaining: Int

  /** For most collections, this is a cheap operation.
   *  Exceptions can override this method.
   */
  def isRemainingCheap = true
}

/** Augments iterators with additional methods, mostly transformers,
 *  assuming they iterate an iterable collection.
 *
 *  @tparam T         type of the elements iterated.
 */
private[collection] trait AugmentedIterableIterator[+T] extends RemainsIterator[T] {

  /* accessors */

  override def count(p: T => Boolean): Int = {
    var i = 0
    while (hasNext) if (p(next())) i += 1
    i
  }

  override def reduce[U >: T](op: (U, U) => U): U = {
    var r: U = next()
    while (hasNext) r = op(r, next())
    r
  }

  override def fold[U >: T](z: U)(op: (U, U) => U): U = {
    var r = z
    while (hasNext) r = op(r, next())
    r
  }

  override def sum[U >: T](implicit num: Numeric[U]): U = {
    var r: U = num.zero
    while (hasNext) r = num.plus(r, next())
    r
  }

  override def product[U >: T](implicit num: Numeric[U]): U = {
    var r: U = num.one
    while (hasNext) r = num.times(r, next())
    r
  }

  override def min[U >: T](implicit ord: Ordering[U]): T = {
    var r = next()
    while (hasNext) {
      val curr = next()
      if (ord.lteq(curr, r)) r = curr
    }
    r
  }

  override def max[U >: T](implicit ord: Ordering[U]): T = {
    var r = next()
    while (hasNext) {
      val curr = next()
      if (ord.gteq(curr, r)) r = curr
    }
    r
  }

  override def copyToArray[U >: T](array: Array[U], from: Int, len: Int) {
    var i = from
    val until = from + len
    while (i < until && hasNext) {
      array(i) = next()
      i += 1
    }
  }

  def reduceLeft[U >: T](howmany: Int, op: (U, U) => U): U = {
    var i = howmany - 1
    var u: U = next()
    while (i > 0 && hasNext) {
      u = op(u, next())
      i -= 1
    }
    u
  }

  /* transformers to combiners */

  def map2combiner[S, That](f: T => S, cb: Combiner[S, That]): Combiner[S, That] = {
    //val cb = pbf(repr)
    if (isRemainingCheap) cb.sizeHint(remaining)
    while (hasNext) cb += f(next())
    cb
  }

  def collect2combiner[S, That](pf: PartialFunction[T, S], cb: Combiner[S, That]): Combiner[S, That] = {
    //val cb = pbf(repr)
    val runWith = pf.runWith(cb += _)
    while (hasNext) {
      val curr = next()
      runWith(curr)
    }
    cb
  }

  def flatmap2combiner[S, That](f: T => GenTraversableOnce[S], cb: Combiner[S, That]): Combiner[S, That] = {
    //val cb = pbf(repr)
    while (hasNext) {
      val traversable = f(next()).seq
      if (traversable.isInstanceOf[Iterable[_]]) cb ++= traversable.asInstanceOf[Iterable[S]].iterator
      else cb ++= traversable
    }
    cb
  }

  def copy2builder[U >: T, Coll, Bld <: Builder[U, Coll]](b: Bld): Bld = {
    if (isRemainingCheap) b.sizeHint(remaining)
    while (hasNext) b += next
    b
  }

  def filter2combiner[U >: T, This](pred: T => Boolean, cb: Combiner[U, This]): Combiner[U, This] = {
    while (hasNext) {
      val curr = next()
      if (pred(curr)) cb += curr
    }
    cb
  }

  def filterNot2combiner[U >: T, This](pred: T => Boolean, cb: Combiner[U, This]): Combiner[U, This] = {
    while (hasNext) {
      val curr = next()
      if (!pred(curr)) cb += curr
    }
    cb
  }

  def partition2combiners[U >: T, This](pred: T => Boolean, btrue: Combiner[U, This], bfalse: Combiner[U, This]) = {
    while (hasNext) {
      val curr = next()
      if (pred(curr)) btrue += curr
      else bfalse += curr
    }
    (btrue, bfalse)
  }

  def take2combiner[U >: T, This](n: Int, cb: Combiner[U, This]): Combiner[U, This] = {
    cb.sizeHint(n)
    var left = n
    while (left > 0) {
      cb += next
      left -= 1
    }
    cb
  }

  def drop2combiner[U >: T, This](n: Int, cb: Combiner[U, This]): Combiner[U, This] = {
    drop(n)
    if (isRemainingCheap) cb.sizeHint(remaining)
    while (hasNext) cb += next
    cb
  }

  def slice2combiner[U >: T, This](from: Int, until: Int, cb: Combiner[U, This]): Combiner[U, This] = {
    drop(from)
    var left = scala.math.max(until - from, 0)
    cb.sizeHint(left)
    while (left > 0) {
      cb += next
      left -= 1
    }
    cb
  }

  def splitAt2combiners[U >: T, This](at: Int, before: Combiner[U, This], after: Combiner[U, This]) = {
    before.sizeHint(at)
    if (isRemainingCheap) after.sizeHint(remaining - at)
    var left = at
    while (left > 0) {
      before += next
      left -= 1
    }
    while (hasNext) after += next
    (before, after)
  }

  def takeWhile2combiner[U >: T, This](p: T => Boolean, cb: Combiner[U, This]) = {
    var loop = true
    while (hasNext && loop) {
      val curr = next()
      if (p(curr)) cb += curr
      else loop = false
    }
    (cb, loop)
  }

  def span2combiners[U >: T, This](p: T => Boolean, before: Combiner[U, This], after: Combiner[U, This]) = {
    var isBefore = true
    while (hasNext && isBefore) {
      val curr = next()
      if (p(curr)) before += curr
      else {
        if (isRemainingCheap) after.sizeHint(remaining + 1)
        after += curr
        isBefore = false
      }
    }
    while (hasNext) after += next
    (before, after)
  }

  def scanToArray[U >: T, A >: U](z: U, op: (U, U) => U, array: Array[A], from: Int) {
    var last = z
    var i = from
    while (hasNext) {
      last = op(last, next())
      array(i) = last
      i += 1
    }
  }

  def scanToCombiner[U >: T, That](startValue: U, op: (U, U) => U, cb: Combiner[U, That]) = {
    var curr = startValue
    while (hasNext) {
      curr = op(curr, next())
      cb += curr
    }
    cb
  }

  def scanToCombiner[U >: T, That](howmany: Int, startValue: U, op: (U, U) => U, cb: Combiner[U, That]) = {
    var curr = startValue
    var left = howmany
    while (left > 0) {
      curr = op(curr, next())
      cb += curr
      left -= 1
    }
    cb
  }

  def zip2combiner[U >: T, S, That](otherpit: RemainsIterator[S], cb: Combiner[(U, S), That]): Combiner[(U, S), That] = {
    if (isRemainingCheap && otherpit.isRemainingCheap) cb.sizeHint(remaining min otherpit.remaining)
    while (hasNext && otherpit.hasNext) {
      cb += ((next(), otherpit.next()))
    }
    cb
  }

  def zipAll2combiner[U >: T, S, That](that: RemainsIterator[S], thiselem: U, thatelem: S, cb: Combiner[(U, S), That]): Combiner[(U, S), That] = {
    if (isRemainingCheap && that.isRemainingCheap) cb.sizeHint(remaining max that.remaining)
    while (this.hasNext && that.hasNext) cb += ((this.next(), that.next()))
    while (this.hasNext) cb += ((this.next(), thatelem))
    while (that.hasNext) cb += ((thiselem, that.next()))
    cb
  }

}

private[collection] trait AugmentedSeqIterator[+T] extends AugmentedIterableIterator[T] {

  /** The exact number of elements this iterator has yet to iterate.
   *  This method doesn't change the state of the iterator.
   */
  def remaining: Int

  /* accessors */

  def prefixLength(pred: T => Boolean): Int = {
    var total = 0
    var loop = true
    while (hasNext && loop) {
      if (pred(next())) total += 1
      else loop = false
    }
    total
  }

  override def indexWhere(pred: T => Boolean): Int = {
    var i = 0
    var loop = true
    while (hasNext && loop) {
      if (pred(next())) loop = false
      else i += 1
    }
    if (loop) -1 else i
  }

  def lastIndexWhere(pred: T => Boolean): Int = {
    var pos = -1
    var i = 0
    while (hasNext) {
      if (pred(next())) pos = i
      i += 1
    }
    pos
  }

  def corresponds[S](corr: (T, S) => Boolean)(that: Iterator[S]): Boolean = {
    while (hasNext && that.hasNext) {
      if (!corr(next(), that.next())) return false
    }
    hasNext == that.hasNext
  }

  /* transformers */

  def reverse2combiner[U >: T, This](cb: Combiner[U, This]): Combiner[U, This] = {
    if (isRemainingCheap) cb.sizeHint(remaining)
    var lst = List[T]()
    while (hasNext) lst ::= next
    while (lst != Nil) {
      cb += lst.head
      lst = lst.tail
    }
    cb
  }

  def reverseMap2combiner[S, That](f: T => S, cb: Combiner[S, That]): Combiner[S, That] = {
    //val cb = cbf(repr)
    if (isRemainingCheap) cb.sizeHint(remaining)
    var lst = List[S]()
    while (hasNext) lst ::= f(next())
    while (lst != Nil) {
      cb += lst.head
      lst = lst.tail
    }
    cb
  }

  def updated2combiner[U >: T, That](index: Int, elem: U, cb: Combiner[U, That]): Combiner[U, That] = {
    //val cb = cbf(repr)
    if (isRemainingCheap) cb.sizeHint(remaining)
    var j = 0
    while (hasNext) {
      if (j == index) {
        cb += elem
        next()
      } else cb += next
      j += 1
    }
    cb
  }

}

/** Parallel iterators allow splitting and provide a `remaining` method to
 *  obtain the number of elements remaining in the iterator.
 *
 *  @tparam T          type of the elements iterated.
 */
trait IterableSplitter[+T]
extends AugmentedIterableIterator[T]
   with Splitter[T]
   with Signalling
   with DelegatedSignalling
{
self =>

  var signalDelegate: Signalling = IdleSignalling

  /** Creates a copy of this iterator. */
  def dup: IterableSplitter[T]

  def split: Seq[IterableSplitter[T]]

  def splitWithSignalling: Seq[IterableSplitter[T]] = {
    val pits = split
    pits foreach { _.signalDelegate = signalDelegate }
    pits
  }

  def shouldSplitFurther[S](coll: ParIterable[S], parallelismLevel: Int) = remaining > thresholdFromSize(coll.size, parallelismLevel)

  /** The number of elements this iterator has yet to traverse. This method
   *  doesn't change the state of the iterator.
   *
   *  This method is used to provide size hints to builders and combiners, and
   *  to approximate positions of iterators within a data structure.
   *
   *  '''Note''': This method may be implemented to return an upper bound on the number of elements
   *  in the iterator, instead of the exact number of elements to iterate.
   *  Parallel collections which have such iterators are called non-strict-splitter collections.
   *
   *  In that case, 2 considerations must be taken into account:
   *
   *    1) classes that inherit `ParIterable` must reimplement methods `take`, `drop`, `slice`, `splitAt`, `copyToArray`
   *       and all others using this information.
   *
   *    2) if an iterator provides an upper bound on the number of elements, then after splitting the sum
   *       of `remaining` values of split iterators must be less than or equal to this upper bound.
   */
  def remaining: Int

  protected def buildString(closure: (String => Unit) => Unit): String = {
    var output = ""
    def appendln(s: String) = output += s + "\n"
    closure(appendln)
    output
  }

  private[parallel] def debugInformation = {
    // can be overridden in subclasses
    "Parallel iterator: " + this.getClass
  }

  /* iterator transformers */

  class Taken(taken: Int) extends IterableSplitter[T] {
    var remaining = taken min self.remaining
    def hasNext = remaining > 0
    def next = { remaining -= 1; self.next() }
    def dup: IterableSplitter[T] = self.dup.take(taken)
    def split: Seq[IterableSplitter[T]] = takeSeq(self.split) { (p, n) => p.take(n) }
    protected[this] def takeSeq[PI <: IterableSplitter[T]](sq: Seq[PI])(taker: (PI, Int) => PI) = {
      val sizes = sq.scanLeft(0)(_ + _.remaining)
      val shortened = for ((it, (from, until)) <- sq zip (sizes.init zip sizes.tail)) yield
        if (until < remaining) it else taker(it, remaining - from)
      shortened filter { _.remaining > 0 }
    }
  }
  /** To lower "virtual class" boilerplate tax, implement creation
   *  in method and override this method in the subclass.
   */
  private[collection] def newTaken(until: Int): Taken = new Taken(until)
  private[collection] def newSliceInternal[U <: Taken](it: U, from1: Int): U = {
    var count = from1
    while (count > 0 && it.hasNext) {
      it.next
      count -= 1
    }
    it
  }
  /** Drop implemented as simple eager consumption. */
  override def drop(n: Int): IterableSplitter[T] = {
    var i = 0
    while (i < n && hasNext) {
      next()
      i += 1
    }
    this
  }
  override def take(n: Int): IterableSplitter[T] = newTaken(n)
  override def slice(from1: Int, until1: Int): IterableSplitter[T] = newSliceInternal(newTaken(until1), from1)

  class Mapped[S](f: T => S) extends IterableSplitter[S] {
    signalDelegate = self.signalDelegate
    def hasNext = self.hasNext
    def next = f(self.next())
    def remaining = self.remaining
    def dup: IterableSplitter[S] = self.dup map f
    def split: Seq[IterableSplitter[S]] = self.split.map { _ map f }
  }

  override def map[S](f: T => S) = new Mapped(f)

  class Appended[U >: T, PI <: IterableSplitter[U]](protected val that: PI) extends IterableSplitter[U] {
    signalDelegate = self.signalDelegate
    protected var curr: IterableSplitter[U] = self
    def hasNext = if (curr.hasNext) true else if (curr eq self) {
      curr = that
      curr.hasNext
    } else false
    def next = if (curr eq self) {
      hasNext
      curr.next()
    } else curr.next()
    def remaining = if (curr eq self) curr.remaining + that.remaining else curr.remaining
    protected def firstNonEmpty = (curr eq self) && curr.hasNext
    def dup: IterableSplitter[U] = self.dup.appendParIterable[U, PI](that)
    def split: Seq[IterableSplitter[U]] = if (firstNonEmpty) Seq(curr, that) else curr.split
  }

  def appendParIterable[U >: T, PI <: IterableSplitter[U]](that: PI) = new Appended[U, PI](that)

  class Zipped[S](protected val that: SeqSplitter[S]) extends IterableSplitter[(T, S)] {
    signalDelegate = self.signalDelegate
    def hasNext = self.hasNext && that.hasNext
    def next = (self.next(), that.next())
    def remaining = self.remaining min that.remaining
    def dup: IterableSplitter[(T, S)] = self.dup.zipParSeq(that)
    def split: Seq[IterableSplitter[(T, S)]] = {
      val selfs = self.split
      val sizes = selfs.map(_.remaining)
      val thats = that.psplit(sizes: _*)
      (selfs zip thats) map { p => p._1 zipParSeq p._2 }
    }
  }

  def zipParSeq[S](that: SeqSplitter[S]) = new Zipped(that)

  class ZippedAll[U >: T, S](protected val that: SeqSplitter[S], protected val thiselem: U, protected val thatelem: S)
  extends IterableSplitter[(U, S)] {
    signalDelegate = self.signalDelegate
    def hasNext = self.hasNext || that.hasNext
    def next = if (self.hasNext) {
      if (that.hasNext) (self.next(), that.next())
      else (self.next(), thatelem)
    } else (thiselem, that.next())

    def remaining = self.remaining max that.remaining
    def dup: IterableSplitter[(U, S)] = self.dup.zipAllParSeq(that, thiselem, thatelem)
    def split: Seq[IterableSplitter[(U, S)]] = {
      val selfrem = self.remaining
      val thatrem = that.remaining
      val thisit = if (selfrem < thatrem) self.appendParIterable[U, SeqSplitter[U]](repetition[U](thiselem, thatrem - selfrem).splitter) else self
      val thatit = if (selfrem > thatrem) that.appendParSeq(repetition(thatelem, selfrem - thatrem).splitter) else that
      val zipped = thisit zipParSeq thatit
      zipped.split
    }
  }

  def zipAllParSeq[S, U >: T, R >: S](that: SeqSplitter[S], thisElem: U, thatElem: R) = new ZippedAll[U, R](that, thisElem, thatElem)
}

/** Parallel sequence iterators allow splitting into arbitrary subsets.
 *
 *  @tparam T          type of the elements iterated.
 */
trait SeqSplitter[+T]
extends IterableSplitter[T]
   with AugmentedSeqIterator[T]
   with PreciseSplitter[T]
{
self =>
  def dup: SeqSplitter[T]
  def split: Seq[SeqSplitter[T]]
  def psplit(sizes: Int*): Seq[SeqSplitter[T]]

  override def splitWithSignalling: Seq[SeqSplitter[T]] = {
    val pits = split
    pits foreach { _.signalDelegate = signalDelegate }
    pits
  }

  def psplitWithSignalling(sizes: Int*): Seq[SeqSplitter[T]] = {
    val pits = psplit(sizes: _*)
    pits foreach { _.signalDelegate = signalDelegate }
    pits
  }

  /** The number of elements this iterator has yet to traverse. This method
   *  doesn't change the state of the iterator. Unlike the version of this method in the supertrait,
   *  method `remaining` in `ParSeqLike.this.ParIterator` must return an exact number
   *  of elements remaining in the iterator.
   *
   *  @return   an exact number of elements this iterator has yet to iterate
   */
  def remaining: Int

  /* iterator transformers */

  class Taken(tk: Int) extends super.Taken(tk) with SeqSplitter[T] {
    override def dup = super.dup.asInstanceOf[SeqSplitter[T]]
    override def split: Seq[SeqSplitter[T]] = super.split.asInstanceOf[Seq[SeqSplitter[T]]]
    def psplit(sizes: Int*): Seq[SeqSplitter[T]] = takeSeq(self.psplit(sizes: _*)) { (p, n) => p.take(n) }
  }
  override private[collection] def newTaken(until: Int): Taken = new Taken(until)
  override def take(n: Int): SeqSplitter[T] = newTaken(n)
  override def slice(from1: Int, until1: Int): SeqSplitter[T] = newSliceInternal(newTaken(until1), from1)

  class Mapped[S](f: T => S) extends super.Mapped[S](f) with SeqSplitter[S] {
    override def dup = super.dup.asInstanceOf[SeqSplitter[S]]
    override def split: Seq[SeqSplitter[S]] = super.split.asInstanceOf[Seq[SeqSplitter[S]]]
    def psplit(sizes: Int*): Seq[SeqSplitter[S]] = self.psplit(sizes: _*).map { _ map f }
  }

  override def map[S](f: T => S) = new Mapped(f)

  class Appended[U >: T, PI <: SeqSplitter[U]](it: PI) extends super.Appended[U, PI](it) with SeqSplitter[U] {
    override def dup = super.dup.asInstanceOf[SeqSplitter[U]]
    override def split: Seq[SeqSplitter[U]] = super.split.asInstanceOf[Seq[SeqSplitter[U]]]
    def psplit(sizes: Int*): Seq[SeqSplitter[U]] = if (firstNonEmpty) {
      val selfrem = self.remaining

      // split sizes
      var appendMiddle = false
      val szcum = sizes.scanLeft(0)(_ + _)
      val splitsizes = sizes.zip(szcum.init zip szcum.tail).flatMap { t =>
        val (sz, (from, until)) = t
        if (from < selfrem && until > selfrem) {
          appendMiddle = true
          Seq(selfrem - from, until - selfrem)
        } else Seq(sz)
      }
      val (selfszfrom, thatszfrom) = splitsizes.zip(szcum.init).span(_._2 < selfrem)
      val (selfsizes, thatsizes) = (selfszfrom map { _._1 }, thatszfrom map { _._1 })

      // split iterators
      val selfs = self.psplit(selfsizes: _*)
      val thats = that.psplit(thatsizes: _*)

      // appended last in self with first in rest if necessary
      if (appendMiddle) selfs.init ++ Seq(selfs.last.appendParSeq[U, SeqSplitter[U]](thats.head)) ++ thats.tail
      else selfs ++ thats
    } else curr.asInstanceOf[SeqSplitter[U]].psplit(sizes: _*)
  }

  def appendParSeq[U >: T, PI <: SeqSplitter[U]](that: PI) = new Appended[U, PI](that)

  class Zipped[S](ti: SeqSplitter[S]) extends super.Zipped[S](ti) with SeqSplitter[(T, S)] {
    override def dup = super.dup.asInstanceOf[SeqSplitter[(T, S)]]
    override def split: Seq[SeqSplitter[(T, S)]] = super.split.asInstanceOf[Seq[SeqSplitter[(T, S)]]]
    def psplit(szs: Int*) = (self.psplit(szs: _*) zip that.psplit(szs: _*)) map { p => p._1 zipParSeq p._2 }
  }

  override def zipParSeq[S](that: SeqSplitter[S]) = new Zipped(that)

  class ZippedAll[U >: T, S](ti: SeqSplitter[S], thise: U, thate: S) extends super.ZippedAll[U, S](ti, thise, thate) with SeqSplitter[(U, S)] {
    override def dup = super.dup.asInstanceOf[SeqSplitter[(U, S)]]
    private def patchem = {
      val selfrem = self.remaining
      val thatrem = that.remaining
      val thisit = if (selfrem < thatrem) self.appendParSeq[U, SeqSplitter[U]](repetition[U](thiselem, thatrem - selfrem).splitter) else self
      val thatit = if (selfrem > thatrem) that.appendParSeq(repetition(thatelem, selfrem - thatrem).splitter) else that
      (thisit, thatit)
    }
    override def split: Seq[SeqSplitter[(U, S)]] = {
      val (thisit, thatit) = patchem
      val zipped = thisit zipParSeq thatit
      zipped.split
    }
    def psplit(sizes: Int*): Seq[SeqSplitter[(U, S)]] = {
      val (thisit, thatit) = patchem
      val zipped = thisit zipParSeq thatit
      zipped.psplit(sizes: _*)
    }
  }

  override def zipAllParSeq[S, U >: T, R >: S](that: SeqSplitter[S], thisElem: U, thatElem: R) = new ZippedAll[U, R](that, thisElem, thatElem)

  def reverse: SeqSplitter[T] = {
    val pa = mutable.ParArray.fromTraversables(self).reverse
    new pa.ParArrayIterator {
      override def reverse = self
    }
  }

  class Patched[U >: T](from: Int, patch: SeqSplitter[U], replaced: Int) extends SeqSplitter[U] {
    signalDelegate = self.signalDelegate
    private[this] val trio = {
      val pits = self.psplit(from, replaced, self.remaining - from - replaced)
      (pits(0).appendParSeq[U, SeqSplitter[U]](patch)) appendParSeq pits(2)
    }
    def hasNext = trio.hasNext
    def next = trio.next
    def remaining = trio.remaining
    def dup = self.dup.patchParSeq(from, patch, replaced)
    def split = trio.split
    def psplit(sizes: Int*) = trio.psplit(sizes: _*)
  }

  def patchParSeq[U >: T](from: Int, patchElems: SeqSplitter[U], replaced: Int) = new Patched(from, patchElems, replaced)

}


text:
package org.bouncycastle.pqc.crypto.xmss;

import java.security.SecureRandom;
import java.text.ParseException;

import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.util.Arrays;

/**
 * XMSS.
 */
public class XMSS
{

    /**
     * XMSS parameters.
     */
    private final XMSSParameters params;
    /**
     * WOTS+ instance.
     */
    private WOTSPlus wotsPlus;
    /**
     * PRNG.
     */
    private SecureRandom prng;

    /**
     * XMSS private key.
     */
    private XMSSPrivateKeyParameters privateKey;
    /**
     * XMSS public key.
     */
    private XMSSPublicKeyParameters publicKey;

    /**
     * XMSS constructor...
     *
     * @param params XMSSParameters.
     */
    public XMSS(XMSSParameters params, SecureRandom prng)
    {
        super();
        if (params == null)
        {
            throw new NullPointerException("params == null");
        }
        this.params = params;
        wotsPlus = params.getWOTSPlus();
        this.prng = prng;
    }

//    public void generateKeys()
//    {
//        /* generate private key */
//        privateKey = generatePrivateKey(params, prng);
//        XMSSNode root = privateKey.getBDSState().initialize(privateKey, (OTSHashAddress)new OTSHashAddress.Builder().build());
//
//        privateKey = new XMSSPrivateKeyParameters.Builder(params).withIndex(privateKey.getIndex())
//            .withSecretKeySeed(privateKey.getSecretKeySeed()).withSecretKeyPRF(privateKey.getSecretKeyPRF())
//            .withPublicSeed(privateKey.getPublicSeed()).withRoot(root.getValue())
//            .withBDSState(privateKey.getBDSState()).build();
//        publicKey = new XMSSPublicKeyParameters.Builder(params).withRoot(root.getValue())
//            .withPublicSeed(getPublicSeed()).build();
//
//    }
//
//    /**
//     * Generate an XMSS private key.
//     *
//     * @return XMSS private key.
//     */
//    private XMSSPrivateKeyParameters generatePrivateKey(XMSSParameters params, SecureRandom prng)
//    {
//        int n = params.getDigestSize();
//        byte[] secretKeySeed = new byte[n];
//        prng.nextBytes(secretKeySeed);
//        byte[] secretKeyPRF = new byte[n];
//        prng.nextBytes(secretKeyPRF);
//        byte[] publicSeed = new byte[n];
//        prng.nextBytes(publicSeed);
//
//        XMSS xmss = new XMSS(params, prng);
//
////        this.privateKey = xmss.privateKey;
////        this.publicKey = xmss.publicKey;
////        this.wotsPlus = xmss.wotsPlus;
////        this.khf = xmss.khf;
//
//        XMSSPrivateKeyParameters privateKey = new XMSSPrivateKeyParameters.Builder(params).withSecretKeySeed(secretKeySeed)
//            .withSecretKeyPRF(secretKeyPRF).withPublicSeed(publicSeed)
//            .withBDSState(new BDS(xmss)).build();
//
//        return privateKey;
//    }

    /**
     * Generate a new XMSS private key / public key pair.
     */
    public void generateKeys()
    {
        XMSSKeyPairGenerator kpGen = new XMSSKeyPairGenerator();

        kpGen.init(new XMSSKeyGenerationParameters(getParams(), prng));

        AsymmetricCipherKeyPair kp = kpGen.generateKeyPair();

        privateKey = (XMSSPrivateKeyParameters)kp.getPrivate();
        publicKey = (XMSSPublicKeyParameters)kp.getPublic();

        wotsPlus.importKeys(new byte[params.getTreeDigestSize()], this.privateKey.getPublicSeed());
    }

    public void importState(XMSSPrivateKeyParameters privateKey, XMSSPublicKeyParameters publicKey)
    {
        if (!Arrays.areEqual(privateKey.getRoot(), publicKey.getRoot()))
        {
            throw new IllegalStateException("root of private key and public key do not match");
        }
        if (!Arrays.areEqual(privateKey.getPublicSeed(), publicKey.getPublicSeed()))
        {
            throw new IllegalStateException("public seed of private key and public key do not match");
        }
        /* import */
        this.privateKey = privateKey;
        this.publicKey = publicKey;

        wotsPlus.importKeys(new byte[params.getTreeDigestSize()], this.privateKey.getPublicSeed());
    }

    /**
     * Import XMSS private key / public key pair.
     *
     * @param privateKey XMSS private key.
     * @param publicKey  XMSS public key.
     */
    public void importState(byte[] privateKey, byte[] publicKey)
    {
        if (privateKey == null)
        {
            throw new NullPointerException("privateKey == null");
        }
        if (publicKey == null)
        {
            throw new NullPointerException("publicKey == null");
        }
        /* import keys */
        XMSSPrivateKeyParameters tmpPrivateKey = new XMSSPrivateKeyParameters.Builder(params)
            .withPrivateKey(privateKey).build();
        XMSSPublicKeyParameters tmpPublicKey = new XMSSPublicKeyParameters.Builder(params).withPublicKey(publicKey)
            .build();
        if (!Arrays.areEqual(tmpPrivateKey.getRoot(), tmpPublicKey.getRoot()))
        {
            throw new IllegalStateException("root of private key and public key do not match");
        }
        if (!Arrays.areEqual(tmpPrivateKey.getPublicSeed(), tmpPublicKey.getPublicSeed()))
        {
            throw new IllegalStateException("public seed of private key and public key do not match");
        }
        /* import */
        this.privateKey = tmpPrivateKey;
        this.publicKey = tmpPublicKey;
        wotsPlus.importKeys(new byte[params.getTreeDigestSize()], this.privateKey.getPublicSeed());
    }

    /**
     * Sign message.
     *
     * @param message Message to sign.
     * @return XMSS signature on digest of message.
     */
    public byte[] sign(byte[] message)
    {
        if (message == null)
        {
            throw new NullPointerException("message == null");
        }
        XMSSSigner signer = new XMSSSigner();

        signer.init(true, privateKey);

        byte[] signature = signer.generateSignature(message);

        privateKey = (XMSSPrivateKeyParameters)signer.getUpdatedPrivateKey();

        importState(privateKey, publicKey);

        return signature;
    }

    /**
     * Verify an XMSS signature.
     *
     * @param message   Message.
     * @param signature XMSS signature.
     * @param publicKey XMSS public key.
     * @return true if signature is valid false else.
     * @throws ParseException
     */
    public boolean verifySignature(byte[] message, byte[] signature, byte[] publicKey)
        throws ParseException
    {
        if (message == null)
        {
            throw new NullPointerException("message == null");
        }
        if (signature == null)
        {
            throw new NullPointerException("signature == null");
        }
        if (publicKey == null)
        {
            throw new NullPointerException("publicKey == null");
        }

        XMSSSigner signer = new XMSSSigner();

        signer.init(false, new XMSSPublicKeyParameters.Builder(getParams()).withPublicKey(publicKey).build());

        return signer.verifySignature(message, signature);
    }

    /**
     * Export XMSS private key.
     *
     * @return XMSS private key.
     */
    public XMSSPrivateKeyParameters exportPrivateKey()
    {
        return privateKey;
    }

    /**
     * Export XMSS public key.
     *
     * @return XMSS public key.
     */
    public XMSSPublicKeyParameters exportPublicKey()
    {
        return publicKey;
    }

    /**
     * Generate a WOTS+ signature on a message without the corresponding
     * authentication path
     *
     * @param messageDigest  Message digest of length n.
     * @param otsHashAddress OTS hash address.
     * @return XMSS signature.
     */
    protected WOTSPlusSignature wotsSign(byte[] messageDigest, OTSHashAddress otsHashAddress)
    {
        if (messageDigest.length != params.getTreeDigestSize())
        {
            throw new IllegalArgumentException("size of messageDigest needs to be equal to size of digest");
        }
        if (otsHashAddress == null)
        {
            throw new NullPointerException("otsHashAddress == null");
        }
        /* (re)initialize WOTS+ instance */
        wotsPlus.importKeys(wotsPlus.getWOTSPlusSecretKey(privateKey.getSecretKeySeed(), otsHashAddress), getPublicSeed());
        /* create WOTS+ signature */
        return wotsPlus.sign(messageDigest, otsHashAddress);
    }

    /**
     * Getter XMSS params.
     *
     * @return XMSS params.
     */
    public XMSSParameters getParams()
    {
        return params;
    }

    /**
     * Getter WOTS+.
     *
     * @return WOTS+ instance.
     */
    protected WOTSPlus getWOTSPlus()
    {
        return wotsPlus;
    }

    /**
     * Getter XMSS root.
     *
     * @return Root of binary tree.
     */
    public byte[] getRoot()
    {
        return privateKey.getRoot();
    }

    protected void setRoot(byte[] root)
    {
        privateKey = new XMSSPrivateKeyParameters.Builder(params)
            .withSecretKeySeed(privateKey.getSecretKeySeed()).withSecretKeyPRF(privateKey.getSecretKeyPRF())
            .withPublicSeed(getPublicSeed()).withRoot(root).withBDSState(privateKey.getBDSState()).build();
        publicKey = new XMSSPublicKeyParameters.Builder(params).withRoot(root).withPublicSeed(getPublicSeed())
            .build();
    }

    /**
     * Getter XMSS index.
     *
     * @return Index.
     */
    public int getIndex()
    {
        return privateKey.getIndex();
    }

    protected void setIndex(int index)
    {
        privateKey = new XMSSPrivateKeyParameters.Builder(params)
            .withSecretKeySeed(privateKey.getSecretKeySeed()).withSecretKeyPRF(privateKey.getSecretKeyPRF())
            .withPublicSeed(privateKey.getPublicSeed()).withRoot(privateKey.getRoot())
            .withBDSState(privateKey.getBDSState()).build();
    }

    /**
     * Getter XMSS public seed.
     *
     * @return Public seed.
     */
    public byte[] getPublicSeed()
    {
        return privateKey.getPublicSeed();
    }

    protected void setPublicSeed(byte[] publicSeed)
    {
        privateKey = new XMSSPrivateKeyParameters.Builder(params)
            .withSecretKeySeed(privateKey.getSecretKeySeed()).withSecretKeyPRF(privateKey.getSecretKeyPRF())
            .withPublicSeed(publicSeed).withRoot(getRoot()).withBDSState(privateKey.getBDSState()).build();
        publicKey = new XMSSPublicKeyParameters.Builder(params).withRoot(getRoot()).withPublicSeed(publicSeed)
            .build();

        wotsPlus.importKeys(new byte[params.getTreeDigestSize()], publicSeed);
    }

    public XMSSPrivateKeyParameters getPrivateKey()
    {
        return privateKey;
    }
}


text:
'use strict';

/**
 * nutrientCalculator/cowsPurchased singleton
 * @module nutrientCalculator/cowsPurchased
 */
angular.module('farmbuild.nutrientCalculator')

	.factory('cowsPurchased',
  function (validations,
            cowTypeDefaults,
            cowValidator,
            cowTypes,
            cows,
            nutrientCalculatorSession
    ) {

		var cowsPurchased = {},
			_isPositiveNumber = validations.isPositiveNumber,
			_isAlphanumeric = validations.isAlphanumeric,
			_isDefined = validations.isDefined,
			_types = angular.copy(cowTypeDefaults),
      _cows = [],
      validator = cowValidator;

    cowsPurchased.validateNew = cows.validateNew;

		/**
		 * Calculates total nutrient imported on to the farm in cows
		 * @method calculate
		 * @param {!array} cows - Array of purchased cows, each item contains details of the cow {type{name, weight}, numberOfCows}
		 * @returns {object} nutrient data of cows purchased
		 * @public
		 * @static
		 */
		cowsPurchased.calculate = function (cows) {
			var numberOfCows = 0,
				weight = 0,
				nitrogenInKg = 0,
				phosphorusInKg = 0,
				potassiumInKg = 0,
				sulphurInKg = 0,
				nitrogenPercentage = 2.8,
				phosphorusPercentage = 0.72,
				potassiumPercentage = 0.2,
				sulphurPercentage = 0.8,
				incomings = [],
				i = 0;

			if (!cows || cows.length === 0) {
				return undefined;
			}

			for (i; i < cows.length; i++) {
				var cowWeight,
					cowCount,
					cow = cows[i];

				if (!cow.name || !cow.weight) {
					return undefined;
				}

				cowWeight = cow.weight;
				cowCount = cow.numberOfCows;

				if (!_isPositiveNumber(cowCount)) {
					return undefined;
				}

				weight += cowWeight * cowCount;
				numberOfCows += cowCount;
				nitrogenInKg += (nitrogenPercentage * cowWeight * cowCount) / 100;
				phosphorusInKg += (phosphorusPercentage * cowWeight * cowCount) / 100;
				potassiumInKg += (potassiumPercentage * cowWeight * cowCount) / 100;
				sulphurInKg += (sulphurPercentage * cowWeight * cowCount) / 100;
				incomings.push({
					name: cow.name,
					numberOfCows: cowCount,
					weight: cow.weight
				});
			}

      var result =  {
				cows: incomings,
				numberOfCows: numberOfCows,
				weight: weight,
				nitrogenInKg: nitrogenInKg,
				phosphorusInKg: phosphorusInKg,
				potassiumInKg: potassiumInKg,
				sulphurInKg: sulphurInKg
			};

      result.types = _types;

      nutrientCalculatorSession.saveSection('cowsPurchased', result);

      return result;
		};

		/**
		 * Adds a new cow type for nutrient calculation
		 * @method addType
		 * @param {!string} name - name of new type, can only contain alphanumeric values with space or underscore but no other special characters
		 * @param {!number} weight - average weight of this type in Kg, value must be > 0
		 * @returns {object} cowsPurchased - useful for chaining multiple add()
		 * @public
		 * @static
		 */
		cowsPurchased.addType = function (name, weight) {
			if (!_isPositiveNumber(weight)) {
				return undefined;
			}

			if (!name || !_isAlphanumeric(name)) {
				return undefined;
			}

			weight = parseFloat(weight);

			_types.push({
				name: name,
				weight: weight
			});

			return cowsPurchased;
		};

				/**
		 * Remove cow(s) with this name from cow types, if there is duplicate in naming all of them would be removed
		 * @method removeTypeByName
		 * @param {!String} name - name of the type you want to remove.
		 * @returns {Object} CowsCulled - useful for chaining functions
		 * @public
		 * @static
		 */
		cowsPurchased.removeTypeByName = function (name) {

			if (!name) {
				return undefined;
			}

			angular.forEach(_types, function(type, i){
				if(type.name === name){
					_types.splice(i, 1);
				}
			});

			return _types;
		};

		/**
		 * Remove this cow from cow types
		 * @method removeTypeByIndex
		 * @param {!String} index - index (starts from 0) of the type you want to remove in types Array
		 * @returns {Object} CowsCulled - useful for chaining functions
		 * @public
		 * @static
		 */
		cowsPurchased.removeTypeByIndex = function (index) {

			if (!_isDefined(index) || index < 0 || index > _types.length-1) {
				return undefined;
			}

			_types.splice(index, 1);

			return _types;
		};

		/**
		 * Returns current cow types
		 * @method types
		 * @returns {object} Types - cow types array
		 * @public
		 * @static
		 */
		cowsPurchased.types = function () {
			return _types;
		};

    cowsPurchased.validateType = function (type) {
      return cowTypes.validate(type);
    };

    /**
     * Returns current cows
     * @method cows
     * @returns {object} Cows - cows array
     * @public
     * @static
     */
    cowsPurchased.cows = function () {
      return _cows;
    };

    /**
     * Loads the fertilizers in cowsPurchasedSection.fertilizers
     * @method load
     * @param cowsPurchasedSection
     * @returns {object} cowsPurchased
     * @public
     * @static
     */
    cowsPurchased.load = function(cowsPurchasedSection) {
      if(!validator.validateAll(cowsPurchasedSection.cows)) {
        return undefined
      }
      _cows = cowsPurchasedSection.cows;
      _types = cowsPurchasedSection.types;

      return cowsPurchased;
    }

		return cowsPurchased;

	});


text:
package org.onosproject.store.service;

import com.google.common.base.MoreObjects;

/**
 * Statistics for a {@link WorkQueue}.
 */
public final class WorkQueueStats {

    private long totalPending;
    private long totalInProgress;
    private long totalCompleted;

    /**
     * Returns a {@code WorkQueueStats} builder.
     * @return builder
     */
    public static Builder builder() {
        return new Builder();
    }

    private WorkQueueStats() {
    }

    public static class Builder {

        WorkQueueStats workQueueStats = new WorkQueueStats();

        public Builder withTotalPending(long value) {
            workQueueStats.totalPending = value;
            return this;
        }

        public Builder withTotalInProgress(long value) {
            workQueueStats.totalInProgress = value;
            return this;
        }

        public Builder withTotalCompleted(long value) {
            workQueueStats.totalCompleted = value;
            return this;
        }

        public WorkQueueStats build() {
            return workQueueStats;
        }
    }

    /**
     * Returns the total pending tasks. These are the tasks that are added but not yet picked up.
     * @return total pending tasks.
     */
    public long totalPending() {
        return this.totalPending;
    }

    /**
     * Returns the total in progress tasks. These are the tasks that are currently being worked on.
     * @return total in progress tasks.
     */
    public long totalInProgress() {
        return this.totalInProgress;
    }

    /**
     * Returns the total completed tasks.
     * @return total completed tasks.
     */
    public long totalCompleted() {
        return this.totalCompleted;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("totalPending", totalPending)
                .add("totalInProgress", totalInProgress)
                .add("totalCompleted", totalCompleted)
                .toString();
    }
}


text:
package org.compass.core.xml.jdom.converter.support;

import java.util.HashMap;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.jdom.Attribute;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMFactory;
import org.jdom.Namespace;
import org.jdom.UncheckedJDOMFactory;

/**
 * Builds a JDOM {@link org.jdom.Document org.jdom.Document} using a
 * {@link javax.xml.stream.XMLStreamReader}.
 *
 * @author kimchy
 */
public class StAXBuilder {

    /**
     * Map that contains conversion from textual attribute types StAX uses,
     * to int values JDOM uses.
     */
    final static HashMap<String, Integer> attrTypes = new HashMap<String, Integer>(32);

    static {
        attrTypes.put("CDATA", Attribute.CDATA_TYPE);
        attrTypes.put("cdata", Attribute.CDATA_TYPE);
        attrTypes.put("ID", Attribute.ID_TYPE);
        attrTypes.put("id", Attribute.ID_TYPE);
        attrTypes.put("IDREF", Attribute.IDREF_TYPE);
        attrTypes.put("idref", Attribute.IDREF_TYPE);
        attrTypes.put("IDREFS", Attribute.IDREFS_TYPE);
        attrTypes.put("idrefs", Attribute.IDREFS_TYPE);
        attrTypes.put("ENTITY", Attribute.ENTITY_TYPE);
        attrTypes.put("entity", Attribute.ENTITY_TYPE);
        attrTypes.put("ENTITIES", Attribute.ENTITIES_TYPE);
        attrTypes.put("entities", Attribute.ENTITIES_TYPE);
        attrTypes.put("NMTOKEN", Attribute.NMTOKEN_TYPE);
        attrTypes.put("nmtoken", Attribute.NMTOKEN_TYPE);
        attrTypes.put("NMTOKENS", Attribute.NMTOKENS_TYPE);
        attrTypes.put("nmtokens", Attribute.NMTOKENS_TYPE);
        attrTypes.put("NOTATION", Attribute.NOTATION_TYPE);
        attrTypes.put("notation", Attribute.NOTATION_TYPE);
        attrTypes.put("ENUMERATED", Attribute.ENUMERATED_TYPE);
        attrTypes.put("enumerated", Attribute.ENUMERATED_TYPE);
    }

    // // // Configuration settings:

    /**
     * The factory for creating new JDOM objects
     */
    private JDOMFactory factory = null;

    /**
     * Whether ignorable white space should be ignored, ie not added
     * in the resulting JDOM tree. If true, it will be ignored; if false,
     * it will be added in the tree. Default value if false.
     */
    protected boolean cfgIgnoreWS = false;

    /**
     * Object that will be used when trying to remove indentation white
     * space: if so, the object is consulted to figure out what consistutes
     * indentation white space, as well as about context in which such
     * white space is to be removed.
     *

     * Note that only such text events (CHARACTERS) are considered that
     * are not known to be fully ignorable (ignorable white space would
     * be reported as SPACE) by this removal process. SPACE events can
     * be trimmed simply by setting {@link #cfgIgnoreWS} to true.
     */
    protected StAXTextModifier textModifier = null;

    /**
     * Default constructor.
     */
    public StAXBuilder() {
    }

    /*
     * This sets a custom JDOMFactory for the builder.  Use this to build
     * the tree with your own subclasses of the JDOM classes.
     *
     * @param factory JDOMFactory to use
     */
    public void setFactory(JDOMFactory f) {
        factory = f;
    }

    public void setTextModifier(StAXTextModifier mod) {
        textModifier = mod;
    }

    /**
     * Method used to set value of {@link #cfgIgnoreWS}; that is, to
     * make parser either remove ignorable white space (true), or
     * to include it (false).
     *

     * Whether all-whitespace text segment is ignorable white space or
     * not is based on DTD read in, as per XML specifications (white space
     * is only significant in mixed content or pure text elements).
     */
    public void setIgnoreWhitespace(boolean state) {
        cfgIgnoreWS = state;
    }

    /**
     * Method used to enable or disable automatic heuristic removal
     * of indentation white  If set to true, the builder will
     * try to remove white space that seems to be used for
     * indentation purposes; otherwise it will not try to do any removal.
     *

     * Note that this setting only applies to all-whitespace segments
     * that have NOT been determined to be ignorable white space (either
     * because DTD is not available, or because such white space is in
     * mixed or text-only element content). As such it is a heuristics
     * that should only be enabled when application knows that such
     * white space removal does not cause problems.
     *

     * Also note that internally the method calls
     * {@link #setTextModifier} with either the default text modifier
     * (true), or with null (false).
     */
    public void setRemoveIndentation(boolean state) {
        if (state) {
            setTextModifier(IndentRemover.getInstance());
        } else {
            setTextModifier(null);
        }
    }

    /**
     * Returns the current {@link org.jdom.JDOMFactory} in use, if
     * one has been previously set with {@link #setFactory}, otherwise
     * null.
     *
     * @return the factory builder will use
     */
    public JDOMFactory getFactory() {
        return factory;
    }

    /**
     * This will build a JDOM tree given a StAX stream reader.
     *
     * @param r Stream reader from which input is read.
     * @return Document - JDOM document object.
     * @throws javax.xml.stream.XMLStreamException If the reader threw such exception (to
     *                            indicate a parsing or I/O problem)
     */
    public Document build(XMLStreamReader r)
            throws XMLStreamException {
        /* Should we do sanity checking to see that r is positioned at
         * beginning? Not doing so will allow creating documents from
         * sub-trees, though?  (not necessarily, depending on the
         * build loop: it may expect END_DOCUMENT?)
         */
        JDOMFactory f = factory;
        if (f == null) {
            f = new UncheckedJDOMFactory();
        }
        Document doc = f.document(null);
        buildTree(f, r, doc, textModifier);
        return doc;
    }

    /**
     * This takes a XMLStreamReader and builds up
     * a JDOM tree. Recursion has been eliminated by using nodes'
     * parent/child relationship; this improves performance somewhat
     * (classic recursion-by-iteration-and-explicit stack transformation)
     *
     * @param f    Node factory to use for creating JDOM nodes
     * @param r    Stream reader to use for reading the document from which
     *             to build the tree
     * @param doc  JDOM Document being built.
     * @param tmod Text modifier to use for modifying content of text
     *             nodes (CHARACTERS, not CDATA), if any; null if no modifications
     *             are needed (modifier is usually used for trimming unnecessary
     *             but non-ignorable white space).
     */
    protected void buildTree(JDOMFactory f, XMLStreamReader r, Document doc,
                             StAXTextModifier tmod)
            throws XMLStreamException {
        Element current = null; // At top level

        /* Only relevant when trying to trim indentation. But if so, let's
         * just always allow modifications in prolog/epilog.
         */
        boolean allowTextMods = (tmod != null);
        int evtType = XMLStreamConstants.START_DOCUMENT;

        main_loop:

        while (true) {
            int prevEvent = evtType;
            evtType = r.next();

            /* 11-Dec-2004, TSa: We may want to trim (indentation) white
             *    space... and it's easiest to do as a completely separate
             *    piece of logic, before the main switch.
             */
            if (allowTextMods) {
                // Ok; did we get CHARACTERS to potentially modify?
                if (evtType == XMLStreamConstants.CHARACTERS) {
                    // Mayhaps we could be interested in modifying it?
                    if (tmod.possiblyModifyText(r, prevEvent)) {
                        /* Need to get text before iterating to see the
                         * following event (as that'll lose it)
                         */
                        String txt = r.getText();
                        evtType = r.next();
                        // So how should the text be modified if at all?
                        txt = tmod.textToIncludeBetween(r, prevEvent, evtType,
                                txt);
                        // Need to output if it's non-empty text, then:
                        if (txt != null && txt.length() > 0) {
                            /* See discussion below for CHARACTERS case; basically
                             * we apparently can't add anything in epilog/prolog,
                             * not even white space.
                             */
                            if (current != null) {
                                f.addContent(current, f.text(txt));
                            }
                        }
                        prevEvent = XMLStreamConstants.CHARACTERS;
                        // Ok, let's fall down to handle new current event
                    }
                }
                // And then can just fall back to the regular handling
            }

            Content child;

            switch (evtType) {
                case XMLStreamConstants.CDATA:
                    child = f.cdata(r.getText());
                    break;

                case XMLStreamConstants.SPACE:
                    if (cfgIgnoreWS) {
                        continue main_loop;
                    }
                    // fall through

                case XMLStreamConstants.CHARACTERS:
                    /* Small complication: although (ignorable) white space
                    * is allowed in prolog/epilog, and StAX may report such
                    * event, JDOM barfs if trying to add it. Thus, let's just
                    * ignore all textual stuff outside the tree:
                    */
                    if (current == null) {
                        continue main_loop;
                    }

                    child = f.text(r.getText());
                    break;

                case XMLStreamConstants.COMMENT:
                    child = f.comment(r.getText());
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    break main_loop;

                case XMLStreamConstants.END_ELEMENT:
                    current = current.getParentElement();
                    if (tmod != null) {
                        allowTextMods = tmod.allowModificationsAfter(r, evtType);
                    }
                    continue main_loop;

                case XMLStreamConstants.ENTITY_DECLARATION:
                case XMLStreamConstants.NOTATION_DECLARATION:
                    /* Shouldn't really get these, but maybe some stream readers
                    * do provide the info. If so, better ignore it -- DTD event
                    * should have most/all we need.
                    */
                    continue main_loop;

                case XMLStreamConstants.ENTITY_REFERENCE:
                    child = f.entityRef(r.getLocalName());
                    break;

                case XMLStreamConstants.PROCESSING_INSTRUCTION:
                    child = f.processingInstruction(r.getPITarget(), r.getPIData());
                    break;

                case XMLStreamConstants.START_ELEMENT:
                    // Ok, need to add a new element...
                {
                    Element newElem = null;
                    String nsURI = r.getNamespaceURI();
                    String elemPrefix = r.getPrefix(); // needed for special handling of elem's namespace
                    String ln = r.getLocalName();

                    if (nsURI == null || nsURI.length() == 0) {
                        if (elemPrefix == null || elemPrefix.length() == 0) {
                            newElem = f.element(ln);
                        } else {
                            /* Happens when a prefix is bound to the default
                             * (empty) namespace...
                             */
                            newElem = f.element(ln, elemPrefix, "");
                        }
                    } else {
                        newElem = f.element(ln, elemPrefix, nsURI);
                    }

                    /* Let's add element right away (probably have to do
                     * it to bind attribute namespaces, too)
                     */
                    if (current == null) { // at root
                        doc.setRootElement(newElem);
                    } else {
                        f.addContent(current, newElem);
                    }

                    // Any declared namespaces?
                    for (int i = 0, len = r.getNamespaceCount(); i < len; ++i) {
                        String prefix = r.getNamespacePrefix(i);
                        if (prefix == null) {
                            prefix = "";
                        }
                        Namespace ns = Namespace.getNamespace(prefix, r.getNamespaceURI(i));

                        // JDOM has special handling for element's "own" ns:
                        if (prefix.equals(elemPrefix)) {
                            ; // already set by when it was constructed...
                        } else {
                            f.addNamespaceDeclaration(newElem, ns);
                        }
                    }

                    // And then the attributes:
                    for (int i = 0, len = r.getAttributeCount(); i < len; ++i) {
                        String prefix = r.getAttributePrefix(i);
                        Namespace ns;

                        if (prefix == null || prefix.length() == 0) {
                            // Attribute not in any namespace
                            ns = Namespace.NO_NAMESPACE;
                        } else {
                            ns = newElem.getNamespace(prefix);
                        }
                        Attribute attr = f.attribute(r.getAttributeLocalName(i),
                                r.getAttributeValue(i),
                                resolveAttrType(r.getAttributeType(i)),
                                ns);
                        f.setAttribute(newElem, attr);
                    }
                    // And then 'push' new element...
                    current = newElem;
                }

                if (tmod != null) {
                    allowTextMods = tmod.allowModificationsAfter(r, evtType);
                }

                // Already added the element, can continue
                continue main_loop;

                case XMLStreamConstants.START_DOCUMENT:
                    /* This should only be received at the beginning of document...
                    * so, should we indicate the problem or not?
                    */
                    /* For now, let it pass: maybe some (broken) readers pass
                    * that info as first event in beginning of doc?
                    */
                    continue main_loop;

                case XMLStreamConstants.DTD:
                    /* !!! Note: StAX does not expose enough information about
                    *  doctype declaration (specifically, public and system id!);
                    *  should (re-)parse information... not yet implemented
                    */
                    // TBI
                    continue main_loop;

                    // Should never get these, from a stream reader:

                    /* (commented out entries are just FYI; default catches
                    * them all)
                    */

                    //case XMLStreamConstants.ATTRIBUTE:
                    //case XMLStreamConstants.NAMESPACE:
                default:
                    throw new XMLStreamException("Unrecognized iterator event type: " + r.getEventType() + "; should not receive such types (broken stream reader?)");
            }

            if (child != null) {
                if (current == null) {
                    f.addContent(doc, child);
                } else {
                    f.addContent(current, child);
                }
            }
        }
    }

    /**
     * Method called when option is turned on;
     * to determine if current CHARACTERS event looks like it might
     * be used for indentation purposes (it is all white space, and
     * is either immediately after a start element, or could be
     * immediately before a start element).
     *

     * The default implementation just checks whether the text segment
     * (known to be all white space) starts with a
     * linefeed character.
     */
    protected boolean isIndentationWhitespace(XMLStreamReader r)
            throws XMLStreamException {
        String text = r.getText();
        // Should never be empty... but let's be sure
        if (text.length() > 0) {
            char c = text.charAt(0);
            return (c == '\n' || c == '\r');
        }
        return false;
    }

    // // // Private methods:

    private static int resolveAttrType(String typeStr) {
        if (typeStr != null && typeStr.length() > 0) {
            Integer I = attrTypes.get(typeStr);
            if (I != null) {
                return I.intValue();
            }
        }
        return Attribute.UNDECLARED_TYPE;
    }

    // // // Basic text modifier class(es)

    public static class IndentRemover
            extends StAXTextModifier {
        final static IndentRemover sInstance = new IndentRemover();

        protected IndentRemover() {
            super();
        }

        public static IndentRemover getInstance() {
            return sInstance;
        }

        /**
         * Always removes indentation after
         * all start and elements without any further checks; essentially
         * allowing (indentation) white space removal anywhere in the
         * document.
         */
        public boolean allowModificationsAfter(XMLStreamReader r, int eventType)
                throws XMLStreamException {
            return true;
        }

        /**
         * Enables modifications for
         * so-called "indentation
         * white space", ie. all-whitespace (non-CDATA) text segment that
         * starts with
         * a linefeed character (\n or \r); provided it follows a non-text
         * event (anything other than CDATA, ENTITY_REFERENCE and CHARACTERS;
         * none of which usually should be adjacent to CHARACTERS event,
         * if text coalescing is enabled, and automatic entity expansion
         * is not disabled).
         */
        public boolean possiblyModifyText(XMLStreamReader r, int prevEvent)
                throws XMLStreamException {
            if (r.getEventType() == XMLStreamConstants.CHARACTERS) {
                if (!(prevEvent == XMLStreamConstants.CHARACTERS
                        || prevEvent == XMLStreamConstants.CDATA
                        || prevEvent == XMLStreamConstants.ENTITY_REFERENCE)) {
                    if (r.isWhiteSpace()) {
                        String txt = r.getText();
                        if (txt.length() > 0) { // should always be true
                            char c = txt.charAt(0);
                            return (c == '\n' || c == '\r');
                        }
                    }
                }
            }
            return false;
        }

        /**
         * If we ever get this far, we will still check that
         * the CHARACTERS event is not immediately followed by another
         * textual event. If so, we'll just remove the (all white space)
         * text event.
         */
        public String textToIncludeBetween(XMLStreamReader r,
                                           int prevEvent, int nextEvent,
                                           String text)
                throws XMLStreamException {
            /* Only remove white space if neither preceding nor following
             * event is of non-ignorable textual type (CHARACTERS, CDATA,
             * ENTITY_REFERENCE; note that SPACE should never be adjacent
             * to CHARACTERS event).
             */
            if (nextEvent == XMLStreamConstants.CHARACTERS
                    || nextEvent == XMLStreamConstants.CDATA
                    || nextEvent == XMLStreamConstants.ENTITY_REFERENCE) {
                return text;
            }

            /* If we got this far, we know it's indentation white space
            * and should just be removed completely:
            */
            return null;
        }
    }

    // // // Testing

    /**
     * Trivial test driver for testing functionality.
     */
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage: java ... [file]");
            System.exit(1);
        }
        String filename = args[0];
        java.io.Reader r = new java.io.FileReader(filename);
        javax.xml.stream.XMLInputFactory f = javax.xml.stream.XMLInputFactory.newInstance();
        XMLStreamReader sr = f.createXMLStreamReader(r);

        StAXBuilder builder = new StAXBuilder();

        Document domDoc = builder.build(sr);
        System.out.println("Done [with " + sr.getClass() + "]:");
        System.out.println("----- JDom -----");
        org.jdom.output.XMLOutputter outputter = new org.jdom.output.XMLOutputter();
        java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
        outputter.output(domDoc, pw);
        pw.flush();
        System.out.println("----- /JDom -----");
    }
}


text:
using System;
using System.Diagnostics.Contracts;
using System.Windows;

namespace Rikrop.Core.Wpf.Behaviors
{
    public static class FeNoCountVisibilityBehaviour
    {
        public static readonly DependencyProperty IsBusyProperty =
            DependencyProperty.RegisterAttached("IsBusy", typeof (bool?), typeof (FeNoCountVisibilityBehaviour), new PropertyMetadata(null, IsBusyPropertyChangedCallback));

        public static readonly DependencyProperty CountProperty =
            DependencyProperty.RegisterAttached("Count", typeof (int?), typeof (FeNoCountVisibilityBehaviour), new PropertyMetadata(null, CountPropertyChangedCallback));

        public static void SetIsBusy(UIElement element, bool? value)
        {
            element.SetValue(IsBusyProperty, value);
        }

        public static bool? GetIsBusy(UIElement element)
        {
            return (bool?) element.GetValue(IsBusyProperty);
        }

        public static void SetCount(UIElement element, int? value)
        {
            element.SetValue(CountProperty, value);
        }

        public static int? GetCount(UIElement element)
        {
            return (int?) element.GetValue(CountProperty);
        }

        private static void IsBusyPropertyChangedCallback(DependencyObject dobj, DependencyPropertyChangedEventArgs dargs)
        {
            Contract.Assume(dobj is FrameworkElement);
            var fe = (FrameworkElement) dobj;

            SetVisibility(fe);
        }

        private static void CountPropertyChangedCallback(DependencyObject dobj, DependencyPropertyChangedEventArgs dargs)
        {
            Contract.Assume(dobj is FrameworkElement);
            var fe = (FrameworkElement) dobj;

            SetVisibility(fe);
        }

        private static void SetVisibility(FrameworkElement fe)
        {
            Contract.Requires<ArgumentNullException>(fe != null);
            fe.Visibility = IsVisible(fe)
                                ? Visibility.Visible
                                : Visibility.Collapsed;
        }

        private static bool IsVisible(FrameworkElement fe)
        {
            Contract.Requires<ArgumentNullException>(fe != null);
            var b = GetIsBusy(fe);
            var c = GetCount(fe);

            if (b.HasValue && c.HasValue)
            {
                return !b.Value && c.Value == 0;
            }

            if (c.HasValue)
            {
                return c.Value > 0;
            }

            return false;
        }
    }
}


text:
module ApiEngine
  class SchemaController < ActionController::Base

    def index
      render json: schema
    end

    private

    def schema
      resp = { resources: {} }
      ApiEngine.models.each do |model|
        model_key = model.to_s.downcase.pluralize.to_sym
        model_schema = {}
        model_schema[model_key] = model.active_model_serializer.schema
        resp[:resources].merge!(model_schema)
      end
      resp
    end

  end
end


text:
//
// Include common header file for this module.
//
#include "CommonHeader.h"

#include "QNCSmmHelpers.h"

//
// Help handle porting bit shifts to IA-64.
//
#define BIT_ZERO 0x00000001

VOID
QNCSmmPublishDispatchProtocols(
  VOID
  )
{
  UINTN      Index;
  EFI_STATUS Status;

  //
  // Install protocol interfaces.
  //
  for (Index = 0; Index < NUM_PROTOCOLS; Index++) {
    Status = gSmst->SmmInstallProtocolInterface (
                 &mPrivateData.InstallMultProtHandle,
                      mPrivateData.Protocols[Index].Guid,
                      EFI_NATIVE_INTERFACE,
                      &mPrivateData.Protocols[Index].Protocols.Generic
                 );

  ASSERT_EFI_ERROR (Status);
}
}

EFI_STATUS
QNCSmmInitHardware(
  VOID
  )
/*++

Routine Description:

  Initialize bits that aren't necessarily related to an SMI source.

Dependencies:

  gSmst - SMM System Table; contains an entry for SMM CPU IO

Returns:

  EFI_SUCCESS.  Asserts, otherwise.

--*/
{
  EFI_STATUS Status;

  //
  // Clear all SMIs
  //
  QNCSmmClearSmi();

  Status = QNCSmmEnableGlobalSmiBit ();
  ASSERT_EFI_ERROR (Status);

  //
  // Be *really* sure to clear all SMIs
  //
  QNCSmmClearSmi ();

  return EFI_SUCCESS;
}

EFI_STATUS
QNCSmmEnableGlobalSmiBit (
  VOID
  )
/*++

Routine Description:

  Enables the QNC to generate SMIs. Note that no SMIs will be generated
  if no SMI sources are enabled. Conversely, no enabled SMI source will
  generate SMIs if SMIs are not globally enabled. This is the main
  switchbox for SMI generation.

Arguments:

  None

Returns:

  EFI_SUCCESS.
  Asserts, otherwise.

--*/
{
  UINT32        NewValue;

  //
  // Enable SMI globally
  //
  NewValue = QNCPortRead (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC);
  NewValue |= SMI_EN;
  QNCPortWrite (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC, NewValue);

  return EFI_SUCCESS;
}

EFI_STATUS
QNCSmmClearSmi(
  VOID
  )
/*++

Routine Description:

  Clears the SMI after all SMI source have been processed.
  Note that this function will not work correctly (as it is
  written) unless all SMI sources have been processed.
  A revision of this function could manually clear all SMI
  status bits to guarantee success.

Returns:

  EFI_SUCCESS.
  Asserts, otherwise.

--*/
{
  BOOLEAN EosSet;
  BOOLEAN SciEn;

  UINT32 Pm1Cnt = 0;
  UINT16 Pm1Sts = 0;
  UINT32 Gpe0Sts = 0;
  UINT32 SmiSts  = 0;

  //
  // Determine whether an ACPI OS is present (via the SCI_EN bit)
  //
  Pm1Cnt = IoRead32(PcdGet16 (PcdPm1blkIoBaseAddress) + R_QNC_PM1BLK_PM1C);
  SciEn = (BOOLEAN)((Pm1Cnt & B_QNC_PM1BLK_PM1C_SCIEN) == B_QNC_PM1BLK_PM1C_SCIEN);

  if (SciEn == FALSE) {

    //
    // Clear any SMIs that double as SCIs (when SCI_EN==0)
    //
    Pm1Sts = (B_QNC_PM1BLK_PM1S_WAKE | B_QNC_PM1BLK_PM1S_PCIEWSTS | B_QNC_PM1BLK_PM1S_RTC | B_QNC_PM1BLK_PM1S_GLOB | B_QNC_PM1BLK_PM1S_TO);

    Gpe0Sts = B_QNC_GPE0BLK_GPE0S_ALL;

    IoOr16((PcdGet16 (PcdPm1blkIoBaseAddress) + R_QNC_PM1BLK_PM1S), Pm1Sts);
    IoOr32(((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + R_QNC_GPE0BLK_GPE0S), Gpe0Sts);
  }

  //
  // Clear all SMIs that are unaffected by SCI_EN
  //
  SmiSts = IoRead32((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + R_QNC_GPE0BLK_SMIS);
  SmiSts |= B_QNC_GPE0BLK_SMIS_ALL;
  IoWrite32(((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + R_QNC_GPE0BLK_SMIS), SmiSts);

  //
  // Try to clear the EOS bit. ASSERT on an error
  //
  EosSet = QNCSmmSetAndCheckEos();
  ASSERT (EosSet);

  return EFI_SUCCESS;
}

BOOLEAN
QNCSmmSetAndCheckEos(
  VOID
  )
{
  //
  // Reset the QNC to generate subsequent SMIs
  //
  IoOr32(((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + R_QNC_GPE0BLK_SMIS), B_QNC_GPE0BLK_SMIS_EOS);
    return TRUE;
}

BOOLEAN
QNCSmmGetSciEn(
  )
{
  BOOLEAN SciEn;
  UINT32 Pm1Cnt;

  //
  // Determine whether an ACPI OS is present (via the SCI_EN bit)
  //
  Pm1Cnt = IoRead32(PcdGet16 (PcdPm1blkIoBaseAddress) + R_QNC_PM1BLK_PM1C);

  SciEn = (BOOLEAN)((Pm1Cnt & B_QNC_PM1BLK_PM1C_SCIEN) == B_QNC_PM1BLK_PM1C_SCIEN);

  return SciEn;
}

//
// These may or may not need to change w/ the QNC version; they're highly IA-32 dependent, though.
//

BOOLEAN
ReadBitDesc (
  CONST QNC_SMM_BIT_DESC  *BitDesc
  )
{
  UINT64           Register;
  UINT32           PciBus;
  UINT32           PciDev;
  UINT32           PciFun;
  UINT32           PciReg;
  BOOLEAN          BitWasOne;

  ASSERT (BitDesc != NULL );
  ASSERT (!IS_BIT_DESC_NULL( *BitDesc ) );

  Register  = 0;
  BitWasOne = FALSE;

  switch (BitDesc->Reg.Type) {

  case ACPI_ADDR_TYPE:
    //
    // Double check that we correctly read in the acpi base address
    //
    ASSERT ((PcdGet16 (PcdPm1blkIoBaseAddress) != 0x0) && ((PcdGet16 (PcdPm1blkIoBaseAddress) & 0x1) != 0x1) );

    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized.
      // Check your assignments to bit descriptions.
      //
      ASSERT (FALSE );
      break;

      case 1:
      Register = (UINT64) IoRead8 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi);
        break;

      case 2:
      Register = (UINT64) IoRead16 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi);
        break;

      case 4:
      Register = (UINT64) IoRead32 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi);
        break;

      default:
        //
        // Unsupported or invalid register size
        //
        ASSERT (FALSE );
        break;
      };

    if ((Register & LShiftU64 (BIT_ZERO, BitDesc->Bit)) != 0) {
        BitWasOne = TRUE;
      } else {
        BitWasOne = FALSE;
      }
    break;

  case GPE_ADDR_TYPE:
      //
    // Double check that we correctly read in the gpe base address
      //
    ASSERT (((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) != 0x0) && (((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) & 0x1) != 0x1) );

    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized.
      // Check your assignments to bit descriptions.
      //
      ASSERT (FALSE );
      break;

    case 1:
      Register = (UINT64) IoRead8 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe);
      break;

    case 2:
      Register = (UINT64) IoRead16 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe);
      break;

    case 4:
      Register = (UINT64) IoRead32 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe);
      break;

    default:
      //
      // Unsupported or invalid register size
      //
      ASSERT (FALSE );
      break;
    };

    if ((Register & LShiftU64 (BIT_ZERO, BitDesc->Bit)) != 0) {
        BitWasOne = TRUE;
      } else {
        BitWasOne = FALSE;
      }
    break;

  case MEMORY_MAPPED_IO_ADDRESS_TYPE:
    //
    // Read the register, and it with the bit to read
    //

    //
    // This code does not support reads greater then 64 bits
    //
    ASSERT (BitDesc->SizeInBytes <= 8);
    CopyMem (&Register, BitDesc->Reg.Data.Mmio, BitDesc->SizeInBytes);
    Register &= LShiftU64 (BIT0, BitDesc->Bit);
    if (Register) {
      BitWasOne = TRUE;
    } else {
      BitWasOne = FALSE;
    }
    break;

  case PCI_ADDR_TYPE:
    PciBus = BitDesc->Reg.Data.pci.Fields.Bus;
    PciDev = BitDesc->Reg.Data.pci.Fields.Dev;
    PciFun = BitDesc->Reg.Data.pci.Fields.Fnc;
    PciReg = BitDesc->Reg.Data.pci.Fields.Reg;
    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized.
      // Check your assignments to bit descriptions.
      ASSERT (FALSE );
      break;

    case 1:
      Register = (UINT64) PciRead8 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg));
      break;

    case 2:
      Register = (UINT64) PciRead16 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg));
      break;

    case 4:
      Register = (UINT64) PciRead32 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg));
      break;

    default:
      //
      // Unsupported or invalid register size
      //
      ASSERT (FALSE );
      break;
    };

    if ((Register & LShiftU64 (BIT_ZERO, BitDesc->Bit)) != 0) {
        BitWasOne = TRUE;
    } else {
      BitWasOne = FALSE;
    }
    break;

  default:
    //
    // This address type is not yet implemented
    //
    ASSERT (FALSE );
    break;
  };

  return BitWasOne;
}

VOID
WriteBitDesc (
  CONST QNC_SMM_BIT_DESC   *BitDesc,
  CONST BOOLEAN           ValueToWrite
  )
{
  UINT64           Register;
  UINT64           AndVal;
  UINT64           OrVal;
  UINT32           PciBus;
  UINT32           PciDev;
  UINT32           PciFun;
  UINT32           PciReg;

  ASSERT (BitDesc != NULL);
  ASSERT (!IS_BIT_DESC_NULL(*BitDesc));

  AndVal = ~(BIT_ZERO << (BitDesc->Bit));
  OrVal  = ((UINT32)ValueToWrite) << (BitDesc->Bit);

  switch (BitDesc->Reg.Type) {

  case ACPI_ADDR_TYPE:
    //
    // Double check that we correctly read in the acpi base address
    //
    ASSERT ((PcdGet16 (PcdPm1blkIoBaseAddress) != 0x0) && ((PcdGet16 (PcdPm1blkIoBaseAddress) & 0x1) != 0x1));

    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized.
      // Check your assignments to bit descriptions.
      //
      ASSERT (FALSE );
      break;

    case 1:
      IoAndThenOr8 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi, (UINT8)AndVal, (UINT8)OrVal);
      break;

    case 2:
      IoAndThenOr16 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi, (UINT16)AndVal, (UINT16)OrVal);
      break;

    case 4:
      IoAndThenOr32 (PcdGet16 (PcdPm1blkIoBaseAddress) + BitDesc->Reg.Data.acpi, (UINT32)AndVal, (UINT32)OrVal);
      break;

    default:
      //
      // Unsupported or invalid register size
      //
      ASSERT (FALSE );
      break;
    };
    break;

  case GPE_ADDR_TYPE:
    //
    // Double check that we correctly read in the gpe base address
    //
    ASSERT (((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) != 0x0) && (((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) & 0x1) != 0x1));

    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized.
      // Check your assignments to bit descriptions.
      //
      ASSERT (FALSE );
      break;

    case 1:
      IoAndThenOr8 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe, (UINT8)AndVal, (UINT8)OrVal);
      break;

    case 2:
      IoAndThenOr16 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe, (UINT16)AndVal, (UINT16)OrVal);
      break;

    case 4:
      IoAndThenOr32 ((UINT16)(LpcPciCfg32 (R_QNC_LPC_GPE0BLK) & 0xFFFF) + BitDesc->Reg.Data.gpe, (UINT32)AndVal, (UINT32)OrVal);
      break;

    default:
      //
      // Unsupported or invalid register size
      //
      ASSERT (FALSE );
      break;
    };
      break;

  case MEMORY_MAPPED_IO_ADDRESS_TYPE:
    //
    // Read the register, or it with the bit to set, then write it back.
    //

    //
    // This code does not support writes greater then 64 bits
    //
    ASSERT (BitDesc->SizeInBytes <= 8);
    CopyMem (&Register, BitDesc->Reg.Data.Mmio, BitDesc->SizeInBytes);
    Register &= AndVal;
    Register |= OrVal;
    CopyMem (BitDesc->Reg.Data.Mmio, &Register, BitDesc->SizeInBytes);
    break;

  case PCI_ADDR_TYPE:
    PciBus = BitDesc->Reg.Data.pci.Fields.Bus;
    PciDev = BitDesc->Reg.Data.pci.Fields.Dev;
    PciFun = BitDesc->Reg.Data.pci.Fields.Fnc;
    PciReg = BitDesc->Reg.Data.pci.Fields.Reg;
    switch (BitDesc->SizeInBytes) {

    case 0:
      //
      // Chances are that this field didn't get initialized -- check your assignments
      // to bit descriptions.
      //
      ASSERT (FALSE );
      break;

    case 1:
      PciAndThenOr8 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg), (UINT8) AndVal, (UINT8) OrVal);
      break;

    case 2:
      PciAndThenOr16 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg), (UINT16) AndVal, (UINT16) OrVal);
      break;

    case 4:
      PciAndThenOr32 (PCI_LIB_ADDRESS (PciBus, PciDev, PciFun, PciReg), (UINT32) AndVal, (UINT32) OrVal);
      break;

    default:
      //
      // Unsupported or invalid register size
      //
      ASSERT (FALSE );
      break;
    };
    break;

    default:
    //
    // This address type is not yet implemented
    //
    ASSERT (FALSE );
    break;
  };
}


text:
"""User views."""

from flask import Blueprint, flash, redirect, render_template, request, url_for

from flask_login import login_required, login_user, logout_user

from .forms import LoginForm, RegisterForm

from store.utils import flash_errors

from .models import User

from store.utils import manager_only

blueprint = Blueprint('user', __name__, url_prefix='/user',
                      static_folder='../static')

@blueprint.route('/members')
@login_required
def members():
    """List members."""
    return render_template('user/members.html')

@blueprint.route('/denied')
@login_required
@manager_only
def cannot_go_here():
    """Should not be here."""
    return "Should not see this."

@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    """Login route."""
    form = LoginForm(request.form)
    # Handle logging in
    if request.method == 'POST':
        if form.validate_on_submit():
            login_user(form.user)
            flash('You are logged in.', 'success')
            redirect_url = request.args.get('next') or url_for('user.members')
            return redirect(redirect_url)
        else:
            flash_errors(form)
    return render_template('user/login.html', form=form)

@blueprint.route('/register', methods=['GET', 'POST'])
def register():
    """Register new user."""
    form = RegisterForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        User.create(id=form.username.data, email=form.email.data,
                    password=form.password.data, active=True)
        flash('Thank you for registering. You can now log in.', 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)
    return render_template('user/register.html', form=form)

@blueprint.route('/logout')
@login_required
def logout():
    """Logout."""
    logout_user()
    flash('You are logged out.', 'info')
    return redirect(url_for('public.home'))


text:
namespace view_manager {

enum ChangeType {
  CHANGE_TYPE_EMBED,
  CHANGE_TYPE_EMBEDDED_APP_DISCONNECTED,
  CHANGE_TYPE_UNEMBED,
  // TODO(sky): nuke NODE.
  CHANGE_TYPE_NODE_BOUNDS_CHANGED,
  CHANGE_TYPE_NODE_VIEWPORT_METRICS_CHANGED,
  CHANGE_TYPE_NODE_HIERARCHY_CHANGED,
  CHANGE_TYPE_NODE_REORDERED,
  CHANGE_TYPE_NODE_VISIBILITY_CHANGED,
  CHANGE_TYPE_NODE_DRAWN_STATE_CHANGED,
  CHANGE_TYPE_NODE_DELETED,
  CHANGE_TYPE_INPUT_EVENT,
  CHANGE_TYPE_PROPERTY_CHANGED,
  CHANGE_TYPE_DELEGATE_EMBED,
  CHANGE_TYPE_FOCUSED,
};

// TODO(sky): consider nuking and converting directly to ViewData.
struct TestView {
  TestView();
  ~TestView();

  // Returns a string description of this.
  std::string ToString() const;

  // Returns a string description that includes visible and drawn.
  std::string ToString2() const;

  mojo::Id parent_id;
  mojo::Id view_id;
  bool visible;
  bool drawn;
  std::map<std::string, std::vector<uint8_t>> properties;
};

// Tracks a call to ViewTreeClient. See the individual functions for the fields
// that are used.
struct Change {
  Change();
  ~Change();

  ChangeType type;
  mojo::ConnectionSpecificId connection_id;
  std::vector<TestView> views;
  mojo::Id view_id;
  mojo::Id view_id2;
  mojo::Id view_id3;
  mojo::Rect bounds;
  mojo::Rect bounds2;
  int32_t event_action;
  mojo::String embed_url;
  mojo::OrderDirection direction;
  bool bool_value;
  std::string property_key;
  std::string property_value;
};

// Converts Changes to string descriptions.
std::vector<std::string> ChangesToDescription1(
    const std::vector<Change>& changes);

// Convenience for returning the description of the first item in |changes|.
// Returns an empty string if |changes| has something other than one entry.
std::string SingleChangeToDescription(const std::vector<Change>& changes);

// Convenience for returning the description of the first item in |views|.
// Returns an empty string if |views| has something other than one entry.
std::string SingleViewDescription(const std::vector<TestView>& views);

// Returns a string description of |changes[0].views|. Returns an empty string
// if change.size() != 1.
std::string ChangeViewDescription(const std::vector<Change>& changes);

// Converts ViewDatas to TestViews.
void ViewDatasToTestViews(const mojo::Array<mojo::ViewDataPtr>& data,
                          std::vector<TestView>* test_views);

// TestChangeTracker is used to record ViewTreeClient functions. It notifies
// a delegate any time a change is added.
class TestChangeTracker {
 public:
  // Used to notify the delegate when a change is added. A change corresponds to
  // a single ViewTreeClient function.
  class Delegate {
   public:
    virtual void OnChangeAdded() = 0;

   protected:
    virtual ~Delegate() {}
  };

  TestChangeTracker();
  ~TestChangeTracker();

  void set_delegate(Delegate* delegate) {
    delegate_ = delegate;
  }

  std::vector<Change>* changes() { return &changes_; }

  // Each of these functions generate a Change. There is one per
  // ViewTreeClient function.
  void OnEmbed(mojo::ConnectionSpecificId connection_id,
               mojo::ViewDataPtr root);
  void OnEmbeddedAppDisconnected(mojo::Id view_id);
  void OnUnembed();
  void OnViewBoundsChanged(mojo::Id view_id,
                           mojo::RectPtr old_bounds,
                           mojo::RectPtr new_bounds);
  void OnViewViewportMetricsChanged(mojo::ViewportMetricsPtr old_bounds,
                                    mojo::ViewportMetricsPtr new_bounds);
  void OnViewHierarchyChanged(mojo::Id view_id,
                              mojo::Id new_parent_id,
                              mojo::Id old_parent_id,
                              mojo::Array<mojo::ViewDataPtr> views);
  void OnViewReordered(mojo::Id view_id,
                       mojo::Id relative_view_id,
                       mojo::OrderDirection direction);
  void OnViewDeleted(mojo::Id view_id);
  void OnViewVisibilityChanged(mojo::Id view_id, bool visible);
  void OnViewDrawnStateChanged(mojo::Id view_id, bool drawn);
  void OnViewInputEvent(mojo::Id view_id, mojo::EventPtr event);
  void OnViewSharedPropertyChanged(mojo::Id view_id,
                                   mojo::String name,
                                   mojo::Array<uint8_t> data);
  void OnViewFocused(mojo::Id view_id);
  void DelegateEmbed(const mojo::String& url);

 private:
  void AddChange(const Change& change);

  Delegate* delegate_;
  std::vector<Change> changes_;

  DISALLOW_COPY_AND_ASSIGN(TestChangeTracker);
};

}  // namespace view_manager

#endif  // COMPONENTS_VIEW_MANAGER_TEST_CHANGE_TRACKER_H_