text:
package org.newdawn.slick.opengl.shader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.lwjgl.opengl.GLContext;
import org.newdawn.slick.Color;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.ResourceLoader;

/**
 * A simple wrapper utility for creating and reusing shaders and shader programs.
 *
 * @author davedes
 */
public class ShaderProgram {

	/** The vertex shader type (GL20.GL_VERTEX_SHADER). */
	public static final int VERTEX_SHADER = GL20.GL_VERTEX_SHADER;
	/** The fragment shader type (GL20.GL_FRAGMENT_SHADER). */
	public static final int FRAGMENT_SHADER = GL20.GL_FRAGMENT_SHADER;

	private static boolean strict = true;

	/**
	 * Returns true if GLSL shaders are supported in hardware on this system. This checks for
	 * the following OpenGL extensions: GL_ARB_shader_objects, GL_ARB_vertex_shader,
	 * GL_ARB_fragment_shader
	 *
	 * @return true if shaders are supported
	 */
	public static boolean isSupported() {
		ContextCapabilities c = GLContext.getCapabilities();
		return c.GL_ARB_shader_objects && c.GL_ARB_vertex_shader && c.GL_ARB_fragment_shader;
	}

	/**
	 * Whether shader programs are to use "strict" uniform/attribute name
	 * checking. That is, when strict mode is enabled, trying to modify or retrieve uniform/attribute
	 * data by name will fail and throw an IllegalArgumentException if there exists no
	 * 'active' uniforms/attributes by the given name. (In GLSL, declared uniforms might still be
	 * "inactive" if they are not used.) If strict mode is disabled, getting/setting uniform/attribute
	 * data will fail silently if the name is not found.
	 * @param enabled true to enable strict mode
	 */
	public static void setStrictMode(boolean enabled) {
		strict = enabled;
	}

	/**
	 * Returns <tt>true</tt> if shader programs are to use "strict" uniform/attribute name
	 * checking. That is, when strict mode is enabled, trying to modify or retrieve uniform/attribute
	 * data by name will fail and throw an IllegalArgumentException if there exists no
	 * 'active' uniforms/attributes by the given name. (In GLSL, declared uniforms might still be
	 * "inactive" if they are not used.) If strict mode is disabled, getting/setting uniform/attribute
	 * data will fail silently if the name is not found.
	 * @return true if strict mode is enabled
	 */
	public static boolean isStrictMode() {
		return strict;
	}

	/**
	 * Disables shaders.
	 */
	public static void unbindAll() {
		ARBShaderObjects.glUseProgramObjectARB(0);
	}

	/** The OpenGL handle for this shader program object. */
	protected int program;
	/** The log for this program. */
	protected String log = "";
	/** A map of uniforms by <name, int>. */
	protected HashMap<String, Integer> uniforms = new HashMap<String, Integer>();
	/** A map of attributes by <name, int>. */
	protected HashMap<String, Integer> attributes = new HashMap<String, Integer>();
	/** The vertex shader source. */
	protected String vertShaderSource;
	/** The fragment shader source. */
	protected String fragShaderSource;
	/** The OpenGL handle for this program's vertex shader object. */
	protected int vert;
	/** The OpenGL handle for this program's fragment shader object. */
	protected int frag;

	private FloatBuffer buf4;
	private IntBuffer ibuf4;

	/**
	 * A convenience method to load a ShaderProgram from two text files.
	 * @param vertFile the location of the vertex shader source
	 * @param fragFile the location of the frag shader source
	 * @return the compiled and linked ShaderProgram
	 * @throws SlickException if there was an issue reading the file, compiling the source,
	 * 				or linking the program
	 */
	public static ShaderProgram loadProgram(String vertFile, String fragFile) throws SlickException {
		return new ShaderProgram(readFile(vertFile), readFile(fragFile));
	}

	/**
	 * Loads the given input stream into a source code string.
	 * @param ref the location of the text file
	 * @return the resulting source code String
	 * @throws SlickException if there was an issue reading the source
	 */
	public static String readFile(String ref) throws SlickException {
		InputStream in = ResourceLoader.getResourceAsStream(ref);
		try { return readFile(in); }
		catch (SlickException e) {
			throw new SlickException("could not load source file: "+ref);
		}
	}

	/**
	 * Loads the given input stream into a source code string.
	 * @param in the input stream
	 * @return the resulting source code String
	 * @throws SlickException if there was an issue reading the source
	 * @author Nitram
	 */
    public static String readFile(InputStream in) throws SlickException {
		try {
			final StringBuffer sBuffer = new StringBuffer();
			final BufferedReader br = new BufferedReader(new InputStreamReader(
					in));
			final char[] buffer = new char[1024];

			int cnt;
			while ((cnt = br.read(buffer, 0, buffer.length)) > -1) {
				sBuffer.append(buffer, 0, cnt);
			}
			br.close();
			return sBuffer.toString();
		} catch (IOException e) {
			throw new SlickException("could not load source file");
		}
	}

    /**
     * Creates a new shader program with the given vertex and fragment shader
     * source code. The given source code is compiled, then the shaders attached
     * and linked.
     *
     * If shaders are not supported on this system (isSupported returns false),
     * a SlickException will be thrown.
     *
     * If one of the shaders does not compile successfully, a SlickException will be thrown.
     *
     * If there was a problem in linking the shaders to the program, a SlickException will
     * be thrown and the program will be deleted.
     *
     * @param vertexShaderSource the shader code to compile, attach and link
     * @param fragShaderSource the frag code to compile, attach and link
     * @throws SlickException if there was an issue
     * @throws IllegalArgumentException if there was an issue
     */
    public ShaderProgram(String vertexShaderSource, String fragShaderSource) throws SlickException {
    	if (vertexShaderSource==null || fragShaderSource==null)
			throw new IllegalArgumentException("shader source must be non-null");
    	if (!isSupported())
			throw new SlickException("no shader support found; driver does not support extension GL_ARB_shader_objects");

    	this.vertShaderSource = vertexShaderSource;
    	this.fragShaderSource = fragShaderSource;
    	vert = compileShader(VERTEX_SHADER, vertexShaderSource);
    	frag = compileShader(FRAGMENT_SHADER, fragShaderSource);
		program = createProgram();
		try {
			linkProgram();
		} catch (SlickException e) {
			release();
			throw e;
		}
		if (log!=null && log.length()!=0)
			Log.warn("GLSL Info: "+log);
    }

	/**
	 * Subclasses may wish to implement this to manually handle program/shader creation, compiling, and linking.
	 * This constructor does nothing; users will need to call compileShader, createProgram and linkProgram manually.
	 * @throws SlickException
	 */
	protected ShaderProgram() {
	}

	/**
	 * Creates a shader program and returns its OpenGL handle. If the result is zero, an exception will be thrown.
	 * @return the OpenGL handle for the newly created shader program
	 * @throws SlickException if the result is zero
	 */
	protected int createProgram() throws SlickException {
		if (!isSupported())
			throw new SlickException("no shader support found; driver does not support extension GL_ARB_shader_objects");
		int program = ARBShaderObjects.glCreateProgramObjectARB();
		if (program == 0)
			throw new SlickException("could not create program; check ShaderProgram.isSupported()");
		return program;
	}

	private String shaderTypeString(int type) {
		if (type==FRAGMENT_SHADER) return "FRAGMENT_SHADER";
		else if (type==VERTEX_SHADER) return "VERTEX_SHADER";
		else if (type==GL32.GL_GEOMETRY_SHADER) return "GEOMETRY_SHADER";
		else return "shader";
	}

	/**
	 * Compiles a shader from source and returns its handle. If the compilation failed,
	 * a SlickException will be thrown. If the compilation had error, info or warnings messages,
	 * they will be appended to this program's log.
	 *
	 * @param type the type to use in compilation
	 * @param source the source code to compile
	 * @return the resulting ID
	 * @throws SlickException if compilation was unsuccessful
	 */
	protected int compileShader(int type, String source) throws SlickException {
		int shader = ARBShaderObjects.glCreateShaderObjectARB(type);
		if (shader==0)
			throw new SlickException("could not create shader object; check ShaderProgram.isSupported()");
		ARBShaderObjects.glShaderSourceARB(shader, source);
		ARBShaderObjects.glCompileShaderARB(shader);
		int comp = ARBShaderObjects.glGetObjectParameteriARB(shader, GL20.GL_COMPILE_STATUS);
		int len = ARBShaderObjects.glGetObjectParameteriARB(shader, GL20.GL_INFO_LOG_LENGTH);
		String t = shaderTypeString(type);
		String err = ARBShaderObjects.glGetInfoLogARB(shader, len);
		if (err!=null&&err.length()!=0)
			log += t+" compile log:\n"+err+"\n";
		if (comp==GL11.GL_FALSE)
			throw new SlickException(log);
		return shader;
	}

	/**
	 * Called to attach vertex and fragment; users may override this for more specific purposes.
	 */
	protected void attachShaders() {
		ARBShaderObjects.glAttachObjectARB(getID(), vert);
		ARBShaderObjects.glAttachObjectARB(getID(), frag);
	}

	/**
	 * Calls attachShaders and links the program.
	 *
	 * @throws SlickException
	 *             if this program is invalid (released) or
	 *             if the link was unsuccessful
	 */
	protected void linkProgram() throws SlickException {
		if (!valid())
			throw new SlickException("trying to link an invalid (i.e. released) program");

		uniforms.clear();
		attributes.clear();

		attachShaders();

        ARBShaderObjects.glLinkProgramARB(program);
        int comp = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_LINK_STATUS);
        int len = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_INFO_LOG_LENGTH);
		String err = ARBShaderObjects.glGetInfoLogARB(program, len);
		if (err!=null&&err.length()!=0) log = err + "\n" + log;
		if (log!=null) log = log.trim();
        if (comp==GL11.GL_FALSE)
			throw new SlickException(log);

        fetchUniforms();
		fetchAttributes();
	}

	/**
	 * Returns the full log of compiling/linking errors, info, warnings, etc.
	 * @return the full log of this ShaderProgram
	 */
	public String getLog() {
		return log;
	}

	/**
	 * Enables this shader for use -- only one shader can be bound at a time. Calling
	 * bind() when another program is bound will simply make this object the active program.
	 * @throw IllegalStateException if this program is invalid
	 */
	public void bind() {
		if (!valid())
			throw new IllegalStateException("trying to enable a program that is not valid");
		ARBShaderObjects.glUseProgramObjectARB(program);
	}

	/**
	 * Unbinds all shaders; this is the equivalent of ShaderProgram.unbindAll(), and only included
	 * for consistency with bind() and the rest of the API (i.e. startUse/endUse). Users do not need to unbind
	 * one shader before binding a new one.
	 */
	public void unbind() {
		ShaderProgram.unbindAll();
	}

	/**
	 * Disables shaders (unbind), then detaches and releases the shaders associated with this program.
	 * This can be called after linking a program in order to free up memory (as the shaders are no longer needed),
	 * however, since it is not a commonly used feature and thus not well tested on all drivers,
	 * it should be used with caution.
	 * Shaders shouldn't be used after being released.
	 */
	public void releaseShaders() {
		unbind();
		if (vert!=0) {
			ARBShaderObjects.glDetachObjectARB(getID(), vert);
			ARBShaderObjects.glDeleteObjectARB(vert);
			vert = 0;
		}
		if (frag!=0) {
			ARBShaderObjects.glDetachObjectARB(getID(), frag);
			ARBShaderObjects.glDeleteObjectARB(frag);
			frag = 0;
		}
	}

	/**
	 * If this program has not yet been released, this will disable shaders (unbind),
	 * then releases this program and its shaders. To only release
	 * the shaders (not the program itself), call releaseShaders().
	 * Programs will be considered "invalid" after being released, and should no longer be used.
	 */
	public void release() {
		if (program!=0) {
			unbind();
			releaseShaders();
			ARBShaderObjects.glDeleteObjectARB(program);
			program = 0;
		}
	}

	/**
	 * Returns the OpenGL handle for this program's vertex shader.
	 * @return the vertex ID
	 */
	public int getVertexShaderID() {
		return vert;
	}

	/**
	 * Returns the OpenGL handle for this program's fragment shader.
	 * @return the fragment ID
	 */
	public int getFragmentShaderID() {
		return frag;
	}

	/**
	 * Returns the source code for the vertex shader.
	 * @return the source code
	 */
	public String getVertexShaderSource() {
		return vertShaderSource;
	}

	/**
	 * Returns the source code for the fragment shader.
	 * @return the source code
	 */
	public String getFragmentShaderSource() {
		return fragShaderSource;
	}

	/**
	 * Returns the OpenGL handle for this shader program
	 * @return the program ID
	 */
	public int getID() {
		return program;
	}

	/**
	 * A shader program is "valid" if it's ID is not zero. Upon
	 * releasing a program, the ID will be set to zero.
	 *
	 * @return whether this program is valid
	 */
	public boolean valid() {
		return program != 0;
	}

	private void fetchUniforms() {
		int len = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_ACTIVE_UNIFORMS);
		//max length of all uniforms stored in program
		int strLen = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_ACTIVE_UNIFORM_MAX_LENGTH);

		for (int i=0; i<len; i++) {
			String name = ARBShaderObjects.glGetActiveUniformARB(program, i, strLen);
			int id = ARBShaderObjects.glGetUniformLocationARB(program, name);
			uniforms.put(name, id);
		}
	}

	private void fetchAttributes() {
		int len = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_ACTIVE_ATTRIBUTES);
		//max length of all attributes stored in program
		int strLen = ARBShaderObjects.glGetObjectParameteriARB(program, GL20.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
		for (int i=0; i<len; i++) {
			String name = ARBVertexShader.glGetActiveAttribARB(program, i, strLen);
			int id = ARBVertexShader.glGetAttribLocationARB(program, name);
			attributes.put(name, id);
		}
	}

	/**
	 * Returns the ID of the given uniform.
	 * @param name the uniform name
	 * @return the ID (location) in the shader program
	 */
	public int getUniformID(String name) {
		Integer locI = uniforms.get(name);
		int location = locI==null ? -1 : locI.intValue();
		if (location!=-1)
			return location;
		location = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if (location == -1 && strict)
			throw new IllegalArgumentException("no active uniform by name '"+name+"' (disable strict compiling to suppress warnings)");
		uniforms.put(name, location);
		return location;
	}

	/**
	 * Returns the ID of the given attribute.
	 * @param name the attribute name
	 * @return the ID (location) in the shader program
	 */
	public int getAttributeID(String name) {
		int location = attributes.get(name);
		if (location!=-1)
			return location;
		location = ARBVertexShader.glGetAttribLocationARB(program, name);
		if (location == -1 && strict)
			throw new IllegalArgumentException("no active attribute by name '"+name+"'");
		attributes.put(name, location);
		return location;
	}

	/**
	 * Returns the names of all active attributes that were found
	 * when linking the program.
	 * @return an array list of active attribute names
	 */
	public String[] getAttributes() {
		return attributes.keySet().toArray(new String[attributes.size()]);
	}

	/**
	 * Returns the names of all active uniforms that were found
	 * when linking the program.
	 * @return an array list of active uniform names
	 */
	public String[] getUniformNames() {
		return uniforms.keySet().toArray(new String[uniforms.size()]);
	}

	/**
	 * Enables the vertex array -- in strict mode, if the vertex attribute
	 * is not found (or it's inactive), an IllegalArgumentException will
	 * be thrown. If strict mode is disabled and the vertex attribute
	 * is not found, this method will return <tt>false</tt> otherwise it
	 * will return <tt>true</tt>.
	 *
	 * @param name the name of the vertex attribute to enable
	 * @return false if strict mode is disabled and this attribute couldn't be found
	 */
	public boolean enableVertexAttribute(String name) {
		int id = getAttributeID(name);
		if (id==-1) return false;
		ARBVertexShader.glEnableVertexAttribArrayARB(id);
		return true;
	}

	/**
	 * Disables the vertex array -- in strict mode, if the vertex attribute
	 * is not found (or it's inactive), an IllegalArgumentException will
	 * be thrown. If strict mode is disabled and the vertex attribute
	 * is not found, this method will return <tt>false</tt> otherwise it
	 * will return <tt>true</tt>.
	 *
	 * @param name the name of the vertex attribute to disable
	 * @return false if strict mode is disabled and this attribute couldn't be found
	 */
	public boolean disableVertexAttribute(String name) {
		int id = getAttributeID(name);
		if (id==-1) return false;
		ARBVertexShader.glDisableVertexAttribArrayARB(id);
		return true;
	}

//	public void setVertexAttribute(String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) {
//		ARBVertexShader.glVertexAttrib
//	}

	/**
	 * Sets the value of an RGBA vec4 uniform to the given color
	 * @param name the RGBA vec4 uniform
	 * @param color the color to assign
	 */
	public void setUniform4f(String name, Color color) {
		setUniform4f(name, color.r, color.g, color.b, color.a);
	}

	/**
	 * Sets the value of a vec2 uniform to the given Vector2f.
	 * @param name the vec2 uniform
	 * @param vec the vector to use
	 */
	public void setUniform2f(String name, Vector2f vec) {
		setUniform2f(name, vec.x, vec.y);
	}

	private FloatBuffer uniformf(String name) {
		if (buf4==null)
			buf4 = BufferUtils.createFloatBuffer(4);
		buf4.clear();
		getUniform(name, buf4);
		return buf4;
	}

	private IntBuffer uniformi(String name) {
		//TODO: add setters/getters for ivec2, ivec3, ivec4
		if (ibuf4==null)
			ibuf4 = BufferUtils.createIntBuffer(4);
		ibuf4.clear();
		getUniform(name, ibuf4);
		return ibuf4;
	}

	/**
	 * A convenience method to retrieve an integer/sampler2D uniform.
	 * @param name the uniform name
	 * @return the value
	 */
	public int getUniform1i(String name) {
		return uniformi(name).get(0);
	}

	/**
	 * A convenience method to retrieve an ivec2 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, IntBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created int[] array with 2 elements; e.g. (x, y)
	 */
	public int[] getUniform2i(String name) {
		IntBuffer buf = uniformi(name);
		return new int[] { buf.get(0), buf.get(1) };
	}

	/**
	 * A convenience method to retrieve an ivec3 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, IntBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created int[] array with 3 elements; e.g. (x, y, z)
	 */
	public int[] getUniform3i(String name) {
		IntBuffer buf = uniformi(name);
		return new int[] { buf.get(0), buf.get(1), buf.get(2) };
	}

	/**
	 * A convenience method to retrieve an ivec4 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, IntBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created int[] array with 2 elements; e.g. (r, g, b, a)
	 */
	public int[] getUniform4i(String name) {
		IntBuffer buf = uniformi(name);
		return new int[] { buf.get(0), buf.get(1), buf.get(2), buf.get(3) };
	}

	/**
	 * A convenience method to retrieve a float uniform.
	 * @param name the uniform name
	 * @return the value
	 */
	public float getUniform1f(String name) {
		return uniformf(name).get(0);
	}

	/**
	 * A convenience method to retrieve a vec2 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, FloatBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created float[] array with 2 elements; e.g. (x, y)
	 */
	public float[] getUniform2f(String name) {
		FloatBuffer buf = uniformf(name);
		return new float[] { buf.get(0), buf.get(1) };
	}

	/**
	 * A convenience method to retrieve a vec3 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, FloatBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created float[] array with 3 elements; e.g. (x, y, z)
	 */
	public float[] getUniform3f(String name) {
		FloatBuffer buf = uniformf(name);
		return new float[] { buf.get(0), buf.get(1), buf.get(2) };
	}

	/**
	 * A convenience method to retrieve a vec4 uniform;
	 * for maximum performance and memory efficiency you
	 * should use getUniform(String, FloatBuffer) with a shared
	 * buffer.
	 * @param name the name of the uniform
	 * @return a newly created float[] array with 4 elements; e.g. (r, g, b, a)
	 */
	public float[] getUniform4f(String name) {
		FloatBuffer buf = uniformf(name);
		return new float[] { buf.get(0), buf.get(1), buf.get(2), buf.get(3) };
	}

	/**
	 * Retrieves data from a uniform and places it in the given buffer. If
	 * strict mode is enabled, this will throw an IllegalArgumentException
	 * if the given uniform is not 'active' -- i.e. if GLSL determined that
	 * the shader isn't using it. If strict mode is disabled, this method will
	 * return <tt>true</tt> if the uniform was found, and <tt>false</tt> otherwise.
	 *
	 * @param name the name of the uniform
	 * @param buf the buffer to place the data
	 * @return true if the uniform was found, false if there is no active uniform by that name
	 */
	public boolean getUniform(String name, FloatBuffer buf) {
		int id = getUniformID(name);
		if (id==-1) return false;
		ARBShaderObjects.glGetUniformARB(program, id, buf);
		return true;
	}

	/**
	 * Retrieves data from a uniform and places it in the given buffer. If
	 * strict mode is enabled, this will throw an IllegalArgumentException
	 * if the given uniform is not 'active' -- i.e. if GLSL determined that
	 * the shader isn't using it. If strict mode is disabled, this method will
	 * return <tt>true</tt> if the uniform was found, and <tt>false</tt> otherwise.
	 *
	 * @param name the name of the uniform
	 * @param buf the buffer to place the data
	 * @return true if the uniform was found, false if there is no active uniform by that name
	 */
	public boolean getUniform(String name, IntBuffer buf) {
		int id = getUniformID(name);
		if (id==-1) return false;
		ARBShaderObjects.glGetUniformARB(program, id, buf);
		return true;
	}

	/**
	 * Whether the shader program was linked with the active uniform by the given name. A
	 * uniform might be "inactive" even if it was declared at the top of a shader;
	 * if GLSL finds that a uniform isn't needed (i.e. not used in shader), then
	 * it will not be active.
	 * @param name the name of the uniform
	 * @return true if this shader program could find the active uniform
	 */
	public boolean hasUniform(String name) {
		return uniforms.containsKey(name);
	}

	/**
	 * Whether the shader program was linked with the active attribute by the given name. A
	 * attribute might be "inactive" even if it was declared at the top of a shader;
	 * if GLSL finds that a attribute isn't needed (i.e. not used in shader), then
	 * it will not be active.
	 * @param name the name of the attribute
	 * @return true if this shader program could find the active attribute
	 */
	public boolean hasAttribute(String name) {
		return attributes.containsKey(name);
	}

	/**
	 * Sets the value of a float uniform.
	 * @param name the uniform by name
	 * @param f the float value
	 */
	public void setUniform1f(String name, float f) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform1fARB(id, f);
	}

	/**
	 * Sets the value of a sampler2D uniform.
	 * @param name the uniform by name
	 * @param i the integer / active texture (e.g. 0 for TEXTURE0)
	 */
	public void setUniform1i(String name, int i) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform1iARB(id, i);
	}

	/**
	 * Sets the value of a vec2 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / tex.s
	 * @param b vec.y / tex.t
	 */
	public void setUniform2f(String name, float a, float b) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform2fARB(id, a, b);
	}

	/**
	 * Sets the value of a vec3 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / color.r / tex.s
	 * @param b vec.y / color.g / tex.t
	 * @param c vec.z / color.b / tex.p
	 */
	public void setUniform3f(String name, float a, float b, float c) {
		int id = getUniformID(name);
		if (id==-1) return;

		ARBShaderObjects.glUniform3fARB(id, a, b, c);
	}

	/**
	 * Sets the value of a vec4 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / color.r
	 * @param b vec.y / color.g
	 * @param c vec.z / color.b
	 * @param d vec.w / color.a
	 */
	public void setUniform4f(String name, float a, float b, float c, float d) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform4fARB(id, a, b, c, d);
	}

	/**
	 * Sets the value of a ivec2 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / tex.s
	 * @param b vec.y / tex.t
	 */
	public void setUniform2i(String name, int a, int b) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform2iARB(id, a, b);
	}

	/**
	 * Sets the value of a ivec3 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / color.r
	 * @param b vec.y / color.g
	 * @param c vec.z / color.b
	 */
	public void setUniform3i(String name, int a, int b, int c) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform3iARB(id, a, b, c);
	}

	/**
	 * Sets the value of a ivec4 uniform.
	 * @param name the uniform by name
	 * @param a vec.x / color.r
	 * @param b vec.y / color.g
	 * @param c vec.z / color.b
	 * @param d vec.w / color.a
	 */
	public void setUniform4i(String name, int a, int b, int c, int d) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniform4iARB(id, a, b, c, d);
	}

	/**
	 * Sets a uniform matrix2 with the given name and transpose.
	 * @param name the name to use
	 * @param transpose whether to transpose the matrix
	 * @param buf the buffer representing the matrix2
	 */
	public void setMatrix2(String name, boolean transpose, FloatBuffer buf) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniformMatrix2ARB(id, transpose, buf);
	}

	/**
	 * Sets a uniform matrix3 with the given name and transpose.
	 * @param name the name to use
	 * @param transpose whether to transpose the matrix
	 * @param buf the buffer representing the matrix3
	 */
	public void setMatrix3(String name, boolean transpose, FloatBuffer buf) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniformMatrix3ARB(id, transpose, buf);
	}

	/**
	 * Sets a uniform matrix4 with the given name and transpose.
	 * @param name the name to use
	 * @param transpose whether to transpose the matrix
	 * @param buf the buffer representing the matrix4
	 */
	public void setMatrix4(String name, boolean transpose, FloatBuffer buf) {
		int id = getUniformID(name);
		if (id==-1) return;
		ARBShaderObjects.glUniformMatrix4ARB(id, transpose, buf);
	}
}


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ExtensionMethods_1 = require("../../ExtensionMethods");
var RuleCollection_1 = require("../../ComplexProperties/RuleCollection");
var XmlElementNames_1 = require("../XmlElementNames");
var ServiceResponse_1 = require("./ServiceResponse");
/**
 * @internal Represents the response to a GetInboxRules operation.
 *
 * @sealed
 */
var GetInboxRulesResponse = (function (_super) {
    __extends(GetInboxRulesResponse, _super);
    /**
     * @internal Initializes a new instance of the **GetInboxRulesResponse** class.
     */
    function GetInboxRulesResponse() {
        _super.call(this);
        this.ruleCollection = new RuleCollection_1.RuleCollection();
    }
    Object.defineProperty(GetInboxRulesResponse.prototype, "Rules", {
        /**
         * @internal Gets the rule collection in the response.
         */
        get: function () {
            return this.ruleCollection;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @internal Reads response elements from Xml JsObject.
     *
     * @param   {any}               jsObject   The response object.
     * @param   {ExchangeService}   service    The service.
     */
    GetInboxRulesResponse.prototype.ReadElementsFromXmlJsObject = function (responseObject, service) {
        this.ruleCollection.OutlookRuleBlobExists = ExtensionMethods_1.Convert.toBool(responseObject[XmlElementNames_1.XmlElementNames.OutlookRuleBlobExists]);
        if (responseObject[XmlElementNames_1.XmlElementNames.InboxRules]) {
            this.ruleCollection.LoadFromXmlJsObject(responseObject[XmlElementNames_1.XmlElementNames.InboxRules], service);
        }
    };
    return GetInboxRulesResponse;
}(ServiceResponse_1.ServiceResponse));
exports.GetInboxRulesResponse = GetInboxRulesResponse;

redpajama_set_name: RedPajamaGithub


text:
package com.amashchenko.eclipse.strutsclipse.strutsxml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.wst.validation.ValidationResult;
import org.eclipse.wst.validation.ValidationState;

import com.amashchenko.eclipse.strutsclipse.AbstractXmlValidator;
import com.amashchenko.eclipse.strutsclipse.ProjectUtil;
import com.amashchenko.eclipse.strutsclipse.xmlparser.ElementRegion;
import com.amashchenko.eclipse.strutsclipse.xmlparser.TagGroup;
import com.amashchenko.eclipse.strutsclipse.xmlparser.TagRegion;

public class StrutsXmlValidator extends AbstractXmlValidator {
	private static final String PROBLEM_MARKER_ID = "com.amashchenko.eclipse.strutsclipse.strutsxmlproblemmarker";

	private static final String DUP_ACTION_MESSAGE_TEXT = "Duplicate action name.";
	private static final String DUP_PACKAGE_MESSAGE_TEXT = "Duplicate package name.";
	private static final String DUP_CONSTANT_MESSAGE_TEXT = "Duplicate constant name.";
	private static final String NO_METHOD_MESSAGE_TEXT = "No such method.";

	private final StrutsXmlParser strutsXmlParser;

	public StrutsXmlValidator() {
		strutsXmlParser = new StrutsXmlParser();
	}

	@Override
	protected String getProblemMarkerId() {
		return PROBLEM_MARKER_ID;
	}

	@Override
	public ValidationResult validate(IResource resource, int kind,
			ValidationState state, IProgressMonitor monitor) {
		IDocument document = null;
		// get document
		try {
			final IDocumentProvider provider = new TextFileDocumentProvider();
			provider.connect(resource);
			document = provider.getDocument(resource);
			provider.disconnect(resource);
		} catch (CoreException e) {
			e.printStackTrace();
		}

		ValidationResult result = new ValidationResult();
		if (document != null) {
			// validate constants
			List<ElementRegion> constantNameRegions = strutsXmlParser
					.getConstantNameRegions(document);
			validateRegions(resource, document, result, constantNameRegions,
					DUP_CONSTANT_MESSAGE_TEXT, IMarker.SEVERITY_WARNING);

			// validate packages
			List<ElementRegion> packageNameRegions = strutsXmlParser
					.getPackageNameRegions(document);
			validateRegions(resource, document, result, packageNameRegions,
					DUP_PACKAGE_MESSAGE_TEXT, IMarker.SEVERITY_WARNING);

			// validate actions
			Map<String, TagGroup> actionRegions = strutsXmlParser
					.getNamespacedActionTagRegions(document);

			Map<String, ElementRegion> dupCheckMap = new HashMap<String, ElementRegion>();
			List<String> reportedActions = new ArrayList<String>();

			for (Entry<String, TagGroup> entr : actionRegions.entrySet()) {
				for (TagRegion tagRegion : entr.getValue().getTagRegions()) {
					if (tagRegion.getAttrs() != null) {
						// check duplicate action names
						ElementRegion nameAttr = tagRegion.getAttrs().get(
								StrutsXmlConstants.NAME_ATTR);
						if (nameAttr != null) {
							String actionName = entr.getKey()
									+ nameAttr.getValue();
							if (dupCheckMap.containsKey(actionName)) {
								result.add(createMessage(resource, document,
										nameAttr.getValueRegion(),
										IMarker.SEVERITY_WARNING,
										DUP_ACTION_MESSAGE_TEXT));

								if (!reportedActions.contains(actionName)) {
									reportedActions.add(actionName);
									result.add(createMessage(resource,
											document,
											dupCheckMap.get(actionName)
													.getValueRegion(),
											IMarker.SEVERITY_WARNING,
											DUP_ACTION_MESSAGE_TEXT));
								}
							} else {
								dupCheckMap.put(actionName, nameAttr);
							}
						}

						// check method existence
						ElementRegion methodAttr = tagRegion.getAttrs().get(
								StrutsXmlConstants.METHOD_ATTR);
						String classAttrVal = tagRegion.getAttrValue(
								StrutsXmlConstants.CLASS_ATTR, null);
						if (classAttrVal != null && methodAttr != null) {
							String methodAttrValue = methodAttr.getValue();

							// skip wildcard methods
							if (methodAttrValue.indexOf('{') == -1) {
								IType clazz = ProjectUtil.findClass(document,
										classAttrVal);
								// skip methods with unknown class
								if (clazz != null) {
									IMethod method = ProjectUtil
											.findClassParameterlessMethod(
													clazz, methodAttrValue);
									if (method == null) {
										result.add(createMessage(resource,
												document,
												methodAttr.getValueRegion(),
												IMarker.SEVERITY_ERROR,
												NO_METHOD_MESSAGE_TEXT));
									}
								}
							}
						}
					}
				}
			}
		}

		return result;
	}
}


text:
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Cogito
{

    /// <summary>
    /// Provides extensions against <see cref="uint"/> values.
    /// </summary>
    public static class UInt32Extensions
    {

        /// <summary>
        /// Calculates the number of trailing zeros in the given unsigned integer.
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int CountLeadingZeros(this uint n)
        {
#if NET5_0 || NETCOREAPP3_0
            return BitOperations.LeadingZeroCount(n);
#else
            if (n == 0)
                return 32;

            return 31 - Log2SoftwareFallback(n);
#endif
        }

        static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
        {
            00, 09, 01, 10, 13, 21, 02, 29,
            11, 14, 16, 18, 22, 25, 03, 30,
            08, 12, 20, 28, 15, 17, 24, 07,
            19, 27, 23, 06, 26, 05, 04, 31
        };

        static int Log2SoftwareFallback(uint value)
        {
            // No AggressiveInlining due to large method size
            // Has conventional contract 0->0 (Log(0) is undefined)

            // Fill trailing zeros with ones, eg 00010010 becomes 00011111
            value |= value >> 01;
            value |= value >> 02;
            value |= value >> 04;
            value |= value >> 08;
            value |= value >> 16;

            // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
            return Unsafe.AddByteOffset(
                // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u
                ref MemoryMarshal.GetReference(Log2DeBruijn),
                // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
                (IntPtr)(int)((value * 0x07C4ACDDu) >> 27));
        }

    }

}


text:
using System;

namespace Dragon.Diagnostics
{
    public abstract class DiagnosticsModuleBase<TOptions> : IDiagnosticModule<TOptions> where TOptions : DiagnosticsOptionsBase
    {
        protected string Log;

        public string Execute(TOptions options)
        {
            if (options.Disabled)
            {
                DebugMessage(GetType().Name + " is disabled, skipping.");
                return Log;
            }
            ExecuteImpl(options);
            return Log;
        }

        protected abstract void ExecuteImpl(TOptions options);

        protected void DebugMessage(string message)
        {
            Console.WriteLine(message);
            Log += message + Environment.NewLine;
        }

    }
}


text:
module Spree
  module PermissionSets
    class ProductManagement < PermissionSets::Base
      def activate!
        can :manage, Spree::Classification
        can :manage, Spree::Image
        can :manage, Spree::OptionType
        can :manage, Spree::OptionValue
        can :manage, Spree::Price
        can :manage, Spree::Product
        can :manage, Spree::ProductProperty
        can :manage, Spree::Property
        can :manage, Spree::Taxon
        can :manage, Spree::Taxonomy
        can :manage, Spree::Variant
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;

namespace Stripe
{
    public class StripeCustomer : StripeObject
    {
        [JsonProperty("object")]
        public string Object { get; set; }

        [JsonProperty("livemode")]
        public bool? LiveMode { get; set; }

        [JsonProperty("cards")]
        public StripeCardList StripeCardList { get; set; }

        [JsonProperty("created")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime Created { get; set; }

        [JsonProperty("account_balance")]
        public int? AccountBalance { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        public string StripeDefaultCardId { get; set; }
        public StripeCard StripeDefaultCard { get; set; }

        [JsonProperty("default_card")]
        internal object InternalDefaultCard
        {
            set
            {
                ExpandableProperty<StripeCard>.Map(value, s => StripeDefaultCardId = s, o => StripeDefaultCard = o);
            }
        }

        [JsonProperty("delinquent")]
        public bool Delinquent { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("discount")]
        public StripeDiscount StripeDiscount { get; set; }

        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        [JsonProperty("subscriptions")]
        public StripeSubscriptionList StripeSubscriptionList { get; set; }

        [JsonProperty("deleted")]
        public bool? Deleted { get; set; }
    }
}


text:
package com.founder.fix.fixflow.expand.identity;

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

import com.founder.fix.bpmn2extensions.coreconfig.UserInfo;
import com.founder.fix.fixflow.core.cache.CacheHandler;
import com.founder.fix.fixflow.core.db.pagination.Pagination;
import com.founder.fix.fixflow.core.exception.FixFlowException;
import com.founder.fix.fixflow.core.impl.Context;
import com.founder.fix.fixflow.core.impl.Page;
import com.founder.fix.fixflow.core.impl.db.SqlCommand;
import com.founder.fix.fixflow.core.impl.identity.GroupDefinition;
import com.founder.fix.fixflow.core.impl.identity.GroupTo;
import com.founder.fix.fixflow.core.impl.identity.UserTo;
import com.founder.fix.fixflow.core.impl.util.StringUtil;

public class GroupDefinitionImpl extends GroupDefinition {

	@Override
	public GroupTo findGroupByGroupId(String groupId) {
		// TODO Auto-generated method stub
		if (groupId == null || groupId.equals("")) {
			return null;
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findGroupByGroupId_" + groupId);
		if (cacheData != null) {
			return (GroupTo) cacheData;
		} else {
			try {
				String groupIdField = getGroupInfo().getGroupIdField();
				String groupNameField = getGroupInfo().getGroupNameField();
				String sqlText = getGroupInfo().getSqlText();
				SqlCommand sqlCommand = getSqlCommand();
				List<Object> objectParamWhere = new ArrayList<Object>();
				objectParamWhere.add(groupId);
				List<Map<String, Object>> dataObj = sqlCommand.queryForList("SELECT USERTABLE.* FROM (" + sqlText + ") USERTABLE where USERTABLE."
						+ groupIdField + "=?", objectParamWhere);
				if (dataObj.size() == 0) {
					return null;
				}
				if (dataObj.get(0).get(groupIdField) == null) {
					return null;
				}
				GroupTo groupTo = new GroupTo(groupId, StringUtil.getString(dataObj.get(0).get(groupNameField)), getId(), dataObj.get(0));
				cache.putCacheData(getId() + "_findGroupByGroupId_" + groupId, groupTo);
				return groupTo;
			} catch (Exception e) {
				e.printStackTrace();
				throw new FixFlowException("获取" + getGroupInfo().getGroupName() + "信息出错!", e);
			}
		}
	}

	public Map<String,Object> findGroups(Page page, Map<String, Object> queryMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		List<GroupTo> resultList = new ArrayList<GroupTo>();
		try {
			String groupIdField = getGroupInfo().getGroupIdField();
			String groupNameField = getGroupInfo().getGroupNameField();
			String supIdField = getGroupInfo().getSupGroupIdField();
			String sqlText = getGroupInfo().getSqlText();
			SqlCommand sqlCommand = getSqlCommand();
			String sql = "SELECT USERTABLE.* FROM (" + sqlText + ") USERTABLE where 1=1";
			String countSql = "SELECT count(*) FROM (" + sqlText + ") USERTABLE where 1=1";
			String whereSql = "";
			if(queryMap!= null && queryMap.containsKey("GROUPID")){
				whereSql += " and " + groupIdField +" like '%"+queryMap.get("GROUPID")+"%'";
			}
			if(queryMap!= null && queryMap.containsKey("GROUPNAME")){
				whereSql += " and " + groupNameField +" like '%"+queryMap.get("GROUPNAME")+"%'";
			}
			if(queryMap!= null && queryMap.containsKey("SUPID")){
				whereSql += " and (" + supIdField +" = '"+queryMap.get("SUPID")+"' or "+groupIdField+"='"+queryMap.get("SUPID")+"')";
			}
			sql += whereSql;
			countSql += whereSql;

			if (page != null) {
				Pagination pagination = Context.getProcessEngineConfiguration().getDbConfig().getPagination();
				sql = pagination.getPaginationSql(sql, page.getFirstResult(), page.getMaxResults(), "*",null);
			}
			List<Map<String, Object>> dataObj = sqlCommand.queryForList(sql, null);
			int count = Integer.parseInt(sqlCommand.queryForValue(countSql).toString());
			for(int i = 0;i<dataObj.size();i++){
				if (dataObj.get(0).get(groupIdField) != null) {
					GroupTo groupTo = new GroupTo(StringUtil.getString(dataObj.get(i).get(groupIdField)), StringUtil.getString(dataObj.get(i).get(groupNameField)), getId(), dataObj.get(i));
					resultList.add(groupTo);
				}
			}
			resultMap.put("groupList", resultList);
			resultMap.put("count", count);
		} catch (Exception e) {
			e.printStackTrace();
			throw new FixFlowException("获取" + getGroupInfo().getGroupName() + "信息出错!", e);
		}

		return resultMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GroupTo> findGroupMembersByUser(String userId) {
		if (userId == null || userId.equals("")) {
			throw new FixFlowException("查询的用户编号不能为空");
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findGroupMembersByUser_" + userId);
		if (cacheData != null) {
			return (List<GroupTo>) cacheData;
		} else {
			try {
				List<GroupTo> groupTos = new ArrayList<GroupTo>();
				SqlCommand sqlCommand = getSqlCommand();
				List<Object> objectParamWhere = new ArrayList<Object>();
				objectParamWhere.add(userId);
				UserInfo userInfo = getGroupInfo().getUserInfo();
				String userIdField = userInfo.getUserIdField();
				@SuppressWarnings("unused")
				String userNameField = userInfo.getUserNameField();
				String groupIdField = userInfo.getGroupIdField();
				String sqlText = userInfo.getSqlText();
				List<Map<String, Object>> dataObj = sqlCommand.queryForList("SELECT USERTABLE.* FROM (" + sqlText + ") USERTABLE where USERTABLE."
						+ userIdField + "=? AND USERTABLE."+groupIdField+" IS NOT NULL", objectParamWhere);
				if(dataObj.size()==0){
					return groupTos;
				}
				for (Map<String, Object> roleTo : dataObj) {
					GroupTo groupTo = new GroupTo(roleTo.get(groupIdField).toString(), StringUtil.getString(roleTo.get(this.getGroupInfo().getGroupNameField())), getId(),
							roleTo);
					groupTos.add(groupTo);
				}
				cache.putCacheData(getId() + "_findGroupMembersByUser_" + userId, groupTos);
				return groupTos;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				throw new FixFlowException("人员获取" + getGroupInfo().getGroupName() + "出错!", e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GroupTo> findGroupChildMembersByGroupId(String groupId) {
		if (groupId == null || groupId.equals("")) {
			throw new FixFlowException("查询的组编号不能为空");
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findGroupChildMembersByGroupId_" + groupId);
		if (cacheData != null) {
			return (List<GroupTo>) cacheData;
		} else {
			List<GroupTo> groupTos = getGroupChild(groupId, false);
			cache.putCacheData(getId() + "_findGroupChildMembersByGroupId_" + groupId, groupTos);
			return groupTos;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GroupTo> findGroupChildMembersIncludeByGroupId(String groupId) {
		if (groupId == null || groupId.equals("")) {
			throw new FixFlowException("查询的组编号不能为空");
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findGroupChildMembersIncludeByGroupId_" + groupId);
		if (cacheData != null) {
			return (List<GroupTo>) cacheData;
		} else {
			List<GroupTo> groupTos = getGroupChild(groupId, true);
			cache.putCacheData(getId() + "_findGroupChildMembersIncludeByGroupId_" + groupId, groupTos);
			return groupTos;
		}
	}

	private List<GroupTo> getGroupChild(String groupId, boolean include) {
		List<GroupTo> groupTos = new ArrayList<GroupTo>();
		try {
			String groupIdField = getGroupInfo().getGroupIdField();
			String groupNameField = getGroupInfo().getGroupNameField();
			String supGroupIdField = getGroupInfo().getSupGroupIdField();
			String sqlText = getGroupInfo().getSqlText();
			SqlCommand sqlCommand = getSqlCommand();
			// 部门编号,父级编号,部门名称
			// 获取这个部门的所有子部门
			List<Map<String, Object>> listMap = sqlCommand.queryForList("SELECT USERTABLE.* FROM (" + sqlText + ") USERTABLE");
			for (Map<String, Object> map : listMap) {
				// 部门编号
				String groupDbId = StringUtil.getString(StringUtil.getString(map.get(groupIdField)));
				// 部门名称
				String groupDbName = StringUtil.getString(StringUtil.getString(map.get(groupNameField)));
				String supGroupDbId = StringUtil.getString(StringUtil.getString(map.get(supGroupIdField)));
				// 部门编号不能为空
				if (StringUtil.isNotEmpty(groupDbId)) {
					// 这里查询出来的结果集会带有父节点本身,父节点本身不需要再递归了。
					if (groupDbId.equals(groupId) && include) {
						// 父节点处理方式,不递归。
						GroupTo groupTo = new GroupTo(groupDbId, groupDbName, getId(), map);
						groupTos.add(groupTo);
					} else {
						if (StringUtil.isNotEmpty(supGroupDbId)) {
							if (supGroupDbId.equals(groupId)) {
								// 子节点处理方式,递归。
								GroupTo groupTo = new GroupTo(groupDbId, groupDbName, getId(), map);
								groupTos.add(groupTo);
								// 递归查找子部门
								findGroupSub(listMap, groupDbId, groupTos);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new FixFlowException("获取子" + getGroupInfo().getGroupName() + "信息出错!", e);
		}
		return groupTos;
	}

	/**
	 * 递归查找子组
	 * @param dt 数据集合
	 * @param id 父亲编号
	 * @param result 返回结果
	 */
	private void findGroupSub(List<Map<String, Object>> listMap, String id, List<GroupTo> groupTos) {
		String groupIdField = getGroupInfo().getGroupIdField();
		String groupNameField = getGroupInfo().getGroupNameField();
		String supGroupIdField = getGroupInfo().getSupGroupIdField();
		for (Map<String, Object> map : listMap) {
			String tmpsupid = StringUtil.getString(map.get(supGroupIdField));
			String tmpid = StringUtil.getString(map.get(groupIdField));
			String tmpName = StringUtil.getString(map.get(groupNameField));
			if (tmpid != null && !tmpid.equals("")) {
				if (tmpsupid != null && tmpsupid.equals(id)) {
					GroupTo groupTo = new GroupTo(tmpid, tmpName, getId(), map);
					groupTos.add(groupTo);
					findGroupSub(listMap, tmpid, groupTos);
				}
			}

		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserTo> findUserChildMembersIncludeByGroupId(String groupId) {
		if (groupId == null || groupId.equals("")) {
			throw new FixFlowException("查询的组编号不能为空");
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findUserChildMembersIncludeByGroupId_" + groupId);
		if (cacheData != null) {
			return (List<UserTo>) cacheData;
		} else {
			try {
				SqlCommand sqlCommand = getSqlCommand();
				List<GroupTo> groupTos = getGroupChild(groupId, true);
				List<Object> objectParamWhere = new ArrayList<Object>();
				String sqlInString = "";
				for (GroupTo groupTo : groupTos) {
					if (sqlInString.equals("")) {
						sqlInString = "?";
						objectParamWhere.add(groupTo.getGroupId());
					} else {
						sqlInString = sqlInString + ",?";
						objectParamWhere.add(groupTo.getGroupId());
					}
				}
				UserInfo userInfo = getGroupInfo().getUserInfo();
				String userIdField = userInfo.getUserIdField();
				String userNameField = userInfo.getUserNameField();
				String groupIdField = userInfo.getGroupIdField();
				String sqlText = userInfo.getSqlText();
				// 这里可能会出现重复记录人名的问题
				List<Map<String, Object>> dataObj = sqlCommand.queryForList("select USERTABLE.* FROM (" + sqlText + ") USERTABLE WHERE USERTABLE."
						+ groupIdField + " in (" + sqlInString + ")", objectParamWhere);
				List<UserTo> userTos = new ArrayList<UserTo>();
				for (Map<String, Object> map : dataObj) {
					UserTo userTo = new UserTo(StringUtil.getString(map.get(userIdField)), StringUtil.getString(map.get(userNameField)), map);
					userTos.add(userTo);
				}
				cache.putCacheData(getId() + "_findUserChildMembersIncludeByGroupId_" + groupId, userTos);
				return userTos;
			} catch (Exception e) {
				e.printStackTrace();
				throw new FixFlowException("从" + getGroupInfo().getGroupName() + "获取用户信息出错!", e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserTo> findUserByGroupId(String groupId) {
		if (groupId == null || groupId.equals("")) {
			throw new FixFlowException("查询的组编号不能为空");
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findUserByGroupId_" + groupId);
		if (cacheData != null) {
			return (List<UserTo>) cacheData;
		} else {
			try {
				SqlCommand sqlCommand = getSqlCommand();
				List<Object> objectParamWhere = new ArrayList<Object>();
				objectParamWhere.add(groupId);
				UserInfo userInfo = getGroupInfo().getUserInfo();
				String userIdField = userInfo.getUserIdField();
				String userNameField = userInfo.getUserNameField();
				String groupIdField = userInfo.getGroupIdField();
				String sqlText = userInfo.getSqlText();
				List<Map<String, Object>> dataObj = sqlCommand.queryForList("SELECT USERTABLE.* FROM (" + sqlText + ") USERTABLE where USERTABLE."
						+ groupIdField + "=?", objectParamWhere);
				List<UserTo> userTos = new ArrayList<UserTo>();
				for (Map<String, Object> map : dataObj) {
					UserTo userTo = new UserTo(StringUtil.getString(map.get(userIdField)), StringUtil.getString(map.get(userNameField)), map);
					userTos.add(userTo);
				}
				cache.putCacheData(getId() + "_findUserByGroupId_" + groupId, userTos);
				return userTos;
			} catch (Exception e) {
				e.printStackTrace();
				throw new FixFlowException("从" + getGroupInfo().getGroupName() + "获取用户信息出错!", e);
			}
		}
	}

	@Override
	public GroupTo findParentGroupByGroupId(String groupId) {
		if (groupId == null || groupId.equals("")) {
			return null;
		}
		CacheHandler cache = Context.getProcessEngineConfiguration().getCacheHandler();
		Object cacheData = cache.getCacheData(getId() + "_findParentGroupByGroupId_" + groupId);
		if (cacheData != null) {
			return (GroupTo) cacheData;
		} else {
			try {
				String groupIdField = getGroupInfo().getGroupIdField();
				String groupNameField = getGroupInfo().getGroupNameField();
				String supGroupIdField = getGroupInfo().getSupGroupIdField();
				String sqlText = getGroupInfo().getSqlText();
				SqlCommand sqlCommand = getSqlCommand();
				List<Object> objectParamWhere = new ArrayList<Object>();
				objectParamWhere.add(groupId);
				List<Map<String, Object>> dataObj = sqlCommand.queryForList(" SELECT USERTABLENEW.* FROM (" + sqlText
						+ ") USERTABLENEW WHERE USERTABLENEW." + groupIdField + " IN (SELECT USERTABLE." + supGroupIdField + " FROM (" + sqlText
						+ ") USERTABLE where USERTABLE." + groupIdField + "=?)", objectParamWhere);
				if (dataObj.size() == 0) {
					return null;
				}
				if (dataObj.get(0).get(groupIdField) == null) {
					return null;
				}
				GroupTo groupTo = new GroupTo(StringUtil.getString(dataObj.get(0).get(groupIdField)), StringUtil.getString(dataObj.get(0).get(groupNameField)), getId(), dataObj.get(0));
				cache.putCacheData(getId() + "_findParentGroupByGroupId_" + groupId, groupTo);
				return groupTo;
			} catch (Exception e) {
				e.printStackTrace();
				throw new FixFlowException("获取" + getGroupInfo().getGroupName() + "信息出错!", e);
			}
		}
	}

}


text:
package com.tuvistavie.xserver.frontend.auth

import play.api.{ Play, Mode }
import scala.util.Random
import java.security.MessageDigest
import sun.misc.BASE64Encoder

import com.tuvistavie.xserver.frontend.util.Config

object UserManager {
  val current = new UserManager {
    implicit val app = Play.current

    val (hasher, tokenGenerator) = Play.mode match {
      case Mode.Prod => (Sha512Hasher, RandomTokenGenerator)
      case _ => (NoOpHasher, SimpleTokenGenerator)
    }
  }
}

trait UserManager {
  protected val hasher: Hasher
  protected val tokenGenerator: TokenGenerator

  private val maxUsers = Config.getInt("application.max_connections")
  private var users = Map[String, User]()
  private val availableIds: Array[Boolean] = Array.fill(maxUsers)(true)

  def canCreateUser = availableIds.exists(_ == true)
  def findUserByToken(token: String) = users.get(token)

  def registerUser(username: String, password: String, properties: UserProperties): User = {
    val id = availableIds.indexOf(true)
    availableIds(id) = false
    val token = hasher.hash(tokenGenerator.generateToken(username, password))
    val user = User(username, id, token, properties)
    users += (token -> user)
    user
  }

  def removeUser(id: Int) = users find { case (k, u) => id == u.id } match {
    case Some((k, u)) => {
      users -= k
      availableIds(u.id) = true
    }
    case None =>
  }
}

trait TokenGenerator {
  def generateToken(username: String, password: String): String
}

object SimpleTokenGenerator extends TokenGenerator {
  override def generateToken(username: String, password: String): String = {
    username + password
  }
}

object RandomTokenGenerator extends TokenGenerator {
  override def generateToken(username: String, password: String): String = {
    val randomString = Random.nextString(Config.getInt("auth.random-string-length"))
    val timeStamp = (System.currentTimeMillis.toString)
    username + randomString + timeStamp + password
  }
}

trait Hasher {
  def hash(str: String): String
}

object NoOpHasher extends Hasher {
  override def hash(str: String) = str
}

trait DigestHasher extends Hasher {
  val hashAlgorithm: String
  override def hash(str: String): String = {
    val md = MessageDigest.getInstance(hashAlgorithm)
    val encoder = new BASE64Encoder()
    encoder.encode(md.digest(str.getBytes))
  }
}

object Sha512Hasher extends DigestHasher {
  override val hashAlgorithm = "SHA-512"
}


text:
#import "ViewController.h"
#import "AppDelegate.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISwitch *subscriptionStatusSwitch;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UILabel *subscriptionStatusLabel;
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoutEmailTrailingSpaceConstraint;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *setEmailActivityIndicatorView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *logoutEmailActivityIndicatorView;
@property (weak, nonatomic) IBOutlet UIButton *setEmailButton;
@end

@implementation ViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    if ([OneSignal getPermissionSubscriptionState].subscriptionStatus.subscribed) {
        self.subscriptionStatusSwitch.on = true;
        self.subscriptionStatusSwitch.userInteractionEnabled = true;
        self.registerButton.backgroundColor = [UIColor greenColor];
        self.registerButton.userInteractionEnabled = false;
    }

    [OneSignal addPermissionObserver:self];
    [OneSignal addSubscriptionObserver:self];
    [OneSignal addEmailSubscriptionObserver:self];

    self.emailTextField.delegate = self;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (AppDelegate*)appDelegate {
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

- (void)displaySettingsNotification {
    UIAlertAction *settings = [UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Tapped Settings");
        if ([[[UIDevice currentDevice] systemVersion] compare:@"10.0" options:NSNumericSearch] != NSOrderedAscending) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];

    [self displayAlert:@"Settings" withMessage:@"Please turn on notifications by going to Settings > Notifications > Allow Notifications" actions:@[settings, cancel]];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)displayError:(NSString *)errorText {
    [self displayAlert:@"An Error Occurred" withMessage:errorText actions:@[]];
}

- (void)displayAlert:(NSString *)title withMessage:(NSString *)message actions:(NSArray<UIAlertAction *>*)actions {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        if (!actions || actions.count == 0) {
            [controller addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:nil]];
        } else {
            for (UIAlertAction *action in actions) {
                [controller addAction:action];
            }
        }
        [self presentViewController:controller animated:true completion:nil];
    });
}

- (void)changeLoadingButtonAnimationStateWithTrailingConstraint:(NSLayoutConstraint *)constraint withActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView animatingState:(BOOL)isAnimating {
    constraint.constant = isAnimating ? 36.0 : 0.0;
    if (isAnimating) {
        [activityIndicatorView startAnimating];
    }

    [UIView animateWithDuration:0.15 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        if (!isAnimating) {
            [activityIndicatorView stopAnimating];
        }
    }];
}

#pragma mark IBActions
- (IBAction)sendTagsButtonPressed:(UIButton *)sender {
    [OneSignal sendTags:@{@"key" : @"value"} onSuccess:^(NSDictionary *result) {
        NSLog(@"success!");
    } onFailure:^(NSError *error) {
        NSLog(@"Error - %@", error.localizedDescription);
    }];
}

- (IBAction)getTagsButtonPressed:(UIButton *)sender {
    [OneSignal getTags:^(NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.textView.text = [NSString stringWithFormat:@"Successfully got tags: \n\n%@", result];
        });
    } onFailure:^(NSError *error) {
        [self displayError:error.localizedDescription];
    }];
}

- (IBAction)updateTagsButtonPressed:(UIButton *)sender {
    NSDictionary *exampleTags = @{@"some_key" : @"some_value", @"users_name" : @"Jon", @"finished_level" : @30, @"has_followers" : @(false), @"added_review" : @(false)};

    [OneSignal sendTags:exampleTags onSuccess:^(NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.textView.text = [NSString stringWithFormat: @"Successfully Sent Tags: \n\n%@", result];
        });
    } onFailure:^(NSError *error) {
        [self displayError:error.localizedDescription];
    }];

}

- (IBAction)getIdsAvailableButtonPressed:(UIButton *)sender {
    [OneSignal IdsAvailable:^(NSString* userId, NSString* pushToken) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (pushToken)
            self.textView.text = [NSString stringWithFormat:@"PlayerId:\n%@\n\nPushToken:\n%@\n", userId, pushToken];
            else
            self.textView.text = @"ERROR: Could not get a pushToken from Apple! Make sure your provisioning profile has 'Push Notifications' enabled and rebuild your app.";

            NSLog(@"\n%@", self.textMultiLine1.text);
        });
    }];
}

- (IBAction)syncEmailButtonPressed:(UIButton *)sender {
    [OneSignal syncHashedEmail:@"test@email.com"];
    NSLog(@"Sync hashed email successful");
}

- (IBAction)promptLocationButtonPressed:(UIButton *)sender {
    [OneSignal promptLocation];
    NSLog(@"Prompted location");
}

- (IBAction)sendFirstExampleNotificationButtonPressed:(UIButton *)sender {
    OSPermissionSubscriptionState *state = [OneSignal getPermissionSubscriptionState];
    NSString *pushToken = state.subscriptionStatus.pushToken;
    NSString *userId = state.subscriptionStatus.userId;

    if (pushToken) {
        NSDictionary *content = @{
          @"include_player_ids" : @[userId],
          @"contents" : @{@"en" : @"This is a notification's message/body"},
          @"headings" : @{@"en" : @"Notification Title"},
          @"subtitle" : @{@"en" : @"An English Subtitle"},
          // If want to open a url with in-app browser
          //"url": "https://google.com",
          // If you want to deep link and pass a URL to your webview, use "data" parameter and use the key in the AppDelegate's notificationOpenedBlock
          @"data" : @{@"OpenURL" : @"https://imgur.com"},
          @"ios_attachments" : @{@"id" : @"https://cdn.pixabay.com/photo/2017/01/16/15/17/hot-air-balloons-1984308_1280.jpg"},
          @"ios_badgeType" : @"Increase",
          @"ios_badgeCount" : @1
        };

        [OneSignal postNotification:content onSuccess:^(NSDictionary *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.textView.text = [NSString stringWithFormat:@"Sent notification with payload: \n\n%@", content];
            });
        } onFailure:^(NSError *error) {
            [self displayError:error.localizedDescription];
        }];
    } else {
        [self displayError:@"Could not send push notification: current user does not have a push token"];
    }
}

- (IBAction)sendSecondExampleNotificationButtonPressed:(UIButton *)sender {
    OSPermissionSubscriptionState *state = [OneSignal getPermissionSubscriptionState];
    NSString *pushToken = state.subscriptionStatus.pushToken;
    NSString *userId = state.subscriptionStatus.userId;

    if (pushToken) {
        NSDictionary *content = @{
          @"include_player_ids" : @[userId],
          @"headings" : @{@"en" : @"Congrats {{username}}!"},
          @"contents" : @{@"en" : @"You finished level {{ finished_level | default: '1'}}! Let's see if you can do more."},
          @"buttons" : @[@{@"id" : @"id1", @"text" : @"green"}, @{@"id" : @"id2", @"text" : @"red"}],
          @"data" : @{@"OpenURL" : @"https://www.arstechnica.com"}
        };

        [OneSignal postNotification:content onSuccess:^(NSDictionary *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.textView.text = [NSString stringWithFormat:@"Successfully sent notification with payload: \n\n%@", content];
            });
        } onFailure:^(NSError *error) {
            [self displayError:error.localizedDescription];
        }];
    } else {
        [self displayError:@"Could not send push notification: current user does not have a push token"];
    }
}

- (IBAction)registerButtonPressed:(UIButton *)sender {
    OSPermissionSubscriptionState *state = [OneSignal getPermissionSubscriptionState];

    if (!state.permissionStatus.hasPrompted) {
        [OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) {
            NSLog(@"User %@ Notifications Permission", accepted ? @"Accepted" : @"Denied");
        }];
    } else {
        [self displaySettingsNotification];
    }
}

- (IBAction)subscriptionSwitchValueChanged:(UISwitch *)sender {
    if (sender.isOn) {
        [OneSignal setSubscription:true];
    } else {
        [OneSignal setSubscription:false];
    }
}

- (IBAction)setEmailButtonPressed:(UIButton *)sender {
    [self.emailTextField resignFirstResponder];

    [self.setEmailActivityIndicatorView startAnimating];
    sender.hidden = true;

    [OneSignal setEmail:self.emailTextField.text withSuccess:^{
        [self.setEmailActivityIndicatorView stopAnimating];
        sender.hidden = false;

    } withFailure:^(NSError *error) {
        [self.setEmailActivityIndicatorView stopAnimating];
        sender.hidden = false;

        [self displayError:error.localizedDescription];
    }];
}

- (IBAction)logoutEmailButtonPressed:(UIButton *)sender {
    [self changeLoadingButtonAnimationStateWithTrailingConstraint:self.logoutEmailTrailingSpaceConstraint withActivityIndicatorView:self.logoutEmailActivityIndicatorView animatingState:true];

    [OneSignal logoutEmailWithSuccess:^{
        [self changeLoadingButtonAnimationStateWithTrailingConstraint:self.logoutEmailTrailingSpaceConstraint withActivityIndicatorView:self.logoutEmailActivityIndicatorView animatingState:false];
    } withFailure:^(NSError *error) {
        [self changeLoadingButtonAnimationStateWithTrailingConstraint:self.logoutEmailTrailingSpaceConstraint withActivityIndicatorView:self.logoutEmailActivityIndicatorView animatingState:false];

        [self displayError:error.localizedDescription];
    }];
}

#pragma mark UITextFieldDelegate Methods
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    return true;
}

#pragma mark OSPermissionStateChanges Delegate Method
-(void)onOSPermissionChanged:(OSPermissionStateChanges *)stateChanges {
    if (stateChanges.from.status == OSNotificationPermissionNotDetermined) {
        if (stateChanges.to.status == OSNotificationPermissionAuthorized) {
            self.registerButton.backgroundColor = [UIColor greenColor];
            self.registerButton.userInteractionEnabled = false;
            self.subscriptionStatusSwitch.userInteractionEnabled = true;
        } else if (stateChanges.to.status == OSNotificationPermissionDenied) {
            [self displaySettingsNotification];
        }
    } else {
        self.registerButton.enabled = true;
        self.subscriptionStatusSwitch.userInteractionEnabled = false;
    }
}

#pragma mark OSSubscriptionStateChanges Delegate Method
-(void)onOSSubscriptionChanged:(OSSubscriptionStateChanges *)stateChanges {
    if (stateChanges.from.subscribed &&  !stateChanges.to.subscribed) {
        self.subscriptionStatusSwitch.on = false;
        self.subscriptionStatusLabel.text = @"Set Subscription OFF";
        self.registerButton.backgroundColor = [UIColor redColor];
    } else if (!stateChanges.from.subscribed && stateChanges.to.subscribed) {
        self.subscriptionStatusSwitch.on = true;
        self.subscriptionStatusLabel.text = @"Set Subscription ON";
        self.registerButton.backgroundColor = [UIColor greenColor];
    }
}

#pragma mark OSEmailSubscriptionStateChanges Delegate Method
-(void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateChanges {
    NSError *error;
    NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:stateChanges.toDictionary options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];
    self.textView.text = jsonString;
}

@end


text:
<!DOCTYPE html>

    <link href="css/awsdocs.css" rel="stylesheet" type="text/css">

    <meta charset="utf-8">

CloudFront Distribution DistributionConfig

DistributionConfig is a property of the AWS::CloudFront::Distribution
                        property that describes which Amazon CloudFront origin servers to get your files from
                        when users
                        request the files through your website or application.

Syntax

JSON

{
   "Aliases" : [ String, ... ],
   "CacheBehaviors" : [ CacheBehavior, ... ],
   "Comment" : String,
   "CustomErrorResponses" : [ CustomErrorResponse, ... ],
   "DefaultCacheBehavior" : DefaultCacheBehavior,
   "DefaultRootObject" : String,
   "Enabled" : Boolean,
   "HttpVersion" : String,
   "IPV6Enabled" : Boolean,
   "Logging" : Logging,
   "Origins" : [ Origin, ... ],
   "PriceClass" : String,
   "Restrictions" : Restriction,
   "ViewerCertificate" : ViewerCertificate,
   "WebACLId" : String
}

YAML

Aliases:
  - String
CacheBehaviors:
  - CacheBehavior
Comment: String
CustomErrorResponses:
  - CustomErrorResponse
DefaultCacheBehavior:
  DefaultCacheBehavior
DefaultRootObject: String
Enabled: Boolean
HttpVersion: String
IPV6Enabled: Boolean
Logging:
  Logging
Origins:
  - Origin
PriceClass: String
Restrictions:
  Restriction
ViewerCertificate:
  ViewerCertificate
WebACLId: String

Properties

Aliases

CNAMEs (alternate domain names), if any, for the distribution.

Required: No

Type: List of String values

Update requires: No interruption

CacheBehaviors

A list of CacheBehavior types for the distribution.

Required: No

Type: List of CloudFront Distribution
                                    CacheBehavior

Update requires: No interruption

Comment

Any comments that you want to include about the distribution. Optional.

When you create a distribution, you can include a comment of up to 128 characters.
                                 You can update the comment at any time.

Required: No

Type: String

Update requires: No interruption

CustomErrorResponses

Whether CloudFront replaces HTTP status codes in the 4xx and
                                 5xx range with custom error messages before returning the response
                                 to the viewer.

Required: No

Type List of CloudFront
                                    Distribution CustomErrorResponse

Update requires: No interruption

DefaultCacheBehavior

The default cache behavior that is triggered if you do not specify the
                                 CacheBehavior property or if files don't match any of the values
                                 of PathPattern in the CacheBehavior property.

Required: Yes

Type: DefaultCacheBehavior type

Update requires: No interruption

DefaultRootObject

The object (such as index.html) that you want CloudFront to request from
                                 your origin when the root URL for your distribution (such as
                                 http://example.com/) is requested.

Note

Specifying a default root object avoids exposing the contents of your distribution.

Required: No

Type: String

Update requires: No interruption

Enabled

Controls whether the distribution is enabled to accept end user requests for content.

Required: Yes

Type: Boolean

Update requires: No interruption

HttpVersion

The latest HTTP version that viewers can use to communicate with CloudFront. Viewers
                                 that don't support the latest version automatically use an earlier HTTP version.
                                 By default, AWS CloudFormation specifies http1.1.

For valid values, see the HttpVersion content for the DistributionConfig data
                                 type in the Amazon CloudFront API Reference.

Required: No

Type: String

Update requires: No interruption

IPV6Enabled

If you want CloudFront to respond to IPv6 DNS requests with an IPv6 address for your
                                 distribution, specify true. If you specify false, CloudFront responds to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses. This allows viewers to submit a second request, for an
                                 IPv4 address for your distribution. For more information and usage guidance, see CreateDistribution
                                 in the Amazon CloudFront API Reference.

Required: No

Type: Boolean

Update requires: No interruption

Logging

Controls whether access logs are written for the distribution. To turn on
                                 access logs, specify this property.

Required: No

Type: Logging
                                 type

Update requires: No interruption

Origins

A list of origins for this CloudFront distribution. For each origin, you can specify
                                 whether it is an Amazon S3 or custom origin.

Required: Yes

Type: List of Origins.

Update requires: No interruption

PriceClass

The price class that corresponds with the maximum price that you want to pay
                                 for the CloudFront service. For more information, see Choosing the Price Class in the
                                 Amazon CloudFront Developer Guide.

For more information about the valid values, see the PriceClass
                                 content for the DistributionConfig data type in the
                                 Amazon CloudFront API Reference.

Required: No

Type: String

Update requires: No interruption

Restrictions

Specifies restrictions on who or how viewers can access your content.

Required: No

Type: CloudFront Distribution
                                    Restrictions

Update requires: No interruption

ViewerCertificate

The certificate to use when viewers use HTTPS to request objects.

Required: No

Type: CloudFront
                                    Distribution ViewerCertificate

Update requires: No interruption

WebACLId

The AWS WAF web ACL to associate
                                 with this distribution. AWS WAF is a web application firewall that enables you to
                                 monitor the HTTP and HTTPS requests that are forwarded to CloudFront and to control
                                 who
                                 can access your content. CloudFront permits or forbids requests based on conditions
                                 that
                                 you specify, such as the IP addresses from which requests originate or the values
                                 of query strings.

Required: No

Type: String

Update requires: No interruption


text:
.header-demo	{ background: #012d52 url(demo_header.png) no-repeat top center; height: 150px; margin-bottom: 10px; text-align: center; }

.header			{ background: #012d52; color: #FFF;}

.content		{ background: #EEE; }

.sidebar		{ background: #9bc911; }

.footer			{ background: #012d52; color: #FFF; }

.info 			{ background: #012d52; padding: 10px; font-family: Verdana, Arial, sans-serif; font-size: 14px; margin: 5px 0; color: #EFEFEF; }

.info2			{ background: #F0F0F0; border: 1px dashed #CCC; padding: 10px; font-family: Verdana, Arial, sans-serif; font-size: 14px; margin: 10px; color: #444; }

.container 		{ padding:5px; margin:2px; border:solid 1px #666; }


text:
package io.fabric8.funktion.model.steps;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.fabric8.funktion.model.StepKinds;

/**
 * If a filter expression is matched then it invokes the child steps
 */
@JsonPropertyOrder({"expression", "language", "steps"})
public class Filter extends ChildSteps<Filter> {
    private String expression;
    private String language;

    public Filter() {
        super(StepKinds.FILTER);
    }

    public Filter(String expression) {
        this();
        this.expression = expression;
    }

    public Filter(String expression, String language) {
        this();
        this.expression = expression;
        this.language = language;
    }

    @Override
    public String toString() {
        return "Filter: " + expression + " => " + getSteps();
    }

    public String getKind() {
        return StepKinds.FILTER;
    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}


text:
package audioCore;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.VoiceChannel;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

public class TrackManager extends AudioEventAdapter {

    private final AudioPlayer PLAYER;
    private final Queue<AudioInfo> queue;

    public TrackManager(AudioPlayer player) {
        this.PLAYER = player;
        this.queue = new LinkedBlockingQueue<>();
    }

    public void queueAdd(AudioTrack track, Member author) {
        AudioInfo info = new AudioInfo(track, author);
        queue.add(info);
    }

    public void queueRemove(AudioTrack track, Member author, TextChannel txtchan) {
            AudioInfo info = new AudioInfo(track, author);
            AudioInfo ai = queue.poll();
            if (ai != null) txtchan.sendMessage("Titel aus der Wiedergabeliste entfernt").queue();
            else txtchan.sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription("Dieser Titel ist nicht in der Wiedergabeliste!").build()).queue();
    }

    public void play() {
        if (PLAYER.getPlayingTrack() == null && !queue.isEmpty())
            PLAYER.playTrack(queue.element().getTrack());
    }

    public void play(AudioTrack track, Member author) {
        if (PLAYER.getPlayingTrack() != null) PLAYER.stopTrack();
        Queue<AudioInfo> subqueue = new LinkedBlockingQueue<>();
        subqueue.add(new AudioInfo(track, author));
        subqueue.addAll(queue);
        for (int i = queue.size();i > 0;i--) {
            queue.poll();
        }
        queue.addAll(subqueue);
        PLAYER.playTrack(track);
    }

    public void playList(AudioTrack track, Member author) {
        AudioInfo info = new AudioInfo(track, author);
        queue.add(info);

        if (PLAYER.getPlayingTrack() == null) {
            PLAYER.playTrack(track);
        }
    }

    public boolean isPaused() {
        return PLAYER.isPaused();
    }

    public void setPause(boolean pause) {
        PLAYER.setPaused(pause);
    }

    public void setVolume(int volume) {
        PLAYER.setVolume(volume);
    }

    public int getVolume() {
        return PLAYER.getVolume();
    }

    public Set<AudioInfo> getQueue() {
        return new LinkedHashSet<>(queue);
    }

    public AudioInfo getInfo(AudioTrack track) {
        return queue.stream()
                .filter(info -> info.getTrack().equals(track))
                .findFirst().orElse(null);
    }

    public void purgeQueue() {
        queue.clear();
    }

    public void shuffleQueue() {
        List<AudioInfo> cQueue = new ArrayList<>(getQueue());
        AudioInfo current = cQueue.get(0);
        cQueue.remove(0);
        Collections.shuffle(cQueue);
        cQueue.add(0, current);
        purgeQueue();
        queue.addAll(cQueue);

    }

    @Override
    public void onTrackStart(AudioPlayer player, AudioTrack track) {
        AudioInfo info = queue.element();
        VoiceChannel vChan = info.getAuthor().getVoiceState().getChannel();

        if (vChan == null) {
            player.stopTrack();
            System.out.println("Kein Channel gefunden");
        } else
            info.getAuthor().getGuild().getAudioManager().openAudioConnection(vChan);
    }

    @Override
    public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
        Guild g = queue.remove().getAuthor().getGuild();

        if (queue.isEmpty()) {
            g.getAudioManager().closeAudioConnection();
        } else
            player.playTrack(queue.element().getTrack());
    }

}


text:
package org.hibernate.event.spi;

import java.io.Serializable;
import java.util.Map;

import org.hibernate.HibernateException;

/**
 * Defines the contract for handling of merge events generated from a session.
 *
 * @author Gavin King
 */
public interface MergeEventListener extends Serializable {

    /**
     * Handle the given merge event.
     *
     * @param event The merge event to be handled.
     * @throws HibernateException
     */
	public void onMerge(MergeEvent event) throws HibernateException;

    /**
     * Handle the given merge event.
     *
     * @param event The merge event to be handled.
     * @throws HibernateException
     */
	public void onMerge(MergeEvent event, Map copiedAlready) throws HibernateException;

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package avengersassemblebridge;

/**
 *
 * @author Nick
 */
public class AvengersAssembleBridge {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Introduce the Scenario and The avengers
        System.out.println("In the comics, the Avengers haven't ever destroyed the Golden Gate Bridge (Citation 1)");

        System.out.println("But, If they were to make a suprise visit to beatiful San Fransisco Bay Area, \nAnd destory the Golden Gate Bridge, not only would there be many political ramifications \nabout Govenrment oversieght of superheros, but they bridge would also need to be rebuilt as well\n");
        //Introduce Legos
        System.out.println("The natural choice to rebuild the bridge, is, of course, to utilize LEGOs");

        double legoHieght = 9.6; // in milimeters
        double legoWidth = 15.8; // in mm
        double legoLength = 31.8; // mm

        System.out.println("A standardized 2X4 Lego Brick is:");
        System.out.println(legoHieght + "mm tall, or "+ (legoHieght= legoHieght/1000) + " Meters");
        System.out.println(legoWidth + "mm wide, or "+ (legoWidth = legoWidth/1000) + " Meters");
        System.out.println(legoLength + "mm wide, or "+ (legoLength = legoLength/1000) + " Meters");
        System.out.println("(citation 2)");
        double legoVolume;
        System.out.println("This gives us a volume of "+(legoVolume = legoHieght*legoWidth*legoLength)+" meters cubed per brick.");

        // Dimensions of Golden Gate bridge
        double bLength = 2788; // length including distance to toll plaza
        double bWidth = 27; // width in meters
        double bDepth = 7.6; // depth
        System.out.println("The Golden Gate Bridge has a length of "+ bLength+" meters, \na deck width of " + bWidth + ", \nand a deck deph of "+ bDepth + " meters. (Citation 3)");
        double dVolume = bLength*bWidth*bDepth;
        System.out.println("Which means, if the Golden Gate Bridge was Just a flat plank, then its volume would be "+ dVolume + " meters cubed");
        double dBricks = dVolume/ legoVolume ;
        //int val = new BigDecimal(stringValue).intValue();
        System.out.println("Which means that it would take "+ dBricks + "(about 100 Billion) standard 2X4 lego bricks \nto recreate *JUST* the deck of the Golden Gate Bridge ");

        System.out.println("But we dont want to replace just the deck of the bridge, we want to replace all of it.\nThe next step would be to rebuild the towers");

        double tHeight = 227;
        double SouthTowerDepth = 34;
        double legWidth = 10;
        double legDepth = 16;

        System.out.println("The Golden Gate Bridge has 2 support towers, each of which is "+ tHeight + " meters tall" );
        System.out.println("Each of these towers has two legs, which at the base are "+ legWidth + " meters wide");
        System.out.println("And " + legDepth + " meters long");
        System.out.println("The two southern legs also have an additional underwater depth of " + SouthTowerDepth+ " meters");
        System.out.println("Using these stats to model the towers, \nthe number of legos required can be found by comparing the volume of the towers \nto the amount of legos needed to make that volume (Citation 4)");
        double ntVolume;
        System.out.println("The hieght of the North tower is " + tHeight + " \nmultiplied by the width ("+legWidth+") and the depth ("+legDepth+") \ngives us the volume of one leg of the north tower:"+( ntVolume= legDepth*legWidth*tHeight)+" cubic meters" );
        System.out.println("Of course since there are two legs in the tower, the total value of the \nnorth tower can be approximated by 2 times the volume, or "+ (2*ntVolume) + " cubic meters.");
        System.out.println("The southern is the same as the northern except that it is "+ SouthTowerDepth + " more meters underwater");
        System.out.println("So you just have to add on that much to the hieght before you take the volume");
        double stVolume = (SouthTowerDepth+tHeight)*legDepth*legWidth;
        System.out.println("Which ends up making one leg of South Tower "+ stVolume + " cubic meters");
        double tBricks;
        double towerVolume;
        System.out.println("Thus the total volume of all the towers is " + (towerVolume=2*stVolume+2*ntVolume) + " cubic meters");
        System.out.println("The legos required to meet this volume is the volume of the Towers \ndivided by the volume of a lego brick, which gives you:" + (tBricks = towerVolume/legoVolume) +" Bricks\nOr, 30 Billion Lego Bricks which, gives a a grand total of " + (tBricks+dBricks)+" Bricks total");

        double cDiameter = .92;
        double cLength = 2332;

        System.out.println("In addtion, the cables are "+ cDiameter +" meters in diameter, and " + cLength+" meters long");
        double cVolume = 3.14159265*(cDiameter/2)*(cDiameter/2)*cLength;
        System.out.println("Which by the same math gives you a volume of "+cVolume+" cubic meters.");
        double cBricks;
        System.out.println("Add two of those together, and then divide by the volume of a lego brick to find the numbers of \nBricks to recreate this: "+ (cBricks=2*cVolume/legoVolume) +" bricks");
        System.out.println("This brings the Grand Total of the all the Lego Bricks to recreate the Golden Gate Bridge to " + (cBricks+tBricks+dBricks) +" Bricks Total!");
        System.out.println("(aka 151.6 Billion Lego Bricks!)");

        citations();
    }
    public static void citations(){
        // first citation
        System.out.println("Citation 1: According to the Marvel wiki, \nThe Golden Gate Bridge is used a back drop for a number of avengers fights\nBut the avengers usually end up saving the bridge, not destroying it. \nhttp://marvel.wikia.com/wiki/Golden_Gate_Bridge");
        System.out.println("Citation 2: I was suprised lego bricks were that specific... \nthey also have a tolerance of .1mm.\nhttp://www.robertcailliau.eu/Lego/Dimensions/zMeasurements-en.xhtml");
        System.out.println("Citation 3: for the length and width: http://goldengatebridge.org/research/factsGGBDesign.php\nfor the depth: http://www.archinomy.com/case-studies/1908/golden-gate-bridge-san-francisco");
        System.out.println("Citation 4: My Brain");
    }

}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
namespace ITCC.Logging.Reader.Core.Enums
{
    public enum ReaderResult
    {
        Ok,
        FileNotFound,
        FailedToOpen
    }
}


text:
package me.predatorray.bud.lisp;

import me.predatorray.bud.lisp.builtin.BuiltinsEnvironment;
import me.predatorray.bud.lisp.evaluator.Evaluator;
import me.predatorray.bud.lisp.evaluator.TcoEvaluator;
import me.predatorray.bud.lisp.lang.BudObject;
import me.predatorray.bud.lisp.lang.Environment;
import me.predatorray.bud.lisp.lexer.Lexer;
import me.predatorray.bud.lisp.parser.Expression;
import me.predatorray.bud.lisp.parser.Parser;
import me.predatorray.bud.lisp.util.Validation;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class BudInterpreter {

    private final Evaluator evaluator;
    private final Environment initial;

    public BudInterpreter() {
        this(new TcoEvaluator());
    }

    public BudInterpreter(Evaluator evaluator) {
        this(evaluator, BuiltinsEnvironment.INSTANCE);
    }

    public BudInterpreter(Evaluator evaluator, Environment initial) {
        this.evaluator = Validation.notNull(evaluator);
        this.initial = Validation.notNull(initial);
    }

    public BudObject interpret(Path sourceFilePath) throws IOException {
        CharSequence sourceSequence = readSourceFromPath(sourceFilePath);
        return interpret(sourceSequence);
    }

    public BudObject interpretInterruptibly(Path sourceFilePath) throws IOException, InterruptedException {
        CharSequence sourceSequence = readSourceFromPath(sourceFilePath);
        return interpretInterruptibly(sourceSequence);
    }

    public BudObject interpret(CharSequence source) {
        List<Expression> expressions = parseSource(source);
        if (expressions.size() == 1) {
            Expression expression = expressions.get(0);
            return evaluator.evaluate(expression, initial);
        } else {
            // TODO same as begin expression
            throw new UnsupportedOperationException();
        }
    }

    public BudObject interpretInterruptibly(CharSequence source) throws InterruptedException {
        List<Expression> expressions = parseSource(source);
        if (expressions.size() == 1) {
            Expression expression = expressions.get(0);
            return evaluator.evaluateInterruptibly(expression, initial);
        } else {
            // TODO same as begin expression
            throw new UnsupportedOperationException();
        }
    }

    private List<Expression> parseSource(CharSequence source) {
        Lexer lexer = new Lexer(source);
        Parser parser = new Parser();
        return parser.parse(lexer);
    }

    private CharSequence readSourceFromPath(Path sourceFilePath) throws IOException {
        Validation.notNull(sourceFilePath);
        StringBuilder sourceSequence = new StringBuilder();
        char[] buffer = new char[2048];
        try (BufferedReader reader = Files.newBufferedReader(sourceFilePath, StandardCharsets.UTF_8)) {
            while (true) {
                int read = reader.read(buffer, 0, buffer.length);
                if (read <= 0) {
                    break;
                }
                sourceSequence.append(buffer, 0, read);
            }
        }
        return sourceSequence;
    }
}


text:
class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.flag = False
        self.children = {}

class Trie(object):

    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TrieNode()
            cur = cur.children[c]
        cur.flag = True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return cur.flag

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie
        that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        cur = self.root
        for c in prefix:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return True

# Your Trie object will be instantiated and called as such:
# trie = Trie()
# trie.insert("somestring")
# trie.search("key")


text:
layout: page
show_meta: false
title: "El Departamento"
subheadline: "A Step-by-Step Guide"
teaser: "This step-by-step guide helps you to customize Feeling Responsive to your needs."
header:
   image_fullwidth: "header_homepage_13.jpg"
permalink: "/departamento/"
---
1. Open `_config.yml` and work it through, it's well documented
2. Add your own `logo.png` to `/images/`.
3. Open `_data/socialmedia.yml` and add your own social media links.
4. Open `_data/navigation.yml` and customize your navigation.
5. Open `_data/language.yml` and translate the theme if necessary.
6. Open `_data/services.yml` and customize links in the footer.
7. Open `_data/network.yml` and customize links in the footer.
8. Open `_data/authors.yml` and edit author information and set default author in `config.yml.
9. [Read the documentation][1] to check out all features of *Feeling Responsive*.
10. Make it yours and add your own content.

Check out the documentation for all the tricks ›

 [1]: {{ site.url }}/documentation/