text:
package com.google.common.truth;

import static com.google.common.base.Strings.lenientFormat;
import static com.google.common.truth.Platform.floatToString;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.NaN;
import static java.lang.Float.POSITIVE_INFINITY;
import static java.lang.Math.nextAfter;
import static org.junit.Assert.fail;

import com.google.common.annotations.GwtIncompatible;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link PrimitiveFloatArraySubject}.
 *
 * @author Christian Gruber (cgruber@israfil.net)
 */
@RunWith(JUnit4.class)
public class PrimitiveFloatArraySubjectTest extends BaseSubjectTestCase {
  private static final float DEFAULT_TOLERANCE = 0.000005f;

  private static final float JUST_OVER_2POINT2 = 2.2000003f;
  private static final float JUST_OVER_3POINT3 = 3.3000002f;
  private static final float TOLERABLE_3POINT3 = 3.3000047f;
  private static final float INTOLERABLE_3POINT3 = 3.3000052f;
  private static final float UNDER_LONG_MIN = -9.223373E18f;
  private static final float TOLERABLE_TWO = 2.0000048f;
  private static final float INTOLERABLE_TWO = 2.0000052f;

  @Test
  @GwtIncompatible("Math.nextAfter")
  public void testFloatConstants_matchNextAfter() {
    assertThat(nextAfter(2.2f, POSITIVE_INFINITY)).isEqualTo(JUST_OVER_2POINT2);
    assertThat(nextAfter(3.3f, POSITIVE_INFINITY)).isEqualTo(JUST_OVER_3POINT3);
    assertThat(nextAfter(3.3f + DEFAULT_TOLERANCE, NEGATIVE_INFINITY)).isEqualTo(TOLERABLE_3POINT3);
    assertThat(nextAfter(3.3f + DEFAULT_TOLERANCE, POSITIVE_INFINITY))
        .isEqualTo(INTOLERABLE_3POINT3);
    assertThat(nextAfter(Long.MIN_VALUE, NEGATIVE_INFINITY)).isEqualTo(UNDER_LONG_MIN);
    assertThat(nextAfter(2.0f + DEFAULT_TOLERANCE, NEGATIVE_INFINITY)).isEqualTo(TOLERABLE_TWO);
    assertThat(nextAfter(2.0f + DEFAULT_TOLERANCE, POSITIVE_INFINITY)).isEqualTo(INTOLERABLE_TWO);
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Success() {
    assertThat(array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f))
        .isEqualTo(array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f));
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_NotEqual() {
    expectFailureWhenTestingThat(array(2.2f)).isEqualTo(array(JUST_OVER_2POINT2));
    assertFailureKeys("expected", "but was", "differs at index");
    assertFailureValue("expected", "[" + floatToString(JUST_OVER_2POINT2) + "]");
    assertFailureValue("but was", "[" + floatToString(2.2f) + "]");
    assertFailureValue("differs at index", "[0]");
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_DifferentOrder() {
    expectFailureWhenTestingThat(array(2.2f, 3.3f)).isEqualTo(array(3.3f, 2.2f));
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_Longer() {
    expectFailureWhenTestingThat(array(2.2f, 3.3f)).isEqualTo(array(2.2f, 3.3f, 4.4f));
    assertFailureKeys("expected", "but was", "wrong length", "expected", "but was");
    assertFailureValueIndexed("expected", 1, "3");
    assertFailureValueIndexed("but was", 1, "2");
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_Shorter() {
    expectFailureWhenTestingThat(array(2.2f, 3.3f)).isEqualTo(array(2.2f));
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_PlusMinusZero() {
    expectFailureWhenTestingThat(array(0.0f)).isEqualTo(array(-0.0f));
    assertFailureValue("expected", "[-0.0]");
    assertFailureValue("but was", "[0.0]");
  }

  @Test
  public void isEqualTo_WithoutToleranceParameter_Fail_NotAnArray() {
    expectFailureWhenTestingThat(array(2.2f, 3.3f, 4.4f)).isEqualTo(new Object());
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_FailEquals() {
    expectFailureWhenTestingThat(
            array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f))
        .isNotEqualTo(array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_NotEqual() {
    assertThat(array(2.2f)).isNotEqualTo(array(JUST_OVER_2POINT2));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_DifferentOrder() {
    assertThat(array(2.2f, 3.3f)).isNotEqualTo(array(3.3f, 2.2f));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_Longer() {
    assertThat(array(2.2f, 3.3f)).isNotEqualTo(array(2.2f, 3.3f, 4.4f));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_Shorter() {
    assertThat(array(2.2f, 3.3f)).isNotEqualTo(array(2.2f));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_PlusMinusZero() {
    assertThat(array(0.0f)).isNotEqualTo(array(-0.0f));
  }

  @Test
  public void isNotEqualTo_WithoutToleranceParameter_Success_NotAnArray() {
    assertThat(array(2.2f, 3.3f, 4.4f)).isNotEqualTo(new Object());
  }

  @Test
  public void usingTolerance_contains_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f)).usingTolerance(DEFAULT_TOLERANCE).contains(2.0f);
  }

  @Test
  public void usingTolerance_contains_successWithExpectedLong() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f)).usingTolerance(DEFAULT_TOLERANCE).contains(2L);
  }

  @Test
  public void usingTolerance_contains_failure() {
    expectFailureWhenTestingThat(array(1.0f, INTOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(2.0f);
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element that is a finite "
                    + "number within %s of <%s>",
                1.0f, INTOLERABLE_TWO, 3.0f, (double) DEFAULT_TOLERANCE, 2.0f));
  }

  @Test
  public void usingTolerance_contains_failureWithInfinity() {
    expectFailureWhenTestingThat(array(1.0f, POSITIVE_INFINITY, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(POSITIVE_INFINITY);
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, Infinity, %s]> "
                    + "contains at least one element that is "
                    + "a finite number within %s of <Infinity>",
                1.0f, 3.0f, (double) DEFAULT_TOLERANCE));
  }

  @Test
  public void usingTolerance_contains_failureWithNaN() {
    expectFailureWhenTestingThat(array(1.0f, NaN, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(NaN);
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, NaN, %s]> "
                    + "contains at least one element that is "
                    + "a finite number within %s of <NaN>",
                1.0f, 3.0f, (double) DEFAULT_TOLERANCE));
  }

  @Test
  public void usingTolerance_contains_successWithNegativeZero() {
    assertThat(array(1.0f, -0.0f, 3.0f)).usingTolerance(0.0f).contains(0.0f);
  }

  @Test
  public void usingTolerance_contains_otherTypes() {
    // Expected value is Double
    assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(2.0);
    // Expected value is Integer
    assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(2);
    // Expected value is Integer.MIN_VALUE. This is -1*2^31, which has an exact float
    // representation. For the actual value we use the next value down, which is 2^8 smaller
    // (because the resolution of floats with absolute values between 2^31 and 2^32 is 2^8). So
    // we'll make the assertion with a tolerance of 2^9.
    assertThat(array(1.0f, Integer.MIN_VALUE + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(1 << 9)
        .contains(Integer.MIN_VALUE);
    // Expected value is Long
    assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(2L);
    // Expected value is Long.MIN_VALUE. This is -1*2^63, which has an exact float representation.
    // For the actual value we use the next value down, which is is 2^40 smaller (because the
    // resolution of floats with absolute values between 2^63 and 2^64 is 2^40). So we'll make the
    // assertion with a tolerance of 2^41.
    assertThat(array(1.0f, UNDER_LONG_MIN, 3.0f)).usingTolerance(1L << 41).contains(Long.MIN_VALUE);
    // Expected value is BigInteger
    assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(BigInteger.valueOf(2));
    // Expected value is BigDecimal
    assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .contains(BigDecimal.valueOf(2.0));
  }

  @Test
  public void usingTolerance_contains_nullExpected() {
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingTolerance(DEFAULT_TOLERANCE).contains(null);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is a finite number "
            + "within "
            + (double) DEFAULT_TOLERANCE
            + " of <null>",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith("compare(" + actual[0] + ", null) threw java.lang.NullPointerException");
  }

  @Test
  public void usingTolerance_contains_negativeTolerance() {
    try {
      assertThat(array(1.0f, 2.0f, 3.0f)).usingTolerance(-1.0f * DEFAULT_TOLERANCE).contains(2.0f);
      fail("Expected IllegalArgumentException to be thrown but wasn't");
    } catch (IllegalArgumentException expected) {
      assertThat(expected)
          .hasMessageThat()
          .isEqualTo("tolerance (" + -1.0 * DEFAULT_TOLERANCE + ") cannot be negative");
    }
  }

  @Test
  public void usingTolerance_containsAtLeast_primitiveFloatArray() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(2.0f, 1.0f));
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(2.0f, 99.99f));
  }

  @Test
  public void usingTolerance_containsAtLeast_primitiveFloatArray_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(2.0f, 1.0f));
  }

  @Test
  public void usingTolerance_containsAtLeast_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(2.0f, 99.99f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element that is a "
                    + "finite number within %s of each element of <[%s, %s]>. "
                    + "It is missing an element that is a finite number within %s of <%s>",
                1.0f,
                TOLERABLE_TWO,
                3.0f,
                (double) DEFAULT_TOLERANCE,
                2.0f,
                99.99f,
                (double) DEFAULT_TOLERANCE,
                99.99f));
  }

  @Test
  public void usingTolerance_containsAtLeast_primitiveFloatArray_inOrder_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(1.0f, 2.0f))
        .inOrder();
  }

  @Test
  public void usingTolerance_containsAtLeast_primitiveFloatArray_inOrder_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAtLeast(array(2.0f, 1.0f))
        .inOrder();
    assertFailureKeys(
        "value of",
        "required elements were all found, but order was wrong",
        "comparing contents by testing that each element is a finite number within "
            + (double) DEFAULT_TOLERANCE
            + " of an expected value",
        "expected order for required elements",
        "but was");
    assertFailureValue(
        "expected order for required elements", lenientFormat("[%s, %s]", 2.0f, 1.0f));
  }

  @Test
  public void usingTolerance_containsAnyOf_primitiveFloatArray_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAnyOf(array(99.99f, 2.0f));
  }

  @Test
  public void usingTolerance_containsAnyOf_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsAnyOf(array(99.99f, 999.999f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element that is "
                    + "a finite number within %s of any element in <[%s, %s]>",
                1.0f, TOLERABLE_TWO, 3.0f, (double) DEFAULT_TOLERANCE, 99.99f, 999.999f));
  }

  @Test
  public void usingTolerance_containsExactly_primitiveFloatArray_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsExactly(array(2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingTolerance_containsExactly_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsExactly(array(2.0f, 1.0f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains exactly one element that is a finite "
                    + "number within %s of each element of <[%s, %s]>. "
                    + "It has unexpected elements <[%s]>",
                1.0f, TOLERABLE_TWO, 3.0f, (double) DEFAULT_TOLERANCE, 2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingTolerance_containsExactly_primitiveFloatArray_inOrder_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsExactly(array(1.0f, 2.0f, 3.0f))
        .inOrder();
  }

  @Test
  public void usingTolerance_containsExactly_primitiveFloatArray_inOrder_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsExactly(array(2.0f, 1.0f, 3.0f))
        .inOrder();
    assertFailureKeys(
        "value of",
        "contents match, but order was wrong",
        "comparing contents by testing that each element is a finite number within "
            + (double) DEFAULT_TOLERANCE
            + " of an expected value",
        "expected",
        "but was");
    assertFailureValue("expected", lenientFormat("[%s, %s, %s]", 2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingTolerance_containsNoneOf_primitiveFloatArray_success() {
    assertThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsNoneOf(array(99.99f, 999.999f));
  }

  @Test
  public void usingTolerance_containsNoneOf_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, TOLERABLE_TWO, 3.0f))
        .usingTolerance(DEFAULT_TOLERANCE)
        .containsNoneOf(array(99.99f, 2.0f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains no element that is a finite number within %s"
                    + " of any element in <[%s, %s]>. It contains <[%s which corresponds to %s]>",
                1.0f,
                TOLERABLE_TWO,
                3.0f,
                (double) DEFAULT_TOLERANCE,
                99.99f,
                2.0f,
                TOLERABLE_TWO,
                2.0f));
  }

  @Test
  public void usingExactEquality_contains_success() {
    assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().contains(2.0f);
  }

  @Test
  public void usingExactEquality_contains_failure() {
    expectFailureWhenTestingThat(array(1.0f, JUST_OVER_2POINT2, 3.0f))
        .usingExactEquality()
        .contains(2.2f);
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element "
                    + "that is exactly equal to <%s>",
                1.0f, JUST_OVER_2POINT2, 3.0f, 2.2f));
  }

  @Test
  public void usingExactEquality_contains_otherTypes() {
    // Expected value is Integer - supported up to +/- 2^24
    assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().contains(2);
    assertThat(array(1.0f, 1 << 24, 3.0f)).usingExactEquality().contains(1 << 24);
    // Expected value is Long - supported up to +/- 2^24
    assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().contains(2L);
    assertThat(array(1.0f, 1 << 24, 3.0f)).usingExactEquality().contains(1L << 24);
  }

  @Test
  public void usingExactEquality_contains_otherTypes_intOutOfRange() {
    int expected = (1 << 24) + 1;
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to <"
            + expected
            + ">",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith(
            "compare("
                + actual[0]
                + ", "
                + expected
                + ") threw java.lang.IllegalArgumentException");
    assertThatFailure()
        .factValue("first exception")
        .contains(
            "Expected value "
                + expected
                + " in assertion using exact float equality was an int with an absolute value "
                + "greater than 2^24 which has no exact float representation");
  }

  @Test
  public void usingExactEquality_contains_otherTypes_longOutOfRange() {
    long expected = (1L << 24) + 1L;
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to <"
            + expected
            + ">",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith(
            "compare("
                + actual[0]
                + ", "
                + expected
                + ") threw java.lang.IllegalArgumentException");
    assertThatFailure()
        .factValue("first exception")
        .contains(
            "Expected value "
                + expected
                + " in assertion using exact float equality was a long with an absolute value "
                + "greater than 2^24 which has no exact float representation");
  }

  @Test
  public void usingExactEquality_contains_otherTypes_doubleNotSupported() {
    double expected = 2.0;
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to <"
            + expected
            + ">",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith(
            "compare("
                + actual[0]
                + ", "
                + expected
                + ") threw java.lang.IllegalArgumentException");
    assertThatFailure()
        .factValue("first exception")
        .contains(
            "Expected value in assertion using exact float equality was a double, which is not "
                + "supported as a double may not have an exact float representation");
  }

  @Test
  public void usingExactEquality_contains_otherTypes_bigIntegerNotSupported() {
    BigInteger expected = BigInteger.valueOf(2);
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to <"
            + expected
            + ">",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith(
            "compare("
                + actual[0]
                + ", "
                + expected
                + ") threw java.lang.IllegalArgumentException");
    assertThatFailure()
        .factValue("first exception")
        .contains(
            "Expected value in assertion using exact float equality was of unsupported type "
                + BigInteger.class
                + " (it may not have an exact float representation)");
  }

  @Test
  public void usingExactEquality_contains_otherTypes_bigDecimalNotSupported() {
    BigDecimal expected = BigDecimal.valueOf(2.0);
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to <"
            + expected
            + ">",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith(
            "compare("
                + actual[0]
                + ", "
                + expected
                + ") threw java.lang.IllegalArgumentException");
    assertThatFailure()
        .factValue("first exception")
        .contains(
            "Expected value in assertion using exact float equality was of unsupported type "
                + BigDecimal.class
                + " (it may not have an exact float representation)");
  }

  @Test
  public void usingExactEquality_contains_successWithInfinity() {
    assertThat(array(1.0f, POSITIVE_INFINITY, 3.0f))
        .usingExactEquality()
        .contains(POSITIVE_INFINITY);
  }

  @Test
  public void usingExactEquality_contains_successWithNaN() {
    assertThat(array(1.0f, NaN, 3.0f)).usingExactEquality().contains(NaN);
  }

  @Test
  public void usingExactEquality_contains_failureWithNegativeZero() {
    expectFailureWhenTestingThat(array(1.0f, -0.0f, 3.0f)).usingExactEquality().contains(0.0f);
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, -0.0, %s]> "
                    + "contains at least one element that is "
                    + "exactly equal to <%s>",
                1.0f, 3.0f, 0.0f));
  }

  @Test
  public void usingExactEquality_contains_nullExpected() {
    float[] actual = array(1.0f, 2.0f, 3.0f);
    expectFailureWhenTestingThat(actual).usingExactEquality().contains(null);
    assertFailureKeys(
        "value of",
        "Not true that <"
            + Arrays.toString(actual)
            + "> contains at least one element that is exactly equal to "
            + "<null>",
        "additionally, one or more exceptions were thrown while comparing elements",
        "first exception");
    assertThatFailure()
        .factValue("first exception")
        .startsWith("compare(" + actual[0] + ", null) threw java.lang.NullPointerException");
  }

  @Test
  public void usingExactEquality_containsAtLeast_primitiveFloatArray_success() {
    assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().containsAtLeast(array(2.0f, 1.0f));
  }

  @Test
  public void usingExactEquality_containsAtLeast_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsAtLeast(array(2.0f, 99.99f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element that is exactly equal "
                    + "to each element of <[%s, %s]>. It is missing an element that is exactly "
                    + "equal to <%s>",
                1.0f, 2.0f, 3.0f, 2.0f, 99.99f, 99.99f));
  }

  @Test
  public void usingExactEquality_containsAtLeast_primitiveFloatArray_inOrder_success() {
    assertThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsAtLeast(array(1.0f, 2.0f))
        .inOrder();
  }

  @Test
  public void usingExactEquality_containsAtLeast_primitiveFloatArray_inOrder_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsAtLeast(array(2.0f, 1.0f))
        .inOrder();
    assertFailureKeys(
        "value of",
        "required elements were all found, but order was wrong",
        "comparing contents by testing that each element is exactly equal to an expected value",
        "expected order for required elements",
        "but was");
    assertFailureValue(
        "expected order for required elements", lenientFormat("[%s, %s]", 2.0f, 1.0f));
  }

  @Test
  public void usingExactEquality_containsAnyOf_primitiveFloatArray_success() {
    assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().containsAnyOf(array(99.99f, 2.0f));
  }

  @Test
  public void usingExactEquality_containsAnyOf_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsAnyOf(array(99.99f, 999.999f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains at least one element that is exactly equal "
                    + "to any element in <[%s, %s]>",
                1.0f, 2.0f, 3.0f, 99.99f, 999.999f));
  }

  @Test
  public void usingExactEquality_containsExactly_primitiveFloatArray_success() {
    assertThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsExactly(array(2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingExactEquality_containsExactly_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsExactly(array(2.0f, 1.0f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains exactly one element that is exactly equal "
                    + "to each element of <[%s, %s]>. It has unexpected elements <[%s]>",
                1.0f, 2.0f, 3.0f, 2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingExactEquality_containsExactly_primitiveFloatArray_inOrder_success() {
    assertThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsExactly(array(1.0f, 2.0f, 3.0f))
        .inOrder();
  }

  @Test
  public void usingExactEquality_containsExactly_primitiveFloatArray_inOrder_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsExactly(array(2.0f, 1.0f, 3.0f))
        .inOrder();
    assertFailureKeys(
        "value of",
        "contents match, but order was wrong",
        "comparing contents by testing that each element is exactly equal to an expected value",
        "expected",
        "but was");
    assertFailureValue("expected", lenientFormat("[%s, %s, %s]", 2.0f, 1.0f, 3.0f));
  }

  @Test
  public void usingExactEquality_containsNoneOf_primitiveFloatArray_success() {
    assertThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsNoneOf(array(99.99f, 999.999f));
  }

  @Test
  public void usingExactEquality_containsNoneOf_primitiveFloatArray_failure() {
    expectFailureWhenTestingThat(array(1.0f, 2.0f, 3.0f))
        .usingExactEquality()
        .containsNoneOf(array(99.99f, 2.0f));
    assertThat(expectFailure.getFailure())
        .hasMessageThat()
        .isEqualTo(
            lenientFormat(
                "value of: array.asList()\nNot true that <[%s, %s, %s]> "
                    + "contains no element that is exactly equal to any "
                    + "element in <[%s, %s]>. It contains <[%s which corresponds to %s]>",
                1.0f, 2.0f, 3.0f, 99.99f, 2.0f, 2.0f, 2.0f));
  }

  private static float[] array(float... primitives) {
    return primitives;
  }

  private PrimitiveFloatArraySubject expectFailureWhenTestingThat(float[] actual) {
    return expectFailure.whenTesting().that(actual);
  }
}


text:
set -e

grunt build
grunt test
grunt lint
./scripts/integration-tests.sh

redpajama_set_name: RedPajamaGithub


text:
/* global describe:true */
import { IFile } from "../file";
import { writeFile as write } from "../writeFiles";
import * as fs from "fs";
import * as path from "path";
import * as rimraf from "rimraf";

describe("writeFiles", () => {
  const dest = path.join(process.cwd(), "tmp");

  beforeEach(done => {
    rimraf(dest, done);
  });

  afterEach(done => {
    rimraf(dest, done);
  });

  it("should write IFile[] to disk", async () => {
    const file: IFile = {
      base: "",
      content: "Hello World!",
      location: "whatever/hello.txt",
      map: null,
    };

    const res = await write(dest, file);
    const out = dest + "/hello.txt";
    expect(res.location).toEqual(out);

    const content = fs.readFileSync(out, "utf-8");
    expect(content).toEqual("Hello World!");
  });

  it("should keep subfolder structure when writing files", async () => {
    const file: IFile = {
      base: "/root/whatever",
      content: "Hello World!",
      location: "/root/whatever/hello.scss",
      map: null,
    };

    const f = await write(dest, file);
    expect(f.location).toEqual(dest + "/root/whatever/hello.scss");
  });

  it.skip("should write files with sourcemaps to disk", () => {
    // TODO
  });
});


text:
package org.cicatiello.interview_exercise.cart.impl;

import java.util.Optional;
import java.util.Set;

import org.cicatiello.interview_exercise.cart.CalculationService;
import org.cicatiello.interview_exercise.cart.CartService;
import org.cicatiello.interview_exercise.model.CartEntry;
import org.cicatiello.interview_exercise.model.Product;
import org.cicatiello.interview_exercise.model.builder.CartEntryBuilder;
import org.cicatiello.interview_exercise.session.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DefaultCartService implements CartService {

	private SessionService sessionService;

	private CalculationService calculationService;

	@Override
	public void addProductToCart(Product product, int quantity) {
		CartEntry entry = findAndGetCartEntryByProduct(product);
		if (entry == null) {
			createAndAddEntryToCart(product, quantity);
		} else {
			adjustCartEntryQuantity(entry, quantity);
		}
		getCalculationService().recalculate();
	}

	private void adjustCartEntryQuantity(CartEntry entry, int quantity) {
		entry.setQuantity(entry.getQuantity() + quantity);
	}

	private CartEntry findAndGetCartEntryByProduct(Product product) {
		Set<CartEntry> entries = getSessionService().getSessionCart().getEntries();
		Optional<CartEntry> hasFoundEntry = entries.stream().filter(entry -> entry.getProduct() == product).findFirst();
		return hasFoundEntry.orElse(null);
	}

	private void createAndAddEntryToCart(Product product, int quantity) {
		CartEntry entry = CartEntryBuilder.create().product(product).quantity(quantity).build();
		addEntryToCart(entry);
	}

	private void addEntryToCart(CartEntry entry) {
		getSessionService().getSessionCart().getEntries().add(entry);
	}

	protected CalculationService getCalculationService() {
		return calculationService;
	}

	@Autowired
	public void setCalculationService(CalculationService calculationService) {
		this.calculationService = calculationService;
	}

	protected SessionService getSessionService() {
		return sessionService;
	}

	@Autowired
	public void setSessionService(SessionService sessionService) {
		this.sessionService = sessionService;
	}

}


text:
var defaults = {
    'squanchiness': 0.95,
    'activated': true
};

$(document).ready(function(){
    loadSquanchPrefs();

    $(".squanchy-button").on("click", function(){
        var activated = $.parseJSON($(this).attr('activated'));
        setSquanchButton(activated, true);
    });

    $(".squanchy-slider").on("change", function(){
        var sliderVal = this.value;
        updateSquanchiness(mapSliderToSquanchiness(sliderVal), true);
    });
});

loadSquanchPrefs = function() {
    tryGetStorageValue('squanchiness', setSquanchySlider, false);
    tryGetStorageValue('activated', setSquanchButton, false);
};

setSquanchySlider = function(squanchiness, reloadTabInd){
    $(".squanchy-slider").val(mapSquanchinessToSlider(squanchiness));

    if (reloadTabInd)
        updateSquanchiness(squanchiness, reloadTabInd);
};

setSquanchButton = function(currentlyActivated, reloadTabInd) {
    var setToActivated = ((currentlyActivated && !reloadTabInd) || (!currentlyActivated && reloadTabInd));

    var squanchButton = $(".squanchy-button");
    var squanchSlider = $(".slider-container");

    squanchButton.html(setToActivated ? "De-Squanch" : "Re-Squanch");
    squanchButton.css("background", (setToActivated ? "#e64343" : "#0ada8f"));
    squanchButton.attr("activated", (setToActivated ? true : false));

    if (setToActivated)
        squanchSlider.slideDown(500);
    else
        squanchSlider.slideUp(500);

    if (reloadCurrentTab)
        updateActivated(setToActivated, reloadTabInd);
};

reloadCurrentTab = function() {
    chrome.tabs.query({active: true}, function(tabs){
        chrome.tabs.reload(tabs[0].id);
    });
};

tryGetStorageValue = function(inputVal, setFunction, reloadTabInd) {
    return chrome.storage.local.get(inputVal, function(data) {
        if (data[inputVal] === undefined) {
            data[inputVal] = defaults[inputVal];
        }

        setFunction(data[inputVal], reloadTabInd);
    });
};

updateSquanchiness = function(squanchiness, reloadTabInd) {
    if (reloadTabInd)
        chrome.storage.local.set({'squanchiness': squanchiness}, reloadCurrentTab);
    else {
        chrome.storage.local.set({'squanchiness': squanchiness});
    }
};

updateActivated = function(activated, reloadTabInd) {
    if (reloadTabInd)
        chrome.storage.local.set({'activated': activated}, reloadCurrentTab);
    else
        chrome.storage.local.set({'activated': activated});
};

mapSliderToSquanchiness = function(sliderVal) {
    // The lower ten slider values produce very subtle squanchiness (<1%)
    if (sliderVal <= 10)
        return 1 - (sliderVal/1000);
    else
        return (1110 - 11*sliderVal)/1000;
};

mapSquanchinessToSlider = function(squanchiness) {
    if (squanchiness >= 0.99)
        return (1000*(1 - squanchiness));
    else
        return -(10/11)*(100*squanchiness - 111);
};


text:
'use strict';

/**@ngInject*/
function ProjectsAdminController() {
}

module.exports = ProjectsAdminController;


text:
#include "third_party/blink/renderer/core/svg/svg_defs_element.h"

#include "third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h"
#include "third_party/blink/renderer/core/svg_names.h"

namespace blink {

SVGDefsElement::SVGDefsElement(Document& document)
    : SVGGraphicsElement(svg_names::kDefsTag, document) {}

LayoutObject* SVGDefsElement::CreateLayoutObject(const ComputedStyle&,
                                                 LegacyLayout) {
  return MakeGarbageCollected<LayoutSVGHiddenContainer>(this);
}

}  // namespace blink


text:
namespace lldb_private {

/// CompilerContext allows an array of these items to be passed to perform
/// detailed lookups in SymbolVendor and SymbolFile functions.
struct CompilerContext {
  CompilerContext(CompilerContextKind t, ConstString n) : kind(t), name(n) {}

  bool operator==(const CompilerContext &rhs) const {
    return kind == rhs.kind && name == rhs.name;
  }
  bool operator!=(const CompilerContext &rhs) const { return !(*this == rhs); }

  void Dump() const;

  CompilerContextKind kind;
  ConstString name;
};

/// Match \p context_chain against \p pattern, which may contain "Any"
/// kinds. The \p context_chain should *not* contain any "Any" kinds.
bool contextMatches(llvm::ArrayRef<CompilerContext> context_chain,
                    llvm::ArrayRef<CompilerContext> pattern);

class SymbolFileType : public std::enable_shared_from_this<SymbolFileType>,
                       public UserID {
public:
  SymbolFileType(SymbolFile &symbol_file, lldb::user_id_t uid)
      : UserID(uid), m_symbol_file(symbol_file) {}

  SymbolFileType(SymbolFile &symbol_file, const lldb::TypeSP &type_sp);

  ~SymbolFileType() {}

  Type *operator->() { return GetType(); }

  Type *GetType();

protected:
  SymbolFile &m_symbol_file;
  lldb::TypeSP m_type_sp;
};

class Type : public std::enable_shared_from_this<Type>, public UserID {
public:
  enum EncodingDataType {
    eEncodingInvalid,
    eEncodingIsUID,      ///< This type is the type whose UID is m_encoding_uid
    eEncodingIsConstUID, ///< This type is the type whose UID is m_encoding_uid
                         /// with the const qualifier added
    eEncodingIsRestrictUID, ///< This type is the type whose UID is
                            /// m_encoding_uid with the restrict qualifier added
    eEncodingIsVolatileUID, ///< This type is the type whose UID is
                            /// m_encoding_uid with the volatile qualifier added
    eEncodingIsTypedefUID,  ///< This type is pointer to a type whose UID is
                            /// m_encoding_uid
    eEncodingIsPointerUID,  ///< This type is pointer to a type whose UID is
                            /// m_encoding_uid
    eEncodingIsLValueReferenceUID, ///< This type is L value reference to a type
                                   /// whose UID is m_encoding_uid
    eEncodingIsRValueReferenceUID, ///< This type is R value reference to a type
                                   /// whose UID is m_encoding_uid
    eEncodingIsSyntheticUID
  };

  // We must force the underlying type of the enum to be unsigned here.  Not
  // all compilers behave the same with regards to the default underlying type
  // of an enum, but because this enum is used in an enum bitfield and integer
  // comparisons are done with the value we need to guarantee that it's always
  // unsigned so that, for example, eResolveStateFull doesn't compare less than
  // eResolveStateUnresolved when used in a 2-bit bitfield.
  typedef enum ResolveStateTag : unsigned {
    eResolveStateUnresolved = 0,
    eResolveStateForward = 1,
    eResolveStateLayout = 2,
    eResolveStateFull = 3
  } ResolveState;

  Type(lldb::user_id_t uid, SymbolFile *symbol_file, ConstString name,
       llvm::Optional<uint64_t> byte_size, SymbolContextScope *context,
       lldb::user_id_t encoding_uid, EncodingDataType encoding_uid_type,
       const Declaration &decl, const CompilerType &compiler_qual_type,
       ResolveState compiler_type_resolve_state);

  // This makes an invalid type.  Used for functions that return a Type when
  // they get an error.
  Type();

  void Dump(Stream *s, bool show_context);

  void DumpTypeName(Stream *s);

  // Since Type instances only keep a "SymbolFile *" internally, other classes
  // like TypeImpl need make sure the module is still around before playing
  // with
  // Type instances. They can store a weak pointer to the Module;
  lldb::ModuleSP GetModule();

  void GetDescription(Stream *s, lldb::DescriptionLevel level, bool show_name);

  SymbolFile *GetSymbolFile() { return m_symbol_file; }
  const SymbolFile *GetSymbolFile() const { return m_symbol_file; }

  ConstString GetName();

  llvm::Optional<uint64_t>
  GetByteSize(ExecutionContextScope *exe_scope = nullptr);

  uint32_t GetNumChildren(bool omit_empty_base_classes);

  bool IsAggregateType();

  bool IsValidType() { return m_encoding_uid_type != eEncodingInvalid; }

  bool IsTypedef() { return m_encoding_uid_type == eEncodingIsTypedefUID; }

  lldb::TypeSP GetTypedefType();

  ConstString GetName() const { return m_name; }

  ConstString GetQualifiedName();

  void DumpValue(ExecutionContext *exe_ctx, Stream *s,
                 const DataExtractor &data, uint32_t data_offset,
                 bool show_type, bool show_summary, bool verbose,
                 lldb::Format format = lldb::eFormatDefault);

  bool DumpValueInMemory(ExecutionContext *exe_ctx, Stream *s,
                         lldb::addr_t address, AddressType address_type,
                         bool show_types, bool show_summary, bool verbose);

  bool ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t address,
                      AddressType address_type, DataExtractor &data);

  bool WriteToMemory(ExecutionContext *exe_ctx, lldb::addr_t address,
                     AddressType address_type, DataExtractor &data);

  bool GetIsDeclaration() const;

  void SetIsDeclaration(bool b);

  bool GetIsExternal() const;

  void SetIsExternal(bool b);

  lldb::Format GetFormat();

  lldb::Encoding GetEncoding(uint64_t &count);

  SymbolContextScope *GetSymbolContextScope() { return m_context; }
  const SymbolContextScope *GetSymbolContextScope() const { return m_context; }
  void SetSymbolContextScope(SymbolContextScope *context) {
    m_context = context;
  }

  const lldb_private::Declaration &GetDeclaration() const;

  // Get the clang type, and resolve definitions for any
  // class/struct/union/enum types completely.
  CompilerType GetFullCompilerType();

  // Get the clang type, and resolve definitions enough so that the type could
  // have layout performed. This allows ptrs and refs to
  // class/struct/union/enum types remain forward declarations.
  CompilerType GetLayoutCompilerType();

  // Get the clang type and leave class/struct/union/enum types as forward
  // declarations if they haven't already been fully defined.
  CompilerType GetForwardCompilerType();

  static int Compare(const Type &a, const Type &b);

  // From a fully qualified typename, split the type into the type basename and
  // the remaining type scope (namespaces/classes).
  static bool GetTypeScopeAndBasename(const llvm::StringRef& name,
                                      llvm::StringRef &scope,
                                      llvm::StringRef &basename,
                                      lldb::TypeClass &type_class);
  void SetEncodingType(Type *encoding_type) { m_encoding_type = encoding_type; }

  uint32_t GetEncodingMask();

  bool IsCompleteObjCClass() { return m_flags.is_complete_objc_class; }

  void SetIsCompleteObjCClass(bool is_complete_objc_class) {
    m_flags.is_complete_objc_class = is_complete_objc_class;
  }

  /// \return whether this is a Swift fixed-size buffer. Resilient variables in
  /// fixed-size buffers may be indirect depending on the runtime size of the
  /// type. This is more a property of the value than of its type.
  bool IsSwiftFixedValueBuffer() const {
    return m_flags.is_swift_fixed_value_buffer;
  }

  void SetSwiftFixedValueBuffer(bool is_swift_fixed_value_buffer) {
    m_flags.is_swift_fixed_value_buffer = is_swift_fixed_value_buffer;
  }

protected:
  ConstString m_name;
  SymbolFile *m_symbol_file;
  SymbolContextScope
      *m_context; // The symbol context in which this type is defined
  Type *m_encoding_type;
  lldb::user_id_t m_encoding_uid;
  EncodingDataType m_encoding_uid_type;
  uint64_t m_byte_size : 63;
  uint64_t m_byte_size_has_value : 1;
  Declaration m_decl;
  CompilerType m_compiler_type;

  struct Flags {
#ifdef __GNUC__
    // using unsigned type here to work around a very noisy gcc warning
    unsigned compiler_type_resolve_state : 2;
#else
    ResolveState compiler_type_resolve_state : 2;
#endif
    bool is_complete_objc_class : 1;
    bool is_swift_fixed_value_buffer : 1;
  } m_flags;

  Type *GetEncodingType();

  bool ResolveClangType(ResolveState compiler_type_resolve_state);
};

// the two classes here are used by the public API as a backend to the SBType
// and SBTypeList classes

// the two classes here are used by the public API as a backend to
// the SBType and SBTypeList classes

class TypeImpl {
public:
  TypeImpl() = default;

  ~TypeImpl() {}

  TypeImpl(const lldb::TypeSP &type_sp);

  TypeImpl(const CompilerType &compiler_type);

  TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic);

  TypeImpl(const CompilerType &compiler_type, const CompilerType &dynamic);

  void SetType(const lldb::TypeSP &type_sp);

  void SetType(const CompilerType &compiler_type);

  void SetType(const lldb::TypeSP &type_sp, const CompilerType &dynamic);

  void SetType(const CompilerType &compiler_type, const CompilerType &dynamic);

  bool operator==(const TypeImpl &rhs) const;

  bool operator!=(const TypeImpl &rhs) const;

  bool IsValid() const;

  explicit operator bool() const;

  void Clear();

  ConstString GetName() const;

  ConstString GetDisplayTypeName() const;

  TypeImpl GetPointerType() const;

  TypeImpl GetPointeeType() const;

  TypeImpl GetReferenceType() const;

  TypeImpl GetTypedefedType() const;

  TypeImpl GetDereferencedType() const;

  TypeImpl GetUnqualifiedType() const;

  TypeImpl GetCanonicalType() const;

  CompilerType GetCompilerType(bool prefer_dynamic);

  TypeSystem *GetTypeSystem(bool prefer_dynamic);

  bool GetDescription(lldb_private::Stream &strm,
                      lldb::DescriptionLevel description_level);

private:
  bool CheckModule(lldb::ModuleSP &module_sp) const;

  lldb::ModuleWP m_module_wp;
  CompilerType m_static_type;
  CompilerType m_dynamic_type;
};

class TypeListImpl {
public:
  TypeListImpl() : m_content() {}

  void Append(const lldb::TypeImplSP &type) { m_content.push_back(type); }

  class AppendVisitor {
  public:
    AppendVisitor(TypeListImpl &type_list) : m_type_list(type_list) {}

    void operator()(const lldb::TypeImplSP &type) { m_type_list.Append(type); }

  private:
    TypeListImpl &m_type_list;
  };

  void Append(const lldb_private::TypeList &type_list);

  lldb::TypeImplSP GetTypeAtIndex(size_t idx) {
    lldb::TypeImplSP type_sp;
    if (idx < GetSize())
      type_sp = m_content[idx];
    return type_sp;
  }

  size_t GetSize() { return m_content.size(); }

private:
  std::vector<lldb::TypeImplSP> m_content;
};

class TypeMemberImpl {
public:
  TypeMemberImpl()
      : m_type_impl_sp(), m_bit_offset(0), m_name(), m_bitfield_bit_size(0),
        m_is_bitfield(false)

  {}

  TypeMemberImpl(const lldb::TypeImplSP &type_impl_sp, uint64_t bit_offset,
                 ConstString name, uint32_t bitfield_bit_size = 0,
                 bool is_bitfield = false)
      : m_type_impl_sp(type_impl_sp), m_bit_offset(bit_offset), m_name(name),
        m_bitfield_bit_size(bitfield_bit_size), m_is_bitfield(is_bitfield) {}

  TypeMemberImpl(const lldb::TypeImplSP &type_impl_sp, uint64_t bit_offset)
      : m_type_impl_sp(type_impl_sp), m_bit_offset(bit_offset), m_name(),
        m_bitfield_bit_size(0), m_is_bitfield(false) {
    if (m_type_impl_sp)
      m_name = m_type_impl_sp->GetName();
  }

  const lldb::TypeImplSP &GetTypeImpl() { return m_type_impl_sp; }

  ConstString GetName() const { return m_name; }

  uint64_t GetBitOffset() const { return m_bit_offset; }

  uint32_t GetBitfieldBitSize() const { return m_bitfield_bit_size; }

  void SetBitfieldBitSize(uint32_t bitfield_bit_size) {
    m_bitfield_bit_size = bitfield_bit_size;
  }

  bool GetIsBitfield() const { return m_is_bitfield; }

  void SetIsBitfield(bool is_bitfield) { m_is_bitfield = is_bitfield; }

protected:
  lldb::TypeImplSP m_type_impl_sp;
  uint64_t m_bit_offset;
  ConstString m_name;
  uint32_t m_bitfield_bit_size; // Bit size for bitfield members only
  bool m_is_bitfield;
};

///
/// Sometimes you can find the name of the type corresponding to an object, but
/// we don't have debug
/// information for it.  If that is the case, you can return one of these
/// objects, and then if it
/// has a full type, you can use that, but if not at least you can print the
/// name for informational
/// purposes.
///

class TypeAndOrName {
public:
  TypeAndOrName() = default;
  TypeAndOrName(lldb::TypeSP &type_sp);
  TypeAndOrName(const CompilerType &compiler_type);
  TypeAndOrName(const char *type_str);
  TypeAndOrName(ConstString &type_const_string);

  bool operator==(const TypeAndOrName &other) const;

  bool operator!=(const TypeAndOrName &other) const;

  ConstString GetName() const;

  CompilerType GetCompilerType() const { return m_compiler_type; }

  void SetName(ConstString type_name);

  void SetName(const char *type_name_cstr);

  void SetTypeSP(lldb::TypeSP type_sp);

  void SetCompilerType(CompilerType compiler_type);

  bool IsEmpty() const;

  bool HasName() const;

  bool HasCompilerType() const;

  bool HasType() const { return HasCompilerType(); }

  void Clear();

  explicit operator bool() { return !IsEmpty(); }

private:
  CompilerType m_compiler_type;
  ConstString m_type_name;
};

class TypeMemberFunctionImpl {
public:
  TypeMemberFunctionImpl()
      : m_type(), m_decl(), m_name(), m_kind(lldb::eMemberFunctionKindUnknown) {
  }

  TypeMemberFunctionImpl(const CompilerType &type, const CompilerDecl &decl,
                         const std::string &name,
                         const lldb::MemberFunctionKind &kind)
      : m_type(type), m_decl(decl), m_name(name), m_kind(kind) {}

  bool IsValid();

  ConstString GetName() const;

  ConstString GetMangledName() const;

  CompilerType GetType() const;

  CompilerType GetReturnType() const;

  size_t GetNumArguments() const;

  CompilerType GetArgumentAtIndex(size_t idx) const;

  lldb::MemberFunctionKind GetKind() const;

  bool GetDescription(Stream &stream);

protected:
  std::string GetPrintableTypeName();

private:
  CompilerType m_type;
  CompilerDecl m_decl;
  ConstString m_name;
  lldb::MemberFunctionKind m_kind;
};

class TypeEnumMemberImpl {
public:
  TypeEnumMemberImpl()
      : m_integer_type_sp(), m_name("<invalid>"), m_value(), m_valid(false) {}

  TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp,
                     ConstString name, const llvm::APSInt &value);

  TypeEnumMemberImpl(const TypeEnumMemberImpl &rhs) = default;

  TypeEnumMemberImpl &operator=(const TypeEnumMemberImpl &rhs);

  bool IsValid() { return m_valid; }

  ConstString GetName() const { return m_name; }

  const lldb::TypeImplSP &GetIntegerType() const { return m_integer_type_sp; }

  uint64_t GetValueAsUnsigned() const { return m_value.getZExtValue(); }

  int64_t GetValueAsSigned() const { return m_value.getSExtValue(); }

protected:
  lldb::TypeImplSP m_integer_type_sp;
  ConstString m_name;
  llvm::APSInt m_value;
  bool m_valid;
};

class TypeEnumMemberListImpl {
public:
  TypeEnumMemberListImpl() : m_content() {}

  void Append(const lldb::TypeEnumMemberImplSP &type) {
    m_content.push_back(type);
  }

  void Append(const lldb_private::TypeEnumMemberListImpl &type_list);

  lldb::TypeEnumMemberImplSP GetTypeEnumMemberAtIndex(size_t idx) {
    lldb::TypeEnumMemberImplSP enum_member;
    if (idx < GetSize())
      enum_member = m_content[idx];
    return enum_member;
  }

  size_t GetSize() { return m_content.size(); }

private:
  std::vector<lldb::TypeEnumMemberImplSP> m_content;
};

} // namespace lldb_private

#endif // liblldb_Type_h_


text:
from __future__ import print_function

__author__ = 'satish'

# Adopted From: Peter Prettenhofer <peter.prettenhofer@gmail.com>
#               Olivier Grisel <olivier.grisel@ensta.org>
#               Mathieu Blondel <mathieu@mblondel.org>
#               Lars Buitinck <L.J.Buitinck@uva.nl>
# License: BSD 3 clause

import logging
import numpy as np
from optparse import OptionParser
import sys
from time import time
import matplotlib.pyplot as plt

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.linear_model import RidgeClassifier
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import Perceptron
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.naive_bayes import BernoulliNB, MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import NearestCentroid
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils.extmath import density
from sklearn import metrics
from sklearn import cross_validation
import pickle
import chardet

def save_obj(obj, name ):
    with open( name + '.pkl', 'wb') as f:
        pickle.dump(obj, f,  protocol=2)

def load_obj(name ):
    with open( name + '.pkl', 'rb') as f:
        return pickle.load(f)

# read in 10 classes of [Most Funny,.... ,Least Funny]
Part10 = load_obj("Chunky10Rankedi")

map = dict()
i = 1
loop = 1
#concatenation factor of 10parts ;;; if concat=5 => 10/5= 2Parts
concat = 5

for part in Part10:
    for vid in part:
        map[vid.strip()] = i
    if loop%concat == 0:
        i+=1
    loop+=1

# map dict has all classes
DataDict = load_obj("ProcessedDesignMatrix")

# Naive and Stupid Approach
DesignMatrix = []
for k in DataDict.keys():
    TDC = DataDict[k]
    rank = map[k]
    data  = ""
    if TDC[0] != "none":
        data  = TDC[0]
        if TDC[1] != "none":
            data = data + " " + TDC[1]
    for com in TDC[2]:
        data = data + " " + com
    DesignMatrix.append([data.encode("UTF-8"),rank])

X=[]
y=[]
for i in DesignMatrix:
    X.append(i[0])
    y.append(i[1])

print(len(X))

X = np.array(X)
y = np.array(y)

skf = cross_validation.StratifiedKFold(y, n_folds=2,shuffle=True)
print(skf)

for train_index, test_index in skf:
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    print('data loaded')

    # categories = ["1","2","3","4","5","6","7","8","9","10"]
    # categories = ["1","2","3","4","5"]
    categories = ["1","2"]

    def size_mb(docs):
        return sum(len(s) for s in docs) / 1e6

    data_train_size_mb = size_mb(X_train)
    data_test_size_mb = size_mb(X_test)

    print("%d documents - %0.3fMB (training set)" % (
        len(X_train), data_train_size_mb))
    print("%d documents - %0.3fMB (test set)" % (
        len(X_test), data_test_size_mb))
    print("%d categories" % len(categories))
    print()

    print("Extracting features from the training data using a sparse vectorizer")
    t0 = time()

    vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,stop_words=None)
    X_train = vectorizer.fit_transform(X_train)
    duration = time() - t0

    print("done in %fs at %0.3fMB/s" % (duration, data_train_size_mb / duration))
    print("n_samples: %d, n_features: %d" % X_train.shape)
    print()

    print("Extracting features from the test data using the same vectorizer")
    t0 = time()

    X_test = vectorizer.transform(X_test)
    duration = time() - t0
    print("done in %fs at %0.3fMB/s" % (duration, data_test_size_mb / duration))
    print("n_samples: %d, n_features: %d" % X_test.shape)
    print()

    # mapping from integer feature name to original token string
    feature_names = vectorizer.get_feature_names()

    ### Vary K Value
    kkk=5000
    print("Extracting "+str(kkk) +" best features by a chi-squared test")
    t0 = time()
    ch2 = SelectKBest(chi2, k=kkk)
    X_train = ch2.fit_transform(X_train, y_train)
    X_test = ch2.transform(X_test)

    feature_names = [feature_names[i] for i in ch2.get_support(indices=True)]
    print("done in %fs" % (time() - t0))
    print()
    feature_names = np.asarray(feature_names)

    ###############################################################################
    # Benchmark classifiers
    # Bench Mark Result Print Function
    def benchmark(clf):
        print('_' * 80)
        print("Training: ")
        print(clf)
        t0 = time()
        # print(clf.__name__)

        clf.fit(X_train, y_train)
        train_time = time() - t0
        print("train time: %0.3fs" % train_time)

        t0 = time()
        pred = clf.predict(X_test)
        test_time = time() - t0
        print("test time:  %0.3fs" % test_time)

        score = metrics.accuracy_score(y_test, pred)
        print("accuracy:   %0.3f" % score)

        if hasattr(clf, 'coef_'):
            print("dimensionality: %d" % clf.coef_.shape[1])
            print("density: %f" % density(clf.coef_))
            print("top 10 keywords per class:")

            rank = np.argsort(clf.coef_[0])
            top10 = rank[-10:]
            bottom10 = rank[:10]
            print("%s: %s" % ("Funny: ", " ".join(feature_names[top10]).encode("utf-8")))
            print("%s: %s" % ("Not Funny: ", " ".join(feature_names[bottom10]).encode("utf-8")))

            print()

        print("classification report:")
        print(metrics.classification_report(y_test, pred,target_names=categories))

        print("confusion matrix:")
        print(metrics.confusion_matrix(y_test, pred))

        print()
        clf_descr = str(clf).split('(')[0]
        return clf_descr, score, train_time, test_time

    results = []

    for penalty in ["l2", "l1"]:
        print('=' * 80)
        print("%s penalty" % penalty.upper())
        # Train Liblinear model
        results.append(benchmark(LinearSVC(loss='l2', penalty=penalty,dual=False, tol=1e-3)))

    # Train sparse Naive Bayes classifiers
    print('=' * 80)
    print("Naive Bayes")
    results.append(benchmark(MultinomialNB(alpha=.01)))
    results.append(benchmark(BernoulliNB(alpha=.01)))

    print('=' * 80)
    print("LinearSVC with L1-based feature selection")
    # The smaller C, the stronger the regularization.
    # The more regularization, the more sparsity.
    results.append(benchmark(Pipeline([
      ('feature_selection', LinearSVC(penalty="l1", dual=False, tol=1e-3)),
      ('classification', LinearSVC())
    ])))


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * xFrameworkPX_Validation_Zenkaku Class File
 *
 * PHP versions 5
 *
 * @category   xFrameworkPX
 * @package    xFrameworkPX_Validation
 * @author     Kazuhiro Kotsutsumi <kotsutsumi@xenophy.com>
 * @copyright  Copyright (c) 2006-2010 Xenophy.CO.,LTD All rights Reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    SVN $Id: Zenkaku.php 1178 2010-01-05 15:13:08Z tamari $
 */

// {{{ xFrameworkPX_Validation_Zenkaku

/**
 * xFrameworkPX_Validation_Zenkaku Class
 *
 * @category   xFrameworkPX
 * @package    xFrameworkPX_Validation
 * @author     Kazuhiro Kotsutsumi <kotsutsumi@xenophy.com>
 * @copyright  Copyright (c) 2006-2010 Xenophy.CO.,LTD All rights Reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    Release: 3.5.0
 * @link       http://www.xframeworkpx.com/api/?class=xFrameworkPX_Validation_Zenkaku
 */
class xFrameworkPX_Validation_Zenkaku
{

    // {{{ validate

    /**
     * validate
     *
     * 全角チェック
     *
     * @param mixed 検査データ
     * @return bool true:OK, false:NG
     * @access public
     */
    public function validate($target)
    {

        // 空はチェックしない
        if (empty($target)) {
            return true;
        }

        // チェック、正しければtrueを返却
        if (preg_match("/[\x{FF61}-\x{FF9F}]/u", $target)) {
            return false; // 半角カナが存在する場合
        }

        return ($target == mb_convert_kana($target, 'RNASKHV'));
    }

    // }}}

}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */


text:
Testimonials

There's nothing better that your feedback. We love it!

Release Management and Code Quality Management

"Our organization has now better stability, fiability, performance, but overall, credibility."

Service Manager

Continuous Code Quality Inspection

"We finally know how good or bad is our code, using standard metrics and measures. Now we can focus and put our efforts in continous code improvement and get instant feedback about it. Code Quality is now a must have and it is part of our development cycle."

Research and Development Manager

Quality Assurance Office

"This project gave us visibility, both internal and external, of all the things we do. Now we have a clear vision of the whole service, inputs, resources, checkpoints, outputs, and all the relationships between them. And then, continuous improvement..."

Healthcare Call Center Service Service Manager

Process Management Centralization and Support with Atlassian Suite

"The organization has improved the way we provide the service by including new process in an easy way. We can also get real-time analytics by business area and focus on continuous improvement."

Dirección General de Tecnologías de la Información y las Comunicaciones Service Manager


text:
package com.navercorp.pinpoint.profiler.monitor.collector;

import java.util.Objects;
import com.navercorp.pinpoint.profiler.context.monitor.metric.CustomMetricRegistryService;
import com.navercorp.pinpoint.profiler.context.monitor.metric.CustomMetricWrapper;
import com.navercorp.pinpoint.profiler.monitor.metric.AgentCustomMetricSnapshot;

import java.util.Map;

/**
 * @author Taejin Koo
 */
public class AgentCustomMetricCollector {

    private final CustomMetricRegistryService customMetricRegistryService;

    public AgentCustomMetricCollector(CustomMetricRegistryService customMetricRegistryService) {
        this.customMetricRegistryService = Objects.requireNonNull(customMetricRegistryService, "customMetricRegistryService");
    }

    public AgentCustomMetricSnapshot collect() {
        Map<String, CustomMetricWrapper> customMetricMap = customMetricRegistryService.getCustomMetricMap();

        int size = customMetricMap.size();

        AgentCustomMetricSnapshot agentCustomMetricSnapshot = new AgentCustomMetricSnapshot(size);
        for (CustomMetricWrapper metricWrapper : customMetricMap.values()) {
            agentCustomMetricSnapshot.add(metricWrapper.snapshot());
        }

        return agentCustomMetricSnapshot;
    }

}