text:
namespace boost
{
namespace hana
{
namespace traits
{
inline namespace ASTImplementation
{
//
// Convenience template for generating predicates.
//
template <bool c>
using truthiness = std::conditional_t<c, std::true_type, std::false_type>;

//
// Quick check to see if a series of zero or more bools all evaluate to true.
//
template <bool... bs>
struct AllTrue
{
  static constexpr auto value = (bs&&...);
};

//
// See if each Ts is derived from Base.
//
//template <typename Base, typename... Ts>
//using all_derived_from = AllTrue<std::is_base_of<Base,Ts>::value...>;

struct PAST {
};

template <class T>
struct IsTraits {
};
template <template <class... T> class TC>
struct IsTraits<detail::hana_trait<TC>> {
  typedef int type;
};
template <class T>
using TraitsType = typename IsTraits<std::remove_cv_t<T>>::type;

}  // namespace ASTImplementation

template <class T>
constexpr bool isTraits = is_detected<TraitsType, T>::value;
template <typename... T>
using AllPAstImpl = AllTrue<(isTraits<T> || std::is_base_of<PAST, T>::value)...>;
template <typename... T>
using AllPAst = std::enable_if_t<AllPAstImpl<T...>::value, void**>;
//
// The language consists of type predicate leaves
// the binary operators &, |, and ^ (and, or, and exclusive or),
// and ! (negation).
//
// We use the compiler's parser to parse the expressions so (of course)
// the precedence and associativity match those of C++.
//
// We leverage the compiler's symbol table to build our compile-time
// ASTs and evaluate them with compile-time template arguments.
//
// This facility produces no runtime executable code.

//====================
// AST leaf nodes:
//     a) ids that wrap a predicate template that can be specilaized with one typename
//     b) binders that bind an argument of a binary predicate to produce an id

// An identifier type that wraps a predicate template.  The template
// takes a typename and passes judgement on it at compile time.
//
// Note use of variadic template template to allow predicates that take trailing defaults.
//
template <template <typename...> class Pred>
struct Id : PAST {
  template <typename T>
  static constexpr bool eval()
  {
    return Pred<T>::value;
  }
};
template <template <typename...> class Pred>
constexpr auto pred()
{
  return Id<Pred>();
}

template < class BPred, typename First>
struct BindT1st : PAST {
  template <typename Second>
  constexpr bool operator()(Second s)const
  {
    BPred b = {};
    First f = {};
    return b(f, s);
  }
};
template <class BPred, typename First,  AllPAst<BPred> = nullptr>
constexpr auto bind1st(BPred, First)
{
  return BindT1st<BPred, First>();
}
template < class BPred, typename Second>
struct BindT2nd : PAST {
  template <typename First>
  constexpr bool operator()(First f)const
  {
    BPred b = {};
    Second s = {};
    return b(f, s);
  }
};
template <class BPred, typename Second, AllPAst<BPred> = nullptr>
constexpr auto bind2nd(BPred, Second)
{
  return BindT2nd<BPred, Second>();
}

namespace detail {
struct Base{};

template <typename P1, typename P2>
struct And : PAST {
  template<class T>
  constexpr bool operator()(T t)const
  {
    P1 p1 = {};
    P2 p2 = {};
    return p1(t)&p2(t);
  }
};
template <typename P1, typename P2, AllPAst<P1, P2> = nullptr>
constexpr auto operator&(P1, P2)
{
  And<P1, P2> a = {};
  return a;
}

template <typename P1, typename P2>
struct Or : PAST {
  template<class T>
  constexpr bool operator()(T t)const
  {
    P1 p1 = {};
    P2 p2 = {};
    return p1(t)|p2(t);
  }
};
template <typename P1, typename P2, AllPAst<P1, P2> = nullptr>
constexpr auto operator|(P1, P2)
{
  Or<P1, P2> a = {};
  return a;
}
template <typename P1, typename P2>
struct Xor : PAST {
  template<class T>
  constexpr bool operator()(T t)const
  {
    P1 p1 = {};
    P2 p2 = {};
    return p1(t)^p2(t);
  }
};
template <typename P1, typename P2, AllPAst<P1, P2> = nullptr>
constexpr auto operator^(P1, P2)
{
  Xor<P1, P2> a = {};
  return a;
}
template <typename P>
struct Not : PAST {
  template<class T, AllPAst<P> = nullptr >
  constexpr bool operator()(T t)const
  {
    P p = {};
    return p(t)?0:1;
  }
};
template <typename P, AllPAst<P> = nullptr>
constexpr auto operator!(P)
{
  return Not<P>();
}
}

// Another way to evaluate an AST object.  In addition to
//     ast.eval<T>()
// this provides the syntax
//     satisfies<T>(ast)
//
// Can also check multiple arguments against the constraint:
//    satisfies<T1, T2, T3>(ast)
//
template <typename... Ts, typename AST, AllPAst<AST> = nullptr>
constexpr bool satisfies(AST)
{
  return AllTrue<AST()(hana::type_c<Ts>)...>::value;
}

// For convenience with SFINAE applications.
// Uses an AST type:
//    Constraint<AST, T>
// checks whether T satisfies the constraints described by AST.
// The result is either void or represents no type.
//
// Can test multiple arguments against the constraint:
//    Constraint<AST, T1, T2, T3>
//
template <typename AST, typename... Ts>
using Constraint = std::enable_if_t<satisfies<Ts...>(AST()), void **>;

// A bool SFINAE constraint.
// Uses an AST object rather than a type.  Same syntax as "satisfies,"
// but result is either true or produces no result.
// Implementation of constraint inspired by example in
// http://en.cppreference.com/w/cpp/language/sfinae
//
template <typename... Ts, typename AST, bool test = AllTrue<AST()(hana::type_c<Ts>)...>::value>
constexpr bool constraint(AST, char (*)[test == true] = nullptr)
{
  return true;
}

//
// Handy but optional names to use as "trailing distinguishers" for
// overloaded member templates that are otherwise identical.
//
template <std::size_t>
struct Ignore {
};
constexpr bool ignore(std::size_t) { return true; }
}  // namespace traits
}  // namespace hana
}  // namespace boost
#endif


text:
<?php

namespace Delatbabel\ViewPages\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

/**
 * Validate Request for Carousel Image form
 *
 * Class CarouselImageFormRequest
 */
class CarouselImageFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rule = [
            'carousels'       => 'required',
            'name'            => 'required',
            'path'            => 'required_without_all:use_html,path_original|mimes:jpg,jpeg,jpe,png,gif',
            'url'             => 'url',
            'displaying_time' => 'required|numeric',
            'html'            => 'required_with:use_html'

        ];
        return $rule;
    }

    /**
     * Custom nice name
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'path' => 'image',
            'url'  => 'link'
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'readline'
require_relative "client"

channel_name = ARGV.shift
unless channel_name
  abort "Uso: #{$PROGRAM_NAME} nome_do_canal"
end

prompt = "#{channel_name} >"

client = Client.new(channel_name)
client.subscribe!

Thread.new do
  loop do
    message = client.receive_message
    puts "\n#{message}"
    Readline.refresh_line
  end
end

stty_save = `stty -g`.chomp
trap('INT') { puts; system('stty', stty_save); exit }

while content = Readline.readline(prompt, true)
  next if content.empty?

  if content == "LIST"
    client.request_list
  else
    client.publish(content)
  end
end


text:
<?php if (!defined('IDIR')) { die; }

/**
* vb3 Import Polls
*
* @package 		ImpEx.vb3
*
*/
class vb3_010 extends vb3_000
{
	var $_dependent 	= '008';

	function vb3_010(&$displayobject)
	{
		$this->_modulestring = $displayobject->phrases['import_poll'];
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_polls'))
				{
					$displayobject->display_now("
{$displayobject->phrases['poll_restart_ok']}
");
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error(substr(get_class($this) , -3), $displayobject->phrases['poll_restart_failed'], $displayobject->phrases['check_db_permissions']);
				}
			}

			// Start up the table
			$displayobject->update_basic('title', $displayobject->phrases['import_poll']);
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_table_header($displayobject->phrases['import_poll']));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code($displayobject->phrases['polls_per_page'],'pollperpage',50));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'], $displayobject->phrases['reset']));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('pollstartat','0');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description("
{$displayobject->phrases['dependant_on']} " . $sessionobject->get_module_title($this->_dependent) . " {$displayobject->phrases['cant_run']} ."));
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'],''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		// Set up working variables.
		$displayobject->update_basic('displaymodules','FALSE');
		$target_database_type 	= $sessionobject->get_session_var('targetdatabasetype');
		$target_table_prefix  	= $sessionobject->get_session_var('targettableprefix');
		$source_database_type 	= $sessionobject->get_session_var('sourcedatabasetype');
		$source_table_prefix  	= $sessionobject->get_session_var('sourcetableprefix');

		$poll_start_at 		= $sessionobject->get_session_var('pollstartat');
		$poll_per_page 		= $sessionobject->get_session_var('pollperpage');

		$class_num				= substr(get_class($this), -3);
		$displayobject->update_basic('displaymodules','FALSE');

		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		if(intval($poll_per_page) == 0)
		{
			$poll_per_page = 10;
		}

		$poll_array	= $this->get_details($Db_source, $source_database_type, $source_table_prefix, $poll_start_at, $poll_per_page, 'poll', 'pollid');
		$thread_ids = $this->get_threads_ids($Db_target, $target_database_type, $target_table_prefix);

		$displayobject->display_now("
{$displayobject->phrases['importing']} " . count($poll_array) . " {$displayobject->phrases['polls']}

{$displayobject->phrases['from']} : " . $poll_start_at . " ::  {$displayobject->phrases['to']} : " . ($poll_start_at + count($poll_array)) . "
");

		$poll_object = new ImpExData( $Db_target, $sessionobject,'poll');

		$start = time();
		foreach ($poll_array as $poll_id => $details)
		{
			$try = (phpversion() < '5' ? $poll_object : clone($poll_object));

			// Mandatory
			$try->set_value('mandatory', 'question',			$details['question']);
			$try->set_value('mandatory', 'dateline',			$details['dateline']);
			$try->set_value('mandatory', 'options',				$details['options']);
			$try->set_value('mandatory', 'votes',				$details['votes']);
			$try->set_value('mandatory', 'importpollid',		$poll_id);

			// Non Mandatory
			$try->set_value('nonmandatory', 'active',			$details['active']);
			$try->set_value('nonmandatory', 'numberoptions',	$details['numberoptions']);
			$try->set_value('nonmandatory', 'timeout',			$details['timeout']);
			$try->set_value('nonmandatory', 'multiple',			$details['multiple']);
			$try->set_value('nonmandatory', 'voters',			$details['voters']);
			$try->set_value('nonmandatory', 'public',			$details['public']);

			$result = $try->import_poll($Db_target,$target_database_type,$target_table_prefix);

			$vb_poll_id = $Db_target->insert_id();

			if($try->is_valid())
			{
				if($result)
				{
					if($try->import_poll_to_vb3_thread($Db_target, $target_database_type, $target_table_prefix, $vb_poll_id, $poll_id))
					{
						$displayobject->display_now('
' . $try->how_complete() . '% ' . $displayobject->phrases['poll'] . ' -> ' . $try->get_value('mandatory', 'question'));
						$sessionobject->add_session_var($class_num . '_objects_done', intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1);
					}
					else
					{
						$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
						$sessionobject->add_error($poll_id, $displayobject->phrases['poll_not_imported_3'], $displayobject->phrases['poll_not_imported_rem']);
						$displayobject->display_now("
{$displayobject->phrases['failed']} :: {$displayobject->phrases['poll_not_imported']}");
					}
				}
				else
				{

					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
					$sessionobject->add_error($poll_id, $displayobject->phrases['poll_not_imported_2'], $displayobject->phrases['poll_not_imported_rem']);
					$displayobject->display_now("
{$displayobject->phrases['failed']} :: {$displayobject->phrases['poll_not_imported_2']}");
				}
			}
			else
			{
				$displayobject->display_now("
{$displayobject->phrases['invalid_object']}" . $try->_failedon);
				$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
			}
			unset($try);
		}

		if (count($poll_array) == 0 OR count($poll_array) < $poll_per_page)
		{
			$sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit'));
			$sessionobject->remove_session_var($class_num . '_start');

			$displayobject->update_html($displayobject->module_finished($this->_modulestring,
				$sessionobject->return_stats($class_num, '_time_taken'),
				$sessionobject->return_stats($class_num, '_objects_done'),
				$sessionobject->return_stats($class_num, '_objects_failed')
			));

			$sessionobject->set_session_var($class_num ,'FINISHED');
			$sessionobject->set_session_var('module','000');
			$sessionobject->set_session_var('autosubmit','0');
			$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
		}

		$sessionobject->set_session_var('pollstartat',$poll_start_at+$poll_per_page);
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}
}
/*======================================================================*\
|| ####################################################################
|| # Downloaded: [#]zeveuilddate[#]
|| # CVS: $RCSfile$ - $Revision: $
|| ####################################################################
\*======================================================================*/
?>


text:
{-

Playing with lens zippers, to understand how they can be used to
manage a Data.Tree

-}
import Control.Lens
import Control.Lens.Zipper
import Data.Tree
import Data.Tree.Lens

-- ---------------------------------------------------------------------

tree1 =
    Node "a"
      [Node "aa" []
      ,Node "ab"
         [Node "aba" []
         ,Node "abb" []
         ]
      ]

-- Attempt: in tree1, go down to [aa,ab], then down to focus on aba
eg2 = zipper tree1
    & downward  branches -- focus is now [aa,ab]
    & fromWithin traverse
    & rightmost

-- p2 = view focus eg2

-- ------------------------
-- Data.Tree.Lens provides

-- root :: Lens' (Tree a) a
-- branches :: Lens' (Tree a) [Tree a]
--
-- The branches are a list,

------------------------------------------------------------------------
-- Utilities to show a forest/tree in ghci

df = putStrLn . drawForest
dt = putStrLn . drawTree


text:
title: "Note for 2020-08-18T21:19:33"
permalink: "/notes/2020/08/18/21-19/"
date: "2020-08-18T09:19:33Z"
meta: "note posted on 2020-08-18T21:19:33"
tags:
- design
- syndicated
syndicationTargets:
- Twitter
---
Bought myself a new dot grid moleskin to design my website on. I find when I step back from the computer my creativity isn't bound by constraints and my mind can wonder to interesting places


text:
import moduleBank from './moduleBank';

export default function entities(state = {}, action) {
  return {
    moduleBank: moduleBank(state.moduleBank, action),
  };
}


text:
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;

ENREGISTRER_PROBLEME(110, "Diophantine reciprocals II") {
    // In the following equation x, y, and n are positive integers.
    //
    //                                          1/x + 1/y = 1/n
    //
    // It can be verified that when n = 1260 there are 113 distinct solutions and this is the least value of n for which
    // the total number of distinct solutions exceeds one hundred.
    //
    // What is the least value of n for which the number of distinct solutions exceeds four million?
    //
    // NOTE: This problem is a much more difficult version of Problem 108 and as it is well beyond the limitations of a
    // brute force approach it requires a clever implementation.
    nombre limite = 4000000;

    vecteur premiers;
    premiers::crible23<nombre>(limite * 3, std::back_inserter(premiers));

    nombre solutions = 0;
    nombre resultat = 0;
    while (solutions <= limite) {
        resultat += 2036934900; // 2^2 * 3^2 * 5^2 * 7^2 * 11 * 13 * 17

        std::map<nombre, size_t> decomposition;
        arithmetique::decomposition(resultat, premiers, decomposition);

        solutions = 1;
        for (auto d: decomposition)
            solutions *= (2 * d.second + 1);

        solutions /= 2;
    }

    return std::to_string(resultat);
}


text:
package io.gatling.http.action.async.sse

import io.gatling.core.action.ActorBasedAction

trait SseAction extends ActorBasedAction {
  override val actorFetchErrorMessage = "Couldn't fetch open sse"
}


text:
// RDVTabBarController.h
// RDVTabBarController
//
// Copyright (c) 2013 Robert Dimitrov
//
// 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.

#import <UIKit/UIKit.h>
#import "RDVTabBar.h"

@protocol RDVTabBarControllerDelegate;

@interface RDVTabBarController : UIViewController <RDVTabBarDelegate>

/**
 * The tab bar controller's delegate object.
 */
@property (nonatomic, weak) id<RDVTabBarControllerDelegate> delegate;

/**
 * An array of the root view controllers displayed by the tab bar interface.
 */
@property (nonatomic, copy) IBOutletCollection(UIViewController) NSArray *viewControllers;

/**
 * The tab bar view associated with this controller. (read-only)
 */
@property (nonatomic, readonly) RDVTabBar *tabBar;

/**
 * The view controller associated with the currently selected tab item.
 */
@property (nonatomic, weak) UIViewController *selectedViewController;

/**
 * The index of the view controller associated with the currently selected tab item.
 */
@property (nonatomic) NSUInteger selectedIndex;

/**
 * A Boolean value that determines whether the tab bar is hidden.
 */
@property (nonatomic, getter=isTabBarHidden) BOOL tabBarHidden;

/**
 * Changes the visibility of the tab bar.
 */
- (void)setTabBarHidden:(BOOL)hidden animated:(BOOL)animated;

@end

@protocol RDVTabBarControllerDelegate <NSObject>
@optional
/**
 * Asks the delegate whether the specified view controller should be made active.
 */
- (BOOL)tabBarController:(RDVTabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;

/**
 * Tells the delegate that the user selected an item in the tab bar.
 */
- (void)tabBarController:(RDVTabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

@end

@interface UIViewController (RDVTabBarControllerItem)

/**
 * The tab bar item that represents the view controller when added to a tab bar controller.
 */
@property(nonatomic, setter = rdv_setTabBarItem:) RDVTabBarItem *rdv_tabBarItem;

/**
 * The nearest ancestor in the view controller hierarchy that is a tab bar controller. (read-only)
 */
@property(nonatomic, readonly) RDVTabBarController *rdv_tabBarController;

@end

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com


text:
package org.motechproject.server.service.impl;

import java.util.Date;

import org.motechproject.server.time.TimePeriod;
import org.openmrs.Patient;

public class ExpectedPNCMotherEncounterSchedule extends
		ExpectedEncounterSchedule {

	protected Integer maxDeliveryValue;
	protected TimePeriod maxDeliveryPeriod;

	@Override
	protected Date getReferenceDate(Patient patient) {
		return registrarBean.getCurrentDeliveryDate(patient);
	}

	@Override
	protected boolean validReferenceDate(Date referenceDate, Date currentDate) {
		Date maxDeliveryDate = calculateDate(referenceDate, maxDeliveryValue,
				maxDeliveryPeriod);
		return super.validReferenceDate(referenceDate, currentDate)
				&& !currentDate.after(maxDeliveryDate);
	}

	public Integer getMaxDeliveryValue() {
		return maxDeliveryValue;
	}

	public void setMaxDeliveryValue(Integer maxDeliveryValue) {
		this.maxDeliveryValue = maxDeliveryValue;
	}

	public TimePeriod getMaxDeliveryPeriod() {
		return maxDeliveryPeriod;
	}

	public void setMaxDeliveryPeriod(TimePeriod maxDeliveryPeriod) {
		this.maxDeliveryPeriod = maxDeliveryPeriod;
	}

}


text:
var express = require('express'),
    https = require('https'),
    fs = require('fs'),
    bodyParser = require('body-parser'),
    path = require('path'),
    cookieParser = require('cookie-parser'),
    _global = require('./global'),
    webpackServer = require('./webpack.server'),
    common = require('./common'),
    bll = require('./bll'),
    viewRoute = require('./routes/views'),
    mobileRoute = require('./routes/mobile'),
    apiRouter = require('./routes/api');

var app = express();
// !(global.__evn == 'prod') && webpackServer.use(app);
webpackServer.use(app);
app.set('view engine', 'jade');
app.set('views', 'views');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

//app.use(filter.permission);
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET,POST");
    res.header("X-Powered-By", ' 3.2.1');
    next();
})
app.use('/', viewRoute.main);
app.use('/article', viewRoute.article);
app.use('/user', viewRoute.user);
app.use('/category', viewRoute.category);
app.use('/api/article', apiRouter.article);
app.use('/api/user', apiRouter.user);
app.use('/api/category', apiRouter.category);
app.use('/api/comment', apiRouter.comment);
app.use('/mobile/article', mobileRoute.article);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'resource')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(function (req, res) {
    res.render('error', {
        title: '404',
        errorTitle: '404 Not Found',
        errorContent: '访问的页面暂时不存在,至于以后,以后再说,呵呵哒'
    });
});
app.listen(80, () => {
    console.log('my server is start,at port %d', 80);
});
const privateKey = fs.readFileSync(path.join(__dirname, 'ssl', 'server.key'), 'utf8');
const certificate = fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt'), 'utf8');
const credentials = {
    key: privateKey,
    cert: certificate
};
https.createServer(credentials, app).listen(443, () => {
    console.log('443 server start');
});

module.exports = app;


text:
<meta charset="UTF-8">
	<meta name="description" content="A collection of quirks in MadCapFlare, with workarounds">
  	<meta name="keywords" content="Flare, MadCap">
  	<meta name="author" content="http://starfallprojects.co.uk/">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .Site.Title }}</title>
<link href="https://fonts.googleapis.com/css?family=Share+Tech+Mono|Work+Sans:300" rel="stylesheet">
<link rel="stylesheet" href="{{ .Site.BaseURL }}/css/cssReset.css" />
<link rel="stylesheet" href="{{ .Site.BaseURL }}/css/styles.css" />


text:
#ifndef SkTLList_DEFINED
#define SkTLList_DEFINED

#include "SkTInternalLList.h"
#include "SkTypes.h"

template <typename T> class SkTLList;
template <typename T>
inline void* operator new(size_t, SkTLList<T>* list,
                          typename SkTLList<T>::Placement placement,
                          const typename SkTLList<T>::Iter& location);

/** Doubly-linked list of objects. The objects' lifetimes are controlled by the list. I.e. the
    the list creates the objects and they are deleted upon removal. This class block-allocates
    space for entries based on a param passed to the constructor.

    Elements of the list can be constructed in place using the following macros:
        SkNEW_INSERT_IN_LLIST_BEFORE(list, location, type_name, args)
        SkNEW_INSERT_IN_LLIST_AFTER(list, location, type_name, args)
    where list is a SkTLList<type_name>*, location is an iterator, and args is the paren-surrounded
    constructor arguments for type_name. These macros behave like addBefore() and addAfter().
*/
template <typename T>
class SkTLList : SkNoncopyable {
private:
    struct Block;
    struct Node {
        char fObj[sizeof(T)];
        SK_DECLARE_INTERNAL_LLIST_INTERFACE(Node);
        Block* fBlock; // owning block.
    };
    typedef SkTInternalLList<Node> NodeList;

public:

    class Iter;

    /** allocCnt is the number of objects to allocate as a group. In the worst case fragmentation
        each object is using the space required for allocCnt unfragmented objects. */
    SkTLList(int allocCnt = 1) : fCount(0), fAllocCnt(allocCnt) {
        SkASSERT(allocCnt > 0);
        this->validate();
    }

    ~SkTLList() {
        this->validate();
        typename NodeList::Iter iter;
        Node* node = iter.init(fList, Iter::kHead_IterStart);
        while (node) {
            SkTCast<T*>(node->fObj)->~T();
            Block* block = node->fBlock;
            node = iter.next();
            if (0 == --block->fNodesInUse) {
                for (int i = 0; i < fAllocCnt; ++i) {
                    block->fNodes[i].~Node();
                }
                sk_free(block);
            }
        }
    }

    T* addToHead(const T& t) {
        this->validate();
        Node* node = this->createNode();
        fList.addToHead(node);
        new (node->fObj) T(t);
        this->validate();
        return reinterpret_cast<T*>(node->fObj);
    }

    T* addToHead() {
        this->validate();
        Node* node = this->createNode();
        fList.addToHead(node);
        new (node->fObj) T;
        this->validate();
        return reinterpret_cast<T*>(node->fObj);
    }

    T* addToTail(const T& t) {
        this->validate();
        Node* node = this->createNode();
        fList.addToTail(node);
        new (node->fObj) T(t);
        this->validate();
        return reinterpret_cast<T*>(node->fObj);
    }

    T* addToTail() {
        this->validate();
        Node* node = this->createNode();
        fList.addToTail(node);
        new (node->fObj) T;
        this->validate();
        return reinterpret_cast<T*>(node->fObj);
    }

    /** Adds a new element to the list before the location indicated by the iterator. If the
        iterator refers to a nullptr location then the new element is added at the tail */
    T* addBefore(const T& t, const Iter& location) {
        return new (this->internalAddBefore(location)) T(t);
    }

    /** Adds a new element to the list after the location indicated by the iterator. If the
        iterator refers to a nullptr location then the new element is added at the head */
    T* addAfter(const T& t, const Iter& location) {
        return new (this->internalAddAfter(location)) T(t);
    }

    /** Convenience methods for getting an iterator initialized to the head/tail of the list. */
    Iter headIter() const { return Iter(*this, Iter::kHead_IterStart); }
    Iter tailIter() const { return Iter(*this, Iter::kTail_IterStart); }

    T* head() { return Iter(*this, Iter::kHead_IterStart).get(); }
    T* tail() { return Iter(*this, Iter::kTail_IterStart).get(); }
    const T* head() const { return Iter(*this, Iter::kHead_IterStart).get(); }
    const T* tail() const { return Iter(*this, Iter::kTail_IterStart).get(); }

    void popHead() {
        this->validate();
        Node* node = fList.head();
        if (node) {
            this->removeNode(node);
        }
        this->validate();
    }

    void popTail() {
        this->validate();
        Node* node = fList.head();
        if (node) {
            this->removeNode(node);
        }
        this->validate();
    }

    void remove(T* t) {
        this->validate();
        Node* node = reinterpret_cast<Node*>(t);
        SkASSERT(reinterpret_cast<T*>(node->fObj) == t);
        this->removeNode(node);
        this->validate();
    }

    void reset() {
        this->validate();
        Iter iter(*this, Iter::kHead_IterStart);
        while (iter.get()) {
            Iter next = iter;
            next.next();
            this->remove(iter.get());
            iter = next;
        }
        SkASSERT(0 == fCount);
        this->validate();
    }

    int count() const { return fCount; }
    bool isEmpty() const { this->validate(); return 0 == fCount; }

    bool operator== (const SkTLList& list) const {
        if (this == &list) {
            return true;
        }
        if (fCount != list.fCount) {
            return false;
        }
        for (Iter a(*this, Iter::kHead_IterStart), b(list, Iter::kHead_IterStart);
             a.get();
             a.next(), b.next()) {
            SkASSERT(b.get()); // already checked that counts match.
            if (!(*a.get() == *b.get())) {
                return false;
            }
        }
        return true;
    }
    bool operator!= (const SkTLList& list) const { return !(*this == list); }

    /** The iterator becomes invalid if the element it refers to is removed from the list. */
    class Iter : private NodeList::Iter {
    private:
        typedef typename NodeList::Iter INHERITED;

    public:
        typedef typename INHERITED::IterStart IterStart;
        //!< Start the iterator at the head of the list.
        static const IterStart kHead_IterStart = INHERITED::kHead_IterStart;
        //!< Start the iterator at the tail of the list.
        static const IterStart kTail_IterStart = INHERITED::kTail_IterStart;

        Iter() {}

        Iter(const SkTLList& list, IterStart start = kHead_IterStart) {
            INHERITED::init(list.fList, start);
        }

        T* init(const SkTLList& list, IterStart start = kHead_IterStart) {
            return this->nodeToObj(INHERITED::init(list.fList, start));
        }

        T* get() { return this->nodeToObj(INHERITED::get()); }

        T* next() { return this->nodeToObj(INHERITED::next()); }

        T* prev() { return this->nodeToObj(INHERITED::prev()); }

        Iter& operator= (const Iter& iter) { INHERITED::operator=(iter); return *this; }

    private:
        friend class SkTLList;
        Node* getNode() { return INHERITED::get(); }

        T* nodeToObj(Node* node) {
            if (node) {
                return reinterpret_cast<T*>(node->fObj);
            } else {
                return nullptr;
            }
        }
    };

    // For use with operator new
    enum Placement {
        kBefore_Placement,
        kAfter_Placement,
    };

private:
    struct Block {
        int fNodesInUse;
        Node fNodes[1];
    };

    size_t blockSize() const { return sizeof(Block) + sizeof(Node) * (fAllocCnt-1); }

    Node* createNode() {
        Node* node = fFreeList.head();
        if (node) {
            fFreeList.remove(node);
            ++node->fBlock->fNodesInUse;
        } else {
            Block* block = reinterpret_cast<Block*>(sk_malloc_throw(this->blockSize()));
            node = &block->fNodes[0];
            new (node) Node;
            node->fBlock = block;
            block->fNodesInUse = 1;
            for (int i = 1; i < fAllocCnt; ++i) {
                new (block->fNodes + i) Node;
                fFreeList.addToHead(block->fNodes + i);
                block->fNodes[i].fBlock = block;
            }
        }
        ++fCount;
        return node;
    }

    void removeNode(Node* node) {
        SkASSERT(node);
        fList.remove(node);
        SkTCast<T*>(node->fObj)->~T();
        if (0 == --node->fBlock->fNodesInUse) {
            Block* block = node->fBlock;
            for (int i = 0; i < fAllocCnt; ++i) {
                if (block->fNodes + i != node) {
                    fFreeList.remove(block->fNodes + i);
                }
                block->fNodes[i].~Node();
            }
            sk_free(block);
        } else {
            fFreeList.addToHead(node);
        }
        --fCount;
        this->validate();
    }

    void validate() const {
#ifdef SK_DEBUG
        SkASSERT((0 == fCount) == fList.isEmpty());
        SkASSERT((0 != fCount) || fFreeList.isEmpty());

        fList.validate();
        fFreeList.validate();
        typename NodeList::Iter iter;
        Node* freeNode = iter.init(fFreeList, Iter::kHead_IterStart);
        while (freeNode) {
            SkASSERT(fFreeList.isInList(freeNode));
            Block* block = freeNode->fBlock;
            SkASSERT(block->fNodesInUse > 0 && block->fNodesInUse < fAllocCnt);

            int activeCnt = 0;
            int freeCnt = 0;
            for (int i = 0; i < fAllocCnt; ++i) {
                bool free = fFreeList.isInList(block->fNodes + i);
                bool active = fList.isInList(block->fNodes + i);
                SkASSERT(free != active);
                activeCnt += active;
                freeCnt += free;
            }
            SkASSERT(activeCnt == block->fNodesInUse);
            freeNode = iter.next();
        }

        int count = 0;
        Node* activeNode = iter.init(fList, Iter::kHead_IterStart);
        while (activeNode) {
            ++count;
            SkASSERT(fList.isInList(activeNode));
            Block* block = activeNode->fBlock;
            SkASSERT(block->fNodesInUse > 0 && block->fNodesInUse <= fAllocCnt);

            int activeCnt = 0;
            int freeCnt = 0;
            for (int i = 0; i < fAllocCnt; ++i) {
                bool free = fFreeList.isInList(block->fNodes + i);
                bool active = fList.isInList(block->fNodes + i);
                SkASSERT(free != active);
                activeCnt += active;
                freeCnt += free;
            }
            SkASSERT(activeCnt == block->fNodesInUse);
            activeNode = iter.next();
        }
        SkASSERT(count == fCount);
#endif
    }

    // Support in-place initializing of objects inserted into the list via operator new.
    friend void* operator new<T>(size_t,
                                 SkTLList* list,
                                 Placement placement,
                                 const Iter& location);

    // Helpers that insert the node and returns a pointer to where the new object should be init'ed.
    void* internalAddBefore(Iter location) {
        this->validate();
        Node* node = this->createNode();
        fList.addBefore(node, location.getNode());
        this->validate();
        return node->fObj;
    }

    void* internalAddAfter(Iter location) {
        this->validate();
        Node* node = this->createNode();
        fList.addAfter(node, location.getNode());
        this->validate();
        return node->fObj;
    }

    NodeList fList;
    NodeList fFreeList;
    int fCount;
    int fAllocCnt;

};

// Use the below macros rather than calling this directly
template <typename T>
void *operator new(size_t, SkTLList<T>* list,
                   typename SkTLList<T>::Placement placement,
                   const typename SkTLList<T>::Iter& location) {
    SkASSERT(list);
    if (SkTLList<T>::kBefore_Placement == placement) {
        return list->internalAddBefore(location);
    } else {
        return list->internalAddAfter(location);
    }
}

// Skia doesn't use C++ exceptions but it may be compiled with them enabled. Having an op delete
// to match the op new silences warnings about missing op delete when a constructor throws an
// exception.
template <typename T>
void operator delete(void*,
                     SkTLList<T>*,
                     typename SkTLList<T>::Placement,
                     const typename SkTLList<T>::Iter&) {
    SK_CRASH();
}

#define SkNEW_INSERT_IN_LLIST_BEFORE(list, location, type_name, args) \
    (new ((list), SkTLList< type_name >::kBefore_Placement, (location)) type_name args)

#define SkNEW_INSERT_IN_LLIST_AFTER(list, location, type_name, args) \
    (new ((list), SkTLList< type_name >::kAfter_Placement, (location)) type_name args)

#define SkNEW_INSERT_AT_LLIST_HEAD(list, type_name, args) \
    SkNEW_INSERT_IN_LLIST_BEFORE((list), (list)->headIter(), type_name, args)

#define SkNEW_INSERT_AT_LLIST_TAIL(list, type_name, args) \
    SkNEW_INSERT_IN_LLIST_AFTER((list), (list)->tailIter(), type_name, args)

#endif


text:
Cadastro de Frequência

      <form action="<?= site_url('frequency/create'); ?>" method="post" class="form-group">

                  Nome
                  <input placeholder="Nome da Frequência..." type="text" class="form-control" name="frequency[frequency_description]"
                  required>

                  Quantidade de Parcelas
                  <input placeholder="Parcelas..." type="number" class="form-control" name="frequency[frequency_count]"
                  required>

                  <a class="btn btn-default" href="<?= site_url('frequency'); ?>"> Voltar
                  <button class="btn btn-success" type="submit"> Salvar</button>

      </form>


text:
Sequel.migration do
  change do
    create_view(:all_pacts,
      Sequel::Model.db[:pacts].select(Sequel[:pacts][:id], Sequel[:c][:id].as(:consumer_id), Sequel[:c][:name].as(:consumer_name),
      Sequel[:cv][:number].as(:consumer_version_number), Sequel[:cv][:order].as(:consumer_version_order),
      Sequel[:p][:id].as(:provider_id), Sequel[:p][:name].as(:provider_name),
      Sequel[:pacts][:json_content]).
      join(:versions, {:id => :version_id}, {:table_alias => :cv, implicit_qualifier: :pacts}).
      join(:pacticipants, {:id => :pacticipant_id}, {:table_alias => :c, implicit_qualifier: :cv}).
      join(:pacticipants, {:id => :provider_id}, {:table_alias => :p, implicit_qualifier: :pacts}))

    create_view(:latest_pact_consumer_version_orders,
      "select provider_id, consumer_id, max(consumer_version_order) as latest_consumer_version_order
      from all_pacts
      group by provider_id, consumer_id"
    )

    create_view(:latest_pacts,
      "select ap.*
      from all_pacts ap
      inner join latest_pact_consumer_version_orders lp
      on ap.consumer_id = lp.consumer_id
           and ap.provider_id = lp.provider_id
           and ap.consumer_version_order = latest_consumer_version_order"
    )
  end
end


text:
FactoryGirl.define do
  factory :phone_book_entry do
    sequence(:last_name) { |n| "Lastname #{n}" }
    sequence(:is_male) { |n| true }
    association :phone_book
  end
end


text:
package com.couchbase.lite.mockserver;

import com.couchbase.lite.Manager;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*

    Mock checkpoint response for a 201 PUT request to update the checkpoint

    {
       "id":"_local/7d3186e30a82a3312fc2c54098a25ce568cd7dfb",
       "ok":true,
       "rev":"0-1"
    }

 */
public class MockCheckpointPut implements SmartMockResponse {

    private String id;
    private String rev;
    private boolean isSticky;
    private long delayMs;

    private String getId() {
        return id;
    }

    private void setId(String id) {
        this.id = id;
    }

    private Map<String, Object> generateMap() {
        Map<String, Object> docMap = new HashMap<String, Object>();
        docMap.put("id", getId());
        docMap.put("ok", true); // ditto
        docMap.put("rev", generateNextRev());
        return docMap;
    }

    private String generateBody() {
        Map documentMap = generateMap();
        try {
            return Manager.getObjectMapper().writeValueAsString(documentMap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * If the rev is empty, then generate rev "0-1"
     * If the rev is "0-1", then generate rev "0-2"
     * etc..
     *
     * @return the next rev to use, with respect to this.rev
     */
    private String generateNextRev() {
        if (getRev() == null) {
            return "0-0001";
        } else {
            StringTokenizer st = new StringTokenizer(getRev(), "-");
            String beforeDash = st.nextToken();
            String afterDash = st.nextToken();
            int afterDashInt = Integer.parseInt(afterDash);
            afterDashInt += 1;
            afterDash = String.format("%s", afterDashInt);
            return String.format("%s-%s", beforeDash, afterDash);
        }
    }

    @Override
    public MockResponse generateMockResponse(RecordedRequest request) {

        MockResponse mockResponse = new MockResponse();

        if (request.getMethod().equals("PUT")) {

            // extract id from request
            // /db/_local/e11a8567a2ecaf27c52d02899fa82258a343d720 -> _local/e11a8567a2ecaf27c52d02899fa82258a343d720
            String path = request.getPath();
            String localDocId = "";
            Pattern pattern = Pattern.compile("/db/_local/(.*)");
            Matcher matcher = pattern.matcher(path);
            if (matcher.find()) {
                localDocId = matcher.group(1);
            } else {
                throw new RuntimeException(String.format("Could not extract local doc id from: %s", path));
            }

            // call setId
            setId(String.format("_local/%s", localDocId));

            // extract the _rev field from the request
            try {
                Map <String, Object> jsonMap = Manager.getObjectMapper().readValue(request.getUtf8Body(), Map.class);
                if (jsonMap.containsKey("_rev")) {
                    setRev((String)jsonMap.get("_rev"));
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            mockResponse.setBody(generateBody());
            MockHelper.set201OKJson(mockResponse);
            return mockResponse;

        } else if (request.getMethod().equals("GET")) {

            MockHelper.set404NotFoundJson(mockResponse);

        } else {
            throw new RuntimeException(String.format("Unexpected method: %s", request.getMethod()));
        }

        return mockResponse;

    }

    @Override
    public boolean isSticky() {
        return this.isSticky;
    }

    @Override
    public long delayMs() {
        return delayMs;
    }

    public void setSticky(boolean isSticky) {
        this.isSticky = isSticky;
    }

    public String getRev() {
        return rev;
    }

    public void setRev(String rev) {
        this.rev = rev;
    }

    public long getDelayMs() {
        return delayMs;
    }

    public void setDelayMs(long delayMs) {
        this.delayMs = delayMs;
    }
}


text:
package com.reason.dune;

import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.project.*;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.util.*;
import com.reason.*;
import org.jetbrains.annotations.*;

import java.util.*;
import java.util.regex.*;

public class OpamProcess {

    private static final Log LOG = Log.create("dune");
    private static final Pattern SEXP = Pattern.compile("\\(\"([^\"]+)\" \"([^\"]+)\"\\)");

    @FunctionalInterface
    public interface ProcessTerminated<T> {
        void run(@Nullable T data);
    }

    private final @NotNull Project m_project;

    public OpamProcess(@NotNull Project project) {
        m_project = project;
    }

    public void list(@NotNull Sdk odk, @NotNull ProcessTerminated<List<String[]>> onProcessTerminated) {
        ArrayList<String[]> installedLibs = new ArrayList<>();

        GeneralCommandLine cli =
                new GeneralCommandLine("opam", "list", "--installed", "--safe", "--color=never", "--switch=" + odk.getVersionString());
        cli.setRedirectErrorStream(true);

        OCamlExecutable executable = OCamlExecutable.getExecutable(odk);
        executable.patchCommandLine(cli, null, true, m_project);

        KillableProcessHandler processHandler;
        try {
            processHandler = new KillableProcessHandler(cli);
            processHandler.addProcessListener(new ProcessListener() {
                @Override
                public void startNotified(@NotNull ProcessEvent event) {
                }

                @Override
                public void processTerminated(@NotNull ProcessEvent event) {
                    onProcessTerminated.run(installedLibs);
                }

                @Override
                public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
                    if (ProcessOutputType.isStdout(outputType)) {
                        String text = event.getText().trim();
                        if (text.charAt(0) != '#') {
                            String[] split = text.split("\\s+", 3);
                            installedLibs.add(new String[]{split[0].trim(), split.length >= 2 ? split[1].trim() : "unknown", split.length >= 3 ? split[2].trim() : ""});
                        }
                    }
                }
            });
            processHandler.startNotify();
        } catch (ExecutionException e) {
            ORNotification.notifyError("Dune", "Can't run opam", e.getMessage(), null);
            installedLibs.add(new String[]{"Error", e.getMessage()});
            onProcessTerminated.run(installedLibs);
        }
    }

    public void env(@NotNull Sdk odk, @NotNull ProcessTerminated<Map<String, String>> onProcessTerminated) {
        Map<String, String> result = new HashMap<>();

        GeneralCommandLine cli = new GeneralCommandLine("opam", "config", "env", "--sexp", "--switch=" + odk.getVersionString());
        cli.setRedirectErrorStream(true);

        OCamlExecutable executable = OCamlExecutable.getExecutable(odk);
        executable.patchCommandLine(cli, null, true, m_project);

        KillableProcessHandler processHandler;
        try {
            processHandler = new KillableProcessHandler(cli);
            processHandler.addProcessListener(new ProcessListener() {
                @Override
                public void startNotified(@NotNull ProcessEvent event) {
                }

                @Override
                public void processTerminated(@NotNull ProcessEvent event) {
                    onProcessTerminated.run(result);
                }

                @Override
                public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
                    if (ProcessOutputType.isStdout(outputType)) {
                        String text = event.getText().trim();
                        Matcher matcher = SEXP.matcher(text);
                        if (matcher.matches()) {
                            String key = matcher.group(1);
                            String value = matcher.group(2);
                            result.put(key, value);
                        }
                    }
                }
            });
            processHandler.startNotify();
        } catch (ExecutionException e) {
            ORNotification.notifyError("Dune", "Can't run opam", e.getMessage(), null);
            onProcessTerminated.run(result);
        }
    }
}


text:
"use strict";

import { Vector } from './Vector';

export class Circle {
  constructor(public center: Vector,
  public radius : number) {
  }

  get area() : number { return this.radius * this.radius * Math.PI; }
  get perimeter() : number { return this.radius * 2 * Math.PI; }
  get circumference() : number { return this.perimeter; }
  get diameter() : number { return this.radius * 2; }
}


text:
package com.intellij.refactoring.typeCook.deductive.builder;

import com.intellij.psi.PsiType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.refactoring.typeCook.deductive.resolver.Binding;

/**
 * Created by IntelliJ IDEA.
 * User: db
 * Date: Jul 20, 2004
 * Time: 6:00:28 PM
 * To change this template use File | Settings | File Templates.
 */
public abstract class Constraint {
  private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.typeCook.deductive.builder.Constraint");

  PsiType myLeft;
  PsiType myRight;

  public Constraint(PsiType left, PsiType right) {
    LOG.assertTrue(left != null, "<null> left type");
    LOG.assertTrue(right != null, "<null> right type");

    myLeft = left;
    myRight = right;
  }

  public PsiType getRight() {
    return myRight;
  }

  public PsiType getLeft() {
    return myLeft;
  }

  abstract String relationString();

  abstract int relationType();

  public String toString() {
    return myLeft.getCanonicalText() + " " + relationString() + " " + myRight.getCanonicalText();
  }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Constraint)) return false;

    final Constraint constraint = (Constraint)o;

    if (myLeft != null ? !myLeft.equals(constraint.myLeft) : constraint.myLeft != null) return false;
    if (myRight != null ? !myRight.equals(constraint.myRight) : constraint.myRight != null) return false;

    return true;
  }

  public int hashCode() {
    int result;
    result = (myLeft != null ? myLeft.hashCode() : 0);
    result = 29 * result + (myRight != null ? myRight.hashCode() : 0);
    return result + relationType();
  }

  public abstract Constraint apply(final Binding b);
}


text:
package org.ecg.refdata.datasource.entities.countryRegion;

import java.util.Collection;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.ecg.refdata.datasource.entities.LocalizedItem;
import org.ecg.refdata.datasource.entities.NameAndDescriptionItem;

/**
 * Class represents JPA entity. Country - region Local Specific Data.
 *
 */
@Entity()
@Table(name = "ref_country_region_lsd_it")
public class CountryRegionLSDItem implements LocalizedItem {

    private static final long serialVersionUID = 6403964230769360136L;
    /**
     * @serial Id of primary key
     */
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seq_ref_country_reg_lsd_it")
    @SequenceGenerator(name = "seq_ref_country_reg_lsd_it", sequenceName = "seq_ref_country_reg_lsd_it", allocationSize = 25)
    private Long id;
    /**
     * @serial {@link CountryRegionItem} field
     */
    @ManyToOne
    @JoinColumn(name = "country_region_item_id", referencedColumnName = "ref_item_mapping_id")
    private CountryRegionItem countryRegionItem;
    /**
     * @serial Language code field
     */
    @Column(name = "language_code", unique = false, nullable = true, length = 2)
    private String languageCode;
    /**
     * @serial Country region code field
     */
    @Column(name = "country_region_code", unique = false, nullable = true, length = 35)
    private String countryRegionName;

    /**
     * Required by hibernate
     */
    public CountryRegionLSDItem() {
    }

    /**
     * Creates CountryRegionLSDItem for a given CountryRegionItem,
     * CountryRegionName and languageCode
     *
     * @param countryRegionItem - referrenced countryRegionItem
     * @param countryRegionName - name of the country region
     * @param languageCode - language code of the name
     */
    public CountryRegionLSDItem(CountryRegionItem countryRegionItem,
            String countryRegionName, String languageCode) {
        super();
        this.countryRegionItem = countryRegionItem;
        this.countryRegionName = countryRegionName;
        this.languageCode = languageCode;
    }

    public String getCountryRegionName() {
        return languageCode;
    }

    public String getLanguageCode() {
        return countryRegionName;
    }

    public CountryRegionItem getCountryRegionItem() {
        return countryRegionItem;
    }

//	@SuppressWarnings("unused")
    public void setCountryRegionItem(CountryRegionItem countryRegionItem) {
        this.countryRegionItem = countryRegionItem;
    }

    public void setLanguageCode(String languageCode) {
        this.languageCode = languageCode;
    }

    public void setCountryRegionName(String countryRegionName) {
        this.countryRegionName = countryRegionName;
    }

    public Long getId() {
        return id;
    }

    @SuppressWarnings("unused")
    private void setId(long id) {
        this.id = id;
    }

    /**
     * Returns countryRegionName in a given requestedLanguageCode from the
     * collection of CountryRegionLSDItem. If a countryRegionName with the given
     * code is found it is returned else if countryRegionName with
     * DEFAULT_LANGUAGE_CODE is found it is returned else if any
     * countryRegionName exists in the collection it is returned else empty
     * string is returned
     *
     * @param codeDescriptionItems - list of codeDescriptions to be search over
     * @param requestedLanguageCode - requested language code of the description
     * @return code description in the preferred language code (if found)
     */
    public static String getLocalizedCountryRegionName(
            Collection<CountryRegionLSDItem> codeDescriptionItems,
            String requestedLanguageCode) {

        CountryRegionLSDItem item = NameAndDescriptionItem.getLocalizedItem(
                codeDescriptionItems, requestedLanguageCode);
        if (item != null) {
            return item.getCountryRegionName();
        }

        return "";
    }

}


text:
package breeze.math

import breeze.numerics.IntMath

/**
 * importing this gives numeric types a "pow" method.
 *
 * @author dlwh
 **/
object PowImplicits {
  // just to make some unrolling less terrible
  // TODO: move this somewhere sensible
  implicit class DoublePow(x: Double) {
    def pow(y: Double) = math.pow(x,y)
  }

  implicit class FloatPow(x: Float) {
    def pow(y: Float) = math.pow(x,y).toFloat
  }

  implicit class IntPow(x: Int) {
    def pow(y: Int) = IntMath.ipow(x, y)
  }

  implicit class LongPow(x: Long) {
    def pow(y: Long) = IntMath.ipow(x, y)
  }

}


text:
import random
import nltk

''' Just a simple class for constructing a bigram-based
    Markov Chain sentence model '''

class WordChain:
    def __init__(self, words):
        print "Building Markov Chain"
        self.tokens = [w for w in (words)
                            if w.isalpha()
                            or w == "."
                            or w == "!"
                            or w == "?"]

        # Do a bigram-based frequency analysis to begin constructing
        # the chain
        self.mapping = {}
        for i in xrange(len(self.tokens)-1):
            w1 = self.tokens[i];
            w2 = self.tokens[i+1];

            # Lowercase words that aren't starting sentences
            # E.g. "I", "Russia", "Smith", etc.
            if w2[0].isupper() and w1 != '.':
                self.tokens[i+1] = w2 = self.tokens[i+1].lower()

            if w1 in self.mapping:
                if w2 in self.mapping[w1]:
                    self.mapping[w1][w2] += 1
                else:
                    self.mapping[w1][w2] = 1
            else:
                self.mapping[w1] = {w2: 1}
        self.normalize_chain()

    # Go through our graph and assign edges a probability
    def normalize_chain(self):
        for word in self.mapping:
            # get the total number of times each bigram starting with
            # 'word' occurs
            total = 0
            for word2 in self.mapping[word].keys():
                total += self.mapping[word][word2]

            # calculate how frequently the 2nd word follows the first
            for word2 in self.mapping[word].keys():
                self.mapping[word][word2] = self.mapping[word][word2]/float(total);

    # Generate psuedo-random numbers to create a new sentence based on our chain
    # Returns a list of words
    def build_sentence(self):
        """
        Get a starting word -- i.e one that's capitalized and is also not
        punctuation

        e.g. to force a sentence to start with a particular word:
            first_word = "The"
        """
        first_word = "."
        while (first_word.islower() or first_word == "." or first_word == "?" or first_word == "!"):
            first_word = self.tokens[random.randint(0, len(self.tokens)-1)]

        # Add it to our sentence
        chain = first_word

        # Keep adding words until we reach a terminator
        # Note: for better efficency, use a running total
        # and binary search to find which word was rolled
        while True:
            rand_num = random.random()
            target = 0
            for word2 in self.mapping[chain[-1]].keys():
                target += self.mapping[chain[-1]][word2]
                if target >= rand_num:
                    # This is the word we "rolled"
                    chain += " "+word2

                    # If the sentence terminated, or no words
                    # have followed this one, return
                    if (word2 == "." or word2 == "?" or word2 == "!" or
                                                    not word2 in self.mapping.keys()):
                        return chain[:-2]+chain[-1];

                    # Go on to the next word
                    break

def main():
    """
    Replace the brown corpus with other corpora
    or use your own textfile like so:
        f = open(filename)
        t = f.read()
    """
    from nltk.corpus import twitter_samples
    words = []
    for sentence in twitter_samples.strings():
        words += nltk.word_tokenize(sentence) + ["."]
    chain = WordChain(words)
    print chain.build_sentence()

if __name__ == "__main__":
    main()


text:
interface WeakMap<K, V> {
    clear(): void;
    delete(key: K): boolean;
    get(key: K): V;
    has(key: K): boolean;
    set(key: K, value?: V): WeakMap<K, V>;
}

interface WeakMapConstructor {
    new (): WeakMap<any, any>;
    new <K, V>(): WeakMap<K, V>;
    prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;


text:
/**
 * @file     bidl_field_direction.h
 * @brief
 * @author
 * @version
 * @date     2012Äê08ÔÂ10ÈÕ 10ʱ39·Ö30Ãë
 *
 **/
#ifndef _BIDL2SL_FIELD_DIRECTION_H_
#define _BIDL2SL_FIELD_DIRECTION_H_

#include "bidl_type.h"

class BidlFieldDirection : public BidlType {
public:
    enum {
        IN,
        OUT,
        ALL
    };

    BidlFieldDirection() : BidlType(), _direction(IN) {
        _type_id = FIELDDIRECTION;
    }

    virtual ~BidlFieldDirection() {
    }

    virtual std::string get_tag() const {
        switch(_direction) {
        case IN:
            return "[in]";
            break;
        case OUT:
            return "[out]";
            break;
        case ALL:
            return "[all]";
            break;
        default:
            return "unknown direction";
        }
    }

    virtual std::string get_tag(const SourceWriter* sw) const {
        return sw->get_direction_tag(_direction);
    }

    void set_direction(int direction) {
        _direction = direction;
    }

    int get_direction() const {
        return _direction;
    }

    bool is_in() const {
        return IN == _direction;
    }

    bool is_out() const {
        return OUT == _direction;
    }

    bool is_all() const {
        return ALL == _direction;
    }

private:
    int _direction;
};
#endif // _BIDL2SL_FIELD_DIRECTION_H_


text:
import { NgModule, Component } from '@angular/core'
import { RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { UIRouterModule } from 'ui-router-ng2';
import { components, componentsList } from './components';
import { sharedServicesList } from './shared/services';
import { sharedComponentList } from './shared/components';
import { AppComponent } from './app';
import { statesConfig } from './app.routes';

@NgModule({
  declarations: [ AppComponent ].concat(componentsList, sharedComponentList),
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    UIRouterModule.forRoot(statesConfig)
  ],
  providers: [].concat(sharedServicesList),
  bootstrap: [ AppComponent ]
})
export class AppModule {}


text:
package com.pungwe.cms.jpa.security.repository;

import com.pungwe.cms.jpa.security.entity.UserProfileImpl;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserProfileRepository extends JpaRepository<UserProfileImpl, String> {

    Optional<UserProfileImpl> findOneByUsername(String username);
}


text:
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.editor.ui;

import org.lwjgl.opengl.awt.AWTGLCanvas;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;

/**
 * TeraEd main class.
 */
@SuppressWarnings("serial")
public final class Viewport extends JPanel {

    private static final Logger logger = LoggerFactory.getLogger(Viewport.class);
    private JLabel startingLabel = new JLabel("Starting Terasology...");

    public Viewport() {
        setLayout(new BorderLayout());
        setSize(1280, 720);
        setMinimumSize(new Dimension(640, 480));
        setPreferredSize(new Dimension(1280, 720));
        setOpaque(false);
        startingLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(startingLabel, BorderLayout.CENTER);
    }

    public void setTerasology(AWTGLCanvas canvas) {
        remove(startingLabel);
        add(canvas, BorderLayout.CENTER);
        revalidate();
    }
}


text:
(function() {
    var nameCityStateFilter = function() {
        return function(customers, filterValue) {
            if (!filterValue) {
                return customers;
            }
            var matches = [];
            filterValue = filterValue.toLowerCase();
            for (var i = 0; i < customers.length; i++) {
                var cust = customers[i];
                if (cust.firstName.toLowerCase().indexOf(filterValue) > -1 ||
                    cust.lastName.toLowerCase().indexOf(filterValue) > -1 ||
                    cust.city.toLowerCase().indexOf(filterValue) > -1 ||
                    cust.state.name.toLowerCase().indexOf(filterValue) > -1) {

                    matches.push(cust);
                }
            }
            return matches;
        };
    };

    angular.module('customersApp').filter('nameCityStateFilter', nameCityStateFilter);
}());


text:
/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

#ifndef __directbuffer__
#define __directbuffer__

#ifdef __cplusplus
extern "C"
{
#endif

JNIEXPORT jobject JNICALL Java_directbuffer_createDirectByteBuffer (JNIEnv *env, jclass);
JNIEXPORT void JNICALL Java_directbuffer_testDirectByteBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testCharBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testDoubleBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testFloatBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testIntBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testLongBuffer (JNIEnv *env, jclass, jobject, jint);
JNIEXPORT void JNICALL Java_directbuffer_testShortBuffer (JNIEnv *env, jclass, jobject, jint);

#ifdef __cplusplus
}
#endif

#endif /* __directbuffer__ */


text:
package galaxyspace.systems.BarnardsSystem.planets.barnarda_c.items;

import galaxyspace.core.prefab.items.GSItemBlockDesc;
import galaxyspace.systems.BarnardsSystem.planets.barnarda_c.blocks.Barnarda_C_Falling_Blocks.EnumFallingBlockBarnardaC;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;

public class ItemBlocksBarnarda_C_Falling extends GSItemBlockDesc
{
    public ItemBlocksBarnarda_C_Falling(Block block) {
        super(block);
        setMaxDamage(0);
        setHasSubtypes(true);
    }

    @Override
    public int getMetadata(int meta)
    {
        return meta;
    }

    @Override
    public String getUnlocalizedName(ItemStack is) {

        int metadata = is.getItemDamage();

        if(metadata > EnumFallingBlockBarnardaC.values().length)
        	return "tile." + EnumFallingBlockBarnardaC.byMetadata(0).getName();

        return "tile." + EnumFallingBlockBarnardaC.byMetadata(metadata).getName();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd">
    <testCase name="Magento\Checkout\Test\TestCase\DeleteProductFromMiniShoppingCartTest" summary="Delete Grouped Product from Mini Shopping Cart" ticketId="MAGETWO-29104">
        <variation name="DeleteGroupedProductFromMiniShoppingCartTestVariation">
            <data name="products" xsi:type="string">groupedProduct::default</data>
            <data name="deletedProductIndex" xsi:type="string">0</data>
            <constraint name="Magento\Checkout\Test\Constraint\AssertCartIsEmpty" />
        </variation>
    </testCase>
</config>


text: Primary links


text:
from datetime import datetime, timedelta
from django.db import models
from django.db.models import Prefetch, Max, Q, F
from django.db.models.fields.related import ManyToOneRel
from django.db.models.options import FieldDoesNotExist

try:

    from django.utils.timezone import utcnow

except ImportError:

    from django.utils.timezone import utc

    def utcnow():
        return datetime.utcnow().replace(tzinfo=utc)

class TimeSeriesQuerySet(models.QuerySet):
    """
        Adds 4 main methods to the Django QuerySet API that can be used to
        update and maintain timeseries data. These methods include:
            prefetch_latest
            filter_outdated
            last_updated
            update_timeseries
    """

    def __init__(self, *args, **kwargs):
        super(TimeSeriesQuerySet, self).__init__(*args, **kwargs)

        self.latest_registry = set()
        self._latest_included = False

    def _clone(self, **kwargs):
        # overriding _clone is required so retain the latest_registry set
        # information
        clone = super(TimeSeriesQuerySet, self)._clone(**kwargs)
        clone.latest_registry = self.latest_registry.copy()
        clone._latest_included = self._latest_included
        return clone

    def prefetch_latest(self, *related_names):
        """
            Exposes the latest associated reverse relation.

            Adds a query per related name.
        """
        prefetch_set = []
        for related_name in set(related_names):
            rev_rel = get_reverse_relation(self.model, related_name)

            field_name = rev_rel.field.name
            RelatedModel = rev_rel.field.model

            attr_name = 'latest_{}'.format(related_name)
            prefetch = Prefetch(
                related_name,
                queryset=RelatedModel.objects.filter(
                    **{field_name + '__in': self}
                ).order_by(field_name, '-created').distinct(field_name),
                to_attr=attr_name
            )
            prefetch_set.append(prefetch)
            self.latest_registry.add(attr_name)

        return self.prefetch_related(*prefetch_set)

    def parse_latest(self, res):
        """
            Checks the prefetched data and assigns either the found object or
            None to the latest_\{related_name\} attribute on the "owning"
            model instance.

            res: a model instance representing the object that owns
                 (by foreign key) the prefetched data.
        """
        # loops over the registered to_attr names to access and check the data
        for name in self.latest_registry:
            value = getattr(res, name)
            if value:
                value = value[0]
            else:
                value = None
            setattr(res, name, value)
        self._latest_included = True

    def get(self, *args, **kwargs):
        # overriding get is required so to parse any prefetched latest results
        res = super(TimeSeriesQuerySet, self).get(*args, **kwargs)
        self.parse_latest(res)
        return res

    def __iter__(self):
        # Overrides the base __iter__ functionality so to
        super_iter = super(TimeSeriesQuerySet, self).__iter__()
        if self._latest_included:
            for res in super_iter:
                yield res
        else:
            for res in super_iter:
                if isinstance(res, self.model):
                    self.parse_latest(res)
                yield res

    def last_updated(self, related_name):
        """
            Annotates the created timestamp of the latest related instance as
            given by the reverse relation's related_name.

            Usage:
                ad = Ad.objects.last_updated('rawdata').first()
                # assuming there's data related to ad
                print ad.rawdata_last_updated
                # prints the timestamp associated to when the ad's raw data was
                # last updated
        """
        return self.annotate(
            **{
                related_name + '_last_updated': Max(
                    related_name + '__created'
                )
            }
        )

    def filter_outdated(self, related_name):
        """
            Returns a queryset that will yield the model instances that have
            "outdated" data associated to reverse related model as given by
            the specified related_name
        """
        rev_rel = get_reverse_relation(self.model, related_name)
        RelatedModel = rev_rel.field.model
        is_safe_cutoff = utcnow() - get_interval(RelatedModel)
        annotated_queryset = self.last_updated(related_name)
        last_updated_query = {
            '{}_last_updated__lt'.format(related_name): is_safe_cutoff
        }
        return annotated_queryset.filter(
            Q(**last_updated_query) |
            Q(**{'{}_last_updated__isnull'.format(related_name): True})
        )

    def update_timeseries(self, related_name, collector, force=False):
        """
            Updates the queryset's related model table
            (as given by related_name) using a provider "collector" callable.

            "collector" must take a queryset of the referenced models as its
            only argument. It must also return an iterable of dictionaries
            that can be used to construct and save instances of the related
            model.

            N.B. Only instances that have outdated data will be updated unless
            explicitly forced using the "force" keyword argument.
        """
        # N.B. runs two queries as such is subject to errors resulting from
        # multitenancy race conditions.
        rev_rel = get_reverse_relation(self.model, related_name)
        RelatedModel = rev_rel.field.model
        if force:
            models = self
        else:
            models = self.filter_outdated(related_name)

        results = collector(models)
        instances = [RelatedModel(**data) for data in results]
        output = RelatedModel.objects.bulk_create(instances)
        return output

class TimeSeriesManager(models.Manager.from_queryset(TimeSeriesQuerySet)):
    pass

class TimeSeriesModel(models.Model):
    """
        Abstract model that can be inherited from to facilitate building out
        your timeseries data framework.

        N.B. TimeSeries models should have a ForeignKey reference to an
        "owning" model and TIMESERIES_INTERVAL timedelta instance.
    """

    created = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        abstract = True
        ordering = ('-created', )
        get_latest_by = 'created'

def LatestQ(related_name, **kwargs):
    """
        Constructs a django.db.models.Q instance that allows queries to be
        executed against the latest associated reverse relation.

        N.B. this method is designed to be used in conjunction with
        timeseries.utils.TimeSeriesQuerySet.last_updated.

        Usage:
        Ad.objects.last_updated('rawdata').filter(
            LatestQ('rawdata', views__gt=1000)
        )
    """
    parsed_kwargs = {
        related_name + "__created": F(related_name + '_last_updated')
    }
    for key, value in kwargs.iteritems():
        parsed_kwargs[related_name + '__' + key] = value
    return Q(**parsed_kwargs)

def q_factory(related_name, q_func=LatestQ):
    """
        Helper function that wraps LatestQ

        Usage:

        LatestRawDataQ = q_factory('rawdata')

        Ad.objects.last_updated('rawdata').filter(
            LatestRawDataQ(views__gt=1000)
        )

    """
    def wrapper(**kwargs):
        return q_func(related_name, **kwargs)
    return wrapper

def get_reverse_relation(model, related_name):
    """
        Helper function that returns a reverse relation instance for a
        given model and the related_name for the reverse relation.

        model: subclass of django.db.models.Model
        related_name: str
    """
    return model._meta.fields_map.get(related_name)

def check_reverse_relation(model, related_name):
    """
        Helper method to check if a given model related_name pair return a
        reverse relation instance that is associated by a ForeignKey.

        model: subclass of django.db.models.Model
        related_name: str
    """
    rel = get_reverse_relation(model, related_name)
    if rel is None:
        raise NotImplementedError(
            '{} does not have a reverse relation by the name "{}"'.format(
                model.__name__, related_name
            )
        )
    elif not isinstance(rel, ManyToOneRel):
        raise TypeError(
            'The reverse relation "{}" on {}.{} is not a ForeignKey.'
            'Timeseries only works with ForeignKey reverse relations.'.format(
                related_name, rel.field.model.__name__, rel.field.name
            )
        )

    return rel

def check_created_field(model):
    """
        Helper method to check if a given model has a created field.

        model must me a class that inherits from django.db.models.Model
    """
    try:
        created = model._meta.get_field_by_name('created')
        assert isinstance(created, models.DateTimeField)
    except FieldDoesNotExist as err:
        raise FieldDoesNotExist(
            'Reverse related model {} must have a created field.\n'.format(
                model.__name__
            ) + str(err)
        )
    except AssertionError:
        raise TypeError(
            '{}.created field must be a DateTimeField'.format(model.__name__)
        )

def get_interval(model):
    """
        Helper method to facilitate the retrieval of TIMESERIES_INTERVAL.

        model must be a Django model class.
    """
    interval = model.TIMESERIES_INTERVAL
    if isinstance(interval, timedelta):
        return interval
    elif isinstance(interval, (int, float, basestring)):
        return timedelta(seconds=int(interval))
    raise ValueError(
        'TIMESERIES_INTERVAL must either be in seconds or an instance of '
        'datetime.timedelta'
    )


text:
#ifndef SHADER_H
#define SHADER_H "[0.0.1@CShader.h]"
/*
*	DESCRIPTION:
*		Module contains implementation of shader class.
*	AUTHOR:
*		Mikhail Demchenko
*		mailto:dev.echo.mike@gmail.com
*		https://github.com/echo-Mike
*	PAIRED WITH: CShader.cpp
*/
//STD
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
//std::map
#include <map>
//std::pair, std::make_pair
#include <utility>
//GLEW
#include <GL/glew.h>
//OUR
#include "CUniforms.h"
//DEBUG
#ifdef DEBUG_SHADER
	#ifndef DEBUG_OUT
		#define DEBUG_OUT std::cout
	#endif
	#ifndef DEBUG_NEXT_LINE
		#define DEBUG_NEXT_LINE std::endl
	#endif
#endif

//Class definition: Shader
class Shader {
	//NO STDCONSTRUCT, NO MOVECONSTRUCT, NO COPYCONSTRUCT
	Shader() = delete;
	Shader(const Shader& s) = delete;
	Shader(const Shader&& s) = delete;
	//Vertex and Fragment shader paths
	std::string vpath, fpath;
	//Uniform container
	std::map<int, std::pair<std::string, UniformHandlerInteface*>> uniforms;
	//The program ID //SPO ID
	GLuint Program;
	//NOT SAFE SOLUTION: OVERFLOW
	//Id counter for current shader
	int incrementId;
public:
	//Returns SPO Id
	GLuint getShaderId() { return Program; }

	//Returns result of uniform search: location detemined by name
	GLint getUniformLocation(const char* _uniformName) {
		GLint _location;
		_location = glGetUniformLocation(Program, _uniformName);
		if (_location == -1) { //Check if uniform not found
			#ifdef DEBUG_SHADER
				DEBUG_OUT << "ERROR::SHADER::getUniformLocation::UNIFORM_NAME_MISSING"<< DEBUG_NEXT_LINE;
				DEBUG_OUT << "\tName: " << _uniformName << DEBUG_NEXT_LINE;
			#endif
		}
		return _location;
	}

	Shader(const GLchar* vertexPath, const GLchar* fragmentPath) :	vpath(vertexPath),
																	fpath(fragmentPath),
																	Program(0),
																	incrementId(0)
	{
		Reload();
	}

	~Shader() {
		//WEAK DESISION: destructor calls on const ptr?
		//Prevent external values from destructor calls
		for (auto &v : uniforms)
			v.second.second = nullptr;
		glDeleteProgram(this->Program);
	}

	int newUniform(const char* _uniformName, UniformHandlerInteface* _handler) {
		uniforms[incrementId] = std::move(std::make_pair(std::string(_uniformName), _handler));
		return incrementId++;
	}

	void deleteUniform(int _index) { uniforms.erase(_index); }

	void Use();

	void Reload();
};
#endif


text:
using Perspex.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace Xamarin.Forms.Platform.PerspexDesktop
{
    public class DesktopWindow : DesktopBaseWindow
    {
        protected override Platform CreatePlatform()
        {
            return new WindowsPlatform(this);
        }
    }
}


text:
package controllers;

import java.util.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import play.*;
import play.mvc.*;
import play.i18n.Lang;
import play.libs.*;
import play.jobs.*;

import models.*;
import utils.*;
import jobs.*;

import javax.mail.internet.InternetAddress;

@play.db.jpa.Transactional
public class Application extends Controller {

    // bug

    public static void aa() {
        try {
            @SuppressWarnings("unused")
            int test = 1;
        } catch (Exception ex) {
        }
    }

    public static void helloZen() {
        renderText("Hello");
    }

    public static void myHomePage(String clientName) {
        renderText(clientName);
    }

    public static void some1() {
        renderText(Invoker.InvocationContext.current());
    }

    @Youhou
    public static void some2() {
        renderText(Invoker.InvocationContext.current());
    }

    @Youhou
    public static void some3() throws Exception {
        JobWithContext job = new JobWithContext();
        Future<String> future = job.now();
        renderText(future.get());
    }

    // bug

    public static void aaa() {
        try {
            boolean test = TestUtil.invokeTest("a");
            Logger.info("test:" + test);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        renderText("IT WORKS");
    }

    public static void ok(String re) {
        renderText("OK: " + re);
    }

    public static void revRoute(String re) {
    	Map<String,Object> par = new HashMap<String, Object>();
    	par.put("re", re);
    	String url = Router.reverse("Application.revRoute", par ).url;
	renderText("OK[revRoute]: " + re + " URL: " + url);
    }

    public static void ressourceWithoutSpecialCharacters(String appId, String verId) {
        Map<String,Object> args = new HashMap<String, Object>();
        args.put("appId", appId);
        args.put("verId", verId);
        String url = Router.reverse("Application.ressourceWithoutSpecialCharacters", args ).url;
        renderText("OK[ressourceWithoutSpecialCharacters]: appId=" + appId + " verId=" + verId + " URL: " + url);
    }

    public static void ressourceWithSpecialCharacters(String appId, String verId) {
       Map<String,Object> args = new HashMap<String, Object>();
       args.put("appId", appId);
       args.put("verId", verId);
       String url = Router.reverse("Application.ressourceWithSpecialCharacters", args ).url;
       renderText("OK[ressourceWithSpecialCharacters]: appId=" + appId + " verId=" + verId + " URL: " + url);
    }

    public static void index() {
        routeArgs.put("lucky", "strike");
        render();
    }

    public static void showIt() {
        renderText("Done");
    }

    public static void index2() {
        renderText(Router.reverse("Application.index2"));
    }

    public static void simpleStatusCode() {
        response.status = 204;
    }

    public static void imagesAssets() {

    }

    public static void dashboard(String client) {
        renderText(client);
    }

    public static void hello(String name) {
        render(name);
    }

    public static void helloWorld(String name) {
        render("/Application/hello.html", name);
    }

    public static void helloSteph(String name) {
        render("/Application/hello.html", name);
    }

    public static void yop() {
        render();
    }

    public static void alertConfirmPrompt() {
        render();
    }

    public static void dynamicClassBinding(boolean fail) {
        render(fail);
    }

    public static void tagContexts() {
        render();
    }

    public static void generateBookWithDateLink(long timeLong) {
        render(timeLong);
    }

    public static void book(Date at) {
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("dd/MM/yy");
        df.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        renderText("Booked at %s !!", df.format(at));
    }

    public static void escapeData() {
        String oops = " Yop ";
        render(oops);
    }

    public static void aGetForm(String name) {
        render("Application/hello.html", name);
    }

    public static void aGetForm2(String name) {
        name = "2" + name;
        render("Application/hello.html", name);
    }

    public static void optional() {
        renderText("OK");
    }

    public static void withQueryParam(String lucky) {
         renderText("OK");
    }

    public static void reverserouting() {
        render("Application/reverse.html");
    }

    public static void reverserouting2() {
        render("Application/reverse2.html");
    }

    public static void reverserouting3() {
        Object def = reverse(); {
            JPABinding.save(new Project("COLCOZ"));
        }
        renderText(def);
    }

    public static void jsRoute() {
        render();
    }

    public static void jsRouteError() {
        render();
    }

    public static void mail() {
        notifiers.Welcome.welcome();
        renderText("OK");
    }

    public static void mail2() {
        Welcome.welcome();
        renderText("OK2");
    }

    public static void mail3() {
        notifiers.Welcome.welcome2();
        renderText("OK3");
    }

    public static void mail4() {
        notifiers.Welcome.welcome3();
        renderText("OK4");
    }

    public static void mail5() throws EmailException {
        HtmlEmail email = new HtmlEmail();
        email.setHtmlMsg("
A Title
");
        email.setTextMsg("alternative message");
        EmailAttachment attachment = new EmailAttachment();
        attachment.setDescription("An image");
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setPath(Play.applicationPath.getPath() + java.io.File.separator + "test" + java.io.File.separator + "fond2.png");
        EmailAttachment attachment2 = new EmailAttachment();
        attachment2.setName("fond3.jpg");
        attachment2.setPath(Play.applicationPath.getPath() + java.io.File.separator + "test" + java.io.File.separator + "fond3.jpg");
        email.attach(attachment);
        email.attach(attachment2);
        email.setFrom("test@localhost");
        email.addTo("test@localhost");
        email.setSubject("test attachments");
        Mail.send(email);
        renderText("OK5");
    }

    public static void mailwithpercentinsubject() {
        notifiers.Welcome.subjectwithpercent();
        renderText("OKPCT");
    }

    public static void mailWithUrls() {
        notifiers.Welcome.welcome_mailWithUrls(false);
        renderText("OK_mailWithUrls");
    }

    public static class MailJob extends Job {
        @Override
        public void doJob() {
            notifiers.Welcome.welcome_mailWithUrls(true);
        }
    }

    public static void mailWithUrlsInJob() throws Exception {
        new MailJob().now().get();
        renderText("OK_mailWithUrlsInJob");
    }

    public static void mailWithEmbeddedImage() {
        notifiers.Welcome.mailWithEmbeddedImage();
        renderText("OK_mailWithEmbeddedImage");
    }

    public static void ifthenelse() {
        boolean a = true;
        boolean b = false;
        String c = "";
        String d = "Yop";
        int e = 0;
        int f = 5;
        Boolean g = null;
        Boolean h = true;
        Object i = null;
        Object j = new Object();
        render(a, b, c, d, e, f, g, h, i, j);
    }

    public static void listTag() {
        List<String> a = new ArrayList<String>();
        a.add("aa");
        a.add("ab");
        a.add("ac");
        int[] b = new int[]{0, 1, 2, 3};
        Iterator d = a.iterator();
        render(a, b, d);
    }

    public static void a() {
        render();
    }

    public static void useSpringBean() {

    }

    @javax.inject.Inject
    static Test myTest;

    public static void useSpringBeanInject() {
        renderText(myTest.yop());
    }

    public static void googleSearch(String word) throws InterruptedException, ExecutionException {
        WS.HttpResponse response = WS.url("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s", word).get();
        long results = response.getJson().getAsJsonObject().getAsJsonObject("responseData").getAsJsonObject("cursor").getAsJsonPrimitive("estimatedResultCount").getAsLong();
        renderText(results);
    }

    public static void selectTag(){
        List<User> users = new ArrayList<User>(12);
        User user;
        for(long i = 0; i < 10; i++) {
        	user = new User("User-" + i);
        	user.k = i;
        	user.i = (int) i;
        	users.add(user);
        }
        user = new User("User-%-10");
        user.k = 10L;
        user.i = (int) 10;
        users.add(user);
        user = new User("User-%%-11");
        user.k = 11L;
        user.i = (int) 11;
        users.add(user);
        render(users);
    }

    public static void fastTag_render_test() {
        render();
    }

    public static void writeChunks() throws UnsupportedEncodingException {
        response.contentType = "text/plain";
        response.setHeader("Transfer-Encoding", "chunked");
        response.writeChunk("a");
        response.writeChunk("b");
        response.writeChunk("c");
        response.writeChunk("æøå");
        response.writeChunk("æøå".getBytes("UTF-8"));
    }

    private static final Object CHUNK_LOCK = new Object();

    public static void writeChunks2() {
        // Some applications may want to keep sending data to the client until
        // the client closes the HTTP connection. To simulate this case, we have
        // an infinite loop that terminates only when an exception occurs, and
        // we need to ensure that an exception will occur when the client closes
        // the HTTP connection.
        // The purpose of the synchronization lock is to test the ability for
        // this method to terminate. If this method does not terminate, a second
        // call to this method will hang with no output.
        synchronized(CHUNK_LOCK) {
            response.contentType = "text/plain";
            response.setHeader("Transfer-Encoding", "chunked");
            Logger.info("Write chunks started.");
            try {
                while (true) {
                    response.writeChunk("Go, Go, Igo!\n");
                }
            }
            catch (Exception e) {
                Logger.info("Write chunks exception.", e);
            }
            Logger.info("Write chunks stopped.");
        }
    }

    public static void makeSureCookieSaved(){
        if(request.cookies!=null && request.cookies.get("PLAY_TEST")!=null){
            response.setCookie("PLAY_TEST", request.cookies.get("PLAY_TEST").value);
        }
        renderText("OK");
    }
}


text:
@interface NXVConcreteBuilder : NSObject

@property (nonatomic, assign) NSInteger foo;
@property (nonatomic, assign) NSInteger bar;
@property (nonatomic, assign) NSInteger baz;

- (instancetype)initWithFoo:(NSInteger)foo;
- (instancetype)withBar:(NSInteger)bar;
- (instancetype)withBaz:(NSInteger)baz;

- (NXVConcreteProduct *)build;

@end


text:
/**
 *
 */
package edu.berkeley.nlp.PCFGLA;

import java.util.ArrayList;
import java.util.List;

import edu.berkeley.nlp.util.PriorityQueue;

/**
 * @author petrov
 *
 */
public class LazyList {
	List<HyperEdge> sortedBegining;
	PriorityQueue<HyperEdge> fringe;
	int nSorted, nFringe;
	boolean[] grammarTags;
//	double bestScore;

	public LazyList(boolean[] tags){
		sortedBegining = new ArrayList<HyperEdge>();
		fringe = new PriorityQueue<HyperEdge>();
		nSorted = 0;
		nFringe = 0;
		grammarTags = tags;
//		bestScore = Double.NEGATIVE_INFINITY;
	}

	public int sortedListSize(){
		return nSorted;
	}

	public void addToFringe(HyperEdge el){
		fringe.add(el, el.score);
		nFringe++;
	}

//	public void addToSorted(HyperEdge el){
//		sortedBegining.add(el);
//		nSorted++;
//	}

	public HyperEdge getKbest(int k){
		if (k>nSorted){
			System.out.println("Don't have this element yet");
			return null;
//		} else if (k==nSorted&&(k==0||!fringe.hasNext())){
//			return null;
		} else if (k==nSorted){ // extract the next best
			expandNextBest();
		}
		if (k==nSorted) return null;
		return sortedBegining.get(k);
	}

	public void expandNextBest(){
		while (fringe.hasNext()) {
			HyperEdge edge = fringe.next();
			boolean isNew = true;
			for (HyperEdge alreadyIn : sortedBegining){
				if (alreadyIn.differsInPOSatMost(edge,grammarTags)) {
					isNew = false;
					break;
				}
			}
			if (isNew){
				sortedBegining.add(edge);
				nFringe--;
				nSorted++;
				break;
			}
		}
	}

}


text:
import objectdraw.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

/**
  * A pop-up class used when the used acquires three strikes
  * @author Andrew Zurn
  */

public class YouLoseWindow extends FrameWindowController implements ActionListener{

  /** lines of text used on the canvas */
  private Text line1, line2, line3;

  /** JButton used to exit the system */
  private JButton exit;

  /** int used to display the acquired score on the screen */
  private int theScore;

  /**
   * Contructor of the YouLoseWindow with a paramter of the score acquired in-game
   * @param score the score acquired inside the game
   */
  public YouLoseWindow(int score){
    theScore = score;
  }

  public void begin(){
    line1 = new Text ( "You Earned 3 Strikes!!!",
                      (canvas.getWidth()/2) - 140, (canvas.getHeight()/2) - 45, canvas);
    line2 = new Text ( "You Lose!", (canvas.getWidth()/2) - 90, (canvas.getHeight()/2) - 25, canvas);
    line3 = new Text ( "Your Score was " + theScore + "!", (canvas.getWidth()/2) - 65,
                      canvas.getHeight() - 45, canvas);
    line2.setBold();
    line1.setFontSize(25);
    line2.setFontSize(35);
    line3.setFontSize(15);
    Container contentPane = getContentPane();
    exit = new JButton ("Exit Game");
    exit.addActionListener( this );
    contentPane.add(exit, BorderLayout.SOUTH);
  }

  /**
   * determines when a GUI compenent is used
   * @param evt the GUI compenent used
   */
  public void actionPerformed(ActionEvent evt){
    if (evt.getSource() == exit){
      System.exit(0);
    }
  }
}


text:
<?php

Yii::import('zii.widgets.grid.CButtonColumn');

/**
 * Bootstrap button column widget.
 */
class TbButtonColumn extends CButtonColumn
{
    /**
     * @var string the view button icon (defaults to TbHtml::ICON_EYE_OPEN).
     */
    public $viewButtonIcon = TbHtml::ICON_EYE_OPEN;
    /**
     * @var string the update button icon (defaults to TbHtml::ICON_PENCIL).
     */
    public $updateButtonIcon = TbHtml::ICON_PENCIL;
    /**
     * @var string the delete button icon (defaults to TbHtml::ICON_TRASH).
     */
    public $deleteButtonIcon = TbHtml::ICON_TRASH;

    /**
     * Initializes the default buttons (view, update and delete).
     */
    protected function initDefaultButtons()
    {
        parent::initDefaultButtons();

        if ($this->viewButtonIcon !== false && !isset($this->buttons['view']['icon'])) {
            $this->buttons['view']['icon'] = $this->viewButtonIcon;
        }
        if ($this->updateButtonIcon !== false && !isset($this->buttons['update']['icon'])) {
            $this->buttons['update']['icon'] = $this->updateButtonIcon;
        }
        if ($this->deleteButtonIcon !== false && !isset($this->buttons['delete']['icon'])) {
            $this->buttons['delete']['icon'] = $this->deleteButtonIcon;
        }
    }

    /**
     * Renders a link button.
     * @param string $id the ID of the button
     * @param array $button the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements.
     * @param integer $row the row number (zero-based)
     * @param mixed $data the data object associated with the row
     */
    protected function renderButton($id, $button, $row, $data)
    {
        if (isset($button['visible']) && !$this->evaluateExpression(
                $button['visible'],
                array('row' => $row, 'data' => $data)
            )
        ) {
            return;
        }

        $url = TbArray::popValue('url', $button, '#');
        if ($url !== '#') {
            $url = $this->evaluateExpression($url, array('data' => $data, 'row' => $row));
        }

        $imageUrl = TbArray::popValue('imageUrl', $button, false);
        $label = TbArray::popValue('label', $button, $id);
        $options = TbArray::popValue('options', $button, array());

        TbArray::defaultValue('title', $label, $options);
        TbArray::defaultValue('rel', 'tooltip', $options);

        if ($icon = TbArray::popValue('icon', $button, false)) {
            echo CHtml::link(TbHtml::icon($icon), $url, $options);
        } else {
            if ($imageUrl && is_string($imageUrl)) {
                echo CHtml::link(CHtml::image($imageUrl, $label), $url, $options);
            } else {
                echo CHtml::link($label, $url, $options);
            }
        }
    }
}


text:
Template.visitorHistory.helpers({
	historyLoaded() {
		return !Template.instance().loadHistory.ready();
	},

	previousChats() {
		return ChatRoom.find({
			_id: { $ne: this.rid },
			'v._id': Template.instance().visitorId.get()
		}, {
			sort: {
				ts: -1
			}
		});
	},

	title() {
		let title = moment(this.ts).format('L LTS');

		if (this.label) {
			title += ' - ' + this.label;
		}

		return title;
	}
});

Template.visitorHistory.onCreated(function() {
	var currentData = Template.currentData();
	this.visitorId = new ReactiveVar();

	this.autorun(() => {
		const room = ChatRoom.findOne({ _id: Template.currentData().rid });
		this.visitorId.set(room.v._id);
	});

	if (currentData && currentData.rid) {
		this.loadHistory = this.subscribe('livechat:visitorHistory', { rid: currentData.rid });
	}
});