text:
<?php

namespace Buzz\Listener;

use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;

class DigestAuthListener implements ListenerInterface
{
    private $username;
    private $password;
    private $realm;

    private $algorithm;
    private $authenticationMethod;
    private $clientNonce;
    private $domain;
    private $entityBody;
    private $method;
    private $nonce;
    private $nonceCount;
    private $opaque;
    private $uri;

    /**
     * QOP options: Only one of the following can be set at any time. setOptions will throw an exception otherwise.
     * OPTION_QOP_AUTH_INT       - Always use auth-int   (if available)
     * OPTION_QOP_AUTH           - Always use auth       (even if auth-int available)
     */
    const OPTION_QOP_AUTH_INT             = 1;
    const OPTION_QOP_AUTH                 = 2;
    /**
     * Ignore server request to downgrade authentication from Digest to Basic.
     * Breaks RFC compatibility, but ensures passwords are never sent using base64 which is trivial for an attacker to decode.
     */
    const OPTION_IGNORE_DOWNGRADE_REQUEST = 4;
    /**
     * Discard Client Nonce on each request.
     */
    const OPTION_DISCARD_CLIENT_NONCE     = 8;

    private $options;

    /**
     * Set OPTION_QOP_BEST_AVAILABLE and OPTION_DISCARD_CLIENT_NONCE by default.
     */
    public function __construct($username = null, $password = null, $realm = null)
    {
        $this->setUsername($username);
        $this->setPassword($password);
        $this->setRealm($realm);
        $this->setOptions(DigestAuthListener::OPTION_QOP_AUTH_INT & DigestAuthListener::OPTION_DISCARD_CLIENT_NONCE);
    }

    /**
     * Passes the returned server headers to parseServerHeaders() to check if any authentication variables need to be set.
     * Inteprets the returned status code and attempts authentication if status is 401 (Authentication Required) by resending
     * the last request with an Authentication header.
     *
     * @param RequestInterface $request  A request object
     * @param MessageInterface $response A response object
     */
    public function postSend(RequestInterface $request, MessageInterface $response)
    {
        $statusCode = $response->getStatusCode();
        $this->parseServerHeaders($response->getHeaders(), $statusCode);
    }

    /**
     * Populates uri, method and entityBody used to generate the Authentication header using the specified request object.
     * Appends the Authentication header if it is present and has been able to be calculated.
     *
     * @param RequestInterface $request  A request object
     */
    public function preSend(RequestInterface $request)
    {
        $this->setUri($request->getResource());
        $this->setMethod($request->getMethod());
        $this->setEntityBody($request->getContent());

        $header = $this->getHeader();
        if($header) {
            $request->addHeader($header);
        }
    }

    /**
     * Sets the password to be used to authenticate the client.
     *
     * @param string $password The password
     *
     * @return void
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * Sets the realm to be used to authenticate the client.
     *
     * @param string $realm The realm
     *
     * @return void
     */
    public function setRealm($realm)
    {
        $this->realm = $realm;
    }

    /**
     * Sets the username to be used to authenticate the client.
     *
     * @param string $username The username
     *
     * @return void
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * Sets the options to be used by this class.
     *
     * @param int $options A bitmask of the constants defined in this class.
     *
     * @return void
     */
    public function setOptions($options)
    {
        if(($options & DigestAuthListener::OPTION_QOP_AUTH_INT) === true) {
            if(($options & DigestAuthListener::OPTION_QOP_AUTH) === true) {
                throw new \InvalidArgumentException('DigestAuthListener: Only one value of OPTION_QOP_AUTH_INT or OPTION_QOP_AUTH may be set.');
            }
            $this->options = $this->options | DigestAuthListener::OPTION_QOP_AUTH_INT;
        } else {
            if(($options & DigestAuthListener::OPTION_QOP_AUTH) === true) {
                $this->options = $this->options | DigestAuthListener::OPTION_QOP_AUTH;
            }
        }

        if(($options & DigestAuthListener::OPTION_IGNORE_DOWNGRADE_REQUEST) === true) {
            $this->options = $this->options | DigestAuthListener::OPTION_IGNORE_DOWNGRADE_REQUEST;
        }

        if(($options & DigestAuthListener::OPTION_DISCARD_CLIENT_NONCE) === true) {
            $this->options = $this->options | DigestAuthListener::OPTION_DISCARD_CLIENT_NONCE;
        }
    }

    /**
     * Discards the Client Nonce forcing the generation of a new Client Nonce on the next request.
     *
     * @return void
     */
    private function discardClientNonce()
    {
        $this->clientNonce = null;
    }

    /**
     * Returns the hashing algorithm to be used to generate the digest value. Currently only returns MD5.
     *
     * @return string The hashing algorithm to be used.
     */
    private function getAlgorithm()
    {
        if($this->algorithm == null) {
            $this->algorithm = 'MD5';
        }
        return $this->algorithm;
    }

    /**
     * Returns the authentication method requested by the server.
     * If OPTION_IGNORE_DOWNGRADE_REQUEST is set this will always return "Digest"
     *
     * @return string Returns either "Digest" or "Basic".
     */
    private function getAuthenticationMethod()
    {
        if(($this->options & DigestAuthListener::OPTION_IGNORE_DOWNGRADE_REQUEST) === true) {
            return "Digest";
        }
        return $this->authenticationMethod;
    }

    /**
     * Returns either the current value of clientNonce or generates a new value if clientNonce is null.
     * Also increments nonceCount.
     *
     * @return string Returns either the current value of clientNonce the newly generated clientNonce;
     */
    private function getClientNonce()
    {
        if($this->clientNonce == null) {
            $this->clientNonce = uniqid();

            if($this->nonceCount == null) {
// If nonceCount is not set then set it to 00000001.
                $this->nonceCount = '00000001';
            } else {
// If it is set then increment it.
                $this->nonceCount++;
// Ensure nonceCount is zero-padded at the start of the string to a length of 8
                while(strlen($this->nonceCount) < 8) {
                    $this->nonceCount = '0' . $this->nonceCount;
                }
            }
        }
        return $this->clientNonce;
    }

    /**
     * Returns a space separated list of uris that the server nonce can be used to generate an authentication response against.
     *
     * @return string Space separated list of uris.
     */
    private function getDomain()
    {
        return $this->domain;
    }

    /**
     * Returns the entity body of the current request.
     * The entity body is the request before it has been encoded with the content-encoding and minus the request headers.
     *
     * @return string The full entity-body.
     */
    private function getEntityBody()
    {
        return (string)$this->entityBody;
    }

    /**
     * Calculates the value of HA1 according to RFC 2617 and RFC 2069.
     *
     * @return string The value of HA1
     */
    private function getHA1()
    {
        $username = $this->getUsername();
        $password = $this->getPassword();
        $realm = $this->getRealm();

        if(($username) AND ($password) AND ($realm)) {
            $algorithm = $this->getAlgorithm();

            if(!isset($algorithm) OR ($algorithm == "MD5")) {

                $A1 = "{$username}:{$realm}:{$password}";
            }
            if($this->algorithm == "MD5-sess") {

                $nonce = $this->getNonce();
                $cnonce = $this->getClientNonce();
                if(($nonce) AND ($cnonce)) {
                    $A1 = $this->hash("{$username}:{$realm}:{$password}") . ":{$nonce}:{$cnonce}";
                }
            }
            if(isset($A1)) {
                $HA1 = $this->hash($A1);
                return $HA1;
            }
        }
        return null;
    }

    /**
     * Calculates the value of HA2 according to RFC 2617 and RFC 2069.
     *
     * @return string The value of HA2
     */
    private function getHA2()
    {
        $method = $this->getMethod();
        $uri = $this->getUri();

        if(($method) AND ($uri)) {
            $qop = $this->getQOP();

            if(!isset($qop) OR ($qop == 'auth')) {
                $A2 = "{$method}:{$uri}";
            }
            if($qop == 'auth-int') {
                $entityBody = $this->getEntityBody();
                $A2 = "{$method}:{$uri}:" . $this->hash($entityBody);
            }

            if(isset($A2)) {
                $HA2 = $this->hash($A2);
                return $HA2;
            }
        }
        return null;
    }

    /**
     * Returns the full Authentication header for use in authenticating the client with either Digest or Basic authentication.
     *
     * @return string The Authentication header to be sent to the server.
     */
    private function getHeader()
    {
        if($this->getAuthenticationMethod() == 'Digest') {
            $username = $this->getUsername();
            $realm = $this->getRealm();
            $nonce = $this->getNonce();
            $response = $this->getResponse();
            if(($username) AND ($realm) AND ($nonce) AND ($response)) {
                $uri = $this->getUri();
                $opaque = $this->getOpaque();
                $domain = $this->getDomain();
                $qop = $this->getQOP();

                $header = "Authorization: Digest";
                $header .= " username=\"" . $username . "\",";
                $header .= " realm=\"" . $realm . "\",";
                $header .= " nonce=\"" . $nonce . "\",";
                $header .= " response=\"" . $response . "\",";

                if($uri) {
                    $header .= " uri=\"" . $uri . "\",";
                }
                if($opaque) {
                    $header .= " opaque=\"" . $opaque . "\",";
                }

                if($qop) {
                    $header .= " qop=" . $qop . ",";

                    $cnonce = $this->getClientNonce();
                    $nc = $this->getNonceCount();

                    if($cnonce) {
                        $header .= " nc=" . $nc . ",";
                    }
                    if($cnonce) {
                        $header .= " cnonce=\"" . $cnonce . "\",";
                    }
                }

// Remove the last comma from the header
                $header = substr($header, 0, strlen($header) - 1);
// Discard the Client Nonce if OPTION_DISCARD_CLIENT_NONCE is set.
                if(($this->options & DigestAuthListener::OPTION_DISCARD_CLIENT_NONCE) === true) {
                    $this->discardClientNonce();
                }
                return $header;
            }
        }
        if($this->getAuthenticationMethod() == 'Basic') {
            $username = $this->getUsername();
            $password = $this->getPassword();
            if(($username) AND ($password)) {
                $header = 'Authorization: Basic ' . base64_encode("{$username}:{$password}");
                return $header;
            }
        }
        return null;
    }

    /**
     * Returns the HTTP method used in the current request.
     *
     * @return string One of GET,POST,PUT,DELETE or HEAD.
     */
    private function getMethod()
    {
        return $this->method;
    }

    /**
     * Returns the value of nonce we have received in the server headers.
     *
     * @return string The value of the server nonce.
     */
    private function getNonce()
    {
        return $this->nonce;
    }

    /**
     * Returns the current nonce counter for the client nonce.
     *
     * @return string An eight digit zero-padded string which reflects the number of times the clientNonce has been generated.
     */
    private function getNonceCount()
    {
        return $this->nonceCount;
    }

    /**
     * Returns the opaque value that was sent to us from the server.
     *
     * @return string The value of opaque.
     */
    private function getOpaque()
    {
        return $this->opaque;
    }

    /**
     * Returns the plaintext password for the client.
     *
     * @return string The value of password.
     */
    private function getPassword()
    {
        return $this->password;
    }

    /**
     * Returns either the realm specified by the client, or the realm specified by the server.
     * If the server set the value of realm then anything set by our client is overwritten.
     *
     * @return string The value of realm.
     */
    private function getRealm()
    {
        return $this->realm;
    }

    /**
     * Calculates the value of response according to RFC 2617 and RFC 2069.
     *
     * @return string The value of response
     */
    private function getResponse()
    {
        $HA1 = $this->getHA1();
        $nonce = $this->getNonce();
        $HA2 = $this->getHA2();

        if(($HA1) AND ($nonce) AND ($HA2)) {
            $qop = $this->getQOP();

            if(!isset($qop)) {
                $response = $this->hash("{$HA1}:{$nonce}:{$HA2}");
                return $response;
            } else {
                $cnonce = $this->getClientNonce();
                $nc = $this->getNonceCount();
                if(($cnonce) AND ($nc)) {
                    $response = $this->hash("{$HA1}:{$nonce}:{$nc}:{$cnonce}:{$qop}:{$HA2}");
                    return $response;
                }
            }
        }
        return null;
    }

    /**
     * Returns the Quality of Protection to be used when authenticating with the server.
     *
     * @return string This will either be auth-int or auth.
     */
    private function getQOP()
    {
// Has the server specified any options for Quality of Protection
        if(isset($this->qop) AND count($this->qop)) {
            if(($this->options & DigestAuthListener::OPTION_QOP_AUTH_INT) === true) {
                if(in_array('auth-int', $this->qop)) {
                    return 'auth-int';
                }
                if(in_array('auth', $this->qop)) {
                    return 'auth';
                }
            }
            if(($this->options & DigestAuthListener::OPTION_QOP_AUTH) === true) {
                if(in_array('auth', $this->qop)) {
                    return 'auth';
                }
                if(in_array('auth-int', $this->qop)) {
                    return 'auth-int';
                }
            }
        }
// Server has not specified any value for Quality of Protection so return null
        return null;
    }

    /**
     * Returns the username set by the client to authenticate with the server.
     *
     * @return string The value of username
     */
    private function getUsername()
    {
        return $this->username;
    }

    /**
     * Returns the uri that we are requesting access to.
     *
     * @return string The value of uri
     */
    private function getUri()
    {
        return $this->uri;
    }

    /**
     * Calculates the hash for a given value using the algorithm specified by the server.
     *
     * @param string $value The value to be hashed
     *
     * @return string The hashed value.
     */
    private function hash($value)
    {
        $algorithm = $this->getAlgorithm();
        if(($algorithm == 'MD5') OR ($algorithm == 'MD5-sess')) {
            return hash('md5', $value);
        }
        return null;
    }

    /**
     * Parses the Authentication-Info header received from the server and calls the relevant setter method on each variable received.
     *
     * @param string $authenticationInfo The full Authentication-Info header.
     *
     * @return void
     */
    private function parseAuthenticationInfoHeader($authenticationInfo)
    {
// Remove "Authentication-Info: " from start of header
        $wwwAuthenticate = substr($wwwAuthenticate, 21, strlen($wwwAuthenticate) - 21);

        $nameValuePairs = $this->parseNameValuePairs($wwwAuthenticate);
        foreach($nameValuePairs as $name => $value) {
            switch($name) {
                case 'message-qop':

                break;
                case 'nextnonce':
// This function needs to only set the Nonce once the rspauth has been verified.
                    $this->setNonce($value);
                break;
                case 'rspauth':
// Check server rspauth value
                break;
            }
        }
    }

    /**
     * Parses a string of name=value pairs separated by commas and returns and array with the name as the index.
     *
     * @param string $nameValuePairs The string containing the name=value pairs.
     *
     * @return array An array with the name used as the index and the values stored within.
     */
    private function parseNameValuePairs($nameValuePairs)
    {
        $parsedNameValuePairs = array();
        $nameValuePairs = explode(',', $nameValuePairs);
        foreach($nameValuePairs as $nameValuePair) {
// Trim the Whitespace from the start and end of the name value pair string
            $nameValuePair = trim($nameValuePair);
// Split $nameValuePair (name=value) into $name and $value
            list($name, $value) = explode('=', $nameValuePair, 2);
// Remove quotes if the string is quoted
            $value = $this->unquoteString($value);
// Add pair to array[name] => value
            $parsedNameValuePairs[$name] = $value;
        }
        return $parsedNameValuePairs;
    }

    /**
     * Parses the server headers received and checks for WWW-Authenticate and Authentication-Info headers.
     * Calls parseWwwAuthenticateHeader() and parseAuthenticationInfoHeader() respectively if either of these headers are present.
     *
     * @param array $headers An array of the headers received by the client.
     *
     * @return void
     */
    private function parseServerHeaders(array $headers)
    {
        foreach($headers as $header) {
// Check to see if the WWW-Authenticate header is present and if so set $authHeader
            if(strtolower(substr($header, 0, 18)) == 'www-authenticate: ') {
                $wwwAuthenticate = $header;
                $this->parseWwwAuthenticateHeader($wwwAuthenticate);
            }
// Check to see if the Authentication-Info header is present and if so set $authInfo
            if(strtolower(substr($header, 0, 21)) == 'authentication-info: ') {
                $authenticationInfo = $header;
                $this->parseAuthenticationInfoHeader($wwwAuthenticate);
            }
        }
    }

    /**
     * Parses the WWW-Authenticate header received from the server and calls the relevant setter method on each variable received.
     *
     * @param string $wwwAuthenticate The full WWW-Authenticate header.
     *
     * @return void
     */
    private function parseWwwAuthenticateHeader($wwwAuthenticate)
    {
// Remove "WWW-Authenticate: " from start of header
        $wwwAuthenticate = substr($wwwAuthenticate, 18, strlen($wwwAuthenticate) - 18);
        if(substr($wwwAuthenticate, 0, 7) == 'Digest ') {
            $this->setAuthenticationMethod('Digest');
// Remove "Digest " from start of header
            $wwwAuthenticate = substr($wwwAuthenticate, 7, strlen($wwwAuthenticate) - 7);

            $nameValuePairs = $this->parseNameValuePairs($wwwAuthenticate);

            foreach($nameValuePairs as $name => $value) {
                switch($name) {
                    case 'algorithm':
                        $this->setAlgorithm($value);
                    break;
                    case 'domain':
                        $this->setDomain($value);
                    break;
                    case 'nonce':
                        $this->setNonce($value);
                    break;
                    case 'realm':
                        $this->setRealm($value);
                    break;
                    case 'opaque':
                        $this->setOpaque($value);
                    break;
                    case 'qop':
                        $this->setQOP(explode(',', $value));
                    break;
                }
            }
        }
        if (substr($wwwAuthenticate, 0, 6) == 'Basic ') {
            $this->setAuthenticationMethod('Basic');
// Remove "Basic " from start of header
            $wwwAuthenticate = substr($wwwAuthenticate, 6, strlen($wwwAuthenticate) - 6);

            $nameValuePairs = $this->parseNameValuePairs($wwwAuthenticate);

            foreach($nameValuePairs as $name => $value) {
                switch($name) {
                    case 'realm':
                        $this->setRealm($value);
                    break;
                }
            }
        }
    }

    /**
     * Sets the hashing algorithm to be used. Currently only uses MD5 specified by either MD5 or MD5-sess.
     * RFCs are currently in draft stage for the proposal of SHA-256 and SHA-512-256.
     * Support will be added once the RFC leaves the draft stage.
     *
     * @param string $algorithm The algorithm the server has requested to use.
     *
     * @throws \InvalidArgumentException If $algorithm is set to anything other than MD5 or MD5-sess.
     *
     * @return void
     */
    private function setAlgorithm($algorithm)
    {
        if(($algorithm == 'MD5') OR ($algorithm == 'MD5-sess')) {
            $this->algorithm = $algorithm;
        } else {
            throw new \InvalidArgumentException('DigestAuthListener: Only MD5 and MD5-sess algorithms are currently supported.');
        }
    }

    /**
     * Sets authentication method to be used. Options are "Digest" and "Basic".
     * If the server and the client are unable to authenticate using Digest then the RFCs state that the server should attempt
     * to authenticate the client using Basic authentication. This ensures that we adhere to that behaviour.
     * This does however create the possibilty of a downgrade attack so it may be an idea to add a way of disabling this functionality
     * as Basic authentication is trivial to decrypt and exposes the username/password to a man-in-the-middle attack.
     *
     * @param string $authenticationMethod The authentication method requested by the server.
     *
     * @throws \InvalidArgumentException If $authenticationMethod is set to anything other than Digest or Basic
     *
     * @return void
     */
    private function setAuthenticationMethod($authenticationMethod)
    {
        if(($authenticationMethod == 'Digest') OR ($authenticationMethod == 'Basic')) {
            $this->authenticationMethod = $authenticationMethod;
        } else {
            throw new \InvalidArgumentException('DigestAuthListener: Only Digest and Basic authentication methods are currently supported.');
        }
    }

    /**
     * Sets the domain to be authenticated against. THIS IS NOT TO BE CONFUSED WITH THE HOSTNAME/DOMAIN.
     * This is specified by the RFC to be a list of uris separated by spaces that the client will be allowed to access.
     * An RFC in draft stage is proposing the removal of this functionality, it does not seem to be in widespread use.
     *
     * @param string $domain The list of uris separated by spaces that the client will be able to access upon successful authentication.
     *
     * @return void
     */
    private function setDomain($value)
    {
        $this->domain = $value;
    }

    /**
     * Sets the Entity Body of the Request for use with qop=auth-int
     *
     * @param string $entityBody The body of the entity (The unencoded request minus the headers).
     *
     * @return void
     */
    private function setEntityBody($entityBody = null)
    {
        $this->entityBody = $entityBody;
    }

    /**
     * Sets the HTTP method being used for the request
     *
     * @param string $method The HTTP method
     *
     * @throws \InvalidArgumentException If $method is set to anything other than GET,POST,PUT,DELETE or HEAD.
     *
     * @return void
     */
    private function setMethod($method = null)
    {
        if($method == 'GET') {
            $this->method = 'GET';
            return;
        }
        if($method == 'POST') {
            $this->method = 'POST';
            return;
        }
        if($method == 'PUT') {
            $this->method = 'PUT';
            return;
        }
        if($method == 'DELETE') {
            $this->method = 'DELETE';
            return;
        }
        if($method == 'HEAD') {
            $this->method = 'HEAD';
            return;
        }
        throw new \InvalidArgumentException('DigestAuthListener: Only GET,POST,PUT,DELETE,HEAD HTTP methods are currently supported.');
    }

    /**
     * Sets the value of nonce
     *
     * @param string $opaque The server nonce value
     *
     * @return void
     */
    private function setNonce($nonce = null)
    {
        $this->nonce = $nonce;
    }

    /**
     * Sets the value of opaque
     *
     * @param string $opaque The opaque value
     *
     * @return void
     */
    private function setOpaque($opaque)
    {
        $this->opaque = $opaque;
    }

    /**
     * Sets the acceptable value(s) for the quality of protection used by the server. Supported values are auth and auth-int.
     * TODO: This method should give precedence to using qop=auth-int first as this offers integrity protection.
     *
     * @param array $qop An array with the values of qop that the server has specified it will accept.
     *
     * @throws \InvalidArgumentException If $qop contains any values other than auth-int or auth.
     *
     * @return void
     */
    private function setQOP(array $qop = array())
    {
        $this->qop = array();
        foreach($qop as $protection) {
            $protection = trim($protection);
            if($protection == 'auth-int') {
                $this->qop[] = 'auth-int';
            } elseif($protection == 'auth') {
                $this->qop[] = 'auth';
            } else {
                throw new \InvalidArgumentException('DigestAuthListener: Only auth-int and auth are supported Quality of Protection mechanisms.');
            }
        }
    }

    /**
     * Sets the value of uri
     *
     * @param string $uri The uri
     *
     * @return void
     */
    private function setUri($uri = null)
    {
        $this->uri = $uri;
    }

    /**
     * If a string contains quotation marks at either end this function will strip them. Otherwise it will remain unchanged.
     *
     * @param string $str The string to be stripped of quotation marks.
     *
     * @return string Returns the original string without the quotation marks at either end.
     */
    private function unquoteString($str = null)
    {
        if($str) {
            if(substr($str, 0, 1) == '"') {
                $str = substr($str, 1, strlen($str) - 1);
            }
            if(substr($str, strlen($str) - 1, 1) == '"') {
                $str = substr($str, 0, strlen($str) - 1);
            }
        }
        return $str;
    }
}


text:
#ifndef SGSXGMATH_H
#define SGSXGMATH_H

#ifdef __cplusplus
extern "C" {
#endif

#include <math.h>
#include <stdarg.h>

#ifndef HEADER_SGSCRIPT_H
# define HEADER_SGSCRIPT_H <sgscript.h>
#endif
#include HEADER_SGSCRIPT_H

#ifndef XGM_VT
#define XGM_VT float
#endif
#ifndef XGM_PROPTYPE
#define XGM_PROPTYPE SGS_OBJPROPTYPE_FLOAT
#endif

#define XGM_SMALL_VT 0.0001f

typedef struct _xgm_vtarray
{
	XGM_VT* data;
	sgs_SizeVal size;
	sgs_SizeVal mem;
}
xgm_vtarray;

SGS_APIFUNC extern sgs_ObjInterface xgm_vec2_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_vec3_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_vec4_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_aabb2_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_aabb3_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_color_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_quat_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_mat3_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_mat4_iface[1];
SGS_APIFUNC extern sgs_ObjInterface xgm_floatarr_iface[1];

SGS_APIFUNC SGSONE sgs_CreateVec2( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y );
SGS_APIFUNC SGSONE sgs_CreateVec3( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z );
SGS_APIFUNC SGSONE sgs_CreateVec4( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w );
SGS_APIFUNC SGSONE sgs_CreateAABB2( SGS_CTX, sgs_Variable* var, XGM_VT x1, XGM_VT y1, XGM_VT x2, XGM_VT y2 );
SGS_APIFUNC SGSONE sgs_CreateAABB3( SGS_CTX, sgs_Variable* var, const XGM_VT* v3a, const XGM_VT* v3b );
SGS_APIFUNC SGSONE sgs_CreateColor( SGS_CTX, sgs_Variable* var, XGM_VT r, XGM_VT g, XGM_VT b, XGM_VT a );
SGS_APIFUNC SGSONE sgs_CreateQuat( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w );
SGS_APIFUNC SGSONE sgs_CreateMat3( SGS_CTX, sgs_Variable* var, const XGM_VT* v9f, int transpose );
SGS_APIFUNC SGSONE sgs_CreateMat4( SGS_CTX, sgs_Variable* var, const XGM_VT* v16f, int transpose );
SGS_APIFUNC SGSONE sgs_CreateFloatArray( SGS_CTX, sgs_Variable* var, const XGM_VT* vfn, sgs_SizeVal size );

SGS_APIFUNC SGSONE sgs_CreateVec2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v2f );
SGS_APIFUNC SGSONE sgs_CreateVec3p( SGS_CTX, sgs_Variable* var, const XGM_VT* v3f );
SGS_APIFUNC SGSONE sgs_CreateVec4p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f );
SGS_APIFUNC SGSONE sgs_CreateAABB2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f );
SGS_APIFUNC SGSONE sgs_CreateAABB3p( SGS_CTX, sgs_Variable* var, const XGM_VT* v6f );
SGS_APIFUNC SGSONE sgs_CreateColorp( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f );
SGS_APIFUNC SGSONE sgs_CreateColorvp( SGS_CTX, sgs_Variable* var, const XGM_VT* vf, int numfloats );
SGS_APIFUNC SGSONE sgs_CreateQuatp( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f );

SGS_APIFUNC SGSBOOL sgs_ParseVT( SGS_CTX, sgs_StkIdx item, XGM_VT* out );
SGS_APIFUNC SGSBOOL sgs_ParseVec2( SGS_CTX, sgs_StkIdx item, XGM_VT* v2f, int strict );
SGS_APIFUNC SGSBOOL sgs_ParseVec3( SGS_CTX, sgs_StkIdx item, XGM_VT* v3f, int strict );
SGS_APIFUNC SGSBOOL sgs_ParseVec4( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict );
SGS_APIFUNC SGSBOOL sgs_ParseAABB2( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f );
SGS_APIFUNC SGSBOOL sgs_ParseAABB3( SGS_CTX, sgs_StkIdx item, XGM_VT* v6f );
SGS_APIFUNC SGSBOOL sgs_ParseColor( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict );
SGS_APIFUNC SGSBOOL sgs_ParseQuat( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict );
SGS_APIFUNC SGSBOOL sgs_ParseMat3( SGS_CTX, sgs_StkIdx item, XGM_VT* v9f );
SGS_APIFUNC SGSBOOL sgs_ParseMat4( SGS_CTX, sgs_StkIdx item, XGM_VT* v16f );
SGS_APIFUNC SGSBOOL sgs_ParseFloatArray( SGS_CTX, sgs_StkIdx item, XGM_VT** vfa, sgs_SizeVal* osz );

SGS_APIFUNC int sgs_ArgCheck_Vec2( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Vec3( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Vec4( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_AABB2( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_AABB3( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Color( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Quat( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Mat3( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_Mat4( SGS_CTX, int argid, va_list* args, int flags );
SGS_APIFUNC int sgs_ArgCheck_FloatArray( SGS_CTX, int argid, va_list* args, int flags );

SGS_APIFUNC int sgs_xgm_module_entry_point( SGS_CTX );

#ifdef __cplusplus
}
#endif

#endif /* SGSXGMATH_H */

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>fontswitching - text partially supported</title>

You should see the result text in between two rectangles.

FAIL ⓅⒶⓈⓈ FAIL


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <title>Control structures.for</title>
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

    Language documentation
  	Contents | Index

for, Control structures

Prototype:

for (expr1; expr2; expr3) statement

Description:

for loops are the most complex loops. They behave similar to their C counterparts.

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to true, the loop continues and the nested statement(s) are executed. If it evaluates to false, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as true, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Example:

for (var i=0, var j="test";i<=10;i++) {
	echo i;
}

for (var i=0;i<=10;i++) {
	echo i;
}

for (var i=0;;i++) {
	if (i>10)
		break;
	echo i;
}

var i=0;
for (;;) {
	if (i>10)
		break;
	i++;
}

Documented by Eduard Suica, generation time: Sun Jan 27 18:15:22 2013
 GMT	(c)2013 Devronium Applications


text:
package com.manniwood.cl4pg.v1.test.ds.pgsimple;

import com.manniwood.cl4pg.v1.datasourceadapters.DataSourceAdapter;
import com.manniwood.cl4pg.v1.datasourceadapters.PgSimpleDataSourceAdapter;
import com.manniwood.cl4pg.v1.test.base.AbstractCopyTest;
import com.manniwood.cl4pg.v1.test.base.AbstractFluentApiTest;
import org.testng.annotations.Test;

@Test
public class PgSimpleFluentApiTest extends AbstractFluentApiTest {

    @Override
    protected DataSourceAdapter configureDataSourceAdapter() {
        return PgSimpleDataSourceAdapter.buildFromDefaultConfFile();
    }

}


text:
require_relative 'common'

describe 'Sanitize::Transformers::CleanDoctype' do
  make_my_diffs_pretty!
  parallelize_me!

  describe 'when :allow_doctype is false' do
    before do
      @s = Sanitize.new(:allow_doctype => false, :elements => ['html'])
    end

    it 'should remove doctype declarations' do
      _(@s.document('<!DOCTYPE html>foo')).must_equal "foo"
      _(@s.fragment('<!DOCTYPE html>foo')).must_equal 'foo'
    end

    it 'should not allow doctype definitions in fragments' do
      _(@s.fragment('<!DOCTYPE html>foo'))
        .must_equal "foo"

      _(@s.fragment('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">foo'))
        .must_equal "foo"

      _(@s.fragment("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">foo"))
        .must_equal "foo"
    end
  end

  describe 'when :allow_doctype is true' do
    before do
      @s = Sanitize.new(:allow_doctype => true, :elements => ['html'])
    end

    it 'should allow doctype declarations in documents' do
      _(@s.document('<!DOCTYPE html>foo'))
        .must_equal "<!DOCTYPE html>foo"

      _(@s.document('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">foo'))
        .must_equal "<!DOCTYPE html>foo"

      _(@s.document("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">foo"))
        .must_equal "<!DOCTYPE html>foo"
    end

    it 'should not allow obviously invalid doctype declarations in documents' do
      _(@s.document('<!DOCTYPE blah blah blah>foo'))
        .must_equal "<!DOCTYPE html>foo"

      _(@s.document('<!DOCTYPE blah>foo'))
        .must_equal "<!DOCTYPE html>foo"

      _(@s.document('<!DOCTYPE html BLAH "-//W3C//DTD HTML 4.01//EN">foo'))
        .must_equal "<!DOCTYPE html>foo"

      _(@s.document('<!whatever>foo'))
        .must_equal "foo"
    end

    it 'should not allow doctype definitions in fragments' do
      _(@s.fragment('<!DOCTYPE html>foo'))
        .must_equal "foo"

      _(@s.fragment('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">foo'))
        .must_equal "foo"

      _(@s.fragment("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">foo"))
        .must_equal "foo"
    end
  end
end


text:
package psidev.psi.mi.jami.xml.io.writer.elements.impl.extended.compact.xml30;

import psidev.psi.mi.jami.model.ModelledInteraction;
import psidev.psi.mi.jami.xml.cache.PsiXmlObjectCache;
import psidev.psi.mi.jami.xml.io.writer.elements.CompactPsiXmlElementWriter;
import psidev.psi.mi.jami.xml.io.writer.elements.impl.extended.xml30.AbstractXmlModelledInteractionWriter;

import javax.xml.stream.XMLStreamWriter;

/**
 * Compact XML 3.0 writer for an expanded modelled interaction (ignore experimental details).
 * It will write cooperative effects as attributes.
 * It will write intra-molecular property, names, interaction types and experiments
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
15/11/13

 */
public class XmlModelledInteractionWriter extends AbstractXmlModelledInteractionWriter<ModelledInteraction>
        implements CompactPsiXmlElementWriter<ModelledInteraction> {

    /**
     *
Constructor for XmlModelledInteractionWriter.

     *
     * @param writer a {@link javax.xml.stream.XMLStreamWriter} object.
     * @param objectIndex a {@link psidev.psi.mi.jami.xml.cache.PsiXmlObjectCache} object.
     */
    public XmlModelledInteractionWriter(XMLStreamWriter writer, PsiXmlObjectCache objectIndex) {
        super(writer, objectIndex);
    }

    /** {@inheritDoc} */
    @Override
    protected void initialiseParticipantWriter() {
        super.setParticipantWriter(new XmlModelledParticipantWriter(getStreamWriter(), getObjectIndex()));
    }
}


text:
/* See LICENSE for licensing information */

package jutgelint

import (
	"bytes"
	"flag"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
)

var (
	write = flag.Bool("write", false, "Write json results")
	name  = flag.String("name", "", "Test name")
)

func init() {
	flag.Parse()
}

const (
	testsDir = "tests"
	inGlob   = "in.*"
)

func inPaths(dir, file string) (string, error) {
	pattern := filepath.Join(testsDir, dir, file)
	paths, err := filepath.Glob(pattern)
	if err != nil {
		return "", err
	}
	return paths[0], nil
}

func doTest(t *testing.T, dir, inPath string) {
	base := filepath.Base(inPath)
	lang, err := ParseLangFilename(base)
	if err != nil {
		t.Errorf("Could not infer language: %v", err)
		return
	}
	outPath := filepath.Join(testsDir, dir, "out"+filepath.Ext(base))
	in, err := os.Open(inPath)
	if err != nil {
		t.Errorf("Failed opening in file %s: %v", inPath, err)
		return
	}
	defer in.Close()
	var out bytes.Buffer
	if err := CheckAndCommentCode(lang, in, &out); err != nil {
		t.Errorf("Failed checking and commenting code '%s': %v", inPath, err)
		return
	}
	got := out.Bytes()
	if *write {
		out, err := os.Create(outPath)
		if err != nil {
			t.Errorf("Failed opening out file '%s': %v", outPath, err)
			return
		}
		defer out.Close()
		_, err = out.Write(got)
		if err != nil {
			t.Errorf("Failed writing out file '%s': %v", outPath, err)
			return
		}
	} else {
		out, err := os.Open(outPath)
		if err != nil {
			t.Errorf("Failed opening out file '%s': %v", outPath, err)
			return
		}
		defer out.Close()
		want, err := ioutil.ReadAll(out)
		if err != nil {
			t.Errorf("Failed reading out file '%s': %v", outPath, err)
			return
		}
		if string(want) != string(got) {
			t.Errorf("Mismatching outputs for '%s'", inPath)
			return
		}
	}
}

func doTestDir(t *testing.T, dir string) {
	inPattern := filepath.Join(testsDir, dir, inGlob)
	inPaths, err := filepath.Glob(inPattern)
	if err != nil {
		t.Errorf("Globbing failed: %v", err)
		return
	}
	for _, path := range inPaths {
		doTest(t, dir, path)
	}
}

func TestCases(t *testing.T) {
	entries, err := ioutil.ReadDir(testsDir)
	if err != nil {
		return
	}
	if *name != "" {
		doTestDir(t, *name)
	} else {
		for _, e := range entries {
			if !e.IsDir() {
				continue
			}
			doTestDir(t, e.Name())
		}
	}
}


text:
from redhat_support_lib.utils.parsehelper import ParseHelper
from redhat_support_lib.infrastructure import contextmanager

class Base(object):
    ''' Returns the proxy to connections pool '''
    def _getProxy(self):
        return contextmanager.get('proxy')

    def __getattr__(self, item):
        return self.superclass.__getattribute__(item)

    def toXml(self):
        '''
        A utility method to print this object's superclass as XML.
        The superclass property should be a member of redhat_support_lib.xml.params.
        '''
        return ParseHelper.toXml(self.superclass)


text:
'use strict';
var Probe = require('../lib/probe.js');
var aspect = require('../lib/aspect.js');
var request = require('../lib/request.js');
var util = require('util');
var am = require('../');

function Strong_MQProbe() {
  Probe.call(this, 'strong-mq');
}
util.inherits(Strong_MQProbe, Probe);

/*
 * Select the methods we want to instrument for each type of queue.
 */
var typeToMethods = {
  createPushQueue: ['publish'],
  createPullQueue: ['on', 'addListener'],
  createPubQueue: ['publish'],
  createSubQueue: ['on', 'addListener'],
};

var typeToEventType = {
  createPushQueue: 'push',
  createPullQueue: 'pull',
  createPubQueue: 'pub',
  createSubQueue: 'sub',
};

Strong_MQProbe.prototype.attach = function(name, target) {
  var that = this;
  if (name != 'strong-mq') {
    return target;
  }
  target.__ddProbeAttached__ = true;
  aspect.after(target, 'create', {}, function(target, methodName, methodArgs, context, connection) {
    aspect.after(connection, ['createPushQueue', 'createPubQueue'], {}, function(
      target,
      methodName,
      methodArgs,
      context,
      queue
    ) {
      var socketType = methodName;
      var methods = typeToMethods[socketType];
      aspect.around(
        queue,
        methods,
        function(target, methodName, methodArgs, context) {
          that.metricsProbeStart(context, methodName, methodArgs);
          that.requestProbeStart(context, methodName, methodArgs);
          aspect.aroundCallback(methodArgs, context, function(target, args, context) {
            // Call the transaction link with a name and the callback for strong trace
            var callbackPosition = aspect.findCallbackArg(methodArgs);
            if (typeof callbackPosition != 'undefined') {
              aspect.strongTraceTransactionLink('strong-mq: ', methodName, methodArgs[callbackPosition]);
            }

            that.metricsProbeEnd(context, methodName, methodArgs);
            that.requestProbeEnd(context, methodName, methodArgs);
          });
        },
        function(target, methodName, methodArgs, context, rc) {
          if (aspect.findCallbackArg(methodArgs) == undefined) {
            that.metricsProbeEnd(context, methodName, methodArgs, typeToEventType[socketType]);
            that.requestProbeEnd(context, methodName, methodArgs, typeToEventType[socketType]);
          }
          return rc;
        }
      );
      return queue;
    });
    aspect.after(connection, ['createPullQueue', 'createSubQueue'], {}, function(
      target,
      methodName,
      methodArgs,
      context,
      queue
    ) {
      var socketType = methodName;
      var methods = typeToMethods[socketType];
      aspect.before(queue, methods, function(target, methodName, methodArgs, context) {
        var eventName = 'message';
        if (aspect.findCallbackArg(methodArgs) != undefined) {
          aspect.aroundCallback(
            methodArgs,
            context,
            function(target, args, context) {
              that.metricsProbeStart(context, eventName, methodArgs);
              that.requestProbeStart(context, eventName, methodArgs);
            },
            function(target, methodArgs, context, rc) {
              // Call the transaction link with a name and the callback for strong trace
              var callbackPosition = aspect.findCallbackArg(methodArgs);
              if (typeof callbackPosition != 'undefined') {
                aspect.strongTraceTransactionLink('strong-mq: ', methodName, methodArgs[callbackPosition]);
              }

              that.metricsProbeEnd(context, eventName, methodArgs, typeToEventType[socketType]);
              that.requestProbeEnd(context, eventName, methodArgs, typeToEventType[socketType]);
              return rc;
            }
          );
        }
      });
      return queue;
    });
    return connection;
  });
  return target;
};

/*
 * Lightweight metrics probe for STRONG-MQ messaging
 * Provide basic information on messages sent and received.
 * These provide:
 *		time:		time event started
 *      type:		whether this was a pub, sub, push or pull event.
 *		method:		if this was a method call (a send) the method name
 *		event:		if this was an event (a message was received) the name of the event
 *		duration:	the time for the request to respond
 */
Strong_MQProbe.prototype.metricsEnd = function(context, methodName, methodArgs, eventType) {
  if (context && context.timer) {
    context.timer.stop();
    // default to quality of service (qos) 0, as that's what the strong-mq module does
    var eventData = {
      time: context.timer.startTimeMillis,
      duration: context.timer.timeDelta,
      type: eventType,
    };
    if (methodName == 'publish') {
      eventData.method = methodName;
    } else {
      eventData.event = 'message';
    }
    am.emit('strong-mq', eventData);
  }
};

/*
 * Heavyweight request probes for STRONG-MQ messages
 */
Strong_MQProbe.prototype.requestStart = function(context, methodName, methodArgs, socketType) {
  if (methodName === 'publish') {
    context.req = request.startRequest('strong-mq', methodName, false, context.timer);
  } else {
    /* Received messages mark the start of requests. */
    context.req = request.startRequest('strong-mq', 'message', true, context.timer);
  }
};

Strong_MQProbe.prototype.requestEnd = function(context, methodName, methodArgs, socketType) {
  if (context && context.req) context.req.stop({ topic: methodArgs[0] });
};

module.exports = Strong_MQProbe;


text:
<?php

namespace ScContent\Options;

/**
 * @author Dolphin <work.dolphin@gmail.com>
 */
interface ModuleWidgetInterface
{
    /**
     * @param array $widgets
     */
    function setWidgets($widgets);

    /**
     * @param  string $name
     * @return array
     */
    function getWidgetByName($name);

    /**
     * @param  string $name
     * @return string
     */
    function getWidgetDisplayName($name);

    /**
     * @return array
     */
    function getWidgets();

    /**
     * @param  string $name
     * @return boolean
     */
    function widgetExists($name);
}


text:
define(
  [
    'backbone',
    'handlebars',
    'bluebird',
    'underscore',
    'jquery',
    'data-download/views/DownloadFilterCardView',
    'views/shared/SwitchView',
    'helpers/utilsHelper',
    'text!data-download/templates/download-filters.handlebars'
  ],
  function(
    Backbone,
    Handlebars,
    Promise,
    _,
    $,
    DownloadFilterCardView,
    SwitchView,
    UtilsHelper,
    tpl
  ) {
    'use strict';
    var DataDownloadIndexView = Backbone.View.extend({
      filters: [
        {
          id: 'country_codes',
          name: 'Countries'
        },
        {
          id: 'jurisdiction_ids',
          name: 'Jurisdictions',
          placeholder: 'Select a country'
        },
        {
          id: 'area_ids',
          name: 'Areas of interest',
          placeholder: 'Select a country'
        },
        {
          id: 'widget_ids',
          name: 'Indicators'
        },
        {
          id: 'dataSource',
          name: 'Data source',
          placeholder: 'Select an indicator',
          hide: true
        },
        {
          id: 'thresholds',
          name: '% Tree cover density',
          placeholder: 'Select an indicator'
        },
        {
          id: 'years',
          name: 'Years',
          placeholder: 'Select an indicator'
        }
      ],
      mandatorys: ['country_codes', 'widget_ids'],
      validationMsg:
        'Please select, at least, a country, an indicator and a year',
      tresh: [10, 15, 20, 25, 30],
      switchs: [
        {
          el: 'outputTypeSwitch',
          param: 'pivot',
          label: 'Output Type',
          options: [
            { label: 'Table', value: 0, selected: true },
            { label: 'Pivot', value: 1 }
          ]
        },
        {
          el: 'filerSwitch',
          param: 'json',
          label: 'File',
          options: [
            { label: '.csv', value: 0, selected: true },
            { label: '.json', value: 1 }
          ]
        }
      ],

      el: '#download-page',
      template: Handlebars.compile(tpl),

      events: {
        'click #download-btn': 'onDownloadClick',
        'click #clear-btn': 'onClearClick'
      },

      initialize: function() {
        this.filterViews = [];
        this.switchViews = [];
        this.filterIndex = {};
        this.availableIndicators = [];
        this.jurisdictionsData = {};
        this.domCache();
        this.getData().then(
          function() {
            this.populate();
            this.render();
          }.bind(this)
        );
      },

      domCache: function() {
        this.filtersContainer = this.$('#filters-container');
      },

      getData: function() {
        return Promise.all([
          $.getJSON('api/widgets'),
          $.getJSON('api/countries')
        ]).then(
          function(data) {
            this.widgets = data[0].widgets;
            this.countries = data[1].countries;
          }.bind(this)
        );
      },

      populate: function() {
        this.filters.forEach(function(filter) {
          switch (filter.id) {
            case 'country_codes':
              filter.options = this.getCountryOptions();
              break;
            case 'jurisdiction_ids':
              filter.options = [];
              break;
            case 'widget_ids':
              filter.options = this.getIndicatorsOptions();
              break;
            case 'dataSource':
              filter.options = [];
              break;
            case 'thresholds':
              filter.options = [];
              break;
            case 'years':
              filter.options = [];
              break;
            default:
              filter.options = [];
          }
        }, this);
      },

      getCountryOptions: function() {
        return this.countries.map(function(country) {
          return {
            value: country.iso,
            name: country.name
          };
        });
      },

      getCountryData: function(iso) {
        return $.getJSON('api/countries/' + iso).then(
          function(data) {
            if (data && data.country && data.country) {
              var parseData = function(items) {
                return items.map(function(item) {
                  return {
                    value: item.id,
                    name: item.name
                  };
                });
              };
              var jurisdictionsData = {
                areasOfInterest: parseData(data.country.areas_of_interest),
                jurisdictions: parseData(data.country.jurisdictions)
              };
              this.jurisdictionsData[iso] = jurisdictionsData;
              return jurisdictionsData;
            }
            return [];
          }.bind(this)
        );
      },

      getIndicatorsOptions: function() {
        return this.widgets.map(function(widget) {
          return {
            value: widget.id + '',
            indicators: widget.indicators.map(function(indicator) {
              return indicator.id;
            }),
            name: widget.name
          };
        });
      },

      setClearVisibility: function(value) {
        if (!this.clearBtn) {
          this.clearBtn = this.$('#clear-btn');
        }
        if (value) {
          this.clearBtn.removeClass('-hide');
        } else {
          this.clearBtn.addClass('-hide');
        }
      },

      onIndicatorsChange: function(selection) {
        var dataSourceOptions = [];
        this.availableIndicators = [];
        this.widgets.forEach(function(widget) {
          if (
            _.include(selection, widget.id + '') &&
            widget.tabs &&
            widget.tabs.length > 0
          ) {
            widget.tabs.forEach(function(tab) {
              this.availableIndicators.push(tab);
              dataSourceOptions.push({
                value: tab.name,
                name: tab.name
              });
            }, this);
          }
        }, this);

        this.filterViews[this.filterIndex.dataSource].renderOptions(
          dataSourceOptions,
          ''
        );
        if (dataSourceOptions) {
          this.filterViews[this.filterIndex.dataSource].setAllMarked(true);
          this.onDataSourceChange(
            dataSourceOptions.map(function(option) {
              return option.value;
            })
          );
        } else {
          this.filterViews[this.filterIndex.dataSource].setAllMarked(false);
        }
        this.setClearVisibility(true);
      },

      onDataSourceChange: function(selection) {
        var years = [];
        var trhesAllowed = false;

        if (selection && selection.length) {
          this.availableIndicators.forEach(function(indicator) {
            if (_.include(selection, indicator.name)) {
              if (indicator.range) {
                years = _.union(years, indicator.range);
              }
              if (indicator.thresh) {
                trhesAllowed = true;
              }
            }
          }, this);

          var yearsOptions = [];
          var yearsMsg = '';
          var selectAllYears = false;
          if (years.length) {
            yearsOptions = years.map(function(year) {
              return { name: year, value: year };
            });
            selectAllYears = true;
          } else {
            yearsMsg = 'No years availables';
          }
          this.filterViews[this.filterIndex.years].renderOptions(
            yearsOptions,
            yearsMsg
          );
          this.filterViews[this.filterIndex.years].setAllMarked(selectAllYears);

          if (trhesAllowed) {
            var trheshOptions = this.tresh.map(function(thresh) {
              return { name: thresh, value: thresh, selected: thresh === 30 };
            });
            this.filterViews[this.filterIndex.thresholds].renderOptions(
              trheshOptions
            );
          } else {
            this.filterViews[this.filterIndex.thresholds].renderOptions(
              [],
              'Threshold selection is not allowed'
            );
          }
        } else {
          this.filterViews[this.filterIndex.thresholds].renderOptions(
            [],
            'Select a data source'
          );
          this.filterViews[this.filterIndex.years].renderOptions(
            [],
            'Select a data source'
          );
          this.filterViews[this.filterIndex.years].setAllMarked(false);
        }
      },

      getTreeCoverOptions: function() {
        return this.tresh.map(function(tresh) {
          return {
            value: tresh,
            name: tresh + '%'
          };
        });
      },

      getYearsOptions: function() {
        return this.years.map(function(year) {
          return {
            value: year,
            name: year
          };
        });
      },

      render: function() {
        this.filtersContainer.html(this.template({ filters: this.filters }));
        this.filters.forEach(function(filter, index) {
          var view = new DownloadFilterCardView({
            el: '#' + filter.id + '-filter-card',
            filter: filter
          });
          this.listenTo(
            view,
            'option:changed',
            this.onOptionChange.bind(this, filter.id)
          );
          var filterindex = {};
          filterindex[filter.id] = index;
          this.filterIndex = _.extend(this.filterIndex, filterindex);
          this.filterViews.push(view);
        }, this);

        this.switchs.forEach(function(option) {
          var view = new SwitchView({
            el: '#' + option.el,
            param: option.param,
            data: {
              label: option.label,
              options: option.options
            }
          });
          this.switchViews.push(view);
        }, this);
      },

      checkDownloadAvailable: function() {
        var mandatorysSelected = 0;
        var hasSelected = function(view) {
          if (!view) return false;
          if (view.selection && view.selection.length > 0) return true;
          return false;
        };
        this.filterViews.forEach(function(view) {
          if (_.include(this.mandatorys, view.filter.id) && hasSelected(view)) {
            mandatorysSelected += 1;
          }
        }, this);
        var isValid = mandatorysSelected === this.mandatorys.length;
        this.$('#download-btn').prop('disabled', !isValid);
        if (!this.validationMsgEl) {
          this.validationMsgEl = this.$('.validation-msg');
        }
        if (isValid) {
          this.validationMsgEl.addClass('-hide');
        } else {
          this.validationMsgEl.removeClass('-hide');
        }
      },

      onOptionChange: function(type, selection) {
        switch (type) {
          case 'country_codes':
            this.onCountryChange(selection);
            break;
          case 'widget_ids':
            this.onIndicatorsChange(selection);
            break;
          case 'dataSource':
            this.onDataSourceChange(selection);
            break;

          default:
            break;
        }
        this.checkDownloadAvailable();
      },

      onCountryChange: function(selection) {
        var jurisIndex = this.filterIndex.jurisdiction_ids;
        var aoiIndex = this.filterIndex.area_ids;
        var jurisView = this.filterViews[jurisIndex];
        var aoiView = this.filterViews[aoiIndex];
        if (jurisView && aoiView) {
          if (selection && selection.length === 1) {
            var jurisdictions = [];
            var areasOfInterest = [];
            Promise.all(
              selection.map(
                function(country) {
                  if (!this.jurisdictionsData[country]) {
                    return this.getCountryData(country);
                  }
                  return this.jurisdictionsData[country];
                }.bind(this)
              )
            ).then(function(data) {
              if (data && data.length) {
                data.forEach(function(d) {
                  jurisdictions = d.jurisdictions.concat(jurisdictions);
                  areasOfInterest = d.areasOfInterest.concat(areasOfInterest);
                });
              }
              function sortByName(a, b) {
                if (a.name < b.name) return -1;
                if (a.name > b.name) return 1;
                return 0;
              }

              var populateOptions = function(options, view, emptyMsg) {
                var sortedOptions = options;
                var hasOptions = options.length > 0;
                if (hasOptions) {
                  sortedOptions = options.sort(sortByName);
                }
                var msg = hasOptions > 0 ? '' : emptyMsg;
                view.renderOptions(sortedOptions, msg);
              };
              populateOptions(
                jurisdictions,
                jurisView,
                'There is no jurisdictions'
              );
              populateOptions(
                areasOfInterest,
                aoiView,
                'There is no area of interest'
              );
            });
          } else if (selection && selection.length > 1) {
            jurisView.renderOptions([], 'Please select only one country');
            jurisView.setAllMarked(false);
            aoiView.renderOptions([], 'Please select only one country');
            aoiView.setAllMarked(false);
          } else {
            jurisView.renderOptions([]);
            jurisView.setAllMarked(false);
            aoiView.renderOptions([]);
            aoiView.setAllMarked(false);
          }
          this.setClearVisibility(true);
        }
      },

      onClearClick: function() {
        this.filterViews.forEach(function(view) {
          view.setAllMarked(false);
        });
        this.setClearVisibility(false);
      },

      onDownloadClick: function(e) {
        e.preventDefault();
        var downloadUrl = '/api/data_portal_downloads'; // TODO: move this to .env
        var query = '';
        var firstParam = true;
        this.filterViews.forEach(function(view, index) {
          if (view.selection.length > 0) {
            if ((index === 0 && firstParam) || query === '') {
              firstParam = false;
              query += '?';
            } else {
              query += '&';
            }
            var value = view.selection.join(',');
            query += view.filter.id + '[]=' + value;
          }
        });

        this.switchViews.forEach(function(view, index) {
          if (view.value === '1') {
            if ((index === 0 && firstParam) || query === '') {
              firstParam = false;
              query += '?';
            } else {
              query += '&';
            }
            query += view.param + '=' + view.value;
          }
        });

        window.open(downloadUrl + query, '_blank');
      }
    });

    return DataDownloadIndexView;
  }
);


text:
class Network::UsersController < NetworkController
  # put /network/users/:id/uuid
  def update_uuid
    user = User.find_by(slug: params[:id])
    if user.nil?
      handle_http_404("Cannot find user with slug #{params[:id]}")
    else
      user.uuid = param_from_request(:uuid)
      user.email = param_from_request(:email) unless user.valid?
      head(user.save ? :no_content : :bad_request)
    end
  end

  private

  def set_handler
    @handler = NetworkManager::UserHandler.new
  end
end


text:
/* Alexander Heinecke, Sasikanth Avancha (Intel Corp.)
******************************************************************************/
#ifndef LIBXSMM_DNN_FUSEDGROUPNORM_H
#define LIBXSMM_DNN_FUSEDGROUPNORM_H

#include "libxsmm_dnn.h"
#include "libxsmm_dnn_tensor.h"

/** Opaque handles which represents LIBXSMM fusedgroupnorm */
LIBXSMM_EXTERN_C typedef struct LIBXSMM_RETARGETABLE libxsmm_dnn_fusedgroupnorm libxsmm_dnn_fusedgroupnorm;

LIBXSMM_API libxsmm_dnn_fusedgroupnorm* libxsmm_dnn_create_fusedgroupnorm(libxsmm_dnn_fusedgroupnorm_desc fusedgroupnorm_desc, libxsmm_dnn_err_t* status);
LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_destroy_fusedgroupnorm(const libxsmm_dnn_fusedgroupnorm* handle);

LIBXSMM_API libxsmm_dnn_tensor_datalayout* libxsmm_dnn_fusedgroupnorm_create_tensor_datalayout(const libxsmm_dnn_fusedgroupnorm* handle, const libxsmm_dnn_tensor_type type, libxsmm_dnn_err_t* status);

LIBXSMM_API size_t libxsmm_dnn_fusedgroupnorm_get_scratch_size(const libxsmm_dnn_fusedgroupnorm* handle, libxsmm_dnn_err_t* status);
LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_bind_scratch(libxsmm_dnn_fusedgroupnorm* handle, const void* scratch);
LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_release_scratch(libxsmm_dnn_fusedgroupnorm* handle);

LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_bind_tensor(libxsmm_dnn_fusedgroupnorm* handle, const libxsmm_dnn_tensor* tensor, const libxsmm_dnn_tensor_type type);
LIBXSMM_API libxsmm_dnn_tensor* libxsmm_dnn_fusedgroupnorm_get_tensor(libxsmm_dnn_fusedgroupnorm* handle, const libxsmm_dnn_tensor_type type, libxsmm_dnn_err_t* status);
LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_release_tensor(libxsmm_dnn_fusedgroupnorm* handle, const libxsmm_dnn_tensor_type type);

LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_execute_st(libxsmm_dnn_fusedgroupnorm* handle, libxsmm_dnn_compute_kind kind,
  /*unsigned*/int start_thread, /*unsigned*/int tid);
LIBXSMM_API libxsmm_dnn_err_t libxsmm_dnn_fusedgroupnorm_reduce_stats_st(libxsmm_dnn_fusedgroupnorm** handles, int num_handles, libxsmm_dnn_compute_kind kind,
  /*unsigned*/int start_thread, /*unsigned*/int tid);

#endif /*LIBXSMM_DNN_FUSEDGROUPNORM_H*/


text:
#include <config.h>

#include <assert.h>

#if HAVE_STDLIB_H
#include <stdlib.h>
#endif /* HAVE_STDLIB_H */

#if HAVE_STRING_H
#include <string.h>
#endif /* HAVE_STRING_H */

#include <ctype.h>

#include <freetds/odbc.h>
#include <freetds/convert.h>
#include <freetds/iconv.h>
#include <freetds/string.h>
#include <odbcss.h>

#define TDS_ISSPACE(c) isspace((unsigned char) (c))

/**
 * Handle conversions from TDS (N)CHAR to ODBC (W)CHAR
 */
static SQLLEN
odbc_convert_char(TDS_STMT * stmt, TDSCOLUMN * curcol, TDS_CHAR * src, TDS_UINT srclen, int desttype, TDS_CHAR * dest, SQLULEN destlen)
{
	const char *ib;
	char *ob;
	size_t il, ol, char_size;

	/* FIXME MARS not correct cause is the global tds but stmt->tds can be NULL on SQLGetData */
	TDSSOCKET *tds = stmt->dbc->tds_socket;

	TDSICONV *conv = curcol->char_conv;
	if (!conv)
		conv = tds->conn->char_convs[client2server_chardata];
	if (desttype == SQL_C_WCHAR) {
		const char *charset = odbc_get_wide_name(tds->conn);
		/* SQL_C_WCHAR, convert to wide encode */
		conv = tds_iconv_get(tds->conn, charset, conv->to.charset.name);
		if (!conv)
			conv = tds_iconv_get(tds->conn, charset, "ISO-8859-1");
#ifdef ENABLE_ODBC_WIDE
	} else {
		conv = tds_iconv_get(tds->conn, tds_dstr_cstr(&stmt->dbc->original_charset), conv->to.charset.name);
		if (!conv)
			conv = tds_iconv_get(tds->conn, tds_dstr_cstr(&stmt->dbc->original_charset), "ISO-8859-1");
		if (!conv)
			conv = tds_iconv_get(tds->conn, "ISO-8859-1", "ISO-8859-1");
#endif
	}

	ib = src;
	il = srclen;
	ob = dest;
	ol = 0;
	char_size = desttype == SQL_C_CHAR ? 1 : SIZEOF_SQLWCHAR;
	if (destlen >= char_size) {
		ol = destlen - char_size;
		memset(&conv->suppress, 0, sizeof(conv->suppress));
		conv->suppress.e2big = 1;
		/* TODO check return value */
		tds_iconv(tds, conv, to_client, &ib, &il, &ob, &ol);
		ol = ob - dest; /* bytes written */
		curcol->column_text_sqlgetdatapos += ib - src;
		/* terminate string */
		memset(ob, 0, char_size);
	}

	/* returned size have to take into account buffer left unconverted */
	if (il == 0 || (conv->from.charset.min_bytes_per_char == conv->from.charset.max_bytes_per_char
	    && conv->to.charset.min_bytes_per_char == conv->to.charset.max_bytes_per_char)) {
		ol += il * conv->from.charset.min_bytes_per_char / conv->to.charset.min_bytes_per_char;
	} else if ((conv->flags & TDS_ENCODING_MEMCPY) != 0) {
		ol += il;
	} else {
		/* TODO convert and discard ?? or return proper SQL_NO_TOTAL values ?? */
		return SQL_NO_TOTAL;
	}
	return ol;
}

/**
 * Handle conversions from TDS NCHAR to ISO8859-1 striping spaces (for fixed types)
 */
static int
odbc_tds_convert_wide_iso(TDSCOLUMN *curcol, TDS_CHAR *src, TDS_UINT srclen, TDS_CHAR *buf, TDS_UINT buf_len)
{
	TDS_CHAR *p;
	/*
	 * TODO check for endian
	 * This affect for instance Sybase under little endian system
	 */

	/* skip white spaces */
	while (srclen > 1 && src[1] == 0 && TDS_ISSPACE(src[0])) {
		srclen -= 2;
		src += 2;
	}

	/* convert */
	p = buf;
	while (buf_len > 1 && srclen > 1 && src[1] == 0) {
		*p++ = src[0];
		--buf_len;
		srclen -= 2;
		src += 2;
	}

	/* skip white spaces */
	while (srclen > 1 && src[1] == 0 && TDS_ISSPACE(src[0])) {
		srclen -= 2;
		src += 2;
	}

	/* still characters, wrong format */
	if (srclen)
		return -1;

	*p = 0;
	return p - buf;
}

/* The following structure is going to write in these structure not using them
 * but just knowing the ABI. Check these ABI. Mainly make sure the alignment
 * is still correct.
 */
TDS_COMPILE_CHECK(ss_time2, sizeof(SQL_SS_TIME2_STRUCT) == 12
	&& TDS_OFFSET(SQL_SS_TIME2_STRUCT, fraction) == 8);
TDS_COMPILE_CHECK(ss_timestampoffset, sizeof(SQL_SS_TIMESTAMPOFFSET_STRUCT) == 20
	&& TDS_OFFSET(SQL_SS_TIMESTAMPOFFSET_STRUCT, fraction) == 12);
TDS_COMPILE_CHECK(date_struct, sizeof(DATE_STRUCT) == 6
	&& TDS_OFFSET(DATE_STRUCT, year) == 0
	&& TDS_OFFSET(DATE_STRUCT, month) == 2
	&& TDS_OFFSET(DATE_STRUCT, day) == 4);
TDS_COMPILE_CHECK(timestamp_struct, sizeof(TIMESTAMP_STRUCT) == 16
	&& TDS_OFFSET(TIMESTAMP_STRUCT, year) == 0
	&& TDS_OFFSET(TIMESTAMP_STRUCT, month) == 2
	&& TDS_OFFSET(TIMESTAMP_STRUCT, day) == 4
	&& TDS_OFFSET(TIMESTAMP_STRUCT, hour) == 6
	&& TDS_OFFSET(TIMESTAMP_STRUCT, minute) == 8
	&& TDS_OFFSET(TIMESTAMP_STRUCT, second) == 10
	&& TDS_OFFSET(TIMESTAMP_STRUCT, fraction) == 12);

/**
 * Handle conversions from MSSQL 2008 DATE/TIME types to binary.
 * These types have a different binary representation in libTDS.
 */
static SQLLEN
odbc_convert_datetime_to_binary(TDS_STMT * stmt, TDSCOLUMN *curcol, int srctype, TDS_DATETIMEALL * dta, TDS_CHAR * dest, SQLULEN destlen)
{
	size_t len, cplen;
	TDS_USMALLINT buf[10];
	TDSDATEREC when;

	tds_datecrack(srctype, dta, &when);

	len = 0;
	if (srctype != SYBMSTIME && srctype != SYBTIME && srctype != SYB5BIGTIME) {
		buf[0] = when.year;
		buf[1] = when.month + 1;
		buf[2] = when.day;
		len = 3;
	}
	if (srctype != SYBMSDATE && srctype != SYBDATE) {
		buf[len++] = when.hour;
		buf[len++] = when.minute;
		buf[len++] = when.second;
		if ((len % 2) != 0)
			buf[len++] = 0;
		*((TDS_UINT*) (buf+len)) = when.decimicrosecond * 100u;
		len += 2;
	}
	if (srctype == SYBMSDATETIMEOFFSET) {
		/* TODO check for negative hour/minutes */
		buf[8] = dta->offset / 60;
		buf[9] = dta->offset % 60;
		len = 10;
	}
	len *= 2;

	/* just return length */
	if (destlen == 0)
		return len;

	cplen = (destlen > len) ? len : destlen;
	memcpy(dest, buf, cplen);
	if (curcol)
		curcol->column_text_sqlgetdatapos += cplen;
	return len;
}

static SQLLEN
odbc_convert_to_binary(TDS_STMT * stmt, TDSCOLUMN *curcol, int srctype, TDS_CHAR * src, TDS_UINT srclen, TDS_CHAR * dest, SQLULEN destlen)
{
	SQLLEN ret = srclen;

	/* special case for date/time */
	switch (srctype) {
	case SYBMSTIME:
	case SYBMSDATE:
	case SYBMSDATETIME2:
	case SYBMSDATETIMEOFFSET:
	case SYBDATE:
	case SYBTIME:
	case SYB5BIGTIME:
	case SYB5BIGDATETIME:
		return odbc_convert_datetime_to_binary(stmt, curcol, srctype, (TDS_DATETIMEALL *) src, dest, destlen);
	}

	/* if destlen == 0 we return only length */
	if (destlen > 0) {
		size_t cplen = (destlen > srclen) ? srclen : destlen;
		/* do not NUL terminate binary buffer */
		memcpy(dest, src, cplen);
		if (curcol)
			curcol->column_text_sqlgetdatapos += cplen;
	}
	return ret;
}

SQLLEN
odbc_tds2sql(TDS_STMT * stmt, TDSCOLUMN *curcol, int srctype, TDS_CHAR * src, TDS_UINT srclen, int desttype, TDS_CHAR * dest, SQLULEN destlen,
	     const struct _drecord *drec_ixd)
{
	TDS_INT nDestSybType;
	TDS_INT nRetVal = TDS_CONVERT_FAIL;
	TDSCONTEXT *context = stmt->dbc->env->tds_ctx;

	CONV_RESULT ores;

	SQLLEN ret = SQL_NULL_DATA;
	int i, cplen;
	int binary_conversion = 0;
	TDS_CHAR conv_buf[256];

	tdsdump_log(TDS_DBG_FUNC, "odbc_tds2sql: src is %d dest = %d\n", srctype, desttype);

	assert(desttype != SQL_C_DEFAULT);

	if (curcol) {
		if (is_blob_col(curcol)) {
			if (srctype == SYBLONGBINARY && (
			    curcol->column_usertype == USER_UNICHAR_TYPE ||
			    curcol->column_usertype == USER_UNIVARCHAR_TYPE))
				srctype = SYBTEXT;
			if (curcol->column_type == SYBVARIANT)
				srctype = ((TDSVARIANT *) src)->type;
			src = ((TDSBLOB *) src)->textvalue;
		}
		if (is_variable_type(curcol->column_type)) {
			src += curcol->column_text_sqlgetdatapos;
			srclen -= curcol->column_text_sqlgetdatapos;
		}
	}

	nDestSybType = odbc_c_to_server_type(desttype);
	if (!nDestSybType) {
		odbc_errs_add(&stmt->errs, "HY003", NULL);
		return SQL_NULL_DATA;
	}

	/* special case for binary type */
	if (desttype == SQL_C_BINARY) {
		tdsdump_log(TDS_DBG_FUNC, "odbc_tds2sql: outputting binary data destlen = %lu \n", (unsigned long) destlen);

		if (is_numeric_type(srctype)) {
			desttype = SQL_C_NUMERIC;
			nDestSybType = SYBNUMERIC;
			/* prevent buffer overflow */
			if (destlen < sizeof(SQL_NUMERIC_STRUCT)) {
				odbc_errs_add(&stmt->errs, "07006", NULL);
				return SQL_NULL_DATA;
			}
			ores.n.precision = ((TDS_NUMERIC *) src)->precision;
			ores.n.scale = ((TDS_NUMERIC *) src)->scale;
		} else {
			return odbc_convert_to_binary(stmt, curcol, srctype, src, srclen, dest, destlen);
		}
	} else if (is_numeric_type(nDestSybType)) {
		/* TODO use descriptor information (APD) ?? However APD can contain SQL_C_DEFAULT... */
		if (drec_ixd)
			ores.n.precision = drec_ixd->sql_desc_precision;
		else
			ores.n.precision = 38;
		ores.n.scale = 0;
	}

	if (is_char_type(srctype)) {
		if (desttype == SQL_C_CHAR || desttype == SQL_C_WCHAR)
			return odbc_convert_char(stmt, curcol, src, srclen, desttype, dest, destlen);
		if (is_unicode_type(srctype)) {
			/*
			 * convert to single and then process normally.
			 * Here we processed SQL_C_BINARY and SQL_C_*CHAR so only fixed types are left
			 */
			i = odbc_tds_convert_wide_iso(curcol, src, srclen, conv_buf, sizeof(conv_buf));
			if (i < 0)
				return SQL_NULL_DATA;
			src = conv_buf;
			srclen = i;
			srctype = SYBVARCHAR;
		}
	}

	if (desttype == SQL_C_WCHAR)
		destlen /= sizeof(SQLWCHAR);
	if (desttype == SQL_C_CHAR || desttype == SQL_C_WCHAR) {
		switch (srctype) {
		case SYBLONGBINARY:
		case SYBBINARY:
		case SYBVARBINARY:
		case SYBIMAGE:
		case XSYBBINARY:
		case XSYBVARBINARY:
			binary_conversion = 1;
			if (destlen && !(destlen % 2))
				--destlen;
		}

		nDestSybType = TDS_CONVERT_CHAR;
		ores.cc.len = destlen;
		ores.cc.c = dest;
	}

	if (desttype == SQL_C_CHAR || desttype == SQL_C_WCHAR) {
		char buf[48];
		TDSDATEREC when;
		int prec;
		const char *fmt = NULL;
		const TDS_DATETIMEALL *dta = (const TDS_DATETIMEALL *) src;

		switch (srctype) {
		case SYBMSDATETIMEOFFSET:
		case SYBMSDATETIME2:
			prec = dta->time_prec;
			goto datetime;
		case SYB5BIGDATETIME:
			prec = 6;
			goto datetime;
		case SYBDATETIME:
			prec = 3;
			goto datetime;
		case SYBDATETIME4:
			prec = 0;
		datetime:
			fmt = "%Y-%m-%d %H:%M:%S.%z";
			break;
		case SYBMSTIME:
			prec = dta->time_prec;
			goto time;
		case SYB5BIGTIME:
			prec = 6;
			goto time;
		case SYBTIME:
			prec = 3;
		time:
			fmt = "%H:%M:%S.%z";
			break;
		case SYBMSDATE:
		case SYBDATE:
			prec = 0;
			fmt = "%Y-%m-%d";
			break;
		}
		if (!fmt) goto normal_conversion;

		tds_datecrack(srctype, src, &when);
		tds_strftime(buf, sizeof(buf), fmt, &when, prec);

		if (srctype == SYBMSDATETIMEOFFSET) {
			char sign = '+';
			int off = dta->offset;
			if (off < 0) {
				sign = '-';
				off = -off;
			}
			sprintf(buf + strlen(buf), " %c%02d:%02d", sign, off / 60, off % 60);
		}

		nRetVal = strlen(buf);
		memcpy(dest, buf, destlen < nRetVal ? destlen : nRetVal);
	} else {
normal_conversion:
		nRetVal = tds_convert(context, srctype, src, srclen, nDestSybType, &ores);
	}
	if (nRetVal < 0) {
		odbc_convert_err_set(&stmt->errs, nRetVal);
		return SQL_NULL_DATA;
	}

	switch (desttype) {

	case SQL_C_CHAR:
		tdsdump_log(TDS_DBG_FUNC, "odbc_tds2sql: outputting character data destlen = %lu \n", (unsigned long) destlen);

		ret = nRetVal;
		/* TODO handle not terminated configuration */
		if (destlen > 0) {
			cplen = (destlen - 1) > nRetVal ? nRetVal : (destlen - 1);
			assert(cplen >= 0);
			/*
			 * odbc always terminate but do not overwrite
			 * destination buffer more than needed
			 */
			/* update datapos only for binary source (char already handled) */
			if (curcol && binary_conversion)
				curcol->column_text_sqlgetdatapos += cplen / 2;
			dest[cplen] = 0;
		} else {
			/* if destlen == 0 we return only length */
		}
		break;

	case SQL_C_WCHAR:
		tdsdump_log(TDS_DBG_FUNC, "odbc_tds2sql: outputting character data destlen = %lu \n", (unsigned long) destlen);

		ret = nRetVal * sizeof(SQLWCHAR);
		/* TODO handle not terminated configuration */
		if (destlen > 0) {
			SQLWCHAR *wp = (SQLWCHAR *) dest;
			SQLCHAR  *p  = (SQLCHAR *)  dest;

			cplen = (destlen - 1) > nRetVal ? nRetVal : (destlen - 1);
			assert(cplen >= 0);
			/*
			 * odbc always terminate but do not overwrite
			 * destination buffer more than needed
			 */
			/* update datapos only for binary source (char already handled) */
			if (curcol && binary_conversion)
				curcol->column_text_sqlgetdatapos += cplen / 2;
			/* convert in place and terminate */
			wp[cplen] = 0;
			while (cplen > 0) {
				--cplen;
				wp[cplen] = p[cplen];
			}
		} else {
			/* if destlen == 0 we return only length */
		}
		break;

	case SQL_C_TYPE_DATE:
	case SQL_C_DATE:
		{
			TDSDATEREC dr;
			DATE_STRUCT *dsp = (DATE_STRUCT *) dest;

			/*
			 * we've already converted the returned value to a SYBMSDATETIME2
			 * now decompose date into constituent parts...
			 */
			tds_datecrack(SYBMSDATETIME2, &(ores.dt), &dr);

			dsp->year = dr.year;
			dsp->month = dr.month + 1;
			dsp->day = dr.day;

			ret = sizeof(DATE_STRUCT);
		}
		break;

	case SQL_C_TYPE_TIME:
	case SQL_C_TIME:
		{
			TDSDATEREC dr;
			TIME_STRUCT *tsp = (TIME_STRUCT *) dest;

			/*
			 * we've already converted the returned value to a SYBMSDATETIME2
			 * now decompose date into constituent parts...
			 */
			tds_datecrack(SYBMSDATETIME2, &(ores.dt), &dr);

			tsp->hour = dr.hour;
			tsp->minute = dr.minute;
			tsp->second = dr.second;

			ret = sizeof(TIME_STRUCT);
		}
		break;

	case SQL_C_TYPE_TIMESTAMP:
	case SQL_C_TIMESTAMP:
		{
			TDSDATEREC dr;
			TIMESTAMP_STRUCT *tssp = (TIMESTAMP_STRUCT *) dest;

			/*
			 * we've already converted the returned value to a SYBMSDATETIME2
			 * now decompose date into constituent parts...
			 */
			tds_datecrack(SYBMSDATETIME2, &(ores.dt), &dr);

			tssp->year = dr.year;
			tssp->month = dr.month + 1;
			tssp->day = dr.day;
			tssp->hour = dr.hour;
			tssp->minute = dr.minute;
			tssp->second = dr.second;
			tssp->fraction = dr.decimicrosecond * 100u;

			ret = sizeof(TIMESTAMP_STRUCT);
		}
		break;

#ifdef SQL_C_SBIGINT
	case SQL_C_SBIGINT:
	case SQL_C_UBIGINT:
		*((TDS_INT8 *) dest) = ores.bi;
		ret = sizeof(TDS_INT8);
		break;
#endif

	case SQL_C_LONG:
	case SQL_C_SLONG:
	case SQL_C_ULONG:
		*((TDS_INT *) dest) = ores.i;
		ret = sizeof(TDS_INT);
		break;

	case SQL_C_SHORT:
	case SQL_C_SSHORT:
	case SQL_C_USHORT:
		*((TDS_SMALLINT *) dest) = ores.si;
		ret = sizeof(TDS_SMALLINT);
		break;

	case SQL_C_TINYINT:
	case SQL_C_STINYINT:
	case SQL_C_UTINYINT:
	case SQL_C_BIT:
		*((TDS_TINYINT *) dest) = ores.ti;
		ret = sizeof(TDS_TINYINT);
		break;

	case SQL_C_DOUBLE:
		*((TDS_FLOAT *) dest) = ores.f;
		ret = sizeof(TDS_FLOAT);
		break;

	case SQL_C_FLOAT:
		*((TDS_REAL *) dest) = ores.r;
		ret = sizeof(TDS_REAL);
		break;

	case SQL_C_NUMERIC:
		{
			/* ODBC numeric is quite different from TDS one ... */
			SQL_NUMERIC_STRUCT *num = (SQL_NUMERIC_STRUCT *) dest;
			num->precision = ores.n.precision;
			num->scale = ores.n.scale;
			num->sign = ores.n.array[0] ^ 1;
			/*
			 * TODO can be greater than SQL_MAX_NUMERIC_LEN ??
			 * seeing Sybase manual wire support bigger numeric but currently
			 * DBs so not support such precision
			 */
			i = ODBC_MIN(tds_numeric_bytes_per_prec[ores.n.precision] - 1, SQL_MAX_NUMERIC_LEN);
			memcpy(num->val, ores.n.array + 1, i);
			tds_swap_bytes(num->val, i);
			if (i < SQL_MAX_NUMERIC_LEN)
				memset(num->val + i, 0, SQL_MAX_NUMERIC_LEN - i);
			ret = sizeof(SQL_NUMERIC_STRUCT);
		}
		break;

#ifdef SQL_C_GUID
	case SQL_C_GUID:
		memcpy(dest, &(ores.u), sizeof(TDS_UNIQUE));
		ret = sizeof(TDS_UNIQUE);
		break;
#endif

	default:
		break;
	}

	return ret;
}


text:
import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { interval } from 'rxjs';
import { mergeMap, takeWhile } from 'rxjs/operators';

import { Route } from './route';
import { RouteMetrics } from './route-metrics';
import { RouteService } from './route.service';

@Component({
    selector: 'route-list',
    templateUrl: './routes.component.html',
    styleUrls: ['./routes.component.css']
})

export class RoutesComponent implements OnInit, OnDestroy {
    @Output() public readonly changeTitle = new EventEmitter();
    public title = 'Current Routes';
    public routes: Route[];
    public selectedRoute: Route;
    public routemetrics: RouteMetrics = new RouteMetrics();

    private alive: boolean;

    constructor(private readonly titleService: Title, private readonly routeService: RouteService) {
        this.titleService.setTitle('Message Routes');

        this.routeService.getRoutes()
            .subscribe(routes => {
                this.routes = routes;
            });
    }

    public ngOnInit(): void {
        this.changeTitle.emit('Camel Routes');
        // Update route metrics every second
        interval(1000)
            .pipe(
                takeWhile(() => this.alive),
                mergeMap(() => this.routeService.getMetrics())
            )
            .subscribe(routeMetrics => this.routemetrics = routeMetrics);
        this.alive = true;
    }

    public ngOnDestroy(): void {
        this.alive = false;
    }

    public trackRoutes(index: number, item: Route): string {
        return item.id;
    }

    public onSelect(route: Route): void {
        this.selectedRoute = route;
    }
}


text:
module Ovaltine
  class StoryboardTemplates

    VIEW_CONTROLLER_DEFINITION_TEMPLATE='+(id)instantiate{IDENTIFIER};'
    VIEW_CONTROLLER_IMPLEMENTATION_TEMPLATE='+(id)instantiate{CAPITALIZED_IDENTIFIER} { return [[self storyboard] instantiateViewControllerWithIdentifier:{IDENTIFIER}]; }'

    STATIC_IDENTIFIER_TEMPLATE='static NSString *const {IDENTIFIER_CONSTANT_NAME} = @"{IDENTIFIER}";'
    SEGUE_DEFINITION_TEMPLATE='+(NSString *){IDENTIFIER};'
    SEGUE_IMPLEMENTATION_TEMPLATE='+(NSString *){IDENTIFIER} { return {IDENTIFIER_CONSTANT_NAME}; }'

    REUSE_DEFINITION_TEMPLATE='+(NSString *){IDENTIFIER};'
    REUSE_IMPLEMENTATION_TEMPLATE='+(NSString *){IDENTIFIER} { return {IDENTIFIER_CONSTANT_NAME}; }'
    STORYBOARD_IMPLEMENTATION_TEMPLATE='[UIStoryboard storyboardWithName:{IDENTIFIER_CONSTANT_NAME} bundle:[NSBundle mainBundle]]'
    STORYBOARD_SECTION_TITLE_TEMPLATE="/** {TITLE} */"

    HEADER_TEMPLATE='''//
// {FILENAME}
// {COPYRIGHT}
// Generated by Ovaltine - http://github.com/kattrali/ovaltine

#import <Foundation/Foundation.h>

@interface {CLASS_NAME} : NSObject

+(UIStoryboard *)storyboard;

{REUSE_IDENTIFIERS}

{SEGUE_IDENTIFIERS}

{VIEW_CONTROLLERS}

@end
'''

    IMPLEMENTATION_TEMPLATE='''//
// {FILENAME}
// {COPYRIGHT}
// Generated by Ovaltine - http://github.com/kattrali/ovaltine

#import <UIKit/UIKit.h>
#import "{CLASS_NAME}.h"

static UIStoryboard *_storyboard = nil;
{STATIC_VARIABLES}

@implementation {CLASS_NAME}

+(UIStoryboard *)storyboard { return _storyboard ?: (_storyboard = {STORYBOARD}); }

{REUSE_IDENTIFIERS}

{SEGUE_IDENTIFIERS}

{VIEW_CONTROLLERS}

@end
'''
  end
end


text:
<?php
namespace DoctrineModule;

use Doctrine\Common\Annotations\Reader,
	//Doctrine\Common\Annotations\AnnotationReader,
	Doctrine\Common\Annotations\CachedReader,
	/*Doctrine\Common\Annotations\FileCacheReader,
	Doctrine\Common\Annotations\IndexedReader,
	Doctrine\Common\Annotations\SimpleAnnotationReader,
	Doctrine\ORM\Mapping\Driver\AnnotationDriver,*/
	Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;

class MappingDriverConfigurator
{
  private $cachedAnnotationReader;

  public function __construct(CachedReader $cachedAnnotationReader = null)
  {
      //echo 'construct'; exit;
      $this->cachedAnnotationReader = $cachedAnnotationReader;
  }

  public function configure(MappingDriverChain $driverChain)
  {
	 //echo 'configure'; exit;

	 if(isset($this->cachedAnnotationReader)){
		$this->usingCachedReader($driverChain);
	 }
  }

  private function usingCachedReader(MappingDriverChain $driverChain)
  {
	  // load superclass metadata mapping only, into driver chain
	  // also registers Gedmo annotations.NOTE: you can personalize it
	  \Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
	    $driverChain,
	    $this->cachedAnnotationReader
	  );

	  /*dump($driverChain);
	  exit(__METHOD__);*/

	  //echo 'registerMappingIntoDriverChainORM'; exit;
  }
}