text:
<?php
namespace Luracast\Restler;

use Luracast\Restler\Data\ApiMethodInfo;
use Luracast\Restler\Data\String;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Exception;

class Routes
{
    public static $prefixingParameterNames = array(
        'id'
    );
    protected static $routes = array();

    protected static $models = array();

    /**
     * Route the public and protected methods of an Api class
     *
     * @param string $className
     * @param string $resourcePath
     * @param int    $version
     *
     * @throws RestException
     */
    public static function addAPIClass($className, $resourcePath = '', $version = 1)
    {

        /*
         * Mapping Rules
         * =============
         *
         * - Optional parameters should not be mapped to URL
         * - If a required parameter is of primitive type
         *      - If one of the self::$prefixingParameterNames
         *              - Map it to URL
         *      - Else If request method is POST/PUT/PATCH
         *              - Map it to body
         *      - Else If request method is GET/DELETE
         *              - Map it to body
         * - If a required parameter is not primitive type
         *      - Do not include it in URL
         */
        $class = new ReflectionClass($className);
        try {
            $classMetadata = CommentParser::parse($class->getDocComment());
        } catch (Exception $e) {
            throw new RestException(500, "Error while parsing comments of `$className` class. " . $e->getMessage());
        }
        $classMetadata['scope'] = $scope = static::scope($class);
        $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC +
            ReflectionMethod::IS_PROTECTED);
        foreach ($methods as $method) {
            $methodUrl = strtolower($method->getName());
            //method name should not begin with _
            if ($methodUrl{0} == '_') {
                continue;
            }
            $doc = $method->getDocComment();

            try {
                $metadata = CommentParser::parse($doc) + $classMetadata;
            } catch (Exception $e) {
                throw new RestException(500, "Error while parsing comments of `{$className}::{$method->getName()}` method. " . $e->getMessage());
            }
            //@access should not be private
            if (isset($metadata['access'])
                && $metadata['access'] == 'private'
            ) {
                continue;
            }
            $arguments = array();
            $defaults = array();
            $params = $method->getParameters();
            $position = 0;
            $pathParams = array();
            $allowAmbiguity
                = (isset($metadata['smart-auto-routing'])
                    && $metadata['smart-auto-routing'] != 'true')
                || !Defaults::$smartAutoRouting;
            $metadata['resourcePath'] = $resourcePath;
            if (isset($classMetadata['description'])) {
                $metadata['classDescription'] = $classMetadata['description'];
            }
            if (isset($classMetadata['classLongDescription'])) {
                $metadata['classLongDescription']
                    = $classMetadata['longDescription'];
            }
            if (!isset($metadata['param'])) {
                $metadata['param'] = array();
            }
            if (isset($metadata['return']['type'])) {
                if ($qualified = Scope::resolve($metadata['return']['type'], $scope))
                    list($metadata['return']['type'], $metadata['return']['children']) =
                        static::getTypeAndModel(new ReflectionClass($qualified), $scope);
            } else {
                //assume return type is array
                $metadata['return']['type'] = 'array';
            }
            foreach ($params as $param) {
                $children = array();
                $type =
                    $param->isArray() ? 'array' : $param->getClass();
                $arguments[$param->getName()] = $position;
                $defaults[$position] = $param->isDefaultValueAvailable() ?
                    $param->getDefaultValue() : null;
                if (!isset($metadata['param'][$position])) {
                    $metadata['param'][$position] = array();
                }
                $m = & $metadata ['param'] [$position];
                $m ['name'] = $param->getName();
                if (empty($m['label']))
                    $m['label'] = static::label($m['name']);
                if (is_null($type) && isset($m['type'])) {
                    $type = $m['type'];
                }
                if ($m['name'] == 'email' && empty($m[CommentParser::$embeddedDataName]['type']) && $type == 'string')
                    $m[CommentParser::$embeddedDataName]['type'] = 'email';
                $m ['default'] = $defaults [$position];
                $m ['required'] = !$param->isOptional();
                $contentType = Util::nestedValue(
                    $m,
                    CommentParser::$embeddedDataName,
                    'type'
                );
                if ($contentType && $qualified = Scope::resolve($contentType, $scope)) {
                    list($m[CommentParser::$embeddedDataName]['type'], $children) = static::getTypeAndModel(
                        new ReflectionClass($qualified), $scope
                    );
                }
                if ($type instanceof ReflectionClass) {
                    list($type, $children) = static::getTypeAndModel($type, $scope);
                } elseif ($type && is_string($type) && $qualified = Scope::resolve($type, $scope)) {
                    list($type, $children)
                        = static::getTypeAndModel(new ReflectionClass($qualified), $scope);
                }
                if (isset($type)) {
                    $m['type'] = $type;
                }
                $m['children'] = $children;

                if ($m['name'] == Defaults::$fullRequestDataName) {
                    $from = 'body';
                    if (!isset($m['type'])) {
                        $type = $m['type'] = 'array';
                    }

                } elseif (isset($m[CommentParser::$embeddedDataName]['from'])) {
                    $from = $m[CommentParser::$embeddedDataName]['from'];
                } else {
                    if ((isset($type) && Util::isObjectOrArray($type))
                    ) {
                        $from = 'body';
                        if (!isset($type)) {
                            $type = $m['type'] = 'array';
                        }
                    } elseif ($m['required'] && in_array($m['name'], static::$prefixingParameterNames)) {
                        $from = 'path';
                    } else {
                        $from = 'body';
                    }
                }
                $m[CommentParser::$embeddedDataName]['from'] = $from;
                if (!isset($m['type'])) {
                    $type = $m['type'] = static::type($defaults[$position]);
                }

                if ($allowAmbiguity || $from == 'path') {
                    $pathParams [] = $position;
                }
                $position++;
            }
            $accessLevel = 0;
            if ($method->isProtected()) {
                $accessLevel = 3;
            } elseif (isset($metadata['access'])) {
                if ($metadata['access'] == 'protected') {
                    $accessLevel = 2;
                } elseif ($metadata['access'] == 'hybrid') {
                    $accessLevel = 1;
                }
            } elseif (isset($metadata['protected'])) {
                $accessLevel = 2;
            }
            /*
            echo " access level $accessLevel for $className::"
            .$method->getName().$method->isProtected().PHP_EOL;
            */

            // take note of the order
            $call = array(
                'url' => null,
                'className' => $className,
                'path' => rtrim($resourcePath, '/'),
                'methodName' => $method->getName(),
                'arguments' => $arguments,
                'defaults' => $defaults,
                'metadata' => $metadata,
                'accessLevel' => $accessLevel,
            );
            // if manual route
            if (preg_match_all(
                '/@url\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)'
                . '[ \t]*\/?(\S*)/s',
                $doc, $matches, PREG_SET_ORDER
            )
            ) {
                foreach ($matches as $match) {
                    $httpMethod = $match[1];
                    $url = rtrim($resourcePath . $match[2], '/');
                    //deep copy the call, as it may change for each @url
                    $copy = unserialize(serialize($call));
                    foreach ($copy['metadata']['param'] as $i => $p) {
                        $inPath =
                            strpos($url, '{' . $p['name'] . '}') ||
                            strpos($url, ':' . $p['name']);
                        if ($inPath) {
                            $copy['metadata']['param'][$i][CommentParser::$embeddedDataName]['from'] = 'path';
                        } elseif (
                            !isset($p[CommentParser::$embeddedDataName]['from']) ||
                            $p[CommentParser::$embeddedDataName]['from'] == 'path'
                        ) {
                            $copy['metadata']['param'][$i][CommentParser::$embeddedDataName]['from'] =
                                $httpMethod == 'GET' ||
                                $httpMethod == 'DELETE'
                                    ? 'query'
                                    : 'body';
                        }
                    }
                    $url = preg_replace_callback('/{[^}]+}|:[^\/]+/',
                        function ($matches) use ($call) {
                            $match = trim($matches[0], '{}:');
                            $index = $call['arguments'][$match];
                            return '{' .
                            Routes::typeChar(isset(
                            $call['metadata']['param'][$index]['type'])
                                ? $call['metadata']['param'][$index]['type']
                                : null)
                            . $index . '}';
                        }, $url);
                    static::addPath($url, $copy, $httpMethod, $version);
                }
                //if auto route enabled, do so
            } elseif (Defaults::$autoRoutingEnabled) {
                // no configuration found so use convention
                if (preg_match_all(
                    '/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)/i',
                    $methodUrl, $matches)
                ) {
                    $httpMethod = strtoupper($matches[0][0]);
                    $methodUrl = substr($methodUrl, strlen($httpMethod));
                } else {
                    $httpMethod = 'GET';
                }
                if ($methodUrl == 'index') {
                    $methodUrl = '';
                }
                $url = empty($methodUrl) ? rtrim($resourcePath, '/')
                    : $resourcePath . $methodUrl;
                $lastPathParam = array_keys($pathParams);
                $lastPathParam = end($lastPathParam);
                for ($position = 0; $position < count($params); $position++) {
                    $from = $metadata['param'][$position][CommentParser::$embeddedDataName]['from'];
                    if ($from == 'body' && ($httpMethod == 'GET' ||
                            $httpMethod == 'DELETE')
                    ) {
                        $call['metadata']['param'][$position][CommentParser::$embeddedDataName]['from']
                            = 'query';
                    }
                }
                if (empty($pathParams) || $allowAmbiguity) {
                    static::addPath($url, $call, $httpMethod, $version);
                }
                foreach ($pathParams as $position) {
                    if (!empty($url))
                        $url .= '/';
                    $url .= '{' .
                        static::typeChar(isset($call['metadata']['param'][$position]['type'])
                            ? $call['metadata']['param'][$position]['type']
                            : null)
                        . $position . '}';
                    if ($allowAmbiguity || $position == $lastPathParam) {
                        static::addPath($url, $call, $httpMethod, $version);
                    }
                }
            }
        }
    }

    /**
     * @access private
     */
    public static function typeChar($type = null)
    {
        if (!$type) {
            return 's';
        }
        switch ($type{0}) {
            case 'i':
            case 'f':
                return 'n';
        }
        return 's';
    }

    protected static function addPath($path, array $call,
                                      $httpMethod = 'GET', $version = 1)
    {
        $call['url'] = preg_replace_callback(
            "/\{\S(\d+)\}/",
            function ($matches) use ($call) {
                return '{' .
                $call['metadata']['param'][$matches[1]]['name'] . '}';
            },
            $path
        );
        //check for wildcard routes
        if (substr($path, -1, 1) == '*') {
            $path = rtrim($path, '/*');
            static::$routes["v$version"]['*'][$path][$httpMethod] = $call;
        } else {
            static::$routes["v$version"][$path][$httpMethod] = $call;
            //create an alias with index if the method name is index
            if ($call['methodName'] == 'index')
                static::$routes["v$version"][ltrim("$path/index", '/')][$httpMethod] = $call;
        }
    }

    /**
     * Find the api method for the given url and http method
     *
     * @param string $path       Requested url path
     * @param string $httpMethod GET|POST|PUT|PATCH|DELETE etc
     * @param int    $version    Api Version number
     * @param array  $data       Data collected from the request
     *
     * @throws RestException
     * @return ApiMethodInfo
     */
    public static function find($path, $httpMethod,
                                $version = 1, array $data = array())
    {
        $p = Util::nestedValue(static::$routes, "v$version");
        if (!$p) {
            throw new RestException(
                404,
                $version == 1 ? '' : "Version $version is not supported"
            );
        }
        $status = 404;
        $message = null;
        $methods = array();
        if (isset($p[$path][$httpMethod])) {
            //================== static routes ==========================
            return static::populate($p[$path][$httpMethod], $data);
        } elseif (isset($p['*'])) {
            //================== wildcard routes ========================
            uksort($p['*'], function ($a, $b) {
                return strlen($b) - strlen($a);
            });
            foreach ($p['*'] as $key => $value) {
                if (strpos($path, $key) === 0 && isset($value[$httpMethod])) {
                    //path found, convert rest of the path to parameters
                    $path = substr($path, strlen($key) + 1);
                    $call = ApiMethodInfo::__set_state($value[$httpMethod]);
                    $call->parameters = empty($path)
                        ? array()
                        : explode('/', $path);
                    return $call;
                }
            }
        }
        //================== dynamic routes =============================
        //add newline char if trailing slash is found
        if (substr($path, -1) == '/')
            $path .= PHP_EOL;
        //if double slash is found fill in newline char;
        $path = str_replace('//', '/' . PHP_EOL . '/', $path);
        ksort($p);
        foreach ($p as $key => $value) {
            if (!isset($value[$httpMethod])) {
                continue;
            }
            $regex = str_replace(array('{', '}'),
                array('(?P<', '>[^/]+)'), $key);
            if (preg_match_all(":^$regex$:i", $path, $matches, PREG_SET_ORDER)) {
                $matches = $matches[0];
                $found = true;
                foreach ($matches as $k => $v) {
                    if (is_numeric($k)) {
                        unset($matches[$k]);
                        continue;
                    }
                    $index = intval(substr($k, 1));
                    $details = $value[$httpMethod]['metadata']['param'][$index];
                    if ($k{0} == 's' || strpos($k, static::pathVarTypeOf($v)) === 0) {
                        //remove the newlines
                        $data[$details['name']] = trim($v, PHP_EOL);
                    } else {
                        $status = 400;
                        $message = 'invalid value specified for `'
                            . $details['name'] . '`';
                        $found = false;
                        break;
                    }
                }
                if ($found) {
                    return static::populate($value[$httpMethod], $data);
                }
            }
        }
        if ($status == 404) {
            //check if other methods are allowed
            if (isset($p[$path])) {
                $status = 405;
                $methods = array_keys($p[$path]);
            }
        }
        if ($status == 405) {
            header('Allow: ' . implode(', ', $methods));
        }
        throw new RestException($status, $message);
    }

    /**
     * Populates the parameter values
     *
     * @param array $call
     * @param       $data
     *
     * @return ApiMethodInfo
     *
     * @access private
     */
    protected static function populate(array $call, $data)
    {
        $call['parameters'] = $call['defaults'];
        $p = & $call['parameters'];
        foreach ($data as $key => $value) {
            if (isset($call['arguments'][$key])) {
                $p[$call['arguments'][$key]] = $value;
            }
        }
        if (Defaults::$smartParameterParsing && 'post' != (string)Util::$restler->requestFormat) {
            if (
                count($p) == 1 &&
                ($m = Util::nestedValue($call, 'metadata', 'param', 0)) &&
                !array_key_exists($m['name'], $data) &&
                array_key_exists(Defaults::$fullRequestDataName, $data) &&
                !is_null($d = $data[Defaults::$fullRequestDataName]) &&
                isset($m['type']) &&
                static::typeMatch($m['type'], $d)
            ) {
                $p[0] = $d;
            } else {
                $bodyParamCount = 0;
                $lastBodyParamIndex = -1;
                $lastM = null;
                foreach ($call['metadata']['param'] as $k => $m) {
                    if ($m[CommentParser::$embeddedDataName]['from'] == 'body') {
                        $bodyParamCount++;
                        $lastBodyParamIndex = $k;
                        $lastM = $m;
                    }
                }
                if (
                    $bodyParamCount == 1 &&
                    !array_key_exists($lastM['name'], $data) &&
                    array_key_exists(Defaults::$fullRequestDataName, $data) &&
                    !is_null($d = $data[Defaults::$fullRequestDataName])
                ) {
                    $p[$lastBodyParamIndex] = $d;
                }
            }
        }
        $r = ApiMethodInfo::__set_state($call);
        $modifier = "_modify_{$r->methodName}_api";
        if (method_exists($r->className, $modifier)) {
            $stage = end(Scope::get('Restler')->getEvents());
            if (empty($stage))
                $stage = 'setup';
            $r = Scope::get($r->className)->$modifier($r, $stage) ? : $r;
        }
        return $r;
    }

    /**
     * @access private
     */
    protected static function pathVarTypeOf($var)
    {
        if (is_numeric($var)) {
            return 'n';
        }
        if ($var === 'true' || $var === 'false') {
            return 'b';
        }
        return 's';
    }

    protected static function typeMatch($type, $var)
    {
        switch ($type) {
            case 'boolean':
            case 'bool':
                return is_bool($var);
            case 'array':
            case 'object':
                return is_array($var);
            case 'string':
            case 'int':
            case 'integer':
            case 'float':
            case 'number':
                return is_scalar($var);
        }
        return true;
    }

    /**
     * Get the type and associated model
     *
     * @param ReflectionClass $class
     * @param array           $scope
     *
     * @throws RestException
     * @throws \Exception
     * @return array
     *
     * @access protected
     */
    protected static function getTypeAndModel(ReflectionClass $class, array $scope)
    {
        $className = $class->getName();
        if (isset(static::$models[$className])) {
            return static::$models[$className];
        }
        $children = array();
        try {
            $props = $class->getProperties(ReflectionProperty::IS_PUBLIC);
            foreach ($props as $prop) {
                $name = $prop->getName();
                $child = array('name' => $name);
                if ($c = $prop->getDocComment()) {
                    $child += Util::nestedValue(CommentParser::parse($c), 'var');
                } else {
                    $o = $class->newInstance();
                    $p = $prop->getValue($o);
                    if (is_object($p)) {
                        $child['type'] = get_class($p);
                    } elseif (is_array($p)) {
                        $child['type'] = 'array';
                        if (count($p)) {
                            $pc = reset($p);
                            if (is_object($pc)) {
                                $child['contentType'] = get_class($pc);
                            }
                        }
                    }
                }
                $child += array(
                    'type' => $child['name'] == 'email' ? 'email' : 'string',
                    'label' => static::label($child['name'])
                );
                isset($child[CommentParser::$embeddedDataName])
                    ? $child[CommentParser::$embeddedDataName] += array('required' => true)
                    : $child[CommentParser::$embeddedDataName]['required'] = true;
                if ($qualified = Scope::resolve($child['type'], $scope)) {
                    list($child['type'], $child['children'])
                        = static::getTypeAndModel(new ReflectionClass($qualified), $scope);
                } elseif (
                    ($contentType = Util::nestedValue($child, CommentParser::$embeddedDataName, 'type')) &&
                    ($qualified = Scope::resolve($contentType, $scope))
                ) {
                    list($child['contentType'], $child['children'])
                        = static::getTypeAndModel(new ReflectionClass($qualified), $scope);
                }
                $children[$name] = $child;
            }
        } catch (Exception $e) {
            if (String::endsWith($e->getFile(), 'CommentParser.php')) {
                throw new RestException(500, "Error while parsing comments of `$className` class. " . $e->getMessage());
            }
            throw $e;
        }
        static::$models[$className] = array($className, $children);
        return static::$models[$className];
    }

    /**
     * Import previously created routes from cache
     *
     * @param array $routes
     */
    public static function fromArray(array $routes)
    {
        static::$routes = $routes;
    }

    /**
     * Export current routes for cache
     *
     * @return array
     */
    public static function toArray()
    {
        return static::$routes;
    }

    public static function type($var)
    {
        if (is_object($var)) return get_class($var);
        if (is_array($var)) return 'array';
        if (is_bool($var)) return 'boolean';
        if (is_numeric($var)) return is_float($var) ? 'float' : 'int';
        return 'string';
    }

    /**
     * Create a label from name of the parameter or property
     *
     * Convert `camelCase` style names into proper `Title Case` names
     *
     * @param string $name
     *
     * @return string
     */
    public static function label($name)
    {
        return ucfirst(preg_replace(array('/(?<=[^A-Z])([A-Z])/', '/(?<=[^0-9])([0-9])/'), ' $0', $name));
    }

    public static function scope(ReflectionClass $class)
    {
        $namespace = $class->getNamespaceName();
        $imports = array(
            '*' => empty($namespace) ? '' : $namespace . '\\'
        );
        $file = file_get_contents($class->getFileName());
        $tokens = token_get_all($file);
        $namespace = '';
        $alias = '';
        $reading = false;
        $last = 0;
        foreach ($tokens as $token) {
            if (is_string($token)) {
                if ($reading && ',' == $token) {
                    //===== STOP =====//
                    $reading = false;
                    if (!empty($namespace))
                        $imports[$alias] = trim($namespace, '\\');
                    //===== START =====//
                    $reading = true;
                    $namespace = '';
                    $alias = '';
                } else {
                    //===== STOP =====//
                    $reading = false;
                    if (!empty($namespace))
                        $imports[$alias] = trim($namespace, '\\');
                }
            } elseif (T_USE == $token[0]) {
                //===== START =====//
                $reading = true;
                $namespace = '';
                $alias = '';
            } elseif ($reading) {
                //echo token_name($token[0]) . ' ' . $token[1] . PHP_EOL;
                switch ($token[0]) {
                    case T_WHITESPACE:
                        continue 2;
                    case T_STRING:
                        $alias = $token[1];
                        if (T_AS == $last) {
                            break;
                        }
                    //don't break;
                    case T_NS_SEPARATOR:
                        $namespace .= $token[1];
                        break;
                }
                $last = $token[0];
            }
        }
        return $imports;
    }
}


text:
using EFCoreExtend.Evaluators;
using EFCoreExtend.Evaluators.Default;
using System;
using System.Linq;

namespace EFCoreExtend.EFCache.BaseCache.Default
{
    public abstract class QueryCacheBase : IQueryCache
    {
        public TRtn Cache<TRtn>(string cacheType, string cacheKey, Func<TRtn> toDBGet,
            IQueryCacheExpiryPolicy expiryPolicy, Type rtnType = null)
        {
            cacheKey.CheckStringIsNullOrEmpty(nameof(cacheKey));
            cacheType.CheckStringIsNullOrEmpty(nameof(cacheType));
            //toDBGet.CheckNull(nameof(toDBGet));

            TRtn rtn;
            bool bRtn;

            if (expiryPolicy == null)
            {
                bRtn = TryGetCache(cacheType, cacheKey, out rtn, rtnType);
            }
            else
            {
                var expiryTime = expiryPolicy.GetExpiryTime();
                if (expiryPolicy.IsUpdateEach && expiryTime.HasValue)
                {
                    bRtn = TryGetCacheAndUpdateCacheTime(cacheType, cacheKey, expiryTime.Value, out rtn, rtnType);
                }
                else
                {
                    bRtn = TryGetCache(cacheType, cacheKey, out rtn, rtnType);
                }
            }

            if (!bRtn)
            {
                rtn = toDBGet();
                if (expiryPolicy == null)
                {
                    SetCache(cacheType, cacheKey, rtn, rtnType);
                }
                else
                {
                    var expiryTime = expiryPolicy.GetExpiryTime();
                    if (expiryTime.HasValue)
                    {
                        SetCache(cacheType, cacheKey, rtn, expiryTime.Value, rtnType);
                    }
                    else
                    {
                        SetCache(cacheType, cacheKey, rtn, rtnType);
                    }
                }
            }

            return rtn;
        }

        #region abstract
        protected abstract bool TryGetCache<TRtn>(string cacheType, string cacheKey, out TRtn rtn, Type rtnType = null);
        protected abstract bool TryGetCacheAndUpdateCacheTime<TRtn>(string cacheType, string cacheKey, DateTime expiry, out TRtn rtn, Type rtnType = null);

        protected abstract void SetCache<TM>(string cacheType, string cacheKey, TM cacheModel, Type rtnType = null);
        protected abstract void SetCache<TM>(string cacheType, string cacheKey, TM cacheModel, DateTime expiry, Type rtnType = null);

        public abstract void Remove(string cacheType, string cacheKey);

        public abstract void RemoveRange(string cacheType);

        public abstract void Clear();

        public abstract void Dispose();
        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "tensorflow/compiler/xla/service/while_loop_invariant_code_motion.h"

#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_verified_test_base.h"
#include "tensorflow/core/lib/core/status_test_util.h"

namespace xla {
namespace {

namespace op = xla::testing::opcode_matchers;

class WhileLoopInvariantCodeMotionTest : public HloVerifiedTestBase {
 public:
  // Makes a computation which has one parameter, of the given shape, and always
  // returns PRED[]{true}.  This is useful as a dummy loop condition.
  HloComputation* MakeAlwaysTrueComputation(const Shape& param_shape,
                                            HloModule* module);
};

static void FindOnlyWhileInstruction(HloComputation* computation,
                                     HloInstruction** while_instruction) {
  *while_instruction = nullptr;
  for (auto* instr : computation->instructions()) {
    if (instr->opcode() == HloOpcode::kWhile) {
      ASSERT_EQ(*while_instruction, nullptr);
      *while_instruction = instr;
    }
  }

  ASSERT_NE(*while_instruction, nullptr);
}

HloComputation* WhileLoopInvariantCodeMotionTest::MakeAlwaysTrueComputation(
    const Shape& param_shape, HloModule* module) {
  HloComputation::Builder builder(TestName() + ".always_true");
  builder.AddInstruction(
      HloInstruction::CreateParameter(0, param_shape, "param"));
  builder.AddInstruction(
      HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(true)));
  return module->AddEmbeddedComputation(builder.Build());
}

TEST_F(WhileLoopInvariantCodeMotionTest, HoistOneInvariantOperation) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, scalar_s32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* add_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kAdd, gte_0, gte_1));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, add_result}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  HloComputation* entry_computation =
      module().AddEntryComputation(builder.Build());
  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_TRUE(simplified_loop);

  HloInstruction* transformed_while;
  FindOnlyWhileInstruction(entry_computation, &transformed_while);

  EXPECT_THAT(entry_computation->instructions(), Contains(op::Add()));
  EXPECT_THAT(transformed_while->while_body()->instructions(),
              Each(Not(op::Add())));
}

TEST_F(WhileLoopInvariantCodeMotionTest, HoistInvariantOperationTree) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, scalar_s32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* gte_2_loop_variant = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 2));

    HloInstruction* add_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kAdd, gte_0, gte_1));
    HloInstruction* mul_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kMultiply, add_result, gte_1));
    HloInstruction* negate_result =
        builder.AddInstruction(HloInstruction::CreateUnary(
            scalar_s32, HloOpcode::kNegate, mul_result));
    HloInstruction* constant = builder.AddInstruction(
        HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(4)));
    HloInstruction* sub_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kSubtract, negate_result, constant));
    HloInstruction* divide_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kDivide, sub_result, gte_2_loop_variant));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, divide_result}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  HloComputation* entry_computation =
      module().AddEntryComputation(builder.Build());
  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_TRUE(simplified_loop);

  HloInstruction* transformed_while;
  FindOnlyWhileInstruction(entry_computation, &transformed_while);

  EXPECT_THAT(entry_computation->instructions(),
              AllOf(Contains(op::Add()), Contains(op::Multiply()),
                    Contains(op::Negate()), Contains(op::Subtract()),
                    Contains(op::Constant()),

                    // The division had a loop varying operand so that better
                    // not be hoisted.
                    Not(Contains(op::Divide()))));

  EXPECT_THAT(transformed_while->while_body()->instructions(),
              Each(Not(AnyOf(op::Add(), op::Multiply(), op::Negate(),
                             op::Subtract(), op::Constant()))));

  EXPECT_THAT(transformed_while->while_body()->instructions(),
              Contains(op::Divide()));
}

TEST_F(WhileLoopInvariantCodeMotionTest,
       DontHoistTriviallyLoopVaryingComputation) {
  // Basic negative test: the add expression is not loop invariant.
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape = ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* add_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kAdd, gte_0, gte_1));
    builder.AddInstruction(HloInstruction::CreateTuple({gte_0, add_result}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  auto* while_inst = builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));

  module().AddEntryComputation(builder.Build());

  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);

  EXPECT_THAT(while_inst->while_body()->instructions(), Contains(op::Add()));
}

TEST_F(WhileLoopInvariantCodeMotionTest,
       DontHoistLoopVaryingComputationWithAlternatingTuples) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, scalar_s32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* add_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kAdd, gte_0, gte_1));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_1, gte_0, add_result}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  auto* while_inst = builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));

  module().AddEntryComputation(builder.Build());
  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);

  EXPECT_THAT(while_inst->while_body()->instructions(), Contains(op::Add()));
}

TEST_F(WhileLoopInvariantCodeMotionTest, DontHoistInstructionWithSideEffects) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  auto token_shape = ShapeUtil::MakeTokenShape();
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, token_shape});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* in_token = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(token_shape, param, 2));
    HloInstruction* out_token = builder.AddInstruction(
        HloInstruction::CreateOutfeed(scalar_s32, gte_0, in_token, ""));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, out_token}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* scalar_param = builder.AddInstruction(
      HloInstruction::CreateParameter(0, scalar_s32, "param"));
  auto* token = builder.AddInstruction(HloInstruction::CreateAfterAll({}));
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateTuple({scalar_param, scalar_param, token}));
  auto* while_inst = builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  builder.AddInstruction(
      HloInstruction::CreateGetTupleElement(scalar_s32, while_inst, 0));
  module().AddEntryComputation(builder.Build());

  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  ASSERT_FALSE(simplified_loop);

  EXPECT_THAT(while_inst->while_body()->instructions(),
              Contains(op::Outfeed()));
}

TEST_F(WhileLoopInvariantCodeMotionTest, DontHoistBitcastAlone) {
  // The bitcast's user, an outfeed, can't be hoisted, so don't hoist the
  // bitcast either.
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  auto scalar_f32 = ShapeUtil::MakeShape(F32, {});
  auto token_shape = ShapeUtil::MakeTokenShape();
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, token_shape});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* in_token = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(token_shape, param, 2));
    HloInstruction* bitcast_inst = builder.AddInstruction(
        HloInstruction::CreateUnary(scalar_f32, HloOpcode::kBitcast, gte_0));
    HloInstruction* out_token = builder.AddInstruction(
        HloInstruction::CreateOutfeed(scalar_f32, bitcast_inst, in_token, ""));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, out_token}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* scalar_param = builder.AddInstruction(
      HloInstruction::CreateParameter(0, scalar_s32, "param"));
  auto* token = builder.AddInstruction(HloInstruction::CreateAfterAll({}));
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateTuple({scalar_param, scalar_param, token}));
  auto* while_inst = builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  builder.AddInstruction(
      HloInstruction::CreateGetTupleElement(scalar_s32, while_inst, 0));

  module().AddEntryComputation(builder.Build());

  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);

  EXPECT_THAT(while_inst->while_body()->instructions(),
              Contains(op::Outfeed()));
  EXPECT_THAT(while_inst->while_body()->instructions(),
              Contains(op::Bitcast()));
}

TEST_F(WhileLoopInvariantCodeMotionTest, HoistBitcastIfNeeded) {
  // The bitcast's user can be hoisted, so hoist the bitcast too.
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  auto scalar_f32 = ShapeUtil::MakeShape(F32, {});
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_f32, scalar_f32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_f32, param, 1));
    HloInstruction* bitcast_inst = builder.AddInstruction(
        HloInstruction::CreateUnary(scalar_f32, HloOpcode::kBitcast, gte_0));
    HloInstruction* add_inst =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_f32, HloOpcode::kAdd, bitcast_inst, gte_1));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, add_inst}));

    return module().AddEmbeddedComputation(builder.Build());
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));

  HloComputation* entry_computation =
      module().AddEntryComputation(builder.Build());

  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_TRUE(simplified_loop);

  HloInstruction* transformed_while;
  FindOnlyWhileInstruction(entry_computation, &transformed_while);

  EXPECT_THAT(transformed_while->while_body()->instructions(),
              Each(Not(op::Add())));
  EXPECT_THAT(transformed_while->while_body()->instructions(),
              Each(Not(op::Bitcast())));
  EXPECT_THAT(entry_computation->instructions(), Contains(op::Add()));
  EXPECT_THAT(entry_computation->instructions(), Contains(op::Bitcast()));
}

TEST_F(WhileLoopInvariantCodeMotionTest, DontHoistControlDependencies) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape =
      ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32, scalar_s32});

  HloComputation* while_body;
  {
    HloComputation::Builder builder(TestName() + ".while_body");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloInstruction* gte_0 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 0));
    HloInstruction* gte_1 = builder.AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    HloInstruction* add_result =
        builder.AddInstruction(HloInstruction::CreateBinary(
            scalar_s32, HloOpcode::kAdd, gte_0, gte_1));
    TF_ASSERT_OK(param->AddControlDependencyTo(add_result));
    builder.AddInstruction(
        HloInstruction::CreateTuple({gte_0, gte_1, add_result}));

    while_body = module().AddEmbeddedComputation(builder.Build());
  }

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  module().AddEntryComputation(builder.Build());
  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);
}

TEST_F(WhileLoopInvariantCodeMotionTest, BodyHasNonTupleRoot) {
  auto scalar_s32 = ShapeUtil::MakeShape(S32, {});
  Shape while_shape = ShapeUtil::MakeTupleShape({scalar_s32, scalar_s32});

  HloComputation* while_body = [&]() {
    HloComputation::Builder builder(TestName() + ".passthrough");
    HloInstruction* param = builder.AddInstruction(
        HloInstruction::CreateParameter(0, while_shape, "param"));
    HloComputation* result = module().AddEmbeddedComputation(builder.Build());

    result->AddInstruction(
        HloInstruction::CreateGetTupleElement(scalar_s32, param, 1));
    return result;
  }();

  HloComputation::Builder builder(TestName());
  auto* init_value = builder.AddInstruction(
      HloInstruction::CreateParameter(0, while_shape, "init_value"));
  builder.AddInstruction(HloInstruction::CreateWhile(
      while_shape, MakeAlwaysTrueComputation(while_shape, &module()),
      while_body, init_value));
  module().AddEntryComputation(builder.Build());
  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);
}

const char* const kConstantHoistingTestCase = R"(
HloModule ModuleWithWhile

body {
  p_body = (f32[2]{0}) parameter(0)
  p_body.1 = f32[2]{0} get-tuple-element(p_body), index=0
  const = f32[2]{0} constant({3, 4})
  add.0 = f32[2]{0} add(p_body.1, const)
  ROOT root = (f32[2]{0}) tuple(add.0)
}

condition {
  p_cond = (f32[2]{0}) parameter(0)
  ROOT result = pred[] constant(true)
}

ENTRY entry {
  const_0 = f32[2]{0} constant({1, 2})
  while_init = (f32[2]{0}) tuple(const_0)
  ROOT while = (f32[2]{0}) while(while_init), condition=condition, body=body
}
)";

TEST_F(WhileLoopInvariantCodeMotionTest, HoistsConstantWhenAsked) {
  ParseAndVerifyModule(kConstantHoistingTestCase);

  TF_ASSERT_OK_AND_ASSIGN(
      bool simplified_loop,
      WhileLoopInvariantCodeMotion{/*hoist_constants=*/true}.Run(&module()));
  EXPECT_TRUE(simplified_loop);

  HloComputation* while_body = module().GetComputationWithName("wide.body");
  ASSERT_NE(while_body, nullptr);

  // We expect the while body to be the equivalent of:
  //
  //  wide.body {
  //    wide_param.1 = (f32[2]{0}, f32[2]{0}) parameter(0)
  //    get-tuple-element.1 = f32[2]{0} get-tuple-element(wide_param.1), index=0
  //    tuple.1 = (f32[2]{0}) tuple(get-tuple-element.1)
  //    get-tuple-element.4 = f32[2]{0} get-tuple-element(tuple.1), index=0
  //    get-tuple-element.7 = f32[2]{0} get-tuple-element(wide_param.1), index=1
  //    add.1 = f32[2]{0} add(get-tuple-element.4, get-tuple-element.7)
  //    tuple.3 = (f32[2]{0}) tuple(add.1)
  //    get-tuple-element.8 = f32[2]{0} get-tuple-element(tuple.3), index=0
  //    get-tuple-element.9 = f32[2]{0} get-tuple-element(wide_param.1), index=1
  //    ROOT tuple.4 = (f32[2]{0}, f32[2]{0}) tuple(get-tuple-element.8,
  //                                                get-tuple-element.9)
  //  }

  auto wide_param_1 = op::Parameter(0);
  auto get_tuple_element_1 = op::GetTupleElement(wide_param_1, 0);
  auto tuple_1 = op::Tuple(get_tuple_element_1);
  auto get_tuple_element_4 = op::GetTupleElement(tuple_1, 0);
  auto get_tuple_element_7 = op::GetTupleElement(wide_param_1, 1);
  auto add_1 = op::Add(get_tuple_element_4, get_tuple_element_7);
  auto tuple_3 = op::Tuple(add_1);
  auto get_tuple_element_8 = op::GetTupleElement(tuple_3, 0);
  auto get_tuple_element_9 = op::GetTupleElement(wide_param_1, 1);
  auto tuple_4 = op::Tuple(get_tuple_element_8, get_tuple_element_9);

  EXPECT_THAT(while_body->root_instruction(), tuple_4);
}

TEST_F(WhileLoopInvariantCodeMotionTest, DoesNotHoistConstantByDefault) {
  ParseAndVerifyModule(kConstantHoistingTestCase);

  TF_ASSERT_OK_AND_ASSIGN(bool simplified_loop,
                          WhileLoopInvariantCodeMotion{}.Run(&module()));
  EXPECT_FALSE(simplified_loop);
}

}  // namespace
}  // namespace xla


text:
using System;
using System.Diagnostics.CodeAnalysis;
using EasyApi.Http;
using EasyApi.Metadata.Providers;
using EasyApi.Pipeline;
using EasyApi.Utils;

namespace EasyApi.Client
{
	public class ServiceClientFactory : IServiceClientFactory
	{
		private readonly IServiceMetadataProvider _metadataProvider;

		public ServiceClientFactory(IServiceMetadataProvider metadataProvider)
		{
			Argument.IsNotNull(metadataProvider, nameof(metadataProvider));

			_metadataProvider = metadataProvider;
		}

		[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "HttpClient is disposed by ServiceClient.")]
		public IServiceClient CreateClient(Type serviceType, ServiceClientSettings settings)
		{
			Argument.IsNotNull(serviceType, nameof(serviceType));
			Argument.IsNotNull(settings, nameof(settings));

			return new ServiceClient(
				_metadataProvider.GetMetadata(serviceType),
				settings.BaseAddress,
				new HttpClient(settings.RequestTimeout),
				new ProcessingPipeline(),
				settings.Properties
			);
		}
	}
}


text:
package com.twitter.zipkin.storage

import com.twitter.zipkin.query.{QueryService, adjusters}
import org.specs.Specification
import org.specs.mock.{ClassMocker, JMocker}
import com.twitter.util.{Await, Future}

class TraceIdsToDurationSpec extends Specification with JMocker with ClassMocker {

  "TraceIdsToDuration" should {

    "fetch durations in batches" in {
      val index = mock[Index]
      val duration1 = TraceIdDuration(1L, 100L, 500L)
      val duration2 = TraceIdDuration(2L, 200L, 600L)
      val duration3 = TraceIdDuration(3L, 300L, 700L)

      expect {
        1.of(index).getTracesDuration(List(1L, 2L)) willReturn Future(List(duration1, duration2))
        1.of(index).getTracesDuration(List(3L)) willReturn Future(List(duration3))
      }

      val td = new TraceIdsToDuration(index, 2)
      td.append(1)
      td.append(2)
      td.append(3)

      val durations = Await.result(td.getDurations())
      durations(0) mustEqual duration1
      durations(1) mustEqual duration2
      durations(2) mustEqual duration3
    }
  }
}


text: alias runpg="dockup && $DOTFILES_ROOT/postgresql/start.sh && dockssh -N -L 5432:localhost:5432"


text:
@font-face {
  font-family: 'icomoon';
  src:  url('fonts/icomoon.eot?9ks2dq');
  src:  url('fonts/icomoon.eot?9ks2dq#iefix') format('embedded-opentype'),
    url('fonts/icomoon.ttf?9ks2dq') format('truetype'),
    url('fonts/icomoon.woff?9ks2dq') format('woff'),
    url('fonts/icomoon.svg?9ks2dq#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
  /* use !important to prevent issues with browser extensions that change fonts */
  font-family: 'icomoon' !important;
  speak: none;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;

  /* Better Font Rendering =========== */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-circled-play2:before {
  content: "\e903";
}
.icon-circled-play:before {
  content: "\e904";
}
.icon-delete2:before {
  content: "\e902";
}
.icon-menu:before {
  content: "\e901";
}
.icon-delete:before {
  content: "\e900";
}


text:
"""
helper functions to work with OATH HOTP (RFC4226) OTP's and YubiHSM
"""

# Copyright (c) 2011 Yubico AB
# See the file COPYING for licence statement.

import struct
import pyhsm.exception
import pyhsm.aead_cmd

__all__ = [
    # constants
    # functions
    'search_for_oath_code',
    # classes
 ]

def search_for_oath_code(hsm, key_handle, nonce, aead, counter, user_code, look_ahead=1):
    """
    Try to validate an OATH HOTP OTP generated by a token whose secret key is
    available to the YubiHSM through the AEAD.

    The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.

    Returns next counter value on successful auth, and None otherwise.
    """
    key_handle = pyhsm.util.input_validate_key_handle(key_handle)
    nonce = pyhsm.util.input_validate_nonce(nonce, pad = False)
    aead = pyhsm.util.input_validate_aead(aead)
    counter = pyhsm.util.input_validate_int(counter, 'counter')
    user_code = pyhsm.util.input_validate_int(user_code, 'user_code')
    hsm.load_temp_key(nonce, key_handle, aead)
    # User might have produced codes never sent to us, so we support trying look_ahead
    # codes to see if we find the user's current code.
    for j in xrange(look_ahead):
        this_counter = counter + j
        secret = struct.pack("> Q", this_counter)
        hmac_result = hsm.hmac_sha1(pyhsm.defines.YSM_TEMP_KEY_HANDLE, secret).get_hash()
        this_code = truncate(hmac_result)
        if this_code == user_code:
            return this_counter + 1
    return None

def truncate(hmac_result, length=6):
    """ Perform the truncating. """
    assert(len(hmac_result) == 20)
    offset   =  ord(hmac_result[19]) & 0xf
    bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
        | (ord(hmac_result[offset+1]) & 0xff) << 16 \
        | (ord(hmac_result[offset+2]) & 0xff) <<  8 \
        | (ord(hmac_result[offset+3]) & 0xff)
    return bin_code % (10 ** length)


text:
package whois

import (
	"fmt"
)

type deAdapter struct {
	defaultAdapter
}

func (a *deAdapter) Prepare(req *Request) error {
	a.defaultAdapter.Prepare(req)
	req.Body = []byte(fmt.Sprintf("-T dn,ace %s\r\n", req.Query)) // http://www.denic.de/en/domains/whois-service.html
	return nil
}

func init() {
	BindAdapter(
		&deAdapter{},
		"whois.denic.de",
	)
}


text:
{%load i18n%}

        {%trans "Avatar"%} {%trans "Management"%}

{%trans "Avatars"%}

{%trans "Luggage"%}

                <input type='checkbox' id='cb-all' />
                {%trans "Name"%}
                {%trans "UUID"%}
                {%trans "Options"%}

            {% for profile in profiles %}

            <input type='checkbox' id='{{profile.uuid}}' name='{{profile.uuid}}'/>
            {{profile.first_name}} {{profile.last_name}}
            {{profile.uuid}}

            {%ifequal online_simulators 0 %}
            <button data-function='opensim.backup_luggage' data-uuid='{{profile.uuid}}' class='action-icon action-icon-disabled backup-region-on backup-region-status-{{region.RegionUUID}}' value='{{profile.uuid}}'></button>
            {%else%}
            <button data-function='opensim.backup_luggage' data-uuid='{{profile.uuid}}' class='action-icon backup-region-on backup-region-status-{{region.RegionUUID}}' value='{{profile.uuid}}'></button>
            {%endifequal%}

            {%endfor%}

                        <button data-function='opensim.sync_avatars' class='fg-button ui-state-default fg-button-icon-left ui-corner-all'>{%trans "Sync"%}</button>

                <input type='checkbox' id='cb-all' />
                {%trans "Description"%}
                {%trans "Modified"%}
                {%trans "Size"%}
                {%trans "Options"%}

            {%for lugg in luggage%}

            <input type='checkbox' id='{{lugg.name}}' name='{{lugg.name}}'/>
            {{lugg.name}}
            {{lugg.modified}}
            {{lugg.size}}

            {%ifequal online_simulators 0 %}
            <button data-function='opensim.load_luggage' data-name='{{lugg.name}}' class='action-icon action-icon-disabled scene-backup-load scene-backup-load-status-{{region.RegionUUID}}'  value='{{lugg.name}}'></button>
            {%else%}
            <button data-function='opensim.load_luggage' data-name='{{lugg.name}}' class='action-icon scene-backup-load scene-backup-load-status-{{region.RegionUUID}}' value='{{lugg.name}}'></button>
            {%endifequal%}
            <button data-function='opensim.download_luggage' data-name='{{lugg.name}}' class='action-icon scene-backup-download scene-backup-load-status-{{region.RegionUUID}}' value='{{lugg.name}}'></button>

            {%endfor%}

                        <button data-function='opensim.delete_luggage' class='btn-active-many fg-button ui-state-default fg-button-icon-left ui-corner-left ui-state-disabled'>{%trans "Delete"%}</button>
                        <button data-uri='/opensim/avatars/luggage/upload/' class='fg-button ui-state-default fg-button-icon-left ui-corner-right'>{%trans "Upload"%}</button>


text:
namespace rbe
{
	namespace Util
	{
		inline status_t LockWithTimeoutCommon(std::function<status_t (bigtime_t)> &fn, bigtime_t timeout)
		{
			status_t status = fn(0);
			if (status != B_OK) {
				bool unblock = false;
				std::function<void ()> f = [&]() {
					while (!unblock) {
						bigtime_t tm = (TICK_TIMEOUT < timeout ? TICK_TIMEOUT : timeout);
						status = fn(tm);
						if (status != B_TIMED_OUT)
							break;
						if (timeout == B_INFINITE_TIMEOUT)
							continue;
						if (timeout < TICK_TIMEOUT)
							break;
						timeout -= TICK_TIMEOUT;
					}
				};
				CallWithoutGVL<std::function<void ()>, bool> g(f, &unblock);
				g();
				rb_thread_check_ints(); // correct?
			}
			return status;
		}

		inline status_t LockLooperWithTimeout(BLooper *looper, bigtime_t timeout)
		{
			std::function<status_t (bigtime_t)> f = [&](bigtime_t tm) -> status_t {
				return looper->LockWithTimeout(tm);
			};
			return LockWithTimeoutCommon(f, timeout);
		}
	} // Util
} // rbe

#endif


text:
SessionStateDelegateChromeos::SessionStateDelegateChromeos()
    : session_state_(SESSION_STATE_LOGIN_PRIMARY) {
  user_manager::UserManager::Get()->AddSessionStateObserver(this);
  chromeos::UserAddingScreen::Get()->AddObserver(this);

  // LoginState is not initialized in unit_tests.
  if (chromeos::LoginState::IsInitialized()) {
    chromeos::LoginState::Get()->AddObserver(this);
    SetSessionState(chromeos::LoginState::Get()->IsUserLoggedIn() ?
        SESSION_STATE_ACTIVE : SESSION_STATE_LOGIN_PRIMARY, true);
  }
}

SessionStateDelegateChromeos::~SessionStateDelegateChromeos() {
  user_manager::UserManager::Get()->RemoveSessionStateObserver(this);
  chromeos::UserAddingScreen::Get()->RemoveObserver(this);

  // LoginState is not initialized in unit_tests.
  if (chromeos::LoginState::IsInitialized())
    chromeos::LoginState::Get()->RemoveObserver(this);
}

content::BrowserContext* SessionStateDelegateChromeos::GetBrowserContextByIndex(
    ash::MultiProfileIndex index) {
  DCHECK_LT(index, NumberOfLoggedInUsers());
  user_manager::User* user =
      user_manager::UserManager::Get()->GetLRULoggedInUsers()[index];
  DCHECK(user);
  return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
}

content::BrowserContext*
SessionStateDelegateChromeos::GetBrowserContextForWindow(
    aura::Window* window) {
  const std::string& user_id =
      chrome::MultiUserWindowManager::GetInstance()->GetWindowOwner(window);
  const user_manager::User* user =
      user_manager::UserManager::Get()->FindUser(user_id);
  DCHECK(user);
  return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
}

int SessionStateDelegateChromeos::GetMaximumNumberOfLoggedInUsers() const {
  // We limit list of logged in users to 10 due to memory constraints.
  // Note that 10 seems excessive, but we want to test how many users are
  // actually added to a session.
  // TODO(nkostylev): Adjust this limitation based on device capabilites.
  // http://crbug.com/230865
  return 10;
}

int SessionStateDelegateChromeos::NumberOfLoggedInUsers() const {
  return user_manager::UserManager::Get()->GetLoggedInUsers().size();
}

bool SessionStateDelegateChromeos::IsActiveUserSessionStarted() const {
  return user_manager::UserManager::Get()->IsSessionStarted();
}

bool SessionStateDelegateChromeos::CanLockScreen() const {
  const user_manager::UserList unlock_users =
      user_manager::UserManager::Get()->GetUnlockUsers();
  return !unlock_users.empty();
}

bool SessionStateDelegateChromeos::IsScreenLocked() const {
  return chromeos::ScreenLocker::default_screen_locker() &&
         chromeos::ScreenLocker::default_screen_locker()->locked();
}

bool SessionStateDelegateChromeos::ShouldLockScreenBeforeSuspending() const {
  const user_manager::UserList logged_in_users =
      user_manager::UserManager::Get()->GetLoggedInUsers();
  for (user_manager::UserList::const_iterator it = logged_in_users.begin();
       it != logged_in_users.end();
       ++it) {
    user_manager::User* user = (*it);
    Profile* profile =
        chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
    if (profile->GetPrefs()->GetBoolean(prefs::kEnableAutoScreenLock))
      return true;
  }
  return false;
}

void SessionStateDelegateChromeos::LockScreen() {
  if (!CanLockScreen())
    return;

  VLOG(1) << "Requesting screen lock from SessionStateDelegate";
  chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
      RequestLockScreen();
}

void SessionStateDelegateChromeos::UnlockScreen() {
  // This is used only for testing thus far.
  NOTIMPLEMENTED();
}

bool SessionStateDelegateChromeos::IsUserSessionBlocked() const {
  bool has_login_manager = CommandLine::ForCurrentProcess()->HasSwitch(
          chromeos::switches::kLoginManager);
  return (has_login_manager && !IsActiveUserSessionStarted()) ||
         IsScreenLocked() ||
         chromeos::UserAddingScreen::Get()->IsRunning();
}

ash::SessionStateDelegate::SessionState
SessionStateDelegateChromeos::GetSessionState() const {
  return session_state_;
}

const user_manager::UserInfo* SessionStateDelegateChromeos::GetUserInfo(
    ash::MultiProfileIndex index) const {
  DCHECK_LT(index, NumberOfLoggedInUsers());
  return user_manager::UserManager::Get()->GetLRULoggedInUsers()[index];
}

const user_manager::UserInfo* SessionStateDelegateChromeos::GetUserInfo(
    content::BrowserContext* context) const {
  DCHECK(context);
  return chromeos::ProfileHelper::Get()->GetUserByProfile(
      Profile::FromBrowserContext(context));
}

bool SessionStateDelegateChromeos::ShouldShowAvatar(
    aura::Window* window) const {
  return chrome::MultiUserWindowManager::GetInstance()->
      ShouldShowAvatar(window);
}

void SessionStateDelegateChromeos::SwitchActiveUser(
    const std::string& user_id) {
  // Disallow switching to an already active user since that might crash.
  // Also check that we got a user id and not an email address.
  DCHECK_EQ(user_id,
            gaia::CanonicalizeEmail(gaia::SanitizeEmail(user_id)));
  if (user_id == user_manager::UserManager::Get()->GetActiveUser()->email())
    return;
  user_manager::UserManager::Get()->SwitchActiveUser(user_id);
}

void SessionStateDelegateChromeos::CycleActiveUser(CycleUser cycle_user) {
  // Make sure there is a user to switch to.
  if (NumberOfLoggedInUsers() <= 1)
    return;

  const user_manager::UserList& logged_in_users =
      user_manager::UserManager::Get()->GetLoggedInUsers();

  std::string user_id =
      user_manager::UserManager::Get()->GetActiveUser()->email();

  // Get an iterator positioned at the active user.
  user_manager::UserList::const_iterator it;
  for (it = logged_in_users.begin();
       it != logged_in_users.end(); ++it) {
    if ((*it)->email() == user_id)
      break;
  }

  // Active user not found.
  if (it == logged_in_users.end())
    return;

  // Get the user's email to select, wrapping to the start/end of the list if
  // necessary.
  switch (cycle_user) {
    case CYCLE_TO_NEXT_USER:
      if (++it == logged_in_users.end())
        user_id = (*logged_in_users.begin())->email();
      else
        user_id = (*it)->email();
      break;
    case CYCLE_TO_PREVIOUS_USER:
      if (it == logged_in_users.begin())
        it = logged_in_users.end();
      user_id = (*(--it))->email();
      break;
  }

  // Switch using the transformed |user_id|.
  user_manager::UserManager::Get()->SwitchActiveUser(user_id);
}

bool SessionStateDelegateChromeos::IsMultiProfileAllowedByPrimaryUserPolicy()
    const {
  return chromeos::MultiProfileUserController::GetPrimaryUserPolicy() ==
         chromeos::MultiProfileUserController::ALLOWED;
}

void SessionStateDelegateChromeos::AddSessionStateObserver(
    ash::SessionStateObserver* observer) {
  session_state_observer_list_.AddObserver(observer);
}

void SessionStateDelegateChromeos::RemoveSessionStateObserver(
    ash::SessionStateObserver* observer) {
  session_state_observer_list_.RemoveObserver(observer);
}

void SessionStateDelegateChromeos::LoggedInStateChanged() {
  SetSessionState(chromeos::LoginState::Get()->IsUserLoggedIn() ?
      SESSION_STATE_ACTIVE : SESSION_STATE_LOGIN_PRIMARY, false);
}

void SessionStateDelegateChromeos::ActiveUserChanged(
    const user_manager::User* active_user) {
  FOR_EACH_OBSERVER(ash::SessionStateObserver,
                    session_state_observer_list_,
                    ActiveUserChanged(active_user->email()));
}

void SessionStateDelegateChromeos::UserAddedToSession(
    const user_manager::User* added_user) {
  FOR_EACH_OBSERVER(ash::SessionStateObserver,
                    session_state_observer_list_,
                    UserAddedToSession(added_user->email()));
}

void SessionStateDelegateChromeos::OnUserAddingStarted() {
  SetSessionState(SESSION_STATE_LOGIN_SECONDARY, false);
}

void SessionStateDelegateChromeos::OnUserAddingFinished() {
  SetSessionState(SESSION_STATE_ACTIVE, false);
}

void SessionStateDelegateChromeos::SetSessionState(SessionState new_state,
                                                   bool force) {
  if (session_state_ == new_state && !force)
    return;

  session_state_ = new_state;
  NotifySessionStateChanged();
}

void SessionStateDelegateChromeos::NotifySessionStateChanged() {
  FOR_EACH_OBSERVER(ash::SessionStateObserver,
                    session_state_observer_list_,
                    SessionStateChanged(session_state_));
}


text:
package org.apache.sling.junit.teleporter.customizers;

import org.apache.sling.junit.rules.TeleporterRule;
import org.apache.sling.testing.teleporter.client.ClientSideTeleporter;
import org.apache.sling.testing.tools.sling.TimeoutsProvider;

public class ITCustomizer implements TeleporterRule.Customizer {

  public static final String BASE_URL_PROP = "launchpad.http.server.url";

  @Override
  public void customize(TeleporterRule t, String options) {
    final ClientSideTeleporter cst = (ClientSideTeleporter)t;
    cst.setBaseUrl(System.getProperty(BASE_URL_PROP, BASE_URL_PROP + "_IS_NOT_SET"));
    cst.setServerCredentials("admin", "admin");
    cst.includeDependencyPrefix("io.wcm.caravan.jaxws.publisher.it");
    cst.setTestReadyTimeoutSeconds(TimeoutsProvider.getInstance().getTimeout(10));
  }

}


text:
Pattern: Use of public AWS EC2 ingress security group rule

Issue: -

## Description

Opening up ports to the public internet is generally to be avoided. You should restrict access to IP addresses or ranges that explicitly require it where possible.

**Resolution**: Set a more restrictive cidr range.

## Examples

The following example will fail the aws-ec2-no-public-ingress-sgr check.
```terraform

 resource "aws_security_group_rule" "bad_example" {
 	type = "ingress"
 	cidr_blocks = ["0.0.0.0/0"]
 }

```

The following example will pass the aws-ec2-no-public-ingress-sgr check.
```terraform

 resource "aws_security_group_rule" "good_example" {
 	type = "ingress"
 	cidr_blocks = ["10.0.0.0/16"]
 }

```

## Further reading

- [https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule#cidr_blocks](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule#cidr_blocks)
- [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html)


text:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\Casting.ps1"
. "$here\Shadow-Copy.ps1"
. "$here\YamlDotNet-Integration.ps1"

$libDir = "$here\..\Libs"
Describe "Load-YamlDotNetLibraries" {

    Setup -Dir "Libs"
    Copy-Item "$libDir\*.dll" "$TestDrive\Libs"

    It "loads assemblies in a way that the dll's can be deleted after loading" {
        $testLibDir = "$TestDrive\Libs"
        Load-YamlDotNetLibraries $testLibDir
        Remove-Item $testLibDir -Recurse
        $testLibDir | Should Not Exist
    }
}

#Note The rest of the tests are dependent on the above test passing :-(
Describe "Convert-YamlScalarNodeToValue" {

    It "takes a YamlScalar and converts it to a value type" {
        $node = New-Object YamlDotNet.RepresentationModel.YamlScalarNode 5
        $result = Convert-YamlScalarNodeToValue $node

        $result | Should Be 5
    }
}

Describe "Convert-YamlSequenceNodeToList" {

    It "taks a YamlSequence and converts it to an array" {
        $yaml = Get-YamlDocumentFromString "---`n- single item`n- second item"

        $result = Convert-YamlSequenceNodeToList $yaml.RootNode
        $result.count | Should Be 2
    }

}

Describe "Convert-YamlMappingNodeToHash" {

    It "takes a YamlMappingNode and converts it to a hash" {
        $yaml = Get-YamlDocumentFromString "---`nkey1:   value1`nkey2:   value2"

        $result = Convert-YamlMappingNodeToHash $yaml.RootNode
        $result.keys.count | Should Be 2
    }

}

Describe "Get-YamlDocumentFromString" {

    It "will return a YamlDocument if given proper YAML" {
        $document = Get-YamlDocumentFromString "---"
        $document.GetType().Name | Should Be "YamlDocument"
    }

}


text:
[![Build Status](https://travis-ci.org/antyakushev/postcss-for.svg)][ci]
[![NPM version](https://badge.fury.io/js/postcss-for.svg)][npm]
[![Dependency Status](https://gemnasium.com/antyakushev/postcss-default-unit.svg)][deps]
[![NPM Downloads](https://img.shields.io/npm/dm/postcss-for.svg)](https://www.npmjs.org/package/postcss-for)
[
    <img align="right" width="135" height="95" src="http://postcss.github.io/postcss/logo-leftp.png" title="Philosopher's stone, logo of PostCSS">
][PostCSS]

[PostCSS] plugin that enables `@for` loop syntax in your CSS.

## Try it out!

You can try postcss-for directly from [codepen].
Just choose [PostCSS] as a preprocessor and pick desired plugin from the list.

[
    ![lalala](https://raw.githubusercontent.com/antyakushev/postcss-for/9a8663762bdb65f94a054926e2eba3b0d8f89c68/resources/codepen.png)
][codepen]

## Usage

```js
postcss([ require('postcss-for') ])
```

Note, that unlike the Sass `@for`, postcss-for in the example below iterates from 1 to 3 *inclusively*.
```css
@for $i from 1 to 3 {
    .b-$i { width: $(i)px; }
}
```

```css
.b-1 {
    width: 1px
}
.b-2 {
    width: 2px
}
.b-3 {
    width: 3px
}
```

This plugin must be set before [postcss-nested] and [postcss-simple-vars].
Therefore dollar variable cannot be used as a loop range parameter.
If you do want to use predefined range parameters though, consider using [postcss-custom-properties] with [postcss-at-rules-variables], or look into this [postcss-for fork](https://github.com/xori/postcss-for).

## More features

`By` keyword is available:

```css
@for $i from 1 to 5 by 2 {
    .b-$i { width: $(i)px; }
}
```

```css
.b-1 {
    width: 1px
}
.b-3 {
    width: 3px
}
.b-5 {
    width: 5px
}
```

Locality of variables in nested loops is supported:
```css
@for $x from 1 to 2 {
    @for $y from 1 to $x {
        @for $z from $y to $x {
            .c-$(x)-$(z)-$(y) { padding: $(x)em $(z)em $(y)em; }
        }
    }
}
```

```css
.c-1-1-1 {
    padding: 1em 1em 1em
}
.c-2-1-1 {
    padding: 2em 1em 1em
}
.c-2-2-1 {
    padding: 2em 2em 1em
}
.c-2-2-2 {
    padding: 2em 2em 2em
}
```

See [PostCSS] docs for examples for your environment.

[PostCSS]:                   https://github.com/postcss/postcss
[postcss-nested]:            https://github.com/postcss/postcss-nested
[postcss-simple-vars]:       https://github.com/postcss/postcss-simple-vars
[postcss-custom-properties]: https://github.com/postcss/postcss-custom-properties
[postcss-at-rules-variables]:https://github.com/GitScrum/postcss-at-rules-variables
[ci]:                        https://travis-ci.org/antyakushev/postcss-for
[deps]:                      https://gemnasium.com/antyakushev/postcss-for
[npm]:                       http://badge.fury.io/js/postcss-for
[codepen]:                   http://codepen.io/antyakushev/pen/oxOBEO


text:
Meteor.methods({
  signInLdsAccountUser: function(inUsername, inPassword) {
    this.unblock();
    try {
      var authUrl="https://signin.lds.org/login.html";

      var result = HTTP.post(authUrl, {params: {username: inUsername, password: inPassword}});

      var ldsAccountCookieValue = result['headers']['set-cookie'];

      for (var c in ldsAccountCookieValue) {
        if (ldsAccountCookieValue[c].indexOf("Expires") !== -1) {
          ldsAccountCookieValue[c] = "";
        }
      }

      var properties = {
        ldsAccount: {
          statusCode:       result.statusCode,
          username:         inUsername,
          cookieValue:      ldsAccountCookieValue,
          updatedAt:        new Date()
        }
      };

      Meteor.users.update(Meteor.user()._id, {
        $set: properties
      }, function(error) {
        if (error) {
          console.log(error.reason);
        }
      });

      //if successful, get the user info needed
      if (result.statusCode == 200) {
        Meteor.call("getUserIndividualId");
        Meteor.call("getUserUnitInfo");
      }

    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  signOutLdsAccountUser: function() {
    this.unblock();
    try {
      var properties = {
        ldsAccount: {
          updatedAt:  new Date()
        }
      };

      Meteor.users.update(Meteor.user()._id, {
        $set: properties
      }, function(error) {
        if (error) {
          console.log(error.reason);
        }
      });

    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getUserUnitInfo: function() {
    this.unblock();
    try {
      //get current user's unit information
      var unit;
      var currentUserUnitUrl="https://www.lds.org/directory/services/ludrs/unit/current-user-ward-stake/";
      result = Meteor.http.call("GET", currentUserUnitUrl, {
        params: {
          timeout: 30000
        },
        headers: {
          "cookie": Meteor.user().ldsAccount.cookieValue,
          "content-type": "application/json",
          "Accept": "application/json"
        },
      });

      unit = JSON.parse(result.content);

      //update the user to have additional fields to link
      var properties = {
        wardUnitNo:   unit.wardUnitNo,
        wardName:     unit.wardName,
        stakeUnitNo:  unit.stakeUnitNo,
        stakeName:    unit.stakeName,
        areaUnitNo:   unit.areaUnitNo,
      };

      Meteor.users.update(Meteor.user()._id, {
        $set: properties
      }, function(error) {
        if (error) {
          console.log(error.reason);
        }
      });

      return true;
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getUserIndividualId: function() {
    this.unblock();
    try {
      //get current user's invidual id
      var currentUser;
      var currentUserInfoUrl="https://www.lds.org/mobiledirectory/services/v2/ldstools/current-user-detail";
      result = Meteor.http.call("GET", currentUserInfoUrl, {
        params: {
          timeout: 30000
        },
        headers: {
          "cookie": Meteor.user().ldsAccount.cookieValue,
          "content-type": "application/json",
          "Accept": "application/json"
        },
      });
      currentUser = JSON.parse(result.content);

      //update the user to have additional fields to link
      var properties = {
        individualId: currentUser.individualId
      };

      Meteor.users.update(Meteor.user()._id, {
        $set: properties
      }, function(error) {
        if (error) {
          console.log(error.reason);
        }
      });

      return true;
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getUserCallingInfo: function() {
    this.unblock();
    try {
      var member = memberCollection.findOne({individualId : Meteor.user().individualId});

      //update the user to have additional fields to link
      var properties = {
        callings:     member.callings
      };

      Meteor.users.update(Meteor.user()._id, {
        $set: properties
      }, function(error) {
        if (error) {
          console.log(error.reason);
        }
      });

      return true;
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getUnits: function() {
    this.unblock();
    try {
      //get units in stake
      var unitList;

      var unitListUrl="https://www.lds.org/directory/services/ludrs/unit/current-user-units/";
      result = Meteor.http.call("GET", unitListUrl, {
        params: {
          timeout: 30000
        },
        headers: {
          "cookie": Meteor.user().ldsAccount.cookieValue,
          "content-type": "application/json",
          "Accept": "application/json"
        },
      });

      unitList = JSON.parse(result.content);

      //remove all wards in stake
      unitCollection.remove({stakeUnitNo: unitList[0].stakeUnitNo});

      //for each unit, insert into units collection
      for(var unitIndex in unitList[0].wards) {
        unitCollection.insert(unitList[0].wards[unitIndex]);
      }
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getWardMembers: function(inWardUnitNo, inStakeUnitNo) {
    this.unblock();
    try {
      var householdList;

      var householdListUrl = "https://www.lds.org/mobiledirectory/services/ludrs/1.1/mem/mobile/member-detaillist-with-callings/" + inWardUnitNo;
      result = Meteor.http.call("GET", householdListUrl, {
        params: {
          timeout: 30000
        },
        headers: {
          "cookie": Meteor.user().ldsAccount.cookieValue,
          "content-type": "application/json",
          "Accept": "application/json"
        },
      });

      parsedResult = JSON.parse(result.content);

      //if it is not for the stake, then get the members (stake is only callings)
      if (inWardUnitNo != inStakeUnitNo) {

        //remove all households and members currently in the ward
        memberCollection.remove({wardUnitNo: inWardUnitNo});
        householdCollection.remove({wardUnitNo: inWardUnitNo});

        householdList = parsedResult.households;

        //add all households in ward
        for(var householdListIndex in householdList) {
          householdCollection.insert(
            _.extend(
              householdList[householdListIndex],
              {
                wardUnitNo: inWardUnitNo,
                stakeUnitNo: inStakeUnitNo
              }
            )
          );

          //insert head of household, spouse, and children, and append on the ward unit number
          if (householdList[householdListIndex].headOfHouse) {
            memberCollection.insert(
              _.extend(
                householdList[householdListIndex].headOfHouse,
                {
                  wardUnitNo: inWardUnitNo,
                  stakeUnitNo: inStakeUnitNo
                }
              )
            );
          }
          if (householdList[householdListIndex].spouse) {
            memberCollection.insert(
              _.extend(
                householdList[householdListIndex].spouse,
                {
                  wardUnitNo: inWardUnitNo,
                  stakeUnitNo: inStakeUnitNo
                }
              )
            );
          }
          for(var childrenIndex in householdList[householdListIndex].children) {
            if (householdList[householdListIndex].children[childrenIndex]) {
              memberCollection.insert(
                _.extend(
                  householdList[householdListIndex].children[childrenIndex],
                  {
                    wardUnitNo: inWardUnitNo,
                    stakeUnitNo: inStakeUnitNo
                  }
                )
              );
            }
          }
        }
        //remove all the junk records
        memberCollection.remove({preferredName: "", wardUnitNo: inWardUnitNo});
      }

      //remove all positions in the ward
      callingCollection.remove({wardUnitNo: inWardUnitNo});
      callingGroupCollection.remove({wardUnitNo: inWardUnitNo});

      var callingList = parsedResult.callings;

      var member;
      var children;
      var assignmentsInGroup;
      //for each group of positions
      for(var callingListIndex in callingList) {
        callingGroupCollection.insert(
          _.extend(
            callingList[callingListIndex],
            {
              wardUnitNo: inWardUnitNo,
              stakeUnitNo: inStakeUnitNo
            }
          )
        );

        memberCollection.update(
          {
            individualId: parseInt(callingList[callingListIndex].individualId)
          },
          {
            $addToSet:
              {
                callings:
                  {
                    orgTypeId:      callingList[callingListIndex].groupName,
                    name:           callingList[callingListIndex].callingName,
                    instanceId:     parseInt(callingList[callingListIndex].groupInstance),
                    positionName:   callingList[callingListIndex].callingName,
                    positionTypeId: parseInt(callingList[callingListIndex].positionId),

                    groupName:      callingList[callingListIndex].groupName,
                    callingName:    callingList[callingListIndex].callingName,
                    positionId:     parseInt(callingList[callingListIndex].positionId),
                    groupKey:       parseInt(callingList[callingListIndex].groupKey),
                    groupInstance:  parseInt(callingList[callingListIndex].groupInstance)
                  }
              }
          }
        );

        /*
        //sometimes assignmentsInGroup just at this level
        assignmentsInGroup = callingList[callingListIndex].assignmentsInGroup;
        for (var assignmentsInGroupIndex in assignmentsInGroup) {
          memberCollection.update(
            {
              individualId: assignmentsInGroup[assignmentsInGroupIndex].individualId
            },
            {
              $addToSet:
                {
                  callings:
                    _.extend(
                      assignmentsInGroup[assignmentsInGroupIndex],
                      {
                        orgTypeId:    callingList[callingListIndex].orgTypeId,
                        name:         callingList[callingListIndex].name,
                        displayOrder: callingList[callingListIndex].displayOrder,
                        instanceId:   callingList[callingListIndex].instanceId
                      }
                    )
                }
            }
          );
          member = memberCollection.findOne({individualId: assignmentsInGroup[assignmentsInGroupIndex].individualId});
          callingCollection.insert(
            _.extend(
              assignmentsInGroup[assignmentsInGroupIndex],
              {
                wardUnitNo: inWardUnitNo,
                stakeUnitNo: inStakeUnitNo,
                member: member
              }
            )
          );
        }

        children = callingList[callingListIndex].children;
        for (var childrenIndex in children) {
          //other times assignmentsInGroup deeper at this level
          assignmentsInGroup = children[childrenIndex].assignmentsInGroup;
          for (var assignmentsInGroupIndex in assignmentsInGroup) {
            memberCollection.update(
              {
                individualId: assignmentsInGroup[assignmentsInGroupIndex].individualId
              },
              {
                $addToSet:
                  {
                    callings:
                      _.extend(
                        assignmentsInGroup[assignmentsInGroupIndex],
                        {
                          orgTypeId:    children[childrenIndex].orgTypeId,
                          name:         children[childrenIndex].name,
                          displayOrder: children[childrenIndex].displayOrder,
                          instanceId:   children[childrenIndex].instanceId
                        }
                      )
                  }
              }
            );
            member = memberCollection.findOne({individualId: assignmentsInGroup[assignmentsInGroupIndex].individualId});
            callingCollection.insert(
              _.extend(
                assignmentsInGroup[assignmentsInGroupIndex],
                {
                  wardUnitNo: inWardUnitNo,
                  stakeUnitNo: inStakeUnitNo,
                  member: member
                }
              )
            );
          }
        }
        */
      }
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getStakeMembers: function(inStakeUnitNo) {
    var unitList = unitCollection.find({stakeUnitNo: inStakeUnitNo}).fetch();
    for (var unitIndex in unitList) {
      Meteor.call("getWardMembers", unitList[unitIndex].wardUnitNo, inStakeUnitNo, function(error) {
        if (error) {
          console.log(error);
        }
      });
    }
    //get stake callings too
    Meteor.call("getWardMembers", inStakeUnitNo, inStakeUnitNo, function(error) {
      if (error) {
        console.log(error);
      }
    });
  },
  getWardOrganizations: function(inWardUnitNo, inStakeUnitNo) {
    this.unblock();
    try {

      var organizationList = organizationCollection.find().fetch();

      for(var organizationListIndex in organizationList) {

        var organization;

        var organizationUrl="https://www.lds.org/directory/services/ludrs/1.1/unit/roster/" + inWardUnitNo + "/" + organizationList[organizationListIndex].key;
        result = Meteor.http.call("GET", organizationUrl, {
          params: {
            timeout: 30000
          },
          headers: {
            "cookie": Meteor.user().ldsAccount.cookieValue,
            "content-type": "application/json",
            "Accept": "application/json"
          },
        });

        organization = JSON.parse(result.content);

        //for each group of positions
        for(var organizationIndex in organization) {
          memberCollection.update(
            {
              individualId: organization[organizationIndex].individualId
            },
            {
              $addToSet:
                {
                  "organizations": organizationList[organizationListIndex]
                }
            }
          );

          memberCollection.update(
            {
              individualId: organization[organizationIndex].individualId
            },
            {
              $set:
                {
                  birthdate:        organization[organizationIndex].birthdate,
                  email:            organization[organizationIndex].email,
                  formattedName:    organization[organizationIndex].formattedName,
                  givenName1:       organization[organizationIndex].givenName1,
                  memberId:         organization[organizationIndex].memberId,
                  phone:            organization[organizationIndex].phone,
                  photoUrl:         organization[organizationIndex].photoUrl
                }
            }
          );
        }
      }
    } catch (e) {
      // Got a network error, time-out or HTTP error in the 400 or 500 range.
      console.log(e);
      return e;
    }
  },
  getStakeOrganizations: function(inStakeUnitNo) {
    var unitList = unitCollection.find({stakeUnitNo: inStakeUnitNo}).fetch();
    for (var unitIndex in unitList) {
      Meteor.call("getWardOrganizations", unitList[unitIndex].wardUnitNo, inStakeUnitNo, function(error) {
        if (error) {
          console.log(error);
        }
      });
    }
  },
  syncMyInfo: function () {
    Meteor.call("getUnits");
    Meteor.call("getUserCallingInfo");
  },
  syncWard: function () {
    Meteor.call("getUnits");
    Meteor.call("getWardMembers", Meteor.user().wardUnitNo, Meteor.user().stakeUnitNo);
    Meteor.call("getWardOrganizations", Meteor.user().wardUnitNo, Meteor.user().stakeUnitNo);
    Meteor.call("getUserCallingInfo");
  },
  syncStake: function () {
    Meteor.call("getUnits");
    Meteor.call("getStakeMembers", Meteor.user().stakeUnitNo);
    Meteor.call("getStakeOrganizations", Meteor.user().stakeUnitNo);
    Meteor.call("getUserCallingInfo");
  }
});