text:
"""Tests for the TypeSpec base class."""

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

import collections

from absl.testing import parameterized

import numpy as np
import six

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import test_util
from tensorflow.python.framework import type_spec
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.platform import googletest
from tensorflow.python.util import nest
from tensorflow.python.util.compat import collections_abc

class TwoTensors(object):
  """A simple value type to test TypeSpec.

  Contains two tensors (x, y) and a string (color).  The color value is a
  stand-in for any extra type metadata we might need to store.
  """

  def __init__(self, x, y, color="red"):
    assert isinstance(color, str)
    self.x = ops.convert_to_tensor(x)
    self.y = ops.convert_to_tensor(y)
    self.color = color

@type_spec.register("tf.TwoTensorsSpec")
class TwoTensorsSpec(type_spec.TypeSpec):
  """A TypeSpec for the TwoTensors value type."""

  def __init__(self, x_shape, x_dtype, y_shape, y_dtype, color="red"):
    self.x_shape = tensor_shape.as_shape(x_shape)
    self.x_dtype = dtypes.as_dtype(x_dtype)
    self.y_shape = tensor_shape.as_shape(y_shape)
    self.y_dtype = dtypes.as_dtype(y_dtype)
    self.color = color

  value_type = property(lambda self: TwoTensors)

  @property
  def _component_specs(self):
    return (tensor_spec.TensorSpec(self.x_shape, self.x_dtype),
            tensor_spec.TensorSpec(self.y_shape, self.y_dtype))

  def _to_components(self, value):
    return (value.x, value.y)

  def _from_components(self, components):
    x, y = components
    return TwoTensors(x, y, self.color)

  def _serialize(self):
    return (self.x_shape, self.x_dtype, self.y_shape, self.y_dtype, self.color)

  @classmethod
  def from_value(cls, value):
    return cls(value.x.shape, value.x.dtype, value.y.shape, value.y.dtype,
               value.color)

type_spec.register_type_spec_from_value_converter(
    TwoTensors, TwoTensorsSpec.from_value)

class TwoComposites(object):
  """A simple value type to test TypeSpec.

  Contains two composite tensorstensors (x, y) and a string (color).
  """

  def __init__(self, x, y, color="red"):
    assert isinstance(color, str)
    self.x = ops.convert_to_tensor_or_composite(x)
    self.y = ops.convert_to_tensor_or_composite(y)
    self.color = color

@type_spec.register("tf.TwoCompositesSpec")
class TwoCompositesSpec(type_spec.TypeSpec):
  """A TypeSpec for the TwoTensors value type."""

  def __init__(self, x_spec, y_spec, color="red"):
    self.x_spec = x_spec
    self.y_spec = y_spec
    self.color = color

  value_type = property(lambda self: TwoComposites)

  @property
  def _component_specs(self):
    return (self.x_spec, self.y_spec)

  def _to_components(self, value):
    return (value.x, value.y)

  def _from_components(self, components):
    x, y = components
    return TwoTensors(x, y, self.color)

  def _serialize(self):
    return (self.x_spec, self.y_spec, self.color)

  @classmethod
  def from_value(cls, value):
    return cls(type_spec.type_spec_from_value(value.x),
               type_spec.type_spec_from_value(value.y),
               value.color)

type_spec.register_type_spec_from_value_converter(
    TwoComposites, TwoCompositesSpec.from_value)

class NestOfTensors(object):
  """CompositeTensor containing a nest of tensors."""

  def __init__(self, x):
    self.nest = x

@type_spec.register("tf.NestOfTensorsSpec")
class NestOfTensorsSpec(type_spec.TypeSpec):
  """A TypeSpec for the NestOfTensors value type."""

  def __init__(self, spec):
    self.spec = spec

  value_type = property(lambda self: NestOfTensors)
  _component_specs = property(lambda self: self.spec)

  def _to_components(self, value):
    return nest.flatten(value)

  def _from_components(self, components):
    return nest.pack_sequence_as(self.spec, components)

  def _serialize(self):
    return self.spec

  def __repr__(self):
    if hasattr(self.spec, "_fields") and isinstance(
        self.spec._fields, collections_abc.Sequence) and all(
            isinstance(f, six.string_types) for f in self.spec._fields):
      return "%s(%r)" % (type(self).__name__, self._serialize())
    return super(type_spec.TypeSpec, self).__repr__()

  @classmethod
  def from_value(cls, value):
    return cls(nest.map_structure(type_spec.type_spec_from_value, value.nest))

  @classmethod
  def _deserialize(cls, spec):
    return cls(spec)

type_spec.register_type_spec_from_value_converter(
    NestOfTensors, NestOfTensorsSpec.from_value)

_TestNamedTuple = collections.namedtuple("NamedTuple", ["a", "b"])
_TestNamedTupleSingleField = collections.namedtuple("SingleField", ["a"])
_TestNamedTupleDifferentField = collections.namedtuple("DifferentField",
                                                       ["a", "c"])

class TypeSpecTest(test_util.TensorFlowTestCase, parameterized.TestCase):

  @parameterized.named_parameters(
      ("FullySpecified",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool)),
      ("UnknownDim",
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool)),
      ("UnknownRank",
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool)),
      ("Metadata",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "blue"),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "blue")),
      ("NumpyMetadata",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      (np.int32(1), np.float32(1.),
                       np.array([[1, 2], [3, 4]]))),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      (np.int32(1), np.float32(1.),
                       np.array([[1, 2], [3, 4]])))),
      )
  def testEquality(self, v1, v2):
    # pylint: disable=g-generic-assert
    self.assertEqual(v1, v2)
    self.assertEqual(v2, v1)
    self.assertFalse(v1 != v2)
    self.assertFalse(v2 != v1)
    self.assertEqual(hash(v1), hash(v2))

  @parameterized.named_parameters(
      ("UnknownDim",
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool)),
      ("UnknownRank",
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool)),
      ("IncompatibleDtype",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.float32)),
      ("IncompatibleRank",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None, None], dtypes.bool)),
      ("IncompatibleDimSize",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 8], dtypes.int32, [None], dtypes.bool)),
      ("IncompatibleMetadata",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "red"),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "blue")),
      ("SwappedValues",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([None], dtypes.bool, [5, 3], dtypes.int32)),
      ("DiffMetadataNumpy",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      np.array([[1, 2], [3, 4]])),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      np.array([[1, 2], [3, 8]]))),
      ("DiffMetadataTensorSpecName",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      tensor_spec.TensorSpec([4], name="a")),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      tensor_spec.TensorSpec([4], name="b"))),
      ("Non-TypeSpec",
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool), 5),
      )
  def testInequality(self, v1, v2):
    # pylint: disable=g-generic-assert
    self.assertNotEqual(v1, v2)
    self.assertNotEqual(v2, v1)
    self.assertFalse(v1 == v2)
    self.assertFalse(v2 == v1)

  @parameterized.named_parameters(
      ("SameValue",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool)),
      ("UnknownDim",
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool)),
      ("UnknownRank",
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool)),
      )
  def testIsCompatibleWith(self, v1, v2):
    self.assertTrue(v1.is_compatible_with(v2))
    self.assertTrue(v2.is_compatible_with(v1))

  @parameterized.named_parameters(
      ("IncompatibleDtype",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.float32)),
      ("IncompatibleRank",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None, None], dtypes.bool)),
      ("IncompatibleDimSize",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 8], dtypes.int32, [None], dtypes.bool)),
      ("IncompatibleMetadata",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "red"),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool, "blue")),
      ("SwappedValues",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([None], dtypes.bool, [5, 3], dtypes.int32)),
      )
  def testIsNotCompatibleWith(self, v1, v2):
    self.assertFalse(v1.is_compatible_with(v2))
    self.assertFalse(v2.is_compatible_with(v1))

  @parameterized.named_parameters(
      ("EqualTypes",
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool)),
      ("UnknownDim",
       TwoTensorsSpec([5, None], dtypes.int32, [8], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool)),
      ("UnknownRank",
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [8], dtypes.bool),
       TwoTensorsSpec(None, dtypes.int32, None, dtypes.bool)),
      ("DiffRank",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None, None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool)),
      ("DiffDimSize",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 8], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, None], dtypes.int32, [None], dtypes.bool)),
      ("DiffMetadataTensorSpecName",
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      tensor_spec.TensorSpec([4], name="a")),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      tensor_spec.TensorSpec([4], name="b")),
       TwoTensorsSpec([5, 3], dtypes.int32, [3], dtypes.bool,
                      tensor_spec.TensorSpec([4], name=None))),
      ("NamedTuple",
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32))),
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32))),
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32)))),
      )
  def testMostSpecificCompatibleType(self, v1, v2, expected):
    self.assertEqual(v1.most_specific_compatible_type(v2), expected)
    self.assertEqual(v2.most_specific_compatible_type(v1), expected)

  @parameterized.named_parameters(
      ("IncompatibleDtype",
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.bool),
       TwoTensorsSpec([5, 3], dtypes.int32, [None], dtypes.float32)),
      ("IncompatibleMetadata",
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool, "red"),
       TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool, "blue")),
      )
  def testMostSpecificCompatibleTypeException(self, v1, v2):
    with self.assertRaises(ValueError):
      v1.most_specific_compatible_type(v2)
    with self.assertRaises(ValueError):
      v2.most_specific_compatible_type(v1)

  def testMostSpecificCompatibleTypeNamedTupleIsNotTuple(self):
    named_tuple_spec_a = NestOfTensorsSpec.from_value(NestOfTensors(
        _TestNamedTuple(a=1, b="aaa")))
    named_tuple_spec_b = NestOfTensorsSpec.from_value(NestOfTensors(
        _TestNamedTuple(a=2, b="bbb")))
    named_tuple_spec_c = NestOfTensorsSpec.from_value(NestOfTensors(
        _TestNamedTuple(a=3, b="ccc")))
    normal_tuple_spec = NestOfTensorsSpec.from_value(NestOfTensors((2, "bbb")))
    result_a_b = named_tuple_spec_a.most_specific_compatible_type(
        named_tuple_spec_b)
    result_b_a = named_tuple_spec_b.most_specific_compatible_type(
        named_tuple_spec_a)
    self.assertEqual(repr(result_a_b), repr(named_tuple_spec_c))
    self.assertEqual(repr(result_b_a), repr(named_tuple_spec_c))
    # Test that spec of named tuple is not equal to spec of normal tuple.
    self.assertNotEqual(repr(result_a_b), repr(normal_tuple_spec))

  @parameterized.named_parameters(
      ("IncompatibleDtype",
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.bool))),
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32)))),
      ("DifferentTupleSize",
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.bool))),
       NestOfTensorsSpec(_TestNamedTupleSingleField(
           a=tensor_spec.TensorSpec((), dtypes.int32)))),
      ("DifferentFieldName",
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32))),
       NestOfTensorsSpec(_TestNamedTupleDifferentField(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           c=tensor_spec.TensorSpec((), dtypes.int32)))),
      ("NamedTupleAndTuple",
       NestOfTensorsSpec(_TestNamedTuple(
           a=tensor_spec.TensorSpec((), dtypes.int32),
           b=tensor_spec.TensorSpec((), dtypes.int32))),
       NestOfTensorsSpec((
           tensor_spec.TensorSpec((), dtypes.int32),
           tensor_spec.TensorSpec((), dtypes.int32)))),
      )
  def testMostSpecificCompatibleTypeForNamedTuplesException(self, v1, v2):
    with self.assertRaises(ValueError):
      v1.most_specific_compatible_type(v2)
    with self.assertRaises(ValueError):
      v2.most_specific_compatible_type(v1)

  def toTensorList(self):
    value = TwoTensors([1, 2, 3], [1.0, 2.0], "red")
    spec = TwoTensorsSpec.from_value(value)
    tensor_list = spec._to_tensor_list(value)
    self.assertLen(tensor_list, 2)
    self.assertIs(tensor_list[0], value.x)
    self.assertIs(tensor_list[1], value.y)

  def fromTensorList(self):
    x = ops.convert_to_tensor([1, 2, 3])
    y = ops.convert_to_tensor([1.0, 2.0])
    color = "green"
    spec = TwoTensorsSpec(x.shape, x.dtype, y.shape, y.dtype, color)
    value = spec._from_tensor_list([x, y])
    self.assertIs(value.x, x)
    self.assertIs(value.y, y)
    self.assertEqual(value.color, color)

  def fromIncompatibleTensorList(self):
    x = ops.convert_to_tensor([1, 2, 3])
    y = ops.convert_to_tensor([1.0, 2.0])
    spec1 = TwoTensorsSpec([100], x.dtype, y.shape, y.dtype, "green")
    spec2 = TwoTensorsSpec(x.shape, x.dtype, y.shape, dtypes.bool, "green")
    with self.assertRaises(ValueError):
      spec1._from_tensor_list([x, y])  # shape mismatch
    with self.assertRaises(ValueError):
      spec2._from_tensor_list([x, y])  # dtype mismatch

  def testFlatTensorSpecs(self):
    spec = TwoTensorsSpec([5], dtypes.int32, [5, 8], dtypes.float32, "red")
    self.assertEqual(spec._flat_tensor_specs,
                     [tensor_spec.TensorSpec([5], dtypes.int32),
                      tensor_spec.TensorSpec([5, 8], dtypes.float32)])

  def testRepr(self):
    spec = TwoTensorsSpec([5, 3], dtypes.int32, None, dtypes.bool)
    self.assertEqual(
        repr(spec),
        "TwoTensorsSpec(%r, %r, %r, %r, %r)" %
        (tensor_shape.TensorShape([5, 3]), dtypes.int32,
         tensor_shape.TensorShape(None), dtypes.bool, "red"))

  def testFromValue(self):
    value = TwoTensors([1, 2, 3], [1.0, 2.0], "red")
    spec = type_spec.type_spec_from_value(value)
    self.assertEqual(spec, TwoTensorsSpec.from_value(value))

  def testNestedRagged(self):
    # Check that TwoCompositeSpecs are compatible if one has a nested
    # RaggedTensorSpec w/ ragged_rank=0 and the other has a corresponding
    # nested TensorSpec.
    spec1 = TwoCompositesSpec(
        ragged_tensor.RaggedTensorSpec([10], dtypes.int32, ragged_rank=0),
        tensor_spec.TensorSpec(None, dtypes.int32))
    spec2 = TwoCompositesSpec(
        tensor_spec.TensorSpec([10], dtypes.int32),
        tensor_spec.TensorSpec(None, dtypes.int32))
    spec3 = TwoCompositesSpec(
        tensor_spec.TensorSpec([12], dtypes.int32),
        tensor_spec.TensorSpec(None, dtypes.int32))
    self.assertTrue(spec1.is_compatible_with(spec2))
    self.assertFalse(spec1.is_compatible_with(spec3))

  def testRegistry(self):
    self.assertEqual("tf.TwoCompositesSpec",
                     type_spec.get_name(TwoCompositesSpec))
    self.assertEqual("tf.TwoTensorsSpec", type_spec.get_name(TwoTensorsSpec))
    self.assertEqual(TwoCompositesSpec,
                     type_spec.lookup("tf.TwoCompositesSpec"))
    self.assertEqual(TwoTensorsSpec, type_spec.lookup("tf.TwoTensorsSpec"))

  def testRegistryTypeErrors(self):
    with self.assertRaisesRegex(TypeError, "Expected `name` to be a string"):
      type_spec.register(None)

    with self.assertRaisesRegex(TypeError, "Expected `name` to be a string"):
      type_spec.register(TwoTensorsSpec)

    with self.assertRaisesRegex(TypeError, "Expected `cls` to be a TypeSpec"):
      type_spec.register("tf.foo")(None)

    with self.assertRaisesRegex(TypeError, "Expected `cls` to be a TypeSpec"):
      type_spec.register("tf.foo")(ragged_tensor.RaggedTensor)

  def testRegistryDuplicateErrors(self):
    with self.assertRaisesRegex(
        ValueError, "Name tf.TwoCompositesSpec has already been registered "
        "for class __main__.TwoCompositesSpec."):

      @type_spec.register("tf.TwoCompositesSpec")  # pylint: disable=unused-variable
      class NewTypeSpec(TwoCompositesSpec):
        pass

    with self.assertRaisesRegex(
        ValueError, "Class __main__.TwoCompositesSpec has already been "
        "registered with name tf.TwoCompositesSpec"):
      type_spec.register("tf.NewName")(TwoCompositesSpec)

  def testRegistryNameErrors(self):
    for bad_name in ["foo", "", "hello world"]:
      with self.assertRaises(ValueError):
        type_spec.register(bad_name)

  def testRegistryLookupErrors(self):
    with self.assertRaises(TypeError):
      type_spec.lookup(None)
    with self.assertRaisesRegex(
        ValueError, "No TypeSpec has been registered with name 'foo.bar'"):
      type_spec.lookup("foo.bar")

  def testRegistryGetNameErrors(self):
    with self.assertRaises(TypeError):
      type_spec.get_name(None)

    class Foo(TwoCompositesSpec):
      pass

    with self.assertRaisesRegex(
        ValueError, "TypeSpec __main__.Foo has not been registered."):
      type_spec.get_name(Foo)

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


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" PolicyId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIB014:policy" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-overrides" Version="1.0" xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:policy:schema:os         access_control-xacml-2.0-policy-schema-os.xsd">
    <Description>
        Policy for Conformance Test IIB014.
        Purpose - Target Matching: Case: match: Subject with non-string SubjectId DataType and value
    </Description>
    <Target/>
    <Rule Effect="Permit" RuleId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIB014:rule">
        <Description>
            Julius Hibbert, identified by X500 Name, can read or
            write Bart Simpson's medical record.
        </Description>
        <Target>
            <AnyOf>
                <AllOf>
                    <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:x500Name-equal">
                        <AttributeValue DataType="urn:oasis:names:tc:xacml:1.0:data-type:x500Name">CN=Julius Hibbert,O=Medi Corporation,C=US</AttributeValue>
                        <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="urn:oasis:names:tc:xacml:1.0:data-type:x500Name" MustBePresent="false"/>
                    </Match>
                </AllOf>
            </AnyOf>
            <AnyOf>
                <AllOf>
                    <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://medico.com/record/patient/BartSimpson</AttributeValue>
                        <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="http://www.w3.org/2001/XMLSchema#anyURI" MustBePresent="false"/>
                    </Match>
                </AllOf>
            </AnyOf>
            <AnyOf>
                <AllOf>
                    <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</AttributeValue>
                        <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                    </Match>
                </AllOf>
                <AllOf>
                    <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">write</AttributeValue>
                        <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                    </Match>
                </AllOf>
            </AnyOf>
        </Target>
    </Rule>
</Policy>

redpajama_set_name: RedPajamaGithub


text:
const partial = require('./partial')

const curry = (f, argsAmount, argsPassed = 0, args) => {
  argsPassed += args.length

  if (argsPassed >= argsAmount) {
    return f(...args)
  }
  else {
    return (...nextArgs) => curry(partial(f, args), argsAmount, argsPassed, nextArgs)
  }
}

module.exports = f => (...args) => curry(f, f.length, 0, args)


text:
{% extends "base.html" %}
{% block title %}start{% endblock %}
{% block containercontent %}

start (someplace inside your app)

We've generated the OAuth request token ({{ oauth_token }}) and are ready for you to authorize twauth-web! Just click the button below, you'll be taken to Twitter to login (if you aren't already) and to grant access to twauth-web. Afterward you'll be redirected back to us.

Authorize twauth-web

What did we just do?

We called {{ request_token_url }} with our application API key and API secret to get a temporary oauth request token. We passed our desired callback URL to this method so that Twitter knows where to redirect you after you authorize our app.

{% endblock %}


text:
using Microsoft.EntityFrameworkCore.Migrations;

namespace NetAdmin.DataAccess.Migrations
{
    public partial class RemoveHashColumn : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                "Hash",
                "Users");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<byte[]>(
                "Hash",
                "Users",
                nullable: true);
        }
    }
}


text:
<?php

namespace Cast\Serialize;

class JSONSerializer extends AbstractSerializer
{
    protected $fileExtension = 'json';

    /**
     * Serialize a model object to file.
     *
     * @param \xPDOObject $object The data to serialize.
     * @param array $options An array of options for the serialization process.
     *
     * @return int|bool The number of bytes written to file or false on failure.
     */
    public function serialize(\xPDOObject $object, array $options = array())
    {
        $data = null;
        $path = $this->serializedModelPath;
        $segments = array();
        $segments[] = 'xPDOObject';
        $segments[] = $this->cast->modx->getTableClass($object->_class);
        $criteria = $pk = $object->getPrimaryKey();
        if (!is_array($pk)) $pk = array($pk);
        $segments[] = implode('-', $pk) . ".{$this->fileExtension}";
        $data = array(
            'class'    => $object->_class,
            'criteria' => $criteria,
            'object'   => $object->toArray('', true, false, true)
        );
        $path .= str_replace('\\', '/', implode('/', $segments));
        $beforeSerialize = isset($options['before_serialize_callback']) ? $options['before_serialize_callback'] : null;
        if ($beforeSerialize instanceof \Closure) {
            $beforeSerialize($this, $object, $data, $segments, $path, $options);
            unset($beforeSerialize);
        }
        $written = $this->cast->modx->getCacheManager()->writeFile($path, json_encode($data, version_compare(phpversion(), '5.4.0', '>=') ? JSON_PRETTY_PRINT : 0));
        $afterSerialize = isset($options['after_serialize_callback']) ? $options['after_serialize_callback'] : null;
        if ($afterSerialize instanceof \Closure) {
            $afterSerialize($this, $object, $options);
            unset($afterSerialize);
        }
        return $written;
    }

    /**
     * Unserialize a model object from file and save it into the database.
     *
     * @param string $path The path of the file to unserialize the object from.
     * @param array $options An array of options for the process.
     *
     * @throws SerializerException If unserialization fails to retrieve valid data.
     * @return bool TRUE if the object is saved to the database, FALSE if save fails.
     */
    public function unserialize($path, array $options = array())
    {
        if (is_readable($this->serializedModelPath . $path)) {
            $data = file_get_contents($this->serializedModelPath . $path);
            if (is_string($data)) {
                $payload = json_decode($data, true);
                $beforeUnserialize = isset($options['before_unserialize_callback']) ? $options['before_unserialize_callback'] : null;
                if ($beforeUnserialize instanceof \Closure) {
                    $beforeUnserialize($this, $path, $payload, $options);
                    unset($beforeUnserialize);
                }
                /** @var \xPDOObject $object */
                if (($object = $this->cast->modx->getObject($payload['class'], $payload['criteria'])) === null) {
                    $object = $this->cast->modx->newObject($payload['class']);
                    $object->fromArray($payload['object'], '', true, true);
                } else {
                    $object->fromArray($payload['object'], '', true, true);
                }
                $saved = $object->save();
                $afterUnserialize = isset($options['after_unserialize_callback']) ? $options['after_unserialize_callback'] : null;
                if ($afterUnserialize instanceof \Closure) {
                    $afterUnserialize($this, $path, $data, $object, $options);
                    unset($afterUnserialize);
                }
                return $saved;
            }
            throw new SerializerException($this, "Could not unserialize {$path} to the MODX database: no content");
        }
        throw new SerializerException($this, "Could not unserialize {$path} to the MODX database: file is not readable or does not exist");
    }
}


text:
namespace Merchello.Web.Search
{
    using Merchello.Web.Models;
    using Merchello.Web.Models.VirtualContent;

    /// <summary>
    /// Marker interface for a ProductContentQueryBuilder.
    /// </summary>
    public interface IProductContentQueryBuilder : ICmsContentQueryBuilder<IProductCollection, IProductFilter, IProductContent>
    {
    }
}


text:
(function () {
  'use strict';

    angular.module('scrumboard.demo')
      .config(['$routeProvider', config])
      .run(['$http', run]);

    function config($routeProvider) {
    //routeProvider provides the route. a url and the controller for the url
      $routeProvider
        .when('/', {
          templateUrl: '/static/html/scrumboard.html',
          controller: 'ScrumboardController',
        })
        .when('/login', {
          templateUrl: '/static/html/login.html',
          controller: 'LoginController',
        })
        .otherwise('/');
    }

    //Takes the cookie and returns it in the header
    //Run runs after everything is loaded
    function run($http) {
      $http.defaults.xsrfHeaderName = 'X-CSRFToken';
      $http.defaults.xsrfCookieName = 'csrftoken';
    }
})();


text:
namespace net {
class StreamSocket;
}

class AndroidDeviceManager
    : public base::RefCountedThreadSafe<
          AndroidDeviceManager,
          content::BrowserThread::DeleteOnUIThread>,
      public base::NonThreadSafe {
 public:
  typedef base::Callback<void(int, const std::string&)> CommandCallback;
  typedef base::Callback<void(int result, net::StreamSocket*)> SocketCallback;
  typedef base::Callback<void(const std::vector<std::string>&)> SerialsCallback;

  struct BrowserInfo {
    BrowserInfo();

    enum Type {
      kTypeChrome,
      kTypeWebView,
      kTypeOther
    };

    std::string socket_name;
    std::string display_name;
    Type type;
  };

  struct DeviceInfo {
    DeviceInfo();
    ~DeviceInfo();

    std::string model;
    bool connected;
    gfx::Size screen_size;
    std::vector<BrowserInfo> browser_info;
  };

  typedef base::Callback<void(const DeviceInfo&)> DeviceInfoCallback;

  class AndroidWebSocket : public base::RefCountedThreadSafe<AndroidWebSocket> {
   public:
    class Delegate {
     public:
      virtual void OnSocketOpened() = 0;
      virtual void OnFrameRead(const std::string& message) = 0;
      virtual void OnSocketClosed(bool closed_by_device) = 0;

     protected:
      virtual ~Delegate() {}
    };

    AndroidWebSocket() {}

    virtual void Connect() = 0;
    virtual void Disconnect() = 0;
    virtual void SendFrame(const std::string& message) = 0;
    virtual void ClearDelegate() = 0;

   protected:
    virtual ~AndroidWebSocket() {}

   private:
    friend class base::RefCountedThreadSafe<AndroidWebSocket>;

    DISALLOW_COPY_AND_ASSIGN(AndroidWebSocket);
  };

  class DeviceProvider;

  class Device : public base::RefCountedThreadSafe<Device>,
                 public base::NonThreadSafe {
   public:
    typedef AndroidDeviceManager::DeviceInfoCallback DeviceInfoCallback;
    typedef AndroidDeviceManager::CommandCallback CommandCallback;
    typedef AndroidDeviceManager::SocketCallback SocketCallback;

    void QueryDeviceInfo(const DeviceInfoCallback& callback);

    void OpenSocket(const std::string& socket_name,
                    const SocketCallback& callback);

    void SendJsonRequest(const std::string& socket_name,
                         const std::string& request,
                         const CommandCallback& callback);

    void HttpUpgrade(const std::string& socket_name,
                     const std::string& url,
                     const SocketCallback& callback);

    scoped_refptr<AndroidWebSocket> CreateWebSocket(
        const std::string& socket_name,
        const std::string& url,
        AndroidWebSocket::Delegate* delegate);

    std::string serial() { return serial_; }

   private:
    friend class AndroidDeviceManager;
    Device(scoped_refptr<base::MessageLoopProxy> device_message_loop,
           scoped_refptr<DeviceProvider> provider,
           const std::string& serial);

    friend class base::RefCountedThreadSafe<Device>;
    virtual ~Device();

    scoped_refptr<base::MessageLoopProxy> device_message_loop_;
    scoped_refptr<DeviceProvider> provider_;
    std::string serial_;
    base::WeakPtrFactory<Device> weak_factory_;

    DISALLOW_COPY_AND_ASSIGN(Device);
  };

  typedef std::vector<scoped_refptr<Device> > Devices;
  typedef base::Callback<void(const Devices&)> DevicesCallback;

  class DeviceProvider : public base::RefCountedThreadSafe<DeviceProvider> {
   public:
    typedef AndroidDeviceManager::SerialsCallback SerialsCallback;
    typedef AndroidDeviceManager::DeviceInfoCallback DeviceInfoCallback;
    typedef AndroidDeviceManager::SocketCallback SocketCallback;
    typedef AndroidDeviceManager::CommandCallback CommandCallback;

    virtual void QueryDevices(const SerialsCallback& callback) = 0;

    virtual void QueryDeviceInfo(const std::string& serial,
                                 const DeviceInfoCallback& callback) = 0;

    virtual void OpenSocket(const std::string& serial,
                            const std::string& socket_name,
                            const SocketCallback& callback) = 0;

    virtual void SendJsonRequest(const std::string& serial,
                                 const std::string& socket_name,
                                 const std::string& request,
                                 const CommandCallback& callback);

    virtual void HttpUpgrade(const std::string& serial,
                             const std::string& socket_name,
                             const std::string& url,
                             const SocketCallback& callback);

    virtual void ReleaseDevice(const std::string& serial);

   protected:
    friend class base::RefCountedThreadSafe<DeviceProvider>;
    DeviceProvider();
    virtual ~DeviceProvider();
  };

  typedef std::vector<scoped_refptr<DeviceProvider> > DeviceProviders;

  static scoped_refptr<AndroidDeviceManager> Create();

  void SetDeviceProviders(const DeviceProviders& providers);

  void QueryDevices(const DevicesCallback& callback);

  struct DeviceDescriptor {
    DeviceDescriptor();
    ~DeviceDescriptor();

    scoped_refptr<DeviceProvider> provider;
    std::string serial;
  };

  typedef std::vector<DeviceDescriptor> DeviceDescriptors;

 private:
  class HandlerThread : public base::RefCountedThreadSafe<HandlerThread> {
   public:
    static scoped_refptr<HandlerThread> GetInstance();
    scoped_refptr<base::MessageLoopProxy> message_loop();

   private:
    friend class base::RefCountedThreadSafe<HandlerThread>;
    static HandlerThread* instance_;
    static void StopThread(base::Thread* thread);

    HandlerThread();
    virtual ~HandlerThread();
    base::Thread* thread_;
  };

  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::UI>;
  friend class base::DeleteHelper<AndroidDeviceManager>;
  AndroidDeviceManager();
  virtual ~AndroidDeviceManager();

  void UpdateDevices(const DevicesCallback& callback,
                     DeviceDescriptors* descriptors);

  typedef std::map<std::string, base::WeakPtr<Device> > DeviceWeakMap;

  scoped_refptr<HandlerThread> handler_thread_;
  DeviceProviders providers_;
  DeviceWeakMap devices_;
};

#endif  // CHROME_BROWSER_DEVTOOLS_DEVICE_ANDROID_DEVICE_MANAGER_H_


text:
'''

    Copyright 2012 Joe Harris

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

'''

'''

    Trivial example of how to all objects from a very large Cloud Files
    container where it has more objects than can be returned in a single
    request. See:

    http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Large_Number_of_Objects-d1e1521.html

'''

import os, sys

# make sure our local copy of txcloudfiles is in sys.path
PATH_TO_TXCF = '../txcloudfiles/'
try:
    import txcloudfiles
except ImportError:
    txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
    if txcfpath not in sys.path:
        sys.path.insert(0, txcfpath)

from twisted.internet import reactor
from txcloudfiles import get_auth, UK_ENDPOINT, US_ENDPOINT

def _got_session(session):
    print '> got session: %s' % session
    container_name = 'some_test_container'
    def _ok((response, container)):
        '''
            'response' is a transport.Response() instance.
            'container' is a cfcontainer.Container() instance.
        '''
        print '> got response: %s' % response
        print '> got container populated with objects: %s' % container
        for obj in container:
            print obj, repr(obj)
        reactor.stop()
    print '> sending request'
    session.list_all_objects(container_name).addCallback(_ok).addErrback(_error)

def _error(e):
    '''
        'e' here will be a twisted.python.failure.Failure() instance wrapping
        a ResponseError() object. ResponseError() instances contain information
        about the request to help you find out why it errored through its
        ResponseError().request attribute.
    '''
    print 'error!'
    print e.printTraceback()
    reactor.stop()

auth = get_auth(UK_ENDPOINT, os.environ.get('TXCFUSR', ''), os.environ.get('TXCFAPI', ''))
auth.get_session().addCallback(_got_session).addErrback(_error)

reactor.run()

'''

    EOF

'''


text:
(function(module) {

  "use strict";

  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  var ObjectId = Schema.ObjectId;
  var GroupSchema;

  GroupSchema = new Schema({
    name: { type: String, required: true },
    description: { type: String, default: '' },
    created: { type: Date, default: Date.now }
  });

  module.exports = mongoose.model('Group', GroupSchema);

}(module));


text:
package fakes

import (
	"fmt"
)

type FakeSha1Calculator struct {
	calculateInputs       map[string]CalculateInput
	CalculateStringInputs map[string]string
}

func NewFakeSha1Calculator() *FakeSha1Calculator {
	return &FakeSha1Calculator{}
}

type CalculateInput struct {
	Sha1 string
	Err  error
}

func (c *FakeSha1Calculator) Calculate(path string) (string, error) {
	calculateInput := c.calculateInputs[path]
	return calculateInput.Sha1, calculateInput.Err
}

func (c *FakeSha1Calculator) CalculateString(data string) string {
	if sha1, found := c.CalculateStringInputs[data]; found {
		return sha1
	}
	panic(fmt.Sprintf("Did not find SHA1 result for '%s'", data))
}

func (c *FakeSha1Calculator) SetCalculateBehavior(calculateInputs map[string]CalculateInput) {
	c.calculateInputs = calculateInputs
}


text:
![Swift](https://img.shields.io/badge/%20in-swift%203.1-orange.svg)
[![Build Status](https://travis-ci.org/dn-m/Pitch.svg?branch=master)](https://travis-ci.org/dn-m/Pitch)
[![codecov](https://codecov.io/gh/dn-m/Pitch/branch/master/graph/badge.svg)](https://codecov.io/gh/dn-m/Pitch)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![GitHub version](https://badge.fury.io/gh/dn-m%2FPitch.svg)](https://badge.fury.io/gh/dn-m%2FPitch)

## Integration

### Carthage
Integrate **Pitch** into your macOS or iOS project with [Carthage](https://github.com/Carthage/Carthage).

1. Follow [these instructions](https://github.com/Carthage/Carthage#installing-carthage) to install Carthage, if necessary.
2. Add `github "dn-m/Pitch"` to your [Cartfile](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile).
3. Follow [these instructions](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) to integrate **Pitch** into your macOS or iOS project.

---

### Documentation
See the [documentation](http://dn-m.github.io/Pitch/).


text:
<!--
  Licensed to the Apache Software
	Foundation (ASF) under one or more contributor license agreements. See the
	NOTICE file distributed with this work for additional information regarding
	copyright ownership. The ASF licenses this file to You under the Apache License,
	Version 2.0 (the "License"); you may not use this file except in compliance
	with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	OR CONDITIONS OF ANY KIND, either express or implied. See the License for
  the specific language governing permissions and limitations under the License.
  -->
<a [attr.href]="'#' + uniqueId"  data-toggle="collapse"  aria-expanded="false" [attr.aria-controls]="uniqueId" class="pr-2 collapsed"
   [ngClass]="{'font-size-12' : fontSize === 12, 'font-size-15' : fontSize === 15, 'border-bottom' : titleSeperator=== true}">
  {{ data.groupName | columnNameTranslate | centerEllipses: strLength  }}  <span *ngIf="countOption" class="group-items-count"> {{ data.groupItems.length }} </span>
</a>
<div class="collapse" [attr.id]="uniqueId" [ngClass]="{'show': data.collapsed === false}">
  <div *ngIf="data.groupItems.length === 0" class="container-fluid no-data-text">
    <i> {{ 'No ' +  data.groupName  | centerEllipses: strLength }}  </i>
  </div>
  <ul  *ngIf="data.groupItems.length > 0"  class="list-group">
    <li *ngFor="let groupItem of data.groupItems" class="list-group-item justify-content-between anchor"
        [ngClass]="{'font-size-12' : fontSize === 12, 'font-size-15' : fontSize === 15}" [attr.title]="groupItem.name"
        (click)="onSelectClick(groupItem.name)">
      {{ groupItem.name | centerEllipses: strLength }}
      <span *ngIf="countOption" class="count"> {{ groupItem.count }} </span>
      <span *ngIf="deleteOption" class="delete" (click)="onDeleteClick($event, groupItem.name)"> </span>
    </li>
  </ul>
</div>


text:
/// <reference path="require.js" />
/// <reference path="jasmine.js" />

requirejs(['./tests/base/base.jasmine.test',
           './tests/ui/ui.jasmine.test'],
    function () { }
);


text:
self=`basename $0`

Usage () {
	cat <<EOF
Usage: $self <subcmd>

Loop thru local subdirectories of the current folder and run

	git <subcmd>

within each that is a git repository.

Most commonly used examples:

	$self remote --verbose
	$self pull origin
	$self status --short
	$self gc
EOF
	exit 1
}

if [ $# -eq 0 ]
then
	Usage
fi

h=`pwd`

for d in */
do
	cd "$h/$d"
	if [ -d .git ]
	then
		echo
		echo "running git in $d"
		git $@ || exit 1
	else
		echo
		echo "$d is not a git repo; skipping..."
	fi
done

# end: git-loop.sh


text:
using namespace raytracer;
using namespace gui;

static const Colour BACKGROUND_COLOUR(0.2f, 0.2f, 0.2f);

RendererWorker::RendererWorker(Raytracer* renderer, Image* canvas) :
	renderer(renderer), canvas(canvas), rendering(false),
	samplingMethod(SINGLESAMPLING), numSamples(3)
{
}

void RendererWorker::setSamplingMethod(SamplingMethod newMethod)
{
	samplingMethod = newMethod;
}

void RendererWorker::setNumSamples(unsigned int newNumSamples)
{
	numSamples = newNumSamples;
}

SamplingMethod RendererWorker::getSamplingMethod() const
{
	return samplingMethod;
}

unsigned int RendererWorker::getNumSamples() const
{
	return numSamples;
}

void RendererWorker::render()
{
	rendering = true;

    // Loop over the pixels of the image
    unsigned int canvasWidth = canvas->getWidth();
    unsigned int canvasHeight = canvas->getHeight();
    Colour resultantColour;

	// By defualt, render single sampled pixels
	PixelRenderingMethod renderingMethod = &RendererWorker::renderSinglesamplePixel;
	// Pick rendering method to use based on chosen sampling method
	switch (samplingMethod)
	{
    case SINGLESAMPLING:
        // do nothing
        break;
	case UNIFORM_MULTISAMPLING:
		renderingMethod = &RendererWorker::renderUniformMultisamplePixel;
		break;
	case RANDOM_MULTISAMPLING:
		renderingMethod = &RendererWorker::renderUniformMultisamplePixel;
		break;
	}

	// Render using the chosen pixel rendering method
	for (unsigned int j = 0; (j < canvasHeight); j++)
	{
		for (unsigned int i = 0; (i < canvasWidth); i++)
        {
        	// If rendering has stopped, emit a finished signal and return from function
        	if (!rendering)
        	{
        		emit finished();
        		return;
        	}

        	Colour resultantColour;
        	bool hit = ((*this).*renderingMethod)(i, j, canvasWidth, canvasHeight, resultantColour);
            if (hit)
                canvas->set(i, j, resultantColour);
            else
                canvas->set(i, j, BACKGROUND_COLOUR);
        }
        emit finishedRow(j);
    }

	emit finished();
}

void RendererWorker::stop()
{
	rendering = false;
}

bool RendererWorker::renderSinglesamplePixel(int i, int j,
	unsigned int canvasWidth, unsigned int canvasHeight, Colour& result)
{
    // Convert pixel coordinates (i, j) to viewing plane coordinates (x, y)
    // Note that this gets the pixel CENTRE due to 0.5f
    float x = (static_cast<float>(i) + 0.5f) / canvasWidth; // a
    float y = (static_cast<float>(j) + 0.5f) / canvasHeight; // b
    return renderer->raytrace(x, y, result);
}

bool RendererWorker::renderUniformMultisamplePixel(int i, int j,
	unsigned int canvasWidth, unsigned int canvasHeight, Colour& result)
{
	// Define RANGE the uniformly sampled pixels will be in
    float minX = static_cast<float>(i) / canvasWidth;
    float minY = static_cast<float>(j) / canvasHeight;
    float maxX = static_cast<float>(i + 1) / canvasWidth;
    float maxY = static_cast<float>(j + 1) / canvasHeight;
    return renderer->uniformMultisample(minX, minY, maxX, maxY, numSamples, result);
}

bool RendererWorker::renderRandomMultisamplePixel(int i, int j,
	unsigned int canvasWidth, unsigned int canvasHeight, Colour& result)
{
    float minX = static_cast<float>(i) / canvasWidth;
    float minY = static_cast<float>(j) / canvasHeight;
    float maxX = static_cast<float>(i + 1) / canvasWidth;
    float maxY = static_cast<float>(j + 1) / canvasHeight;
    return renderer->randomMultisample(minX, minY, maxX, maxY, numSamples, result);
}


text:
import { Component, Input, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'adf-about-github-link',
    templateUrl: './about-github-link.component.html',
    encapsulation: ViewEncapsulation.None
})
export class AboutGithubLinkComponent {
    /** Commit corresponding to the version of ADF to be used. */
    @Input()
    url = 'https://github.com/Alfresco/alfresco-ng2-components/commits/';

    /** Current version of the app running */
    @Input()
    version: string = '';

    /** Title of app running */
    @Input()
    application: string = '';

    constructor() {}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.panoramio">
    <application android:icon="@drawable/icon">
        <activity android:name=".Panoramio" android:label="@string/app_name"
        	android:theme="@style/Theme.Panoramio">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

		<activity android:name=".ImageList" android:label="@string/app_name"
			android:theme="@android:style/Theme.Light"/>

		<activity android:name=".ViewImage" android:label="@string/app_name"
			android:theme="@style/Theme.Panoramio"/>

     	<activity android:name=".ViewMap" android:label="@string/app_name"/>

		<uses-library android:name="com.google.android.maps" />
    </application>
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="10"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>


text:
using System;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace AmCharts.Windows.QuickCharts
{
    /// <summary>
    /// Represents category axis in serial chart (usually x-axis)
    /// </summary>
    public class CategoryAxis : Control
    {
        /// <summary>
        /// Instantiates CategoryAxis object
        /// </summary>
        public CategoryAxis()
        {
            this.DefaultStyleKey = typeof(CategoryAxis);

            HorizontalAlignment = HorizontalAlignment.Stretch;
        }

        private Canvas _valuesPanel;
        private Canvas _tickPanel;
        private List<string> _values = new List<string>();
        private List<double> _locations = new List<double>();
        private List<TextBlock> _valueBoxes = new List<TextBlock>();
        private List<Line> _valueTicks = new List<Line>();

        /// <summary>
        /// Applies control template
        /// </summary>
        protected override void OnApplyTemplate()
        {
            _valuesPanel = (Canvas)TreeHelper.TemplateFindName("PART_ValuesPanel", this);
            _tickPanel = (Canvas)TreeHelper.TemplateFindName("PART_TickPanel", this);
        }

        /// <summary>
        /// Measures desired size for the axis.
        /// </summary>
        /// <param name="constraint">Constraint</param>
        /// <returns>Desired size</returns>
        protected override Size MeasureOverride(Size constraint)
        {
            Size desiredSize = new Size(0, 0);
            if (!double.IsInfinity(constraint.Width))
            {
                desiredSize.Width = constraint.Width;
            }
            double maxBoxHeight = 0;
            foreach (TextBlock valueBox in _valueBoxes)
            {
                valueBox.Measure(new Size(constraint.Width, constraint.Height - 8));
                maxBoxHeight = Math.Max(maxBoxHeight, valueBox.GetDesiredSize().Height);
            }
            desiredSize.Height = maxBoxHeight + 20;

            return desiredSize;
        }

        /// <summary>
        /// Arranges axis labels
        /// </summary>
        /// <param name="arrangeBounds">Arrange bounds</param>
        /// <returns>Arranged bounds</returns>
        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            foreach (TextBlock valueBox in _valueBoxes)
            {
                Size tbSize = valueBox.GetDesiredSize();
                double newLeft = (double)valueBox.GetValue(Canvas.LeftProperty) - tbSize.Width / 2;
                double newTop = 3;
                valueBox.SetValue(Canvas.TopProperty, newTop);
                valueBox.SetValue(Canvas.LeftProperty, newLeft);
            }

            return base.ArrangeOverride(arrangeBounds);
        }

        /// <summary>
        /// Sets values to be displayed as axis labels
        /// </summary>
        /// <param name="values">Values</param>
        public void SetValues(IEnumerable<string> values)
        {
            _values = new List<string>(values);
            CreateValueObjects();
        }

        /// <summary>
        /// Set's locations of value labels (ticks) on the axis.
        /// </summary>
        /// <param name="locations">Value locations (coordinates)</param>
        public void SetLocations(IEnumerable<double> locations)
        {
            _locations = new List<double>(locations);
            SetObjectLocations();
            InvalidateArrange();
        }

        private void CreateValueObjects()
        {
            int count = Math.Min(_values.Count, _valueBoxes.Count);
            for (int i = 0; i < count; i++)
            {
                SetValueBoxText(i);
            }

            if (_values.Count != _valueBoxes.Count)
            {
                AddRemoveValueObjects(count);
            }
        }

        private void AddRemoveValueObjects(int count)
        {
            if (_values.Count > _valueBoxes.Count)
            {
                AddValueObjects(count);
            }
            else if (_values.Count < _valueBoxes.Count)
            {
                RemoveValueObjects(count);
            }
        }

        private void AddValueObjects(int count)
        {
            for (int i = count; i < _values.Count; i++)
            {
                _valueBoxes.Add(new TextBlock());
                SetValueBoxText(i);
                _valueTicks.Add(
                    new Line()
                    {
                        Stroke = Foreground,
                        StrokeThickness = 1,
                        Y1 = 0, Y2 = 5
                    });

                _valuesPanel.Children.Add(_valueBoxes[i]);
                _tickPanel.Children.Add(_valueTicks[i]);
            }
            this.InvalidateMeasure();
        }

        private void RemoveValueObjects(int count)
        {
            for (int i = _valueBoxes.Count -1; i >= count; i--)
            {
                _valuesPanel.Children.Remove(_valueBoxes[i]);
                _tickPanel.Children.Remove(_valueTicks[i]);
                _valueBoxes.RemoveAt(i);
                _valueTicks.RemoveAt(i);
            }
        }

        private void SetValueBoxText(int index)
        {
            _valueBoxes[index].Text = _values[index];
        }

        private void SetObjectLocations()
        {
            for (int i = 0; i < _valueBoxes.Count; i++)
            {
                _valueBoxes[i].SetValue(Canvas.LeftProperty, _locations[i]);
                _valueTicks[i].SetValue(Canvas.LeftProperty, _locations[i]);
            }
        }

    }

}