text:
package org.apache.spark.sql.catalyst.util

import java.time.{Duration, Period}
import java.util.concurrent.TimeUnit

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.plans.SQLHelper
import org.apache.spark.sql.catalyst.util.DateTimeConstants._
import org.apache.spark.sql.catalyst.util.DateTimeUtils.millisToMicros
import org.apache.spark.sql.catalyst.util.IntervalStringStyles.{ANSI_STYLE, HIVE_STYLE}
import org.apache.spark.sql.catalyst.util.IntervalUtils._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.DayTimeIntervalType
import org.apache.spark.unsafe.types.{CalendarInterval, UTF8String}

class IntervalUtilsSuite extends SparkFunSuite with SQLHelper {

  private def checkFromString(input: String, expected: CalendarInterval): Unit = {
    assert(stringToInterval(UTF8String.fromString(input)) === expected)
    assert(safeStringToInterval(UTF8String.fromString(input)) === expected)
  }

  private def checkFromInvalidString(input: String, errorMsg: String): Unit = {
    failFuncWithInvalidInput(input, errorMsg, s => stringToInterval(UTF8String.fromString(s)))
    assert(safeStringToInterval(UTF8String.fromString(input)) === null)
  }

  private def failFuncWithInvalidInput(
      input: String, errorMsg: String, converter: String => CalendarInterval): Unit = {
    withClue("Expected to throw an exception for the invalid input") {
      val e = intercept[IllegalArgumentException](converter(input))
      assert(e.getMessage.contains(errorMsg))
    }
  }

  private def testSingleUnit(
    unit: String, number: Int, months: Int, days: Int, microseconds: Long): Unit = {
    for (prefix <- Seq("interval ", "")) {
      val input1 = prefix + number + " " + unit
      val input2 = prefix + number + " " + unit + "s"
      val result = new CalendarInterval(months, days, microseconds)
      checkFromString(input1, result)
      checkFromString(input2, result)
    }
  }

  test("string to interval: basic") {
    testSingleUnit("YEAR", 3, 36, 0, 0)
    testSingleUnit("Month", 3, 3, 0, 0)
    testSingleUnit("Week", 3, 0, 21, 0)
    testSingleUnit("DAY", 3, 0, 3, 0)
    testSingleUnit("HouR", 3, 0, 0, 3 * MICROS_PER_HOUR)
    testSingleUnit("MiNuTe", 3, 0, 0, 3 * MICROS_PER_MINUTE)
    testSingleUnit("Second", 3, 0, 0, 3 * MICROS_PER_SECOND)
    testSingleUnit("MilliSecond", 3, 0, 0, millisToMicros(3))
    testSingleUnit("MicroSecond", 3, 0, 0, 3)

    checkFromInvalidString(null, "cannot be null")

    for (input <- Seq("", "interval", "foo", "foo 1 day")) {
      checkFromInvalidString(input, "Error parsing")
    }
  }

  test("string to interval: interval with dangling parts should not results null") {
    checkFromInvalidString("+", "expect a number after '+' but hit EOL")
    checkFromInvalidString("-", "expect a number after '-' but hit EOL")
    checkFromInvalidString("+ 2", "expect a unit name after '2' but hit EOL")
    checkFromInvalidString("- 1", "expect a unit name after '1' but hit EOL")
    checkFromInvalidString("1", "expect a unit name after '1' but hit EOL")
    checkFromInvalidString("1.2", "expect a unit name after '1.2' but hit EOL")
    checkFromInvalidString("1 day 2", "expect a unit name after '2' but hit EOL")
    checkFromInvalidString("1 day 2.2", "expect a unit name after '2.2' but hit EOL")
    checkFromInvalidString("1 day -", "expect a number after '-' but hit EOL")
    checkFromInvalidString("-.", "expect a unit name after '-.' but hit EOL")
  }

  test("string to interval: multiple units") {
    Seq(
      "-1 MONTH 1 day -1 microseconds" -> new CalendarInterval(-1, 1, -1),
      " 123 MONTHS        123 DAYS  123 Microsecond    " -> new CalendarInterval(123, 123, 123),
      "interval -1 day +3 Microseconds" -> new CalendarInterval(0, -1, 3),
      "interval -   1 day +     3 Microseconds" -> new CalendarInterval(0, -1, 3),
      "  interval  8  years -11 months 123  weeks   -1 day " +
        "23 hours -22 minutes 1 second  -123  millisecond    567 microseconds " ->
        new CalendarInterval(85, 860, 81480877567L)).foreach { case (input, expected) =>
      checkFromString(input, expected)
    }
  }

  test("string to interval: special cases") {
    // Support any order of interval units
    checkFromString("1 day 1 year", new CalendarInterval(12, 1, 0))
    // Allow duplicated units and summarize their values
    checkFromString("1 day 10 day", new CalendarInterval(0, 11, 0))
    // Only the seconds units can have the fractional part
    checkFromInvalidString("1.5 days", "'days' cannot have fractional part")
    checkFromInvalidString("1. hour", "'hour' cannot have fractional part")
    checkFromInvalidString("1 hourX", "invalid unit 'hourx'")
    checkFromInvalidString("~1 hour", "unrecognized number '~1'")
    checkFromInvalidString("1 Mour", "invalid unit 'mour'")
    checkFromInvalidString("1 aour", "invalid unit 'aour'")
    checkFromInvalidString("1a1 hour", "invalid value '1a1'")
    checkFromInvalidString("1.1a1 seconds", "invalid value '1.1a1'")
    checkFromInvalidString("2234567890 days", "integer overflow")
    checkFromInvalidString(". seconds", "invalid value '.'")
  }

  test("string to interval: whitespaces") {
    checkFromInvalidString(" ", "Error parsing ' ' to interval")
    checkFromInvalidString("\n", "Error parsing '\n' to interval")
    checkFromInvalidString("\t", "Error parsing '\t' to interval")
    checkFromString("1 \t day \n 2 \r hour", new CalendarInterval(0, 1, 2 * MICROS_PER_HOUR))
    checkFromInvalidString("interval1 \t day \n 2 \r hour", "invalid interval prefix interval1")
    checkFromString("interval\r1\tday", new CalendarInterval(0, 1, 0))
    // scalastyle:off nonascii
    checkFromInvalidString("中国 interval 1 day", "unrecognized number '中国'")
    checkFromInvalidString("interval浙江 1 day", "invalid interval prefix interval浙江")
    checkFromInvalidString("interval 1杭州 day", "invalid value '1杭州'")
    checkFromInvalidString("interval 1 滨江day", "invalid unit '滨江day'")
    checkFromInvalidString("interval 1 day长河", "invalid unit 'day长河'")
    checkFromInvalidString("interval 1 day 网商路", "unrecognized number '网商路'")
    // scalastyle:on nonascii
  }

  test("string to interval: seconds with fractional part") {
    checkFromString("0.1 seconds", new CalendarInterval(0, 0, 100000))
    checkFromString("1. seconds", new CalendarInterval(0, 0, 1000000))
    checkFromString("123.001 seconds", new CalendarInterval(0, 0, 123001000))
    checkFromString("1.001001 seconds", new CalendarInterval(0, 0, 1001001))
    checkFromString("1 minute 1.001001 seconds", new CalendarInterval(0, 0, 61001001))
    checkFromString("-1.5 seconds", new CalendarInterval(0, 0, -1500000))
    // truncate nanoseconds to microseconds
    checkFromString("0.999999999 seconds", new CalendarInterval(0, 0, 999999))
    checkFromString(".999999999 seconds", new CalendarInterval(0, 0, 999999))
    checkFromInvalidString("0.123456789123 seconds", "'0.123456789123' is out of range")
  }

  test("from year-month string") {
    assert(fromYearMonthString("99-10") === new CalendarInterval(99 * 12 + 10, 0, 0L))
    assert(fromYearMonthString("+99-10") === new CalendarInterval(99 * 12 + 10, 0, 0L))
    assert(fromYearMonthString("-8-10") === new CalendarInterval(-8 * 12 - 10, 0, 0L))
    failFuncWithInvalidInput("99-15", "month 15 outside range", fromYearMonthString)
    failFuncWithInvalidInput("9a9-15", "Interval string does not match year-month format",
      fromYearMonthString)

    // whitespaces
    assert(fromYearMonthString("99-10 ") === new CalendarInterval(99 * 12 + 10, 0, 0L))
    assert(fromYearMonthString("+99-10\t") === new CalendarInterval(99 * 12 + 10, 0, 0L))
    assert(fromYearMonthString("\t\t-8-10\t") === new CalendarInterval(-8 * 12 - 10, 0, 0L))
    failFuncWithInvalidInput("99\t-15", "Interval string does not match year-month format",
      fromYearMonthString)
    failFuncWithInvalidInput("-\t99-15", "Interval string does not match year-month format",
      fromYearMonthString)

    assert(fromYearMonthString("178956970-6") == new CalendarInterval(Int.MaxValue - 1, 0, 0))
    assert(fromYearMonthString("178956970-7") == new CalendarInterval(Int.MaxValue, 0, 0))

    val e1 = intercept[IllegalArgumentException]{
      assert(fromYearMonthString("178956970-8") == new CalendarInterval(Int.MinValue, 0, 0))
    }.getMessage
    assert(e1.contains("integer overflow"))
    assert(fromYearMonthString("-178956970-8") == new CalendarInterval(Int.MinValue, 0, 0))
    val e2 = intercept[IllegalArgumentException]{
      assert(fromYearMonthString("-178956970-9") == new CalendarInterval(Int.MinValue, 0, 0))
    }.getMessage
    assert(e2.contains("integer overflow"))
  }

  test("from day-time string - legacy") {
    withSQLConf(SQLConf.LEGACY_FROM_DAYTIME_STRING.key -> "true") {
      assert(fromDayTimeString("5 12:40:30.999999999") ===
        new CalendarInterval(
          0,
          5,
          12 * MICROS_PER_HOUR +
            40 * MICROS_PER_MINUTE +
            30 * MICROS_PER_SECOND + 999999L))
      assert(fromDayTimeString("10 0:12:0.888") ===
        new CalendarInterval(
          0,
          10,
          12 * MICROS_PER_MINUTE + millisToMicros(888)))
      assert(fromDayTimeString("-3 0:0:0") === new CalendarInterval(0, -3, 0L))

      failFuncWithInvalidInput("5 30:12:20", "hour 30 outside range", fromDayTimeString)
      failFuncWithInvalidInput("5 30-12", "must match day-time format", fromDayTimeString)
    }
  }

  test("interval duration") {
    def duration(s: String, unit: TimeUnit, daysPerMonth: Int): Long = {
      IntervalUtils.getDuration(stringToInterval(UTF8String.fromString(s)), unit, daysPerMonth)
    }

    assert(duration("0 seconds", TimeUnit.MILLISECONDS, 31) === 0)
    assert(duration("1 month", TimeUnit.DAYS, 31) === 31)
    assert(duration("1 microsecond", TimeUnit.MICROSECONDS, 30) === 1)
    assert(duration("1 month -30 days", TimeUnit.DAYS, 31) === 1)

    val e = intercept[ArithmeticException] {
      duration(Integer.MAX_VALUE + " month", TimeUnit.SECONDS, 31)
    }
    assert(e.getMessage.contains("overflow"))
  }

  test("negative interval") {
    def isNegative(s: String, daysPerMonth: Int): Boolean = {
      IntervalUtils.isNegative(stringToInterval(UTF8String.fromString(s)), daysPerMonth)
    }

    assert(isNegative("-1 months", 28))
    assert(isNegative("-1 microsecond", 30))
    assert(isNegative("-1 month 30 days", 31))
    assert(isNegative("2 months -61 days", 30))
    assert(isNegative("-1 year -2 seconds", 30))
    assert(!isNegative("0 months", 28))
    assert(!isNegative("1 year -360 days", 31))
    assert(!isNegative("-1 year 380 days", 31))
  }

  test("negate") {
    assert(negateExact(new CalendarInterval(1, 2, 3)) === new CalendarInterval(-1, -2, -3))
    assert(negate(new CalendarInterval(1, 2, 3)) === new CalendarInterval(-1, -2, -3))
  }

  test("subtract one interval by another") {
    val input1 = new CalendarInterval(3, 1, 1 * MICROS_PER_HOUR)
    val input2 = new CalendarInterval(2, 4, 100 * MICROS_PER_HOUR)
    val input3 = new CalendarInterval(-10, -30, -81 * MICROS_PER_HOUR)
    val input4 = new CalendarInterval(75, 150, 200 * MICROS_PER_HOUR)
    Seq[(CalendarInterval, CalendarInterval) => CalendarInterval](subtractExact, subtract)
      .foreach { func =>
        assert(new CalendarInterval(1, -3, -99 * MICROS_PER_HOUR) === func(input1, input2))
        assert(new CalendarInterval(-85, -180, -281 * MICROS_PER_HOUR) === func(input3, input4))
      }
  }

  test("add two intervals") {
    val input1 = new CalendarInterval(3, 1, 1 * MICROS_PER_HOUR)
    val input2 = new CalendarInterval(2, 4, 100 * MICROS_PER_HOUR)
    val input3 = new CalendarInterval(-10, -30, -81 * MICROS_PER_HOUR)
    val input4 = new CalendarInterval(75, 150, 200 * MICROS_PER_HOUR)
    Seq[(CalendarInterval, CalendarInterval) => CalendarInterval](addExact, add).foreach { func =>
      assert(new CalendarInterval(5, 5, 101 * MICROS_PER_HOUR) === func(input1, input2))
      assert(new CalendarInterval(65, 120, 119 * MICROS_PER_HOUR) === func(input3, input4))
    }
  }

  test("multiply by num") {
    Seq[(CalendarInterval, Double) => CalendarInterval](multiply, multiplyExact).foreach { func =>
      var interval = new CalendarInterval(0, 0, 0)
      assert(interval === func(interval, 0))
      interval = new CalendarInterval(123, 456, 789)
      assert(new CalendarInterval(123 * 42, 456 * 42, 789 * 42) === func(interval, 42))
      interval = new CalendarInterval(-123, -456, -789)
      assert(new CalendarInterval(-123 * 42, -456 * 42, -789 * 42) === func(interval, 42))
      interval = new CalendarInterval(1, 5, 0)
      assert(new CalendarInterval(1, 7, 12 * MICROS_PER_HOUR) === func(interval, 1.5))
      interval = new CalendarInterval(2, 2, 2 * MICROS_PER_HOUR)
      assert(new CalendarInterval(2, 2, 12 * MICROS_PER_HOUR) === func(interval, 1.2))
    }

    val interval = new CalendarInterval(2, 0, 0)
    assert(multiply(interval, Integer.MAX_VALUE) === new CalendarInterval(Int.MaxValue, 0, 0))

    val e = intercept[ArithmeticException](multiplyExact(interval, Integer.MAX_VALUE))
    assert(e.getMessage.contains("overflow"))
  }

  test("divide by num") {
    Seq[(CalendarInterval, Double) => CalendarInterval](divide, divideExact).foreach { func =>
      var interval = new CalendarInterval(0, 0, 0)
      assert(interval === func(interval, 10))
      interval = new CalendarInterval(1, 3, 30 * MICROS_PER_SECOND)
      assert(new CalendarInterval(0, 1, 12 * MICROS_PER_HOUR + 15 * MICROS_PER_SECOND) ===
        func(interval, 2))
      assert(new CalendarInterval(2, 6, MICROS_PER_MINUTE) === func(interval, 0.5))
      interval = new CalendarInterval(-1, 0, -30 * MICROS_PER_SECOND)
      assert(new CalendarInterval(0, 0, -15 * MICROS_PER_SECOND) === func(interval, 2))
      assert(new CalendarInterval(-2, 0, -MICROS_PER_MINUTE) === func(interval, 0.5))
    }

    var interval = new CalendarInterval(Int.MaxValue, Int.MaxValue, 0)
    assert(divide(interval, 0.9) === new CalendarInterval(Int.MaxValue, Int.MaxValue,
      ((Int.MaxValue / 9.0) * MICROS_PER_DAY).round))
    val e1 = intercept[ArithmeticException](divideExact(interval, 0.9))
    assert(e1.getMessage.contains("integer overflow"))

    interval = new CalendarInterval(123, 456, 789)
    assert(divide(interval, 0) === null)
    val e2 = intercept[ArithmeticException](divideExact(interval, 0))
    assert(e2.getMessage.contains("Division by zero"))
  }

  test("from day-time string") {
    import org.apache.spark.sql.types.DayTimeIntervalType._
    def check(input: String, from: Byte, to: Byte, expected: String): Unit = {
      withClue(s"from = $from, to = $to") {
        val expectedUtf8 = UTF8String.fromString(expected)
        assert(fromDayTimeString(input, from, to) === safeStringToInterval(expectedUtf8))
      }
    }
    def checkFail(input: String, from: Byte, to: Byte, errMsg: String): Unit = {
      failFuncWithInvalidInput(input, errMsg, s => fromDayTimeString(s, from, to))
    }

    check("12:40", HOUR, MINUTE, "12 hours 40 minutes")
    check("+12:40", HOUR, MINUTE, "12 hours 40 minutes")
    check("-12:40", HOUR, MINUTE, "-12 hours -40 minutes")
    checkFail("5 12:40", HOUR, MINUTE, "Interval string does not match day-time format")

    check("12:40:30.999999999", HOUR, SECOND, "12 hours 40 minutes 30.999999 seconds")
    check("+12:40:30.123456789", HOUR, SECOND, "12 hours 40 minutes 30.123456 seconds")
    check("-12:40:30.123456789", HOUR, SECOND, "-12 hours -40 minutes -30.123456 seconds")
    checkFail("5 12:40:30", HOUR, SECOND, "Interval string does not match day-time format")
    checkFail("12:40:30.0123456789", HOUR, SECOND,
      "Interval string does not match day-time format")

    check("40:30.123456789", MINUTE, SECOND, "40 minutes 30.123456 seconds")
    check("+40:30.123456789", MINUTE, SECOND, "40 minutes 30.123456 seconds")
    check("-40:30.123456789", MINUTE, SECOND, "-40 minutes -30.123456 seconds")
    checkFail("12:40:30", MINUTE, SECOND, "Interval string does not match day-time format")

    check("5 12", DAY, HOUR, "5 days 12 hours")
    check("+5 12", DAY, HOUR, "5 days 12 hours")
    check("-5 12", DAY, HOUR, "-5 days -12 hours")
    checkFail("5 12:30", DAY, HOUR, "Interval string does not match day-time format")

    check("5 12:40", DAY, MINUTE, "5 days 12 hours 40 minutes")
    check("+5 12:40", DAY, MINUTE, "5 days 12 hours 40 minutes")
    check("-5 12:40", DAY, MINUTE, "-5 days -12 hours -40 minutes")
    checkFail("5 12", DAY, MINUTE, "Interval string does not match day-time format")

    check("5 12:40:30.123", DAY, SECOND, "5 days 12 hours 40 minutes 30.123 seconds")
    check("+5 12:40:30.123456", DAY, SECOND, "5 days 12 hours 40 minutes 30.123456 seconds")
    check("-5 12:40:30.123456789", DAY, SECOND, "-5 days -12 hours -40 minutes -30.123456 seconds")
    checkFail("5 12", DAY, SECOND, "Interval string does not match day-time format")

    checkFail("5 30:12:20", DAY, SECOND, "hour 30 outside range")
    checkFail("5 30-12", DAY, SECOND, "Interval string does not match day-time format")

    // whitespaces
    check("\t +5 12:40\t ", DAY, MINUTE, "5 days 12 hours 40 minutes")
    checkFail("+5\t 12:40", DAY, MINUTE, "Interval string does not match day-time format")

  }

  test("interval overflow check") {
    val maxMonth = new CalendarInterval(Int.MaxValue, 0, 0)
    val minMonth = new CalendarInterval(Int.MinValue, 0, 0)
    val oneMonth = new CalendarInterval(1, 0, 0)
    val maxDay = new CalendarInterval(0, Int.MaxValue, 0)
    val minDay = new CalendarInterval(0, Int.MinValue, 0)
    val oneDay = new CalendarInterval(0, 1, 0)
    val maxMicros = new CalendarInterval(0, 0, Long.MaxValue)
    val minMicros = new CalendarInterval(0, 0, Long.MinValue)
    val oneMicros = new CalendarInterval(0, 0, 1)
    intercept[ArithmeticException](negateExact(minMonth))
    assert(negate(minMonth) === minMonth)

    intercept[ArithmeticException](addExact(maxMonth, oneMonth))
    intercept[ArithmeticException](addExact(maxDay, oneDay))
    intercept[ArithmeticException](addExact(maxMicros, oneMicros))
    assert(add(maxMonth, oneMonth) === minMonth)
    assert(add(maxDay, oneDay) === minDay)
    assert(add(maxMicros, oneMicros) === minMicros)

    intercept[ArithmeticException](subtractExact(minDay, oneDay))
    intercept[ArithmeticException](subtractExact(minMonth, oneMonth))
    intercept[ArithmeticException](subtractExact(minMicros, oneMicros))
    assert(subtract(minMonth, oneMonth) === maxMonth)
    assert(subtract(minDay, oneDay) === maxDay)
    assert(subtract(minMicros, oneMicros) === maxMicros)

    intercept[ArithmeticException](multiplyExact(maxMonth, 2))
    intercept[ArithmeticException](divideExact(maxDay, 0.5))
  }

  test("SPARK-34605: microseconds to duration") {
    assert(microsToDuration(0).isZero)
    assert(microsToDuration(-1).toNanos === -1000)
    assert(microsToDuration(1).toNanos === 1000)
    assert(microsToDuration(Long.MaxValue).toDays === 106751991)
    assert(microsToDuration(Long.MinValue).toDays === -106751991)
  }

  test("SPARK-34605: duration to microseconds") {
    assert(durationToMicros(Duration.ZERO) === 0)
    assert(durationToMicros(Duration.ofSeconds(-1)) === -1000000)
    assert(durationToMicros(Duration.ofNanos(123456)) === 123)
    assert(durationToMicros(Duration.ofDays(106751991)) ===
      (Long.MaxValue / MICROS_PER_DAY) * MICROS_PER_DAY)

    val errMsg = intercept[ArithmeticException] {
      durationToMicros(Duration.ofDays(106751991 + 1))
    }.getMessage
    assert(errMsg.contains("long overflow"))
  }

  test("SPARK-34615: period to months") {
    assert(periodToMonths(Period.ZERO) === 0)
    assert(periodToMonths(Period.of(0, -1, 0)) === -1)
    assert(periodToMonths(Period.of(-1, 0, 10)) === -12) // ignore days
    assert(periodToMonths(Period.of(178956970, 7, 0)) === Int.MaxValue)
    assert(periodToMonths(Period.of(-178956970, -8, 123)) === Int.MinValue)
    assert(periodToMonths(Period.of(0, Int.MaxValue, Int.MaxValue)) === Int.MaxValue)

    val errMsg = intercept[ArithmeticException] {
      periodToMonths(Period.of(Int.MaxValue, 0, 0))
    }.getMessage
    assert(errMsg.contains("integer overflow"))
  }

  test("SPARK-34615: months to period") {
    assert(monthsToPeriod(0) === Period.ZERO)
    assert(monthsToPeriod(-11) === Period.of(0, -11, 0))
    assert(monthsToPeriod(11) === Period.of(0, 11, 0))
    assert(monthsToPeriod(27) === Period.of(2, 3, 0))
    assert(monthsToPeriod(-13) === Period.of(-1, -1, 0))
    assert(monthsToPeriod(Int.MaxValue) === Period.ofYears(178956970).withMonths(7))
    assert(monthsToPeriod(Int.MinValue) === Period.ofYears(-178956970).withMonths(-8))
  }

  test("SPARK-34695: round trip conversion of micros -> duration -> micros") {
    Seq(
      0,
      MICROS_PER_SECOND - 1,
      -MICROS_PER_SECOND + 1,
      MICROS_PER_SECOND,
      -MICROS_PER_SECOND,
      Long.MaxValue - MICROS_PER_SECOND,
      Long.MinValue + MICROS_PER_SECOND,
      Long.MaxValue,
      Long.MinValue).foreach { micros =>
      val duration = microsToDuration(micros)
      assert(durationToMicros(duration) === micros)
    }
  }

  test("SPARK-34715: Add round trip tests for period <-> month and duration <-> micros") {
    // Months -> Period -> Months
    Seq(
      0,
      MONTHS_PER_YEAR - 1,
      MONTHS_PER_YEAR + 1,
      MONTHS_PER_YEAR,
      -MONTHS_PER_YEAR,
      Int.MaxValue - MONTHS_PER_YEAR,
      Int.MinValue + MONTHS_PER_YEAR,
      Int.MaxValue,
      Int.MinValue).foreach { months =>
      val period = monthsToPeriod(months)
      assert(periodToMonths(period) === months)
    }
    // Period -> Months -> Period
    Seq(
      monthsToPeriod(0),
      monthsToPeriod(MONTHS_PER_YEAR - 1),
      monthsToPeriod(MONTHS_PER_YEAR + 1),
      monthsToPeriod(MONTHS_PER_YEAR),
      monthsToPeriod(-MONTHS_PER_YEAR),
      monthsToPeriod(Int.MaxValue - MONTHS_PER_YEAR),
      monthsToPeriod(Int.MinValue + MONTHS_PER_YEAR),
      monthsToPeriod(Int.MaxValue),
      monthsToPeriod(Int.MinValue)).foreach { period =>
      val months = periodToMonths(period)
      assert(monthsToPeriod(months) === period)
    }
    // Duration -> micros -> Duration
    Seq(
      microsToDuration(0),
      microsToDuration(MICROS_PER_SECOND - 1),
      microsToDuration(-MICROS_PER_SECOND + 1),
      microsToDuration(MICROS_PER_SECOND),
      microsToDuration(-MICROS_PER_SECOND),
      microsToDuration(Long.MaxValue - MICROS_PER_SECOND),
      microsToDuration(Long.MinValue + MICROS_PER_SECOND),
      microsToDuration(Long.MaxValue),
      microsToDuration(Long.MinValue)).foreach { duration =>
      val micros = durationToMicros(duration)
      assert(microsToDuration(micros) === duration)
    }
  }

  test("SPARK-35016: format year-month intervals") {
    import org.apache.spark.sql.types.YearMonthIntervalType._
    Seq(
      0 -> ("0-0", "INTERVAL '0-0' YEAR TO MONTH"),
      -11 -> ("-0-11", "INTERVAL '-0-11' YEAR TO MONTH"),
      11 -> ("0-11", "INTERVAL '0-11' YEAR TO MONTH"),
      -13 -> ("-1-1", "INTERVAL '-1-1' YEAR TO MONTH"),
      13 -> ("1-1", "INTERVAL '1-1' YEAR TO MONTH"),
      -24 -> ("-2-0", "INTERVAL '-2-0' YEAR TO MONTH"),
      24 -> ("2-0", "INTERVAL '2-0' YEAR TO MONTH"),
      Int.MinValue -> ("-178956970-8", "INTERVAL '-178956970-8' YEAR TO MONTH"),
      Int.MaxValue -> ("178956970-7", "INTERVAL '178956970-7' YEAR TO MONTH")
    ).foreach { case (months, (hiveIntervalStr, ansiIntervalStr)) =>
      assert(toYearMonthIntervalString(months, ANSI_STYLE, YEAR, MONTH) === ansiIntervalStr)
      assert(toYearMonthIntervalString(months, HIVE_STYLE, YEAR, MONTH) === hiveIntervalStr)
    }
  }

  test("SPARK-35016: format day-time intervals") {
    import DayTimeIntervalType._
    Seq(
      0L -> ("0 00:00:00.000000000", "INTERVAL '0 00:00:00' DAY TO SECOND"),
      -1L -> ("-0 00:00:00.000001000", "INTERVAL '-0 00:00:00.000001' DAY TO SECOND"),
      10 * MICROS_PER_MILLIS -> ("0 00:00:00.010000000", "INTERVAL '0 00:00:00.01' DAY TO SECOND"),
      (-123 * MICROS_PER_DAY - 3 * MICROS_PER_SECOND) ->
        ("-123 00:00:03.000000000", "INTERVAL '-123 00:00:03' DAY TO SECOND"),
      Long.MinValue -> ("-106751991 04:00:54.775808000",
        "INTERVAL '-106751991 04:00:54.775808' DAY TO SECOND")
    ).foreach { case (micros, (hiveIntervalStr, ansiIntervalStr)) =>
      assert(toDayTimeIntervalString(micros, ANSI_STYLE, DAY, SECOND) === ansiIntervalStr)
      assert(toDayTimeIntervalString(micros, HIVE_STYLE, DAY, SECOND) === hiveIntervalStr)
    }
  }

  test("SPARK-35734: Format day-time intervals using type fields") {
    import DayTimeIntervalType._
    Seq(
      0L ->
        ("INTERVAL '0 00:00:00' DAY TO SECOND",
          "INTERVAL '0 00:00' DAY TO MINUTE",
          "INTERVAL '0 00' DAY TO HOUR",
          "INTERVAL '00:00:00' HOUR TO SECOND",
          "INTERVAL '00:00' HOUR TO MINUTE",
          "INTERVAL '00:00' MINUTE TO SECOND",
          "INTERVAL '0' DAY",
          "INTERVAL '00' HOUR",
          "INTERVAL '00' MINUTE",
          "INTERVAL '00' SECOND"),
      -1L ->
        ("INTERVAL '-0 00:00:00.000001' DAY TO SECOND",
          "INTERVAL '-0 00:00' DAY TO MINUTE",
          "INTERVAL '-0 00' DAY TO HOUR",
          "INTERVAL '-00:00:00.000001' HOUR TO SECOND",
          "INTERVAL '-00:00' HOUR TO MINUTE",
          "INTERVAL '-00:00.000001' MINUTE TO SECOND",
          "INTERVAL '-0' DAY",
          "INTERVAL '-00' HOUR",
          "INTERVAL '-00' MINUTE",
          "INTERVAL '-00.000001' SECOND"),
      10 * MICROS_PER_MILLIS ->
        ("INTERVAL '0 00:00:00.01' DAY TO SECOND",
          "INTERVAL '0 00:00' DAY TO MINUTE",
          "INTERVAL '0 00' DAY TO HOUR",
          "INTERVAL '00:00:00.01' HOUR TO SECOND",
          "INTERVAL '00:00' HOUR TO MINUTE",
          "INTERVAL '00:00.01' MINUTE TO SECOND",
          "INTERVAL '0' DAY",
          "INTERVAL '00' HOUR",
          "INTERVAL '00' MINUTE",
          "INTERVAL '00.01' SECOND"),
      (-123 * MICROS_PER_DAY - 3 * MICROS_PER_SECOND) ->
        ("INTERVAL '-123 00:00:03' DAY TO SECOND",
          "INTERVAL '-123 00:00' DAY TO MINUTE",
          "INTERVAL '-123 00' DAY TO HOUR",
          "INTERVAL '-2952:00:03' HOUR TO SECOND",
          "INTERVAL '-2952:00' HOUR TO MINUTE",
          "INTERVAL '-177120:03' MINUTE TO SECOND",
          "INTERVAL '-123' DAY",
          "INTERVAL '-2952' HOUR",
          "INTERVAL '-177120' MINUTE",
          "INTERVAL '-10627203' SECOND"),
      Long.MinValue ->
        ("INTERVAL '-106751991 04:00:54.775808' DAY TO SECOND",
          "INTERVAL '-106751991 04:00' DAY TO MINUTE",
          "INTERVAL '-106751991 04' DAY TO HOUR",
          "INTERVAL '-2562047788:00:54.775808' HOUR TO SECOND",
          "INTERVAL '-2562047788:00' HOUR TO MINUTE",
          "INTERVAL '-153722867280:54.775808' MINUTE TO SECOND",
          "INTERVAL '-106751991' DAY",
          "INTERVAL '-2562047788' HOUR",
          "INTERVAL '-153722867280' MINUTE",
          "INTERVAL '-9223372036854.775808' SECOND"),
      69159782123456L ->
        ("INTERVAL '800 11:03:02.123456' DAY TO SECOND",
          "INTERVAL '800 11:03' DAY TO MINUTE",
          "INTERVAL '800 11' DAY TO HOUR",
          "INTERVAL '19211:03:02.123456' HOUR TO SECOND",
          "INTERVAL '19211:03' HOUR TO MINUTE",
          "INTERVAL '1152663:02.123456' MINUTE TO SECOND",
          "INTERVAL '800' DAY",
          "INTERVAL '19211' HOUR",
          "INTERVAL '1152663' MINUTE",
          "INTERVAL '69159782.123456' SECOND"),
      -69159782123456L ->
        ("INTERVAL '-800 11:03:02.123456' DAY TO SECOND",
          "INTERVAL '-800 11:03' DAY TO MINUTE",
          "INTERVAL '-800 11' DAY TO HOUR",
          "INTERVAL '-19211:03:02.123456' HOUR TO SECOND",
          "INTERVAL '-19211:03' HOUR TO MINUTE",
          "INTERVAL '-1152663:02.123456' MINUTE TO SECOND",
          "INTERVAL '-800' DAY",
          "INTERVAL '-19211' HOUR",
          "INTERVAL '-1152663' MINUTE",
          "INTERVAL '-69159782.123456' SECOND")
    ).foreach {
      case (
        micros, (
          dayToSec,
          dayToMinute,
          dayToHour,
          hourToSec,
          hourToMinute,
          minuteToSec,
          day,
          hour,
          minute,
          sec)) =>
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, DAY, SECOND) === dayToSec)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, DAY, MINUTE) === dayToMinute)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, DAY, HOUR) === dayToHour)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, HOUR, SECOND) === hourToSec)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, HOUR, MINUTE) === hourToMinute)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, MINUTE, SECOND) === minuteToSec)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, DAY, DAY) === day)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, HOUR, HOUR) === hour)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, MINUTE, MINUTE) === minute)
        assert(toDayTimeIntervalString(micros, ANSI_STYLE, SECOND, SECOND) === sec)
    }
  }

  test("SPARK-35771: Format year-month intervals using type fields") {
    import org.apache.spark.sql.types.YearMonthIntervalType._
    Seq(
      0 ->
        ("INTERVAL '0-0' YEAR TO MONTH", "INTERVAL '0' YEAR", "INTERVAL '0' MONTH"),
      -11 -> ("INTERVAL '-0-11' YEAR TO MONTH", "INTERVAL '-0' YEAR", "INTERVAL '-11' MONTH"),
      11 -> ("INTERVAL '0-11' YEAR TO MONTH", "INTERVAL '0' YEAR", "INTERVAL '11' MONTH"),
      -13 -> ("INTERVAL '-1-1' YEAR TO MONTH", "INTERVAL '-1' YEAR", "INTERVAL '-13' MONTH"),
      13 -> ("INTERVAL '1-1' YEAR TO MONTH", "INTERVAL '1' YEAR", "INTERVAL '13' MONTH"),
      -24 -> ("INTERVAL '-2-0' YEAR TO MONTH", "INTERVAL '-2' YEAR", "INTERVAL '-24' MONTH"),
      24 -> ("INTERVAL '2-0' YEAR TO MONTH", "INTERVAL '2' YEAR", "INTERVAL '24' MONTH"),
      Int.MinValue ->
        ("INTERVAL '-178956970-8' YEAR TO MONTH",
          "INTERVAL '-178956970' YEAR",
          "INTERVAL '-2147483648' MONTH"),
      Int.MaxValue ->
        ("INTERVAL '178956970-7' YEAR TO MONTH",
          "INTERVAL '178956970' YEAR",
          "INTERVAL '2147483647' MONTH")
    ).foreach { case (months, (yearToMonth, year, month)) =>
      assert(toYearMonthIntervalString(months, ANSI_STYLE, YEAR, MONTH) === yearToMonth)
      assert(toYearMonthIntervalString(months, ANSI_STYLE, YEAR, YEAR) === year)
      assert(toYearMonthIntervalString(months, ANSI_STYLE, MONTH, MONTH) === month)
    }
  }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34209
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Fusion.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Fusion.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
        /// </summary>
        public static System.Drawing.Icon fusionIcon {
            get {
                object obj = ResourceManager.GetObject("fusionIcon", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        public static System.Drawing.Bitmap fusionSplash {
            get {
                object obj = ResourceManager.GetObject("fusionSplash", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        public static System.Drawing.Bitmap launchHeader {
            get {
                object obj = ResourceManager.GetObject("launchHeader", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import rospy
import math
from sensor_msgs.msg import Imu
from tf.transformations import euler_from_quaternion

rad2degrees = 180.0 / math.pi
degrees2rad = math.pi / 180.0

class ImuHandler(object):
    """
    Handler for ROS topics of type: sensor_msgs/imu
    Args:
        topic_name: Name of ROS topic to be subscribed
        buffer_size: Variable buffer, depend on frame rate of topic, default: 500
        queue_size: Subscriber queue_size
    """

    def __init__(self, topic_name, buffer_size=500, queue_size=10):
        self.imu_data = Imu()
        [self.roll, self.pitch, self.yaw,
         self.angular_x, self.angular_y, self.angular_z,
         self.lin_acc_x, self.lin_acc_y, self.lin_acc_z] = np.zeros((9, 1)) * 0.0

        [self._roll, self._pitch, self._yaw,
         self._angular_x, self._angular_y, self._angular_z,
         self._lin_acc_x, self._lin_acc_y, self._lin_acc_z] = np.zeros((9, 1)) * 0.0

        self.topic_imu = topic_name
        self.queue_size = queue_size
        self.buffer_size = buffer_size
        self.counter = 0

        self.buffer = np.zeros([self.buffer_size, 9])

        self.sub = rospy.Subscriber(self.topic_imu, Imu, self.callback, queue_size=self.queue_size)

    def callback(self, msg):
        self.imu_data = msg

        quat = (
            self.imu_data.orientation.x,
            self.imu_data.orientation.y,
            self.imu_data.orientation.z,
            self.imu_data.orientation.w)

        (self._roll, self._pitch, self._yaw) = euler_from_quaternion(quat)

        self._angular_x = self.imu_data.angular_velocity.x
        self._angular_y = self.imu_data.angular_velocity.y
        self._angular_z = self.imu_data.angular_velocity.z

        self._lin_acc_x = self.imu_data.linear_acceleration.x
        self._lin_acc_y = self.imu_data.linear_acceleration.y
        self._lin_acc_z = self.imu_data.linear_acceleration.z

        if self.counter < self.buffer_size:
            self.buffer[self.counter] = [self._roll, self._pitch, self._yaw,
                                         self._angular_x, self._angular_y, self._angular_z,
                                         self._lin_acc_x, self._lin_acc_y, self._lin_acc_z]
        else:
            rospy.loginfo("ImuHandler for: " + self.topic_imu + " has reached buffer size.")

        self.counter += 1

    def get_value(self):
        if self.counter > 0:
            self.roll = np.sum(self.buffer[:, 0]) / self.counter
            self.pitch = np.sum(self.buffer[:, 1]) / self.counter
            self.yaw = np.sum(self.buffer[:, 2]) / self.counter

            self.angular_x = np.sum(self.buffer[:, 3]) / self.counter
            self.angular_y = np.sum(self.buffer[:, 4]) / self.counter
            self.angular_z = np.sum(self.buffer[:, 5]) / self.counter

            self.lin_acc_x = np.sum(self.buffer[:, 6]) / self.counter
            self.lin_acc_y = np.sum(self.buffer[:, 7]) / self.counter
            self.lin_acc_z = np.sum(self.buffer[:, 8]) / self.counter

        self.buffer = np.zeros([self.buffer_size, 9])
        self.counter = 0

        # return instant measurement
        # return [self._roll, self._pitch, self._yaw, self._angular_x, self._angular_y, self._angular_z]
        # return Mean measurement
        return [self.roll, self.pitch, self.yaw,
                self.angular_x, self.angular_y, self.angular_z,
                self.lin_acc_x, self.lin_acc_y, self.lin_acc_z]


text:
package me.prettyprint.cassandra.connection;

import me.prettyprint.cassandra.connection.factory.HClientFactory;
import me.prettyprint.cassandra.service.CassandraHost;
import me.prettyprint.cassandra.service.CassandraClientMonitor;

import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

/**
 * Selects the least active host based on the number of active connections.
 * The list of hosts is shuffled on each pass to account for the case
 * where a number of hosts are at the minimum number of connections
 * (ie. they are not busy).
 *
 *
 * @author zznate
 */
public class LeastActiveBalancingPolicy implements LoadBalancingPolicy {

  private static final long serialVersionUID = 329849818218657061L;
  private static final Logger log = LoggerFactory.getLogger(LeastActiveBalancingPolicy.class);

  @Override
  public HClientPool getPool(Collection<HClientPool> pools, Set<CassandraHost> excludeHosts) {
    List<HClientPool> vals = Lists.newArrayList(pools);
    // shuffle pools to avoid always returning the same one when we are not terribly busy
    Collections.shuffle(vals);
    Collections.sort(vals, new ShufflingCompare());
    Iterator<HClientPool> iterator = vals.iterator();
    HClientPool concurrentHClientPool = iterator.next();
    if ( excludeHosts != null && excludeHosts.size() > 0 ) {
      while (iterator.hasNext()) {
        if ( !excludeHosts.contains(concurrentHClientPool.getCassandraHost()) ) {
          break;
        }
        concurrentHClientPool = (ConcurrentHClientPool) iterator.next();
      }
    }
    return concurrentHClientPool;
  }

  /**
   * Make the results of this Comparator stable (and thus transitive) by caching the numActive value
   * for each HClientPool as they are seen, then reusing the cached value instead of the current value
   * (which may have changed) if the same pool is compared again.
   *
   * Without this change the new TimSort algorithm in Java 7 sometimes throws a:
   * java.lang.IllegalArgumentException: Comparison method violates its general contract!
   */
  static final class ShufflingCompare implements Comparator<HClientPool> {
    private Map<HClientPool, Integer> cachedActive = new HashMap<HClientPool, Integer>();

    public int compare(HClientPool o1, HClientPool o2) {
      if ( log.isDebugEnabled() ) {
        log.debug("comparing 1: {} and count {} with 2: {} and count {}",
          new Object[]{o1.getCassandraHost(), o1.getNumActive(), o2.getCassandraHost(), o2.getNumActive()});
      }
      return getNumActive(o1) - getNumActive(o2);
    }
    private int getNumActive(HClientPool p) {
      Integer ret = cachedActive.get(p);
      if (ret == null) {
        ret = p.getNumActive();
        cachedActive.put(p, ret);
      }
      return ret;
    }
  }

  @Override
  public HClientPool createConnection(HClientFactory clientFactory, CassandraHost host, CassandraClientMonitor monitor) {
	  return new ConcurrentHClientPool(clientFactory, host, monitor);
  }
}


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-ba2d5549-7d43-4c28-a003-29f7f29e761a" version="1.1.1" timestamp="2013-04-30T18:14:37+00:00">
    <stix:Incidents>
        <stix:Incident id="example:incident-eb1c8c1f-0c3e-4e5f-81af-0952b40e37c4" timestamp="2014-05-10T00:58:19+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>SNCB Europe put by mistake on their public HTTP server a text file with 1.4M records of their customers. Including name, address, email, birthdate, sexe, even phone numbers in some cases. That file got indexed by Google and Bing and a user found it and posted the link on a forum. </incident:Title>
            <incident:External_ID source="VERIS">2022C66A-B2CF-4500-963A-599CFB0E776B</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="month">2012-12-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">swidup</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">National Belgian Railway Company</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>BE</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Database</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Personal: 1400000</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-eef31f89-1b41-4524-b70c-d90b918055fd" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://storify.com/xdamman/sncb-europe-leaks-1-4m-personal-data-of-its-custom, http://storify.com/xdamman/sncbgate-nmbsgate, http://www.huntonprivacyblog.com/2013/04/articles/belgian-privacy-commission-refers-data-breach-case-to-public-prosecutor/</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-eef31f89-1b41-4524-b70c-d90b918055fd" timestamp="2014-12-22T16:23:12.561000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Type timestamp="2014-12-22T16:23:12.561000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Insider Threat</stixCommon:Value>
                <stixCommon:Description>Unknown</stixCommon:Description>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:23:12.561000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Motivation>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
package snippet;

import java.util.*;

/**
 * Created by Administrator on 2017/10/1.
 */
public class RemoveDuplicates {
    public static void main(String args[]){
        byHashSet();

        byLinkedHashSet();
    }

    public static void byHashSet(){
        //ArrayList with duplicates String
        List<String> duplicateList = (List<String>) Arrays.asList("Android" , "Android", "iOS", "Windows mobile");
        System.out.println("size of Arraylist with duplicates: " + duplicateList.size()); //should print 4 becaues of duplicates Android

        System.out.println(duplicateList);

        //Converting ArrayList to HashSet to remove duplicates
        HashSet<String> listToSet = new HashSet<String>(duplicateList);

        //Creating Arraylist without duplicate values
        List<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
        System.out.println("size of ArrayList without duplicates: " + listToSet.size()); //should print 3 becaues of duplicates Android removed

        System.out.println(listWithoutDuplicates);
    }

    /**
     * keep the insertion order of elements
     */
    public static void byLinkedHashSet(){
        //ArrayList with duplicates String
        List<String> duplicateList = (List<String>) Arrays.asList("Android" , "Android", "iOS", "Windows mobile");
        //should print 4 becaues of duplicates Android
        System.out.println("size of Arraylist with duplicates: " + duplicateList.size());
        System.out.println("ArrayList with duplicates: " + duplicateList);

        //Converting ArrayList to HashSet to remove duplicates
        LinkedHashSet<String> listToSet = new LinkedHashSet<String>(duplicateList);

        //Creating Arraylist without duplicate values
        List<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
        //should print 3 becaues of duplicates Android removed
        System.out.println("size of ArrayList without duplicates: " + listToSet.size());
        System.out.println("ArrayList after removing duplicates in same order: " + listWithoutDuplicates);
    }
}


text:
using Newtonsoft.Json.Linq;

namespace OpenDMS.Storage.Providers.CouchDB.Model
{
    public class Attachment : BaseStorageObject
    {
        private bool? _stub = null;

        public bool? Stub
        {
            get { return _stub; }
            set { _stub = value; ResetLength(); }
        }

        public string ContentType
        {
            get { return this["content_type"].Value<string>(); }
            set { this["content_type"] = value; ResetLength(); }
        }

        public long AttachmentLength
        {
            get { return this["length"].Value<long>(); }
            set { this["length"] = value; ResetLength(); }
        }

        public Attachment()
            : base()
        {
            _stub = null;
        }

        public Attachment(string json)
            : this(Parse(json))
        {
        }

        public Attachment(JToken token)
            : this((JObject)token)
        {
        }

        public Attachment(JObject jobj)
            : base(jobj)
        {
        }

        private bool? GetStub()
        {
            if(this["stub"] != null)
                return this["stub"].Value<bool>();
            return null;
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('smarthouse', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Log',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('type', models.CharField(max_length=50)),
                ('id_arduino', models.IntegerField()),
                ('value', models.FloatField()),
                ('date', models.DateField()),
            ],
        ),
        migrations.RemoveField(
            model_name='arduino',
            name='crypto_key',
        ),
    ]


text:
package cmd

import (
	"github.com/tuxagon/yata-cli/yata"
	"github.com/urfave/cli"
)

type completeArgs struct {
	id int
}

func (a *completeArgs) Parse(ctx *cli.Context) {
	a.id = parseIDWithIndex(ctx, 0)
}

// Complete will mark the specified task as completed
func Complete(ctx *cli.Context) error {
	args := &completeArgs{}
	args.Parse(ctx)

	manager := yata.NewTaskManager()
	task, _ := manager.GetByID(uint32(args.id))
	if task != nil {
		task.Completed = true
		manager.Save(*task)
	} else {
		yata.PrintfColor("red+h", "Sorry, no task with an ID of %d was found", args.id)
	}

	return nil
}


text:
            Properties
            Methods
            Events
                        Direct Link

Class Ext.menu.MenuMgr

Package:	Ext.menu

Defined In:	MenuMgr.js

Class:	MenuMgr

Extends:	Object

            *
Provides a common registry of all menu items on a page so that they can be easily accessed by id.

This class is a singleton and cannot be created directly.

Public Properties

This class has no public properties.

Public Methods

                Method
                Defined By

            get( String/Object menu ) : Ext.menu.Menu

Returns a Ext.menu.Menu object

                Returns a Ext.menu.Menu object

        Parameters:

menu : String/Object
The string menu id, an existing menu object reference, or a Menu config that will
be used to generate and return a new Menu instance.

        Returns:

Ext.menu.Menu
The specified menu, or null if none are found

        MenuMgr

            hideAll() : void

Hides all menus that are currently visible

                Hides all menus that are currently visible

        Parameters:

None.

        Returns:

void

        MenuMgr

Public Events

This class has no public events.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/bg_white"
              android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:layout_marginTop="5dp">

        <EditText
            android:id="@+id/dm_et"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="15dp"
            android:layout_weight="6"
            android:background="@null"
            android:gravity="center_vertical"
            android:hint="查询关键词:如大海,女人,朋友"/>

        <Button
            android:id="@+id/dm_btn"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="dm_btn"
            android:padding="1dp"
            android:text="查询"/>

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/view_height"
        android:background="@color/Grey_900"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/first_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#ffff0000"
        android:dividerHeight="1dp"/>

</LinearLayout>


text:
require_relative 'custom_accessor'
require_relative 'test_result_parser'
module DATSauce
  class TestResult
    extend CustomAccessor

    custom_attr_accessor :log, :resultsSummary, :startDate, :testRunId, :resultType, :status, :runTime, :scenarioPath, :errorMessage,
                         :failedStep, :id, :endDate, :testId, :screenShotId

    def initialize(results, start_date, run_id, result_type, end_date, test_id, screen_shot_id)
      @resultsSummary = DATSauce::ResultsParser::Cucumber::Test.parse_results results
      @log = JSON.generate results
      @testId = test_id
      @startDate = start_date
      @endDate = end_date
      @testRunId = run_id
      @id = run_id + "#{(Time.now.to_i/1000)+rand(10000)}"
      @resultType = result_type
      @status = @resultsSummary[:status]
      @runTime = @resultsSummary[:runTime]
      @scenarioPath = @resultsSummary[:scenarioPath]
      @screenShotId = screen_shot_id
      if @status == 'failed'
        @errorMessage = @resultsSummary[:errorMessage]
        @failedStep = @resultsSummary[:failedStep]
      end

    end

    def to_hash
      obj = {}
      TestResult.attrs.each do |attr|
        obj[attr] = send(attr)
      end
      obj
    end

    def to_json
      JSON.generate to_hash
    end

    def to_s(log = false)
      str = ''
      TestResult.attrs.each do |attr|
        str << "#{attr}: #{send(attr)}\n" unless attr == :log && !log
      end
      str
    end
  end

end


text:
using System.IO;
using System.Xml;

using DotNetNuke.Services.Authentication;
using DotNetNuke.Services.Installer.Packages;

#endregion

namespace DotNetNuke.Services.Installer.Writers
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The AuthenticationPackageWriter class
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// -----------------------------------------------------------------------------
    public class AuthenticationPackageWriter : PackageWriterBase
    {
		#region "Constructors"

        public AuthenticationPackageWriter(PackageInfo package) : base(package)
        {
            AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID);
            Initialize();
        }

        public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) : base(package)
        {
            AuthSystem = authSystem;
            Initialize();
        }

		#endregion

		#region "Public Properties"

		/// -----------------------------------------------------------------------------
		/// <summary>
		/// Gets the associated Authentication System
		/// </summary>
		/// <value>An AuthenticationInfo object</value>
		/// -----------------------------------------------------------------------------
        public AuthenticationInfo AuthSystem { get; set; }

		#endregion

		#region "Private Methods"

        private void Initialize()
        {
            BasePath = Path.Combine("DesktopModules\\AuthenticationServices", AuthSystem.AuthenticationType);
            AppCodePath = Path.Combine("App_Code\\AuthenticationServices", AuthSystem.AuthenticationType);
            AssemblyPath = "bin";
        }

        private void WriteAuthenticationComponent(XmlWriter writer)
        {
			//Start component Element
            writer.WriteStartElement("component");
            writer.WriteAttributeString("type", "AuthenticationSystem");

            //Start authenticationService Element
            writer.WriteStartElement("authenticationService");

            writer.WriteElementString("type", AuthSystem.AuthenticationType);
            writer.WriteElementString("settingsControlSrc", AuthSystem.SettingsControlSrc);
            writer.WriteElementString("loginControlSrc", AuthSystem.LoginControlSrc);
            writer.WriteElementString("logoffControlSrc", AuthSystem.LogoffControlSrc);

            //End authenticationService Element
            writer.WriteEndElement();

            //End component Element
            writer.WriteEndElement();
        }

		#endregion

        protected override void WriteManifestComponent(XmlWriter writer)
        {
			//Write Authentication Component
            WriteAuthenticationComponent(writer);
        }
    }
}


text:
package dggameComponents;

import java.util.LinkedList;

import base.GameOutputable;
import base.InputResponder;
import base.ActivationStackManager;
import base.Game;
import base.GameStateGenerator;
import base.InputManager;
import base.Player;
import base.PlayerOrder;
import base.StateChangeManager;
import base.TurnManager;

public class DGGame extends Game {

	public DGGame(LinkedList<Player> players, GameOutputable gameOutput) {
		super(players, gameOutput);
	}

	@Override
	protected InputManager createInputManager(InputResponder gameOutput) {
		return new InputManager(gameOutput);
	}

	@Override
	protected PlayerOrder createPlayerOrder(LinkedList<Player> players) {
		return new PlayerOrder(players);
	}

	@Override
	protected TurnManager createTurnManager() {
		return new DGTurnManager();
	}

	@Override
	protected GameStateGenerator createGameStateGenerator() {
		return new GameStateGenerator();
	}

	@Override
	protected StateChangeManager createStateChangeManager() {
		return new StateChangeManager();
	}

	@Override
	protected ActivationStackManager createActivationStackManager() {
		return new ActivationStackManager();
	}

}


text:
//
//  GetAddresses.h
//  GetAddresses
//
//  Created by Srs on 16/6/7.
//  Copyright © 2016年 Srs. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface GetAddresses : NSObject

/*!
 * 获取当前设备ip地址
 */
+ (NSString *) getIPAddresses;

@end


text:
import { getTestBed, TestBed, inject } from '@angular/core/testing';
import { Component } from '@angular/core';

import { DOCUMENT } from '@angular/platform-browser';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AtlantisUiModule } from './atlantis-ui.module.js';

import { dialogService } from './dialog.service.js';

var assert = require('assert');

class dialogTestComponent {
  constructor(document) {
    this.showStandard = false;
    this.showWithOptions = false;
    this.document = document;
  }

  static get annotations() {
    return [
      new Component({
        template: `

          <button type="button" class="btn btn-primary btn-sm" (click)="showStandard = true">
            Default dialog
          </button>
          <atlui-dlg [(show)]="showStandard">

Some text in the dialog.

          </atlui-dlg>

          <button type="button" class="btn btn-primary btn-sm" (click)="showWithOptions = true">
            Default dialog
          </button>
          <atlui-dlg [(show)]="showWithOptions" [isResizable]="true" [width]="600" [height]="450"
            [minWidth]="300" [minHeight]="300" [maxWidth]="1000" [maxHeight]="600" [title]="'dialog Header'">

Some text in the dialog.

          </atlui-dlg>

          <button type="button" class="btn btn-primary btn-sm" (click)="showMaxSize = true">
            Default dialog
          </button>
          <atlui-dlg [container]="document.body" [(show)]="showMaxSize" [isResizable]="true" [width]="600" [height]="450"
            [minWidth]="300" [minHeight]="300" [maxWidth]="2000" [maxHeight]="3000" [title]="'dialog Header'">

Some text in the dialog.

          </atlui-dlg>

          <button type="button" class="btn btn-primary btn-sm" (click)="showinfMinSize = true">
            Default dialog
          </button>
          <atlui-dlg [container]="document.body" [(show)]="showinfMinSize" [isResizable]="true" [width]="200" [height]="200"
            [minWidth]="300" [minHeight]="300" [title]="'dialog Header'">

Some text in the dialog.

          </atlui-dlg>

`
      })
    ];
  }
}
dialogTestComponent.parameters = [DOCUMENT];

describe('dialog', function() {
  var fixture, ds, container;

  beforeEach((function() {
    TestBed.configureTestingModule({
      imports: [AtlantisUiModule.forRoot({}), FormsModule, ReactiveFormsModule],
      declarations: [dialogTestComponent],
      providers: [dialogService]
    });
    TestBed.compileComponents();
  }));

  beforeEach(inject([dialogService], (dialogService)=> {
    ds = dialogService;
    fixture = TestBed.createComponent(dialogTestComponent);
    fixture.detectChanges();
    container = fixture.componentInstance;
  }));

  afterEach(function() {
    getTestBed().resetTestingModule();
  });

  it('should render correct dialog', () => {
    var dlg = document.querySelectorAll('.modal-dialog');
    var dlgContent = dlg[0].querySelector('.modal-content');
    var dlgContent2 = dlg[1].querySelector('.modal-content');
    var dlgContent3 = dlg[2].querySelector('.modal-content');
    var dlgContent4 = dlg[3].querySelector('.modal-content');

    assert.strictEqual(dlg[0].style.display, 'none');
    assert.strictEqual(dlg[0].style.zIndex, '');
    assert.strictEqual(ds.dialogs.length, 0);

    assert.strictEqual(dlgContent.style.width, '300px');
    assert.strictEqual(dlgContent.style.minWidth, '100px');
    if (parseInt(dlgContent.style.maxWidth) >= window.innerWidth) {
      assert.strictEqual(dlgContent.style.maxWidth, window.innerWidth+"px");
    } else {
      assert.strictEqual(dlgContent.style.maxWidth, "");
    }

    assert.strictEqual(dlgContent.style.height, '500px');
    assert.strictEqual(dlgContent.style.minHeight, '100px');
    if (parseInt(dlgContent.style.maxHeight) >= window.innerHeight) {
      assert.strictEqual(dlgContent.style.maxHeight, window.innerHeight+"px");
    } else {
      assert.strictEqual(dlgContent.style.maxHeight, "");
    }

    assert.strictEqual(dlgContent2.style.width, '600px');
    assert.strictEqual(dlgContent2.style.minWidth, '300px');
    if (parseInt(dlgContent2.style.maxWidth) >= window.innerWidth) {
      assert.strictEqual(dlgContent2.style.maxWidth, window.innerWidth+"px");
    } else {
      assert.strictEqual(dlgContent2.style.maxWidth, "1000px");
    }

    assert.strictEqual(dlgContent2.style.height, '450px');
    assert.strictEqual(dlgContent2.style.minHeight, '300px');
    if (parseInt(dlgContent2.style.maxHeight) >= window.innerHeight) {
      assert.strictEqual(dlgContent2.style.maxHeight, window.innerHeight+"px");
    } else {
      assert.strictEqual(dlgContent2.style.maxHeight, "600px");
    }

    assert.strictEqual(dlgContent3.style.width, '600px');
    assert.strictEqual(dlgContent3.style.minWidth, '300px');
    if (parseInt(dlgContent3.style.maxWidth) >= window.innerWidth) {
      assert.strictEqual(dlgContent3.style.maxWidth, window.innerWidth+"px");
    } else {
      assert.strictEqual(dlgContent3.style.maxWidth, "1000px");
    }

    assert.strictEqual(dlgContent3.style.height, '450px');
    assert.strictEqual(dlgContent3.style.minHeight, '300px');
    if (parseInt(dlgContent3.style.maxHeight) >= window.innerHeight) {
      assert.strictEqual(dlgContent3.style.maxHeight, window.innerHeight+"px");
    } else if (parseInt(dlgContent3.style.maxHeight) >= document.body.offsetHeight) {
      assert.strictEqual(dlgContent3.style.maxHeight, document.body.offsetHeight+"px");
    } else {
      assert.strictEqual(dlgContent3.style.maxHeight, "600px");
    }

    assert.strictEqual(dlgContent4.style.width, '300px');
    assert.strictEqual(dlgContent4.style.minWidth, '300px');
    if (parseInt(dlgContent4.style.maxWidth) >= window.innerWidth) {
      assert.strictEqual(dlgContent4.style.maxWidth, window.innerWidth+"px");
    } else {
      assert.strictEqual(dlgContent4.style.maxWidth, "1000px");
    }

    assert.strictEqual(dlgContent4.style.height, '300px');
    assert.strictEqual(dlgContent4.style.minHeight, '300px');
    if (parseInt(dlgContent4.style.maxHeight) >= window.innerHeight) {
      assert.strictEqual(dlgContent4.style.maxHeight, window.innerHeight+"px");
    } else if (parseInt(dlgContent4.style.maxHeight) >= document.body.offsetHeight) {
      assert.strictEqual(dlgContent4.style.maxHeight, document.body.offsetHeight+"px");
    } else {
      assert.strictEqual(dlgContent4.style.maxHeight, "600px");
    }

  });

  it('should show on button click then close on close button click', () => {
    var button = document.querySelector('#standard button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, true);

    var dlg = document.querySelectorAll('.modal-dialog');
    var closeButton = dlg[0].querySelector(".close");

    assert.strictEqual(dlg[0].style.display, 'block');
    assert.strictEqual(dlg[0].style.zIndex, '980');

    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 0);
    assert.strictEqual(container.showStandard, false);
    button = document.querySelector('#withOptions button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showWithOptions, true);

    assert.strictEqual(dlg[1].style.display, 'block');
    assert.strictEqual(dlg[1].style.zIndex, '980');

    closeButton = dlg[1].querySelector(".close");
    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 0);
    assert.strictEqual(container.showWithOptions, false);
  });

  it('should open multiple dialog', () => {
    var button = document.querySelector('#standard button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, true);

    var dlg = document.querySelectorAll('.modal-dialog');

    button = document.querySelector('#withOptions button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 2);
    assert.strictEqual(container.showWithOptions, true);

    var closeButton = dlg[0].querySelector(".close");
    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, false);

    closeButton = dlg[1].querySelector(".close");
    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 0);
    assert.strictEqual(container.showWithOptions, false);
  });

  it('should focus on click', () => {
    var button = document.querySelector('#standard button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, true);

    var dlg = document.querySelectorAll('.modal-dialog');

    button = document.querySelector('#withOptions button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 2);
    assert.strictEqual(container.showWithOptions, true);

    assert.strictEqual(dlg[0].style.zIndex, "980");
    assert.strictEqual(dlg[1].style.zIndex, "981");

    var mousedown = new Event('mousedown', { 'bubbles': true });

    dlg[0].querySelector('.modal-content').dispatchEvent(mousedown);
    fixture.detectChanges();

    assert.strictEqual(dlg[0].style.zIndex, "981");
    assert.strictEqual(dlg[1].style.zIndex, "980");

    var closeButton = dlg[0].querySelector(".close");
    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, false);

    closeButton = dlg[1].querySelector(".close");
    closeButton.click();
    fixture.detectChanges();

    assert.strictEqual(ds.dialogs.length, 0);
    assert.strictEqual(container.showWithOptions, false);
  });

  it('should move when drag on modal-header', () => {
    var button = document.querySelector('#standard button');
    button.click();
    fixture.detectChanges();
    assert.strictEqual(ds.dialogs.length, 1);
    assert.strictEqual(container.showStandard, true);

    var draggable = document.querySelector(".modal-header");

    var mousedown = new Event('mousedown', { 'bubbles': true });
    mousedown.clientX = 10;
    mousedown.clientY = 5;

    draggable.dispatchEvent(mousedown);
    fixture.detectChanges();

    var dlg = document.querySelector(".modal-dialog");

    var draggableStyle1 = window.getComputedStyle(dlg);

    assert.strictEqual(draggableStyle1.getPropertyValue('z-index'), '99999');
    var top = draggableStyle1.getPropertyValue('top');
    var left = draggableStyle1.getPropertyValue('left');

    var mouseMove = new Event('mousemove', {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: 50,
      clientY: 20
    });

    draggable.dispatchEvent(mouseMove);
    fixture.detectChanges();

    var mouseUp = new Event('mouseup', { 'bubbles': true });
    draggable.dispatchEvent(mouseUp);
    fixture.detectChanges();
    var draggableTop1 = draggableStyle1.getPropertyValue("top");
    var draggableLeft1 = draggableStyle1.getPropertyValue("left");

    assert.strictEqual(draggableTop1, top);
    assert.strictEqual(draggableLeft1, left);
    assert.strictEqual(draggableStyle1.getPropertyValue('z-index'), '980');

  });

});


text:
#include <Modules/Legacy/Fields/ClipFieldByMesh.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VField.h>

#include <Core/Algorithms/Legacy/Fields/ClipMesh/ClipMeshBySelection.h>
#include <Core/Algorithms/Legacy/Fields/DistanceField/CalculateIsInsideField.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>

using namespace SCIRun;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;

MODULE_INFO_DEF(ClipFieldByMesh, NewField, SCIRun)

/// @class ClipFieldByMesh
/// @brief Clip a mesh to another mesh.

ClipFieldByMesh::ClipFieldByMesh() : Module(staticInfo_, false)
{
  INITIALIZE_PORT(InputField);
  INITIALIZE_PORT(ObjectField);
  INITIALIZE_PORT(OutputField);
  INITIALIZE_PORT(Mapping);
}

void ClipFieldByMesh::execute()
{
  auto input = getRequiredInput(InputField);
  FieldHandle output;
  auto object = getRequiredInput(ObjectField);
  FieldHandle selection;
  MatrixHandle interpolant;

  if (needToExecute())
  {
    //TODO: two-algo module

    CalculateIsInsideFieldAlgo insideAlgo;
    //insideAlgo.setLogger(getLogger());

    insideAlgo.setOption(Parameters::FieldOutputType, "char");
    insideAlgo.setOption(Parameters::SamplingScheme, "regular2");

    if (!insideAlgo.runImpl(input,object,selection))
    {
      THROW_ALGORITHM_PROCESSING_ERROR("False returned from inside algo");
    }

    ClipMeshBySelectionAlgo clipAlgo;
    if (!selection || !selection->vfield() || !input->vmesh())
    {
      THROW_ALGORITHM_PROCESSING_ERROR("Selection output field is null");
    }

    if (input->vmesh()->num_elems() == selection->vfield()->num_values())
      clipAlgo.setOption(Parameters::ClipMethod, "Element Center");

    if (!clipAlgo.runImpl(input,selection,output,interpolant))
    {
      THROW_ALGORITHM_PROCESSING_ERROR("False returned from clip algo");
    }

    sendOutput(OutputField, output);
    sendOutput(Mapping, interpolant);
  }
}


text:
.class public final Landroid/support/v7/media/MediaRouterJellybean$SelectRouteWorkaround;
.super Ljava/lang/Object;
.source "MediaRouterJellybean.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v7/media/MediaRouterJellybean;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "SelectRouteWorkaround"
.end annotation

# instance fields
.field private mSelectRouteIntMethod:Ljava/lang/reflect/Method;

# direct methods
.method public constructor <init>()V
    .locals 6

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    sget v1, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v2, 0x10

    if-lt v1, v2, :cond_0

    sget v1, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v2, 0x11

    if-le v1, v2, :cond_1

    :cond_0
    new-instance v1, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v1}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v1

    :cond_1
    :try_start_0
    const-class v1, Landroid/media/MediaRouter;

    const-string/jumbo v2, "selectRouteInt"

    const/4 v3, 0x2

    new-array v3, v3, [Ljava/lang/Class;

    sget-object v4, Ljava/lang/Integer;->TYPE:Ljava/lang/Class;

    const/4 v5, 0x0

    aput-object v4, v3, v5

    const-class v4, Landroid/media/MediaRouter$RouteInfo;

    const/4 v5, 0x1

    aput-object v4, v3, v5

    invoke-virtual {v1, v2, v3}, Ljava/lang/Class;->getMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v1

    iput-object v1, p0, Landroid/support/v7/media/MediaRouterJellybean$SelectRouteWorkaround;->mSelectRouteIntMethod:Ljava/lang/reflect/Method;
    :try_end_0
    .catch Ljava/lang/NoSuchMethodException; {:try_start_0 .. :try_end_0} :catch_0

    :goto_0
    return-void

    :catch_0
    move-exception v0

    goto :goto_0
.end method

# virtual methods
.method public selectRoute(Ljava/lang/Object;ILjava/lang/Object;)V
    .locals 9

    move-object v4, p1

    check-cast v4, Landroid/media/MediaRouter;

    move-object v2, p3

    check-cast v2, Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v2}, Landroid/media/MediaRouter$RouteInfo;->getSupportedTypes()I

    move-result v3

    const/high16 v5, 0x800000

    and-int/2addr v5, v3

    if-nez v5, :cond_0

    iget-object v5, p0, Landroid/support/v7/media/MediaRouterJellybean$SelectRouteWorkaround;->mSelectRouteIntMethod:Ljava/lang/reflect/Method;

    if-eqz v5, :cond_1

    :try_start_0
    iget-object v5, p0, Landroid/support/v7/media/MediaRouterJellybean$SelectRouteWorkaround;->mSelectRouteIntMethod:Ljava/lang/reflect/Method;

    const/4 v6, 0x2

    new-array v6, v6, [Ljava/lang/Object;

    invoke-static {p2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v7

    const/4 v8, 0x0

    aput-object v7, v6, v8

    const/4 v7, 0x1

    aput-object v2, v6, v7

    invoke-virtual {v5, v4, v6}, Ljava/lang/reflect/Method;->invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/lang/reflect/InvocationTargetException; {:try_start_0 .. :try_end_0} :catch_0

    return-void

    :catch_0
    move-exception v1

    const-string/jumbo v5, "MediaRouterJellybean"

    const-string/jumbo v6, "Cannot programmatically select non-user route.  Media routing may not work."

    invoke-static {v5, v6, v1}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    :cond_0
    :goto_0
    invoke-virtual {v4, p2, v2}, Landroid/media/MediaRouter;->selectRoute(ILandroid/media/MediaRouter$RouteInfo;)V

    return-void

    :catch_1
    move-exception v0

    const-string/jumbo v5, "MediaRouterJellybean"

    const-string/jumbo v6, "Cannot programmatically select non-user route.  Media routing may not work."

    invoke-static {v5, v6, v0}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    :cond_1
    const-string/jumbo v5, "MediaRouterJellybean"

    const-string/jumbo v6, "Cannot programmatically select non-user route because the platform is missing the selectRouteInt() method.  Media routing may not work."

    invoke-static {v5, v6}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method


text:
package com.hazelcast.collection.impl.list.operations;

import com.hazelcast.collection.impl.collection.CollectionDataSerializerHook;
import com.hazelcast.collection.impl.collection.CollectionItem;
import com.hazelcast.collection.impl.collection.operations.CollectionAddBackupOperation;
import com.hazelcast.collection.impl.collection.operations.CollectionAddOperation;
import com.hazelcast.collection.impl.list.ListContainer;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.Operation;

import java.io.IOException;

public class ListAddOperation extends CollectionAddOperation {

    private int index = -1;

    public ListAddOperation() {
    }

    public ListAddOperation(String name, int index, Data value) {
        super(name, value);
        this.index = index;
    }

    @Override
    public void run() throws Exception {
        final ListContainer listContainer = getOrCreateListContainer();
        response = false;
        if (!hasEnoughCapacity(1)) {
            return;
        }

        final CollectionItem item = listContainer.add(index, value);
        if (item != null) {
            itemId = item.getItemId();
            response = true;
        }
    }

    @Override
    public Operation getBackupOperation() {
        return new CollectionAddBackupOperation(name, itemId, value);
    }

    @Override
    public int getClassId() {
        return CollectionDataSerializerHook.LIST_ADD;
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeInt(index);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        index = in.readInt();
    }
}


text:
using System;
using EasyNetQ.ChannelDispatcher;
using EasyNetQ.Consumer;
using EasyNetQ.Persistent;
using EasyNetQ.Producer;
using FluentAssertions;
using NSubstitute;
using RabbitMQ.Client;
using Xunit;

namespace EasyNetQ.Tests.ChannelDispatcherTests;

public class When_an_action_is_invoked_using_multi_channel : IDisposable
{
    private readonly IPersistentChannelDispatcher dispatcher;
    private readonly IPersistentChannelFactory channelFactory;
    private readonly int actionResult;
    private readonly IProducerConnection producerConnection;

    public When_an_action_is_invoked_using_multi_channel()
    {
        channelFactory = Substitute.For<IPersistentChannelFactory>();
        producerConnection = Substitute.For<IProducerConnection>();
        var consumerConnection = Substitute.For<IConsumerConnection>();
        var channel = Substitute.For<IPersistentChannel>();
        var action = Substitute.For<Func<IModel, int>>();
        channelFactory.CreatePersistentChannel(producerConnection, new PersistentChannelOptions()).Returns(channel);
        channel.InvokeChannelActionAsync(action).Returns(42);

        dispatcher = new MultiPersistentChannelDispatcher(1, producerConnection, consumerConnection, channelFactory);
        actionResult = dispatcher.InvokeAsync(action, PersistentChannelDispatchOptions.ProducerTopology)
            .GetAwaiter()
            .GetResult();
    }

    public void Dispose()
    {
        dispatcher.Dispose();
    }

    [Fact]
    public void Should_create_a_persistent_channel()
    {
        channelFactory.Received().CreatePersistentChannel(producerConnection, new PersistentChannelOptions());
    }

    [Fact]
    public void Should_receive_action_result()
    {
        actionResult.Should().Be(42);
    }
}

// ReSharper restore InconsistentNaming


text:
#include "THGeneral.h"

/* Torch Error Handling */
static void defaultTorchErrorHandlerFunction(const char *msg)
{
  printf("$ Error: %s\n", msg);
  exit(-1);
}

static void (*torchErrorHandlerFunction)(const char *msg) = defaultTorchErrorHandlerFunction;

void THError(const char *fmt, ...)
{
  static char msg[1024];
  va_list args;

  /* vasprintf not standard */
  /* vsnprintf: how to handle if does not exists? */
  va_start(args, fmt);
  vsnprintf(msg, 1024, fmt, args);
  va_end(args);

  (*torchErrorHandlerFunction)(msg);
}

void THSetErrorHandler( void (*torchErrorHandlerFunction_)(const char *msg) )
{
  if(torchErrorHandlerFunction_)
    torchErrorHandlerFunction = torchErrorHandlerFunction_;
  else
    torchErrorHandlerFunction = defaultTorchErrorHandlerFunction;
}

/* Torch Arg Checking Handling */
static void defaultTorchArgCheckHandlerFunction(int condition, int argNumber, const char *msg)
{
  if(!condition)
  {
    if(msg)
      printf("$ Invalid argument %d: %s\n", argNumber, msg);
    else
      printf("$ Invalid argument %d\n", argNumber);
    exit(-1);
  }
}
static void (*torchArgCheckHandlerFunction)(int condition, int argNumber, const char *msg) = defaultTorchArgCheckHandlerFunction;

void THArgCheck(int condition, int argNumber, const char *msg)
{
  (*torchArgCheckHandlerFunction)(condition, argNumber, msg);
}

void THSetArgCheckHandler( void (*torchArgCheckHandlerFunction_)(int condition, int argNumber, const char *msg) )
{
  if(torchArgCheckHandlerFunction_)
    torchArgCheckHandlerFunction = torchArgCheckHandlerFunction_;
  else
    torchArgCheckHandlerFunction = defaultTorchArgCheckHandlerFunction;
}

void* THAlloc(long size)
{
  void *ptr;

  if(size < 0)
    THError("$ Torch: invalid memory size -- maybe an overflow?");

  if(size == 0)
    return NULL;

  ptr = malloc(size);
  if(!ptr)
    THError("$ Torch: not enough memory: you tried to allocate %dGB. Buy new RAM!", size/1073741824);

  return ptr;
}

void* THRealloc(void *ptr, long size)
{
  if(!ptr)
    return(THAlloc(size));

  if(size == 0)
  {
    THFree(ptr);
    return NULL;
  }

  if(size < 0)
    THError("$ Torch: invalid memory size -- maybe an overflow?");

  ptr = realloc(ptr, size);
  if(!ptr)
    THError("$ Torch: not enough memory: you tried to reallocate %dGB. Buy new RAM!", size/1073741824);
  return ptr;
}

void THFree(void *ptr)
{
  free(ptr);
}

#ifdef _MSC_VER
double log1p(const double x)
{
  volatile double y;
  y = 1 + x;
  return log(y) - ((y-1)-x)/y ;  /* cancels errors with IEEE arithmetic */
}
#endif