text:
package org.diorite.utils.reflections;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.Map;

import org.diorite.cfg.system.ConfigField;
import org.diorite.utils.SimpleEnum;

@SuppressWarnings({"unchecked", "ObjectEquality"})
public final class DioriteReflectionUtils
{
    private DioriteReflectionUtils()
    {
    }

    /**
     * Method will try find simple method setter and getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find element.
     * @param <T>   type of field.
     *
     * @return Element for field value.
     */
    public static <T> ReflectElement<T> getReflectElement(final ConfigField field)
    {
        return getReflectElement(field.getField(), field.getField().getDeclaringClass());
    }

    /**
     * Method will try find simple method setter and getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param fieldName name of field to find element.
     * @param clazz     clazz with this field.
     * @param <T>       type of field.
     *
     * @return Element for field value.
     */
    public static <T> ReflectElement<T> getReflectElement(final String fieldName, final Class<?> clazz)
    {
        final ReflectGetter<T> getter = getReflectGetter(fieldName, clazz);
        if (getter instanceof ReflectField)
        {
            final ReflectField<T> reflectField = (ReflectField<T>) getter;
            return new ReflectElement<>(reflectField, reflectField);
        }
        else
        {
            return new ReflectElement<>(getter, getReflectSetter(fieldName, clazz));
        }
    }

    /**
     * Method will try find simple method setter and getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find element.
     * @param <T>   type of field.
     *
     * @return Element for field value.
     */
    public static <T> ReflectElement<T> getReflectElement(final Field field)
    {
        return getReflectElement(field, field.getDeclaringClass());
    }

    /**
     * Method will try find simple method setter and getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find element.
     * @param clazz clazz with this field.
     * @param <T>   type of field.
     *
     * @return Element for field value.
     */
    public static <T> ReflectElement<T> getReflectElement(final Field field, final Class<?> clazz)
    {
        final ReflectGetter<T> getter = getReflectGetter(field, clazz);
        if (getter instanceof ReflectField)
        {
            final ReflectField<T> reflectField = (ReflectField<T>) getter;
            return new ReflectElement<>(reflectField, reflectField);
        }
        else
        {
            return new ReflectElement<>(getter, getReflectSetter(field, clazz));
        }
    }

    /**
     * Method will try find simple method setter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find setter.
     * @param <T>   type of field.
     *
     * @return Setter for field value.
     */
    public static <T> ReflectSetter<T> getReflectSetter(final ConfigField field)
    {
        return getReflectSetter(field.getField(), field.getField().getDeclaringClass());
    }

    /**
     * Method will try find simple method setter for selected field,
     * or directly use field if method can't be found.
     *
     * @param fieldName name of field to find setter.
     * @param clazz     clazz with this field.
     * @param <T>       type of field.
     *
     * @return Setter for field value.
     */
    public static <T> ReflectSetter<T> getReflectSetter(String fieldName, final Class<?> clazz)
    {
        final String fieldNameCpy = fieldName;
        fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        Method m = null;
        try
        {
            m = clazz.getMethod("get" + fieldName);
        } catch (final NoSuchMethodException ignored1)
        {
            try
            {
                m = clazz.getMethod("is" + fieldName);
            } catch (final NoSuchMethodException ignored2)
            {
                for (final Method cm : clazz.getMethods())
                {
                    if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
                    {
                        m = cm;
                        break;
                    }
                }
            }
        }

        if (m != null)
        {
            return new ReflectMethodSetter<>(m);
        }
        else
        {
            return new ReflectField<>(getField(clazz, fieldNameCpy));
        }
    }

    /**
     * Method will try find simple method setter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find setter.
     * @param <T>   type of field.
     *
     * @return Setter for field value.
     */
    public static <T> ReflectSetter<T> getReflectSetter(final Field field)
    {
        return getReflectSetter(field, field.getDeclaringClass());
    }

    /**
     * Method will try find simple method setter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find setter.
     * @param clazz clazz with this field.
     * @param <T>   type of field.
     *
     * @return Setter for field value.
     */
    public static <T> ReflectSetter<T> getReflectSetter(final Field field, final Class<?> clazz)
    {
        String fieldName = field.getName();
        fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        Method m = null;
        try
        {
            m = clazz.getMethod("set" + fieldName);
        } catch (final NoSuchMethodException ignored1)
        {
            for (final Method cm : clazz.getMethods())
            {
                if (cm.getName().equalsIgnoreCase("set" + fieldName) && (cm.getParameterCount() == 1))
                {
                    m = cm;
                    break;
                }
            }
        }

        if (m != null)
        {
            return new ReflectMethodSetter<>(m);
        }
        else
        {
            return new ReflectField<>(field);
        }
    }

    /**
     * Method will try find simple method getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find getter.
     * @param <T>   type of field.
     *
     * @return Getter for field value.
     */
    public static <T> ReflectGetter<T> getReflectGetter(final ConfigField field)
    {
        return getReflectGetter(field.getField(), field.getField().getDeclaringClass());
    }

    /**
     * Method will try find simple method getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param fieldName name of field to find getter.
     * @param clazz     clazz with this field.
     * @param <T>       type of field.
     *
     * @return Getter for field value.
     */
    public static <T> ReflectGetter<T> getReflectGetter(String fieldName, final Class<?> clazz)
    {
        final String fieldNameCpy = fieldName;
        fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        Method m = null;
        try
        {
            m = clazz.getMethod("get" + fieldName);
        } catch (final NoSuchMethodException ignored1)
        {
            try
            {
                m = clazz.getMethod("is" + fieldName);
            } catch (final NoSuchMethodException ignored2)
            {
                for (final Method cm : clazz.getMethods())
                {
                    if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
                    {
                        m = cm;
                        break;
                    }
                }
            }
        }

        if (m != null)
        {
            return new ReflectMethodGetter<>(m);
        }
        else
        {
            return new ReflectField<>(getField(clazz, fieldNameCpy));
        }
    }

    /**
     * Method will try find simple method getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find getter.
     * @param <T>   type of field.
     *
     * @return Getter for field value.
     */
    public static <T> ReflectGetter<T> getReflectGetter(final Field field)
    {
        return getReflectGetter(field, field.getDeclaringClass());
    }

    /**
     * Method will try find simple method getter for selected field,
     * or directly use field if method can't be found.
     *
     * @param field field to find getter.
     * @param clazz clazz with this field.
     * @param <T>   type of field.
     *
     * @return Getter for field value.
     */
    public static <T> ReflectGetter<T> getReflectGetter(final Field field, final Class<?> clazz)
    {
        String fieldName = field.getName();
        fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        Method m = null;
        try
        {
            m = clazz.getMethod("get" + fieldName);
        } catch (final NoSuchMethodException ignored1)
        {
            try
            {
                m = clazz.getMethod("is" + fieldName);
            } catch (final NoSuchMethodException ignored2)
            {
                for (final Method cm : clazz.getMethods())
                {
                    if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
                    {
                        m = cm;
                        break;
                    }
                }
            }
        }

        if (m != null)
        {
            return new ReflectMethodGetter<>(m);
        }
        else
        {
            return new ReflectField<>(field);
        }
    }

    /**
     * Safe method to get one of enum values by name or ordinal,
     * use -1 as id, to use only name,
     * and null or empty string for name, to use only ordinal id.
     *
     * @param name      name of enum field (ignore-case)
     * @param id        ordinal id.
     * @param enumClass class of enum.
     * @param <T>       type of enum.
     *
     * @return enum element or null.
     */
    public static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, final Class<? extends SimpleEnum<T>> enumClass)
    {
        return getSimpleEnumValueSafe(name, id, enumClass, null);
    }

    /**
     * Safe method to get one of enum values by name or ordinal,
     * use -1 as id, to use only name,
     * and null or empty string for name, to use only ordinal id.
     *
     * @param name name of enum field (ignore-case)
     * @param id   ordinal id.
     * @param def  default value, can't be null.
     * @param <T>  type of enum.
     *
     * @return enum element or def.
     */
    public static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, final T def)
    {
        return getSimpleEnumValueSafe(name, id, def.getClass(), def);
    }

    private static final Map<Class<?>, Method> simpleEnumMethods = new IdentityHashMap<>(40);

    private static <T extends SimpleEnum<T>> T getSimpleEnumValueSafe(final String name, final int id, Class<?> enumClass, final Object def)
    {
        do
        {
            try
            {
                Method m = simpleEnumMethods.get(enumClass);
                if (m == null)
                {
                    m = enumClass.getMethod("values");
                    simpleEnumMethods.put(enumClass, m);
                }
                final SimpleEnum<?>[] objects = (SimpleEnum<?>[]) m.invoke(null);
                for (final SimpleEnum<?> object : objects)
                {
                    if (object.name().equalsIgnoreCase(name) || (object.ordinal() == id))
                    {
                        return (T) object;
                    }
                }
            } catch (final Exception ignored)
            {
            }
            enumClass = enumClass.getSuperclass();
        } while ((enumClass != null) && ! (enumClass.equals(Object.class)));
        return (T) def;
    }

    /**
     * Safe method to get one of enum values by name or ordinal,
     * use -1 as id, to use only name,
     * and null or empty string for name, to use only ordinal id.
     *
     * @param name      name of enum field (ignore-case)
     * @param id        ordinal id.
     * @param enumClass class of enum.
     * @param <T>       type of enum.
     *
     * @return enum element or null.
     */
    public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass)
    {
        return getEnumValueSafe(name, id, enumClass, null);
    }

    /**
     * Safe method to get one of enum values by name or ordinal,
     * use -1 as id, to use only name,
     * and null or empty string for name, to use only ordinal id.
     *
     * @param name name of enum field (ignore-case)
     * @param id   ordinal id.
     * @param def  default value, can't be null.
     * @param <T>  type of enum.
     *
     * @return enum element or def.
     */
    public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final T def)
    {
        return getEnumValueSafe(name, id, def.getDeclaringClass(), def);
    }

    private static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass, final T def)
    {
        final T[] elements = enumClass.getEnumConstants();
        for (final T element : elements)
        {
            if (element.name().equalsIgnoreCase(name) || (element.ordinal() == id))
            {
                return element;
            }
        }
        return def;
    }

    /**
     * Retrieve a field accessor for a specific field type and name.
     *
     * @param target    - the target type.
     * @param name      - the name of the field, or NULL to ignore.
     * @param fieldType - a compatible field type.
     * @param <T>       - type of field.
     *
     * @return The field accessor.
     */
    public static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType)
    {
        return getField(target, name, fieldType, 0);
    }

    /**
     * Retrieve a field accessor for a specific field type and name.
     *
     * @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
     * @param name      - the name of the field, or NULL to ignore.
     * @param fieldType - a compatible field type.
     * @param <T>       - type of field.
     *
     * @return The field accessor.
     */
    public static <T> FieldAccessor<T> getField(final String className, final String name, final Class<T> fieldType)
    {
        return getField(getCanonicalClass(className), name, fieldType, 0);
    }

    /**
     * Retrieve a field accessor for a specific field type and name.
     *
     * @param target    - the target type.
     * @param fieldType - a compatible field type.
     * @param index     - the number of compatible fields to skip.
     * @param <T>       - type of field.
     *
     * @return The field accessor.
     */
    public static <T> FieldAccessor<T> getField(final Class<?> target, final Class<T> fieldType, final int index)
    {
        return getField(target, null, fieldType, index);
    }

    /**
     * Retrieve a field accessor for a specific field type and name.
     *
     * @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
     * @param fieldType - a compatible field type.
     * @param index     - the number of compatible fields to skip.
     * @param <T>       - type of field.
     *
     * @return The field accessor.
     */
    public static <T> FieldAccessor<T> getField(final String className, final Class<T> fieldType, final int index)
    {
        return getField(getCanonicalClass(className), fieldType, index);
    }

    /**
     * Set given accessible object as accessible if needed.
     *
     * @param o   accessible to get access.
     * @param <T> type of accessible object, used to keep type of returned value.
     *
     * @return this same object as given.
     */
    public static <T extends AccessibleObject> T getAccess(final T o)
    {
        if (! o.isAccessible())
        {
            o.setAccessible(true);
        }
        return o;
    }

    /**
     * Set field as accessible, and remove final flag if set.
     *
     * @param field field to get access.
     *
     * @return this same field.
     */
    public static Field getAccess(final Field field)
    {
        getAccess((AccessibleObject) field);
        if (Modifier.isFinal(field.getModifiers()))
        {
            try
            {
                final Field modifiersField = Field.class.getDeclaredField("modifiers");
                getAccess(modifiersField);
                modifiersField.setInt(field, field.getModifiers() & ~ Modifier.FINAL);
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
            {
                throw new IllegalArgumentException("That shouldn't happend (0)");
            }
        }
        return field;
    }

    /**
     * Search for the first publically and privately defined field of thie given name.
     *
     * @param target class to search in.
     * @param name   name of field.
     * @param <T>    type of field.
     *
     * @return field accessor for this field.
     *
     * @throws IllegalStateException If we cannot find this field.
     */
    public static <T> FieldAccessor<T> getField(final Class<?> target, final String name)
    {
        for (final Field field : target.getDeclaredFields())
        {
            if (((name == null) || field.getName().equals(name)))
            {
                getAccess(field);
                return new FieldAccessor<>(field);
            }
        }

        // Search in parent classes
        if (target.getSuperclass() != null)
        {
            return getField(target.getSuperclass(), name);
        }
        throw new IllegalArgumentException("Cannot find field with name " + name);
    }

    // Common method
    private static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType, int index)
    {
        for (final Field field : target.getDeclaredFields())
        {
            if (((name == null) || field.getName().equals(name)) && (fieldType.isAssignableFrom(field.getType()) && (index-- <= 0)))
            {
                getAccess(field);
                return new FieldAccessor<>(field);
            }
        }

        // Search in parent classes
        if (target.getSuperclass() != null)
        {
            return getField(target.getSuperclass(), name, fieldType, index);
        }
        throw new IllegalArgumentException("Cannot find field with type " + fieldType + " in " + target + ", index: " + index);
    }

    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param className  - lookup name of the class, see {@link #getCanonicalClass(String)}.
     * @param methodName - the method name, or NULL to skip.
     * @param params     - the expected parameters.
     *
     * @return An object that invokes this specific method.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    public static MethodInvoker getMethod(final String className, final String methodName, final Class<?>... params)
    {
        return getSimpleMethod(getCanonicalClass(className), methodName, null, params);
    }

    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param clazz      - a class to start with.
     * @param methodName - the method name, or NULL to skip.
     * @param params     - the expected parameters.
     *
     * @return An object that invokes this specific method.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    public static MethodInvoker getMethod(final Class<?> clazz, final String methodName, final Class<?>... params)
    {
        return getSimpleMethod(clazz, methodName, null, params);
    }

    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param clazz      - a class to start with.
     * @param methodName - the method name, or NULL to skip.
     * @param returnType - the expected return type, or NULL to ignore.
     * @param params     - the expected parameters.
     *
     * @return An object that invokes this specific method.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    public static MethodInvoker getTypedMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
    {
        for (final Method method : clazz.getDeclaredMethods())
        {
            if (((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)) && Arrays.equals(method.getParameterTypes(), params))
            {
                getAccess(method);
                return new MethodInvoker(method);
            }
        }
        // Search in every superclass
        if (clazz.getSuperclass() != null)
        {
            return getMethod(clazz.getSuperclass(), methodName, params);
        }
        throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
    }

    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param clazz      - a class to start with.
     * @param methodName - the method name, or NULL to skip.
     * @param returnType - the expected return type, or NULL to ignore.
     * @param params     - the expected parameters.
     *
     * @return An object that invokes this specific method.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    private static MethodInvoker getSimpleMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
    {
        for (final Method method : clazz.getDeclaredMethods())
        {
            if (((params.length == 0) || Arrays.equals(method.getParameterTypes(), params)) && ((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)))
            {
                getAccess(method);
                return new MethodInvoker(method);
            }
        }
        // Search in every superclass
        if (clazz.getSuperclass() != null)
        {
            return getMethod(clazz.getSuperclass(), methodName, params);
        }
        throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
    }

    /**
     * Search for the first publically and privately defined constructor of the given name and parameter count.
     *
     * @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
     * @param params    - the expected parameters.
     *
     * @return An object that invokes this constructor.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    public static ConstructorInvoker getConstructor(final String className, final Class<?>... params)
    {
        return getConstructor(getCanonicalClass(className), params);
    }

    /**
     * Search for the first publically and privately defined constructor of the given name and parameter count.
     *
     * @param clazz  - a class to start with.
     * @param params - the expected parameters.
     *
     * @return An object that invokes this constructor.
     *
     * @throws IllegalStateException If we cannot find this method.
     */
    public static ConstructorInvoker getConstructor(final Class<?> clazz, final Class<?>... params)
    {
        for (final Constructor<?> constructor : clazz.getDeclaredConstructors())
        {
            if (Arrays.equals(constructor.getParameterTypes(), params))
            {
                getAccess(constructor);
                return new ConstructorInvoker(constructor);
            }
        }
        throw new IllegalStateException(String.format("Unable to find constructor for %s (%s).", clazz, Arrays.asList(params)));
    }

    /**
     * Search for nested class with givan name.
     *
     * @param clazz - a class to start with.
     * @param name  - name of class.
     *
     * @return nested class form given class.
     */
    public static Class<?> getNestedClass(final Class<?> clazz, final String name)
    {
        for (final Class<?> nc : clazz.getDeclaredClasses())
        {
            if ((name == null) || nc.getSimpleName().equals(name))
            {
                return nc;
            }
        }
        if (clazz.getSuperclass() != null)
        {
            return getNestedClass(clazz.getSuperclass(), name);
        }
        throw new IllegalStateException("Unable to find nested class: " + name + " in " + clazz.getName());
    }

    /**
     * If given class is non-primitive type {@link Class#isPrimitive()} then it will return
     * privitive class for it. Like: Boolean.class {@literal ->} boolean.class
     * If given class is primitive, then it will return given class.
     * If given class can't be primitive (like {@link String}) then it will return given class.
     *
     * @param clazz class to get primitive of it.
     *
     * @return primitive class if possible.
     */
    @SuppressWarnings("ObjectEquality")
    public static Class<?> getPrimitive(final Class<?> clazz)
    {
        if (clazz.isPrimitive())
        {
            return clazz;
        }
        if (clazz == Boolean.class)
        {
            return boolean.class;
        }
        if (clazz == Byte.class)
        {
            return byte.class;
        }
        if (clazz == Short.class)
        {
            return short.class;
        }
        if (clazz == Character.class)
        {
            return char.class;
        }
        if (clazz == Integer.class)
        {
            return int.class;
        }
        if (clazz == Long.class)
        {
            return long.class;
        }
        if (clazz == Float.class)
        {
            return float.class;
        }
        if (clazz == Double.class)
        {
            return double.class;
        }
        return clazz;
    }

    /**
     * If given class is primitive type {@link Class#isPrimitive()} then it will return
     * wrapper class for it. Like: boolean.class {@literal ->} Boolean.class
     * If given class isn't primitive, then it will return given class.
     *
     * @param clazz class to get wrapper of it.
     *
     * @return non-primitive class.
     */
    @SuppressWarnings("ObjectEquality")
    public static Class<?> getWrapperClass(final Class<?> clazz)
    {
        if (! clazz.isPrimitive())
        {
            return clazz;
        }
        if (clazz == boolean.class)
        {
            return Boolean.class;
        }
        if (clazz == byte.class)
        {
            return Byte.class;
        }
        if (clazz == short.class)
        {
            return Short.class;
        }
        if (clazz == char.class)
        {
            return Character.class;
        }
        if (clazz == int.class)
        {
            return Integer.class;
        }
        if (clazz == long.class)
        {
            return Long.class;
        }
        if (clazz == float.class)
        {
            return Float.class;
        }
        if (clazz == double.class)
        {
            return Double.class;
        }
        throw new Error("Unknown primitive type?"); // not possible?
    }

    /**
     * Get array class for given class.
     *
     * @param clazz class to get array type of it.
     *
     * @return array version of class.
     */
    @SuppressWarnings("ObjectEquality")
    public static Class<?> getArrayClass(final Class<?> clazz)
    {
        if (clazz.isPrimitive())
        {
            if (clazz == boolean.class)
            {
                return boolean[].class;
            }
            if (clazz == byte.class)
            {
                return byte[].class;
            }
            if (clazz == short.class)
            {
                return short[].class;
            }
            if (clazz == char.class)
            {
                return char[].class;
            }
            if (clazz == int.class)
            {
                return int[].class;
            }
            if (clazz == long.class)
            {
                return long[].class;
            }
            if (clazz == float.class)
            {
                return float[].class;
            }
            if (clazz == double.class)
            {
                return double[].class;
            }
        }
        if (clazz.isArray())
        {
            return getCanonicalClass("[" + clazz.getName());
        }
        return getCanonicalClass("[L" + clazz.getName() + ";");
    }

    /**
     * Return class for given name or throw exception.
     *
     * @param canonicalName name of class to find.
     *
     * @return class for given name.
     *
     * @throws IllegalArgumentException if there is no class with given name.
     */
    public static Class<?> getCanonicalClass(final String canonicalName) throws IllegalArgumentException
    {
        try
        {
            return Class.forName(canonicalName);
        } catch (final ClassNotFoundException e)
        {
            throw new IllegalArgumentException("Cannot find " + canonicalName, e);
        }
    }
}


text:
package org.yuanheng.cookcc.exception;

import java.text.MessageFormat;

/**
 * @author Heng Yuan
 * @version $Id$
 */
public class UnknownNameException extends InvalidRegExException
{
	public static MessageFormat ERROR_MSG = new MessageFormat ("unknown name: {0}");

	public UnknownNameException (int lineNumber, String name, String input)
	{
		super (lineNumber, ERROR_MSG.format (new Object[]{name}), input);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.onosproject.net.sensorflow;

import com.google.common.base.MoreObjects;
import org.onosproject.net.flow.instructions.Instruction;

/**
 * Created by aca on 9/24/15.
 */
public class SensorFlowSetPacketValueConstInstruction implements SensorFlowInstruction {
    private int packetPos;
    private int val;

    public SensorFlowSetPacketValueConstInstruction(int packetPos, int val) {
        this.packetPos = packetPos;
        this.val = val;
    }

    public int packetPosition() {
        return packetPos;
    }

    public int value() {
        return val;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(SensorFlowSetPacketValueConstInstruction.class)
                .add("position", packetPos)
                .add("value", val)
                .toString();
    }

    @Override
    public Type getSensorFlowInstructionType() {
        return Type.SET_PKT_VAL_CONST;
    }

    @Override
    public boolean multimatch() {
        return false;
    }

    @Override
    public Instruction.Type type() {
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SensorFlowSetPacketValueConstInstruction)) {
            return false;
        }

        SensorFlowSetPacketValueConstInstruction that = (SensorFlowSetPacketValueConstInstruction) o;

        if (packetPos != that.packetPos) {
            return false;
        }
        return val == that.val;

    }

    @Override
    public int hashCode() {
        int result = packetPos;
        result = 31 * result + val;
        return result;
    }
}


text:
package com.cinchapi.concourse.server.plugin.data;

import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Set;

import org.junit.Assert;
import org.junit.Test;

import com.cinchapi.concourse.server.plugin.io.PluginSerializer;
import com.cinchapi.concourse.thrift.ComplexTObject;
import com.cinchapi.concourse.time.Time;
import com.cinchapi.concourse.util.Convert;
import com.cinchapi.concourse.util.Numbers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;

/**
 * Unit tests for
 * {@link com.cinchapi.concourse.server.plugin.data.ObjectResultDataset}
 *
 * @author Jeff Nelson
 */
public class ObjectResultDatasetTest {

    @Test
    public void testReproNPE() {
        ObjectResultDataset dataset = new ObjectResultDataset(
                new TObjectResultDataset());
        dataset.insert(0L, "key", true);
        Assert.assertFalse(dataset.get(0L).isEmpty());
        Assert.assertFalse(dataset.get(0L, "key").isEmpty());
    }

    @Test
    public void testEntrySetNotEmpty() {
        TObjectResultDataset dataset = new TObjectResultDataset();
        dataset.insert(1L, "age", Convert.javaToThrift(100));
        ObjectResultDataset dataset2 = new ObjectResultDataset(dataset);
        Assert.assertFalse(dataset2.entrySet().isEmpty());
    }

    @Test
    public void testConvertToComplexTObject() {
        TObjectResultDataset dataset = new TObjectResultDataset();
        dataset.insert(1L, "age", Convert.javaToThrift(100));
        ObjectResultDataset expected = new ObjectResultDataset(dataset);
        ComplexTObject complex = ComplexTObject.fromJavaObject(expected);
        Map<Long, Map<String, Object>> actual = complex.getJavaObject();
        expected.forEach((key, value) -> {
            Assert.assertTrue(actual.containsKey(key));
            Assert.assertTrue(actual.containsValue(value));
        });
    }

    @Test
    public void testSerialization() {
        ObjectResultDataset dataset = new ObjectResultDataset(
                new TObjectResultDataset());
        dataset.insert(1L, "name", "Jeff Nelson");
        PluginSerializer serializer = new PluginSerializer();
        ByteBuffer bytes = serializer.serialize(dataset);
        ComplexTObject complex = ComplexTObject.fromJavaObject(bytes);
        ByteBuffer bytes2 = complex.getJavaObject();
        Object obj = serializer.deserialize(bytes2);
        Assert.assertEquals(dataset, obj);
    }

    @Test
    public void testGetKeyRecordIterator() {
        ObjectResultDataset dataset = new ObjectResultDataset(
                new TObjectResultDataset());
        dataset.insert(1L, "name", "Jeff Nelson");
        Set<Object> set = dataset.get(1L, "name");
        for (Object obj : set) {
            Assert.assertNotNull(obj);
        }
    }

    @Test
    public void testInvertedEntrySetWhenNoData() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        Map<String, Map<Object, Set<Long>>> inverted = dataset.invert();
        Assert.assertNotNull(inverted.get("foo").entrySet().iterator());
    }

    @Test
    public void testGetEntityGetAttributeIteratorNoNpe() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "name", "Jeff Nelson");
        Assert.assertNotNull(dataset.get(1L).get("name").iterator().next());
    }

    @Test
    public void testInvertedAttributeKeyDeletedIfEmpty() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "name", "Jeff Nelson");
        dataset.remove(1L);
        Assert.assertFalse(dataset.invert().containsKey("name"));
    }

    @Test
    public void testInvertedAttributeValueKeyDeletedIfEmpty() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "name", "Jeff Nelson");
        dataset.insert(2L, "name", "Jeff Nelson");
        dataset.remove(1L);
        Assert.assertTrue(dataset.invert().containsKey("name"));
        Assert.assertFalse(
                dataset.invert().get("name").get("Jeff Nelson").contains(1L));
        Assert.assertTrue(
                dataset.invert().get("name").get("Jeff Nelson").contains(2L));
    }

    @Test
    public void testCacheDeletedAfterDeletingEntity() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "name", "Jeff Nelson");
        dataset.insert(2L, "name", "Jeff Nelson");
        dataset.remove(1L);
        dataset.forEach((record, data) -> {
            Assert.assertNotEquals(Long.valueOf(1), record);
        });
    }

    @Test
    public void testRemoveConcurrentModificationExceptionRepro() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "name", "Jeff Nelson");
        dataset.insert(1L, "age", 29);
        dataset.insert(1L, "enabled", true);
        dataset.remove(1L);
    }

    @Test
    public void testRecordAttributeIsEmpty() {
        ObjectResultDataset dataset = new ObjectResultDataset();
        dataset.insert(1L, "age", 23);
        Assert.assertTrue(dataset.get(1L, "name").isEmpty());
    }

    @Test
    public void testDispersion() {
        ObjectResultDataset a = new ObjectResultDataset();
        Map<String, Integer> names = Maps.newHashMap();
        names.put("Jeff Nelson", 2);
        names.put("John Doe", 4);
        names.put("Jane Doe", 6);
        names.put("Jonathan Barronville", 8);
        names.put("Lilian Brown", 10);
        names.put("Kylie Jenner", 12);
        names.put("Adrian Brown", 14);
        Map<Integer, Integer> ages = Maps.newHashMap();
        ages.put(20, 1);
        ages.put(30, 1);
        ages.put(31, 2);
        ages.put(32, 2);
        ages.put(33, 1);
        ages.put(40, 1);
        ages.put(41, 1);
        names.forEach((name, count) -> {
            for (int i = 0; i < count; ++i) {
                a.insert(Time.now(), "name", name);
            }
        });
        ages.forEach((age, count) -> {
            for (int i = 0; i < count; ++i) {
                a.insert(Time.now(), "age", age);
            }
        });
        Assert.assertTrue(((TrackingMultimap<Object, Long>) a.invert("name"))
                .spread() > ((TrackingMultimap<Object, Long>) a.invert("age"))
                        .spread());
    }

    @Test
    public void testAttributeDistinctiveness() {
        ObjectResultDataset a = new ObjectResultDataset();
        a.insert(1L, "name", "Jeff Nelson");
        Assert.assertFalse(Numbers.areEqual(0,
                ((TrackingMultimap<Object, Long>) a.invert("name"))
                        .distinctiveness()));
    }

    @Test
    public void testGetRow() {
        ObjectResultDataset a = new ObjectResultDataset();
        a.insert(1L, "name", "Jeff Nelson");
        Assert.assertNotNull(a.get(1L));
    }

    @Test
    public void testInvertedPutAll() {
        ObjectResultDataset a = new ObjectResultDataset();
        a.insert(1L, "name", "Jeff Nelson");
        Map<String, Map<Object, Set<Long>>> data = Maps.newLinkedHashMap();
        data.put("age", ImmutableMap.of(100, ImmutableSet.of(1L)));
        a.invert().putAll(data);
        Assert.assertTrue(a.invert().keySet().contains("age"));
    }

}


text:
package org.sudoku.conf;

public enum SlaveStatus {

    READY_TO_SERVE, //after slave starts
    SERVE, //slave resolves square cells
    IDLE, //slave needs data to resolve next step
    DONE; //square is resolved

}


text:
from __future__ import print_function, division
import numpy as np
from ctypes import c_int, sizeof

#
#
#
class openmx_mat_c():

  def __init__(self, natoms, Total_NumOrbs, FNAN, natn):
    """
      Bookkeeper for the OpenMX matrices (costom sparse format from OpenMX (and Fireball?))
      natoms : number of atoms in the unit cell
      Total_NumOrbs : array of size (natoms+1) in which we store number of atomic orbitals per each atom. The array is one-based?
      FNAN : array of size (natoms+1). the number of first nearest neighbouring atoms per atom. The array is one-based ?
      natn : array of size (natoms+1,max(FNAN)+1) grobal index of neighboring atoms of an atom ct_AN
    """
    assert natoms>0
    self.natoms = natoms
    assert len(Total_NumOrbs)==natoms+1
    self.Total_NumOrbs = Total_NumOrbs
    self.Total_NumOrbs_mx = max(Total_NumOrbs)
    assert len(FNAN)==natoms+1
    self.FNAN = FNAN
    self.FNAN_mx = max(FNAN)
    assert natn.shape==(natoms+1, max(FNAN)+1)
    self.natn = natn

  def get_dims(self):
    return [self.natoms+1, self.FNAN_mx+1, self.Total_NumOrbs_mx, self.Total_NumOrbs_mx]

  def fromfile(self, f, out=None, dtype=np.float):
    """ Read from an open file f """
    if out is None:
      res = np.zeros((self.natoms+1, self.FNAN_mx+1, self.Total_NumOrbs_mx, self.Total_NumOrbs_mx), dtype=dtype)
    else :
      res = out

    for ct_AN in range(1,self.natoms+1):
      for h_AN in range(0,self.FNAN[ct_AN]+1):
        for i in range(self.Total_NumOrbs[ct_AN]):
          c = self.Total_NumOrbs[self.natn[ct_AN,h_AN]]
          res[ct_AN,h_AN,i,0:c] = np.fromfile(f, count=c)

    return res


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class energy.usef.dso.workflow.dto.ConnectionCapacityLimitationPeriodDto (usef-root-pom 1.3.6 API)</title>
<meta name="date" content="2016-09-29">
<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

Prev

Next

Frames

No Frames

All Classes

Uses of Class
energy.usef.dso.workflow.dto.ConnectionCapacityLimitationPeriodDto

Packages that use ConnectionCapacityLimitationPeriodDto

Package
Description

energy.usef.dso.workflow.transformer

Transformer classes of the Distribution System Operator.

Uses of ConnectionCapacityLimitationPeriodDto in energy.usef.dso.workflow.transformer

Methods in energy.usef.dso.workflow.transformer with parameters of type ConnectionCapacityLimitationPeriodDto

Modifier and Type
Method and Description

static ConnectionCapacityLimitationPeriod
DsoMeterEventTransformer.transformToModel(ConnectionCapacityLimitationPeriodDto connectionMeterEventPeriodDto)

Transforms ConnectionCapacityLimitationPeriodDto to DB model ConnectionCapacityLimitationPeriod.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
"""
Script entry point
"""

from src.calrissian.atomic_network import AtomicNetwork
from src.calrissian.layers.atomic import Atomic
from src.calrissian.layers.atomic import AtomicInput
from src.calrissian.optimizers.atomic_sgd import AtomicSGD

import numpy as np

def main():

    train_X = np.asarray([[0.2, -0.3]])
    train_Y = np.asarray([[0.0, 1.0, 0.0]])

    net = AtomicNetwork(cost="mse", atomic_input=AtomicInput(2))
    net.append(Atomic(2, 5, activation="sigmoid"))
    net.append(Atomic(5, 3, activation="sigmoid"))

    print(net.predict(train_X))
    print(net.cost(train_X, train_Y))
    print(net.cost_gradient(train_X, train_Y))

    net.fit(train_X, train_Y, AtomicSGD(mini_batch_size=1, n_epochs=10))

if __name__ == "__main__":

    # Ensure same seed
    np.random.seed(100)

    main()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Project 3</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Мой сайт-портфолио">
    <meta name="author" content="Pavel Hmelnov">
    <link rel="canonical" href="https://github.com/hmelnoff/sites/2014/07/16/project-3/">
    <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

	<link rel="stylesheet" href="/libs/bootstrap/bootstrap-grid.min.css">
	<link rel="stylesheet" href="/libs/linea/styles.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.3.0/animate.min.css">
	<link rel="stylesheet" href="/libs/magnific-popup/magnific-popup.css">
	<link rel="stylesheet" href="/css/fonts.css" />
	<link rel="stylesheet" href="/css/main.css" />
	<link rel="stylesheet" href="/css/skins/blue.css" />
	<link rel="stylesheet" href="/css/media.css" />

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

Обо мне

Резюме

Портфолио

Контакты

						logo

					<button class="toggle_mnu">

					</button>

Обо мне

Резюме

Портфолио

Контакты

Павел Хмельнов

WEB-ДИЗАЙНЕР  FRONT-END РАЗРАБОТЧИК

Портфолио

Мои последние работы

Все работы

Сайты

Айдентика

Логотипы

Landing Page, Portfolio

Резюме-портфолио

								Посмтореть

Landing Page, Portfolio

Используется адаптивная сетка Bootstrap, JQuery, Animate.css, Magnific Popup, Parallax, PageScroll2Id, Bootstrap-validate.

									<button title="Close (Esc)" type="button" class="mfp-close">×</button>

Ethanol

Landing Page

								Посмтореть

Ethanol

Используется адаптивная сетка Bootstrap, JQuery, MixitUp. Ссылка на PSD-файл

									<button title="Close (Esc)" type="button" class="mfp-close">×</button>

Flask, Bootstrap, Jquery

Корпоративный сайт

								Посмтореть

Flask, Bootstrap, Jquery

В данной работе используется шаблонизатор для языка программирования Python, Jinja. Представлена работа с api Yandex.Translate и сервис по заказу корпоративных обедов.

									<button title="Close (Esc)" type="button" class="mfp-close">×</button>

Bazinger

Landing Page

								Посмтореть

Bazinger

Проект собирается с помощью менеджера задач Gulp, испольщуется адаптивная сетка Bootstrap. Ссылка на PSD-файл

									<button title="Close (Esc)" type="button" class="mfp-close">×</button>

УралТЭП

Корпоративный сайт

								Посмтореть

УралТЭП

Альтернативный вариант сайта ЗАО ПИЦ УралТЭП.  Проект на основе CMS Joomla.

									<button title="Close (Esc)" type="button" class="mfp-close">×</button>

Обо мне

ПОЗНАКОМИМСЯ БЛИЖЕ

Фото

ПЕРСОНАЛЬНАЯ ИНФОРМАЦИЯ

Павел Хмельнов

Профессиональное создание сайтов: разрботка дизайна, HTML верстка, посадка на CMS WordPress

День рождения: 25 августа 1986 года

Номер телефона: +7 952 732 40 46

E-mail: pavelhmelnov@gmail.com

Веб-сайт: vk.com/hmelnoff

Резюме

Мои знания и достижения

Работа

04.2009 - ...

ЗАО "Проектно-инженерный центр УралТЭП"Инженер 1 категории

— Осуществление поддержки, обучение и консультирования сотрудников компании по вопросам, касающимся компьютеров и программного обеспечения.

 — оперативная помощь сотрудникам по устранению неисправностей, определение, локализация и устранение ошибок.

 — Выполнение служебных заданий, поручений и указаний непосредственного руководителя.

 — выполнение работ по установке и настройке программ и программных средств, утвержденных политикой компании.

 — принятие и фиксирование в HelpDesk системе заявок от пользователей, контролирование процесса их устранения.

 — установка новых рабочих мест и осуществление переноса существующих.

 — ведение учета приема/ выдачи техники, принадлежащей IT департаменту.

 — настройка ПК и КПК, мобильных телефонов на базе IOS, Android, тестирование, выявление и устранение неисправности компьютеров и копировальной техники.

 — осуществление учета расходных материалов для обеспечения бесперебойного функционирования принтеров и копировальной техники.

 — оформление документов (приход/расход) и учет оборудования на складе IT.

 — ведение учета лицензионного ПО.

 — проведение ежегодной инвентаризации IT оборудования.

 — предоставление информации сотрудникам компании по общим вопросам в области IT.

07.2008 - 07.2009

Ренессанс Страхование, Группаспециалист

Ведение базы данных убытков, заведение страховых полисов и убытков в единую информационную базу

01.2008 — 03.2008

"Свердловэнерго" "Западные электрические сети"Техник

прохождение производственной практики, проведение тепловизионного контроля электрооборудования.

Учеба

2003-2008

СтудентРоссийский государственный профессионально-педагогический университет, Екатеринбург

Институт электроэнергетики и информатики, Электроэнергетика, электротехника и электротехнологии

Контакты

Оставьте ваше сообщение

Адрес

г. Екатеринбург, ул. Стахановская 132

Телефон

+7 952 732 40 46

Веб-сайт

github.com/hmelnoff

					<form action="http://formspree.io/pavelhmelnov@gmail.com" method="post" class="main_form" target="_blank">

							*Ваше имя:
							<input type="text" name="Name" placeholder="Ваше имя" required data-validation-required-message="Вы не ввели имя">

							*Ваш E-mail:
							<input type="email" name="E-mail" placeholder="Ваш E-mail" required data-validation-required-message="Вы не ввели E-mail" data-validation-email-message="Некорректный E-mail">

							*Ваше сообщение:
							<textarea name="Message" placeholder="Ваше сообщение" required data-validation-required-message="Вы не ввели сообщение"></textarea>

						<button>Отправить</button>
					</form>

				© 2016 Павел Хмельнов


text:
var getTag = require('./_getTag'),
    isArguments = require('./isArguments'),
    isArray = require('./isArray'),
    isArrayLike = require('./isArrayLike'),
    isBuffer = require('./isBuffer'),
    isFunction = require('./isFunction'),
    isObjectLike = require('./isObjectLike'),
    isPrototype = require('./_isPrototype'),
    isString = require('./isString'),
    nativeKeys = require('./_nativeKeys');

/** `Object#toString` result references. */
var mapTag = '[object Map]',
    setTag = '[object Set]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');

/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty(null);
 * // => true
 *
 * _.isEmpty(true);
 * // => true
 *
 * _.isEmpty(1);
 * // => true
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({ 'a': 1 });
 * // => false
 */
function isEmpty(value) {
  if (isArrayLike(value) &&
      (isArray(value) || isString(value) || isFunction(value.splice) ||
        isArguments(value) || isBuffer(value))) {
    return !value.length;
  }
  if (isObjectLike(value)) {
    var tag = getTag(value);
    if (tag == mapTag || tag == setTag) {
      return !value.size;
    }
  }
  var isProto = isPrototype(value);
  for (var key in value) {
    if (hasOwnProperty.call(value, key) &&
        !(isProto && key == 'constructor')) {
      return false;
    }
  }
  return !(nonEnumShadows && nativeKeys(value).length);
}

module.exports = isEmpty;


text:
using Microsoft.Xaml.Interactivity;
using Template10.Common;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Markup;

namespace Template10.Behaviors
{
    /// <summary>
    /// The Throttled Event Behavior attaches to a target's event, and executes child actions at a rate no faster than the throttle set (in milliseconds).
    /// </summary>
    [ContentProperty(Name = "Actions")]
    public sealed class ThrottledEventTriggerBehavior : EventTriggerBehaviorBase
    {
        private readonly EventThrottleHelper throttleHelper;

        public ThrottledEventTriggerBehavior()
        {
            throttleHelper = new EventThrottleHelper();
            throttleHelper.ThrottledEvent += ThrottleHelperOnThrottledEvent;
        }

        private void ThrottleHelperOnThrottledEvent(object sender, object eventArgs)
        {
            Interaction.ExecuteActions(this.ResolvedSource, this.Actions, eventArgs);
        }

        /// <summary>
        /// Throttle period (in milliseconds).
        /// </summary>
        public int Throttle
        {
            get { return (int) GetValue(ThrottleProperty); }
            set { SetValue(ThrottleProperty, value); }
        }

        /// <summary>
        /// Throttle period (in milliseconds)
        /// </summary>
        public static readonly DependencyProperty ThrottleProperty = DependencyProperty.Register(nameof(Throttle), typeof (int), typeof (ThrottledEventTriggerBehavior), new PropertyMetadata(1000, ThrottlePropertyChangedCallback));

        private static void ThrottlePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var obj = (ThrottledEventTriggerBehavior)d;
            obj.throttleHelper.Throttle = (int) e.NewValue;
        }

        /// <summary>
        /// Reset throttle timer after each event.
        /// </summary>
        public bool ResetTimer
        {
            get { return (bool) GetValue(ResetTimerProperty); }
            set { SetValue(ResetTimerProperty, value); }
        }

        /// <summary>
        /// Reset throttle timer after each event.
        /// </summary>
        public static readonly DependencyProperty ResetTimerProperty = DependencyProperty.Register(nameof(ResetTimer), typeof (bool), typeof (ThrottledEventTriggerBehavior), new PropertyMetadata(false, ResetTimerPropertyChangedCallback));

        private static void ResetTimerPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var obj = (ThrottledEventTriggerBehavior)d;
            obj.throttleHelper.ResetTimer = (bool)e.NewValue;
        }

        /// <summary>
        /// Actions to be done on event triggering. In default implementation list of actions is executed immediately.
        /// This is a main class extension point if some additional actions should be done on event trigger.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="eventArgs">Event argument.</param>
        protected override void OnEvent(object sender, object eventArgs)
        {
            throttleHelper.DispatchTriggerEvent(eventArgs);
        }
    }
}


text:
package middleware

import (
	"fmt"

	"github.com/Sirupsen/logrus"
	"github.com/drone/drone/remote"
	"github.com/drone/drone/remote/bitbucket"
	"github.com/drone/drone/remote/bitbucketserver"
	"github.com/drone/drone/remote/github"
	"github.com/drone/drone/remote/gitlab"
	"github.com/drone/drone/remote/gogs"
	"github.com/gin-gonic/gin"
	"github.com/urfave/cli"
)

// Remote is a middleware function that initializes the Remote and attaches to
// the context of every http.Request.
func Remote(c *cli.Context) gin.HandlerFunc {
	v, err := setupRemote(c)
	if err != nil {
		logrus.Fatalln(err)
	}
	return func(c *gin.Context) {
		remote.ToContext(c, v)
	}
}

// helper function to setup the remote from the CLI arguments.
func setupRemote(c *cli.Context) (remote.Remote, error) {
	switch {
	case c.Bool("github"):
		return setupGithub(c)
	case c.Bool("gitlab"):
		return setupGitlab(c)
	case c.Bool("bitbucket"):
		return setupBitbucket(c)
	case c.Bool("stash"):
		return setupStash(c)
	case c.Bool("gogs"):
		return setupGogs(c)
	default:
		return nil, fmt.Errorf("version control system not configured")
	}
}

// helper function to setup the Bitbucket remote from the CLI arguments.
func setupBitbucket(c *cli.Context) (remote.Remote, error) {
	return bitbucket.New(
		c.String("bitbucket-client"),
		c.String("bitbucket-secret"),
	), nil
}

// helper function to setup the Gogs remote from the CLI arguments.
func setupGogs(c *cli.Context) (remote.Remote, error) {
	return gogs.New(gogs.Opts{
		URL:         c.String("gogs-server"),
		Username:    c.String("gogs-git-username"),
		Password:    c.String("gogs-git-password"),
		PrivateMode: c.Bool("gogs-private-mode"),
		SkipVerify:  c.Bool("gogs-skip-verify"),
	})
}

// helper function to setup the Stash remote from the CLI arguments.
func setupStash(c *cli.Context) (remote.Remote, error) {
	return bitbucketserver.New(bitbucketserver.Opts{
		URL:               c.String("stash-server"),
		Username:          c.String("stash-git-username"),
		Password:          c.String("stash-git-password"),
		ConsumerKey:       c.String("stash-consumer-key"),
		ConsumerRSA:       c.String("stash-consumer-rsa"),
		ConsumerRSAString: c.String("stash-consumer-rsa-string"),
		SkipVerify:        c.Bool("stash-skip-verify"),
	})
}

// helper function to setup the Gitlab remote from the CLI arguments.
func setupGitlab(c *cli.Context) (remote.Remote, error) {
	return gitlab.New(gitlab.Opts{
		URL:         c.String("gitlab-server"),
		Client:      c.String("gitlab-client"),
		Secret:      c.String("gitlab-secret"),
		Username:    c.String("gitlab-git-username"),
		Password:    c.String("gitlab-git-password"),
		PrivateMode: c.Bool("gitlab-private-mode"),
		SkipVerify:  c.Bool("gitlab-skip-verify"),
	})
}

// helper function to setup the GitHub remote from the CLI arguments.
func setupGithub(c *cli.Context) (remote.Remote, error) {
	return github.New(github.Opts{
		URL:         c.String("github-server"),
		Context:     c.String("github-context"),
		Client:      c.String("github-client"),
		Secret:      c.String("github-secret"),
		Scopes:      c.StringSlice("github-scope"),
		Username:    c.String("github-git-username"),
		Password:    c.String("github-git-password"),
		PrivateMode: c.Bool("github-private-mode"),
		SkipVerify:  c.Bool("github-skip-verify"),
		MergeRef:    c.BoolT("github-merge-ref"),
	})
}


text:
package twins

// IdentityProvider specifies an API for generating unique identifiers.
type IdentityProvider interface {
	// ID generates the unique identifier.
	ID() (string, error)

	// IsValid checks whether string is a valid uuid4.
	IsValid(u4 string) error
}


text:
define(function() {
    return function() {
        //UUIDv4 generator from dojox/uuid
        var HEX_RADIX = 16;

        function _generateRandomEightCharacterHexString(){
            // Make random32bitNumber be a randomly generated floating point number
            // between 0 and (4,294,967,296 - 1), inclusive.
            var random32bitNumber = Math.floor( (Math.random() % 1) * Math.pow(2, 32) );
            var eightCharacterHexString = random32bitNumber.toString(HEX_RADIX);
            while(eightCharacterHexString.length < 8){
                eightCharacterHexString = "0" + eightCharacterHexString;
            }
            return eightCharacterHexString; // for example: "3B12F1DF"
        }

        var hyphen = "-";
        var versionCodeForRandomlyGeneratedUuids = "4"; // 8 == binary2hex("0100")
        var variantCodeForDCEUuids = "8"; // 8 == binary2hex("1000")
        var a = _generateRandomEightCharacterHexString();
        var b = _generateRandomEightCharacterHexString();
        b = b.substring(0, 4) + hyphen + versionCodeForRandomlyGeneratedUuids + b.substring(5, 8);
        var c = _generateRandomEightCharacterHexString();
        c = variantCodeForDCEUuids + c.substring(1, 4) + hyphen + c.substring(4, 8);
        var d = _generateRandomEightCharacterHexString();
        var returnValue = a + hyphen + b + hyphen + c + d;
        returnValue = returnValue.toLowerCase();
        return returnValue; // String
    };
});


text:
import React, { PropTypes } from 'react';

import './styles.sass';
import userImage from '../../assets/images/user.svg';

const BasicInfo = ({data}) => {
  return(

{data.name}

  );
};

BasicInfo.propTypes = {
  data: PropTypes.object.isRequired
};

export default BasicInfo;


text:
class DragEventType(object):

    ENTER = 'ENTER'
    LEAVE = 'LEAVE'
    OVER = 'OVER'
    DROP = 'DROP'

    _values = [ENTER, LEAVE, OVER, DROP]

    @classmethod
    def values(cls):
        return cls._values[:]


text:
'use strict'

const RenderRows = require('./render-rows')
const createRow = RenderRows.createRow
const socket = require('./socket')
const on = require('dom-event')
const classList = require('class-list')
const loop = require('frame-loop')

const searchInput = document.getElementById('search')
const pauseButtonClassList = classList(document.getElementById('pause'))

var column_visibility = { timestamp: '' };
console.log(column_visibility);

const maxInMemory = 10000
var maxInDom = 500
const refreshInterval = 250
const table = document.getElementById('log-table')

const lines = []
const render = RenderRows(table)
var renderLines = []
var currentSearchString = ''

socket.tailf(function(line) {
	if (lines.length >= maxInMemory) {
		lines.shift()
	}
	lines.push(line)

	if (currentSearchString === '' || lineMatchesSearchString(line)) {
		renderLines.push(line)
		if (renderLines.length >= maxInDom) {
			renderLines.shift()
		}
	}
})

scrollToBottom()

function lineMatchesSearchString(line) {
	return line.toLowerCase().indexOf(currentSearchString.toLowerCase()) !== -1
}

function refreshRenderLines() {
	if (currentSearchString) {
		renderLines = lines.filter(lineMatchesSearchString).slice(-maxInDom)
	} else {
		renderLines = lines.slice(-maxInDom)
	}
}

const engine = loop({
	fps: 10,
	correction: 0
}, function() {
	const bottom = atBottom()

	render(renderLines, column_visibility)

	if (bottom) {
		scrollToBottom()
	}
})

engine.run()

engine.on('fps', fps => console.log('actual fps:', fps))

onChange('max-on-screen', function(newValue) {
	const intValue = parseInt(newValue)

	if (intValue > 0) {
		maxInDom = intValue
		refreshRenderLines()
	}
})

onChange('search', newValue => {
	currentSearchString = newValue
	console.log('currentSearchString is', currentSearchString)
	refreshRenderLines()
})

onClick('timestamp', function() {
  classList(document.getElementById('timestamp')).toggle('active')
  classList(document.getElementById('timestamp_column')).toggle('hidden')
  if ( column_visibility.timestamp == 'hidden' ) {
    column_visibility.timestamp = ''
  } else {
    column_visibility.timestamp = 'hidden'
  }
  refreshRenderLines()
})

onClick('facility', function() {
  classList(document.getElementById('facility')).toggle('active')
  classList(document.getElementById('facility_column')).toggle('hidden')
  if ( column_visibility.facility == 'hidden' ) {
    column_visibility.facility = ''
  } else {
    column_visibility.facility = 'hidden'
  }
  refreshRenderLines()
})

onClick('level', function() {
  classList(document.getElementById('level')).toggle('active')
  classList(document.getElementById('level_column')).toggle('hidden')
  if ( column_visibility.level == 'hidden' ) {
    column_visibility.level = ''
  } else {
    column_visibility.level = 'hidden'
  }
  refreshRenderLines()
})

onClick('process', function() {
  classList(document.getElementById('process')).toggle('active')
  classList(document.getElementById('process_column')).toggle('hidden')
  if ( column_visibility.process == 'hidden' ) {
    column_visibility.process = ''
  } else {
    column_visibility.process = 'hidden'
  }
  refreshRenderLines()
})

onClick('pid', function() {
  classList(document.getElementById('pid')).toggle('active')
  classList(document.getElementById('pid_column')).toggle('hidden')
  if ( column_visibility.pid == 'hidden' ) {
    column_visibility.pid = ''
  } else {
    column_visibility.pid = 'hidden'
  }
  refreshRenderLines()
})

onClick('ip', function() {
  classList(document.getElementById('ip')).toggle('active')
  classList(document.getElementById('ip_column')).toggle('hidden')
  if ( column_visibility.ip == 'hidden' ) {
    column_visibility.ip = ''
  } else {
    column_visibility.ip = 'hidden'
  }
  refreshRenderLines()
})

onClick('hostname', function() {
  classList(document.getElementById('hostname')).toggle('active')
  classList(document.getElementById('hostname_column')).toggle('hidden')
  if ( column_visibility.hostname == 'hidden' ) {
    column_visibility.hostname = ''
  } else {
    column_visibility.hostname = 'hidden'
  }
  refreshRenderLines()
})

onClick('pause', function() {
	engine.toggle()
	pauseButtonClassList.toggle('active')
})

function onClick(id, cb) {
	const e = document.getElementById(id)
	on(e, 'click', cb)
}

function onChange(id, cb) {
	const e = document.getElementById(id)
	on(e, 'keyup', function(event) {
		cb(e.value)
	})
}

function scrollToBottom() {
	const bottom = document.body.scrollHeight - window.innerHeight
	window.scrollTo(0, bottom)
}

function atBottom() {
	const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop
	const bottom = document.body.scrollHeight - window.innerHeight
	return bottom - scrollPosition < 50
}


text:
class AddLastModifiedToTrip < ActiveRecord::Migration
  def change
  	add_column :trips, :last_modified, :date
  end
end


text:
package com.mossle.bpm.cmd;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.mossle.bpm.graph.ActivitiHistoryGraphBuilder;
import com.mossle.bpm.graph.Edge;
import com.mossle.bpm.graph.Graph;
import com.mossle.bpm.graph.Node;

import com.mossle.core.spring.ApplicationContextHelper;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.HistoricActivityInstanceQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.cmd.GetDeploymentProcessDefinitionCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;

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

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 退回任务.
 */
public class RollbackTaskCmd implements Command<Integer> {
    private static Logger logger = LoggerFactory
            .getLogger(RollbackTaskCmd.class);
    private String taskId;

    /**
     * 这个taskId是运行阶段task的id.
     */
    public RollbackTaskCmd(String taskId) {
        this.taskId = taskId;
    }

    /**
     * 退回流程.
     *
     * @return 0-退回成功 1-流程结束 2-下一结点已经通过,不能退回
     */
    public Integer execute(CommandContext commandContext) {
        // 尝试查找最近的上游userTask
        String historyTaskId = this.findNearestUserTask();

        if (historyTaskId == null) {
            logger.info("cannot rollback {}", taskId);

            return 2;
        }

        // 先找到历史任务
        HistoricTaskInstanceEntity historicTaskInstanceEntity = Context
                .getCommandContext().getHistoricTaskInstanceEntityManager()
                .findHistoricTaskInstanceById(historyTaskId);

        // 再反向查找历史任务对应的历史节点
        HistoricActivityInstanceEntity historicActivityInstanceEntity = getHistoricActivityInstanceEntity(historyTaskId);

        Graph graph = new ActivitiHistoryGraphBuilder(
                historicTaskInstanceEntity.getProcessInstanceId()).build();

        Node node = graph.findById(historicActivityInstanceEntity.getId());

        if (!checkCouldRollback(node)) {
            logger.info("cannot rollback {}", taskId);

            return 2;
        }

        if (this.isSameBranch(historicTaskInstanceEntity)) {
            // 如果退回的目标节点的executionId与当前task的executionId一样,说明是同一个分支
            // 只删除当前分支的task
            this.deleteActiveTask();
        } else {
            // 否则认为是从分支跳回主干
            // 删除所有活动中的task
            this.deleteActiveTasks(historicTaskInstanceEntity
                    .getProcessInstanceId());

            // 获得期望退回的节点后面的所有节点历史
            List<String> historyNodeIds = new ArrayList<String>();
            collectNodes(node, historyNodeIds);
            this.deleteHistoryActivities(historyNodeIds);
        }

        // 恢复期望退回的任务和历史
        this.processHistoryTask(historicTaskInstanceEntity,
                historicActivityInstanceEntity);

        logger.info("activiti is rollback {}",
                historicTaskInstanceEntity.getName());

        return 0;
    }

    public boolean isSameBranch(
            HistoricTaskInstanceEntity historicTaskInstanceEntity) {
        TaskEntity taskEntity = Context.getCommandContext()
                .getTaskEntityManager().findTaskById(taskId);

        return taskEntity.getExecutionId().equals(
                historicTaskInstanceEntity.getExecutionId());
    }

    public String findNearestUserTask() {
        TaskEntity taskEntity = Context.getCommandContext()
                .getTaskEntityManager().findTaskById(taskId);

        if (taskEntity == null) {
            logger.debug("cannot find task : {}", taskId);

            return null;
        }

        Graph graph = new ActivitiHistoryGraphBuilder(
                taskEntity.getProcessInstanceId()).build();
        JdbcTemplate jdbcTemplate = ApplicationContextHelper
                .getBean(JdbcTemplate.class);
        String historicActivityInstanceId = jdbcTemplate.queryForObject(
                "select id_ from ACT_HI_ACTINST where task_id_=?",
                String.class, taskId);
        Node node = graph.findById(historicActivityInstanceId);

        String previousHistoricActivityInstanceId = this.findIncomingNode(
                graph, node);

        if (previousHistoricActivityInstanceId == null) {
            logger.debug(
                    "cannot find previous historic activity instance : {}",
                    taskEntity);

            return null;
        }

        return jdbcTemplate.queryForObject(
                "select task_id_ from ACT_HI_ACTINST where id_=?",
                String.class, previousHistoricActivityInstanceId);
    }

    public String findIncomingNode(Graph graph, Node node) {
        for (Edge edge : graph.getEdges()) {
            Node src = edge.getSrc();
            Node dest = edge.getDest();
            String srcType = src.getType();

            if (!dest.getId().equals(node.getId())) {
                continue;
            }

            if ("userTask".equals(srcType)) {
                boolean isSkip = isSkipActivity(src.getId());

                if (isSkip) {
                    return this.findIncomingNode(graph, src);
                } else {
                    return src.getId();
                }
            } else if (srcType.endsWith("Gateway")) {
                return this.findIncomingNode(graph, src);
            } else {
                logger.info("cannot rollback, previous node is not userTask : "
                        + src.getId() + " " + srcType + "(" + src.getName()
                        + ")");

                return null;
            }
        }

        logger.info("cannot rollback, this : " + node.getId() + " "
                + node.getType() + "(" + node.getName() + ")");

        return null;
    }

    public HistoricActivityInstanceEntity getHistoricActivityInstanceEntity(
            String historyTaskId) {
        logger.info("historyTaskId : {}", historyTaskId);

        JdbcTemplate jdbcTemplate = ApplicationContextHelper
                .getBean(JdbcTemplate.class);
        String historicActivityInstanceId = jdbcTemplate.queryForObject(
                "select id_ from ACT_HI_ACTINST where task_id_=?",
                String.class, historyTaskId);
        logger.info("historicActivityInstanceId : {}",
                historicActivityInstanceId);

        HistoricActivityInstanceQueryImpl historicActivityInstanceQueryImpl = new HistoricActivityInstanceQueryImpl();
        historicActivityInstanceQueryImpl
                .activityInstanceId(historicActivityInstanceId);

        HistoricActivityInstanceEntity historicActivityInstanceEntity = (HistoricActivityInstanceEntity) Context
                .getCommandContext()
                .getHistoricActivityInstanceEntityManager()
                .findHistoricActivityInstancesByQueryCriteria(
                        historicActivityInstanceQueryImpl, new Page(0, 1))
                .get(0);

        return historicActivityInstanceEntity;
    }

    public boolean checkCouldRollback(Node node) {
        // TODO: 如果是catchEvent,也应该可以退回,到时候再说
        for (Edge edge : node.getEdges()) {
            Node dest = edge.getDest();
            String type = dest.getType();

            if ("userTask".equals(type)) {
                if (!dest.isActive()) {
                    boolean isSkip = isSkipActivity(dest.getId());

                    if (isSkip) {
                        return checkCouldRollback(dest);
                    } else {
                        logger.info("cannot rollback, " + type + "("
                                + dest.getName() + ") is complete.");

                        return false;
                    }
                }
            } else if (type.endsWith("Gateway")) {
                return checkCouldRollback(dest);
            } else {
                logger.info("cannot rollback, " + type + "(" + dest.getName()
                        + ") is complete.");

                return false;
            }
        }

        return true;
    }

    public void deleteActiveTasks(String processInstanceId) {
        Context.getCommandContext().getTaskEntityManager()
                .deleteTasksByProcessInstanceId(processInstanceId, "退回", false);

        JdbcTemplate jdbcTemplate = ApplicationContextHelper
                .getBean(JdbcTemplate.class);
        List<Map<String, Object>> list = jdbcTemplate
                .queryForList(
                        "select * from ACT_HI_ACTINST where proc_inst_id_=? and end_time_ is null",
                        processInstanceId);
        Date now = new Date();

        for (Map<String, Object> map : list) {
            Date startTime = (Date) map.get("start_time_");
            long duration = now.getTime() - startTime.getTime();
            jdbcTemplate
                    .update("update ACT_HI_ACTINST set end_time_=?,duration_=? where id_=?",
                            now, duration, map.get("id_"));
        }
    }

    public void collectNodes(Node node, List<String> historyNodeIds) {
        logger.info("node : {}, {}, {}", node.getId(), node.getType(),
                node.getName());

        for (Edge edge : node.getEdges()) {
            logger.info("edge : {}", edge.getName());

            Node dest = edge.getDest();
            historyNodeIds.add(dest.getId());
            collectNodes(dest, historyNodeIds);
        }
    }

    public void deleteHistoryActivities(List<String> historyNodeIds) {
        /*
         * JdbcTemplate jdbcTemplate = ApplicationContextHelper .getBean(JdbcTemplate.class);
         * logger.info("historyNodeIds : {}", historyNodeIds);
         *
         * for (String id : historyNodeIds) { jdbcTemplate.update("delete from ACT_HI_ACTINST where id_=?", id); }
         */
    }

    public void processHistoryTask(
            HistoricTaskInstanceEntity historicTaskInstanceEntity,
            HistoricActivityInstanceEntity historicActivityInstanceEntity) {
        /*
         * historicTaskInstanceEntity.setEndTime(null); historicTaskInstanceEntity.setDurationInMillis(null);
         * historicActivityInstanceEntity.setEndTime(null); historicActivityInstanceEntity.setDurationInMillis(null);
         */

        // 创建新任务
        TaskEntity task = TaskEntity.create(new Date());
        task.setProcessDefinitionId(historicTaskInstanceEntity
                .getProcessDefinitionId());
        // task.setId(historicTaskInstanceEntity.getId());
        task.setAssigneeWithoutCascade(historicTaskInstanceEntity.getAssignee());
        task.setParentTaskIdWithoutCascade(historicTaskInstanceEntity
                .getParentTaskId());
        task.setNameWithoutCascade(historicTaskInstanceEntity.getName());
        task.setTaskDefinitionKey(historicTaskInstanceEntity
                .getTaskDefinitionKey());
        task.setExecutionId(historicTaskInstanceEntity.getExecutionId());
        task.setPriority(historicTaskInstanceEntity.getPriority());
        task.setProcessInstanceId(historicTaskInstanceEntity
                .getProcessInstanceId());
        task.setExecutionId(historicTaskInstanceEntity.getExecutionId());
        task.setDescriptionWithoutCascade(historicTaskInstanceEntity
                .getDescription());

        Context.getCommandContext().getTaskEntityManager().insert(task);

        // 把流程指向任务对应的节点
        ExecutionEntity executionEntity = Context.getCommandContext()
                .getExecutionEntityManager()
                .findExecutionById(historicTaskInstanceEntity.getExecutionId());
        executionEntity
                .setActivity(getActivity(historicActivityInstanceEntity));

        // 创建HistoricActivityInstance
        Context.getCommandContext().getHistoryManager()
                .recordActivityStart(executionEntity);

        // 创建HistoricTaskInstance
        Context.getCommandContext().getHistoryManager()
                .recordTaskCreated(task, executionEntity);
        Context.getCommandContext().getHistoryManager().recordTaskId(task);
    }

    public ActivityImpl getActivity(
            HistoricActivityInstanceEntity historicActivityInstanceEntity) {
        ProcessDefinitionEntity processDefinitionEntity = new GetDeploymentProcessDefinitionCmd(
                historicActivityInstanceEntity.getProcessDefinitionId())
                .execute(Context.getCommandContext());

        return processDefinitionEntity
                .findActivity(historicActivityInstanceEntity.getActivityId());
    }

    /**
     * 删除未完成任务.
     */
    public void deleteActiveTask() {
        TaskEntity taskEntity = Context.getCommandContext()
                .getTaskEntityManager().findTaskById(taskId);
        Context.getCommandContext().getTaskEntityManager()
                .deleteTask(taskEntity, "回退", false);

        JdbcTemplate jdbcTemplate = ApplicationContextHelper
                .getBean(JdbcTemplate.class);
        List<Map<String, Object>> list = jdbcTemplate
                .queryForList(
                        "select * from ACT_HI_ACTINST where task_id_=? and end_time_ is null",
                        taskId);
        Date now = new Date();

        for (Map<String, Object> map : list) {
            Date startTime = (Date) map.get("start_time_");
            long duration = now.getTime() - startTime.getTime();
            jdbcTemplate
                    .update("update ACT_HI_ACTINST set end_time_=?,duration_=? where id_=?",
                            now, duration, map.get("id_"));
        }
    }

    public boolean isSkipActivity(String historyActivityId) {
        JdbcTemplate jdbcTemplate = ApplicationContextHelper
                .getBean(JdbcTemplate.class);
        String historyTaskId = jdbcTemplate.queryForObject(
                "select task_id_ from ACT_HI_ACTINST where id_=?",
                String.class, historyActivityId);

        HistoricTaskInstanceEntity historicTaskInstanceEntity = Context
                .getCommandContext().getHistoricTaskInstanceEntityManager()
                .findHistoricTaskInstanceById(historyTaskId);
        String deleteReason = historicTaskInstanceEntity.getDeleteReason();

        return "跳过".equals(deleteReason);
    }
}


text:
package metropolia.minhtn.chatapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.WebSocket;

import org.json.JSONException;
import org.json.JSONObject;

import metropolia.minhtn.chatapplication.constants.ApiUrl;
import metropolia.minhtn.chatapplication.models.Message;
import metropolia.minhtn.chatapplication.models.Messages;
import metropolia.minhtn.chatapplication.service.MessageAdapter;
import metropolia.minhtn.chatapplication.service.MessageObserver;

public class PublicChatActivity extends AppCompatActivity implements MessageObserver {

    WebSocket publicSocket;
    EditText txtMsg;
    Button btnSend;
    MessageAdapter adapter;
    Messages messages;
    ListView messageList;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_chat);

        // TODO: CLOSE SOCKET WHEN STOPPED
        txtMsg = (EditText) findViewById(R.id.txtMessage);
        btnSend = (Button) findViewById(R.id.btnSend);
        messageList = (ListView) findViewById(R.id.message_list);

        messages = Messages.getInstance();
        messages.registerObservers(this);
        adapter = new MessageAdapter(this, messages);
        messageList.setAdapter(adapter);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (publicSocket != null) {
                    String msgToSend = txtMsg.getText().toString();
                    if (msgToSend.isEmpty() || msgToSend.isEmpty()) {
                        Toast.makeText(PublicChatActivity.this, "Please input something", Toast.LENGTH_SHORT).show();
                    } else {
                        publicSocket.send(msgToSend);
                    }
                    txtMsg.setText("");
                } else {
                    Toast.makeText(PublicChatActivity.this, "Socket error , please reconnect ?", Toast.LENGTH_SHORT).show();
                }
            }
        });
        if (publicSocket == null) {
            AsyncHttpClient.getDefaultInstance().websocket(ApiUrl.CHAT, null, new AsyncHttpClient.WebSocketConnectCallback() {
                @Override
                public void onCompleted(Exception ex, WebSocket webSocket) {
                    if (ex != null) {
                        ex.printStackTrace();
                        return;
                    }

                    String fullName;
                    if (savedInstanceState == null) {
                        Bundle extras = getIntent().getExtras();
                        if (extras == null) {
                            fullName = null;
                        } else {
                            fullName = extras.getString("fullName");
                        }
                    } else {
                        fullName = (String) savedInstanceState.getSerializable("fullName");
                    }

                    publicSocket = webSocket;
                    Log.d("socketsend", "sent something");

                    webSocket.send(fullName);

                    //webSocket.send("Tri Nguyen");
//                webSocket.send(new byte[10]);
//                publicSocket.send("Hello I am newb from here");

                    // Seems to not working har har har
//                webSocket.setDataCallback(new DataCallback() {
//                    @Override
//                    public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
//                        Log.d("Msg","Something happneded");
//                        bb.recycle();
//                    }
//                });

                    webSocket.setStringCallback(new WebSocket.StringCallback() {
                        @Override
                        public void onStringAvailable(String s) {
                            Log.d("msss", s);
                            try {
                                JSONObject json = new JSONObject(s);
                                String message = "";
                                String[] split = new String[]{};
                                if (json.has("message")) {
                                    message = json.getString("message");
                                    split = message.split(":");
                                    messages.addMessage(new Message(split[0], split[1]));
                                } else if (json.has("users")) {
                                    Log.d("USER", "new usersss");
                                }

                                PublicChatActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        messages.notifyObservers();
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        } else {
//        publicSocket.send("Tri Nguyen : Test Nguyen");
        }
    }

    @Override
    public void refresh() {
        adapter.notifyDataSetChanged();
        messageList.setSelection(messageList.getCount() - 1);
    }

}


text:
Fabricator(:tcc_definition) do
  activity_url { Faker::Internet.url }
  course_id { Fabricate.sequence(:course_id, 1) }
  defense_date { Faker::Date.forward(30) }
  internal_name { Faker::Lorem.sentence(3) }
  moodle_instance_id { Fabricate.sequence(:moodle_instance_id, 1) }
  internal_course_id { Fabricate.sequence(:internal_course_id) }
  minimum_references {  Faker::Number.between(1, 6) } # >=1
  auto_save_minutes {  Faker::Number.between(0, 3) } # 0 a 10
  pdf_link_hours {  Faker::Number.between(1, 4) }# 1 a 72
end

Fabricator(:tcc_definition_with_all, :class_name => :tcc_definition, :from => :tcc_definition) do
  chapter_definitions(count: 3) { |attr, i| Fabricate.build(:chapter_definition_without_tcc, position: i) }
end


text:
#pragma once

#include "kdriveManagedConfig.h"
#include "Connector.h"
#include <kdrive/baos/BaosServerItems.h>

namespace unmanaged
{
typedef kdrive::baos::BaosServerItems BaosServerItems;
}

namespace kdrive
{
namespace baos
{
namespace bindings
{

///
///	BaosServerItems is used to get/set the server item parameters
///	from/on the remote device.
///
/// <remarks>
///	It wraps the GetServerItem and SetServerItem services,
///	which are byte based and provides the appropriate interpretation to
///	convert the parameters to their corresponding values.
/// </remarks>
public ref class BaosServerItems
{
public:

	///
	///	Creates a BaosServerItems object with a specified connector
	///
	BaosServerItems(Connector^ connector)

		: serverItem_(0)
	{
		try
		{
			serverItem_ = new unmanaged::BaosServerItems(connector->getUnmanaged());
		}
		WZ_KDRIVE_CLR_DEFAULT_CATCH
	}

	///
	///	Destroys the BaosServerItems.
	///	Destructor cleans up unmanaged and managed resources.
	///
	~BaosServerItems()
	{
		// call finalizer to release unmanaged resources
		this->!BaosServerItems();
	}

	///
	///	Gets the hardware type.
	///
	/// <remarks>
	///	Can be used to identify the hardware type.

	///	It is mapped to property PID_HARDWARE_TYPE in the device object.

	///	Server item: hardware type, id 1
	/// </remarks>
	array<unsigned char>^ getHardwareType()
	{
		try
		{
			const std::vector<unsigned char>& data = serverItem_->getHardwareType();
			return interop::ArrayCreator::Copy(&data[0], data.size());
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the version of the ObjectServer hardware
	///
	/// <remarks>
	///	Coding Ex.: 0x10 = Version 1.0

	///	Server item: hardware version, id 2
	/// </remarks>
	unsigned char getHardwareVersion()
	{
		try
		{
			return serverItem_->getHardwareVersion();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the version of ObjectServer firmware.
	///
	/// <remarks>
	///	Coding Ex.: 0x10 = Version 1.0

	///	Server item: firmware version, id 3
	/// </remarks>
	unsigned char getFirmwareVersion()
	{
		try
		{
			return serverItem_->getFirmwareVersion();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the KNX manufacturer code of the device.
	///
	/// <remarks>
	///	Not modified by ETS.

	///	It is mapped to property PID_MANUFACTURER_ID in the device object.

	///	Server item: KNX manufacture code DEV, id 4
	/// </remarks>
	unsigned int getManufactureCodeDevice()
	{
		try
		{
			return serverItem_->getManufactureCodeDevice();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the KNX manufacturer code loaded by ETS.
	///
	/// <remarks>
	///	It is mapped to bytes 0 and 1 of property

	///	PID_APPLICATION_VER in the application object.

	///	Server item: KNX manufacture code APP, id 5
	/// </remarks>
	unsigned int getManufactureCodeApp()
	{
		try
		{
			return serverItem_->getManufactureCodeApp();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the id of application loaded by ETS.
	///
	/// <remarks>
	///	It is mapped to bytes 2 and 3 of property

	///	PID_APPLICATION_VER in the application object.

	///	Server item: application id (ETS), id 6
	/// </remarks>
	unsigned int getApplicationId()
	{
		try
		{
			return serverItem_->getApplicationId();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the version of application loaded by ETS.
	///
	/// <remarks>
	///	It is mapped to byte 4 of property PID_APPLICATION_VER
	///	in application object.

	///	Server item: application version (ETS), id 7
	/// </remarks>
	unsigned char getApplicationVersion()
	{
		try
		{
			return serverItem_->getApplicationVersion();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets KNX serial number of device.
	///
	/// <remarks>
	///	It is mapped to property PID_SERIAL_NUMBER in the device object.

	///	Server item: serial number, id 8
	/// </remarks>
	array<unsigned char>^ getSerialNumber()
	{
		try
		{
			const std::vector<unsigned char>& data = serverItem_->getSerialNumber();
			return interop::ArrayCreator::Copy(&data[0], data.size());
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the time since reset in ms.
	///
	/// <remarks>
	///	Server item: time since reset, id 9
	/// </remarks>
	unsigned long getTimeSinceReset()
	{
		try
		{
			return serverItem_->getTimeSinceReset();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Returns true if the KNX bus is connected, otherwise false.
	///
	/// <remarks>
	///	Server item: bus connection state, id 10
	/// </remarks>
	bool isBusConnected()
	{
		try
		{
			return serverItem_->isBusConnected();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the maximal buffer size.
	///
	/// <remarks>
	///	Server item: Maximal buffer size, id 11
	/// </remarks>
	unsigned int getMaxBufferSize()
	{
		try
		{
			return serverItem_->getMaxBufferSize();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the length of the description string.
	///
	/// <remarks>
	///	Server item: Length of description string, id 12
	/// </remarks>
	unsigned int getLengthOfDescriptionString()
	{
		try
		{
			return serverItem_->getLengthOfDescriptionString();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Possible values for server item Baudrate, id 13
	///
	enum class Baudrate
	{
		Unknown = unmanaged::BaosServerItems::Unknown,
		B19200 = unmanaged::BaosServerItems::B19200,
		B115200 = unmanaged::BaosServerItems::B115200
	};

	///
	///	Sets the Baudrate
	///
	/// <remarks>
	///	Values: BaosServerItems::Unknown,
	///	BaosServerItems::BB19200, BaosServerItems::B115200
	/// <seealso cref="Baudrate" />
	/// </remarks>
	void setBaudrate(unsigned char baudrate)
	{
		try
		{
			return serverItem_->setBaudrate(baudrate);
		}
		WZ_KDRIVE_CLR_DEFAULT_CATCH
	}

	///
	///	Gets the baudrate.
	///
	/// <remarks>
	///	Server item: Baudrate, id 13
	/// <seealso cref="Baudrate" />
	/// </remarks>
	unsigned char getBaudrate()
	{
		try
		{
			return serverItem_->getBaudrate();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Sets the current buffer size.
	///
	/// <remarks>
	///	Server item: Current buffer size, id 14
	/// </remarks>
	void setBufferSize(unsigned int bufferSize)
	{
		try
		{
			return serverItem_->setBufferSize(bufferSize);
		}
		WZ_KDRIVE_CLR_DEFAULT_CATCH
	}

	///
	///	Gets the current buffer size.
	///
	/// <remarks>
	///	Server item: Current buffer size, id 14
	/// </remarks>
	unsigned int getBufferSize()
	{
		try
		{
			return serverItem_->getBufferSize();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Possible values for server item ProgrammingMode, id 15
	///
	enum class ProgrammingMode
	{
		NotActive = unmanaged::BaosServerItems::NotActive,
		Active = unmanaged::BaosServerItems::Active
	};

	///
	///	Sets the programming mode
	///
	/// <remarks>
	///	Values: ProgrammingMode::NotActive ProgrammingMode::Active

	///	Server item: Programming mode, id 15
	/// <seealso cref="ProgrammingMode" />
	/// </remarks>
	void setProgrammingMode(unsigned char programmingMode)
	{
		try
		{
			return serverItem_->setProgrammingMode(programmingMode);
		}
		WZ_KDRIVE_CLR_DEFAULT_CATCH
	}

	///
	///	Gets the programming mode.
	///
	/// <remarks>
	///	Server item: Programming mode, id 15
	/// <seealso cref="ProgrammingMode" />
	/// </remarks>
	unsigned char getProgrammingMode()
	{
		try
		{
			return serverItem_->getProgrammingMode();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the version of the ObjectServer binary protocol
	///
	/// <remarks>
	///	Server item: Protocol Version (Binary), id 16
	/// </remarks>
	unsigned char getBinaryProtocolVersion()
	{
		try
		{
			return serverItem_->getBinaryProtocolVersion();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Possible values for server item Indication Sending, id 17
	///
	enum class IndicationSetting
	{
		IndicationSetting_NotActive = unmanaged::BaosServerItems::IndicationSetting_NotActive,
		IndicationSetting_Active = unmanaged::BaosServerItems::IndicationSetting_Active
	};

	///
	///	Sets the indication setting
	///
	/// <remarks>
	///	Values: IndicationSetting::IndicationSetting_NotActive IndicationSetting::IndicationSetting_Active

	///	Server item: Indication Sending, id 17
	/// </remarks>
	void setIndicationSetting(unsigned char indicationSetting)
	{
		try
		{
			return serverItem_->setIndicationSetting(indicationSetting);
		}
		WZ_KDRIVE_CLR_DEFAULT_CATCH
	}

	///
	///	Gets the indication setting
	///
	/// <remarks>
	///	Server item: Indication Sending, id 17
	/// </remarks>
	unsigned char getIndicationSetting()
	{
		try
		{
			return serverItem_->getIndicationSetting();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

	///
	///	Gets the version of the ObjectServer web services protocol
	///
	/// <remarks>
	///	Server item: Protocol Version (WebService), id 18
	/// </remarks>
	unsigned char getWebServicesProtocolVersion()
	{
		try
		{
			return serverItem_->getWebServicesProtocolVersion();
		}
		WZ_KDRIVE_CLR_CATCH_BLACK_HOLE
	}

protected:
	///
	///	Finalizer (non-deterministic destructor)
	///	cleans up unmanaged resources.
	///
	!BaosServerItems()
	{
		try
		{
			if (serverItem_)
			{
				delete serverItem_;
				serverItem_ = 0;
			}
		}
		catch (...)
		{
		}
	}

private:
	unmanaged::BaosServerItems* serverItem_;
};

}
}
} // end namespace kdrive::baos::bindings


text:
mysql_chef_gem 'default' do
  action :install
end

directory node['mysql']['datadir'] do
  owner 'mysql'
  group 'mysql'
  mode '0644'
  action :create
end

directory node['mysql']['logdir'] do
  owner 'mysql'
  group 'mysql'
  mode '0644'
  action :create
end

mysql_service 'default' do
  port node['mysql']['port']
  bind_address '0.0.0.0'
  version node['mysql']['version']
  charset 'utf8'
  data_dir node['mysql']['datadir']
  initial_root_password node['mysql']['root_password']
  action [:create, :start]
end

mysql_connection_info = {
  :host     => '127.0.0.1',
  :username => 'root',
  :password => node['mysql']['root_password']
}

mysql_database 'default' do
  database_name node['database']['name']
  connection mysql_connection_info
  action :create
end

mysql_database_user node['database']['user']['name'] do
  connection mysql_connection_info
  password node['database']['user']['password']
  database_name node['database']['name']
  host '%'
  privileges [:select,:update,:insert]
  require_ssl false
  action :grant
end


text:
package shuaicj.hello.enumtest.op.extend;

/**
 * Another two operations.
 *
 * @author shuaicj 2017/02/05
 */
public enum ExtendedOperation implements Operation {

    EXP("^") {
        @Override
        public double apply(double x, double y) {
            return Math.pow(x, y);
        }
    },

    REMAINDER("%") {
        @Override
        public double apply(double x, double y) {
            return x % y;
        }
    };

    private final String symbol;

    ExtendedOperation(String symbol) {
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return symbol;
    }
}