text:
<?php
namespace Gt\Csrf;

use Gt\Csrf\Exception\CsrfTokenInvalidException;
use Gt\Csrf\Exception\CsrfTokenSpentException;
use Gt\Session\SessionStore;

class SessionTokenStore extends TokenStore {
	const SESSION_KEY = "tokenList";

	/** @var SessionStore */
	protected $session;

	public function __construct(
		SessionStore $session,
		int $maxTokens = null
	) {
		$this->session = $session;
		parent::__construct($maxTokens);
	}

	public function saveToken(string $token):void {
		$tokenList = $this->session->get(self::SESSION_KEY) ?? [];
		$tokenList[$token] = null;

		while(count($tokenList) > $this->getMaxTokens()) {
			array_shift($tokenList);
		}

		$this->session->set(self::SESSION_KEY, $tokenList);
	}

	public function verifyToken(string $token):void {
		$tokenList = $this->session->get(self::SESSION_KEY) ?? [];

		if(!array_key_exists($token, $tokenList)) {
			throw new CsrfTokenInvalidException(
				$token
			);
		}
		elseif(!is_null($tokenList[$token])) {
			throw new CsrfTokenSpentException(
				$token,
				$tokenList[$token]
			);
		}
	}

	public function consumeToken(string $token):void {
		$tokenList = $this->session->get(self::SESSION_KEY) ?? [];
		$tokenList[$token] = time();
		$this->session->set(self::SESSION_KEY, $tokenList);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Amer. Acad. Arts 38: 40 (1902)

#### Original name
Laboulbenia hawaiensis Thaxt.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
using NodaTime;
using StudentsCalendar.Core;
using StudentsCalendar.UI.Services;

namespace StudentsCalendar.UI.Main
{
	/// <summary>
	/// Widok miesiąca podzielonego na tygodnie. Pozwala na wyświetlenie aktualnego tygodnia i kilku poprzednich/następnych.
	/// </summary>
	public sealed class MonthViewModel
		: Screen, IViewModel
	{
		private const int MaxWeeks = 2;

		private readonly ICurrentCalendar CurrentCalendar;
		private readonly ILayoutArranger LayoutArranger;

		/// <summary>
		/// Wskazuje, czy aktualnie wybrany kalendarz jest prawidłowy i da się wyświetlić zawartość tego ViewModelu.
		/// </summary>
		public bool IsDataValid { get; private set; }

		/// <summary>
		/// Pobiera listę tygodni załadowanych do ViewModelu.
		/// </summary>
		public IReadOnlyList<ArrangedWeek> Weeks { get; private set; }

		/// <summary>
		/// Pobiera aktualny tydzień.
		/// </summary>
		public ArrangedWeek CurrentWeek { get; private set; }

		/// <summary>
		/// Inicjalizuje obiekt niezbędnymi zależnościami.
		/// </summary>
		/// <param name="calendar"></param>
		/// <param name="layoutArranger"></param>
		public MonthViewModel(ICurrentCalendar calendar, ILayoutArranger layoutArranger)
		{
			this.DisplayName = "Widok miesiąca";

			this.CurrentCalendar = calendar;
			this.LayoutArranger = layoutArranger;
		}

		protected override void OnInitialize()
		{
			base.OnInitialize();

			this.IsDataValid = true;
			do
			{
				if (this.CurrentCalendar.Calendar == null)
				{
					this.IsDataValid = false;
					break;
				}

				var generated = this.CurrentCalendar.Calendar;

				var today = DateHelper.Today;
				var thisWeek = today.IsoDayOfWeek != IsoDayOfWeek.Monday ? today.Previous(IsoDayOfWeek.Monday) : today;

				var currentWeek = generated.Weeks
					.Select((w, i) => new { Week = w, Index = i })
					.FirstOrDefault(w => w.Week.Date == thisWeek);

				if (currentWeek == null)
				{
					this.IsDataValid = false;
					break;
				}

				var weekIndex = currentWeek.Index;

				int startWeekIndex = Math.Max(weekIndex - MaxWeeks, 0);
				int endWeekIndex = Math.Min(weekIndex + MaxWeeks + 1, generated.Weeks.Count);

				this.Weeks = generated.Weeks
					.Skip(startWeekIndex)
					.Take(endWeekIndex - startWeekIndex)
					.Select(this.LayoutArranger.Arrange)
					.ToArray();
				this.CurrentWeek = this.Weeks[weekIndex - startWeekIndex];

			} while (false);

			this.Refresh();
		}
	}
}


text:
class Puppet::Provider::Rabbitmqctl < Puppet::Provider
  def self.rabbitmqctl_cmd(*args)
    rabbitmqctl '-q', *args
  end

  def rabbitmqctl_cmd(*args)
    self.class.rabbitmqctl_cmd *args
  end

  def self.by_name(items)
    by_key(items) { |item| item.name }
  end

  def self.by_key(items)
    hash_by_key = {}
    items.each do |item|
      key = yield item
      hash_by_key[key] = item
    end
    return hash_by_key
  end
end


text:
set -e

docker build -f Dockerfile.x86 --platform linux/386 -t pythia:latest .
rm -rf ninja/*
docker run --platform linux/386 --rm -v "$(pwd)"/:/data -w /data/ninja pythia:latest cmake -G Ninja -DCMAKE_PREFIX_PATH=@Pythia/python-310-embed-linux32 -DUSE_64BIT_BUILD=OFF -DCMAKE_BUILD_TYPE=RelWithDebInfo ..
docker run --platform linux/386 --rm -v "$(pwd)"/:/data -w /data/ninja pythia:latest ninja


text:
package utils;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Utility class implementing some convenience methods to work with HTTP.
 *
 * @author Simon Stastny
 *
 */
public class HttpUtils {

	/**
	 * Method for getting a document on a specified URL.
	 * @param url url where the document is located at
	 * @return contents of the document
	 */
	public static String getDocument(String url) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}

			HttpEntity getResponseEntity = getResponse.getEntity();

			StringWriter writer = new StringWriter();
			IOUtils.copy(getResponseEntity.getContent(), writer);
			return writer.toString();

		} catch (IOException e) {
			getRequest.abort();
		}

		return null;
	}

}


text:
'use strict'
var util = require('util')

var User = exports.User = function User (msg) {
  var err = new Error(msg)
  Error.captureStackTrace(err, User)
  err.code = 'EGAUGE'
  return err
}

exports.MissingTemplateValue = function MissingTemplateValue (item, values) {
  var err = new User(util.format('Missing template value "%s"', item.type))
  Error.captureStackTrace(err, MissingTemplateValue)
  err.template = item
  err.values = values
  return err
}

exports.Internal = function Internal (msg) {
  var err = new Error(msg)
  Error.captureStackTrace(err, Internal)
  err.code = 'EGAUGEINTERNAL'
  return err
}


text:
#import <UIKit/UIKit.h>
#import <ZBarSDK/ZBarSDK.h>
#import <CoreGraphics/CoreGraphics.h>
#import <AVFoundation/AVFoundation.h>
//#import <PhotoLibrary/PhotoLibrary.h>
#import "QROutputController.h"
#import "QRCode.h"
#import "QREncoder.h"
#import "DataMatrix.h"

#define OPTIONS_PANE_SPACER_SIZE 15

static char qrControllerKey;

typedef enum {
    PLCameraModePhoto = 0,
    PLCameraModeVideo = 1,
    PLCameraModePanorama = 2
} PLCameraMode;

typedef enum {
    PLCameraDeviceBack = 0,
    PLCameraDeviceFront = 1
} PLCameraDevice;

/* Debug code
%hook SpringBoard

- (void)applicationOpenURL:(id)arg1 withApplication:(id)arg2 sender:(id)arg3 publicURLsOnly:(BOOL)arg4 animating:(BOOL)arg5 needsPermission:(BOOL)arg6 additionalActivationFlags:(id)arg7{
	NSLog(@"arg1: %@\narg2: %@\narg3: %@\npublicURLsOnly: %d\nanimating: %d\nneedsPermission: %d\nadditionalActivationFlags: %@", arg1, arg2, arg3, arg4, arg5, arg6, arg7);
	%orig;
}

%end */

@interface PLCameraController : NSObject{

}

@property(readonly) float panoramaPreviewScale;
@property(readonly, nonatomic) struct CGSize panoramaPreviewSize;

@end

%hook PLCameraController

%new
- (void)_associateQRController:(id) object{
    objc_setAssociatedObject(self, &qrControllerKey, object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

%new
- (id)_getQRController {
    return objc_getAssociatedObject(self, &qrControllerKey);
}

%new
-(void)qrCodeSwitchChanged:(id) sender{
	if([sender isOn]){
      		NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
		[userDefaults setBool:true forKey:@"PLQRIsEnabled"];
		[userDefaults synchronize];
		[[self _getQRController] setEnabledBySwitch:true];
    } else{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	[userDefaults setBool:false forKey:@"PLQRIsEnabled"];
	[userDefaults synchronize];
    	[[self _getQRController] setEnabledBySwitch:false];
    }
}

- (BOOL)_setupCamera {
	NSLog(@"Setup Camera");
    BOOL orig = %orig();

    if ([self isCameraApp] && orig) {
        QROutputController *outputController = [[QROutputController alloc] init];
        [outputController setDelegate:self];

        [self _associateQRController:outputController];

        [outputController release];
    }

    return orig;
}

/*
- (void)_destroyCamera{
	//[self _associateQRController:nil];
	%orig;
}*/
- (void)_setCameraMode:(int)arg1 cameraDevice:(int)arg2 {
	NSLog(@"Set camera mode!");
	%orig;
}

- (void)_configureSessionWithCameraMode:(PLCameraMode)cameraMode cameraDevice:(PLCameraDevice)cameraDevice {

	/*if(cameraMode != PLCameraModePanorama){
		%orig;
	}*/

    	AVCaptureOutput *output = [[self _getQRController] output];
    if (!output) return;

    if (cameraMode == PLCameraModePhoto) {
        if ([[self currentSession] canAddOutput:output]) {
        	if(![[[self currentSession] outputs] containsObject:output]){
            	[[self currentSession] addOutput:output];
        	}
			[[self _getQRController] setEnabled:true];
        }else{
        	NSLog(@"Can't add output!");
        }
    } else {
		[[self _getQRController] setEnabled:false];

		if([[[self currentSession] outputs] containsObject:output]){

    		[[self currentSession] removeOutput:output];
    	}

    }

    //if(cameraMode == PLCameraModePanorama){
    	%orig;
    //}

    NSLog(@"Controller preview scale: %f", [[objc_getClass("PLCameraController") sharedInstance] panoramaPreviewScale]);
	CGSize previewSize = [[objc_getClass("PLCameraController") sharedInstance] panoramaPreviewSize];
	NSLog(@"Controller preview size: width: %f, height: %f", previewSize.width, previewSize.height);

    NSLog(@"%@", [[self currentSession] outputs]);
}

/*- (void)cameraControllerModeWillChange:(id)cameraController{
		AVCaptureOutput *output = [[self _getQRController] output];
    if (!output) return;
	[[self currentSession] removeOutput:output];

		[[self _getQRController] setEnabled:false];
		%orig;
}*/

%new
- (void)scannedSymbols:(ZBarSymbolSet*)symbols{
	for(ZBarSymbol *symbol in symbols){
		QRCode *code = [[QRCode alloc] initWithCodeData:[symbol data] outputController:[self _getQRController]];
 		[code performAction];
		//[code release];
	}
}

%end

%hook PLCameraPanoramaView

- (id)initWithFrame:(struct CGRect)arg1 centerYOffset:(float)arg2 panoramaPreviewScale:(float)arg3 panoramaPreviewSize:(struct CGSize)arg4{
	/*
	NSArray *stack = [NSThread callStackSymbols];
	NSString *methodThatDidLogging = [stack objectAtIndex:1];

	NSLog(@"Method: %@", methodThatDidLogging);

	NSLog(@"frame: width: %f height: %f", arg1.size.width, arg1.size.height);
	NSLog(@"Center Y offset: %f", arg2);
	NSLog(@"Preview scale: %f", arg3);
	NSLog(@"Preview Size: width: %f height: %f", arg4.width, arg4.height);

	NSLog(@"Controller preview scale: %f", [[objc_getClass("PLCameraController") sharedInstance] panoramaPreviewScale]);

	NSLog(@"Controller preview size: width: %f, height: %f", previewSize.width, previewSize.height);*/
	CGSize previewSize = CGSizeMake(306, 86);

	return %orig(arg1, arg2, 0.5, previewSize);
}

%end

static char qrGroupKey;

%hook PLCameraSettingsView

%new
- (void)setQRGroup:(id) object{
    objc_setAssociatedObject(self, &qrGroupKey, object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

%new
- (id)qrGroup {
    return objc_getAssociatedObject(self, &qrGroupKey);
}

- (id)initWithFrame:(CGRect)arg1 showGrid:(BOOL)arg2 showHDR:(BOOL)arg3 showPano:(BOOL)arg4{
	Class PLCameraSettingsGroupView = objc_getClass("PLCameraSettingsGroupView");

	UIView *qrGroup = [[PLCameraSettingsGroupView alloc] initWithFrame:CGRectMake(0, 0, arg1.size.width, 50)];
	[qrGroup setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
	[qrGroup setTitle:@"Enable QR"];

	UISwitch *qrSwitch = [[UISwitch alloc] init];
	[qrSwitch addTarget:[objc_getClass("PLCameraController") sharedInstance] action:@selector(qrCodeSwitchChanged:) forControlEvents:UIControlEventValueChanged];
	[qrSwitch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"PLQRIsEnabled"] animated:false];
	[[objc_getClass("PLCameraController") sharedInstance] qrCodeSwitchChanged:qrSwitch];
	[qrSwitch setOnTintColor:[UIColor colorWithRed:0.176 green:0.176 blue:0.176 alpha:1]];
	[qrGroup setAccessorySwitch:qrSwitch];

	CGRect arg1modifier = arg1;
	arg1modifier.size.height += qrGroup.frame.size.height + OPTIONS_PANE_SPACER_SIZE;

	self = %orig(arg1modifier, arg2, arg3, arg4);

	[self setClipsToBounds:true];

	[self setQRGroup:qrGroup];

	return self;

}

- (void)layoutSubviews{
	%orig;
	UIView *qrGroup = [self qrGroup];

	CGRect arg1modifier = [self frame];
	arg1modifier.size.height += qrGroup.frame.size.height + OPTIONS_PANE_SPACER_SIZE;
	[self setFrame:arg1modifier];

	[qrGroup setType:0];
	[self addSubview:qrGroup];

	for (UIView *subview in [self subviews]){
		if(subview == qrGroup) continue;
		CGRect frame = subview.frame;
		frame.origin.y += qrGroup.frame.size.height + OPTIONS_PANE_SPACER_SIZE;
		[subview setFrame:frame];
	}

	if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
		CGRect frame = [self frame];
		frame.origin.y -= qrGroup.frame.size.height + OPTIONS_PANE_SPACER_SIZE;
		[self setFrame:frame];
	}

}

%end

/*

%hook ABPersonTableViewActionsDelegate

- (id)addActionWithTitle:(id)arg1 content:(id)arg2 target:(id)arg3 selector:(SEL)arg4 property:(int)arg5 actionGrouping:(int)arg6 ordering:(int)arg7{
	NSLog(@"Title: %@", arg1);
	%orig;
}
- (id)addActionWithTitle:(id)arg1 shortTitle:(id)arg2 detailText:(id)arg3 style:(int)arg4 target:(id)arg5 selector:(SEL)arg6 property:(int)arg7 actionGrouping:(int)arg8 ordering:(int)arg9{
NSLog(@"Title: %@", arg1);
	%orig;
}
- (id)addActionWithTitle:(id)arg1 shortTitle:(id)arg2 target:(id)arg3 selector:(SEL)arg4 property:(int)arg5 actionGrouping:(int)arg6 ordering:(int)arg7{
NSLog(@"Title: %@", arg1);
	%orig;
}

%end*/

@interface ABActionSheetDelegate : NSObject{

}

-(BOOL)canShareContact;

@end

%hook SBAssistantController

- (BOOL)uiPlugin:(id)arg1 openURL:(id)arg2{
	NSLog(@"UIPlugin: %@", arg1);
	return %orig;
}

- (BOOL)uiPlugin:(id)arg1 launchApplicationWithBundleID:(id)arg2 openURL:(id)arg3{
	NSLog(@"(bundleID) UIPlugin: %@", arg1);
	return %orig;
}

%end

%hook ABPersonTableViewSharingDelegate

- (void)shareContact:(id)arg1{

	   UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share Contact Using:"
                                                                 delegate:self
                                                        cancelButtonTitle:nil
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
	if([self canSendMail]){
		[actionSheet addButtonWithTitle:@"Email"];
	}
	if([self canSendMMS]){
		[actionSheet addButtonWithTitle:@"Message"];
	}

	[actionSheet addButtonWithTitle:@"QR Code"];
	actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
	[actionSheet showInView:[[self helper] viewForActionSheet]];
	//[actionSheet release];
	//%orig;
}

%new
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	switch(buttonIndex){
		case 0:[self shareContactByEmail:self]; break;
		case 1:[self shareContactByTextMessage:self]; break;
		case 2:[self shareContactByQRCode]; break;
	}

}

- (BOOL)canShareContact{
	return true;
}

static UINavigationController *qrController;

%new
-(void)shareContactByQRCode{
	UIViewController *viewController = [[UIViewController alloc] init];
	UINavigationController *navController = [[UINavigationController alloc] init];

	[viewController setTitle:@"Share"];

	 UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(closeQRView)];

	viewController.navigationItem.rightBarButtonItem = closeButton;

	ABRecordRef person = [[self helper] _personToUseForAddressBook];

	ABRecordRef people[1];
	people[0] = person;
	CFArrayRef peopleArray = CFArrayCreate(NULL, (const void **)people, 1, &kCFTypeArrayCallBacks);
	NSData *vCardData = CFBridgingRelease(ABPersonCreateVCardRepresentationWithPeople(peopleArray));
	NSString *vCard = [[NSString alloc] initWithData:vCardData encoding:NSUTF8StringEncoding];

	 int qrcodeImageDimension = viewController.view.bounds.size.width;
	  DataMatrix* qrMatrix = [QREncoder encodeWithECLevel:QR_ECLEVEL_AUTO version:QR_VERSION_AUTO string:[self removeImageFromVCF:vCard]];
	  UIImage* qrcodeImage = [QREncoder renderDataMatrix:qrMatrix imageDimension:qrcodeImageDimension];
	 UIImageView* qrcodeImageView = [[UIImageView alloc] initWithImage:qrcodeImage];
	CGRect controllerFrame = [viewController.view frame];
	[qrcodeImageView setFrame:CGRectMake(0, 0, controllerFrame.size.width, controllerFrame.size.width)];

    UITableView *backgroundView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style: UITableViewStyleGrouped];
    backgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [viewController.view addSubview:backgroundView];
    [viewController.view addSubview:qrcodeImageView];

	[navController pushViewController:viewController animated:NO];

	viewController.view.backgroundColor = [UIColor whiteColor];
	[[[self helper] viewController] presentModalViewController:navController animated:YES];
	qrController = navController;

	[qrcodeImageView setCenter:[backgroundView center]];

	//[[self helper] pushViewController:viewController];
    /*UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(someMethod)];
    [self navigationItem] setLeftBarButtonItem:cancelButton];
    [cancelButton release];*/
}

%new
-(void)closeQRView{
	[qrController dismissModalViewControllerAnimated:true];
}

%new
- (NSString *)removeImageFromVCF:(NSString *)yourString { //Gracias freshking

NSScanner *theScanner;
NSString *text = nil;

theScanner = [NSScanner scannerWithString:yourString];

if ([yourString rangeOfString:@"X-SOCIALPROFILE"].location == NSNotFound) {

    while ([theScanner isAtEnd] == NO) {

        [theScanner scanUpToString:@"PHOTO" intoString:NULL] ;
        [theScanner scanUpToString:@"END:VCARD" intoString:&text] ;

        yourString = [yourString stringByReplacingOccurrencesOfString:
                      [NSString stringWithFormat:@"%@", text] withString:@""];
    }

}else{

    while ([theScanner isAtEnd] == NO) {

        [theScanner scanUpToString:@"PHOTO" intoString:NULL] ;
        [theScanner scanUpToString:@"X-SOCIALPROFILE" intoString:&text] ;

        [theScanner scanUpToString:@"END:VCARD" intoString:NULL];

        yourString = [yourString stringByReplacingOccurrencesOfString:
                      [NSString stringWithFormat:@"%@", text] withString:@""];

    }

}

return yourString;
}

%end


text:
<?php
	// location
	if(!isset($location)) {
		$location = Utility::currentPageURL();
	}
?>
<?php if(!isset($nomodal) || !$nomodal): ?>

<?php endif; ?>

Login to Felix Online

	<form action="<?php echo AUTHENTICATION_PATH; ?>login/?goto=<?php echo $location; ?>" id="loginForm" class="" method="post">

						IC Username

						<input type="text" name="username" id="user" class="small" placeholder="a.gast"/>

						IC Password

						<input type="password" name="password" id="password" placeholder="•••••••••••"/>

						Remember Me?

						<input type="checkbox" name="remember" id="rememberButton" value="rememberme" checked="checked" />

						<input type="submit" value="Login (SSL)" name="login" id="submit" class="login-button button small radius" />

	</form>
<?php if(!isset($nomodal) || !$nomodal): ?>
	<button class="close-button" data-close aria-label="Close modal" type="button">
		×
	</button>

<?php endif; ?>


text:
package com.facebook.buck.rules;

import com.facebook.buck.android.AndroidDirectoryResolver;
import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.util.ProcessExecutor;
import com.google.common.base.Optional;

import java.io.IOException;
import java.nio.file.Path;

/**
 * Contain items used to construct a {@link KnownBuildRuleTypes} that are shared between all
 * {@link Cell} instances.
 */
public class KnownBuildRuleTypesFactory {

  private final ProcessExecutor executor;
  private final AndroidDirectoryResolver directoryResolver;
  private final Optional<Path> testTempDirOverride;

  public KnownBuildRuleTypesFactory(
      ProcessExecutor executor,
      AndroidDirectoryResolver directoryResolver,
      Optional<Path> testTempDirOverride) {

    this.executor = executor;
    this.directoryResolver = directoryResolver;
    this.testTempDirOverride = testTempDirOverride;
  }

  public KnownBuildRuleTypes create(BuckConfig config) throws IOException, InterruptedException {
    return KnownBuildRuleTypes.createInstance(
        config,
        executor,
        directoryResolver,
        testTempDirOverride);
  }

}


text:
package main

import (
	"log"
	"net"
	"net/http"
	"net/rpc"

	"github.com/boltdb/bolt"
	"github.com/powerman/narada-go/narada/bootstrap"
	"github.com/powerman/rpc-codec/jsonrpc2"
	"github.com/qarea/ctxtg"
	"github.com/qarea/jirams/api"
	"github.com/qarea/jirams/cfg"
	"github.com/qarea/jirams/jira"
	"github.com/qarea/jirams/store"
)

type appParams struct {
	BoltDB    *bolt.DB
	PublicKey []byte
}

func start(params appParams) {
	var (
		httpListener net.Listener
	)
	userStore := store.New(params.BoltDB)
	jiraClient := jira.NewClient(userStore)
	tokenParser, err := ctxtg.NewRSATokenParser(params.PublicKey)
	if err != nil {
		panic(err)
	}
	rpcInterface := api.NewRPCAPI(jiraClient, tokenParser)
	rpc.Register(rpcInterface)

	http.Handle(cfg.HTTP.BasePath+"/rpc", jsonrpc2.HTTPHandler(nil))
	httpListener, err = net.Listen("tcp", cfg.HTTP.Listen)
	if err != nil {
		panic(err)
	}
	defer httpListener.Close()

	if err := bootstrap.Unlock(); err != nil {
		log.Fatal(err)
	}

	l.NOTICE("Listening on %s", httpListener.Addr().String())
	l.Fatal(http.Serve(httpListener, nil))
}


text:
<?php

namespace denbora\R_T_G_Services\services\RESTv3;

use denbora\R_T_G_Services\R_T_G_ServiceException;

class ServiceService extends RestV3Service
{
    const SERVICE_NAME = 'Service';

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getCurrenciesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetCurrencies', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getCommentGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetComment', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function updateCommentPUT($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'UpdateComment', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function deleteCommentDELETE($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'DeleteComment', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getDownloadUrlGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetDownloadUrl', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getCustomerTypesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetCustomerTypes', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getCustomerCategoriesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetCustomerCategories', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getCustomerStatusesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetCustomerStatuses', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     * @deprecated Use {@see \denbora\R_T_G_Services\services\RESTv2\AffiliateService::getDownloadsGET()}
     */
    public function getDownloadsGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetDownloads', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function searchCommentGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'SearchComment', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function createCommentPOST($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'CreateComment', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getDownloadIdPOST($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetDownloadId', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function pinCommentPOST($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'PinComment', $queryJSON);
    }
}


text:
package com.epam.ta.reportportal.dao;

import com.epam.ta.reportportal.entity.ServerSettings;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

/**
 * @author Ivan Budaev
 */
public interface ServerSettingsRepository extends ReportPortalRepository<ServerSettings, Long>, ServerSettingsRepositoryCustom {

	@Query(value = "INSERT INTO server_settings (key, value) VALUES ('secret.key', gen_random_bytes(32)) RETURNING value", nativeQuery = true)
	String generateSecret();

	Optional<ServerSettings> findByKey(String key);
}


text:
#include "pch.h"
#include "SmokeEffect.h"
#include "GameManager.h"
#include "ResourceManager.h"

bool SmokeEffect::init()
{
	if (!FlyRoundEffect::init())
	{
		return false;
	}

	return true;
}

void SmokeEffect::enter()
{
	setVisible(true);
}

void SmokeEffect::exit()
{
	m_IsDead = true;
}

void SmokeEffect::update(float dTime)
{
	FlyRoundEffect::update(dTime);

	setPosition(getPosition() + cocos2d::Point(-3 + (rand() % 6), 3));
}

void SmokeEffect::dead()
{
	removeFromParent();
}


text:
import os
import re
import sys

VALUE = "VALUE"
REF = "REF"
OUT = "OUT"

AstFromNeon = {
    None: ("TYPE_NOTHING", VALUE),
    "POINTER": ("TYPE_POINTER", VALUE),
    "Cell": ("TYPE_GENERIC", VALUE),
    "Boolean": ("TYPE_BOOLEAN", VALUE),
    "Number": ("TYPE_NUMBER", VALUE),
    "INOUT Number": ("TYPE_NUMBER", REF),
    "OUT Number": ("TYPE_NUMBER", OUT),
    "String": ("TYPE_STRING", VALUE),
    "INOUT String": ("TYPE_STRING", REF),
    "OUT String": ("TYPE_STRING", OUT),
    "Bytes": ("TYPE_BYTES", VALUE),
    "INOUT Bytes": ("TYPE_BYTES", REF),
    "OUT Bytes": ("TYPE_BYTES", OUT),
    "Object": ("TYPE_OBJECT", VALUE),
    "Array": ("TYPE_ARRAY", VALUE),
    "INOUT Array": ("TYPE_ARRAY", REF),
    "Array<Number>": ("TYPE_ARRAY_NUMBER", VALUE),
    "Array<String>": ("TYPE_ARRAY_STRING", VALUE),
    "INOUT Array<String>": ("TYPE_ARRAY_STRING", REF),
    "OUT Array<String>": ("TYPE_ARRAY_STRING", OUT),
    "Array<Object>": ("TYPE_ARRAY_OBJECT", VALUE),
    "Dictionary": ("TYPE_DICTIONARY", VALUE),
    "INOUT Dictionary": ("TYPE_DICTIONARY", REF),
    "Dictionary<Number>": ("TYPE_DICTIONARY_NUMBER", VALUE),
    "Dictionary<String>": ("TYPE_DICTIONARY_STRING", VALUE),
    "Dictionary<Object>": ("TYPE_DICTIONARY_OBJECT", VALUE),
}

CppFromAstParam = {
    ("TYPE_NOTHING", VALUE): "void",
    ("TYPE_GENERIC", VALUE): "Cell",
    ("TYPE_GENERIC", REF): "Cell *",
    ("TYPE_GENERIC", OUT): "Cell",
    ("TYPE_POINTER", VALUE): "void *",
    ("TYPE_POINTER", REF): "void **",
    ("TYPE_POINTER", OUT): "void *",
    ("TYPE_BOOLEAN", VALUE): "bool",
    ("TYPE_BOOLEAN", REF): "bool *",
    ("TYPE_NUMBER", VALUE): "Number",
    ("TYPE_NUMBER", REF): "Number *",
    ("TYPE_NUMBER", OUT): "Number",
    ("TYPE_STRING", VALUE): "const utf8string &",
    ("TYPE_STRING", REF): "utf8string *",
    ("TYPE_STRING", OUT): "utf8string",
    ("TYPE_BYTES", VALUE): "const std::vector<unsigned char> &",
    ("TYPE_BYTES", REF): "std::vector<unsigned char> *",
    ("TYPE_BYTES", OUT): "std::vector<unsigned char>",
    ("TYPE_OBJECT", VALUE): "std::shared_ptr<Object>",
    ("TYPE_ARRAY", VALUE): "Cell",
    ("TYPE_ARRAY", REF): "Cell *",
    ("TYPE_ARRAY_NUMBER", VALUE): "std::vector<Number>",
    ("TYPE_ARRAY_STRING", VALUE): "std::vector<utf8string>",
    ("TYPE_ARRAY_STRING", REF): "std::vector<utf8string>",
    ("TYPE_ARRAY_STRING", OUT): "std::vector<utf8string>",
    ("TYPE_ARRAY_OBJECT", VALUE): "std::vector<std::shared_ptr<Object>>",
    ("TYPE_DICTIONARY", VALUE): "Cell",
    ("TYPE_DICTIONARY", REF): "Cell *",
    ("TYPE_DICTIONARY_NUMBER", VALUE): "std::map<utf8string, Number>",
    ("TYPE_DICTIONARY_STRING", VALUE): "std::map<utf8string, utf8string>",
    ("TYPE_DICTIONARY_OBJECT", VALUE): "std::map<utf8string, std::shared_ptr<Object>>",
}

CppFromAstReturn = {
    ("TYPE_NOTHING", VALUE): "void",
    ("TYPE_GENERIC", VALUE): "Cell",
    ("TYPE_GENERIC", REF): "Cell *",
    ("TYPE_POINTER", VALUE): "void *",
    ("TYPE_POINTER", REF): "void **",
    ("TYPE_BOOLEAN", VALUE): "bool",
    ("TYPE_BOOLEAN", REF): "bool *",
    ("TYPE_NUMBER", VALUE): "Number",
    ("TYPE_NUMBER", REF): "Number *",
    ("TYPE_STRING", VALUE): "utf8string",
    ("TYPE_STRING", REF): "utf8string *",
    ("TYPE_BYTES", VALUE): "std::vector<unsigned char>",
    ("TYPE_BYTES", REF): "std::vector<unsigned char> *",
    ("TYPE_OBJECT", VALUE): "std::shared_ptr<Object>",
    ("TYPE_ARRAY", VALUE): "Cell",
    ("TYPE_ARRAY_NUMBER", VALUE): "std::vector<Number>",
    ("TYPE_ARRAY_STRING", VALUE): "std::vector<utf8string>",
    ("TYPE_ARRAY_STRING", REF): "std::vector<utf8string> *",
    ("TYPE_ARRAY_OBJECT", VALUE): "std::vector<std::shared_ptr<Object>>",
    ("TYPE_DICTIONARY_OBJECT", VALUE): "std::map<utf8string, std::shared_ptr<Object>>",
}

CppFromAstArg = {
    ("TYPE_POINTER", VALUE): "void *",
    ("TYPE_POINTER", REF): "void **",
    ("TYPE_POINTER", OUT): "void **",
    ("TYPE_GENERIC", VALUE): "Cell &",
    ("TYPE_GENERIC", REF): "Cell *",
    ("TYPE_GENERIC", OUT): "Cell *",
    ("TYPE_BOOLEAN", VALUE): "bool",
    ("TYPE_BOOLEAN", REF): "bool *",
    ("TYPE_NUMBER", VALUE): "Number",
    ("TYPE_NUMBER", REF): "Number *",
    ("TYPE_NUMBER", OUT): "Number *",
    ("TYPE_STRING", VALUE): "const utf8string &",
    ("TYPE_STRING", REF): "utf8string *",
    ("TYPE_STRING", OUT): "utf8string *",
    ("TYPE_BYTES", VALUE): "const std::vector<unsigned char> &",
    ("TYPE_BYTES", REF): "std::vector<unsigned char> *",
    ("TYPE_BYTES", OUT): "std::vector<unsigned char> *",
    ("TYPE_OBJECT", VALUE): "const std::shared_ptr<Object> &",
    ("TYPE_ARRAY", VALUE): "Cell &",
    ("TYPE_ARRAY", REF): "Cell *",
    ("TYPE_ARRAY_NUMBER", VALUE): "const std::vector<Number> &",
    ("TYPE_ARRAY_STRING", VALUE): "const std::vector<utf8string> &",
    ("TYPE_ARRAY_STRING", REF): "std::vector<utf8string> *",
    ("TYPE_ARRAY_STRING", OUT): "std::vector<utf8string> *",
    ("TYPE_ARRAY_OBJECT", VALUE): "std::vector<std::shared_ptr<Object>>",
    ("TYPE_DICTIONARY", VALUE): "Cell &",
    ("TYPE_DICTIONARY", REF): "Cell *",
    ("TYPE_DICTIONARY_NUMBER", VALUE): "const std::map<utf8string, Number> &",
    ("TYPE_DICTIONARY_STRING", VALUE): "const std::map<utf8string, utf8string> &",
    ("TYPE_DICTIONARY_OBJECT", VALUE): "std::map<utf8string, std::shared_ptr<Object>>",
}

JvmFromAst = {
    ("TYPE_NOTHING", VALUE): "V",
    ("TYPE_POINTER", VALUE): "Ljava/lang/Object;",
    ("TYPE_POINTER", REF): "Ljava/lang/Object;",
    ("TYPE_GENERIC", VALUE): "Ljava/lang/Object;",
    ("TYPE_GENERIC", REF): "Ljava/lang/Object;",
    ("TYPE_GENERIC", OUT): "Ljava/lang/Object;", # TODO
    ("TYPE_BOOLEAN", VALUE): "Ljava/lang/Boolean;",
    ("TYPE_NUMBER", VALUE): "Lneon/type/Number;",
    ("TYPE_NUMBER", REF): "Lneon/type/Number;",
    ("TYPE_NUMBER", OUT): "Lneon/type/Number;", # TODO
    ("TYPE_STRING", VALUE): "Ljava/lang/String;",
    ("TYPE_STRING", REF): "Ljava/lang/String;",
    ("TYPE_STRING", OUT): "Ljava/lang/String;", # TODO
    ("TYPE_BYTES", VALUE): "[B",
    ("TYPE_BYTES", REF): "[B",
    ("TYPE_BYTES", OUT): "Ljava/lang/Object;", # TODO
    ("TYPE_OBJECT", VALUE): "Ljava/lang/Object;",
    ("TYPE_ARRAY", VALUE): "Lneon/type/Array;",
    ("TYPE_ARRAY", REF): "Lneon/type/Array;",
    ("TYPE_ARRAY_NUMBER", VALUE): "Lneon/type/Array;",
    ("TYPE_ARRAY_STRING", VALUE): "Lneon/type/Array;",
    ("TYPE_ARRAY_STRING", OUT): "Lneon/type/Array;", # TODO
    ("TYPE_ARRAY_OBJECT", VALUE): "Lneon/type/Array;",
    ("TYPE_DICTIONARY", VALUE): "Ljava/util/Map;",
    ("TYPE_DICTIONARY", REF): "Ljava/util/Map;",
    ("TYPE_DICTIONARY_NUMBER", VALUE): "Ljava/util/Map;",
    ("TYPE_DICTIONARY_STRING", VALUE): "Ljava/util/Map;",
    ("TYPE_DICTIONARY_OBJECT", VALUE): "Ljava/util/Map;",
}

CellField = {
    ("TYPE_POINTER", VALUE): "address()",
    ("TYPE_POINTER", REF): "address()->address()",
    ("TYPE_BOOLEAN", VALUE): "boolean()",
    ("TYPE_BOOLEAN", REF): "address()->boolean()",
    ("TYPE_NUMBER", VALUE): "number()",
    ("TYPE_NUMBER", REF): "address()->number()",
    ("TYPE_STRING", VALUE): "string()",
    ("TYPE_STRING", REF): "address()->string_for_write()",
    ("TYPE_STRING", OUT): "address()->string_for_write()",
    ("TYPE_BYTES", VALUE): "bytes()",
    ("TYPE_BYTES", REF): "address()->bytes_for_write()",
    ("TYPE_BYTES", OUT): "address()->bytes()",
    ("TYPE_OBJECT", VALUE): "object()",
    ("TYPE_ARRAY_NUMBER", VALUE): "array()",
    ("TYPE_ARRAY_STRING", VALUE): "array()",
    ("TYPE_ARRAY_STRING", REF): "array()",
    ("TYPE_ARRAY_STRING", OUT): "array()",
    ("TYPE_DICTIONARY_STRING", VALUE): "dictionary()",
}

ArrayElementField = {
    ("TYPE_ARRAY_NUMBER", VALUE): "number()",
    ("TYPE_ARRAY_STRING", VALUE): "string()",
    ("TYPE_ARRAY_STRING", REF): "string()",
    ("TYPE_ARRAY_OBJECT", VALUE): "object()",
    ("TYPE_DICTIONARY_NUMBER", VALUE): "number()",
    ("TYPE_DICTIONARY_STRING", VALUE): "string()",
    ("TYPE_DICTIONARY_OBJECT", VALUE): "object()",
}

def parse_params(paramstr):
    r = []
    if not paramstr:
        return r, False
    def next_token(s, i):
        m = re.match(r"\s*([\w<>]+|.)", s[i:])
        if m is None:
            return "", i
        t = m.group(1)
        return t, i + m.end(0)
    i = 0
    while True:
        mode = ""
        names = []
        while True:
            t, i = next_token(paramstr, i)
            assert re.match(r"[\w_]+$", t), (paramstr, i, t)
            if t in ["OUT", "INOUT"]:
                mode = t
                t, i = next_token(paramstr, i)
            names.append(t)
            t, i = next_token(paramstr, i)
            if t != ",":
                break
        assert t == ":", (paramstr, i, t)
        t, i = next_token(paramstr, i)
        typename = t
        m = re.match(r"Array<(.*)>$", typename)
        if m is not None and m.group(1) not in ["Number", "String", "Object"]:
            typename = "Array"
        r.extend(zip(["{} {}".format(mode, typename).strip()] * len(names), names))
        t, i = next_token(paramstr, i)
        if t != ",":
            break
    variadic = False
    if t == "." and paramstr[i:i+2] == "..":
        variadic = True
        r[-1] = ("Array<" + r[-1][0] + ">", r[-1][1])
        t, i = next_token(paramstr, i)
        t, i = next_token(paramstr, i)
        t, i = next_token(paramstr, i)
    assert t in ["", "DEFAULT"], (paramstr, i, t)
    return r, variadic

enums = dict()
choices = dict()
variables = dict()
functions = dict()
exceptions = []
exported = set()

for fn in sys.argv[1:]:
    if fn.endswith(".neon"):
        prefix = os.path.basename(fn)[:-5] + "$"
        with open(fn) as f:
            in_enum = None
            in_choice = None
            for s in f:
                a = s.split()
                if a[:1] == ["TYPE"]:
                    m = re.match("TYPE\s+(\w+)\s+IS\s+(\S+)\s*(\s+IMPLEMENTS\s+\w+)?$", s)
                    assert m, s
                    name = m.group(1)
                    atype = m.group(2)
                    if atype == "POINTER":
                        AstFromNeon[name] = ("TYPE_POINTER", VALUE)
                        AstFromNeon["INOUT "+name] = ("TYPE_POINTER", REF)
                        AstFromNeon["OUT "+name] = ("TYPE_POINTER", OUT)
                    elif atype == "ENUM":
                        # TODO: Why is this TYPE_GENERIC? It should be TYPE_NUMBER.
                        AstFromNeon[name] = ("TYPE_GENERIC", VALUE)
                        AstFromNeon["INOUT "+name] = ("TYPE_GENERIC", REF)
                        enums[name] = []
                        in_enum = name
                    elif atype == "CHOICE":
                        AstFromNeon[name] = ("TYPE_GENERIC", VALUE)
                        choices[name] = []
                        in_choice = name
                    elif atype == "Object":
                        AstFromNeon[name] = ("TYPE_OBJECT", VALUE)
                        AstFromNeon["INOUT "+name] = ("TYPE_OBJECT", REF)
                        AstFromNeon["OUT "+name] = ("TYPE_OBJECT", OUT)
                    else:
                        AstFromNeon[name] = ("TYPE_GENERIC", VALUE)
                        AstFromNeon["INOUT "+name] = ("TYPE_GENERIC", REF)
                        AstFromNeon["OUT "+name] = ("TYPE_GENERIC", OUT)
                elif a[:3] == ["DECLARE", "NATIVE", "FUNCTION"]:
                    m = re.search(r"((\w+)\.)?(\w+)\((.*?)\)(:\s*(\S+))?\s*$", s)
                    assert m is not None
                    name = prefix + (m.group(2) + "__" if m.group(1) else "") + m.group(3)
                    paramstr = m.group(4)
                    rtype = m.group(6)
                    params, variadic = parse_params(paramstr)
                    functions[name] = [
                        name,
                        AstFromNeon[rtype],
                        rtype.split()[-1] if rtype is not None else None,
                        name in exported or prefix == "builtin$",
                        [AstFromNeon[x[0]] for x in params],
                        [x[0].split()[-1] for x in params],
                        [x[1] for x in params],
                        variadic
                    ]
                elif a[:3] == ["DECLARE", "NATIVE", "CONSTANT"]:
                    m = re.search(r"(\w+)\s*:\s*(\S+)", s)
                    assert m is not None
                    name = prefix + "_CONSTANT_" + m.group(1)
                    ntype = m.group(2)
                    assert ntype in ["Number", "String"]
                    ctype = ntype
                    if ctype == "String":
                        ctype = "utf8string"
                    a = name.split("$")
                    functions[name] = [
                        name,
                        AstFromNeon[ntype],
                        ntype,
                        name in exported,
                        [],
                        [],
                        [],
                        False
                    ]
                elif a[:3] == ["DECLARE", "NATIVE", "VAR"]:
                    m = re.search(r"(\w+)\s*:\s*(\S+)", s)
                    assert m is not None
                    name = prefix + m.group(1)
                    ntype = m.group(2)
                    atype = {
                        "Array<String>": "ast::TYPE_ARRAY_STRING",
                        "File": "dynamic_cast<const ast::Type *>(scope->lookupName(\"File\"))",
                        "Number": "ast::TYPE_NUMBER",
                        "TextFile": "dynamic_cast<const ast::Type *>(scope->lookupName(\"TextFile\"))",
                    }[ntype]
                    variables[name] = [name, atype]
                elif a[:1] == ["EXCEPTION"]:
                    exceptions.append((prefix, a[1]))
                elif a[:1] == ["EXPORT"]:
                    exported.add(prefix + a[1])
                elif in_enum:
                    if a[:2] == ["END", "ENUM"]:
                        in_enum = None
                    else:
                        enums[in_enum].append(a[0])
                elif in_choice:
                    if a[:2] == ["END", "CHOICE"]:
                        in_choice = None
                    else:
                        choices[in_choice].append(a[0].split(":")[0])
    else:
        print("Unexpected file: {}".format(fn), file=sys.stderr)
        sys.exit(1)

thunks = set()

for name, rtype, rtypename, exported, params, paramtypes, paramnames, variadic in functions.values():
    thunks.add((rtype, tuple(params)))

with open("gen/thunks.inc", "w") as inc:
    for rtype, params in thunks:
        print("static void thunk_{}_{}(opstack<Cell> &{}, void *func)".format(rtype[0], "_".join("{}_{}".format(p, m) for p, m in params), "stack" if (params or rtype[0] != "TYPE_NOTHING") else ""), file=inc)
        print("{", file=inc)
        d = 0
        for i, a in reversed(list(enumerate(params))):
            from_stack = True
            if a[0].startswith("TYPE_ARRAY_") and a[1] == VALUE:
                print("    {} a{};".format(CppFromAstParam[a], i), file=inc)
                print("    for (auto x: stack.peek({}).array()) a{}.push_back(x.{});".format(d, i, ArrayElementField[a]), file=inc)
            elif a[0].startswith("TYPE_ARRAY_") and a[1] == REF:
                print("    {} t{};".format(CppFromAstParam[a], i), file=inc)
                print("    for (auto x: stack.peek({}).address()->array()) t{}.push_back(x.{});".format(d, i, ArrayElementField[a]), file=inc)
                print("    {} *a{} = &t{};".format(CppFromAstParam[a], i, i), file=inc)
            elif a[0].startswith("TYPE_ARRAY_") and a[1] == OUT:
                print("    {} t{};".format(CppFromAstParam[a], i), file=inc)
                print("    {} *a{} = &t{};".format(CppFromAstParam[a], i, i), file=inc)
                from_stack = False
            elif a[0].startswith("TYPE_DICTIONARY_") and a[1] == VALUE:
                print("    {} a{};".format(CppFromAstParam[a], i), file=inc)
                print("    for (auto x: stack.peek({}).dictionary()) a{}[x.first] = x.second.{};".format(d, i, ArrayElementField[a]), file=inc)
            elif a in [("TYPE_GENERIC", VALUE), ("TYPE_ARRAY", VALUE), ("TYPE_DICTIONARY", VALUE)]:
                print("    {} a{} = stack.peek({});".format(CppFromAstParam[a], i, d), file=inc)
            elif a in [("TYPE_GENERIC", REF), ("TYPE_ARRAY", REF), ("TYPE_DICTIONARY", REF)]:
                print("    {} a{} = stack.peek({}).address();".format(CppFromAstParam[a], i, d), file=inc)
            elif a[1] == REF:
                print("    {} a{} = &stack.peek({}).{};".format(CppFromAstParam[a], i, d, CellField[a]), file=inc)
            elif a[1] == OUT:
                print("    {} t{};".format(CppFromAstParam[a], i), file=inc)
                print("    {} *a{} = &t{};".format(CppFromAstParam[a], i, i), file=inc)
                from_stack = False
            else:
                print("    {} a{} = stack.peek({}).{};".format(CppFromAstParam[a], i, d, CellField[a]), file=inc)
            if from_stack:
                d += 1
        stack_count = sum(1 for x in params if x[1] != OUT)
        assert d == stack_count
        print("    try {", file=inc)
        print("        {}reinterpret_cast<{} (*)({})>(func)({});".format("auto r = " if rtype[0] != "TYPE_NOTHING" else "", CppFromAstReturn[rtype], ",".join(CppFromAstArg[x] for x in params), ",".join("a{}".format(x) for x in range(len(params)))), file=inc)
        for i, a in reversed(list(enumerate(params))):
            d = len(params) - 1 - i
            if a[0].startswith("TYPE_ARRAY_") and a[1] == REF:
                print("        stack.peek({}).address()->array_for_write().clear();".format(d), file=inc)
                print("        for (auto x: t{}) stack.peek({}).address()->array_for_write().push_back(Cell(x));".format(i, d), file=inc)
        if params:
            print("        stack.drop({});".format(stack_count), file=inc)
        if rtype[0] != "TYPE_NOTHING":
            if rtype[0].startswith("TYPE_ARRAY_"):
                print("        std::vector<Cell> t;", file=inc)
                print("        for (auto x: r) t.push_back(Cell(x));", file=inc)
                print("        stack.push(Cell(t));", file=inc)
            elif rtype[0].startswith("TYPE_DICTIONARY_"):
                print("        std::map<utf8string, Cell> t;", file=inc)
                print("        for (auto x: r) t[x.first] = Cell(x.second);", file=inc)
                print("        stack.push(Cell(t));", file=inc)
            elif rtype[0] == "TYPE_POINTER":
                print("        stack.push(Cell::makeAddress(r));", file=inc)
            else:
                print("        stack.push(Cell(r));", file=inc)
        for i, a in reversed(list(enumerate(params))):
            if a[1] == OUT:
                if a[0].startswith("TYPE_ARRAY_"):
                    print("        std::vector<Cell> o{};".format(i), file=inc)
                    print("        for (auto x: t{}) o{}.push_back(Cell(x));".format(i, i), file=inc)
                    print("        stack.push(Cell(o{}));".format(i), file=inc)
                else:
                    print("        stack.push(Cell(t{}));".format(i), file=inc)
        print("    } catch (RtlException &) {", file=inc)
        if params:
            print("        stack.drop({});".format(stack_count), file=inc)
        print("        throw;", file=inc)
        print("    }", file=inc)
        print("}", file=inc)
        print("", file=inc)

with open("gen/variables_compile.inc", "w") as inc:
    print("static void init_builtin_variables(const std::string &module, ast::Scope *scope)", file=inc)
    print("{", file=inc)
    for name, atype in variables.values():
        i = name.index("$")
        module = name[:i]
        modname = name[i+1:]
        print("    if (module == \"{}\") scope->addName(Token(IDENTIFIER, \"{}\"), \"{}\", new ast::PredefinedVariable(\"{}\", {}));".format(module, modname, modname, name, atype), file=inc)
    print("}", file=inc)

with open("gen/variables_exec.inc", "w") as inc:
    print("namespace rtl {", file=inc)
    for name, atype in variables.values():
        a = name.split("$")
        print("namespace ne_{} {{ extern Cell VAR_{}; }}".format(a[0], a[1]), file=inc)
    print("}", file=inc)
    print("static struct {", file=inc)
    print("    const char *name;", file=inc)
    print("    Cell *value;", file=inc)
    print("} BuiltinVariables[] = {", file=inc)
    for name, atype, in variables.values():
        a = name.split("$")
        print("    {{\"{}\", &rtl::ne_{}::VAR_{}}},".format(name, a[0], a[1]), file=inc)
    print("};", file=inc)

with open("gen/functions_compile.inc", "w") as inc:
    print("struct PredefinedType {", file=inc)
    print("    const ast::Type *type;", file=inc)
    print("    const char *modtypename;", file=inc)
    print("};", file=inc)
    print("static struct {", file=inc)
    print("    const char *name;", file=inc)
    print("    PredefinedType returntype;", file=inc)
    print("    bool exported;", file=inc)
    print("    int count;", file=inc)
    print("    struct {ast::ParameterType::Mode mode; const char *name; PredefinedType ptype; } params[10];", file=inc)
    print("    bool variadic;", file=inc)
    print("}} BuiltinFunctions[{}];".format(len(functions)), file=inc)
    print("void init_builtin_functions() {", file=inc)
    bfi = 0
    for name, rtype, rtypename, exported, params, paramtypes, paramnames, variadic in functions.values():
        print("    BuiltinFunctions[{}] = {{\"{}\", {{{}, {}}}, {}, {}, {{{}}}, {}}};".format(
            bfi,
            name,
            "ast::"+rtype[0] if rtype[0] not in ["TYPE_GENERIC","TYPE_POINTER","TYPE_ARRAY","TYPE_DICTIONARY"] else "nullptr",
            "\"{}\"".format(rtypename) or "nullptr",
            "true" if exported else "false",
            len(params),
            ",".join("{{ast::ParameterType::Mode::{},\"{}\",{{{},{}}}}}".format("IN" if m == VALUE else "INOUT" if m == REF else "OUT", n, "ast::"+p if p not in ["TYPE_GENERIC","TYPE_POINTER","TYPE_ARRAY","TYPE_DICTIONARY"] else "nullptr", "\"{}\"".format(t) or "nullptr") for (p, m), t, n in zip(params, paramtypes, paramnames)),
            "true" if variadic else "false"
        ), file=inc)
        bfi += 1
    print("}", file=inc)

with open("gen/functions_compile_jvm.inc", "w") as inc:
    print("static struct {", file=inc)
    print("    const char *name;", file=inc)
    print("    const char *module;", file=inc)
    print("    const char *function;", file=inc)
    print("    const char *signature;", file=inc)
    print("} FunctionSignatures[] = {", file=inc)
    for name, rtype, rtypename, exported, params, paramtypes, paramnames, variadic in functions.values():
        module, function = name.split("$")
        if function in [
            "int",
        ]:
            function += "_"
        print("    {{\"{}\", \"{}\", \"{}\", \"{}\"}},".format(
            name,
            "neon/{}".format(module.title()),
            function,
            "(" + "".join(JvmFromAst[(p, m)] for (p, m), t, n in zip(params, paramtypes, paramnames)) + ")" + ("[Ljava/lang/Object;" if any(x[1] == REF for x in params) else JvmFromAst[rtype])
        ), file=inc)
    print("};", file=inc)

with open("gen/functions_exec.inc", "w") as inc:
    print("namespace rtl {", file=inc)
    cpp_name = {}
    for name, rtype, rtypename, exported, params, paramtypes, paramnames, variadic in functions.values():
        assert "." not in name
        a = name.split("$")
        if a[1] in [
            "int", "delete",
            "timegm",
        ] or a[0] in "curses":
            a[1] += "_"
        cpp_name[name] = "{}::{}".format(*a)
        print("namespace ne_{} {{ extern {} {}({}); }}".format(a[0], CppFromAstReturn[rtype], a[1], ", ".join(CppFromAstArg[x] for x in params)), file=inc)
    print("}", file=inc)
    print("static struct {", file=inc)
    print("    const char *name;", file=inc)
    print("    Thunk thunk;", file=inc)
    print("    void *func;", file=inc)
    print("} BuiltinFunctions[] = {", file=inc)
    for name, rtype, rtypename, exported, params, paramtypes, paramnames, variadic in functions.values():
        print("    {{\"{}\", {}, reinterpret_cast<void *>(rtl::ne_{})}},".format(name, "thunk_{}_{}".format(rtype[0], "_".join("{}_{}".format(p, m) for p, m in params)), cpp_name[name]), file=inc)
    print("};", file=inc)

with open("gen/enums.inc", "w") as inc:
    for name, values in enums.items():
        for i, v in enumerate(values):
            print("static const uint32_t ENUM_{}_{} = {};".format(name, v, i), file=inc)

with open("gen/choices.inc", "w") as inc:
    for name, values in choices.items():
        for i, v in enumerate(values):
            print("static const uint32_t CHOICE_{}_{} = {};".format(name, v, i), file=inc)

with open("gen/exceptions.inc", "w") as inc:
    print("struct ExceptionName {", file=inc)
    print("    const char *name;", file=inc)
    print("    const char *sub[10];", file=inc)
    print("};", file=inc)
    print("namespace rtl {", file=inc)
    for prefix, name in exceptions:
        print("namespace ne_{} {{ static const ExceptionName Exception_{} = {{\"{}\", {{{}NULL}}}}; }}".format(prefix[:-1], name.replace(".", "_"), name, "".join("\"{}\", ".format(e[1].split(".")[-1]) for e in exceptions if e[1].startswith(name+"."))), file=inc)
    print("", file=inc)
    print("}", file=inc)


text:
package net.runelite.rs.api;

import net.runelite.api.PlayerComposition;
import net.runelite.mapping.Import;

public interface RSPlayerComposition extends PlayerComposition
{
	@Import("isFemale")
	boolean isFemale();

	@Import("bodyPartColours")
	int[] getBodyPartColours();

	@Import("equipmentIds")
	@Override
	int[] getEquipmentIds();

	@Import("transformedNpcId")
	@Override
	void setTransformedNpcId(int id);
}


text:
"""Utilities for ImageNet data preprocessing & prediction decoding."""

import json
import warnings

import numpy as np

from keras import activations
from keras import backend
from keras.utils import data_utils

# isort: off
from tensorflow.python.util.tf_export import keras_export

CLASS_INDEX = None
CLASS_INDEX_PATH = (
    "https://storage.googleapis.com/download.tensorflow.org/"
    "data/imagenet_class_index.json"
)

PREPROCESS_INPUT_DOC = """
  Preprocesses a tensor or Numpy array encoding a batch of images.

  Usage example with `applications.MobileNet`:

  ```python
  i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
  x = tf.cast(i, tf.float32)
  x = tf.keras.applications.mobilenet.preprocess_input(x)
  core = tf.keras.applications.MobileNet()
  x = core(x)
  model = tf.keras.Model(inputs=[i], outputs=[x])

  image = tf.image.decode_png(tf.io.read_file('file.png'))
  result = model(image)
  ```

  Args:
    x: A floating point `numpy.array` or a `tf.Tensor`, 3D or 4D with 3 color
      channels, with values in the range [0, 255].
      The preprocessed data are written over the input data
      if the data types are compatible. To avoid this
      behaviour, `numpy.copy(x)` can be used.
    data_format: Optional data format of the image tensor/array. Defaults to
      None, in which case the global setting
      `tf.keras.backend.image_data_format()` is used (unless you changed it,
      it defaults to "channels_last").{mode}

  Returns:
      Preprocessed `numpy.array` or a `tf.Tensor` with type `float32`.
      {ret}

  Raises:
      {error}
  """

PREPROCESS_INPUT_MODE_DOC = """
    mode: One of "caffe", "tf" or "torch". Defaults to "caffe".
      - caffe: will convert the images from RGB to BGR,
          then will zero-center each color channel with
          respect to the ImageNet dataset,
          without scaling.
      - tf: will scale pixels between -1 and 1,
          sample-wise.
      - torch: will scale pixels between 0 and 1 and then
          will normalize each channel with respect to the
          ImageNet dataset.
  """

PREPROCESS_INPUT_DEFAULT_ERROR_DOC = """
    ValueError: In case of unknown `mode` or `data_format` argument."""

PREPROCESS_INPUT_ERROR_DOC = """
    ValueError: In case of unknown `data_format` argument."""

PREPROCESS_INPUT_RET_DOC_TF = """
      The inputs pixel values are scaled between -1 and 1, sample-wise."""

PREPROCESS_INPUT_RET_DOC_TORCH = """
      The input pixels values are scaled between 0 and 1 and each channel is
      normalized with respect to the ImageNet dataset."""

PREPROCESS_INPUT_RET_DOC_CAFFE = """
      The images are converted from RGB to BGR, then each color channel is
      zero-centered with respect to the ImageNet dataset, without scaling."""

@keras_export("keras.applications.imagenet_utils.preprocess_input")
def preprocess_input(x, data_format=None, mode="caffe"):
    """Preprocesses a tensor or Numpy array encoding a batch of images."""
    if mode not in {"caffe", "tf", "torch"}:
        raise ValueError(
            "Expected mode to be one of `caffe`, `tf` or `torch`. "
            f"Received: mode={mode}"
        )

    if data_format is None:
        data_format = backend.image_data_format()
    elif data_format not in {"channels_first", "channels_last"}:
        raise ValueError(
            "Expected data_format to be one of `channels_first` or "
            f"`channels_last`. Received: data_format={data_format}"
        )

    if isinstance(x, np.ndarray):
        return _preprocess_numpy_input(x, data_format=data_format, mode=mode)
    else:
        return _preprocess_symbolic_input(x, data_format=data_format, mode=mode)

preprocess_input.__doc__ = PREPROCESS_INPUT_DOC.format(
    mode=PREPROCESS_INPUT_MODE_DOC,
    ret="",
    error=PREPROCESS_INPUT_DEFAULT_ERROR_DOC,
)

@keras_export("keras.applications.imagenet_utils.decode_predictions")
def decode_predictions(preds, top=5):
    """Decodes the prediction of an ImageNet model.

    Args:
      preds: Numpy array encoding a batch of predictions.
      top: Integer, how many top-guesses to return. Defaults to 5.

    Returns:
      A list of lists of top class prediction tuples
      `(class_name, class_description, score)`.
      One list of tuples per sample in batch input.

    Raises:
      ValueError: In case of invalid shape of the `pred` array
        (must be 2D).
    """
    global CLASS_INDEX

    if len(preds.shape) != 2 or preds.shape[1] != 1000:
        raise ValueError(
            "`decode_predictions` expects "
            "a batch of predictions "
            "(i.e. a 2D array of shape (samples, 1000)). "
            "Found array with shape: " + str(preds.shape)
        )
    if CLASS_INDEX is None:
        fpath = data_utils.get_file(
            "imagenet_class_index.json",
            CLASS_INDEX_PATH,
            cache_subdir="models",
            file_hash="c2c37ea517e94d9795004a39431a14cb",
        )
        with open(fpath) as f:
            CLASS_INDEX = json.load(f)
    results = []
    for pred in preds:
        top_indices = pred.argsort()[-top:][::-1]
        result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices]
        result.sort(key=lambda x: x[2], reverse=True)
        results.append(result)
    return results

def _preprocess_numpy_input(x, data_format, mode):
    """Preprocesses a Numpy array encoding a batch of images.

    Args:
      x: Input array, 3D or 4D.
      data_format: Data format of the image array.
      mode: One of "caffe", "tf" or "torch".
        - caffe: will convert the images from RGB to BGR,
            then will zero-center each color channel with
            respect to the ImageNet dataset,
            without scaling.
        - tf: will scale pixels between -1 and 1,
            sample-wise.
        - torch: will scale pixels between 0 and 1 and then
            will normalize each channel with respect to the
            ImageNet dataset.

    Returns:
        Preprocessed Numpy array.
    """
    if not issubclass(x.dtype.type, np.floating):
        x = x.astype(backend.floatx(), copy=False)

    if mode == "tf":
        x /= 127.5
        x -= 1.0
        return x
    elif mode == "torch":
        x /= 255.0
        mean = [0.485, 0.456, 0.406]
        std = [0.229, 0.224, 0.225]
    else:
        if data_format == "channels_first":
            # 'RGB'->'BGR'
            if x.ndim == 3:
                x = x[::-1, ...]
            else:
                x = x[:, ::-1, ...]
        else:
            # 'RGB'->'BGR'
            x = x[..., ::-1]
        mean = [103.939, 116.779, 123.68]
        std = None

    # Zero-center by mean pixel
    if data_format == "channels_first":
        if x.ndim == 3:
            x[0, :, :] -= mean[0]
            x[1, :, :] -= mean[1]
            x[2, :, :] -= mean[2]
            if std is not None:
                x[0, :, :] /= std[0]
                x[1, :, :] /= std[1]
                x[2, :, :] /= std[2]
        else:
            x[:, 0, :, :] -= mean[0]
            x[:, 1, :, :] -= mean[1]
            x[:, 2, :, :] -= mean[2]
            if std is not None:
                x[:, 0, :, :] /= std[0]
                x[:, 1, :, :] /= std[1]
                x[:, 2, :, :] /= std[2]
    else:
        x[..., 0] -= mean[0]
        x[..., 1] -= mean[1]
        x[..., 2] -= mean[2]
        if std is not None:
            x[..., 0] /= std[0]
            x[..., 1] /= std[1]
            x[..., 2] /= std[2]
    return x

def _preprocess_symbolic_input(x, data_format, mode):
    """Preprocesses a tensor encoding a batch of images.

    Args:
      x: Input tensor, 3D or 4D.
      data_format: Data format of the image tensor.
      mode: One of "caffe", "tf" or "torch".
        - caffe: will convert the images from RGB to BGR,
            then will zero-center each color channel with
            respect to the ImageNet dataset,
            without scaling.
        - tf: will scale pixels between -1 and 1,
            sample-wise.
        - torch: will scale pixels between 0 and 1 and then
            will normalize each channel with respect to the
            ImageNet dataset.

    Returns:
        Preprocessed tensor.
    """
    if mode == "tf":
        x /= 127.5
        x -= 1.0
        return x
    elif mode == "torch":
        x /= 255.0
        mean = [0.485, 0.456, 0.406]
        std = [0.229, 0.224, 0.225]
    else:
        if data_format == "channels_first":
            # 'RGB'->'BGR'
            if backend.ndim(x) == 3:
                x = x[::-1, ...]
            else:
                x = x[:, ::-1, ...]
        else:
            # 'RGB'->'BGR'
            x = x[..., ::-1]
        mean = [103.939, 116.779, 123.68]
        std = None

    mean_tensor = backend.constant(-np.array(mean))

    # Zero-center by mean pixel
    if backend.dtype(x) != backend.dtype(mean_tensor):
        x = backend.bias_add(
            x,
            backend.cast(mean_tensor, backend.dtype(x)),
            data_format=data_format,
        )
    else:
        x = backend.bias_add(x, mean_tensor, data_format)
    if std is not None:
        std_tensor = backend.constant(np.array(std), dtype=backend.dtype(x))
        if data_format == "channels_first":
            std_tensor = backend.reshape(std_tensor, (-1, 1, 1))
        x /= std_tensor
    return x

def obtain_input_shape(
    input_shape,
    default_size,
    min_size,
    data_format,
    require_flatten,
    weights=None,
):
    """Internal utility to compute/validate a model's input shape.

    Args:
      input_shape: Either None (will return the default network input shape),
        or a user-provided shape to be validated.
      default_size: Default input width/height for the model.
      min_size: Minimum input width/height accepted by the model.
      data_format: Image data format to use.
      require_flatten: Whether the model is expected to
        be linked to a classifier via a Flatten layer.
      weights: One of `None` (random initialization)
        or 'imagenet' (pre-training on ImageNet).
        If weights='imagenet' input channels must be equal to 3.

    Returns:
      An integer shape tuple (may include None entries).

    Raises:
      ValueError: In case of invalid argument values.
    """
    if weights != "imagenet" and input_shape and len(input_shape) == 3:
        if data_format == "channels_first":
            if input_shape[0] not in {1, 3}:
                warnings.warn(
                    "This model usually expects 1 or 3 input channels. "
                    "However, it was passed an input_shape with "
                    + str(input_shape[0])
                    + " input channels.",
                    stacklevel=2,
                )
            default_shape = (input_shape[0], default_size, default_size)
        else:
            if input_shape[-1] not in {1, 3}:
                warnings.warn(
                    "This model usually expects 1 or 3 input channels. "
                    "However, it was passed an input_shape with "
                    + str(input_shape[-1])
                    + " input channels.",
                    stacklevel=2,
                )
            default_shape = (default_size, default_size, input_shape[-1])
    else:
        if data_format == "channels_first":
            default_shape = (3, default_size, default_size)
        else:
            default_shape = (default_size, default_size, 3)
    if weights == "imagenet" and require_flatten:
        if input_shape is not None:
            if input_shape != default_shape:
                raise ValueError(
                    "When setting `include_top=True` "
                    "and loading `imagenet` weights, "
                    f"`input_shape` should be {default_shape}.  "
                    f"Received: input_shape={input_shape}"
                )
        return default_shape
    if input_shape:
        if data_format == "channels_first":
            if input_shape is not None:
                if len(input_shape) != 3:
                    raise ValueError(
                        "`input_shape` must be a tuple of three integers."
                    )
                if input_shape[0] != 3 and weights == "imagenet":
                    raise ValueError(
                        "The input must have 3 channels; Received "
                        f"`input_shape={input_shape}`"
                    )
                if (
                    input_shape[1] is not None and input_shape[1] < min_size
                ) or (input_shape[2] is not None and input_shape[2] < min_size):
                    raise ValueError(
                        f"Input size must be at least {min_size}"
                        f"x{min_size}; Received: "
                        f"input_shape={input_shape}"
                    )
        else:
            if input_shape is not None:
                if len(input_shape) != 3:
                    raise ValueError(
                        "`input_shape` must be a tuple of three integers."
                    )
                if input_shape[-1] != 3 and weights == "imagenet":
                    raise ValueError(
                        "The input must have 3 channels; Received "
                        f"`input_shape={input_shape}`"
                    )
                if (
                    input_shape[0] is not None and input_shape[0] < min_size
                ) or (input_shape[1] is not None and input_shape[1] < min_size):
                    raise ValueError(
                        "Input size must be at least "
                        f"{min_size}x{min_size}; Received: "
                        f"input_shape={input_shape}"
                    )
    else:
        if require_flatten:
            input_shape = default_shape
        else:
            if data_format == "channels_first":
                input_shape = (3, None, None)
            else:
                input_shape = (None, None, 3)
    if require_flatten:
        if None in input_shape:
            raise ValueError(
                "If `include_top` is True, "
                "you should specify a static `input_shape`. "
                f"Received: input_shape={input_shape}"
            )
    return input_shape

def correct_pad(inputs, kernel_size):
    """Returns a tuple for zero-padding for 2D convolution with downsampling.

    Args:
      inputs: Input tensor.
      kernel_size: An integer or tuple/list of 2 integers.

    Returns:
      A tuple.
    """
    img_dim = 2 if backend.image_data_format() == "channels_first" else 1
    input_size = backend.int_shape(inputs)[img_dim : (img_dim + 2)]
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size)
    if input_size[0] is None:
        adjust = (1, 1)
    else:
        adjust = (1 - input_size[0] % 2, 1 - input_size[1] % 2)
    correct = (kernel_size[0] // 2, kernel_size[1] // 2)
    return (
        (correct[0] - adjust[0], correct[0]),
        (correct[1] - adjust[1], correct[1]),
    )

def validate_activation(classifier_activation, weights):
    """validates that the classifer_activation is compatible with the weights.

    Args:
      classifier_activation: str or callable activation function
      weights: The pretrained weights to load.

    Raises:
      ValueError: if an activation other than `None` or `softmax` are used with
        pretrained weights.
    """
    if weights is None:
        return

    classifier_activation = activations.get(classifier_activation)
    if classifier_activation not in {
        activations.get("softmax"),
        activations.get(None),
    }:
        raise ValueError(
            "Only `None` and `softmax` activations are allowed "
            "for the `classifier_activation` argument when using "
            "pretrained weights, with `include_top=True`; Received: "
            f"classifier_activation={classifier_activation}"
        )


text:
/**
 * Bootstraps the application and makes the ROUTER_PROVIDERS and the APP_BASE_HREF available to it.
 * @see https://angular.io/docs/ts/latest/api/platform-browser-dynamic/index/bootstrap-function.html
 */
// import { enableProdMode }   from '@angular/core';
// import { platformBrowser }  from '@angular/platform-browser';
// import { AppModule }        from './app.module';
// const platform = platformBrowser();
// import { AppModuleNgFactory } from './app.module.ngfactory';

// enableProdMode();

// platformBrowser().bootstrapModuleFactory(platform);

// In order to start the Service Worker located at "/worker-basic.min.js"
// uncomment this line. More about Service Workers here
// https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
//
// if ('serviceWorker' in navigator) {
//   (<any>navigator).serviceWorker.register('/worker-basic.min.js').then((registration: any) =>
//       console.log('ServiceWorker registration successful with scope: ', registration.scope))
//     .catch((err: any) =>
//       console.log('ServiceWorker registration failed: ', err));
// }


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/plas"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_centerInParent="true" />

</RelativeLayout>


text:
class Comunicate < ActiveRecord::Base
  belongs_to :atq
  belongs_to :product
end


text:
namespace media {

// Interface used by a decryptor to fire key events.
// See: http://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/encrypted-media.html#event-summary
class DecryptorClient {
 public:
  // Signals that a key has been added.
  virtual void KeyAdded(const std::string& key_system,
                        const std::string& session_id) = 0;

  // Signals that a key error occurred. The |system_code| is key
  // system-dependent. For clear key system, the |system_code| is always zero.
  virtual void KeyError(const std::string& key_system,
                        const std::string& session_id,
                        Decryptor::KeyError error_code,
                        int system_code) = 0;

  // Signals that a key message has been generated.
  virtual void KeyMessage(const std::string& key_system,
                          const std::string& session_id,
                          scoped_array<uint8> message,
                          int message_length,
                          const std::string& default_url) = 0;

  // Signals that a key is needed for decryption. |key_system| and |session_id|
  // can be empty if the key system has not been selected.
  // TODO(xhwang): Figure out if "type" is optional for NeedKey fired from the
  // decoder.
  virtual void NeedKey(const std::string& key_system,
                       const std::string& session_id,
                       const std::string& type,
                       scoped_array<uint8> init_data,
                       int init_data_length) = 0;

 protected:
  virtual ~DecryptorClient() {}
};

}  // namespace media

#endif  // MEDIA_BASE_DECRYPTOR_CLIENT_H_


text:
© • Dr. Eliezer Trybuch, DPM

Office Hours: 9am - 4pm Tuesday & Thursday


text:
import unreal_engine as ue
from unreal_engine import FARFilter

_filter = FARFilter()
_filter.class_names = ['StaticMesh']

# when passing True to the second argument of get_assets_by_filter(), you will get FAssetData instead of UObject
for asset_data in ue.get_assets_by_filter(_filter, True):
    has_custom_thumbnail = asset_data.has_custom_thumbnail()
    has_cached_thumbnail = asset_data.has_cached_thumbnail()
    try:
        thumbnail = asset_data.get_thumbnail()
    except:
        thumbnail = None
    ue.log('Asset: {0} Loaded: {1} CustomThumbnail: {2} CachedThumbnail: {3} Thumbnail: {4}'.format(asset_data.object_path, asset_data.is_asset_loaded(), has_custom_thumbnail, has_cached_thumbnail, thumbnail))


text:
// [START earthengine__apidocs__ee_featurecollection_first]
// A global power plant FeatureCollection.
var fc = ee.FeatureCollection('WRI/GPPD/power_plants');

print('The first feature (power plant) in the collection', fc.first());
// [END earthengine__apidocs__ee_featurecollection_first]


text:
package dev.clojurephant.plugin.clojurescript;

import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.file.DirectoryProperty;

public interface ClojureScriptExtension {
  DirectoryProperty getRootOutputDir();

  NamedDomainObjectContainer<ClojureScriptBuild> getBuilds();
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTeamsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('team_logo')->nullable();
            $table->string('slug', 65535);
            $table->enum('visibilty', [
                'private',
                'public'
            ]);
            $table->integer('user_id')->unsigned();
            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('teams');
    }
}


text:
package main

import (
	"beam.apache.org/learning/katas/core_transforms/map/pardo/pkg/task"
	"context"
	"github.com/apache/beam/sdks/go/pkg/beam"
	"github.com/apache/beam/sdks/go/pkg/beam/log"
	"github.com/apache/beam/sdks/go/pkg/beam/x/beamx"
	"github.com/apache/beam/sdks/go/pkg/beam/x/debug"
)

func main() {
	ctx := context.Background()

	p, s := beam.NewPipelineWithRoot()

	input := beam.Create(s, 1, 2, 3, 4, 5)

	output := task.ApplyTransform(s, input)

	debug.Print(s, output)

	err := beamx.Run(ctx, p)

	if err != nil {
		log.Exitf(context.Background(), "Failed to execute job: %v", err)
	}
}


text:
mqtt

test2222test


text:
layout: post
title: 'Velouté de berce et d'égopode :'
date: 2014-05-15 20:29:43.000000000 +02:00
categories:
- Recette
tags: []
status: publish
type: post
published: true
author:
  first_name: Laeti
excerpt:
---

- 50 % de berce
- 50 % d'égopode

Faire bouillir dans un peu d'eau 15 minutes

- Une échalote
- De la crème
- Sel, poivre
- ... pas trop d'épices, car le goût de la berce et de l'égopode au naturel est déjà magique ;-) !

Mixer et c'est fini ! Et c'est tellement bon !

<img class="alignleft wp-image-3433 size-thumbnail" src="/assets/CAM_0222-150x150.jpg" alt="Made by Samsung DVC" width="150" height="150" />


text:
<title>TestNG:  Test1</title>
<link href="../testng.css" rel="stylesheet" type="text/css" />
<link href="../my-testng.css" rel="stylesheet" type="text/css" />

Test1

Tests passed/Failed/Skipped:	0/1/0

Started on:	Mon Jul 28 22:32:44 MUT 2014

Total time:	62 seconds (62844 ms)

Included groups:

Excluded groups:

(Hover the method name to see the test class name)

FAILED TESTS

Test method
Exception
Time (seconds)
Instance

testUntitled
Test class: ru.st.selenium.LoginTest

org.openqa.selenium.WebDriverException: chrome not reachable
  (Session info: chrome=36.0.1985.125)
  (Driver info: chromedriver=2.10.267521,platform=Windows NT 5.1 SP3 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.97 seconds
Build info: version: '2.40.0', revision: '4c5c0568b004f67810ee41c459549aa4b09c651e', time: '2014-02-19 11:13:01'
System info: host: 'microsof-61a05c', ip: '192.168.0.105', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_65'
Session ID: c57fb274dbcbb28593161063e9f3b32a
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\DOCUME~1\Admin\LOCALS~1\Temp\scoped_dir5524_29399}, rotatable=false, locationContextEnabled=true, version=36.0.1985.125, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]
	at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
	at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:573)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:326)
	at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:367)
	at org.openqa.selenium.By$ById.findElement(By.java:214)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:318)
	at ru.st.selenium.LoginTest.testUntitled(LoginTest.java:20)
... Removed 31 stack frames

Click to show all stack frames

org.openqa.selenium.WebDriverException: chrome not reachable
  (Session info: chrome=36.0.1985.125)
  (Driver info: chromedriver=2.10.267521,platform=Windows NT 5.1 SP3 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.97 seconds
Build info: version: '2.40.0', revision: '4c5c0568b004f67810ee41c459549aa4b09c651e', time: '2014-02-19 11:13:01'
System info: host: 'microsof-61a05c', ip: '192.168.0.105', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_65'
Session ID: c57fb274dbcbb28593161063e9f3b32a
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\DOCUME~1\Admin\LOCALS~1\Temp\scoped_dir5524_29399}, rotatable=false, locationContextEnabled=true, version=36.0.1985.125, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
	at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
	at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:573)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:326)
	at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:367)
	at org.openqa.selenium.By$ById.findElement(By.java:214)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:318)
	at ru.st.selenium.LoginTest.testUntitled(LoginTest.java:20)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
	at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
	at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
	at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
	at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
	at org.testng.TestRunner.privateRun(TestRunner.java:767)
	at org.testng.TestRunner.run(TestRunner.java:617)
	at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
	at org.testng.SuiteRunner.run(SuiteRunner.java:254)
	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
	at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
	at org.testng.TestNG.run(TestNG.java:1057)
	at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:217)
	at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
	at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:92)
	at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

52
ru.st.selenium.LoginTest@1a8f100


text:
This script automates renewing your Let's Encrypt SSL certificate.

### Requirements
- git
- A working Apache HTTP server OR
- Access to the webroot for each domain being authenticated OR
- Ability to open port 80 to the outside world

### Installation

```sh
$ sudo git clone https://github.com/letsencrypt/letsencrypt /usr/share/letsencrypt
$ sudo mkdir /etc/letsencrypt
```

##### 1. Copy standalone.ini or webroot.ini based on your configuration

```sh
$ sudo cp webroot.ini /etc/letsencrypt/YOURDOMAIN.com.ini
```

##### 2. Edit /etc/letsencrypt/YOURDOMAIN.com.ini to match your settings. Add all subdomains that you need. Leave test mode enabled to make sure your settings are correct.

```sh
$ sudo mkdir /root/bin ; sudo cp autorenew-letsencrypt-cert.sh /root/bin
```

##### 3. Edit root's crontab to make this run monthly. Add the contents from the "crontab" file in this repo.

```sh
$ sudo crontab -e
```

##### 4. Run the script.

```sh
$ sudo /root/bin/autorenew-letsencrypt-cert.sh mydomain.com
```

##### 5. If your configuration is correct, edit /etc/letsencrypt/YOURDOMAIN.com.ini and comment out the following line:

```
; server = https://acme-staging.api.letsencrypt.org/directory
```

##### 6. Run the script again, but this time in live mode!

```sh
$ sudo /root/bin/autorenew-letsencrypt-cert.sh mydomain.com
```

##### 7. Have fun! :)


text:
package gg.uhc.uhc.modules.team.prefixes;

import gg.uhc.flagcommands.converters.EnumConverter;
import gg.uhc.flagcommands.joptsimple.ValueConversionException;
import gg.uhc.flagcommands.joptsimple.ValueConverter;

import com.google.common.collect.Sets;
import org.bukkit.ChatColor;

import java.util.Set;

public class PrefixColourPredicateConverter implements ValueConverter<PrefixColourPredicate> {

    protected final EnumConverter<ChatColor> colourConverter = EnumConverter.forEnum(ChatColor.class);

    @Override
    public PrefixColourPredicate convert(String toConvert) {
        boolean exact = false;
        String value = toConvert;

        if (value.length() > 0 && value.charAt(0) == '=') {
            exact = true;
            value = value.substring(1);
        }

        final String[] parts = value.split("\\+");

        if (parts.length == 0) {
            throw new ValueConversionException("Must supply at least 1 formatting code to filter out");
        }

        final Set<ChatColor> colours = Sets.newHashSetWithExpectedSize(parts.length);

        for (final String part : parts) {
            colours.add(colourConverter.convert(part));
        }

        return new PrefixColourPredicate(exact, colours);
    }

    @Override
    public Class<PrefixColourPredicate> valueType() {
        return PrefixColourPredicate.class;
    }

    @Override
    public String valuePattern() {
        return null;
    }
}


text:
<?php

/**
 * Add_project Class
 *
 * @category	Projects
 * @author	Sawan Eranga
 * @link	http://localhost/seppro/index.php/Add_project
 */

class Project extends CI_Controller {

    /**
     * Constructor
     *
     * @access	public
     * @param	none
     * @return	none
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * Load the add_project view
     *
     * @access	public
     * @param	none
     * @return	none
     */
    public function index() {
        $this->load->view('project/add_project');
    }

    /**
     * form submit controller function
     *
     * @access	public
     * @param	none
     * @return	none
     */
    public function frm_submit() {
        $this->load->model('Project_model/Project_model');
        $sta = $this->Project_model->set_project_info();
        echo $sta;
    }

    /**
     * View project controller function
     *
     * @access	public
     * @param	none
     * @return	none
     */
    public function view_project() {
        $this->load->model('Project_model/Project_model');
        $all_data["prj"] = $this->Project_model->get_project_info();
        $this->load->view('project/view_project',$all_data);
    }

    public function update_project() {
//        $this->load->model('Project_model/Project_model');
//        $all_data["prj"] = $this->Project_model->get_project_info();
        $this->load->view('project/update_project');
    }
}


text:
// Copyright John Maddock 2006.
// Copyright Paul A. Bristow 2007, 2010.

// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

// test_gamma_dist.cpp

// http://en.wikipedia.org/wiki/Gamma_distribution
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm
// Also:
// Weisstein, Eric W. "Gamma Distribution."
// From MathWorld--A Wolfram Web Resource.
// http://mathworld.wolfram.com/GammaDistribution.html

#include <pch.hpp> // include directory libs/math/src/tr1/ is needed.

#include <boost/math/concepts/real_concept.hpp> // for real_concept
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp> // Boost.Test
#include <boost/test/floating_point_comparison.hpp>

#include <boost/math/distributions/gamma.hpp>
    using boost::math::gamma_distribution;
#include <boost/math/tools/test.hpp>
#include "test_out_of_range.hpp"

#include <iostream>
#include <iomanip>
   using std::cout;
   using std::endl;
   using std::setprecision;
#include <limits>
  using std::numeric_limits;

template <class RealType>
RealType NaivePDF(RealType shape, RealType scale, RealType x)
{
   // Deliberately naive PDF calculator again which
   // we'll compare our pdf function.  However some
   // published values to compare against would be better....
   using namespace std;
   RealType result = log(x) * (shape - 1) - x / scale - boost::math::lgamma(shape) - log(scale) * shape;
   return exp(result);
}

template <class RealType>
void check_gamma(RealType shape, RealType scale, RealType x, RealType p, RealType q, RealType tol)
{
   BOOST_CHECK_CLOSE(
      ::boost::math::cdf(
         gamma_distribution<RealType>(shape, scale),    // distribution.
         x),                                            // random variable.
         p,                                             // probability.
         tol);                                          // %tolerance.
   BOOST_CHECK_CLOSE(
      ::boost::math::cdf(
         complement(
            gamma_distribution<RealType>(shape, scale), // distribution.
            x)),                                        // random variable.
         q,                                             // probability complement.
         tol);                                          // %tolerance.
   if(p < 0.999)
   {
      BOOST_CHECK_CLOSE(
         ::boost::math::quantile(
            gamma_distribution<RealType>(shape, scale),    // distribution.
            p),                                            // probability.
            x,                                             // random variable.
            tol);                                          // %tolerance.
   }
   if(q < 0.999)
   {
      BOOST_CHECK_CLOSE(
         ::boost::math::quantile(
            complement(
               gamma_distribution<RealType>(shape, scale), // distribution.
               q)),                                        // probability complement.
            x,                                             // random variable.
            tol);                                          // %tolerance.
   }
   // PDF:
   BOOST_CHECK_CLOSE(
      boost::math::pdf(
         gamma_distribution<RealType>(shape, scale),    // distribution.
         x),                                            // random variable.
         NaivePDF(shape, scale, x),                     // PDF
         tol);                                          // %tolerance.
}

template <class RealType>
void test_spots(RealType)
{
   // Basic sanity checks
   //
   // 15 decimal places expressed as a persentage.
   // The first tests use values generated by MathCAD,
   // and should be accurate to around double precision.
   //
   RealType tolerance = (std::max)(RealType(5e-14f), std::numeric_limits<RealType>::epsilon() * 20) * 100;
   cout << "Tolerance for type " << typeid(RealType).name()  << " is " << tolerance << " %" << endl;

   check_gamma(
      static_cast<RealType>(0.5),
      static_cast<RealType>(1),
      static_cast<RealType>(0.5),
      static_cast<RealType>(0.682689492137085),
      static_cast<RealType>(1-0.682689492137085),
      tolerance);
   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1),
      static_cast<RealType>(0.5),
      static_cast<RealType>(0.090204010431050),
      static_cast<RealType>(1-0.090204010431050),
      tolerance);
   check_gamma(
      static_cast<RealType>(40),
      static_cast<RealType>(1),
      static_cast<RealType>(10),
      static_cast<RealType>(7.34163631456064E-13),
      static_cast<RealType>(1-7.34163631456064E-13),
      tolerance);

   //
   // Some more test data generated by the online
   // calculator at http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm
   // This has the advantage of supporting the scale parameter as well
   // as shape, but has only a few digits accuracy, and produces
   // some deeply suspect values if the shape parameter is < 1
   // (it doesn't agree with MathCAD or this implementation).
   // To be fair the incomplete gamma is tricky to get right in this area...
   //
   tolerance = 1e-5f * 100; // 5 decimal places as a persentage
   cout << "Tolerance for type " << typeid(RealType).name()  << " is " << tolerance << " %" << endl;

   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1)/5,
      static_cast<RealType>(0.1),
      static_cast<RealType>(0.090204),
      static_cast<RealType>(1-0.090204),
      tolerance);
   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1)/5,
      static_cast<RealType>(0.5),
      static_cast<RealType>(1-0.287298),
      static_cast<RealType>(0.287298),
      tolerance);
   check_gamma(
      static_cast<RealType>(3),
      static_cast<RealType>(2),
      static_cast<RealType>(1),
      static_cast<RealType>(0.014388),
      static_cast<RealType>(1-0.014388),
      tolerance * 10); // one less decimal place in the test value
   check_gamma(
      static_cast<RealType>(3),
      static_cast<RealType>(2),
      static_cast<RealType>(5),
      static_cast<RealType>(0.456187),
      static_cast<RealType>(1-0.456187),
      tolerance);

    RealType tol2 = boost::math::tools::epsilon<RealType>() * 5 * 100;  // 5 eps as a persentage
    gamma_distribution<RealType> dist(8, 3);
    RealType x = static_cast<RealType>(0.125);
    using namespace std; // ADL of std names.
    // mean:
    BOOST_CHECK_CLOSE(
       mean(dist)
       , static_cast<RealType>(8*3), tol2);
    // variance:
    BOOST_CHECK_CLOSE(
       variance(dist)
       , static_cast<RealType>(8*3*3), tol2);
    // std deviation:
    BOOST_CHECK_CLOSE(
       standard_deviation(dist)
       , sqrt(static_cast<RealType>(8*3*3)), tol2);
    // hazard:
    BOOST_CHECK_CLOSE(
       hazard(dist, x)
       , pdf(dist, x) / cdf(complement(dist, x)), tol2);
    // cumulative hazard:
    BOOST_CHECK_CLOSE(
       chf(dist, x)
       , -log(cdf(complement(dist, x))), tol2);
    // coefficient_of_variation:
    BOOST_CHECK_CLOSE(
       coefficient_of_variation(dist)
       , standard_deviation(dist) / mean(dist), tol2);
    // mode:
    BOOST_CHECK_CLOSE(
       mode(dist)
       , static_cast<RealType>(7 * 3), tol2);
    // skewness:
    BOOST_CHECK_CLOSE(
       skewness(dist)
       , 2 / sqrt(static_cast<RealType>(8)), tol2);
    // kertosis:
    BOOST_CHECK_CLOSE(
       kurtosis(dist)
       , 3 + 6 / static_cast<RealType>(8), tol2);
    // kertosis excess:
    BOOST_CHECK_CLOSE(
       kurtosis_excess(dist)
       , 6 / static_cast<RealType>(8), tol2);

    BOOST_CHECK_CLOSE(
       median(dist), static_cast<RealType>(23.007748327502412), // double precision test value
       (std::max)(tol2, static_cast<RealType>(std::numeric_limits<double>::epsilon() * 2 * 100))); // 2 eps as persent
    // Rely on default definition in derived accessors.

   // error tests
   check_out_of_range<boost::math::gamma_distribution<RealType> >(1, 1);
   BOOST_CHECK_THROW(boost::math::gamma_distribution<RealType>(0, 1), std::domain_error);
   BOOST_CHECK_THROW(boost::math::gamma_distribution<RealType>(-1, 1), std::domain_error);
   BOOST_CHECK_THROW(boost::math::gamma_distribution<RealType>(1, 0), std::domain_error);
   BOOST_CHECK_THROW(boost::math::gamma_distribution<RealType>(1, -1), std::domain_error);

} // template <class RealType>void test_spots(RealType)

BOOST_AUTO_TEST_CASE( test_main )
{
   // Basic sanity-check spot values.
   // (Parameter value, arbitrarily zero, only communicates the floating point type).
  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %
  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  test_spots(0.0L); // Test long double.
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.
#endif
#else
   std::cout << "<note>The long double tests have been disabled on this platform "
      "either because the long double overloads of the usual math functions are "
      "not available at all, or because they are too inaccurate for these tests "
      "to pass.</note>" << std::cout;
#endif

} // BOOST_AUTO_TEST_CASE( test_main )

/*

Output:

Autorun "i:\boost-06-05-03-1300\libs\math\test\Math_test\debug\test_gamma_dist.exe"
Running 1 test case...
Tolerance for type float is 0.000238419 %
Tolerance for type float is 0.001 %
Tolerance for type double is 5e-012 %
Tolerance for type double is 0.001 %
Tolerance for type long double is 5e-012 %
Tolerance for type long double is 0.001 %
Tolerance for type class boost::math::concepts::real_concept is 5e-012 %
Tolerance for type class boost::math::concepts::real_concept is 0.001 %
*** No errors detected

*/