text:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Xml;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Collections;

namespace Umbraco.Extensions
{
    /// <summary>
    /// Provides object extension methods.
    /// </summary>
    public static class ObjectExtensions
    {
        private static readonly ConcurrentDictionary<Type, Type> NullableGenericCache = new ConcurrentDictionary<Type, Type>();
        private static readonly ConcurrentDictionary<CompositeTypeTypeKey, TypeConverter> InputTypeConverterCache = new ConcurrentDictionary<CompositeTypeTypeKey, TypeConverter>();
        private static readonly ConcurrentDictionary<CompositeTypeTypeKey, TypeConverter> DestinationTypeConverterCache = new ConcurrentDictionary<CompositeTypeTypeKey, TypeConverter>();
        private static readonly ConcurrentDictionary<CompositeTypeTypeKey, bool> AssignableTypeCache = new ConcurrentDictionary<CompositeTypeTypeKey, bool>();
        private static readonly ConcurrentDictionary<Type, bool> BoolConvertCache = new ConcurrentDictionary<Type, bool>();

        private static readonly char[] NumberDecimalSeparatorsToNormalize = { '.', ',' };
        private static readonly CustomBooleanTypeConverter CustomBooleanTypeConverter = new CustomBooleanTypeConverter();

        //private static readonly ConcurrentDictionary<Type, Func<object>> ObjectFactoryCache = new ConcurrentDictionary<Type, Func<object>>();

        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> AsEnumerableOfOne<T>(this T input)
        {
            return Enumerable.Repeat(input, 1);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        public static void DisposeIfDisposable(this object input)
        {
            if (input is IDisposable disposable)
                disposable.Dispose();
        }

        /// <summary>
        /// Provides a shortcut way of safely casting an input when you cannot guarantee the <typeparamref name="T"/> is
        /// an instance type (i.e., when the C# AS keyword is not applicable).
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static T SafeCast<T>(this object input)
        {
            if (ReferenceEquals(null, input) || ReferenceEquals(default(T), input)) return default;
            if (input is T variable) return variable;
            return default;
        }

        /// <summary>
        /// Attempts to convert the input object to the output type.
        /// </summary>
        /// <remarks>This code is an optimized version of the original Umbraco method</remarks>
        /// <typeparam name="T">The type to convert to</typeparam>
        /// <param name="input">The input.</param>
        /// <returns>The <see cref="Attempt{T}"/></returns>
        public static Attempt<T> TryConvertTo<T>(this object input)
        {
            Attempt<object> result = TryConvertTo(input, typeof(T));

            if (result.Success)
            {
                return Attempt<T>.Succeed((T)result.Result);
            }

            if (input == null)
            {
                if (typeof(T).IsValueType)
                {
                    // fail, cannot convert null to a value type
                    return Attempt<T>.Fail();
                }
                else
                {
                    // sure, null can be any object
                    return Attempt<T>.Succeed((T)input);
                }
            }

            // just try to cast
            try
            {
                return Attempt<T>.Succeed((T)input);
            }
            catch (Exception e)
            {
                return Attempt<T>.Fail(e);
            }
        }

        /// <summary>
        /// Attempts to convert the input object to the output type.
        /// </summary>
        /// <remarks>This code is an optimized version of the original Umbraco method</remarks>
        /// <param name="input">The input.</param>
        /// <param name="target">The type to convert to</param>
        /// <returns>The <see cref="Attempt{Object}"/></returns>
        public static Attempt<object> TryConvertTo(this object input, Type target)
        {
            if (target == null)
            {
                return Attempt<object>.Fail();
            }

            try
            {
                if (input == null)
                {
                    // Nullable is ok
                    if (target.IsGenericType && GetCachedGenericNullableType(target) != null)
                    {
                        return Attempt<object>.Succeed(null);
                    }

                    // Reference types are ok
                    return Attempt<object>.If(target.IsValueType == false, null);
                }

                var inputType = input.GetType();

                // Easy
                if (target == typeof(object) || inputType == target)
                {
                    return Attempt.Succeed(input);
                }

                // Check for string so that overloaders of ToString() can take advantage of the conversion.
                if (target == typeof(string))
                {
                    return Attempt<object>.Succeed(input.ToString());
                }

                // If we've got a nullable of something, we try to convert directly to that thing.
                // We cache the destination type and underlying nullable types
                // Any other generic types need to fall through
                if (target.IsGenericType)
                {
                    var underlying = GetCachedGenericNullableType(target);
                    if (underlying != null)
                    {
                        // Special case for empty strings for bools/dates which should return null if an empty string.
                        if (input is string inputString)
                        {
                            // TODO: Why the check against only bool/date when a string is null/empty? In what scenario can we convert to another type when the string is null or empty other than just being null?
                            if (string.IsNullOrEmpty(inputString) && (underlying == typeof(DateTime) || underlying == typeof(bool)))
                            {
                                return Attempt<object>.Succeed(null);
                            }
                        }

                        // Recursively call into this method with the inner (not-nullable) type and handle the outcome
                        var inner = input.TryConvertTo(underlying);

                        // And if successful, fall on through to rewrap in a nullable; if failed, pass on the exception
                        if (inner.Success)
                        {
                            input = inner.Result; // Now fall on through...
                        }
                        else
                        {
                            return Attempt<object>.Fail(inner.Exception);
                        }
                    }
                }
                else
                {
                    // target is not a generic type

                    if (input is string inputString)
                    {
                        // Try convert from string, returns an Attempt if the string could be
                        // processed (either succeeded or failed), else null if we need to try
                        // other methods
                        var result = TryConvertToFromString(inputString, target);
                        if (result.HasValue)
                        {
                            return result.Value;
                        }
                    }

                    // TODO: Do a check for destination type being IEnumerable<T> and source type implementing IEnumerable<T> with
                    // the same 'T', then we'd have to find the extension method for the type AsEnumerable() and execute it.
                    if (GetCachedCanAssign(input, inputType, target))
                    {
                        return Attempt.Succeed(Convert.ChangeType(input, target));
                    }
                }

                if (target == typeof(bool))
                {
                    if (GetCachedCanConvertToBoolean(inputType))
                    {
                        return Attempt.Succeed(CustomBooleanTypeConverter.ConvertFrom(input));
                    }
                }

                var inputConverter = GetCachedSourceTypeConverter(inputType, target);
                if (inputConverter != null)
                {
                    return Attempt.Succeed(inputConverter.ConvertTo(input, target));
                }

                var outputConverter = GetCachedTargetTypeConverter(inputType, target);
                if (outputConverter != null)
                {
                    return Attempt.Succeed(outputConverter.ConvertFrom(input));
                }

                if (target.IsGenericType && GetCachedGenericNullableType(target) != null)
                {
                    // cannot Convert.ChangeType as that does not work with nullable
                    // input has already been converted to the underlying type - just
                    // return input, there's an implicit conversion from T to T? anyways
                    return Attempt.Succeed(input);
                }

                // Re-check convertibles since we altered the input through recursion
                if (input is IConvertible convertible2)
                {
                    return Attempt.Succeed(Convert.ChangeType(convertible2, target));
                }
            }
            catch (Exception e)
            {
                return Attempt<object>.Fail(e);
            }

            return Attempt<object>.Fail();
        }

        /// <summary>
        /// Attempts to convert the input string to the output type.
        /// </summary>
        /// <remarks>This code is an optimized version of the original Umbraco method</remarks>
        /// <param name="input">The input.</param>
        /// <param name="target">The type to convert to</param>
        /// <returns>The <see cref="Nullable{Attempt}"/></returns>
        private static Attempt<object>? TryConvertToFromString(this string input, Type target)
        {
            // Easy
            if (target == typeof(string))
            {
                return Attempt<object>.Succeed(input);
            }

            // Null, empty, whitespaces
            if (string.IsNullOrWhiteSpace(input))
            {
                if (target == typeof(bool))
                {
                    // null/empty = bool false
                    return Attempt<object>.Succeed(false);
                }

                if (target == typeof(DateTime))
                {
                    // null/empty = min DateTime value
                    return Attempt<object>.Succeed(DateTime.MinValue);
                }

                // Cannot decide here,
                // Any of the types below will fail parsing and will return a failed attempt
                // but anything else will not be processed and will return null
                // so even though the string is null/empty we have to proceed.
            }

            // Look for type conversions in the expected order of frequency of use.
            //
            // By using a mixture of ordered if statements and switches we can optimize both for
            // fast conditional checking for most frequently used types and the branching
            // that does not depend on previous values available to switch statements.
            if (target.IsPrimitive)
            {
                if (target == typeof(int))
                {
                    if (int.TryParse(input,  out var value))
                    {
                        return Attempt<object>.Succeed(value);
                    }

                    // Because decimal 100.01m will happily convert to integer 100, it
                    // makes sense that string "100.01" *also* converts to integer 100.
                    var input2 = NormalizeNumberDecimalSeparator(input);
                    return Attempt<object>.If(decimal.TryParse(input2,  out var value2), Convert.ToInt32(value2));
                }

                if (target == typeof(long))
                {
                    if (long.TryParse(input, out var value))
                    {
                        return Attempt<object>.Succeed(value);
                    }

                    // Same as int
                    var input2 = NormalizeNumberDecimalSeparator(input);
                    return Attempt<object>.If(decimal.TryParse(input2, out var value2), Convert.ToInt64(value2));
                }

                // TODO: Should we do the decimal trick for short, byte, unsigned?

                if (target == typeof(bool))
                {
                    if (bool.TryParse(input,  out var value))
                    {
                        return Attempt<object>.Succeed(value);
                    }

                    // Don't declare failure so the CustomBooleanTypeConverter can try
                    return null;
                }

                // Calling this method directly is faster than any attempt to cache it.
                switch (Type.GetTypeCode(target))
                {
                    case TypeCode.Int16:
                        return Attempt<object>.If(short.TryParse(input, out var value), value);

                    case TypeCode.Double:
                        var input2 = NormalizeNumberDecimalSeparator(input);
                        return Attempt<object>.If(double.TryParse(input2,  out var valueD), valueD);

                    case TypeCode.Single:
                        var input3 = NormalizeNumberDecimalSeparator(input);
                        return Attempt<object>.If(float.TryParse(input3,  out var valueF), valueF);

                    case TypeCode.Char:
                        return Attempt<object>.If(char.TryParse(input, out var valueC), valueC);

                    case TypeCode.Byte:
                        return Attempt<object>.If(byte.TryParse(input, out var valueB), valueB);

                    case TypeCode.SByte:
                        return Attempt<object>.If(sbyte.TryParse(input, out var valueSb), valueSb);

                    case TypeCode.UInt32:
                        return Attempt<object>.If(uint.TryParse(input,  out var valueU), valueU);

                    case TypeCode.UInt16:
                        return Attempt<object>.If(ushort.TryParse(input,  out var valueUs), valueUs);

                    case TypeCode.UInt64:
                        return Attempt<object>.If(ulong.TryParse(input,  out var valueUl), valueUl);
                }
            }
            else if (target == typeof(Guid))
            {
                return Attempt<object>.If(Guid.TryParse(input, out var value), value);
            }
            else if (target == typeof(DateTime))
            {
                if (DateTime.TryParse(input, out var value))
                {
                    switch (value.Kind)
                    {
                        case DateTimeKind.Unspecified:
                        case DateTimeKind.Utc:
                            return Attempt<object>.Succeed(value);

                        case DateTimeKind.Local:
                            return Attempt<object>.Succeed(value.ToUniversalTime());

                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }

                return Attempt<object>.Fail();
            }
            else if (target == typeof(DateTimeOffset))
            {
                return Attempt<object>.If(DateTimeOffset.TryParse(input, out var value), value);
            }
            else if (target == typeof(TimeSpan))
            {
                return Attempt<object>.If(TimeSpan.TryParse(input, out var value), value);
            }
            else if (target == typeof(decimal))
            {
                var input2 = NormalizeNumberDecimalSeparator(input);
                return Attempt<object>.If(decimal.TryParse(input2, out var value), value);
            }
            else if (input != null && target == typeof(Version))
            {
                return Attempt<object>.If(Version.TryParse(input, out var value), value);
            }

            // E_NOTIMPL IPAddress, BigInteger
			return null; // we can't decide...
        }
        internal static void CheckThrowObjectDisposed(this IDisposable disposable, bool isDisposed, string objectname)
        {
            // TODO: Localize this exception
            if (isDisposed)
                throw new ObjectDisposedException(objectname);
        }

        //public enum PropertyNamesCaseType
        //{
        //    CamelCase,
        //    CaseInsensitive
        //}

        ///// <summary>
        ///// Convert an object to a JSON string with camelCase formatting
        ///// </summary>
        ///// <param name="obj"></param>
        ///// <returns></returns>
        //public static string ToJsonString(this object obj)
        //{
        //    return obj.ToJsonString(PropertyNamesCaseType.CamelCase);
        //}

        ///// <summary>
        ///// Convert an object to a JSON string with the specified formatting
        ///// </summary>
        ///// <param name="obj">The obj.</param>
        ///// <param name="propertyNamesCaseType">Type of the property names case.</param>
        ///// <returns></returns>
        //public static string ToJsonString(this object obj, PropertyNamesCaseType propertyNamesCaseType)
        //{
        //    var type = obj.GetType();
        //    var dateTimeStyle = "yyyy-MM-dd HH:mm:ss";

        //    if (type.IsPrimitive || typeof(string).IsAssignableFrom(type))
        //    {
        //        return obj.ToString();
        //    }

        //    if (typeof(DateTime).IsAssignableFrom(type) || typeof(DateTimeOffset).IsAssignableFrom(type))
        //    {
        //        return Convert.ToDateTime(obj).ToString(dateTimeStyle);
        //    }

        //    var serializer = new JsonSerializer();

        //    switch (propertyNamesCaseType)
        //    {
        //        case PropertyNamesCaseType.CamelCase:
        //            serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
        //            break;
        //    }

        //    var dateTimeConverter = new IsoDateTimeConverter
        //        {
        //            DateTimeStyles = System.Globalization.DateTimeStyles.None,
        //            DateTimeFormat = dateTimeStyle
        //        };

        //    if (typeof(IDictionary).IsAssignableFrom(type))
        //    {
        //        return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
        //    }

        //    if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type)))
        //    {
        //        return JArray.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
        //    }

        //    return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
        //}

        /// <summary>
        /// Converts an object into a dictionary
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <typeparam name="TVal"> </typeparam>
        /// <param name="o"></param>
        /// <param name="ignoreProperties"></param>
        /// <returns></returns>
        public static IDictionary<string, TVal> ToDictionary<T, TProperty, TVal>(this T o, params Expression<Func<T, TProperty>>[] ignoreProperties)
        {
            return o.ToDictionary<TVal>(ignoreProperties.Select(e => o.GetPropertyInfo(e)).Select(propInfo => propInfo.Name).ToArray());
        }

        /// <summary>
        /// Turns object into dictionary
        /// </summary>
        /// <param name="o"></param>
        /// <param name="ignoreProperties">Properties to ignore</param>
        /// <returns></returns>
        public static IDictionary<string, TVal> ToDictionary<TVal>(this object o, params string[] ignoreProperties)
        {
            if (o != null)
            {
                var props = TypeDescriptor.GetProperties(o);
                var d = new Dictionary<string, TVal>();
                foreach (var prop in props.Cast<PropertyDescriptor>().Where(x => ignoreProperties.Contains(x.Name) == false))
                {
                    var val = prop.GetValue(o);
                    if (val != null)
                    {
                        d.Add(prop.Name, (TVal)val);
                    }
                }
                return d;
            }
            return new Dictionary<string, TVal>();
        }

        internal static string ToDebugString(this object obj, int levels = 0)
        {
            if (obj == null) return "{null}";
            try
            {
                if (obj is string)
                {
                    return "\"{0}\"".InvariantFormat(obj);
                }
                if (obj is int || obj is short || obj is long || obj is float || obj is double || obj is bool || obj is int? || obj is short? || obj is long? || obj is float? || obj is double? || obj is bool?)
                {
                    return "{0}".InvariantFormat(obj);
                }
                if (obj is Enum)
                {
                    return "[{0}]".InvariantFormat(obj);
                }
                if (obj is IEnumerable)
                {
                    var enumerable = (obj as IEnumerable);

                    var items = (from object enumItem in enumerable let value = GetEnumPropertyDebugString(enumItem, levels) where value != null select value).Take(10).ToList();

                    return items.Any()
                            ? "{{ {0} }}".InvariantFormat(string.Join(", ", items))
                            : null;
                }

                var props = obj.GetType().GetProperties();
                if ((props.Length == 2) && props[0].Name == "Key" && props[1].Name == "Value" && levels > -2)
                {
                    try
                    {
                        var key = props[0].GetValue(obj, null) as string;
                        var value = props[1].GetValue(obj, null).ToDebugString(levels - 1);
                        return "{0}={1}".InvariantFormat(key, value);
                    }
                    catch (Exception)
                    {
                        return "[KeyValuePropertyException]";
                    }
                }
                if (levels > -1)
                {
                    var items =
                        (from propertyInfo in props
                         let value = GetPropertyDebugString(propertyInfo, obj, levels)
                         where value != null
                         select "{0}={1}".InvariantFormat(propertyInfo.Name, value)).ToArray();

                    return items.Any()
                            ? "[{0}]:{{ {1} }}".InvariantFormat(obj.GetType().Name, String.Join(", ", items))
                            : null;
                }
            }
            catch (Exception ex)
            {
                return "[Exception:{0}]".InvariantFormat(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// Attempts to serialize the value to an XmlString using ToXmlString
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static Attempt<string> TryConvertToXmlString(this object value, Type type)
        {
            try
            {
                var output = value.ToXmlString(type);
                return Attempt.Succeed(output);
            }
            catch (NotSupportedException ex)
            {
                return Attempt<string>.Fail(ex);
            }
        }

        /// <summary>
        /// Returns an XmlSerialized safe string representation for the value
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type">The Type can only be a primitive type or Guid and byte[] otherwise an exception is thrown</param>
        /// <returns></returns>
        public static string ToXmlString(this object value, Type type)
        {
            if (value == null) return string.Empty;
            if (type == typeof(string)) return (value.ToString().IsNullOrWhiteSpace() ? "" : value.ToString());
            if (type == typeof(bool)) return XmlConvert.ToString((bool)value);
            if (type == typeof(byte)) return XmlConvert.ToString((byte)value);
            if (type == typeof(char)) return XmlConvert.ToString((char)value);
            if (type == typeof(DateTime)) return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.Unspecified);
            if (type == typeof(DateTimeOffset)) return XmlConvert.ToString((DateTimeOffset)value);
            if (type == typeof(decimal)) return XmlConvert.ToString((decimal)value);
            if (type == typeof(double)) return XmlConvert.ToString((double)value);
            if (type == typeof(float)) return XmlConvert.ToString((float)value);
            if (type == typeof(Guid)) return XmlConvert.ToString((Guid)value);
            if (type == typeof(int)) return XmlConvert.ToString((int)value);
            if (type == typeof(long)) return XmlConvert.ToString((long)value);
            if (type == typeof(sbyte)) return XmlConvert.ToString((sbyte)value);
            if (type == typeof(short)) return XmlConvert.ToString((short)value);
            if (type == typeof(TimeSpan)) return XmlConvert.ToString((TimeSpan)value);
            if (type == typeof(uint)) return XmlConvert.ToString((uint)value);
            if (type == typeof(ulong)) return XmlConvert.ToString((ulong)value);
            if (type == typeof(ushort)) return XmlConvert.ToString((ushort)value);

            throw new NotSupportedException("Cannot convert type " + type.FullName + " to a string using ToXmlString as it is not supported by XmlConvert");
        }

        /// <summary>
        /// Returns an XmlSerialized safe string representation for the value and type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToXmlString<T>(this object value)
        {
            return value.ToXmlString(typeof (T));
        }

        private static string GetEnumPropertyDebugString(object enumItem, int levels)
        {
            try
            {
                return enumItem.ToDebugString(levels - 1);
            }
            catch (Exception)
            {
                return "[GetEnumPartException]";
            }
        }

        private static string GetPropertyDebugString(PropertyInfo propertyInfo, object obj, int levels)
        {
            try
            {
                return propertyInfo.GetValue(obj, null).ToDebugString(levels - 1);
            }
            catch (Exception)
            {
                return "[GetPropertyValueException]";
            }
        }

        public static Guid AsGuid(this object value)
        {
            return value is Guid guid ? guid : Guid.Empty;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static string NormalizeNumberDecimalSeparator(string s)
        {
            var normalized = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
            return s.ReplaceMany(NumberDecimalSeparatorsToNormalize, normalized);
        }

        // gets a converter for source, that can convert to target, or null if none exists
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static TypeConverter GetCachedSourceTypeConverter(Type source, Type target)
        {
            var key = new CompositeTypeTypeKey(source, target);

            if (InputTypeConverterCache.TryGetValue(key, out var typeConverter))
            {
                return typeConverter;
            }

            var converter = TypeDescriptor.GetConverter(source);
            if (converter.CanConvertTo(target))
            {
                return InputTypeConverterCache[key] = converter;
            }

            return InputTypeConverterCache[key] = null;
        }

        // gets a converter for target, that can convert from source, or null if none exists
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static TypeConverter GetCachedTargetTypeConverter(Type source, Type target)
        {
            var key = new CompositeTypeTypeKey(source, target);

            if (DestinationTypeConverterCache.TryGetValue(key, out var typeConverter))
            {
                return typeConverter;
            }

            var converter = TypeDescriptor.GetConverter(target);
            if (converter.CanConvertFrom(source))
            {
                return DestinationTypeConverterCache[key] = converter;
            }

            return DestinationTypeConverterCache[key] = null;
        }

        // gets the underlying type of a nullable type, or null if the type is not nullable
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static Type GetCachedGenericNullableType(Type type)
        {
            if (NullableGenericCache.TryGetValue(type, out var underlyingType))
            {
                return underlyingType;
            }

            if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                Type underlying = Nullable.GetUnderlyingType(type);
                return NullableGenericCache[type] = underlying;
            }

            return NullableGenericCache[type] = null;
        }

        // gets an IConvertible from source to target type, or null if none exists
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool GetCachedCanAssign(object input, Type source, Type target)
        {
            var key = new CompositeTypeTypeKey(source, target);
            if (AssignableTypeCache.TryGetValue(key, out var canConvert))
            {
                return canConvert;
            }

            // "object is" is faster than "Type.IsAssignableFrom.
            // We can use it to very quickly determine whether true/false
            if (input is IConvertible && target.IsAssignableFrom(source))
            {
                return AssignableTypeCache[key] = true;
            }

            return AssignableTypeCache[key] = false;
        }

        // determines whether a type can be converted to boolean
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool GetCachedCanConvertToBoolean(Type type)
        {
            if (BoolConvertCache.TryGetValue(type, out var result))
            {
                return result;
            }

            if (CustomBooleanTypeConverter.CanConvertFrom(type))
            {
                return BoolConvertCache[type] = true;
            }

            return BoolConvertCache[type] = false;
        }

    }
}


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

<title>Uses of Interface org.springframework.jdbc.core.SqlTypeValue (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.springframework.jdbc.core.SqlTypeValue

Packages that use SqlTypeValue

Package
Description

org.springframework.jdbc.core

Provides the core JDBC framework, based on JdbcTemplate
 and its associated callback interfaces and helper objects.

org.springframework.jdbc.core.support

Classes supporting the org.springframework.jdbc.core package.

Uses of SqlTypeValue in org.springframework.jdbc.core

Subinterfaces of SqlTypeValue in org.springframework.jdbc.core

Modifier and Type
Interface and Description

interface
DisposableSqlTypeValue

Subinterface of SqlTypeValue that adds a cleanup callback,
 to be invoked after the value has been set and the corresponding
 statement has been executed.

Uses of SqlTypeValue in org.springframework.jdbc.core.support

Classes in org.springframework.jdbc.core.support that implement SqlTypeValue

Modifier and Type
Class and Description

class
AbstractSqlTypeValue

Abstract implementation of the SqlTypeValue interface, for convenient
 creation of type values that are supposed to be passed into the
 PreparedStatement.setObject method.

class
SqlLobValue

Object to represent an SQL BLOB/CLOB value parameter.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
package com.luyue.examples.algorithms.unionfind;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.luyue.examples.algorithms.unionfind.QuickUnion;

public class QuickUnionTest {

    @Test
    public void testConnected() {
        QuickUnion qu = new QuickUnion(10);
        qu.union(0, 5);
        qu.union(5, 6);
        qu.union(1, 6);
        qu.union(1, 2);
        qu.union(2, 7);
        qu.union(3, 4);
        qu.union(3, 8);
        qu.union(4, 9);

        assertTrue(qu.connected(0, 7));
        assertTrue(qu.connected(5, 7));
        assertTrue(qu.connected(2, 5));
        assertTrue(qu.connected(8, 9));
        assertTrue(qu.connected(3, 4));
        assertTrue(qu.connected(9, 3));
        assertFalse(qu.connected(0, 9));
    }

}


text:
using System.Collections.Generic;
using System.Globalization;
using Avalonia.Media;
using Avalonia.Platform;

namespace Avalonia.UnitTests
{
    public class MockFontManagerImpl : IFontManagerImpl
    {
        private readonly string _defaultFamilyName;

        public MockFontManagerImpl(string defaultFamilyName = "Default")
        {
            _defaultFamilyName = defaultFamilyName;
        }

        public string GetDefaultFontFamilyName()
        {
            return _defaultFamilyName;
        }

        public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false)
        {
            return new[] { _defaultFamilyName };
        }

        public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight,
            FontStretch fontStretch, FontFamily fontFamily,
            CultureInfo culture, out Typeface fontKey)
        {
            fontKey = new Typeface(_defaultFamilyName);

            return false;
        }

        public IGlyphTypeface CreateGlyphTypeface(Typeface typeface)
        {
            return new MockGlyphTypeface();
        }
    }
}


text:
import org.junit.Test;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

@SuppressWarnings("javadoc")
public class ColorLogbackTest extends ColorBaseTest {
    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("log-logback");

    static {
        System.out.println("===============================");
        System.out.println("==== Color logger - logback ===");
        System.out.println("===============================");
    }

    private static void selectLoggingConfigFile(String configFileName) {
        LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            configurator.doConfigure(getTargetDir() + configFileName);
        } catch (@SuppressWarnings("unused") JoranException e) {
            // StatusPrinter will handle this
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }

    private void doTheLogging(String configFileName) {
        selectLoggingConfigFile(configFileName);

        System.out.println();
        logger.error("error");
        logger.warn("warn");
        logger.info("info");
        logger.debug("debug");
        logger.trace("trace");

        System.out.println();
        Exception e = new NullPointerException("Just testing");
        logger.error("error with exception", e);
        logger.warn("warn with exception", e);
        logger.info("info with exception", e);
        logger.debug("debug with exception", e);
        logger.trace("trace with exception", e);
    }

    @Test
    public void colorLoggingLogback() {
        doTheLogging("logbackNormal.xml");
        doTheLogging("logbackNormalRegion.xml");
        doTheLogging("logbackColorEsc.xml");
        doTheLogging("logbackColorEscRegion.xml");
        System.out.println();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ServiceCallout async="false" continueOnError="false" enabled="true" name="Callout-Complete-Transfer">
    <DisplayName>Callout: Complete Transfer</DisplayName>
    <Properties/>
    <Request clearPayload="false" variable="FetchTransferRequest">
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
        <Set>
            <Payload contentType="application/json" variablePrefix="@" variableSuffix="#">
                {
                    "customerId":"@customer_id#",
                    "account_number": "@account_number#"
                }
            </Payload>
            <Verb>POST</Verb>
        </Set>
    </Request>
    <Response>CompleteTransferResponse</Response>
    <HTTPTargetConnection>
        <Properties>
            <Property name="success.codes">2xx,4xx,5xx</Property>
        </Properties>
        <URL>{{ edgeBasePath }}/apis/v1/transfers/complete/{messageid}</URL>
    </HTTPTargetConnection>
</ServiceCallout>


text:
const ERROR = 'error';
const OFF = 'off';

module.exports = {
    'extends': 'eslint:recommended',
    'env': {
        'browser': false,
        'es6': true,
        'node': true,
        'mocha': true
    },
    'parserOptions': {
        'ecmaVersion': 6,
        'sourceType': 'script',
        'ecmaFeatures': {}
    },
    'plugins': [
        'mocha'
    ],
    'rules': {
        // Possible Errors - http://eslint.org/docs/rules/#possible-errors
        'no-template-curly-in-string': ERROR,
        'no-unsafe-negation': ERROR,

        // Best Practices - http://eslint.org/docs/rules/#best-practices
        'block-scoped-var': ERROR,
        'class-methods-use-this': ERROR,
        'consistent-return': ERROR,
        'curly': ERROR,
        'default-case': ERROR,
        'dot-location': [ERROR, 'property'],
        'dot-notation': ERROR,
        'eqeqeq': ERROR,
        'guard-for-in': ERROR,
        'no-caller': ERROR,
        'no-console': OFF,
        'no-div-regex': ERROR,
        'no-else-return': ERROR,
        'no-empty-function': ERROR,
        'no-eval': ERROR,
        'no-extend-native': ERROR,
        'no-extra-bind': ERROR,
        'no-floating-decimal': ERROR,
        'no-global-assign': ERROR,
        'no-implicit-coercion': ERROR,
        'no-implied-eval': ERROR,
        'no-invalid-this': ERROR,
        'no-iterator': ERROR,
        'no-labels': ERROR,
        'no-lone-blocks': ERROR,
        'no-loop-func': ERROR,
        'no-magic-numbers': OFF,
        'no-multi-spaces': ERROR,
        'no-new-func': ERROR,
        'no-new-wrappers': ERROR,
        'no-new': ERROR,
        'no-octal-escape': ERROR,
        'no-param-reassign': ERROR,
        'no-proto': ERROR,
        'no-return-assign': [ERROR, 'always'],
        'no-return-await': ERROR,
        'no-script-url': ERROR,
        'no-self-compare': ERROR,
        'no-sequences': ERROR,
        'no-throw-literal': ERROR,
        'no-unmodified-loop-condition': ERROR,
        'no-unused-expressions': ERROR,
        'no-useless-call': ERROR,
        'no-useless-concat': ERROR,
        'no-useless-escape': ERROR,
        'no-useless-return': ERROR,
        'no-void': ERROR,
        'no-warning-comments': ERROR,
        'no-with': ERROR,
        'prefer-promise-reject-errors': ERROR,
        'radix': [ERROR, 'as-needed'],
        'require-await': ERROR,
        'vars-on-top': ERROR,
        'wrap-iife': ERROR,
        'yoda': ERROR,

        // Strict Mode - http://eslint.org/docs/rules/#strict-mode
        'strict': [ERROR, 'safe'],

        // Variables - http://eslint.org/docs/rules/#variables
        'no-shadow-restricted-names': ERROR,
        'no-shadow': ERROR,
        'no-undefined': ERROR,
        'no-use-before-define': [ERROR, {'functions': false, 'classes': false}],

        // Node and CommonJS - http://eslint.org/docs/rules/#nodejs-and-commonjs
        'callback-return': ERROR,
        'global-require': ERROR,
        'handle-callback-err': [ERROR, '^.*(e|E)rr'],
        'no-mixed-requires': ERROR,
        'no-new-require': ERROR,
        'no-path-concat': ERROR,
        'no-process-env': ERROR,
        'no-process-exit': ERROR,

        // Stylistic Issues - http://eslint.org/docs/rules/#stylistic-issues
        'array-bracket-spacing': [ERROR, 'never'],
        'block-spacing': ERROR,
        'brace-style': [ERROR, '1tbs'],
        'camelcase': ERROR,
        'comma-dangle': [ERROR, 'never'],
        'comma-spacing': [ERROR, {'before': false, 'after': true}],
        'comma-style': [ERROR, 'last'],
        'computed-property-spacing': [ERROR, 'never'],
        'eol-last': [ERROR, 'always'],
        'func-call-spacing': [ERROR, 'never'],
        'func-name-matching': ERROR,
        'func-style': [ERROR, 'declaration', {'allowArrowFunctions': true}],
        'id-blacklist': [ERROR, 'e', 'cb', 'callback'],
        'id-length': ERROR,
        'indent': [ERROR, 4],
        'key-spacing': [ERROR, {'beforeColon': false}],
        'key-spacing': [ERROR, {'mode': 'strict'}],
        'keyword-spacing': ERROR,
        'linebreak-style': [ERROR, 'unix'],
        'max-depth': [ERROR, 4],
        'max-len': [ERROR, 120],
        'max-lines': ERROR,
        'max-nested-callbacks': [ERROR, 4],
        'max-params': [ERROR, 5],
        'max-statements-per-line': [ERROR, {'max': 1}],
        'max-statements': [ERROR, 20],
        'new-cap': ERROR,
        'new-parens': ERROR,
        'newline-after-var': ERROR,
        'newline-before-return': ERROR,
        'newline-per-chained-call': ERROR,
        'no-array-constructor': ERROR,
        'no-bitwise': ERROR,
        'no-mixed-operators': ERROR,
        'no-mixed-spaces-and-tabs': ERROR,
        'no-multi-assign': ERROR,
        'no-multiple-empty-lines': ERROR,
        'no-negated-condition': ERROR,
        'no-nested-ternary': ERROR,
        'no-new-object': ERROR,
        'no-plusplus': [ERROR, {'allowForLoopAfterthoughts': true}],
        'no-trailing-spaces': ERROR,
        'no-underscore-dangle': ERROR,
        'no-unneeded-ternary': ERROR,
        'no-whitespace-before-property': ERROR,
        'object-curly-newline': OFF,
        'object-curly-spacing': [ERROR, 'never'],
        'object-property-newline': ERROR,
        'one-var-declaration-per-line': [ERROR, 'always'],
        'one-var': [ERROR, 'never'],
        'padded-blocks': [ERROR, 'never'],
        'quote-props': [ERROR, 'as-needed'],
        'quotes': [ERROR, 'single'],
        'semi-spacing': ERROR,
        'semi': ERROR,
        'space-before-blocks': ERROR,
        'space-before-function-paren': [ERROR, {'anonymous': 'always', 'named': 'never', 'asyncArrow': 'always'}],
        'space-in-parens': ERROR,
        'space-infix-ops': [ERROR, {'int32Hint': false}],
        'space-unary-ops': ERROR,
        'template-tag-spacing': ERROR,
        'unicode-bom': ERROR,

        // EcmaScript 6 - http://eslint.org/docs/rules/#ecmascript-6
        'arrow-body-style': [ERROR, 'as-needed'],
        'arrow-parens': ERROR,
        'arrow-spacing': ERROR,
        'generator-star-spacing': ERROR,
        'no-confusing-arrow': [ERROR, {'allowParens': false}],
        'no-duplicate-imports': [ERROR, {'includeExports': true}],
        'no-useless-computed-key': ERROR,
        'no-useless-constructor': ERROR,
        'no-useless-rename': ERROR,
        'object-shorthand': OFF,
        'prefer-numeric-literals': ERROR,
        'prefer-rest-params': ERROR,
        'prefer-spread': ERROR,
        'prefer-template': ERROR,
        'require-yield': ERROR,
        'sort-imports': ERROR,
        'symbol-description': ERROR,
        'template-curly-spacing': ERROR,
        'yield-star-spacing': ERROR,

        // Mocha Plugin - https://github.com/lo1tuma/eslint-plugin-mocha
        'mocha/handle-done-callback': ERROR,
        'mocha/no-exclusive-tests': ERROR,
        'mocha/no-global-tests': ERROR,
        'mocha/no-hooks-for-single-case': ERROR,
        'mocha/no-identical-title': ERROR,
        'mocha/no-mocha-arrows': ERROR,
        'mocha/no-nested-tests': ERROR,
        'mocha/no-return-and-callback': ERROR,
        'mocha/no-sibling-hooks': ERROR,
        'mocha/no-skipped-tests': ERROR,
        'mocha/no-top-level-hooks': ERROR
    }
}


text:
package io.reactivex.internal.operators.single;

import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;

/**
 * Breaks the references between the upstream and downstream when the Maybe terminates.
 * <p>History: 2.1.5 - experimental
 * @param <T> the value type
 * @since 2.2
 */
public final class SingleDetach<T> extends Single<T> {

    final SingleSource<T> source;

    public SingleDetach(SingleSource<T> source) {
        this.source = source;
    }

    @Override
    protected void subscribeActual(SingleObserver<? super T> observer) {
        source.subscribe(new DetachSingleObserver<T>(observer));
    }

    static final class DetachSingleObserver<T> implements SingleObserver<T>, Disposable {

        SingleObserver<? super T> downstream;

        Disposable upstream;

        DetachSingleObserver(SingleObserver<? super T> downstream) {
            this.downstream = downstream;
        }

        @Override
        public void dispose() {
            downstream = null;
            upstream.dispose();
            upstream = DisposableHelper.DISPOSED;
        }

        @Override
        public boolean isDisposed() {
            return upstream.isDisposed();
        }

        @Override
        public void onSubscribe(Disposable d) {
            if (DisposableHelper.validate(this.upstream, d)) {
                this.upstream = d;

                downstream.onSubscribe(this);
            }
        }

        @Override
        public void onSuccess(T value) {
            upstream = DisposableHelper.DISPOSED;
            SingleObserver<? super T> a = downstream;
            if (a != null) {
                downstream = null;
                a.onSuccess(value);
            }
        }

        @Override
        public void onError(Throwable e) {
            upstream = DisposableHelper.DISPOSED;
            SingleObserver<? super T> a = downstream;
            if (a != null) {
                downstream = null;
                a.onError(e);
            }
        }
    }
}


text:
<?php

namespace harrytang\fineuploader;

use yii\web\AssetBundle;

class FineuploaderAsset extends AssetBundle {

    public $sourcePath = '@harrytang/fineuploader/assets';
    public $js=[
        'jquery.fine-uploader/jquery.fine-uploader.min.js'
    ];
    public $css = [
        'jquery.fine-uploader/fine-uploader.min.css',
    ];
    public $depends = [
        'yii\web\JqueryAsset',
    ];

}


text:
angular.module('tragile.sprints')

.controller('SprintCreateCtrl', function($scope, $location, $state, api, sprintService, Project){
    $scope.projects = [];
    $scope.formData = {
        boardType: 'scrum'
    };
    $scope.formErrors = {};

    var projectId = $location.search().projectId;

    api.all('projects').getList().then(function(projects){
        $scope.projects = projects;
        var project = _.find(projects, function(project){
            return project.id === projectId;
        });
        $scope.formData.project = project || projects[0];
    });
    $scope.formData.start = moment().format("YYYY-MM-DD");
    $scope.formData.end = moment().add('days', 14).format("YYYY-MM-DD");

    $scope.submit = function(){
        formData = angular.copy($scope.formData);
        formData.project = $scope.formData.project.id;
        sprintService.save(formData).then(function(response){
            $state.go('sprints.entry', {sprintId: response.id});
        }, function(response) {
            $scope.formErrors = response.data;
        });
    };
});


text:
package com.sissi.protocol.iq.vcard;

import java.util.Iterator;
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.sissi.field.Field;
import com.sissi.field.Fields;
import com.sissi.field.impl.BeanFields;
import com.sissi.io.read.Collector;
import com.sissi.io.read.Metadata;
import com.sissi.protocol.Protocol;
import com.sissi.protocol.iq.data.XInput;
import com.sissi.protocol.iq.data.XNickname;
import com.sissi.protocol.iq.vcard.field.Photo;
import com.sissi.protocol.iq.vcard.field.muc.Activate;

/**
 * @author kim 2013年12月5日
 */
@Metadata(uri = VCard.XMLNS, localName = VCard.NAME)
@XmlType(namespace = VCard.XMLNS)
@XmlRootElement(name = VCard.NAME)
public class VCard extends Protocol implements Fields, Collector {

	public final static String XMLNS = "vcard-temp";

	public final static String NAME = "vCard";

	private final BeanFields fields = new BeanFields(false);

	@XmlAttribute
	public String getXmlns() {
		return XMLNS;
	}

	@XmlElements({ @XmlElement(name = Activate.NAME, type = Activate.class),@XmlElement(name = XInput.NAME, type = XInput.class), @XmlElement(name = XNickname.NAME, type = XNickname.class), @XmlElement(name = Photo.NAME, type = Photo.class) })
	public List<Field<?>> getFields() {
		return this.fields.getFields();
	}

	public VCard add(Field<?> field) {
		this.fields.add(field);
		return this;
	}

	@Override
	public void set(String localName, Object ob) {
		this.fields.add(Field.class.cast(ob));
	}

	public Fields addField(Field<?> field) {
		this.fields.add(field);
		return this;
	}

	@Override
	public Iterator<Field<?>> iterator() {
		return this.fields.iterator();
	}

	@Override
	public boolean isEmbed() {
		return this.fields.isEmbed();
	}

	public boolean isEmpty() {
		return this.fields.isEmpty();
	}

	public Fields findFields(String name) {
		return this.fields.findFields(name);
	}

	@Override
	public <T extends Field<?>> T findField(String name, Class<T> clazz) {
		return this.fields.findField(name, clazz);
	}
}