<?php

use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Router\Exceptions\RouterException;
use Config\App;
use Config\Services;

// CodeIgniter URL Helpers

if (! function_exists('_get_uri')) {
    /**
     * Used by the other URL functions to build a
     * framework-specific URI based on the App config.
     *
     * @internal Outside of the framework this should not be used directly.
     *
     * @param string $relativePath May include queries or fragments
     *
     * @throws InvalidArgumentException For invalid paths or config
     */
    function _get_uri(string $relativePath = '', ?App $config = null): URI
    {
        $config ??= config('App');

        if ($config->baseURL === '') {
            throw new InvalidArgumentException('_get_uri() requires a valid baseURL.');
        }

        // If a full URI was passed then convert it
        if (is_int(strpos($relativePath, '://'))) {
            $full         = new URI($relativePath);
            $relativePath = URI::createURIString(null, null, $full->getPath(), $full->getQuery(), $full->getFragment());
        }

        $relativePath = URI::removeDotSegments($relativePath);

        // Build the full URL based on $config and $relativePath
        $url = rtrim($config->baseURL, '/ ') . '/';

        // Check for an index page
        if ($config->indexPage !== '') {
            $url .= $config->indexPage;

            // Check if we need a separator
            if ($relativePath !== '' && $relativePath[0] !== '/' && $relativePath[0] !== '?') {
                $url .= '/';
            }
        }

        $url .= $relativePath;

        $uri = new URI($url);

        // Check if the baseURL scheme needs to be coerced into its secure version
        if ($config->forceGlobalSecureRequests && $uri->getScheme() === 'http') {
            $uri->setScheme('https');
        }

        return $uri;
    }
}

if (! function_exists('site_url')) {
    /**
     * Returns a site URL as defined by the App config.
     *
     * @param mixed    $relativePath URI string or array of URI segments
     * @param App|null $config       Alternate configuration to use
     */
    function site_url($relativePath = '', ?string $scheme = null, ?App $config = null): string
    {
        // Convert array of segments to a string
        if (is_array($relativePath)) {
            $relativePath = implode('/', $relativePath);
        }

        $uri = _get_uri($relativePath, $config);

        return URI::createURIString($scheme ?? $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment());
    }
}

if (! function_exists('base_url')) {
    /**
     * Returns the base URL as defined by the App config.
     * Base URLs are trimmed site URLs without the index page.
     *
     * @param mixed  $relativePath URI string or array of URI segments
     * @param string $scheme
     */
    function base_url($relativePath = '', ?string $scheme = null): string
    {
        $config            = clone config('App');
        $config->indexPage = '';

        return rtrim(site_url($relativePath, $scheme, $config), '/');
    }
}

if (! function_exists('current_url')) {
    /**
     * Returns the current full URL based on the IncomingRequest.
     * String returns ignore query and fragment parts.
     *
     * @param bool                 $returnObject True to return an object instead of a string
     * @param IncomingRequest|null $request      A request to use when retrieving the path
     *
     * @return string|URI
     */
    function current_url(bool $returnObject = false, ?IncomingRequest $request = null)
    {
        $request ??= Services::request();
        $path = $request->getPath();

        // Append queries and fragments
        if ($query = $request->getUri()->getQuery()) {
            $path .= '?' . $query;
        }
        if ($fragment = $request->getUri()->getFragment()) {
            $path .= '#' . $fragment;
        }

        $uri = _get_uri($path);

        return $returnObject ? $uri : URI::createURIString($uri->getScheme(), $uri->getAuthority(), $uri->getPath());
    }
}

if (! function_exists('previous_url')) {
    /**
     * Returns the previous URL the current visitor was on. For security reasons
     * we first check in a saved session variable, if it exists, and use that.
     * If that's not available, however, we'll use a sanitized url from $_SERVER['HTTP_REFERER']
     * which can be set by the user so is untrusted and not set by certain browsers/servers.
     *
     * @return mixed|string|URI
     */
    function previous_url(bool $returnObject = false)
    {
        // Grab from the session first, if we have it,
        // since it's more reliable and safer.
        // Otherwise, grab a sanitized version from $_SERVER.
        $referer = $_SESSION['_ci_previous_url'] ?? Services::request()->getServer('HTTP_REFERER', FILTER_SANITIZE_URL);

        $referer ??= site_url('/');

        return $returnObject ? new URI($referer) : $referer;
    }
}

if (! function_exists('uri_string')) {
    /**
     * URL String
     *
     * Returns the path part of the current URL
     *
     * @param bool $relative Whether the resulting path should be relative to baseURL
     */
    function uri_string(bool $relative = false): string
    {
        return $relative
            ? ltrim(Services::request()->getPath(), '/')
            : Services::request()->getUri()->getPath();
    }
}

if (! function_exists('index_page')) {
    /**
     * Index page
     *
     * Returns the "index_page" from your config file
     *
     * @param App|null $altConfig Alternate configuration to use
     */
    function index_page(?App $altConfig = null): string
    {
        // use alternate config if provided, else default one
        $config = $altConfig ?? config(App::class);

        return $config->indexPage;
    }
}

if (! function_exists('anchor')) {
    /**
     * Anchor Link
     *
     * Creates an anchor based on the local URL.
     *
     * @param mixed    $uri        URI string or array of URI segments
     * @param string   $title      The link title
     * @param mixed    $attributes Any attributes
     * @param App|null $altConfig  Alternate configuration to use
     */
    function anchor($uri = '', string $title = '', $attributes = '', ?App $altConfig = null): string
    {
        // use alternate config if provided, else default one
        $config = $altConfig ?? config(App::class);

        $siteUrl = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config));
        // eliminate trailing slash
        $siteUrl = rtrim($siteUrl, '/');

        if ($title === '') {
            $title = $siteUrl;
        }

        if ($attributes !== '') {
            $attributes = stringify_attributes($attributes);
        }

        return '' . $title . '';
    }
}

if (! function_exists('anchor_popup')) {
    /**
     * Anchor Link - Pop-up version
     *
     * Creates an anchor based on the local URL. The link
     * opens a new window based on the attributes specified.
     *
     * @param string   $uri        the URL
     * @param string   $title      the link title
     * @param mixed    $attributes any attributes
     * @param App|null $altConfig  Alternate configuration to use
     */
    function anchor_popup($uri = '', string $title = '', $attributes = false, ?App $altConfig = null): string
    {
        // use alternate config if provided, else default one
        $config = $altConfig ?? config(App::class);

        $siteUrl = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config);
        $siteUrl = rtrim($siteUrl, '/');

        if ($title === '') {
            $title = $siteUrl;
        }

        if ($attributes === false) {
            return '" . $title . '';
        }

        if (! is_array($attributes)) {
            $attributes = [$attributes];

            // Ref: http://www.w3schools.com/jsref/met_win_open.asp
            $windowName = '_blank';
        } elseif (! empty($attributes['window_name'])) {
            $windowName = $attributes['window_name'];
            unset($attributes['window_name']);
        } else {
            $windowName = '_blank';
        }

        foreach (['width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0'] as $key => $val) {
            $atts[$key] = $attributes[$key] ?? $val;
            unset($attributes[$key]);
        }

        $attributes = stringify_attributes($attributes);

        return '' . $title . '';
    }
}

if (! function_exists('mailto')) {
    /**
     * Mailto Link
     *
     * @param string $email      the email address
     * @param string $title      the link title
     * @param mixed  $attributes any attributes
     */
    function mailto(string $email, string $title = '', $attributes = ''): string
    {
        if (trim($title) === '') {
            $title = $email;
        }

        return '' . $title . '';
    }
}

if (! function_exists('safe_mailto')) {
    /**
     * Encoded Mailto Link
     *
     * Create a spam-protected mailto link written in Javascript
     *
     * @param string $email      the email address
     * @param string $title      the link title
     * @param mixed  $attributes any attributes
     */
    function safe_mailto(string $email, string $title = '', $attributes = ''): string
    {
        if (trim($title) === '') {
            $title = $email;
        }

        $x = str_split('<a href="mailto:', 1);

        for ($i = 0, $l = strlen($email); $i < $l; $i++) {
            $x[] = '|' . ord($email[$i]);
        }

        $x[] = '"';

        if ($attributes !== '') {
            if (is_array($attributes)) {
                foreach ($attributes as $key => $val) {
                    $x[] = ' ' . $key . '="';

                    for ($i = 0, $l = strlen($val); $i < $l; $i++) {
                        $x[] = '|' . ord($val[$i]);
                    }

                    $x[] = '"';
                }
            } else {
                for ($i = 0, $l = mb_strlen($attributes); $i < $l; $i++) {
                    $x[] = mb_substr($attributes, $i, 1);
                }
            }
        }

        $x[] = '>';

        $temp = [];

        for ($i = 0, $l = strlen($title); $i < $l; $i++) {
            $ordinal = ord($title[$i]);

            if ($ordinal < 128) {
                $x[] = '|' . $ordinal;
            } else {
                if (empty($temp)) {
                    $count = ($ordinal < 224) ? 2 : 3;
                }

                $temp[] = $ordinal;

                if (count($temp) === $count) {
                    $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64);
                    $x[]    = '|' . $number;
                    $count  = 1;
                    $temp   = [];
                }
            }
        }

        $x[] = '<';
        $x[] = '/';
        $x[] = 'a';
        $x[] = '>';

        $x = array_reverse($x);

        // improve obfuscation by eliminating newlines & whitespace
        $output = '');
    }
}

if (! function_exists('auto_link')) {
    /**
     * Auto-linker
     *
     * Automatically links URL and Email addresses.
     * Note: There's a bit of extra code here to deal with
     * URLs or emails that end in a period. We'll strip these
     * off and add them after the link.
     *
     * @param string $str   the string
     * @param string $type  the type: email, url, or both
     * @param bool   $popup whether to create pop-up links
     */
    function auto_link(string $str, string $type = 'both', bool $popup = false): string
    {
        // Find and replace any URLs.
        if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[^\s()<>;]+\w#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
            // Set our target HTML if using popup links.
            $target = ($popup) ? ' target="_blank"' : '';

            // We process the links in reverse order (last -> first) so that
            // the returned string offsets from preg_match_all() are not
            // moved as we add more HTML.
            foreach (array_reverse($matches) as $match) {
                // $match[0] is the matched string/link
                // $match[1] is either a protocol prefix or 'www.'
                //
                // With PREG_OFFSET_CAPTURE, both of the above is an array,
                // where the actual value is held in [0] and its offset at the [1] index.
                $a   = '' . $match[0][0] . '';
                $str = substr_replace($str, $a, $match[0][1], strlen($match[0][0]));
            }
        }

        // Find and replace any emails.
        if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) {
            foreach (array_reverse($matches[0]) as $match) {
                if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== false) {
                    $str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0]));
                }
            }
        }

        return $str;
    }
}

if (! function_exists('prep_url')) {
    /**
     * Prep URL - Simply adds the http:// or https:// part if no scheme is included.
     *
     * Formerly used URI, but that does not play nicely with URIs missing
     * the scheme.
     *
     * @param string $str    the URL
     * @param bool   $secure set true if you want to force https://
     */
    function prep_url(string $str = '', bool $secure = false): string
    {
        if (in_array($str, ['http://', 'https://', '//', ''], true)) {
            return '';
        }

        if (parse_url($str, PHP_URL_SCHEME) === null) {
            $str = 'http://' . ltrim($str, '/');
        }

        // force replace http:// with https://
        if ($secure) {
            $str = preg_replace('/^(?:http):/i', 'https:', $str);
        }

        return $str;
    }
}

if (! function_exists('url_title')) {
    /**
     * Create URL Title
     *
     * Takes a "title" string as input and creates a
     * human-friendly URL string with a "separator" string
     * as the word separator.
     *
     * @param string $str       Input string
     * @param string $separator Word separator (usually '-' or '_')
     * @param bool   $lowercase Whether to transform the output string to lowercase
     */
    function url_title(string $str, string $separator = '-', bool $lowercase = false): string
    {
        $qSeparator = preg_quote($separator, '#');

        $trans = [
            '&.+?;'                  => '',
            '[^\w\d\pL\pM _-]'       => '',
            '\s+'                    => $separator,
            '(' . $qSeparator . ')+' => $separator,
        ];

        $str = strip_tags($str);

        foreach ($trans as $key => $val) {
            $str = preg_replace('#' . $key . '#iu', $val, $str);
        }

        if ($lowercase === true) {
            $str = mb_strtolower($str);
        }

        return trim(trim($str, $separator));
    }
}

if (! function_exists('mb_url_title')) {
    /**
     * Create URL Title that takes into account accented characters
     *
     * Takes a "title" string as input and creates a
     * human-friendly URL string with a "separator" string
     * as the word separator.
     *
     * @param string $str       Input string
     * @param string $separator Word separator (usually '-' or '_')
     * @param bool   $lowercase Whether to transform the output string to lowercase
     */
    function mb_url_title(string $str, string $separator = '-', bool $lowercase = false): string
    {
        helper('text');

        return url_title(convert_accented_characters($str), $separator, $lowercase);
    }
}

if (! function_exists('url_to')) {
    /**
     * Get the full, absolute URL to a controller method
     * (with additional arguments)
     *
     * @param mixed ...$args
     *
     * @throws RouterException
     */
    function url_to(string $controller, ...$args): string
    {
        if (! $route = route_to($controller, ...$args)) {
            $explode = explode('::', $controller);

            if (isset($explode[1])) {
                throw RouterException::forControllerNotFound($explode[0], $explode[1]);
            }

            throw RouterException::forInvalidRoute($controller);
        }

        return site_url($route);
    }
}

if (! function_exists('url_is')) {
    /**
     * Determines if current url path contains
     * the given path. It may contain a wildcard (*)
     * which will allow any valid character.
     *
     * Example:
     *   if (url_is('admin*)) ...
     */
    function url_is(string $path): bool
    {
        // Setup our regex to allow wildcards
        $path        = '/' . trim(str_replace('*', '(\S)*', $path), '/ ');
        $currentPath = '/' . trim(uri_string(true), '/ ');

        return (bool) preg_match("|^{$path}$|", $currentPath, $matches);
    }
}


import { Component } from "@angular/core";

@Component({
    moduleId: module.id,
    templateUrl: "./nested-routers.component.html"
})
export class NestedRoutersComponent { }


[![npm version](https://badge.fury.io/js/react-state-hoc.svg)](https://badge.fury.io/js/react-state-hoc)
[![Build Status](https://travis-ci.org/troch/react-state-hoc.svg?branch=v1.0.4)](https://travis-ci.org/troch/react-state-hoc)

# React state component (higher-order)

> A React higher-order component for abstracting away state

Keep your components simple, testable, and composable by using higher-order components. This higher-order component will abstract state away from components, so you can keep using functional stateless components.

## Installation

```sh
npm install --save react-state-hoc
# or
yarn add react-state-hoc
```

## API

### withState(initialState, mapSetStateToProps?, mergeProps?)(BaseComponent)

Wraps your `BaseComponent` with a stateful component, passing the state into the `BaseComponent` as props. By default, state will be spread into the component's props, plus the `setState` function is passed through. If you specify a `mapSetStateToProps` function, `setState` will not be passed through.

Two optional arguments allow you to a) define state creators, and b) customise which props are passed into the `BaseComponent`.

*   `initialState` can be either:
    * An object, to be used as the component's initial state.

        ```js
        withState({ visible: true })(BaseComponent)
        ```

    * A function, which maps initial props to initial state.

        ```js
        withState(props => ({ visible: props.visible }))(BaseComponent)
        ```

*   `mapSetStateToProps` can be either:
    * An object, containing state creators. Each state creator is a function which maps input arguments to new state. State creators are a convenient shorthand which automatically binds `setState` into smaller functions. Functions can also be provided as well as objects: they are supported by `setState` (see [https://reactjs.org/docs/react-component.html#setstate](https://reactjs.org/docs/react-component.html#setstate))

        ```js
        withState(
            { visible: true },
            { setVisibility: visible => ({ visible }) }
        )(BaseComponent)
        ```

    * A function, mapping `initialProps` and `setState` to state creators.

        ```js
        withState({ state: null }, initialProps => setState => ({
            setValue: value => setState({
                someState: initialProps.mapValue(value)
            })
        }))(BaseComponent)
        ```

        **Default:**

        ```js
        () => setState => ({ setState })

        ```

* `mergeProps`: A function mapping the current `props`, `state` and `stateCreators` into the `BaseComponent`'s props.

    ```js
    withState(
        { visible: true },
        { setVisibility: visible => ({ visible }) },
        (props, state, stateCreators) => ({
            ...state,
            ...stateCreators
            // deliberately not passing props through to BaseComponent
        })
    )(BaseComponent)
    ```

    **Default:**

    ```js
    (props, state, stateCreators) => ({ ...props, ...state, ...stateCreators })
    ```

## Example

```javascript
import React from 'react'
import ReactDOM from 'react-dom'
import withState from 'react-state-hoc'

function StatelessButton({ counter, setCounter }) {
    return (
        <button onClick={() => setCounter(counter + 1)}>
            Clicked {counter} times.
        </button>
    )
}

const mapSetStateToProps = () => setState => ({
    setCounter: counter => setState({ counter })
})

const StatefulButton1 = withState({ counter: 0 }, mapSetStateToProps)(
    StatelessButton
)

const StatefulButton2 = withState({ counter: 10 }, mapSetStateToProps)(
    StatelessButton
)

ReactDOM.render(
    <div>
        <StatefulButton1 />
        <StatefulButton2 />
    </div>,
    document.getElementById('app')
)
```


package com.github.gwtmaterialdesign.client.application.sidenavmini;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;

import javax.inject.Inject;

public class MiniSideNavView extends ViewImpl implements MiniSideNavPresenter.MyView {
    interface Binder extends UiBinder<Widget, MiniSideNavView> {
    }

    @Inject
    MiniSideNavView(Binder uiBinder) {
        initWidget(uiBinder.createAndBindUi(this));
    }
}


export { default as Title } from './title';


package com.github.gquintana.beepbeep.script;

import com.github.gquintana.beepbeep.TestConsumer;
import com.github.gquintana.beepbeep.pipeline.ScriptStartEvent;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

public class ResourceScriptScannerGlobTest {
    @Test
    public void testFileGlob() throws IOException {
        checkResourceGlobScan("*.sql", 1);
        checkResourceGlobScan("**/*.sql", 11);
        checkResourceGlobScan("com/github/gquintana/**/*.sql", 10);
        checkResourceGlobScan("com/github/gquintana/beepbeep/sql/init/*.sql", 2);
    }

    private void checkResourceGlobScan(String fileGlob, int fileNb) throws IOException {
        TestConsumer<ScriptStartEvent> end = new TestConsumer<>();
        ResourceScriptScanner.resourceGlob(getClass().getClassLoader(), fileGlob, end).scan();
        assertThat(end.events).hasSize(fileNb);
    }

}


using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.Core.Input;

namespace API
{
	public static class Text
	{
	    private static GraphicsContext graphics;

	    private static ShaderProgram textureShaderProgram;
	    private static ShaderProgram colorShaderProgram;

	    private static Matrix4 projectionMatrix;
	    private static Matrix4 viewMatrix;

	    private static VertexBuffer rectVertices;
	    private static VertexBuffer circleVertices;

	    private static Dictionary<string, TextSprite> spriteDict;
	    private static int spriteNamelessCount;

	    private static Font defaultFont;
	    private static Font currentFont;

	    public static bool Init(GraphicsContext graphicsContext, Stopwatch swInit = null)
	    {
	        graphics = graphicsContext;

	        textureShaderProgram = createSimpleTextureShader();
	        colorShaderProgram = createSimpleColorShader();

	        projectionMatrix = Matrix4.Ortho(0, Width,
	                                         0, Height,
	                                         0.0f, 32768.0f);

	        viewMatrix = Matrix4.LookAt(new Vector3(0, Height, 0),
	                                    new Vector3(0, Height, 1),
	                                    new Vector3(0, -1, 0));

	        rectVertices =  new VertexBuffer(4, VertexFormat.Float3);
	        rectVertices.SetVertices(0, new float[]{0, 0, 0,
	                                                1, 0, 0,
	                                                1, 1, 0,
	                                                0, 1, 0});

	        circleVertices =  new VertexBuffer(36, VertexFormat.Float3);
	        float[] circleVertex = new float[3 * 36];
	        for (int i = 0; i < 36; i++) {
	            float radian = ((i * 10) / 180.0f * FMath.PI);
	            circleVertex[3 * i + 0] = FMath.Cos(radian);
	            circleVertex[3 * i + 1] = FMath.Sin(radian);
	            circleVertex[3 * i + 2] = 0.0f;
	        }
	        circleVertices.SetVertices(0, circleVertex);

	        defaultFont = new Font(FontAlias.System, 24, FontStyle.Regular);
	        SetDefaultFont();

	        spriteDict = new Dictionary<string, TextSprite>();
	        spriteNamelessCount = 0;

	        return true;
	    }

	    /// Terminate
	    public static void Term()
	    {
	        ClearSprite();

	        defaultFont.Dispose();
	        circleVertices.Dispose();
	        rectVertices.Dispose();
	        colorShaderProgram.Dispose();
	        textureShaderProgram.Dispose();
	        graphics = null;
	    }

	    public static int Width
	    {
	        get {return graphics.GetFrameBuffer().Width;}
	    }

	    public static int Height
	    {
	        get {return graphics.GetFrameBuffer().Height;}
	    }

	    /// Touch coordinates -> screen coordinates conversion : X
	    public static int TouchPixelX(TouchData touchData)
	    {
	        return (int)((touchData.X + 0.5f) * Width);
	    }

	    /// Touch coordinates -> screen coordinates conversion : Y
	    public static int TouchPixelY(TouchData touchData)
	    {
	        return (int)((touchData.Y + 0.5f) * Height);
	    }

	    public static void AddSprite(TextSprite sprite)
	    {
	        AddSprite("[nameless]:" + spriteNamelessCount, sprite);
	        spriteNamelessCount++;
	    }

	    public static void AddSprite(string key, TextSprite sprite)
	    {
	        if (spriteDict.ContainsKey(key) == false) {
	            spriteDict.Add(key, sprite);
	        }
	    }

	    /// Register a sprite that draws text
	    public static void AddSprite(string key, string text, uint argb, Font font, int positionX, int positionY)
	    {
	        if (spriteDict.ContainsKey(text) == false) {
	            AddSprite(key, new TextSprite(text, argb, font, positionX, positionY));
	        }
	    }

	    /// Register a sprite that draws text
	    public static void AddSprite(string text, uint argb, int positionX, int positionY)
	    {
	        AddSprite(text, text, argb, currentFont, positionX, positionY);
	    }

	    public static void RemoveSprite(string key)
	    {
	        if (spriteDict.ContainsKey(key)) {
	            spriteDict[key].Dispose();
	            spriteDict.Remove(key);
	        }
	    }

	    public static void ClearSprite()
	    {
	        foreach (string key in spriteDict.Keys) {
	            spriteDict[key].Dispose();
	        }

	        spriteDict.Clear();
	        spriteNamelessCount = 0;
	    }

	    // if use Text's method, please call this method.
	    public static void Update()
	    {
	        int keyNo = 0;

	        string[] removeKey = new string[spriteDict.Count];

	        foreach (var key in spriteDict.Keys) {
	            if(false == spriteDict[key].CheckLifeTimer())
	            {
	                removeKey[keyNo] = key;
	                keyNo++;
	            }
	        }

	        for(int i = 0; i < keyNo; i++)
	        {
	            if(removeKey[i] != null)
	            {
	                RemoveSprite(removeKey[i]);
	            }
	        }
	    }

	    public static void DrawSprite(string key)
	    {
	        if (spriteDict.ContainsKey(key)) {
	            DrawSprite(spriteDict[key]);
	        }
	    }

	    public static void DrawSprite(TextSprite sprite)
	    {
	        var modelMatrix = sprite.CreateModelMatrix();
	        var worldViewProj = projectionMatrix * viewMatrix * modelMatrix;

	        textureShaderProgram.SetUniformValue(0, ref worldViewProj);

	        graphics.SetShaderProgram(textureShaderProgram);
	        graphics.SetVertexBuffer(0, sprite.Vertices);
	        graphics.SetTexture(0, sprite.Texture);

	        graphics.Enable(EnableMode.Blend);
	        graphics.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha);

	        graphics.DrawArrays(DrawMode.TriangleFan, 0, 4);

	        sprite.SetLifeTimer();
	    }

	    public static Font CurrentFont
	    {
	        get {return currentFont;}
	    }

	    public static Font SetDefaultFont()
	    {
	        return SetFont(defaultFont);
	    }

	    public static Font SetFont(Font font)
	    {
	        Font previousFont = currentFont;
	        currentFont = font;
	        return previousFont;
	    }

	    public static void DrawText(string text, uint argb, Font font, int positionX, int positionY)
	    {
	        AddSprite(text, text, argb, font, positionX, positionY);
	        DrawSprite(text);
	    }

	    public static void DrawText(string text, uint argb, int positionX, int positionY)
	    {
	        AddSprite(text, text, argb, currentFont, positionX, positionY);
	        DrawSprite(text);
	    }

	    public static void FillVertices(VertexBuffer vertices, uint argb, float positionX, float positionY, float scaleX, float scaleY)
	    {
	        var transMatrix = Matrix4.Translation(new Vector3(positionX, positionY, 0.0f));
	        var scaleMatrix = Matrix4.Scale(new Vector3(scaleX, scaleY, 1.0f));
	        var modelMatrix = transMatrix * scaleMatrix;

	        var worldViewProj = projectionMatrix * viewMatrix * modelMatrix;

	        colorShaderProgram.SetUniformValue(0, ref worldViewProj);

	        Vector4 color = new Vector4((float)((argb >> 16) & 0xff) / 0xff,
	                                    (float)((argb >> 8) & 0xff) / 0xff,
	                                    (float)((argb >> 0) & 0xff) / 0xff,
	                                    (float)((argb >> 24) & 0xff) / 0xff);
	        colorShaderProgram.SetUniformValue(colorShaderProgram.FindUniform("MaterialColor"), ref color);

	        graphics.SetShaderProgram(colorShaderProgram);
	        graphics.SetVertexBuffer(0, vertices);

	        graphics.DrawArrays(DrawMode.TriangleFan, 0, vertices.VertexCount);
	    }

		public static Texture2D createTexture(string text, Font font, uint argb)
		{
			int width = font.GetTextWidth(text, 0, text.Length);
			int height = font.Metrics.Height;

			var image = new Image(ImageMode.Rgba,
			new ImageSize(width, height),
			new ImageColor(0, 0, 0, 0));

			image.DrawText(text,
			new ImageColor((int)((argb >> 16) & 0xff),
			               (int)((argb >> 8) & 0xff),
			               (int)((argb >> 0) & 0xff),
			               (int)((argb >> 24) & 0xff)),
			font, new ImagePosition(0, 0));

			var texture = new Texture2D(width, height, false, PixelFormat.Rgba);
			texture.SetPixels(0, image.ToBuffer());
			image.Dispose();

			return texture;
		}

	    private static ShaderProgram createSimpleTextureShader()
	    {
	        string ResourceName = "API.shaders.Texture.cgx";

	        Assembly resourceAssembly = Assembly.GetExecutingAssembly();
	        if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null)
	        {
	            throw new FileNotFoundException("File not found.", ResourceName);
	        }

	        Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName);
	        Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length];
	        fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length);

	        var shaderProgram = new ShaderProgram(dataBufferVertex);
	        // var shaderProgram = new ShaderProgram("/Application/shaders/Texture.cgx");

	        shaderProgram.SetAttributeBinding(0, "a_Position");
	        shaderProgram.SetAttributeBinding(1, "a_TexCoord");

	        shaderProgram.SetUniformBinding(0, "WorldViewProj");

	        return shaderProgram;
	    }

	    private static ShaderProgram createSimpleColorShader()
	    {
	        string ResourceName = "API.shaders.Simple.cgx";

	        Assembly resourceAssembly = Assembly.GetExecutingAssembly();
	        if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null)
	        {
	            throw new FileNotFoundException("File not found.", ResourceName);
	        }

	        Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName);
	        Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length];
	        fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length);

	        var shaderProgram = new ShaderProgram(dataBufferVertex);
	        // var shaderProgram = new ShaderProgram("/Application/shaders/Simple.cgx");

	        shaderProgram.SetAttributeBinding(0, "a_Position");
	        //shaderProgram.SetAttributeBinding(1, "a_Color0");

	        shaderProgram.SetUniformBinding(0, "WorldViewProj");

	        return shaderProgram;
	    }
	}

}


"""
Low-level classes for managing data transfer.
"""
from __future__ import print_function

from collections import namedtuple, Counter
from concurrent.futures import ThreadPoolExecutor
import logging
import multiprocessing
import signal
import sys
import threading
import time
import uuid
import operator
import os

from .exceptions import DatalakeIncompleteTransferException

logger = logging.getLogger(__name__)

class StateManager(object):
    """
    Manages state for any hashable object.

    When tracking multiple files and their chunks, each file/chunk can be in
    any valid state for that particular type.

    At the simplest level, we need to set and retrieve an object's current
    state, while only allowing valid states to be used. In addition, we also
    need to give statistics about a group of objects (are all objects in one
    state? how many objects are in each available state?).

    Parameters
    ----------
    states : list of valid states
        Managed objects can only use these defined states.

    Examples
    --------
    >>> StateManager('draft', 'review', 'complete')  # doctest: +SKIP
    <StateManager: draft=0 review=0 complete=0>
    >>> mgr = StateManager('off', 'on')
    >>> mgr['foo'] = 'on'
    >>> mgr['bar'] = 'off'
    >>> mgr['quux'] = 'on'
    >>> mgr  # doctest: +SKIP
    <StateManager: off=1 on=2>
    >>> mgr.contains_all('on')
    False
    >>> mgr['bar'] = 'on'
    >>> mgr.contains_all('on')
    True
    >>> mgr.contains_none('off')
    True

    Internal class used by `ADLTransferClient`.
    """
    def __init__(self, *states):
        self._states = {state: set() for state in states}
        self._objects = {}

    @property
    def states(self):
        return list(self._states)

    @property
    def objects(self):
        return list(self._objects)

    def __iter__(self):
        return iter(self._objects.items())

    def __getitem__(self, obj):
        return self._objects[obj]

    def __setitem__(self, obj, state):
        if obj in self._objects:
            self._states[self._objects[obj]].discard(obj)
        self._states[state].add(obj)
        self._objects[obj] = state

    def contains_all(self, state):
        """ Return whether all managed objects are in the given state """
        objs = self._states[state]
        return len(objs) > 0 and len(self.objects) - len(objs) == 0

    def contains_none(self, *states):
        """ Return whether no managed objects are in the given states """
        return all([len(self._states[state]) == 0 for state in states])

    def __str__(self):
        status = " ".join(
            ["%s=%d" % (s, len(self._states[s])) for s in self._states])
        return "<StateManager: " + status + ">"

    __repr__ = __str__

# Named tuples used to serialize client progress
File = namedtuple('File', 'src dst state length chunks exception')
Chunk = namedtuple('Chunk', 'name state offset expected actual exception')

class ADLTransferClient(object):
    """
    Client for transferring data from/to Azure DataLake Store

    This is intended as the underlying class for `ADLDownloader` and
    `ADLUploader`. If necessary, it can be used directly for additional
    control.

    Parameters
    ----------
    adlfs: ADL filesystem instance
    name: str
        Unique ID used for persistence.
    transfer: callable
        Function or callable object invoked when transferring chunks. See
        ``Function Signatures``.
    merge: callable [None]
        Function or callable object invoked when merging chunks. For each file
        containing only one chunk, no merge function will be called, even if
        provided. If None, then merging is skipped. See
        ``Function Signatures``.
    nthreads: int [None]
        Number of threads to use (minimum is 1). If None, uses the number of
        cores.
    chunksize: int [2**28]
        Number of bytes for a chunk. Large files are split into chunks. Files
        smaller than this number will always be transferred in a single thread.
    buffersize: int [2**25]
        Number of bytes for internal buffer. This block cannot be bigger than
        a chunk and cannot be smaller than a block.
    blocksize: int [2**25]
        Number of bytes for a block. Within each chunk, we write a smaller
        block for each API call. This block cannot be bigger than a chunk.
    chunked: bool [True]
        If set, each transferred chunk is stored in a separate file until
        chunks are gathered into a single file. Otherwise, each chunk will be
        written into the same destination file.
    unique_temporary: bool [True]
        If set, transferred chunks are written into a unique temporary
        directory.
    persist_path: str [None]
        Path used for persisting a client's state. If None, then `save()`
        and `load()` will be empty operations.
    delimiter: byte(s) or None
        If set, will transfer blocks using delimiters, as well as split
        files for transferring on that delimiter.
    parent: ADLDownloader, ADLUploader or None
        In typical usage, the transfer client is created in the context of an
        upload or download, which can be persisted between sessions.

    Temporary Files
    ---------------

    When a merge step is available, the client will write chunks to temporary
    files before merging. The exact temporary file looks like this in
    pseudo-BNF:

    >>> # {dirname}/{basename}.segments[.{unique_str}]/{basename}_{offset}

    Function Signatures
    -------------------

    To perform the actual work needed by the client, the user must pass in two
    callables, `transfer` and `merge`. If merge is not provided, then the
    merge step will be skipped.

    The `transfer` callable has the function signature,
    `fn(adlfs, src, dst, offset, size, buffersize, blocksize, shutdown_event)`.
    `adlfs` is the ADL filesystem instance. `src` and `dst` refer to the source
    and destination of the respective file transfer. `offset` is the location
    in `src` to read `size` bytes from. `buffersize` is the number of bytes
    used for internal buffering before transfer. `blocksize` is the number of
    bytes in a chunk to write at one time. The callable should return an
    integer representing the number of bytes written.

    The `merge` callable has the function signature,
    `fn(adlfs, outfile, files, shutdown_event)`. `adlfs` is the ADL filesystem
    instance. `outfile` is the result of merging `files`.

    For both callables, `shutdown_event` is optional. In particular,
    `shutdown_event` is a `threading.Event` that is passed to the callable.
    The event will be set when a shutdown is requested. It is good practice
    to listen for this.

    Internal State
    --------------

    self._fstates: StateManager
        This captures the current state of each transferred file.
    self._files: dict
        Using a tuple of the file source/destination as the key, this
        dictionary stores the file metadata and all chunk states. The
        dictionary key is `(src, dst)` and the value is
        `dict(length, cstates, exception)`.
    self._chunks: dict
        Using a tuple of the chunk name/offset as the key, this dictionary
        stores the chunk metadata and has a reference to the chunk's parent
        file. The dictionary key is `(name, offset)` and the value is
        `dict(parent=(src, dst), expected, actual, exception)`.
    self._ffutures: dict
        Using a Future object as the key, this dictionary provides a reverse
        lookup for the file associated with the given future. The returned
        value is the file's primary key, `(src, dst)`.
    self._cfutures: dict
        Using a Future object as the key, this dictionary provides a reverse
        lookup for the chunk associated with the given future. The returned
        value is the chunk's primary key, `(name, offset)`.

    See Also
    --------
    azure.datalake.store.multithread.ADLDownloader
    azure.datalake.store.multithread.ADLUploader
    """

    def __init__(self, adlfs, transfer, merge=None, nthreads=None,
                 chunksize=2**28, blocksize=2**25, chunked=True,
                 unique_temporary=True, delimiter=None,
                 parent=None, verbose=False, buffersize=2**25):
        self._adlfs = adlfs
        self._parent = parent
        self._transfer = transfer
        self._merge = merge
        self._nthreads = max(1, nthreads or multiprocessing.cpu_count())
        self._chunksize = chunksize
        self._buffersize = buffersize
        self._blocksize = blocksize
        self._chunked = chunked
        self._unique_temporary = unique_temporary
        self._unique_str = uuid.uuid4().hex
        self.verbose = verbose

        # Internal state tracking files/chunks/futures
        self._files = {}
        self._chunks = {}
        self._ffutures = {}
        self._cfutures = {}
        self._fstates = StateManager(
            'pending', 'transferring', 'merging', 'finished', 'cancelled',
            'errored')

    def submit(self, src, dst, length):
        """
        Split a given file into chunks.

        All submitted files/chunks start in the `pending` state until `run()`
        is called.
        """
        cstates = StateManager(
            'pending', 'running', 'finished', 'cancelled', 'errored')

        # Create unique temporary directory for each file
        if self._chunked:
            if self._unique_temporary:
                filename = "{}.segments.{}".format(dst.name, self._unique_str)
            else:
                filename = "{}.segments".format(dst.name)
            tmpdir = dst.parent/filename
        else:
            tmpdir = None

        # TODO: might need xrange support for py2
        offsets = range(0, length, self._chunksize)

        # in the case of empty files, ensure that the initial offset of 0 is properly added.
        if not offsets:
            if not length:
                offsets = [0]
            else:
                raise DatalakeIncompleteTransferException('Could not compute offsets for source: {}, with destination: {} and expected length: {}.'.format(src, dst, length))

        tmpdir_and_offsets = tmpdir and len(offsets) > 1
        for offset in offsets:
            if tmpdir_and_offsets:
                name = tmpdir / "{}_{}".format(dst.name, offset)
            else:
                name = dst
            cstates[(name, offset)] = 'pending'
            self._chunks[(name, offset)] = {
                "parent": (src, dst),
                "expected": min(length - offset, self._chunksize),
                "actual": 0,
                "exception": None}
            logger.debug("Submitted %s, byte offset %d", name, offset)

        self._fstates[(src, dst)] = 'pending'
        self._files[(src, dst)] = {
            "length": length,
            "cstates": cstates,
            "exception": None}

    def _submit(self, fn, *args, **kwargs):
        kwargs['shutdown_event'] = self._shutdown_event
        future = self._pool.submit(fn, *args, **kwargs)
        future.add_done_callback(self._update)
        return future

    def _start(self, src, dst):
        key = (src, dst)
        self._fstates[key] = 'transferring'
        for obj in self._files[key]['cstates'].objects:
            name, offset = obj
            cs = self._files[key]['cstates']
            if obj in cs.objects and cs[obj] == 'finished':
                continue
            cs[obj] = 'running'
            future = self._submit(
                self._transfer, self._adlfs, src, name, offset,
                self._chunks[obj]['expected'], self._buffersize,
                self._blocksize)
            self._cfutures[future] = obj

    @property
    def active(self):
        """ Return whether the transfer is active """
        return not self._fstates.contains_none('pending', 'transferring', 'merging')

    @property
    def successful(self):
        """
        Return whether the transfer completed successfully.

        It will raise AssertionError if the transfer is active.
        """
        assert not self.active
        return self._fstates.contains_all('finished')

    @property
    def progress(self):
        """ Return a summary of all transferred file/chunks """
        files = []
        for key in self._files:
            src, dst = key
            chunks = []
            for obj in self._files[key]['cstates'].objects:
                name, offset = obj
                chunks.append(Chunk(
                    name=name,
                    offset=offset,
                    state=self._files[key]['cstates'][obj],
                    expected=self._chunks[obj]['expected'],
                    actual=self._chunks[obj]['actual'],
                    exception=self._chunks[obj]['exception']))
            files.append(File(
                src=src,
                dst=dst,
                state=self._fstates[key],
                length=self._files[key]['length'],
                chunks=chunks,
                exception=self._files[key]['exception']))
        return files

    def _rename_file(self, src, dst, overwrite=False):
        """ Rename a file from file_name.inprogress to just file_name. Invoked once download completes on a file.

        Internal function used by `download`.
        """
        try:
            # we do a final check to make sure someone didn't create the destination file while download was occuring
            # if the user did not specify overwrite.
            if os.path.isfile(dst):
                if not overwrite:
                    raise FileExistsError(dst)
                os.remove(dst)
            os.rename(src, dst)
        except Exception as e:
            logger.error('Rename failed for source file: %r; %r', src, e)
            raise e

        logger.debug('Renamed %r to %r', src, dst)

    def _update(self, future):
        if future in self._cfutures:
            obj = self._cfutures[future]
            parent = self._chunks[obj]['parent']
            cstates = self._files[parent]['cstates']
            src, dst = parent

            if future.cancelled():
                cstates[obj] = 'cancelled'
            elif future.exception():
                self._chunks[obj]['exception'] = repr(future.exception())
                cstates[obj] = 'errored'
            else:
                nbytes, exception = future.result()
                self._chunks[obj]['actual'] = nbytes
                self._chunks[obj]['exception'] = exception
                if exception:
                    cstates[obj] = 'errored'
                elif self._chunks[obj]['expected'] != nbytes:
                    name, offset = obj
                    cstates[obj] = 'errored'
                    exception = DatalakeIncompleteTransferException(
                        'chunk {}, offset {}: expected {} bytes, transferred {} bytes'.format(
                            name, offset, self._chunks[obj]['expected'],
                            self._chunks[obj]['actual']))
                    self._chunks[obj]['exception'] = exception
                    logger.error("Incomplete transfer: %s -> %s, %s",
                                 src, dst, repr(exception))
                else:
                    cstates[obj] = 'finished'

            if cstates.contains_all('finished'):
                logger.debug("Chunks transferred")
                if self._merge and len(cstates.objects) > 1:
                    logger.debug("Merging file: %s", self._fstates[parent])
                    self._fstates[parent] = 'merging'
                    merge_future = self._submit(
                        self._merge, self._adlfs, dst,
                        [chunk for chunk, _ in sorted(cstates.objects,
                                                      key=operator.itemgetter(1))],
                        overwrite=self._parent._overwrite)
                    self._ffutures[merge_future] = parent
                else:
                    if not self._chunked and str(dst).endswith('.inprogress'):
                        logger.debug("Renaming file to remove .inprogress: %s", self._fstates[parent])
                        self._fstates[parent] = 'merging'
                        self._rename_file(dst, dst.replace('.inprogress',''), overwrite=self._parent._overwrite)
                        dst = dst.replace('.inprogress', '')

                    self._fstates[parent] = 'finished'
                    logger.info("Transferred %s -> %s", src, dst)
            elif cstates.contains_none('running'):
                logger.error("Transfer failed: %s -> %s", src, dst)
                self._fstates[parent] = 'errored'
        elif future in self._ffutures:
            src, dst = self._ffutures[future]

            if future.cancelled():
                self._fstates[(src, dst)] = 'cancelled'
            elif future.exception():
                self._files[(src, dst)]['exception'] = repr(future.exception())
                self._fstates[(src, dst)] = 'errored'
            else:
                exception = future.result()
                self._files[(src, dst)]['exception'] = exception
                if exception:
                    self._fstates[(src, dst)] = 'errored'
                else:
                    self._fstates[(src, dst)] = 'finished'
                    logger.info("Transferred %s -> %s", src, dst)
        # TODO: Re-enable progress saving when a less IO intensive solution is available.
        # See issue: https://github.com/Azure/azure-data-lake-store-python/issues/117
        #self.save()
        if self.verbose:
            print('\b' * 200, self.status, end='')
            sys.stdout.flush()

    @property
    def status(self):
        c = sum([Counter([c.state for c in f.chunks]) for f in
                 self.progress], Counter())
        return dict(c)

    def run(self, nthreads=None, monitor=True, before_start=None):
        self._pool = ThreadPoolExecutor(self._nthreads)
        self._shutdown_event = threading.Event()
        self._nthreads = nthreads or self._nthreads
        self._ffutures = {}
        self._cfutures = {}
        for src, dst in self._files:
            if before_start:
                before_start(self._adlfs, src, dst)
            self._start(src, dst)
        before_start = None
        if monitor:
            self.monitor()
            has_errors = False
            error_list = []
            for f in self.progress:
                for chunk in f.chunks:
                    if chunk.state == 'finished':
                        continue
                    if chunk.exception:
                        error_string = '{} -> {}, chunk {} {}: {}, {}'.format(
                            f.src, f.dst, chunk.name, chunk.offset,
                            chunk.state, repr(chunk.exception))
                        logger.error(error_string)
                        has_errors = True
                        error_list.append(error_string)
                    else:
                        error_string = '{} -> {}, chunk {} {}: {}'.format(
                            f.src, f.dst, chunk.name, chunk.offset,
                            chunk.state)
                        logger.error(error_string)
                        error_list.append(error_string)
                        has_errors = True
            if has_errors:
                raise DatalakeIncompleteTransferException('One more more exceptions occured during transfer, resulting in an incomplete transfer. \n\n List of exceptions and errors:\n {}'.format('\n'.join(error_list)))

    def _wait(self, poll=0.1, timeout=0):
        start = time.time()
        while self.active:
            if timeout > 0 and time.time() - start > timeout:
                break
            time.sleep(poll)

    def _clear(self):
        self._cfutures = {}
        self._ffutures = {}
        self._pool = None

    def shutdown(self):
        """
        Shutdown task threads in an orderly fashion.

        Within the context of this method, we disable Ctrl+C keystroke events
        until all threads have exited. We re-enable Ctrl+C keystroke events
        before leaving.
        """
        handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
        try:
            logger.debug("Shutting down worker threads")
            self._shutdown_event.set()
            self._pool.shutdown(wait=True)
        except Exception as e:
            logger.error("Unexpected exception occurred during shutdown: %s", repr(e))
        else:
            logger.debug("Shutdown complete")
        finally:
            signal.signal(signal.SIGINT, handler)

    def monitor(self, poll=0.1, timeout=0):
        """ Wait for download to happen """
        try:
            self._wait(poll, timeout)
        except KeyboardInterrupt:
            logger.warning("%s suspended and persisted", self)
            self.shutdown()
        self._clear()

        # TODO: Re-enable progress saving when a less IO intensive solution is available.
        # See issue: https://github.com/Azure/azure-data-lake-store-python/issues/117
        #self.save()

    def __getstate__(self):
        dic2 = self.__dict__.copy()
        dic2.pop('_cfutures', None)
        dic2.pop('_ffutures', None)
        dic2.pop('_pool', None)
        dic2.pop('_shutdown_event', None)

        dic2['_files'] = dic2.get('_files', {}).copy()
        dic2['_chunks'] = dic2.get('_chunks', {}).copy()

        return dic2

    def save(self, keep=True):
        if self._parent is not None:
            self._parent.save(keep=keep)


#pragma once

#include <algorithm>
#include <cstdint>
#include <vector>

namespace mirrage::util {

	template <class T>
	class sorted_vector {
	  public:
		using const_iterator         = typename std::vector<T>::const_iterator;
		using const_reverse_iterator = typename std::vector<T>::const_reverse_iterator;

		sorted_vector() = default;
		sorted_vector(std::vector<T> data) : _data(data) { std::sort(data.begin(), data.end()); }

		template <class U, typename = std::enable_if_t<std::is_same_v<std::remove_reference_t<U>, T>>>
		auto insert(U&& v) -> T&
		{
			auto lb = std::lower_bound(_data.begin(), _data.end(), v);
			return *_data.insert(lb, std::forward<U>(v));
		}
		template <class Key,
		          class... Args,
		          typename = std::enable_if_t<!std::is_same_v<std::remove_reference_t<Key>, T>>>
		auto emplace(const Key& key, Args&&... args) -> T&
		{
			auto lb = std::lower_bound(_data.begin(), _data.end(), key);
			return *_data.emplace(lb, std::forward<Args>(args)...);
		}

		void erase(const T& v)
		{
			auto lb = std::lower_bound(_data.begin(), _data.end(), v);
			if(lb != _data.end() && *lb == v) {
				_data.erase(lb);
			}
		}

		template <class Key>
		auto find(const Key& key) -> const_iterator
		{
			auto iter = std::lower_bound(begin(), end(), key);
			return iter != end() && *iter == key ? iter : end();
		}

		void erase(const_iterator iter) { _data.erase(iter); }
		void erase(const_iterator begin, const_iterator end) { _data.erase(begin, end); }

		auto pop_back() -> T
		{
			auto v = back();
			_data.pop_back();
			return v;
		}

		auto front() { return _data.front(); }
		auto back() { return _data.back(); }

		auto clear() { return _data.clear(); }

		void reserve(std::size_t n) { _data.reserve(n); }

		auto size() const { return _data.size(); }
		auto empty() const { return _data.empty(); }
		auto begin() const { return _data.begin(); }
		auto end() const { return _data.end(); }
		auto rbegin() const { return _data.rbegin(); }
		auto rend() const { return _data.rend(); }

		decltype(auto) operator[](std::int64_t i) { return _data.at(i); }

	  private:
		std::vector<T> _data;
	};

} // namespace mirrage::util


echo "Challenge 1"

TEST=`diff -wBq ../my_files/nsorts.txt ../my_files/asorts.txt`
VAL="Files my_files/nsorts.txt and my_files/asorts.txt differ"

if [ $"VAL"=$"TEST" ] ; then
	echo ...passed ;
else
	echo ...failed ;
fi

echo "Challenge 2"

if [ `cat ../my_files/asia_count` -eq 77301 ] ; then
	echo ...passed ;
else
	echo ...failed ;
fi

echo "Challenge 3"

echo "bear\ndeer\nfox\nrabbit\nraccoon" > test

TEST=`diff -wBq test ../my_files/unique_animals.txt`
VAL="Files test and my_files/unique_animals do not differ"

if [ $"VAL"=$"TEST" ] ; then
	echo ...passed ;
else
	echo ...failed ;
fi


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using System.Drawing;
using Sharp2D;
using Sharp2D.Core;
using Sharp2D.Core.Interfaces;
using Sharp2D.Game.Worlds;

namespace Sharp2D.Game.Sprites
{
    public sealed class TileSprite : Sprite, ICollidable
    {
        public TiledWorld World { get; private set; }
        public int ID { get; private set; }
        public TileSet TileSet { get; private set; }
        public Layer ParentLayer { get; private set; }
        public bool FlippedDiagonally { get; internal set; }
        public bool FlippedHorizontally { get; internal set; }
        public bool FlippedVertically { get; internal set; }

        public TileSprite(int ID, TileSet parent, Layer parentLayer, int data_index, TiledWorld world)
        {
            this.World = world;
            this.ID = ID;
            this.TileSet = parent;
            this.ParentLayer = parentLayer;

            Width = TileSet.TileWidth;
            Height = TileSet.TileHeight;

            X = data_index % parentLayer.Width;
            Y = data_index / parentLayer.Width;

            X *= TileSet.TileWidth;
            Y *= TileSet.TileHeight;

            Layer = 1f/ParentLayer.LayerNumber;

            IsStatic = !(parent.TileProperties.ContainsKey(ID) && parent.TileProperties[ID].ContainsKey("static") && parent.TileProperties[ID]["static"].ToLower() == "true");

            _setTexCoords();

            Texture = TileSet.TileTexture;

            if (IsCollidable)
            {
                Hitbox = new Hitbox("Space", new List<Vector2>
                {
                    new Vector2(0, 0),
                    new Vector2(Width, 0),
                    new Vector2(Width, Height),
                    new Vector2(0, Height)
                });
                Hitbox.AddCollidable(this);
            }
        }

        public bool IsCollidable
        {
            get { return TileSet.TileProperties.ContainsKey(ID) && TileSet.TileProperties[ID].ContainsKey("collide"); }
        }

        public override bool HasAlpha
        {
            get
            {
                return TileHasAlpha;
            }
        }

        public bool HasProperty(string key)
        {
            return TileSet.TileProperties.ContainsKey(ID) && TileSet.TileProperties[ID].ContainsKey(key);
        }

        public string GetProperty(string key)
        {
            return !HasProperty(key) ? null : TileSet.TileProperties[ID][key];
        }

        private void _setTexCoords()
        {
            if (World.texcoords_cache.ContainsKey(ID))
            {
                TexCoords = World.texcoords_cache[ID];
                return;
            }

            int tilepos = (ID - TileSet.FirstGID) + 1;
            float x, y, width, height;
            int step = (tilepos - 1) % TileSet.TilesPerRow, row = 0;

            for (int i = 0; i != ID; i++)
            {
                if (i % TileSet.TilesPerRow == 0 && i != 0)
                    row++;
            }

            x = TileSet.TileWidth * step;
            y = TileSet.TileHeight * row;
            y = TileSet.TileTexture.TextureHeight + y;
            width = x + TileSet.TileWidth;
            height = y + TileSet.TileHeight;

            TexCoords = new TexCoords(x, y, width, height, TileSet.TileTexture);

            World.texcoords_cache.Add(ID, TexCoords);

            IsStatic = true;
        }

        public bool TileHasAlpha
        {
            get
            {
                if (TileSet.containsAlpha.ContainsKey(ID))
                    return TileSet.containsAlpha[ID];

                int tilepos = (ID - TileSet.FirstGID) + 1;
                int step = (tilepos - 1) % TileSet.TilesPerRow, row = 0;

                for (int i = 0; i != ID; i++)
                {
                    if (i % TileSet.TilesPerRow == 0 && i != 0)
                        row++;
                }

                int x = TileSet.TileWidth * step;
                int y = TileSet.TileHeight * row;
                int width = TileSet.TileWidth;
                int height = TileSet.TileHeight;

                var testBmp = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage(testBmp))
                {
                    g.DrawImage(Texture.Bitmap, new RectangleF(0, 0, width, height), new RectangleF(x, y, width, height), GraphicsUnit.Pixel);
                }

                bool cached_alpha_answer = testBmp.ContainsAlpha();
                TileSet.containsAlpha.Add(ID, cached_alpha_answer);

                testBmp.Dispose();
                return cached_alpha_answer;
            }
        }

        protected override void OnLoad()
        {
            //TODO Do some loading of something
        }

        protected override void OnUnload()
        {
            //TODO Do some unloading of something
        }

        protected override void OnDispose()
        {
            //TODO Dispose something..
        }

        protected override void OnDisplay()
        {
            //TODO Display related stuff (badpokerface)
        }

        protected override void BeforeDraw()
        {
            //TODO Do something before it's drawn
        }

        public event EventHandler OnCollision;
        public Hitbox Hitbox { get; set; }

        public CollisionResult CollidesWith(ICollidable c)
        {
            return new CollisionResult {Intersecting = false, WillIntersect = false, TranslationVector = new Vector2()};
        }

        public override string Name
        {
            get { return "Tile #" + ID; }
        }
    }
}


<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="app-theme.html">
<dom-module id="total-price">

    <template>
        <firebase-document path="/categories" data="{{categories}}"> </firebase-document>
        <firebase-document path="/stores/[[storeId]]/stock" data="{{data}}"> </firebase-document>

        <paper-material id="tabelize" elevation="1" animated class$="[[passedDownClass]]">
            <paper-menu><template is="dom-repeat" items="[[getObjectValues(categories)]]">
                <paper-submenu disabled="[[emptySubCart(item, data, quantities)]]">
                    <paper-icon-item class="menu-trigger" disabled="[[shouldDisable(item, data, quantities)]]">
                        <iron-icon icon="my-icons:tag" item-icon></iron-icon>
                        <paper-item-body>

[[capitalize(item)]]<template is="dom-if" if="[[notStore(store)]]"></template>

</paper-item-body>
                        <template is="dom-if" if="[[store]]">

[[getCategoryTotalQuanta(item, data, quantities)]]

                        </template>
                        <template is="dom-if" if="[[notStore(store)]]">

[[getCategoryTotal(item, data, quantities)]]

                        </template>
                    </paper-icon-item>
                    <paper-menu class="menu-content" selected="0">
                        <template is="dom-repeat" items="[[getSubCart(item, data, quantities)]]">
                            <paper-icon-item>
                                <iron-icon icon="my-icons:shopping-basket" item-icon></iron-icon>
                                <paper-item-body two-line>

[[capitalize(item.id)]]

[[item.quanta]] units in Cart

                                </paper-item-body>

[[parseMoney(item.price)]]

                            </paper-icon-item>
                        </template>
                    </paper-menu>
                </paper-submenu>
            </template></paper-menu>
            <template is="dom-if" if="[[store]]">

                    <paper-button id="proceedToCartButton" raised>
                        <iron-icon icon="my-icons:cart"></iron-icon>
                        Proceed to Cart
                    </paper-button>

            </template>
            <template is="dom-if" if="[[notStoreTracking(store, tracking)]]">
                <paper-material elevation="2" animated>

<iron-icon id="cart" icon="my-icons:cart"></iron-icon>Cart Total: [[cartTotal]]

                </paper-material>
            </template>
        </paper-material>

    </template>

</dom-module>


module SugoiAliasesUpdator
  class AliasesParser

    attr_accessor :changed_labels

    def initialize(filepath)
      @native_lines = File.readlines(filepath)
      @changed_labels = []
    end

    def add(target_email, to)
      check_labels!(to)
      to.each do |x|
        unless label_mails_hash[x].include?(target_email)
          label_mails_hash[x].push(target_email)
          @changed_labels << x
        end
      end
      render!
    end

    def rm(target_email, from)
      if ['ALL'] == from
        label_mails_hash.each do |label, emails|
          if emails.include?(target_email)
            label_mails_hash[label].delete(target_email)
            @changed_labels << label
          end
        end
        return render!
      end

      check_labels!(from)
      from.each do |label|
        if label_mails_hash[label].include?(target_email)
          label_mails_hash[label].delete(target_email)
          @changed_labels << label
        end
      end
      render!
    end

    def list(target_email)
      finded = []
      label_mails_hash.each do |key, value|
        finded.push(key) if value.include?(target_email)
      end
      finded.join(',')
    end

    def render!
      new_lines = []
      @native_lines.each do |line|
        line_paser = LineParser.new(line)
        if line_paser.is_aliaes_line && @changed_labels.include?(line_paser.label)
          line = "#{line_paser.label}:#{line_paser.margin}#{label_mails_hash[line_paser.label].join(", ")}\n"
        end
        new_lines << line
      end
      new_lines.join
    end

    private

    def label_mails_hash
      @label_mails_hash ||= {}.tap do |h|
        @native_lines.each do |line|
          line_paser = LineParser.new(line)
          if line_paser.is_aliaes_line
            emails_line = line_paser.emails_line
            h[line_paser.label] = line_paser.emails_line.split(/\,\s?/)
          end
        end
      end
    end

    def check_labels!(inputed_labels)
      unknown_labels = inputed_labels - label_mails_hash.keys
      if unknown_labels.size > 0
        raise("unknown labels #{unknown_labels.join(', ')}")
      end
    end
  end
end


SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
null

### Remarks
null

life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Coffea/Coffea mauritiana/ Syn. Coffea nossikumbaensis/README.md


/*!
 * numbro.js language configuration
 * language : German
 * locale: Austria
 * author : Tim McIntosh (StayinFront NZ)
 */
(function () {
    'use strict';

    var language = {
        langLocaleCode: 'de-AT',
        cultureCode: 'de-AT',
        delimiters: {
            thousands: ' ',
            decimal: ','
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function () {
            return '.';
        },
        currency: {
            symbol: '€',
            code: 'EUR'
        }
    };

    // Node
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = language;
    }
    // Browser
    if (typeof window !== 'undefined' && window.numbro && window.numbro.culture) {
        window.numbro.culture(language.cultureCode, language);
    }
}.call(typeof window === 'undefined' ? this : window));


ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Leptogium adpressum Nyl.

### Remarks
null


/**
 * Loads the update static resource page
 *
 * @class MODx.page.UpdateStatic
 * @extends MODx.Component
 * @param {Object} config An object of config properties
 * @xtype modx-page-static-update
 */
MODx.page.UpdateStatic = function(config) {
    config = config || {record:{}};
    config.record = config.record || {};
    Ext.apply(config.record,{
        'parent-cmb': config.record['parent']
    });

    Ext.applyIf(config,{
        url: MODx.config.connectors_url+'resource/index.php'
        ,which_editor: 'none'
        ,formpanel: 'modx-panel-resource'
        ,id: 'modx-page-update-resource'
        ,action: 'update'
        ,actions: {
            'new': MODx.action['resource/create']
            ,edit: MODx.action['resource/update']
            ,preview: MODx.action['resource/preview']
            ,cancel: MODx.action['welcome']
        }
        ,components: [{
            xtype: 'modx-panel-static'
            ,renderTo: 'modx-panel-static-div'
            ,resource: config.resource
            ,record: config.record || {}
            ,publish_document: config.publish_document
            ,access_permissions: config.access_permissions
            ,show_tvs: config.show_tvs
            ,url: config.url
        }]
        ,loadStay: true
        ,buttons: this.getButtons(config)
    });
    MODx.page.UpdateStatic.superclass.constructor.call(this,config);
};
Ext.extend(MODx.page.UpdateStatic,MODx.Component,{
    preview: function() {
        window.open(this.config.preview_url);
        return false;
    }

    ,duplicateResource: function(btn,e) {
        MODx.msg.confirm({
            text: _('resource_duplicate_confirm')
            ,url: MODx.config.connectors_url+'resource/index.php'
            ,params: {
                action: 'duplicate'
                ,id: this.config.resource
            }
            ,listeners: {
                success: {fn:function(r) {
                    MODx.loadPage(MODx.action['resource/update'], 'id='+r.object.id);
                },scope:this}
            }
        });
    }

    ,deleteResource: function(btn,e) {
        MODx.msg.confirm({
            text: _('resource_delete_confirm')
            ,url: MODx.config.connectors_url+'resource/index.php'
            ,params: {
                action: 'delete'
                ,id: this.config.resource
            }
            ,listeners: {
                success: {fn:function(r) {
                    MODx.loadPage(MODx.action['resource/update'], 'id='+r.object.id);
                },scope:this}
            }
        });
    }

    ,cancel: function(btn,e) {
        var fp = Ext.getCmp(this.config.formpanel);
        if (fp && fp.isDirty()) {
            Ext.Msg.confirm(_('warning'),_('resource_cancel_dirty_confirm'),function(e) {
                if (e == 'yes') {
                    MODx.releaseLock(MODx.request.id);
                    MODx.sleep(400);
                    MODx.loadPage(MODx.action['welcome']);
                }
            },this);
        } else {
            MODx.releaseLock(MODx.request.id);
            MODx.loadPage(MODx.action['welcome']);
        }
    }
    ,getButtons: function(cfg) {
        var btns = [];
        if (cfg.canSave == 1) {
            btns.push({
                process: 'update'
                ,id: 'modx-abtn-save'
                ,text: _('save')
                ,method: 'remote'
                ,checkDirty: cfg.richtext || MODx.request.reload ? false : true
                ,keys: [{
                    key: MODx.config.keymap_save || 's'
                    ,ctrl: true
                }]
            });
            btns.push('-');
        } else {
            btns.push({
                text: cfg.lockedText || _('locked')
                ,handler: Ext.emptyFn
                ,disabled: true
                ,id: 'modx-abtn-locked'
            });
            btns.push('-');
        }
        if (cfg.canCreate == 1) {
            btns.push({
                process: 'duplicate'
                ,text: _('duplicate')
                ,handler: this.duplicateResource
                ,scope:this
                ,id: 'modx-abtn-duplicate'
            });
            btns.push('-');
        }
        if (cfg.canDelete == 1 && !cfg.locked) {
            btns.push({
                process: 'delete'
                ,text: _('delete')
                ,handler: this.deleteResource
                ,scope:this
                ,id: 'modx-abtn-delete'
            });
            btns.push('-');
        }
        btns.push({
            process: 'preview'
            ,text: _('view')
            ,handler: this.preview
            ,scope: this
            ,id: 'modx-abtn-preview'
        });
        btns.push('-');
        btns.push({
            process: 'cancel'
            ,text: _('cancel')
            ,handler: this.cancel
            ,scope: this
            ,id: 'modx-abtn-cancel'
        });
        btns.push('-');
        btns.push({
            text: _('help_ex')
            ,handler: MODx.loadHelpPane
            ,id: 'modx-abtn-help'
        });
        return btns;
    }
});
Ext.reg('modx-page-static-update',MODx.page.UpdateStatic);


'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Iterator component to be used to display a list of entities, using a single field
 *
 * @example Display all the books by the current author
 * <ReferenceManyField reference="books" target="author_id">
 *     <SingleFieldList>
 *         <ChipField source="title" />
 *     </SingleFieldList>
 * </ReferenceManyField>
 */
var SingleFieldList = function SingleFieldList(_ref) {
    var ids = _ref.ids,
        data = _ref.data,
        resource = _ref.resource,
        basePath = _ref.basePath,
        children = _ref.children;
    return _react2.default.createElement(
        'div',
        { style: { display: 'flex', flexWrap: 'wrap' } },
        ids.map(function (id) {
            return _react2.default.cloneElement(children, {
                key: id,
                record: data[id],
                resource: resource,
                basePath: basePath
            });
        })
    );
};

SingleFieldList.propTypes = {
    children: _react.PropTypes.element.isRequired
};

exports.default = SingleFieldList;
module.exports = exports['default'];


@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


import {Injectable} from "angular2/core";
import {CONTACTS} from "./mocks/data";
import {Contact} from "./contact";

@Injectable()
export class ContactService{
  getContacts(){
    return Promise.resolve(CONTACTS);
  }
  getContactById(id){
    return Promise.resolve(CONTACTS.find(x=>x.id == id));
  }
  insertContact(contact:Contact){
    Promise.resolve(CONTACTS)
      .then(
        (contacts:Contact[])=> contacts.push(contact)
      );
  }
}