text:
#include "config.h"
#include "core/dom/shadow/InsertionPoint.h"

#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/QualifiedName.h"
#include "core/dom/StaticNodeList.h"
#include "core/dom/shadow/ElementShadow.h"

namespace blink {

using namespace HTMLNames;

InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document& document)
    : HTMLElement(tagName, document, CreateInsertionPoint)
    , m_registeredWithShadowRoot(false)
{
    setHasCustomStyleCallbacks();
}

InsertionPoint::~InsertionPoint()
{
}

void InsertionPoint::setDistribution(ContentDistribution& distribution)
{
    if (shouldUseFallbackElements()) {
        for (Node* child = firstChild(); child; child = child->nextSibling())
            child->lazyReattachIfAttached();
    }

    // Attempt not to reattach nodes that would be distributed to the exact same
    // location by comparing the old and new distributions.

    size_t i = 0;
    size_t j = 0;

    for ( ; i < m_distribution.size() && j < distribution.size(); ++i, ++j) {
        if (m_distribution.size() < distribution.size()) {
            // If the new distribution is larger than the old one, reattach all nodes in
            // the new distribution that were inserted.
            for ( ; j < distribution.size() && m_distribution.at(i) != distribution.at(j); ++j)
                distribution.at(j)->lazyReattachIfAttached();
        } else if (m_distribution.size() > distribution.size()) {
            // If the old distribution is larger than the new one, reattach all nodes in
            // the old distribution that were removed.
            for ( ; i < m_distribution.size() && m_distribution.at(i) != distribution.at(j); ++i)
                m_distribution.at(i)->lazyReattachIfAttached();
        } else if (m_distribution.at(i) != distribution.at(j)) {
            // If both distributions are the same length reattach both old and new.
            m_distribution.at(i)->lazyReattachIfAttached();
            distribution.at(j)->lazyReattachIfAttached();
        }
    }

    // If we hit the end of either list above we need to reattach all remaining nodes.

    for ( ; i < m_distribution.size(); ++i)
        m_distribution.at(i)->lazyReattachIfAttached();

    for ( ; j < distribution.size(); ++j)
        distribution.at(j)->lazyReattachIfAttached();

    m_distribution.swap(distribution);
    m_distribution.shrinkToFit();
}

void InsertionPoint::attach(const AttachContext& context)
{
    // We need to attach the distribution here so that they're inserted in the right order
    // otherwise the n^2 protection inside RenderTreeBuilder will cause them to be
    // inserted in the wrong place later. This also lets distributed nodes benefit from
    // the n^2 protection.
    for (size_t i = 0; i < m_distribution.size(); ++i) {
        if (m_distribution.at(i)->needsAttach())
            m_distribution.at(i)->attach(context);
    }

    HTMLElement::attach(context);
}

void InsertionPoint::detach(const AttachContext& context)
{
    for (size_t i = 0; i < m_distribution.size(); ++i)
        m_distribution.at(i)->lazyReattachIfAttached();

    HTMLElement::detach(context);
}

void InsertionPoint::willRecalcStyle(StyleRecalcChange change)
{
    if (change < Inherit && styleChangeType() < SubtreeStyleChange)
        return;
    for (size_t i = 0; i < m_distribution.size(); ++i)
        m_distribution.at(i)->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::PropagateInheritChangeToDistributedNodes));
}

bool InsertionPoint::shouldUseFallbackElements() const
{
    return isActive() && !hasDistribution();
}

bool InsertionPoint::canBeActive() const
{
    if (!isInShadowTree())
        return false;
    return !Traversal<InsertionPoint>::firstAncestor(*this);
}

bool InsertionPoint::isActive() const
{
    if (!canBeActive())
        return false;
    ShadowRoot* shadowRoot = containingShadowRoot();
    if (!shadowRoot)
        return false;
    if (!isHTMLShadowElement(*this) || shadowRoot->descendantShadowElementCount() <= 1)
        return true;

    // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case.
    const WillBeHeapVector<RefPtrWillBeMember<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints();
    for (size_t i = 0; i < insertionPoints.size(); ++i) {
        InsertionPoint* point = insertionPoints[i].get();
        if (isHTMLShadowElement(*point))
            return point == this;
    }
    return true;
}

bool InsertionPoint::isShadowInsertionPoint() const
{
    return isHTMLShadowElement(*this) && isActive();
}

bool InsertionPoint::isContentInsertionPoint() const
{
    return isHTMLContentElement(*this) && isActive();
}

PassRefPtrWillBeRawPtr<StaticNodeList> InsertionPoint::getDistributedNodes()
{
    document().updateDistributionForNodeIfNeeded(this);

    WillBeHeapVector<RefPtrWillBeMember<Node> > nodes;
    nodes.reserveInitialCapacity(m_distribution.size());
    for (size_t i = 0; i < m_distribution.size(); ++i)
        nodes.uncheckedAppend(m_distribution.at(i));

    return StaticNodeList::adopt(nodes);
}

bool InsertionPoint::rendererIsNeeded(const RenderStyle& style)
{
    return !isActive() && HTMLElement::rendererIsNeeded(style);
}

void InsertionPoint::childrenChanged(const ChildrenChange& change)
{
    HTMLElement::childrenChanged(change);
    if (ShadowRoot* root = containingShadowRoot()) {
        if (ElementShadow* rootOwner = root->owner())
            rootOwner->setNeedsDistributionRecalc();
    }
}

Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint)
{
    HTMLElement::insertedInto(insertionPoint);
    if (ShadowRoot* root = containingShadowRoot()) {
        if (ElementShadow* rootOwner = root->owner()) {
            rootOwner->setNeedsDistributionRecalc();
            if (canBeActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
                m_registeredWithShadowRoot = true;
                root->didAddInsertionPoint(this);
                if (canAffectSelector())
                    rootOwner->willAffectSelector();
            }
        }
    }

    return InsertionDone;
}

void InsertionPoint::removedFrom(ContainerNode* insertionPoint)
{
    ShadowRoot* root = containingShadowRoot();
    if (!root)
        root = insertionPoint->containingShadowRoot();

    if (root) {
        if (ElementShadow* rootOwner = root->owner())
            rootOwner->setNeedsDistributionRecalc();
    }

    // host can be null when removedFrom() is called from ElementShadow destructor.
    ElementShadow* rootOwner = root ? root->owner() : 0;

    // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up.
    clearDistribution();

    if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
        ASSERT(root);
        m_registeredWithShadowRoot = false;
        root->didRemoveInsertionPoint(this);
        if (rootOwner) {
            if (canAffectSelector())
                rootOwner->willAffectSelector();
        }
    }

    HTMLElement::removedFrom(insertionPoint);
}

void InsertionPoint::trace(Visitor* visitor)
{
    visitor->trace(m_distribution);
    HTMLElement::trace(visitor);
}

const InsertionPoint* resolveReprojection(const Node* projectedNode)
{
    ASSERT(projectedNode);
    const InsertionPoint* insertionPoint = 0;
    const Node* current = projectedNode;
    ElementShadow* lastElementShadow = 0;
    while (true) {
        ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
        if (!shadow || shadow == lastElementShadow)
            break;
        lastElementShadow = shadow;
        const InsertionPoint* insertedTo = shadow->finalDestinationInsertionPointFor(projectedNode);
        if (!insertedTo)
            break;
        ASSERT(current != insertedTo);
        current = insertedTo;
        insertionPoint = insertedTo;
    }
    return insertionPoint;
}

void collectDestinationInsertionPoints(const Node& node, WillBeHeapVector<RawPtrWillBeMember<InsertionPoint>, 8>& results)
{
    const Node* current = &node;
    ElementShadow* lastElementShadow = 0;
    while (true) {
        ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
        if (!shadow || shadow == lastElementShadow)
            return;
        lastElementShadow = shadow;
        const DestinationInsertionPoints* insertionPoints = shadow->destinationInsertionPointsFor(&node);
        if (!insertionPoints)
            return;
        for (size_t i = 0; i < insertionPoints->size(); ++i)
            results.append(insertionPoints->at(i).get());
        ASSERT(current != insertionPoints->last().get());
        current = insertionPoints->last().get();
    }
}

} // namespace blink


text:
'use strict';
const Derivative = require('./Derivative');
const DerivativeNumber = require('./DerivativeNumber');
const DerivativeBoolean = require('./DerivativeBoolean');
const DerivativeString = require('./DerivativeString');
const DerivativeList = require('./DerivativeList');
const DerivativeMap = require('./DerivativeMap');

module.exports = {
    //side effects
    forEach: function (sideEffect, context) {
        return this.get().forEach(sideEffect, context);
    },

    //reading values
    getKey: function (key, notSetValue) {
        return new Derivative([this, key, notSetValue], (list, key, notSetValue) => list.get(key, notSetValue));
    },

    has: function (key) {
        return new DerivativeBoolean([this, key], (list, key) => list.has(key));
    },

    includes: function (value) {
        return new DerivativeBoolean([this, value], (list, value) => list.includes(value));
    },

    first: function () {
        return new Derivative([this], (list) => list.first());
    },

    last: function () {
        return new Derivative([this], (list) => list.last());
    },

    getSize: function () {
        return new DerivativeNumber([this], (list) => list.size);
    },

    //reducing a value
    reduce: function (reducer, initial, context) {
        return new Derivative([this, initial], (list, initial) => list.reduce(reducer, initial, context));
    },

    reduceRight: function (reducer, initialReduction, context) {
        return new Derivative([this, initial], (list, initial) => list.reduceRight(reducer, initial, context));
    },

    every: function (predicate, context) {
        return new DerivativeBoolean([this], (list) => list.every(predicate, context));
    },

    some: function (predicate, context) {
        return new DerivativeBoolean([this], (list) => list.some(predicate, context));
    },

    join: function (separator) {
        return new DerivativeString([this, separator], (list, separator) => list.join(separator));
    },

    isEmpty: function () {
        return new DerivativeBoolean([this], (list) => list.isEmpty());
    },

    count: function (predicate, context) {
        return new DerivativeNumber([this], (list) => list.count(predicate, context));
    },

    //search for value
    find: function (predicate, context, notSetValue) {
        return new Derivative([this], (list) => list.find(predicate, context, notSetValue));
    },

    findLast: function (predicate, context, notSetValue) {
        return new Derivative([this], (list) => list.findLast(predicate, context, notSetValue));
    },

    findEntry: function (predicate, context, notSetValue) {
        return new Derivative([this], (list) => list.findEntry(predicate, context, notSetValue));
    },

    findLastEntry: function (predicate, context, notSetValue) {
        return new Derivative([this], (list) => list.findLastEntry(predicate, context, notSetValue));
    },

    findKey: function (predicate, context) {
        return new Derivative([this], (list) => list.findKey(predicate, context));
    },

    findLastKey: function (predicate, context) {
        return new Derivative([this], (list) => list.findLastKey(predicate, context));
    },

    keyOf: function (searchValue) {
        return new Derivative([this, searchValue], (list, searchValue) => list.keyOf(searchValue));
    },

    lastKeyOf: function (searchValue) {
        return new Derivative([this, searchValue], (list, searchValue) => list.lastKeyOf(searchValue));
    },

    max: function (comparator) {
        return new Derivative([this], (list) => list.max(comparator));
    },

    maxBy: function (comparatorValueMapper, comparator) {
        return new Derivative([this], (list) => list.maxBy(comparatorValueMapper, comparator));
    },

    min: function (comparator) {
        return new Derivative([this], (list) => list.min(comparator));
    },

    minBy: function (comparatorValueMapper, comparator) {
        return new Derivative([this], (list) => list.minBy(comparatorValueMapper, comparator));
    },

    //comparison
    isSubset: function (iterable) {
        return new DerivativeBoolean([this, iterable], (list, iterable) => list.isSubset(iterable));
    },

    isSuperset: function (iterable) {
        return new DerivativeBoolean([this, iterable], (list, iterable) => list.isSuperset(iterable));
    },

    //conversion
    toList: function () {
        return new DerivativeList([this], (map) => map.toList());
    },

    toMap: function () {
        return new DerivativeMap([this], (list) => list.toMap());
    },
};

redpajama_set_name: RedPajamaGithub


text:
"""Tests for utility functions."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import itertools

import numpy as np

from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops.linalg import linear_operator_diag
import tensorflow.python.ops.nn_grad  # pylint: disable=unused-import
from tensorflow.python.platform import test

def _powerset(x):
  s = list(x)
  return itertools.chain.from_iterable(
      itertools.combinations(s, r) for r in range(len(s) + 1))

def _matrix_diag(d):
  """Batch version of np.diag."""
  orig_shape = d.shape
  d = np.reshape(d, (int(np.prod(d.shape[:-1])), d.shape[-1]))
  diag_list = []
  for i in range(d.shape[0]):
    diag_list.append(np.diag(d[i, ...]))
  return np.reshape(diag_list, orig_shape + (d.shape[-1],))

def _make_tril_scale(
    loc=None,
    scale_tril=None,
    scale_diag=None,
    scale_identity_multiplier=None,
    shape_hint=None):
  if scale_tril is not None:
    scale_tril = np.tril(scale_tril)
    if scale_diag is not None:
      scale_tril += _matrix_diag(np.array(scale_diag, dtype=np.float32))
    if scale_identity_multiplier is not None:
      scale_tril += (
          scale_identity_multiplier * _matrix_diag(np.ones(
              [scale_tril.shape[-1]], dtype=np.float32)))
    return scale_tril
  return _make_diag_scale(
      loc, scale_diag, scale_identity_multiplier, shape_hint)

def _make_diag_scale(
    loc=None,
    scale_diag=None,
    scale_identity_multiplier=None,
    shape_hint=None):
  if scale_diag is not None:
    scale_diag = np.asarray(scale_diag)
    if scale_identity_multiplier is not None:
      scale_diag += scale_identity_multiplier
    return _matrix_diag(scale_diag)

  if loc is None and shape_hint is None:
    return None

  if shape_hint is None:
    shape_hint = loc.shape[-1]
  if scale_identity_multiplier is None:
    scale_identity_multiplier = 1.
  return scale_identity_multiplier * np.diag(np.ones(shape_hint))

class MakeTrilScaleTest(test.TestCase):

  def _testLegalInputs(
      self, loc=None, shape_hint=None, scale_params=None):
    for args in _powerset(scale_params.items()):
      with self.test_session():
        args = dict(args)

        scale_args = dict({
            "loc": loc,
            "shape_hint": shape_hint}, **args)
        expected_scale = _make_tril_scale(**scale_args)
        if expected_scale is None:
          # Not enough shape information was specified.
          with self.assertRaisesRegexp(ValueError, ("is specified.")):
            scale = distribution_util.make_tril_scale(**scale_args)
            scale.to_dense().eval()
        else:
          scale = distribution_util.make_tril_scale(**scale_args)
          self.assertAllClose(expected_scale, scale.to_dense().eval())

  def testLegalInputs(self):
    self._testLegalInputs(
        loc=np.array([-1., -1.], dtype=np.float32),
        shape_hint=2,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [2., 3.],
            "scale_tril": [[1., 0.],
                           [-3., 3.]],
        })

  def testLegalInputsMultidimensional(self):
    self._testLegalInputs(
        loc=np.array([[[-1., -1., 2.], [-2., -3., 4.]]], dtype=np.float32),
        shape_hint=3,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [[[2., 3., 4.], [3., 4., 5.]]],
            "scale_tril": [[[[1., 0., 0.],
                             [-3., 3., 0.],
                             [1., -2., 1.]],
                            [[2., 1., 0.],
                             [-4., 7., 0.],
                             [1., -1., 1.]]]]
        })

  def testZeroTriU(self):
    with self.test_session():
      scale = distribution_util.make_tril_scale(scale_tril=[[1., 1], [1., 1.]])
      self.assertAllClose([[1., 0], [1., 1.]], scale.to_dense().eval())

  def testValidateArgs(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be non-zero"):
        scale = distribution_util.make_tril_scale(
            scale_tril=[[0., 1], [1., 1.]], validate_args=True)
        scale.to_dense().eval()

  def testAssertPositive(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be positive"):
        scale = distribution_util.make_tril_scale(
            scale_tril=[[-1., 1], [1., 1.]],
            validate_args=True,
            assert_positive=True)
        scale.to_dense().eval()

class MakeDiagScaleTest(test.TestCase):

  def _testLegalInputs(
      self, loc=None, shape_hint=None, scale_params=None):
    for args in _powerset(scale_params.items()):
      with self.test_session():
        args = dict(args)

        scale_args = dict({
            "loc": loc,
            "shape_hint": shape_hint}, **args)
        expected_scale = _make_diag_scale(**scale_args)
        if expected_scale is None:
          # Not enough shape information was specified.
          with self.assertRaisesRegexp(ValueError, ("is specified.")):
            scale = distribution_util.make_diag_scale(**scale_args)
            scale.to_dense().eval()
        else:
          scale = distribution_util.make_diag_scale(**scale_args)
          self.assertAllClose(expected_scale, scale.to_dense().eval())

  def testLegalInputs(self):
    self._testLegalInputs(
        loc=np.array([-1., -1.], dtype=np.float32),
        shape_hint=2,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [2., 3.]
        })

  def testLegalInputsMultidimensional(self):
    self._testLegalInputs(
        loc=np.array([[[-1., -1., 2.], [-2., -3., 4.]]], dtype=np.float32),
        shape_hint=3,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [[[2., 3., 4.], [3., 4., 5.]]]
        })

  def testValidateArgs(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be non-zero"):
        scale = distribution_util.make_diag_scale(
            scale_diag=[[0., 1], [1., 1.]], validate_args=True)
        scale.to_dense().eval()

  def testAssertPositive(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be positive"):
        scale = distribution_util.make_diag_scale(
            scale_diag=[[-1., 1], [1., 1.]],
            validate_args=True,
            assert_positive=True)
        scale.to_dense().eval()

class ShapesFromLocAndScaleTest(test.TestCase):

  def test_static_loc_static_scale_non_matching_event_size_raises(self):
    loc = constant_op.constant(np.zeros((2, 4)))
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    with self.assertRaisesRegexp(ValueError, "could not be broadcast"):
      distribution_util.shapes_from_loc_and_scale(loc, scale)

  def test_static_loc_static_scale(self):
    loc = constant_op.constant(np.zeros((2, 3)))
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
        loc, scale)

    self.assertEqual(tensor_shape.TensorShape([5, 2]), batch_shape)
    self.assertEqual(tensor_shape.TensorShape([3]), event_shape)

  def test_static_loc_dynamic_scale(self):
    loc = constant_op.constant(np.zeros((2, 3)))
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 1, 3))})
      self.assertAllEqual([5, 2], batch_shape)
      self.assertAllEqual([3], event_shape)

  def test_dynamic_loc_static_scale(self):
    loc = array_ops.placeholder(dtypes.float64)
    diag = constant_op.constant(np.ones((5, 2, 3)))
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session():
      batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
          loc, scale)
      # batch_shape depends on both args, and so is dynamic.  Since loc did not
      # have static shape, we inferred event shape entirely from scale, and this
      # is available statically.
      self.assertAllEqual(
          [5, 2], batch_shape.eval(feed_dict={loc: np.zeros((2, 3))}))
      self.assertAllEqual([3], event_shape)

  def test_dynamic_loc_dynamic_scale(self):
    loc = array_ops.placeholder(dtypes.float64)
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 2, 3)), loc: np.zeros((2, 3))})
      self.assertAllEqual([5, 2], batch_shape)
      self.assertAllEqual([3], event_shape)

  def test_none_loc_static_scale(self):
    loc = None
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
        loc, scale)

    self.assertEqual(tensor_shape.TensorShape([5, 1]), batch_shape)
    self.assertEqual(tensor_shape.TensorShape([3]), event_shape)

  def test_none_loc_dynamic_scale(self):
    loc = None
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 1, 3))})
      self.assertAllEqual([5, 1], batch_shape)
      self.assertAllEqual([3], event_shape)

class GetBroadcastShapeTest(test.TestCase):

  def test_all_static_shapes_work(self):
    x = array_ops.ones((2, 1, 3))
    y = array_ops.ones((1, 5, 3))
    z = array_ops.ones(())
    self.assertAllEqual([2, 5, 3],
                        distribution_util.get_broadcast_shape(x, y, z))

  def test_with_some_dynamic_shapes_works(self):
    x = array_ops.ones((2, 1, 3))
    y = array_ops.placeholder(x.dtype)
    z = array_ops.ones(())
    with self.test_session() as sess:
      bcast_shape = sess.run(
          distribution_util.get_broadcast_shape(x, y, z),
          feed_dict={y: np.ones((1, 5, 3)).astype(np.float32)})
      self.assertAllEqual([2, 5, 3], bcast_shape)

class TridiagTest(test.TestCase):

  def testWorksCorrectlyNoBatches(self):
    with self.test_session():
      self.assertAllEqual(
          [[4., 8., 0., 0.],
           [1., 5., 9., 0.],
           [0., 2., 6., 10.],
           [0., 0., 3, 7.]],
          distribution_util.tridiag(
              [1., 2., 3.],
              [4., 5., 6., 7.],
              [8., 9., 10.]).eval())

  def testWorksCorrectlyBatches(self):
    with self.test_session():
      self.assertAllClose(
          [[[4., 8., 0., 0.],
            [1., 5., 9., 0.],
            [0., 2., 6., 10.],
            [0., 0., 3, 7.]],
           [[0.7, 0.1, 0.0, 0.0],
            [0.8, 0.6, 0.2, 0.0],
            [0.0, 0.9, 0.5, 0.3],
            [0.0, 0.0, 1.0, 0.4]]],
          distribution_util.tridiag(
              [[1., 2., 3.],
               [0.8, 0.9, 1.]],
              [[4., 5., 6., 7.],
               [0.7, 0.6, 0.5, 0.4]],
              [[8., 9., 10.],
               [0.1, 0.2, 0.3]]).eval(),
          rtol=1e-5, atol=0.)

  def testHandlesNone(self):
    with self.test_session():
      self.assertAllClose(
          [[[4., 0., 0., 0.],
            [0., 5., 0., 0.],
            [0., 0., 6., 0.],
            [0., 0., 0, 7.]],
           [[0.7, 0.0, 0.0, 0.0],
            [0.0, 0.6, 0.0, 0.0],
            [0.0, 0.0, 0.5, 0.0],
            [0.0, 0.0, 0.0, 0.4]]],
          distribution_util.tridiag(
              diag=[[4., 5., 6., 7.],
                    [0.7, 0.6, 0.5, 0.4]]).eval(),
          rtol=1e-5, atol=0.)

class MixtureStddevTest(test.TestCase):

  def test_mixture_dev(self):
    mixture_weights = np.array([
        [1.0/3, 1.0/3, 1.0/3],
        [0.750, 0.250, 0.000]
    ])
    component_means = np.array([
        [1.0, 1.0, 1.0],
        [-5, 0, 1.25]
    ])
    component_devs = np.array([
        [1.0, 1.0, 1.0],
        [0.01, 2.0, 0.1]
    ])

    # The first case should trivially have a standard deviation of 1.0 because
    # all components are identical and have that standard deviation.
    # The second case was computed by hand.
    expected_devs = np.array([
        1.0,
        2.3848637277
    ])

    weights_tf = array_ops.constant(mixture_weights)
    means_tf = array_ops.constant(component_means)
    sigmas_tf = array_ops.constant(component_devs)
    mix_dev = distribution_util.mixture_stddev(weights_tf,
                                               means_tf,
                                               sigmas_tf)

    with self.test_session() as sess:
      actual_devs = sess.run(mix_dev)

    self.assertAllClose(actual_devs, expected_devs)

if __name__ == "__main__":
  test.main()


text:
package com.amazonaws.services.simplesystemsmanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Attributes are the entries within the inventory item content. It contains name and value.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InventoryItemAttribute implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Name of the inventory item attribute.
     *

     */
    private String name;
    /**
     *

     * The data type of the inventory item attribute.
     *

     */
    private String dataType;

    /**
     *

     * Name of the inventory item attribute.
     *

     *
     * @param name
     *        Name of the inventory item attribute.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * Name of the inventory item attribute.
     *

     *
     * @return Name of the inventory item attribute.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * Name of the inventory item attribute.
     *

     *
     * @param name
     *        Name of the inventory item attribute.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InventoryItemAttribute withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The data type of the inventory item attribute.
     *

     *
     * @param dataType
     *        The data type of the inventory item attribute.
     * @see InventoryAttributeDataType
     */

    public void setDataType(String dataType) {
        this.dataType = dataType;
    }

    /**
     *

     * The data type of the inventory item attribute.
     *

     *
     * @return The data type of the inventory item attribute.
     * @see InventoryAttributeDataType
     */

    public String getDataType() {
        return this.dataType;
    }

    /**
     *

     * The data type of the inventory item attribute.
     *

     *
     * @param dataType
     *        The data type of the inventory item attribute.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see InventoryAttributeDataType
     */

    public InventoryItemAttribute withDataType(String dataType) {
        setDataType(dataType);
        return this;
    }

    /**
     *

     * The data type of the inventory item attribute.
     *

     *
     * @param dataType
     *        The data type of the inventory item attribute.
     * @see InventoryAttributeDataType
     */

    public void setDataType(InventoryAttributeDataType dataType) {
        withDataType(dataType);
    }

    /**
     *

     * The data type of the inventory item attribute.
     *

     *
     * @param dataType
     *        The data type of the inventory item attribute.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see InventoryAttributeDataType
     */

    public InventoryItemAttribute withDataType(InventoryAttributeDataType dataType) {
        this.dataType = dataType.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getDataType() != null)
            sb.append("DataType: ").append(getDataType());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof InventoryItemAttribute == false)
            return false;
        InventoryItemAttribute other = (InventoryItemAttribute) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getDataType() == null ^ this.getDataType() == null)
            return false;
        if (other.getDataType() != null && other.getDataType().equals(this.getDataType()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDataType() == null) ? 0 : getDataType().hashCode());
        return hashCode;
    }

    @Override
    public InventoryItemAttribute clone() {
        try {
            return (InventoryItemAttribute) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.simplesystemsmanagement.model.transform.InventoryItemAttributeMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>KolekcionarDretvi (Mdomladov Zadaća 1)</title>
<meta name="date" content="2017-04-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.foi.nwtis.mdomladov.zadaca_1

Class KolekcionarDretvi

java.lang.Object

org.foi.nwtis.mdomladov.zadaca_1.KolekcionarDretvi

public class KolekcionarDretvi
extends java.lang.Object

Klasa za čuvanje podataka i stanja o dretvama

Author:

Marko Domladovac

Field Summary

Fields

Modifier and Type
Field and Description

protected static java.util.ArrayList<org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva>
radneDretve

Deklaracija kolekcije radnih dretvi

Constructor Summary

Constructors

Constructor and Description

KolekcionarDretvi()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static java.util.Collection<KonfDretva>
getAktivneDretve()

Dohvaćanje aktivne dretve

static <T> T
getByName(java.lang.String naziv)

Dohvaćanje aktivnih dretvi tj.

static java.util.ArrayList<org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva>
getRadneDretve()

Dohvaćanje radne dretve

static void
putAktivnaDretva(java.lang.String naziv,
                KonfDretva dretva)

Dodavanje aktivne dretve u kolekciju

static void
putRadnaDretva(org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva dretva)

Dodavanje radne dretve u kolekciju

static boolean
removeRadnaDretva(org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva dretva)

Brisanje radne dretve iz kolekcije

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

radneDretve

protected static java.util.ArrayList<org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva> radneDretve

Deklaracija kolekcije radnih dretvi

Constructor Detail

KolekcionarDretvi

public KolekcionarDretvi()

Method Detail

getByName

public static <T> T getByName(java.lang.String naziv)

Dohvaćanje aktivnih dretvi tj. dretvi sustava

Type Parameters:

T -

Parameters:

naziv -

Returns:

removeRadnaDretva

public static boolean removeRadnaDretva(org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva dretva)

Brisanje radne dretve iz kolekcije

Parameters:

dretva -

Returns:

putAktivnaDretva

public static void putAktivnaDretva(java.lang.String naziv,
                                    KonfDretva dretva)

Dodavanje aktivne dretve u kolekciju

Parameters:

naziv -

dretva -

putRadnaDretva

public static void putRadnaDretva(org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva dretva)

Dodavanje radne dretve u kolekciju

Parameters:

dretva -

getAktivneDretve

public static java.util.Collection<KonfDretva> getAktivneDretve()

Dohvaćanje aktivne dretve

Returns:

getRadneDretve

public static java.util.ArrayList<org.foi.nwtis.mdomladov.zadaca_1.RadnaDretva> getRadneDretve()

Dohvaćanje radne dretve

Returns:

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © NWTiS mdomladov


text:
package bammerbom.ultimatecore.sponge.modules.food.commands;

import bammerbom.ultimatecore.sponge.api.command.HighCommand;
import bammerbom.ultimatecore.sponge.api.command.annotations.CommandInfo;
import bammerbom.ultimatecore.sponge.api.command.argument.Arguments;
import bammerbom.ultimatecore.sponge.api.command.argument.arguments.PlayerArgument;
import bammerbom.ultimatecore.sponge.api.language.utils.Messages;
import bammerbom.ultimatecore.sponge.api.permission.Permission;
import bammerbom.ultimatecore.sponge.modules.food.FoodModule;
import bammerbom.ultimatecore.sponge.modules.food.api.FoodPermissions;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.entity.FoodData;
import org.spongepowered.api.data.property.item.SaturationProperty;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.text.Text;

import java.util.Arrays;
import java.util.List;

@CommandInfo(module = FoodModule.class, aliases = {"food", "feed", "eat"})
public class FoodCommand implements HighCommand {
    @Override
    public Permission getPermission() {
        return FoodPermissions.UC_FOOD_FOOD_BASE;
    }

    @Override
    public List<Permission> getPermissions() {
        return Arrays.asList(FoodPermissions.UC_FOOD_FOOD_BASE, FoodPermissions.UC_FOOD_FOOD_OTHERS);
    }

    @Override
    public CommandElement[] getArguments() {
        return new CommandElement[]{
                Arguments.builder(new PlayerArgument(Text.of("player"))).optional().onlyOne().build()
        };
    }

    @Override
    public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
        checkPermission(sender, FoodPermissions.UC_FOOD_FOOD_BASE);
        if (!args.hasAny("player")) {
            checkIfPlayer(sender);
            Player p = (Player) sender;
            p.offer(Keys.FOOD_LEVEL, p.get(FoodData.class).get().foodLevel().getMaxValue());
            p.offer(Keys.SATURATION, ItemStack.builder().itemType(ItemTypes.COOKED_BEEF).build().getProperty(SaturationProperty.class).get().getValue());
            Messages.send(p, "food.command.food.success.self");
            return CommandResult.success();
        } else {
            checkPermission(sender, FoodPermissions.UC_FOOD_FOOD_OTHERS);
            Player t = args.<Player>getOne("player").get();
            t.offer(Keys.FOOD_LEVEL, t.get(FoodData.class).get().foodLevel().getMaxValue());
            t.offer(Keys.SATURATION, ItemStack.builder().itemType(ItemTypes.COOKED_BEEF).build().getProperty(SaturationProperty.class).get().getValue());
            Messages.send(sender, "food.command.food.success.others.self", "%player%", t);
            Messages.send(t, "food.command.food.success.others.others", "%player%", sender);
            return CommandResult.success();
        }
    }
}


text:
namespace Sp.Samples.BuildIntegration
{
	partial class SpAgent
	{
		// NOTE: This value needs to reflect the specific permutation package you are using to protect your app
		const string PermutationShortId = "c638d";
	 }
}


text:
using Signum.Entities.Workflow;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Linq.Expressions;
using System.Xml;

namespace Signum.Engine.Workflow
{
    public partial class WorkflowBuilder
    {
        public static readonly XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        public static readonly XNamespace bpmn = "http://www.omg.org/spec/BPMN/20100524/MODEL";
        public static readonly XNamespace bpmndi = "http://www.omg.org/spec/BPMN/20100524/DI";
        public static readonly XNamespace dc = "http://www.omg.org/spec/DD/20100524/DC";
        public static readonly XNamespace di = "http://www.omg.org/spec/DD/20100524/DI";
        public static readonly string targetNamespace = "http://bpmn.io/schema/bpmn";

        private Dictionary<Lite<WorkflowPoolEntity>, PoolBuilder> pools;
        private List<XmlEntity<WorkflowConnectionEntity>> messageFlows; //Contains the connections that cross two different Pools EXCLUDING the connections internal to each pool
        private WorkflowEntity workflow;

        public WorkflowBuilder(WorkflowEntity wf)
        {
            using (HeavyProfiler.Log("WorkflowBuilder"))
            using (new EntityCache())
            {
                this.workflow = wf;

                List<WorkflowConnectionEntity> connections;
                List<WorkflowEventEntity> events;
                List<WorkflowActivityEntity> activities;
                List<WorkflowGatewayEntity> gateways;
                List<WorkflowLaneEntity> lanes;
                List<WorkflowPoolEntity> poolEntities;

                if (wf.IsNew)
                {
                    connections = new List<WorkflowConnectionEntity>();
                    events = new List<WorkflowEventEntity>();
                    activities = new List<WorkflowActivityEntity>();
                    gateways = new List<WorkflowGatewayEntity>();
                    lanes = new List<WorkflowLaneEntity>();
                    poolEntities = new List<WorkflowPoolEntity>();
                }
                else
                {
                    connections = wf.WorkflowConnections().ToList();
                    events = wf.WorkflowEvents().ToList();
                    activities = wf.WorkflowActivities().ToList();
                    gateways = wf.WorkflowGateways().ToList();
                    lanes = wf.WorkflowPools().SelectMany(a => a.WorkflowLanes()).ToList();
                    poolEntities = wf.WorkflowPools().ToList();
                }

                var xmlConnections = connections.Select(a => new XmlEntity<WorkflowConnectionEntity>(a)).ToList();
                var nodes = events.Cast<IWorkflowNodeEntity>().Concat(activities).Concat(gateways).ToList();

                this.pools = (from pool in poolEntities
                              let laneBuilders = (from lane in lanes
                                                  where lane.Pool.Is(pool)
                                                  select new LaneBuilder(lane,
                                                  activities.Where(a => a.Lane.Is(lane)),
                                                  events.Where(a => a.Lane.Is(lane)),
                                                  gateways.Where(a => a.Lane.Is(lane)),
                                                  xmlConnections.Where(c => c.Entity.From.Lane.Is(lane) || c.Entity.To.Lane.Is(lane))))

                              let sequenceFlows = xmlConnections.Where(c => c.Entity.From.Lane.Pool.Is(pool) && c.Entity.To.Lane.Pool.Is(pool))

                              select new PoolBuilder(pool, laneBuilders, sequenceFlows))
                              .ToDictionary(a=>a.pool.Entity.ToLite());

                this.messageFlows = xmlConnections.Where(c => !c.Entity.From.Lane.Pool.Is(c.Entity.To.Lane.Pool)).ToList();

            }
        }

        internal WorkflowModel GetWorkflowModel()
        {
            XDocument xml = GetXDocument();

            Dictionary<string, ModelEntity> dic = new Dictionary<string, ModelEntity>();

            dic.AddRange(this.pools.Values.Select(pb => pb.pool.ToModelKVP()));

            var lanes = this.pools.Values.SelectMany(pb => pb.GetLanes());
            dic.AddRange(lanes.Select(lb => lb.lane.ToModelKVP()));

            dic.AddRange(lanes.SelectMany(lb => lb.GetActivities()).Select(a => a.ToModelKVP()));

            // Only Start events because end event has no model and extra properties for now
            dic.AddRange(lanes.SelectMany(lb => lb.GetEvents().Where(e => e.Entity.Type.IsStart() || e.Entity.Type == WorkflowEventType.IntermediateTimer)).Select(a => a.ToModelKVP()));

            dic.AddRange(this.messageFlows.Select(mf => mf.ToModelKVP()));
            dic.AddRange(this.pools.Values.SelectMany(pb => pb.GetSequenceFlows()).Select(sf => sf.ToModelKVP()));

            return new WorkflowModel
            {
                DiagramXml = xml.ToString(),
                Entities = dic.Select(kvp => new BpmnEntityPairEmbedded { BpmnElementId = kvp.Key, Model = kvp.Value }).ToMList()
            };
        }

        public static XDocument ParseDocument(string diagramXml)
        {
            XmlNamespaceManager nmgr = new XmlNamespaceManager(new NameTable());
            nmgr.AddNamespace("xsi", WorkflowBuilder.xsi.NamespaceName);
            nmgr.AddNamespace("bpmn", WorkflowBuilder.bpmn.NamespaceName);
            nmgr.AddNamespace("bpmndi", WorkflowBuilder.bpmndi.NamespaceName);
            nmgr.AddNamespace("dc", WorkflowBuilder.dc.NamespaceName);
            nmgr.AddNamespace("di", WorkflowBuilder.di.NamespaceName);

            XmlParserContext pctx = new XmlParserContext(null, nmgr, null, XmlSpace.None);
            XmlTextReader reader = new XmlTextReader(diagramXml, XmlNodeType.Document, pctx);

            return XDocument.Load(reader);
        }

        public XDocument GetXDocument()
        {
            return new XDocument(
              new XDeclaration("1.0", "UTF-8", null),
                  new XElement(bpmn + "definitions",
                      new XAttribute(XNamespace.Xmlns + "bpmn", bpmn.NamespaceName),
                      new XAttribute(XNamespace.Xmlns + "bpmndi", bpmndi.NamespaceName),
                      new XAttribute(XNamespace.Xmlns + "dc", dc.NamespaceName),
                      new XAttribute(XNamespace.Xmlns + "di", di.NamespaceName),
                      new XAttribute("targetNamespace", targetNamespace),
                      new XElement(bpmn + "collaboration",
                        new XAttribute("id", "Collaboration_" + workflow.Id),
                        pools.Values.Select(a => a.GetParticipantElement()).ToList(),
                        GetMessageFlowElements()),
                      GetProcesses(),
                      new XElement(bpmndi + "BPMNDiagram",
                          new XAttribute("id", "BPMNDiagram" + workflow.Id),
                          new XElement(bpmndi + "BPMNPlane",
                              new XAttribute("id", "BPMNPlane_" + workflow.Id),
                              new XAttribute("bpmnElement", "Collaboration_" + workflow.Id),
                              GetDiagramElements()))));
        }

        internal List<XElement> GetMessageFlowElements()
        {
            return messageFlows.Select(a =>
                new XElement(bpmn + "messageFlow",
                    new XAttribute("id", a.bpmnElementId),
                    a.Entity.Name.HasText() ? new XAttribute("name", a.Entity.Name) : null!,
                    new XAttribute("sourceRef", GetBpmnElementId(a.Entity.From)),
                    new XAttribute("targetRef", GetBpmnElementId(a.Entity.To))
                )
            ).ToList();
        }

        internal List<XElement> GetProcesses()
        {
            return pools.Values.Select(a => a.GetProcessElement()).ToList();
        }

        internal List<XElement> GetDiagramElements()
        {
            List<XElement> res = new List<XElement>();
            res.AddRange(pools.Values.SelectMany(a => a.GetDiagramElements()).ToList());
            res.AddRange(messageFlows.Select(a => a.Element));
            return res;
        }

        public void ApplyChanges(WorkflowModel model, WorkflowReplacementModel? replacements)
        {
            var document =  WorkflowBuilder.ParseDocument(model.DiagramXml);

            var participants = document.Descendants(bpmn + "collaboration").Elements(bpmn + "participant").ToDictionaryEx(a => a.Attribute("id")!.Value);
            var processElements = document.Descendants(bpmn + "process").ToDictionaryEx(a => a.Attribute("id")!.Value);
            var diagramElements = document.Descendants(bpmndi + "BPMNPlane").Elements().ToDictionaryEx(a => a.Attribute("bpmnElement")!.Value, "bpmnElement");

            if (participants.Count != processElements.Count)
                throw new InvalidOperationException(WorkflowValidationMessage.ParticipantsAndProcessesAreNotSynchronized.NiceToString());

            Locator locator = new Workflow.Locator(this, diagramElements, model, replacements);

            var messageFlows = document.Descendants(bpmn + "collaboration").Elements(bpmn + "messageFlow").ToDictionaryEx(a => a.Attribute("id")!.Value);
            var oldMessageFlows = this.messageFlows.ToDictionaryEx(a => a.bpmnElementId, "messageFlows");

            Synchronizer.Synchronize(messageFlows, oldMessageFlows,
               null,
               (id, omf) =>
               {
                   this.messageFlows.Remove(omf);
                   omf.Entity.Delete(WorkflowConnectionOperation.Delete);
               },
               (id, mf, omf) =>
               {
                   omf.Entity.ApplyXml(mf, locator);
               });

            var oldPools = this.pools.Values.ToDictionaryEx(a => a.pool.bpmnElementId, "pools");
            Synchronizer.Synchronize(participants, oldPools,
                createNew: (id, pa) =>
                {
                    var wp = new WorkflowPoolEntity { Xml = new WorkflowXmlEmbedded(), Workflow = this.workflow }.ApplyXml(pa, locator);
                    var pb = new PoolBuilder(wp, Enumerable.Empty<LaneBuilder>(), Enumerable.Empty<XmlEntity<WorkflowConnectionEntity>>());
                    this.pools.Add(wp.ToLite(), pb);
                    pb.ApplyChanges(processElements.GetOrThrow(pa.Attribute("processRef")!.Value), locator);
                },
                removeOld: null,
                merge: (id, pa, pb) =>
                {
                    var wp = pb.pool.Entity.ApplyXml(pa, locator);
                    pb.ApplyChanges(processElements.GetOrThrow(pa.Attribute("processRef")!.Value), locator);
                });

            Synchronizer.Synchronize(participants, oldPools,
                createNew: null,
                removeOld: (id, pb) =>
                {
                    this.pools.Remove(pb.pool.Entity.ToLite());
                    pb.pool.Entity.Delete(WorkflowPoolOperation.Delete);
                },
                merge: null);

            Synchronizer.Synchronize(messageFlows, oldMessageFlows,
                (id, mf) =>
                {
                    var wc = new WorkflowConnectionEntity { Xml = new WorkflowXmlEmbedded() }.ApplyXml(mf, locator);
                    this.messageFlows.Add(new XmlEntity<WorkflowConnectionEntity>(wc));
                },
                null,
                (id, mf, omf) =>
                {
                    omf.Entity.ApplyXml(mf, locator);
                });
        }

        internal IWorkflowNodeEntity? FindEntity(string bpmElementId)
        {
            return this.pools.Values.Select(pb => pb.FindEntity(bpmElementId)).NotNull().SingleOrDefaultEx();
        }

        internal LaneBuilder FindLane(WorkflowLaneEntity lane)
        {
            return this.pools.Values.SelectMany(a => a.GetLanes()).Single(l => l.lane.Entity.Is(lane));
        }

        private string GetBpmnElementId(IWorkflowNodeEntity node)
        {
            return this.pools.GetOrThrow(node.Lane.Pool.ToLite()).GetLaneBuilder(node.Lane.ToLite()).GetBpmnElementId(node);
        }

        public WorkflowReplacementModel PreviewChanges(XDocument document, WorkflowModel model)
        {
            var oldTasks = this.pools.Values.SelectMany(p => p.GetAllActivities()).Select(a=>a.Entity);
            var oldIntermediateEvents = this.pools.Values.SelectMany(p => p.GetLanes().SelectMany(l => l.GetEvents().Where(e => e.Entity.Type == WorkflowEventType.IntermediateTimer))).Select(a => a.Entity);
            var oldNodes = oldTasks.Cast<IWorkflowNodeEntity>().Concat(oldIntermediateEvents.Cast<IWorkflowNodeEntity>()).ToDictionary(node => node.BpmnElementId);

            var newNodes = document.Descendants().Where(a => LaneBuilder.WorkflowActivityTypes.Values.Contains(a.Name.LocalName) || a.Name.LocalName == LaneBuilder.WorkflowEventTypes[WorkflowEventType.IntermediateTimer])
                .ToDictionary(a => a.Attribute("id")!.Value);

            var entities = model.Entities.ToDictionaryEx(a => a.BpmnElementId);

            return new WorkflowReplacementModel
            {
                Replacements = oldNodes.Where(kvp => !newNodes.ContainsKey(kvp.Key) && kvp.Value.CaseActivities().Any())
                .Select(a => new WorkflowReplacementItemEmbedded
                {
                    OldNode = a.Value.ToLite(),
                    SubWorkflow = (a.Value as WorkflowActivityEntity)?.SubWorkflow?.Workflow.ToLite()
                })
                .ToMList(),

                NewTasks = newNodes.Select(kvp => new NewTasksEmbedded
                {
                    BpmnId = kvp.Key,
                    Name = kvp.Value.Attribute("name")?.Value!,
                    SubWorkflow = (entities.GetOrThrow(kvp.Key).Model as WorkflowActivityModel)?.SubWorkflow?.Workflow.ToLite()
                }).ToMList(),
            };
        }

        internal WorkflowEntity Clone()
        {
            var newName = 0.To(1000).Select(i => $"Copy{(i == 0 ? "" : $" ({i})")} of {this.workflow.Name}").FirstEx(s => !Database.Query<WorkflowEntity>().Any(w => w.Name == s));

            WorkflowEntity newWorkflow = new WorkflowEntity
            {
                Name = newName,
                MainEntityType = this.workflow.MainEntityType,
                ExpirationDate = this.workflow.ExpirationDate,
            };
            newWorkflow.MainEntityStrategies.AddRange(this.workflow.MainEntityStrategies);
            newWorkflow.Save();

            Dictionary<IWorkflowNodeEntity, IWorkflowNodeEntity> nodes = new Dictionary<IWorkflowNodeEntity, IWorkflowNodeEntity>();

            using (OperationLogic.AllowSave<WorkflowPoolEntity>())
            using (OperationLogic.AllowSave<WorkflowLaneEntity>())
            using (OperationLogic.AllowSave<WorkflowActivityEntity>())
            using (OperationLogic.AllowSave<WorkflowGatewayEntity>())
            using (OperationLogic.AllowSave<WorkflowEventEntity>())
            {
                foreach (var pb in this.pools.Values)
                {
                    pb.Clone(newWorkflow, nodes);
                }
            }

            using (OperationLogic.AllowSave<WorkflowConnectionEntity>())
            {
                var allConnections = GetAllConnections().ToDictionaryEx(a => a.bpmnElementId);
                allConnections.Values.Select(c => new WorkflowConnectionEntity
                {
                    Name = c.Entity.Name,
                    BpmnElementId = c.bpmnElementId,
                    Action = c.Entity.Action,
                    Condition = c.Entity.Condition,
                    Type = c.Entity.Type,
                    Order = c.Entity.Order,
                    Xml = c.Entity.Xml,
                    From = nodes.GetOrThrow(c.Entity.From),
                    To = nodes.GetOrThrow(c.Entity.To),
                }).SaveList();
            }

            foreach (var item in nodes.Where(a => a.Key is WorkflowEventEntity e && e.Type.IsScheduledStart()))
            {
                WorkflowEventTaskLogic.CloneScheduledTasks((WorkflowEventEntity)item.Key, (WorkflowEventEntity)item.Value);
            }

            WorkflowBuilder wb = new WorkflowBuilder(newWorkflow);
            newWorkflow.FullDiagramXml = new WorkflowXmlEmbedded { DiagramXml = wb.GetXDocument().ToString() };
            newWorkflow.Save();

            return newWorkflow;
        }

        public void Delete() {
            Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool.Workflow.Is(this.workflow)).UnsafeDelete();
            Database.Query<WorkflowConnectionEntity>().Where(a => a.To.Lane.Pool.Workflow.Is(this.workflow)).UnsafeDelete();
            this.pools.SingleEx().Value.DeleteAll(null);
            this.workflow.Cases().UnsafeDelete();
            this.workflow.Delete();
        }

        private void DeleteCases(Expression<Func<CaseEntity, bool>> filter)
        {
            this.pools.SingleEx().Value.DeleteCaseActivities(filter);
            Database.Query<CaseEntity>()
                .Where(c => c.Workflow.Is(this.workflow) && filter.Evaluate(c))
                .UnsafeDelete();
        }

        private IEnumerable<XmlEntity<WorkflowConnectionEntity>> GetAllConnections()
        {
            return this.messageFlows.Concat(this.pools.Values.SelectMany(p => p.GetSequenceFlows()));
        }

        public void ValidateGraph(List<WorkflowIssue> issuesContainer)
        {
            WorkflowNodeGraph wg = new WorkflowNodeGraph
            {
                Workflow = this.workflow,
                Activities = this.pools.SelectMany(p => p.Value.GetLanes().SelectMany(l => l.GetActivities())).Select(a => a.Entity).ToDictionary(a => a.ToLite()),
                Events = this.pools.SelectMany(p => p.Value.GetLanes().SelectMany(l => l.GetEvents())).Select(a => a.Entity).ToDictionary(a => a.ToLite()),
                Gateways = this.pools.SelectMany(p => p.Value.GetLanes().SelectMany(l => l.GetGateways())).Select(a => a.Entity).ToDictionary(a => a.ToLite()),
                Connections = this.GetAllConnections().Select(a => a.Entity).ToDictionary(a => a.ToLite()),
            };

            wg.FillGraphs();
            wg.Validate(issuesContainer, (g, newDirection) =>
            {
                g.Direction = newDirection;
                g.Execute(WorkflowGatewayOperation.Save);
            });
        }
    }

    public class Locator
    {
        WorkflowBuilder wb;
        Dictionary<string, XElement> diagramElements;
        Dictionary<string, ModelEntity> entitiesFromModel;

        public Locator(WorkflowBuilder wb, Dictionary<string, XElement> diagramElements, WorkflowModel model, WorkflowReplacementModel? replacements)
        {
            this.wb = wb;
            this.diagramElements = diagramElements;
            this.Replacements = (replacements?.Replacements).EmptyIfNull().ToDictionary(a => a.OldNode!, a => a.NewNode!);
            this.entitiesFromModel = model.Entities.ToDictionary(a => a.BpmnElementId!, a => a.Model!);
        }

        public IWorkflowNodeEntity? FindEntity(string bpmElementId)
        {
            return wb.FindEntity(bpmElementId);
        }

        internal WorkflowBuilder.LaneBuilder FindLane(WorkflowLaneEntity lane)
        {
            return wb.FindLane(lane);
        }

        public bool ExistDiagram(string bpmElementId)
        {
            return diagramElements.ContainsKey(bpmElementId);
        }

        public XElement GetDiagram(string bpmElementId)
        {
            return diagramElements.GetOrThrow(bpmElementId);
        }

        public Dictionary<Lite<IWorkflowNodeEntity>, string> Replacements;
        public IWorkflowNodeEntity? GetReplacement(Lite<IWorkflowNodeEntity> lite)
        {
            string bpmnElementId = Replacements.GetOrThrow(lite);
            return this.FindEntity(bpmnElementId);
        }

        internal T? GetModelEntity<T>(string bpmnElementId)
            where T : ModelEntity, new()
        {
            return (T?)this.entitiesFromModel.TryGetC(bpmnElementId);
        }

        internal bool HasReplacement(Lite<IWorkflowNodeEntity> lite)
        {
            return Replacements.GetOrThrow(lite).HasText();
        }
    }

    public static class NodeEntityExtensions
    {
        public static WorkflowPoolEntity ApplyXml(this WorkflowPoolEntity wp, XElement participant, Locator locator)
        {
            var bpmnElementId = participant.Attribute("id")!.Value;
            var model = locator.GetModelEntity<WorkflowPoolModel>(bpmnElementId);
            if (model != null)
                wp.SetModel(model);
            wp.BpmnElementId = bpmnElementId;
            wp.Name = participant.Attribute("name")!.Value;
            wp.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();
            if (GraphExplorer.HasChanges(wp))
                wp.Execute(WorkflowPoolOperation.Save);
            return wp;
        }

        public static WorkflowLaneEntity ApplyXml(this WorkflowLaneEntity wl, XElement lane, Locator locator)
        {
            var bpmnElementId = lane.Attribute("id")!.Value;
            var model = locator.GetModelEntity<WorkflowLaneModel>(bpmnElementId);
            if (model != null)
                wl.SetModel(model);
            wl.BpmnElementId = bpmnElementId;
            wl.Name = lane.Attribute("name")!.Value;
            wl.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();
            if (GraphExplorer.HasChanges(wl))
                wl.Execute(WorkflowLaneOperation.Save);

            return wl;
        }

        public static WorkflowEventEntity ApplyXml(this WorkflowEventEntity we, XElement @event, Locator locator)
        {
            var bpmnElementId = @event.Attribute("id")!.Value;
            we.BpmnElementId = bpmnElementId;
            var model = locator.GetModelEntity<WorkflowEventModel>(bpmnElementId);
            if (model != null)
                we.SetModel(model);
            else
            {
                we.Name = @event.Attribute("name")?.Value;
                we.Type = WorkflowBuilder.LaneBuilder.WorkflowEventTypes.First(kvp => kvp.Value == @event.Name.LocalName).Key;
            }

            we.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();

            if (GraphExplorer.HasChanges(we))
                we.Execute(WorkflowEventOperation.Save);

            if (model != null)
                WorkflowEventTaskModel.ApplyModel(we, model.Task);

            return we;
        }

        public static WorkflowActivityEntity ApplyXml(this WorkflowActivityEntity wa, XElement activity, Locator locator, Dictionary<string, XmlEntity<WorkflowEventEntity>> currentEvents)
        {
            var bpmnElementId = activity.Attribute("id")!.Value;
            var model = locator.GetModelEntity<WorkflowActivityModel>(bpmnElementId);
            if (model != null)
            {
                wa.SetModel(model);

                var oldTimers = wa.BoundaryTimers.ToDictionaryEx(a => a.BpmnElementId, "oldTimers");
                var timers = model.BoundaryTimers.ToDictionaryEx(a => a.BpmnElementId, "newTimers");

                Synchronizer.Synchronize(timers, oldTimers,
                    (id, m) =>
                    {
                        var we = new WorkflowEventEntity()
                        {
                            Name = m.Name,
                            Lane = wa.Lane,
                            BpmnElementId = id,
                            Xml = new WorkflowXmlEmbedded() { DiagramXml = locator.GetDiagram(id).ToString() },
                            Type = m.Type,
                            Timer = m.Timer,
                        };
                        wa.BoundaryTimers.Add(we);
                        currentEvents.Add(id, new XmlEntity<WorkflowEventEntity>(we));
                    },

                    (id, e) =>
                    {
                        wa.BoundaryTimers.Remove(e);
                        currentEvents.Remove(id);
                    },

                    (id, m,  e) =>
                    {
                        e.Xml.DiagramXml = locator.GetDiagram(id).ToString();
                        e.SetModel(m);
                    });
            }
            wa.BpmnElementId = bpmnElementId;
            wa.Name = activity.Attribute("name")?.Value ?? bpmnElementId;
            wa.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();
            if (GraphExplorer.HasChanges(wa))
                wa.Execute(WorkflowActivityOperation.Save);

            return wa;
        }

        public static WorkflowGatewayEntity ApplyXml(this WorkflowGatewayEntity wg, XElement gateway, Locator locator)
        {
            var bpmnElementId = gateway.Attribute("id")!.Value;
            wg.BpmnElementId = bpmnElementId;
            wg.Name = gateway.Attribute("name")?.Value;
            wg.Type = WorkflowBuilder.LaneBuilder.WorkflowGatewayTypes.Single(kvp => kvp.Value == gateway.Name.LocalName).Key;
            wg.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();
            if (GraphExplorer.HasChanges(wg))
                wg.Execute(WorkflowGatewayOperation.Save);

            return wg;
        }

        public static WorkflowConnectionEntity ApplyXml(this WorkflowConnectionEntity wc, XElement flow, Locator locator)
        {
            wc.From = locator.FindEntity(flow.Attribute("sourceRef")!.Value)!;
            wc.To = locator.FindEntity(flow.Attribute("targetRef")!.Value)!;

            var bpmnElementId = flow.Attribute("id")!.Value;
            var model = locator.GetModelEntity<WorkflowConnectionModel>(bpmnElementId);
            if (model != null)
                wc.SetModel(model);
            wc.BpmnElementId = bpmnElementId;

            var name = flow.Attribute("name")?.Value;
            if (name != null)
                name = (name.TryBeforeLast(":") ?? name);

            if (model != null && model.Order.HasValue)
                name = name + ": " + model.Order.ToString();

            wc.Name = name;
            wc.Xml.DiagramXml = locator.GetDiagram(bpmnElementId).ToString();

            var gateway = (wc.From as WorkflowGatewayEntity);

            if (gateway == null || gateway.Type != WorkflowGatewayType.Exclusive)
            {
                wc.Order = null;
            };

            if (gateway == null || gateway.Type == WorkflowGatewayType.Parallel)
                wc.Condition = null;

            if (GraphExplorer.HasChanges(wc))
                wc.Execute(WorkflowConnectionOperation.Save);
            return wc;
        }
    }

    public class XmlEntity<T>
    where T : Entity, IWorkflowObjectEntity, IWithModel
    {
        public XmlEntity(T entity)
        {
            var finalXml = @"<bpmn:definitions xmlns:xsi = " + ToQuoted(WorkflowBuilder.xsi.ToString()) + " " +
                          @"xmlns:bpmn = " + ToQuoted(WorkflowBuilder.bpmn.ToString()) + " " +
                          @"xmlns:bpmndi = " + ToQuoted(WorkflowBuilder.bpmndi.ToString()) + " " +
                          @"xmlns:dc = " + ToQuoted(WorkflowBuilder.dc.ToString()) + " " +
                          @"xmlns:di = " + ToQuoted(WorkflowBuilder.di.ToString()) + @" id = ""Definitions_1"" targetNamespace = " + ToQuoted(WorkflowBuilder.targetNamespace) + " > " +
                          @"<bpmndi:BPMNDiagram id = ""BPMNDiagram_1"" >"
                           + entity.Xml.DiagramXml +
                          @"</bpmndi:BPMNDiagram>" +
                          @"</bpmn:definitions>";

            Entity = entity;
            Document = XDocument.Parse(finalXml);
            this.Element = Document.Root!.Element(WorkflowBuilder.bpmndi + "BPMNDiagram")!.Elements().First();
            bpmnElementId = Element.Attribute("bpmnElement")!.Value;
        }

        public XDocument Document;
        public XElement Element { get; private set; }
        public string bpmnElementId;

        public T Entity;

        public KeyValuePair<string, Entity> ToKVP() => new KeyValuePair<string, Entity>(bpmnElementId, Entity);
        public KeyValuePair<string, ModelEntity> ToModelKVP() => new KeyValuePair<string, ModelEntity>(bpmnElementId, Entity.GetModel());

        public override string ToString() => $"{bpmnElementId} {Entity.GetType().Name} {Entity.GetName()}";

        public string ToQuoted(string str)
        {
            return "\"" + str + "\"";
        }
    }

}


text:
'use strict';
const AddonSocketOn = require('../addon/socket_on');

class TaskQRCodeSocketOn extends AddonSocketOn {
    static get socketEventKeys () {
        return ['qrHover', 'qrPick', 'qrScrollStage', 'qrScrollUser'];
    }

    static qrHover (socketProject, user, {taskId}) {
        socketProject.emits(user, 'qrHover', {taskId});
        return Promise.resolve();
    }

    static qrPick (socketProject, user, {taskId}) {
        socketProject.emits(user, 'qrPick', {taskId});
        return Promise.resolve();
    }

    static qrScrollStage (socketProject, user, {stageId, dy}) {
        socketProject.emits(user, 'qrScrollStage', {stageId, dy});
        return Promise.resolve();
    }

    static qrScrollUser (socketProject, user, {dy}) {
        socketProject.emits(user, 'qrScrollUser', {dy});
        return Promise.resolve();
    }
}

module.exports = TaskQRCodeSocketOn;


text:
package com.vaadin.client.widget.escalator;

import com.google.gwt.dom.client.Element;

/**
 * A representation of a spacer element in a
 * {@link com.vaadin.client.widget.escalator.RowContainer.BodyRowContainer}.
 *
 * @since 7.5.0
 * @author Vaadin Ltd
 */
public interface Spacer {

    /**
     * Gets the root element for the spacer content.
     *
     * @return the root element for the spacer content
     */
    Element getElement();

    /**
     * Gets the decorative element for this spacer.
     */
    Element getDecoElement();

    /**
     * Gets the row index.
     *
     * @return the row index.
     */
    int getRow();
}


text:
<?php

// =============================================================================
// FUNCTIONS/GLOBAL/CONDITIONALS.PHP
// -----------------------------------------------------------------------------
// Conditional functions to check the status of various locations.
// =============================================================================

// =============================================================================
// TABLE OF CONTENTS
// -----------------------------------------------------------------------------
//   01. Is Blank Page Template
//   02. Is Portfolio
//   03. Is Portfolio Item
//   04. Is Portfolio Category
//   05. Is Portfolio Tag
//   06. Is Shop
//   07. Is Product
//   08. Is Product Category
//   09. Is Product Tag
//   10. Is Product Index
//   11. Is bbPress
//   12. Is BuddyPress
//   13. Is BuddyPress Activity Directory
//   14. Is BuddyPress Groups Directory
//   15. Is BuddyPress Group
//   16. Is BuddyPress Members Directory
//   17. Is BuddyPress User
//   18. Is BuddyPress Blogs Directory
//   19. Is BuddyPress Component
// =============================================================================

// Is Blank Page Template
// =============================================================================

//
// Integers 1-8 are acceptible inputs.
//

function x_is_blank( $number ) {

  if ( is_page_template( 'template-blank-' . $number . '.php' ) ) {
    return true;
  } else {
    return false;
  }

}

// Is Portfolio
// =============================================================================

function x_is_portfolio() {

  if ( is_page_template( 'template-layout-portfolio.php' ) ) {
    return true;
  } else {
    return false;
  }

}

// Is Portfolio Item
// =============================================================================

function x_is_portfolio_item() {

  if ( is_singular( 'x-portfolio' ) ) {
    return true;
  } else {
    return false;
  }

}

// Is Portfolio Category
// =============================================================================

function x_is_portfolio_category() {

  if ( is_tax( 'portfolio-category' ) ) {
    return true;
  } else {
    return false;
  }

}

// Is Portfolio Tag
// =============================================================================

function x_is_portfolio_tag() {

  if ( is_tax( 'portfolio-tag' ) ) {
    return true;
  } else {
    return false;
  }

}

// Is Shop
// =============================================================================

function x_is_shop() {

  if ( function_exists( 'is_shop' ) && is_shop() ) {
    return true;
  } else {
    return false;
  }

}

// Is Product
// =============================================================================

function x_is_product() {

  if ( function_exists( 'is_product' ) && is_product() ) {
    return true;
  } else {
    return false;
  }

}

// Is Product Category
// =============================================================================

function x_is_product_category() {

  if ( function_exists( 'is_product_category' ) && is_product_category() ) {
    return true;
  } else {
    return false;
  }

}

// Is Product Tag
// =============================================================================

function x_is_product_tag() {

  if ( function_exists( 'is_product_tag' ) && is_product_tag() ) {
    return true;
  } else {
    return false;
  }

}

// Is Product Index
// =============================================================================

function x_is_product_index() {

  if ( x_is_shop() || x_is_product_category() || is_product_tag() ) {
    return true;
  } else {
    return false;
  }

}

// Is bbPress
// =============================================================================

function x_is_bbpress() {

  if ( function_exists( 'is_bbpress' ) && is_bbpress() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress
// =============================================================================

function x_is_buddypress() {

  if ( function_exists( 'is_buddypress' ) && is_buddypress() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Activity Directory
// =============================================================================

function x_is_buddypress_activity_directory() {

  if ( function_exists( 'bp_is_activity_directory' ) && bp_is_activity_directory() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Groups Directory
// =============================================================================

function x_is_buddypress_groups_directory() {

  if ( function_exists( 'bp_is_groups_directory' ) && bp_is_groups_directory() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Group
// =============================================================================

function x_is_buddypress_group() {

  if ( function_exists( 'bp_is_group' ) && bp_is_group() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Members Directory
// =============================================================================

function x_is_buddypress_members_directory() {

  if ( function_exists( 'bp_is_members_directory' ) && bp_is_members_directory() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress User
// =============================================================================

function x_is_buddypress_user() {

  if ( function_exists( 'bp_is_user' ) && bp_is_user() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Blogs Directory
// =============================================================================

function x_is_buddypress_blogs_directory() {

  if ( function_exists( 'bp_is_blogs_directory' ) && bp_is_blogs_directory() ) {
    return true;
  } else {
    return false;
  }

}

// Is BuddyPress Component
// =============================================================================

//
// Component values.
//
// 01. members
// 02. xprofile
// 03. activity
// 04. blogs
// 05. messages
// 06. friends
// 07. groups
// 08. forums
// 09. notifications
// 10. settings
// 11. activate
// 12. register
//

function x_is_buddypress_component( $component ) {

  if ( function_exists( 'bp_is_current_component' ) && bp_is_current_component( $component ) ) {
    return true;
  } else {
    return false;
  }

}


text:
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;

namespace Mosa.Platform.ARMv6.Instructions
{
	/// <summary>
	/// Mov instruction: Copies operand to destination
	/// "Has only one operand. Constant support is limited to loading an 8-bit immediate value in ARMv6-M. If the operand is a shifted register, the instruction is an LSL, LSR, ASR, or ROR instruction instead."
	/// </summary>
	public class Mov : ARMv6Instruction
	{
		#region Construction

		/// <summary>
		/// Initializes a new instance of <see cref="Mov"/>.
		/// </summary>
		public Mov() :
			base(1, 3)
		{
		}

		#endregion Construction

		#region Methods

		/// <summary>
		/// Emits the specified platform instruction.
		/// </summary>
		/// <param name="node">The node.</param>
		/// <param name="emitter">The emitter.</param>
		protected override void Emit(InstructionNode node, MachineCodeEmitter emitter)
		{
			EmitDataProcessingInstruction(node, emitter, Bits.b1101);
		}

		/// <summary>
		/// Allows visitor based dispatch for this instruction object.
		/// </summary>
		/// <param name="visitor">The visitor object.</param>
		/// <param name="context">The context.</param>
		public override void Visit(IARMv6Visitor visitor, Context context)
		{
			visitor.Mov(context);
		}

		#endregion Methods
	}
}


text: "/styles.css" "/loader.gif"


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zanclus.codepalousa</groupId>
    <artifactId>deltaspike-restlet-archetype</artifactId>
    <version>2.3.1-2-SNAPSHOT</version>
    <packaging>maven-archetype</packaging>

    <name>deltaspike-restlet-archetype</name>
    <description>A Maven Archetype for generating a basic ReSTlet Application stub which can then be expanded</description>
    <url>https://github.com/InfoSec812/deltaspike-restlet-archetype</url>
    <developers>
        <developer>
            <name>Deven Phillips</name>
            <url>https://github.com/InfoSec812</url>
        </developer>
    </developers>
    <scm>
        <url>https://github.com/InfoSec812/deltaspike-restlet-archetype</url>
    </scm>
    <licenses>
        <license>
            <distribution>repo</distribution>
            <name>Apache License 2.0</name>
        </license>
    </licenses>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.archetype</groupId>
                <artifactId>archetype-packaging</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>

        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-archetype-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.3</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.5</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                        <configuration>
                            <classifier>javadoc</classifier>
                            <includes>
                                <include>README.md</include>
                            </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>sign-artifacts</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
"""
    Pygments basic API tests
    ~~~~~~~~~~~~~~~~~~~~~~~~

    :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from __future__ import print_function

import random
import unittest

from pygments import lexers, formatters, filters, format
from pygments.token import _TokenType, Text
from pygments.lexer import RegexLexer
from pygments.formatters.img import FontNotFound
from pygments.util import text_type, StringIO, xrange, ClassNotFound

import support

TESTFILE, TESTDIR = support.location(__file__)

test_content = [chr(i) for i in xrange(33, 128)] * 5
random.shuffle(test_content)
test_content = ''.join(test_content) + '\n'

def test_lexer_instantiate_all():
    # instantiate every lexer, to see if the token type defs are correct
    def verify(name):
        getattr(lexers, name)
    for x in lexers.LEXERS:
        yield verify, x

def test_lexer_classes():
    # test that every lexer class has the correct public API
    def verify(cls):
        assert type(cls.name) is str
        for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes':
            assert hasattr(cls, attr)
            assert type(getattr(cls, attr)) is list, \
                "%s: %s attribute wrong" % (cls, attr)
        result = cls.analyse_text("abc")
        assert isinstance(result, float) and 0.0 <= result <= 1.0
        result = cls.analyse_text(".abc")
        assert isinstance(result, float) and 0.0 <= result <= 1.0

        assert all(al.lower() == al for al in cls.aliases)

        inst = cls(opt1="val1", opt2="val2")
        if issubclass(cls, RegexLexer):
            if not hasattr(cls, '_tokens'):
                # if there's no "_tokens", the lexer has to be one with
                # multiple tokendef variants
                assert cls.token_variants
                for variant in cls.tokens:
                    assert 'root' in cls.tokens[variant]
            else:
                assert 'root' in cls._tokens, \
                       '%s has no root state' % cls

        if cls.name in ['XQuery', 'Opa']:   # XXX temporary
            return

        try:
            tokens = list(inst.get_tokens(test_content))
        except KeyboardInterrupt:
            raise KeyboardInterrupt('interrupted %s.get_tokens(): test_content=%r' % (cls.__name__, test_content))
        txt = ""
        for token in tokens:
            assert isinstance(token, tuple)
            assert isinstance(token[0], _TokenType)
            if isinstance(token[1], str):
                print(repr(token[1]))
            assert isinstance(token[1], text_type)
            txt += token[1]
        assert txt == test_content, "%s lexer roundtrip failed: %r != %r" % \
            (cls.name, test_content, txt)

    for lexer in lexers._iter_lexerclasses(plugins=False):
        yield verify, lexer

def test_lexer_options():
    # test that the basic options work
    def ensure(tokens, output):
        concatenated = ''.join(token[1] for token in tokens)
        assert concatenated == output, \
            '%s: %r != %r' % (lexer, concatenated, output)

    def verify(cls):
        inst = cls(stripnl=False)
        ensure(inst.get_tokens('a\nb'), 'a\nb\n')
        ensure(inst.get_tokens('\n\n\n'), '\n\n\n')
        inst = cls(stripall=True)
        ensure(inst.get_tokens('   \n  b\n\n\n'), 'b\n')
        # some lexers require full lines in input
        if cls.__name__ not in (
                'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer',
                'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer',
                'BashSessionLexer', 'LiterateHaskellLexer', 'LiterateAgdaLexer',
                'PostgresConsoleLexer', 'ElixirConsoleLexer', 'JuliaConsoleLexer',
                'RobotFrameworkLexer', 'DylanConsoleLexer', 'ShellSessionLexer',
                'LiterateIdrisLexer', 'LiterateCryptolLexer'):
            inst = cls(ensurenl=False)
            ensure(inst.get_tokens('a\nb'), 'a\nb')
            inst = cls(ensurenl=False, stripall=True)
            ensure(inst.get_tokens('a\nb\n\n'), 'a\nb')

    for lexer in lexers._iter_lexerclasses(plugins=False):
        if lexer.__name__ == 'RawTokenLexer':
            # this one is special
            continue
        yield verify, lexer

def test_get_lexers():
    # test that the lexers functions work
    def verify(func, args):
        x = func(opt='val', *args)
        assert isinstance(x, lexers.PythonLexer)
        assert x.options["opt"] == "val"

    for func, args in [(lexers.get_lexer_by_name, ("python",)),
                       (lexers.get_lexer_for_filename, ("test.py",)),
                       (lexers.get_lexer_for_mimetype, ("text/x-python",)),
                       (lexers.guess_lexer, ("#!/usr/bin/python -O\nprint",)),
                       (lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>"))
                       ]:
        yield verify, func, args

    for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items():
        assert cls == lexers.find_lexer_class(lname).__name__

        for alias in aliases:
            assert cls == lexers.get_lexer_by_name(alias).__class__.__name__

        for mimetype in mimetypes:
            assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__

    try:
        lexers.get_lexer_by_name(None)
    except ClassNotFound:
        pass
    else:
        raise Exception

def test_formatter_public_api():
    # test that every formatter class has the correct public API
    ts = list(lexers.PythonLexer().get_tokens("def f(): pass"))
    out = StringIO()

    def verify(formatter):
        info = formatters.FORMATTERS[formatter.__name__]
        assert len(info) == 5
        assert info[1], "missing formatter name"
        assert info[2], "missing formatter aliases"
        assert info[4], "missing formatter docstring"

        if formatter.name == 'Raw tokens':
            # will not work with Unicode output file
            return

        try:
            inst = formatter(opt1="val1")
        except (ImportError, FontNotFound):
            raise support.SkipTest
        try:
            inst.get_style_defs()
        except NotImplementedError:
            # may be raised by formatters for which it doesn't make sense
            pass
        inst.format(ts, out)

    for name in formatters.FORMATTERS:
        formatter = getattr(formatters, name)
        yield verify, formatter

def test_formatter_encodings():
    from pygments.formatters import HtmlFormatter

    # unicode output
    fmt = HtmlFormatter()
    tokens = [(Text, u"ä")]
    out = format(tokens, fmt)
    assert type(out) is text_type
    assert u"ä" in out

    # encoding option
    fmt = HtmlFormatter(encoding="latin1")
    tokens = [(Text, u"ä")]
    assert u"ä".encode("latin1") in format(tokens, fmt)

    # encoding and outencoding option
    fmt = HtmlFormatter(encoding="latin1", outencoding="utf8")
    tokens = [(Text, u"ä")]
    assert u"ä".encode("utf8") in format(tokens, fmt)

def test_formatter_unicode_handling():
    # test that the formatter supports encoding and Unicode
    tokens = list(lexers.PythonLexer(encoding='utf-8').
                  get_tokens("def f(): 'ä'"))

    def verify(formatter):
        try:
            inst = formatter(encoding=None)
        except (ImportError, FontNotFound):
            # some dependency or font not installed
            raise support.SkipTest

        if formatter.name != 'Raw tokens':
            out = format(tokens, inst)
            if formatter.unicodeoutput:
                assert type(out) is text_type, '%s: %r' % (formatter, out)

            inst = formatter(encoding='utf-8')
            out = format(tokens, inst)
            assert type(out) is bytes, '%s: %r' % (formatter, out)
            # Cannot test for encoding, since formatters may have to escape
            # non-ASCII characters.
        else:
            inst = formatter()
            out = format(tokens, inst)
            assert type(out) is bytes, '%s: %r' % (formatter, out)

    for formatter, info in formatters.FORMATTERS.items():
        # this tests the automatic importing as well
        fmter = getattr(formatters, formatter)
        yield verify, fmter

def test_get_formatters():
    # test that the formatters functions work
    x = formatters.get_formatter_by_name("html", opt="val")
    assert isinstance(x, formatters.HtmlFormatter)
    assert x.options["opt"] == "val"

    x = formatters.get_formatter_for_filename("a.html", opt="val")
    assert isinstance(x, formatters.HtmlFormatter)
    assert x.options["opt"] == "val"

def test_styles():
    # minimal style test
    from pygments.formatters import HtmlFormatter
    HtmlFormatter(style="pastie")

class FiltersTest(unittest.TestCase):

    def test_basic(self):
        filter_args = {
            'whitespace': {'spaces': True, 'tabs': True, 'newlines': True},
            'highlight': {'names': ['isinstance', 'lexers', 'x']},
        }
        for x in filters.FILTERS:
            lx = lexers.PythonLexer()
            lx.add_filter(x, **filter_args.get(x, {}))
            fp = open(TESTFILE, 'rb')
            try:
                text = fp.read().decode('utf-8')
            finally:
                fp.close()
            tokens = list(lx.get_tokens(text))
            roundtext = ''.join([t[1] for t in tokens])
            if x not in ('whitespace', 'keywordcase'):
                # these filters change the text
                self.assertEqual(roundtext, text,
                                 "lexer roundtrip with %s filter failed" % x)

    def test_raiseonerror(self):
        lx = lexers.PythonLexer()
        lx.add_filter('raiseonerror', excclass=RuntimeError)
        self.assertRaises(RuntimeError, list, lx.get_tokens('$'))

    def test_whitespace(self):
        lx = lexers.PythonLexer()
        lx.add_filter('whitespace', spaces='%')
        fp = open(TESTFILE, 'rb')
        try:
            text = fp.read().decode('utf-8')
        finally:
            fp.close()
        lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
        self.assertFalse(' ' in lxtext)

    def test_keywordcase(self):
        lx = lexers.PythonLexer()
        lx.add_filter('keywordcase', case='capitalize')
        fp = open(TESTFILE, 'rb')
        try:
            text = fp.read().decode('utf-8')
        finally:
            fp.close()
        lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
        self.assertTrue('Def' in lxtext and 'Class' in lxtext)

    def test_codetag(self):
        lx = lexers.PythonLexer()
        lx.add_filter('codetagify')
        text = u'# BUG: text'
        tokens = list(lx.get_tokens(text))
        self.assertEqual('# ', tokens[0][1])
        self.assertEqual('BUG', tokens[1][1])

    def test_codetag_boundary(self):
        # ticket #368
        lx = lexers.PythonLexer()
        lx.add_filter('codetagify')
        text = u'# DEBUG: text'
        tokens = list(lx.get_tokens(text))
        self.assertEqual('# DEBUG: text', tokens[0][1])


text:
#region License

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

#endregion

using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using TWUtilities40;

namespace TradeWright.TradeBuild.Applications.Chart
{
    class Program
    {
        private static _TWUtilities TW;
        private static ConsoleHandler1 mConsoleHandler;

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            System.Diagnostics.Debug.WriteLine("============================== Start program ==============================");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);

            SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

            TW = new TWUtilities();

            Application.ThreadException += (s, ex) => HandleException(ex.Exception);
            AppDomain.CurrentDomain.UnhandledException += (s, ex) => HandleException((Exception)ex.ExceptionObject);
            TW.UnhandledErrorHandler.UnhandledError += (ref TWUtilities40.ErrorEventData ev) => HandleError(ev);

            TW.ApplicationGroupName = "TradeWright";
            TW.ApplicationName = "Chart";
            TW.DefaultLogLevel = LogLevels.LogLevelHighDetail;

            TW.SetupDefaultLogging(Environment.CommandLine, true, true);
            mConsoleHandler= createConsoleHandler(TW);

            //TW.EnableTracing("");

            var chartApp = new ChartApp();
            chartApp.MainFormClosed += (s, e) =>
            {
                TW.LogMessage("Application.Exit()");
                TW.TerminateTWUtilities();
                Application.Exit();
            };
            var task = chartApp.StartAsync($"{Application.ProductName} V{Application.ProductVersion}", mConsoleHandler);
            HandleExceptions(task);

            Application.Run();
            Application.Exit();
        }

        private static ConsoleHandler1
        createConsoleHandler(
            _TWUtilities TW)
        {
            System.Diagnostics.Debug.WriteLine("Create ConsoleHandler");
            ConsoleHandler1 consoleHandler = new ConsoleHandler1();
            TW.LogMessage("ConsoleHandler is ready");
            return consoleHandler;
        }

        // this is the error handler for unhandled errors occurring within the
        // TradeBuild COM components
        private static void HandleError(TWUtilities40.ErrorEventData e)
        {
            TW.LogMessage("***** Unhandled COM error on thread {Thread.CurrentThread.ManagedThreadId} *****", TWUtilities40.LogLevels.LogLevelSevere);
            var s = $"Error {e.ErrorCode}: {e.ErrorMessage}\n{e.ErrorSource}";
            TW.LogMessage(s, TWUtilities40.LogLevels.LogLevelSevere);
            Environment.FailFast($"***** Unhandled COM error *****\n{s}");
        }

        // this is the error handler for unhandled exceptions occurring within the
        // .Net code
        private static void HandleException(Exception e)
        {
            TW.LogMessage($"***** Unhandled exception on thread {Thread.CurrentThread.ManagedThreadId} *****{Environment.NewLine}{e}", TWUtilities40.LogLevels.LogLevelSevere);
            Environment.FailFast("***** Unhandled exception *****", e);
        }

        private static async void
        HandleExceptions(Task task)
        {
            try
            {
                await Task.Yield();
                await task;
            }
            catch (Exception e)
            {
                TW.LogMessage($"***** Unhandled exception on thread {Thread.CurrentThread.ManagedThreadId} *****{Environment.NewLine}{e}", LogLevels.LogLevelSevere);
                Application.Exit();
            }
        }

    }
}


text:
package com.technophobia.substeps.intellij.parser

import com.intellij.extapi.psi.PsiFileBase
import com.intellij.psi.FileViewProvider
import com.technophobia.substeps.intellij.filetypes.FeatureFileType
import com.intellij.openapi.fileTypes.FileType

class FeatureFileImpl(fvp: FileViewProvider) extends PsiFileBase(fvp, FeatureFileType.getLanguage) {

  def getFileType: FileType = FeatureFileType

}