text:
//
//  xsocket.c
//  DarwinCore
//
//  Created by yarshure on 2017/9/26.
//  Copyright © 2017年 Kong XiangBo. All rights reserved.
//

#include "xsocket.h"
#include "shared.h"
#include <asl.h>
#include <os/log.h>
#include <stdatomic.h>
#include <libkern/OSAtomic.h>
#import "GCDSocketServer.h"
//#define SNOW(format, ...)  os_log_info(OS_LOG_DEFAULT, format, ...)
int server_check_in(int port,bool share)
{
    int sockfd = -1;
    CFShow( CFSTR( "server_check_in - not managed" ) );

    /* We're running under a debugger, so set up the socket by hand. In this
     * case, we're setting up a TCP socket that listens on port 1138. Under
     * launchd, all of this is taken care of for us in the plist.
     */
    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    assert(sockfd != -1);
    int sock_opt = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*)&sock_opt, sizeof(sock_opt) ) == -1){
        return false;
    }

    struct sockaddr_in saddr;
    (void)bzero(&saddr, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    if(share){
        saddr.sin_addr.s_addr = INADDR_ANY;
    }else {
        saddr.sin_addr.s_addr = inet_addr("127.0.0.1");//INADDR_ANY;
    }

    int result = bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
    assert(result == 0);

    result = listen(sockfd, -1);
    assert(result == 0);
    return sockfd;
}


text:
<?php

class MainController
{
	public static $ModuleList = array();
	public static $activeModule;
	private static $stop_execute = false;
	private static $listSize;
	private static $keys = array();

	public static $page_title;

	public static function loadEngineTasks()
	{
		CodonRewrite::ProcessRewrite();
		Vars::setParameters();

		self::$activeModule = strtoupper(CodonRewrite::$current_module);
		Config::loadSettings();
		self::loadModules();
	}

	/**
	 * Search for any modules in the core/modules directory
	 * 	Then call loadModules() after building the list
	 *
	 * @param string $path Base folder from where to run modules
	 */
	protected static function getModulesFromPath($path)
	{
		$dh = opendir($path);

		while (($file = readdir($dh)) !== false)
		{
		    if($file != "." && $file != "..")
		    {
		    	if(is_dir($path.'/'.$file))
		    	{
					$fullpath = $path . DS . $file . DS . $file . '.php';

					if(file_exists($fullpath))
					{
						$file = strtoupper($file);
						$modules[$file] = $fullpath;
					}
				}
		    }
		}

		closedir($dh);
		return $modules;
	}

	/**
	 * Load and initialize any modules from a list
	 *
	 * @param array $ModuleList List of modules. $key is name, $value is path
	 */
	public static function loadModules()
	{
		global $NAVBAR;
		global $HTMLHead;

		self::$ModuleList = self::getModulesFromPath(CODON_MODULES_PATH);
		if(empty(self::$ModuleList))
		{
			Debug::showCritical('No modules were found in module path! ('.CODON_MODULES_PATH.')');
			return;
		}

		self::$listSize = sizeof(self::$ModuleList);
		self::$keys = array_keys(self::$ModuleList);

		for ($i=0; $i<self::$listSize; $i++)
		{
			$ModuleName = self::$keys[$i];
			$ModuleController = self::$ModuleList[$ModuleName];

			if(file_exists($ModuleController))
			{
				include_once $ModuleController;

				if(class_exists($ModuleName))
				{
					$ModuleName = strtoupper($ModuleName);
					global $$ModuleName;

					$$ModuleName = new $ModuleName();
					$$ModuleName->init($ModuleName); // Call the parent constructor

					if(self::$activeModule == $ModuleName)
					{
						# Skip it for now, run it last since it's the active
						#	one, and may overwrite some other parameters
						continue;
					}
					else
					{
						ob_start();
						self::Run($ModuleName, 'NavBar');
						$NAVBAR .= ob_get_clean();

						self::Run($ModuleName, 'HTMLHead');
						$HTMLHead .= ob_get_clean();

						@ob_end_clean();
					}
				}
			}
		}

		# Run the init tasks
		ob_start();
		self::Run(self::$activeModule, 'NavBar');
		$NAVBAR .= ob_get_clean();

		self::Run(self::$activeModule, 'HTMLHead');
		$HTMLHead .= ob_get_clean();

		@ob_end_clean();
	}

	/**
	 * Return an instance of the module/controller specified
	 *
	 */
	public static function getInstance($module)
	{
		$ModuleName = strtoupper($module);
		global $$ModuleName;

		// Make sure this module is valid
		if(!is_object($$ModuleName))
		{
			return false;
		}

		return $$ModuleName;
	}

	/**
	 * This runs the Controller() function of all the
	 * 	modules, and gives priority to the module passed
	 *	in the parameter
	 *
	 * @param string $module_priority Module that is called first
	 *
	 * Change - Oct 2009
	 *	Makes this more "cake-esque" - check if the "Controller" function
	 *	exists (for backwards compat), if it doesn't then run the function
	 *	defined by the "action" bit in the URL
	 */
	public static function RunAllActions()
	{
		//$call_function = 'Controller';
		$ModuleName = strtoupper(self::$activeModule);
		global $$ModuleName;

		// Make sure this module is valid
		if(!is_object($$ModuleName))
		{
			Debug::showCritical("The module \"{$ModuleName}\" doesn't exist!");
			return;
		}

		// Check if we have a function for the page we are calling
		$name = CodonRewrite::$current_action;
		if($name == '')
		{
			$call_function = 'index';
		}
		else
		{
			$call_function = $name;
		}

		/* Don't call self::Run() - parameters could change. They have to stay the same
			due to the fact that outside modules, etc will still use Run(), so it has
			to stay the same */

		$ret = call_user_func_array(array($$ModuleName, $call_function), CodonRewrite::$params);

		/* Set the title, based on what the module has, if it's blank,
			then just set it to the module name */
		self::$page_title = $$ModuleName->title;
		if(strlen(self::$page_title) === 0)
		{
			self::$page_title = ucwords(strtolower($ModuleName));
		}

		return true;
	}

	/**
	 * Call a specific function in a module
	 *	Function accepts additional parameters, and then passes
	 *	those parameters to the function which is being called.
	 *
	 * @param string $ModuleName Name of the module to call
	 * @param string $MethodName Method in the module to call
	 * @return value
	 */
	public static function Run($ModuleName, $MethodName)
	{
		$ModuleName = strtoupper($ModuleName);
		global $$ModuleName;

		// have a reference to the self
		if(!is_object($$ModuleName) || ! method_exists($$ModuleName, $MethodName))
		{
			return false;
		}

		// if there are parameters added, then call the function
		//	using those additional params
		$args = func_num_args();
		if($args>2)
		{
			$vals=array();
			for($i=2;$i<$args;$i++)
			{
				$param = func_get_arg($i);
				array_push($vals, $param);
			}

			return call_user_func_array(array($$ModuleName, $MethodName), $vals);
		}
		else
		{
			//no parameters, straight return
			return $$ModuleName->$MethodName();
		}
	}

	/**
	 * This stops execution of additional modules when
	 * 	RunAllActions() is being called. After the current
	 *	module is called, no more of them will be called
	 *	afterwards
	 */
	public static function stopExecution()
	{
		self::$stop_execute = true;
	}

	/**
	 * Seperate function because it will be expanded with API
	 *	later on when the install routines, etc are included
	 *	just makes sure the module is a valid one in the module's list
	 *
	 * @param string $Module See if $Module is a valid, initilized module
	 */
	protected static function valid_module($Module)
	{
		if(self::$ModuleList[$Module] != '')
			return true;

		return false;
	}

	/**
	 * Return the list of loaded modules
	 *
	 * @return array List of active modules
	 */
	public static function getModuleList()
	{
		return self::$ModuleList;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * This file is part of Gush package.
 *
 * (c) Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\ThirdParty\Gitlab\Adapter;

use Buzz\Message\Response;
use Gitlab\Client;
use Gitlab\Model;
use Gush\Adapter\Configurator;
use Gush\Exception\AdapterException;

/**
 * @author Julien Bianchi <contact@jubianchi.fr>
 */
trait GitLabAdapter
{
    /**
     * @var Client|null
     */
    protected $client;

    /**
     * {@inheritdoc}
     */
    public function __construct(array $configuration)
    {
        $this->configuration = $configuration;
    }

    /**
     * @param Client $client
     *
     * @return $this
     */
    public function setClient(Client $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * @throws \RuntimeException
     *
     * @return Model\Project
     */
    protected function getCurrentProject()
    {
        static $currentProject;

        if (null === $currentProject || $currentProject->name !== $this->getRepository() || $currentProject->owner !== $this->getUsername()) {
            $currentProject = $this->findProject($this->getUsername(), $this->getRepository());
        }

        if (null === $currentProject) {
            throw new \RuntimeException(
                sprintf(
                    'Could not guess current gitlab project, tried %s/%s',
                    $this->getUsername(),
                    $this->getRepository()
                )
            );
        }

        return $currentProject;
    }

    protected function findProject($namespace, $projectName)
    {
        return Model\Project::fromArray($this->client, $this->client->api('projects')->show($namespace.'/'.$projectName));
    }

    /**
     * @throws \Exception
     *
     * @return bool
     */
    public function authenticate()
    {
        if (Configurator::AUTH_HTTP_TOKEN !== $this->configuration['authentication']['http-auth-type']) {
            throw new AdapterException('Authentication type for GitLab must be Token.');
        }

        $this->client->authenticate(
            $this->configuration['authentication']['password-or-token'],
            Client::AUTH_HTTP_TOKEN
        );

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isAuthenticated()
    {
        return is_array($this->client->api('projects')->owned());
    }

    /**
     * {@inheritdoc}
     */
    public function getTokenGenerationUrl()
    {
        return sprintf('%/profile/account', $this->configuration['repo_domain_url']);
    }

    protected static function getPagination(Response $response)
    {
        $header = $response->getHeader('Link');

        if (empty($header)) {
            return;
        }

        $pagination = [];

        foreach (explode(',', $header) as $link) {
            preg_match('/<(.*)>; rel="(.*)"/i', trim($link, ','), $match);

            if (3 === count($match)) {
                $pagination[$match[2]] = $match[1];
            }
        }

        return $pagination;
    }
}


text:
function showResponseBands(fap,ftp,fas,x,U,V,M,Q,R,str)
% showResponseBands(fap,ftp,fas,x,U,V,M,Q,R,str)

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

if (nargin ~= 9) && (nargin ~= 10)
  print_usage("showResponseBands(fap,ftp,fas,x,U,V,M,Q,R,str)";
endif
L=512;
subplot(311);
wap=fap*(0:(L-1))*2*pi/L;
Ap=iirA(wap,x,U,V,M,Q,R);
plot(0.5*wap/pi,20*log10(Ap));
xlabel("Frequency");
ylabel("Amplitude(dB)");
grid("on");
if nargin==10
  title(str);
endif
subplot(312);
wtp=ftp*(0:(L-1))*2*pi/L;
T=iirT(wtp,x,U,V,M,Q,R);
plot(0.5*wtp/pi,T);
xlabel("Frequency");
ylabel("Delay(samples)");
subplot(313);
dfas=(0.5-fas)/(L-1);
was=2*pi*(fas+(dfas*(0:(L-1))));
As=iirA(was,x,U,V,M,Q,R);
plot(0.5*was/pi,20*log10(As));
axis([fas, 0.5, -60, -20]);
xlabel("Frequency");
ylabel("Amplitude(dB)");
grid("on");

endfunction


text:
/* global Request, Blob */
import {
  getCSRFTokenFromContext,
  CSRFTokenPropertyName,
  replaceCSRFTokenInRequestBody
} from './api';

/**
 * Adds or replaces a query string parameter to the given url.
 *
 * @param {String} url - The url to operate on.
 * @param {String} name - The name of the search parameter.
 * @param {String} value - The value of the search parameter.
 * @return {String} The updated url with the new name, value search parameter.
 */
export function addOrReplaceUrlSearchParameter(url, name, value) {
  let search, newUrl;
  const reName = new RegExp('('+name+'=)([^&]+)');

  // replace/add the name/value parameter in the url.
  if (reName.test(url)) {
    newUrl = url.replace(reName, '$1'+value);
  } else {
    search = url.split('?');
    url = url.replace(/\?$/, '');
    newUrl = url + ( search[1] ? '&' : '?' );
    newUrl += [name, value].join('=');
  }

  return newUrl;
}

/**
 * strip search!
 *
 * Removes the search/query portion from a URL.
 * E.g. stripSearchParameters("https://example.com/index.html?a=b&c=d")
 *     ➔ "https://example.com/index.html"
 *
 * @param {String} url - the url of a request.
 * @return {String} A url with the entire query string removed.
 */
export function stripSearchParameters(url) {
  return url.replace(/\?(?:.*)$/, '');
}

/**
 * Add or update a cache busting parameter to the given URL.
 *
 * @param {String} url - The url to add or update the cache busting parameter.
 * @return {String} A url with the cache busting parameter added or updated.
 */
export function cacheBustRequest (url) {
  return addOrReplaceUrlSearchParameter(url, 'sw-cache', Date.now());
}

/**
 * Utility method to dehydrate a Request to a plain object for IDBObjectStore.
 *
 * @private
 *
 * @param {Request} request - The input Request object.
 * @param {String} bodyType - One of the Request Body methods: arrayBuffer,
 * blob, json, text, or formData
 * @return {Promise} Promise resolves to dehydrated request state.
 */
export function dehydrateRequest (request, bodyType) {
  const bodyGetter = request[bodyType];

  return bodyGetter.call(request).then(function (body) {
    return {
      method: request.method,
      url: request.url,
      bodyType: bodyType,
      body: body
    };
  });
}

/**
 * Utility method to rehydrate a Request from a plain object from IDBObjectStore.
 *
 * @private
 *
 * @param {Object} state - The dehydrated request state.
 * @param {String} state.url - The request url.
 * @param {String} state.method - The request method.
 * @param {String} state.bodyType - Must be 'json'.
 * @param {Object} state.body - The request body.
 * @param {Object} [state.body.context] - The request body context.
 * @param {Object} [apiInfo] - contains timeout, cors, and CSRF token to use.
 * If specified, any existing csrf value in the request state url is replaced,
 * or a new key/value is added to the end of the url.
 * @param {Object} [apiInfo.xhrContext] - contains csrfToken.
 * @param {String} [apiInfo.xhrContext._csrf] - The csrfToken.
 * @return {Request} A new Request object from state.
 */
export function rehydrateRequest (state, apiInfo) {
  let body, url;
  const csrfToken = getCSRFTokenFromContext(apiInfo.xhrContext);

  // If csrfToken specified, add/replace one in the body and url
  if (csrfToken) {
    url = addOrReplaceUrlSearchParameter(
      state.url,
      CSRFTokenPropertyName,
      csrfToken
    );
    replaceCSRFTokenInRequestBody(state.body, csrfToken);
  }

  // Only supporting json bodyType for this app.
  if (state.bodyType === 'json') {
    body = new Blob([JSON.stringify(state.body)], {
      type: 'application/json'
    });
  }

  return new Request (url, {
    method: state.method,
    body: body,
    credentials: 'include'
  });
}


text:
<?php

    require_once("Table.class.php");

    class Product implements Table {

        private $product_id;
        private $name;
        private $description;
        private $price;
        private $quantity;
        private $image;
        private $sale_price;
        private $on_sale;

        function getName(){ return $this->name; }
        function getDescription(){ return $this->description; }
        function getPrice(){ return $this->price; }
        function getQuantity(){ return $this->quantity; }
        function getImage(){ return $this->image; }
        function getSale_price(){ return $this->sale_price; }
        function getOn_sale(){ return $this->on_sale; }
        function getCartPrice() { return ($this->on_sale?$this->sale_price:$this->price); }

        function setProduct_id($product_id) { $this->product_id = $product_id; }
        function setName($name) { $this->name = $name; }
        function setDescription($description) { $this->description = $description; }
        function setPrice($price) { $this->price = $price; }
        function setQuantity($quantity) { $this->quantity = $quantity; }
        function setImage($image) { $this->image = $image; }
        function setSale_price($sale_price) { $this->sale_price = $sale_price; }
        function setOn_sale($on_sale) { $this->on_sale = $on_sale; }

        function getOnSale() { return "SELECT * FROM products WHERE on_sale = 1 AND quantity > 0 LIMIT 5"; }
        function getOnCatalog() { return "SELECT * FROM products WHERE on_sale = 0 AND quantity > 0 LIMIT :plimit OFFSET :poffset"; }
        function getUpdateQuantity() { return "UPDATE products SET quantity = :quantity WHERE product_id = :id"; }
        function getUpdateQuantityParams() { return array("quantity"=>$this->quantity, "id"=>$this->product_id); }
        function getUpdate() { return "UPDATE products SET name = :name, description = :description, price = :price, quantity = :quantity, image = :image, sale_price = :sale_price, on_sale = :on_sale WHERE product_id = :id"; }
        function getParamsUpdate() { return array("id"=>$this->product_id, "name"=>$this->name, "description"=>$this->description, "price"=>$this->price, "quantity"=>$this->quantity, "image"=>$this->image, "sale_price"=>$this->sale_price, "on_sale"=>$this->on_sale); }
        //function getSelectByUser() { return "SELECT * FROM products WHERE product_id IN (SELECT product_id FROM carts WHERE user_id = :user_id)"; }

        public function getId() { return $this->product_id; }
        public function getClassName() { return "Product"; }
        public function getInsert() { return "INSERT INTO products (name, description, price, quantity, image, sale_price, on_sale) VALUES (:name, :description, :price, :quantity, :image, :sale_price, :on_sale)"; }
        public function getParamsInsert() { return array("name"=>$this->name, "description"=>$this->description, "price"=>$this->price, "quantity"=>$this->quantity, "image"=>$this->image, "sale_price"=>$this->sale_price, "on_sale"=>$this->on_sale); }
        public function getSelectById() { return "SELECT * FROM products WHERE product_id = :id"; }
        public function getSelect() { return "SELECT * FROM products"; }

    }


text:
 #define _DDCURSOR_

 #include "DDTraits.hpp"

 #define DDARRAY_CURSOR_MEMBER(...) template <typename ValueT> __VA_ARGS__ DDArrayCursor<ValueT>
 #define DDTABLE_CURSOR_MEMBER(...) template <typename ValueT> __VA_ARGS__ DDTableCursor<ValueT>

DD_BEGIN
enum class DDCursorCatagory {
    UNKNOWN = 0,
    FIXED = 1,
    UNDIRECTIONAL = 2,
    BIDIRECTIONAL = 3,
    FREE_ACCESS = 4

};

template <typename CursorT>
struct DDCursorTraits;
template <typename ValueT>
struct DDCursorTraits<ValueT*>;

template <typename CursorT>
struct DDIsUCursor;

template <typename CursorT>
struct DDIsBCursor;

template <typename CursorT>
struct DDIsFCursor;

template <typename CursorT>
struct DDDereference;

template <typename CursorT>
using DDCursorValueType = DDDereference<CursorT>;

template <typename CursorT>
struct DDCursorDifferenceType;

struct DDUCursorBasic;

struct DDBCursorBasic;

struct DDFCursorBasic;

template <typename ValueT>
struct DDTableCursor;

template <typename ValueT>
struct DDArrayCursor;

DDIMPLEMENT_BEGIN
template <typename NodeT>
struct DDListCursor_;

DDIMPLEMENT_END

template <typename NodeT>
struct DDUListCursor;

template <typename NodeT>
struct DDBListCursor;

template <typename CursorT>
using Dereference = typename DDDereference<CursorT>::Type;

template <typename CursorT>
using CursorValueType = typename DDCursorValueType<CursorT>::Type;
template <typename CursorT>
using CursorDifferenceType = typename DDCursorDifferenceType<CursorT>::Type;

template <typename ValueT, LengthType length_c>
DDArrayCursor<ValueT> begin(ArrayType<ValueT, length_c>& array);
template <typename ContainerT>
typename ContainerT::Cursor begin(ContainerT& container);

template <typename ValueT, LengthType length_c>
DDArrayCursor<ValueT> end(ArrayType<ValueT, length_c>& array);
template <typename ContainerT>
typename ContainerT::Cursor end(ContainerT& container);

DDIMPLEMENT_BEGIN
template <typename UCursorT>
ProcessType advance_(UCursorT& begin, CursorDifferenceType<UCursorT> step, DDFalseType) noexcept(true);
template <typename FCursorT>
ProcessType advance_(FCursorT& begin, CursorDifferenceType<FCursorT> step, DDTrueType) noexcept(true);

DDIMPLEMENT_END

template <typename UCursorT>
ProcessType advance(UCursorT& begin, CursorDifferenceType<UCursorT> step) noexcept;

DDIMPLEMENT_BEGIN
template <typename UCursorT>
CursorDifferenceType<UCursorT> distance_(UCursorT begin, UCursorT end, DDFalseType) noexcept(true);
template <typename FCursorT>
CursorDifferenceType<FCursorT> distance_(FCursorT begin, FCursorT end, DDTrueType) noexcept(true);

DDIMPLEMENT_END

template <typename UCursorT>
CursorDifferenceType<UCursorT> distance(UCursorT begin, UCursorT end) noexcept(true);

template <typename CursorT>
struct DDCursorTraits {
    public:
    using ValueType = RemoveReference<decltype(*CursorT())>;
    using ReferenceType = ValueType&;
    using PointerType = ValueType*;
    using DifferenceType = LengthType;
    static constexpr DDCursorCatagory catagory = CursorT::catagory;

};

template <typename ValueT>
struct DDCursorTraits<ValueT*> {
    public:
    using ValueType = ValueT;
    using ReferenceType = ValueT&;
    using PointerType = ValueT*;
    using DifferenceType = RemoveConst<decltype(PointerType() - PointerType())>;
    static constexpr DDCursorCatagory catagory = DDCursorCatagory::FREE_ACCESS;

};

template <typename CursorT>
struct DDIsUCursor : public DDBoolConstant<DDCursorTraits<CursorT>::catagory >= DDCursorCatagory::UNDIRECTIONAL> {
};

template <typename CursorT>
struct DDIsBCursor : public DDBoolConstant<DDCursorTraits<CursorT>::catagory >= DDCursorCatagory::BIDIRECTIONAL> {
};

template <typename CursorT>
struct DDIsFCursor : public DDBoolConstant<DDCursorTraits<CursorT>::catagory >= DDCursorCatagory::FREE_ACCESS> {
};

template <typename CursorT>
struct DDDereference {
    public:
    using Type = typename DDCursorTraits<CursorT>::ValueType;

};

template <typename CursorT>
struct DDCursorDifferenceType {
    public:
    using Type = typename DDCursorTraits<CursorT>::DifferenceType;

};

struct DDUCursorBasic {
    public:
    static constexpr DDCursorCatagory catagory = DDCursorCatagory::UNDIRECTIONAL;

};

struct DDBCursorBasic {
    public:
    static constexpr DDCursorCatagory catagory = DDCursorCatagory::BIDIRECTIONAL;

};

struct DDFCursorBasic {
    public:
    static constexpr DDCursorCatagory catagory = DDCursorCatagory::FREE_ACCESS;

};

template <typename ValueT>
struct DDArrayCursor : public DDFCursorBasic {
    public:
    using ValueType = ValueT;
    using ReferenceType = ValueT&;
    using PointerType = ValueT*;
    using DifferenceType = LengthType;

    public:
    DDArrayCursor() noexcept(true) = default;
    DDArrayCursor(DDArrayCursor<ValueT> const& origin) noexcept(true) = default;
    DDArrayCursor(ValueT* target) noexcept(true);

    public:
    ~DDArrayCursor() noexcept(true) = default;

    public:
    DDArrayCursor<ValueT>& operator =(DDArrayCursor<ValueT> const& origin) noexcept(true) = default;

    public:
    DDArrayCursor<ValueT>& operator ++() noexcept(true);
    DDArrayCursor<ValueT> operator ++(IntSignType) noexcept(true);
    DDArrayCursor<ValueT>& operator --() noexcept(true);
    DDArrayCursor<ValueT> operator --(IntSignType) noexcept(true);
    DDArrayCursor<ValueT>& operator +=(DifferenceType step) noexcept(true);
    DDArrayCursor<ValueT>& operator -=(DifferenceType step) noexcept(true);
    ValueT& operator [](SubscriptType index) const noexcept(true);
    ValueT& operator *() const noexcept(true);
    ValueT* operator ->() const noexcept(true);
    explicit operator ValueT*() const noexcept(true);
    explicit operator ValidityType() const noexcept(true);

    private:
    ValueT* m_target = nullptr;

};

template <typename ValueT>
struct DDTableCursor : public DDFCursorBasic {
    public:
    using ValueType = ValueT;
    using ReferenceType = ValueT&;
    using PointerType = ValueT*;
    using DifferenceType = LengthType;

    public:
    DDTableCursor() noexcept(true) = default;
    DDTableCursor(DDTableCursor<ValueT> const& origin) noexcept(true) = default;

    private:
    DDTableCursor(ValueT** target) noexcept(true);

    public:
    ~DDTableCursor() noexcept(true) = default;

    public:
    DDTableCursor<ValueT>& operator =(DDTableCursor<ValueT> const& origin) noexcept(true) = default;

    public:
    DDTableCursor<ValueT>& operator ++() noexcept(true);
    DDTableCursor<ValueT> operator ++(IntSignType) noexcept(true);
    DDTableCursor<ValueT>& operator --() noexcept(true);
    DDTableCursor<ValueT> operator --(IntSignType) noexcept(true);
    DDTableCursor<ValueT>& operator +=(LengthType step) noexcept(true);
    DDTableCursor<ValueT>& operator -=(LengthType step) noexcept(true);
    ValueT& operator [](SubscriptType index) const noexcept(true);
    ValueT& operator *() const noexcept(true);
    ValueT* operator ->() const noexcept(true);
    explicit operator ValueT*() const noexcept(true);
    explicit operator ValidityType() const noexcept;

    private:
    ValueT** m_target = nullptr;

};

DDIMPLEMENT_BEGIN
template <typename ValueT>
struct DDListCursor_;

DDIMPLEMENT_END

template <typename ValueT>
struct DDUListCursor;

template <typename ValueT>
struct DDBListCursor;

DD_END

DD_BEGIN
DDIMPLEMENT_BEGIN
template <typename UCursorT>
ProcessType advance_(UCursorT& begin, CursorDifferenceType<UCursorT> step, DDFalseType) noexcept(true) {
    constexpr auto end = decltype(step)();
    for (; step < end; ++step) {
        --begin;
    }
    for (; end < step; --step) {
        ++begin;
    }
    return;
}

template <typename FCursorT>
ProcessType advance_(FCursorT& begin, CursorDifferenceType<FCursorT> step, DDTrueType) noexcept(true) {
    begin += step;
    return;
}

DDIMPLEMENT_END

template <typename UCursorT>
ProcessType advance(UCursorT& begin, CursorDifferenceType<UCursorT> step) noexcept(true) {
    DDImplement::advance_(begin, step, DDIsFCursor<UCursorT>());
    return;
}

DDIMPLEMENT_BEGIN
template <typename UCursorT>
CursorDifferenceType<UCursorT> distance_(UCursorT begin, UCursorT end, DDFalseType) noexcept {
    auto distance = CursorDifferenceType<UCursorT>();
    while (begin != end) {
        ++begin;
        ++distance;
    }
    return distance;
}

template <typename FCursorT>
inline CursorDifferenceType<FCursorT> distance_(FCursorT begin, FCursorT end, DDTrueType) noexcept {
    return end - begin;
}

DDIMPLEMENT_END

template <typename UCursorT>
inline CursorDifferenceType<UCursorT> distance(UCursorT begin, UCursorT end) noexcept {
    return DDImplement::distance_(begin, end, DDIsFCursor<UCursorT>());
}

DDARRAY_CURSOR_MEMBER(inline)::DDArrayCursor(ValueT* target) noexcept(true) : m_target(target) {
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>&)::operator ++() noexcept(true) {
    ++this->m_target;
    return *this;
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>)::operator ++(IntSignType) noexcept(true) {
    return DDArrayCursor<ValueT>(this->m_target++);
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>&)::operator --() noexcept(true) {
    --this->m_target;
    return *this;
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>)::operator --(IntSignType) noexcept(true) {
    return DDArrayCursor<ValueT>(this->m_target--);
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>&)::operator +=(LengthType step) noexcept(true) {
    this->m_target += step;
    return *this;
}

DDARRAY_CURSOR_MEMBER(inline DDArrayCursor<ValueT>&)::operator -=(LengthType step) noexcept(true) {
    this->m_target -= step;
    return *this;
}

DDARRAY_CURSOR_MEMBER(ValueT&)::operator [](SubscriptType index) const noexcept(true) {
    return this->m_target[index];
}

DDARRAY_CURSOR_MEMBER(ValueT&)::operator *() const noexcept(true) {
    return *this->m_target;
}

DDARRAY_CURSOR_MEMBER(ValueT*)::operator ->() const noexcept(true) {
    return this->m_target;
}

DDARRAY_CURSOR_MEMBER()::operator ValueT*() const noexcept(true) {
    return this->m_target;
}

DDARRAY_CURSOR_MEMBER()::operator ValidityType() const noexcept(true) {
    return this->m_target;
}

DDTABLE_CURSOR_MEMBER(inline)::DDTableCursor(ValueT** target) noexcept(true) : m_target(target) {
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>&)::operator ++() noexcept(true) {
    ++this->m_target;
    return *this;
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>)::operator ++(IntSignType) noexcept(true) {
    return DDTableCursor<ValueT>(this->m_target++);
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>&)::operator --() noexcept(true) {
    --this->m_target;
    return *this;
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>)::operator --(IntSignType) noexcept(true) {
    return DDTableCursor<ValueT>(this->m_target--);
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>&)::operator +=(LengthType step) noexcept(true) {
    this->m_target += step;
    return *this;
}

DDTABLE_CURSOR_MEMBER(inline DDTableCursor<ValueT>&)::operator -=(LengthType step) noexcept(true) {
    this->m_target -= step;
    return *this;
}

DDTABLE_CURSOR_MEMBER(ValueT&)::operator [](SubscriptType index) const noexcept(true) {
    return *this->m_target[index];
}

DDTABLE_CURSOR_MEMBER(ValueT&)::operator *() const noexcept(true) {
    return **this->m_target;
}

DDTABLE_CURSOR_MEMBER(ValueT*)::operator ->() const noexcept(true) {
    return *this->m_target;
}

DDTABLE_CURSOR_MEMBER()::operator ValueT*() const noexcept(true) {
    return *this->m_target;
}

DDTABLE_CURSOR_MEMBER(inline)::operator ValidityType() const noexcept(true) {
    return *this->m_target;
}

DD_END

 #undef DDARRAY_CURSOR_MEMBER
 #undef DDTABLE_CURSOR_MEMBER

#endif


text: {{item.name}}


text:
package androidx.leanback.widget;

import static androidx.leanback.widget.BaseCardView.LayoutParams.MATCH_PARENT;
import static androidx.leanback.widget.BaseCardView.LayoutParams.VIEW_TYPE_INFO;
import static androidx.leanback.widget.BaseCardView.LayoutParams.VIEW_TYPE_MAIN;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.view.View;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

@SmallTest
@RunWith(AndroidJUnit4.class)
public class BaseCardViewTest {

    BaseCardView.LayoutParams createLayoutParams(int viewType, int width, int height) {
        BaseCardView.LayoutParams lp = new BaseCardView.LayoutParams(width, height);
        lp.viewType = viewType;
        return lp;
    }

    void mockInfoHeightAnimation(BaseCardView view, int width, int startHeight, int endHeight) {
        ((BaseCardView.InfoHeightAnimation) view.getAnimation()).mockStart();
        measureAndLayout(view, width, startHeight);
        ((BaseCardView.InfoHeightAnimation) view.getAnimation()).mockEnd();
        assertNull(view.getAnimation());
        measureAndLayout(view, width, endHeight);
    }

    void mockInfoAlphaAnimation(BaseCardView view, View infoView,
            float startAlpha, float endAlpha) {
        ((BaseCardView.InfoAlphaAnimation) view.getAnimation()).mockStart();
        assertEquals(startAlpha, infoView.getAlpha(), 0.01f);
        assertEquals(View.VISIBLE, infoView.getVisibility());
        ((BaseCardView.InfoAlphaAnimation) view.getAnimation()).mockEnd();
        assertNull(view.getAnimation());
        assertEquals(endAlpha, infoView.getAlpha(), 0.01f);
        assertEquals(endAlpha == 0f? View.GONE: View.VISIBLE, infoView.getVisibility());
    }

    void measureAndLayout(View view, int expectedWidth, int expectedHeight) {
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        assertEquals(expectedWidth, view.getMeasuredWidth());
        assertEquals(expectedHeight, view.getMeasuredHeight());
        view.layout(0, 0, expectedWidth, expectedHeight);
    }

    void verifyLayoutTimes(View.OnLayoutChangeListener listener, int timesCalled) {
        verify(listener, times(timesCalled)).onLayoutChange(any(View.class),
                any(Integer.class), any(Integer.class), any(Integer.class), any(Integer.class),
                any(Integer.class), any(Integer.class), any(Integer.class), any(Integer.class));
    }

    @Test
    public void infoOver_InfoVisibleAlways() {
        BaseCardView cardView = new BaseCardView(ApplicationProvider.getApplicationContext());
        View main = new View(cardView.getContext());
        main.setLayoutParams(createLayoutParams(VIEW_TYPE_MAIN, 500, 500));
        cardView.addView(main);
        View info = new View(cardView.getContext());
        View.OnLayoutChangeListener onLayout = Mockito.mock(View.OnLayoutChangeListener.class);
        info.addOnLayoutChangeListener(onLayout);
        info.setLayoutParams(createLayoutParams(VIEW_TYPE_INFO, MATCH_PARENT, 200));
        cardView.addView(info);
        cardView.setCardType(BaseCardView.CARD_TYPE_INFO_OVER);
        cardView.setInfoVisibility(BaseCardView.CARD_REGION_VISIBLE_ALWAYS);

        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(true);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(false);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setSelected(true);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setSelected(false);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);
    }

    @Test
    public void infoUnder_InfoVisibleAlways() {
        BaseCardView cardView = new BaseCardView(ApplicationProvider.getApplicationContext());
        View main = new View(cardView.getContext());
        main.setLayoutParams(createLayoutParams(VIEW_TYPE_MAIN, 500, 500));
        cardView.addView(main);
        View info = new View(cardView.getContext());
        View.OnLayoutChangeListener onLayout = Mockito.mock(View.OnLayoutChangeListener.class);
        info.addOnLayoutChangeListener(onLayout);
        info.setLayoutParams(createLayoutParams(VIEW_TYPE_INFO, MATCH_PARENT, 200));
        cardView.addView(info);
        cardView.setCardType(BaseCardView.CARD_TYPE_INFO_UNDER);
        cardView.setInfoVisibility(BaseCardView.CARD_REGION_VISIBLE_ALWAYS);

        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(true);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(false);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setSelected(true);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setSelected(false);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());
        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);
    }

    @Test
    public void infoUnder_InfoVisibleActivated() {
        BaseCardView cardView = new BaseCardView(ApplicationProvider.getApplicationContext());
        View main = new View(cardView.getContext());
        main.setLayoutParams(createLayoutParams(VIEW_TYPE_MAIN, 500, 500));
        cardView.addView(main);
        View info = new View(cardView.getContext());
        View.OnLayoutChangeListener onLayout = Mockito.mock(View.OnLayoutChangeListener.class);
        info.addOnLayoutChangeListener(onLayout);
        info.setLayoutParams(createLayoutParams(VIEW_TYPE_INFO, MATCH_PARENT, 200));
        cardView.addView(info);
        cardView.setCardType(BaseCardView.CARD_TYPE_INFO_UNDER);
        cardView.setInfoVisibility(BaseCardView.CARD_REGION_VISIBLE_ACTIVATED);

        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 0);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(true);
        assertTrue(cardView.isLayoutRequested());
        measureAndLayout(cardView, 500, 700);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        cardView.setActivated(false);
        assertTrue(cardView.isLayoutRequested());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        // changing selected does not affect size
        cardView.setSelected(true);
        assertFalse(cardView.isLayoutRequested());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);

        // changing selected does not affect size
        cardView.setSelected(false);
        assertFalse(cardView.isLayoutRequested());
        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 1);
        assertEquals(1f, info.getAlpha(), 0.01f);
    }

    @Test
    public void infoUnder_InfoVisibleSelected() {
        final BaseCardView cardView = new BaseCardView(ApplicationProvider.getApplicationContext());
        View main = new View(cardView.getContext());
        main.setLayoutParams(createLayoutParams(VIEW_TYPE_MAIN, 500, 500));
        cardView.addView(main);
        View info = new View(cardView.getContext());
        View.OnLayoutChangeListener onLayout = Mockito.mock(View.OnLayoutChangeListener.class);
        info.addOnLayoutChangeListener(onLayout);
        info.setLayoutParams(createLayoutParams(VIEW_TYPE_INFO, MATCH_PARENT, 200));
        cardView.addView(info);
        cardView.setCardType(BaseCardView.CARD_TYPE_INFO_UNDER);
        cardView.setInfoVisibility(BaseCardView.CARD_REGION_VISIBLE_SELECTED);

        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 0);
        assertEquals(1f, info.getAlpha(), 0.01f);

        // changing activated does not affect size
        cardView.setActivated(true);
        measureAndLayout(cardView, 500, 500);
        assertNull(cardView.getAnimation());
        assertEquals(1f, info.getAlpha(), 0.01f);

        // start info height animation 500 -> 700
        cardView.setSelected(true);
        assertEquals(1f, info.getAlpha(), 0.01f);
        mockInfoHeightAnimation(cardView, 500 /*width*/, 500 /*startHeight*/, 700 /*endHeight*/);

        // changing activated does not affect size
        cardView.setActivated(false);
        assertEquals(1f, info.getAlpha(), 0.01f);
        measureAndLayout(cardView, 500, 700);
        assertNull(cardView.getAnimation());

        // start info height animation 700 -> 500
        cardView.setSelected(false);
        assertEquals(1f, info.getAlpha(), 0.01f);
        mockInfoHeightAnimation(cardView, 500 /*width*/, 700 /*startHeight*/, 500 /*endHeight*/);
    }

    @Test
    public void infoOver_InfoVisibleSelected() {
        final BaseCardView cardView = new BaseCardView(ApplicationProvider.getApplicationContext());
        View main = new View(cardView.getContext());
        main.setLayoutParams(createLayoutParams(VIEW_TYPE_MAIN, 500, 500));
        cardView.addView(main);
        View info = new View(cardView.getContext());
        View.OnLayoutChangeListener onLayout = Mockito.mock(View.OnLayoutChangeListener.class);
        info.addOnLayoutChangeListener(onLayout);
        info.setLayoutParams(createLayoutParams(VIEW_TYPE_INFO, MATCH_PARENT, 200));
        cardView.addView(info);
        cardView.setCardType(BaseCardView.CARD_TYPE_INFO_OVER);
        cardView.setInfoVisibility(BaseCardView.CARD_REGION_VISIBLE_SELECTED);

        measureAndLayout(cardView, 500, 500);
        verifyLayoutTimes(onLayout, 0);
        assertFalse(cardView.isSelected());
        assertFalse(cardView.isActivated());
        assertEquals(0f, info.getAlpha(), 0.01f);

        cardView.setActivated(true);
        assertFalse(cardView.isLayoutRequested());
        assertNull(cardView.getAnimation());

        assertEquals(info.getVisibility(), View.GONE);
        assertEquals(0f, info.getAlpha(), 0.01f);
        // start info animation alpha 0f -> 1f
        cardView.setSelected(true);
        // change visibility when start animation causing layout requested
        assertTrue(cardView.isLayoutRequested());
        measureAndLayout(cardView, 500, 500);
        mockInfoAlphaAnimation(cardView, info, 0f, 1f);
        assertEquals(1f, info.getAlpha(), 0.01f);

        // start info animation alpha 1f -> 0f
        cardView.setSelected(false);
        assertFalse(cardView.isLayoutRequested());
        mockInfoAlphaAnimation(cardView, info, 1f, 0f);
        assertEquals(0f, info.getAlpha(), 0.01f);
    }

}


text:
/************
* Example .net program. In Visual Studio Code, go to File -> Open Folder... and select vscode/codeExamples
* In the terminal, run "dotnet restore"
* With the C# extention installed, you can place breakpoints and use the debugger tool.
************/

using System;
using codeExamples.AnonymousTypes;
using codeExamples.Async;
using codeExamples.Lambdas;
using codeExamples.Sugar;

namespace codeExamples
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Anonymous Type Examples");
            Console.WriteLine("Example 1");
            new AnonymousTypeExamples().Example1();
            Console.WriteLine();
            Console.WriteLine("Example 2");
            dynamic dynamic = new AnonymousTypeExamples().Example2();
            Console.WriteLine(dynamic.ID);
            Console.WriteLine(dynamic.Name);
            Console.WriteLine();
            Console.WriteLine("Example 3");
            new AnonymousTypeExamples().UsingLegalAnonymousType();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Lamda Expression Examples");
            Console.WriteLine("Example 1");
            new LambdaExample1().Example();
            Console.WriteLine();
            Console.WriteLine("Example 2");
            new LambdaExample2().Example();
            Console.WriteLine();
            Console.WriteLine("Example 3");
            new LambdaExample3().Example();
            Console.WriteLine();
            Console.WriteLine("Example 4");
            new LambdaExample4().Example();
            Console.WriteLine();
            Console.WriteLine("Example 5");
            new LambdaExample5().Example();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Async Examples");
            Console.WriteLine("Example 1");
            new AsyncExample1().ExampleAsync().Wait();
            new AsyncExample1().Example();
            Console.WriteLine("Misc Examples");
            Console.WriteLine("Example 1");
            new Setter().Example();
        }
    }
}


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

/**
 *
 * @author ivo
 */
public class Criterios {

    //criterios melhor caminho
    private boolean viagemMenorDistancia;
    private boolean viagemMenorTempoViagem;
    private boolean viagemMaisBarata;

    //criterios por comparacao
    private boolean comparacaoViagemMenorDistancia;
    private boolean comparacaoVigemMenorTempoViagem;
    private boolean comparacaoViagemMaisBarata;

    private Integer duracaoMaxima;
    private Integer tempoEsperaTotalMaximo;
    private Integer tempoEsperaMaximoParagem;
    private Double precoTotalMaximo;
    private Double precoMaximoTroco;
    private String transportadora;

    /**
     * create classe criterios with all null fields
     */
    public Criterios() {
        this.viagemMaisBarata = false;
        this.viagemMenorDistancia = false;
        this.viagemMenorTempoViagem = false;
        this.comparacaoViagemMaisBarata = false;
        this.comparacaoViagemMenorDistancia = false;
        this.comparacaoVigemMenorTempoViagem = false;
        this.duracaoMaxima = null;
        this.tempoEsperaTotalMaximo = null;
        this.tempoEsperaMaximoParagem = null;
        this.precoTotalMaximo = null;
        this.precoMaximoTroco = null;
        this.transportadora = null;
    }

    /**
     * create classe criterios with the desired criteria
     *
     * @param duracaoMaxima
     * @param tempoEsperaTotalMaximo
     * @param tempoEsperaMaximoParagem
     * @param precoTotalMaximo
     * @param precoMaximoTroco
     */
    public Criterios(Integer duracaoMaxima, Integer tempoEsperaTotalMaximo, Integer tempoEsperaMaximoParagem, Double precoTotalMaximo, Double precoMaximoTroco) {
        this.viagemMaisBarata = false;
        this.viagemMenorDistancia = false;
        this.viagemMenorTempoViagem = false;
        this.comparacaoViagemMaisBarata = false;
        this.comparacaoViagemMenorDistancia = false;
        this.comparacaoVigemMenorTempoViagem = false;
        this.duracaoMaxima = null;
        this.tempoEsperaTotalMaximo = null;
        this.tempoEsperaMaximoParagem = null;
        this.precoTotalMaximo = null;
        this.precoMaximoTroco = null;
        this.duracaoMaxima = duracaoMaxima;
        this.tempoEsperaTotalMaximo = tempoEsperaTotalMaximo;
        this.tempoEsperaMaximoParagem = tempoEsperaMaximoParagem;
        this.precoTotalMaximo = precoTotalMaximo;
        this.precoMaximoTroco = precoMaximoTroco;
    }

    public boolean isViagemMenorDistancia() {
        return viagemMenorDistancia;
    }

    public boolean isViagemMenorTempoViagem() {
        return viagemMenorTempoViagem;
    }

    public boolean isViagemMaisBarata() {
        return viagemMaisBarata;
    }

    public void setViagemMenorDistancia(boolean viagemMenorDistancia) {
        this.viagemMenorDistancia = viagemMenorDistancia;
    }

    public void setVigemMenorTempoViagem(boolean vigemMenorTempoViagem) {
        this.viagemMenorTempoViagem = vigemMenorTempoViagem;
    }

    public void setViagemMaisBarata(boolean viagemMaisBarata) {
        this.viagemMaisBarata = viagemMaisBarata;
    }

    public Integer getDuracaoMaxima() {
        return duracaoMaxima;
    }

    public Integer getTempoEsperaTotalMaximo() {
        return tempoEsperaTotalMaximo;
    }

    public Integer getTempoEsperaMaximoParagem() {
        return tempoEsperaMaximoParagem;
    }

    public Double getPrecoTotalMaximo() {
        return precoTotalMaximo;
    }

    public Double getPrecoMaximoTroco() {
        return precoMaximoTroco;
    }

    public void setComparacaoViagemMenorDistancia(boolean comparacaoViagemMenorDistancia) {
        this.comparacaoViagemMenorDistancia = comparacaoViagemMenorDistancia;
    }

    public void setComparacaoVigemMenorTempoViagem(boolean comparacaoVigemMenorTempoViagem) {
        this.comparacaoVigemMenorTempoViagem = comparacaoVigemMenorTempoViagem;
    }

    public void setComparacaoViagemMaisBarata(boolean comparacaoViagemMaisBarata) {
        this.comparacaoViagemMaisBarata = comparacaoViagemMaisBarata;
    }

    //por comparação
    public boolean isComparacaoViagemMenorDistancia() {
        return comparacaoViagemMenorDistancia;
    }

    public boolean isComparacaoVigemMenorTempoViagem() {
        return comparacaoVigemMenorTempoViagem;
    }

    public boolean isComparacaoViagemMaisBarata() {
        return comparacaoViagemMaisBarata;
    }

    public String getTransportadora() {
        return transportadora;
    }

    public void setTransportadora(String transportadora) {
        this.transportadora = transportadora;
    }

}


text:
A rails engine (proof-of-concept) to cache assets smartly and easy on browsers with local storage feature embedded

## USAGE: ##

Just require the gem on your Gemfile.

An option ":local_storage => true" on your include tag is enough to activate the feature

``` ruby
javascript_include_tag "test.js", { :local_storage => true }
```


text:
package com.sm.replica.server;

import com.sm.message.Request;
import com.sm.replica.ParaList;
import com.sm.store.OpType;
import com.sm.store.StoreParas;
import com.sm.transport.Utils.ServerState;
import com.sm.utils.ThreadPoolFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.*;
import voldemort.store.cachestore.Key;
import voldemort.store.cachestore.StoreException;
import voldemort.store.cachestore.Value;
import voldemort.store.cachestore.impl.CacheStore;
import voldemort.store.cachestore.impl.CacheValue;
import voldemort.versioning.ObsoleteVersionException;

import java.util.Map;
import java.util.concurrent.*;

import static com.sm.store.StoreParas.*;
import static com.sm.store.Utils.isOverLoaded;

public class ReplicaServerHandler extends SimpleChannelUpstreamHandler  {
    private static final Log logger = LogFactory.getLog(ReplicaServerHandler.class);

    private Map<String, CacheStore> storeMap;
    protected ServerState serverState;
    protected int freq =20;
    protected int maxThreads;
    protected int maxQueue ;
    protected Executor threadPools;

    public ReplicaServerHandler() {
    }

    public ReplicaServerHandler(Map<String, CacheStore> storeMap) {
        this(storeMap,  Runtime.getRuntime().availableProcessors() );
    }

    public ReplicaServerHandler(Map<String, CacheStore> storeMap, int maxThreads) {
        this.storeMap = storeMap;
        serverState = ServerState.Active;
        this.maxThreads = maxThreads;
        init();
    }

    private void init() {
        if ( Runtime.getRuntime().availableProcessors() > maxThreads )
            this.maxThreads = Runtime.getRuntime().availableProcessors();
        if ( maxQueue < maxThreads * 1000 )
            maxQueue = maxThreads * 1000;
        BlockingQueue<Runnable> queue= new LinkedBlockingQueue<Runnable>(maxQueue );
        threadPools = new ThreadPoolExecutor( maxThreads, maxThreads , 30, TimeUnit.SECONDS , queue, new ThreadPoolFactory("Replica") );
    }

    public void shutdown() {
        logger.warn("server in shutdown state");
        serverState = ServerState.Shutdown;
    }

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
      super.handleUpstream(ctx, e);
    }

    public int getFreq() {
        return freq;
    }

    public void setFreq(int freq) {
        this.freq = freq;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        Request req =  (Request) e.getMessage();
        if ( req.getHeader().getVersion() % freq == 0)
            logger.info("receive " + req.toString()+" from "+e.getRemoteAddress().toString());
        try {
            if ( isOverLoaded( (ThreadPoolExecutor) threadPools))  {
                logger.warn( "thread pools overload !!! close connection");
                ctx.getChannel().close();
            }
            else
                threadPools.execute( new SyncReplCall( req, ctx));
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            ctx.getChannel().close();
        }
    }

    protected void setError(ParaList paraList, String message) {
        for (StoreParas each : paraList.getLists()) {
            // set for Store Exception
            each.setErrorCode(2 );
            if ( each.getOpType() == OpType.Put ) {
                each.getValue().setData( message.getBytes());
            }
        }
    }

    public void processParaList(Request req, ChannelHandlerContext ctx) {
        ParaList paraList = null;
        try {
            CacheStore store = storeMap.get( req.getHeader().getName() );
            if ( store == null )
                throw new StoreException("Store "+req.getHeader().getName()+" not exits");
            //check request type it must be Normal which was send by Replica Client
            if ( req.getType() != Request.RequestType.Normal) {
                logger.error("wrong request type expect Normal but get "+req.getType().toString());
                ctx.getChannel().close();
            }
            else {
                paraList = ParaList.toParaList( req.getPayload() );
                if ( store.isShutDown() ) {
                    logger.error("server in shut down state, close channel");
                    ctx.getChannel().close();
                    return;
                }
                for ( int i=0; i< paraList.getSize() ; i++) {
                    processRequest( store, paraList.getLists().get(i));
                }
                req.setPayload( paraList.toBytes());
                ctx.getChannel().write( req);
            }
        } catch (Exception ex) {
            logger.error("close channel "+ex.getMessage()+" "+ctx.getChannel().getRemoteAddress(), ex);
            if ( paraList != null ) {
                setError( paraList, ex.getMessage());
                req.setPayload(  paraList.toBytes());
                ctx.getChannel().write(req);
            }
            else
                ctx.getChannel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
      logger.error( e.getCause().getMessage(), e.getCause() );
      e.getChannel().close();
    }

    protected void processRequest(CacheStore store, StoreParas paras) {
        try {
             switch( paras.getOpType() ) {
                 case Get: {
                     Value value = processGet(store, paras.getKey() );
                     paras.setErrorCode(NO_ERROR );
                     paras.setValue(value);
                     break;
                 }
                 case Put: {
                     processPut(store, paras.getKey(), paras.getValue() );
                     paras.setErrorCode( NO_ERROR);
                     paras.setValue(null);
                     break;
                 }
                 case Remove: {
                     boolean rs = processRemove(store, paras.getKey());
                     paras.setErrorCode( NO_ERROR);
                     paras.setRemove( rs ? (byte) 0 : (byte) 1);
                     break;
                 }
                 default:  {
                     logger.warn("unknown type "+paras.getKey().toString());
                     paras.setErrorCode( STORE_EXCEPTION);
                     checkValue( paras);
                     paras.getValue().setData( "unknown type".getBytes());
                 }
             }
        } catch( ObsoleteVersionException sx) {
             paras.setErrorCode( OBSOLETE);
             paras.getValue().setData( sx.getMessage().toString().getBytes());

        } catch (Exception ex) {
             logger.error( ex.getMessage(), ex);
             paras.setErrorCode( STORE_EXCEPTION);
             byte[] data ;
             if ( ex.getMessage() != null )
                 data = ex.getMessage().getBytes();
             else
                 data = new byte[0];
             checkValue( paras);
             paras.getValue().setData(data );
        }

    }

    // make sure value is not null
    private void checkValue(StoreParas paras) {
        if ( paras.getValue() == null  ) {
            paras.setValue(CacheValue.createValue(new byte[0]));
        }
    }

    private Value processGet(CacheStore store, Key key) {
        return store.get(key);
    }

    private void processPut(CacheStore store, Key key, Value value) {
        store.put(key, value);

    }

    private boolean processRemove(CacheStore store, Key key){
        return store.remove(key);
    }

    class SyncReplCall implements Runnable {

        private Request request;
        private ChannelHandlerContext ctx;

        public SyncReplCall(Request request, ChannelHandlerContext ctx) {

            this.request = request;
            this.ctx = ctx;
        }

        @Override
        public void run() {
            try {
                processParaList( request, ctx);
            } catch (Throwable th) {
                logger.error(th.getMessage(), th);
            }
        }

    }

}


text:
A super simple library to read or create [Swagger](http://swagger.io/) API documents.
This is the engine used in other gems to translate API definitions (grape, rails) into Swagger definitions.

Note: Only Swagger Version 2.0 of the spec is supported.

## Install

You can install the gem as

```
gem install ruby-swagger
```

or adding it to your bundle:

```
gem 'ruby-swagger'
```

and then

```
bundle install
```

If you are using ruby-swagger inside a Grape project, make sure the ruby-swagger is defined after grape in your gemfile.
If you have problem finding the extended methods, you can manually require it with:

```
require 'ruby-swagger'
require 'ruby-swagger/grape/grape'
```

and then bundle install.

## What you get

This gem provides mostly 2 independent services for your ruby swagger documentation.

1. It provides an object-oriented implementation of the [Swagger 2.0 Specification](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md) This part of the gem - under swagger/data - allows you to manipulate Swagger-2.0 documents in an object-oriented way

2. A set of tasks and grape extensions to convert your grape API documentation into a Swagger 2.0 documentation. Using these tasks you can:

  (a) extract, from the Grape API structure, a file system representation in YAML of your documentation.
This is not your final documentation (yet) but, similarly to Jakyll, you can now have other parties (technical writer) editing and maintaining
your documentation in a yaml-like version. These tasks allow you to maintain the YAML version of your documentation up-to-date with the Grape definition of your API.

  (b) extend the Grape syntax of the API defining OAuth2 scopes, errors, permissions, deprecation, etc. These extensions are read by this library
and included in your documentation

  (c) compile the Swagger 2.0 documentation from the YAML version of your documentation. This is the final artifact that you can deploy
under public/ or distribute in other ways (CDN on S3)

  (d) auto generate all the API clients by running the swagger-codegen task. You can distribute the API clients on public/ or using other ways (CDN on S3?)

  (e) you can automate a+b+c+d+e in your continuous deployment so your documentation and clients are always up-to-date

## Usage

Assuming you have included the gem into your Gemfile, you should see a new swagger: namespace into your rake tasks. For example, running `rake -T`:

```
...
rake swagger:compile_doc
rake swagger:compile_clients:...
rake swagger:grape:generate_doc[base_class]
...
```

### Extracting the documentation from your Grape API

You can run the command

```
rake swagger:grape:generate_doc[base_class]
```

where base_class is the root class of your API definition in Grape.

For example, if all your API is mounted into a "APIBase" class:

```
rake swagger:grape:generate_doc[ApiBase]
```

will extract all the documentation from all the routes coming from that base class.

This task will create by default a new directory structure under ./doc/swagger - this directory will contain all the YAML documentation of your project.

See below for the structure.

#### YAML documentation structure

Your documentation will be structured in a set of YAML files - you can edit parts of it. In the parts that you can edit, you can use the ERB syntax - for example: `host: <%= ENV['host'] %>`.

The ./doc/swagger is structured in the following way:

* ./doc/swagger/base_doc.yaml

  This file is written *only the first time* you execute the `rake swagger:grape:generate_doc` task and never overwritten. This file contains
all the basic information for your API: the author, contact information, license, base URL, version, security schemes, format, etc.
It is equivalent to the [basic object of Swagger](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
Once it is created is never updated by ruby-swagger tasks, so it is your duty to manually change any of the contact information, license, etc.

* ./doc/swagger/securityDefinitions.yaml

  This file is written *only the first time* you execute the `rake swagger:grape:generate_doc` task and never overwritten. This files contains the security
definitions of your API and it is equivalent to the [securityDefinitions object of swagger](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityDefinitionsObject)
Once it is created is never updated by ruby-swagger tasks, so it is your duty to manually change any of the contact information, license, etc.

* ./doc/swagger/scopes (folder)

  Define the OAuth2 scopes of the API (optional). This file gets regenerated by the `rake swagger:grape:generate_doc` task at each run. However, the description part is left untouched.

* ./doc/swagger/paths (folder)

  This folder contains a structure of subfolders that is 1-1 mapped with your API. Each folder represent a path component in your route.
Each file name is the verb whose that path is accessible from. The API version and API prefix is stripped when generating the file system structure.

  **Example #1**: if you have a GET API available at /api/v1/users/activity, you will have a ./doc/swagger/paths/users/activity/get.yaml file containing the documentation for that API method.

  **Example #2**: if you have a POST API method available at /api/v1/users, you will have a ./doc/swagger/paths/users/post.yaml file containing the documentation for that API method.

  Within each file there is the full definition of the API operation. When you execute the `rake swagger:grape:generate_doc` task,
some properties will be overwritten by the Grape documentation - some will not. This means you can edit the documentation from the YAML file
while the structural properties of the API are still reflecting the Grape definition.

  The following properties are NOT overwritten by the rake task:

  * summary
  * description

  Everything else gets regenerated by the rake task.

You can check in your ./doc/swagger structure in Github and have other parties work with you on the documentation.
You can regenerate / reupdate the documentation rerunning the `rake swagger:grape:generate_doc` task. You can have this task running as part of your continuous deployment or have it running as post git hook.

### Extracting the documentation from your Grape API

Assuming you have generated your documentation using `swagger:grape:generate_doc`, you can now compile the entire documentation into a valid
Swagger 2.0 file. You can do that by running the task

```
rake swagger:compile_doc
```

This task will read all the documentation definition under ./doc/swagger/ and produce a single swagger file under ./doc/swagger/swagger.json

This is your Swagger 2.0 documentation. You can now move this file under /public (if you want to distribute it like this) or upload it
on S3, CDN, etc. This is the live definition of your API.

Each time you run the `swagger:compile_doc task`, the swagger.json file is regenerated (overwritten). You can check in the swagger.json file under your version control system.

### Auto generate clients

You can use the `rake swagger:generate_client:all` task.

### Grape extensions

This gem includes a number of Grape DSL extensions and method helpers that you can use when defining your API.

#### The api_desc helper method

This helper method allows you to extend the "desc" method for Grape and let you define more context for your API method. This is an example of API
definition using the api_desc method (rather than the Grape desc method):

```ruby
    api_desc 'Retrieves applications list', { opt: 'a' } do
      detail 'This API does this and that and more'     #You can use GFM (Github Flavored Markdown) here
      headers authentication_headers.merge('X-Content' => {description: 'A custom header', type: 'String'})
      scopes %w(application:read application:write)     #You can use a string or an array of string
      tags 'applications'   # You can use a string or an array of string
      deprecated true       # Turn on the deprecation warning
      hidden false          # If true, it is excluded from the documentation
      api_name 'get_applications'   # A unique name for the API method. Used for autogenerating clients or doc
      response ApplicationEntity, root: 'applications', isArray: true, headers: result_headers
      errors std_errors.merge("418" => {entity: ErrorBoomEntity, description: "Yes, I am a teapot"})
    end
    params do
      ...
    end
    get '/' do
    ...
    end
```

The helper has the same syntax of the "desc" Grape method when defining an API operation.
It supports a short description as first parameter, an optional hash of parameters (where, for example, you can define which headers your API support) and a block.
The block extends your definition mapping it to your Swagger documentation. The allowed extensions in the api_desc block are:

  * **detail** String (in GFM format) - Set the documentation for the API method
  * **headers** Hash - A hash containing headers supported in the request
  * **deprecated** True|False - If set to true, the method will be marked as deprecated in the Swagger documentation. Default: false
  * **hidden** True|False - If set to true, the method will be excluded by the documentation
  * **scopes** String|Array of strings - Defines OAuth2 scopes the method will need to satisfy. Default: nil
  * **tags** String|Array of strings - List of tags used to organize your documentation. Default: nil
  * **api_name** String - A unique name for the API. Used in building the documentation or the auto-clients
  * **response** Entity and Hash - An object representing the expected result of the method when the operation is successful. You can optionally provide the root of the object and if the result is an array. You can also include the response headers. Default: nil
  * **errors** Hash - A key/value representation of the errors the method can raise. The key is an http error code, the value is an hash. The keys are: entity (the object used to incapuslate the error), description is the documentation of the error

#### The api_present helper method

If you are using the api_desc method, you can use the api_present helper in your API definition instead of using the present method.
For example:

```
    api_desc 'Retrieves applications list' do
      response ApplicationEntity, root: 'applications'
    end
    get '/' do
      api_present Application.all
    end
```

The api_present helper will take care of wrapping the Application model into an ApplicationEntity and use the 'applications' key root in the api response.

## Note on Patches/Pull Requests

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Submit a pull request.

## Help

If you have found a bug or you want to get in touch with us, write an email to <open@gild.com>.

## Special thanks

* [brennovich](https://github.com/brennovich)


text:
package jade.tools.logging.ontology;

//#J2ME_EXCLUDE_FILE

import jade.content.Concept;
import jade.util.leap.List;

public class LoggerInfo implements Concept {
	private String name;
	private int level;
	private List handlers;
	private String file;

	public LoggerInfo() {

	}

	public LoggerInfo(String name, int level) {
		setName(name);
		setLevel(level);
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getLevel() {
		return level;
	}

	public void setHandlers(List handlers) {
		this.handlers = handlers;
	}

	public List getHandlers() {
		return handlers;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getFile() {
		return file;
	}

	public String toString() {
		return name;
	}
}


text:
using System;
using System.Collections.ObjectModel;
using VkNet.Enums;
using VkNet.Model.Attachments;
using VkNet.Utils;

namespace VkNet.Model
{
	/// <summary>
	/// Информация о продукте.
	/// </summary>
	[Serializable]
	public class Market:IVkModel
	{
		/// <summary>
		/// Идентификатор
		/// </summary>
		public long Id { get; set; }

		/// <summary>
		/// Идентификатор владельца товара
		/// </summary>
		public long? OwnerId { get; set; }

		/// <summary>
		/// Название товара
		/// </summary>
		public string Title { get; set; }

		/// <summary>
		/// Текст описания товара
		/// </summary>
		public string Description { get; set; }

		/// <summary>
		/// Цена
		/// </summary>
		public Price Price { get; set; }

		/// <summary>
		/// Категория товара
		/// </summary>
		public MarketCategory MarketCategory { get; set; }

		/// <summary>
		/// URL изображения-обложки товара
		/// </summary>
		public Uri ThumbPhoto { get; set; }

		/// <summary>
		/// Дата создания товара в формате Unixtime.
		/// </summary>
		public DateTime? Date { get; set; }

		/// <summary>
		/// Статус доступности товара
		/// </summary>
		public ProductAvailability Availability { get; set; }

		/// <summary>
		/// Изображения товара
		/// </summary>
		public ReadOnlyCollection<Photo> Photos { get; set; }

		/// <summary>
		/// Возможность комментировать товар для текущего пользователя
		/// </summary>
		public bool? CanComment { get; set; }

		/// <summary>
		/// Возможность сделать репост товара для текущего пользователя
		/// </summary>
		public bool? CanRepost { get; set; }

		/// <summary>
		/// Информация об отметках «Мне нравится»
		/// </summary>
		public Likes Likes { get; set; }

		/// <summary>
		/// Разобрать из json.
		/// </summary>
		/// <param name="response">Ответ сервера.</param>
		/// <returns></returns>
		internal static Market FromJson(VkResponse response)
		{
			var result = new Market
			{
				Id = response["id"] ?? -1,
				OwnerId = response["owner_id"],
				Title = response["title"],
				Description = response["description"],
				Price = response["price"],
				MarketCategory = response["category"],
				ThumbPhoto = response["thumb_photo"],
				Date = response["date"],
				Availability = response["availability"],
				Photos = response["photos"].ToReadOnlyCollectionOf<Photo>(x => x),
				CanComment = response["can_comment"],
				CanRepost = response["can_repost"],
				Likes = response["likes"]
			};

			return result;
		}

		/// <summary>
		/// Преобразовать из JSON
		/// </summary>
		/// <param name="response">Ответ от сервера.</param>
		/// <returns></returns>
		IVkModel IVkModel.FromJson(VkResponse response)
		{
			return FromJson(response);
		}
	}
}


text:
'use strict';
var utils = require('../utils');
var features = require('../features');
var validator = require('validator');
var custom = require('../custom');
var sendy = require('../addons/sendy');
var Observable = utils.Observable;
var userModel;

module.exports = Observable.extend({
  constructor: function UserHandler(sandbox) {
    Observable.apply(this, arguments);

    this.models = sandbox.models;
    userModel = sandbox.models.user;
    this.mailer = sandbox.mailer;
    this.helpers = sandbox.helpers;

  },

  updateLastSeen: function (req, res, next) {
    if (req.session.user) {
      // just touch the last_seen field
      userModel.updateOwnershipData(req.session.user.name, {
        last_seen: new Date() // jshint ignore:line
      }, function () {});
    }
    next();
  },

  saveVanityURL: function (req, res) {
    userModel.saveBookmark(req.session.user, req.bin, 'vanity', function (err) {
      if (err) {
        return res.send(500, err);
      }
      res.send({ ok: true });
    });
  },

  loadVanityURL: function (req, res, next) {
    if (req.subdomain) {
      if (custom[req.subdomain]) {
        return next('route');
      }
      // test if this is a user with vanity feature
      userModel.load(req.subdomain, function (error, user) {
        if (error) {
          return next('route');
        }

        if (features('vanity', { session: { user: user }})) {
          // do magic
          userModel.getBookmark(user, 'vanity', function (err, data) {
            if (err || data.length === 0) {
              if (err) {
                console.error(err);
              }
              return res.redirect(req.app.get('url full'));
            }

            req.params.rev = data[0].revision;
            req.params.bin = data[0].url;

            req.params.quiet = 'quiet';
            next();
          });
        } else {
          return res.redirect(req.app.get('url full'));
        }
      }.bind(this));
    } else {
      next('route');
    }
  },

  validateRegister: function (req, res, next) {
    var username  = req.param('username');
    var email = req.param('email').trim();
    var key = req.param('key');
    var flagged = req.param('flagged') || false;
    var missingValues = [];
    var user = {
      name: username,
      email: email,
      flagged: flagged,
      key: key,
    };

    if (!username || !key || !email) {
      for (var param in user) {
        if (!user[param]) {
          missingValues.push(param);
        }
      }

      missingValues = missingValues.reduce(function(str, val, i, arr){
          return str += val + (i < arr.length -1 ? ', ' : '.');
        }, '');

      req.error = {
        ok: false,
        message: 'Missing username or password',
        raw: 'Missing values for ' + missingValues,
        status: 400
      };

      // Not enough details
      return next();
    }

    var reg = /^[a-zA-Z0-9_\-]+$/;
    if (!reg.test(username)) {
      req.error = {
        ok: false,
        message: 'Only numbers, letters, underscore and dash are allowed in the username.',
        raw: 'Character not allowed',
        status: 400
      };

      return next();
    }

    if (!validator.isEmail(email)) {
      req.error = {
        ok: false,
        message: 'Your email address doesn\'t look valid. Please try again.',
        raw: 'Invalid email',
        status: 400
      };

      return next();
    }

    if (req.app.settings.reserved.indexOf(username) !== -1) {
      req.error = {
        ok: false,
        message: 'Too late I\'m afraid, that username is taken.',
        status: 400
      };

      return next();
    }

    userModel.load(username, function (err, result) {
      if (result) {
        // Username taken
        req.error = {
          ok: false,
          message: 'Too late I\'m afraid, that username is taken.',
          status: 400
        };
        return next();
      }

      userModel.create(user, function (err, id) {
        if (err) {
          return next(err);
        }

        if (features('sendy') && email) {
          sendy.setSubscribed({
            name: username,
            email: email,
            id: id
          }, true);
        }

        // TODO send welcome email

        req.validatedUser = user;
        next();
      });
    });
  },

  validateLogin: function (req, res, next) {
    var username  = req.param('username');
    var key = req.param('key');

    userModel.load(username, function (err, user) {

      var validationComplete = function(err, validated){
        if (validated) {
          req.validatedUser = user;
        } else {
          req.error = {
            ok: false,
            message: 'No dice I\'m afraid, those details didn\'t work.',
            status: 401
          };
        }
        return next();
      };

      if (err || !user) {
        // we're returning failed details, but not indicating whether it's
        // username or password - this is on purpose.
        req.error = {
          ok: false,
          message: 'No dice I\'m afraid, those details didn\'t work.',
          status: 400
        };
        return next();
      }

      if (user.created && !!user.created.getTime) {//()) {
        userModel.valid(key, user.key, validationComplete);
      } else {
        // No created timestamp so this is an old password. Validate it then
        // update it to use the new algorithm.
        userModel.validOldKey(key, user.key, function(err, valid) {
          validationComplete = validationComplete.bind(null, err , valid);

          if (err || !valid) {
            return validationComplete();
          }

          // note that validationComplete is called with original `err, valid`
          // arguments that are part of *this* closure.
          userModel.upgradeKey(user.name, key, validationComplete);
        });

      }

    });

  }

});


text:
$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

// Toggle Development Assistance Helpers
$(document).ready(function() {
  $('[data-role="toggleGrid"]').click(function(e) {
    e.preventDefault();
    $('body').toggleClass('development-grid');
    if ($('body').hasClass('development-grid')) {
      $('.close-demo').css('display', 'block');
    } else {
      $('.close-demo').css('display', 'none');
    }
  });

  $('[data-role="toggleCodeframe"]').click(function(e) {
    e.preventDefault();
    $('body').toggleClass('development-codeframe');
    if ($('body').hasClass('development-codeframe')) {
      $('.close-demo').css('display', 'block');
    } else {
      $('.close-demo').css('display', 'none');
    }
  });

  $('.close-demo').click(function(e) {
    e.preventDefault();
    $('body').removeClass('development-codeframe');
    $('body').removeClass('development-grid');
    $(this).css('display', 'none');
  });
});


text:
package com.google.errorprone.bugpatterns.time;

import com.google.errorprone.CompilationTestHelper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link ProtoTimestampGetSecondsGetNano}.
 *
 * @author kak@google.com (Kurt Alfred Kluever)
 */
@RunWith(JUnit4.class)
@Ignore("b/130667208")
public class ProtoTimestampGetSecondsGetNanoTest {

  private final CompilationTestHelper compilationHelper =
      CompilationTestHelper.newInstance(ProtoTimestampGetSecondsGetNano.class, getClass());

  @Test
  public void testGetSecondsWithGetNanos() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static void foo(Timestamp timestamp) {",
            "    long seconds = timestamp.getSeconds();",
            "    int nanos = timestamp.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsWithGetNanosInReturnType() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.common.collect.ImmutableMap;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static int foo(Timestamp timestamp) {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    return timestamp.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsWithGetNanosInReturnType2() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.common.collect.ImmutableMap;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static ImmutableMap<String, Object> foo(Timestamp timestamp) {",
            "    return ImmutableMap.of(",
            "        \"seconds\", timestamp.getSeconds(), \"nanos\", timestamp.getNanos());",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsWithGetNanosDifferentScope() {
    // Ideally we would also catch cases like this, but it requires scanning "too much" of the class
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static void foo(Timestamp timestamp) {",
            "    long seconds = timestamp.getSeconds();",
            "    if (true) {",
            "      // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "      int nanos = timestamp.getNanos();",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsWithGetNanosInDifferentMethods() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static void foo(Timestamp timestamp) {",
            "    long seconds = timestamp.getSeconds();",
            "  }",
            "  public static void bar(Timestamp timestamp) {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = timestamp.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsOnly() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static void foo(Timestamp timestamp) {",
            "    long seconds = timestamp.getSeconds();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoOnly() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  public static void foo(Timestamp timestamp) {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = timestamp.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoInMethodGetSecondsInClassVariable() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  private static final long seconds = TIMESTAMP.getSeconds();",
            "  public static void foo() {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = TIMESTAMP.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsOnlyInStaticBlock() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  static {",
            "    long seconds = Timestamp.getDefaultInstance().getSeconds();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoOnlyInStaticBlock() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  static {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = Timestamp.getDefaultInstance().getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsOnlyInClassBlock() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  private final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  private final long seconds = TIMESTAMP.getSeconds();",
            "  private final int nanos = TIMESTAMP.getNanos();",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoOnlyInClassBlock() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "  private final int nanos = Timestamp.getDefaultInstance().getNanos();",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoInInnerClassGetSecondsInMethod() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  public static void foo() {",
            "    long seconds = TIMESTAMP.getSeconds();",
            "    Object obj = new Object() {",
            "      @Override public String toString() {",
            "        // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "        return String.valueOf(TIMESTAMP.getNanos()); ",
            "      }",
            "    };",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoInInnerClassGetSecondsInClassVariable() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  long seconds = TIMESTAMP.getSeconds();",
            "  Object obj = new Object() {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    long nanos = TIMESTAMP.getNanos();",
            "  };",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoInMethodGetSecondsInLambda() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  public static void foo() {",
            "    Runnable r = () -> TIMESTAMP.getSeconds();",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = TIMESTAMP.getNanos();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetSecondsInLambda() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "import java.util.function.Supplier;",
            "public class TestCase {",
            "  private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  public void foo() {",
            "    doSomething(() -> TIMESTAMP.getSeconds());",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    int nanos = TIMESTAMP.getNanos();",
            "  }",
            "  public void doSomething(Supplier<Long> supplier) {",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetNanoInLambda() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.protobuf.Timestamp;",
            "public class TestCase {",
            "  private static final Timestamp TIMESTAMP = Timestamp.getDefaultInstance();",
            "  public static void foo() {",
            "    // BUG: Diagnostic contains: ProtoTimestampGetSecondsGetNano",
            "    Runnable r = () -> TIMESTAMP.getNanos();",
            "    long seconds = TIMESTAMP.getSeconds();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testGetMessageGetSecondsGetNanos() {
    compilationHelper
        .addSourceLines(
            "test/TestCase.java",
            "package test;",
            "import com.google.errorprone.bugpatterns.time.Test.DurationTimestamp;",
            "public class TestCase {",
            "  public static void foo(DurationTimestamp durationTimestamp) {",
            "    long seconds = durationTimestamp.getTestTimestamp().getSeconds();",
            "    int nanos = durationTimestamp.getTestTimestamp().getNanos();",
            "  }",
            "}")
        .doTest();
  }
}


text:
package org.cometd.client.ext;

import java.util.HashMap;
import java.util.Map;

import org.cometd.bayeux.Message.Mutable;
import org.cometd.bayeux.client.ClientSession;
import org.cometd.bayeux.client.ClientSession.Extension;

public class TimesyncClientExtension extends Extension.Adapter
{
    private volatile int _lag;
    private volatile int _offset;

    @Override
    public boolean rcvMeta(ClientSession session, Mutable message)
    {
        Map<String, Object> ext = message.getExt(false);
        if (ext != null)
        {
            @SuppressWarnings("unchecked")
            Map<String, Object> sync = (Map<String, Object>)ext.get("timesync");
            if (sync != null)
            {
                long now = System.currentTimeMillis();

                final long tc = ((Number)sync.get("tc")).longValue();
                final long ts = ((Number)sync.get("ts")).longValue();
                final int p = ((Number)sync.get("p")).intValue();
                // final int a=((Number)sync.get("a")).intValue();

                int l2 = (int)((now - tc - p) / 2);
                int o2 = (int)(ts - tc - l2);

                _lag = _lag == 0 ? l2 : (_lag + l2) / 2;
                _offset = _offset == 0 ? o2 : (_offset + o2) / 2;
            }
        }

        return true;
    }

    @Override
    public boolean sendMeta(ClientSession session, Mutable message)
    {
        Map<String, Object> ext = message.getExt(true);
        long now = System.currentTimeMillis();
        Map<String, Object> timesync = new HashMap<>(3);
        timesync.put("tc", now);
        timesync.put("l", _lag);
        timesync.put("o", _offset);
        ext.put("timesync", timesync);
        return true;
    }

    public int getOffset()
    {
        return _offset;
    }

    public int getLag()
    {
        return _lag;
    }

    public long getServerTime()
    {
        return System.currentTimeMillis() + _offset;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type language="gradle" name="org.gradle.api.artifacts.PublishException" version="3.0" superType="org.gradle.api.GradleException">
    <description>
A PublishException is thrown when a dependency configuration cannot be published for some reason.

</description>
</type>


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "date".
 *
 * @property string $id
 * @property integer $seconds
 * @property integer $minutes
 * @property integer $hours
 * @property integer $number_day
 * @property integer $number_weeks_day
 * @property integer $number_month
 * @property integer $year
 * @property integer $number_years_day
 * @property string $weekday
 * @property string $month
 * @property string $unix_time
 * @property string $event
 * @property string $persona_id
 *
 * @property Person $persona
 */
class Date extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'date';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['seconds', 'minutes', 'hours', 'number_day', 'number_weeks_day', 'number_month', 'year', 'number_years_day', 'weekday', 'month', 'unix_time', 'event', 'persona_id'], 'required'],
            [['seconds', 'minutes', 'hours', 'number_day', 'number_weeks_day', 'number_month', 'year', 'number_years_day', 'unix_time', 'persona_id'], 'integer'],
            [['weekday', 'month'], 'string', 'max' => 17],
            [['event'], 'string', 'max' => 71],
            [['persona_id'], 'exist', 'skipOnError' => true, 'targetClass' => Person::className(), 'targetAttribute' => ['persona_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'seconds' => Yii::t('app', 'Seconds'),
            'minutes' => Yii::t('app', 'Minutes'),
            'hours' => Yii::t('app', 'Hours'),
            'number_day' => Yii::t('app', 'Number Day'),
            'number_weeks_day' => Yii::t('app', 'Number Weeks Day'),
            'number_month' => Yii::t('app', 'Number Month'),
            'year' => Yii::t('app', 'Year'),
            'number_years_day' => Yii::t('app', 'Number Years Day'),
            'weekday' => Yii::t('app', 'Weekday'),
            'month' => Yii::t('app', 'Month'),
            'unix_time' => Yii::t('app', 'Unix Time'),
            'event' => Yii::t('app', 'Event'),
            'persona_id' => Yii::t('app', 'Persona ID'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPersona()
    {
        return $this->hasOne(Person::className(), ['id' => 'persona_id']);
    }

    /**
     * @inheritdoc
     * @return \app\models\query\DateQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\models\query\DateQuery(get_called_class());
    }
}


text:
from direct.task import Task
from toontown.hood import ZoneUtil
from toontown.toonbase import ToontownGlobals

class ToontownAccess:
    def __init__(self):
        self.startupModules = []

    def initModuleInfo(self):
        self.startupModules = self.getModuleList()
        taskMgr.doMethodLater(300, self.checkModuleInfo, 'moduleListTask')

    def delete(self):
        taskMgr.remove('moduleListTask')
        del self.startupModules

    def checkModuleInfo(self, task):
        currentModuleList = self.getModuleList()
        newModules = []
        for module in currentModuleList:
            if module not in self.startupModules:
                self.startupModules.insert(0, module)
                newModules.insert(0, module)

        self.sendUpdate('setModuleInfo', [newModules])
        return task.again

    def getModuleList(self):
        # TODO: This funciton is supposed to return a list of all modules that
        # have been linked into the process at runtime. It is only needed for
        # hack detect.
        return []

    def sendUpdate(self, fieldName, args = [], sendToId = None):
        if base.cr and hasattr(base, 'localAvatar'):
            dg = base.localAvatar.dclass.clientFormatUpdate(fieldName, sendToId or base.localAvatar.doId, args)
            base.cr.send(dg)

    def canAccess(self, zoneId=None):
        return True


text:
namespace Elements
{
    public class Comment : Element
    {
        private string contents;

        public string Contents
        {
            get
            {
                return this.contents;
            }
        }

        public Comment(CharacterBuffer buffer)
        {
            //this.Image = ImageType.Comment;
            this.Start = buffer.IndexInOriginalBuffer;
            do
            {
                if (buffer.IsAtEnd)
                {
                    break;
                }
                buffer.MoveNext();
            }
            while (buffer.CurrentCharacter != '\n');
            this.End = buffer.IndexInOriginalBuffer;
            this.Literal = buffer.Substring(this.Start - buffer.Offset, this.End - this.Start);
            this.contents = this.Literal.Remove(0, 1).Trim();
            this.Description = string.Concat("Comment: ", this.contents);
            buffer.MoveNext();
        }
    }
}