text:
using System.IO;
using AutoObjectBuilder;
using NUnit.Framework;
using ObjectAutoBuilder.Test.Base;
using ObjectAutoBuilder.Test.Helper;

namespace ObjectAutoBuilder.Test.Integration
{
    public class SystemInfoFixture : TestFixtureBase
    {
        [Test]
        public void T1()
        {
            FileInfo info = Auto.Make<FileInfo>();

            Assert.That(info, Is.Not.Null);
            Assert.That(info.FullName, Is.EqualTo(@"C:\filename"));
        }

        [Test]
        public void T2()
        {
            SystemInfoTest info = Auto.Make<SystemInfoTest>();

            Assert.That(info, Is.Not.Null);
            Assert.That(info.FilePath.FullName, Is.EqualTo(@"C:\filepath"));
        }

        [Test]
        public void T3()
        {
            DirectoryInfo info = Auto.Make<DirectoryInfo>();

            Assert.That(info, Is.Not.Null);
            Assert.That(info.FullName, Is.EqualTo(@"C:\directoryname"));
        }

        [Test]
        public void T4()
        {
            SystemInfoTest info = Auto.Make<SystemInfoTest>();

            Assert.That(info, Is.Not.Null);
            Assert.That(info.DirectoryPath.FullName, Is.EqualTo(@"C:\directorypath"));
        }
    }
}


text:
module Imgix
  module InstanceMethods
    # def attachment_for(name, options)
    #   @_attachments ||= {}
    #   @_attachments[name] ||= Imgix::Attachment.new(name, self, options)
    # end

    # Detrmine the base url given the imgix configurations
    def base_url
        url = URI::Generic.build(
            scheme: self.class.imgix_config.protocol(),
            host: [self.class.imgix_config.subdomain(), self.class.imgix_config.base_url()].join(".")
        )

        return url
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef COLLECT_VIEW_H
#define COLLECT_VIEW_H

#include "contiki-conf.h"
#include "net/linkaddr.h"
#include "net/rime/collect.h"

struct collect_view_data_msg {
  uint16_t len;
  uint16_t clock;
  uint16_t timesynch_time;
  uint16_t cpu;
  uint16_t lpm;
  uint16_t transmit;
  uint16_t listen;
  uint16_t parent;
  uint16_t parent_etx;
  uint16_t current_rtmetric;
  uint16_t num_neighbors;
  uint16_t beacon_interval;

  uint16_t sensors[10];
};

void collect_view_construct_message(struct collect_view_data_msg *msg,
                                    const linkaddr_t *parent,
                                    uint16_t etx_to_parent,
                                    uint16_t current_rtmetric,
                                    uint16_t num_neighbors,
                                    uint16_t beacon_interval);

void collect_view_arch_read_sensors(struct collect_view_data_msg *msg);

#endif /* COLLECT_VIEW_H */


text:
<?php

declare(strict_types = 1);

namespace Sop\X509\AttributeCertificate;

use Sop\ASN1\Element;
use Sop\ASN1\Type\Constructed\Sequence;
use Sop\ASN1\Type\Primitive\BitString;
use Sop\ASN1\Type\Primitive\Enumerated;
use Sop\ASN1\Type\Primitive\ObjectIdentifier;
use Sop\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
use Sop\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType;

/**
 * Implements *ObjectDigestInfo* ASN.1 type.
 *
 * @see https://tools.ietf.org/html/rfc5755#section-4.1
 * @see https://tools.ietf.org/html/rfc5755#section-7.3
 */
class ObjectDigestInfo
{
    const TYPE_PUBLIC_KEY = 0;
    const TYPE_PUBLIC_KEY_CERT = 1;
    const TYPE_OTHER_OBJECT_TYPES = 2;

    /**
     * Object type.
     *
     * @var int
     */
    protected $_digestedObjectType;

    /**
     * OID of other object type.
     *
     * @var null|string
     */
    protected $_otherObjectTypeID;

    /**
     * Digest algorithm.
     *
     * @var AlgorithmIdentifierType
     */
    protected $_digestAlgorithm;

    /**
     * Object digest.
     *
     * @var BitString
     */
    protected $_objectDigest;

    /**
     * Constructor.
     *
     * @param int                     $type
     * @param AlgorithmIdentifierType $algo
     * @param BitString               $digest
     */
    public function __construct(int $type, AlgorithmIdentifierType $algo,
        BitString $digest)
    {
        $this->_digestedObjectType = $type;
        $this->_otherObjectTypeID = null;
        $this->_digestAlgorithm = $algo;
        $this->_objectDigest = $digest;
    }

    /**
     * Initialize from ASN.1.
     *
     * @param Sequence $seq
     *
     * @return self
     */
    public static function fromASN1(Sequence $seq): ObjectDigestInfo
    {
        $idx = 0;
        $oid = null;
        $type = $seq->at($idx++)->asEnumerated()->intNumber();
        if ($seq->has($idx, Element::TYPE_OBJECT_IDENTIFIER)) {
            $oid = $seq->at($idx++)->asObjectIdentifier()->oid();
        }
        $algo = AlgorithmIdentifier::fromASN1($seq->at($idx++)->asSequence());
        $digest = $seq->at($idx)->asBitString();
        $obj = new self($type, $algo, $digest);
        $obj->_otherObjectTypeID = $oid;
        return $obj;
    }

    /**
     * Generate ASN.1 structure.
     *
     * @return Sequence
     */
    public function toASN1(): Sequence
    {
        $elements = [new Enumerated($this->_digestedObjectType)];
        if (isset($this->_otherObjectTypeID)) {
            $elements[] = new ObjectIdentifier($this->_otherObjectTypeID);
        }
        $elements[] = $this->_digestAlgorithm->toASN1();
        $elements[] = $this->_objectDigest;
        return new Sequence(...$elements);
    }
}


text:
$(document).ready(function() {
    // Init Materialize components
    $('.button-collapse').sideNav({
            //menuWidth: 300, // Default is 240
            //edge: 'right', // Choose the horizontal origin
            closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor
        }
    );

    // Hide all pages but the dashboard
    $('.page').not('#pageDashboard').hide().css({left: '-200vw'});

    // Switch pages on nav-link clicks
    $('.nav-link').on('click', function(e) {
        e.preventDefault();
        $('.nav-link').not($(this)).parent().removeClass('active');
        $(this).parent().addClass('active');
        var page = $(this).attr('href');
        $.display.toggleLoadingScreen();
        $.display.switchPage(page);
    });
});


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.AutoScaling.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;

namespace Amazon.AutoScaling.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Create Launch Configuration Request Marshaller
    /// </summary>
    public class CreateLaunchConfigurationRequestMarshaller : IMarshaller<IRequest, CreateLaunchConfigurationRequest>
    {
        public IRequest Marshall(CreateLaunchConfigurationRequest createLaunchConfigurationRequest)
        {
            IRequest request = new DefaultRequest(createLaunchConfigurationRequest, "AmazonAutoScaling");
            request.Parameters.Add("Action", "CreateLaunchConfiguration");
            request.Parameters.Add("Version", "2011-01-01");
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetLaunchConfigurationName())
            {
                request.Parameters.Add("LaunchConfigurationName", StringUtils.FromString(createLaunchConfigurationRequest.LaunchConfigurationName));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetImageId())
            {
                request.Parameters.Add("ImageId", StringUtils.FromString(createLaunchConfigurationRequest.ImageId));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetKeyName())
            {
                request.Parameters.Add("KeyName", StringUtils.FromString(createLaunchConfigurationRequest.KeyName));
            }
            if (createLaunchConfigurationRequest != null)
            {
                List<string> securityGroupsList = createLaunchConfigurationRequest.SecurityGroups;

                int securityGroupsListIndex = 1;
                foreach (string securityGroupsListValue in securityGroupsList)
                {
                    request.Parameters.Add("SecurityGroups.member." + securityGroupsListIndex, StringUtils.FromString(securityGroupsListValue));
                    securityGroupsListIndex++;
                }
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetUserData())
            {
                request.Parameters.Add("UserData", StringUtils.FromString(createLaunchConfigurationRequest.UserData));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetInstanceType())
            {
                request.Parameters.Add("InstanceType", StringUtils.FromString(createLaunchConfigurationRequest.InstanceType));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetKernelId())
            {
                request.Parameters.Add("KernelId", StringUtils.FromString(createLaunchConfigurationRequest.KernelId));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetRamdiskId())
            {
                request.Parameters.Add("RamdiskId", StringUtils.FromString(createLaunchConfigurationRequest.RamdiskId));
            }

            if (createLaunchConfigurationRequest != null)
            {
                List<BlockDeviceMapping> blockDeviceMappingsList = createLaunchConfigurationRequest.BlockDeviceMappings;
                int blockDeviceMappingsListIndex = 1;
                foreach (BlockDeviceMapping blockDeviceMappingsListValue in blockDeviceMappingsList)
                {
                    if (blockDeviceMappingsListValue != null && blockDeviceMappingsListValue.IsSetVirtualName())
                    {
                        request.Parameters.Add("BlockDeviceMappings.member." + blockDeviceMappingsListIndex + ".VirtualName", StringUtils.FromString(blockDeviceMappingsListValue.VirtualName));
                    }
                    if (blockDeviceMappingsListValue != null && blockDeviceMappingsListValue.IsSetDeviceName())
                    {
                        request.Parameters.Add("BlockDeviceMappings.member." + blockDeviceMappingsListIndex + ".DeviceName", StringUtils.FromString(blockDeviceMappingsListValue.DeviceName));
                    }
                    if (blockDeviceMappingsListValue != null)
                    {
                        Ebs ebs = blockDeviceMappingsListValue.Ebs;
                        if (ebs != null && ebs.IsSetSnapshotId())
                        {
                            request.Parameters.Add("BlockDeviceMappings.member." + blockDeviceMappingsListIndex + ".Ebs.SnapshotId", StringUtils.FromString(ebs.SnapshotId));
                        }
                        if (ebs != null && ebs.IsSetVolumeSize())
                        {
                            request.Parameters.Add("BlockDeviceMappings.member." + blockDeviceMappingsListIndex + ".Ebs.VolumeSize", StringUtils.FromInt(ebs.VolumeSize));
                        }
                    }

                    blockDeviceMappingsListIndex++;
                }
            }
            if (createLaunchConfigurationRequest != null)
            {
                InstanceMonitoring instanceMonitoring = createLaunchConfigurationRequest.InstanceMonitoring;
                if (instanceMonitoring != null && instanceMonitoring.IsSetEnabled())
                {
                    request.Parameters.Add("InstanceMonitoring.Enabled", StringUtils.FromBool(instanceMonitoring.Enabled));
                }
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetSpotPrice())
            {
                request.Parameters.Add("SpotPrice", StringUtils.FromString(createLaunchConfigurationRequest.SpotPrice));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetIamInstanceProfile())
            {
                request.Parameters.Add("IamInstanceProfile", StringUtils.FromString(createLaunchConfigurationRequest.IamInstanceProfile));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetEbsOptimized())
            {
                request.Parameters.Add("EbsOptimized", StringUtils.FromBool(createLaunchConfigurationRequest.EbsOptimized));
            }
            if (createLaunchConfigurationRequest != null && createLaunchConfigurationRequest.IsSetAssociatePublicIpAddress())
            {
                request.Parameters.Add("AssociatePublicIpAddress", StringUtils.FromBool(createLaunchConfigurationRequest.AssociatePublicIpAddress));
            }

            return request;
        }
    }
}


text:
/**
 * Created by kozervar on 2016-07-18.
 */
'use strict';
import fs from 'fs';
import { logger } from './index';
import md5pf from 'md5-part-file';
import NapijsFile from './../NapijsFile';
/**
 *
 * @param file
 * @returns {Promise}
 */
export default function(file){
    return new Promise((resolve,reject)=> {
        var stats = fs.statSync(file);
        var fileSizeInBytes = stats['size'];
        var fileWithHash = new NapijsFile(file);
        md5pf(file, 0, 10485760, function (err, hash) {
            if (err) {
                reject('Something went wrong during md5 hash calculation for file ' + file);
            } else {
                fileWithHash.hash = hash;
                fileWithHash.bytes = fileSizeInBytes;
                resolve(fileWithHash);
            }
        });
    });
}


text:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
var http=require('http');
var controllers=require("./controllers/starterController.js");
var bodyParser=require('body-parser');

controllers.init(app);
app.set("view engine", "vash");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var server = http.createServer(app);

var port = process.env.PORT || 3000;

if(!module.parent) {
server.listen(port, function(err){
  console.log("serrver started on port" + port);
});
}
module.exports.getApp = app;

// var path = require('path');
// var favicon = require('serve-favicon');
// var logger = require('morgan');
// var cookieParser = require('cookie-parser');
// var bodyParser = require('body-parser');

// var index = require('./routes/index');
// var users = require('./routes/users');

// // view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

// // uncomment after placing your favicon in /public
// //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', index);
// app.use('/users', users);

// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });

// // error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

// module.exports = app;


text:
/** @file version.h
 * @brief namespaces for C++11 and C++14
 */
#ifndef PBL_CPP_VERSION_H
#define PBL_CPP_VERSION_H

#include <cstddef>

/// @todo Value may not be correct, because as of writing C++17 isn't official
#if __cplusplus >= 201703L
#define CPP17
#endif
#if __cplusplus >= 201402L
#define CPP14
#endif
#if __cplusplus >= 201103L
#define CPP11
#endif

/* Namespace macros. It's sometimes necessary to put something into the "std"
 * namespace. For example, a specialization of std::hash. These macros can be
 * used to put the code in the correct namespace.
 */
#ifdef CPP17
#define CPP17_NAMESPACE std
#else
#define CPP17_NAMESPACE cpp17
#endif
#ifdef CPP14
#define CPP14_NAMESPACE std
#else
#define CPP14_NAMESPACE cpp14
#endif
#ifdef CPP11
#define CPP11_NAMESPACE std
#else
#define CPP11_NAMESPACE cpp11
#endif

namespace cpp11
{
}

#ifndef CPP11
namespace cpp11
{
class nullptr_t
{
public:
	template< class T >
	operator T*() const
	{
		return 0;
	}

	template< class C, class T >
	operator T C::*( ) const
	{
		return 0;
	}
private:
	void operator&() const;
};

}

const cpp11::nullptr_t nullptr = {};
#endif // ifndef CPP11

namespace cpp14
{
}

namespace cpp17
{
}

/* cpp points to either std or cpp11/14/17 as appropriate
 */
namespace cpp
{
using namespace ::std;
using namespace ::cpp11;
using namespace ::cpp14;
using namespace ::cpp17;
}

#endif // PBL_CPP_VERSION_H


text:
import { Middleware, Context } from 'koa';

declare namespace KoaBouncer {
    export class ValidationError extends Error {
        name: string;
        message: string;
        bouncer: {
            key: string,
            message: string
        }
        constructor(key: string, message: string);
    }

    export class Validator {
        constructor(props: {ctx: Context, key: string, vals: any})
        required(tip?: string): Validator
        optional(): Validator
        check(result: any, tip?: string): Validator
        checkNot(result: any, tip?: string): Validator
        checkPred(pred: any, tip?: string): Validator
        checkNotPred(pred: any, tip?: string): Validator
        tap(f: (arg: any) => any, tip?: string): Validator
        isIn(arr: any[], tip?: string): Validator
        isNotIn(arr: any[], tip?: string): Validator
        isArray(tip?: string): Validator
        eq(otherVal: string, tip?: string): Validator
        gt(otherVal: number, tip?: string): Validator
        gte(otherVal: number, tip?: string): Validator
        lt(otherVal: number, tip?: string): Validator
        lte(otherVal: number, tip?: string): Validator
        isLength(min: number, max: number, tip?: string): Validator
        defaultTo(valueOrFunction: any): Validator
        isString(tip?: string): Validator
        isInt(tip?: string): Validator
        toInt(tip?: string): Validator
        isFiniteNumber(tip?: string): Validator
        toArray(): Validator
        toInts(tip?: string): Validator
        uniq(): Validator
        toBoolean(): Validator
        toDecimal(tip?: string): Validator
        toFloat(tip?: string): Validator
        toFiniteFloat(): Validator
        toString(): Validator
        trim(): Validator
        match(regexp: RegExp, tip?: string): Validator
        notMatch(regexp: RegExp, tip?: string): Validator
        fromJson(tip?: string): Validator
        isAlpha(tip?: string): Validator
        isAlphanumeric(tip?: string): Validator
        isNumeric(tip?: string): Validator
        isAscii(tip?: string): Validator
        isBase64(tip?: string): Validator
        isEmail(tip?: string): Validator
        isHexColor(tip?: string): Validator
        isUuid(tip?: string): Validator
        isJson(tip?: string): Validator
        encodeBase64(tip?: string): Validator
        clamp(min: number, max: number): Validator

        static addMethod(name: string, fn: Function): void;
    }

    interface MiddlewareOption {
        getParams?: (ctx: Context) => any;
        getQuery?: (ctx: Context) => any;
        getBody?: (ctx: Context) => any;
    }

    export function middleware(opts?: MiddlewareOption): Middleware;
    export function isSafeInteger(n: number): boolean;
}

declare module "koa" {
    interface Context {
        vals: any;
        validateBody: (key: string) => KoaBouncer.Validator;
        validateQuery: (key: string) => KoaBouncer.Validator;
        validateParam: (key: string) => KoaBouncer.Validator;
        check: (result: any, tip?: string) => void;
        checkNot: (result: any, tip?: string) => KoaBouncer.Validator;
    }
}

export = KoaBouncer;


text:
Personal repo to keep my most commonly used partial views available for any project im working on.

Includes:
 - Dropdown for UK Counties.
 - Dropdown for Months of the Year.
 - File Upload Attachment Input.

Requires:
 - Laravel 5.3.
 - Laravel Blade.
 - Bootstrap 3.0 (Specifically for the file upload styles).


text:
<?xml version="1.0"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

    <title>Paragraph</title>
    <para>Some random content...</para>


text:
require 'rails_helper'

describe GreetUngreetedStudents do
  let(:greeter) { create(:admin) }
  let(:student) { create(:user) }
  let(:course) { create(:course) }
  let(:subject) { described_class.new(course, greeter) }

  before do
    create(:courses_user, user: student, course:)
    stub_raw_action
    stub_contributors_query
    stub_oauth_edit
  end

  it 'posts enrollment templates and welcome message for an ungreeted student' do
    expect(student.greeted).to eq(false)
    # New section for the welcome message
    expect_any_instance_of(WikiEdits).to receive(:add_new_section).and_call_original
    # Templates are added to the top of user page, talk page, sandbox
    expect(AddSandboxTemplate).to receive(:new)
    expect_any_instance_of(WikiEdits).to receive(:add_to_page_top).twice.and_call_original
    subject
    expect(student.reload.greeted).to eq(true)
  end
end


text:
package dk.onlinecity.qrr.detect;

import dk.onlinecity.qrr.util.Mext;

/**
 * This class represents a alignment pattern. This class is used in the
 * detection part.
 *
 * @author Thomas Duerlund (td@onlinecity.dk)
 */
public class AlignmentPattern
{
	private int x;
	private int y;
	private double moduleSize;
	private int denisty;

	public AlignmentPattern(int x, int y, double moduleSize)
	{
		this.x = x;
		this.y = y;
		this.moduleSize = moduleSize;
		denisty = 1;
	}

	public int getX()
	{
		return x;
	}

	public int getY()
	{
		return y;
	}

	public void incDensity()
	{
		denisty++;
	}

	public int getDensity()
	{
		return denisty;
	}

	/**
	 * Returns the distance to the alignment pattern line.
	 *
	 * @param x0
	 *            Alignment pattern line start x coordinate.
	 * @param y0
	 *            Alignment pattern line start y coordinate.
	 * @param x1
	 *            Alignment pattern line end x coordinate.
	 * @param y1
	 *            Alignment pattern line end y coordinate.
	 * @return Distance to the alignment pattern line.
	 */
	public double distToAlignmentPatternLine(int x0, int y0, int x1, int y1)
	{
		double[] a = new double[] { x1 - x0, y1 - y0 };
		double[] b = new double[] { x - x0, y - y0 };
		double scalar = Mext.dotProduct(a, b) / (Mext.dotProduct(a, a));
		// return the length of the vector b's projection onto a -> b.
		return Mext.vectorLength(scalar * a[0] - b[0], scalar * a[1] - b[1]);
	}

	public boolean almostEqual(double moduleSize, int x, int y)
	{
		return Math.abs(x - this.x) <= moduleSize && Math.abs(y - this.y) <= moduleSize && (Math.abs(moduleSize - this.moduleSize) <= 1.0);
	}
}


text:
class Activity < ActiveRecord::Base
  belongs_to :itinerary
  belongs_to :location

  validates :description, :itinerary_id, presence: :true

  accepts_nested_attributes_for :location

  # after_save :make_location, only: :new

  def make_location(params)
    new_location = Location.create(name: params[:name], address: params[:address], city: params[:city])
    self.update(location_id: new_location.id)
  end

end


text:
package org.beanone.flattener;

import static org.beanone.flattener.FlattenerContants.CTYPE_SUFFIX;
import static org.beanone.flattener.FlattenerContants.REF_SUFFIX;
import static org.beanone.flattener.FlattenerContants.SIZE_SUFFIX;

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

import org.beanone.flattener.api.FlattenerRegistry;
import org.beanone.flattener.api.KeyStack;
import org.beanone.flattener.api.Unflattener;
import org.beanone.flattener.exception.FlattenerException;

/**
 * Abstraction implementation of Flattener.
 *
 * @author Hongyan Li
 *
 */
public abstract class AbstractUnflattener implements Unflattener {
	private static final ThreadLocal<Map<String, Object>> VALUE_REFS = new ThreadLocal<Map<String, Object>>() {
		@Override
		protected Map<String, Object> initialValue() {
			return new HashMap<>();
		}
	};

	private final FlattenerRegistry flattenerRegistry;
	private final FlattenerUtil util;

	protected AbstractUnflattener(FlattenerRegistry flattenerRegistry) {
		if (flattenerRegistry == null) {
			throw new IllegalArgumentException("FlattenerRegistry is null!");
		}
		this.flattenerRegistry = flattenerRegistry;
		this.util = new FlattenerUtil();
	}

	@Override
	public final FlattenerRegistry getFlattenerRegistry() {
		return this.flattenerRegistry;
	}

	@Override
	public Object unflat(Map<String, String> flattened) {
		try {
			return Unflattener.super.unflat(flattened);
		} finally {
			VALUE_REFS.get().clear();
		}
	}

	@Override
	public Object unflat(Map<String, String> flatted, KeyStack keyStack,
	        Class<?> clazz) {
		try {
			final String classKey = keyStack.pop();
			final String prefix = classKey.substring(0,
			        classKey.length() - CTYPE_SUFFIX.length());
			final Object object = doCreateObject(flatted, keyStack, clazz);
			VALUE_REFS.get().put(prefix, object);
			while (!keyStack.isEmpty()) {
				final String key = keyStack.peek();
				if (!key.startsWith(prefix)) {
					break;
				}
				if (key.endsWith(CTYPE_SUFFIX)) {
					final Object value = unflat(flatted, keyStack,
					        flatted.get(key));
					doPopulate(object, key, CTYPE_SUFFIX.length(), value);
				} else if (key.endsWith(SIZE_SUFFIX)) {
					keyStack.pop();
				} else if (key.endsWith(REF_SUFFIX)) {
					keyStack.pop();
					final String refObjectKey = flatted.get(key);
					final Object value = VALUE_REFS.get().get(refObjectKey);
					doPopulate(object, key, REF_SUFFIX.length(), value);
				} else {
					keyStack.pop();
					final String typedValueStr = flatted.get(key);
					final Object value = getFlattenerRegistry()
					        .parsePrimitive(typedValueStr);
					doPopulate(object, key, 0, value);
				}
			}
			return object;
		} catch (final ReflectiveOperationException e) {
			throw new FlattenerException(e);
		}
	}

	protected abstract Object doCreateObject(Map<String, String> flatted,
	        KeyStack keyStack, Class<?> clazz)
	        throws ReflectiveOperationException;

	protected abstract void doPopulate(Object object, String key,
	        int suffixSize, Object value) throws ReflectiveOperationException;

	protected final FlattenerUtil getUtil() {
		return this.util;
	}
}


text:
package rss1

import (
	"encoding/xml"
	"github.com/aaron-lebo/ocd/feeds/modules/dublincore"
	"github.com/aaron-lebo/ocd/feeds/modules/syndication"
	"github.com/aaron-lebo/ocd/feeds/modules/taxonomy"
)

type RDF struct {
	XMLName xml.Name `xml:"http://www.w3.org/1999/02/22-rdf-syntax-ns# RDF"`
	Channel Channel  `xml:"channel"`
	Items   []Item   `xml:"item"`
}

type Channel struct {
	About       string    `xml:"about,attr"`
	Title       string    `xml:"title"`
	Link        string    `xml:"link"`
	Description string    `xml:"description"`
	Image       Image     `xml:"image"`
	Items       []Li      `xml:"items>Seq>li"`
	TextInput   TextInput `xml:"textinput"`
	dublincore.DublinCore
	syndication.Syndication
}

type Item struct {
	About       string `xml:"about,attr"`
	Title       string `xml:"title"`
	Link        string `xml:"link"`
	Description string `xml:"description"`
	dublincore.DublinCore
	taxonomy.Taxonomy
}

type Image struct {
	About string `xml:"about,attr"`
	Title string `xml:"title"`
	Url   string `xml:"url"`
	Link  string `xml:"link"`
	dublincore.DublinCore
}

type Li struct {
	Resource string `xml:"resource,attr"`
}

type TextInput struct {
	About       string `xml:"about,attr"`
	Title       string `xml:"title"`
	Description string `xml:"description"`
	Name        string `xml:"name"`
	Link        string `xml:"link"`
	dublincore.DublinCore
}


text:
package io.datarouter.nodewatch.service;

import io.datarouter.storage.client.ClientId;

public interface NodewatchClientConfiguration{

	boolean isCountableClient(ClientId clientId);

}


text:
window.THREE = THREE;

require('three/examples/js/controls/OrbitControls.js');
// require('three/examples/js/controls/PointerLockControls');
require('./PointerLockControls.js'); // with touchmove and mac trackpad support

const device = require('device.js')();

import config from '../config.js';
import WalkerTouchControls from './walkerTouchControls.js';

let disableWalkerEvent;
try {
    disableWalkerEvent = new Event('disableWalker');
} catch (e) {
    disableWalkerEvent = document.createEvent('Event');
    disableWalkerEvent.initEvent('disableWalker', true, true);
}

let self;
const v = {
    height: 1.6,
    moveForward: false,
    moveLeft: false,
    moveBackward: false,
    moveRight: false,
    speedModifier: 1,
    shiftSpeedModifier: 2,
    jump: false,
    isJumping: false,
    moveForwardBackMultiplier: 1,
    moveLeftRightMultiplier: 0.9,
    mobileRotateHorizontalMult: 0.35,
    mobileRotateVerticalMult: 0.5,
    mobileLookLeftRight: 0,
    mobileLookUpDown: 0,
    velocity: new THREE.Vector3(0, 0, 0),
    raycaster: new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(0, -1, 0), 0, 10),
    walkingSpeed: 65,
    jumpStrength: 8,
    gravity: 30
};

const tA = new THREE.Vector3();
const tB = new THREE.Vector3();
const tC = new THREE.Vector3();

const onKeyDown = function(e) {
    switch (e.keyCode) {
    case 38: // up
    case 87: // w
        v.moveForward = true;
        break;
    case 37: // left
    case 65: // a
        v.moveLeft = true;
        break;
    case 40: // down
    case 83: // s
        v.moveBackward = true;
        break;
    case 39: // right
    case 68: // d
        v.moveRight = true;
        break;
    case 16: // shift
        v.speedModifier = v.shiftSpeedModifier;
        break;
    case 32: // space
        v.jump = true;
        break;
    case 27: // escape
        if (!this.orbitControls.enabled) this.disableWalker();
        break;
    default:
    }
};

const onKeyUp = function(e) {
    switch (e.keyCode) {
    case 38: // up
    case 87: // w
        v.moveForward = false;
        break;
    case 37: // left
    case 65: // a
        v.moveLeft = false;
        break;
    case 40: // down
    case 83: // s
        v.moveBackward = false;
        break;
    case 39: // right
    case 68: // d
        v.moveRight = false;
        break;
    case 16: // shift
        v.speedModifier = 1;
        break;
    case 32: // space
        v.jump = false;
        break;
    default:
    }
};

class Controls {
    constructor(camera, domElement, scene) {
        self = this;

        this.camera = camera;
        this.domElement = domElement;
        this.walkerEnabled = false;
        this.isDesktop = device.desktop();
        this.rotateOnMouseDown = false;

        this.walkerTouchControls = null;

        this.orbitControls = new THREE.OrbitControls(camera, domElement);
        this.orbitControls.enableDamping = true;
        this.orbitControls.minDistance = 1;
        this.orbitControls.maxDistance = 1000;
        this.orbitControls.rotateSpeed = 0.25;

        this.infoEl = document.createElement('div');
        this.infoEl.className = 'buttonsRoot';
        this.infoEl.style.background = 'rgba(255,255,255,0.4)';
        if (!this.isDesktop) {
            this.infoEl.style.width = '60%';
            this.infoEl.style.height = '20%';
            this.infoEl.style.right = '0';
            this.infoEl.innerHTML = 'Controls: touch joystick to move, touch out of joystick to look around.';
        } else {
            this.infoEl.innerHTML = 'Controls: WASD / Space / Shift + mouse. Press Escape to exit.';
        }

        this.walkerControls = new THREE.PointerLockControls(camera, domElement);
        this._controlsObject = this.walkerControls.getObject();
        this._controlsObject.name = 'pointerLockObject';
        scene.add(this._controlsObject);

        this.resetCameraOrbit();

        this.navMesh = new THREE.Group();

        this.onKeyDown = onKeyDown.bind(this);
        this.onKeyUp = onKeyUp.bind(this);
    }

    enableWalker(dungeon) {
        this.createNavMesh(dungeon.rooms, dungeon.tunnels);
        const spawnRoomInd = Math.floor(Math.random() * dungeon.rooms.length);

        this.resetCameraWalker();

        this._controlsObject.position.fromArray([dungeon.rooms[spawnRoomInd].x, 6, dungeon.rooms[spawnRoomInd].y]); // Binding Point
        this._controlsObject.rotation.y = 0; // Rotates Yaw Object
        this._controlsObject.children[0].rotation.x = 0; // Rotates Pitch Object

        this.rotateOnMouseDown = false;
        if (this.isDesktop) {
            this._addKeyboardListeners();
            if (!this._preparePointerLock()) { // safari couldn't lock the pointer
                this.rotateOnMouseDown = true;
                this._rotateOnMouseDownEnable();
            }
        } else {
            if (!this.walkerTouchControls) {
                this.walkerTouchControls = new WalkerTouchControls(v, config);
            }
            this.walkerTouchControls.enable();
            this.walkerTouchControls.resetJoystickDiv();
        }

        document.body.appendChild(this.infoEl);

        this.orbitControls.enabled = false;
        this.walkerControls.enabled = !this.rotateOnMouseDown;
    }

    disableWalker() {
        this.resetCameraOrbit();

        if (this.isDesktop) {
            this._removeKeyboardListeners();
            this._removePointerLock();
            if (this.rotateOnMouseDown) {
                this._rotateOnMouseDownDisable();
            }
        } else {
            this.walkerTouchControls.disable();
        }

        document.body.removeChild(this.infoEl);

        this.orbitControls.enabled = true;
        this.walkerControls.enabled = false;

        this.clearNavMesh();
        document.dispatchEvent(disableWalkerEvent);
    }

    resetCameraOrbit() {
        this.camera.position.fromArray(config.camera.cameraPos);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0));
        this.camera.near = config.camera.near;
        this.camera.far = config.camera.far;
        this.camera.updateProjectionMatrix();

        this._controlsObject.position.set(0, 0, 0); // Resets Binding Point offset
        this._controlsObject.rotation.y = 0; // Resets Yaw Object
        this._controlsObject.children[0].rotation.x = 0; // Resets Pitch Object
    }

    resetCameraWalker() {
        this.camera.position.set(0, 0, 0);
        this.camera.rotation.set(0, 0, 0);
        this.camera.near = config.camera.walkerNear;
        this.camera.far = config.camera.walkerFar;
        this.camera.updateProjectionMatrix();
    }

    update(delta) {
        if (this.orbitControls.enabled) {
            this.orbitControls.update();
        } else {
            const cObj = this._controlsObject;

            if (!this.isDesktop) {
                cObj.rotation.y -= v.mobileLookLeftRight * v.mobileRotateHorizontalMult * delta;
                cObj.children[0].rotation.x += v.mobileLookUpDown * v.mobileRotateVerticalMult * delta;
                cObj.children[0].rotation.x = Math.min(Math.max(
                    cObj.children[0].rotation.x, -Math.PI / 2
                ), Math.PI / 2);

                this.walkerTouchControls.applyInertia();
            }

            let raycastedObj;

            v.raycaster.ray.origin.copy(cObj.position);

            let intersections = [];
            intersections = v.raycaster.intersectObjects(this.navMesh.children, false);

            const isOnObject = intersections.length > 0;

            v.velocity.x -= v.velocity.x * 10.0 * delta;
            v.velocity.z -= v.velocity.z * 10.0 * delta;
            v.velocity.y -= v.gravity * delta;

            if (v.moveForward) v.velocity.z -= v.walkingSpeed * v.speedModifier * v.moveForwardBackMultiplier * delta;
            if (v.moveBackward) v.velocity.z += v.walkingSpeed * v.speedModifier * v.moveForwardBackMultiplier * delta;
            if (v.moveLeft) v.velocity.x -= v.walkingSpeed * v.speedModifier * v.moveLeftRightMultiplier * delta;
            if (v.moveRight) v.velocity.x += v.walkingSpeed * v.speedModifier * v.moveLeftRightMultiplier * delta;
            if (v.jump && !v.isJumping) {
                v.velocity.y = v.jumpStrength;
                v.isJumping = true;
            }

            if (isOnObject) {
                raycastedObj = intersections[0];
                if (raycastedObj.distance + v.velocity.y * delta <= v.height) {
                    cObj.position.y = intersections[0].point.y + v.height;
                    v.velocity.y = 0;
                    v.isJumping = false;
                }
            }

            cObj.translateY(v.velocity.y * delta);

            const prevPos = cObj.position.clone();
            cObj.translateX(v.velocity.x * delta);
            cObj.translateZ(v.velocity.z * delta);

            v.raycaster.ray.origin.copy(cObj.position);
            intersections = [];
            intersections = v.raycaster.intersectObjects(this.navMesh.children, false);

            const willBeOnObject = intersections.length > 0;

            if (isOnObject && !willBeOnObject) {
                const newP = cObj.position.clone();

                const posArr = raycastedObj.object.geometry.attributes.position.array;
                tA.fromArray(posArr, raycastedObj.face.a * 3).applyMatrix4(raycastedObj.object.matrixWorld);
                tB.fromArray(posArr, raycastedObj.face.b * 3).applyMatrix4(raycastedObj.object.matrixWorld);
                tC.fromArray(posArr, raycastedObj.face.c * 3).applyMatrix4(raycastedObj.object.matrixWorld);

                const triCenter = new THREE.Vector3(0).add(tA).add(tB).add(tC).divideScalar(3);
                let intersection = this._linesIntersectsXZ(tA, tB, prevPos, newP);
                if (!intersection.intersect) {
                    intersection = this._linesIntersectsXZ(tB, tC, prevPos, newP);
                    if (!intersection.intersect) {
                        intersection = this._linesIntersectsXZ(tA, tC, prevPos, newP);
                    }
                }

                if (intersection.intersect) {
                    const A = intersection.A;
                    const B = intersection.B;

                    const a = new THREE.Vector3().subVectors(B, A);

                    const proj = new THREE.Vector3().subVectors(cObj.position, A).projectOnVector(a);

                    proj.add(A);

                    proj.add(new THREE.Vector3().subVectors(triCenter, proj).divideScalar(1000));

                    proj.y = prevPos.y;

                    cObj.position.copy(proj);
                } else {
                    cObj.position.copy(prevPos);
                }

                // TODO: should work without it (but it doesn't)
                v.raycaster.ray.origin.copy(cObj.position);
                intersections = [];
                intersections = v.raycaster.intersectObjects(this.navMesh.children, false);
                if (intersections.length < 1) cObj.position.copy(prevPos);
            }
        }
    }

    _linesIntersectsXZ(A, B, C, D) {
        const s1 = new THREE.Vector2(B.x - A.x, B.z - A.z);
        const s2 = new THREE.Vector2(D.x - C.x, D.z - C.z);

        const s = (-s1.y * (A.x - C.x) + s1.x * (A.z - C.z)) / (-s2.x * s1.y + s1.x * s2.y);
        const t = (s2.x * (A.z - C.z) - s2.y * (A.x - C.x)) / (-s2.x * s1.y + s1.x * s2.y);

        const doIntersect = s >= 0 && s <= 1 && t >= 0 && t <= 1;
        return {intersect: doIntersect, A, B};
    }

    createNavMesh(rooms, tunnels) {
        const navMesh = this.navMesh;
        const cubeGeom = new THREE.BoxBufferGeometry(1, 1, 1);
        let tunnel, isHorizontal, x, y, xS, yS;

        // scaling meshes down so camera couldn't get into walls
        for (let i = 0; i < rooms.length; i++) {
            const room = new THREE.Mesh(cubeGeom);
            room.scale.set(rooms[i].w - 0.04, config.visParams.floorHeight, rooms[i].h - 0.04);
            room.position.set(rooms[i].x, 0, rooms[i].y);
            navMesh.add(room);
        }

        for (let i = 0; i < tunnels.length; i += 4) {
            tunnel = new THREE.Mesh(cubeGeom);
            isHorizontal = tunnels[i + 2] - tunnels[i] > tunnels[i + 3] - tunnels[i + 1];
            x = isHorizontal ? (tunnels[i] + tunnels[i + 2]) / 2 : (tunnels[i] + 0.5);
            xS = isHorizontal ? tunnels[i + 2] - tunnels[i] - 0.04 : 1 - 0.04;

            y = isHorizontal ? (tunnels[i + 1] + 0.5) : (tunnels[i + 1] + tunnels[i + 3]) / 2;
            yS = isHorizontal ? 1 - 0.04 : tunnels[i + 3] - tunnels[i + 1] - 0.04;

            tunnel.scale.set(xS, config.visParams.tunnelHeight, yS);
            tunnel.position.set(x, 0, y);
            navMesh.add(tunnel);
        }

        navMesh.updateMatrixWorld(true);
    }

    clearNavMesh() {
        for (let i = this.navMesh.children.length - 1; i >= 0; i--) {
            this.navMesh.children[i].geometry.dispose();
            this.navMesh.remove(this.navMesh.children[i]);
        }
    }

    _rotateOnMouseDownEnable() {
        this.domElement.addEventListener('mousedown', this._onMousePressTouchStart, false);
        this.domElement.addEventListener('mouseup', this._onMouseReleaseTouchEnd, false);
        this.domElement.addEventListener('mouseout', this._onMouseReleaseTouchEnd, false);
    }

    _rotateOnMouseDownDisable() {
        this.domElement.removeEventListener('mousedown', this._onMousePressTouchStart, false);
        this.domElement.removeEventListener('mouseup', this._onMouseReleaseTouchEnd, false);
        this.domElement.removeEventListener('mouseout', this._onMouseReleaseTouchEnd, false);
    }

    _onMousePressTouchStart(e) {
        e.preventDefault();
        if (e.changedTouches && e.changedTouches.length && !self.walkerControls.enabled) {
            // disabled path for touch devices
            // self.walkerControls.touchId = e.changedTouches[0].identifier;
            // self.walkerControls.touchLastPos.x = e.changedTouches[0].clientX;
            // self.walkerControls.touchLastPos.y = e.changedTouches[0].clientY;
        } else {
            self.walkerControls.mouseLastPos.x = e.clientX;
            self.walkerControls.mouseLastPos.y = e.clientY;
        }
        self.walkerControls.enabled = true;
    }
    _onMouseReleaseTouchEnd() {
        self.walkerControls.enabled = false;
    }

    _pointerlockchange() {
        const element = document.body;
        if (document.pointerLockElement === element ||
        document.mozPointerLockElement === element ||
        document.webkitPointerLockElement === element) {
            // self.walkerControls.enabled = true;
        } else {
            if (!self.orbitControls.enabled) self.disableWalker();
        }
    }

    _pointerlockerror() {
        const element = document.body;
        element.innerHTML = 'PointerLock Error';
    }

    _preparePointerLock() {
        const element = document.body;
        let success = false;
        if ('pointerLockElement' in document || 'mozPointerLockElement' in document ||
             'webkitPointerLockElement' in document) {
            document.addEventListener('pointerlockchange', this._pointerlockchange, false);
            document.addEventListener('mozpointerlockchange', this._pointerlockchange, false);
            document.addEventListener('webkitpointerlockchange', this._pointerlockchange, false);

            document.addEventListener('pointerlockerror', this._pointerlockerror, false);
            document.addEventListener('mozpointerlockerror', this._pointerlockerror, false);
            document.addEventListener('webkitpointerlockerror', this._pointerlockerror, false);

            element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock
            || element.webkitRequestPointerLock;
            element.requestPointerLock();
            success = true;
        }
        return success;
    }

    _removePointerLock() {
        document.removeEventListener('pointerlockchange', this._pointerlockchange, false);
        document.removeEventListener('mozpointerlockchange', this._pointerlockchange, false);
        document.removeEventListener('webkitpointerlockchange', this._pointerlockchange, false);

        document.removeEventListener('pointerlockerror', this._pointerlockerror, false);
        document.removeEventListener('mozpointerlockerror', this._pointerlockerror, false);
        document.removeEventListener('webkitpointerlockerror', this._pointerlockerror, false);
    }

    _addKeyboardListeners() {
        document.addEventListener('keydown', this.onKeyDown, false);
        document.addEventListener('keyup', this.onKeyUp, false);
    }

    _removeKeyboardListeners() {
        document.removeEventListener('keydown', this.onKeyDown, false);
        document.removeEventListener('keyup', this.onKeyUp, false);
    }

    dispose() {
        this.orbitControls.dispose();
        this.walkerControls.dispose();
    }
}

export default Controls;


text:
/* Mednafen - Multi-system Emulator
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/* TODO:
	Note to self: Emulating the SPU at more timing accuracy than sample, and emulating the whole SPU RAM write port FIFO thing and hypothetical periodic FIFO commit to
	SPU RAM(maybe every 32 CPU cycles, with exceptions?) will likely necessitate a much more timing-accurate CPU core, and emulation of the SPU delay register(or at least the
	effects of the standard value written to it), to avoid game glitches.  Probably more trouble than it's worth....

	SPU IRQ emulation isn't totally correct, behavior is kind of complex; run more tests on PS1.

	Test reverb upsampler on the real thing.

	Alter reverb algorithm to process in the pattern of L,R,L,R,L,R on each input sample, instead of doing both L and R on every 2 input samples(make
	sure the real thing does it this way too, I think it at least runs the downsampler this way).

	Alter reverb algorithm to perform saturation more often, as occurs on the real thing.

	See if sample flag & 0x8 does anything weird, like suppressing the program-readable block end flag setting.

	Determine the actual purpose of global register 0x2C(is it REALLY an address multiplier?  And if so, does it affect the reverb offsets too?)

	For ADSR and volume sweep, should the divider be reset to 0 on &0x8000 == true, or should the upper bit be cleared?

	Should shift occur on all stages of ADPCM sample decoding, or only at the end?

	On the real thing, there's some kind of weirdness with ADSR when you voice on when attack_rate(raw) = 0x7F; the envelope level register is repeatedly
	reset to 0, which you can see by manual writes to the envelope level register.  Normally in the attack phase when attack_rate = 0x7F, enveloping is 		effectively stuck/paused such that the value you write is sticky and won't be replaced or reset.  Note that after you voice on, you can write a new 		attack_rate < 0x7F, and enveloping will work "normally" again shortly afterwards.  You can even write an attack_rate of 0x7F at that point to pause 		enveloping 		clocking.  I doubt any games rely on this, but it's something to keep in mind if we ever need greater insight as to how the SPU 	functions at a low-level in 		order to emulate it at cycle granularity rather than sample granularity, and it may not be a bad idea to 		investigate this oddity further and emulate it in 		the future regardless.

	Voice 1 and 3 waveform output writes to SPURAM might not be correct(noted due to problems reading this area of SPU RAM on the real thing
	based on my expectations of how this should work).
*/

/*
 Notes:
	All addresses(for 16-bit access, at least) within the SPU address space appear to be fully read/write as if they were RAM, though
	values at some addresses(like the envelope current value) will be "overwritten" by the sound processing at certain times.

	32-bit and 8-bit reads act as if it were RAM(not tested with all addresses, but a few, assuming the rest are the same), but 8-bit writes
	to odd addresses appear to be ignored, and 8-bit writes to even addresses are treated as 16-bit writes(most likely, but, need to code custom assembly to
	fully test the upper 8 bits).  NOTE: the preceding information doesn't necessarily cover accesses with side effects, they still need to be tested; and it
	of course covers reads/writes from the point of view of software running on the CPU.

	It doesn't appear to be possible to enable FM on the first channel/voice(channel/voice 0).

	Lower bit of channel start address appears to be masked out to 0(such that ADPCM block decoding is always 8 16-bit units, 16 bytes, aligned), as far as
	block-decoding and flag-set program-readable loop address go.
*/

/*
 Update() isn't called on Read and Writes for performance reasons, it's called with sufficient granularity from the event
 system, though this will obviously need to change if we ever emulate the SPU with better precision than per-sample(pair).
*/

#define SPUIRQ_DBG(format, ...) { printf("[SPUIRQDBG] " format " -- Voice 22 CA=0x%06x,LA=0x%06x\n", ## __VA_ARGS__, Voices[22].CurAddr, Voices[22].LoopAddr); }

#include "psx.h"
#include "cdc.h"
#include "spu.h"

namespace MDFN_IEN_PSX
{

static const int16 FIR_Table[256][4] =
{
 #include "spu_fir_table.inc"
};

PS_SPU::PS_SPU()
{
 last_rate = -1;
 last_quality = ~0U;

 IntermediateBufferPos = 0;
 memset(IntermediateBuffer, 0, sizeof(IntermediateBuffer));
}

PS_SPU::~PS_SPU()
{
}

void PS_SPU::Power(void)
{
 clock_divider = 768;

 memset(SPURAM, 0, sizeof(SPURAM));

 for(int i = 0; i < 24; i++)
 {
  memset(Voices[i].DecodeBuffer, 0, sizeof(Voices[i].DecodeBuffer));
  Voices[i].DecodeM2 = 0;
  Voices[i].DecodeM1 = 0;

  Voices[i].DecodePlayDelay = 0;
  Voices[i].DecodeWritePos = 0;
  Voices[i].DecodeReadPos = 0;
  Voices[i].DecodeAvail = 0;

  Voices[i].DecodeShift = 0;
  Voices[i].DecodeWeight = 0;
  Voices[i].DecodeFlags = 0;

  Voices[i].IgnoreSampLA = false;

  Voices[i].Sweep[0].Power();
  Voices[i].Sweep[1].Power();

  Voices[i].Pitch = 0;
  Voices[i].CurPhase = 0;

  Voices[i].StartAddr = 0;

  Voices[i].CurAddr = 0;

  Voices[i].ADSRControl = 0;

  Voices[i].LoopAddr = 0;

  Voices[i].PreLRSample = 0;

  memset(&Voices[i].ADSR, 0, sizeof(SPU_ADSR));
 }

 GlobalSweep[0].Power();
 GlobalSweep[1].Power();

 NoiseDivider = 0;
 NoiseCounter = 0;
 LFSR = 0;

 FM_Mode = 0;
 Noise_Mode = 0;
 Reverb_Mode = 0;
 ReverbWA = 0;

 ReverbVol[0] = ReverbVol[1] = 0;

 CDVol[0] = CDVol[1] = 0;

 ExternVol[0] = ExternVol[1] = 0;

 IRQAddr = 0;

 RWAddr = 0;

 SPUControl = 0;

 VoiceOn = 0;
 VoiceOff = 0;

 BlockEnd = 0;

 CWA = 0;

 memset(Regs, 0, sizeof(Regs));

 memset(RDSB, 0, sizeof(RDSB));
 memset(RUSB, 0, sizeof(RUSB));
 RvbResPos = 0;

 ReverbCur = ReverbWA;

 IRQAsserted = false;
}

static INLINE void CalcVCDelta(const uint8 zs, uint8 speed, bool log_mode, bool dec_mode, bool inv_increment, int16 Current, int &increment, int &divinco)
{
  increment = (7 - (speed & 0x3));

  if(inv_increment)
   increment = ~increment;

  divinco = 32768;

  if(speed < 0x2C)
   increment = (unsigned)increment << ((0x2F - speed) >> 2);

  if(speed >= 0x30)
   divinco >>= (speed - 0x2C) >> 2;

  if(log_mode)
  {
   if(dec_mode)	// Log decrement mode
    increment = (Current * increment) >> 15;
   else			// Log increment mode
   {
    if((Current & 0x7FFF) >= 0x6000)
    {
     if(speed < 0x28)
      increment >>= 2;
     else if(speed >= 0x2C)
      divinco >>= 2;
     else	// 0x28 ... 0x2B
     {
      increment >>= 1;
      divinco >>= 1;
     }
    }
   }
  } // end if(log_mode)

  if(divinco == 0 && speed < zs) //0x7F)
   divinco = 1;
}

INLINE void SPU_Sweep::Power(void)
{
 Control = 0;
 Current = 0;
 Divider = 0;
}

INLINE void SPU_Sweep::WriteControl(uint16 value)
{
 Control = value;
}

INLINE int16 SPU_Sweep::ReadVolume(void)
{
 return((int16)Current);
}

void SPU_Sweep::Clock(void)
{
 if(!(Control & 0x8000))
 {
  Current = (Control & 0x7FFF) << 1;
  return;
 }

 if(Control & 0x8000) 	// Sweep enabled
 {
  const bool log_mode = (bool)(Control & 0x4000);
  const bool dec_mode = (bool)(Control & 0x2000);
  const bool inv_mode = (bool)(Control & 0x1000);
  const bool inv_increment = (dec_mode ^ inv_mode) | (dec_mode & log_mode);
  const uint16 vc_cv_xor = (inv_mode & !(dec_mode & log_mode)) ? 0xFFFF : 0x0000;
  const uint16 TestInvert = inv_mode ? 0xFFFF : 0x0000;
  int increment;
  int divinco;

  CalcVCDelta(0x7F, Control & 0x7F, log_mode, dec_mode, inv_increment, (int16)(Current ^ vc_cv_xor), increment, divinco);
  //printf("%d %d\n", divinco, increment);

  if((dec_mode & !(inv_mode & log_mode)) && ((Current & 0x8000) == (inv_mode ? 0x0000 : 0x8000) || (Current == 0)))
  {
   //
   // Not sure if this condition should stop the Divider adding or force the increment value to 0.
   //
   Current = 0;
  }
  else
  {
   Divider += divinco;

   if(Divider & 0x8000)
   {
    Divider = 0;

    if(dec_mode || ((Current ^ TestInvert) != 0x7FFF))
    {
     uint16 PrevCurrent = Current;
     Current = Current + increment;

     //printf("%04x %04x\n", PrevCurrent, Current);

     if(!dec_mode && ((Current ^ PrevCurrent) & 0x8000) && ((Current ^ TestInvert) & 0x8000))
      Current = 0x7FFF ^ TestInvert;
    }
   }
  }
 }
}

INLINE void SPU_Sweep::WriteVolume(int16 value)
{
 Current = value;
}

//
// Take care not to trigger SPU IRQ for the next block before its decoding start.
//
void PS_SPU::RunDecoder(SPU_Voice *voice)
{
 // 5 through 0xF appear to be 0 on the real thing.
 static const int32 Weights[16][2] =
 {
  // s-1    s-2
  {   0,    0 },
  {  60,    0 },
  { 115,  -52 },
  {  98,  -55 },
  { 122,  -60 },
 };

 if(voice->DecodeAvail >= 11)
 {
  if(SPUControl & 0x40)
  {
   unsigned test_addr = (voice->CurAddr - 1) & 0x3FFFF;
   if(IRQAddr == test_addr || IRQAddr == (test_addr & 0x3FFF8))
   {
    //SPUIRQ_DBG("SPU IRQ (VDA): 0x%06x", addr);
    IRQAsserted = true;
    IRQ_Assert(IRQ_SPU, IRQAsserted);
   }
  }
  return;
 }

 if((voice->CurAddr & 0x7) == 0)
 {
  //
  // Handle delayed flags from the previously-decoded block.
  //
  // NOTE: The timing of setting the BlockEnd bit here, and forcing ADSR envelope volume to 0, is a bit late.  (And I'm not sure if it should be done once
  // per decoded block, or more than once, but that's probably not something games would rely on, but we should test it anyway).
  //
  // Correctish timing can be achieved by moving this block of code up above voice->DecodeAvail >= 11, and sticking it inside an: if(voice->DecodeAvail <= 12),
  // though more tests are needed on the ADPCM decoding process as a whole before we should actually make such a change.  Additionally, we'd probably
  // have to separate the CurAddr = LoopAddr logic, so we don't generate spurious early SPU IRQs.
  //
  if(voice->DecodeFlags & 0x1)
  {
   voice->CurAddr = voice->LoopAddr & ~0x7;

   BlockEnd |= 1 << (voice - Voices);

   if(!(voice->DecodeFlags & 0x2))	// Force enveloping to 0 if not "looping".  TODO: Should we reset the ADSR divider counter too?
   {
    if(!(Noise_Mode & (1 << (voice - Voices))))
    {
     voice->ADSR.Phase = ADSR_RELEASE;
     voice->ADSR.EnvLevel = 0;
    }
   }
  }
 }

 //for(int z = 0; z < 4; z++)
 {
  if(SPUControl & 0x40)
  {
   unsigned test_addr = voice->CurAddr & 0x3FFFF;
   if(IRQAddr == test_addr || IRQAddr == (test_addr & 0x3FFF8))
   {
    //SPUIRQ_DBG("SPU IRQ: 0x%06x", addr);
    IRQAsserted = true;
    IRQ_Assert(IRQ_SPU, IRQAsserted);
   }
  }

  if((voice->CurAddr & 0x7) == 0)
  {
   const uint16 CV = SPURAM[voice->CurAddr];

   voice->DecodeShift = CV & 0xF;
   voice->DecodeWeight = (CV >> 4) & 0xF;
   voice->DecodeFlags = (CV >> 8) & 0xFF;

   if(voice->DecodeFlags & 0x4)
   {
    if(!voice->IgnoreSampLA)
    {
     voice->LoopAddr = voice->CurAddr;
    }
    else
    {
     if(voice->LoopAddr != voice->CurAddr)
     {
      PSX_DBG(PSX_DBG_FLOOD, "[SPU] Ignore: LoopAddr=0x%08x, SampLA=0x%08x\n", voice->LoopAddr, voice->CurAddr);
     }
    }
   }
   voice->CurAddr = (voice->CurAddr + 1) & 0x3FFFF;
  }

  //
  // Don't else this block; we need to ALWAYS decode 4 samples per call to RunDecoder() if DecodeAvail < 11, or else sample playback
  // at higher rates will fail horribly.
  //
  {
   const int32 weight_m1 = Weights[voice->DecodeWeight][0];
   const int32 weight_m2 = Weights[voice->DecodeWeight][1];
   uint16 CV;
   unsigned shift;
   uint32 coded;
   int16 *tb = &voice->DecodeBuffer[voice->DecodeWritePos];

   CV = SPURAM[voice->CurAddr];
   shift = voice->DecodeShift;

   if(MDFN_UNLIKELY(shift > 12))
   {
    //PSX_DBG(PSX_DBG_FLOOD, "[SPU] Buggy/Illegal ADPCM block shift value on voice %u: %u\n", (unsigned)(voice - Voices), shift);

    shift = 8;
    CV &= 0x8888;
   }

   coded = (uint32)CV << 12;

   for(int i = 0; i < 4; i++)
   {
    int32 sample = (int16)(coded & 0xF000) >> shift;

    sample += ((voice->DecodeM2 * weight_m2) >> 6);
    sample += ((voice->DecodeM1 * weight_m1) >> 6);

    clamp(&sample, -32768, 32767);

    tb[i] = sample;
    voice->DecodeM2 = voice->DecodeM1;
    voice->DecodeM1 = sample;
    coded >>= 4;
   }
   voice->DecodeWritePos = (voice->DecodeWritePos + 4) & 0x1F;
   voice->DecodeAvail += 4;
   voice->CurAddr = (voice->CurAddr + 1) & 0x3FFFF;
  }
 }
}

void PS_SPU::CacheEnvelope(SPU_Voice *voice)
{
 uint32 raw = voice->ADSRControl;
 SPU_ADSR *ADSR = &voice->ADSR;
 int32 Sl, Dr, Ar, Rr, Sr;

 Sl = (raw >> 0) & 0x0F;
 Dr = (raw >> 4) & 0x0F;
 Ar = (raw >> 8) & 0x7F;

 Rr = (raw >> 16) & 0x1F;
 Sr = (raw >> 22) & 0x7F;

 ADSR->AttackExp = (bool)(raw & (1 << 15));
 ADSR->ReleaseExp = (bool)(raw & (1 << 21));
 ADSR->SustainExp = (bool)(raw & (1 << 31));
 ADSR->SustainDec = (bool)(raw & (1 << 30));

 ADSR->AttackRate = Ar;
 ADSR->DecayRate = Dr << 2;
 ADSR->SustainRate = Sr;
 ADSR->ReleaseRate = Rr << 2;

 ADSR->SustainLevel = (Sl + 1) << 11;
}

void PS_SPU::ResetEnvelope(SPU_Voice *voice)
{
 SPU_ADSR *ADSR = &voice->ADSR;

 ADSR->EnvLevel = 0;
 ADSR->Divider = 0;
 ADSR->Phase = ADSR_ATTACK;
}

void PS_SPU::ReleaseEnvelope(SPU_Voice *voice)
{
 SPU_ADSR *ADSR = &voice->ADSR;

 ADSR->Divider = 0;
 ADSR->Phase = ADSR_RELEASE;
}

void PS_SPU::RunEnvelope(SPU_Voice *voice)
{
 SPU_ADSR *ADSR = &voice->ADSR;
 int increment;
 int divinco;
 int16 uoflow_reset;

 if(ADSR->Phase == ADSR_ATTACK && ADSR->EnvLevel == 0x7FFF)
  ADSR->Phase++;

 //static INLINE void CalcVCDelta(const uint8 zs, uint8 speed, bool log_mode, bool decrement, bool inv_increment, int16 Current, int &increment, int &divinco)
 switch(ADSR->Phase)
 {
  default:	// Won't happen, but helps shut up gcc warnings.
  case ADSR_ATTACK:
	CalcVCDelta(0x7F, ADSR->AttackRate, ADSR->AttackExp, false, false, (int16)ADSR->EnvLevel, increment, divinco);
	uoflow_reset = 0x7FFF;
	break;

  case ADSR_DECAY:
	CalcVCDelta(0x1F << 2, ADSR->DecayRate, true, true, true, (int16)ADSR->EnvLevel, increment, divinco);
	uoflow_reset = 0;
	break;

  case ADSR_SUSTAIN:
	CalcVCDelta(0x7F, ADSR->SustainRate, ADSR->SustainExp, ADSR->SustainDec, ADSR->SustainDec, (int16)ADSR->EnvLevel, increment, divinco);
	uoflow_reset = ADSR->SustainDec ? 0 : 0x7FFF;
	break;

  case ADSR_RELEASE:
	CalcVCDelta(0x1F << 2, ADSR->ReleaseRate, ADSR->ReleaseExp, true, true, (int16)ADSR->EnvLevel, increment, divinco);
	uoflow_reset = 0;
	break;
 }

 ADSR->Divider += divinco;
 if(ADSR->Divider & 0x8000)
 {
  const uint16 prev_level = ADSR->EnvLevel;

  ADSR->Divider = 0;
  ADSR->EnvLevel += increment;

  if(ADSR->Phase == ADSR_ATTACK)
  {
   // If previous the upper bit was 0, but now it's 1, handle overflow.
   if(((prev_level ^ ADSR->EnvLevel) & ADSR->EnvLevel) & 0x8000)
    ADSR->EnvLevel = uoflow_reset;
  }
  else
  {
   if(ADSR->EnvLevel & 0x8000)
    ADSR->EnvLevel = uoflow_reset;
  }
  if(ADSR->Phase == ADSR_DECAY && (uint16)ADSR->EnvLevel < ADSR->SustainLevel)
   ADSR->Phase++;
 }
}

INLINE void PS_SPU::CheckIRQAddr(uint32 addr)
{
 if(SPUControl & 0x40)
 {
  if(IRQAddr == addr)
  {
   //SPUIRQ_DBG("SPU IRQ (ALT): 0x%06x", addr);
   IRQAsserted = true;
   IRQ_Assert(IRQ_SPU, IRQAsserted);
  }
 }
}

INLINE void PS_SPU::WriteSPURAM(uint32 addr, uint16 value)
{
 CheckIRQAddr(addr);

 SPURAM[addr] = value;
}

INLINE uint16 PS_SPU::ReadSPURAM(uint32 addr)
{
 CheckIRQAddr(addr);
 return(SPURAM[addr]);
}

#include "spu_reverb.inc"

INLINE void PS_SPU::RunNoise(void)
{
 const unsigned rf = ((SPUControl >> 8) & 0x3F);
 uint32 NoiseDividerInc = (2 << (rf >> 2));
 uint32 NoiseCounterInc = 4 + (rf & 0x3);

 if(rf >= 0x3C)
 {
  NoiseDividerInc = 0x8000;
  NoiseCounterInc = 8;
 }

 NoiseDivider += NoiseDividerInc;
 if(NoiseDivider & 0x8000)
 {
  NoiseDivider = 0;

  NoiseCounter += NoiseCounterInc;
  if(NoiseCounter & 0x8)
  {
   NoiseCounter &= 0x7;
   LFSR = (LFSR << 1) | (((LFSR >> 15) ^ (LFSR >> 12) ^ (LFSR >> 11) ^ (LFSR >> 10) ^ 1) & 1);
  }
 }
}

int32 PS_SPU::UpdateFromCDC(int32 clocks)
//pscpu_timestamp_t PS_SPU::Update(const pscpu_timestamp_t timestamp)
{
 //int32 clocks = timestamp - lastts;
 int32 sample_clocks = 0;
 //lastts = timestamp;

 clock_divider -= clocks;

 while(clock_divider <= 0)
 {
  clock_divider += 768;
  sample_clocks++;
 }

while(sample_clocks > 0)
 {
  // xxx[0] = left, xxx[1] = right

  // Accumulated sound output.
  int32 accum[2] = { 0, 0 };

  // Accumulated sound output for reverb input
  int32 accum_fv[2] = { 0, 0 };

  // Output of reverb processing.
  int32 reverb[2] = { 0, 0 };

  // Final output.
  int32 output[2] = { 0, 0 };

  const uint32 PhaseModCache = FM_Mode & ~ 1;
/*
**
** 0x1F801DAE Notes and Conjecture:
**   -------------------------------------------------------------------------------------
**   |   15   14 | 13 | 12 | 11 | 10  | 9  | 8 |  7 |  6  | 5    4    3    2    1    0   |
**   |      ?    | *13| ?  | ba | *10 | wrr|rdr| df |  is |      c                       |
**   -------------------------------------------------------------------------------------
**
**	c - Appears to be delayed copy of lower 6 bits from 0x1F801DAA.
**
**     is - Interrupt asserted out status. (apparently not instantaneous status though...)
**
**     df - Related to (c & 0x30) == 0x20 or (c & 0x30) == 0x30, at least.
**          0 = DMA busy(FIFO not empty when in DMA write mode?)?
**	    1 = DMA ready?  Something to do with the FIFO?
**
**     rdr - Read(DMA read?) Ready?
**
**     wrr - Write(DMA write?) Ready?
**
**     *10 - Unknown.  Some sort of (FIFO?) busy status?(BIOS tests for this bit in places)
**
**     ba - Alternates between 0 and 1, even when SPUControl bit15 is 0; might be related to CD audio and voice 1 and 3 writing to SPU RAM.
**
**     *13 - Unknown, was set to 1 when testing with an SPU delay system reg value of 0x200921E1(test result might not be reliable, re-run).
*/
  SPUStatus = SPUControl & 0x3F;
  SPUStatus |= IRQAsserted ? 0x40 : 0x00;

  if(Regs[0xD6] == 0x4)	// TODO: Investigate more(case 0x2C in global regs r/w handler)
   SPUStatus |= (CWA & 0x100) ? 0x800 : 0x000;

  for(int voice_num = 0; voice_num < 24; voice_num++)
  {
   SPU_Voice *voice = &Voices[voice_num];
   int32 voice_pvs;

   voice->PreLRSample = 0;

   //PSX_WARNING("[SPU] Voice %d CurPhase=%08x, pitch=%04x, CurAddr=%08x", voice_num, voice->CurPhase, voice->Pitch, voice->CurAddr);

   //
   // Decode new samples if necessary.
   //
   RunDecoder(voice);

   //
   //
   //
   int l, r;

   if(Noise_Mode & (1 << voice_num))
    voice_pvs = (int16)LFSR;
   else
   {
    const int si = voice->DecodeReadPos;
    const int pi = ((voice->CurPhase & 0xFFF) >> 4);

    voice_pvs = ((voice->DecodeBuffer[(si + 0) & 0x1F] * FIR_Table[pi][0]) +
	         (voice->DecodeBuffer[(si + 1) & 0x1F] * FIR_Table[pi][1]) +
	         (voice->DecodeBuffer[(si + 2) & 0x1F] * FIR_Table[pi][2]) +
 	         (voice->DecodeBuffer[(si + 3) & 0x1F] * FIR_Table[pi][3])) >> 15;
   }

   voice_pvs = (voice_pvs * (int16)voice->ADSR.EnvLevel) >> 15;
   voice->PreLRSample = voice_pvs;

   if(voice_num == 1 || voice_num == 3)
   {
    int index = voice_num >> 1;

    WriteSPURAM(0x400 | (index * 0x200) | CWA, voice_pvs);
   }

   l = (voice_pvs * voice->Sweep[0].ReadVolume()) >> 15;
   r = (voice_pvs * voice->Sweep[1].ReadVolume()) >> 15;

   accum[0] += l;
   accum[1] += r;

   if(Reverb_Mode & (1 << voice_num))
   {
    accum_fv[0] += l;
    accum_fv[1] += r;
	 }

   // Run sweep
   for(int lr = 0; lr < 2; lr++)
    voice->Sweep[lr].Clock();

   // Increment stuff
   if(!voice->DecodePlayDelay)
   {
    unsigned phase_inc;

    // Run enveloping
    RunEnvelope(voice);

    if(PhaseModCache & (1 << voice_num))
    {
     // This old formula: phase_inc = (voice->Pitch * ((voice - 1)->PreLRSample + 0x8000)) >> 15;
     // is incorrect, as it does not handle carrier pitches >= 0x8000 properly.
     phase_inc = voice->Pitch + (((int16)voice->Pitch * ((voice - 1)->PreLRSample)) >> 15);
    }
    else
     phase_inc = voice->Pitch;

    if(phase_inc > 0x3FFF)
     phase_inc = 0x3FFF;

    {
     const uint32 tmp_phase = voice->CurPhase + phase_inc;
     const unsigned used = tmp_phase >> 12;

     voice->CurPhase = tmp_phase & 0xFFF;
     voice->DecodeAvail -= used;
     voice->DecodeReadPos = (voice->DecodeReadPos + used) & 0x1F;
    }
   }
   else
    voice->DecodePlayDelay--;

   if(VoiceOff & (1U << voice_num))
   {
    if(voice->ADSR.Phase != ADSR_RELEASE)
    {
     ReleaseEnvelope(voice);
    }
   }

   if(VoiceOn & (1U << voice_num))
   {
    //printf("Voice On: %u\n", voice_num);

    ResetEnvelope(voice);

    voice->DecodeFlags = 0;
    voice->DecodeWritePos = 0;
    voice->DecodeReadPos = 0;
    voice->DecodeAvail = 0;
    voice->DecodePlayDelay = 4;

    BlockEnd &= ~(1 << voice_num);

    //
    // Weight/filter previous value initialization:
    //
    voice->DecodeM2 = 0;
    voice->DecodeM1 = 0;

    voice->CurPhase = 0;
    voice->CurAddr = voice->StartAddr & ~0x7;
    voice->IgnoreSampLA = false;
   }

   if(!(SPUControl & 0x8000))
   {
    voice->ADSR.Phase = ADSR_RELEASE;
    voice->ADSR.EnvLevel = 0;
   }
  }

  VoiceOff = 0;
  VoiceOn = 0;

  // "Mute" control doesn't seem to affect CD audio(though CD audio reverb wasn't tested...)
  // TODO: If we add sub-sample timing accuracy, see if it's checked for every channel at different times, or just once.
  if(!(SPUControl & 0x4000))
  {
   accum[0] = 0;
   accum[1] = 0;
   accum_fv[0] = 0;
   accum_fv[1] = 0;
  }

  // Get CD-DA
  {
   int32 cda_raw[2];
   int32 cdav[2];

   CDC->GetCDAudio(cda_raw);	// PS_CDC::GetCDAudio() guarantees the variables passed by reference will be set to 0,
				// and that their range shall be -32768 through 32767.

   WriteSPURAM(CWA | 0x000, cda_raw[0]);
   WriteSPURAM(CWA | 0x200, cda_raw[1]);

   for(unsigned i = 0; i < 2; i++)
    cdav[i] = (cda_raw[i] * CDVol[i]) >> 15;

   if(SPUControl & 0x0001)
   {
    accum[0] += cdav[0];
    accum[1] += cdav[1];

    if(SPUControl & 0x0004)	// TODO: Test this bit(and see if it is really dependent on bit0)
    {
     accum_fv[0] += cdav[0];
     accum_fv[1] += cdav[1];
    }
   }
  }

  CWA = (CWA + 1) & 0x1FF;

  RunNoise();

  for(unsigned lr = 0; lr < 2; lr++)
   clamp(&accum_fv[lr], -32768, 32767);

  RunReverb(accum_fv, reverb);

  for(unsigned lr = 0; lr < 2; lr++)
  {
   accum[lr] += ((reverb[lr] * ReverbVol[lr]) >> 15);
   clamp(&accum[lr], -32768, 32767);
   output[lr] = (accum[lr] * GlobalSweep[lr].ReadVolume()) >> 15;
   clamp(&output[lr], -32768, 32767);
  }

  if(IntermediateBufferPos < 4096)	// Overflow might occur in some debugger use cases.
  {
   // 75%, for some (resampling) headroom.
   for(unsigned lr = 0; lr < 2; lr++)
    IntermediateBuffer[IntermediateBufferPos][lr] = (output[lr] * 3 + 2) >> 2;

   IntermediateBufferPos++;
  }

  sample_clocks--;

  // Clock global sweep
  for(unsigned lr = 0; lr < 2; lr++)
   GlobalSweep[lr].Clock();
 }

 //assert(clock_divider < 768);

 return clock_divider;
}

void PS_SPU::WriteDMA(uint32 V)
{
 //SPUIRQ_DBG("DMA Write, RWAddr after=0x%06x", RWAddr);
 WriteSPURAM(RWAddr, V);
 RWAddr = (RWAddr + 1) & 0x3FFFF;

 WriteSPURAM(RWAddr, V >> 16);
 RWAddr = (RWAddr + 1) & 0x3FFFF;

 CheckIRQAddr(RWAddr);
}

uint32 PS_SPU::ReadDMA(void)
{
 uint32 ret;

 ret = (uint16)ReadSPURAM(RWAddr);
 RWAddr = (RWAddr + 1) & 0x3FFFF;

 ret |= (uint32)(uint16)ReadSPURAM(RWAddr) << 16;
 RWAddr = (RWAddr + 1) & 0x3FFFF;

 CheckIRQAddr(RWAddr);

 //SPUIRQ_DBG("DMA Read, RWAddr after=0x%06x", RWAddr);

 return(ret);
}

void PS_SPU::Write(pscpu_timestamp_t timestamp, uint32 A, uint16 V)
{
 //if((A & 0x3FF) < 0x180)
 // PSX_WARNING("[SPU] Write: %08x %04x", A, V);

 A &= 0x3FF;

 if(A >= 0x200)
 {
  //printf("Write: %08x %04x\n", A, V);
  if(A < 0x260)
  {
   SPU_Voice *voice = &Voices[(A - 0x200) >> 2];
   voice->Sweep[(A & 2) >> 1].WriteVolume(V);
  }
  else if(A < 0x280)
   AuxRegs[(A & 0x1F) >> 1] = V;

  return;
 }

 if(A < 0x180)
 {
  SPU_Voice *voice = &Voices[A >> 4];

  switch(A & 0xF)
  {
   case 0x00:
   case 0x02:
	     voice->Sweep[(A & 2) >> 1].WriteControl(V);
	     break;

   case 0x04: voice->Pitch = V;
	      break;

   case 0x06: voice->StartAddr = (V << 2) & 0x3FFFF;
	      break;

   case 0x08: voice->ADSRControl &= 0xFFFF0000;
	      voice->ADSRControl |= V;
	      CacheEnvelope(voice);
	      break;

   case 0x0A: voice->ADSRControl &= 0x0000FFFF;
	      voice->ADSRControl |= V << 16;
	      CacheEnvelope(voice);
	      break;

   case 0x0C: voice->ADSR.EnvLevel = V;
	      break;

   case 0x0E: voice->LoopAddr = (V << 2) & 0x3FFFF;
	      voice->IgnoreSampLA = true;
	      //if((voice - Voices) == 22)
	      //{
	      // SPUIRQ_DBG("Manual loop address setting for voice %d: %04x", (int)(voice - Voices), V);
	      //}
	      break;
  }
 }
 else
 {
  switch(A & 0x7F)
  {
   case 0x00:
   case 0x02: GlobalSweep[(A & 2) >> 1].WriteControl(V);
	      break;

   case 0x04: ReverbVol[0] = (int16)V;
	      break;

   case 0x06: ReverbVol[1] = (int16)V;
	      break;

   // Voice ON:
   case 0x08: VoiceOn &= 0xFFFF0000;
	      VoiceOn |= V << 0;
	      break;

   case 0x0a: VoiceOn &= 0x0000FFFF;
              VoiceOn |= (V & 0xFF) << 16;
	      break;

   // Voice OFF:
   case 0x0c: VoiceOff &= 0xFFFF0000;
              VoiceOff |= V << 0;
	      break;

   case 0x0e: VoiceOff &= 0x0000FFFF;
              VoiceOff |= (V & 0xFF) << 16;
	      break;

   case 0x10: FM_Mode &= 0xFFFF0000;
	      FM_Mode |= V << 0;
	      break;

   case 0x12: FM_Mode &= 0x0000FFFF;
	      FM_Mode |= (V & 0xFF) << 16;
	      break;

   case 0x14: Noise_Mode &= 0xFFFF0000;
	      Noise_Mode |= V << 0;
	      break;

   case 0x16: Noise_Mode &= 0x0000FFFF;
	      Noise_Mode |= (V & 0xFF) << 16;
	      break;

   case 0x18: Reverb_Mode &= 0xFFFF0000;
	      Reverb_Mode |= V << 0;
	      break;

   case 0x1A: Reverb_Mode &= 0x0000FFFF;
	      Reverb_Mode |= (V & 0xFF) << 16;
	      break;

   case 0x1C: BlockEnd &= 0xFFFF0000;
	      BlockEnd |= V << 0;
	      break;

   case 0x1E: BlockEnd &= 0x0000FFFF;
	      BlockEnd |= V << 16;
	      break;

   case 0x22: ReverbWA = (V << 2) & 0x3FFFF;
	      ReverbCur = ReverbWA;
	      //PSX_WARNING("[SPU] Reverb WA set: 0x%04x", V);
	      break;

   case 0x24: IRQAddr = (V << 2) & 0x3FFFF;
	      CheckIRQAddr(RWAddr);
	      //SPUIRQ_DBG("Set IRQAddr=0x%06x", IRQAddr);
	      break;

   case 0x26: RWAddr = (V << 2) & 0x3FFFF;
	      CheckIRQAddr(RWAddr);
	      //SPUIRQ_DBG("Set RWAddr=0x%06x", RWAddr);
	      break;

   case 0x28: WriteSPURAM(RWAddr, V);
	      RWAddr = (RWAddr + 1) & 0x3FFFF;
	      CheckIRQAddr(RWAddr);
	      break;

   case 0x2A: //if((SPUControl & 0x80) && !(V & 0x80))
	      // printf("\n\n\n\n ************** REVERB PROCESSING DISABLED\n\n\n\n");

	      SPUControl = V;
	      //SPUIRQ_DBG("Set SPUControl=0x%04x -- IRQA=%06x, RWA=%06x", V, IRQAddr, RWAddr);
	      //printf("SPU control write: %04x\n", V);
	      if(!(V & 0x40))
	      {
	       IRQAsserted = false;
	       IRQ_Assert(IRQ_SPU, IRQAsserted);
	      }
	      CheckIRQAddr(RWAddr);
	      break;

   case 0x2C: PSX_WARNING("[SPU] Global reg 0x2c set: 0x%04x", V);
	      break;

   case 0x30: CDVol[0] = V;
	      break;

   case 0x32: CDVol[1] = V;
	      break;

   case 0x34: ExternVol[0] = V;
	      break;

   case 0x36: ExternVol[1] = V;
	      break;

   case 0x38:
   case 0x3A: GlobalSweep[(A & 2) >> 1].WriteVolume(V);
	      break;
  }
 }

 Regs[(A & 0x1FF) >> 1] = V;
}

uint16 PS_SPU::Read(pscpu_timestamp_t timestamp, uint32 A)
{
 A &= 0x3FF;

 PSX_DBGINFO("[SPU] Read: %08x", A);

 if(A >= 0x200)
 {
  if(A < 0x260)
  {
   SPU_Voice *voice = &Voices[(A - 0x200) >> 2];

   //printf("Read: %08x %04x\n", A, voice->Sweep[(A & 2) >> 1].ReadVolume());

   return voice->Sweep[(A & 2) >> 1].ReadVolume();
  }
  else if(A < 0x280)
   return(AuxRegs[(A & 0x1F) >> 1]);

  return(0xFFFF);
 }

 if(A < 0x180)
 {
  SPU_Voice *voice = &Voices[A >> 4];

  switch(A & 0xF)
  {
   case 0x0C: return(voice->ADSR.EnvLevel);
   case 0x0E: return(voice->LoopAddr >> 2);
  }
 }
 else
 {
  switch(A & 0x7F)
  {
   case 0x1C: return(BlockEnd);
   case 0x1E: return(BlockEnd >> 16);

   case 0x26: //PSX_WARNING("[SPU] RWADDR Read");
	      break;

   case 0x28: PSX_WARNING("[SPU] SPURAM Read port(?) Read");

	      {
	       uint16 ret = ReadSPURAM(RWAddr);

	       RWAddr = (RWAddr + 1) & 0x3FFFF;
	       CheckIRQAddr(RWAddr);

	       return(ret);
	      }

   case 0x2a:
	return(SPUControl);

/* FIXME: What is this used for? */
   case 0x3C:
	//PSX_WARNING("[SPU] Read Unknown: %08x", A);
	return(0);

   case 0x38:
   case 0x3A: return(GlobalSweep[(A & 2) >> 1].ReadVolume());
  }
 }

 return(Regs[(A & 0x1FF) >> 1]);
}

void PS_SPU::StartFrame(double rate, uint32 quality)
{
 if((int)rate != last_rate || quality != last_quality)
 {
  int err = 0;

  last_rate = (int)rate;
  last_quality = quality;
 }

}

int32 PS_SPU::EndFrame(int16 *SoundBuf)
{
 //lastts = 0;

 if(last_rate == 44100)
 {
  int32 ret = IntermediateBufferPos;

  memcpy(SoundBuf, IntermediateBuffer, IntermediateBufferPos * 2 * sizeof(int16));
  IntermediateBufferPos = 0;

  return(ret);
 }
 else
 {
  IntermediateBufferPos = 0;
  return 0;
 }
}

SYNCFUNC(PS_SPU)
{
	NSS(Voices);

  NSS(NoiseCounter);
  NSS(LFSR);

  NSS(FM_Mode);
  NSS(Noise_Mode);
  NSS(Reverb_Mode);

  NSS(ReverbWA);

  NSS(GlobalSweep);

  NSS(ReverbVol);

  NSS(CDVol);
  NSS(ExternVol);

  NSS(IRQAddr);

  NSS(RWAddr);

  NSS(SPUControl);

  NSS(VoiceOn);
  NSS(VoiceOff);

  NSS(BlockEnd);

  NSS(CWA);

  NSS(Regs);
  NSS(AuxRegs);

  NSS(RDSB);
  NSS(RUSB);
  NSS(RvbResPos);

  NSS(ReverbCur);
  NSS(IRQAsserted);

  NSS(clock_divider);

  NSS(SPURAM);

	//if(isReader)
	//{
		//there was more weird crap here about controlling the range of variables. just sanity checks, I guess? to prevent crashes? no thanks, id rather have crashes alert me to nondeterminisms.
		//and another thing like this, which I think makes no sense. I really need to test these.
		IRQ_Assert(IRQ_SPU, IRQAsserted);
	//}

		//sanity check this
		  //RvbResPos &= 0x3F;
}

uint16 PS_SPU::PeekSPURAM(uint32 address)
{
 return(SPURAM[address & 0x3FFFF]);
}

void PS_SPU::PokeSPURAM(uint32 address, uint16 value)
{
 SPURAM[address & 0x3FFFF] = value;
}

uint32 PS_SPU::GetRegister(unsigned int which, char *special, const uint32 special_len)
{
 uint32 ret = 0xDEADBEEF;

 if(which >= 0x8000)
 {
  unsigned int v = (which - 0x8000) >> 8;

  switch((which & 0xFF) | 0x8000)
  {
   case GSREG_V0_VOL_CTRL_L:
	ret = Regs[v * 8 + 0x0];
	break;

   case GSREG_V0_VOL_CTRL_R:
	ret = Regs[v * 8 + 0x1];
	break;

   case GSREG_V0_VOL_L:
	ret = Voices[v].Sweep[0].ReadVolume() & 0xFFFF;
	break;

   case GSREG_V0_VOL_R:
	ret = Voices[v].Sweep[1].ReadVolume() & 0xFFFF;
	break;

   case GSREG_V0_PITCH:
	ret = Voices[v].Pitch;
	break;

   case GSREG_V0_STARTADDR:
	ret = Voices[v].StartAddr;
	break;

   case GSREG_V0_ADSR_CTRL:
	ret = Voices[v].ADSRControl;
	break;

   case GSREG_V0_ADSR_LEVEL:
	ret = Voices[v].ADSR.EnvLevel;
	break;

   case GSREG_V0_LOOP_ADDR:
	ret = Voices[v].LoopAddr;
	break;

   case GSREG_V0_READ_ADDR:
	ret = Voices[v].CurAddr;
	break;
  }
 }
 else if(which >= GSREG_FB_SRC_A && which <= GSREG_IN_COEF_R)
 {
	ret = ReverbRegs[which - GSREG_FB_SRC_A];
 }
 else switch(which)
 {
  case GSREG_SPUCONTROL:
	ret = SPUControl;
	break;

  case GSREG_FM_ON:
	ret = FM_Mode;
	break;

  case GSREG_NOISE_ON:
	ret = Noise_Mode;
	break;

  case GSREG_REVERB_ON:
	ret = Reverb_Mode;
	break;

  case GSREG_CDVOL_L:
	ret = (uint16)CDVol[0];
	break;

  case GSREG_CDVOL_R:
	ret = (uint16)CDVol[1];
	break;

  case GSREG_MAINVOL_CTRL_L:
	ret = Regs[0xC0];
	break;

  case GSREG_MAINVOL_CTRL_R:
	ret = Regs[0xC1];
	break;

  case GSREG_MAINVOL_L:
	ret = GlobalSweep[0].ReadVolume() & 0xFFFF;
	break;

  case GSREG_MAINVOL_R:
	ret = GlobalSweep[1].ReadVolume() & 0xFFFF;
	break;

  case GSREG_RVBVOL_L:
	ret = (uint16)ReverbVol[0];
	break;

  case GSREG_RVBVOL_R:
	ret = (uint16)ReverbVol[1];
	break;

  case GSREG_RWADDR:
	ret = RWAddr;
	break;

  case GSREG_IRQADDR:
	ret = IRQAddr;
	break;

  case GSREG_REVERBWA:
	ret = ReverbWA >> 2;
	break;

  case GSREG_VOICEON:
	ret = VoiceOn;
	break;

  case GSREG_VOICEOFF:
	ret = VoiceOff;
	break;

  case GSREG_BLOCKEND:
	ret = BlockEnd;
	break;
 }

 return(ret);
}

void PS_SPU::SetRegister(unsigned int which, uint32 value)
{
 if(which >= GSREG_FB_SRC_A && which <= GSREG_IN_COEF_R)
 {
	ReverbRegs[which - GSREG_FB_SRC_A] = value;
 }
 else switch(which)
 {
  case GSREG_SPUCONTROL:
	SPUControl = value;
	break;

  case GSREG_FM_ON:
	FM_Mode = value & 0xFFFFFF;
	break;

  case GSREG_NOISE_ON:
	Noise_Mode = value & 0xFFFFFF;
	break;

  case GSREG_REVERB_ON:
	Reverb_Mode = value & 0xFFFFFF;
	break;

  case GSREG_CDVOL_L:
	CDVol[0] = (int16)value;
	break;

  case GSREG_CDVOL_R:
	CDVol[1] = (int16)value;
	break;

  case GSREG_MAINVOL_CTRL_L:
	Regs[0xC0] = value;
	GlobalSweep[0].WriteControl(value);
	//GlobalSweep[0].Control = value;
	break;

  case GSREG_MAINVOL_CTRL_R:
	Regs[0xC1] = value;
	GlobalSweep[1].WriteControl(value);
	//GlobalSweep[1].Control = value;
	break;

  case GSREG_MAINVOL_L:
	GlobalSweep[0].WriteVolume(value);
	break;

  case GSREG_MAINVOL_R:
	GlobalSweep[1].WriteVolume(value);
	break;

  case GSREG_RVBVOL_L:
	ReverbVol[0] = (int16)value;
	break;

  case GSREG_RVBVOL_R:
	ReverbVol[1] = (int16)value;
	break;

  case GSREG_RWADDR:
	RWAddr = value & 0x3FFFF;
	break;

  case GSREG_IRQADDR:
	IRQAddr = value & 0x3FFFC;
	break;

  //
  // REVERB_WA
  //

  case GSREG_VOICEON:
        VoiceOn = value & 0xFFFFFF;
        break;

  case GSREG_VOICEOFF:
        VoiceOff = value & 0xFFFFFF;
        break;

  case GSREG_BLOCKEND:
        BlockEnd = value & 0xFFFFFF;
        break;
 }
}

}


text:
@interface Grupos_VIew_Controller ()
{
    HomeModel *_homeModel;
    NSArray *_feedItems;
    Grupos *_GrupoSeleccionado;
}
@end
@implementation Grupos_VIew_Controller
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set this view controller object as the delegate and data source for the table view
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;

    // Create array object and assign it to _feedItems variable
    _feedItems = [[NSArray alloc] init];

    // Create new HomeModel object and assign it to _homeModel variable
    _homeModel = [[HomeModel alloc] init];

    // Set this view controller object as the delegate for the home model object
    _homeModel.delegate = self;

    // Call the download items method of the home model object
    [_homeModel downloadItems];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)itemsDownloaded:(NSArray *)items
{
    // This delegate method will get called when the items are finished downloading

    // Set the downloaded items to the array
    _feedItems = items;

    // Reload the table view
    [self.listTableView reloadData];
}

#pragma mark Table View Delegate Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of feed items (initially 0)
    return _feedItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Retrieve cell
    NSString *cellIdentifier = @"BasicCell";
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    // Get the location to be shown
    Grupos *item = _feedItems[indexPath.row];

    // Get references to labels of cell
    NSString * formato_celda = [NSString stringWithFormat:@"%@ - %@",item.Clave,item.Materia];
    myCell.textLabel.text = formato_celda;

    return myCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Set selected location to var
    _GrupoSeleccionado = _feedItems[indexPath.row];

    // Manually call segue to detail view controller
    [self performSegueWithIdentifier:@"detailSegue" sender:self];
}

#pragma mark Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get reference to the destination view controller
    Detail_Grupo_View_Controller *detailVC = segue.destinationViewController;

    // Set the property to the selected location so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    detailVC.Grupo_Seleccionado = _GrupoSeleccionado;
}

@end


text: 3D-GP, a currently in progress 3D fork of 2D-GP


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

namespace Sidekick.MVVM.Models
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;

  using Catel.Collections;

  using Sidekick.Shared.Utils;

  /// Pageable implementation which holds all items in memory.
  /// <typeparam name="T">Objects type</typeparam>
  /// <seealso cref="Sidekick.MVVM.Models.PageableCollectionBase{T}" />
  public class InMemoryPageableCollection<T> : PageableCollectionBase<T>
  {
    #region Constructors

    /// Initializes a new instance of the <see cref="InMemoryPageableCollection{T}" /> class.
    /// <param name="allObjects">All objects.</param>
    public InMemoryPageableCollection(IEnumerable<T> allObjects = null)
    {
      AllObjects = new FastObservableCollection<T>(allObjects);
    }

    /// Initializes a new instance of the <see cref="InMemoryPageableCollection{T}" /> class.
    /// <param name="allObjects">All objects.</param>
    /// <param name="pageSize">Size of the page.</param>
    public InMemoryPageableCollection(IEnumerable<T> allObjects, int pageSize) : base(pageSize)
    {
      AllObjects = new FastObservableCollection<T>(allObjects);
    }

    #endregion

    #region Properties

    /// Total page count (total item count / page size).
    public override int TotalPageCount
      =>
      AllObjects != null && PageSize > 0
        ? (int)Math.Ceiling(AllObjects.Count / (float)PageSize)
        : 0;

    /// Holds objects to page
    protected FastObservableCollection<T> AllObjects { get; set; }

    #endregion

    #region Methods

    /// Removes an item from collection/store.
    /// <param name="item">Item to remove</param>
    /// <returns></returns>
    public override Task<bool> RemoveAsync(T item)
    {
      return DoRemoveAsync(() => RemoveFromList(item));
    }

    /// Removes items from collection/store.
    /// <param name="items">Items to remove</param>
    /// <returns></returns>
    public override Task<bool> RemoveAsync(IEnumerable<T> items)
    {
      return DoRemoveAsync(() => RemoveFromList(items));
    }

    /// Add an item to collection/store.
    /// <param name="item">Item to add</param>
    /// <returns></returns>
    public override Task<bool> AddAsync(T item)
    {
      return DoAddAsync(() => AddToList(item));
    }

    /// Add items to collection/store.
    /// <param name="items">Items to add</param>
    /// <returns></returns>
    public override Task<bool> AddAsync(IEnumerable<T> items)
    {
      return DoAddAsync(() => AddToList(items));
    }

    /// Update page item according to current page.
    /// <returns></returns>
    public override Task UpdateCurrentPageItemsAsync()
    {
      int skip = (CurrentPage - 1) * PageSize;

      using (CurrentPageItems.SuspendChangeNotifications())
        ((ICollection<T>)CurrentPageItems).ReplaceRange(AllObjects.Skip(skip).Take(PageSize));

      return TaskConstants.Completed;
    }

    //
    // Allows to override Add/Remove behavior to add features (such as DB)

    /// Removes item from list synchronously.
    /// <param name="item">The item.</param>
    /// <returns></returns>
    protected Task<bool> RemoveFromList(T item)
    {
      AllObjects.Remove(item);
      return TaskConstants.BooleanTrue;
    }

    /// Removes items from list synchronously.
    /// <param name="items">The items.</param>
    /// <returns></returns>
    protected Task<bool> RemoveFromList(IEnumerable<T> items)
    {
      AllObjects.RemoveItems(items);
      return TaskConstants.BooleanTrue;
    }

    /// Adds item to list synchronously.
    /// <param name="item">The item.</param>
    /// <returns></returns>
    protected Task<bool> AddToList(T item)
    {
      int insertPosition = (CurrentPage - 1) * PageSize;

      AllObjects.Insert(insertPosition, item);

      return TaskConstants.BooleanTrue;
    }

    /// Adds items to list synchronously.
    /// <param name="items">The items.</param>
    /// <returns></returns>
    protected Task<bool> AddToList(IEnumerable<T> items)
    {
      int insertPosition = (CurrentPage - 1) * PageSize;

      AllObjects.InsertItems(items, insertPosition);

      return TaskConstants.BooleanTrue;
    }

    #endregion
  }
}


text:
from main import BaseHandler

class MainHandler(BaseHandler):
    """render front page"""

    def get(self):
        self.render("index.html")


text:
package com.nowellpoint.api.util;

public class MessageConstants {
	public static final String REGISTRATION_MISSING_LAST_NAME = "registration.missing.last.name";
	public static final String REGISTRATION_MISSING_EMAIL = "registration.missing.email";
	public static final String REGISTRATION_MISSING_COUNTRY_CODE = "registration.missing.country.code";
	public static final String REGISTRATION_MISSING_DOMAIN = "registration.missing.domain";
	public static final String REGISTRATION_MISSING_PLAN_ID = "registration.missing.plan.id";
	public static final String REGISTRATION_ACCOUNT_CONFLICT = "registration.account.conflict";
	public static final String REGISTRATION_DOMAIN_CONFLICT = "registration.domain.conflict";
	public static final String REGISTRATION_RECEIVED = "registration.received";
	public static final String REGISTRATION_INVALID_OR_EXPIRED = "registration.invalid.or.expired";
	public static final String REGISTRATION_INVALID_PLAN = "registration.invalid.plan";
	public static final String SLACK_MESSAGE_SUBJECT = "slack.message.subject";
	public static final String SLACK_TEST_MESSAGE = "slack.test.message";
	public static final String SLACK_MISSING_WEBHOOK_URL = "slack.missing.webhook.url";
	public static final String SLACK_MISSING_USERNAME = "slack.missing.username";
	public static final String SLACK_MISSING_MESSAGE_TEXT = "slack.missing.message.text";
	public static final String JOB_UNABLE_TO_SUBMIT = "job.unable.to.submit";
	public static final String JOB_INVALID_ACTION = "job.invalid.action";
	public static final String UNEXPECTED_EXCEPTION = "unexpected.exception";
	public static final String INVALID_COUNTRY_PARAMETERS = "invalid.country.parameters";
	public static final String UNABLE_TO_REMOVE_CREDIT_CARD = "unable.to.remove.credit.card";
	public static final String CONNECTOR_INVALID_TYPE = "connector.invalid.type";
	public static final String CONNECTOR_MISSING_NAME = "connector.missing.name";
	public static final String CONNECTOR_MISSING_CLIENT_ID = "connector.missing.client.id";
	public static final String CONNECTOR_MISSING_CLIENT_SECRET = "connector.missing.client.secret";
	public static final String CONNECTOR_MISSING_USERNAME = "connector.missing.username";
	public static final String CONNECTOR_MISSING_PASSWORD = "connector.missing.password";
	public static final String CONNECTOR_INVALID_STATUS = "connector.invalid.status";
	public static final String CONNECTOR_TYPE_SCHEME_MISMATCH = "connector.type.scheme.mismatch";
	public static final String CONNECTOR_ALREADY_DISCONNECTED = "connector.already.disconnected";
	public static final String CONNECTOR_CANNOT_REFRESH = "connector.cannot.refresh";
}