text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Globalization;
using System.Numerics;
using System.Reflection;

namespace SharpLib.Json
{
    internal enum PrimitiveTypeCode
    {
        Empty,

        Object,

        Char,

        CharNullable,

        Boolean,

        BooleanNullable,

        SByte,

        SByteNullable,

        Int16,

        Int16Nullable,

        UInt16,

        UInt16Nullable,

        Int32,

        Int32Nullable,

        Byte,

        ByteNullable,

        UInt32,

        UInt32Nullable,

        Int64,

        Int64Nullable,

        UInt64,

        UInt64Nullable,

        Single,

        SingleNullable,

        Double,

        DoubleNullable,

        DateTime,

        DateTimeNullable,

        DateTimeOffset,

        DateTimeOffsetNullable,

        Decimal,

        DecimalNullable,

        Guid,

        GuidNullable,

        TimeSpan,

        TimeSpanNullable,

        BigInteger,

        BigIntegerNullable,

        Uri,

        String,

        Bytes,

        DBNull
    }

    internal class TypeInformation
    {
        #region Свойства

        public Type Type { get; set; }

        public PrimitiveTypeCode TypeCode { get; set; }

        #endregion
    }

    internal enum ParseResult
    {
        None,

        Success,

        Overflow,

        Invalid
    }

    internal static class ConvertUtils
    {
        #region Перечисления

        internal enum ConvertResult
        {
            Success,

            CannotConvertNull,

            NotInstantiableType,

            NoValidConversion
        }

        #endregion

        #region Поля

        private static readonly ThreadSafeStore<TypeConvertKey, Func<object, object>> CastConverters =
            new ThreadSafeStore<TypeConvertKey, Func<object, object>>(CreateCastConverter);

        private static readonly TypeInformation[] PrimitiveTypeCodes =
        {
            new TypeInformation
            {
                Type = typeof(object),
                TypeCode = PrimitiveTypeCode.Empty
            },
            new TypeInformation
            {
                Type = typeof(object),
                TypeCode = PrimitiveTypeCode.Object
            },
            new TypeInformation
            {
                Type = typeof(object),
                TypeCode = PrimitiveTypeCode.DBNull
            },
            new TypeInformation
            {
                Type = typeof(bool),
                TypeCode = PrimitiveTypeCode.Boolean
            },
            new TypeInformation
            {
                Type = typeof(char),
                TypeCode = PrimitiveTypeCode.Char
            },
            new TypeInformation
            {
                Type = typeof(sbyte),
                TypeCode = PrimitiveTypeCode.SByte
            },
            new TypeInformation
            {
                Type = typeof(byte),
                TypeCode = PrimitiveTypeCode.Byte
            },
            new TypeInformation
            {
                Type = typeof(short),
                TypeCode = PrimitiveTypeCode.Int16
            },
            new TypeInformation
            {
                Type = typeof(ushort),
                TypeCode = PrimitiveTypeCode.UInt16
            },
            new TypeInformation
            {
                Type = typeof(int),
                TypeCode = PrimitiveTypeCode.Int32
            },
            new TypeInformation
            {
                Type = typeof(uint),
                TypeCode = PrimitiveTypeCode.UInt32
            },
            new TypeInformation
            {
                Type = typeof(long),
                TypeCode = PrimitiveTypeCode.Int64
            },
            new TypeInformation
            {
                Type = typeof(ulong),
                TypeCode = PrimitiveTypeCode.UInt64
            },
            new TypeInformation
            {
                Type = typeof(float),
                TypeCode = PrimitiveTypeCode.Single
            },
            new TypeInformation
            {
                Type = typeof(double),
                TypeCode = PrimitiveTypeCode.Double
            },
            new TypeInformation
            {
                Type = typeof(decimal),
                TypeCode = PrimitiveTypeCode.Decimal
            },
            new TypeInformation
            {
                Type = typeof(DateTime),
                TypeCode = PrimitiveTypeCode.DateTime
            },
            new TypeInformation
            {
                Type = typeof(object),
                TypeCode = PrimitiveTypeCode.Empty
            },
            new TypeInformation
            {
                Type = typeof(string),
                TypeCode = PrimitiveTypeCode.String
            }
        };

        private static readonly Dictionary<Type, PrimitiveTypeCode> TypeCodeMap =
            new Dictionary<Type, PrimitiveTypeCode>
            {
                { typeof(char), PrimitiveTypeCode.Char },
                { typeof(char?), PrimitiveTypeCode.CharNullable },
                { typeof(bool), PrimitiveTypeCode.Boolean },
                { typeof(bool?), PrimitiveTypeCode.BooleanNullable },
                { typeof(sbyte), PrimitiveTypeCode.SByte },
                { typeof(sbyte?), PrimitiveTypeCode.SByteNullable },
                { typeof(short), PrimitiveTypeCode.Int16 },
                { typeof(short?), PrimitiveTypeCode.Int16Nullable },
                { typeof(ushort), PrimitiveTypeCode.UInt16 },
                { typeof(ushort?), PrimitiveTypeCode.UInt16Nullable },
                { typeof(int), PrimitiveTypeCode.Int32 },
                { typeof(int?), PrimitiveTypeCode.Int32Nullable },
                { typeof(byte), PrimitiveTypeCode.Byte },
                { typeof(byte?), PrimitiveTypeCode.ByteNullable },
                { typeof(uint), PrimitiveTypeCode.UInt32 },
                { typeof(uint?), PrimitiveTypeCode.UInt32Nullable },
                { typeof(long), PrimitiveTypeCode.Int64 },
                { typeof(long?), PrimitiveTypeCode.Int64Nullable },
                { typeof(ulong), PrimitiveTypeCode.UInt64 },
                { typeof(ulong?), PrimitiveTypeCode.UInt64Nullable },
                { typeof(float), PrimitiveTypeCode.Single },
                { typeof(float?), PrimitiveTypeCode.SingleNullable },
                { typeof(double), PrimitiveTypeCode.Double },
                { typeof(double?), PrimitiveTypeCode.DoubleNullable },
                { typeof(DateTime), PrimitiveTypeCode.DateTime },
                { typeof(DateTime?), PrimitiveTypeCode.DateTimeNullable },
                { typeof(DateTimeOffset), PrimitiveTypeCode.DateTimeOffset },
                { typeof(DateTimeOffset?), PrimitiveTypeCode.DateTimeOffsetNullable },
                { typeof(decimal), PrimitiveTypeCode.Decimal },
                { typeof(decimal?), PrimitiveTypeCode.DecimalNullable },
                { typeof(Guid), PrimitiveTypeCode.Guid },
                { typeof(Guid?), PrimitiveTypeCode.GuidNullable },
                { typeof(TimeSpan), PrimitiveTypeCode.TimeSpan },
                { typeof(TimeSpan?), PrimitiveTypeCode.TimeSpanNullable },
                { typeof(BigInteger), PrimitiveTypeCode.BigInteger },
                { typeof(BigInteger?), PrimitiveTypeCode.BigIntegerNullable },
                { typeof(Uri), PrimitiveTypeCode.Uri },
                { typeof(string), PrimitiveTypeCode.String },
                { typeof(byte[]), PrimitiveTypeCode.Bytes },
                { typeof(DBNull), PrimitiveTypeCode.DBNull }
            };

        #endregion

        #region Методы

        public static PrimitiveTypeCode GetTypeCode(Type t)
        {
            bool isEnum;
            return GetTypeCode(t, out isEnum);
        }

        public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum)
        {
            PrimitiveTypeCode typeCode;
            if (TypeCodeMap.TryGetValue(t, out typeCode))
            {
                isEnum = false;
                return typeCode;
            }

            if (t.IsEnum())
            {
                isEnum = true;
                return GetTypeCode(Enum.GetUnderlyingType(t));
            }

            if (ReflectionUtils.IsNullableType(t))
            {
                Type nonNullable = Nullable.GetUnderlyingType(t);
                if (nonNullable.IsEnum())
                {
                    Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable));
                    isEnum = true;
                    return GetTypeCode(nullableUnderlyingType);
                }
            }

            isEnum = false;
            return PrimitiveTypeCode.Object;
        }

        public static TypeInformation GetTypeInformation(IConvertible convertable)
        {
            TypeInformation typeInformation = PrimitiveTypeCodes[(int)convertable.GetTypeCode()];
            return typeInformation;
        }

        public static bool IsConvertible(Type t)
        {
            return typeof(IConvertible).IsAssignableFrom(t);
        }

        public static TimeSpan ParseTimeSpan(string input)
        {
            return TimeSpan.Parse(input, CultureInfo.InvariantCulture);
        }

        private static Func<object, object> CreateCastConverter(TypeConvertKey t)
        {
            MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType });
            if (castMethodInfo == null)
            {
                castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType });
            }

            if (castMethodInfo == null)
            {
                return null;
            }

            MethodCall<object, object> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(castMethodInfo);

            return o => call(null, o);
        }

        internal static BigInteger ToBigInteger(object value)
        {
            if (value is BigInteger)
            {
                return (BigInteger)value;
            }
            if (value is string)
            {
                return BigInteger.Parse((string)value, CultureInfo.InvariantCulture);
            }
            if (value is float)
            {
                return new BigInteger((float)value);
            }
            if (value is double)
            {
                return new BigInteger((double)value);
            }
            if (value is decimal)
            {
                return new BigInteger((decimal)value);
            }
            if (value is int)
            {
                return new BigInteger((int)value);
            }
            if (value is long)
            {
                return new BigInteger((long)value);
            }
            if (value is uint)
            {
                return new BigInteger((uint)value);
            }
            if (value is ulong)
            {
                return new BigInteger((ulong)value);
            }
            if (value is byte[])
            {
                return new BigInteger((byte[])value);
            }

            throw new InvalidCastException("Cannot convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
        }

        public static object FromBigInteger(BigInteger i, Type targetType)
        {
            if (targetType == typeof(decimal))
            {
                return (decimal)i;
            }
            if (targetType == typeof(double))
            {
                return (double)i;
            }
            if (targetType == typeof(float))
            {
                return (float)i;
            }
            if (targetType == typeof(ulong))
            {
                return (ulong)i;
            }

            try
            {
                return System.Convert.ChangeType((long)i, targetType, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Can not convert from BigInteger to {0}.".FormatWith(CultureInfo.InvariantCulture, targetType), ex);
            }
        }

        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            object value;
            switch (TryConvertInternal(initialValue, culture, targetType, out value))
            {
                case ConvertResult.Success:
                    return value;
                case ConvertResult.CannotConvertNull:
                    throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));
                case ConvertResult.NotInstantiableType:
                    throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
                case ConvertResult.NoValidConversion:
                    throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));
                default:
                    throw new InvalidOperationException("Unexpected conversion result.");
            }
        }

        private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value)
        {
            try
            {
                if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success)
                {
                    return true;
                }

                value = null;
                return false;
            }
            catch
            {
                value = null;
                return false;
            }
        }

        private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                value = initialValue;
                return ConvertResult.Success;
            }

            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        value = Enum.Parse(targetType, initialValue.ToString(), true);
                        return ConvertResult.Success;
                    }
                    if (IsInteger(initialValue))
                    {
                        value = Enum.ToObject(targetType, initialValue);
                        return ConvertResult.Success;
                    }
                }

                value = System.Convert.ChangeType(initialValue, targetType, culture);
                return ConvertResult.Success;
            }

#if !NET20
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                value = new DateTimeOffset((DateTime)initialValue);
                return ConvertResult.Success;
            }
#endif

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                value = new Guid((byte[])initialValue);
                return ConvertResult.Success;
            }

            if (initialValue is Guid && targetType == typeof(byte[]))
            {
                value = ((Guid)initialValue).ToByteArray();
                return ConvertResult.Success;
            }

            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    value = new Guid((string)initialValue);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(Uri))
                {
                    value = new Uri((string)initialValue, UriKind.RelativeOrAbsolute);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(TimeSpan))
                {
                    value = ParseTimeSpan((string)initialValue);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(byte[]))
                {
                    value = System.Convert.FromBase64String((string)initialValue);
                    return ConvertResult.Success;
                }
                if (typeof(Type).IsAssignableFrom(targetType))
                {
                    value = Type.GetType((string)initialValue, true);
                    return ConvertResult.Success;
                }
            }

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
            if (targetType == typeof(BigInteger))
            {
                value = ToBigInteger(initialValue);
                return ConvertResult.Success;
            }
            if (initialValue is BigInteger)
            {
                value = FromBigInteger((BigInteger)initialValue, targetType);
                return ConvertResult.Success;
            }
#endif

#if !(NETFX_CORE || PORTABLE40 || PORTABLE)

            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
                value = toConverter.ConvertTo(null, culture, initialValue, targetType);
                return ConvertResult.Success;
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
                value = fromConverter.ConvertFrom(null, culture, initialValue);
                return ConvertResult.Success;
            }
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)

            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    value = EnsureTypeAssignable(null, initialType, targetType);
                    return ConvertResult.Success;
                }

                value = null;
                return ConvertResult.CannotConvertNull;
            }
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            if (initialValue is INullable)
            {
                value = EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType);
                return ConvertResult.Success;
            }
#endif

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                value = null;
                return ConvertResult.NotInstantiableType;
            }

            value = null;
            return ConvertResult.NoValidConversion;
        }

        public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType)
        {
            object convertedValue;

            if (targetType == typeof(object))
            {
                return initialValue;
            }

            if (initialValue == null && ReflectionUtils.IsNullable(targetType))
            {
                return null;
            }

            if (TryConvert(initialValue, culture, targetType, out convertedValue))
            {
                return convertedValue;
            }

            return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType);
        }

        private static object EnsureTypeAssignable(object value, Type initialType, Type targetType)
        {
            Type valueType = (value != null) ? value.GetType() : null;

            if (value != null)
            {
                if (targetType.IsAssignableFrom(valueType))
                {
                    return value;
                }

                Func<object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType));
                if (castConverter != null)
                {
                    return castConverter(value);
                }
            }
            else
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return null;
                }
            }

            throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType));
        }

        public static object ToValue(INullable nullableValue)
        {
            if (nullableValue == null)
            {
                return null;
            }
            if (nullableValue is SqlInt32)
            {
                return ToValue((SqlInt32)nullableValue);
            }
            if (nullableValue is SqlInt64)
            {
                return ToValue((SqlInt64)nullableValue);
            }
            if (nullableValue is SqlBoolean)
            {
                return ToValue((SqlBoolean)nullableValue);
            }
            if (nullableValue is SqlString)
            {
                return ToValue((SqlString)nullableValue);
            }
            if (nullableValue is SqlDateTime)
            {
                return ToValue((SqlDateTime)nullableValue);
            }

            throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType()));
        }

        internal static TypeConverter GetConverter(Type t)
        {
            return JsonTypeReflector.GetTypeConverter(t);
        }

        public static bool IsInteger(object value)
        {
            switch (GetTypeCode(value.GetType()))
            {
                case PrimitiveTypeCode.SByte:
                case PrimitiveTypeCode.Byte:
                case PrimitiveTypeCode.Int16:
                case PrimitiveTypeCode.UInt16:
                case PrimitiveTypeCode.Int32:
                case PrimitiveTypeCode.UInt32:
                case PrimitiveTypeCode.Int64:
                case PrimitiveTypeCode.UInt64:
                    return true;
                default:
                    return false;
            }
        }

        public static ParseResult Int32TryParse(char[] chars, int start, int length, out int value)
        {
            value = 0;

            if (length == 0)
            {
                return ParseResult.Invalid;
            }

            bool isNegative = (chars[start] == '-');

            if (isNegative)
            {
                if (length == 1)
                {
                    return ParseResult.Invalid;
                }

                start++;
                length--;
            }

            int end = start + length;

            for (int i = start; i < end; i++)
            {
                int c = chars[i] - '0';

                if (c < 0 || c > 9)
                {
                    return ParseResult.Invalid;
                }

                int newValue = (10 * value) - c;

                if (newValue > value)
                {
                    i++;

                    for (; i < end; i++)
                    {
                        c = chars[i] - '0';

                        if (c < 0 || c > 9)
                        {
                            return ParseResult.Invalid;
                        }
                    }

                    return ParseResult.Overflow;
                }

                value = newValue;
            }

            if (!isNegative)
            {
                if (value == int.MinValue)
                {
                    return ParseResult.Overflow;
                }

                value = -value;
            }

            return ParseResult.Success;
        }

        public static ParseResult Int64TryParse(char[] chars, int start, int length, out long value)
        {
            value = 0;

            if (length == 0)
            {
                return ParseResult.Invalid;
            }

            bool isNegative = (chars[start] == '-');

            if (isNegative)
            {
                if (length == 1)
                {
                    return ParseResult.Invalid;
                }

                start++;
                length--;
            }

            int end = start + length;

            for (int i = start; i < end; i++)
            {
                int c = chars[i] - '0';

                if (c < 0 || c > 9)
                {
                    return ParseResult.Invalid;
                }

                long newValue = (10 * value) - c;

                if (newValue > value)
                {
                    i++;

                    for (; i < end; i++)
                    {
                        c = chars[i] - '0';

                        if (c < 0 || c > 9)
                        {
                            return ParseResult.Invalid;
                        }
                    }

                    return ParseResult.Overflow;
                }

                value = newValue;
            }

            if (!isNegative)
            {
                if (value == long.MinValue)
                {
                    return ParseResult.Overflow;
                }

                value = -value;
            }

            return ParseResult.Success;
        }

        public static bool TryConvertGuid(string s, out Guid g)
        {
            return Guid.TryParse(s, out g);
        }

        #endregion

        #region Вложенный класс: TypeConvertKey

        internal struct TypeConvertKey : IEquatable<TypeConvertKey>
        {
            #region Поля

            private readonly Type _initialType;

            private readonly Type _targetType;

            #endregion

            #region Свойства

            public Type InitialType
            {
                get { return _initialType; }
            }

            public Type TargetType
            {
                get { return _targetType; }
            }

            #endregion

            #region Конструктор

            public TypeConvertKey(Type initialType, Type targetType)
            {
                _initialType = initialType;
                _targetType = targetType;
            }

            #endregion

            #region Методы

            public override int GetHashCode()
            {
                return _initialType.GetHashCode() ^ _targetType.GetHashCode();
            }

            public override bool Equals(object obj)
            {
                if (!(obj is TypeConvertKey))
                {
                    return false;
                }

                return Equals((TypeConvertKey)obj);
            }

            public bool Equals(TypeConvertKey other)
            {
                return (_initialType == other._initialType && _targetType == other._targetType);
            }

            #endregion
        }

        #endregion
    }
}


text:
import unittest

from datetime import date
from dateutil.relativedelta import relativedelta

import holidays

class TestUY(unittest.TestCase):
    def setUp(self):
        self.holidays = holidays.UY(observed=True)

    def test_new_years(self):
        self.holidays.observed = False
        self.assertNotIn(date(2010, 12, 31), self.holidays)
        self.assertNotIn(date(2017, 1, 2), self.holidays)
        self.holidays.observed = True
        self.assertIn(date(2017, 1, 1), self.holidays)
        for year in range(1900, 2100):
            dt = date(year, 1, 1)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_carnival_day(self):
        for dt in [
            date(2021, 2, 15),
            date(2021, 2, 16),
            date(2018, 2, 12),
            date(2018, 2, 13),
            date(2017, 2, 27),
            date(2017, 2, 28),
            date(2016, 2, 8),
            date(2016, 2, 9),
        ]:
            self.assertIn(dt, self.holidays)

    def test_dia_de_reyes(self):
        self.holidays.observed = False
        for year in range(1900, 2100):
            dt = date(year, 1, 6)
        self.assertIn(dt, self.holidays)

    def test_holy_week_day(self):
        for dt in [
            date(2021, 1, 6),
        ]:
            self.assertIn(dt, self.holidays)

    def test_labor_day(self):
        self.holidays.observed = False
        self.assertNotIn(date(2010, 4, 30), self.holidays)
        self.assertNotIn(date(2011, 5, 2), self.holidays)
        self.holidays.observed = True
        self.assertIn(date(1922, 5, 1), self.holidays)
        for year in range(1900, 2100):
            dt = date(year, 5, 1)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_batalla_de_las_piedras_day(self):
        self.holidays.observed = False
        self.assertNotIn(date(1811, 5, 18), self.holidays)
        self.assertNotIn(date(2021, 5, 18), self.holidays)
        self.holidays.observed = True
        for year in range(1900, 2100):
            dt = date(year, 5, 1)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_natalicio_artigas_day(self):
        for year in range(1900, 2100):
            dt = date(year, 6, 19)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_jura_de_la_constitucion_day(self):
        for year in range(1900, 2100):
            dt = date(year, 7, 18)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_declaratoria_de_la_independencia_day(self):
        self.holidays.observed = True
        for year in range(1900, 2100):
            dt = date(year, 8, 25)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_dia_de_la_raza_day(self):
        for year in range(1900, 2100):
            dt = date(year, 10, 11)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_dia_de_los_difuntos_day(self):
        for year in range(1900, 2100):
            dt = date(year, 11, 2)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

    def test_christmas(self):
        for year in range(1900, 2100):
            dt = date(year, 12, 25)
            self.assertIn(dt, self.holidays)
            self.assertNotIn(dt + relativedelta(days=-1), self.holidays)
            self.assertNotIn(dt + relativedelta(days=+1), self.holidays)

redpajama_set_name: RedPajamaGithub


text:
package org.hl7.fhir.r4.utils;

// todo:
// - generate sort order parameters
// - generate inherited search parameters

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.conformance.ProfileUtilities;
import org.hl7.fhir.r4.context.IWorkerContext;
import org.hl7.fhir.r4.model.Constants;
import org.hl7.fhir.r4.model.ElementDefinition;
import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r4.model.Enumerations.SearchParamType;
import org.hl7.fhir.r4.model.SearchParameter;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.utilities.Utilities;

public class GraphQLSchemaGenerator {

  public enum FHIROperationType {READ, SEARCH, CREATE, UPDATE, DELETE};

  private static final String INNER_TYPE_NAME = "gql.type.name";
  IWorkerContext context;

  public GraphQLSchemaGenerator(IWorkerContext context) {
    super();
    this.context = context;
  }

  public void generateTypes(OutputStream stream) throws IOException, FHIRException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));

    Map<String, StructureDefinition> pl = new HashMap<String, StructureDefinition>();
    Map<String, StructureDefinition> tl = new HashMap<String, StructureDefinition>();
    for (StructureDefinition sd : context.allStructures()) {
      if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) {
        pl.put(sd.getName(), sd);
      }
      if (sd.getKind() == StructureDefinitionKind.COMPLEXTYPE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) {
        tl.put(sd.getName(), sd);
      }
    }
    writer.write("# FHIR GraphQL Schema. Version "+Constants.VERSION+"-"+Constants.REVISION+"\r\n\r\n");
    writer.write("# FHIR Defined Primitive types\r\n");
    for (String n : sorted(pl.keySet()))
      generatePrimitive(writer, pl.get(n));
    writer.write("\r\n");
    writer.write("# FHIR Defined Search Parameter Types\r\n");
    for (SearchParamType dir : SearchParamType.values()) {
      if (dir != SearchParamType.NULL)
        generateSearchParamType(writer, dir.toCode());
    }
    writer.write("\r\n");
    generateElementBase(writer);
    for (String n : sorted(tl.keySet()))
      generateType(writer, tl.get(n));
    writer.flush();
    writer.close();
  }

  public void generateResource(OutputStream stream, StructureDefinition sd, List<SearchParameter> parameters, EnumSet<FHIROperationType> operations) throws IOException, FHIRException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
    writer.write("# FHIR GraphQL Schema. Version "+Constants.VERSION+"-"+Constants.REVISION+"\r\n\r\n");
    generateType(writer, sd);
    if (operations.contains(FHIROperationType.READ))
      generateIdAccess(writer, sd.getName());
    if (operations.contains(FHIROperationType.SEARCH)) {
      generateListAccess(writer, parameters, sd.getName());
      generateConnectionAccess(writer, parameters, sd.getName());
    }
    if (operations.contains(FHIROperationType.CREATE))
      generateCreate(writer, sd.getName());
    if (operations.contains(FHIROperationType.UPDATE))
      generateUpdate(writer, sd.getName());
    if (operations.contains(FHIROperationType.DELETE))
      generateDelete(writer, sd.getName());
    writer.flush();
    writer.close();
  }

  private void generateCreate(BufferedWriter writer, String name) throws IOException {
    writer.write("type "+name+"CreateType {\r\n");
    writer.write("  "+name+"Create(");
    param(writer, "resource", name, false, false);
    writer.write(") : "+name+"Creation\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
    writer.write("type "+name+"Creation {\r\n");
    writer.write("  location : String\r\n");
    writer.write("  resource : "+name+"\r\n");
    writer.write("  information : OperationOutcome\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void generateUpdate(BufferedWriter writer, String name) throws IOException {
    writer.write("type "+name+"UpdateType {\r\n");
    writer.write("  "+name+"Update(");
    param(writer, "id", "ID", false, false);
    param(writer, "resource", name, false, false);
    writer.write(") : "+name+"Update\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
    writer.write("type "+name+"Update {\r\n");
    writer.write("  resource : "+name+"\r\n");
    writer.write("  information : OperationOutcome\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void generateDelete(BufferedWriter writer, String name) throws IOException {
    writer.write("type "+name+"DeleteType {\r\n");
    writer.write("  "+name+"Delete(");
    param(writer, "id", "ID", false, false);
    writer.write(") : "+name+"Delete\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
    writer.write("type "+name+"Delete {\r\n");
    writer.write("  information : OperationOutcome\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void generateListAccess(BufferedWriter writer, List<SearchParameter> parameters, String name) throws IOException {
    writer.write("type "+name+"ListType {\r\n");
    writer.write("  "+name+"List(");
    param(writer, "_filter", "String", false, false);
    for (SearchParameter sp : parameters)
      param(writer, sp.getName().replace("-", "_"), getGqlname(sp.getType().toCode()), true, true);
    param(writer, "_sort", "String", false, true);
    param(writer, "_count", "Int", false, true);
    param(writer, "_cursor", "String", false, true);
    writer.write(") : ["+name+"]\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void param(BufferedWriter writer, String name, String type, boolean list, boolean line) throws IOException {
    if (line)
      writer.write("\r\n    ");
    writer.write(name);
    writer.write(" : ");
    if (list)
      writer.write("[");
    writer.write(type);
    if (list)
      writer.write("]");
  }

  private void generateConnectionAccess(BufferedWriter writer, List<SearchParameter> parameters, String name) throws IOException {
    writer.write("type "+name+"ConnectionType {\r\n");
    writer.write("  "+name+"Conection(");
    param(writer, "_filter", "String", false, false);
    for (SearchParameter sp : parameters)
      param(writer, sp.getName().replace("-", "_"), getGqlname(sp.getType().toCode()), true, true);
    param(writer, "_sort", "String", false, true);
    param(writer, "_count", "Int", false, true);
    param(writer, "_cursor", "String", false, true);
    writer.write(") : "+name+"Connection\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
    writer.write("type "+name+"Connection {\r\n");
    writer.write("  count : Int\r\n");
    writer.write("  offset : Int\r\n");
    writer.write("  pagesize : Int\r\n");
    writer.write("  first : ID\r\n");
    writer.write("  previous : ID\r\n");
    writer.write("  next : ID\r\n");
    writer.write("  last : ID\r\n");
    writer.write("  edges : ["+name+"Edge]\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
    writer.write("type "+name+"Edge {\r\n");
    writer.write("  mode : String\r\n");
    writer.write("  score : Float\r\n");
    writer.write("  resource : "+name+"\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void generateIdAccess(BufferedWriter writer, String name) throws IOException {
    writer.write("type "+name+"ReadType {\r\n");
    writer.write("  "+name+"(id : ID!) : "+name+"\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");
  }

  private void generateElementBase(BufferedWriter writer) throws IOException {
    writer.write("type ElementBase {\r\n");
    writer.write("  id : ID\r\n");
    writer.write("  extension : [Extension]{\r\n");
    writer.write("}\r\n");
    writer.write("\r\n");

  }

  private void generateType(BufferedWriter writer, StructureDefinition sd) throws IOException {
    if (sd.getAbstract())
      return;

    List<StringBuilder> list = new ArrayList<StringBuilder>();
    StringBuilder b = new StringBuilder();
    list.add(b);
    b.append("type ");
    b.append(sd.getName());
    b.append(" {\r\n");
    ElementDefinition ed = sd.getSnapshot().getElementFirstRep();
    generateProperties(list, b, sd.getName(), sd, ed, "type");
    b.append("}");
    b.append("\r\n");
    b.append("\r\n");
    for (StringBuilder bs : list)
      writer.write(bs.toString());
    list.clear();
    b = new StringBuilder();
    list.add(b);
    b.append("input ");
    b.append(sd.getName());
    b.append(" {\r\n");
    ed = sd.getSnapshot().getElementFirstRep();
    generateProperties(list, b, sd.getName(), sd, ed, "input");
    b.append("}");
    b.append("\r\n");
    b.append("\r\n");
    for (StringBuilder bs : list)
      writer.write(bs.toString());
  }

  private void generateProperties(List<StringBuilder> list, StringBuilder b, String typeName, StructureDefinition sd, ElementDefinition ed, String mode) throws IOException {
    List<ElementDefinition> children = ProfileUtilities.getChildList(sd, ed);
    for (ElementDefinition child : children) {
      if (child.hasContentReference()) {
        ElementDefinition ref = resolveContentReference(sd, child.getContentReference());
        generateProperty(list, b, typeName, sd, child, ref.getType().get(0), false, ref, mode);
      } else if (child.getType().size() == 1) {
        generateProperty(list, b, typeName, sd, child, child.getType().get(0), false, null, mode);
      } else {
        boolean ref  = false;
        for (TypeRefComponent t : child.getType()) {
          if (!"Reference".equals(t.getCode()))
            generateProperty(list, b, typeName, sd, child, t, true, null, mode);
          else if (!ref) {
            ref = true;
            generateProperty(list, b, typeName, sd, child, t, true, null, mode);
          }
        }
      }
    }
  }

  private ElementDefinition resolveContentReference(StructureDefinition sd, String contentReference) {
    String id = contentReference.substring(1);
    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
      if (id.equals(ed.getId()))
        return ed;
    }
    throw new Error("Unable to find "+id);
  }

  private void generateProperty(List<StringBuilder> list, StringBuilder b, String typeName, StructureDefinition sd, ElementDefinition child, TypeRefComponent typeDetails, boolean suffix, ElementDefinition cr, String mode) throws IOException {
    if (isPrimitive(typeDetails)) {
      String n = getGqlname(typeDetails.getCode());
      b.append("  ");
      b.append(tail(child.getPath(), suffix));
      if (suffix)
        b.append(Utilities.capitalize(typeDetails.getCode()));
      b.append(": ");
      b.append(n);
      if (!child.getPath().endsWith(".id")) {
        b.append("  _");
        b.append(tail(child.getPath(), suffix));
        if (suffix)
          b.append(Utilities.capitalize(typeDetails.getCode()));
        if (!child.getMax().equals("1"))
          b.append(": [ElementBase]\r\n");
        else
          b.append(": ElementBase\r\n");
      } else
        b.append("\r\n");
    } else {
      b.append("  ");
      b.append(tail(child.getPath(), suffix));
      if (suffix)
        b.append(Utilities.capitalize(typeDetails.getCode()));
      b.append(": ");
      if (!child.getMax().equals("1"))
        b.append("[");
      String type = typeDetails.getCode();
      if (cr != null)
        b.append(generateInnerType(list, sd, typeName, cr, mode));
      else if (Utilities.existsInList(type, "Element", "BackboneElement"))
        b.append(generateInnerType(list, sd, typeName, child, mode));
      else
        b.append(type);
      if (!child.getMax().equals("1"))
        b.append("]");
      if (child.getMin() != 0 && !suffix)
        b.append("!");
      b.append("\r\n");
    }
  }

  private String generateInnerType(List<StringBuilder> list, StructureDefinition sd, String name, ElementDefinition child, String mode) throws IOException {
    if (child.hasUserData(INNER_TYPE_NAME+"."+mode))
      return child.getUserString(INNER_TYPE_NAME+"."+mode);

    String typeName = name+Utilities.capitalize(tail(child.getPath(), false));
    child.setUserData(INNER_TYPE_NAME+"."+mode, typeName);
    StringBuilder b = new StringBuilder();
    list.add(b);
    b.append(mode);
    b.append(" ");
    b.append(typeName);
    b.append(" {\r\n");
    generateProperties(list, b, typeName, sd, child, mode);
    b.append("}");
    b.append("\r\n");
    b.append("\r\n");
    return typeName;
  }

  private String tail(String path, boolean suffix) {
    if (suffix)
      path = path.substring(0, path.length()-3);
    int i = path.lastIndexOf(".");
    return i < 0 ? path : path.substring(i + 1);
  }

  private boolean isPrimitive(TypeRefComponent type) {
    String typeName = type.getCode();
    StructureDefinition sd = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/"+typeName);
    if (sd == null)
      return false;
    return sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE;
  }

  private List<String> sorted(Set<String> keys) {
    List<String> sl = new ArrayList<>();
    sl.addAll(keys);
    Collections.sort(sl);
    return sl;
  }

  private void generatePrimitive(BufferedWriter writer, StructureDefinition sd) throws IOException, FHIRException {
    String gqlName = getGqlname(sd.getName());
    if (gqlName.equals(sd.getName())) {
      writer.write("Scalar ");
      writer.write(sd.getName());
      writer.write(" # JSON Format: ");
      writer.write(getJsonFormat(sd));
    } else  {
      writer.write("# Type ");
      writer.write(sd.getName());
      writer.write(": use GraphQL Scalar type ");
      writer.write(gqlName);
    }
    writer.write("\r\n");
  }

  private void generateSearchParamType(BufferedWriter writer, String name) throws IOException, FHIRException {
    String gqlName = getGqlname(name);
    if (gqlName.equals(name)) {
      writer.write("Scalar ");
      writer.write(name);
      writer.write(" # JSON Format: String");
    } else  {
      writer.write("# Search Param ");
      writer.write(name);
      writer.write(": use GraphQL Scalar type ");
      writer.write(gqlName);
    }
    writer.write("\r\n");
  }

  private String getJsonFormat(StructureDefinition sd) throws FHIRException {
    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
      if (!ed.getType().isEmpty() &&  ed.getType().get(0).getCodeElement().hasExtension("http://hl7.org/fhir/StructureDefinition/structuredefinition-json-type"))
        return ed.getType().get(0).getCodeElement().getExtensionString("http://hl7.org/fhir/StructureDefinition/structuredefinition-json-type");
    }
    return "??";
  }

  private String getGqlname(String name) {
    if (name.equals("string"))
      return "String";
    if (name.equals("integer"))
      return "Int";
    if (name.equals("boolean"))
      return "Boolean";
    if (name.equals("id"))
      return "ID";
    return name;
  }
}


text:
@interface FCPlaybackVC : FCSuperVC

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// This example demonstrates how to add futures for a given underlying asset.
    /// It also shows how you can prefilter contracts easily based on expirations, and how you
    /// can inspect the futures chain to pick a specific contract to trade.
    /// </summary>
    /// <meta name="tag" content="using data" />
    /// <meta name="tag" content="benchmarks" />
    /// <meta name="tag" content="futures" />
    public class BasicTemplateFuturesAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        // S&P 500 EMini futures
        private const string RootSP500 = Futures.Indices.SP500EMini;
        public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.USA);

        // Gold futures
        private const string RootGold = Futures.Metals.Gold;
        public Symbol Gold = QuantConnect.Symbol.Create(RootGold, SecurityType.Future, Market.USA);

        /// <summary>
        /// Initialize your algorithm and add desired assets.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 08);
            SetEndDate(2013, 10, 10);
            SetCash(1000000);

            var futureSP500 = AddFuture(RootSP500);
            var futureGold = AddFuture(RootGold);

            // set our expiry filter for this futures chain
            futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
            futureGold.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));

            var benchmark = AddEquity("SPY");
            SetBenchmark(benchmark.Symbol);
        }

        /// <summary>
        /// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
        /// </summary>
        /// <param name="slice">The current slice of data keyed by symbol string</param>
        public override void OnData(Slice slice)
        {
            if (!Portfolio.Invested)
            {
                foreach(var chain in slice.FutureChains)
                {
                    // find the front contract expiring no earlier than in 90 days
                    var contract = (
                        from futuresContract in chain.Value.OrderBy(x => x.Expiry)
                        where futuresContract.Expiry > Time.Date.AddDays(90)
                        select futuresContract
                    ).FirstOrDefault();

                    // if found, trade it
                    if (contract != null)
                    {
                        MarketOrder(contract.Symbol, 1);
                    }
                }
            }
            else
            {
                Liquidate();
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp, Language.Python };

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "8220"},
            {"Average Win", "0.00%"},
            {"Average Loss", "0.00%"},
            {"Compounding Annual Return", "-100.000%"},
            {"Drawdown", "13.500%"},
            {"Expectancy", "-0.818"},
            {"Net Profit", "-13.517%"},
            {"Sharpe Ratio", "-29.354"},
            {"Loss Rate", "89%"},
            {"Win Rate", "11%"},
            {"Profit-Loss Ratio", "0.69"},
            {"Alpha", "-7.746"},
            {"Beta", "-0.859"},
            {"Annual Standard Deviation", "0.305"},
            {"Annual Variance", "0.093"},
            {"Information Ratio", "-24.985"},
            {"Tracking Error", "0.414"},
            {"Treynor Ratio", "10.413"},
            {"Total Fees", "$15207.00"}
        };
    }
}


text:
package azkaban.flowtrigger;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import azkaban.Constants;
import azkaban.db.DatabaseOperator;
import azkaban.flowtrigger.database.FlowTriggerInstanceLoader;
import azkaban.flowtrigger.database.JdbcFlowTriggerInstanceLoaderImpl;
import azkaban.project.DirectoryYamlFlowLoader;
import azkaban.project.FlowLoaderUtils;
import azkaban.project.FlowTrigger;
import azkaban.project.FlowTriggerDependency;
import azkaban.project.JdbcProjectImpl;
import azkaban.project.JdbcProjectImplTest;
import azkaban.project.Project;
import azkaban.project.ProjectLoader;
import azkaban.project.ProjectManager;
import azkaban.test.Utils;
import azkaban.test.executions.ExecutionsTestUtil;
import azkaban.utils.Props;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlowTriggerInstanceLoaderTest {

  private static final Logger logger = LoggerFactory.getLogger(FlowTriggerInstanceLoaderTest.class);
  private static final String test_project_zip_dir = "flowtriggeryamltest";
  private static final String test_flow_file = "flow_trigger.flow";
  private static final int project_id = 123;
  private static final String project_name = "test";
  private static final int project_version = 3;
  private static final String flow_id = "flow_trigger";
  private static final int flow_version = 1;
  private static final Props props = new Props();
  private static final String submitUser = "uploadUser1";
  private static DatabaseOperator dbOperator;
  private static ProjectLoader projLoader;
  private static FlowTrigger flowTrigger;
  private static FlowTriggerInstanceLoader triggerInstLoader;
  private static Project project;
  private static ProjectManager projManager;

  @AfterClass
  public static void destroyDB() {
    try {
      dbOperator.update("SHUTDOWN");
      dbOperator.update("DROP ALL OBJECTS");
      dbOperator.update("SHUTDOWN");
    } catch (final SQLException e) {
      logger.error("unable to destroy db", e);
    }
  }

  @BeforeClass
  public static void setup() throws Exception {
    dbOperator = Utils.initTestDB();
    projLoader = new JdbcProjectImpl(props, dbOperator);
    projManager = mock(ProjectManager.class);
    triggerInstLoader = new JdbcFlowTriggerInstanceLoaderImpl(dbOperator, projLoader, projManager);
    project = new Project(project_id, project_name);

    final DirectoryYamlFlowLoader yamlFlowLoader = new DirectoryYamlFlowLoader(new Props());
    yamlFlowLoader
        .loadProjectFlow(project, ExecutionsTestUtil.getFlowDir(test_project_zip_dir));
    project.setVersion(project_version);
    project.setFlows(yamlFlowLoader.getFlowMap());
    project.setLastModifiedUser(submitUser);

    final File flowFile = new File(JdbcProjectImplTest.class.getClassLoader().getResource
        (test_flow_file).getFile());

    when(projManager.getProject(project_id)).thenReturn(project);

    projLoader
        .uploadFlowFile(project_id, project_version, flowFile, flow_version);
    flowTrigger = FlowLoaderUtils.getFlowTriggerFromYamlFile(flowFile);
  }

  private TriggerInstance createTriggerInstance(final FlowTrigger flowTrigger, final String flowId,
      final int flowVersion, final String submitUser, final Project project, final long startTime) {
    final String triggerInstId = UUID.randomUUID().toString();
    final List<DependencyInstance> depInstList = new ArrayList<>();
    for (final FlowTriggerDependency dep : flowTrigger.getDependencies()) {
      final String depName = dep.getName();
      final DependencyInstanceContext context = new TestDependencyInstanceContext(null, null, null);
      final Status status = Status.RUNNING;
      final CancellationCause cause = CancellationCause.NONE;
      final DependencyInstance depInst = new DependencyInstance(depName, startTime, 0, context,
          status, cause);
      depInstList.add(depInst);
    }

    final int flowExecId = Constants.UNASSIGNED_EXEC_ID;
    final TriggerInstance triggerInstance = new TriggerInstance(triggerInstId, flowTrigger,
        flowId, flowVersion, submitUser, depInstList, flowExecId, project);

    return triggerInstance;
  }

  @Test
  public void testUploadTriggerInstance() {
    final TriggerInstance expectedTriggerInst = this.createTriggerInstance(this.flowTrigger, this
        .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis());

    this.triggerInstLoader.uploadTriggerInstance(expectedTriggerInst);

    final TriggerInstance actualTriggerInst = this.triggerInstLoader
        .getTriggerInstanceById(expectedTriggerInst.getId());

    assertThat(expectedTriggerInst.getFlowTrigger().toString())
        .isEqualToIgnoringWhitespace(actualTriggerInst.getFlowTrigger().toString());

    assertThat(expectedTriggerInst).isEqualToIgnoringGivenFields(actualTriggerInst,
        "depInstances", "flowTrigger");

    assertThat(expectedTriggerInst.getDepInstances())
        .usingElementComparatorIgnoringFields("triggerInstance", "context")
        .containsAll(actualTriggerInst.getDepInstances())
        .hasSameSizeAs(actualTriggerInst.getDepInstances());
  }

  private void assertTriggerInstancesEqual(final TriggerInstance actual,
      final TriggerInstance expected, final boolean ignoreFlowTrigger) {
    if (!ignoreFlowTrigger) {
      if (actual.getFlowTrigger() != null && expected.getFlowTrigger() != null) {
        assertThat(actual.getFlowTrigger().toString())
            .isEqualToIgnoringWhitespace(expected.getFlowTrigger().toString());
      } else {
        assertThat(actual.getFlowTrigger()).isNull();
        assertThat(expected.getFlowTrigger()).isNull();
      }
    }

    assertThat(actual).isEqualToIgnoringGivenFields(expected, "depInstances", "flowTrigger");

    assertThat(actual.getDepInstances())
        .usingComparatorForElementFieldsWithType((d1, d2) -> {
          if (d1 == null && d2 == null) {
            return 0;
          } else if (d1 != null && d2 != null && d1.getTime() == d2.getTime()) {
            return 0;
          } else {
            return -1;
          }
        }, Date.class)
        .usingElementComparatorIgnoringFields("triggerInstance", "context")
        .containsExactlyInAnyOrder(expected.getDepInstances()
            .toArray(new DependencyInstance[expected.getDepInstances().size()]));
  }

  @Test
  public void testUpdateDependencyExecutionStatus() {
    final TriggerInstance expectedTriggerInst = this.createTriggerInstance(this.flowTrigger, this
        .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis());

    this.triggerInstLoader.uploadTriggerInstance(expectedTriggerInst);
    for (final DependencyInstance depInst : expectedTriggerInst.getDepInstances()) {
      depInst.setStatus(Status.CANCELLED);
      depInst.setEndTime(System.currentTimeMillis());
      depInst.setCancellationCause(CancellationCause.MANUAL);
      this.triggerInstLoader.updateDependencyExecutionStatus(depInst);
    }

    final TriggerInstance actualTriggerInst = this.triggerInstLoader
        .getTriggerInstanceById(expectedTriggerInst.getId());
    assertTriggerInstancesEqual(actualTriggerInst, expectedTriggerInst, false);
  }

  private void finalizeTriggerInstanceWithSuccess(final TriggerInstance triggerInst, final int
      associateFlowExecId) {
    for (final DependencyInstance depInst : triggerInst.getDepInstances()) {
      depInst.setStatus(Status.SUCCEEDED);
      depInst.getTriggerInstance().setFlowExecId(associateFlowExecId);
      depInst.setEndTime(System.currentTimeMillis());
    }
  }

  private void finalizeTriggerInstanceWithCancelled(final TriggerInstance triggerInst) {
    for (final DependencyInstance depInst : triggerInst.getDepInstances()) {
      depInst.setStatus(Status.CANCELLED);
      depInst.setCancellationCause(CancellationCause.TIMEOUT);
      depInst.setEndTime(System.currentTimeMillis());
    }
  }

  private void finalizeTriggerInstanceWithCancelling(final TriggerInstance triggerInst) {
    for (final DependencyInstance depInst : triggerInst.getDepInstances()) {
      depInst.setStatus(Status.CANCELLING);
    }
  }

  private void shuffleAndUpload(final List<TriggerInstance> all) {
    final List<TriggerInstance> shuffled = new ArrayList<>(all);
    Collections.shuffle(shuffled);
    shuffled.forEach(triggerInst -> this.triggerInstLoader.uploadTriggerInstance(triggerInst));
  }

  @Test
  public void testGetIncompleteTriggerInstancesReturnsEmpty() {
    final List<TriggerInstance> all = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
      all.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()));
      if (i <= 2) {
        finalizeTriggerInstanceWithCancelled(all.get(i));
      } else {
        finalizeTriggerInstanceWithSuccess(all.get(i), 1000);
      }
    }
    this.shuffleAndUpload(all);
    final List<TriggerInstance> actual = new ArrayList<>(this.triggerInstLoader
        .getIncompleteTriggerInstances());
    all.sort(Comparator.comparing(TriggerInstance::getId));
    actual.sort(Comparator.comparing(TriggerInstance::getId));

    assertThat(actual).isEmpty();
  }

  @Test
  public void testGetIncompleteTriggerInstances() {
    final List<TriggerInstance> allInstances = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
      allInstances.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()));
    }

    finalizeTriggerInstanceWithCancelled(allInstances.get(0));
    finalizeTriggerInstanceWithSuccess(allInstances.get(1), 1000);
    // this trigger instance should still count as incomplete one since no flow execution has
    // been started
    finalizeTriggerInstanceWithSuccess(allInstances.get(2), -1);

    this.shuffleAndUpload(allInstances);

    final List<TriggerInstance> expected = allInstances.subList(2, allInstances.size());
    final List<TriggerInstance> actual = new ArrayList<>(this.triggerInstLoader
        .getIncompleteTriggerInstances());
    assertTwoTriggerInstanceListsEqual(actual, expected, false, false);
  }

  @Test
  public void testGetRunningTriggerInstancesReturnsEmpty() throws InterruptedException {
    final List<TriggerInstance> all = new ArrayList<>();
    for (int i = 0; i < 15; i++) {
      all.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()
          + i * 10000));
      finalizeTriggerInstanceWithSuccess(all.get(i), 1000);
    }

    this.shuffleAndUpload(all);

    final Collection<TriggerInstance> running = this.triggerInstLoader.getRunning();
    assertThat(running).isEmpty();
  }

  @Test
  public void testGetRunningTriggerInstances() throws InterruptedException {
    final List<TriggerInstance> all = new ArrayList<>();
    for (int i = 0; i < 15; i++) {
      all.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()
          + i * 10000));
      if (i <= 3) {
        finalizeTriggerInstanceWithCancelled(all.get(i));
      } else if (i <= 6) {
        finalizeTriggerInstanceWithSuccess(all.get(i), 1000);
      } else if (i <= 9) {
        finalizeTriggerInstanceWithCancelling(all.get(i));
      }
      //sleep for a while to ensure endtime is different for each trigger instance
      Thread.sleep(1000);
    }

    this.shuffleAndUpload(all);

    final List<TriggerInstance> finished = all.subList(7, all.size());

    final List<TriggerInstance> expected = new ArrayList<>(finished);
    expected.sort(Comparator.comparing(TriggerInstance::getStartTime));

    final Collection<TriggerInstance> running = this.triggerInstLoader.getRunning();
    assertTwoTriggerInstanceListsEqual(new ArrayList<>(running), expected, true, true);
  }

  private void assertTwoTriggerInstanceListsEqual(final List<TriggerInstance> actual,
      final List<TriggerInstance> expected, final boolean ignoreFlowTrigger,
      final boolean keepOriginalOrder) {
    if (!keepOriginalOrder) {
      expected.sort(Comparator.comparing(TriggerInstance::getId));
      actual.sort(Comparator.comparing(TriggerInstance::getId));
    }

    assertThat(actual).hasSameSizeAs(expected);
    final Iterator<TriggerInstance> it1 = actual.iterator();
    final Iterator<TriggerInstance> it2 = expected.iterator();
    while (it1.hasNext() && it2.hasNext()) {
      //8bfafb89-ac79-45a0-a049-b55038b0886b
      assertTriggerInstancesEqual(it1.next(), it2.next(), ignoreFlowTrigger);
    }
  }

  @Test
  public void testUpdateAssociatedFlowExecId() {
    final TriggerInstance expectedTriggerInst = this.createTriggerInstance(this.flowTrigger, this
        .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis());
    this.triggerInstLoader.uploadTriggerInstance(expectedTriggerInst);
    finalizeTriggerInstanceWithSuccess(expectedTriggerInst, 1000);

    expectedTriggerInst.getDepInstances()
        .forEach(depInst -> this.triggerInstLoader.updateDependencyExecutionStatus(depInst));

    this.triggerInstLoader.updateAssociatedFlowExecId(expectedTriggerInst);

    final TriggerInstance actualTriggerInst = this.triggerInstLoader
        .getTriggerInstanceById(expectedTriggerInst.getId());

    assertTriggerInstancesEqual(actualTriggerInst, expectedTriggerInst, false);
  }

  @Test
  public void testGetRecentlyFinishedReturnsEmpty() {
    final List<TriggerInstance> all = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      all.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()));
    }

    this.shuffleAndUpload(all);

    final Collection<TriggerInstance> recentlyFinished = this.triggerInstLoader
        .getRecentlyFinished(10);
    assertThat(recentlyFinished).isEmpty();
  }

  @Test
  public void testGetRecentlyFinished() throws InterruptedException {

    final List<TriggerInstance> all = new ArrayList<>();
    for (int i = 0; i < 15; i++) {
      all.add(this.createTriggerInstance(this.flowTrigger, this
          .flow_id, this.flow_version, this.submitUser, this.project, System.currentTimeMillis()
          + i * 10000));
      if (i <= 3) {
        finalizeTriggerInstanceWithCancelled(all.get(i));
      } else if (i <= 6) {
        finalizeTriggerInstanceWithSuccess(all.get(i), 1000);
      } else if (i <= 9) {
        finalizeTriggerInstanceWithCancelling(all.get(i));
      }
      //sleep for a while to ensure endtime is different for each trigger instance
      Thread.sleep(1000);
    }

    this.shuffleAndUpload(all);

    final List<TriggerInstance> finished = all.subList(0, 7);
    finished.sort((o1, o2) -> ((Long) o2.getEndTime()).compareTo(o1.getEndTime()));

    List<TriggerInstance> expected = new ArrayList<>(finished);
    expected.sort(Comparator.comparing(TriggerInstance::getStartTime));

    Collection<TriggerInstance> recentlyFinished = this.triggerInstLoader
        .getRecentlyFinished(10);
    assertTwoTriggerInstanceListsEqual(new ArrayList<>(recentlyFinished), expected, true, true);

    expected = new ArrayList<>(finished.subList(0, 3));
    expected.sort(Comparator.comparing(TriggerInstance::getStartTime));
    recentlyFinished = this.triggerInstLoader.getRecentlyFinished(3);
    assertTwoTriggerInstanceListsEqual(new ArrayList<>(recentlyFinished), expected, true, true);

    expected = new ArrayList<>(finished.subList(0, 1));
    recentlyFinished = this.triggerInstLoader.getRecentlyFinished(1);
    assertTwoTriggerInstanceListsEqual(new ArrayList<>(recentlyFinished), expected, true, true);
  }

  @After
  public void cleanDB() {
    try {
      dbOperator.update("TRUNCATE TABLE execution_dependencies");
    } catch (final SQLException e) {
      e.printStackTrace();
    }
  }
}


text:
<template name="afFileUpload">

			{{#if fileUpload}}
				{{#with fileUpload}}
					{{> Template.dynamic template=template data=data}}
				{{/with}}

					 {{removeLabel}}
			{{else}}

					 {{label}}
					<input class="hidden" id="file-{{name}}" file-input="{{name}}" type="file" />

				Take a Photo
			{{/if}}

			<input type="text" style="display:none;" data-cfs-collection="{{this.atts.collection}}" {{fileUploadAtts}} value="{{value}}">

        <input type="file" class="text-center center-block well well-sm">

</template>

<template name="fileThumbIcon">

</template>

<template name="fileThumbImg">

</template>


text:
<?php

/**
 * Enter description here ...
 *
 * @method Mage_Sales_Model_Resource_Quote_Address_Rate _getResource()
 * @method Mage_Sales_Model_Resource_Quote_Address_Rate getResource()
 * @method int getAddressId()
 * @method Mage_Sales_Model_Quote_Address_Rate setAddressId(int $value)
 * @method string getCreatedAt()
 * @method Mage_Sales_Model_Quote_Address_Rate setCreatedAt(string $value)
 * @method string getUpdatedAt()
 * @method Mage_Sales_Model_Quote_Address_Rate setUpdatedAt(string $value)
 * @method string getCarrier()
 * @method Mage_Sales_Model_Quote_Address_Rate setCarrier(string $value)
 * @method string getCarrierTitle()
 * @method Mage_Sales_Model_Quote_Address_Rate setCarrierTitle(string $value)
 * @method string getCode()
 * @method Mage_Sales_Model_Quote_Address_Rate setCode(string $value)
 * @method string getMethod()
 * @method Mage_Sales_Model_Quote_Address_Rate setMethod(string $value)
 * @method string getMethodDescription()
 * @method Mage_Sales_Model_Quote_Address_Rate setMethodDescription(string $value)
 * @method float getPrice()
 * @method Mage_Sales_Model_Quote_Address_Rate setPrice(float $value)
 * @method string getErrorMessage()
 * @method Mage_Sales_Model_Quote_Address_Rate setErrorMessage(string $value)
 * @method string getMethodTitle()
 * @method Mage_Sales_Model_Quote_Address_Rate setMethodTitle(string $value)
 *
 * @category    Mage
 * @package     Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Sales_Model_Quote_Address_Rate extends Mage_Shipping_Model_Rate_Abstract
{
    protected $_address;

    protected function _construct()
    {
        $this->_init('sales/quote_address_rate');
    }

    protected function _beforeSave()
    {
        parent::_beforeSave();
        if ($this->getAddress()) {
            $this->setAddressId($this->getAddress()->getId());
        }
        return $this;
    }

    public function setAddress(Mage_Sales_Model_Quote_Address $address)
    {
        $this->_address = $address;
        return $this;
    }

    public function getAddress()
    {
        return $this->_address;
    }

    public function importShippingRate(Mage_Shipping_Model_Rate_Result_Abstract $rate)
    {
        if ($rate instanceof Mage_Shipping_Model_Rate_Result_Error) {
            $this
                ->setCode($rate->getCarrier().'_error')
                ->setCarrier($rate->getCarrier())
                ->setCarrierTitle($rate->getCarrierTitle())
                ->setErrorMessage($rate->getErrorMessage())
            ;
        } elseif ($rate instanceof Mage_Shipping_Model_Rate_Result_Method) {
            $this
                ->setCode($rate->getCarrier().'_'.$rate->getMethod())
                ->setCarrier($rate->getCarrier())
                ->setCarrierTitle($rate->getCarrierTitle())
                ->setMethod($rate->getMethod())
                ->setMethodTitle($rate->getMethodTitle())
                ->setMethodDescription($rate->getMethodDescription())
                ->setPrice($rate->getPrice())
            ;
        }
        return $this;
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p348;

import org.gradle.test.performance.mediummonolithicjavaproject.p346.Production6936;
import org.gradle.test.performance.mediummonolithicjavaproject.p347.Production6949;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test6963 {
    Production6963 objectUnderTest = new Production6963();

    @Test
    public void testProperty0() {
        Production6936 value = new Production6936();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production6949 value = new Production6949();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production6962 value = new Production6962();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
var Server = require ('./browser/Server');
var MultimediaStream = require ('./browser/MultimediaStream');
var EventEmitter = require ('events').EventEmitter;
var url = require ('url');

var eventQueue = {};

/**     @module substation
    @super EventEmitter
    Realtime application gateway and authentication provider.
*/
var servers = {};
var core = new EventEmitter();
module.exports = core;
core.MultimediaStream = MultimediaStream;
core.getUserMedia = MultimediaStream.getUserMedia;

/**     @property/Function inherit
    There are two big issues with `util.inherits`: It won't work with IE <9 and you have to bundle
    the entire `util` package to get it. This version works around both issues.
@argument/Function child
@argument/Function parent
*/
core.inherit = require ('./browser/inherit');

/**     @property/Function emit

*/
core.emit = function (eventName) {
    if (this.listeners (eventName).length)
        return EventEmitter.prototype.emit.apply (this, arguments);
    if (Object.hasOwnProperty.call (eventQueue, eventName))
        eventQueue[eventName].push (arguments);
    else
        eventQueue[eventName] = [ arguments ];
};
core.on ('newListener', function (event, listener) {
    if (!Object.hasOwnProperty.call (eventQueue, event))
        return;

    var queue = eventQueue[event];
    delete eventQueue[event];
    var i=0, j=queue.length;
    process.nextTick (function queueStep(){
        EventEmitter.emit.apply (core, queue[i]);
        i++;
        if (i >= j)
            return;
        process.nextTick (queueStep);
    });
});

/**     @property/Function getServer

@argument/String path
@returns/substation.Server server
*/
function getServer (path, options) {
    var host = path ? url.parse (path) : window.location;
    if (!host) throw new Error ('invalid url');
    if (Object.hasOwnProperty.call (servers, host)) {
        var server = servers[host];
        if (options)
            server.updateOptions (options);
        return server;
    }
    return servers[host] = new Server (core, host, options);
}
core.getServer = getServer;

/**     @property/Function sendEvents
    Fire an Array of events from the module Object and this domain's Server instance, if it already
    exists.
*/
function sendEvents (events) {
    for (var i=0,j=events.length; i<j; i++)
        core.emit.apply (core, events[i]);
}
core.sendEvents = sendEvents;

/**     @property/events.EventEmitter otherTabs
    @super events.EventEmitter
    Emit events from the `otherTabs` Object in other tabs.
*/
window.otherTabs = new EventEmitter();
window.otherTabs.emit = function(){
    var info = Array.prototype.slice.call (arguments);
    window.localStorage.setItem ('__substation_event', JSON.stringify (info));
};
window.addEventListener ('storage', function (event) {
    if (event.key != '__substation_event') return;
    EventEmitter.prototype.emit.apply (otherTabs.emitter, JSON.parse (event.newValue));
});


text:
<?php

require_once('./classes/eveapi/class.api.php');
require_once('./classes/eveapi/class.characters.php');
require_once('./classes/eveapi/class.facwarstats.php');

require_once('./print-as-html.php');
require_once('./config.php');

$api = new Api();
$api->setDebug(true);
$api->setUseCache(true); // that's the default, done for testing purposes
$api->setTimeTolerance(5); // also the default value
$api->setCredentials($apiuser,$apipass);
$apicharsxml = $api->getCharacters();
$apichars = Characters::getCharacters($apicharsxml);

// Find the character I'm interested in

foreach($apichars as $index => $thischar)
{
	if($thischar['charname']==$mychar)
	{
		$apichar=$thischar['charid'];
		$apicorp=$thischar['corpid'];
	}
}

// Set Credentials
$api->setCredentials($apiuser,$apipass,$apichar);

print ("
Raw char faction war stats output
");
$dataxml = $api->getFacWarStats();
$data = FacWarStats::getFacWarStats($dataxml);
print_as_html(print_r($data,TRUE));

unset ($dataxml,$data);

print ("
Raw corp faction war stats output
");
$dataxml = $api->getFacWarStats(true);
$data = FacWarStats::getFacWarStats($dataxml);
print_as_html(print_r($data,TRUE));

unset ($dataxml,$data);

$api->printErrors();
?>


text:
	<title>Alex Bellos's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Alex Bellos's panel show appearances

Alex Bellos has appeared in 3 episodes between 2010-2017.  Alex Bellos on IMDB. Alex Bellos on Wikipedia.

2010

2011

2012

2013

2014

2015

2016

2017

2017-01-23 / The Infinite Monkey Cage

2014-07-07 / The Infinite Monkey Cage

2010-11-29 / The Infinite Monkey Cage


text:
"use strict"

var ndarray = require("ndarray")
var fill = require("ndarray-fill")

// TODO: refactor with voxel-land
module.exports = function(game, opts) {
  return new TerrainPlugin(game, opts);
};
module.exports.pluginInfo = {
  loadAfter: ['voxel-registry', 'voxel-mesher']
};

function TerrainPlugin(game, opts) {
  this.shell = game.shell;

  this.registry = game.plugins.get('voxel-registry');
  if (!this.registry) throw new Error('lib/terrain requires voxel-registry plugin');

  this.mesher = game.plugins.get('voxel-mesher');
  if (!this.mesher) throw new Error('lib/terrain requires voxel-mesher plugin');

  this.enable();
};

TerrainPlugin.prototype.enable = function() {
  // once the game is about to initialize, gather all registered materials and build voxels
  // TODO: this doesn't really have to be done on gl-init, only when the blocks are ready. refactor with lib/blocks.js
  this.shell.on('gl-init', this.onInit = this.addVoxels.bind(this));
};

TerrainPlugin.prototype.disable = function() {
  this.shell.removeListener('gl-init', this.onInit);
};

// bit in voxel array to indicate voxel is opaque (transparent if not set)
var OPAQUE = 1<<15;

TerrainPlugin.prototype.addVoxels = function() {
  var terrainMaterials = {};
  for (var blockName in this.registry.blockName2Index) {
    var blockIndex = this.registry.blockName2Index[blockName];
    if (this.registry.getProp(blockName, 'transparent')) {
      terrainMaterials[blockName] = blockIndex - 1 // TODO: remove -1 offset? leave 0 as 'air' (unused) in texture arrays?
    } else {
      terrainMaterials[blockName] = OPAQUE|(blockIndex - 1) // TODO: separate arrays? https://github.com/mikolalysenko/ao-mesher/issues/2
    }
  }

  // add voxels
  this.mesher.addVoxelArray(createTerrain(terrainMaterials));
};

var createTerrain = function(materials) {
  var size = [33,33,33]
  var result = ndarray(new Int32Array(size[0]*size[1]*size[2]), size)
  //Fill ndarray with function
  fill(result, function(i,j,k) {
    //Terrain

    if (i===30 && j===30 && k===30) {
      // face texture test
      return materials.wool
    }

    if(i <=1 || i>=31 || j <= 1 || j >= 31 || k <= 1 || k >= 31) {
      return 0 // air
    }

    // tree
    if (i===7 && k===8 && 21<j && j<31) {
      return materials.logOak
    }
    var x = i - 7
    var y = j - 28
    var z = k - 8
    if (x*x + y*y + z*z < (Math.random()+1.0) * 5.0) {
      return materials.leavesOak
    }

    // glass structure
    x = i - 20
    y = j - 28
    z = k - 8
    if (x*x + y*y + z*z < 5.0) {
      return materials.glass
    }

    // lake
    x = i - 5
    y = j - 24
    z = k - 19
    if (x*x + y*y + z*z < 3.0) {
      return materials.water
    }

    // rolling hills
    var h0 = 3.0 * Math.sin(Math.PI * i / 12.0 - Math.PI * k * 0.1) + 22
    if(j > h0+1) {
      return 0 // air
    }
    // grassy surface with dirt
    if(h0 <= j) {
      return materials.grass
    }
    var h1 = 2.0 * Math.sin(Math.PI * i * 0.25 - Math.PI * k * 0.3) + 20
    if(h1 <= j) {
      return materials.dirt
    }

    // stone with ores
    if(4 < j) {
      return Math.random() < 0.1 ?
          materials.oreDiamond :
          materials.stone
    }
    return materials.lava
  })
  return result
};


text:
var pickMaterials : Material[];
var currentMaterialID : int = 0;
var chooseMeshRenderer : SkinnedMeshRenderer;

function Start () {

}

function Update () {
	if(Input.GetMouseButtonDown(0)){
		if( guiTexture.HitTest(Input.mousePosition)){
			currentMaterialID ++;
			if(currentMaterialID >= pickMaterials.Length){
				currentMaterialID = 0;
			}
			chooseMeshRenderer.material = pickMaterials[currentMaterialID];
		}
	}
}


text:
Manage the client config files

The client stores configuration in the current user's home directory (under the .kube directory as config). When you login the first time, a new config file is created, and subsequent project changes with the 'project' command will set the current context. These subcommands allow you to manage the config directly.

Reference: https://github.com/kubernetes/kubernetes/blob/master/docs/user-guide/kubeconfig-file.md

Usage:
  oc config SUBCOMMAND [options]

Examples:
  # Change the config context to use
  oc config use-context my-context

  # Set the value of a config preference
  oc config set preferences.some true

Available Commands:
  current-context Displays the current-context
  delete-cluster  Delete the specified cluster from the kubeconfig
  delete-context  Delete the specified context from the kubeconfig
  get-clusters    Display clusters defined in the kubeconfig
  get-contexts    Describe one or many contexts
  rename-context  Renames a context from the kubeconfig file.
  set             Sets an individual value in a kubeconfig file
  set-cluster     Sets a cluster entry in kubeconfig
  set-context     Sets a context entry in kubeconfig
  set-credentials Sets a user entry in kubeconfig
  unset           Unsets an individual value in a kubeconfig file
  use-context     Sets the current-context in a kubeconfig file
  view            Display merged kubeconfig settings or a specified kubeconfig file

Use "oc <command> --help" for more information about a given command.
Use "oc options" for a list of global command-line options (applies to all commands).


text:
from base64 import b64encode
from django.conf import settings
from mediagenerator.generators.bundles.base import Filter, FileFilter
from mediagenerator.utils import media_url, prepare_patterns, find_file
from mimetypes import guess_type
import logging
import os
import posixpath
import re

url_re = re.compile(r'url\s*\(["\']?([\w\.][^:]*?)["\']?\)', re.UNICODE)

# Whether to rewrite CSS URLs, at all
REWRITE_CSS_URLS = getattr(settings, 'REWRITE_CSS_URLS', True)
# Whether to rewrite CSS URLs relative to the respective source file
# or whether to use "absolute" URL rewriting (i.e., relative URLs are
# considered absolute with regards to STATICFILES_URL)
REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = getattr(settings,
    'REWRITE_CSS_URLS_RELATIVE_TO_SOURCE', True)

GENERATE_DATA_URIS = getattr(settings, 'GENERATE_DATA_URIS', False)
MAX_DATA_URI_FILE_SIZE = getattr(settings, 'MAX_DATA_URI_FILE_SIZE', 12*1024)
IGNORE_PATTERN = prepare_patterns(getattr(settings,
   'IGNORE_DATA_URI_PATTERNS', (r'.*\.htc',)), 'IGNORE_DATA_URI_PATTERNS')

class URLRewriter(object):
    def __init__(self, base_path='./'):
        if not base_path:
            base_path = './'
        self.base_path = base_path

    def rewrite_urls(self, content):
        if not REWRITE_CSS_URLS:
            return content
        return url_re.sub(self.fixurls, content)

    def fixurls(self, match):
        url = match.group(1)
        hashid = ''
        if '#' in url:
            url, hashid = url.split('#', 1)
            hashid = '#' + hashid
        if ':' not in url and not url.startswith('/'):
            rebased_url = posixpath.join(self.base_path, url)
            rebased_url = posixpath.normpath(rebased_url)
            try:
                if GENERATE_DATA_URIS:
                    path = find_file(rebased_url)
                    if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \
                            not IGNORE_PATTERN.match(rebased_url):
                        data = b64encode(open(path, 'rb').read())
                        mime = guess_type(path)[0] or 'application/octet-stream'
                        return 'url(data:%s;base64,%s)' % (mime, data)
                url = media_url(rebased_url)
            except:
                logging.error('URL not found: %s' % url)
        return 'url(%s%s)' % (url, hashid)

class CSSURL(Filter):
    """Rewrites URLs relative to media folder ("absolute" rewriting)."""
    def __init__(self, **kwargs):
        super(CSSURL, self).__init__(**kwargs)
        assert self.filetype == 'css', (
            'CSSURL only supports CSS output. '
            'The parent filter expects "%s".' % self.filetype)

    def get_output(self, variation):
        rewriter = URLRewriter()
        for input in self.get_input(variation):
            yield rewriter.rewrite_urls(input)

    def get_dev_output(self, name, variation):
        rewriter = URLRewriter()
        content = super(CSSURL, self).get_dev_output(name, variation)
        return rewriter.rewrite_urls(content)

class CSSURLFileFilter(FileFilter):
    """Rewrites URLs relative to input file's location."""
    def get_dev_output(self, name, variation):
        content = super(CSSURLFileFilter, self).get_dev_output(name, variation)
        if not REWRITE_CSS_URLS_RELATIVE_TO_SOURCE:
            return content
        rewriter = URLRewriter(posixpath.dirname(name))
        return rewriter.rewrite_urls(content)


text:
// by hxdone

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || !p || !q)
            return NULL;
        TreeNode* smaller = (p->val <= q->val) ? p : q;
        TreeNode* bigger = (smaller == p) ? q : p;
        if (root->val >= smaller->val) {
            if (root->val <= bigger->val)
                return root;
            else
                return lowestCommonAncestor(root->left, p, q);
        } else
            return lowestCommonAncestor(root->right, p, q);
    }
};