text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

namespace WPFDesign.Core.Adorners
{
    /// <summary>
    /// Describes the space in which an adorner is placed.
    /// </summary>
    public enum AdornerPlacementSpace
    {
        /// <summary>
        /// The adorner is affected by the render transform of the adorned element.
        /// </summary>
        Render,

        /// <summary>
        /// The adorner is affected by the layout transform of the adorned element.
        /// </summary>
        Layout,

        /// <summary>
        /// The adorner is not affected by transforms of designed controls.
        /// </summary>
        Designer
    }
}


text:
package io.dashboardhub.tweeterwall.controller;

import io.dashboardhub.tweeterwall.service.TwitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class DefaultController {

    @Autowired
    private TwitterService twitterService;

    @RequestMapping(value = {"/s/{uid}"}, method = RequestMethod.GET)
    public String dashboard(Model model, @PathVariable("uid") String uid) {
        model.addAttribute("tweets", twitterService.search(uid));

        return "default/dashboard";
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.world.block.shapes;

import com.bulletphysics.collision.shapes.BoxShape;
import com.bulletphysics.collision.shapes.CollisionShape;
import com.bulletphysics.collision.shapes.CompoundShape;
import com.bulletphysics.collision.shapes.ConvexHullShape;
import com.bulletphysics.collision.shapes.SphereShape;
import com.bulletphysics.linearmath.Transform;
import com.bulletphysics.util.ObjectArrayList;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.procedure.TIntProcedure;
import org.terasology.assets.ResourceUrn;
import org.terasology.assets.format.AbstractAssetFileFormat;
import org.terasology.assets.format.AssetDataFile;
import org.terasology.assets.module.annotations.RegisterAssetFileFormat;
import org.terasology.math.Rotation;
import org.terasology.math.VecMath;
import org.terasology.math.geom.Vector2f;
import org.terasology.math.geom.Vector3f;
import org.terasology.utilities.gson.Vector2fTypeAdapter;
import org.terasology.utilities.gson.Vector3fTypeAdapter;
import org.terasology.world.block.BlockPart;

import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;

/**
 * @author Immortius
 */
@RegisterAssetFileFormat
public class JsonBlockShapeLoader extends AbstractAssetFileFormat<BlockShapeData> {
    private static final BoxShape CUBE_SHAPE = new BoxShape(new javax.vecmath.Vector3f(0.5f, 0.5f, 0.5f));
    private Gson gson;

    public JsonBlockShapeLoader() {
        super("shape");
        gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(BlockShapeData.class, new BlockShapeHandler())
                .registerTypeAdapter(BlockMeshPart.class, new BlockMeshPartHandler())
                .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapter())
                .registerTypeAdapter(Vector2f.class, new Vector2fTypeAdapter())
                .create();
    }

    @Override
    public BlockShapeData load(ResourceUrn resourceUrn, List<AssetDataFile> inputs) throws IOException {
        try (InputStreamReader reader = new InputStreamReader(inputs.get(0).openStream(), Charsets.UTF_8)) {
            return gson.fromJson(reader, BlockShapeData.class);
        }
    }

    private static class BlockShapeHandler implements JsonDeserializer<BlockShapeData> {

        public static final String DISPLAY_NAME = "displayName";
        public static final String PITCH_SYMMETRIC = "pitchSymmetric";
        public static final String YAW_SYMMETRIC = "yawSymmetric";
        public static final String ROLL_SYMMETRIC = "rollSymmetric";
        public static final String SYMMETRIC = "symmetric";
        public static final String CONVEX_HULL = "convexHull";
        public static final String COLLIDERS = "colliders";
        public static final String COLLISION = "collision";
        public static final String FULL_SIDE = "fullSide";
        public static final String TYPE = "type";
        public static final String AABB = "AABB";
        public static final String SPHERE = "Sphere";
        public static final String POSITION = "position";
        public static final String EXTENTS = "extents";
        public static final String RADIUS = "radius";

        @Override
        public BlockShapeData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            BlockShapeData shape = new BlockShapeData();
            JsonObject shapeObj = json.getAsJsonObject();

            if (shapeObj.has(DISPLAY_NAME)) {
                shape.setDisplayName(shapeObj.getAsJsonPrimitive(DISPLAY_NAME).getAsString());
            }

            for (BlockPart part : BlockPart.values()) {
                if (shapeObj.has(part.toString().toLowerCase(Locale.ENGLISH))) {
                    JsonObject meshObj = shapeObj.getAsJsonObject(part.toString().toLowerCase(Locale.ENGLISH));
                    shape.setMeshPart(part, (BlockMeshPart) context.deserialize(meshObj, BlockMeshPart.class));
                    if (part.isSide() && meshObj.has(FULL_SIDE)) {
                        shape.setBlockingSide(part.getSide(), meshObj.get(FULL_SIDE).getAsBoolean());
                    }
                }
            }

            if (shapeObj.has(COLLISION) && shapeObj.get(COLLISION).isJsonObject()) {
                JsonObject collisionInfo = shapeObj.get(COLLISION).getAsJsonObject();
                processCollision(context, shape, collisionInfo);
            } else {
                shape.setCollisionShape(CUBE_SHAPE);
                shape.setCollisionSymmetric(true);
            }
            return shape;
        }

        private void processCollision(JsonDeserializationContext context, BlockShapeData shape, JsonObject collisionInfo) {
            if (collisionInfo.has(PITCH_SYMMETRIC) && collisionInfo.get(PITCH_SYMMETRIC).isJsonPrimitive()
                    && collisionInfo.get(PITCH_SYMMETRIC).getAsJsonPrimitive().isBoolean()) {
                shape.setPitchSymmetric(collisionInfo.get(PITCH_SYMMETRIC).getAsBoolean());
            }
            if (collisionInfo.has(YAW_SYMMETRIC) && collisionInfo.get(YAW_SYMMETRIC).isJsonPrimitive()
                    && collisionInfo.get(YAW_SYMMETRIC).getAsJsonPrimitive().isBoolean()) {
                shape.setYawSymmetric(collisionInfo.get(YAW_SYMMETRIC).getAsBoolean());
            }
            if (collisionInfo.has(ROLL_SYMMETRIC) && collisionInfo.get(ROLL_SYMMETRIC).isJsonPrimitive()
                    && collisionInfo.get(ROLL_SYMMETRIC).getAsJsonPrimitive().isBoolean()) {
                shape.setRollSymmetric(collisionInfo.get(ROLL_SYMMETRIC).getAsBoolean());
            }

            if (collisionInfo.has(SYMMETRIC) && collisionInfo.get(SYMMETRIC).isJsonPrimitive()
                    && collisionInfo.get(SYMMETRIC).getAsJsonPrimitive().isBoolean()) {
                if (collisionInfo.get(SYMMETRIC).getAsBoolean()) {
                    shape.setCollisionSymmetric(true);
                }
            }

            if (collisionInfo.has(CONVEX_HULL) && collisionInfo.get(CONVEX_HULL).isJsonPrimitive()
                    && collisionInfo.get(CONVEX_HULL).getAsJsonPrimitive().isBoolean()) {
                ObjectArrayList<javax.vecmath.Vector3f> verts = buildVertList(shape);
                ConvexHullShape convexHull = new ConvexHullShape(verts);
                shape.setCollisionShape(convexHull);
            } else if (collisionInfo.has(COLLIDERS) && collisionInfo.get(COLLIDERS).isJsonArray()
                    && collisionInfo.get(COLLIDERS).getAsJsonArray().size() > 0) {
                JsonArray colliderArray = collisionInfo.get(COLLIDERS).getAsJsonArray();
                processColliders(context, colliderArray, shape);
            } else {
                shape.setCollisionShape(CUBE_SHAPE);
                shape.setCollisionSymmetric(true);
            }
        }

        private ObjectArrayList<javax.vecmath.Vector3f> buildVertList(BlockShapeData shape) {
            ObjectArrayList<javax.vecmath.Vector3f> result = new ObjectArrayList<>();
            for (BlockPart part : BlockPart.values()) {
                BlockMeshPart meshPart = shape.getMeshPart(part);
                if (meshPart != null) {
                    for (int i = 0; i < meshPart.size(); ++i) {
                        result.add(VecMath.to(meshPart.getVertex(i)));
                    }
                }
            }
            return result;
        }

        private void processColliders(JsonDeserializationContext context, JsonArray colliderArray, BlockShapeData shape) {

            List<ColliderInfo> colliders = Lists.newArrayList();
            for (JsonElement elem : colliderArray) {
                if (elem.isJsonObject()) {
                    JsonObject colliderObj = elem.getAsJsonObject();
                    if (colliderObj.has(TYPE) && colliderObj.get(TYPE).isJsonPrimitive() && colliderObj.getAsJsonPrimitive(TYPE).isString()) {
                        String type = colliderObj.get(TYPE).getAsString();
                        if (AABB.equals(type)) {
                            colliders.add(processAABBShape(context, colliderObj));
                        } else if (SPHERE.equals(type)) {
                            colliders.add(processSphereShape(context, colliderObj));
                        }
                    }
                }
            }
            if (colliders.size() > 1) {
                ColliderInfo info = processCompoundShape(colliders);
                shape.setCollisionShape(info.collisionShape);
                shape.setCollisionOffset(info.offset);
            } else if (colliders.size() == 1) {
                shape.setCollisionShape(colliders.get(0).collisionShape);
                shape.setCollisionOffset(colliders.get(0).offset);
            } else {
                shape.setCollisionShape(CUBE_SHAPE);
                shape.setCollisionOffset(new Vector3f(0, 0, 0));
                shape.setCollisionSymmetric(true);
            }
        }

        private ColliderInfo processCompoundShape(List<ColliderInfo> colliders) {
            CompoundShape collisionShape = new CompoundShape();

            for (ColliderInfo collider : colliders) {
                Transform transform = new Transform(new javax.vecmath.Matrix4f(VecMath.to(Rotation.none().getQuat4f()), VecMath.to(collider.offset), 1.0f));
                collisionShape.addChildShape(transform, collider.collisionShape);
            }
            return new ColliderInfo(new Vector3f(), collisionShape);
        }

        private ColliderInfo processAABBShape(JsonDeserializationContext context, JsonObject colliderDef) {
            Vector3f offset = context.deserialize(colliderDef.get(POSITION), Vector3f.class);
            Vector3f extent = context.deserialize(colliderDef.get(EXTENTS), Vector3f.class);
            if (offset == null) {
                throw new JsonParseException("AABB Collider missing position");
            }
            if (extent == null) {
                throw new JsonParseException("AABB Collider missing extents");
            }
            extent.absolute();

            return new ColliderInfo(offset, new BoxShape(VecMath.to(extent)));
        }

        private ColliderInfo processSphereShape(JsonDeserializationContext context, JsonObject colliderDef) {
            Vector3f offset = context.deserialize(colliderDef.get(POSITION), Vector3f.class);
            float radius = colliderDef.get(RADIUS).getAsFloat();
            if (offset == null) {
                throw new JsonParseException("Sphere Collider missing position");
            }

            return new ColliderInfo(offset, new SphereShape(radius));
        }

        private static class ColliderInfo {
            public Vector3f offset;
            public CollisionShape collisionShape;

            public ColliderInfo(Vector3f offset, CollisionShape shape) {
                this.offset = offset;
                this.collisionShape = shape;
            }
        }
    }

    private static class BlockMeshPartHandler implements JsonDeserializer<BlockMeshPart> {

        @Override
        public BlockMeshPart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            final JsonObject meshObj = json.getAsJsonObject();
            final Vector3f[] vertices = context.deserialize(meshObj.get("vertices"), Vector3f[].class);
            final Vector3f[] normals = context.deserialize(meshObj.get("normals"), Vector3f[].class);
            final Vector2f[] texCoords = context.deserialize(meshObj.get("texcoords"), Vector2f[].class);

            if (vertices == null) {
                throw new JsonParseException("Vertices missing");
            }
            if (normals == null) {
                throw new JsonParseException("Normals missing");
            }
            if (texCoords == null) {
                throw new JsonParseException("Texcoords missing");
            }
            if (!meshObj.has("faces")) {
                throw new JsonParseException("Faces missing");
            }

            if (vertices.length != normals.length || vertices.length != texCoords.length) {
                throw new JsonParseException("vertices, normals and texcoords must have the same length");
            }

            // Normalise the normals for safety
            for (Vector3f norm : normals) {
                norm.normalize();
            }

            int[][] faces = context.deserialize(meshObj.get("faces"), int[][].class);

            // Convert faces to indices via triangle fan
            TIntList indices = new TIntArrayList();
            for (int[] face : faces) {
                for (int tri = 0; tri < face.length - 2; tri++) {
                    indices.add(face[0]);
                    indices.add(face[tri + 1]);
                    indices.add(face[tri + 2]);
                }
            }

            // Check indices in bounds
            indices.forEach(new TIntProcedure() {
                @Override
                public boolean execute(int value) {
                    if (value < 0 || value >= vertices.length) {
                        throw new JsonParseException("Face value out of range: " + value + ", max vertex is " + (vertices.length - 1));
                    }
                    return true;
                }
            });

            return new BlockMeshPart(vertices, normals, texCoords, indices.toArray());
        }
    }

}


text:
<?php

namespace OpenDataAPI\aggregator\constants;

class Currency {

    const USD = 'USD';
    const EUR = 'EUR';
    const UAH = 'UAH';
    const RUB = 'RUB';

    //TODO: continue list...

}


text:
    target_os = "windows",
    target_os = "linux",
    target_os = "android",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
))]

use std::ffi::{CStr, CString};
use std::ops::{Deref, DerefMut};
use std::os::raw;
use std::sync::{Arc, Mutex};

use glutin_egl_sys as ffi;
use libloading;
#[cfg(unix)]
use libloading::os::unix as libloading_os;
#[cfg(windows)]
use libloading::os::windows as libloading_os;
#[cfg(any(
    target_os = "android",
    target_os = "windows",
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
))]
use winit::dpi;

use self::make_current_guard::MakeCurrentGuard;
use crate::api::dlloader::{SymTrait, SymWrapper};
#[cfg(not(target_os = "windows"))]
use crate::Rect;
use crate::{
    Api, ContextError, CreationError, GlAttributes, GlRequest, PixelFormat,
    PixelFormatRequirements, ReleaseBehavior, Robustness,
};

#[derive(Clone)]
pub struct Egl(pub SymWrapper<ffi::egl::Egl>);

/// Because `*const raw::c_void` doesn't implement `Sync`.
unsafe impl Sync for Egl {}

type EglGetProcAddressType = libloading_os::Symbol<
    unsafe extern "C" fn(*const std::os::raw::c_void) -> *const std::os::raw::c_void,
>;

lazy_static! {
    static ref EGL_GET_PROC_ADDRESS: Arc<Mutex<Option<EglGetProcAddressType>>> =
        Arc::new(Mutex::new(None));
}

impl SymTrait for ffi::egl::Egl {
    fn load_with(lib: &libloading::Library) -> Self {
        let f = move |s: &'static str| -> *const std::os::raw::c_void {
            // Check if the symbol is available in the library directly. If
            // it is, just return it.
            if let Ok(sym) = unsafe {
                lib.get(std::ffi::CString::new(s.as_bytes()).unwrap().as_bytes_with_nul())
            } {
                return *sym;
            }

            let mut egl_get_proc_address = (*EGL_GET_PROC_ADDRESS).lock().unwrap();
            if egl_get_proc_address.is_none() {
                unsafe {
                    let sym: libloading::Symbol<
                        unsafe extern "C" fn(
                            *const std::os::raw::c_void,
                        )
                            -> *const std::os::raw::c_void,
                    > = lib.get(b"eglGetProcAddress").unwrap();
                    *egl_get_proc_address = Some(sym.into_raw());
                }
            }

            // The symbol was not available in the library, so ask
            // eglGetProcAddress for it. Note that eglGetProcAddress was
            // only able to look up extension functions prior to EGL 1.5,
            // hence this two-part dance.
            unsafe {
                (egl_get_proc_address.as_ref().unwrap())(
                    std::ffi::CString::new(s.as_bytes()).unwrap().as_bytes_with_nul().as_ptr()
                        as *const std::os::raw::c_void,
                )
            }
        };

        Self::load_with(f)
    }
}

impl Egl {
    pub fn new() -> Result<Self, ()> {
        #[cfg(target_os = "windows")]
        let paths = vec!["libEGL.dll", "atioglxx.dll"];

        #[cfg(not(target_os = "windows"))]
        let paths = vec!["libEGL.so.1", "libEGL.so"];

        SymWrapper::new(paths).map(Egl)
    }
}

mod make_current_guard;

impl Deref for Egl {
    type Target = ffi::egl::Egl;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Egl {
    fn deref_mut(&mut self) -> &mut ffi::egl::Egl {
        &mut self.0
    }
}

lazy_static! {
    pub static ref EGL: Option<Egl> = Egl::new().ok();
}

/// Specifies the type of display passed as `native_display`.
#[derive(Debug)]
#[allow(dead_code)]
pub enum NativeDisplay {
    /// `None` means `EGL_DEFAULT_DISPLAY`.
    X11(Option<ffi::EGLNativeDisplayType>),
    /// `None` means `EGL_DEFAULT_DISPLAY`.
    Gbm(Option<ffi::EGLNativeDisplayType>),
    /// `None` means `EGL_DEFAULT_DISPLAY`.
    Wayland(Option<ffi::EGLNativeDisplayType>),
    /// `EGL_DEFAULT_DISPLAY` is mandatory for Android.
    Android,
    // TODO: should be `EGLDeviceEXT`
    Device(ffi::EGLNativeDisplayType),
    /// Don't specify any display type. Useful on windows. `None` means
    /// `EGL_DEFAULT_DISPLAY`.
    Other(Option<ffi::EGLNativeDisplayType>),
}

#[derive(Debug)]
pub struct Context {
    display: ffi::egl::types::EGLDisplay,
    context: ffi::egl::types::EGLContext,
    surface: Option<parking_lot::Mutex<ffi::egl::types::EGLSurface>>,
    api: Api,
    pixel_format: PixelFormat,
}

fn get_egl_version(
    display: ffi::egl::types::EGLDisplay,
) -> Result<(ffi::egl::types::EGLint, ffi::egl::types::EGLint), CreationError> {
    unsafe {
        let egl = EGL.as_ref().unwrap();
        let mut major: ffi::egl::types::EGLint = std::mem::zeroed();
        let mut minor: ffi::egl::types::EGLint = std::mem::zeroed();

        if egl.Initialize(display, &mut major, &mut minor) == 0 {
            return Err(CreationError::OsError("eglInitialize failed".to_string()));
        }

        Ok((major, minor))
    }
}

unsafe fn bind_and_get_api<'a>(
    opengl: &'a GlAttributes<&'a Context>,
    egl_version: (ffi::egl::types::EGLint, ffi::egl::types::EGLint),
) -> Result<(Option<(u8, u8)>, Api), CreationError> {
    let egl = EGL.as_ref().unwrap();
    match opengl.version {
        GlRequest::Latest => {
            if egl_version >= (1, 4) {
                if egl.BindAPI(ffi::egl::OPENGL_API) != 0 {
                    Ok((None, Api::OpenGl))
                } else if egl.BindAPI(ffi::egl::OPENGL_ES_API) != 0 {
                    Ok((None, Api::OpenGlEs))
                } else {
                    Err(CreationError::OpenGlVersionNotSupported)
                }
            } else {
                Ok((None, Api::OpenGlEs))
            }
        }
        GlRequest::Specific(Api::OpenGlEs, version) => {
            if egl_version >= (1, 2) && egl.BindAPI(ffi::egl::OPENGL_ES_API) == 0 {
                return Err(CreationError::OpenGlVersionNotSupported);
            }
            Ok((Some(version), Api::OpenGlEs))
        }
        GlRequest::Specific(Api::OpenGl, version) => {
            if egl_version < (1, 4) {
                return Err(CreationError::OpenGlVersionNotSupported);
            }
            if egl.BindAPI(ffi::egl::OPENGL_API) == 0 {
                return Err(CreationError::OpenGlVersionNotSupported);
            }
            Ok((Some(version), Api::OpenGl))
        }
        GlRequest::Specific(_, _) => Err(CreationError::OpenGlVersionNotSupported),
        GlRequest::GlThenGles { opengles_version, opengl_version } => {
            if egl_version >= (1, 4) {
                if egl.BindAPI(ffi::egl::OPENGL_API) != 0 {
                    Ok((Some(opengl_version), Api::OpenGl))
                } else if egl.BindAPI(ffi::egl::OPENGL_ES_API) != 0 {
                    Ok((Some(opengles_version), Api::OpenGlEs))
                } else {
                    Err(CreationError::OpenGlVersionNotSupported)
                }
            } else {
                Ok((Some(opengles_version), Api::OpenGlEs))
            }
        }
    }
}

fn get_native_display(native_display: &NativeDisplay) -> *const raw::c_void {
    let egl = EGL.as_ref().unwrap();
    // the first step is to query the list of extensions without any display, if
    // supported
    let dp_extensions = unsafe {
        let p = egl.QueryString(ffi::egl::NO_DISPLAY, ffi::egl::EXTENSIONS as i32);

        // this possibility is available only with EGL 1.5 or
        // EGL_EXT_platform_base, otherwise `eglQueryString` returns an
        // error
        if p.is_null() {
            vec![]
        } else {
            let p = CStr::from_ptr(p);
            let list = String::from_utf8(p.to_bytes().to_vec()).unwrap_or_default();
            list.split(' ').map(|e| e.to_string()).collect::<Vec<_>>()
        }
    };

    let has_dp_extension = |e: &str| dp_extensions.iter().any(|s| s == e);

    match *native_display {
        // Note: Some EGL implementations are missing the
        // `eglGetPlatformDisplay(EXT)` symbol       despite reporting
        // `EGL_EXT_platform_base`. I'm pretty sure this is a bug.
        //       Therefore we detect whether the symbol is loaded in addition to
        // checking for       extensions.
        NativeDisplay::X11(display)
            if has_dp_extension("EGL_KHR_platform_x11") && egl.GetPlatformDisplay.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            // TODO: `PLATFORM_X11_SCREEN_KHR`
            unsafe {
                egl.GetPlatformDisplay(ffi::egl::PLATFORM_X11_KHR, d as *mut _, std::ptr::null())
            }
        }

        NativeDisplay::X11(display)
            if has_dp_extension("EGL_EXT_platform_x11")
                && egl.GetPlatformDisplayEXT.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            // TODO: `PLATFORM_X11_SCREEN_EXT`
            unsafe {
                egl.GetPlatformDisplayEXT(ffi::egl::PLATFORM_X11_EXT, d as *mut _, std::ptr::null())
            }
        }

        NativeDisplay::Gbm(display)
            if has_dp_extension("EGL_KHR_platform_gbm") && egl.GetPlatformDisplay.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            unsafe {
                egl.GetPlatformDisplay(ffi::egl::PLATFORM_GBM_KHR, d as *mut _, std::ptr::null())
            }
        }

        NativeDisplay::Gbm(display)
            if has_dp_extension("EGL_MESA_platform_gbm")
                && egl.GetPlatformDisplayEXT.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            unsafe {
                egl.GetPlatformDisplayEXT(ffi::egl::PLATFORM_GBM_KHR, d as *mut _, std::ptr::null())
            }
        }

        NativeDisplay::Wayland(display)
            if has_dp_extension("EGL_KHR_platform_wayland")
                && egl.GetPlatformDisplay.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            unsafe {
                egl.GetPlatformDisplay(
                    ffi::egl::PLATFORM_WAYLAND_KHR,
                    d as *mut _,
                    std::ptr::null(),
                )
            }
        }

        NativeDisplay::Wayland(display)
            if has_dp_extension("EGL_EXT_platform_wayland")
                && egl.GetPlatformDisplayEXT.is_loaded() =>
        {
            let d = display.unwrap_or(ffi::egl::DEFAULT_DISPLAY as *const _);
            unsafe {
                egl.GetPlatformDisplayEXT(
                    ffi::egl::PLATFORM_WAYLAND_EXT,
                    d as *mut _,
                    std::ptr::null(),
                )
            }
        }

        NativeDisplay::Android
            if has_dp_extension("EGL_KHR_platform_android")
                && egl.GetPlatformDisplay.is_loaded() =>
        unsafe {
            egl.GetPlatformDisplay(
                ffi::egl::PLATFORM_ANDROID_KHR,
                ffi::egl::DEFAULT_DISPLAY as *mut _,
                std::ptr::null(),
            )
        },

        NativeDisplay::Device(display)
            if has_dp_extension("EGL_EXT_platform_device")
                && egl.GetPlatformDisplay.is_loaded() =>
        unsafe {
            egl.GetPlatformDisplay(
                ffi::egl::PLATFORM_DEVICE_EXT,
                display as *mut _,
                std::ptr::null(),
            )
        },

        NativeDisplay::X11(Some(display))
        | NativeDisplay::Gbm(Some(display))
        | NativeDisplay::Wayland(Some(display))
        | NativeDisplay::Device(display)
        | NativeDisplay::Other(Some(display)) => unsafe { egl.GetDisplay(display as *mut _) },

        NativeDisplay::X11(None)
        | NativeDisplay::Gbm(None)
        | NativeDisplay::Wayland(None)
        | NativeDisplay::Android
        | NativeDisplay::Other(None) => unsafe {
            egl.GetDisplay(ffi::egl::DEFAULT_DISPLAY as *mut _)
        },
    }
}

#[allow(dead_code)] // Not all platforms use all
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SurfaceType {
    PBuffer,
    Window,
    Surfaceless,
}

impl Context {
    /// Start building an EGL context.
    ///
    /// This function initializes some things and chooses the pixel format.
    ///
    /// To finish the process, you must call [`ContextPrototype::finish()`].
    #[allow(clippy::new_ret_no_self)]
    pub fn new<'a, F>(
        pf_reqs: &PixelFormatRequirements,
        opengl: &'a GlAttributes<&'a Context>,
        native_display: NativeDisplay,
        surface_type: SurfaceType,
        config_selector: F,
    ) -> Result<ContextPrototype<'a>, CreationError>
    where
        F: FnMut(
            Vec<ffi::egl::types::EGLConfig>,
            ffi::egl::types::EGLDisplay,
        ) -> Result<ffi::egl::types::EGLConfig, ()>,
    {
        let egl = EGL.as_ref().unwrap();
        // calling `eglGetDisplay` or equivalent
        let display = get_native_display(&native_display);

        if display.is_null() {
            return Err(CreationError::OsError("Could not create EGL display object".to_string()));
        }

        let egl_version = get_egl_version(display)?;

        // the list of extensions supported by the client once initialized is
        // different from the list of extensions obtained earlier
        let extensions = if egl_version >= (1, 2) {
            let p =
                unsafe { CStr::from_ptr(egl.QueryString(display, ffi::egl::EXTENSIONS as i32)) };
            let list = String::from_utf8(p.to_bytes().to_vec()).unwrap_or_default();
            list.split(' ').map(|e| e.to_string()).collect::<Vec<_>>()
        } else {
            vec![]
        };

        // binding the right API and choosing the version
        let (version, api) = unsafe { bind_and_get_api(opengl, egl_version)? };

        let (config_id, pixel_format) = unsafe {
            choose_fbconfig(
                display,
                &egl_version,
                api,
                version,
                pf_reqs,
                surface_type,
                opengl,
                config_selector,
            )?
        };

        Ok(ContextPrototype {
            opengl,
            display,
            egl_version,
            extensions,
            api,
            version,
            config_id,
            pixel_format,
        })
    }

    unsafe fn check_make_current(&self, ret: Option<u32>) -> Result<(), ContextError> {
        let egl = EGL.as_ref().unwrap();
        if ret == Some(0) {
            match egl.GetError() as u32 {
                ffi::egl::CONTEXT_LOST => Err(ContextError::ContextLost),
                err => {
                    panic!("make_current: eglMakeCurrent failed (eglGetError returned 0x{:x})", err)
                }
            }
        } else {
            Ok(())
        }
    }

    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        let egl = EGL.as_ref().unwrap();
        let surface = self.surface.as_ref().map(|s| *s.lock()).unwrap_or(ffi::egl::NO_SURFACE);
        let ret = egl.MakeCurrent(self.display, surface, surface, self.context);

        self.check_make_current(Some(ret))
    }

    pub unsafe fn make_not_current(&self) -> Result<(), ContextError> {
        let egl = EGL.as_ref().unwrap();

        let surface_eq = if let Some(surface) = self.surface.as_ref().map(|s| *s.lock()) {
            egl.GetCurrentSurface(ffi::egl::DRAW as i32) == surface
                || egl.GetCurrentSurface(ffi::egl::READ as i32) == surface
        } else {
            false
        };

        if surface_eq || egl.GetCurrentContext() == self.context {
            let ret = egl.MakeCurrent(
                self.display,
                ffi::egl::NO_SURFACE,
                ffi::egl::NO_SURFACE,
                ffi::egl::NO_CONTEXT,
            );

            self.check_make_current(Some(ret))
        } else {
            self.check_make_current(None)
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        let egl = EGL.as_ref().unwrap();
        unsafe { egl.GetCurrentContext() == self.context }
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        self.api
    }

    #[inline]
    pub unsafe fn raw_handle(&self) -> ffi::egl::types::EGLContext {
        self.context
    }

    #[inline]
    pub unsafe fn get_egl_display(&self) -> ffi::egl::types::EGLDisplay {
        self.display
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void {
        let egl = EGL.as_ref().unwrap();
        let addr = CString::new(addr.as_bytes()).unwrap();
        let addr = addr.as_ptr();
        unsafe { egl.GetProcAddress(addr) as *const _ }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        let egl = EGL.as_ref().unwrap();
        let surface = self.surface.as_ref().unwrap().lock();
        if *surface == ffi::egl::NO_SURFACE {
            return Err(ContextError::ContextLost);
        }

        let ret = unsafe { egl.SwapBuffers(self.display, *surface) };

        if ret == 0 {
            match unsafe { egl.GetError() } as u32 {
                ffi::egl::CONTEXT_LOST => Err(ContextError::ContextLost),
                err => {
                    panic!("swap_buffers: eglSwapBuffers failed (eglGetError returned 0x{:x})", err)
                }
            }
        } else {
            Ok(())
        }
    }

    #[inline]
    #[cfg(not(target_os = "windows"))]
    pub fn swap_buffers_with_damage(&self, rects: &[Rect]) -> Result<(), ContextError> {
        let egl = EGL.as_ref().unwrap();

        if !egl.SwapBuffersWithDamageKHR.is_loaded() {
            return Err(ContextError::FunctionUnavailable);
        }

        let surface = self.surface.as_ref().unwrap().lock();
        if *surface == ffi::egl::NO_SURFACE {
            return Err(ContextError::ContextLost);
        }

        let mut ffirects: Vec<ffi::egl::types::EGLint> = Vec::with_capacity(rects.len() * 4);

        for rect in rects {
            ffirects.push(rect.x as ffi::egl::types::EGLint);
            ffirects.push(rect.y as ffi::egl::types::EGLint);
            ffirects.push(rect.width as ffi::egl::types::EGLint);
            ffirects.push(rect.height as ffi::egl::types::EGLint);
        }

        let ret = unsafe {
            egl.SwapBuffersWithDamageKHR(
                self.display,
                *surface,
                ffirects.as_mut_ptr(),
                rects.len() as ffi::egl::types::EGLint,
            )
        };

        if ret == ffi::egl::FALSE {
            match unsafe { egl.GetError() } as u32 {
                ffi::egl::CONTEXT_LOST => Err(ContextError::ContextLost),
                err => {
                    panic!("swap_buffers: eglSwapBuffers failed (eglGetError returned 0x{:x})", err)
                }
            }
        } else {
            Ok(())
        }
    }

    #[inline]
    #[cfg(not(target_os = "windows"))]
    pub fn swap_buffers_with_damage_supported(&self) -> bool {
        let egl = EGL.as_ref().unwrap();
        egl.SwapBuffersWithDamageKHR.is_loaded()
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        self.pixel_format.clone()
    }

    #[inline]
    pub fn buffer_age(&self) -> u32 {
        let egl = EGL.as_ref().unwrap();
        let surface = self.surface.as_ref().unwrap().lock();

        let mut buffer_age = 0;
        let result = unsafe {
            egl.QuerySurface(
                self.display,
                *surface as *const _,
                ffi::egl::BUFFER_AGE_EXT as i32,
                &mut buffer_age,
            )
        };

        if result == ffi::egl::FALSE {
            0
        } else {
            buffer_age as u32
        }
    }
}

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

impl Drop for Context {
    fn drop(&mut self) {
        unsafe {
            // https://stackoverflow.com/questions/54402688/recreate-eglcreatewindowsurface-with-same-native-window
            let egl = EGL.as_ref().unwrap();
            let surface = self.surface.as_ref().map(|s| *s.lock()).unwrap_or(ffi::egl::NO_SURFACE);
            // Ok, so we got to call `glFinish` before destroying the context
            // to ensure it actually gets destroyed. This requires making the
            // this context current.
            let mut guard = MakeCurrentGuard::new(self.display, surface, surface, self.context)
                .map_err(ContextError::OsError)
                .unwrap();

            guard.if_any_same_then_invalidate(surface, surface, self.context);

            let gl_finish_fn = self.get_proc_address("glFinish");
            assert!(!gl_finish_fn.is_null());
            let gl_finish_fn = std::mem::transmute::<_, extern "system" fn()>(gl_finish_fn);
            gl_finish_fn();

            egl.DestroyContext(self.display, self.context);
            self.context = ffi::egl::NO_CONTEXT;
            egl.DestroySurface(self.display, surface);
            if let Some(ref surface) = self.surface {
                let mut surface = surface.lock();
                *surface = ffi::egl::NO_SURFACE;
            }

            // In a reasonable world, we could uncomment the line bellow.
            //
            // This is no such world. Lets talk about something.
            //
            // You see, every call to `get_native_display` returns the exact
            // same display, just look at the docs:
            //
            // "Multiple calls made to eglGetDisplay with the same display_id
            // will return the same EGLDisplay handle."
            //
            // My EGL implementation does not do any ref counting, nor do the
            // EGL docs mention ref counting anywhere. In fact, the docs state
            // that there will be *no effect*, which, in a way, implies no ref
            // counting:
            //
            // "Initializing an already initialized EGL display connection has
            // no effect besides returning the version numbers."
            //
            // So, if we terminate the display, other people who are using it
            // won't be so happy.
            //
            // Well, how did I stumble on this issue you might ask...
            //
            // In this case, the "other people" was us, for it appears my EGL
            // implementation does not follow the docs,  or maybe I'm misreading
            // them. You see, according to the egl docs:
            //
            // "To release the current context without assigning a new one, set
            // context to EGL_NO_CONTEXT and set draw and read to
            // EGL_NO_SURFACE.  [...] ******This is the only case where an
            // uninitialized display may be passed to eglMakeCurrent.******"
            // (Emphasis mine).
            //
            // Well, my computer returns EGL_BAD_DISPLAY if the display passed
            // to eglMakeCurrent is uninitialized, which allowed to me to spot
            // this issue.
            //
            // I would have assumed that if EGL was going to provide us with
            // the same EGLDisplay that they'd at least do
            // some ref counting, but they don't.
            //
            // FIXME: Technically we are leaking resources, not much we can do.
            // Yeah, we could have a global static that does ref counting
            // ourselves, but what if some other library is using the display.
            //
            // On unix operating systems, we could preload a little lib that
            // does ref counting on that level, but:
            //      A) What about other platforms?
            //      B) Do you *really* want all glutin programs to preload a
            //      library?
            //      C) Who the hell is going to maintain that?
            //
            // egl.Terminate(self.display);
        }
    }
}

#[derive(Debug)]
pub struct ContextPrototype<'a> {
    opengl: &'a GlAttributes<&'a Context>,
    display: ffi::egl::types::EGLDisplay,
    egl_version: (ffi::egl::types::EGLint, ffi::egl::types::EGLint),
    extensions: Vec<String>,
    api: Api,
    version: Option<(u8, u8)>,
    config_id: ffi::egl::types::EGLConfig,
    pixel_format: PixelFormat,
}

#[cfg(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
))]
#[cfg(feature = "x11")]
pub fn get_native_visual_id(
    display: ffi::egl::types::EGLDisplay,
    config_id: ffi::egl::types::EGLConfig,
) -> ffi::egl::types::EGLint {
    let egl = EGL.as_ref().unwrap();
    let mut value = unsafe { std::mem::zeroed() };
    let ret = unsafe {
        egl.GetConfigAttrib(
            display,
            config_id,
            ffi::egl::NATIVE_VISUAL_ID as ffi::egl::types::EGLint,
            &mut value,
        )
    };
    if ret == 0 {
        panic!("get_native_visual_id: eglGetConfigAttrib failed with 0x{:x}", unsafe {
            egl.GetError()
        })
    };
    value
}

impl<'a> ContextPrototype<'a> {
    #[cfg(any(
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd",
    ))]
    #[cfg(feature = "x11")]
    pub fn get_native_visual_id(&self) -> ffi::egl::types::EGLint {
        get_native_visual_id(self.display, self.config_id)
    }

    pub fn finish(self, nwin: ffi::EGLNativeWindowType) -> Result<Context, CreationError> {
        let egl = EGL.as_ref().unwrap();
        let surface = unsafe {
            let surface =
                egl.CreateWindowSurface(self.display, self.config_id, nwin, std::ptr::null());
            if surface.is_null() {
                return Err(CreationError::OsError("eglCreateWindowSurface failed".to_string()));
            }
            surface
        };

        self.finish_impl(Some(surface))
    }

    #[cfg(any(
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd",
    ))]
    pub fn finish_surfaceless(self) -> Result<Context, CreationError> {
        // FIXME: Also check for the GL_OES_surfaceless_context *CONTEXT*
        // extension
        if !self.extensions.iter().any(|s| s == "EGL_KHR_surfaceless_context") {
            Err(CreationError::NotSupported("EGL surfaceless not supported".to_string()))
        } else {
            self.finish_impl(None)
        }
    }

    #[cfg(any(
        target_os = "android",
        target_os = "windows",
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd",
    ))]
    pub fn finish_pbuffer(self, size: dpi::PhysicalSize<u32>) -> Result<Context, CreationError> {
        let size: (u32, u32) = size.into();

        let egl = EGL.as_ref().unwrap();
        let attrs = &[
            ffi::egl::WIDTH as raw::c_int,
            size.0 as raw::c_int,
            ffi::egl::HEIGHT as raw::c_int,
            size.1 as raw::c_int,
            ffi::egl::NONE as raw::c_int,
        ];

        let surface = unsafe {
            let surface = egl.CreatePbufferSurface(self.display, self.config_id, attrs.as_ptr());
            if surface.is_null() || surface == ffi::egl::NO_SURFACE {
                return Err(CreationError::OsError("eglCreatePbufferSurface failed".to_string()));
            }
            surface
        };

        self.finish_impl(Some(surface))
    }

    fn finish_impl(
        self,
        surface: Option<ffi::egl::types::EGLSurface>,
    ) -> Result<Context, CreationError> {
        let share = match self.opengl.sharing {
            Some(ctx) => ctx.context,
            None => std::ptr::null(),
        };

        let context = unsafe {
            if let Some(version) = self.version {
                create_context(
                    self.display,
                    &self.egl_version,
                    &self.extensions,
                    self.api,
                    version,
                    self.config_id,
                    self.opengl.debug,
                    self.opengl.robustness,
                    share,
                )?
            } else if self.api == Api::OpenGlEs {
                if let Ok(ctx) = create_context(
                    self.display,
                    &self.egl_version,
                    &self.extensions,
                    self.api,
                    (2, 0),
                    self.config_id,
                    self.opengl.debug,
                    self.opengl.robustness,
                    share,
                ) {
                    ctx
                } else if let Ok(ctx) = create_context(
                    self.display,
                    &self.egl_version,
                    &self.extensions,
                    self.api,
                    (1, 0),
                    self.config_id,
                    self.opengl.debug,
                    self.opengl.robustness,
                    share,
                ) {
                    ctx
                } else {
                    return Err(CreationError::OpenGlVersionNotSupported);
                }
            } else if let Ok(ctx) = create_context(
                self.display,
                &self.egl_version,
                &self.extensions,
                self.api,
                (3, 2),
                self.config_id,
                self.opengl.debug,
                self.opengl.robustness,
                share,
            ) {
                ctx
            } else if let Ok(ctx) = create_context(
                self.display,
                &self.egl_version,
                &self.extensions,
                self.api,
                (3, 1),
                self.config_id,
                self.opengl.debug,
                self.opengl.robustness,
                share,
            ) {
                ctx
            } else if let Ok(ctx) = create_context(
                self.display,
                &self.egl_version,
                &self.extensions,
                self.api,
                (1, 0),
                self.config_id,
                self.opengl.debug,
                self.opengl.robustness,
                share,
            ) {
                ctx
            } else {
                return Err(CreationError::OpenGlVersionNotSupported);
            }
        };

        if let Some(surface) = surface {
            // VSync defaults to enabled; disable it if it was not requested.
            if !self.opengl.vsync {
                let _guard = MakeCurrentGuard::new(self.display, surface, surface, context)
                    .map_err(CreationError::OsError)?;

                let egl = EGL.as_ref().unwrap();
                unsafe {
                    if egl.SwapInterval(self.display, 0) == ffi::egl::FALSE {
                        panic!("finish_impl: eglSwapInterval failed: 0x{:x}", egl.GetError());
                    }
                }
            }
        }

        Ok(Context {
            display: self.display,
            context,
            surface: surface.map(parking_lot::Mutex::new),
            api: self.api,
            pixel_format: self.pixel_format,
        })
    }
}

unsafe fn choose_fbconfig<F>(
    display: ffi::egl::types::EGLDisplay,
    egl_version: &(ffi::egl::types::EGLint, ffi::egl::types::EGLint),
    api: Api,
    version: Option<(u8, u8)>,
    pf_reqs: &PixelFormatRequirements,
    surface_type: SurfaceType,
    opengl: &GlAttributes<&Context>,
    mut config_selector: F,
) -> Result<(ffi::egl::types::EGLConfig, PixelFormat), CreationError>
where
    F: FnMut(
        Vec<ffi::egl::types::EGLConfig>,
        ffi::egl::types::EGLDisplay,
    ) -> Result<ffi::egl::types::EGLConfig, ()>,
{
    let egl = EGL.as_ref().unwrap();

    let descriptor = {
        let mut out: Vec<raw::c_int> = Vec::with_capacity(37);

        if egl_version >= &(1, 2) {
            out.push(ffi::egl::COLOR_BUFFER_TYPE as raw::c_int);
            out.push(ffi::egl::RGB_BUFFER as raw::c_int);
        }

        out.push(ffi::egl::SURFACE_TYPE as raw::c_int);
        let surface_type = match surface_type {
            SurfaceType::Window => ffi::egl::WINDOW_BIT,
            SurfaceType::PBuffer => ffi::egl::PBUFFER_BIT,
            SurfaceType::Surfaceless => 0,
        };
        out.push(surface_type as raw::c_int);

        match (api, version) {
            (Api::OpenGlEs, Some((3, _))) => {
                if egl_version < &(1, 3) {
                    return Err(CreationError::NoAvailablePixelFormat);
                }
                out.push(ffi::egl::RENDERABLE_TYPE as raw::c_int);
                out.push(ffi::egl::OPENGL_ES3_BIT as raw::c_int);
                out.push(ffi::egl::CONFORMANT as raw::c_int);
                out.push(ffi::egl::OPENGL_ES3_BIT as raw::c_int);
            }
            (Api::OpenGlEs, Some((2, _))) => {
                if egl_version < &(1, 3) {
                    return Err(CreationError::NoAvailablePixelFormat);
                }
                out.push(ffi::egl::RENDERABLE_TYPE as raw::c_int);
                out.push(ffi::egl::OPENGL_ES2_BIT as raw::c_int);
                out.push(ffi::egl::CONFORMANT as raw::c_int);
                out.push(ffi::egl::OPENGL_ES2_BIT as raw::c_int);
            }
            (Api::OpenGlEs, _) => {
                if egl_version >= &(1, 3) {
                    out.push(ffi::egl::RENDERABLE_TYPE as raw::c_int);
                    out.push(ffi::egl::OPENGL_ES_BIT as raw::c_int);
                    out.push(ffi::egl::CONFORMANT as raw::c_int);
                    out.push(ffi::egl::OPENGL_ES_BIT as raw::c_int);
                }
            }
            (Api::OpenGl, _) => {
                if egl_version < &(1, 3) {
                    return Err(CreationError::NoAvailablePixelFormat);
                }
                out.push(ffi::egl::RENDERABLE_TYPE as raw::c_int);
                out.push(ffi::egl::OPENGL_BIT as raw::c_int);
                out.push(ffi::egl::CONFORMANT as raw::c_int);
                out.push(ffi::egl::OPENGL_BIT as raw::c_int);
            }
            (_, _) => unimplemented!(),
        };

        if let Some(hardware_accelerated) = pf_reqs.hardware_accelerated {
            out.push(ffi::egl::CONFIG_CAVEAT as raw::c_int);
            out.push(if hardware_accelerated {
                ffi::egl::NONE as raw::c_int
            } else {
                ffi::egl::SLOW_CONFIG as raw::c_int
            });
        }

        if let Some(color) = pf_reqs.color_bits {
            out.push(ffi::egl::RED_SIZE as raw::c_int);
            out.push((color / 3) as raw::c_int);
            out.push(ffi::egl::GREEN_SIZE as raw::c_int);
            out.push((color / 3 + if color % 3 != 0 { 1 } else { 0 }) as raw::c_int);
            out.push(ffi::egl::BLUE_SIZE as raw::c_int);
            out.push((color / 3 + if color % 3 == 2 { 1 } else { 0 }) as raw::c_int);
        }

        if let Some(alpha) = pf_reqs.alpha_bits {
            out.push(ffi::egl::ALPHA_SIZE as raw::c_int);
            out.push(alpha as raw::c_int);
        }

        if let Some(depth) = pf_reqs.depth_bits {
            out.push(ffi::egl::DEPTH_SIZE as raw::c_int);
            out.push(depth as raw::c_int);
        }

        if let Some(stencil) = pf_reqs.stencil_bits {
            out.push(ffi::egl::STENCIL_SIZE as raw::c_int);
            out.push(stencil as raw::c_int);
        }

        if let Some(true) = pf_reqs.double_buffer {
            return Err(CreationError::NoAvailablePixelFormat);
        }

        if let Some(multisampling) = pf_reqs.multisampling {
            out.push(ffi::egl::SAMPLES as raw::c_int);
            out.push(multisampling as raw::c_int);
        }

        if pf_reqs.stereoscopy {
            return Err(CreationError::NoAvailablePixelFormat);
        }

        if let Some(xid) = pf_reqs.x11_visual_xid {
            out.push(ffi::egl::NATIVE_VISUAL_ID as raw::c_int);
            out.push(xid as raw::c_int);
        }

        // FIXME: srgb is not taken into account

        match pf_reqs.release_behavior {
            ReleaseBehavior::Flush => (),
            ReleaseBehavior::None => {
                // TODO: with EGL you need to manually set the behavior
                unimplemented!()
            }
        }

        out.push(ffi::egl::NONE as raw::c_int);
        out
    };

    // calling `eglChooseConfig`
    let mut num_configs = std::mem::zeroed();
    if egl.ChooseConfig(display, descriptor.as_ptr(), std::ptr::null_mut(), 0, &mut num_configs)
        == 0
    {
        return Err(CreationError::OsError("eglChooseConfig failed".to_string()));
    }

    if num_configs == 0 {
        return Err(CreationError::NoAvailablePixelFormat);
    }

    let mut config_ids = Vec::with_capacity(num_configs as usize);
    config_ids.resize_with(num_configs as usize, || std::mem::zeroed());
    if egl.ChooseConfig(
        display,
        descriptor.as_ptr(),
        config_ids.as_mut_ptr(),
        num_configs,
        &mut num_configs,
    ) == 0
    {
        return Err(CreationError::OsError("eglChooseConfig failed".to_string()));
    }

    // We're interested in those configs which allow our desired VSync.
    let desired_swap_interval = if opengl.vsync { 1 } else { 0 };

    let config_ids = config_ids
        .into_iter()
        .filter(|&config| {
            let mut min_swap_interval = 0;
            let _res = egl.GetConfigAttrib(
                display,
                config,
                ffi::egl::MIN_SWAP_INTERVAL as ffi::egl::types::EGLint,
                &mut min_swap_interval,
            );

            if desired_swap_interval < min_swap_interval {
                return false;
            }

            let mut max_swap_interval = 0;
            let _res = egl.GetConfigAttrib(
                display,
                config,
                ffi::egl::MAX_SWAP_INTERVAL as ffi::egl::types::EGLint,
                &mut max_swap_interval,
            );

            if desired_swap_interval > max_swap_interval {
                return false;
            }

            true
        })
        .collect::<Vec<_>>();

    if config_ids.is_empty() {
        return Err(CreationError::NoAvailablePixelFormat);
    }

    let config_id =
        config_selector(config_ids, display).map_err(|_| CreationError::NoAvailablePixelFormat)?;

    // analyzing each config
    macro_rules! attrib {
        ($egl:expr, $display:expr, $config:expr, $attr:expr) => {{
            let mut value = std::mem::zeroed();
            let res = $egl.GetConfigAttrib(
                $display,
                $config,
                $attr as ffi::egl::types::EGLint,
                &mut value,
            );
            if res == 0 {
                return Err(CreationError::OsError("eglGetConfigAttrib failed".to_string()));
            }
            value
        }};
    }

    let desc = PixelFormat {
        hardware_accelerated: attrib!(egl, display, config_id, ffi::egl::CONFIG_CAVEAT)
            != ffi::egl::SLOW_CONFIG as i32,
        color_bits: attrib!(egl, display, config_id, ffi::egl::RED_SIZE) as u8
            + attrib!(egl, display, config_id, ffi::egl::BLUE_SIZE) as u8
            + attrib!(egl, display, config_id, ffi::egl::GREEN_SIZE) as u8,
        alpha_bits: attrib!(egl, display, config_id, ffi::egl::ALPHA_SIZE) as u8,
        depth_bits: attrib!(egl, display, config_id, ffi::egl::DEPTH_SIZE) as u8,
        stencil_bits: attrib!(egl, display, config_id, ffi::egl::STENCIL_SIZE) as u8,
        stereoscopy: false,
        double_buffer: true,
        multisampling: match attrib!(egl, display, config_id, ffi::egl::SAMPLES) {
            0 | 1 => None,
            a => Some(a as u16),
        },
        srgb: false, // TODO: use EGL_KHR_gl_colorspace to know that
    };

    Ok((config_id, desc))
}

unsafe fn create_context(
    display: ffi::egl::types::EGLDisplay,
    egl_version: &(ffi::egl::types::EGLint, ffi::egl::types::EGLint),
    extensions: &[String],
    api: Api,
    version: (u8, u8),
    config_id: ffi::egl::types::EGLConfig,
    gl_debug: bool,
    gl_robustness: Robustness,
    share: ffi::EGLContext,
) -> Result<ffi::egl::types::EGLContext, CreationError> {
    let egl = EGL.as_ref().unwrap();

    let mut context_attributes = Vec::with_capacity(10);
    let mut flags = 0;

    if egl_version >= &(1, 5) || extensions.iter().any(|s| s == "EGL_KHR_create_context") {
        context_attributes.push(ffi::egl::CONTEXT_MAJOR_VERSION as i32);
        context_attributes.push(version.0 as i32);
        context_attributes.push(ffi::egl::CONTEXT_MINOR_VERSION as i32);
        context_attributes.push(version.1 as i32);

        // handling robustness
        let supports_robustness = egl_version >= &(1, 5)
            || extensions.iter().any(|s| s == "EGL_EXT_create_context_robustness");

        match gl_robustness {
            Robustness::NotRobust => (),

            Robustness::NoError => {
                if extensions.iter().any(|s| s == "EGL_KHR_create_context_no_error") {
                    context_attributes.push(ffi::egl::CONTEXT_OPENGL_NO_ERROR_KHR as raw::c_int);
                    context_attributes.push(1);
                }
            }

            Robustness::RobustNoResetNotification => {
                if supports_robustness {
                    context_attributes
                        .push(ffi::egl::CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY as raw::c_int);
                    context_attributes.push(ffi::egl::NO_RESET_NOTIFICATION as raw::c_int);
                    flags |= ffi::egl::CONTEXT_OPENGL_ROBUST_ACCESS as raw::c_int;
                } else {
                    return Err(CreationError::RobustnessNotSupported);
                }
            }

            Robustness::TryRobustNoResetNotification => {
                if supports_robustness {
                    context_attributes
                        .push(ffi::egl::CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY as raw::c_int);
                    context_attributes.push(ffi::egl::NO_RESET_NOTIFICATION as raw::c_int);
                    flags |= ffi::egl::CONTEXT_OPENGL_ROBUST_ACCESS as raw::c_int;
                }
            }

            Robustness::RobustLoseContextOnReset => {
                if supports_robustness {
                    context_attributes
                        .push(ffi::egl::CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY as raw::c_int);
                    context_attributes.push(ffi::egl::LOSE_CONTEXT_ON_RESET as raw::c_int);
                    flags |= ffi::egl::CONTEXT_OPENGL_ROBUST_ACCESS as raw::c_int;
                } else {
                    return Err(CreationError::RobustnessNotSupported);
                }
            }

            Robustness::TryRobustLoseContextOnReset => {
                if supports_robustness {
                    context_attributes
                        .push(ffi::egl::CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY as raw::c_int);
                    context_attributes.push(ffi::egl::LOSE_CONTEXT_ON_RESET as raw::c_int);
                    flags |= ffi::egl::CONTEXT_OPENGL_ROBUST_ACCESS as raw::c_int;
                }
            }
        }

        if gl_debug && egl_version >= &(1, 5) {
            context_attributes.push(ffi::egl::CONTEXT_OPENGL_DEBUG as i32);
            context_attributes.push(ffi::egl::TRUE as i32);

            // TODO: using this flag sometimes generates an error
            //       there was a change in the specs that added this flag, so it
            // may not be       supported everywhere ; however it is
            // not possible to know whether it is       supported or
            // not flags = flags |
            // ffi::egl::CONTEXT_OPENGL_DEBUG_BIT_KHR as i32;
        }

        // In at least some configurations, the Android emulator's GL
        // implementation advertises support for the
        // EGL_KHR_create_context extension but returns BAD_ATTRIBUTE
        // when CONTEXT_FLAGS_KHR is used.
        if flags != 0 {
            context_attributes.push(ffi::egl::CONTEXT_FLAGS_KHR as i32);
            context_attributes.push(flags);
        }
    } else if egl_version >= &(1, 3) && api == Api::OpenGlEs {
        // robustness is not supported
        match gl_robustness {
            Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => {
                return Err(CreationError::RobustnessNotSupported);
            }
            _ => (),
        }

        context_attributes.push(ffi::egl::CONTEXT_CLIENT_VERSION as i32);
        context_attributes.push(version.0 as i32);
    }

    context_attributes.push(ffi::egl::NONE as i32);

    let context = egl.CreateContext(display, config_id, share, context_attributes.as_ptr());

    if context.is_null() {
        match egl.GetError() as u32 {
            ffi::egl::BAD_MATCH | ffi::egl::BAD_ATTRIBUTE => {
                return Err(CreationError::OpenGlVersionNotSupported);
            }
            e => panic!("create_context: eglCreateContext failed: 0x{:x}", e),
        }
    }

    Ok(context)
}


text:
<?php

/**
 * Mockery
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://github.com/padraic/mockery/master/LICENSE
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to padraic@php.net so we can send you a copy immediately.
 */

namespace test\Mockery;

use Mockery\Adapter\Phpunit\MockeryTestCase;

class MockClassWithUnknownTypeHintTest extends MockeryTestCase
{
    protected function setUp()
    {
        $this->container = new \Mockery\Container;
    }

    protected function tearDown()
    {
        $this->container->mockery_close();
    }

    /** @test */
    public function itShouldSuccessfullyBuildTheMock()
    {
        $this->container->mock("test\Mockery\HasUnknownClassAsTypeHintOnMethod");
    }

}

class HasUnknownClassAsTypeHintOnMethod
{
    public function foo(\UnknownTestClass\Bar $bar)
    {

    }
}


text:
package at.illecker.storm.commons.dict;

import java.util.Set;

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

import at.illecker.storm.commons.Configuration;
import at.illecker.storm.commons.util.io.FileUtils;

public class FirstNames {
  private static final Logger LOG = LoggerFactory.getLogger(FirstNames.class);
  private static final FirstNames INSTANCE = new FirstNames();

  private Set<String> m_firstNames = null;

  private FirstNames() {
    for (String file : Configuration.getFirstNames()) {
      LOG.info("Load FirstNames from: " + file);
      if (m_firstNames == null) {
        m_firstNames = FileUtils.readFile(file, true);
      } else {
        m_firstNames.addAll(FileUtils.readFile(file, true));
      }
    }
  }

  public static FirstNames getInstance() {
    return INSTANCE;
  }

  public boolean isFirstName(String value) {
    return m_firstNames.contains(value.toLowerCase());
  }

  public static void main(String[] args) {
    FirstNames firstNames = FirstNames.getInstance();
    // test FirstNames
    String[] testFirstNames = new String[] { "Kevin", "Martin", "martin",
        "justin" };
    for (String s : testFirstNames) {
      System.out
          .println("isFirstName(" + s + "): " + firstNames.isFirstName(s));
    }
  }
}


text:
bower install --save 'https://github.com/mibamur/disqus-comments.git#master'
bower install --save 'https://github.com/marcus7777/development.git#master'
bower install --save 'https://github.com/marcus7777/utilities.git#master'
bower install --save 'https://github.com/community-polymer-elements/polymer-third-party.git#master'

# get list files
ls bower_components/community-polymer-elements/catalog_patch/ > list_patch

# copy files
cp -rf bower_components/community-polymer-elements/catalog_patch/* ./
mkdir -p dist/images/
cp -rf app/images/polymer.svg dist/images/
cp -rf favicons dist/favicons
cp -rf favicons app/favicons

# run
./disqus.sh
./index_hr.sh
./index_logo.sh
./index_theme.sh
./favicons.sh
node add_json.js

# remove
echo "removing"
for i in `cat list_patch`; do rm -rf $i; done
rm list_patch


text:
using namespace Ogre;
using namespace OgreBites;

const uint32 NonRefractiveSurfaces  = 0x00000001;
const uint32 RefractiveSurfaces     = 0x00000002;
const uint32 ReflectedSurfaces      = 0x00000004;
const uint32 RegularSurfaces        = NonRefractiveSurfaces|ReflectedSurfaces;

class _OgreSampleClassExport Sample_Fresnel : public SdkSample, public CompositorWorkspaceListener
{
    uint32 mPreviousVisibilityFlags;
public:

    Sample_Fresnel() : NUM_FISH(30), NUM_FISH_WAYPOINTS(10), FISH_PATH_LENGTH(200), FISH_SCALE(2)
    {
        mInfo["Title"] = "Fresnel";
        mInfo["Description"] = "Shows how to create reflections and refractions using render-to-texture, "
                                "shaders and visibility mask, completely controlled via the compositor.\n"
                                "See Fresnel.compositor and C++ code on how to setup the pipeline.\n\n"
                                "NOTE: This demo is a bit outdated. Typical AAA games use screen-space "
                                "refractions, which are bit less accurate but avoid an extra scene pass.\n"
                                "This other technique is explained in GPU Gems 2, Chapter 19 "
                                "'Generic Refraction Simulation'";
        mInfo["Thumbnail"] = "thumb_fresnel.png";
        mInfo["Category"] = "API Usage";
    }

    ~Sample_Fresnel()
    {
    }

    StringVector getRequiredPlugins()
    {
        StringVector names;
        if (!GpuProgramManager::getSingleton().isSyntaxSupported("glsles") && !GpuProgramManager::getSingleton().isSyntaxSupported("glsl150"))
            names.push_back("Cg Program Manager");
        return names;
    }

    void testCapabilities(const RenderSystemCapabilities* caps)
    {
        if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !caps->hasCapability(RSC_FRAGMENT_PROGRAM))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your graphics card does not support vertex and fragment"
                " programs, so you cannot run this sample. Sorry!", "FresnelSample::testCapabilities");
        }

        if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") &&
            !GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0") &&
            !GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") &&
            !GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4") &&
            !GpuProgramManager::getSingleton().isSyntaxSupported("glsles") &&
            !GpuProgramManager::getSingleton().isSyntaxSupported("glsl"))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your graphics card does not support advanced fragment"
                " programs, so you cannot run this sample. Sorry!", "FresnelSample::testCapabilities");
        }
    }

    bool frameRenderingQueued(const FrameEvent &evt)
    {
        // update the fish spline path animations and loop as needed
        mFishAnimTime += evt.timeSinceLastFrame;
        while (mFishAnimTime >= FISH_PATH_LENGTH) mFishAnimTime -= FISH_PATH_LENGTH;

        for (unsigned int i = 0; i < NUM_FISH; i++)
        {
            mFishAnimStates[i]->addTime(evt.timeSinceLastFrame * 2);  // update fish swim animation

            // set the new position based on the spline path and set the direction based on displacement
            Vector3 lastPos = mFishNodes[i]->getPosition();
            mFishNodes[i]->setPosition(mFishSplines[i].interpolate(mFishAnimTime / FISH_PATH_LENGTH));
            mFishNodes[i]->setDirection(mFishNodes[i]->getPosition() - lastPos, Node::TS_PARENT, Vector3::NEGATIVE_UNIT_X);
            mFishNodes[i]->setFixedYawAxis(true);
        }

        return SdkSample::frameRenderingQueued(evt);
    }

    virtual void passPreExecute( CompositorPass *pass )
    {
        //Demo Note: Be very careful when modifying the camera in a listener.
        //Ogre 2.0 is more sensitive to changes mid-render than 1.x. For example,
        //Ogre has already built the light list of all objects seen by all cameras.
        //If we altered the camera's position, some entities would be incorrectly
        //lit or shadowed.
        if( pass->getDefinition()->mIdentifier == 59645 )
        {
            mCamera->setAutoAspectRatio( false );
            mCamera->enableReflection(mWaterPlane);
            mCamera->enableCustomNearClipPlane(mWaterPlane);
        }
        else if( pass->getDefinition()->mIdentifier == 59646 )
        {
            mCamera->setAutoAspectRatio( false );
            mCamera->enableCustomNearClipPlane(mInvWaterPlane);
            mCamera->disableCustomNearClipPlane();
        }
        else
        {
            mCamera->setAutoAspectRatio( true );
            mCamera->disableReflection();
            mCamera->disableCustomNearClipPlane();
        }
    }

protected:

    virtual CompositorWorkspace* setupCompositor()
    {
        // The compositor scripts are also part of this sample. Go to Fresnel.compositor
        // to see the sample scripts on how to setup the rendering pipeline.
        CompositorManager2 *compositorManager = mRoot->getCompositorManager2();

        const Ogre::IdString workspaceName( "FresnelSampleWorkspace" );
        CompositorWorkspace *workspace = compositorManager->addWorkspace( mSceneMgr, mWindow,
                                                                    mCamera, workspaceName, true );
        workspace->setListener( this );

        return workspace;
    }

    void setupContent()
    {
        mPreviousVisibilityFlags = MovableObject::getDefaultVisibilityFlags();
        MovableObject::setDefaultVisibilityFlags( RegularSurfaces );

        mCamera->setPosition(-50, 125, 760);
        mCameraMan->setTopSpeed(280);

        mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));  // set ambient light

        mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox");  // set a skybox

        // make the scene's main light come from above
        Light* l = mSceneMgr->createLight();
        mSceneMgr->createSceneNode()->attachObject( l );
        l->setType(Light::LT_DIRECTIONAL);
        l->setDirection(Vector3::NEGATIVE_UNIT_Y);

        setupWater();
        setupProps();
        setupFish();
    }

    void setupWater()
    {
        // create our water plane mesh
        mWaterPlane = Plane(Vector3::UNIT_Y, 0);
        mInvWaterPlane=Plane(Vector3::NEGATIVE_UNIT_Y, 0);
        MeshManager::getSingleton().createPlane("water", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            mWaterPlane, 700, 1300, 10, 10, true, 1, 3, 5, Vector3::UNIT_Z);

        // create a water entity using our mesh, give it the shader material, and attach it to the origin
        mWater = mSceneMgr->createEntity("water");
        mWater->setName("Water");
        mWater->setMaterialName("Examples/FresnelReflectionRefraction");
        mWater->setVisibilityFlags( RefractiveSurfaces );
        mWater->setRenderQueueGroup( 95 );
        mSceneMgr->getRootSceneNode()->attachObject(mWater);
    }

    void setupProps()
    {
        Entity* ent;

        // setting up props might take a while, so create a progress bar for visual feedback
        ProgressBar* pb = mTrayMgr->createProgressBar(TL_CENTER, "FresnelBuildingBar", "Creating Props...", 280, 100);
        mTrayMgr->showBackdrop("SdkTrays/Shade");

        pb->setComment("Upper Bath");
        ent = mSceneMgr->createEntity("RomanBathUpper.mesh" );
        ent->setName("UpperBath");
        mSceneMgr->getRootSceneNode()->attachObject(ent);
        mSurfaceEnts.push_back(ent);
        pb->setProgress(0.4);

        pb->setComment("Columns");
        ent = mSceneMgr->createEntity("columns.mesh");
        ent->setName("Columns");
        mSceneMgr->getRootSceneNode()->attachObject(ent);
        mSurfaceEnts.push_back(ent);
        pb->setProgress(0.5);

        pb->setComment("Ogre Head");
        ent = mSceneMgr->createEntity("ogrehead.mesh");
        ent->setName("Head");
        ent->setMaterialName("RomanBath/OgreStone");
        mSurfaceEnts.push_back(ent);
        pb->setProgress(0.6);

        SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
        headNode->setPosition(-350, 55, 130);
        headNode->yaw(Degree(90));
        headNode->attachObject(ent);

        pb->setComment("Lower Bath");
        ent = mSceneMgr->createEntity("RomanBathLower.mesh");
        ent->setName("LowerBath");
        mSceneMgr->getRootSceneNode()->attachObject(ent);
        mSubmergedEnts.push_back(ent);
        pb->setProgress(1);

        mTrayMgr->destroyWidget(pb);
        mTrayMgr->hideBackdrop();
    }

    void setupFish()
    {
        mFishNodes.resize(NUM_FISH);
        mFishAnimStates.resize(NUM_FISH);
        mFishSplines.resize(NUM_FISH);

        for (unsigned int i = 0; i < NUM_FISH; i++)
        {
            // create fish entity
            Entity* ent = mSceneMgr->createEntity("fish.mesh");
            ent->setName("Fish" + StringConverter::toString(i + 1));
            ent->setVisibilityFlags( NonRefractiveSurfaces ); //Fishes are underwater, and hence don't reflect
            mSubmergedEnts.push_back(ent);

            // create an appropriately scaled node and attach the entity
            mFishNodes[i] = mSceneMgr->getRootSceneNode()->createChildSceneNode();
            mFishNodes[i]->setScale(Vector3::UNIT_SCALE * FISH_SCALE);
            mFishNodes[i]->attachObject(ent);

            // enable and save the swim animation state
            mFishAnimStates[i] = ent->getAnimationState("swim");
            mFishAnimStates[i]->setEnabled(true);

            mFishSplines[i].setAutoCalculate(false);  // save the tangent calculation for when we are all done

            // generate random waypoints for the fish to swim through
            for (unsigned int j = 0; j < NUM_FISH_WAYPOINTS; j++)
            {
                Vector3 pos(Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700);

                if (j > 0)  // make sure the waypoint isn't too far from the last, or our fish will be turbo-fish
                {
                    const Vector3& lastPos = mFishSplines[i].getPoint(j - 1);
                    Vector3 delta = pos - lastPos;
                    if (delta.length() > 750) pos = lastPos + delta.normalisedCopy() * 750;
                }

                mFishSplines[i].addPoint(pos);
            }

            // close the spline and calculate all the tangents at once
            mFishSplines[i].addPoint(mFishSplines[i].getPoint(0));
            mFishSplines[i].recalcTangents();
        }

        mFishAnimTime = 0;
    }

    void cleanupContent()
    {
        mSurfaceEnts.clear();
        mSubmergedEnts.clear();
        mFishNodes.clear();
        mFishAnimStates.clear();
        mFishSplines.clear();

        MeshManager::getSingleton().remove("water");

        //Restore global settings
        MovableObject::setDefaultVisibilityFlags( mPreviousVisibilityFlags );
    }

    const unsigned int NUM_FISH;
    const unsigned int NUM_FISH_WAYPOINTS;
    const unsigned int FISH_PATH_LENGTH;
    const Real FISH_SCALE;
    std::vector<Entity*> mSurfaceEnts;
    std::vector<Entity*> mSubmergedEnts;
    Plane mWaterPlane;
    Plane mInvWaterPlane;
    Entity* mWater;
    std::vector<SceneNode*> mFishNodes;
    std::vector<AnimationState*> mFishAnimStates;
    std::vector<SimpleSpline> mFishSplines;
    Real mFishAnimTime;
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<locale xmlns="http://purl.org/net/xbiblio/csl" version="1.0" xml:lang="zh-TW">
  <info>
    <translator>
      <name>sati-bodhi</name>
    </translator>
    <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
    <updated>2014-05-15T23:31:02+00:00</updated>
  </info>
  <style-options punctuation-in-quote="false"/>
  <date form="text">
    <date-part name="year" suffix="年"/>
    <date-part name="month" form="numeric" suffix="月"/>
    <date-part name="day" suffix="日"/>
  </date>
  <date form="numeric">
    <date-part name="year"/>
    <date-part name="month" form="numeric-leading-zeros" prefix="/"/>
    <date-part name="day" form="numeric-leading-zeros" prefix="/"/>
  </date>
  <terms>
    <term name="advance-online-publication">advance online publication</term>
    <term name="album">album</term>
    <term name="audio-recording">audio recording</term>
    <term name="film">film</term>
    <term name="henceforth">henceforth</term>
    <term name="loc-cit">loc. cit.</term> <!-- like ibid., the abbreviated form is the regular form  -->
    <term name="no-place">no place</term>
    <term name="no-place" form="short">n.p.</term>
    <term name="no-publisher">no publisher</term> <!-- sine nomine -->
    <term name="no-publisher" form="short">n.p.</term>
    <term name="on">on</term>
    <term name="op-cit">op. cit.</term> <!-- like ibid., the abbreviated form is the regular form  -->
    <term name="original-work-published">original work published</term>
    <term name="personal-communication">私人通訊</term>
    <term name="podcast">podcast</term>
    <term name="podcast-episode">podcast episode</term>
    <term name="preprint">preprint</term>
    <term name="radio-broadcast">radio broadcast</term>
    <term name="radio-series">radio series</term>
    <term name="radio-series-episode">radio series episode</term>
    <term name="special-issue">special issue</term>
    <term name="special-section">special section</term>
    <term name="television-broadcast">television broadcast</term>
    <term name="television-series">television series</term>
    <term name="television-series-episode">television series episode</term>
    <term name="video">video</term>
    <term name="working-paper">working paper</term>
    <term name="accessed">引見於</term>
    <term name="and">及</term>
    <term name="and others">及其他</term>
    <term name="anonymous">作者不詳</term>
    <term name="anonymous" form="short">無名氏</term>
    <term name="at">於</term>
    <term name="available at">載於</term>
    <term name="by">著</term>
    <term name="circa">介於</term>
    <term name="circa" form="short">約</term>
    <term name="cited">見引於</term>
    <term name="edition">版本</term>
    <term name="edition" form="short">本</term>
    <term name="et-al">等</term>
    <term name="forthcoming">即將出版</term>
    <term name="from">從</term>
    <term name="ibid">同上</term>
    <term name="in">收入</term>
    <term name="in press">印行中</term>
    <term name="internet">互聯網</term>
    <term name="interview">訪談</term>
    <term name="letter">信函</term>
    <term name="no date">日期不詳</term>
    <term name="no date" form="short">不詳</term>
    <term name="online">線上</term>
    <term name="presented at">發表於</term>
    <term name="reference">參考</term>
    <term name="reference" form="short">參</term>
    <term name="retrieved">讀取於</term>
    <term name="scale">比例</term>
    <term name="version">版</term>

    <!-- LONG ITEM TYPE FORMS -->
    <term name="article">preprint</term>
    <term name="article-journal">journal article</term>
    <term name="article-magazine">magazine article</term>
    <term name="article-newspaper">newspaper article</term>
    <term name="bill">bill</term>
    <term name="book">book</term>
    <term name="broadcast">broadcast</term>
    <term name="chapter">book chapter</term>
    <term name="classic">classic</term>
    <term name="collection">collection</term>
    <term name="dataset">dataset</term>
    <term name="document">document</term>
    <term name="entry">entry</term>
    <term name="entry-dictionary">dictionary entry</term>
    <term name="entry-encyclopedia">encyclopedia entry</term>
    <term name="event">event</term>
    <!-- figure is in the list of locator terms -->
    <term name="graphic">graphic</term>
    <term name="hearing">hearing</term>
    <term name="interview">interview</term>
    <term name="legal_case">legal case</term>
    <term name="legislation">legislation</term>
    <term name="manuscript">manuscript</term>
    <term name="map">map</term>
    <term name="motion_picture">video recording</term>
    <term name="musical_score">musical score</term>
    <term name="pamphlet">pamphlet</term>
    <term name="paper-conference">conference paper</term>
    <term name="patent">patent</term>
    <term name="performance">performance</term>
    <term name="periodical">periodical</term>
    <term name="personal_communication">私人通訊</term>
    <term name="post">post</term>
    <term name="post-weblog">blog post</term>
    <term name="regulation">regulation</term>
    <term name="report">report</term>
    <term name="review">review</term>
    <term name="review-book">book review</term>
    <term name="software">software</term>
    <term name="song">audio recording</term>
    <term name="speech">presentation</term>
    <term name="standard">standard</term>
    <term name="thesis">thesis</term>
    <term name="treaty">treaty</term>
    <term name="webpage">webpage</term>

    <!-- SHORT ITEM TYPE FORMS -->
    <term name="article-journal" form="short">journal art.</term>
    <term name="article-magazine" form="short">mag. art.</term>
    <term name="article-newspaper" form="short">newspaper art.</term>
    <term name="book" form="short">bk.</term>
    <term name="chapter" form="short">bk. chap.</term>
    <term name="document" form="short">doc.</term>
    <!-- figure is in the list of locator terms -->
    <term name="graphic" form="short">graph.</term>
    <term name="interview" form="short">interv.</term>
    <term name="manuscript" form="short">MS</term>
    <term name="motion_picture" form="short">video rec.</term>
    <term name="report" form="short">rep.</term>
    <term name="review" form="short">rev.</term>
    <term name="review-book" form="short">bk. rev.</term>
    <term name="song" form="short">audio rec.</term>

    <!-- HISTORICAL ERA TERMS -->
    <term name="ad">西元</term>
    <term name="bc">西元前</term>
    <term name="bce">BCE</term>
    <term name="ce">CE</term>

    <!-- PUNCTUATION -->
    <term name="open-quote">「</term>
    <term name="close-quote">」</term>
    <term name="open-inner-quote">『</term>
    <term name="close-inner-quote">』</term>
    <term name="page-range-delimiter">–</term>
    <term name="colon">:</term>
    <term name="comma">,</term>
    <term name="semicolon">;</term>

    <!-- ORDINALS -->
    <term name="ordinal"></term>

    <!-- LONG ORDINALS -->
    <term name="long-ordinal-01">一</term>
    <term name="long-ordinal-02">二</term>
    <term name="long-ordinal-03">三</term>
    <term name="long-ordinal-04">四</term>
    <term name="long-ordinal-05">五</term>
    <term name="long-ordinal-06">六</term>
    <term name="long-ordinal-07">七</term>
    <term name="long-ordinal-08">八</term>
    <term name="long-ordinal-09">九</term>
    <term name="long-ordinal-10">十</term>

    <!-- LONG LOCATOR FORMS -->
    <term name="act">
      <single>act</single>
      <multiple>acts</multiple>
    </term>
    <term name="appendix">
      <single>appendix</single>
      <multiple>appendices</multiple>
    </term>
    <term name="article-locator">
      <single>article</single>
      <multiple>articles</multiple>
    </term>
    <term name="canon">
      <single>canon</single>
      <multiple>canons</multiple>
    </term>
    <term name="elocation">
      <single>location</single>
      <multiple>locations</multiple>
    </term>
    <term name="equation">
      <single>equation</single>
      <multiple>equations</multiple>
    </term>
    <term name="rule">
      <single>rule</single>
      <multiple>rules</multiple>
    </term>
    <term name="scene">
      <single>scene</single>
      <multiple>scenes</multiple>
    </term>
    <term name="table">
      <single>table</single>
      <multiple>tables</multiple>
    </term>
    <term name="timestamp"> <!-- generally blank -->
      <single></single>
      <multiple></multiple>
    </term>
    <term name="title-locator">
      <single>title</single>
      <multiple>titles</multiple>
    </term>
    <term name="book">冊</term>
    <term name="chapter">章</term>
    <term name="column">欄</term>
    <term name="figure">圖表</term>
    <term name="folio">版</term>
    <term name="issue">期</term>
    <term name="line">行</term>
    <term name="note">註腳</term>
    <term name="opus">作品</term>
    <term name="page">頁</term>
    <term name="number-of-pages">總頁數</term>
    <term name="paragraph">段落</term>
    <term name="part">部分</term>
    <term name="section">節</term>
    <term name="sub-verbo">另見</term>
    <term name="verse">篇</term>
    <term name="volume">卷</term>

    <!-- SHORT LOCATOR FORMS -->
    <term name="appendix">
      <single>app.</single>
      <multiple>apps.</multiple>
    </term>
    <term name="article-locator">
      <single>art.</single>
      <multiple>arts.</multiple>
    </term>
    <term name="elocation">
      <single>loc.</single>
      <multiple>locs.</multiple>
    </term>
    <term name="equation">
      <single>eq.</single>
      <multiple>eqs.</multiple>
    </term>
    <term name="rule">
      <single>r.</single>
      <multiple>rr.</multiple>
    </term>
    <term name="scene">
      <single>sc.</single>
      <multiple>scs.</multiple>
    </term>
    <term name="table">
      <single>tbl.</single>
      <multiple>tbls.</multiple>
    </term>
    <term name="timestamp"> <!-- generally blank -->
      <single></single>
      <multiple></multiple>
    </term>
    <term name="title-locator">
      <single>tit.</single>
      <multiple>tits.</multiple>
    </term>
    <term name="book" form="short">冊</term>
    <term name="chapter" form="short">章</term>
    <term name="column" form="short">欄</term>
    <term name="figure" form="short">圖</term>
    <term name="issue" form="short">期</term>
    <term name="line" form="short">行</term>
    <term name="note" form="short">註</term>
    <term name="opus" form="short">op.</term>
    <term name="page" form="short">頁</term>
    <term name="number-of-pages" form="short">共</term>
    <term name="paragraph" form="short">段</term>
    <term name="part" form="short">部</term>
    <term name="section" form="short">節</term>
    <term name="sub-verbo" form="short">另見</term>
    <term name="verse" form="short">篇</term>
    <term name="volume" form="short">卷</term>

    <!-- SYMBOL LOCATOR FORMS -->
    <term name="paragraph" form="symbol">
      <single>¶</single>
      <multiple>¶¶</multiple>
    </term>
    <term name="section" form="symbol">
      <single>§</single>
      <multiple>§§</multiple>
    </term>

    <!-- LONG ROLE FORMS -->
    <term name="chair">
      <single>chair</single>
      <multiple>chairs</multiple>
    </term>
    <term name="compiler">
      <single>compiler</single>
      <multiple>compilers</multiple>
    </term>
    <term name="contributor">
      <single>contributor</single>
      <multiple>contributors</multiple>
    </term>
    <term name="curator">
      <single>curator</single>
      <multiple>curators</multiple>
    </term>
    <term name="executive-producer">
      <single>executive producer</single>
      <multiple>executive producers</multiple>
    </term>
    <term name="guest">
      <single>guest</single>
      <multiple>guests</multiple>
    </term>
    <term name="host">
      <single>host</single>
      <multiple>hosts</multiple>
    </term>
    <term name="narrator">
      <single>narrator</single>
      <multiple>narrators</multiple>
    </term>
    <term name="organizer">
      <single>organizer</single>
      <multiple>organizers</multiple>
    </term>
    <term name="performer">
      <single>performer</single>
      <multiple>performers</multiple>
    </term>
    <term name="producer">
      <single>producer</single>
      <multiple>producers</multiple>
    </term>
    <term name="script-writer">
      <single>writer</single>
      <multiple>writers</multiple>
    </term>
    <term name="series-creator">
      <single>series creator</single>
      <multiple>series creators</multiple>
    </term>
    <term name="author">作者</term>
    <term name="director">導演</term>
    <term name="editor">編輯</term>
    <term name="editorial-director">主編</term>
    <term name="illustrator">繪圖師</term>
    <term name="interviewer">採訪員</term>
    <term name="recipient">收信人</term>
    <term name="translator">翻譯員</term>
    <term name="editortranslator">編譯員</term>
    <term name="reviewed-author">評論人</term>

    <!-- SHORT ROLE FORMS -->
    <term name="compiler" form="short">
      <single>comp.</single>
      <multiple>comps.</multiple>
    </term>
    <term name="contributor" form="short">
      <single>contrib.</single>
      <multiple>contribs.</multiple>
    </term>
    <term name="curator" form="short">
      <single>cur.</single>
      <multiple>curs.</multiple>
    </term>
    <term name="executive-producer" form="short">
      <single>exec. prod.</single>
      <multiple>exec. prods.</multiple>
    </term>
    <term name="narrator" form="short">
      <single>narr.</single>
      <multiple>narrs.</multiple>
    </term>
    <term name="organizer" form="short">
      <single>org.</single>
      <multiple>orgs.</multiple>
    </term>
    <term name="performer" form="short">
      <single>perf.</single>
      <multiple>perfs.</multiple>
    </term>
    <term name="producer" form="short">
      <single>prod.</single>
      <multiple>prods.</multiple>
    </term>
    <term name="script-writer" form="short">
      <single>writ.</single>
      <multiple>writs.</multiple>
    </term>
    <term name="series-creator" form="short">
      <single>cre.</single>
      <multiple>cres.</multiple>
    </term>
    <term name="author" form="short">作者</term>
    <term name="director" form="short">導演</term>
    <term name="editor" form="short">編輯</term>
    <term name="editorial-director" form="short">主編</term>
    <term name="illustrator" form="short">繪圖師</term>
    <term name="interviewer" form="short">採訪員</term>
    <term name="recipient" form="short">收信人</term>
    <term name="translator" form="short">翻譯員</term>
    <term name="editortranslator" form="short">編譯員</term>
    <term name="reviewed-author" form="short">評論人</term>

    <!-- VERB ROLE FORMS -->
    <term name="chair" form="verb">chaired by</term>
    <term name="compiler" form="verb">compiled by</term>
    <term name="contributor" form="verb">with</term>
    <term name="curator" form="verb">curated by</term>
    <term name="executive-producer" form="verb">executive produced by</term>
    <term name="guest" form="verb">with guest</term>
    <term name="host" form="verb">hosted by</term>
    <term name="narrator" form="verb">narrated by</term>
    <term name="organizer" form="verb">organized by</term>
    <term name="performer" form="verb">performed by</term>
    <term name="producer" form="verb">produced by</term>
    <term name="script-writer" form="verb">written by</term>
    <term name="series-creator" form="verb">created by</term>
    <term name="author" form="verb">著</term>
    <term name="container-author" form="verb">著</term>
    <term name="director" form="verb">指導</term>
    <term name="editor" form="verb">編輯</term>
    <term name="collection-editor" form="verb">點校</term>
    <term name="editorial-director" form="verb">主編</term>
    <term name="illustrator" form="verb">繪圖</term>
    <term name="interviewer" form="verb">採訪</term>
    <term name="recipient" form="verb">受函</term>
    <term name="reviewed-author" form="verb">點評</term>
    <term name="translator" form="verb">翻譯</term>
    <term name="editortranslator" form="verb">編譯</term>

    <!-- SHORT VERB ROLE FORMS -->
    <term name="compiler" form="verb-short">comp. by</term>
    <term name="contributor" form="verb-short">w.</term>
    <term name="curator" form="verb-short">cur. by</term>
    <term name="executive-producer" form="verb-short">exec. prod. by</term>
    <term name="guest" form="verb-short">w. guest</term>
    <term name="host" form="verb-short">hosted by</term>
    <term name="narrator" form="verb-short">narr. by</term>
    <term name="organizer" form="verb-short">org. by</term>
    <term name="performer" form="verb-short">perf. by</term>
    <term name="producer" form="verb-short">prod. by</term>
    <term name="script-writer" form="verb-short">writ. by</term>
    <term name="series-creator" form="verb-short">cre. by</term>
    <term name="director" form="verb-short">導</term>
    <term name="editor" form="verb-short">編</term>
    <term name="collection-editor" form="verb-short">校</term>
    <term name="editorial-director" form="verb-short">編</term>
    <term name="illustrator" form="verb-short">繪</term>
    <term name="translator" form="verb-short">譯</term>
    <term name="reviewed-author" form="verb-short">評</term>

    <!-- LONG MONTH FORMS -->
    <term name="month-01">一月</term>
    <term name="month-02">二月</term>
    <term name="month-03">三月</term>
    <term name="month-04">四月</term>
    <term name="month-05">五月</term>
    <term name="month-06">六月</term>
    <term name="month-07">七月</term>
    <term name="month-08">八月</term>
    <term name="month-09">九月</term>
    <term name="month-10">十月</term>
    <term name="month-11">十一月</term>
    <term name="month-12">十二月</term>

    <!-- SHORT MONTH FORMS -->
    <term name="month-01" form="short">1月</term>
    <term name="month-02" form="short">2月</term>
    <term name="month-03" form="short">3月</term>
    <term name="month-04" form="short">4月</term>
    <term name="month-05" form="short">5月</term>
    <term name="month-06" form="short">6月</term>
    <term name="month-07" form="short">7月</term>
    <term name="month-08" form="short">8月</term>
    <term name="month-09" form="short">9月</term>
    <term name="month-10" form="short">10月</term>
    <term name="month-11" form="short">11月</term>
    <term name="month-12" form="short">12月</term>

    <!-- SEASONS -->
    <term name="season-01">春</term>
    <term name="season-02">夏</term>
    <term name="season-03">秋</term>
    <term name="season-04">冬</term>
  </terms>
</locale>