text:
using System;
using System.Globalization;

namespace PowerLib.System.Globalization
{
	/// <summary>
	/// Calendar extension methods
	/// </summary>
	public static class CalendarExtension
	{
		public const int FractionTicks = 10000;
		public const int MillisecondsPerSecond = 1000;
		public const int SecondsPerMinute = 60;
		public const int MinutesPerHour = 60;
		public const int HoursPerDay = 24;
		public const int DaysInWeek = 7;

		/// <summary>
		/// Get day ordinal number in week
		/// </summary>
		/// <param name="currDayOfWeek">Current day of week</param>
		/// <param name="firstDayOfWeek">First day of week</param>
		/// <returns>Day ordinal number</returns>
		public static int GetOrdinalByDayOfWeek(DayOfWeek currDayOfWeek, DayOfWeek firstDayOfWeek)
		{
			return (int)currDayOfWeek - (int)firstDayOfWeek + ((currDayOfWeek >= firstDayOfWeek) ? 1 : 8);
		}

		/// <summary>
		/// Get day of week
		/// </summary>
		/// <param name="ordinal">Day ordinal number in week</param>
		/// <param name="firstDayOfWeek">First day of week</param>
		/// <returns>Day of week</returns>
		public static DayOfWeek GetDayOfWeekByOrdinal(int ordinal, DayOfWeek firstDayOfWeek)
		{
			if (ordinal < 1 || ordinal > 7)
				throw new ArgumentOutOfRangeException("ordinal");
			return (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), ((int)firstDayOfWeek + ordinal - 1) % 7);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="millenia"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddMillenia(this Calendar calendar, DateTime dtm, int millenia, bool eraBound)
		{
			DateTime dtmResult = calendar.AddYears(dtm, millenia * 1000);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="centuries"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddCenturies(this Calendar calendar, DateTime dtm, int centuries, bool eraBound)
		{
			DateTime dtmResult = calendar.AddYears(dtm, centuries * 100);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="years"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddYears(this Calendar calendar, DateTime dtm, int years, bool eraBound)
		{
			DateTime dtmResult = calendar.AddYears(dtm, years);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="halves"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddHalves(this Calendar calendar, DateTime dtm, int halves, bool eraBound)
		{
			int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtm), calendar.GetEra(dtm));
			if (monthsInYear % 2 != 0)
				throw new InvalidOperationException();
			DateTime dtmResult = calendar.AddYears(dtm, halves / 2);
			dtmResult = calendar.AddMonths(dtmResult, monthsInYear / 2 * halves % 2);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="quarters"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddQuarters(this Calendar calendar, DateTime dtm, int quarters, bool eraBound)
		{
			int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtm), calendar.GetEra(dtm));
			if (monthsInYear % 4 != 0)
				throw new InvalidOperationException();
			DateTime dtmResult = calendar.AddYears(dtm, quarters / 4);
			dtmResult = calendar.AddMonths(dtm, monthsInYear / 4 * quarters % 4);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="months"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddMonths(this Calendar calendar, DateTime dtm, int months, bool eraBound)
		{
			DateTime dtmResult = calendar.AddMonths(dtm, months);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="weeks"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddWeeks(this Calendar calendar, DateTime dtm, int weeks, bool eraBound)
		{
			DateTime dtmResult = calendar.AddWeeks(dtm, weeks);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="weeks"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddWeeks(this Calendar calendar, DateTime dtm, int weeks, DayOfWeek firstDayOfWeek, bool eraBound)
		{
			DateTime dtmResult;
			if (weeks > 0)
			{
				dtmResult = calendar.AddDays(dtm, 8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(dtm), firstDayOfWeek));
				weeks -= 1;
			}
			else if (weeks < 0)
			{
				dtmResult = calendar.AddDays(dtm, -6 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(dtm), firstDayOfWeek));
				weeks += 1;
			}
			else
				dtmResult = dtm;
			if (weeks != 0)
				dtmResult = calendar.AddWeeks(dtmResult, weeks);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="days"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddDays(this Calendar calendar, DateTime dtm, int days, bool eraBound)
		{
			DateTime dtmResult = calendar.AddDays(dtm, days);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="hours"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddHours(this Calendar calendar, DateTime dtm, int hours, bool eraBound)
		{
			DateTime dtmResult = calendar.AddHours(dtm, hours);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="minutes"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddMinutes(this Calendar calendar, DateTime dtm, int minutes, bool eraBound)
		{
			DateTime dtmResult = calendar.AddMinutes(dtm, minutes);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="seconds"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddSeconds(this Calendar calendar, DateTime dtm, int seconds, bool eraBound)
		{
			DateTime dtmResult = calendar.AddSeconds(dtm, seconds);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="milliseconds"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddMilliseconds(this Calendar calendar, DateTime dtm, int milliseconds, bool eraBound)
		{
			DateTime dtmResult = calendar.AddMilliseconds(dtm, milliseconds);
			if (eraBound && calendar.GetEra(dtm) != calendar.GetEra(dtmResult))
				throw new ArgumentException("The resulting DateTime is outside the supported range of era");
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="dtmPrecision"></param>
		/// <param name="units"></param>
		/// <param name="eraBound"></param>
		/// <returns></returns>
		public static DateTime AddUnits(this Calendar calendar, DateTime dtm, DateTimePrecision dtmPrecision, int units, bool eraBound)
		{
			switch (dtmPrecision)
			{
				case DateTimePrecision.Millenium:
					return AddMillenia(calendar, dtm, units, eraBound);
				case DateTimePrecision.Century:
					return AddCenturies(calendar, dtm, units, eraBound);
				case DateTimePrecision.Year:
					return AddYears(calendar, dtm, units, eraBound);
				case DateTimePrecision.Half:
					return AddHalves(calendar, dtm, units, eraBound);
				case DateTimePrecision.Quarter:
					return AddQuarters(calendar, dtm, units, eraBound);
				case DateTimePrecision.Month:
					return AddMonths(calendar, dtm, units, eraBound);
				case DateTimePrecision.Week:
					return AddWeeks(calendar, dtm, units, eraBound);
				case DateTimePrecision.Day:
					return AddDays(calendar, dtm, units, eraBound);
				case DateTimePrecision.Hour:
					return AddHours(calendar, dtm, units, eraBound);
				case DateTimePrecision.Minute:
					return AddMinutes(calendar, dtm, units, eraBound);
				case DateTimePrecision.Second:
					return AddSeconds(calendar, dtm, units, eraBound);
				case DateTimePrecision.Millisecond:
					return AddMilliseconds(calendar, dtm, units, eraBound);
				default:
					throw new ArgumentException("Invalid datetime precision", "dtmPrecision");
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <returns></returns>
		public static int GetMonthsInYear(this Calendar calendar, int year)
		{
			return calendar.GetMonthsInYear(year);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetMonthsInYear(this Calendar calendar, int year, int era)
		{
			return calendar.GetMonthsInYear(year, era);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static int GetWeeksInYear(this Calendar calendar, int year, DayOfWeek firstDayOfWeek)
		{
			int daysInYear = calendar.GetDaysInYear(year);
			int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.ToDateTime(year, 1, 1, 0, 0, 0, 0)), firstDayOfWeek)) % 7;
			return ((partialDays > 0) ? 1 : 0) + (daysInYear - partialDays) / 7 + (((daysInYear - partialDays) % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetWeeksInYear(this Calendar calendar, int year, DayOfWeek firstDayOfWeek, int era)
		{
			int daysInYear = calendar.GetDaysInYear(year, era);
			int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.ToDateTime(year, 1, 1, 0, 0, 0, 0, era)), firstDayOfWeek)) % 7;
			return ((partialDays > 0) ? 1 : 0) + (daysInYear - partialDays) / 7 + (((daysInYear - partialDays) % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <returns></returns>
		public static int GetWeeksInYear(this Calendar calendar, int year)
		{
			int daysInYear = calendar.GetDaysInYear(year);
			return daysInYear / 7 + ((daysInYear % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetWeeksInYear(this Calendar calendar, int year, int era)
		{
			int daysInYear = calendar.GetDaysInYear(year, era);
			return daysInYear / 7 + ((daysInYear % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static int GetWeeksInMonth(this Calendar calendar, int year, int month, DayOfWeek firstDayOfWeek)
		{
			int daysInMonth = calendar.GetDaysInMonth(year, month);
			int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.ToDateTime(year, month, 1, 0, 0, 0, 0)), firstDayOfWeek)) % 7;
			return ((partialDays > 0) ? 1 : 0) + (daysInMonth - partialDays) / 7 + (((daysInMonth - partialDays) % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetWeeksInMonth(this Calendar calendar, int year, int month, DayOfWeek firstDayOfWeek, int era)
		{
			int daysInMonth = calendar.GetDaysInMonth(year, month, era);
			int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.ToDateTime(year, month, 1, 0, 0, 0, 0, era)), firstDayOfWeek)) % 7;
			return ((partialDays > 0) ? 1 : 0) + (daysInMonth - partialDays) / 7 + (((daysInMonth - partialDays) % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <returns></returns>
		public static int GetWeeksInMonth(this Calendar calendar, int year, int month)
		{
			int daysInMonth = calendar.GetDaysInMonth(year, month);
			return daysInMonth / 7 + ((daysInMonth % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetWeeksInMonth(this Calendar calendar, int year, int month, int era)
		{
			int daysInMonth = calendar.GetDaysInMonth(year, month, era);
			return daysInMonth / 7 + ((daysInMonth % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <returns></returns>
		public static int GetDaysInYear(this Calendar calendar, int year)
		{
			return calendar.GetDaysInYear(year);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetDaysInYear(this Calendar calendar, int year, int era)
		{
			return calendar.GetDaysInYear(year, era);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <returns></returns>
		public static int GetDaysInMonth(this Calendar calendar, int year, int month)
		{
			return calendar.GetDaysInMonth(year, month);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static int GetDaysInMonth(this Calendar calendar, int year, int month, int era)
		{
			return calendar.GetDaysInMonth(year, month, era);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetEra(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetEra(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetMillenium(this Calendar calendar, DateTime dtm)
		{
			return (calendar.GetYear(dtm) - 1) / 1000 + 1;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetCentury(this Calendar calendar, DateTime dtm)
		{
			return (calendar.GetYear(dtm) - 1) / 100 + 1;
		}

		public static int GetYear(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetYear(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetMonth(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetMonth(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetQuarter(this Calendar calendar, DateTime dtm)
		{
			int monthsInYear = calendar.GetMonthsInYear(calendar.GetMonth(dtm));
			if (monthsInYear % 4 != 0)
				throw new NotSupportedException();
			int monthOfYear = calendar.GetMonth(dtm);
			return (monthOfYear / (monthsInYear / 4)) + ((monthOfYear % (monthsInYear / 4) > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetHalf(this Calendar calendar, DateTime dtm)
		{
			int monthsInYear = calendar.GetMonthsInYear(calendar.GetMonth(dtm));
			if (monthsInYear % 2 != 0)
				throw new NotSupportedException();
			int monthOfYear = calendar.GetMonth(dtm);
			return (monthOfYear / (monthsInYear / 2)) + ((monthOfYear % (monthsInYear / 2) > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="minDaysInFirstWeek"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static int GetWeekOfYear(this Calendar calendar, DateTime dtm, int minDaysInFirstWeek, DayOfWeek firstDayOfWeek)
		{
			if (minDaysInFirstWeek < 1 || minDaysInFirstWeek > 7)
				throw new ArgumentOutOfRangeException("MinDaysInWeek");
			int dayOfYear = calendar.GetDayOfYear(dtm);
			int daysInYear = calendar.GetDaysInYear(calendar.GetYear(dtm));
			int dayOrdinal = GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(dtm), firstDayOfWeek);
			if (dayOrdinal - dayOfYear > 7 - minDaysInFirstWeek)
				return GetWeekOfYear(calendar, calendar.AddDays(dtm, -dayOfYear), minDaysInFirstWeek, firstDayOfWeek);
			else if (daysInYear - dayOfYear + dayOrdinal <= 7 - minDaysInFirstWeek)
				return GetWeekOfYear(calendar, calendar.AddDays(dtm, daysInYear - dayOfYear + 1), minDaysInFirstWeek, firstDayOfWeek);
			else
			{
				int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.AddDays(dtm, -dayOfYear + 1)), firstDayOfWeek)) % 7;
				return ((partialDays >= minDaysInFirstWeek) ? 1 : 0) + (dayOfYear - partialDays) / 7 + (((dayOfYear - partialDays) % 7 > 0) ? 1 : 0);
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetWeekOfYear(this Calendar calendar, DateTime dtm)
		{
			int dayOfYear = calendar.GetDayOfYear(dtm);
			return dayOfYear / 7 + ((dayOfYear % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static int GetWeekOfMonth(this Calendar calendar, DateTime dtm, DayOfWeek firstDayOfWeek)
		{
			int dayOfMonth = calendar.GetDayOfMonth(dtm);
			int partialDays = (8 - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(calendar.AddDays(dtm, -calendar.GetDayOfMonth(dtm) + 1)), firstDayOfWeek)) % 7;
			return ((partialDays > 0) ? 1 : 0) + (dayOfMonth - partialDays) / 7 + (((dayOfMonth - partialDays) % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetWeekOfMonth(this Calendar calendar, DateTime dtm)
		{
			int dayOfMonth = calendar.GetDayOfMonth(dtm);
			return dayOfMonth / 7 + ((dayOfMonth % 7 > 0) ? 1 : 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetDayOfYear(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetDayOfYear(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetDayOfMonth(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetDayOfMonth(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static DayOfWeek GetDayOfWeek(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetDayOfWeek(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetHour(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetHour(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetMinute(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetMinute(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static int GetSecond(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetSecond(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <returns></returns>
		public static double GetMilliseconds(this Calendar calendar, DateTime dtm)
		{
			return calendar.GetMilliseconds(dtm);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="day"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int day)
		{
			return calendar.ToDateTime(year, month, day, 0, 0, 0, 0);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="day"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int day, int era)
		{
			return calendar.ToDateTime(year, month, day, 0, 0, 0, 0, era);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="minDaysInFirstWeek"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int week, DayOfWeek day, int minDaysInFirstWeek, DayOfWeek firstDayOfWeek)
		{
			if (week < 1)
				throw new ArgumentOutOfRangeException("week");
			DateTime first = calendar.ToDateTime(year, 1, 1, 0, 0, 0, 0);
			int firstOrdinal = GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(first), firstDayOfWeek);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, firstDayOfWeek);
			int daysOffset = dayOrdinal - firstOrdinal;
			if ((week -= (8 - firstOrdinal >= minDaysInFirstWeek) ? 1 : 0) > 0)
				daysOffset += 7 + (week - 1) * 7;
			if (daysOffset >= calendar.GetDaysInYear(year))
				throw new ArgumentException("Exceeds days in year");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="minDaysInFirstWeek"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int week, DayOfWeek day, int minDaysInFirstWeek, DayOfWeek firstDayOfWeek, int era)
		{
			if (week < 1)
				throw new ArgumentOutOfRangeException("week");
			DateTime first = calendar.ToDateTime(year, 1, 1, 0, 0, 0, 0, era);
			int firstOrdinal = GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(first), firstDayOfWeek);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, firstDayOfWeek);
			int daysOffset = dayOrdinal - firstOrdinal;
			if ((week -= (8 - firstOrdinal >= minDaysInFirstWeek) ? 1 : 0) > 0)
				daysOffset += 7 + (week - 1) * 7;
			if (daysOffset >= calendar.GetDaysInYear(year, era))
				throw new ArgumentException("Exceeds days in year");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int week, DayOfWeek day)
		{
			DateTime first = ToDateTime(calendar, year, 1, 1);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, calendar.GetDayOfWeek(first));
			int daysOffset = (week - 1) * 7 + dayOrdinal - 1;
			if (daysOffset >= calendar.GetDaysInYear(year))
				throw new ArgumentException("Exceeds days in year");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int week, DayOfWeek day, int era)
		{
			DateTime first = ToDateTime(calendar, year, 1, 1, era);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, calendar.GetDayOfWeek(first));
			int daysOffset = (week - 1) * 7 + dayOrdinal - 1;
			if (daysOffset >= calendar.GetDaysInYear(year, era))
				throw new ArgumentException("Exceeds days in year");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int week, DayOfWeek day, DayOfWeek firstDayOfWeek)
		{
			if (week < 1)
				throw new ArgumentOutOfRangeException("week");
			DateTime first = calendar.ToDateTime(year, month, 1, 0, 0, 0, 0);
			int firstOrdinal = GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(first), firstDayOfWeek);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, firstDayOfWeek);
			int daysOffset = dayOrdinal - firstOrdinal;
			if (--week > 0)
				daysOffset += 7 + (week - 1) * 7;
			if (daysOffset >= calendar.GetDaysInMonth(year, month))
				throw new ArgumentException("Exceeds days in month");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int week, DayOfWeek day, DayOfWeek firstDayOfWeek, int era)
		{
			if (week < 1)
				throw new ArgumentOutOfRangeException("week");
			DateTime first = calendar.ToDateTime(year, month, 1, 0, 0, 0, 0, era);
			int firstOrdinal = GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(first), firstDayOfWeek);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, firstDayOfWeek);
			int daysOffset = dayOrdinal - firstOrdinal;
			if (--week > 0)
				daysOffset += 7 + (week - 1) * 7;
			if (daysOffset >= calendar.GetDaysInMonth(year, month, era))
				throw new ArgumentException("Exceeds days in month");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int week, DayOfWeek day)
		{
			DateTime first = ToDateTime(calendar, year, month, 1);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, calendar.GetDayOfWeek(first));
			int daysOffset = (week - 1) * 7 + dayOrdinal - 1;
			if (daysOffset >= calendar.GetDaysInMonth(year, month))
				throw new ArgumentException("Exceeds days in month");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="year"></param>
		/// <param name="month"></param>
		/// <param name="week"></param>
		/// <param name="day"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime ToDateTime(this Calendar calendar, int year, int month, int week, DayOfWeek day, int era)
		{
			DateTime first = ToDateTime(calendar, year, month, 1, era);
			int dayOrdinal = GetOrdinalByDayOfWeek(day, calendar.GetDayOfWeek(first));
			int daysOffset = (week - 1) * 7 + dayOrdinal - 1;
			if (daysOffset >= calendar.GetDaysInMonth(year, month, era))
				throw new ArgumentException("Exceeds days in month");
			return calendar.AddDays(first, daysOffset);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="dtmPrecision"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static DateTime GetMinDateTime(this Calendar calendar, DateTime dtm, DateTimePrecision dtmPrecision, DayOfWeek firstDayOfWeek)
		{
			DateTime dtmResult;
			if (dtmPrecision == DateTimePrecision.Era)
			{
				dtmResult = GetEraMinDateTime(calendar, calendar.GetEra(dtm));
			}
			else
			{
				dtmResult = dtm;
				if (dtmPrecision != DateTimePrecision.Tick)
				{
					dtmResult -= TimeSpan.FromTicks(dtmResult.Ticks % FractionTicks);
					if (dtmPrecision != DateTimePrecision.Millisecond)
					{
						dtmResult = AddMilliseconds(calendar, dtmResult, -(int)calendar.GetMilliseconds(dtmResult), true);
						if (dtmPrecision != DateTimePrecision.Second)
						{
							dtmResult = AddSeconds(calendar, dtmResult, -calendar.GetSecond(dtmResult), true);
							if (dtmPrecision != DateTimePrecision.Minute)
							{
								dtmResult = AddMinutes(calendar, dtmResult, -calendar.GetMinute(dtmResult), true);
								if (dtmPrecision != DateTimePrecision.Hour)
								{
									dtmResult = AddHours(calendar, dtmResult, -calendar.GetHour(dtmResult), true);
									if (dtmPrecision != DateTimePrecision.Day)
									{
										try
										{
											if (dtmPrecision == DateTimePrecision.Week)
											{
												dtmResult = AddDays(calendar, dtmResult, -(GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(dtmResult), firstDayOfWeek) - 1), true);
											}
											else
											{
												if (dtmPrecision == DateTimePrecision.Quarter)
												{
													int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtmResult), calendar.GetEra(dtmResult));
													if (monthsInYear % 4 != 0)
														throw new InvalidOperationException("Incompatible datetime precision");
													dtmResult = AddMonths(calendar, dtmResult, -(calendar.GetMonth(dtmResult) - 1) % (monthsInYear / 4), true);
												}
												else if (dtmPrecision == DateTimePrecision.Half)
												{
													int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtmResult), calendar.GetEra(dtmResult));
													if (monthsInYear % 2 != 0)
														throw new InvalidOperationException("Incompatible datetime precision");
													dtmResult = AddMonths(calendar, dtmResult, -(calendar.GetMonth(dtmResult) - 1) % (monthsInYear / 2), true);
												}
												else if (dtmPrecision != DateTimePrecision.Month)
												{
													if (dtmPrecision == DateTimePrecision.Millenium)
														dtmResult = AddMillenia(calendar, dtmResult, -(calendar.GetYear(dtmResult) - 1 % 1000), true);
													else if (dtmPrecision == DateTimePrecision.Century)
														dtmResult = AddYears(calendar, dtmResult, -(calendar.GetYear(dtmResult) - 1 % 100), true);

													dtmResult = AddMonths(calendar, dtmResult, -(calendar.GetMonth(dtmResult) - 1), true);
												}
												dtmResult = AddDays(calendar, dtmResult, -(calendar.GetDayOfMonth(dtmResult) - 1), true);
											}
										}
										catch (ArgumentException ex)
										{
											if (ex.ParamName != null)
												throw ex;
											dtmResult = GetEraMinDateTime(calendar, calendar.GetEra(dtm));
										}
									}
								}
							}
						}
					}
				}
			}
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="dtm"></param>
		/// <param name="dtmPrecision"></param>
		/// <param name="firstDayOfWeek"></param>
		/// <returns></returns>
		public static DateTime GetMaxDateTime(this Calendar calendar, DateTime dtm, DateTimePrecision dtmPrecision, DayOfWeek firstDayOfWeek)
		{
			DateTime dtmResult;
			if (dtmPrecision == DateTimePrecision.Era)
			{
				dtmResult = GetEraMaxDateTime(calendar, calendar.GetEra(dtm));
			}
			else
			{
				dtmResult = dtm;
				if (dtmPrecision != DateTimePrecision.Tick)
				{
					dtmResult += TimeSpan.FromTicks(FractionTicks - 1 - dtmResult.Ticks % FractionTicks);
					if (dtmPrecision != DateTimePrecision.Millisecond)
					{
						dtmResult = AddMilliseconds(calendar, dtmResult, MillisecondsPerSecond - 1 - (int)calendar.GetMilliseconds(dtmResult), true);
						if (dtmPrecision != DateTimePrecision.Second)
						{
							dtmResult = AddSeconds(calendar, dtmResult, SecondsPerMinute - 1 - calendar.GetSecond(dtmResult), true);
							if (dtmPrecision != DateTimePrecision.Minute)
							{
								dtmResult = AddMinutes(calendar, dtmResult, MinutesPerHour - 1 - calendar.GetMinute(dtmResult), true);
								if (dtmPrecision != DateTimePrecision.Hour)
								{
									dtmResult = AddHours(calendar, dtmResult, HoursPerDay - 1 - calendar.GetHour(dtmResult), true);
									if (dtmPrecision != DateTimePrecision.Day)
									{
										try
										{
											if (dtmPrecision == DateTimePrecision.Week)
											{
												dtmResult = AddDays(calendar, dtmResult, DaysInWeek - GetOrdinalByDayOfWeek(calendar.GetDayOfWeek(dtmResult), firstDayOfWeek), true);
											}
											else
											{
												if (dtmPrecision == DateTimePrecision.Quarter)
												{
													int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtmResult), calendar.GetEra(dtmResult));
													if (monthsInYear % 4 != 0)
														throw new InvalidOperationException("Incompatible datetime precision");
													dtmResult = AddMonths(calendar, dtmResult, monthsInYear / 4 - calendar.GetMonth(dtmResult) % (monthsInYear / 4), true);
												}
												else if (dtmPrecision == DateTimePrecision.Half)
												{
													int monthsInYear = calendar.GetMonthsInYear(calendar.GetYear(dtmResult), calendar.GetEra(dtmResult));
													if (monthsInYear % 2 != 0)
														throw new InvalidOperationException("Incompatible datetime precision");
													dtmResult = AddMonths(calendar, dtmResult, monthsInYear / 2 - calendar.GetMonth(dtmResult) % (monthsInYear / 2), true);
												}
												else if (dtmPrecision != DateTimePrecision.Month)
												{
													if (dtmPrecision == DateTimePrecision.Millenium)
														dtmResult = AddMillenia(calendar, dtmResult, 1000 -calendar.GetYear(dtmResult) % 100 , true);
													else if (dtmPrecision == DateTimePrecision.Century)
														dtmResult = AddYears(calendar, dtmResult, 100 - calendar.GetYear(dtmResult) % 100, true);
													dtmResult = AddMonths(calendar, dtmResult, calendar.GetMonthsInYear(calendar.GetYear(dtmResult), calendar.GetEra(dtmResult)) - calendar.GetMonth(dtmResult), true);
												}
												dtmResult = AddDays(calendar, dtmResult, calendar.GetDaysInMonth(calendar.GetYear(dtmResult), calendar.GetMonth(dtmResult), calendar.GetEra(dtmResult)) - calendar.GetDayOfMonth(dtmResult), true);
											}
										}
										catch (ArgumentException ex)
										{
											if (ex.ParamName != null)
												throw ex;
											dtmResult = GetEraMaxDateTime(calendar, calendar.GetEra(dtm));
										}
									}
								}
							}
						}
					}
				}
			}
			return dtmResult;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime GetEraMinDateTime(this Calendar calendar, int era)
		{
			if (era <= 0 || era > calendar.Eras.Length)
				throw new ArgumentOutOfRangeException("era");
			else if (era == 1)
				return calendar.MinSupportedDateTime;
			else
			{
				DateTime dtm = calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era);
				int pastDays = calendar.GetDaysInYear(1, era) - 1;
				DateTime dtmUp = calendar.AddDays(dtm, pastDays);
				while (calendar.GetEra(dtm) != era)
				{
					for (DateTime dtmMid = calendar.AddDays(dtmUp, -(pastDays / 2 + pastDays % 2));
						calendar.GetEra(dtmMid) >= era && pastDays != 0;
						dtmMid = calendar.AddDays(dtmUp, -(pastDays / 2 + pastDays % 2)))
					{
						dtmUp = dtmMid;
						pastDays = (dtmUp - dtm).Days;
					}
					for (DateTime dtmMid = calendar.AddDays(dtm, (pastDays / 2 + pastDays % 2));
						calendar.GetEra(dtmMid) < era || pastDays == 1;
						dtmMid = calendar.AddDays(dtm, (pastDays / 2 + pastDays % 2)))
					{
						dtm = dtmMid;
						pastDays = (dtmUp - dtm).Days;
					}
				}
				return dtm;
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="era"></param>
		/// <returns></returns>
		public static DateTime GetEraMaxDateTime(this Calendar calendar, int era)
		{
			if (era <= 0 || era > calendar.Eras.Length)
				throw new ArgumentOutOfRangeException("era");
			else if (era == calendar.Eras.Length)
				return calendar.MaxSupportedDateTime;
			else
				return GetEraMinDateTime(calendar, era + 1) - TimeSpan.FromTicks(1);
		}
	}
}


text:
using System;
using System.IO;
using PullRequestReleaseNotes.Models;

namespace PullRequestReleaseNotes.Publishers
{
    public static class FilePublisher
    {
        public static bool PublishMarkdownReleaseHistoryFile(string releaseHistoryMarkdown, ProgramArgs programArgs)
        {
            try
            {
                File.WriteAllText(programArgs.OutputFileName, releaseHistoryMarkdown);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to save release notes to file: {programArgs.OutputFileName}. Exception: {e.Message}");
                return false;
            }
            return true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package codeu.chat.server.bots;

import java.util.ArrayList;

import codeu.chat.util.CommandTokenizer;
import codeu.chat.util.Uuid;
import codeu.chat.common.Bot;

public class HangmanBot extends Bot {

	private String word;
	private String guessString = "";
	private int lives = 6;

	public String loseOrRejectGuessWith(String message) {
		lives -= 1;
		if (lives < 0) {
			String returnMessage = "Out of lives! Sorry but you lose! The word was " + word;
			word = null;
			return returnMessage;
		}
		message += "\n" + lives + " lives left!";
		return message;
	}

	@Override
	public String reactTo(String message, Uuid sender) {
		// turn the message into a command
		CommandTokenizer tokenizer = new CommandTokenizer(message);
		String command = tokenizer.getCommand();
		ArrayList<String> args = (ArrayList<String>) tokenizer.getRemainingArgs();

		switch (command) {
		// resets the guesstring to a string of x dashes where x is the length of the
		// new given word.
		// resets lives to 6
		case "hangman-start":
			word = args.get(0).toLowerCase();
			guessString = "";
			for (int i = 0; i < word.length(); i++) {
				guessString += "-";
			}
			lives = 6;
			return "Welcome to your hangman! To guess, please use \"hangman-guess <guessLetter>\"";
		case "hangman-guess":
			// if game not yet started
			if (word == null) {
				return "Please start a hangman game before you start guessing!";
			}
			// gets the guess string or single character
			String guess = args.get(0).toLowerCase();
			// if it's a word
			if (guess.length() > 1) {
				// check if the guessed word is correct
				if (word.equals(guess)) {
					String returnMessage = "You did it! You win! The word was " + word;
					word = null;
					return returnMessage;
				} else {
					return loseOrRejectGuessWith("Nope! The word certainly isn't \"" + guess + "\"");
				}
			} else {
				int lastIndexOfLetter = -1;
				// Loop through all the insances of the guessed character
				// each time, replace the dash in guesstring with the actual letter
				while (word.indexOf(guess, lastIndexOfLetter) != -1) {
					lastIndexOfLetter = word.indexOf(guess, lastIndexOfLetter);
					System.out.println("lastIndex" + lastIndexOfLetter);
					guessString = guessString.substring(0, lastIndexOfLetter) + guess
							+ guessString.substring(lastIndexOfLetter + 1);
					// this is done because indexOf includes the starting index
					lastIndexOfLetter++;
				}
				// if the guess was not found inside of the word
				if (lastIndexOfLetter == -1) {
					return loseOrRejectGuessWith(
							"Nope! Sorry but the word does not contain any " + guess + "'s...\n" + guessString);
				}
				// if the guessString is out of dashes and is complete
				if (guessString.equals(word)) {
					String returnMessage = "You did it! You win! The word was " + word;
					word = null;
					return returnMessage;
				}
				return "Yay! Correct!\n" + guessString;
			}
		default:
			return null;
		}

	}

	@Override
	public String onAdd() {
		return "Hey All! Type \"hangman-start <Word>\" to play some hangman!";
	}

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="10dp"
        android:layout_gravity="center_horizontal"
        android:adjustViewBounds="true"
        android:src="@drawable/scale" >
    </ImageView>

    <TextView
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textSize="15sp" >
    </TextView>

</LinearLayout>


text:
copyright:
  years: 2017
lastupdated: "2017-05-08"

---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:pre: .pre}

# Customizing the login widget
{: #login-widget}

You can configure your login widget to display the logo and colors of your choice.
{:shortdesc}

When the {{site.data.keyword.appid_short}} service is configured with two or more identity providers, the user can select an identity provider in the login widget. You can customize your login widget by completing the following steps:

1. Open the {{site.data.keyword.appid_short_notm}} service dashboard.
2. Select the **Login Customization** section, where you can modify the appearance of the login widget to align with your company's brand.
3. Upload your company's logo by selecting a PNG or JPG file from your local system. The recommended image size is 320 x 320 pixels. The maximum file size is 100 Kb.
4. Select a header color for the widget from the color picker, or enter the hex code for another color.
5. Inspect the preview pane, and click **Save Changes** when you are happy with your customizations. A confirmation message is displayed.

You are not required to rebuild your application. The image is stored in the {{site.data.keyword.appid_short}} database and is displayed at the next login.


text:
class AsyncWorker : public Nan::AsyncWorker {
  public:
    AsyncWorker(Nan::Callback *callback)
      : Nan::AsyncWorker(callback), errtype_(Error) {};

    enum ErrorType {
      Error,
      TypeError,
      RangeError
    };

    void SetError(ErrorType errtype, const char* msg) {
      errtype_ = errtype;
      SetErrorMessage(msg);
    }

    void HandleErrorCallback() {
      Nan::HandleScope scope;

      v8::Local<v8::Value> err;
      switch (errtype_) {
        case TypeError:
          err = v8::Exception::TypeError(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked());
          break;
        case RangeError:
          err = v8::Exception::RangeError(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked());
          break;
        default:
          err = v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked());
          break;
      }

      v8::Local<v8::Value> argv[] = {err};
      callback->Call(1, argv);
    }

  protected:
    ErrorType errtype_;
};

#endif


text:
package networkmachine

import (
	"bytes"
	"encoding/json"
	"fmt"
	"hps"
)

type Machine struct {
	name       string
	kind       string
	properties map[string]*hps.Property
	machines   []hps.IMachine
}

func NewMachine(name string, kind string) *Machine {
	m := &Machine{}
	m.name = name
	m.kind = kind
	m.properties = map[string]*hps.Property{}
	m.machines = []hps.IMachine{}
	_ = hps.IMachine(m)
	_ = INetworkMachine(m)
	return m
}

func (m *Machine) Name() string {
	return m.name
}

func (m *Machine) Kind() string {
	return m.kind
}

func (m *Machine) Event(time float64) (hps.IEvent, bool) {
	var event hps.IEvent = nil

	for _, mm := range m.machines {
		if e, ok := mm.Event(time); ok && (event == nil || event.Time() > e.Time()) {
			event = e
		}
	}

	return event, event != nil
}

func (m *Machine) Properties() []*hps.Property {
	list := []*hps.Property{}
	for _, p := range m.properties {
		list = append(list, p)
	}
	return list
}

func (m *Machine) AddProperty(name, dataType string) *hps.Property {
	p := hps.NewProperty(name, dataType)
	m.properties[name] = p
	return p
}

func (m *Machine) Property(name string) (*hps.Property, bool) {
	p, ok := m.properties[name]
	return p, ok
}

func (m *Machine) AddMachine(machine hps.IMachine) error {
	if _, ok := m.GetMachine(machine.Name()); ok {
		return fmt.Errorf("A machine named \"%s\" already exists in this network.")
	}
	m.machines = append(m.machines, machine)
	return nil
}

func (m *Machine) GetMachine(name string) (hps.IMachine, bool) {
	for _, sm := range m.machines {
		if sm.Name() == name {
			return sm, true
		}
	}
	return nil, false
}

func (m *Machine) Machines() []hps.IMachine {
	list := []hps.IMachine{}
	for _, v := range m.machines {
		list = append(list, v)
	}
	return list
}

func (m *Machine) MarshalJSON() ([]byte, error) {
	machines, _ := m.MarshalMachinesJSON()
	content, _ := json.Marshal(struct {
		Machines *json.RawMessage `json:"machines"`
	}{(*json.RawMessage)(&machines)})

	properties, _ := m.MarshalPropertiesJSON()

	return json.Marshal(struct {
		Name       string           `json:"name"`
		Machine    string           `json:"machine"`
		Content    *json.RawMessage `json:"content"`
		Properties *json.RawMessage `json:"properties"`
	}{m.Name(), m.Kind(), (*json.RawMessage)(&content), (*json.RawMessage)(&properties)})
}

func (m *Machine) MarshalPropertiesJSON() ([]byte, error) {
	buf := bytes.Buffer{}
	buf.WriteString("{")
	for i, property := range m.Properties() {
		if i != 0 {
			buf.WriteString(",")
		}
		key, _ := json.Marshal(property.Name())
		buf.Write(key)
		buf.WriteString(":")
		value, _ := json.Marshal(property)
		buf.Write(value)
	}
	buf.WriteString("}")
	return buf.Bytes(), nil
}

func (m *Machine) MarshalMachinesJSON() ([]byte, error) {
	buf := bytes.Buffer{}
	buf.WriteString("{")
	for i, machine := range m.Machines() {
		if i != 0 {
			buf.WriteString(",")
		}
		key, _ := json.Marshal(machine.Name())
		buf.Write(key)
		buf.WriteString(":")
		value, _ := json.Marshal(machine)
		buf.Write(value)
	}
	buf.WriteString("}")
	return buf.Bytes(), nil
}


text:
<!DOCTYPE html>

        <title>Customer</title>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />

        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />

        <link rel="stylesheet" href="css/ionic.min.css">
        <link rel="stylesheet" href="css/login.css">

        <ion-side-menus>

            <ion-side-menu-content edge-drag-threshold="25">
                <ion-nav-bar class="bar-positive">
                    <ion-nav-back-button class="button-icon ion-arrow-left-c">
                    </ion-nav-back-button>
                </ion-nav-bar>
                <ion-nav-buttons side="left">
                    <button class="button button-icon button-clear ion-navicon" ng-click="toggleLeft()">
                    </button>
                </ion-nav-buttons>
                <ion-nav-view animation="no-animation" name="main"></ion-nav-view>
            </ion-side-menu-content>

            <ion-side-menu side="left" ng-controller="sideMenuCtrl">
                <ion-header-bar class="bar-assertive">

Ayarlar

                </ion-header-bar>
                <ion-content>

                        Login
                        Customer info
                         Logout

                </ion-content>
            </ion-side-menu>

        </ion-side-menus>


text:
<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\Tests\Models\Cache\City;
use Doctrine\Tests\Models\Cache\State;
use Doctrine\Tests\Models\Cache\Travel;
use Doctrine\Tests\Models\Cache\Traveler;

/**
 * @group DDC-2183
 */
class SecondLevelCacheOneToManyTest extends SecondLevelCacheAbstractTest
{
    public function testShouldNotPutCollectionInverseSideOnPersist()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();
        $this->_em->clear();

        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId()));
        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId()));

        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId()));
        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId()));
    }

    public function testPutAndLoadOneToManyRelation()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();
        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $this->cache->evictEntityRegion(State::CLASSNAME);
        $this->cache->evictEntityRegion(City::CLASSNAME);
        $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities');

        $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId()));
        $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId()));

        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId()));
        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId()));

        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId()));
        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId()));
        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(0)->getId()));
        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(1)->getId()));

        $s1 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());
        $s2 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId());

        $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount());
        $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount());
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::CLASSNAME)));

        //trigger lazy load
        $this->assertCount(2, $s1->getCities());
        $this->assertCount(2, $s2->getCities());

        $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount());
        $this->assertEquals(4, $this->secondLevelCacheLogger->getMissCount());
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));

        $this->assertInstanceOf(City::CLASSNAME, $s1->getCities()->get(0));
        $this->assertInstanceOf(City::CLASSNAME, $s1->getCities()->get(1));

        $this->assertInstanceOf(City::CLASSNAME, $s2->getCities()->get(0));
        $this->assertInstanceOf(City::CLASSNAME, $s2->getCities()->get(1));

        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId()));
        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId()));

        $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId()));
        $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId()));

        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId()));
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId()));
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(0)->getId()));
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(1)->getId()));

        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $queryCount = $this->getCurrentQueryCount();

        $s3 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());
        $s4 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId());

        //trigger lazy load from cache
        $this->assertCount(2, $s3->getCities());
        $this->assertCount(2, $s4->getCities());

        $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));

        $this->assertInstanceOf(City::CLASSNAME, $s3->getCities()->get(0));
        $this->assertInstanceOf(City::CLASSNAME, $s3->getCities()->get(1));
        $this->assertInstanceOf(City::CLASSNAME, $s4->getCities()->get(0));
        $this->assertInstanceOf(City::CLASSNAME, $s4->getCities()->get(1));

        $this->assertNotSame($s1->getCities()->get(0), $s3->getCities()->get(0));
        $this->assertEquals($s1->getCities()->get(0)->getId(), $s3->getCities()->get(0)->getId());
        $this->assertEquals($s1->getCities()->get(0)->getName(), $s3->getCities()->get(0)->getName());

        $this->assertNotSame($s1->getCities()->get(1), $s3->getCities()->get(1));
        $this->assertEquals($s1->getCities()->get(1)->getId(), $s3->getCities()->get(1)->getId());
        $this->assertEquals($s1->getCities()->get(1)->getName(), $s3->getCities()->get(1)->getName());

        $this->assertNotSame($s2->getCities()->get(0), $s4->getCities()->get(0));
        $this->assertEquals($s2->getCities()->get(0)->getId(), $s4->getCities()->get(0)->getId());
        $this->assertEquals($s2->getCities()->get(0)->getName(), $s4->getCities()->get(0)->getName());

        $this->assertNotSame($s2->getCities()->get(1), $s4->getCities()->get(1));
        $this->assertEquals($s2->getCities()->get(1)->getId(), $s4->getCities()->get(1)->getId());
        $this->assertEquals($s2->getCities()->get(1)->getName(), $s4->getCities()->get(1)->getName());

        $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals($queryCount, $this->getCurrentQueryCount());
    }

    public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();
        $this->_em->clear();

        //trigger lazy load from database
        $this->assertCount(2, $this->_em->find(State::CLASSNAME, $this->states[0]->getId())->getCities());

        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId()));
        $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId()));
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId()));
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId()));

        $queryCount = $this->getCurrentQueryCount();
        $stateId    = $this->states[0]->getId();
        $state      = $this->_em->find(State::CLASSNAME, $stateId);
        $cityId     = $this->states[0]->getCities()->get(1)->getId();

        //trigger lazy load from cache
        $this->assertCount(2, $state->getCities());
        $this->assertEquals($queryCount, $this->getCurrentQueryCount());
        $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $cityId));

        $this->cache->evictEntity(City::CLASSNAME, $cityId);

        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $cityId));
        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId));
        $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $stateId));

        $this->_em->clear();

        $state = $this->_em->find(State::CLASSNAME, $stateId);

        //trigger lazy load from database
        $this->assertCount(2, $state->getCities());
        $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());
    }

    public function testShoudNotPutOneToManyRelationOnPersist()
    {
        $this->loadFixturesCountries();
        $this->evictRegions();

        $state = new State("State Foo", $this->countries[0]);

        $this->_em->persist($state);
        $this->_em->flush();
        $this->_em->clear();

        $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $state->getId()));
        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $state->getId()));
    }

    public function testOneToManyRemove()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();
        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $this->cache->evictEntityRegion(State::CLASSNAME);
        $this->cache->evictEntityRegion(City::CLASSNAME);
        $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities');

        $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId()));
        $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId()));
        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId()));
        $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId()));

        $entity = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());

        $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::CLASSNAME)));

        //trigger lazy load
        $this->assertCount(2, $entity->getCities());

        $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount());
        $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));

        $this->assertInstanceOf(City::CLASSNAME, $entity->getCities()->get(0));
        $this->assertInstanceOf(City::CLASSNAME, $entity->getCities()->get(1));

        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $queryCount = $this->getCurrentQueryCount();
        $state      = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());

        //trigger lazy load from cache
        $this->assertCount(2, $state->getCities());

        $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));

        $city0 = $state->getCities()->get(0);
        $city1 = $state->getCities()->get(1);

        $this->assertInstanceOf(City::CLASSNAME, $city0);
        $this->assertInstanceOf(City::CLASSNAME, $city1);

        $this->assertEquals($entity->getCities()->get(0)->getName(), $city0->getName());
        $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName());

        $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals($queryCount, $this->getCurrentQueryCount());

        $state->getCities()->removeElement($city0);

        $this->_em->remove($city0);
        $this->_em->persist($state);
        $this->_em->flush();

        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $queryCount = $this->getCurrentQueryCount();
        $state      = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());

        //trigger lazy load from cache
        $this->assertCount(1, $state->getCities());

        $city1 = $state->getCities()->get(0);
        $this->assertInstanceOf(City::CLASSNAME, $city1);
        $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName());

        $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));

        $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());

        $state->getCities()->remove(0);

        $this->_em->remove($city1);
        $this->_em->persist($state);
        $this->_em->flush();

        $this->_em->clear();
        $this->secondLevelCacheLogger->clearStats();

        $queryCount = $this->getCurrentQueryCount();
        $state      = $this->_em->find(State::CLASSNAME, $this->states[0]->getId());

        $this->assertCount(0, $state->getCities());

        $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount());
        $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME)));
        $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities')));
    }

    public function testOneToManyWithEmptyRelation()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();

        $this->secondLevelCacheLogger->clearStats();
        $this->cache->evictEntityRegion(City::CLASSNAME);
        $this->cache->evictEntityRegion(State::CLASSNAME);
        $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities');
        $this->_em->clear();

        $entitiId   = $this->states[2]->getId(); // bavaria (cities count = 0)
        $queryCount = $this->getCurrentQueryCount();
        $entity     = $this->_em->find(State::CLASSNAME, $entitiId);

        $this->assertEquals(0, $entity->getCities()->count());
        $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount());

        $this->_em->clear();

        $queryCount = $this->getCurrentQueryCount();
        $entity     = $this->_em->find(State::CLASSNAME, $entitiId);

        $this->assertEquals(0, $entity->getCities()->count());
        $this->assertEquals($queryCount, $this->getCurrentQueryCount());

    }

    public function testOneToManyCount()
    {
        $this->loadFixturesCountries();
        $this->loadFixturesStates();
        $this->loadFixturesCities();

        $this->secondLevelCacheLogger->clearStats();
        $this->cache->evictEntityRegion(City::CLASSNAME);
        $this->cache->evictEntityRegion(State::CLASSNAME);
        $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities');
        $this->_em->clear();

        $entityId   = $this->states[0]->getId();
        $queryCount = $this->getCurrentQueryCount();
        $entity     = $this->_em->find(State::CLASSNAME, $entityId);

        $this->assertEquals(2, $entity->getCities()->count());
        $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount());

        $this->_em->clear();

        $queryCount = $this->getCurrentQueryCount();
        $entity     = $this->_em->find(State::CLASSNAME, $entityId);

        $this->assertEquals(2, $entity->getCities()->count());
        $this->assertEquals($queryCount, $this->getCurrentQueryCount());
    }

    public function testCacheInitializeCollectionWithNewObjects()
    {
        $this->_em->clear();
        $this->evictRegions();

        $traveler = new Traveler("Doctrine Bot");

        for ($i=0; $i<3; ++$i) {
            $traveler->getTravels()->add(new Travel($traveler));
        }

        $this->_em->persist($traveler);
        $this->_em->flush();
        $this->_em->clear();

        $this->assertCount(3, $traveler->getTravels());

        $travelerId = $traveler->getId();
        $queryCount = $this->getCurrentQueryCount();
        $entity     = $this->_em->find(Traveler::CLASSNAME, $travelerId);

        $this->assertEquals($queryCount, $this->getCurrentQueryCount());
        $this->assertFalse($entity->getTravels()->isInitialized());

        $newItem = new Travel($entity);
        $entity->getTravels()->add($newItem);

        $this->assertFalse($entity->getTravels()->isInitialized());
        $this->assertCount(4, $entity->getTravels());
        $this->assertTrue($entity->getTravels()->isInitialized());
        $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());

        $this->_em->flush();
        $this->_em->clear();

        $query  = "SELECT t, tt FROM Doctrine\Tests\Models\Cache\Traveler t JOIN t.travels tt WHERE t.id = $travelerId";
        $result = $this->_em->createQuery($query)->getSingleResult();

        $this->assertEquals(4, $result->getTravels()->count());
    }
}


text:
skmultilearn\.model\_selection\.iterative\_stratification module
================================================================

.. automodule:: skmultilearn.model_selection.iterative_stratification
    :members:
    :show-inheritance:


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

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

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

# E-Commerce Recommendation Template with rate event as training data.

This examples demonstrates how to modify E-Commerce Recommendation template to use "rate" event as Training Data.

However, recent "view" event is still used for recommendation for new user (to recommend items similar to what new user just recently viewed) and the returned scores are not predicted rating but a ranked scores for new user.

This template also supports that the user may rate same item multiple times and latest rating value will be used for training. The modification can be further simplified if the support of this case is not needed.

The modification is based on E-Commerce Recommendation template v0.1.1.

You can find the complete modified source code in `src/` directory.

## Documentation

Please refer to http://predictionio.incubator.apache.org/templates/ecommercerecommendation/quickstart/
and
http://predictionio.incubator.apache.org/templates/ecommercerecommendation/train-with-rate-event/

### import sample data

```
$ python data/import_eventserver.py --access_key <your_access_key>
```


text:
package com.github.symcal

import java.util.concurrent.atomic.AtomicInteger
import java.util.function.DoubleUnaryOperator

import com.github.symcal.javacompiler.JavaInMemoryCompiler

/** Adapt [[DoubleUnaryOperator]] to the usual function interface by adding `apply()`.
  *
  * @param f A Java function.
  */
case class JavaCompiledFunction(f: DoubleUnaryOperator) extends AnyVal {
  def apply(x: Double): Double = f.applyAsDouble(x)
}

object JavaCompiledFunction {
  val uniqueCounter = new AtomicInteger(0)

  def compile(arg: (String, String)): JavaCompiledFunction = {
    val (x, exprUsingX) = arg
    val n = uniqueCounter.incrementAndGet()
    val className = s"NewCompiledFunction$n"
    val packageName = "com.github.symcal.java_compiled_function"
    val fqClassName = s"$packageName.$className"

    val javaCode: String =
      s"""
         |package $packageName;
         |import java.util.function.DoubleUnaryOperator;
         |public class $className implements DoubleUnaryOperator {
         |  public double applyAsDouble(double $x) {
         |    return ($exprUsingX);
         |  }
         |}
      """.stripMargin
    JavaInMemoryCompiler.compile(fqClassName, javaCode)
  }
}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/filter_base.dir/src/filter_base.cpp.o"
  "devel/lib/libfilter_base.pdb"
  "devel/lib/libfilter_base.so"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/filter_base.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
require 'spec_helper'

describe RSpec::Apib::Writer do
  let(:example)   { double() }
  let(:request)   { double() }
  let(:response)  { double() }
  let(:routes)    { double() }
  let(:doc)       { {} }

  subject { described_class.new(doc) }

  it { should respond_to :write }

  describe '#write' do
    before :each do
      allow(subject).to receive(:pre_docs).and_return 'pre_docs'
      allow(subject).to receive(:build).and_return 'build'
      allow(subject).to receive(:post_docs).and_return 'post_docs'
      allow(subject).to receive :write_to_file
    end

    it 'calls #pre_docs' do
      expect(subject).to receive :pre_docs
      subject.write
    end

    it 'calls #build' do
      expect(subject).to receive :build
      subject.write
    end

    it 'calls #post_docs' do
      expect(subject).to receive :post_docs
      subject.write
    end

    it 'calls #write_to_file with generated data' do
      expect(subject).to receive(:write_to_file)
        .with("pre_docs\n\nbuild\n\npost_docs")
      subject.write
    end
  end

  describe '#write_to_file' do
    it 'opens the configured file' do
      allow(RSpec::Apib.config).to receive(:dest_file).and_return 'foo'
      expect(File).to receive(:open).with('foo', 'w')
      subject.send :write_to_file, ''
    end

    it 'writes the given data to the opened file' do
      file = double()
      allow(File).to receive(:open).and_yield file
      expect(file).to receive(:write).with('foo')
      subject.send :write_to_file, 'foo'
    end
  end

  pending '#write_to_file'
  pending '#pre_docs'
  pending '#post_docs'
  pending '#build'

  describe '#build' do
    let(:doc) do
      {
        'foo' => {
          'GET' => {
            request: {
              headers: {}
            },
            response: [doc_response]
          }
        },
        'baz' => {
          'GET' => {
            request: {
              headers: {}
            },
            response: [doc_response]
          }
        }
      }
    end

    let(:doc_response) do
      {
        status: 200,
        headers: {},
        description: "foo\nbar"
      }
    end

    it 'adds propper indentation to multi line descriptions' do
      result = subject.send :build
      expect(result).to include "    foo\n    bar"
    end

    it 'it works with a nil description' do
      doc_response[:description] = nil
      result = subject.send :build
      expect(result).to be_a String
    end

    it 'sorts the groups alphabetically' do
      doc_response[:description] = nil
      result = subject.send :build
      pos_foo = result.index('# Group foo')
      pos_baz = result.index('# Group baz')
      expect(pos_baz).to be < pos_foo
    end
  end
end


text:
Crowbar uses the basic Rails MVC approach for UI development with some small AJAX extension.

While there are more sophisticated and scalable models, the development team feels that Rails MVC provides sufficient experience without additional complexity.  Maintainability and simplicity of the UI are primary goals at this point.

We expect to revisit this assumption in the future and encourage community development of this UI or other approaches.


text:
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
import React, { PropTypes } from 'react';
import { Platform, TouchableNativeFeedback, TouchableHighlight, View } from 'react-native';
import theme from '../themes';
import { listStyles as styles } from '../styles';
const { colors } = theme;
const Item = (props) => ((Platform.OS === 'android') ?
    React.createElement(TouchableNativeFeedback, __assign({}, props, {onPress: props.onPress, background: TouchableNativeFeedback.Ripple(colors.light, false)}), React.createElement(View, {style: [styles.item, props.style]}, props.children)) :
    React.createElement(TouchableHighlight, __assign({}, props, {underlay: colors.light, onPress: props.onPress}), React.createElement(View, {style: [styles.item, props.style]}, props.children)));
Item.propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node
    ]),
    onPress: PropTypes.func,
    style: PropTypes.any
};
Item.defaultProps = {};
export default Item;


text:
<?php
	require_once("models/config.php");
	if (!securePage($_SERVER['PHP_SELF'])){
		die();
	}
	require_once("models/db-settings.php");
	require_once("functions.php");

	$board_id = trim($_REQUEST["boardid"]);
?>

		<?php echo translate('Press "Delete board" if you really want to delete the board'); ?>

		<a id="delete_button" href="#" onclick="delete_board();" class='action with-text' title='<?php echo translate("Delete board"); ?>'><?php echo translate('Delete board'); ?>


text:
from __future__ import absolute_import

import re
import time
import requests
import json
import auth
import sys
import traceback
import os.path
import fnmatch

try:
    from graphite_api.intervals import Interval, IntervalSet
    from graphite_api.node import LeafNode, BranchNode
except ImportError:
    from graphite.intervals import Interval, IntervalSet
    from graphite.node import LeafNode, BranchNode

# curl -XPOST -H "Accept: application/json, text/plain, */*" -H "Content-Type: application/x-www-form-urlencoded" 'http://127.0.0.1:8888/render' -d "target=rackspace.*.*.*.*.*.*.*.*.available&from=-6h&until=now&format=json&maxDataPoints=1552"

secs_per_res = {
  'FULL': 1,
  'MIN5': 5*60,
  'MIN20': 20*60,
  'MIN60': 60*60,
  'MIN240': 240*60,
  'MIN1440': 1440*60}

def calc_res(start, stop):
  # make an educated guess about the likely number of data points returned.
  num_points = (stop - start) / 60
  res = 'FULL'
  if num_points > 400:
    num_points = (stop - start) / secs_per_res['MIN5']
    res = 'MIN5'
  if num_points > 800:
    num_points = (stop - start) / secs_per_res['MIN20']
    res = 'MIN20'
  if num_points > 800:
    num_points = (stop - start) / secs_per_res['MIN60']
    res = 'MIN60'
  if num_points > 800:
    num_points = (stop - start) / secs_per_res['MIN240']
    res = 'MIN240'
  if num_points > 800:
    num_points = (stop - start) / secs_per_res['MIN1440']
    res = 'MIN1440'
  return res

class TenantBluefloodFinder(object):
  __fetch_multi__ = 'tenant_blueflood'
  def __init__(self, config=None):
    print("Blueflood Finder v25")
    if config is not None:
      bf_config = config.get('blueflood', {})
      urls = bf_config.get('urls', bf_config.get('url', '').strip('/'))
      tenant = bf_config.get('tenant', None)
      authentication_module =  bf_config.get('authentication_module', None)
      authentication_class =  bf_config.get('authentication_class', None)
      enable_submetrics = bf_config.get('enable_submetrics', False)
      submetric_aliases = bf_config.get('submetric_aliases', {})
    else:
      from django.conf import settings
      urls = getattr(settings, 'BF_QUERY')
      tenant = getattr(settings, 'BF_TENANT')
      authentication_module = getattr(settings, 'BF_AUTHENTICATION_MODULE', None)
      authentication_class = getattr(settings, 'BF_AUTHENTICATION_CLASS', None)
      enable_submetrics = getattr(settings, 'BF_ENABLE_SUBMETRICS', False)
      submetric_aliases = getattr(settings, 'BF_SUBMETRIC_ALIASES', {})

    if authentication_module:
      module = __import__(authentication_module)
      class_ = getattr(module, authentication_class)
      bfauth = class_(config)
      auth.set_auth(bfauth)

    self.tenant = tenant
    self.bf_query_endpoint = urls[0]
    self.enable_submetrics = enable_submetrics
    self.submetric_aliases = submetric_aliases
    self.client = BluefloodClient(self.bf_query_endpoint, self.tenant,
                                  self.enable_submetrics, self.submetric_aliases)
    print("BF finder submetrics enabled: ", enable_submetrics)

  def complete(self, metric, query_depth):
    metric_parts = metric.split('.')
    if self.enable_submetrics:
      complete_len = query_depth - 1
    else:
      complete_len = query_depth
    return (len(metric_parts) == complete_len)

  def make_request(self, url, payload, headers):
    if auth.is_active():
      headers['X-Auth-Token'] = auth.get_token(False)
    r = requests.get(url, params=payload, headers=headers)
    if r.status_code == 401 and auth.is_active():
      headers['X-Auth-Token'] = auth.get_token(True)
      r = requests.get(url, params=payload, headers=headers)
    return r

  def find_metrics_endpoint(self, endpoint, tenant):
    return "%s/v2.0/%s/metrics/search" % (endpoint, tenant)

  def find_metrics(self, query):
    print "BluefloodClient.find_metrics: " + str(query)
    payload = {'query': query}
    headers = auth.headers()
    endpoint = self.find_metrics_endpoint(self.bf_query_endpoint, self.tenant)
    r = self.make_request(endpoint, payload, headers)

    if r.status_code == 200:
        return [m['metric'] for m in r.json()]
    else:
      return []

  def find_nodes_with_submetrics(self, query):
    # By definition, when using submetrics, the names of all Leafnodes must end in a submetric alias
    # BF doesn't know about the submetric aliases and so the aliases, (or globs corresponding to them,)
    # must be massaged before querying BF.
    # There are two cases above:

    # 1. When you want a list of valid submetric aliases, i.e. a complete metric name followed by ".*"
    # 2. When you have a query contains a valid submetric alias, i.e a complete metric name followed
    #    by a valid submetric alias like "._avg"

    # Every submetric leaf node is covered by one of the above two cases.  Everything else is a
    # branch node.

    query_parts = query.pattern.split('.')
    query_depth = len(query_parts)

    # The pattern which all complete metrics will match
    complete_pattern = '.'.join(query_parts[0:-1])

    if (query_depth > 1) and (query_parts[-1] == '*'):
      #  In this if clause we are searching for complete metric names
      #  followed by a ".*". If so, we are requesting a list of submetric
      #  names, so return leaf nodes for each submetric alias that is
      #  enabled

      # First modify the pattern to get a superset that includes already complete
      #  submetrics
      new_pattern = complete_pattern + '*'
      for metric in self.find_metrics(new_pattern):
        metric_parts = metric.split('.')
        if self.complete(metric, query_depth) and fnmatch.fnmatchcase(metric, complete_pattern):
          for alias, _ in self.submetric_aliases.items():
            yield TenantBluefloodLeafNode('.'.join(metric_parts + [alias]),
                                          TenantBluefloodReader(metric, self.tenant,
                                                                self.bf_query_endpoint,
                                                                self.enable_submetrics,
                                                                self.submetric_aliases))
        else:
          # Make sure the branch nodes match the original pattern
          if fnmatch.fnmatchcase(metric, query.pattern):
            yield BranchNode('.'.join(metric_parts[:query_depth]))

    #if searching for a particular submetric alias, create a leaf node for it
    elif (query_depth > 1) and (query_parts[-1] in self.submetric_aliases):
      for metric in self.find_metrics(complete_pattern):
        if self.complete(metric, query_depth):
          yield TenantBluefloodLeafNode('.'.join([metric, query_parts[-1]]), TenantBluefloodReader(metric, self.tenant, self.bf_query_endpoint, self.enable_submetrics, self.submetric_aliases))

    #everything else is a branch node
    else:
      for metric in self.find_metrics(query.pattern):
        metric_parts = metric.split('.')
        if not self.complete(metric, query_depth):
          yield BranchNode('.'.join(metric_parts[:query_depth]))

  def find_nodes_without_submetrics(self, query):
    query_parts = query.pattern.split('.')
    query_depth = len(query_parts)

    for metric in self.find_metrics(query.pattern):
      metric_parts = metric.split('.')
      if not self.complete(metric, query_depth):
        yield BranchNode('.'.join(metric_parts[:query_depth]))
      else:
        yield TenantBluefloodLeafNode(metric, TenantBluefloodReader(metric, self.tenant, self.bf_query_endpoint, self.enable_submetrics, self.submetric_aliases))

  def find_nodes(self, query):
    #yields all valid metric names matching glob based query
    try:
      print "TenantBluefloodFinder.query: " + str(query.pattern)

      if self.enable_submetrics:
        return self.find_nodes_with_submetrics(query)
      else:
        return self.find_nodes_without_submetrics(query)

    except Exception as e:
     print "Exception in Blueflood find_nodes: "
     print e
     exc_info = sys.exc_info()
     tb = traceback.format_exception(*exc_info)
     for line in tb:
       print(line)
     raise e

  def fetch_multi(self, nodes, start_time, end_time):
    return self.client.fetch_multi(nodes, start_time, end_time)

class TenantBluefloodReader(object):
  __slots__ = ('metric', 'tenant', 'bf_query_endpoint',
               'enable_submetrics', 'submetric_aliases')
  supported = True

  def __init__(self, metric, tenant, endpoint, enable_submetrics, submetric_aliases):

    # print 'READER ' + tenant + ' ' + metric
    self.metric = metric
    self.tenant = tenant
    self.bf_query_endpoint = endpoint
    self.enable_submetrics = enable_submetrics
    self.submetric_aliases = submetric_aliases

  def get_intervals(self):
    # todo: make this a lot smarter.
    intervals = []
    millis = int(round(time.time() * 1000))
    intervals.append(Interval(0, millis))
    return IntervalSet(intervals)

  def fetch(self, start_time, end_time):
    # remember, graphite treats time as seconds-since-epoch. BF treats time as millis-since-epoch.
    if not self.metric:
      return ((start_time, end_time, 1), [])
    else:
      client = BluefloodClient(self.bf_query_endpoint, self.tenant,
                                  self.enable_submetrics, self.submetric_aliases)
      reader = TenantBluefloodReader(self.metric, self.tenant, self.bf_query_endpoint,
                                     self.enable_submetrics, self.submetric_aliases)
      node = TenantBluefloodLeafNode(self.metric, reader)

      time_info, dictionary = client.fetch_multi([node], start_time, end_time)

      return (time_info, dictionary[self.metric])

class BluefloodClient(object):
  def __init__(self, host, tenant, enable_submetrics, submetric_aliases):
    self.host = host
    self.tenant = tenant
    self.enable_submetrics = enable_submetrics
    self.submetric_aliases = submetric_aliases
    # This is the maximum number of json characters permitted by the
    #  BF multiplot handler.
    # The actual max is 8000, but I want to leave a margin for error
    #  because I can't be certain of the exact way the json is generated
    self.maxlen_per_req = 7000
    # this is for: "'' ," that surround each metric
    self.overhead_per_metric = 4
    self.maxmetrics_per_req = 100

  def gen_data_key(self, values):
    # Determines which key to use for the data
    if not len(values):
      return None
    value_res_order = ['average', 'latest', 'numPoints']
    present_keys = [v for v in value_res_order if v in values[0]]
    if present_keys:
      return present_keys[0]
    else:
      return None

  def current_datapoint_passed(self, v_iter, ts):
    # Determines if the current datapoint is too old to be considered
    if not len(v_iter):
      return False
    datapoint_ts = v_iter[0]['timestamp']/1000
    if (ts > datapoint_ts):
      return True
    return False

  def current_datapoint_valid(self, v_iter, data_key, ts, step):
    # Determines if the current datapoint be included in the current step
    #assumes current_datapoint_passed() is true
    if (not len(v_iter)) or not (data_key in v_iter[0]):
      return False
    datapoint_ts = v_iter[0]['timestamp']/1000
    if (datapoint_ts < (ts + step)):
      return True
    return False

  def process_path(self, values, start_time, end_time, step, data_key):
    # Generates datapoints in graphite-api format
    # Graphite-api requires the points be "step" seconds apart in time
    #  with Null's interleaved if needed
    if not data_key:
      print "No valid keys present"
      return []
    v_iter = values
    ret_arr = []
    for ts in range(start_time, end_time, step):

      # Skip datapoints that have already passed
      #  NOTE/TODO: this while loop has the effect of dropping all but the first datapoint in each step
      #  (Graphite requires exactly one datapoint/step.)  It would be better to rollup the datapoints
      #  if there are more than one/step.  However that will only happen when we have full res metrics
      #  with sub-second frequencies.  We believe that case is too rare to worry about right now.
      while self.current_datapoint_passed(v_iter, ts):
        v_iter = v_iter[1:]
      if self.current_datapoint_valid(v_iter, data_key, ts, step):
        ret_arr.append(v_iter[0][data_key])
      else:
        ret_arr.append(None)

    return ret_arr

  def get_multi_endpoint(self, endpoint, tenant):
    return "%s/v2.0/%s/views" % (endpoint, tenant)

  def get_metric_data(self, endpoint, tenant, metric_list, payload, headers):
    #Generate Multiplot query to get metrics in list
    url = self.get_multi_endpoint(endpoint,tenant)
    if auth.is_active():
      headers['X-Auth-Token'] = auth.get_token(False)
    r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers)
    if r.status_code == 401 and auth.is_active():
      headers['X-Auth-Token'] = auth.get_token(True)
      r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers)
    if r.status_code != 200:
      print("get_metric_data failed; response: ", r.status_code, tenant, metric_list)
      return None
    else:
      return r.json()['metrics']

  def gen_payload(self, start_time, end_time, res):
    payload = {
      'from': start_time * 1000,
      'to': end_time * 1000,
      'points': 1000
    }
    if self.enable_submetrics:
      payload['select'] = ','.join(self.submetric_aliases.values())
    return payload

  def gen_keys(self, node, metrics):
    # returns metrics_key and data_key
    #  metrics_key, (the name of the metric, which varies
    #   depending on if submetric aliases are used.)
    #  data_key, (the name of the key to use for the individual datapoint
    #   returned by BF
    metrics_key = None
    data_key = None
    if self.enable_submetrics:
      path_parts = node.path.split('.')
      test_key = '.'.join(path_parts[0:-1])
      if test_key in metrics:
        metrics_key = test_key
        data_key = self.submetric_aliases[path_parts[-1]]
    elif node.path in metrics:
      metrics_key = node.path
      data_key = self.gen_data_key(metrics[metrics_key])
    return metrics_key, data_key

  def gen_dict(self, nodes, responses, start_time, real_end_time, step):
    metrics = {x['metric'] : x['data'] for x in responses}
    dictionary = {}
    for n in nodes:
      metrics_key, data_key = self.gen_keys(n, metrics)
      if metrics_key:
        dictionary[n.path] = self.process_path(metrics[metrics_key], start_time, real_end_time, step, data_key)
    return dictionary

  def group_has_room(self, cur_metric, cur_path, tot_len, remaining_paths):
    if cur_metric >= self.maxmetrics_per_req:
      return False
    if cur_path >= len(remaining_paths):
      return False
    new_total = tot_len + len(remaining_paths[cur_path]) + self.overhead_per_metric
    if new_total >= self.maxlen_per_req:
      return False
    return True

  def gen_next_group(self, remaining_paths, groups):
    # creates a group of metrics that doesn't exceed limits
    cur_metric = 0
    cur_path = 0
    tot_len = 2 # for the brackets
    while self.group_has_room(cur_metric, cur_path, tot_len, remaining_paths):
      tot_len += len(remaining_paths[cur_path]) + 2 # for the ", "
      cur_metric += 1
      cur_path += 1
    return remaining_paths[cur_path:], groups + [remaining_paths[0:cur_path]]

  def gen_groups(self, nodes):
    # creates groups of metrics none of which exceed limits
    groups = []
    remaining_paths = [node.path for node in nodes]
    if self.enable_submetrics:
      remaining_paths = ['.'.join(p.split('.')[0:-1]) for p in remaining_paths]
    while remaining_paths:
      new_remaining_paths, groups = self.gen_next_group(remaining_paths, groups)
      #check for infinite loops/should never happen
      if len(remaining_paths) == len(new_remaining_paths):
        raise IndexError("Invalid path found; breaking out of loop.")
      else:
        remaining_paths = new_remaining_paths
    return groups

  def gen_responses(self, groups, payload):
    #converts groups of requests into a single list of responses
    headers = auth.headers()
    responses = reduce(lambda x,y: x+y,
                     [self.get_metric_data(self.host,
                                           self.tenant, g, payload, headers)
                      for g in groups])
    responses = responses or []
    return responses

  def fetch_multi(self, nodes, start_time, end_time):
    try:
      res = calc_res(start_time, end_time)
      step = secs_per_res[res]
      payload = self.gen_payload(start_time, end_time, res)
      # Limit size of MPlot requests by dividing into groups
      groups = self.gen_groups(nodes)
      responses = self.gen_responses(groups, payload)
      real_end_time = end_time + step
      dictionary = self.gen_dict(nodes, responses, start_time, real_end_time, step)
      time_info = (start_time, real_end_time, step)
      return (time_info, dictionary)

    except Exception as e:
      print "Exception in Blueflood fetch_multi: "
      print e
      exc_info = sys.exc_info()
      tb = traceback.format_exception(*exc_info)
      for line in tb:
        print(line)
      raise e

class TenantBluefloodLeafNode(LeafNode):
  __fetch_multi__ = 'tenant_blueflood'


text:
using System;
using System.IO;

namespace Spring.Util
{
    /// <summary>
    /// Utility methods for IO handling
    /// </summary>
    internal sealed class IOUtils
    {
        private IOUtils()
        {
            throw new InvalidOperationException("instantiation not supported");
        }

        /// <summary>
        /// Copies one stream into another.
        /// (Don't forget to call <see cref="Stream.Flush"/> on the destination stream!)
        /// </summary>
        /// <remarks>
        /// Does not close the input stream!
        /// </remarks>
        public static void CopyStream(Stream src, Stream dest)
        {
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];

            int bytesRead = 0;
            while ((bytesRead = src.Read(buffer, 0, bufferSize)) > 0)
            {
                dest.Write(buffer, 0, bytesRead);
            }
        }

        /// <summary>
        /// Reads a stream into a byte array.
        /// </summary>
        /// <remarks>
        /// Does not close the input stream!
        /// </remarks>
        public static byte[] ToByteArray(Stream src)
        {
            MemoryStream stm = new MemoryStream();
            CopyStream(src, stm);
            stm.Close();
            return stm.ToArray();
        }

    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.github.xtension</groupId>
  <artifactId>xtension</artifactId>
  <version>0.1-SNAPSHOT</version>

  <properties>
    <xtend.version>2.4.2</xtend.version>
    <guava.version>14.0.1</guava.version>
    <java.version>1.6</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.xtend</groupId>
      <artifactId>org.eclipse.xtend.lib</artifactId>
      <version>${xtend.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>1.3.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-guava</artifactId>
      <version>1.0.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
          <encoding>${project.build.sourceEncoding}</encoding>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.eclipse.xtend</groupId>
        <artifactId>xtend-maven-plugin</artifactId>
        <version>${xtend.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <outputDirectory>src/main/xtend-gen</outputDirectory>
              <testOutputDirectory>src/test/xtend-gen</testOutputDirectory>
              <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>