text:
#include <stdio.h>
#include <stdlib.h>

#include "intltest.h"

#if !UCONFIG_NO_FORMATTING && !UCONFIG_NO_BREAK_ITERATION

#include "unicode/localpointer.h"
#include "unicode/numfmt.h"
#include "unicode/reldatefmt.h"
#include "cmemory.h"

static const char *DirectionStr(UDateDirection direction);
static const char *RelativeUnitStr(UDateRelativeUnit unit);
static const char *AbsoluteUnitStr(UDateAbsoluteUnit unit);

typedef struct WithQuantityExpected {
    double value;
    UDateDirection direction;
    UDateRelativeUnit unit;
    const char *expected;
} WithQuantityExpected;

typedef struct WithoutQuantityExpected {
    UDateDirection direction;
    UDateAbsoluteUnit unit;
    const char *expected;
} WithoutQuantityExpected;

static WithQuantityExpected kEnglish[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0 seconds"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0.5 seconds"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 1 second"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 2 seconds"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 0 minutes"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 0.5 minutes"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 1 minute"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 2 minutes"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 0 hours"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 0.5 hours"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 1 hour"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 2 hours"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 0 days"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 0.5 days"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 1 day"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 2 days"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 0 weeks"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 0.5 weeks"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 1 week"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 2 weeks"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 0 months"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 0.5 months"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 1 month"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 2 months"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 0 years"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 0.5 years"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 1 year"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 2 years"},

        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0 seconds ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0.5 seconds ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "1 second ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "2 seconds ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0 minutes ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0.5 minutes ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "1 minute ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "2 minutes ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0 hours ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0.5 hours ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "1 hour ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "2 hours ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0 days ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0.5 days ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "1 day ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "2 days ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0 weeks ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0.5 weeks ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "1 week ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "2 weeks ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0 months ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0.5 months ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "1 month ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "2 months ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0 years ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0.5 years ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "1 year ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "2 years ago"}
};

static WithQuantityExpected kEnglishCaps[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "In 0 seconds"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "In 0.5 seconds"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "In 1 second"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "In 2 seconds"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "In 0 minutes"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "In 0.5 minutes"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "In 1 minute"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "In 2 minutes"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "In 0 hours"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "In 0.5 hours"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "In 1 hour"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "In 2 hours"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "In 0 days"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "In 0.5 days"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "In 1 day"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "In 2 days"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "In 0 weeks"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "In 0.5 weeks"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "In 1 week"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "In 2 weeks"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "In 0 months"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "In 0.5 months"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "In 1 month"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "In 2 months"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "In 0 years"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "In 0.5 years"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "In 1 year"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "In 2 years"},

        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0 seconds ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0.5 seconds ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "1 second ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "2 seconds ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0 minutes ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0.5 minutes ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "1 minute ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "2 minutes ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0 hours ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0.5 hours ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "1 hour ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "2 hours ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0 days ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0.5 days ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "1 day ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "2 days ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0 weeks ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0.5 weeks ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "1 week ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "2 weeks ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0 months ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0.5 months ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "1 month ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "2 months ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0 years ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0.5 years ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "1 year ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "2 years ago"}
};

static WithQuantityExpected kEnglishShort[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0 sec."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0.5 sec."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 1 sec."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 2 sec."},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 0 min."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 0.5 min."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 1 min."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MINUTES, "in 2 min."},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 0 hr."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 0.5 hr."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 1 hr."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_HOURS, "in 2 hr."},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 0 days"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 0.5 days"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 1 day"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, "in 2 days"},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 0 wk."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 0.5 wk."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 1 wk."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_WEEKS, "in 2 wk."},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 0 mo."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 0.5 mo."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 1 mo."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "in 2 mo."},
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 0 yr."},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 0.5 yr."},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 1 yr."},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_YEARS, "in 2 yr."},

        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0 sec. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "0.5 sec. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "1 sec. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_SECONDS, "2 sec. ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0 min. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "0.5 min. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "1 min. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MINUTES, "2 min. ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0 hr. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "0.5 hr. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "1 hr. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_HOURS, "2 hr. ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0 days ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "0.5 days ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "1 day ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_DAYS, "2 days ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0 wk. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "0.5 wk. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "1 wk. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_WEEKS, "2 wk. ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0 mo. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "0.5 mo. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "1 mo. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_MONTHS, "2 mo. ago"},
        {0.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0 yr. ago"},
        {0.5, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "0.5 yr. ago"},
        {1.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "1 yr. ago"},
        {2.0, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, "2 yr. ago"}
};

static WithQuantityExpected kEnglishDecimal[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0.0 seconds"},
        {0.5, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 0.5 seconds"},
        {1.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 1.0 seconds"},
        {2.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_SECONDS, "in 2.0 seconds"}
};

static WithQuantityExpected kSerbian[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 0 \\u043c\\u0435\\u0441\\u0435\\u0446\\u0438"},
        {1.2, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 1,2 \\u043c\\u0435\\u0441\\u0435\\u0446\\u0430"},
        {21.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 21 \\u043c\\u0435\\u0441\\u0435\\u0446"}
};

static WithQuantityExpected kSerbianNarrow[] = {
        {0.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 0 \\u043c."},
        {1.2, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 1,2 \\u043c."},
        {21.0, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_MONTHS, "\\u0437\\u0430 21 \\u043c."}
};

static WithoutQuantityExpected kEnglishNoQuantity[] = {
        {UDAT_DIRECTION_NEXT_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, "tomorrow"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEEK, "next week"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONTH, "next month"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_YEAR, "next year"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONDAY, "next Monday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_TUESDAY, "next Tuesday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEDNESDAY, "next Wednesday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_THURSDAY, "next Thursday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_FRIDAY, "next Friday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SATURDAY, "next Saturday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, "next Sunday"},

        {UDAT_DIRECTION_LAST_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, "yesterday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEEK, "last week"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONTH, "last month"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_YEAR, "last year"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONDAY, "last Monday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_TUESDAY, "last Tuesday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEDNESDAY, "last Wednesday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_THURSDAY, "last Thursday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_FRIDAY, "last Friday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SATURDAY, "last Saturday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, "last Sunday"},

        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, "today"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEEK, "this week"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONTH, "this month"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_YEAR, "this year"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONDAY, "this Monday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_TUESDAY, "this Tuesday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEDNESDAY, "this Wednesday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_THURSDAY, "this Thursday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_FRIDAY, "this Friday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SATURDAY, "this Saturday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, "this Sunday"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_DAY, "day"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEEK, "week"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONTH, "month"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_YEAR, "year"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONDAY, "Monday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_TUESDAY, "Tuesday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEDNESDAY, "Wednesday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_THURSDAY, "Thursday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_FRIDAY, "Friday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SATURDAY, "Saturday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, "Sunday"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, "now"}
};

static WithoutQuantityExpected kEnglishNoQuantityCaps[] = {
        {UDAT_DIRECTION_NEXT_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, "Tomorrow"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEEK, "Next week"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONTH, "Next month"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_YEAR, "Next year"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONDAY, "Next Monday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_TUESDAY, "Next Tuesday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEDNESDAY, "Next Wednesday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_THURSDAY, "Next Thursday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_FRIDAY, "Next Friday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SATURDAY, "Next Saturday"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, "Next Sunday"},

        {UDAT_DIRECTION_LAST_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, "Yesterday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEEK, "Last week"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONTH, "Last month"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_YEAR, "Last year"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONDAY, "Last Monday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_TUESDAY, "Last Tuesday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEDNESDAY, "Last Wednesday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_THURSDAY, "Last Thursday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_FRIDAY, "Last Friday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SATURDAY, "Last Saturday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, "Last Sunday"},

        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, "Today"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEEK, "This week"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONTH, "This month"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_YEAR, "This year"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONDAY, "This Monday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_TUESDAY, "This Tuesday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEDNESDAY, "This Wednesday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_THURSDAY, "This Thursday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_FRIDAY, "This Friday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SATURDAY, "This Saturday"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, "This Sunday"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_DAY, "Day"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEEK, "Week"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONTH, "Month"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_YEAR, "Year"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONDAY, "Monday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_TUESDAY, "Tuesday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEDNESDAY, "Wednesday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_THURSDAY, "Thursday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_FRIDAY, "Friday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SATURDAY, "Saturday"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, "Sunday"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, "Now"}
};

static WithoutQuantityExpected kEnglishNoQuantityShort[] = {
        {UDAT_DIRECTION_NEXT_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, "tomorrow"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEEK, "next wk."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONTH, "next mo."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_YEAR, "next yr."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONDAY, "next Mon."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_TUESDAY, "next Tue."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEDNESDAY, "next Wed."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_THURSDAY, "next Thu."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_FRIDAY, "next Fri."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SATURDAY, "next Sat."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, "next Sun."},

        {UDAT_DIRECTION_LAST_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, "yesterday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEEK, "last wk."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONTH, "last mo."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_YEAR, "last yr."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONDAY, "last Mon."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_TUESDAY, "last Tue."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEDNESDAY, "last Wed."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_THURSDAY, "last Thu."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_FRIDAY, "last Fri."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SATURDAY, "last Sat."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, "last Sun."},

        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, "today"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEEK, "this wk."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONTH, "this mo."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_YEAR, "this yr."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONDAY, "this Mon."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_TUESDAY, "this Tue."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEDNESDAY, "this Wed."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_THURSDAY, "this Thu."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_FRIDAY, "this Fri."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SATURDAY, "this Sat."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, "this Sun."},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_DAY, "day"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEEK, "wk."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONTH, "mo."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_YEAR, "yr."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONDAY, "Mo"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_TUESDAY, "Tu"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEDNESDAY, "We"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_THURSDAY, "Th"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_FRIDAY, "Fr"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SATURDAY, "Sa"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, "Su"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, "now"}
};

static WithoutQuantityExpected kEnglishNoQuantityNarrow[] = {
        {UDAT_DIRECTION_NEXT_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, "tomorrow"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEEK, "next wk."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONTH, "next mo."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_YEAR, "next yr."},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_MONDAY, "next M"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_TUESDAY, "next Tu"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_WEDNESDAY, "next W"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_THURSDAY, "next Th"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_FRIDAY, "next F"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SATURDAY, "next Sa"},
        {UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, "next Su"},

        {UDAT_DIRECTION_LAST_2, UDAT_ABSOLUTE_DAY, ""},

        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, "yesterday"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEEK, "last wk."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONTH, "last mo."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_YEAR, "last yr."},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_MONDAY, "last M"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_TUESDAY, "last Tu"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_WEDNESDAY, "last W"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_THURSDAY, "last Th"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_FRIDAY, "last F"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SATURDAY, "last Sa"},
        {UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, "last Su"},

        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, "today"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEEK, "this wk."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONTH, "this mo."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_YEAR, "this yr."},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_MONDAY, "this M"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_TUESDAY, "this Tu"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_WEDNESDAY, "this W"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_THURSDAY, "this Th"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_FRIDAY, "this F"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SATURDAY, "this Sa"},
        {UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, "this Su"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_DAY, "day"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEEK, "wk."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONTH, "mo."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_YEAR, "yr."},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_MONDAY, "M"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_TUESDAY, "T"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_WEDNESDAY, "W"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_THURSDAY, "T"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_FRIDAY, "F"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SATURDAY, "S"},
        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, "S"},

        {UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, "now"}
};

static WithoutQuantityExpected kSpanishNoQuantity[] = {
        {UDAT_DIRECTION_NEXT_2, UDAT_ABSOLUTE_DAY, "pasado ma\\u00F1ana"},
        {UDAT_DIRECTION_LAST_2, UDAT_ABSOLUTE_DAY, "anteayer"}
};

class RelativeDateTimeFormatterTest : public IntlTest {
public:
    RelativeDateTimeFormatterTest() {
    }

    void runIndexedTest(int32_t index, UBool exec, const char *&name, char *par=0);
private:
    void TestEnglish();
    void TestEnglishCaps();
    void TestEnglishShort();
    void TestEnglishNarrow();
    void TestSerbian();
    void TestSerbianFallback();
    void TestEnglishNoQuantity();
    void TestEnglishNoQuantityCaps();
    void TestEnglishNoQuantityShort();
    void TestEnglishNoQuantityNarrow();
    void TestSpanishNoQuantity();
    void TestFormatWithQuantityIllegalArgument();
    void TestFormatWithoutQuantityIllegalArgument();
    void TestCustomNumberFormat();
    void TestGetters();
    void TestCombineDateAndTime();
    void TestBadDisplayContext();
    void RunTest(
            const Locale& locale,
            const WithQuantityExpected* expectedResults,
            int32_t expectedResultLength);
    void RunTest(
            const Locale& locale,
            UDateRelativeDateTimeFormatterStyle style,
            const WithQuantityExpected* expectedResults,
            int32_t expectedResultLength);
    void RunTest(
            const Locale& locale,
            const WithoutQuantityExpected* expectedResults,
            int32_t expectedResultLength);
    void RunTest(
            const Locale& locale,
            UDateRelativeDateTimeFormatterStyle style,
            const WithoutQuantityExpected* expectedResults,
            int32_t expectedResultLength);
    void RunTest(
            const RelativeDateTimeFormatter& fmt,
            const WithQuantityExpected* expectedResults,
            int32_t expectedResultLength,
            const char *description);
    void RunTest(
            const RelativeDateTimeFormatter& fmt,
            const WithoutQuantityExpected* expectedResults,
            int32_t expectedResultLength,
            const char *description);
    void CheckExpectedResult(
            const RelativeDateTimeFormatter& fmt,
            const WithQuantityExpected& expectedResult,
            const char* description);
    void CheckExpectedResult(
            const RelativeDateTimeFormatter& fmt,
            const WithoutQuantityExpected& expectedResult,
            const char* description);
    void VerifyIllegalArgument(
            const RelativeDateTimeFormatter& fmt,
            UDateDirection direction,
            UDateRelativeUnit unit);
    void VerifyIllegalArgument(
            const RelativeDateTimeFormatter& fmt,
            UDateDirection direction,
            UDateAbsoluteUnit unit);
};

void RelativeDateTimeFormatterTest::runIndexedTest(
        int32_t index, UBool exec, const char *&name, char *) {
    if (exec) {
        logln("TestSuite RelativeDateTimeFormatterTest: ");
    }
    TESTCASE_AUTO_BEGIN;
    TESTCASE_AUTO(TestEnglish);
    TESTCASE_AUTO(TestEnglishCaps);
    TESTCASE_AUTO(TestEnglishShort);
    TESTCASE_AUTO(TestEnglishNarrow);
    TESTCASE_AUTO(TestSerbian);
    TESTCASE_AUTO(TestSerbianFallback);
    TESTCASE_AUTO(TestEnglishNoQuantity);
    TESTCASE_AUTO(TestEnglishNoQuantityCaps);
    TESTCASE_AUTO(TestEnglishNoQuantityShort);
    TESTCASE_AUTO(TestEnglishNoQuantityNarrow);
    TESTCASE_AUTO(TestSpanishNoQuantity);
    TESTCASE_AUTO(TestFormatWithQuantityIllegalArgument);
    TESTCASE_AUTO(TestFormatWithoutQuantityIllegalArgument);
    TESTCASE_AUTO(TestCustomNumberFormat);
    TESTCASE_AUTO(TestGetters);
    TESTCASE_AUTO(TestCombineDateAndTime);
    TESTCASE_AUTO(TestBadDisplayContext);
    TESTCASE_AUTO_END;
}

void RelativeDateTimeFormatterTest::TestEnglish() {
    RunTest("en", kEnglish, UPRV_LENGTHOF(kEnglish));
}

void RelativeDateTimeFormatterTest::TestEnglishCaps() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            "en",
            NULL,
            UDAT_STYLE_LONG,
            UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE,
            status);
    if (U_FAILURE(status)) {
        dataerrln("Failed call to RelativeDateTimeFormatter(\"en\", NULL, UDAT_STYLE_LONG, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, status); : %s", u_errorName(status));
        return;
    }
    RelativeDateTimeFormatter fmt3(status);

    // Test assignment and copy constructor with capitalization on.
    RelativeDateTimeFormatter fmt2(fmt);
    fmt3 = fmt2;
    assertSuccess("", status);
    RunTest(fmt3, kEnglishCaps, UPRV_LENGTHOF(kEnglishCaps), "en caps");
}

void RelativeDateTimeFormatterTest::TestEnglishShort() {
    RunTest("en", UDAT_STYLE_SHORT, kEnglishShort, UPRV_LENGTHOF(kEnglishShort));
}

void RelativeDateTimeFormatterTest::TestEnglishNarrow() {
    RunTest("en", UDAT_STYLE_NARROW, kEnglishShort, UPRV_LENGTHOF(kEnglishShort));
}

void RelativeDateTimeFormatterTest::TestSerbian() {
    RunTest("sr", kSerbian, UPRV_LENGTHOF(kSerbian));
}

void RelativeDateTimeFormatterTest::TestSerbianFallback() {
    RunTest("sr", UDAT_STYLE_NARROW, kSerbianNarrow, UPRV_LENGTHOF(kSerbianNarrow));
}

void RelativeDateTimeFormatterTest::TestEnglishNoQuantity() {
    RunTest("en", kEnglishNoQuantity, UPRV_LENGTHOF(kEnglishNoQuantity));
}

void RelativeDateTimeFormatterTest::TestEnglishNoQuantityCaps() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            "en",
            NULL,
            UDAT_STYLE_LONG,
            UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE,
            status);
    if (assertSuccess("RelativeDateTimeFormatter", status, TRUE) == FALSE) {
        return;
    }
    RunTest(
            fmt,
            kEnglishNoQuantityCaps,
            UPRV_LENGTHOF(kEnglishNoQuantityCaps),
            "en caps no quantity");
}

void RelativeDateTimeFormatterTest::TestEnglishNoQuantityShort() {
    RunTest(
            "en",
            UDAT_STYLE_SHORT,
            kEnglishNoQuantityShort,
            UPRV_LENGTHOF(kEnglishNoQuantityShort));
}

void RelativeDateTimeFormatterTest::TestEnglishNoQuantityNarrow() {
    RunTest(
            "en",
            UDAT_STYLE_NARROW,
            kEnglishNoQuantityNarrow,
            UPRV_LENGTHOF(kEnglishNoQuantityNarrow));
}

void RelativeDateTimeFormatterTest::TestSpanishNoQuantity() {
    RunTest("es", kSpanishNoQuantity, UPRV_LENGTHOF(kSpanishNoQuantity));
}

void RelativeDateTimeFormatterTest::TestFormatWithQuantityIllegalArgument() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt("en", status);
    if (U_FAILURE(status)) {
        dataerrln("Failure creating format object - %s", u_errorName(status));
        return;
    }
    VerifyIllegalArgument(fmt, UDAT_DIRECTION_PLAIN, UDAT_RELATIVE_DAYS);
    VerifyIllegalArgument(fmt, UDAT_DIRECTION_THIS, UDAT_RELATIVE_DAYS);
}

void RelativeDateTimeFormatterTest::TestFormatWithoutQuantityIllegalArgument() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt("en", status);
    if (U_FAILURE(status)) {
        dataerrln("Failure creating format object - %s", u_errorName(status));
        return;
    }
    VerifyIllegalArgument(fmt, UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_NOW);
    VerifyIllegalArgument(fmt, UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_NOW);
    VerifyIllegalArgument(fmt, UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_NOW);
}

void RelativeDateTimeFormatterTest::TestCustomNumberFormat() {
    NumberFormat *nf;
    UErrorCode status = U_ZERO_ERROR;
    {
        RelativeDateTimeFormatter fmt("en", status);
        if (U_FAILURE(status)) {
            dataerrln(
                    "Failure creating format object - %s", u_errorName(status));
            return;
        }
        nf = (NumberFormat *) fmt.getNumberFormat().clone();
    }
    nf->setMinimumFractionDigits(1);
    nf->setMaximumFractionDigits(1);
    RelativeDateTimeFormatter fmt("en", nf, status);

    // Test copy constructor.
    RelativeDateTimeFormatter fmt2(fmt);
    RunTest(fmt2, kEnglishDecimal, UPRV_LENGTHOF(kEnglishDecimal), "en decimal digits");

    // Test assignment
    fmt = RelativeDateTimeFormatter("es", status);
    RunTest(fmt, kSpanishNoQuantity, UPRV_LENGTHOF(kSpanishNoQuantity), "assignment operator");

}

void RelativeDateTimeFormatterTest::TestGetters() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            "en",
            NULL,
            UDAT_STYLE_NARROW,
            UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,
            status);
    if (U_FAILURE(status)) {
        dataerrln("Failed call to RelativeDateTimeFormatter(\"en\", NULL, UDAT_STYLE_NARROW, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, status);) : %s", u_errorName(status));
        return;
    }
    RelativeDateTimeFormatter fmt3(status);

    // copy and assignment.
    RelativeDateTimeFormatter fmt2(fmt);
    fmt3 = fmt2;
    assertEquals("style", UDAT_STYLE_NARROW, fmt3.getFormatStyle());
    assertEquals(
            "context",
            UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,
            fmt3.getCapitalizationContext());
    assertSuccess("", status);
}

void RelativeDateTimeFormatterTest::TestCombineDateAndTime() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt("en", status);
    if (U_FAILURE(status)) {
        dataerrln("Failure creating format object - %s", u_errorName(status));
        return;
    }
    UnicodeString actual;
    fmt.combineDateAndTime(
        UnicodeString("yesterday"),
        UnicodeString("3:50"),
        actual,
        status);
    UnicodeString expected("yesterday, 3:50");
    if (expected != actual) {
        errln("Expected "+expected+", got "+actual);
    }
}

void RelativeDateTimeFormatterTest::TestBadDisplayContext() {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            "en", NULL, UDAT_STYLE_LONG, UDISPCTX_STANDARD_NAMES, status);
    if (status != U_ILLEGAL_ARGUMENT_ERROR) {
        errln("Expected U_ILLEGAL_ARGUMENT_ERROR, got %s", u_errorName(status));
    }
}

void RelativeDateTimeFormatterTest::RunTest(
        const Locale& locale,
        const WithQuantityExpected* expectedResults,
        int32_t expectedResultLength) {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(locale, status);
    if (U_FAILURE(status)) {
        dataerrln("Unable to create format object - %s", u_errorName(status));
        return;
    }
    RunTest(fmt, expectedResults, expectedResultLength, locale.getName());
}

void RelativeDateTimeFormatterTest::RunTest(
        const Locale& locale,
        UDateRelativeDateTimeFormatterStyle style,
        const WithQuantityExpected* expectedResults,
        int32_t expectedResultLength) {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            locale, NULL, style, UDISPCTX_CAPITALIZATION_NONE, status);
    if (U_FAILURE(status)) {
        dataerrln("Unable to create format object - %s", u_errorName(status));
        return;
    }
    RunTest(fmt, expectedResults, expectedResultLength, locale.getName());
}

void RelativeDateTimeFormatterTest::RunTest(
        const Locale& locale,
        const WithoutQuantityExpected* expectedResults,
        int32_t expectedResultLength) {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(locale, status);
    if (U_FAILURE(status)) {
        dataerrln("Unable to create format object - %s", u_errorName(status));
        return;
    }
    RunTest(fmt, expectedResults, expectedResultLength, locale.getName());
}

void RelativeDateTimeFormatterTest::RunTest(
        const Locale& locale,
        UDateRelativeDateTimeFormatterStyle style,
        const WithoutQuantityExpected* expectedResults,
        int32_t expectedResultLength) {
    UErrorCode status = U_ZERO_ERROR;
    RelativeDateTimeFormatter fmt(
            locale, NULL, style, UDISPCTX_CAPITALIZATION_NONE, status);
    if (U_FAILURE(status)) {
        dataerrln("Unable to create format object - %s", u_errorName(status));
        return;
    }
    RunTest(fmt, expectedResults, expectedResultLength, locale.getName());
}

void RelativeDateTimeFormatterTest::RunTest(
        const RelativeDateTimeFormatter& fmt,
        const WithQuantityExpected* expectedResults,
        int32_t expectedResultLength,
        const char *description) {
    for (int32_t i = 0; i < expectedResultLength; ++i) {
        CheckExpectedResult(fmt, expectedResults[i], description);
    }
}

void RelativeDateTimeFormatterTest::RunTest(
        const RelativeDateTimeFormatter& fmt,
        const WithoutQuantityExpected* expectedResults,
        int32_t expectedResultLength,
        const char *description) {
    for (int32_t i = 0; i < expectedResultLength; ++i) {
        CheckExpectedResult(fmt, expectedResults[i], description);
    }
}

void RelativeDateTimeFormatterTest::CheckExpectedResult(
        const RelativeDateTimeFormatter& fmt,
        const WithQuantityExpected& expectedResult,
        const char* description) {
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString actual;
    fmt.format(expectedResult.value, expectedResult.direction, expectedResult.unit, actual, status);
    UnicodeString expected(expectedResult.expected, -1, US_INV);
    expected = expected.unescape();
    char buffer[256];
    sprintf(
            buffer,
            "%s, %f, %s, %s",
            description,
            expectedResult.value,
            DirectionStr(expectedResult.direction),
            RelativeUnitStr(expectedResult.unit));
    if (actual != expected) {
        errln(UnicodeString("Fail: Expected: ") + expected
                + ", Got: " + actual
                + ", For: " + buffer);
    }
}

void RelativeDateTimeFormatterTest::CheckExpectedResult(
        const RelativeDateTimeFormatter& fmt,
        const WithoutQuantityExpected& expectedResult,
        const char* description) {
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString actual;
    fmt.format(expectedResult.direction, expectedResult.unit, actual, status);
    UnicodeString expected(expectedResult.expected, -1, US_INV);
    expected = expected.unescape();
    char buffer[256];
    sprintf(
            buffer,
            "%s, %s, %s",
            description,
            DirectionStr(expectedResult.direction),
            AbsoluteUnitStr(expectedResult.unit));
    if (actual != expected) {
        errln(UnicodeString("Fail: Expected: ") + expected
                + ", Got: " + actual
                + ", For: " + buffer);
    }
}

void RelativeDateTimeFormatterTest::VerifyIllegalArgument(
        const RelativeDateTimeFormatter& fmt,
        UDateDirection direction,
        UDateRelativeUnit unit) {
    UnicodeString appendTo;
    UErrorCode status = U_ZERO_ERROR;
    fmt.format(1.0, direction, unit, appendTo, status);
    if (status != U_ILLEGAL_ARGUMENT_ERROR) {
        errln("Expected U_ILLEGAL_ARGUMENT_ERROR, got %s", u_errorName(status));
    }
}

void RelativeDateTimeFormatterTest::VerifyIllegalArgument(
        const RelativeDateTimeFormatter& fmt,
        UDateDirection direction,
        UDateAbsoluteUnit unit) {
    UnicodeString appendTo;
    UErrorCode status = U_ZERO_ERROR;
    fmt.format(direction, unit, appendTo, status);
    if (status != U_ILLEGAL_ARGUMENT_ERROR) {
        errln("Expected U_ILLEGAL_ARGUMENT_ERROR, got %s", u_errorName(status));
    }
}

static const char *kLast2 = "Last_2";
static const char *kLast = "Last";
static const char *kThis = "This";
static const char *kNext = "Next";
static const char *kNext2 = "Next_2";
static const char *kPlain = "Plain";

static const char *kSeconds = "Seconds";
static const char *kMinutes = "Minutes";
static const char *kHours = "Hours";
static const char *kDays = "Days";
static const char *kWeeks = "Weeks";
static const char *kMonths = "Months";
static const char *kYears = "Years";

static const char *kSunday = "Sunday";
static const char *kMonday = "Monday";
static const char *kTuesday = "Tuesday";
static const char *kWednesday = "Wednesday";
static const char *kThursday = "Thursday";
static const char *kFriday = "Friday";
static const char *kSaturday = "Saturday";
static const char *kDay = "Day";
static const char *kWeek = "Week";
static const char *kMonth = "Month";
static const char *kYear = "Year";
static const char *kNow = "Now";

static const char *kUndefined = "Undefined";

static const char *DirectionStr(
        UDateDirection direction) {
    switch (direction) {
        case UDAT_DIRECTION_LAST_2:
            return kLast2;
        case UDAT_DIRECTION_LAST:
            return kLast;
        case UDAT_DIRECTION_THIS:
            return kThis;
        case UDAT_DIRECTION_NEXT:
            return kNext;
        case UDAT_DIRECTION_NEXT_2:
            return kNext2;
        case UDAT_DIRECTION_PLAIN:
            return kPlain;
        default:
            return kUndefined;
    }
    return kUndefined;
}

static const char *RelativeUnitStr(
        UDateRelativeUnit unit) {
    switch (unit) {
        case UDAT_RELATIVE_SECONDS:
            return kSeconds;
        case UDAT_RELATIVE_MINUTES:
            return kMinutes;
        case UDAT_RELATIVE_HOURS:
            return kHours;
        case UDAT_RELATIVE_DAYS:
            return kDays;
        case UDAT_RELATIVE_WEEKS:
            return kWeeks;
        case UDAT_RELATIVE_MONTHS:
            return kMonths;
        case UDAT_RELATIVE_YEARS:
            return kYears;
        default:
            return kUndefined;
    }
    return kUndefined;
}

static const char *AbsoluteUnitStr(
        UDateAbsoluteUnit unit) {
    switch (unit) {
        case UDAT_ABSOLUTE_SUNDAY:
            return kSunday;
        case UDAT_ABSOLUTE_MONDAY:
            return kMonday;
        case UDAT_ABSOLUTE_TUESDAY:
            return kTuesday;
        case UDAT_ABSOLUTE_WEDNESDAY:
            return kWednesday;
        case UDAT_ABSOLUTE_THURSDAY:
            return kThursday;
        case UDAT_ABSOLUTE_FRIDAY:
            return kFriday;
        case UDAT_ABSOLUTE_SATURDAY:
            return kSaturday;
        case UDAT_ABSOLUTE_DAY:
            return kDay;
        case UDAT_ABSOLUTE_WEEK:
            return kWeek;
        case UDAT_ABSOLUTE_MONTH:
            return kMonth;
        case UDAT_ABSOLUTE_YEAR:
            return kYear;
        case UDAT_ABSOLUTE_NOW:
            return kNow;
        default:
            return kUndefined;
    }
    return kUndefined;
}

extern IntlTest *createRelativeDateTimeFormatterTest() {
    return new RelativeDateTimeFormatterTest();
}

#endif


text:
<?php

namespace Pok\PoolDBM\Console\Helper;

use Symfony\Component\Console\Helper\Helper;

use Pok\PoolDBM\Twig\TwigExtension;

class TemplateEngineHelper extends Helper implements TemplateHelperInterface
{
    /**
     * @var \Twig_Environment
     */
    protected $twig;

    /**
     * Constructor.
     *
     * @param string|array $paths   A path or an array of paths where to look for templates
     * @param array        $options An array of options environment
     */
    public function __construct($paths, array $options = array())
    {
        $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem($paths), $options);
        $this->twig->addExtension(new TwigExtension());
    }

    /**
     * {@inheritdoc}
     */
    public function render($name, array $context = array())
    {
        return $this->twig->render($name, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'template';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace GLOTR;
use Nette\Application\UI\Form;

class MyForm extends Form
{
	public function __construct(IContainer $parent = NULL, $name = NULL)
    {
        parent::__construct($parent, $name);
		\Nette\Forms\Container::extensionMethod('addDatePicker', function (\Nette\Forms\Container $container, $name, $label = NULL) {
            return $container[$name] = new \JanTvrdik\Components\DatePicker($label);
        });
	}
	public function addError($message, $translate = true)
	{
		if($translate && $this->getTranslator())
			$message = $this->getTranslator()->translate($message);

		parent::addError($message);
	}

}


text:
package teslamaxcompute

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Point is a nested struct in teslamaxcompute response
type Point struct {
	CpuMaxQuota CpuMaxQuota `json:"CpuMaxQuota" xml:"CpuMaxQuota"`
	CpuMinQuota CpuMinQuota `json:"CpuMinQuota" xml:"CpuMinQuota"`
	MemUsed     MemUsed     `json:"MemUsed" xml:"MemUsed"`
	CpuUsed     CpuUsed     `json:"CpuUsed" xml:"CpuUsed"`
	MemMaxQuota MemMaxQuota `json:"MemMaxQuota" xml:"MemMaxQuota"`
	MemMinQuota MemMinQuota `json:"MemMinQuota" xml:"MemMinQuota"`
}


text:
#include "myimageprovider.h"

#include <QDebug>

#include "id3tag.h"
#include "myid3data.h"

MyImageProvider::MyImageProvider(ImageType type, Flags flags) :
    QQuickImageProvider(type,flags)
    , m_value(0)
{
}

MyImageProvider::~MyImageProvider()
{
}

/*
void MyImageProvider::setValue(int v)
{
//    static int nextFrameNumber = 0;
//    emit signalNewFrameReady(nextFrameNumber++);
    if (v != m_value) {
        emit valueChanged(v);
        m_value = v;
    }
}
*/

/*
void MyImageProvider::signalNewFrameReady(int frameNumber)
{
    (void)frameNumber;
}
*/

QImage MyImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
    qDebug() << "requestImage(): id: " << id;
    (void)requestedSize;
    //qDebug() << "reequestedSize: " << requestedSize.width() << " " << requestedSize.height();

    //QImage res = QImage(QString("/home/ericosur/gcode/snippet/qt/qml-flip/prev.jpg"));
    QImage res;
    size->setHeight(500);
    size->setWidth(500);

    MyId3Data *id3 = nullptr;
    if ( m_cache.contains(id) ) {
        id3 = m_cache.object(id);
        if (id3 != nullptr) {
            res = id3->get_img();
        } else {
            //qDebug() << "requestImage(): no img";
            res = QImage(); // TODO: use default image
        }
    } else {
        //qDebug() << "requestImage(): img not load...";
        res = QImage(); // TODO: use default image
    }

    return res;
}


text:
{% extends 'myapp/base_myapp.html' %}

{% load static %}

{% block content %}

Django Magic Themes

Beauty themes ready for use

          Frontend Guide

More documentation soon

If you like/dislike this approach, get in touch and let's talk and narrow down the solution rather
      than starting another pluggable app for one tiny group.

{% endblock content %}


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

<TITLE>
edu.upenn.cis.taggers.malignancy (Penn Bio Tagger JavaDoc)
</TITLE>

<META NAME="date" CONTENT="2012-11-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

edu.upenn.cis.taggers.malignancy

Classes

MalignancySegmentationEvaluator

MalignancyTagger

MalignancyTrainer

MaligSentence2TokenSequence


text:
module MongoMapper
  module Plugins
    module Caching
      extend ActiveSupport::Concern

      def cache_key(*suffixes)
        cache_key = case
                      when !persisted?
                        "#{self.class.name}/new"
                      when timestamp = self[:updated_at]
                        "#{self.class.name}/#{id}-#{timestamp.to_s(:number)}"
                      else
                        "#{self.class.name}/#{id}"
                    end
        cache_key += "/#{suffixes.join('/')}" unless suffixes.empty?
        cache_key
      end
    end
  end
end


text:
package cloud::azure::management::insightsmetrics::mode::listlogicaldisks;

use base qw(centreon::plugins::mode);

use strict;
use warnings;
use JSON::XS;

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'name'           => { name => 'name' },
        'resource:s'     => { name => 'resource' },
        'workspace-id:s' => { name => 'workspace_id' }
    });
    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') {
        $self->{output}->add_option_msg(short_msg => "Need to specify --resource option.");
        $self->{output}->option_exit();
    }
}

sub manage_selection {
    my ($self, %options) = @_;

   my $query = 'InsightsMetrics | where Namespace == "LogicalDisk" | distinct Tags, _ResourceId, Computer';
   if (defined($self->{option_results}->{name})) {
       $query .= '| where Computer == "' . $self->{option_results}->{resource} . '"';
   } else {
       $query .= '| where _ResourceId == "' . $self->{option_results}->{resource} . '"';
   }

    my $results = $options{custom}->azure_get_insights_analytics(
        workspace_id => $self->{option_results}->{workspace_id},
        query        => $query,
        timespan     => $self->{option_results}->{timespan},
        disco        => 1
    );

    foreach my $entry (keys %{$results->{data}}) {
        my $decoded_tag = $options{custom}->json_decode(content => $results->{data}->{$entry}->{tags});

        $self->{logicaldisk}->{$decoded_tag->{"vm.azm.ms/mountId"}}->{name} = $decoded_tag->{"vm.azm.ms/mountId"};
    }

    if (scalar(keys %{$self->{logicaldisk}}) <= 0) {
        $self->{output}->add_option_msg(short_msg => "No logical disks found. Can be: filters, cache file.");
        $self->{output}->option_exit();
    }
}

sub run {
    my ($self, %options) = @_;

    $self->manage_selection(%options);
    foreach my $mount (sort keys %{$self->{logicaldisk}}) {
        $self->{output}->output_add(long_msg => '[name = ' . $mount . ']' );
    }

    $self->{output}->output_add(
        severity => 'OK',
        short_msg => 'List logical disks:'
    );
    $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
    $self->{output}->exit();
}

sub disco_format {
    my ($self, %options) = @_;

    $self->{output}->add_disco_format(elements => [ 'name' ]);
}

sub disco_show {
    my ($self, %options) = @_;

    $self->manage_selection(%options);
    foreach my $mount (sort keys %{$self->{logicaldisk}}) {
        $self->{output}->add_disco_entry(name => $self->{logicaldisk}->{$mount}->{name});
    }
}

1;

__END__

=head1 MODE

List Azure Computer logical disks.

Example:

perl centreon_plugins.pl --plugin=cloud::azure::management::insightsmetrics::plugin --custommode=api --mode=list-logical-disks
--subscription=1111 --tenant=2222 --client-id=3333 --client-secret=4444 --workspace-id=5555 --verbose --resource='azure-vm1'
--name

=over 8

=item B<--workspace-id>
(Mandatory)
Specify the Azure Log Analytics Workspace ID.

=item B<--resource>

(Mandatory)
Specify the Azure VM Resource ID or name. Short name can be used if the option --name is defined.
Example: --resource='/subscriptions/1234abcd-5678-defg-9012-3456789abcde/resourcegroups/my_resourcegroup/providers/microsoft.compute/virtualmachines/azure-vm1'

=item B<--name>

(Optional)
Use only the name of the VM resource rather than the full ID.
Example: --resource='azure-vm1' --name

=back

=cut


text:
<!SLIDE section center>
# Abstração

<!SLIDE>
# Pilares do Paradigma Orientação a Objetos

Este módulo refere-se a um dos quatro pilares do paradigma orientado a objetos.

* Herança
* Polimorfismo
* **Abstração**
* Encapsulamento

<!SLIDE>
# Hierarquia de Automóveis

Vamos voltar ao exemplo da hierarquia de automóveis apresentado no módulo de Herança.

![.fancyborder](_images/abstracao-automovel-carro-moto.png)

Nesta hierarquia, a classe Automovel foi criada como forma de abstrair um
conceito geral representado em ambas as classes.

<!SLIDE>
# Classes Abstratas

A forma de representar estes conceitos abstratos é realizado no Paradigma
Orientado a Objetos com **Classes Abstratas**.

.callout **Classes Abstratas** organizam elementos comuns a várias classes. - *James Rumbaugh*

No exemplo, a classe Automovel está fazendo o papel de uma classe abstrata, pois está representando
um conceito abstrato.

<!SLIDE>
# Características e Comportamentos em Comum

Usamos classes abstratas para representar grupos que têm características em comum, mas que diferem em detalhes específicos.

<!SLIDE>
# Classes Abstratas vs Classes Concretas

**Classes Concretas** são as classes que representam, de fato, as entidades modeladas do mundo real.

**Classes Abstratas**, por outro lado, agrupam diversas classes concretas que compartilhem o mesmo conceito
(características e comportamentos).

<!SLIDE>
# Intâncias de Classes

Como Classes Abstratas são classes que servem de modelo para classes concretas ou agrupam
características e comportamentos em comum, não faz sentido ter instâncias de classes abstratas.

Portanto, classes abstratas não devem e não podem ser instanciadas.

    @@@ Java
    Automovel automovel = new Automovel (); // ERRO DE COMPILAÇÃO

    Carro carro = new Carro (); // OK
    Moto moto = new Moto (); // OK

<!SLIDE>
# Representação em Java

Em Java, utilizamos a palavra-chave *abstract* para declarar uma classe abstrata.

No exemplo, a classe Automovel transformada em classe abstrata fica da seguinte forma:

    @@@ Java
    public abstract class Automovel {

      private String marca;

      public Automovel (String marca) {
	    this.marca = marca;
	  }
    }

Desta forma, a classe Automovel não pode ser instanciada.

<!SLIDE>
# Comportamentos abstratos

A classe abstrata implementa as características gerais
e seus métodos abstratos são implementados nas subclasses com seus detalhes.

<!SLIDE>
# Classes Abstratas vs Classes Concretas

A classe abstrata Automovel

    @@@ Java
    public abstract class Automovel {

      private String marca;

      public Automovel (String marca) {
	    this.marca = marca;
	  }
    }

A classe concreta Carro

    @@@Java
    public class Carro extends Automovel {
	  // corpo do código
	}

A classe concreta Moto

    @@@Java
    public class Moto extends Automovel {
	  // corpo do código
	}

<!SLIDE>
# Métodos Abstratos

Se uma classe abstrata definir um método abstrato, as classes concretas devem implementar o método.

    @@@ Java
    public abstract class Automovel {

	  private String marca;

	  public Automovel (String marca) {
	    this.marca = marca;
      }

	  public abstract int quantidadeRodas ();
    }

<!SLIDE>
# Representação em UML

Nome da classe e nome do método escrito em itálico indica que a classe é abstrata ou o método é abstrato.

![.fancyborder](_images/classe-metodo-abstrato-automovel.png)

<!SLIDE>
# Por que utilizar Classe Abstrata?

Como não podemos instanciar uma classe abstrata, tratar conceitos abstratos desta forma, gera uma maior consistência ao sistema.

A decisão de transformar ou não uma classe em abstrata depende do seu domínio.

<!SLIDE>
# Classes Abstratas

Uma classe abstrata é um recurso que podemos utilizar quando queremos compartilhar funcionalidades em comum entre clases,
mas não queremos permitir que sejam instanciadas.

<!SLIDE>
# Métodos Abstratos

Métodos abstratos são métodos pertencentes a classes abstratas
que devem ser declarados sem implementação.

    @@@ Java
   	public abstract String quantidadeRodas ();

<!SLIDE>
# Classes Abstratas

Classes abstratas podem ter zero, um ou mais métodos abstratos.

    @@@ Java
    public abstract class Automovel {

	  private String marca;

	  public Automovel (String marca) {
	    this.marca = marca;
      }

	  public abstract int quantidadeRodas ();
    }

* Uma classe abstrata declara atributos e comportamentos comuns das várias classes em uma hierarquia.

<!SLIDE>
# Classes Abstratas

* As subclasses devem sobrescrever os métodos abstratos para se tornarem concretas.

<!SLIDE>
# Classe Concreta herdada de Classe Abstrata

    @@@Java
    public class Moto extends Veiculo {
	public Moto (String marca) {
		super (marca);
	}
	public int quantidadeRodas () {
		return 2;
	}

<!SLIDE>
# Classe Concreta herdada de Classe Abstrata

    @@@Java
    public class Carro extends Veiculo {
	public Carro (String marca) {
		super (marca);
	}
	public int quantidadeRodas () {
		return 4;
	}

<!SLIDE>
# Usando Classes abstratas

Uma classe Abstrata não pode ser instanciada

    @@@ Java
	Automovel automovel =  new Automovel (); // ERRO de Compilação!!!!

A instanciação de uma classe concreta pode ser atribuida para uma variável
do mesmo tipo da classe concreta.

    @@@ Java
	Carro carro = new Carro ("Ford");

E também pode ser atribuída para qualquer classe herdada na hierarquia,
inclusive para a classe abstrata, que no exemplo é a super classe.

    @@@ Java
	Automovel automovel = new Carro ("Ford");

<!SLIDE>
# Método final

* Não podem ser sobrescritos em uma subclasse

* Métodos final são resolvidos em tempo de compilação, isto é conhecido como vinculação estática.

<!SLIDE>
# Método final

    @@@ Java
    public class Automovel {

      // restante do código não apresentado.

      public final String getMarca() {
	    return marca;
      }
    }

Errado

    @@@ Java
    public class Moto extends Automovel {

      public String getMarca() {
	    return this.marca;
      }

    }

<!SLIDE>
# Classes final

* Não podem ser estendidas por uma subclasse

* Todos os métodos em um classe final são implicitamente final.

<!SLIDE>
# Classes final

    @@@ Java
    public final class Moto extends Veiculo {
       // ...
    }

Errado

    @@@ Java
    public final class Triciclo extends Moto {
        // ...
    }

<!SLIDE>
# Classe Base em Java

Em Java, todas as classes herdam da classe **Object**.

A classe **Object** é a raiz da hierarquia de classes.

Toda classe tem **Object** como uma superclasse.

Documentação: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

<!SLIDE>
# Métodos da Classe Object

Possui apenas o construtor padrão e uma lista pequena de métodos.

Alguns dos métodos são:

    @@@ Java
    // indica se algum outro objeto é igual a um outro
    boolean	equals(Object obj)

    // Retorna o valor do hash code para o objeto
    int	hashCode()

    // Retorna a representação do objeto em uma String
    String	toString()

    // Retorna a classe do objeto em execução
    Class<?> getClass()


text:
package ParticleSystem;

import ParticleSystem.Utility.Util_Random;

import java.awt.image.BufferedImage;
import java.awt.geom.Point2D;
import java.util.Random;

/**
 * Write a description of class ShowerEvent here.
 *
 * @author Chirstopher Sheaf
 */
public class SprayEffect implements ParticleEffect {
    double direction;
    double arcWidth;
    double forceMultiplier;
    double gravity;

    Random randomGen;
    ViewScreen screen;

    public SprayEffect(double direction, double arcWidth, double forceMultiplier, double gravity, ViewScreen screen) {
        this.direction = direction;
        this.arcWidth = arcWidth;
        this.forceMultiplier = forceMultiplier;
        this.gravity = gravity;

        randomGen = new Random();
        this.screen = screen;
    }

    public Particle[] spawnParticles(BufferedImage particleSprite, Point2D.Double location, int numberOfParticles) {
        Particle[] particleArray = new Particle[numberOfParticles];

        for (int i = 0; i < numberOfParticles; i++) {
            particleArray[i] = new Particle(
                Util_Random.randomPointInCircle(1, location, 1.0, 0.0), //Initial coordinates
                Util_Random.randomPointInCircle(5 * forceMultiplier, null, arcWidth, direction), //Initial velocity
                0.98, //Friction
                gravity, //Gravity
                100.0 * forceMultiplier, //Maximum velocity
                randomGen.nextInt(25) + 15, //Maximum age
                particleSprite, //Image
                screen
            );
        }

        return particleArray;
    }
}


text:
calendModController.controller('EventoPrivadoDetalleController', [
                                                '$scope',
                                                '$routeParams',
                                                '$uibModal',
                                                '$location',
                                                'calImagService',
                                                'calEvenService',
    function ($scope, $routeParams,  $uibModal, $location, calImagService, calEvenService) {

      	$scope.eventoId = $routeParams.idEventoPrivado;
		$scope.bandera = false;
		$scope.evento = {};
		$scope.checkboxModel = {};
		$scope.vecInvitados = [];
		$scope.vecNotiCorreo = [];
		$scope.vecNotiAplicacion = [];

		calEvenService.getEventoId($scope.eventoId).then(
			function(dataEvento){
				$scope.bandera = true;
			  	$scope.evento = {
				    id: dataEvento[0].CAL_EVENTOS.evencons,
				    nombre: dataEvento[0].CAL_EVENTOS.evendesc,
				    fechaInicio: new Date(dataEvento[0].CAL_EVENTOS.evenfein).getDate()+"/"+((new Date(dataEvento[0].CAL_EVENTOS.evenfein).getMonth().valueOf())+1)+"/"+new Date(dataEvento[0].CAL_EVENTOS.evenfein).getFullYear(),
                  	fechaFin: new Date(dataEvento[0].CAL_EVENTOS.evenfefi).getDate()+"/"+((new Date(dataEvento[0].CAL_EVENTOS.evenfefi).getMonth().valueOf())+1)+"/"+new Date(dataEvento[0].CAL_EVENTOS.evenfefi).getFullYear()
			  	}
			  	if (dataEvento[0].CAL_EVENINVI !== undefined) {
				  	for (var i = 0; i < dataEvento[0].CAL_EVENINVI.length; i++) {
				  		$scope.vecInvitados.push(dataEvento[0].CAL_EVENINVI[i]);
				  	}
				}
			  	if(dataEvento[0].CAL_EVENTOS.evenvibu == 1){
					$scope.checkboxModel = {
					   value : true
				 	};
				}
				else{
					$scope.checkboxModel = {
					   value : false
				 	};
				}

				if (dataEvento[0].CAL_EVENNOTI !== undefined) {
					calEvenService.getAllAlertas().then(
						function (dataAlertas) {
							for (var i = 0; i < dataEvento[0].CAL_EVENNOTI.length; i++) {
						  		if (dataEvento[0].CAL_EVENNOTI[i].evnotipo === 2901 && dataEvento[0].CAL_EVENNOTI[i].evnoesta !== 5) {
						  			for (var j = 0; j < dataAlertas.length; j++) {
						  				if (dataEvento[0].CAL_EVENNOTI[i].evnoaler === dataAlertas[j].tbnumero) {
						  					$scope.vecNotiAplicacion.push(dataAlertas[j].tbvalor);
						  				}
								  	};
						  		}
						  		if (dataEvento[0].CAL_EVENNOTI[i].evnotipo === 2902 && dataEvento[0].CAL_EVENNOTI[i].evnoesta !== 5) {
						  			for (var j = 0; j < dataAlertas.length; j++) {
						  				if (dataEvento[0].CAL_EVENNOTI[i].evnoaler === dataAlertas[j].tbnumero) {
						  					$scope.vecNotiCorreo.push(dataAlertas[j].tbvalor);
						  				}
								  	};
						  		}
					  		}

						},
						function(error){
						    console.log(error.statusText);
						}
					);
				}

				if (dataEvento[0].CAL_EVENTOS.evenicon !== null) {
				  	calImagService.getImagenId(dataEvento[0].CAL_EVENTOS.evenicon).then(
				        function(dataImagen){
							$scope.evento.iconoEvento = dataImagen.IMAGCODI;
				        },
				        function(error){
				            console.log(error.statusText);
				        }
			      	);
			    }
		      	calEvenService.getAllTipoEvento().then(
		      		function (dataTipoEvento) {
						for (var i = 0; i < dataTipoEvento.length; i++) {
							if (dataTipoEvento[i].tbnumero === dataEvento[0].CAL_EVENTOS.eventipo) {
								$scope.evento.tipoEvento = dataTipoEvento[i].tbvalor;
							}
						};
					}
			   	);
				calEvenService.getAllRepeticion().then(
					function (dataRepeticion) {
						for (var i = 0; i < dataRepeticion.length; i++) {
							if (dataRepeticion[i].tbnumero === dataEvento[0].CAL_EVENTOS.evenperi) {
								$scope.evento.repeticion = dataRepeticion[i].tbvalor;
							}
						}
					}
				);

				calEvenService.getAllImportancia().then(
					function (dataImportancia) {
						for (var i = 0; i < dataImportancia.length; i++) {
							if (dataImportancia[i].tbnumero === dataEvento[0].CAL_EVENTOS.evenimpo) {
								$scope.evento.importancia = dataImportancia[i].tbvalor;
							}
						};
					}
				);
			},
			function(error){
			    console.log(error.statusText);
			}
		);

		$scope.Cambiar = function() {
          	openCambiar('sm', $scope.eventoId);
      	}

		function openCambiar(size, idCambiar) {
		  $scope.idCambiar = idCambiar;
		  var modalInstance = $uibModal.open({
		      templateUrl: 'views/administrador/eventos-privados/cambiar-tipo.html',
		      controller: 'CambiarTipoModalController',
		      size: size,
		      resolve: {
		          idCambiar : function(){
		              return $scope.idCambiar;
		          }
		      }
		  });
		}
}]);


text:
var fs = require('fs');
const CentrallyIssuedToken = artifacts.require('./CentrallyIssuedToken.sol');
const TokenChanger = artifacts.require('./TokenChanger.sol');

function cd_project_root() {
    while (!fs.existsSync('truffle.js'))
        process.chdir('..')
}

function log(name, promise) {
    logErr(name, promise);
    logResponse(name, promise);
}

function logErr(name, promise) {
    promise.catch(err => console.log(name, err));
}

function logResponse(name, promise) {
    promise.then(value => console.log(name, value))
}

module.exports = function (callback) {
    cd_project_root();
    addresses = fs.readFileSync("addresses", "utf8").split('\n');

    STORJ = CentrallyIssuedToken.at(addresses[0]);
    TILE = CentrallyIssuedToken.at(addresses[1]);
    changer = TokenChanger.at(addresses[2]);

    // 200K Storj, 4M TILE held in contract to start
    // I'm assuming TILE at $0.25 and Storj at $0.50
    // So $100K Storj, $1M TILE
    STORJ.transfer(changer.address, 2e12, { from: web3.eth.accounts[0] });
    TILE.transfer(changer.address, 4e13, { from: web3.eth.accounts[0] });

    // Transfer 100 TILE to user
    TILE.transfer(web3.eth.accounts[1], 1e9, { from: web3.eth.accounts[0] });

    // Approve 100 TILE to TokenChanger
    prom = TILE.approve(changer.address, 0, { from: web3.eth.accounts[1] });
    logErr('tile approve', prom);
    prom = TILE.approve(changer.address, 1e9, { from: web3.eth.accounts[1] });
    logErr('tile approve', prom);

    // Sell 100 TILE
    prom = changer.sellTile(1e9, {
        from: web3.eth.accounts[1],
        gas: 200e3
    });
    logErr('sell tile', prom);

    // Approve 40 STORJ to TokenChanger
    prom = STORJ.approve(changer.address, 0, { from: web3.eth.accounts[1] });
    logErr('storj approve', prom);
    prom = STORJ.approve(changer.address, 4e8, { from: web3.eth.accounts[1] });
    logErr('storj approve', prom);

    // Sell 40 STORJ
    prom = changer.sellStorj(4e8, {
        from: web3.eth.accounts[1],
        gas: 200e3
    });
    logErr('sell storj', prom);

    setTimeout(() => {
        log('storj price', changer.storjPrice())
        log('tile price', changer.tilePrice())
        log('contract storj balance', STORJ.balanceOf(addresses[2]))
        log('contract tile balance', TILE.balanceOf(addresses[2]))
        log('user storj balance', STORJ.balanceOf(web3.eth.accounts[1]))
        log('user tile balance', TILE.balanceOf(web3.eth.accounts[1]))
    }, 500);

    callback();
}


text:
[meow][1] is an ity wrapper for the [growl][2] command line [program][3].

[1]: http://github.com/softprops/meow/
[2]: http://growl.info/
[3]: http://growl.info/extras.php#growlnotify/


text:
from collections import Counter
from collections import deque
from collections import defaultdict
from apriori import apriori
from index import InvertedIndex
from typing import Counter, DefaultDict, Dict, Iterator, List, Tuple
import time
import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

class FPNode:
    count: int
    children: Dict[int, 'FPNode']
    parent: 'FPNode'

    def __init__(self, item=None, count=0, parent=None):
        self.item = item
        # Number of paths which include this node.
        self.count = count
        self.children = {}
        self.parent = parent

    def is_root(self) -> bool:
        return self.parent is None

    def __str__(self, level=0) -> str:
        ret = ("[root]" if self.is_root()
               else " " * level + str(self.item) + ":" + str(self.count))
        ret += "\n"
        # Print out the child nodes in decreasing order of count, tie break on
        # lexicographical order. As with sort_transaction() below, we achieve
        # this by relying on the fact that python's sort is stable, so we
        # sort first lexicographically, and again by count.
        children = sorted(self.children.values(), key=lambda node: node.item)
        children = sorted(children, key=lambda node: node.count, reverse=True)
        for node in children:
            ret += node.__str__(level + 1)
        return ret

    def __repr__(self) -> str:
        return self.__str__()

class FPTree:
    root: FPNode
    header: DefaultDict
    item_count: Counter

    def __init__(self):
        self.root = FPNode()
        self.header = defaultdict(list)
        self.item_count = Counter()

    def insert(self, transaction: Iterator[int], count: int = 1) -> None:
        assert(count > 0)
        parent = self.root
        parent.count += count
        for item in transaction:
            self.item_count[item] += count
            if item not in parent.children:
                node = FPNode(item, count, parent)
                parent.children[item] = node
                parent = node
                self.header[item].append(parent)
            else:
                parent = parent.children[item]
                parent.count += count

    def __str__(self):
        return "(" + str(self.root) + ")"

def path_to_root(node: FPNode) -> List[int]:
    path: List[int]= []
    while not node.is_root():
        path += [node.item]
        node = node.parent
    return path

def construct_conditional_tree(tree: FPTree, item: int) -> FPTree:
    conditional_tree = FPTree()
    for node in tree.header[item]:
        path = path_to_root(node.parent)
        conditional_tree.insert(reversed(path), node.count)
    return conditional_tree

def fp_growth(
        tree: FPTree,
        min_count: int,
        path: List[int],
        path_count: int,
        itemsets: List[List[int]],
        itemset_counts: Dict[Tuple[int, ...], int]) -> None:
    # For each item in the tree that is frequent, in increasing order
    # of frequency...
    for item in sorted(
            tree.item_count.keys(),
            key=lambda i: tree.item_count[i]):
        if tree.item_count[item] < min_count:
            # Item is no longer frequent on this path, skip.
            continue

        # Build conditional tree of all patterns in this tree which start
        # with this item.
        conditional_tree = construct_conditional_tree(tree, item)
        itemset = path + [item]
        itemset.sort()
        new_path_count = conditional_tree.root.count
        fp_growth(
            conditional_tree,
            min_count,
            itemset,
            new_path_count,
            itemsets,
            itemset_counts)

        # Need to store the support of this itemset, so we
        # can look it up during rule generation later on.
        itemset_key = tuple(itemset)
        assert(itemset_key not in itemset_counts)
        itemset_counts[itemset_key] = new_path_count

        itemsets.append(itemset)

def mine_fp_tree(transactions, min_support):
    (tree, num_transactions) = construct_initial_tree(transactions, min_support)
    min_count = min_support * num_transactions
    itemsets = []
    itemset_counts = dict()
    start = time.time()
    fp_growth(
        tree,
        min_count,
        [],
        num_transactions,
        itemsets,
        itemset_counts)
    duration = time.time() - start
    print("FPGrowth generated {} itemset in {:.2f}".format(len(itemsets), duration))
    return (itemsets, itemset_counts, num_transactions)

def sort_transaction(transaction, frequency):
    # Sorts by non-increasing item frequency. We need the sort to tie
    # break consistently; so that when two items have the same frequency,
    # we always sort them into the same order. This is so that when we're
    # sorting the trees and we re-insert sorted paths, that the path
    # overlap in a consistent way. We achieve this ordering by sorting
    # twice; once lexicographically, and then a second time in order of
    # frequency. This works because Python's sort is stable; items that
    # compare equal aren't permuted.
    if frequency is None:
        return transaction
    if not isinstance(frequency, Counter):
        raise TypeError("frequency must be Counter")
    return sorted(transaction, key=lambda item: frequency[item], reverse=True)

def count_item_frequency_in(transactions):
    frequency = Counter()
    num_transactions = 0
    for transaction in transactions:
        num_transactions += 1
        for item in transaction:
            frequency[item] += 1
    return (frequency, num_transactions)

def construct_initial_tree(transactions, min_support):
    start = time.time()
    print("Counting item frequencies... ")
    (frequency, num_transactions) = count_item_frequency_in(transactions)
    duration = time.time() - start
    print("Counted item frequencies in {:.2f} seconds".format(duration))
    start = time.time()
    min_count = num_transactions * min_support
    print("Building initial FPTree")
    tree = FPTree()
    for transaction in transactions:
        # Remove infrequent items from transaction. They cannot contribute to
        # producing frequent itemsets, and just slow down the tree algorithms.
        transaction = filter(
            lambda item: frequency[item] >= min_count,
            transaction)
        tree.insert(sort_transaction(transaction, frequency))
    duration = time.time() - start
    print("Built initial tree in {:.2f} seconds".format(duration))
    return (tree, num_transactions)


text:
package com.dfyy.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.dfyy.web.authentication.AdminUserDetails;
import com.dfyy.web.authentication.LoginUtil;

public class ZoneHelper {

	private static final int DefaultZone = 370783;
	private static final int QINGZHOU = 370781;
	private static final int ZHIXIAN = 371522;

	public static List<Integer> getZones(String zones) {
		List<Integer> zs = new ArrayList<>();
		if (StringUtils.isBlank(zones)) {
			zs.add(DefaultZone);
		} else {
			String[] tmep = StringUtils.split(zones, ',');
			for (String string : tmep) {
				zs.add(Integer.parseInt(string));
			}
		}
		return zs;
	}

	public static List<Integer> getZones2(String zones) {
		List<Integer> zs = new ArrayList<>();
		if (StringUtils.isBlank(zones)) {
			zs.add(DefaultZone);
		} else {
			String[] tmep = StringUtils.split(zones, ',');
			for (String string : tmep) {
				zs.add(Integer.parseInt(string));
			}
			if (zs.contains(370781) || zs.contains(370783) || zs.contains(371522)) {

			} else {
				zs.add(DefaultZone);
			}
		}
		return zs;
	}

	public static int getZone(String zone) {
		if (StringUtils.isBlank(zone)) {
			return DefaultZone;
		} else {
			int z =  Integer.parseInt(zone);
			if(z == QINGZHOU || z == ZHIXIAN){
				return z;
			}
			return DefaultZone;
		}
	}

	public static List<Integer> getCurrentZoneAsList() {
		List<Integer> zs = new ArrayList<>();
		AdminUserDetails loginUser = LoginUtil.getLoginAdmin();
		if (loginUser != null) {
			zs.add(loginUser.getZone().getId());
		} else {
			zs.add(0);
		}
		return zs;
	}

	public static Integer getCurrentZone() {
		AdminUserDetails loginUser = LoginUtil.getLoginAdmin();
		if (loginUser != null) {
			return loginUser.getZone().getId();
		} else {
			return DefaultZone;
		}
	}
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('participants', '0002_auto_20151005_1917'),
    ]

    operations = [
        migrations.CreateModel(
            name='CallEntry',
            fields=[
                ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),
                ('start_time', models.DateTimeField(auto_now_add=True)),
                ('end_time', models.DateTimeField(null=True)),
                ('participant', models.ForeignKey(to='participants.Participant')),
            ],
        ),
    ]


text:
"""
Copyright (C) 2015-2016 Kinnay, MrRean, RoadrunnerWMC
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY Yannik Marchand ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yannik Marchand BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation
are those of the authors and should not be interpreted as representing
official policies, either expressed or implied, of Yannik Marchand.
"""

import struct

def String(data,offs):
    return data[offs:].split(b'\0')[0].decode('shift-jis')

def UI24(data,offs):
    return struct.unpack('>I',b'\x00'+data[offs:offs+3])[0]

def UI32(data,offs):
    return struct.unpack_from('>I',data,offs)[0]

class ValueNode:
    def __init__(self,v,offs,byml):
        self.val = v
        self.offs = offs
        self.byml = byml

    def __str__(self):
        return str(self.val)

    def parse(self):
        pass

class StringNode(ValueNode):
    def changeValue(self,val):
        self.val = str(val)
        self.byml.stringChanged(self)

class BooleanNode(ValueNode):
    def changeValue(self,val):
        self.val = bool(val)
        bchar = b'\x01' if self.val else b'\x00'
        self.byml.data = self.byml.data[:self.offs]+bchar+self.byml.data[self.offs+1:]

class IntegerNode(ValueNode):
    def changeValue(self,val):
        self.val = int(val)
        self.byml.data = self.byml.data[:self.offs]+struct.pack('>i',self.val)+self.byml.data[self.offs+4:]

class FloatNode(ValueNode):
    def changeValue(self,val):
        self.val = float(val)
        self.byml.data = self.byml.data[:self.offs]+struct.pack('>f',self.val)+self.byml.data[self.offs+4:]

class NoneNode(ValueNode):
    pass

class DictNode:
    def __init__(self,offs,byml):
        self.parsed = False
        self.offs = offs
        self.dict = {}
        self.byml = byml

    def __iter__(self):
        return iter(self.subNodes())

    def parse(self):
        if self.parsed:
            return

        offs = self.offs
        data = self.byml.data
        count = UI24(data,offs)
        offs+=3

        for i in range(count):
            name = UI24(data,offs)
            nodetype = data[offs+3]
            value = UI32(data,offs+4)
            offs+=8

            sname = self.byml.nodes[name]
            if nodetype == 0xA0:
                self.dict[sname] = StringNode(self.byml.strings[value],offs-4,self.byml)
            elif nodetype == 0xC0:
                self.dict[sname] = ArrayNode(value+1,self.byml)
            elif nodetype == 0xC1:
                self.dict[sname] = DictNode(value+1,self.byml)
            elif nodetype == 0xD0:
                s = True if value else False
                self.dict[sname] = BooleanNode(s,offs-4,self.byml)
            elif nodetype == 0xD1:
                if value>0x80000000:
                    value-=0x100000000
                self.dict[sname] = IntegerNode(value,offs-4,self.byml)
            elif nodetype == 0xD2:
                v = struct.unpack('>f',struct.pack('>I',value))[0]
                self.dict[sname] = FloatNode(v,offs-4,self.byml)
            elif nodetype == 0xFF:
                self.dict[sname] = NoneNode(None,offs-8,self.byml)
            else:
                raise ValueError("Unknown Dictionary Node Type: "+hex(nodetype))

        self.parsed = True

    def __getitem__(self,name):
        node = self.getSubNode(name)
        if isinstance(node,ValueNode):
            return node.val
        return node

    def getSubNode(self,name):
        if not name in self.dict:
            raise ValueError("Dictionary has no sub node named "+str(name))

        self.dict[name].parse()
        return self.dict[name]

    def getSubValue(self,name):
        node = self.getSubNode(name)
        if not isinstance(node,ValueNode):
            raise TypeError("Diction sub node is not a value node")
        return node.val

    def subNodes(self):
        for obj in self.dict.values():
            obj.parse()
        return self.dict

class ArrayNode:
    def __init__(self,offs,byml):
        self.parsed = False
        self.offs = offs
        self.array = []
        self.byml = byml

    def __getitem__(self,name):
        node = self.getSubNode(name)
        if isinstance(node,ValueNode):
            return node.val
        return node

    def __len__(self):
        return len(self.array)

    def __iter__(self):
        return iter(self.subNodes())

    def parse(self):
        if self.parsed:
            return

        offs = self.offs
        data = self.byml.data
        count = UI24(data,offs)
        offs+=3

        types = []
        for i in range(count):
            types.append(data[offs])
            offs+=1

        if offs%4:
            offs+=4-(offs%4)

        offsets = []
        for i in range(count):
            offsets.append([offs,UI32(data,offs)])
            offs+=4

        for i in range(count):
            type = types[i]
            offs = offsets[i]
            if type == 0xA0:
                self.array.append(StringNode(self.byml.strings[offs[1]],offs[0]),self.byml)
            elif type == 0xC1:
                self.array.append(DictNode(offs[1]+1,self.byml))
            else:
                raise ValueError("Unknown array node type: "+hex(type))

        self.parsed = True

    def subNodes(self):
        for obj in self.array:
            obj.parse()
        return self.array

class BYML:
    def __init__(self,data):
        self.data = data
        assert data[:2] == b'BY'
        self.offs1 = UI32(data,4)
        self.offs2 = UI32(data,8)
        self.offs3 = UI32(data,12)
        self.nodes = []
        self.strings = []
        self.doStringTable(self.offs1,self.nodes)
        self.stringEnd = self.doStringTable(self.offs2,self.strings)
        self.stringUpdates = []
        self.rootNode = self.getRootNode(self.offs3)
        self.rootNode.parse()

    def doStringTable(self,offs,l):
        soffs = offs
        assert self.data[offs] == 0xC2
        count = UI24(self.data,offs+1)
        offs+=4
        for i in range(count):
            l.append(String(self.data,soffs+UI32(self.data,offs)))
            offs+=4
        return offs

    def getRootNode(self,offs):
        type = self.data[offs]
        if type == 0xC0:
            node = ArrayNode(offs+1,self)
        elif type == 0xC1:
            node = DictNode(offs+1,self)
        else:
            raise ValueError('Unknown Section Type: '+hex(type))
        return node

    def stringChanged(self,node):
        if not node in self.stringUpdates:
            self.stringUpdates.append(node)

    def saveChanges(self):
        for node in self.stringUpdates:
            if node.val not in self.strings:
                self.strings.append(node.val)
                self.offs3 += 4
                self.data = self.data[:self.stringEnd]+struct.pack('>I',len(self.data))+self.data[self.stringEnd:]
                self.data += node.val+b'\x00'
            self.data = self.data[:node.offs]+struct.pack('>I',self.strings.index(node.val))+self.data[node.offs+4:]

        self.data = self.data[:12]+struct.pack('>I',self.offs3)+self.data[16:]
        self.data = self.data[:self.offs2+1]+struct.pack('>I',len(self.strings))[1:]+self.data[self.offs2+4:]

        self.stringUpdates = []


text:
.profile {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: green;
  padding-top: 5rem;
  text-align: center;
}

.content {
  display: flex;
  flex-direction: column;
  max-width: 300px;

  button {
    margin: 1rem;
  }
}

.error {
  color: red;
}


text:
namespace nbla {

NBLA_REGISTER_FUNCTION_SOURCE(MulScalar, double, bool);
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Patellaria signata Ellis & Everh.

### Remarks
null


text:
<?php
/**
 * @package framework
 * @subpackage model
 * @deprecated 3.0 Use {@link DataExtension}.
 */
abstract class DataObjectDecorator extends DataExtension {

	public function __construct() {
		Deprecation::notice('3.0', 'DataObjectDecorator is deprecated. Use DataExtension instead.',
			Deprecation::SCOPE_CLASS);
		parent::__construct();
	}

}


text:
"use strict";

const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const HTMLElement = require("./HTMLElement.js");
const impl = utils.implSymbol;

function HTMLPreElement() {
  throw new TypeError("Illegal constructor");
}
Object.setPrototypeOf(HTMLPreElement.prototype, HTMLElement.interface.prototype);
Object.setPrototypeOf(HTMLPreElement, HTMLElement.interface);

Object.defineProperty(HTMLPreElement.prototype, "width", {
  get() {
    const value = parseInt(this.getAttribute("width"));
    return isNaN(value) || value < -2147483648 || value > 2147483647 ? 0 : value;
  },
  set(V) {
    V = conversions["long"](V, {
      context: "Failed to set the 'width' property on 'HTMLPreElement': The provided value"
    });
    this.setAttribute("width", String(V));
  },
  enumerable: true,
  configurable: true
});

Object.defineProperty(HTMLPreElement.prototype, Symbol.toStringTag, {
  value: "HTMLPreElement",
  writable: false,
  enumerable: false,
  configurable: true
});

const iface = {
  mixedInto: [],
  is(obj) {
    if (obj) {
      if (obj[impl] instanceof Impl.implementation) {
        return true;
      }
      for (let i = 0; i < module.exports.mixedInto.length; ++i) {
        if (obj instanceof module.exports.mixedInto[i]) {
          return true;
        }
      }
    }
    return false;
  },
  isImpl(obj) {
    if (obj) {
      if (obj instanceof Impl.implementation) {
        return true;
      }

      const wrapper = utils.wrapperForImpl(obj);
      for (let i = 0; i < module.exports.mixedInto.length; ++i) {
        if (wrapper instanceof module.exports.mixedInto[i]) {
          return true;
        }
      }
    }
    return false;
  },
  convert(obj, { context = "The provided value" } = {}) {
    if (module.exports.is(obj)) {
      return utils.implForWrapper(obj);
    }
    throw new TypeError(`${context} is not of type 'HTMLPreElement'.`);
  },
  create(constructorArgs, privateData) {
    let obj = Object.create(HTMLPreElement.prototype);
    this.setup(obj, constructorArgs, privateData);
    return obj;
  },
  createImpl(constructorArgs, privateData) {
    let obj = Object.create(HTMLPreElement.prototype);
    this.setup(obj, constructorArgs, privateData);
    return utils.implForWrapper(obj);
  },
  _internalSetup(obj) {
    HTMLElement._internalSetup(obj);
  },
  setup(obj, constructorArgs, privateData) {
    if (!privateData) privateData = {};
    privateData.wrapper = obj;

    this._internalSetup(obj);

    Object.defineProperty(obj, impl, {
      value: new Impl.implementation(constructorArgs, privateData),
      writable: false,
      enumerable: false,
      configurable: true
    });
    obj[impl][utils.wrapperSymbol] = obj;
  },
  interface: HTMLPreElement,
  expose: {
    Window: { HTMLPreElement: HTMLPreElement }
  }
};
module.exports = iface;

const Impl = require("../nodes/HTMLPreElement-impl.js");


text:
require "minitest/autorun"
require_relative '../lib/favourite_language_guesser'

class FavouriteLanguageGuesserTest < MiniTest::Unit::TestCase
  def setup
    @lg = FavouriteLanguageGuesser.new
  end

  def test_favourite_language_is_the_most_used_language
    assert_equal('Ruby', @lg.favourite_language('rubinius'))
  end

  def test_favourite_language_with_nonexistent_username_raises_exception
    assert_raises(GitHubAPI::UserNotFoundError) do
      @lg.favourite_language('auserthatdoesnotexist')
    end
  end

  def test_used_languages_raises_exception_when_no_repositories_updated
    assert_raises(FavouriteLanguageGuesser::NoUpdatedRepositoriesWithinTimeframeError) do
      @lg.used_languages('whymirror', 12)
    end
  end

  def test_used_languages_since_x_months_ago
    assert_instance_of(Hash, @lg.used_languages('rubinius', 6))
  end
end


text:
/*
 Write a JavaScript function treeHouseCompare(value) that accepts the following parameters: integers a and b.
 The function compares the area of the house and the area of the tree (Figure 1)
 and returns the name of the figure with bigger area (house or tree) and the value of the area.
*/

'use strict';

function treeHouseCompare(a, b) {
    var houseArea = Math.pow(a, 2) + (a * b) / 2;
    var treeArea = b * (b / 3) + Math.PI * Math.pow(b * 2 / 3, 2);
    return houseArea > treeArea ? 'house/' + houseArea.toFixed(2) : 'tree/' +  treeArea.toFixed(2);
}

console.log(treeHouseCompare(3, 2)); //house/12.00
console.log(treeHouseCompare(3, 3)); //tree/15.57
console.log(treeHouseCompare(4, 5)); //tree/43.24


text:
package org.ovirt.engine.ui.uicommonweb.models.events;

import org.ovirt.engine.core.common.businessentities.AuditLog;
import org.ovirt.engine.ui.uicommonweb.models.Model;

public class EventModel extends Model {

    private AuditLog event;

    public AuditLog getEvent() {
        return event;
    }

    public void setEvent(AuditLog event) {
        this.event = event;
    }

}


text:
<?
include "config.php";
include "header.php";
echo "
That page does not exist.
";
?>

Please select a section from above or below.

Semiconductors

Passives

Electromechanical

Interconnects

Reports

<? if($_SERVER['PHP_AUTH_USER']=="benjamin") echo "Access: Full";
else echo "Access: Read-Only";

?>


text:
class CreateIndicesForGoogleStats < ActiveRecord::Migration
  def self.up
    execute('create index taxon_concept_id on google_analytics_page_stats(taxon_concept_id)')
    execute('create index user_month on google_analytics_partner_taxa(user_id, month)')
  end

  def self.down
    remove_index :google_analytics_page_stats, :taxon_concept_id
    remove_index :google_analytics_partner_taxa, :user_month
  end
end


text:
import { coerceBooleanProperty, coerceNumberProperty } from '@angular/cdk/coercion';

export function isPresent(obj: any): boolean {
    return obj !== undefined && obj !== null;
}

export function isDate(obj: any): boolean {
    return !/Invalid|NaN/.test(new Date(obj).toString());
}

export function isNumeric(value: any): boolean {
    return !isNaN(value - parseFloat(value));
}

export function isEmptyArray(arr: any): boolean {
    if (Array.isArray(arr)) {
        return arr.length === 0 || arr.every(i => !i);
    }
    return false;
}

export function arrayEquals<T>(array1: T[], array2: T[]): boolean {
    if (!array1 || !array2 || array1.length !== array2.length) {
        return false;
    }

    const len = array1.length;
    for (let i = 0; i < len; i++) {
        if (array1[i] !== array2[i]) {
            return false;
        }
    }
    return true;
}

export function toArray<T>(value: T | T[]): T[] {
    let ret: T[];
    if (value === undefined || value == null) {
        ret = [];
    } else if (!Array.isArray(value)) {
        ret = [value];
    } else {
        ret = value;
    }
    return ret;
}

export function toBoolean(value: boolean | string): boolean {
  return coerceBooleanProperty(value);
}

export function toNumber<D>(value: number | string, fallback: D): number | D {
  return coerceNumberProperty(value, fallback);
}