text:
"""Tests for tensorflow.ops.parsing_ops."""

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

import copy

import numpy as np

from tensorflow.contrib.data.python.ops import parsing_ops as contrib_parsing_ops
from tensorflow.core.example import example_pb2
from tensorflow.core.example import feature_pb2
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import parsing_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging

# Helpers for creating Example objects
example = example_pb2.Example
feature = feature_pb2.Feature
features = lambda d: feature_pb2.Features(feature=d)
bytes_feature = lambda v: feature(bytes_list=feature_pb2.BytesList(value=v))
int64_feature = lambda v: feature(int64_list=feature_pb2.Int64List(value=v))
float_feature = lambda v: feature(float_list=feature_pb2.FloatList(value=v))
# Helpers for creating SequenceExample objects
feature_list = lambda l: feature_pb2.FeatureList(feature=l)
feature_lists = lambda d: feature_pb2.FeatureLists(feature_list=d)
sequence_example = example_pb2.SequenceExample

def _compare_output_to_expected(tester, dict_tensors, expected_tensors,
                                flat_output):
  tester.assertEqual(set(dict_tensors.keys()), set(expected_tensors.keys()))

  i = 0  # Index into the flattened output of session.run()
  for k, v in sorted(dict_tensors.items()):
    # TODO(shivaniagrawal): flat_output is same as v.
    expected_v = expected_tensors[k]
    tf_logging.info("Comparing key: %s", k)
    print("i", i, "flat_output", flat_output[i], "expected_v", expected_v)
    if sparse_tensor.is_sparse(v):
      # Three outputs for SparseTensor : indices, values, shape.
      tester.assertEqual([k, len(expected_v)], [k, 3])
      print("i", i, "flat_output", flat_output[i].indices, "expected_v",
            expected_v[0])
      tester.assertAllEqual(expected_v[0], flat_output[i].indices)
      tester.assertAllEqual(expected_v[1], flat_output[i].values)
      tester.assertAllEqual(expected_v[2], flat_output[i].dense_shape)
    else:
      # One output for standard Tensor.
      tester.assertAllEqual(expected_v, flat_output[i])
    i += 1

class ParseExampleTest(test.TestCase):

  def _test(self,
            input_tensor,
            feature_val,
            expected_values=None,
            expected_err=None):

    with self.cached_session() as sess:
      if expected_err:
        with self.assertRaisesWithPredicateMatch(expected_err[0],
                                                 expected_err[1]):
          dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply(
              contrib_parsing_ops.parse_example_dataset(feature_val))
          get_next = dataset.make_one_shot_iterator().get_next()
          sess.run(get_next)
        return
      else:
        # Returns dict w/ Tensors and SparseTensors.
        # Check values.
        dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply(
            contrib_parsing_ops.parse_example_dataset(feature_val))
        get_next = dataset.make_one_shot_iterator().get_next()
        result = sess.run(get_next)
        flattened = nest.flatten(result)
        print("result", result, "expected_values", expected_values)
        _compare_output_to_expected(self, result, expected_values, flattened)

      # Check shapes; if serialized is a Tensor we need its size to
      # properly check.
      batch_size = (
          input_tensor.eval().size if isinstance(input_tensor, ops.Tensor) else
          np.asarray(input_tensor).size)
      for k, f in feature_val.items():
        print("output_shapes as list ",
              tuple(dataset.output_shapes[k].as_list()))
        if isinstance(f, parsing_ops.FixedLenFeature) and f.shape is not None:
          self.assertEqual(dataset.output_shapes[k].as_list()[0], batch_size)
        elif isinstance(f, parsing_ops.VarLenFeature):
          self.assertEqual(dataset.output_shapes[k].as_list()[1], None)

  def testEmptySerializedWithAllDefaults(self):
    sparse_name = "st_a"
    a_name = "a"
    b_name = "b"
    c_name = "c:has_a_tricky_name"
    a_default = [0, 42, 0]
    b_default = np.random.rand(3, 3).astype(bytes)
    c_default = np.random.rand(2).astype(np.float32)

    expected_st_a = (  # indices, values, shape
        np.empty(
            (0, 2), dtype=np.int64),  # indices
        np.empty(
            (0,), dtype=np.int64),  # sp_a is DT_INT64
        np.array(
            [2, 0], dtype=np.int64))  # batch == 2, max_elems = 0

    expected_output = {
        sparse_name: expected_st_a,
        a_name: np.array(2 * [[a_default]]),
        b_name: np.array(2 * [b_default]),
        c_name: np.array(2 * [c_default]),
    }

    self._test(
        ops.convert_to_tensor(["", ""]), {
            sparse_name:
                parsing_ops.VarLenFeature(dtypes.int64),
            a_name:
                parsing_ops.FixedLenFeature(
                    (1, 3), dtypes.int64, default_value=a_default),
            b_name:
                parsing_ops.FixedLenFeature(
                    (3, 3), dtypes.string, default_value=b_default),
            c_name:
                parsing_ops.FixedLenFeature(
                    (2,), dtypes.float32, default_value=c_default),
        },
        expected_values=expected_output)

  def testEmptySerializedWithoutDefaultsShouldFail(self):
    input_features = {
        "st_a":
            parsing_ops.VarLenFeature(dtypes.int64),
        "a":
            parsing_ops.FixedLenFeature(
                (1, 3), dtypes.int64, default_value=[0, 42, 0]),
        "b":
            parsing_ops.FixedLenFeature(
                (3, 3),
                dtypes.string,
                default_value=np.random.rand(3, 3).astype(bytes)),
        # Feature "c" is missing a default, this gap will cause failure.
        "c":
            parsing_ops.FixedLenFeature(
                (2,), dtype=dtypes.float32),
    }

    # Edge case where the key is there but the feature value is empty
    original = example(features=features({"c": feature()}))
    self._test(
        [original.SerializeToString()],
        input_features,
        expected_err=(errors_impl.InvalidArgumentError,
                      "Feature: c \\(data type: float\\) is required"))

    # Standard case of missing key and value.
    self._test(
        ["", ""],
        input_features,
        expected_err=(errors_impl.InvalidArgumentError,
                      "Feature: c \\(data type: float\\) is required"))

  def testDenseNotMatchingShapeShouldFail(self):
    original = [
        example(features=features({
            "a": float_feature([1, 1, 3]),
        })), example(features=features({
            "a": float_feature([-1, -1]),
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    self._test(
        ops.convert_to_tensor(serialized),
        {"a": parsing_ops.FixedLenFeature((1, 3), dtypes.float32)},
        expected_err=(errors_impl.InvalidArgumentError,
                      "Key: a, Index: 1.  Number of float values"))

  def testDenseDefaultNoShapeShouldFail(self):
    original = [example(features=features({"a": float_feature([1, 1, 3]),})),]

    serialized = [m.SerializeToString() for m in original]

    self._test(
        ops.convert_to_tensor(serialized),
        {"a": parsing_ops.FixedLenFeature(None, dtypes.float32)},
        expected_err=(ValueError, "Missing shape for feature a"))

  def testSerializedContainingSparse(self):
    original = [
        example(features=features({
            "st_c": float_feature([3, 4])
        })),
        example(features=features({
            "st_c": float_feature([]),  # empty float list
        })),
        example(features=features({
            "st_d": feature(),  # feature with nothing in it
        })),
        example(features=features({
            "st_c": float_feature([1, 2, -1]),
            "st_d": bytes_feature([b"hi"])
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_st_c = (  # indices, values, shape
        np.array(
            [[0, 0], [0, 1], [3, 0], [3, 1], [3, 2]], dtype=np.int64), np.array(
                [3.0, 4.0, 1.0, 2.0, -1.0], dtype=np.float32), np.array(
                    [4, 3], dtype=np.int64))  # batch == 2, max_elems = 3

    expected_st_d = (  # indices, values, shape
        np.array(
            [[3, 0]], dtype=np.int64), np.array(
                ["hi"], dtype=bytes), np.array(
                    [4, 1], dtype=np.int64))  # batch == 2, max_elems = 1

    expected_output = {
        "st_c": expected_st_c,
        "st_d": expected_st_d,
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            "st_c": parsing_ops.VarLenFeature(dtypes.float32),
            "st_d": parsing_ops.VarLenFeature(dtypes.string)
        },
        expected_values=expected_output)

  def testSerializedContainingSparseFeature(self):
    original = [
        example(features=features({
            "val": float_feature([3, 4]),
            "idx": int64_feature([5, 10])
        })),
        example(features=features({
            "val": float_feature([]),  # empty float list
            "idx": int64_feature([])
        })),
        example(features=features({
            "val": feature(),  # feature with nothing in it
            # missing idx feature
        })),
        example(features=features({
            "val": float_feature([1, 2, -1]),
            "idx":
                int64_feature([0, 9, 3])  # unsorted
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_sp = (  # indices, values, shape
        np.array(
            [[0, 5], [0, 10], [3, 0], [3, 3], [3, 9]], dtype=np.int64),
        np.array(
            [3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32), np.array(
                [4, 13], dtype=np.int64))  # batch == 4, max_elems = 13

    expected_output = {"sp": expected_sp,}

    self._test(
        ops.convert_to_tensor(serialized),
        {"sp": parsing_ops.SparseFeature(["idx"], "val", dtypes.float32, [13])},
        expected_values=expected_output)

  def testSerializedContainingSparseFeatureReuse(self):
    original = [
        example(features=features({
            "val1": float_feature([3, 4]),
            "val2": float_feature([5, 6]),
            "idx": int64_feature([5, 10])
        })),
        example(features=features({
            "val1": float_feature([]),  # empty float list
            "idx": int64_feature([])
        })),
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_sp1 = (  # indices, values, shape
        np.array(
            [[0, 5], [0, 10]], dtype=np.int64), np.array(
                [3.0, 4.0], dtype=np.float32), np.array(
                    [2, 13], dtype=np.int64))  # batch == 2, max_elems = 13

    expected_sp2 = (  # indices, values, shape
        np.array(
            [[0, 5], [0, 10]], dtype=np.int64), np.array(
                [5.0, 6.0], dtype=np.float32), np.array(
                    [2, 7], dtype=np.int64))  # batch == 2, max_elems = 13

    expected_output = {
        "sp1": expected_sp1,
        "sp2": expected_sp2,
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            "sp1":
                parsing_ops.SparseFeature("idx", "val1", dtypes.float32, 13),
            "sp2":
                parsing_ops.SparseFeature(
                    "idx", "val2", dtypes.float32, size=7, already_sorted=True)
        },
        expected_values=expected_output)

  def testSerializedContaining3DSparseFeature(self):
    original = [
        example(features=features({
            "val": float_feature([3, 4]),
            "idx0": int64_feature([5, 10]),
            "idx1": int64_feature([0, 2]),
        })),
        example(features=features({
            "val": float_feature([]),  # empty float list
            "idx0": int64_feature([]),
            "idx1": int64_feature([]),
        })),
        example(features=features({
            "val": feature(),  # feature with nothing in it
            # missing idx feature
        })),
        example(features=features({
            "val": float_feature([1, 2, -1]),
            "idx0": int64_feature([0, 9, 3]),  # unsorted
            "idx1": int64_feature([1, 0, 2]),
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_sp = (
        # indices
        np.array(
            [[0, 5, 0], [0, 10, 2], [3, 0, 1], [3, 3, 2], [3, 9, 0]],
            dtype=np.int64),
        # values
        np.array([3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32),
        # shape batch == 4, max_elems = 13
        np.array([4, 13, 3], dtype=np.int64))

    expected_output = {"sp": expected_sp,}

    self._test(
        ops.convert_to_tensor(serialized), {
            "sp":
                parsing_ops.SparseFeature(["idx0", "idx1"], "val",
                                          dtypes.float32, [13, 3])
        },
        expected_values=expected_output)

  def testSerializedContainingDense(self):
    aname = "a"
    bname = "b*has+a:tricky_name"
    original = [
        example(features=features({
            aname: float_feature([1, 1]),
            bname: bytes_feature([b"b0_str"]),
        })), example(features=features({
            aname: float_feature([-1, -1]),
            bname: bytes_feature([b""]),
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_output = {
        aname:
            np.array(
                [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1),
        bname:
            np.array(
                ["b0_str", ""], dtype=bytes).reshape(2, 1, 1, 1, 1),
    }

    # No defaults, values required
    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32),
            bname:
                parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string),
        },
        expected_values=expected_output)

  # This test is identical as the previous one except
  # for the creation of 'serialized'.
  def testSerializedContainingDenseWithConcat(self):
    aname = "a"
    bname = "b*has+a:tricky_name"
    # TODO(lew): Feature appearing twice should be an error in future.
    original = [
        (example(features=features({
            aname: float_feature([10, 10]),
        })), example(features=features({
            aname: float_feature([1, 1]),
            bname: bytes_feature([b"b0_str"]),
        }))),
        (
            example(features=features({
                bname: bytes_feature([b"b100"]),
            })),
            example(features=features({
                aname: float_feature([-1, -1]),
                bname: bytes_feature([b"b1"]),
            })),),
    ]

    serialized = [
        m.SerializeToString() + n.SerializeToString() for (m, n) in original
    ]

    expected_output = {
        aname:
            np.array(
                [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1),
        bname:
            np.array(
                ["b0_str", "b1"], dtype=bytes).reshape(2, 1, 1, 1, 1),
    }

    # No defaults, values required
    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32),
            bname:
                parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string),
        },
        expected_values=expected_output)

  def testSerializedContainingDenseScalar(self):
    original = [
        example(features=features({
            "a": float_feature([1]),
        })), example(features=features({}))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_output = {
        "a":
            np.array(
                [[1], [-1]], dtype=np.float32)  # 2x1 (column vector)
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            "a":
                parsing_ops.FixedLenFeature(
                    (1,), dtype=dtypes.float32, default_value=-1),
        },
        expected_values=expected_output)

  def testSerializedContainingDenseWithDefaults(self):
    original = [
        example(features=features({
            "a": float_feature([1, 1]),
        })),
        example(features=features({
            "b": bytes_feature([b"b1"]),
        })),
        example(features=features({
            "b": feature()
        })),
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_output = {
        "a":
            np.array(
                [[1, 1], [3, -3], [3, -3]], dtype=np.float32).reshape(3, 1, 2,
                                                                      1),
        "b":
            np.array(
                ["tmp_str", "b1", "tmp_str"], dtype=bytes).reshape(3, 1, 1, 1,
                                                                   1),
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            "a":
                parsing_ops.FixedLenFeature(
                    (1, 2, 1), dtype=dtypes.float32, default_value=[3.0, -3.0]),
            "b":
                parsing_ops.FixedLenFeature(
                    (1, 1, 1, 1), dtype=dtypes.string, default_value="tmp_str"),
        },
        expected_values=expected_output)

  def testSerializedContainingSparseAndSparseFeatureAndDenseWithNoDefault(self):
    expected_st_a = (  # indices, values, shape
        np.empty(
            (0, 2), dtype=np.int64),  # indices
        np.empty(
            (0,), dtype=np.int64),  # sp_a is DT_INT64
        np.array(
            [2, 0], dtype=np.int64))  # batch == 2, max_elems = 0
    expected_sp = (  # indices, values, shape
        np.array(
            [[0, 0], [0, 3], [1, 7]], dtype=np.int64), np.array(
                ["a", "b", "c"], dtype="|S"), np.array(
                    [2, 13], dtype=np.int64))  # batch == 4, max_elems = 13

    original = [
        example(features=features({
            "c": float_feature([3, 4]),
            "val": bytes_feature([b"a", b"b"]),
            "idx": int64_feature([0, 3])
        })), example(features=features({
            "c": float_feature([1, 2]),
            "val": bytes_feature([b"c"]),
            "idx": int64_feature([7])
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    a_default = [1, 2, 3]
    b_default = np.random.rand(3, 3).astype(bytes)
    expected_output = {
        "st_a": expected_st_a,
        "sp": expected_sp,
        "a": np.array(2 * [[a_default]]),
        "b": np.array(2 * [b_default]),
        "c": np.array(
            [[3, 4], [1, 2]], dtype=np.float32),
    }

    self._test(
        ops.convert_to_tensor(serialized),
        {
            "st_a":
                parsing_ops.VarLenFeature(dtypes.int64),
            "sp":
                parsing_ops.SparseFeature("idx", "val", dtypes.string, 13),
            "a":
                parsing_ops.FixedLenFeature(
                    (1, 3), dtypes.int64, default_value=a_default),
            "b":
                parsing_ops.FixedLenFeature(
                    (3, 3), dtypes.string, default_value=b_default),
            # Feature "c" must be provided, since it has no default_value.
            "c":
                parsing_ops.FixedLenFeature((2,), dtypes.float32),
        },
        expected_values=expected_output)

  def testSerializedContainingSparseAndSparseFeatureWithReuse(self):
    expected_idx = (  # indices, values, shape
        np.array(
            [[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.int64),
        np.array([0, 3, 7, 1]), np.array(
            [2, 2], dtype=np.int64))  # batch == 4, max_elems = 2

    expected_sp = (  # indices, values, shape
        np.array(
            [[0, 0], [0, 3], [1, 1], [1, 7]], dtype=np.int64), np.array(
                ["a", "b", "d", "c"], dtype="|S"), np.array(
                    [2, 13], dtype=np.int64))  # batch == 4, max_elems = 13

    original = [
        example(features=features({
            "val": bytes_feature([b"a", b"b"]),
            "idx": int64_feature([0, 3])
        })), example(features=features({
            "val": bytes_feature([b"c", b"d"]),
            "idx": int64_feature([7, 1])
        }))
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_output = {
        "idx": expected_idx,
        "sp": expected_sp,
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            "idx":
                parsing_ops.VarLenFeature(dtypes.int64),
            "sp":
                parsing_ops.SparseFeature(["idx"], "val", dtypes.string, [13]),
        },
        expected_values=expected_output)

  def _testSerializedContainingVarLenDenseLargerBatch(self, batch_size):
    # During parsing, data read from the serialized proto is stored in buffers.
    # For small batch sizes, a buffer will contain one minibatch entry.
    # For larger batch sizes, a buffer may contain several minibatch
    # entries.  This test identified a bug where the code that copied
    # data out of the buffers and into the output tensors assumed each
    # buffer only contained one minibatch entry.  The bug has since been fixed.
    truth_int = [i for i in range(batch_size)]
    truth_str = [[("foo%d" % i).encode(), ("bar%d" % i).encode()]
                 for i in range(batch_size)]

    expected_str = copy.deepcopy(truth_str)

    # Delete some intermediate entries
    for i in range(batch_size):
      col = 1
      if np.random.rand() < 0.25:
        # w.p. 25%, drop out the second entry
        expected_str[i][col] = b"default"
        col -= 1
        truth_str[i].pop()
      if np.random.rand() < 0.25:
        # w.p. 25%, drop out the second entry (possibly again)
        expected_str[i][col] = b"default"
        truth_str[i].pop()

    expected_output = {
        # Batch size batch_size, 1 time step.
        "a": np.array(truth_int, dtype=np.int64).reshape(batch_size, 1),
        # Batch size batch_size, 2 time steps.
        "b": np.array(expected_str, dtype="|S").reshape(batch_size, 2),
    }

    original = [
        example(features=features(
            {"a": int64_feature([truth_int[i]]),
             "b": bytes_feature(truth_str[i])}))
        for i in range(batch_size)
    ]

    serialized = [m.SerializeToString() for m in original]

    self._test(
        ops.convert_to_tensor(serialized, dtype=dtypes.string), {
            "a":
                parsing_ops.FixedLenSequenceFeature(
                    shape=(),
                    dtype=dtypes.int64,
                    allow_missing=True,
                    default_value=-1),
            "b":
                parsing_ops.FixedLenSequenceFeature(
                    shape=[],
                    dtype=dtypes.string,
                    allow_missing=True,
                    default_value="default"),
        },
        expected_values=expected_output)

  def testSerializedContainingVarLenDenseLargerBatch(self):
    np.random.seed(3456)
    for batch_size in (1, 10, 20, 100, 256):
      self._testSerializedContainingVarLenDenseLargerBatch(batch_size)

  def testSerializedContainingVarLenDense(self):
    aname = "a"
    bname = "b"
    cname = "c"
    dname = "d"
    original = [
        example(features=features({
            cname: int64_feature([2]),
        })),
        example(features=features({
            aname: float_feature([1, 1]),
            bname: bytes_feature([b"b0_str", b"b1_str"]),
        })),
        example(features=features({
            aname: float_feature([-1, -1, 2, 2]),
            bname: bytes_feature([b"b1"]),
        })),
        example(features=features({
            aname: float_feature([]),
            cname: int64_feature([3]),
        })),
    ]

    serialized = [m.SerializeToString() for m in original]

    expected_output = {
        aname:
            np.array(
                [
                    [0, 0, 0, 0],
                    [1, 1, 0, 0],
                    [-1, -1, 2, 2],
                    [0, 0, 0, 0],
                ],
                dtype=np.float32).reshape(4, 2, 2, 1),
        bname:
            np.array(
                [["", ""], ["b0_str", "b1_str"], ["b1", ""], ["", ""]],
                dtype=bytes).reshape(4, 2, 1, 1, 1),
        cname:
            np.array([2, 0, 0, 3], dtype=np.int64).reshape(4, 1),
        dname:
            np.empty(shape=(4, 0), dtype=bytes),
    }

    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1), dtype=dtypes.float32, allow_missing=True),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (1, 1, 1), dtype=dtypes.string, allow_missing=True),
            cname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.int64, allow_missing=True),
            dname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.string, allow_missing=True),
        },
        expected_values=expected_output)

    # Test with padding values.
    expected_output_custom_padding = dict(expected_output)
    expected_output_custom_padding[aname] = np.array(
        [
            [-2, -2, -2, -2],
            [1, 1, -2, -2],
            [-1, -1, 2, 2],
            [-2, -2, -2, -2],
        ],
        dtype=np.float32).reshape(4, 2, 2, 1)

    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1),
                    dtype=dtypes.float32,
                    allow_missing=True,
                    default_value=-2.0),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (1, 1, 1), dtype=dtypes.string, allow_missing=True),
            cname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.int64, allow_missing=True),
            dname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.string, allow_missing=True),
        }, expected_output_custom_padding)

    # Change number of required values so the inputs are not a
    # multiple of this size.
    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1), dtype=dtypes.float32, allow_missing=True),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1, 1), dtype=dtypes.string, allow_missing=True),
        },
        expected_err=(
            errors_impl.OpError, "Key: b, Index: 2.  "
            "Number of bytes values is not a multiple of stride length."))

    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1),
                    dtype=dtypes.float32,
                    allow_missing=True,
                    default_value=[]),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1, 1), dtype=dtypes.string, allow_missing=True),
        },
        expected_err=(ValueError,
                      "Cannot reshape a tensor with 0 elements to shape"))

    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenFeature((None, 2, 1), dtype=dtypes.float32),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1, 1), dtype=dtypes.string, allow_missing=True),
        },
        expected_err=(ValueError,
                      "First dimension of shape for feature a unknown. "
                      "Consider using FixedLenSequenceFeature."))

    self._test(
        ops.convert_to_tensor(serialized), {
            cname:
                parsing_ops.FixedLenFeature(
                    (1, None), dtype=dtypes.int64, default_value=[[1]]),
        },
        expected_err=(ValueError,
                      "All dimensions of shape for feature c need to be known "
                      r"but received \(1, None\)."))

    self._test(
        ops.convert_to_tensor(serialized), {
            aname:
                parsing_ops.FixedLenSequenceFeature(
                    (2, 1), dtype=dtypes.float32, allow_missing=True),
            bname:
                parsing_ops.FixedLenSequenceFeature(
                    (1, 1, 1), dtype=dtypes.string, allow_missing=True),
            cname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.int64, allow_missing=False),
            dname:
                parsing_ops.FixedLenSequenceFeature(
                    shape=[], dtype=dtypes.string, allow_missing=True),
        },
        expected_err=(ValueError,
                      "Unsupported: FixedLenSequenceFeature requires "
                      "allow_missing to be True."))

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


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
  <resource name="oPlayer" type="RESOURCE"/>
  <resource name="oPlatform" type="RESOURCE"/>
</resources>

redpajama_set_name: RedPajamaGithub


text:
describe('the canary spec', () => {
  it('shows the infrastructure works', () => {
    true.should.be.true();
  });
});


text:
/**
 * @file ConteneurTDE.cpp
 * Le Puzzle
 * @brief Composant de conteneur d'items de capacité extensible
 */

#include <cassert>

#include "ConteneurTDE.h"

/**
 * @brief Initialise un conteneur d'items
 * Allocation en mémoire dynamique du conteneur d'items
 * de capacité (capa) extensible par pas d'extension (p)
 * @see detruire, pour sa désallocation en fin d'utilisation
 * @param[out] c : le conteneur d'items
 * @param [in] capa : capacité du conteneur
 * @param [in] p : pas d'extension de capacité
 * @pre capa>0 et p>0
 */
void initialiser(ConteneurTDE& c, unsigned int capa, unsigned int p) {
	assert((capa>0) && (p>0));
	c.capacite = capa;
	c.pasExtension = p;
	// arrêt du programme en cas d'erreur d'allocation
	c.tab = new Item[capa];
	/* Affichage pour une trace de l'allocation en TP
	 * Affichage à supprimer après le test du conteneur */
	//cout << "Allocation initiale de " << capa*sizeof(Item) << " octets ("
	//	 << capa << " item(s))" << endl;
}

/**
 * @brief Désalloue un conteneur d'items en mémoire dynamique
 * @see initialiser, le conteneur d'items a déjà été alloué
 * @param[in,out] c : le conteneur d'items
 */
void detruire(ConteneurTDE& c) {
	delete [] c.tab;
	c.tab = NULL;
}

/**
 * @brief Lecture d'un item d'un conteneur d'items
 * @param[in] c : le conteneur d'items
 * @param[in] i : la position de l'item dans le conteneur
 * @return l'item à la position i
 * @pre i < c.capacite
 */
 Item lire(const ConteneurTDE& c, unsigned int i) {
	assert(i < c.capacite);
	return c.tab[i];
}

/**
 * @brief Ecrire un item dans un conteneur d'items
 * @param[in,out] c : le conteneur d'items
 * @param[in] i : la position où ajouter/modifier l'item
 * @param[in] it : l'item à écrire
 */
void ecrire(ConteneurTDE& c, unsigned int i, const Item& it) {
	if (i>=c.capacite) {
		/* Stratégie de réallocation proportionnelle au pas d'extension :
		 * initialisez la nouvelle taille du conteneur (newTaille)
		 * à i * c.pasExtension */
		unsigned int newTaille = (i+1) * c.pasExtension;
		/* Allouez en mémoire dynamique un nouveau tableau (newT)
		 * à cette nouvelle taille*/
		Item* newT = new Item[newTaille];
		/* Recopiez les items déjà stockés dans le conteneur */
    	for (unsigned int i = 0; i < c.capacite; ++i)
      		newT[i] = c.tab[i];
      	/* Désallouez l'ancien tableau support du conteneur */
    	delete [] c.tab;
    	/* Actualiser la mise à jour du conteneur en mémoire dynamique
    	 * Faites pointer le tableau support du conteneur
    	 * sur le nouveau tableau en mémoire dynamique */
    	c.tab = newT;
    	/* Actualisez la taille du conteneur */
    	c.capacite = newTaille;
    		/* Affichage pour une trace de l'allocation en TP
	 	* En TP, pour tracer l'extension de l'allocation en mémoire,
	 	* affichez les informations qui suivent.
	 	* Cet affichage sera supprimé après le test du conteneur */
		//cout << "Extension - Allocaton/Réallocation de "
		// << newTaille*sizeof(Item)<< " octets (" << newTaille << " items)."
		//<< endl;
	}
	/* Ecriture de l'item (it) à la position i dans le conteneur */
	c.tab[i] = it;
}


text:
<?php

class JavaPage extends HostingPage {

	public function renderContent() {
		return $this->renderInstancesSection()
			.$this->renderCodeSection();
	}
}


text:
/* 作者: dailc
 * 时间: 2017-05-21
 * 描述: Copy-List-with-Random-Pointer
 *
 * 来自: https://leetcode.com/problems/copy-list-with-random-pointer
 */
(function(exports) {
	function RandomListNode(label) {
    	this.label = label;
    	this.next = this.random = null;
 	}
	/**
	 * @description singleNumber
	 * @param {number[]} nums
 	 * @return {number}
	 */
	exports.copyRandomList = function(head) {
		if(!head) {
			return null;
		}
		var hash = {};
		var newHead = {};
		var tmp = head;
		var tmpNew = newHead;
		while(tmp) {
			var node = null;
			if(hash[tmp.label]) {
				node = hash[tmp.label];
			} else {
				node = new RandomListNode(tmp.label);
				hash[tmp.label] = node;
			}
			var random = tmp.random;
			if(random) {
				var randomNode = null;
				if(hash[random.label]) {
					randomNode = hash[random.label];
				} else {
					randomNode = new RandomListNode(random.label);
					hash[random.label] = randomNode;
				}
				node.random = randomNode;
			}
			tmpNew.next = node;
			tmpNew = tmpNew.next;
			tmp = tmp.next;
		}
		return newHead.next;
	};

})(window.LeetCode = window.LeetCode || {});


text:
#include <errno.h>
#include <soc.h>
#include <clock_control.h>
#include <dt-bindings/clock/kinetis_sim.h>
#include <fsl_clock.h>

#define LOG_LEVEL CONFIG_CLOCK_CONTROL_LOG_LEVEL
#include <logging/log.h>
LOG_MODULE_REGISTER(clock_control);

static int mcux_sim_on(struct device *dev, clock_control_subsys_t sub_system)
{
	return 0;
}

static int mcux_sim_off(struct device *dev, clock_control_subsys_t sub_system)
{
	return 0;
}

static int mcux_sim_get_subsys_rate(struct device *dev,
				    clock_control_subsys_t sub_system,
				    u32_t *rate)
{
	clock_name_t clock_name;

	switch ((u32_t) sub_system) {
	case KINETIS_SIM_LPO_CLK:
		clock_name = kCLOCK_LpoClk;
		break;
	default:
		clock_name = (clock_name_t) sub_system;
		break;
	}

	*rate = CLOCK_GetFreq(clock_name);

	return 0;
}

static int mcux_sim_init(struct device *dev)
{
#ifdef DT_SIM_CLKOUT_DIVIDER
	SIM->CHIPCTL = (SIM->CHIPCTL & ~SIM_CHIPCTL_CLKOUTDIV_MASK)
		| SIM_CHIPCTL_CLKOUTDIV(DT_SIM_CLKOUT_DIVIDER);
#endif
#ifdef DT_SIM_CLKOUT_SOURCE
	SIM->CHIPCTL = (SIM->CHIPCTL & ~SIM_CHIPCTL_CLKOUTSEL_MASK)
		| SIM_CHIPCTL_CLKOUTSEL(DT_SIM_CLKOUT_SOURCE);
#endif

	return 0;
}

static const struct clock_control_driver_api mcux_sim_driver_api = {
	.on = mcux_sim_on,
	.off = mcux_sim_off,
	.get_rate = mcux_sim_get_subsys_rate,
};

DEVICE_AND_API_INIT(mcux_sim, DT_SIM_NAME,
		    &mcux_sim_init,
		    NULL, NULL,
		    PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEVICE,
		    &mcux_sim_driver_api);


text:
/**
 * Created by cmdv on 16/06/15.
 */
import Rx from 'rx';
import $ from 'jquery';

var $dragTarget = $('.dragTarget');
var $dragArea = $('.dragArea');

// Get the three major events
var mouseup = Rx.Observable.fromEvent($dragTarget, 'mouseup');
var mousemove = Rx.Observable.fromEvent(document, 'mousemove');
var mousedown = Rx.Observable.fromEvent($dragTarget, 'mousedown');

var _mouseUp = mouseup.subscribe(() => $dragTarget.css({cursor:'-webkit-grab'}) );

var mousedrag = mousedown.flatMap(function (e) {

  $dragTarget.css({cursor:'-webkit-grabbing'});
  // calculate offsets when mouse down
  var startX = e.offsetX, startY = e.offsetY;

  // Calculate delta with mousemove until mouseup
  return mousemove.map(function (mm) {
    mm.preventDefault();

    // accommodate for site header and sidebar
    var offsets = $dragArea.offset();

    return {
      left: mm.clientX - startX - offsets.left,
      top: mm.clientY - startY - offsets.top
    };
  }).takeUntil(mouseup);
});

// Update position
var subscription = mousedrag.subscribe(function (pos) {

  $dragTarget.css({top: pos.top, left: pos.left});

});


text:
void* emalloc(size_t size);
void ewc(int code, const char* message, ...);
char* strrep(const char* string, const char* substr, const char* replacement);

#endif


text:
import equals from './util/equals.js';
import capitalize from './capitalize.js';

// a -> Boolean
const isCapitalized = (s) => equals(s, capitalize(s));

export default isCapitalized;


text:
import { TabVisualClues } from "app/Components/StickyTabPage/StickyTabPage"
import { ContentTabs } from "./ContentTabs"
import { NavigationalTabs } from "./NavigationalTabs"
import { StepTabs } from "./StepTabs"
export * from "./Tab"

export { NavigationalTabs, ContentTabs, StepTabs }

export const TAB_BAR_HEIGHT = 44

export type TabsType = Array<{
  label: string
  superscript?: string
  completed?: boolean
  visualClues?: TabVisualClues
}>

export interface TabsProps {
  onTabPress: (tablabel: string, tabIndex: number) => void
  activeTab: number
  tabs: TabsType
}


text:
package com.github.cxfplus.com.sun.xml.bind.v2.runtime.reflect.opt;

import com.github.cxfplus.com.sun.xml.bind.DatatypeConverterImpl;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.reflect.DefaultTransducedAccessor;

/**
 * Template {@link TransducedAccessor} for a boolean field.
 *
 *

 * All the TransducedAccessor_field are generated from TransducedAccessor_field_B y t e
 *
 * @author Kohsuke Kawaguchi
 *
 * @see TransducedAccessor#get
 */
public final class TransducedAccessor_method_Boolean extends DefaultTransducedAccessor {
    public String print(Object o) {
        return DatatypeConverterImpl._printBoolean( ((Bean)o).get_boolean() );
    }

    public void parse(Object o, CharSequence lexical) {
        ((Bean)o).set_boolean(DatatypeConverterImpl._parseBoolean(lexical));
    }

    public boolean hasValue(Object o) {
        return true;
    }
//
//    public void writeLeafElement(Object o, QName tagName, String fieldName, XMLSerializer w) throws SAXException, AccessorException {
//        w.leafElement(tagName, ((Bean)o).get_boolean(), fieldName );
//    }
}


text:
import labeller from './labeller'

require('dotenv').config()

process.on('unhandledRejection', function(reason, p) {
  console.log('Unhandled rejection in promise', p, 'caused by', reason)
})

const API_TOKEN = process.env.GITHUB_TOKEN
const pathArray = process.cwd().split('/')
const folderName = pathArray[pathArray.length - 1]

labeller(API_TOKEN, folderName)


text:
''' test_label_generation
making unique slugs
'''
import unittest

from application.utilities import generate_label

class GenerateLabel(unittest.TestCase):
    ''' nonstandard chars
    '''
    def test_default(self):
        value = 'tada'
        existing_labels = ['et', 'voila']
        expected = 'tada'
        self.assertEqual(generate_label(value, existing_labels), expected)

    def test_duplicate(self):
        value = 'tada'
        existing_labels = ['et', 'voila', 'tada']
        expected = 'tada-1'
        self.assertEqual(generate_label(value, existing_labels), expected)

    def test_three_duplicates(self):
        value = 'tada'
        existing_labels = ['et', 'voila', 'tada', 'tada-1', 'tada-2']
        expected = 'tada-3'
        self.assertEqual(generate_label(value, existing_labels), expected)

    def test_invalid_chars(self):
        value = 'tada??'
        existing_labels = ['et', 'voila']
        expected = 'tada'
        self.assertEqual(generate_label(value, existing_labels), expected)

    def test_invalid_chars_with_duplicates(self):
        value = 'tada??'
        existing_labels = ['et', 'voila', 'tada', 'tada-1']
        expected = 'tada-2'
        self.assertEqual(generate_label(value, existing_labels), expected)


text:
_**Note:**
This document describes how to run GitLab under a relative URL for installations
from source. If you are using an Omnibus package,
[the steps are different][omnibus-rel]. Use this guide along with the
[installation guide](installation.md) if you are installing GitLab for the
first time._

---

While it is recommended to install GitLab on its own (sub)domain, sometimes
this is not possible due to a variety of reasons. In that case, GitLab can also
be installed under a relative URL, for example `https://example.com/gitlab`.

There is no limit to how deeply nested the relative URL can be. For example you
could serve GitLab under `/foo/bar/gitlab/git` without any issues.

Note that by changing the URL on an existing GitLab installation, all remote
URLs will change, so you'll have to manually edit them in any local repository
that points to your GitLab instance.

---

The TL;DR list of configuration files that you need to change in order to
serve GitLab under a relative URL is:

- `/home/git/gitlab/config/application.rb`
- `/home/git/gitlab/config/gitlab.yml`
- `/home/git/gitlab/config/unicorn.rb`
- `/home/git/gitlab-shell/config.yml`
- `/etc/default/gitlab`

After all the changes you need to recompile the assets and [restart GitLab].

### Relative URL requirements

If you configure GitLab with a relative URL, the assets (JavaScript, CSS, fonts,
images, etc.) will need to be recompiled, which is a task which consumes a lot
of CPU and memory resources. To avoid out-of-memory errors, you should have at
least 2GB of RAM available on your system, while we recommend 4GB RAM, and 4 or
8 CPU cores.

See the [requirements](requirements.md) document for more information.

### Enable relative URL in GitLab

_**Note:**
Do not make any changes to your web server configuration file regarding
relative URL. The relative URL support is implemented by GitLab Workhorse._

---

Before following the steps below to enable relative URL in GitLab, some
assumptions are made:

- GitLab is served under `/gitlab`
- The directory under which GitLab is installed is `/home/git/`

Make sure to follow all steps below:

1.  (Optional) If you run short on resources, you can temporarily free up some
    memory by shutting down the GitLab service with the following command:

    ```shell
    sudo service gitlab stop
    ```

1.  Edit `/home/git/gitlab/config/application.rb` and uncomment/change the
    following line:

    ```ruby
    config.relative_url_root = "/gitlab"
    ```

1.  Edit `/home/git/gitlab/config/gitlab.yml` and uncomment/change the
    following line:

    ```yaml
    relative_url_root: /gitlab
    ```

1.  Edit `/home/git/gitlab/config/unicorn.rb` and uncomment/change the
    following line:

    ```ruby
    ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
    ```

1.  Edit `/home/git/gitlab-shell/config.yml` and append the relative path to
    the following line:

    ```yaml
    gitlab_url: http://127.0.0.1/gitlab
    ```

1.  Make sure you have copied the supplied init script and the defaults file
    as stated in the [installation guide](installation.md#install-init-script).
    Then, edit `/etc/default/gitlab` and set in `gitlab_workhorse_options` the
    `-authBackend` setting to read like:

    ```shell
    -authBackend http://127.0.0.1:8080/gitlab
    ```

    **Note:**
    If you are using a custom init script, make sure to edit the above
    gitlab-workhorse setting as needed.

1.  After all the above changes recompile the assets. This is an important task
    and will take some time to complete depending on the server resources:

    ```
    cd /home/git/gitlab
    sudo -u git -H bundle exec rake assets:clean assets:precompile RAILS_ENV=production
    ```

1. [Restart GitLab][] for the changes to take effect.

### Disable relative URL in GitLab

To disable the relative URL, follow the same steps as above and set up the
GitLab URL to one that doesn't contain a relative path.

[omnibus-rel]: http://doc.gitlab.com/omnibus/settings/configuration.html#configuring-a-relative-url-for-gitlab "How to setup relative URL in Omnibus GitLab"
[restart gitlab]: ../administration/restart_gitlab.md#installations-from-source "How to restart GitLab"


text:
package de.idos.updates;

import de.idos.updates.store.NullInstallation;
import de.idos.updates.store.OngoingInstallation;

import static de.idos.updates.UpdateAvailability.Available;

public class UpdateCheck implements Updater {
  private final UpdateConnection updateConnection;
  private boolean checkHasRun = false;
  private Version currentVersion;
  private InstallableUpdate latestUpdate;

  public UpdateCheck(UpdateConnection updateConnection) {
    this.updateConnection = updateConnection;
  }

  @Override
  public UpdateAvailability hasUpdate() {
    assertCheckHasRun();
    return latestUpdate.isUpdateFrom(currentVersion);
  }

  @Override
  public Version getInstalledVersion() {
    assertCheckHasRun();
    return currentVersion;
  }

  @Override
  public Version getLatestVersion() {
    assertCheckHasRun();
    if (!latestVersionIsNewerThanInstalledVersion()) {
      return currentVersion;
    }
    return latestUpdate.getVersion();
  }

  @Override
  public OngoingInstallation updateToLatestVersion() {
    assertCheckHasRun();
    if (latestVersionIsNewerThanInstalledVersion()) {
      return latestUpdate.install();
    }
    return new NullInstallation();
  }

  @Override
  public synchronized void runCheck() {
    if (!checkHasRun) {
      this.currentVersion = updateConnection.getLatestInstalledVersion();
      this.latestUpdate = updateConnection.getLatestAvailableUpdate();
      this.checkHasRun = true;
    }
  }

  private boolean latestVersionIsNewerThanInstalledVersion() {
    return hasUpdate() == Available;
  }

  private void assertCheckHasRun() {
    if (!checkHasRun) {
      throw new IllegalStateException("The check for updates has not yet run. Please execute it by calling 'runCheck()' before calling other methods.");
    }
  }
}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// Filing Returns Model
    /// </summary>
    public class FilingReturnModelBasic
    {
        /// <summary>
        /// The unique ID number of the company filing return.
        /// </summary>
        public Int64? companyId { get; set; }

        /// <summary>
        /// The unique ID number of this filing return.
        /// </summary>
        public Int64? id { get; set; }

        /// <summary>
        /// The filing id that this return belongs too
        /// </summary>
        public Int64? filingId { get; set; }

        /// <summary>
        /// The resourceFileId of the return
        /// </summary>
        public Int64? resourceFileId { get; set; }

        /// <summary>
        /// The region id that this return belongs too
        /// </summary>
        public Int64? filingRegionId { get; set; }

        /// <summary>
        /// The unique ID number of the filing calendar associated with this return.
        /// </summary>
        public Int64? filingCalendarId { get; set; }

        /// <summary>
        /// The country of the form.
        /// </summary>
        public String country { get; set; }

        /// <summary>
        /// The region of the form.
        /// </summary>
        public String region { get; set; }

        /// <summary>
        /// The month of the filing period for this tax filing.
        /// The filing period represents the year and month of the last day of taxes being reported on this filing.
        /// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
        /// </summary>
        public Int32? endPeriodMonth { get; set; }

        /// <summary>
        /// The year of the filing period for this tax filing.
        /// The filing period represents the year and month of the last day of taxes being reported on this filing.
        /// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
        /// </summary>
        public Int16? endPeriodYear { get; set; }

        /// <summary>
        /// The current status of the filing return.
        /// </summary>
        public FilingStatusId? status { get; set; }

        /// <summary>
        /// The filing frequency of the return.
        /// </summary>
        public FilingFrequencyId? filingFrequency { get; set; }

        /// <summary>
        /// The date the return was filed by Avalara.
        /// </summary>
        public DateTime? filedDate { get; set; }

        /// <summary>
        /// The sales amount.
        /// </summary>
        public Decimal? salesAmount { get; set; }

        /// <summary>
        /// The filing type of the return.
        /// </summary>
        public FilingTypeId? filingType { get; set; }

        /// <summary>
        /// The name of the form.
        /// </summary>
        public String formName { get; set; }

        /// <summary>
        /// The remittance amount of the return.
        /// </summary>
        public Decimal? remitAmount { get; set; }

        /// <summary>
        /// The unique code of the form.
        /// </summary>
        public String formCode { get; set; }

        /// <summary>
        /// A description for the return.
        /// </summary>
        public String description { get; set; }

        /// <summary>
        /// The taxable amount.
        /// </summary>
        public Decimal? taxableAmount { get; set; }

        /// <summary>
        /// The tax amount.
        /// </summary>
        public Decimal? taxAmount { get; set; }

        /// <summary>
        /// The amount collected by avalara for this return
        /// </summary>
        public Decimal? collectAmount { get; set; }

        /// <summary>
        /// The tax due amount.
        /// </summary>
        public Decimal? taxDueAmount { get; set; }

        /// <summary>
        /// The non-taxable amount.
        /// </summary>
        public Decimal? nonTaxableAmount { get; set; }

        /// <summary>
        /// The non-taxable due amount.
        /// </summary>
        public Decimal? nonTaxableDueAmount { get; set; }

        /// <summary>
        /// Consumer use tax liability.
        /// </summary>
        public Decimal? consumerUseTaxAmount { get; set; }

        /// <summary>
        /// Consumer use non-taxable amount.
        /// </summary>
        public Decimal? consumerUseNonTaxableAmount { get; set; }

        /// <summary>
        /// Consumer use taxable amount.
        /// </summary>
        public Decimal? consumerUseTaxableAmount { get; set; }

        /// <summary>
        /// The amount of sales excluded from the liability calculation
        /// </summary>
        public Decimal? excludedSalesAmount { get; set; }

        /// <summary>
        /// The amount of non-taxable sales excluded from the liability calculation
        /// </summary>
        public Decimal? excludedNonTaxableAmount { get; set; }

        /// <summary>
        /// The amount of tax excluded from the liability calculation
        /// </summary>
        public Decimal? excludedTaxAmount { get; set; }

        /// <summary>
        /// Accrual type of the return
        /// </summary>
        public AccrualType? accrualType { get; set; }

        /// <summary>
        /// The attachments for this return.
        /// </summary>
        public List<FilingAttachmentModel> attachments { get; set; }

        /// <summary>
        /// The date when this record was created.
        /// </summary>
        public DateTime? createdDate { get; set; }

        /// <summary>
        /// The User ID of the user who created this record.
        /// </summary>
        public Int32? createdUserId { get; set; }

        /// <summary>
        /// The date/time when this record was last modified.
        /// </summary>
        public DateTime? modifiedDate { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
package org.apache.geode.internal.size;

import static org.apache.geode.internal.size.SizeTestUtil.*;
import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.util.ObjectSizer;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class SizeClassOnceObjectSizerJUnitTest {

  @Test
  public void test() {
    byte[] b1 = new byte[5];
    byte[] b2 = new byte[15];

    // Make sure that we actually size byte arrays each time
    assertEquals(roundup(OBJECT_SIZE + 4 + 5), ObjectSizer.SIZE_CLASS_ONCE.sizeof(b1));
    assertEquals(roundup(OBJECT_SIZE + 4 + 15), ObjectSizer.SIZE_CLASS_ONCE.sizeof(b2));

    String s1 = "12345";
    String s2 = "1234567890";

    // The size of a string varies based on the JDK version. With 1.7.0_06
    // a couple of fields were removed. So just measure the size of an empty string.
    String emptyString = "";
    int emptySize = ObjectSizer.SIZE_CLASS_ONCE.sizeof(emptyString)
        - ObjectSizer.SIZE_CLASS_ONCE.sizeof(new char[0]);

    // Make sure that we actually size strings each time
    assertEquals(emptySize + roundup(OBJECT_SIZE + 4 + 5 * 2),
        ObjectSizer.SIZE_CLASS_ONCE.sizeof(s1));
    assertEquals(emptySize + roundup(OBJECT_SIZE + 4 + 10 * 2),
        ObjectSizer.SIZE_CLASS_ONCE.sizeof(s2));

    TestObject t1 = new TestObject(5);
    TestObject t2 = new TestObject(15);
    int t1Size = ObjectSizer.SIZE_CLASS_ONCE.sizeof(t1);
    assertEquals(roundup(OBJECT_SIZE + REFERENCE_SIZE) + roundup(OBJECT_SIZE + 4 + 5), t1Size);
    // Since we are using SIZE_CLASS_ONCE t2 should have the same size as t1
    assertEquals(t1Size, ObjectSizer.SIZE_CLASS_ONCE.sizeof(t2));
  }

  private static class TestObject {
    private final byte[] field;

    public TestObject(int size) {
      this.field = new byte[size];
    }
  }

}


text: export * from './BingoActions';


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace TestInMemory
{
    public class DumpDbNameMiddleware
    {
        private readonly RequestDelegate next;

        public DumpDbNameMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext ctx, SomeDbContext db)
        {
            if (ctx.Request.Path.StartsWithSegments("/db"))
            {
                await ctx.Response.WriteAsync(db.Database.ProviderName);
            }
            else
            {
                await next(ctx);
            }
        }
    }
}


text:
[![CI Status](https://img.shields.io/travis/encosw/ChopraSSO.svg?style=flat)](https://travis-ci.org/encosw/ChopraSSO)
[![Version](https://img.shields.io/cocoapods/v/ChopraSSO.svg?style=flat)](https://cocoapods.org/pods/ChopraSSO)
[![License](https://img.shields.io/cocoapods/l/ChopraSSO.svg?style=flat)](https://cocoapods.org/pods/ChopraSSO)
[![Platform](https://img.shields.io/cocoapods/p/ChopraSSO.svg?style=flat)](https://cocoapods.org/pods/ChopraSSO)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

ChopraSSO is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'ChopraSSO'
```

## Author

encosw, kovacs.ors@encosoft.hu

## License

ChopraSSO is available under the MIT license. See the LICENSE file for more info.


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/EC2CreateVolumeResponseUnmarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/EC2CreateVolumeResponseUnmarshaller</TokenIdentifier>
			<Abstract type="html">Create Volume Response Unmarshaller</Abstract>
			<DeclaredIn>EC2CreateVolumeResponseUnmarshaller.h</DeclaredIn>

			<NodeRef refid="442"/>
		</Token>

	</File>
</Tokens>


text:
#include "sysdep.h"

#ifdef GCC

#include "sys/time.h"

 // Returns a time index in milliseconds
unsigned get_tick_count()
{
    static struct timezone tz = { 0,0 };
    static const float t1 = 1000.0f;
    static const float t2 = 0.01;
    timeval t;
    gettimeofday(&t, &tz);
    return long((t.tv_sec & 0x000FFFFF)*t1 + t.tv_usec*t2);
}

#endif


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Abouts on Kashyap Tumkur's Blog</title>
    <link>http://kashyaptumkur.com/about/</link>
    <description>Recent content in Abouts on Kashyap Tumkur's Blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Fri, 01 Jan 2016 00:00:00 -0700</lastBuildDate>
    <atom:link href="http://kashyaptumkur.com/about/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>About</title>
      <link>http://kashyaptumkur.com/about/</link>
      <pubDate>Fri, 01 Jan 2016 00:00:00 -0700</pubDate>

      <guid>http://kashyaptumkur.com/about/</guid>
      <description>
I&rsquo;m Kashyap Tumkur, a software engineer, technology geek, and an avid reader based out of Northern California. I set up this blog to journal my experiences and polish my writing skills. If you&rsquo;re looking for my professional information, see my LinkedIn page.

</description>
    </item>

  </channel>
</rss>


text:
<!DOCTYPE html>

		<title>Counter App Demo</title>
		<link rel="stylesheet" type="text/css" href="demo.css" />

Documentation

Counter App Demo

Echo Counter encapsulates interaction with the Echo Count API and provides a simple live updating number.


text: package gocacher


text:
module Scalr
  class Caller

    # TODO: cache responses for some actions? For example, we fetch farm details a number of times...

    # to save typing we map parameters to shorter names
    #   Scalr API name   => Our short name
    PARAM_ALIASES = {
        application_id:     :application,
        farm_id:            :farm,
        records_limit:      :limit,
        remote_path:        :path,
        farm_role_id:       :role,
        script_id:          :script,
        server_id:          :server,
        start_from:         :start,
        deployment_task_id: :task,
    }

    def self.collect_options(params, api_names)
      new(nil).collect_options(params, api_names)
    end

    def self.variable_value(variable_name, options)
      response = new(:global_variables_list).invoke(options)
      if response && response.success?
        matched = response.content.detect {|pair| pair.name_equals?(variable_name)}
        matched.nil? ? nil : matched.value
      else
        error = response.nil? ? '(unknown error, no response)' : response.error
        raise "Failed to fetch variable #{variable_name}: #{error}"
      end
    end

    def initialize(action_name)
      @action_name  = action_name
      unless @action_name.nil? # hack!
        @request_info = Scalr::Request.action(action_name)
        raise "Unknown action [Given: #{action_name.to_s}]" unless @request_info
      end
      @partial_options = {}
    end

    # store options away until later, will be re-used
    # with every invoke()
    def partial_options(options)
      @partial_options = @partial_options.merge(options)
      self
    end

    def dispatch(params)
      options = collect_options(params, @request_info[:inputs].keys)
      invoke(options)
    end

    def invoke(options = {})
      valid_keys = @request_info[:inputs].keys
      valid_options = options.
          merge(@partial_options).
          delete_if {|key,_| !valid_keys.include?(key)}
      begin
        Scalr.send(@action_name, valid_options)
      rescue Scalr::Request::InvalidInputError => e
        $stderr.puts("ERROR: #{e.message}")
        nil
      end
    end

    # allow use of either our short name or Scalr API name
    # return: hash of API option name (e.g., :farm_id) to value that
    #         will be used for that option
    def collect_options(params, api_names = @request_info[:inputs].keys)
      options = {}
      api_names.each do |api_name|
        cli_name = map_parameter_key(api_name)
        first_value = first_value_for(params, cli_name, api_name)
        value = transform_value(api_name, first_value, params)
        options[api_name] = value if value
      end
      options
    end

    def map_parameter_key(key)
      PARAM_ALIASES[key.to_sym] || key.to_sym
    end

    def first_value_for(params, *keys)
      keys.each do |key|
        option = option_by_name(params, key)
        if option
          value = option.values.length > 1 ? option.values : option.value
          return value if value
        end
      end
      nil
    end

# Note that we're using params.find vs params['name'] because
# the latter kills the program (weird!)
    def option_by_name(params, name)
      params.find {|option| option.name.to_s == name.to_s}
    end

# allow transformations/lookups of data from the user
    def transform_value(name, value, params)
      if name == :farm_id
        # if the application is given and the farm is not, see if the
        # application can be resolved to a farm
        if value.nil? && application_name = first_value_for(params, 'application')
          Scalr.match_alias('farm', application_name)
        elsif ! value.nil?
          resolve_farm(value)
        end
      elsif name == :farm_role_id && option_by_name(params, 'farm') && ! value.nil?
        roles = resolve_farm_role(value, params)
        if roles.empty?
          raise "Cannot resolve farm role [Farm: #{params['farm'].value}] [Role: #{value}]"
        else
          roles.first
        end
      elsif name == :script_id && ! value.nil?
        resolve_script(value)
      elsif name == :server_id && ! value.nil?
        if match_info = value.match(/^(\w+)\.(\d+)$/) # heroku format
          role_name = match_info[1]
          server_index = match_info[2]
          roles = resolve_farm_role(role_name, params)
          if roles.empty?
            raise "Cannot resolve farm role [Farm: #{params['farm'].value}] [Role: #{role_name}]"
          end
          server_guid = resolve_server_index(server_index, params, roles.first)
          if server_guid.nil?
            raise "Cannot resolve server index to GUID [Farm: #{params['farm'].value}] [Role/server: #{value}]"
          end
          server_guid
        elsif value.to_s.length < 10 # < 4 => int, < 10 => string with ID start (short hash)
          server_guid = resolve_server_index(value, params)
          if server_guid.nil?
            raise "Cannot resolve server index to GUID [Farm: #{params['farm'].value}] [Role: #{params['role'].value}] [Server index: #{value}]"
          end
          server_guid
        else
          value
        end
      elsif name == :application_id && ! value.nil?
        resolve_application(value)
      else
        value
      end
    end

    def resolve_application(app_alias)
      return app_alias if app_alias.match(/^\d+$/) || Scalr.is_aliased_name?('application', app_alias)
      Scalr.match_alias('application', app_alias)
    end

    def resolve_farm(farm_alias)
      return farm_alias if farm_alias.match(/^\d+$/) || Scalr.is_aliased_name?('farm', farm_alias)
      Scalr.match_alias('farm', farm_alias)
    end

    # returns an array of farm role IDs
    def resolve_farm_role(name, params, response = nil)
      role_names = []
      if Scalr.is_aliased_name?('role', name)
        role_names << name
      elsif name != 'all'
        role_names << Scalr.match_alias('role', name)
      end

      unless response
        response = self.class.new(:farm_get_details).dispatch(params)
        unless response.success?
          $stderr.puts('Failed to get farm details!')
          #generic_error(response)
          return []
        end
      end

      response.content.
          find_all {|role_info| name == 'all' || role_names.include?(role_info.name.downcase)}.
          map {|role_info| role_info.id}
    end

    def resolve_script(name)
      return name if name.strip.match(/^\d+$/)

      response = self.class.new(:scripts_list).invoke()
      return nil unless response.success?
      script = response.content.find {|script| script.name.downcase == name.downcase}
      unless script
        raise "Failed to find a script with name '#{name}'"
      end
      script.id
    end

    # given a count of a server within a role, or a string with the start of a GUID,
    # resolve it to a fully-qualified  server ID (GUID)
    def resolve_server_index(index, params, role_id = nil)
      response = self.class.new(:farm_get_details).dispatch(params)
      return nil unless response.success?

      # if we have a role available to disambiguate, use it
      if role_id
        role = response.content.find {|role_info| role_id.to_s == role_info[:id]}
        unless role
          raise "No role with ID #{role_id} exists in farm #{params['farm'].value}"
        end
        servers = role.servers
      elsif option_by_name(params, 'role') && params['role'].given?
        role_ids = resolve_farm_role(params['role'].value, params, response)
        servers = response.content.find {|role_info| role_ids.include?(role_info[:id])}.servers
      else
        servers = response.content.flat_map {|role_info| role_info.servers}
      end

      if index.to_s.length > 4
        matching = servers.find_all {|server| server.id.match(/^#{index.to_s}/)}
      else
        matching = servers.find_all {|server| index.to_i == server.index}
      end

      # if too many, remove non-running ones
      if matching.length > 1
        matching = servers.find_all {|server| server.running?}
      end

      # if STILL too many you probably didn't assign a role...
      if matching.length > 1
        raise "Too many servers match index '#{index}' within the farm! Specify a role to disambiguate."
      end

      matching.empty? ? nil : matching.first.id
    end
  end
end


text:
package org.springframework.web.util;

import java.io.File;
import java.util.Collection;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpRequest;
import org.springframework.util.MultiValueMap;

abstract public class WebUtils
{
    public WebUtils(){}
    public static <T> T getNativeRequest(ServletRequest p0, Class<T> p1){ return null; }
    public static <T> T getNativeResponse(ServletResponse p0, Class<T> p1){ return null; }
    public static Boolean getDefaultHtmlEscape(ServletContext p0){ return null; }
    public static Boolean getResponseEncodedHtmlEscape(ServletContext p0){ return null; }
    public static Cookie getCookie(HttpServletRequest p0, String p1){ return null; }
    public static File getTempDir(ServletContext p0){ return null; }
    public static Map<String, Object> getParametersStartingWith(ServletRequest p0, String p1){ return null; }
    public static MultiValueMap<String, String> parseMatrixVariables(String p0){ return null; }
    public static Object getRequiredSessionAttribute(HttpServletRequest p0, String p1){ return null; }
    public static Object getSessionAttribute(HttpServletRequest p0, String p1){ return null; }
    public static Object getSessionMutex(HttpSession p0){ return null; }
    public static String CONTENT_TYPE_CHARSET_PREFIX = null;
    public static String DEFAULT_CHARACTER_ENCODING = null;
    public static String DEFAULT_WEB_APP_ROOT_KEY = null;
    public static String ERROR_EXCEPTION_ATTRIBUTE = null;
    public static String ERROR_EXCEPTION_TYPE_ATTRIBUTE = null;
    public static String ERROR_MESSAGE_ATTRIBUTE = null;
    public static String ERROR_REQUEST_URI_ATTRIBUTE = null;
    public static String ERROR_SERVLET_NAME_ATTRIBUTE = null;
    public static String ERROR_STATUS_CODE_ATTRIBUTE = null;
    public static String FORWARD_CONTEXT_PATH_ATTRIBUTE = null;
    public static String FORWARD_PATH_INFO_ATTRIBUTE = null;
    public static String FORWARD_QUERY_STRING_ATTRIBUTE = null;
    public static String FORWARD_REQUEST_URI_ATTRIBUTE = null;
    public static String FORWARD_SERVLET_PATH_ATTRIBUTE = null;
    public static String HTML_ESCAPE_CONTEXT_PARAM = null;
    public static String INCLUDE_CONTEXT_PATH_ATTRIBUTE = null;
    public static String INCLUDE_PATH_INFO_ATTRIBUTE = null;
    public static String INCLUDE_QUERY_STRING_ATTRIBUTE = null;
    public static String INCLUDE_REQUEST_URI_ATTRIBUTE = null;
    public static String INCLUDE_SERVLET_PATH_ATTRIBUTE = null;
    public static String RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM = null;
    public static String SESSION_MUTEX_ATTRIBUTE = null;
    public static String TEMP_DIR_CONTEXT_ATTRIBUTE = null;
    public static String WEB_APP_ROOT_KEY_PARAM = null;
    public static String findParameterValue(Map<String, ? extends Object> p0, String p1){ return null; }
    public static String findParameterValue(ServletRequest p0, String p1){ return null; }
    public static String getRealPath(ServletContext p0, String p1){ return null; }
    public static String getSessionId(HttpServletRequest p0){ return null; }
    public static String[] SUBMIT_IMAGE_SUFFIXES = null;
    public static boolean hasSubmitParameter(ServletRequest p0, String p1){ return false; }
    public static boolean isIncludeRequest(ServletRequest p0){ return false; }
    public static boolean isSameOrigin(HttpRequest p0){ return false; }
    public static boolean isValidOrigin(HttpRequest p0, Collection<String> p1){ return false; }
    public static void clearErrorRequestAttributes(HttpServletRequest p0){}
    public static void exposeErrorRequestAttributes(HttpServletRequest p0, Throwable p1, String p2){}
    public static void removeWebAppRootSystemProperty(ServletContext p0){}
    public static void setSessionAttribute(HttpServletRequest p0, String p1, Object p2){}
    public static void setWebAppRootSystemProperty(ServletContext p0){}
}


text:
package org.bpmscript.process;

import org.bpmscript.ICompletedResult;
import org.bpmscript.IFailedResult;
import org.bpmscript.IKilledResult;
import org.bpmscript.IPausedResult;

/**
 * Observer interface for listening for instance state changes
 */
public interface IInstanceListener {

    /**
     * Called when an instance is first created
     *
     * @param pid the instance that was created
     * @param definition the definition that created it
     */
	void instanceCreated(String pid, IDefinition definition);

	/**
	 * Called when an instance pauses i.e. persists itself and is
	 * not yet completed.
	 *
	 * @param pid the instance that pauses
	 * @param result the paused result, including the continuation
	 */
	void instancePaused(String pid, IPausedResult result);

	/**
	 * Called if the instance fails
	 *
	 * @param pid the failing instance
	 * @param result the failed result including the exception
	 */
    void instanceFailed(String pid, IFailedResult result);

    /**
     * Called when an instance is killed
     *
     * @param pid the instance id that was killed
     * @param result the killed result
     */
    void instanceKilled(String pid, IKilledResult result);

    /**
     * Called when an instance completes
     *
     * @param pid the instance that completed
     * @param result the completed result
     */
	void instanceCompleted(String pid, ICompletedResult result);

}


text:
.. :orphan:

x
  default: ``0``

  the x-coordinate to place, relative to the upper-left corner of the card and moving right as it increases. Supports :doc:`/units` and :doc:`/shorthands`.

  Also can be ``:center`` or ``:middle`` for half the width of the deck.

y
  default: ``0``

  the y-coordinate to place, relative to the upper-left corner of the card and moving downward as it increases. Supports :doc:`/units` and :doc:`/shorthands`.

  Also can be ``:center`` or ``:middle`` for half the height of the deck.


text:
if is_osx; then
    export MAKEFLAGS=-j1
    export CFLAGS=-I$MP_PREFIX/include/
    export LIBS=$MP_PREFIX/lib/libiconv.a
    export LDFLAGS="-L${HB_PREFIX}/opt/openssl/lib"
    export CPPFLAGS=-I${HB_PREFIX}/opt/openssl/include
    export PKG_CONFIG_PATH=${HB_PREFIX}/opt/openssl/lib/pkgconfig
fi

### Download and compile source...
[ ! -d $DOTFILES/build ] && mkdir -p $DOTFILES/build
cd $DOTFILES/build

[ -d nmh ] || git clone git://git.savannah.nongnu.org/nmh.git

cd nmh &&
    git pull &&
    ./autogen.sh &&
    ./configure --prefix=/usr/local --with-tls --with-mts=smtp &&
    make &&
    make install

#git clone git@github.com:nicm/fdm.git &&
#    cd fdm &&
#    ./autogen.sh &&
#    ./configure --prefix=/usr/local &&
#    make &&
#    make install


text:
<?php namespace ResourceApp;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class Aula extends Model
{
     /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'aulas';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['numero', 'edificio', 'aireAcondicionado', 'proyector', 'computadora'];

}


text:
<?php

namespace WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * LigneFraisForfait
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\LigneFraisForfaitRepository")
 */
class LigneFraisForfait
{
    /**
     * @var FicheFrais
     *
     * @ORM\ManyToOne(
     *      targetEntity="WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FicheFrais",
     *      inversedBy="lignesFraisForfait"
     * )
     * @ORM\JoinColumn(nullable=false)
     */
    private $ficheFrais;

    /**
     * @var FraisForfait
     *
     * @ORM\OneToMany(
     *      targetEntity="WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FraisForfait",
     *      mappedBy="lignesFraisForfait",
     *      cascade={"persist"}
     * )
     */
    private $fraisForfait;

    /**
     * @var Visiteur
     *
     * @ORM\ManyToOne(
     *      targetEntity="WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\Visiteur",
     *      inversedBy="lignesFraisForfait"
     * )
     * @ORM\JoinColumn(nullable=false)
     */
    private $visiteur;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $idVisiteur;

    /**
     * @var string
     *
     * @ORM\Column(name="mois", type="string", length=6)
     */
    private $mois;

    /**
     * @var string
     *
     * @ORM\Column(name="idFraisForfait", type="string", length=3)
     */
    private $idFraisForfait;

    /**
     * @var integer
     *
     * @ORM\Column(name="quantite", type="integer")
     */
    private $quantite;

    /**
     * Get id
     *
     * @return integer
     */
    public function getIdVisiteur()
    {
        return $this->idVisiteur;
    }

    /**
     * Get mois
     *
     * @return string
     */
    public function getMois()
    {
        return $this->mois;
    }

    /**
     * Get idFraisForfait
     *
     * @return string
     */
    public function getIdFraisForfait()
    {
        return $this->idFraisForfait;
    }

    /**
     * Set quantite
     *
     * @param integer $quantite
     * @return LigneFraisForfait
     */
    public function setQuantite($quantite)
    {
        $this->quantite = $quantite;

        return $this;
    }

    /**
     * Get quantite
     *
     * @return integer
     */
    public function getQuantite()
    {
        return $this->quantite;
    }

    /**
     * Set mois
     *
     * @param string $mois
     * @return LigneFraisForfait
     */
    public function setMois($mois)
    {
        $this->mois = $mois;

        return $this;
    }

    /**
     * Set idFraisForfait
     *
     * @param string $idFraisForfait
     * @return LigneFraisForfait
     */
    public function setIdFraisForfait($idFraisForfait)
    {
        $this->idFraisForfait = $idFraisForfait;

        return $this;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->fraisForfait = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set ficheFrais
     *
     * @param \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FicheFrais $ficheFrais
     * @return LigneFraisForfait
     */
    public function setFicheFrais(\WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FicheFrais $ficheFrais)
    {
        $this->ficheFrais = $ficheFrais;

        return $this;
    }

    /**
     * Get ficheFrais
     *
     * @return \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FicheFrais
     */
    public function getFicheFrais()
    {
        return $this->ficheFrais;
    }

    /**
     * Add fraisForfait
     *
     * @param \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FraisForfait $fraisForfait
     * @return LigneFraisForfait
     */
    public function addFraisForfait(\WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FraisForfait $fraisForfait)
    {
        $this->fraisForfait[] = $fraisForfait;

        return $this;
    }

    /**
     * Remove fraisForfait
     *
     * @param \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FraisForfait $fraisForfait
     */
    public function removeFraisForfait(\WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\FraisForfait $fraisForfait)
    {
        $this->fraisForfait->removeElement($fraisForfait);
    }

    /**
     * Get fraisForfait
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getFraisForfait()
    {
        return $this->fraisForfait;
    }

    /**
     * Set visiteur
     *
     * @param \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\Visiteur $visiteur
     * @return LigneFraisForfait
     */
    public function setVisiteur(\WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\Visiteur $visiteur)
    {
        $this->visiteur = $visiteur;

        return $this;
    }

    /**
     * Get visiteur
     *
     * @return \WilsonCorp\Bundle\Comptabilite\FraisBundle\Entity\Visiteur
     */
    public function getVisiteur()
    {
        return $this->visiteur;
    }
}


text:
/*
    *
    * 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.
*/
package org.freeeed.search.web.controller;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.freeeed.search.web.WebConstants;
import org.freeeed.search.web.session.SolrSessionObject;
import org.freeeed.search.web.solr.SolrTagService;
import org.freeeed.search.web.solr.SolrTagService.Result;
import org.springframework.web.servlet.ModelAndView;

/**
 * Class TagController.
 *
 * Tag specific documents with a given tag.
 *
 * @author ilazarov
 *
 */
public class TagController extends SecureController {
    private static final Logger log = Logger.getLogger(TagController.class);

    private SolrTagService solrTagService;

    @Override
    public ModelAndView execute() {
        String action = (String) valueStack.get("action");
        log.debug("Tag action received: " + action);

        HttpSession session = this.request.getSession(true);
        SolrSessionObject solrSession = (SolrSessionObject)
            session.getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);

        if (solrSession == null) {
            return new ModelAndView(WebConstants.TAG_PAGE);
        }

        if ("newtag".equals(action)) {
            String tag = (String) valueStack.get("tag");
            String documentId = (String) valueStack.get("docid");

            log.debug("Will do tagging for - documentId: " + documentId + ", tag: " + tag);

            if (documentId != null && tag != null && documentId.length() > 0 && tag.trim().length() > 0) {
                Result result = solrTagService.tagDocument(documentId, tag);

                valueStack.put("result", result);
            }
        } else if ("deletetag".equals(action)) {
            String tag = (String) valueStack.get("tag");
            String documentId = (String) valueStack.get("docid");

            log.debug("Will do delete tag for - documentId: " + documentId + ", tag: " + tag);

            if (documentId != null && tag != null && documentId.length() > 0 && tag.trim().length() > 0) {
                Result result = solrTagService.removeTag(documentId, tag);

                valueStack.put("result", result);
            }
        } else if ("tagall".equals(action)) {
            String tag = (String) valueStack.get("tag");

            log.debug("Will do tag all, tag: " + tag);

            if (tag != null && tag.trim().length() > 0) {
                Result result = solrTagService.tagAllDocuments(solrSession, tag);

                valueStack.put("result", result);
            }
        } else if ("tagpage".equals(action)) {
            String tag = (String) valueStack.get("tag");

            log.debug("Will do tag page, tag: " + tag);

            if (tag != null && tag.trim().length() > 0) {
                Result result = solrTagService.tagThisPageDocuments(solrSession, tag);

                valueStack.put("result", result);
            }
        }

        return new ModelAndView(WebConstants.TAG_PAGE);
    }

    public void setSolrTagService(SolrTagService solrTagService) {
        this.solrTagService = solrTagService;
    }
}


text:
require 'helper'
require 'write_xlsx'

class ForTest
  include Writexlsx::Utility
end

class TestOptionHashForWorkbook < Minitest::Test
  def setup
    @obj = ForTest.new
    @options = {
      :tempdir         => 'temp',
      :date_1904       => false,
      :optimization    => false,
      :excel2003_style => false
    }
    @default_format_properties = { :size => 12, :color => 'red' }
  end

  #
  # Workbook.new(file)
  #  => options = {}
  #  => default_format_properties = {}
  #
  def test_empty
    options, default_format_properties = @obj.process_workbook_options
    assert_empty(options)
    assert_empty(default_format_properties)
  end

  #
  # Workbook.new(file, date_1904: false, color: 'red', size: 12)
  #  => options = {date_1904: false}
  #  => default_formats = {color: 'red', size: 12}
  #
  def test_one_flat_hash
    params = @options.merge(@default_format_properties)
    options, default_format_properties = @obj.process_workbook_options(params)
    assert_equal(@options, options)
    assert_equal(@default_format_properties, default_format_properties)
  end

  #
  # Workbook.new(file, date_1904: false,
  #              default_format_properties: {color: 'red', size: 12} )
  #  => options = {date_1904: false}
  #  => default_formats = {color: 'red', size: 12}
  #
  def test_one_hash_includes_format_key
    params = @options.dup
    params[:default_format_properties] = @default_format_properties

    options, default_format_properties = @obj.process_workbook_options(params)
    assert_equal(@options, options)
    assert_equal(@default_format_properties, default_format_properties)
  end

  #
  # Workbook.new(file, {date_1904: false},
  #                    {color: 'red', size: 12} )
  #  => options = {date_1904: false}
  #  => default_formats = {color: 'red', size: 12}
  #
  def test_two_hash
    options, default_format_properties =
      @obj.process_workbook_options(@options, @default_format_properties)

    assert_equal(@options, options)
    assert_equal(@default_format_properties, default_format_properties)
  end
end


text:
from . import test_access_rights

checks = [
    test_access_rights,
]

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'

get '/' do
	erb "Hello World of Mine! Original pattern has been modified for Ruby School"
end

get '/about' do
  erb :about
end

get '/visit' do
  erb :visit
end

post '/visit' do
  user_name = params[:username];
  user_phone = params[:userphone];
  user_date = params[:userdate];
  barbername = params[:barbername]

  combined_data = "#{user_name} - #{user_phone} - #{user_date} - #{barbername}\n\n"

  users_file = File.open "public/visits.txt", "a" do |file|
  file.write(combined_data)
  file.write "\n"
  end
  @message = "Complete"
  erb :thankyou

end

get '/contacts' do
  erb :contacts
end

get '/thankyou' do
  erb :thankyou
end


text:
module SassListen
  class Listener
    class Config
      DEFAULTS = {
        # Listener options
        debug: false, # TODO: is this broken?
        wait_for_delay: nil, # NOTE: should be provided by adapter if possible
        relative: false,

        # Backend selecting options
        force_polling: false,
        polling_fallback_message: nil
      }

      def initialize(opts)
        @options = DEFAULTS.merge(opts)
        @relative = @options[:relative]
        @min_delay_between_events = @options[:wait_for_delay]
        @silencer_rules = @options # silencer will extract what it needs
      end

      def relative?
        @relative
      end

      def min_delay_between_events
        @min_delay_between_events
      end

      def silencer_rules
        @silencer_rules
      end

      def adapter_instance_options(klass)
        valid_keys = klass.const_get('DEFAULTS').keys
        Hash[@options.select { |key, _| valid_keys.include?(key) }]
      end

      def adapter_select_options
        valid_keys = %w(force_polling polling_fallback_message).map(&:to_sym)
        Hash[@options.select { |key, _| valid_keys.include?(key) }]
      end
    end
  end
end


text:
package alien4cloud.paas.wf.validation;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Some state steps are run in parallel and should not.
 *
 * TODO: which one ?
 */
@Getter
@Setter
@AllArgsConstructor(suppressConstructorProperties = true)
@NoArgsConstructor
public class ParallelSetStatesError extends AbstractWorkflowError {
    private String nodeId;
}


text:
redirect_to: https://anvio.org/help/7/artifacts/genbank-file
---


text:
Nearest Garage Sales

                        <div class="google-map"
                             center="position.coords"
                             zoom="zoomProperty"
                             markers="markersProperty"
                             latitude="clickedLatitudeProperty"
                             longitude="clickedLongitudeProperty"
                             mark-click="true"
                             draggable="true"
                             fit="false"
                             events="eventsProperty"
                             style="height: 1000px; width: 100%">


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;

namespace _06_CalculateAgain_
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger n = BigInteger.Parse(Console.ReadLine());
            BigInteger k = BigInteger.Parse(Console.ReadLine());
            BigInteger nFactorial = 1;
            BigInteger kFactorial = 1;
            BigInteger result = 1;
            for (BigInteger i = n; i > k; i--)
            {
                result = result * i;
            }
            Console.WriteLine(result);

        }
    }
}


text:
class Rdf::Builders::LangLiteralHandler < Rdf::Builders::BaseHandler
  def initialize(key, options = {})
    @key = key
    @options = options
  end

  def call(predicate, objects)
    objects.each do |object|
      if object.literal?
        lang = object.language
        lang ||= :invariant
        value = object.object
        @context.attributes[@key] = {} unless @context.attributes.key?(@key)
        if overwrite? || @context.attributes[@key][lang].blank?
          @context.attributes[@key][lang] = value
        end
      elsif object.uri?
        if overwrite? || @context.attributes[@key].blank?
          @context.attributes[@key] = object.to_s
        end
      end
    end
  end

  private

  def overwrite?
    return true if !@options.key?(:overwrites)
    @options[:overwrites]
  end
end


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

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password
    </uses-policies>
</device-admin>


text: from .test_plugin import Plugin


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Einstein
{
    public static class ObjectExtensions
    {
        public static TSource If<TSource>(this TSource instance, Func<TSource, bool> guard, Action<TSource> action)
        {
            if (guard(instance))
                action(instance);
            return instance;
        }

        public static TProperty If<TSource, TProperty>(this TSource instance, Func<TSource, bool> guard,
            Func<TSource, TProperty> action, TProperty fallback = default(TProperty))
        {
            return guard(instance) ? action(instance) : fallback;
        }

        public static TSource Perform<TSource>(this TSource instance, Action<TSource> action)
        {
            return instance.If(x => x != null, action);
        }

        public static PropertyInfo GetPropertyInfo<TSource, TProperty>(this TSource instance,
            Expression<Func<TSource, TProperty>> property)
        {
            if (instance == null)
                throw new NullReferenceException();

            var memberExpression = property.Body as MemberExpression;
            var propertyInfo = memberExpression != null ? memberExpression.Member as PropertyInfo : null;

            if (propertyInfo == null)
                throw new ArgumentException(string.Format("Invalid property for {0}", typeof(TSource).FullName));

            return propertyInfo;
        }

        public static TSource IfNullThen<TSource, TProperty, TValue>(this TSource instance,
            Expression<Func<TSource, TProperty>> property, TValue value)
        {
            instance.GetPropertyInfo(property).If(x => x.GetValue(instance) == null, x => x.SetValue(instance, value));
            return instance;
        }

        public static bool IsObjectOfType<T>(this object source, out T target) where T : class
        {
            target = source as T;
            return target != null;
        }
    }
}


text:
package com.compositesw.services.system.admin.resource;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for functionList complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="functionList">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="function" type="{http://www.compositesw.com/services/system/admin/resource}function" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "functionList", propOrder = {
    "function"
})
public class FunctionList {

    protected List<Function> function;

    /**
     * Gets the value of the function property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the function property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getFunction().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Function }
     *
     *
     */
    public List<Function> getFunction() {
        if (function == null) {
            function = new ArrayList<Function>();
        }
        return this.function;
    }

}


text:
package com.intellij.xml;

import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.PsiTreeChangeEventImpl;
import com.intellij.psi.impl.PsiTreeChangePreprocessorBase;
import com.intellij.psi.xml.XmlFile;
import org.jetbrains.annotations.NotNull;

public class XmlPsiTreeChangePreprocessor extends PsiTreeChangePreprocessorBase {
  public XmlPsiTreeChangePreprocessor(@NotNull Project project) {
    super(project);
  }

  @Override
  protected boolean acceptsEvent(@NotNull PsiTreeChangeEventImpl event) {
    return event.getFile() instanceof XmlFile;
  }

  @Override
  protected boolean isOutOfCodeBlock(@NotNull PsiElement element) {
    // any xml element isn't inside a "code block"
    // cause we display even attributes and tag values in structure view
    return element.getLanguage() instanceof XMLLanguage;
  }

}