text:
package com.beetle.framework.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarFile;

public final class ClassUtil {

	public static ClassLoader getClassLoader() {
		ClassLoader classLoader = null;
		try {
			classLoader = Thread.currentThread().getContextClassLoader();
		} catch (Exception t1) {
			try {
				classLoader = ClassUtil.class.getClassLoader();
			} catch (Exception t2) {
				t2.printStackTrace();
			}
		}
		return classLoader;
	}

	public static Class<?> loadClass(final String className) {
		Class<?> clazz;
		try {
			clazz = getClassLoader().loadClass(className);
		} catch (Exception t1) {
			try {
				clazz = Class.forName(className);
			} catch (Exception t2) {
				t2.printStackTrace();
				return null;
			}
		}
		return clazz;
	}

	/**
	 * 找出某个接口或抽象类在某个jar中所有的实现类
	 *
	 * @param clazz
	 * @param jarfile
	 * @return
	 * @throws IOException
	 */
	public static Class<?>[] findImpClass(Class<?> clazz, String jarfile, ClassLoader loader) throws IOException {
		JarFile jarFile = new JarFile(jarfile);
		Enumeration<?> ee = jarFile.entries();
		ArrayList<Class<?>> result = new ArrayList<Class<?>>();
		try {
			while (ee.hasMoreElements()) {
				String entry = ee.nextElement().toString();
				if (entry.endsWith(".class") && entry.indexOf('$') == -1) {
					String clazzName = entry.replace('/', '.');
					clazzName = clazzName.substring(0, clazzName.length() - 6);
					Class<?> testClass = loadclass(loader, clazzName);
					if (testClass == null) {
						continue;
					}
					if (clazz.isInterface()) {
						if (hasInterface(testClass, clazz))
							result.add(testClass);
					} else {
						if (isSubClassOf(testClass, clazz))
							result.add(testClass);

					}
				}
			}
			Class<?>[] cls = (Class[]) result.toArray(new Class[result.size()]);
			return cls;
		} finally {
			result.clear();
			jarFile.close();
		}
	}

	private static Class<?> loadclass(ClassLoader loader, String clazzName) {
		Class<?> testClass = null;
		try {
			testClass = loader.loadClass(clazzName);
		} catch (Error e) {
			// e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return testClass;
	}

	/**
	 * 根据包路径返回其所有的类
	 *
	 * @param packageName
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
		String path = packageName.replace('.', '/');
		Enumeration<URL> resources = ClassUtil.class.getClassLoader().getResources(path);
		List<File> dirs = new ArrayList<File>();
		while (resources.hasMoreElements()) {
			URL resource = resources.nextElement();
			dirs.add(new File(resource.getFile()));
		}
		ArrayList<Class> classes = new ArrayList<Class>();
		for (File directory : dirs) {
			classes.addAll(findClasses(directory, packageName));
		}
		return classes.toArray(new Class[classes.size()]);
	}

	/**
	 * @param jarFileName
	 * @param packageName
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static Class[] findClassesInJar(String jarFileName, String packageName) throws IOException {
		JarFile jarFile = new JarFile(jarFileName);
		ArrayList<Class> result = new ArrayList<Class>();
		try {
			Enumeration ee = jarFile.entries();
			while (ee.hasMoreElements()) {
				String entry = ee.nextElement().toString();
				if (entry.endsWith(".class") && entry.indexOf('$') == -1) {
					String clazzName = entry.replace('/', '.');
					clazzName = clazzName.substring(0, clazzName.length() - 6);
					if (!clazzName.startsWith(packageName)) {
						continue;
					}
					Class testClass = null;
					try {
						testClass = Class.forName(clazzName);
						result.add(testClass);
					} catch (Error e) {

					} catch (ClassNotFoundException e) {
						// e.printStackTrace();
					}
					if (testClass == null) {
						continue;
					}
				}
			}
			Class[] cls = result.toArray(new Class[result.size()]);
			return cls;
		} finally {
			result.clear();
			jarFile.close();
		}
	}

	@SuppressWarnings("rawtypes")
	public static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
		List<Class> classes = new ArrayList<Class>();
		if (!directory.exists()) {
			return classes;
		}
		File[] files = directory.listFiles();
		if (files == null) {
			return classes;
		}
		for (File file : files) {
			if (file.isDirectory()) {
				classes.addAll(findClasses(file, packageName + "." + file.getName()));
			} else if (file.getName().endsWith(".class")) {
				classes.add(
						Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
			}
		}
		return classes;
	}

	/**
	 * 找出某个接口或抽象类在某个jar中所有的实现类
	 *
	 * @param clazz
	 * @param jarfile
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static Class[] findImpClass(Class clazz, String jarfile) throws IOException {
		JarFile jarFile = new JarFile(jarfile);
		ArrayList<Class> result = new ArrayList<Class>();
		try {
			Enumeration ee = jarFile.entries();
			while (ee.hasMoreElements()) {
				String entry = ee.nextElement().toString();
				if (entry.endsWith(".class") && entry.indexOf('$') == -1) {
					String clazzName = entry.replace('/', '.');
					clazzName = clazzName.substring(0, clazzName.length() - 6);
					Class testClass = null;
					try {
						testClass = Class.forName(clazzName);
					} catch (Error e) {

					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					if (testClass == null) {
						continue;
					}
					if (clazz.isInterface()) {
						if (hasInterface(testClass, clazz)) {
							result.add(testClass);
						}
					} else {
						if (isSubClassOf(testClass, clazz)) {
							result.add(testClass);
						}
					}
				}
			}
			Class[] cls = result.toArray(new Class[result.size()]);
			return cls;
		} finally {
			result.clear();
			jarFile.close();
		}
	}

	@SuppressWarnings({ "rawtypes" })
	public static boolean isSubClassOf(Class clazz, Class superClass) {
		return clazz.getSuperclass().equals(superClass);
	}

	public static boolean isRootSubClassOf(Class<?> clazz, Class<?> superClass) {
		// return clazz.getSuperclass().equals(superClass);
		Class<?> c = clazz.getSuperclass();
		if (c.equals(superClass)) {
			return true;
		} else if (c.equals(Object.class)) {
			return false;
		}
		return isRootSubClassOf(c, superClass);
	}

	@SuppressWarnings({ "rawtypes" })
	private static boolean hasInterface(Class clazz, Class theInterface) {
		Class cc[] = clazz.getInterfaces();
		for (int i = 0; i < cc.length; i++) {
			if (cc[i].equals(theInterface)) {
				return true;
			}
		}
		return false;
	}

	public static <T> T newInstance(Class<T> clazz) {
		if (!clazz.isInterface()) {
			try {
				return clazz.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 获取所有属性包括父类
	 *
	 * @param object
	 * @return
	 */
	public static Field[] getAllFields(Class<?> clazz) {
		List<Field> fieldList = new ArrayList<>();
		while (clazz != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = clazz.getSuperclass();
		}
		Field[] fields = new Field[fieldList.size()];
		fieldList.toArray(fields);
		return fields;
	}

	@SuppressWarnings({ "rawtypes" })
	public static Object newInstance(final String className, final Class[] constrParamTypes,
			final Object[] constrParamValues) throws Exception {
		Object instance;
		try {
			instance = loadClass(className).getConstructor(constrParamTypes).newInstance(constrParamValues);

			if (instance == null) {
				return null;
			}
		} catch (InvocationTargetException ite) {
			Throwable t = ite.getTargetException();

			if (t instanceof Exception) {
				throw (Exception) t;
			}

			throw ite;
		} catch (Exception t) {
			throw t;
		}
		return instance;
	}

	@SuppressWarnings({ "rawtypes" })
	public static Object invoke(final Object object, final String methodName, final Class[] methodParamTypes,
			final Object[] methodParamValues) throws Exception {
		Object result = null;
		try {
			result = object.getClass().getMethod(methodName, methodParamTypes).invoke(object, methodParamValues);
		} catch (InvocationTargetException ite) {
			Throwable t = ite.getTargetException();
			if (t instanceof Exception) {
				throw (Exception) t;
			}
			throw ite;
		} catch (Exception t) {
			t.printStackTrace();
		}
		return result;
	}

	public static Method getClassMethod(Class<?> c, String methodName) {
		Method[] ms = c.getMethods();
		for (int i = 0; i < ms.length; i++) {
			Method m = ms[i];
			if (m.getName().equals(methodName)) {
				return m;
			}
		}
		return null;
	}

	public static Method getMethod(Object o, String methodName) {
		if ((methodName == null) || (o == null)) {
			return null;
		}
		Method[] ms = o.getClass().getMethods();
		for (int i = 0; i < ms.length; i++) {
			Method m = ms[i];
			if (m.getName().equals(methodName)) {
				return m;
			}
		}
		return null;
	}

	@SuppressWarnings({ "rawtypes" })
	public static Object invoke(Object obj, String method, Object[] params, Class[] param_types)
			throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
		Method m = obj.getClass().getMethod(method, param_types);
		return m.invoke(obj, params);
	}

	public static Object invokeSimple(Object obj, String methodName, Object[] params)
			throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
		Method m = getClassMethod(obj.getClass(), methodName);
		if (m == null) {
			throw new NoSuchMethodException(obj.getClass().getName() + "." + methodName + ",not found!");
		}
		return m.invoke(obj, params);
	}

	@SuppressWarnings({ "rawtypes" })
	public static Object invoke(Object obj, String method, Object[] params)
			throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
		Method[] all_methods = obj.getClass().getMethods();
		Method method2invoke = null;
		// find method with the same name and matching argument types
		for (int i = 0; i < all_methods.length; i++) {
			Method m = all_methods[i];
			if (m.getName().equals(method)) {
				Class[] pt = m.getParameterTypes();
				boolean match = true;
				int match_loops = pt.length;
				if (match_loops != params.length) {
					continue;
				}
				for (int j = 0; j < match_loops; j++) {
					if (pt[i].isInstance(params[i]) == false) {
						match = false;
						break;
					}
				}
				if (match == true) {
					method2invoke = m;
				}
			}
		}

		// throw an exception if no method to invoke
		if (method2invoke == null) {
			String t = "(";
			for (int i = 0; i < params.length; i++) {
				if (i != 0) {
					t += ", ";
				}
				t += params[i].getClass().getName();
			}
			t += ")";
			throw new NoSuchMethodException(obj.getClass().getName() + "." + method + t);
		}

		// finally, invoke founded method
		return method2invoke.invoke(obj, params);
	}

	@SuppressWarnings({ "rawtypes" })
	public static boolean isContainMethod(Class c, String methodName) {
		boolean bl = false;
		Method ms[] = c.getDeclaredMethods();
		for (int i = 0; i < ms.length; i++) {
			if (ms[i].getName().equals(methodName)) {
				bl = true;
				break;
			}
		}
		return bl;
	}

	@SuppressWarnings({ "rawtypes" })
	public static boolean isThreadSafe(Class c) {
		boolean bl = true;
		Field[] fs = c.getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			int r = fs[i].getModifiers();
			if (r >= 0 && r <= 2) {
				bl = false;
				break;
			}
		}
		return bl;
	}

	public static final String genMethodKey(Method fm) {
		String a = fm.toGenericString();
		int ii = a.indexOf('(');
		String b = a.substring(ii);
		String c = a.substring(0, ii);
		int jj = c.lastIndexOf('.');
		String d = c.substring(jj);
		String f = d + b;
		return f;
	}

	/**
	 * 获取某个包下面所有的接口及其实现类(只能返回一个实现)
	 *
	 * @param packName
	 *            包名
	 * @param jarFilename
	 * @return
	 */
	public static Map<Class<?>, Class<?>> getPackAllInterfaceImplMap(String packName, String jarFilename) {
		Map<Class<?>, Class<?>> classkvMap = new HashMap<Class<?>, Class<?>>();
		List<Class<?>> interfaceList = new ArrayList<Class<?>>();
		List<Class<?>> impList = new ArrayList<Class<?>>();
		try {
			@SuppressWarnings("rawtypes")
			Class[] ca = findClassesInJar(jarFilename, packName);
			for (int i = 0; i < ca.length; i++) {
				// System.out.println(ca[i]);
				if (ca[i].isInterface()) {
					interfaceList.add(ca[i]);
				} else {
					impList.add(ca[i]);
				}
			}
			for (int i = 0; i < impList.size(); i++) {
				Class<?> imp = impList.get(i);
				@SuppressWarnings("rawtypes")
				Class[] ff = imp.getInterfaces();
				if (ff == null || ff.length == 0) {
					continue;
				}
				for (int j = 0; j < interfaceList.size(); j++) {
					Class<?> face = interfaceList.get(j);
					// System.out.println(ff[0]);
					// System.out.println(face);
					if (ff[0].equals(face)) {
						classkvMap.put(face, imp);
						break;
					}
				}
			}
			// System.out.println(classkvMap);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			interfaceList.clear();
			impList.clear();
		}
		return classkvMap;
	}

	/**
	 * 获取某个包下面所有的接口及其实现类(只能返回一个实现)
	 *
	 * @param packName
	 *            包名
	 * @return
	 */
	public static Map<Class<?>, Class<?>> getPackAllInterfaceImplMap(String packName) {
		Map<Class<?>, Class<?>> classkvMap = new HashMap<Class<?>, Class<?>>();
		List<Class<?>> interfaceList = new ArrayList<Class<?>>();
		List<Class<?>> impList = new ArrayList<Class<?>>();
		try {
			@SuppressWarnings("rawtypes")
			Class[] ca = getClasses(packName);
			for (int i = 0; i < ca.length; i++) {
				// System.out.println(ca[i]);
				if (ca[i].isInterface()) {
					interfaceList.add(ca[i]);
				} else {
					impList.add(ca[i]);
				}
			}
			for (int i = 0; i < impList.size(); i++) {
				Class<?> imp = impList.get(i);
				@SuppressWarnings("rawtypes")
				Class[] ff = imp.getInterfaces();
				if (ff == null || ff.length == 0) {
					continue;
				}
				for (int j = 0; j < interfaceList.size(); j++) {
					Class<?> face = interfaceList.get(j);
					// System.out.println(ff[0]);
					// System.out.println(face);
					if (ff[0].equals(face)) {
						classkvMap.put(face, imp);
						break;
					}
				}
			}
			// System.out.println(classkvMap);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			interfaceList.clear();
			impList.clear();
		}
		return classkvMap;
	}
}


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: bigip_pool
short_description: Manages F5 BIG-IP LTM pools.
description:
  - Manages F5 BIG-IP LTM pools via iControl REST API.
version_added: 1.2
author:
  - Tim Rupp (@caphrim007)
  - Wojciech Wypior (@wojtek0806)
notes:
  - Requires BIG-IP software version >= 11.
  - F5 developed module 'F5-SDK' required (https://github.com/F5Networks/f5-common-python).
  - Best run as a local_action in your playbook.
requirements:
  - f5-sdk
options:
  description:
    description:
      - Specifies descriptive text that identifies the pool.
    version_added: "2.3"
  name:
    description:
      - Pool name
    required: True
    aliases:
      - pool
  lb_method:
    description:
      - Load balancing method. When creating a new pool, if this value is not
        specified, the default of C(round-robin) will be used.
    version_added: "1.3"
    choices:
      - dynamic-ratio-member
      - dynamic-ratio-node
      - fastest-app-response
      - fastest-node
      - least-connections-member
      - least-connections-node
      - least-sessions
      - observed-member
      - observed-node
      - predictive-member
      - predictive-node
      - ratio-least-connections-member
      - ratio-least-connections-node
      - ratio-member
      - ratio-node
      - ratio-session
      - round-robin
      - weighted-least-connections-member
      - weighted-least-connections-nod
  monitor_type:
    description:
      - Monitor rule type when C(monitors) > 1.
    version_added: "1.3"
    choices: ['and_list', 'm_of_n']
  quorum:
    description:
      - Monitor quorum value when C(monitor_type) is C(m_of_n).
    version_added: "1.3"
  monitors:
    description:
      - Monitor template name list. If the partition is not provided as part of
        the monitor name, then the C(partition) option will be used instead.
    version_added: "1.3"
  slow_ramp_time:
    description:
      - Sets the ramp-up time (in seconds) to gradually ramp up the load on
        newly added or freshly detected up pool members.
    version_added: "1.3"
  reselect_tries:
    description:
      - Sets the number of times the system tries to contact a pool member
        after a passive failure.
    version_added: "2.2"
  service_down_action:
    description:
      - Sets the action to take when node goes down in pool.
    version_added: "1.3"
    choices:
      - none
      - reset
      - drop
      - reselect
  host:
    description:
      - Pool member IP.
    aliases:
      - address
  port:
    description:
      - Pool member port.
extends_documentation_fragment: f5
'''

EXAMPLES = '''
- name: Create pool
  bigip_pool:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
      state: "present"
      name: "my-pool"
      partition: "Common"
      lb_method: "least_connection_member"
      slow_ramp_time: 120
  delegate_to: localhost

- name: Modify load balancer method
  bigip_pool:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
      state: "present"
      name: "my-pool"
      partition: "Common"
      lb_method: "round_robin"
  delegate_to: localhost

- name: Add pool member
  bigip_pool:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
      state: "present"
      name: "my-pool"
      partition: "Common"
      host: "{{ ansible_default_ipv4['address'] }}"
      port: 80
  delegate_to: localhost

- name: Remove pool member from pool
  bigip_pool:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
      state: "absent"
      name: "my-pool"
      partition: "Common"
      host: "{{ ansible_default_ipv4['address'] }}"
      port: 80
  delegate_to: localhost

- name: Delete pool
  bigip_pool:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
      state: "absent"
      name: "my-pool"
      partition: "Common"
  delegate_to: localhost
'''

RETURN = '''
monitor_type:
    description: The contact that was set on the datacenter.
    returned: changed
    type: string
    sample: "admin@root.local"
quorum:
    description: The quorum that was set on the pool
    returned: changed
    type: int
    sample: 2
monitors:
    description: Monitors set on the pool.
    returned: changed
    type: list
    sample: ['/Common/http', '/Common/gateway_icmp']
service_down_action:
    description: Service down action that is set on the pool.
    returned: changed
    type: string
    sample: "reset"
description:
    description: Description set on the pool.
    returned: changed
    type: string
    sample: "Pool of web servers"
lb_method:
    description: The LB method set for the pool.
    returned: changed
    type: string
    sample: "round-robin"
host:
    description: IP of pool member included in pool.
    returned: changed
    type: string
    sample: "10.10.10.10"
port:
    description: Port of pool member included in pool.
    returned: changed
    type: int
    sample: 80
slow_ramp_time:
    description: The new value that is set for the slow ramp-up time.
    returned: changed
    type: int
    sample: 500
reselect_tries:
    description: The new value that is set for the number of tries to contact member
    returned: changed
    type: int
    sample: 10
'''

import re
import os
from netaddr import IPAddress, AddrFormatError
from ansible.module_utils.f5_utils import (
    AnsibleF5Client,
    AnsibleF5Parameters,
    HAS_F5SDK,
    F5ModuleError,
    iControlUnexpectedHTTPError
)

class Parameters(AnsibleF5Parameters):
    api_map = {
        'loadBalancingMode': 'lb_method',
        'slowRampTime': 'slow_ramp_time',
        'reselectTries': 'reselect_tries',
        'serviceDownAction': 'service_down_action'
    }

    updatables = [
        'monitor_type', 'quorum', 'monitors', 'service_down_action',
        'description', 'lb_method', 'slow_ramp_time', 'reselect_tries',
        'host', 'port'
    ]

    returnables = [
        'monitor_type', 'quorum', 'monitors', 'service_down_action',
        'description', 'lb_method', 'host', 'port', 'slow_ramp_time',
        'reselect_tries', 'monitor', 'member_name', 'name', 'partition'
    ]

    api_attributes = [
        'description', 'name', 'loadBalancingMode', 'monitor', 'slowRampTime',
        'reselectTries', 'serviceDownAction'
    ]

    def __init__(self, params=None):
        super(Parameters, self).__init__(params)
        self._values['__warnings'] = []

    @property
    def lb_method(self):
        lb_map = {
            'ratio_node_address': 'ratio-node',
            'dynamic_ratio': 'dynamic-ratio-node',
            'least_connection_member': 'least-connections-member',
            'least_connection_node_address': 'least-connections-node',
            'fastest_node_address': 'fastest-node',
            'observed_node_address': 'observed-node',
            'predictive_node_address': 'predictive-node',
            'weighted_least_connection_member': 'weighted-least-connections-member',
            'weighted_least_connection_node_address': 'weighted-least-connections-node',
            'ratio_least_connection_member': 'ratio-least-connections-member',
            'ratio_least_connection_node_address': 'ratio-least-connections-node'
        }
        lb_method = self._values['lb_method']
        if lb_method is None:
            return None

        spec = ArgumentSpec()
        if lb_method in spec.lb_choice_removed:
            raise F5ModuleError(
                "The provided lb_method is not supported"
            )
        if lb_method in spec.lb_choice_deprecated:
            self._values['__warnings'].append(
                dict(
                    msg="The provided lb_method '{0}' is deprecated".format(lb_method),
                    version='2.4'
                )
            )
            lb_method = lb_map.get(lb_method, lb_method.replace('_', '-'))
        try:
            assert lb_method in spec.lb_choice
        except AssertionError:
            raise F5ModuleError('Provided lb_method is unknown')
        return lb_method

    @property
    def monitors(self):
        monitors = list()
        monitor_list = self._values['monitors']
        monitor_type = self._values['monitor_type']
        error1 = "The 'monitor_type' parameter cannot be empty when " \
                 "'monitors' parameter is specified."
        error2 = "The 'monitor' parameter cannot be empty when " \
                 "'monitor_type' parameter is specified"
        if monitor_list is not None and monitor_type is None:
            raise F5ModuleError(error1)
        elif monitor_list is None and monitor_type is not None:
            raise F5ModuleError(error2)
        elif monitor_list is None:
            return None

        for m in monitor_list:
            if re.match(r'\/\w+\/\w+', m):
                m = '/{0}/{1}'.format(self.partition, os.path.basename(m))
            elif re.match(r'\w+', m):
                m = '/{0}/{1}'.format(self.partition, m)
            else:
                raise F5ModuleError(
                    "Unknown monitor format '{0}'".format(m)
                )
            monitors.append(m)

        return monitors

    @property
    def quorum(self):
        value = self._values['quorum']
        error = "Quorum value must be specified with monitor_type 'm_of_n'."
        if self._values['monitor_type'] == 'm_of_n' and value is None:
            raise F5ModuleError(error)
        return value

    @property
    def monitor(self):
        monitors = self.monitors
        monitor_type = self._values['monitor_type']
        quorum = self.quorum

        if monitors is None:
            return None

        if monitor_type == 'and_list':
            and_list = list()
            for m in monitors:
                if monitors.index(m) == 0:
                    and_list.append(m)
                else:
                    and_list.append('and')
                    and_list.append(m)
            result = ' '.join(and_list)
        else:
            min_list = list()
            prefix = 'min {0} of {{'.format(str(quorum))
            min_list.append(prefix)
            for m in monitors:
                min_list.append(m)
            min_list.append('}')
            result = ' '.join(min_list)

        return result

    @property
    def host(self):
        value = self._values['host']
        if value is None:
            return None
        msg = "'%s' is not a valid IP address" % value
        try:
            IPAddress(value)
        except AddrFormatError:
            raise F5ModuleError(msg)
        return value

    @host.setter
    def host(self, value):
        self._values['host'] = value

    @property
    def port(self):
        value = self._values['port']
        if value is None:
            return None
        msg = "The provided port '%s' must be between 0 and 65535" % value
        if value < 0 or value > 65535:
            raise F5ModuleError(msg)
        return value

    @port.setter
    def port(self, value):
        self._values['port'] = value

    @property
    def member_name(self):
        if self.host is None or self.port is None:
            return None
        mname = str(self.host) + ':' + str(self.port)
        return mname

    def to_return(self):
        result = {}
        for returnable in self.returnables:
            result[returnable] = getattr(self, returnable)
        result = self._filter_params(result)
        return result

    def api_params(self):
        result = {}
        for api_attribute in self.api_attributes:
            if self.api_map is not None and api_attribute in self.api_map:
                result[api_attribute] = getattr(
                    self, self.api_map[api_attribute]
                )
            else:
                result[api_attribute] = getattr(self, api_attribute)
        result = self._filter_params(result)
        return result

class ModuleManager(object):
    def __init__(self, client):
        self.client = client
        self.have = None
        self.want = Parameters(self.client.module.params)
        self.changes = Parameters()

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        try:
            if state == "present":
                changed = self.present()
            elif state == "absent":
                changed = self.absent()
        except iControlUnexpectedHTTPError as e:
            raise F5ModuleError(str(e))

        changes = self.changes.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations()
        return result

    def _announce_deprecations(self):
        warnings = []
        if self.want:
            warnings += self.want._values.get('__warnings', [])
        if self.have:
            warnings += self.have._values.get('__warnings', [])
        for warning in warnings:
            self.client.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def _set_changed_options(self):
        changed = {}
        for key in Parameters.returnables:
            if getattr(self.want, key) is not None:
                changed[key] = getattr(self.want, key)
        if changed:
            self.changes = Parameters(changed)

    def _update_changed_options(self):
        changed = {}
        for key in Parameters.updatables:
            if getattr(self.want, key) is not None:
                attr1 = getattr(self.want, key)
                attr2 = getattr(self.have, key)
                if attr1 != attr2:
                    changed[key] = attr1
        if changed:
            self.changes = Parameters(changed)
            return True
        return False

    def _member_does_not_exist(self, members):
        name = self.want.member_name
        # Return False if name is None, so that we don't attempt to create it
        if name is None:
            return False
        for member in members:
            if member.name == name:
                host, port = name.split(':')
                self.have.host = host
                self.have.port = int(port)
                return False
        return True

    def present(self):
        if self.exists():
            return self.update()
        else:
            return self.create()

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def update(self):
        self.have, members, poolres = self.read_current_from_device()
        if not self.client.check_mode:
            if self._member_does_not_exist(members):
                self.create_member_on_device(poolres)
        if not self.should_update():
            return False
        if self.client.check_mode:
            return True
        self.update_on_device()
        return True

    def remove(self):
        if self.client.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the Pool")
        return True

    def create(self):
        self._set_changed_options()
        if self.client.check_mode:
            return True
        self.create_on_device()
        if self.want.member_name:
            self.have, members, poolres = self.read_current_from_device()
            if self._member_does_not_exist(members):
                self.create_member_on_device(poolres)
        return True

    def create_on_device(self):
        params = self.want.api_params()
        self.client.api.tm.ltm.pools.pool.create(
            partition=self.want.partition, **params
        )

    def create_member_on_device(self, poolres):
        poolres.members_s.members.create(
            name=self.want.member_name,
            partition=self.want.partition
        )

    def update_on_device(self):
        params = self.want.api_params()
        result = self.client.api.tm.ltm.pools.pool.load(
            name=self.want.name,
            partition=self.want.partition
        )
        result.modify(**params)

    def exists(self):
        return self.client.api.tm.ltm.pools.pool.exists(
            name=self.want.name,
            partition=self.want.partition
        )

    def remove_from_device(self):
        result = self.client.api.tm.ltm.pools.pool.load(
            name=self.want.name,
            partition=self.want.partition
        )
        if self.want.member_name and self.want.port and self.want.pool:
            member = result.members_s.members.load(
                name=self.want.member_name,
                partition=self.want.partition
            )
            if member:
                member.delete()
                self.delete_node_on_device()
        else:
            result.delete()

    def read_current_from_device(self):
        tmp_res = self.client.api.tm.ltm.pools.pool.load(
            name=self.want.name,
            partition=self.want.partition
        )
        members = tmp_res.members_s.get_collection()

        result = tmp_res.attrs
        return Parameters(result), members, tmp_res

    def delete_node_on_device(self):
        resource = self.client.api.tm.ltm.nodes.node.load(
            name=self.want.host,
            partition=self.want.partition
        )
        try:
            resource.delete()
        except iControlUnexpectedHTTPError as e:
            # If we cannot remove it, it is in use, it is up to user to delete
            # it later.
            if "is referenced by a member of pool" in str(e):
                return
            else:
                raise

class ArgumentSpec(object):
    def __init__(self):
        self.lb_choice_deprecated = [
            'round_robin',
            'ratio_member',
            'least_connection_member',
            'observed_member',
            'predictive_member',
            'ratio_node_address',
            'least_connection_node_address',
            'fastest_node_address',
            'observed_node_address',
            'predictive_node_address',
            'dynamic_ratio',
            'fastest_app_response',
            'least_sessions',
            'dynamic_ratio_member',
            'ratio_session',
            'weighted_least_connection_member',
            'ratio_least_connection_member',
            'weighted_least_connection_node_address',
            'ratio_least_connection_node_address'
        ]
        self.lb_choice_removed = [
            'l3_addr'
        ]
        self.lb_choice = [
            'dynamic-ratio-member',
            'dynamic-ratio-node',
            'fastest-app-response',
            'fastest-node',
            'least-connections-member',
            'least-connections-node',
            'least-sessions',
            'observed-member',
            'observed-node',
            'predictive-member',
            'predictive-node',
            'ratio-least-connections-member',
            'ratio-least-connections-node',
            'ratio-member',
            'ratio-node',
            'ratio-session',
            'round-robin',
            'weighted-least-connections-member',
            'weighted-least-connections-node'
        ]
        lb_choices = self.lb_choice_removed + self.lb_choice + self.lb_choice_deprecated
        self.supports_check_mode = True
        self.argument_spec = dict(
            name=dict(
                required=True,
                aliases=['pool']
            ),
            lb_method=dict(
                choices=lb_choices
            ),
            monitor_type=dict(
                choices=[
                    'and_list', 'm_of_n'
                ]
            ),
            quorum=dict(
                type='int'
            ),
            monitors=dict(
                type='list'
            ),
            slow_ramp_time=dict(
                type='int'
            ),
            reselect_tries=dict(
                type='int'
            ),
            service_down_action=dict(
                choices=[
                    'none', 'reset',
                    'drop', 'reselect'
                ]
            ),
            description=dict(),
            host=dict(
                aliases=['address'],
                removed_in_version='2.4'
            ),
            port=dict(
                type='int',
                removed_in_version='2.4'
            )
        )
        self.f5_product_name = 'bigip'

def main():
    if not HAS_F5SDK:
        raise F5ModuleError("The python f5-sdk module is required")

    spec = ArgumentSpec()

    client = AnsibleF5Client(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode,
        f5_product_name=spec.f5_product_name
    )

    try:
        mm = ModuleManager(client)
        results = mm.exec_module()
        client.module.exit_json(**results)
    except F5ModuleError as e:
        client.module.fail_json(msg=str(e))

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
"use strict";
/**
 * run all scripts
 *
 * param:
 * - filter     ... function to filter the complete script list upon
 * - filterAll  ... get the complete script list and filter upon that
 *                  the return value is than used as new script list
 * - log        ... callback for logging
 *
 */

//includes
var Fs  = require( 'fs' ),
    Q   = require( 'q' ),
    Log = require( './log.js' ),
    Cfg = require( './../config/config' );

module.exports = function runScripts( param ){

  // get list of analysis scripts
  var scripts = listFiles( __dirname + '/../' ).sort();

  // filter the 00 namespace from scripts
  scripts = scripts.filter( (name) => {
    if( name.substr( 0,2 ) == '00' ) {
      return false;
    } else {
      return true;
    }
  });

  // if param is set, filter accordingly
  if( param && ('filterAll' in param) ) {
    scripts = param.filterAll( scripts );
  }

  // if param is set, filter accordingly
  if( param && ('filter' in param) ) {
    scripts = scripts.filter( param.filter );
  }

  // run remaining scripts in waterfall
  return scripts.reduce( function( prevTask, script ){
    return prevTask.then(function(){
                      var module = require( __dirname + '/../' + script );
                      return module();
                    });
  }, Q(true) );

};

/**
* list of files in a given path
* - removes some files like, e.g., .gitignore
*/
function listFiles( path ) {

 // RegExp to check for analysis script files
 var analysisRegexp = /^[a0-9]\d{3}.*\.js$/i;

 // list all files and filter
 return Fs.readdirSync( path )
          .filter( function( file ){
            return (file.substr(0, 4) != '0000')     // not the current file
                   && analysisRegexp.test( file );   // but any other analysis file
          });
}


text:
package com.rp.aula.design.abstractfactory.exercicio;

public class Sistema {

	public static void main(String[] args) {

		ProdutoFactory f = new PizzaFornoLenhaFactory();
		System.out.println(f.criaPizza().calculaPreco());

		f = new PizzaFornoConvencionalFactory();
		System.out.println(f.criaPizza().calculaPreco());
	}

}


text:
import React, { Component } from 'react';
import './index.css';

class GameInfo extends Component  {

  pixelsToScroll() {
    let {offsetHeight: hdHeight} = this.historyDiv;
    let {offsetHeight: hlHeight} = this.historyList;
    let ΔHeight = hdHeight - hlHeight;
    return ΔHeight < 0 ? -ΔHeight : 0;
  }

  renderArrow() {
    return (
       ⇦
    );
  }

  componentDidMount() {
    this.historyDiv.scrollTop += this.pixelsToScroll();
  }

  componentDidUpdate() {
    this.historyDiv.scrollTop += this.pixelsToScroll();
  }

  render() {
    return (

              score: {
                this.props.draw ?

                    DRAW
                   :
                this.props.winners && this.props.winners.score ?

                    {
                      Object.keys(this.props.winners.score).map(player => (

                          {player} ({this.props.winners.score[player]})

                      ))
                    }
                   :
              }

                next player: {this.props.xIsNext ? this.props.X : this.props.O}

              <button onClick={() => this.props.jumpTo(0)}>

                  Game start

              </button>
              {this.props.pointer === 0 && this.renderArrow()}

 {this.historyDiv = e}}>

 {this.historyList = e}}>
              {
                this.props.history.slice(1).map((step,i) => {
                  const move = i + 1;
                  return (

                      <button onClick={() => this.props.jumpTo(move)}>

                          move #{move}

                      </button>
                      {this.props.pointer === move && this.renderArrow()}

                  );
                })
              }

    );
  }
}

export default GameInfo;


text:
		<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet">

Ben Taylor: Select Performances

> Dreams of Massachusetts

					Live coding a robotic zither designed by EMMI (Expressive Machines, Musical Instruments). This performance uses a homemade live coding language I designed to explore the use of audio signals as pattern generators. Performed at the 2017 New Interfaces for Musical Expression (NIME) conference in Copenhagen, DK.

> WonderGarden

					A music performance that uses the audience's phones as a collective speaker system. A performer uses the internet to send control gestures to web browsers in audience phones, causing them to synthesize audio. Performed at Mill 180 Park in Easthampton, MA with a grant from Easthampton City Arts. For more on this genre, see my paper A History of the Audience as a Speaker Array.

> The Last Cloud

					A media art performance in which I look back on my daily life using the main technology of my daily life: the web browser. In The Last Cloud I live code the browser in a collage of internet media, cell phone videos, and websites. Glitching quicktime players; harmonizing with dialtones; browsing as performance; browsing as dreaming.


text:
package jvmmonitor.agent;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sun.tools.attach.VirtualMachine;
import jvmmonitor.agent.flag.JVMFlagItem;
import org.apache.commons.lang3.StringUtils;
import sun.jvmstat.monitor.LongMonitor;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.StringMonitor;
import sun.tools.attach.HotSpotVirtualMachine;

import java.io.*;
import java.net.*;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;

/**
 * Created by peiliping on 16-12-19.
 */
public class Util {

    private static final String SPLIT = ",";

    public static Set<Integer> parse2IntSet(String args) {
        Set<Integer> result = Sets.newHashSet();
        if (StringUtils.isNotBlank(args)) {
            String[] pidsStr = args.split(SPLIT);
            for (String pidStr : pidsStr) {
                result.add(Integer.valueOf(pidStr));
            }
        }
        return result;
    }

    public static Set<String> parse2StringSet(String args) {
        Set<String> result = Sets.newHashSet();
        if (StringUtils.isNotBlank(args)) {
            String[] ekws = args.split(SPLIT);
            for (String ekw : ekws) {
                result.add(ekw);
            }
        }
        return result;
    }

    public static String getValueFromMonitoredVm(MonitoredVm mvm, String key) {
        StringMonitor sm = null;
        try {
            sm = (StringMonitor) mvm.findByName(key);
        } catch (MonitorException e) {
            e.printStackTrace();
        }
        return sm == null ? "Unknown" : sm.stringValue();
    }

    public static long getLongValueFromMonitoredVm(MonitoredVm mvm, String key, long def) {
        LongMonitor lm = null;
        try {
            lm = (LongMonitor) mvm.findByName(key);
        } catch (MonitorException e) {
            e.printStackTrace();
        }
        return lm == null ? def : lm.longValue();
    }

    public static String getLocalIP() {
        String localIP = null;
        String netIP = null;
        Enumeration<NetworkInterface> nInterfaces = null;
        try {
            nInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
        }
        boolean finded = false;
        while (nInterfaces.hasMoreElements() && !finded) {
            Enumeration<InetAddress> inetAddress = nInterfaces.nextElement().getInetAddresses();
            while (inetAddress.hasMoreElements()) {
                InetAddress address = inetAddress.nextElement();
                if (!address.isSiteLocalAddress() && !address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1 && isInnerNet(address.getHostAddress())) {
                    netIP = address.getHostAddress();
                    finded = true;
                    break;
                } else if (address.isSiteLocalAddress() && !address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1 && isInnerNet(address.getHostAddress())) {
                    localIP = address.getHostAddress();
                }
            }
        }
        return (netIP != null && !"".equals(netIP)) ? netIP : localIP;
    }

    public static boolean isInnerNet(String v) {
        if (v.startsWith("10.") || v.startsWith("172.") || v.startsWith("192.168"))
            return true;
        return false;
    }

    public static String toString(InputStream input, String encoding) throws IOException {
        return (null == encoding) ? toString(new InputStreamReader(input)) : toString(new InputStreamReader(input, encoding));
    }

    public static String toString(Reader reader) throws IOException {
        CharArrayWriter sw = new CharArrayWriter();
        copy(reader, sw);
        return sw.toString();
    }

    public static long copy(Reader input, Writer output) throws IOException {
        char[] buffer = new char[1 << 12];
        long count = 0;
        for (int n = 0; (n = input.read(buffer)) >= 0; ) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static HttpResult httpGet(String url) {
        return httpGet(url, "utf-8");
    }

    public static HttpResult httpGet(String url, String encoding) {
        int trytimes = 3;
        while (trytimes > 0) {
            HttpURLConnection connection = null;
            try {
                URL u = new URL(url);
                connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(100);
                connection.connect();
                int respCode = connection.getResponseCode();
                String resp = null;
                if (HttpURLConnection.HTTP_OK == respCode) {
                    resp = toString(connection.getInputStream(), encoding);
                } else {
                    resp = toString(connection.getErrorStream(), encoding);
                }
                return new HttpResult(HttpURLConnection.HTTP_OK == respCode, resp);
            } catch (Exception e) {
                trytimes--;
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
        return new HttpResult(false, "Try my best,but failed![" + url + "]");
    }

    public static HttpResult httpPost(String url, byte[] params) {
        return httpPost(url, "utf-8", null, params);
    }

    public static HttpResult httpPost(String url, String params) {
        return httpPost(url, "utf-8", params, null);
    }

    public static HttpResult httpPost(String url, String encoding, String paramsString, byte[] params) {
        int trytimes = 3;
        while (trytimes > 0) {
            HttpURLConnection connection = null;
            try {
                URL u = new URL(url);
                connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(100);
                connection.setReadTimeout(1000);
                connection.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
                if (paramsString == null) {
                    wr.write(params);
                } else {
                    wr.writeBytes(paramsString);
                }
                wr.flush();
                wr.close();
                int respCode = connection.getResponseCode();
                String resp = null;
                if (HttpURLConnection.HTTP_OK == respCode) {
                    resp = toString(connection.getInputStream(), encoding);
                } else {
                    resp = toString(connection.getErrorStream(), encoding);
                }
                return new HttpResult(HttpURLConnection.HTTP_OK == respCode, resp);
            } catch (Exception e) {
                trytimes--;
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
        return new HttpResult(false, "Try my best,but failed![" + url + "]");
    }

    public static class HttpResult {
        final public boolean success;
        final public String  content;

        public HttpResult(boolean success, String content) {
            this.success = success;
            this.content = content;
        }
    }

    public static String buildParams(String base, String key, String value) {
        base = ((base != null && base.length() > 0) ? (base + "&") : "");
        return base + key + "=" + value;
    }

    public static <K> byte[] compress(K k) throws IOException {
        byte[] jsonData = JSON.toJSONBytes(k);
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(1024);
        GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput, 1024);
        gzipOutput.write(jsonData);
        gzipOutput.close();
        return byteOutput.toByteArray();
    }

    public static List<JVMFlagItem> parseFlags(String pid) {
        try {
            VirtualMachine vm = VirtualMachine.attach(pid);
            HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
            InputStream in = hvm.executeJCmd("VM.flags -all");
            byte buffer[] = new byte[256];
            StringBuilder sbd = new StringBuilder(100000);
            int n;
            do {
                n = in.read(buffer);
                if (n > 0) {
                    String s = new String(buffer, 0, n, "UTF-8");
                    sbd.append(s);
                }
            } while (n > 0);
            in.close();
            vm.detach();
            String[] flags = sbd.toString().split("\n");
            List<JVMFlagItem> result = Lists.newArrayListWithCapacity(128);
            Pattern ptn = Pattern.compile("\\s*([^\\s]+)\\s+([^\\s]+)\\s+(=|:=)([^\\{]+)\\{(.*)\\}");
            for (int i = 1; i < flags.length; i++) {
                Matcher m = ptn.matcher(flags[i]);
                if (m.find()) {
                    result.add(JVMFlagItem.builder().flagName(m.group(2)).original(m.group(3).equals("=")).value(m.group(4).trim()).type(m.group(5)).build());
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class payment extends CI_Controller {

	private $mrh_pass1 = 'evsY7kHJWTCWtTXTdk';

	private $mrh_pass2 = 'ayk75VeIlIBwFp2XrH';

	public function __construct(){
		parent::__construct();
		$this->load->model(array(
			'menu_model',
			'order_model',
		));
		$this->load->library(array(
			'session',
			'ion_auth',
		));
		$this->data['main_menu']     = $this->menu_model->get_menu('main');
		$this->data['help_menu']     = $this->menu_model->get_menu('help');
		$this->data['services_menu'] = $this->menu_model->get_menu('services');

		set_alert($this->session->flashdata('success'), false, 'success');
		set_alert($this->session->flashdata('danger'), false, 'danger');
	}

	public function index() {
		custom_404();
	}

	function result() {
		$mrh_pass2 = $this->mrh_pass2;

		$out_summ = $_REQUEST['OutSum'];
		$inv_id   = $_REQUEST['InvId'];
		$crc      = $_REQUEST['SignatureValue'];

		$crc = strtoupper($crc);

		$my_crc = strtoupper(md5("$out_summ:$inv_id:$mrh_pass2"));

		// проверка корректности подписи
		// check signature
		if ($my_crc != $crc)
		{
			echo "bad sign\n";
			exit;
		}

		$payment_info = $this->db->where(array(
			'id'          => $inv_id,
			'total_price' => $out_summ,
			'status'      => 0
		))->get('payments')->row_array();

		if (empty($payment_info)) {
			echo "bad sign\n";
			exit;
		}
		$this->db->trans_begin();
		$this->db->where('id', $payment_info['order_id'])->update('orders', array('status' => 2));
		$this->db->where('id', $payment_info['id'])->update('payments', array('status' => 1));
		$this->db->trans_commit();
		$order_info = $this->db->where('id', $payment_info['order_id'])->get('orders')->row_array();
		$email_info = array(
			'order_id'   => $order_info['id'],
			'start_date' => date('d.m.Y в H:i', $order_info['start_date']),
		);
		$this->order_model->send_mail($this->ion_auth->user($order_info['client_id'])->row()->email, 'Оплата успешно произведена', 'paid_order', $email_info);
		if (!empty($order_info['cleaner_id'])) {
			$this->order_model->send_mail($this->ion_auth->user($order_info['cleaner_id'])->row()->email, 'Оплата успешно произведена', 'paid_order', $email_info);
		}

		// success
		echo "OK$inv_id\n";
		exit;
	}

	function success() {
		// your registration data
		$mrh_pass1 = $this->mrh_pass1;

		// HTTP parameters:
		$out_summ = $_REQUEST["OutSum"];
		$inv_id   = $_REQUEST["InvId"];
		$crc      = $_REQUEST["SignatureValue"];

		$crc = strtoupper($crc);  // force uppercase

		// build own CRC
		$my_crc = strtoupper(md5("$out_summ:$inv_id:$mrh_pass1"));

		if (strtoupper($my_crc) != strtoupper($crc)) {
			return redirect();
		}

		$payment_info = $this->db->where(array('id' =>  $inv_id, 'status' => 1))->get('payments')->row_array();
		if (empty($payment_info)) {
			return redirect();
		}

		$this->session->set_flashdata('success', 'Поздравляем! Оплата успешно совершена');
		return redirect();
	}

	function fail() {
		$this->session->set_flashdata('danger', 'Вы отказались от оплаты. Заказ #'.$_REQUEST["InvId"]);
		return redirect();
	}
}


text:
<?php
namespace yiiunit\extensions\gii;

use yii\gii\generators\model\Generator as ModelGenerator;
use Yii;
/**
 * SchemaTest checks that Gii model generator supports multiple schemas
 * @group gii
 * @group pgsql
 */
class SchemaTest extends GiiTestCase
{
    protected $driverName = 'pgsql';

    public function testPrefixesGenerator()
    {
        $generator = new ModelGenerator();
        $generator->template = 'default';
        $generator->tableName = 'schema1.*';

        $files = $generator->generate();

        if (version_compare(str_replace('-dev', '', Yii::getVersion()), '2.0.4', '<')) {
            $this->markTestSkipped('This feature is only available since Yii 2.0.4.');
        }

        $this->assertEquals(2, count($files));
        $this->assertEquals("Schema1Table1", basename($files[0]->path, '.php'));
        $this->assertEquals("Schema1Table2", basename($files[1]->path, '.php'));
    }

    public function testRelationsGenerator()
    {
        $generator = new ModelGenerator();
        $generator->template = 'default';
        $generator->tableName = 'schema1.*';

        $files = $generator->generate();
        $this->assertEquals(2, count($files));
        $modelCode = $files[0]->content;
        $modelClass = basename($files[0]->path, '.php');

        if (version_compare(str_replace('-dev', '', Yii::getVersion()), '2.0.4', '<')) {
            $this->markTestSkipped('This feature is only available since Yii 2.0.4.');
        }

        $relations = [
            "\$this->hasMany(Schema2Table1::className(), ['fk1' => 'fk2', 'fk2' => 'fk1']);",
            "\$this->hasMany(Schema2Table1::className(), ['fk3' => 'fk4', 'fk4' => 'fk3']);",
            "\$this->hasOne(Schema2Table2::className(), ['fk1' => 'fk1', 'fk2' => 'fk2']);",
        ];
        foreach ($relations as $relation) {
            $this->assertTrue(strpos($modelCode, $relation) !== false, "Model $modelClass should contain this relation: $relation.\n$modelCode");
        }

        $generator = new ModelGenerator();
        $generator->template = 'default';
        $generator->tableName = 'schema2.*';

        $files = $generator->generate();
        $this->assertEquals(2, count($files));
        $modelCode = $files[0]->content;
        $modelClass = basename($files[0]->path, '.php');

        $relations = [
            "\$this->hasOne(Schema1Table1::className(), ['fk2' => 'fk1', 'fk1' => 'fk2']);",
            "\$this->hasOne(Schema1Table1::className(), ['fk4' => 'fk3', 'fk3' => 'fk4']);",
            "\$this->hasOne(Schema2Table2::className(), ['fk5' => 'fk5', 'fk6' => 'fk6']);",
        ];
        foreach ($relations as $relation) {
            $this->assertTrue(strpos($modelCode, $relation) !== false, "Model $modelClass should contain this relation: $relation.\n$modelCode");
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
jQuery.fn.topLink = function(settings) {
	settings = jQuery.extend({
		min: 1,
		fadeSpeed: 200
	}, settings);
	return this.each(function() {
		//listen for scroll
		var el = jQuery(this);
		el.hide(); //in case the user forgot
		jQuery(window).scroll(function() {
			if(jQuery(window).scrollTop() >= settings.min)
			{
				el.fadeIn(settings.fadeSpeed);
			}
			else
			{
				el.fadeOut(settings.fadeSpeed);
			}
		});
	});
};

//Theme scripts
jQuery(document).ready(function($){

    $('#top-link').topLink({
		min: 400,
		fadeSpeed: 500
	});

    $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });

    //enable scrollspy
    //$('#top-nav').scrollspy()

    //$('.carousel').carousel()
    $('.bj-tooltip').tooltip();

    //add some responsive stuff

    var width = $(window).width();

    if ((width >= 1860)) {

        $('body').addClass('screen-xlarge');

    }else if ((width > 1560) && (width <= 1850)){

        $('body').addClass('screen-large');
    }
    else if((width > 1160) && (width <= 1550)){

        $('body').addClass('screen-medium');
    }
    else if ((width >= 920 ) && (width <= 1150)){

        $('body').addClass('screen-default');

    } else if ((width >= 768) && (width <= 918)){

        $('body').addClass('tablet-landscape');

    }else if ((width >= 481) && (width <= 767)){

        $('body').addClass('tablet-portrait');

    } else if ((width <= 480)){

        $('body').addClass('mobile-phone, phone');

    }

    var top_nav = $('#top-nav').data('trigger');
    if(top_nav) {
        //$('body').addClass('top-nav-padding');

        $('#nav-separator').waypoint(function(direction){
            console.log("trigger " + top_nav +' ' + direction);
            if(direction == 'down'){
                $('#top-nav').addClass('navbar-fixed-top');
                $('#top-nav').transition({ opacity: 0.5});
                $('#top-nav').transition({ opacity: 0.95});
            } else if(direction == 'up') {
                $('body').removeClass('top-nav-padding');
                $('#top-nav').removeClass('navbar-fixed-top');
                $('#top-nav').transition({ opacity: 0.5});
                $('#top-nav').transition({ opacity: 0.95});
            }

        }, { offset: 0});
    }

    $('.nav-button').click(function(){
       var menu = $(this).data('nav-menu');
       // console.log(menu);
       // $(menu).toggleClass('display');
       $(menu).slideToggle();
    });

})


text:
package com.wolandsoft.sss.activity.fragment.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wolandsoft.sss.R;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Alert dialog to be presented as fragment element.
 *
 * @author Alexander Shulgin
 */
public class FileDialogFragment extends DialogFragment {
    private static final String KEY_IS_FILE_CHOOSER = "file_chooser";
    private static final String KEY_CURRENT_PATH = "current_path";
    private final File mBasePath = Environment.getExternalStorageDirectory();
    private OnDialogToFragmentInteract mListener;
    private TextView mTxtSelectedFile;
    private FolderListAdapter mAdapter;
    private File mCurrentPath = mBasePath;
    private boolean mIsFileChooser = false;

    public static FileDialogFragment newInstance(boolean isFileChooser) {
        FileDialogFragment fragment = new FileDialogFragment();
        Bundle args = new Bundle();
        args.putBoolean(KEY_IS_FILE_CHOOSER, isFileChooser);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Fragment parent = getTargetFragment();
        if (parent instanceof OnDialogToFragmentInteract) {
            mListener = (OnDialogToFragmentInteract) parent;
        } else {
            throw new ClassCastException(
                    String.format(
                            getString(R.string.internal_exception_must_implement),
                            parent.toString(),
                            OnDialogToFragmentInteract.class.getName()
                    )
            );
        }
        Bundle args = getArguments();
        if (args != null && !args.isEmpty()) {
            mIsFileChooser = args.getBoolean(KEY_IS_FILE_CHOOSER);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        @SuppressWarnings("RedundantCast")
        View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_file_list, (ViewGroup) null);
        ListView listView = (ListView) v.findViewById(R.id.lstItems);
        mTxtSelectedFile = (TextView) v.findViewById(R.id.txtTitle);
        if (savedInstanceState != null) {
            mCurrentPath = (File) savedInstanceState.getSerializable(KEY_CURRENT_PATH);
        }
        //mTxtSelectedFile.setText(getResources().getString(R.string.label_path_prefix) + mCurrentPath.getName());
        List<ListItem> list = loadFileList(mCurrentPath);
        mAdapter = new FolderListAdapter(list);
        listView.setAdapter(mAdapter);
        mTxtSelectedFile.setText(mIsFileChooser ? R.string.label_select_file : R.string.label_select_directory);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        if (!mIsFileChooser) {
            builder.setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String selectedPath = mCurrentPath.getPath().substring(mBasePath.getPath().length());
                                    mListener.onFileSelected(mCurrentPath, selectedPath);
                                }
                            });
                            dialog.dismiss();
                        }
                    }
            );
        }
        final AlertDialog dialog = builder.create();
        listView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ListItem li = (ListItem) mAdapter.getItem(position);
                        if (li.isBackButton) {
                            mCurrentPath = mCurrentPath.getParentFile();
                        } else {
                            mCurrentPath = new File(mCurrentPath, li.label);
                        }
                        final String selectedPath = mCurrentPath.getPath().substring(mBasePath.getPath().length());
                        if (li.isFile) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mListener.onFileSelected(mCurrentPath, selectedPath);
                                }
                            });
                            dialog.dismiss();
                            return;
                        }
                        mTxtSelectedFile.setText(selectedPath.length() > 0 ? selectedPath :
                                getString(mIsFileChooser ? R.string.label_select_file : R.string.label_select_directory));
                        List<ListItem> list = loadFileList(mCurrentPath);
                        mAdapter.updateModel(list);
                    }
                });
        return dialog;
    }

    private List<ListItem> loadFileList(File path) {
        File[] fileList;
        if (path.exists()) {
            FilenameFilter filter = new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    return (sel.isDirectory() || mIsFileChooser) && !filename.startsWith(".");
                }

            };
            fileList = path.listFiles(filter);
        } else {
            fileList = new File[0];
        }
        List<ListItem> list = new ArrayList<>();
        if (!path.equals(mBasePath)) {
            ListItem li = new ListItem();
            li.iconId = R.mipmap.img24dp_back;
            li.iconDescId = R.string.label_back;
            li.isBackButton = true;
            li.label = getString(R.string.label_back);
            list.add(li);
        }
        for (File file : fileList) {
            ListItem li = new ListItem();
            li.label = file.getName();
            if (file.isFile()) {
                li.isFile = true;
                li.iconId = R.mipmap.img24dp_file;
                li.iconDescId = R.string.label_file;
            }
            list.add(li);
        }
        Collections.sort(list);
        return list;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(KEY_CURRENT_PATH, mCurrentPath);
    }

    /**
     * This interface should be implemented by parent fragment in order to receive callbacks from this fragment.
     */
    public interface OnDialogToFragmentInteract {
        void onFileSelected(File path, String uiPath);
    }

    public static class FolderListAdapter extends BaseAdapter {
        private List<ListItem> mFileList;

        public FolderListAdapter(List<ListItem> fileList) {
            mFileList = fileList;
        }

        public void updateModel(List<ListItem> fileList) {
            mFileList = fileList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mFileList.size();
        }

        @Override
        public Object getItem(int position) {
            return mFileList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater) parent.getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                convertView = mInflater.inflate(R.layout.dialog_file_include_card, parent, false);
            }
            ListItem item = (ListItem) getItem(position);
            ImageView img = (ImageView) convertView.findViewById(R.id.imgIcon);
            img.setImageResource(item.iconId);
            img.setContentDescription(parent.getContext().getString(item.iconDescId));
            TextView txt = (TextView) convertView.findViewById(R.id.txtFile);
            txt.setText(item.label);
            return convertView;
        }
    }

    private static class ListItem implements Comparable<ListItem> {
        boolean isFile = false;
        boolean isBackButton = false;
        String label;
        int iconId = R.mipmap.img24dp_directory;
        int iconDescId = R.string.label_directory;

        @Override
        public int compareTo(@NonNull ListItem o) {
            if (o.isBackButton)
                return 1;

            if (o.isFile != isFile)
                return o.isFile ? 0 : 1;

            return label.compareTo(o.label);
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.hive;

import io.airlift.configuration.Config;
import io.airlift.units.DataSize;
import io.prestosql.orc.OrcWriterOptions;

@SuppressWarnings("unused")
public class OrcFileWriterConfig
{
    private OrcWriterOptions options = new OrcWriterOptions();

    public OrcWriterOptions toOrcWriterOptions()
    {
        return options;
    }

    public DataSize getStripeMinSize()
    {
        return options.getStripeMinSize();
    }

    @Config("hive.orc.writer.stripe-min-size")
    public OrcFileWriterConfig setStripeMinSize(DataSize stripeMinSize)
    {
        options = options.withStripeMinSize(stripeMinSize);
        return this;
    }

    public DataSize getStripeMaxSize()
    {
        return options.getStripeMaxSize();
    }

    @Config("hive.orc.writer.stripe-max-size")
    public OrcFileWriterConfig setStripeMaxSize(DataSize stripeMaxSize)
    {
        options = options.withStripeMaxSize(stripeMaxSize);
        return this;
    }

    public int getStripeMaxRowCount()
    {
        return options.getStripeMaxRowCount();
    }

    @Config("hive.orc.writer.stripe-max-rows")
    public OrcFileWriterConfig setStripeMaxRowCount(int stripeMaxRowCount)
    {
        options = options.withStripeMaxRowCount(stripeMaxRowCount);
        return this;
    }

    public int getRowGroupMaxRowCount()
    {
        return options.getRowGroupMaxRowCount();
    }

    @Config("hive.orc.writer.row-group-max-rows")
    public OrcFileWriterConfig setRowGroupMaxRowCount(int rowGroupMaxRowCount)
    {
        options = options.withRowGroupMaxRowCount(rowGroupMaxRowCount);
        return this;
    }

    public DataSize getDictionaryMaxMemory()
    {
        return options.getDictionaryMaxMemory();
    }

    @Config("hive.orc.writer.dictionary-max-memory")
    public OrcFileWriterConfig setDictionaryMaxMemory(DataSize dictionaryMaxMemory)
    {
        options = options.withDictionaryMaxMemory(dictionaryMaxMemory);
        return this;
    }

    public DataSize getStringStatisticsLimit()
    {
        return options.getMaxStringStatisticsLimit();
    }

    @Config("hive.orc.writer.string-statistics-limit")
    public OrcFileWriterConfig setStringStatisticsLimit(DataSize stringStatisticsLimit)
    {
        options = options.withMaxStringStatisticsLimit(stringStatisticsLimit);
        return this;
    }

    public DataSize getMaxCompressionBufferSize()
    {
        return options.getMaxCompressionBufferSize();
    }

    @Config("hive.orc.writer.max-compression-buffer-size")
    public OrcFileWriterConfig setMaxCompressionBufferSize(DataSize maxCompressionBufferSize)
    {
        options = options.withMaxCompressionBufferSize(maxCompressionBufferSize);
        return this;
    }
}


text:
first('email', ' has-error') }} has-feedback">
    {!! Form::email('email',null, ['class'=>'form-control', 'placeholder'=>Lang::get('admin-lang.email')]) !!}

first('password', ' has-error') }} has-feedback">
   {!! Form::password('password',['class'=>'form-control','placeholder'=> Lang::get('password')]) !!}

        @if(Session::has('flash_alert_notice'))

             {{ Session::get('flash_alert_notice') }}

      @endif

    {!! Form::submit(Lang::get('admin-lang.sign_in'), ['class'=>'btn btn-primary btn-block btn-flat', 'id'=>'login', 'value'=>  Lang::get('admin-lang.sign_in') ]) !!}


text:
<?php

namespace Doctrine\Tests\Models\DDC1872;

/**
 * @Entity
 */
class DDC1872ExampleEntityWithoutOverride
{
    use DDC1872ExampleTrait;
}


text:
#ifndef XORG_GTEST_EVEMU_DEVICE_H_
#define XORG_GTEST_EVEMU_DEVICE_H_

#include <memory>
#include <string>

extern "C" {

#include <evemu.h>

} // extern "C"

namespace xorg {
namespace testing {
namespace evemu {

/**
 * @class Device xorg-gtest-device.h xorg/gtest/evemu/xorg-gtest-device.h
 *
 * evemu input device for replaying events through the Linux uinput
 * evdev subsystem.
 *
 * Use the Recording class to play back a specific recording.
 */

class Device {
 public:
  /**
   * Create a new device context.
   *
   * @param [in] path Path to evemu device property file.
   *
   * @throws std::runtime_error if the device property file could not be found
   *         or the device could not be created.
   */
  explicit Device(const std::string& path);
  ~Device();

  /**
   * Play a evemu recording through the device.
   *
   * Plays the recording from the beginning through the end. This call will
   * block until the recording has finished.
   *
   * @param [in] path Path to evemu recording file.
   *
   * @throws std::runtime_error if playback failed for any reason.
   */
  void Play(const std::string& path) const;

  /**
   * Play a single event through the device.
   *
   * Plays an event with the given type, code and value through the device.
   *
   * @param [in] type Evdev interface event type, e.g. EV_ABS, EV_REL, EV_KEY.
   * @param [in] code Evdev interface event code, e.g. ABS_X, REL_Y, BTN_LEFT
   * @param [in] value Event value
   * @param [in] sync If true, submit an EV_SYN event after this event
   *
   * @throws std::runtime_error if playback failed for any reason.
   */
  void PlayOne(int type, int code, int value, bool sync = false);

  /**
   * Return the /dev/input/eventX device node for this device.
   *
   * Note that evemu doesn't know the device node, so we traverse the file
   * system looking for it. There is a tiny chance of the device node being
   * wrong, or the device disappearing before we find it. If the device
   * node cannot be found, an empty string is returned.
   *
   * @return The string representing the device node
   */
  const std::string& GetDeviceNode(void);

  /**
   * Check if a device supports a specific event.
   *
   * @param [in] type Type of the event (EV_REL, EV_ABS, ...)
   * @param [in] code Event code (ABS_X, REL_Y, ...)
   *
   * @return true if this device supports this event or false otherwise.
   */
  bool HasEvent(int type, int code);

  /**
   * Retrieve data about an absolute axis on this device.
   *
   * @param [in] code The axis to query (e.g. ABS_X)
   * @param [out] min Min value for this axis
   * @param [out] max Max value for this axis
   * @param [out] fuzz Fuzz value for this axis
   * @param [out] flat Flat value for this axis
   * @param [out] resolution Resolution of this axis
   *
   * @return false if this device doesn't have this axis, or true on success
   */
  bool GetAbsData(int code, int *min, int *max, int *fuzz = NULL, int *flat = NULL, int *resolution = NULL);

 private:
  struct Private;
  std::auto_ptr<Private> d_;

  /* Disable copy constructor & assignment operator */
  Device(const Device&);
  Device& operator=(const Device&);

  void GuessDeviceNode(time_t ctime);
};

} // namespace evemu
} // namespace testing
} // namespace xorg

#endif // XORG_GTEST_EVEMU_DEVICE_H_


text:
/*global window, document, location, CodeMirror, jsyaml, inspect, base64, hasher*/

window.runDemo = function runDemo() {
  'use strict';

  var source, result, initial, permalink, timer1, timer2 = null,
      fallback = document.getElementById('source').value || '';

  // add sexy constructor
  var sexyType = new jsyaml.Type('!sexy', {
    loader: {
      kind: 'array',
      resolver: function (object, explicit) {
        var index, length;

        for (index = 0, length = object.length; index < length; index += 1) {
          object[index] = 'sexy ' + object[index];
        }

        return object;
      }
    }
  });

  var SEXY_SCHEMA = jsyaml.Schema.create([ sexyType ]);

  function parse() {
    var str, obj;

    try {
      str = source.getValue();
      obj = jsyaml.load(str, { schema: SEXY_SCHEMA });

      permalink.href = '#yaml=' + base64.encode(str);

      result.setOption('mode', 'javascript');
      result.setValue(inspect(obj, false, 10));
    } catch (err) {
      result.setOption('mode', 'text/plain');
      result.setValue(err.stack || err.message || String(err));
    }
  }

  function updateSource() {
    var yaml;

    if (location.hash && '#yaml=' === location.hash.toString().slice(0,6)) {
      yaml = base64.decode(location.hash.slice(6));
    }

    source.setValue(yaml || fallback);
    parse();
  }

  permalink = document.getElementById('permalink');

  source = CodeMirror.fromTextArea(document.getElementById('source'), {
    mode: 'yaml',
    undoDepth: 1,
    onKeyEvent: function (_, evt) {
      switch (evt.keyCode) {
        case 37:
        case 38:
        case 39:
        case 40:
          return;
      }

      if (evt.type === 'keyup') {
        window.clearTimeout(timer1);
        timer1 = window.setTimeout(parse, 500);

        if (null === timer2) {
          timer2 = setTimeout(function () {
            window.clearTimeout(timer1);
            window.clearTimeout(timer2);
            timer2 = null;
            parse();
          }, 1000);
        }
      }
    }
  });

  result = CodeMirror.fromTextArea(document.getElementById('result'), {
    readOnly: true
  });

  // initial source
  updateSource();

  // start monitor hash change
  hasher.prependHash = '';
  hasher.changed.add(updateSource);
  hasher.initialized.add(updateSource);
  hasher.init();
};

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////


text:
<?php
/**
 * @codeCoverageIgnore
 */
final class CodeFormatter extends BaseCodeFormatter {
	private $currentTiming = null;

	private $timings = [];

	public function afterExecutedPass($source, $className) {
		$cn = get_class($className);
		$this->timings[$cn] = microtime(true) - $this->currentTiming;
		echo $cn, ':', (memory_get_usage() / 1024 / 1024), "\t", (memory_get_peak_usage() / 1024 / 1024), PHP_EOL;
	}

	public function afterFormat($source) {
		asort($this->timings, SORT_NUMERIC);
		$total = array_sum($this->timings);

		$lines = [];
		foreach ($this->timings as $pass => $timing) {
			$lines[] = [$pass, $timing, str_pad(round($timing / $total * 100, 3) . '%', 8, ' ', STR_PAD_LEFT)];
		}
		echo tabwriter($lines);
	}

	public function beforeFormat($source) {
		echo 'before:', (memory_get_usage() / 1024 / 1024), "\t", (memory_get_peak_usage() / 1024 / 1024), PHP_EOL;
	}

	public function beforePass($source, $className) {
		$this->currentTiming = microtime(true);
	}
}


text:
import {Component, EventEmitter, Output} from "@angular/core";

import {ListComponent} from "../base/list.component";
import {UserBriefModel} from "../../model/brief/user-brief-model";
import {UserAuthService} from "../../service/user-auth.service";
import {UserAuthModel} from "../../model/full/user-auth-model";

@Component({
    selector: 'user-list',
    templateUrl: './user-list.component.html'
})
export class UserListComponent extends ListComponent<UserAuthModel, UserBriefModel> {
    @Output('onChangePassDone') changePassCallBack: EventEmitter<null> = new EventEmitter();

    constructor(service: UserAuthService) {
        super(service);
    }

    protected getEmptyModel(): UserAuthModel {
        return UserAuthModel.empty();
    }

    onChangePassDone() {
        this.changePassCallBack.emit();
    }
}


text:
package kubecfg

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/wait"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/version"
	"github.com/golang/glog"
	"gopkg.in/v1/yaml"
)

func GetServerVersion(client *client.Client) (*version.Info, error) {
	info, err := client.ServerVersion()
	if err != nil {
		return nil, fmt.Errorf("Got error: %v", err)
	}
	return info, nil
}

func promptForString(field string, r io.Reader) string {
	fmt.Printf("Please enter %s: ", field)
	var result string
	fmt.Fscan(r, &result)
	return result
}

// LoadAuthInfo parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist.
func LoadAuthInfo(path string, r io.Reader) (*client.AuthInfo, error) {
	var auth client.AuthInfo
	if _, err := os.Stat(path); os.IsNotExist(err) {
		auth.User = promptForString("Username", r)
		auth.Password = promptForString("Password", r)
		data, err := json.Marshal(auth)
		if err != nil {
			return &auth, err
		}
		err = ioutil.WriteFile(path, data, 0600)
		return &auth, err
	}
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(data, &auth)
	if err != nil {
		return nil, err
	}
	return &auth, err
}

// Update performs a rolling update of a collection of pods.
// 'name' points to a replication controller.
// 'client' is used for updating pods.
// 'updatePeriod' is the time between pod updates.
// 'imageName' is the new image to update for the template.  This will work
//     with the first container in the pod.  There is no support yet for
//     updating more complex replication controllers.  If this is blank then no
//     update of the image is performed.
func Update(name string, client client.Interface, updatePeriod time.Duration, imageName string) error {
	controller, err := client.GetReplicationController(name)
	if err != nil {
		return err
	}

	if len(imageName) != 0 {
		controller.DesiredState.PodTemplate.DesiredState.Manifest.Containers[0].Image = imageName
		controller, err = client.UpdateReplicationController(controller)
		if err != nil {
			return err
		}
	}

	s := labels.Set(controller.DesiredState.ReplicaSelector).AsSelector()

	podList, err := client.ListPods(s)
	if err != nil {
		return err
	}
	expected := len(podList.Items)
	if expected == 0 {
		return nil
	}
	for _, pod := range podList.Items {
		// We delete the pod here, the controller will recreate it.  This will result in pulling
		// a new Docker image.  This isn't a full "update" but it's what we support for now.
		err = client.DeletePod(pod.ID)
		if err != nil {
			return err
		}
		time.Sleep(updatePeriod)
	}
	return wait.Poll(time.Second*5, time.Second*300, func() (bool, error) {
		podList, err := client.ListPods(s)
		if err != nil {
			return false, err
		}
		return len(podList.Items) == expected, nil
	})
}

// StopController stops a controller named 'name' by setting replicas to zero.
func StopController(name string, client client.Interface) error {
	return ResizeController(name, 0, client)
}

// ResizeController resizes a controller named 'name' by setting replicas to 'replicas'.
func ResizeController(name string, replicas int, client client.Interface) error {
	controller, err := client.GetReplicationController(name)
	if err != nil {
		return err
	}
	controller.DesiredState.Replicas = replicas
	controllerOut, err := client.UpdateReplicationController(controller)
	if err != nil {
		return err
	}
	data, err := yaml.Marshal(controllerOut)
	if err != nil {
		return err
	}
	fmt.Print(string(data))
	return nil
}

func portsFromString(spec string) []api.Port {
	parts := strings.Split(spec, ",")
	var result []api.Port
	for _, part := range parts {
		pieces := strings.Split(part, ":")
		if len(pieces) != 2 {
			glog.Infof("Bad port spec: %s", part)
			continue
		}
		host, err := strconv.Atoi(pieces[0])
		if err != nil {
			glog.Errorf("Host part is not integer: %s %v", pieces[0], err)
			continue
		}
		container, err := strconv.Atoi(pieces[1])
		if err != nil {
			glog.Errorf("Container part is not integer: %s %v", pieces[1], err)
			continue
		}
		result = append(result, api.Port{ContainerPort: container, HostPort: host})
	}
	return result
}

// RunController creates a new replication controller named 'name' which creates 'replicas' pods running 'image'.
func RunController(image, name string, replicas int, client client.Interface, portSpec string, servicePort int) error {
	if servicePort > 0 && !util.IsDNSLabel(name) {
		return fmt.Errorf("Service creation requested, but an invalid name for a service was provided (%s). Service names must be valid DNS labels.", name)
	}
	controller := &api.ReplicationController{
		JSONBase: api.JSONBase{
			ID: name,
		},
		DesiredState: api.ReplicationControllerState{
			Replicas: replicas,
			ReplicaSelector: map[string]string{
				"replicationController": name,
			},
			PodTemplate: api.PodTemplate{
				DesiredState: api.PodState{
					Manifest: api.ContainerManifest{
						Version: "v1beta2",
						Containers: []api.Container{
							{
								Name:  strings.ToLower(name),
								Image: image,
								Ports: portsFromString(portSpec),
							},
						},
					},
				},
				Labels: map[string]string{
					"replicationController": name,
				},
			},
		},
	}

	controllerOut, err := client.CreateReplicationController(controller)
	if err != nil {
		return err
	}
	data, err := yaml.Marshal(controllerOut)
	if err != nil {
		return err
	}
	fmt.Print(string(data))

	if servicePort > 0 {
		svc, err := createService(name, servicePort, client)
		if err != nil {
			return err
		}
		data, err = yaml.Marshal(svc)
		if err != nil {
			return err
		}
		fmt.Printf(string(data))
	}
	return nil
}

func createService(name string, port int, client client.Interface) (*api.Service, error) {
	svc := &api.Service{
		JSONBase: api.JSONBase{ID: name},
		Port:     port,
		Labels: map[string]string{
			"name": name,
		},
		Selector: map[string]string{
			"name": name,
		},
	}
	svc, err := client.CreateService(svc)
	return svc, err
}

// DeleteController deletes a replication controller named 'name', requires that the controller
// already be stopped.
func DeleteController(name string, client client.Interface) error {
	controller, err := client.GetReplicationController(name)
	if err != nil {
		return err
	}
	if controller.DesiredState.Replicas != 0 {
		return fmt.Errorf("controller has non-zero replicas (%d), please stop it first", controller.DesiredState.Replicas)
	}
	return client.DeleteReplicationController(name)
}


text:
#include "config.h"
#include "util.h"
#include "../src/charls.h"

#include <vector>

void TestFile16BitAs12(SZC strName, int ioffs, Size size2, int ccomp, bool littleEndianFile)
{
    std::vector<BYTE> rgbyteUncompressed;
    if (!ReadFile(strName, &rgbyteUncompressed, ioffs))
        return;

    FixEndian(&rgbyteUncompressed, littleEndianFile);

    USHORT* pushort = (USHORT*)&rgbyteUncompressed[0];

    for (int i = 0; i < (int)rgbyteUncompressed.size()/2; ++i)
    {
        pushort[i] = pushort[i] >> 4;
    }

    TestRoundTrip(strName, rgbyteUncompressed, size2, 12, ccomp);
}

void TestPerformance(int loopCount)
{
    ////TestFile("test/bad.raw", 0, Size(512, 512),  8, 1);

    // RGBA image (This is a common PNG sample)
    TestFile("test/alphatest.raw", 0, Size(380, 287), 8, 4, false, loopCount);

    Size size1024 = Size(1024, 1024);
    Size size512 = Size(512, 512);

    // 16 bit mono
    TestFile("test/MR2_UNC", 1728, size1024, 16, 1, true, loopCount);

    // 8 bit mono
    TestFile("test/0015.raw", 0, size1024, 8, 1, false, loopCount);
    TestFile("test/lena8b.raw", 0, size512, 8, 1, false, loopCount);

    // 8 bit color
    TestFile("test/desktop.ppm", 40, Size(1280, 1024), 8, 3, false, loopCount);

    // 12 bit RGB
    TestFile("test/SIEMENS-MR-RGB-16Bits.dcm", -1, Size(192, 256), 12, 3, true, loopCount);
    TestFile16BitAs12("test/DSC_5455.raw", 142949, Size(300, 200), 3, true);

    // 16 bit RGB
    TestFile("test/DSC_5455.raw", 142949, Size(300, 200), 16, 3, true, loopCount);
}

void TestLargeImagePerformance(int loopCount)
{
    TestFile("test/rgb8bit/artificial.ppm", 17, Size(3072, 2048), 8, 3, false, loopCount);
    TestFile("test/rgb8bit/bridge.ppm", 17, Size(2749, 4049), 8, 3, false, loopCount);
    TestFile("test/rgb8bit/flower_foveon.ppm", 17, Size(2268, 1512), 8, 3, false, loopCount);
    //TestFile("test/rgb8bit/big_building.ppm", 17, Size(7216,5412),  8, 3);
    //  TestFile("test/rgb16bit/bridge.ppm", 19, Size(2749,4049),  16, 3, true);
}

void PerformanceTests(int loopCount)
{
    printf("Test Perf (with loop count %i)\r\n", loopCount);
    TestPerformance(loopCount);

#ifndef _DEBUG
    printf("Test Large Images Performance\r\n");
    TestLargeImagePerformance(loopCount);
#endif
}

void DecodePerformanceTests(int loopCount)
{
    printf("Test decode Perf (with loop count %i)\r\n", loopCount);

    std::vector<uint8_t> jpeglsCompressed;
    if (!ReadFile("decodetest.jls", &jpeglsCompressed, 0, 0))
        return;

    JlsParameters info;
    auto result = JpegLsReadHeader(jpeglsCompressed.data(), jpeglsCompressed.size(), &info);
    if (result != charls::ApiResult::OK)
        return;

    std::vector<uint8_t> uncompressed(info.height * info.width * 2);

    for (int i = 0; i < loopCount; ++i)
    {

        result = JpegLsDecode(uncompressed.data(), uncompressed.size(), jpeglsCompressed.data(), jpeglsCompressed.size(), &info);
        if (result != charls::ApiResult::OK)
            return;
    }
}


text:
<?php

namespace tests\QATools\QATools\PageObject\PageUrlMatcher;

use Mockery as m;
use QATools\QATools\PageObject\Annotation\IMatchUrlAnnotation;
use QATools\QATools\PageObject\PageUrlMatcher\IPageUrlMatcher;
use tests\QATools\QATools\TestCase;

abstract class AbstractPageUrlMatcherTestCase extends TestCase
{

	/**
	 * Page url matcher class.
	 *
	 * @var string
	 */
	protected $className;

	/**
	 * Page url matcher.
	 *
	 * @var IPageUrlMatcher
	 */
	protected $pageUrlMatcher;

	/**
	 * @before
	 */
	protected function setUpTest()
	{
		$this->pageUrlMatcher = new $this->className();

		parent::setUpTest();
	}

	abstract public function testPriority();

	abstract public function testGetAnnotationName();

	abstract public function testGetAnnotationClass();

	/**
	 * @dataProvider matchesDataProvider
	 */
	public function testMatches($annotations, $url, $expected_matches)
	{
		$parsed_annotations = array();

		foreach ( $annotations as $annotation_params ) {
			$parsed_annotations[] = $this->createAnnotation($annotation_params);
		}

		$this->assertEquals($expected_matches, $this->pageUrlMatcher->matches($url, $parsed_annotations));
	}

	abstract public function matchesDataProvider();

	/**
	 * Creates annotation instance, that matcher will use.
	 *
	 * @param array $parameters Parameters.
	 *
	 * @return IMatchUrlAnnotation
	 */
	abstract public function createAnnotation(array $parameters);

}