text:
package sbt.internal.scripted;

import java.io.File;

import xsbti.Logger;

public class ScriptConfig {

	private String label;
	private File testDirectory;
	private Logger logger;

	public ScriptConfig(String label, File testDirectory, Logger logger) {
		this.label = label;
		this.testDirectory = testDirectory;
		this.logger = logger;
	}

	public String label() {
		return this.label;
	}

	public File testDirectory() {
		return this.testDirectory;
	}

	public Logger logger() {
		return this.logger;
	}

}

redpajama_set_name: RedPajamaGithub


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

namespace SSMScripter.Runner
{
    public class RunConfig
    {
        public RunConfig()
        {
            RunTool = null;
            RunArgs = null;
        }

        public string RunTool {get; set;}

        public string RunArgs { get; set; }

        public static readonly RunConfig Undefined = new RunConfig();

        public bool IsUndefined()
        {
            return Undefined.Equals(this);
        }
    }
}


text:
package org.hibernate.metamodel.relational.state;

import java.util.List;

/**
 * @author Gail Badner
 */
public interface TupleRelationalState extends ValueRelationalState {
	List<SimpleValueRelationalState> getRelationalStates();
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.iceberg.delete;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.slice.SizeOf;
import org.apache.iceberg.FileContent;
import org.apache.iceberg.FileFormat;
import org.openjdk.jol.info.ClassLayout;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static io.airlift.slice.SizeOf.SIZE_OF_INT;
import static io.airlift.slice.SizeOf.estimatedSizeOf;
import static java.util.Objects.requireNonNull;

public final class DeleteFile
{
    private static final long INSTANCE_SIZE = ClassLayout.parseClass(DeleteFile.class).instanceSize();

    private final FileContent content;
    private final String path;
    private final FileFormat format;
    private final long recordCount;
    private final long fileSizeInBytes;
    private final List<Integer> equalityFieldIds;
    private final Map<Integer, byte[]> lowerBounds;
    private final Map<Integer, byte[]> upperBounds;

    public static DeleteFile fromIceberg(org.apache.iceberg.DeleteFile deleteFile)
    {
        Map<Integer, byte[]> lowerBounds = firstNonNull(deleteFile.lowerBounds(), ImmutableMap.<Integer, ByteBuffer>of())
                .entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().array().clone()));
        Map<Integer, byte[]> upperBounds = firstNonNull(deleteFile.upperBounds(), ImmutableMap.<Integer, ByteBuffer>of())
                .entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().array().clone()));

        return new DeleteFile(
                deleteFile.content(),
                deleteFile.path().toString(),
                deleteFile.format(),
                deleteFile.recordCount(),
                deleteFile.fileSizeInBytes(),
                Optional.ofNullable(deleteFile.equalityFieldIds()).orElseGet(ImmutableList::of),
                lowerBounds,
                upperBounds);
    }

    @JsonCreator
    public DeleteFile(
            FileContent content,
            String path,
            FileFormat format,
            long recordCount,
            long fileSizeInBytes,
            List<Integer> equalityFieldIds,
            Map<Integer, byte[]> lowerBounds,
            Map<Integer, byte[]> upperBounds)
    {
        this.content = requireNonNull(content, "content is null");
        this.path = requireNonNull(path, "path is null");
        this.format = requireNonNull(format, "format is null");
        this.recordCount = recordCount;
        this.fileSizeInBytes = fileSizeInBytes;
        this.equalityFieldIds = ImmutableList.copyOf(requireNonNull(equalityFieldIds, "equalityFieldIds is null"));
        this.lowerBounds = ImmutableMap.copyOf(requireNonNull(lowerBounds, "lowerBounds is null"));
        this.upperBounds = ImmutableMap.copyOf(requireNonNull(upperBounds, "upperBounds is null"));
    }

    @JsonProperty
    public FileContent content()
    {
        return content;
    }

    @JsonProperty
    public String path()
    {
        return path;
    }

    @JsonProperty
    public FileFormat format()
    {
        return format;
    }

    @JsonProperty
    public long recordCount()
    {
        return recordCount;
    }

    @JsonProperty
    public long fileSizeInBytes()
    {
        return fileSizeInBytes;
    }

    @JsonProperty
    public List<Integer> equalityFieldIds()
    {
        return equalityFieldIds;
    }

    @JsonProperty
    public Map<Integer, byte[]> getLowerBounds()
    {
        return lowerBounds;
    }

    @JsonProperty
    public Map<Integer, byte[]> getUpperBounds()
    {
        return upperBounds;
    }

    public long getRetainedSizeInBytes()
    {
        return INSTANCE_SIZE
                + estimatedSizeOf(path)
                + estimatedSizeOf(equalityFieldIds, ignored -> SIZE_OF_INT)
                + estimatedSizeOf(lowerBounds, entry -> SIZE_OF_INT, SizeOf::sizeOf)
                + estimatedSizeOf(upperBounds, entry -> SIZE_OF_INT, SizeOf::sizeOf);
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .addValue(path)
                .add("records", recordCount)
                .toString();
    }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file is autogenerated by
//     java_cpp_enum.py
// From
//     ../../media/capture/video/android/video_capture_device_android.h

package org.chromium.media;

import android.support.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@IntDef({
    AndroidImageFormat.NV21, AndroidImageFormat.YUV_420_888, AndroidImageFormat.YV12,
    AndroidImageFormat.UNKNOWN
})
@Retention(RetentionPolicy.SOURCE)
public @interface AndroidImageFormat {
  /**
   * Android graphics ImageFormat mapping, see reference in:
   * http://developer.android.com/reference/android/graphics/ImageFormat.html
   */
  int NV21 = 17;
  int YUV_420_888 = 35;
  int YV12 = 842094169;
  int UNKNOWN = 0;
}


text:
<?php

// Call Zend_Json_Server_SmdTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Json_Server_SmdTest::main");
}

require_once 'Zend/Json/Server/Smd.php';
require_once 'Zend/Json/Server/Smd/Service.php';
require_once 'Zend/Json.php';

/**
 * Test class for Zend_Json_Server_Smd
 *
 * @category   Zend
 * @package    Zend_Json_Server
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Json
 * @group      Zend_Json_Server
 */
class Zend_Json_Server_SmdTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {

        $suite  = new PHPUnit_Framework_TestSuite("Zend_Json_Server_SmdTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        $this->smd = new Zend_Json_Server_Smd();
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }

    public function testTransportShouldDefaultToPost()
    {
        $this->assertEquals('POST', $this->smd->getTransport());
    }

    public function testTransportAccessorsShouldWorkUnderNormalInput()
    {
        $this->smd->setTransport('POST');
        $this->assertEquals('POST', $this->smd->getTransport());
    }

    public function testTransportShouldBeLimitedToPost()
    {
        foreach (array('GET', 'REST') as $transport) {
            try {
                $this->smd->setTransport($transport);
                $this->fail('Invalid transport should throw exception');
            } catch (Zend_Json_Server_Exception $e) {
                $this->assertContains('Invalid transport', $e->getMessage());
            }
        }
    }

    public function testEnvelopeShouldDefaultToJsonRpcVersion1()
    {
        $this->assertEquals(Zend_Json_Server_Smd::ENV_JSONRPC_1, $this->smd->getEnvelope());
    }

    public function testEnvelopeAccessorsShouldWorkUnderNormalInput()
    {
        $this->testEnvelopeShouldDefaultToJsonRpcVersion1();
        $this->smd->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
        $this->assertEquals(Zend_Json_Server_Smd::ENV_JSONRPC_2, $this->smd->getEnvelope());
        $this->smd->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_1);
        $this->assertEquals(Zend_Json_Server_Smd::ENV_JSONRPC_1, $this->smd->getEnvelope());
    }

    public function testEnvelopeShouldBeLimitedToJsonRpcVersions()
    {
        foreach (array('URL', 'PATH', 'JSON') as $env) {
            try {
                $this->smd->setEnvelope($env);
                $this->fail('Invalid envelope type should throw exception');
            } catch (Zend_Json_Server_Exception $e) {
                $this->assertContains('Invalid envelope', $e->getMessage());
            }
        }
    }

    public function testContentTypeShouldDefaultToApplicationJson()
    {
        $this->assertEquals('application/json', $this->smd->getContentType());
    }

    public function testContentTypeAccessorsShouldWorkUnderNormalInput()
    {
        foreach (array('text/json', 'text/plain', 'application/x-json') as $type) {
            $this->smd->setContentType($type);
            $this->assertEquals($type, $this->smd->getContentType());
        }
    }

    public function testContentTypeShouldBeLimitedToMimeFormatStrings()
    {
        foreach (array('plain', 'json', 'foobar') as $type) {
            try {
                $this->smd->setContentType($type);
                $this->fail('Invalid content type should raise exception');
            } catch (Zend_Json_Server_Exception $e) {
                $this->assertContains('Invalid content type', $e->getMessage());
            }
        }
    }

    public function testTargetShouldDefaultToNull()
    {
        $this->assertNull($this->smd->getTarget());
    }

    public function testTargetAccessorsShouldWorkUnderNormalInput()
    {
        $this->testTargetShouldDefaultToNull();
        $this->smd->setTarget('foo');
        $this->assertEquals('foo', $this->smd->getTarget());
    }

    public function testIdShouldDefaultToNull()
    {
        $this->assertNull($this->smd->getId());
    }

    public function testIdAccessorsShouldWorkUnderNormalInput()
    {
        $this->testIdShouldDefaultToNull();
        $this->smd->setId('foo');
        $this->assertEquals('foo', $this->smd->getId());
    }

    public function testDescriptionShouldDefaultToNull()
    {
        $this->assertNull($this->smd->getDescription());
    }

    public function testDescriptionAccessorsShouldWorkUnderNormalInput()
    {
        $this->testDescriptionShouldDefaultToNull();
        $this->smd->setDescription('foo');
        $this->assertEquals('foo', $this->smd->getDescription());
    }

    public function testDojoCompatibilityShouldBeDisabledByDefault()
    {
        $this->assertFalse($this->smd->isDojoCompatible());
    }

    public function testDojoCompatibilityFlagShouldBeMutable()
    {
        $this->testDojoCompatibilityShouldBeDisabledByDefault();
        $this->smd->setDojoCompatible(true);
        $this->assertTrue($this->smd->isDojoCompatible());
        $this->smd->setDojoCompatible(false);
        $this->assertFalse($this->smd->isDojoCompatible());
    }

    public function testServicesShouldBeEmptyByDefault()
    {
        $services = $this->smd->getServices();
        $this->assertTrue(is_array($services));
        $this->assertTrue(empty($services));
    }

    public function testShouldBeAbleToUseServiceObjectToAddService()
    {
        $service = new Zend_Json_Server_Smd_Service('foo');
        $this->smd->addService($service);
        $this->assertSame($service, $this->smd->getService('foo'));
    }

    public function testShouldBeAbleToUseArrayToAddService()
    {
        $service = array(
            'name' => 'foo',
        );
        $this->smd->addService($service);
        $foo = $this->smd->getService('foo');
        $this->assertTrue($foo instanceof Zend_Json_Server_Smd_Service);
        $this->assertEquals('foo', $foo->getName());
    }

    public function testAddingServiceWithExistingServiceNameShouldThrowException()
    {
        $service = new Zend_Json_Server_Smd_Service('foo');
        $this->smd->addService($service);
        $test    = new Zend_Json_Server_Smd_Service('foo');
        try {
            $this->smd->addService($test);
            $this->fail('Adding service with existing service name should throw exception');
        } catch (Zend_Json_Server_Exception $e) {
            $this->assertContains('already register', $e->getMessage());
        }
    }

    public function testAttemptingToRegisterInvalidServiceShouldThrowException()
    {
        foreach (array('foo', false, 1, 1.0) as $service) {
            try {
                $this->smd->addService($service);
                $this->fail('Attempt to register invalid service should throw exception');
            } catch (Zend_Json_Server_Exception $e) {
                $this->assertContains('Invalid service', $e->getMessage());
            }
        }
    }

    public function testShouldBeAbleToAddManyServicesAtOnceWithArrayOfServiceObjects()
    {
        $one   = new Zend_Json_Server_Smd_Service('one');
        $two   = new Zend_Json_Server_Smd_Service('two');
        $three = new Zend_Json_Server_Smd_Service('three');
        $services = array($one, $two, $three);
        $this->smd->addServices($services);
        $test = $this->smd->getServices();
        $this->assertSame($services, array_values($test));
    }

    public function testShouldBeAbleToAddManyServicesAtOnceWithArrayOfArrays()
    {
        $services = array(
            array('name' => 'one'),
            array('name' => 'two'),
            array('name' => 'three'),
        );
        $this->smd->addServices($services);
        $test = $this->smd->getServices();
        $this->assertSame(array('one', 'two', 'three'), array_keys($test));
    }

    public function testShouldBeAbleToAddManyServicesAtOnceWithMixedArrayOfObjectsAndArrays()
    {
        $two = new Zend_Json_Server_Smd_Service('two');
        $services = array(
            array('name' => 'one'),
            $two,
            array('name' => 'three'),
        );
        $this->smd->addServices($services);
        $test = $this->smd->getServices();
        $this->assertSame(array('one', 'two', 'three'), array_keys($test));
        $this->assertEquals($two, $test['two']);
    }

    public function testSetServicesShouldOverwriteExistingServices()
    {
        $this->testShouldBeAbleToAddManyServicesAtOnceWithMixedArrayOfObjectsAndArrays();
        $five = new Zend_Json_Server_Smd_Service('five');
        $services = array(
            array('name' => 'four'),
            $five,
            array('name' => 'six'),
        );
        $this->smd->setServices($services);
        $test = $this->smd->getServices();
        $this->assertSame(array('four', 'five', 'six'), array_keys($test));
        $this->assertEquals($five, $test['five']);
    }

    public function testShouldBeAbleToRetrieveServiceByName()
    {
        $this->testShouldBeAbleToUseServiceObjectToAddService();
    }

    public function testShouldBeAbleToRemoveServiceByName()
    {
        $this->testShouldBeAbleToUseServiceObjectToAddService();
        $this->assertTrue($this->smd->removeService('foo'));
        $this->assertFalse($this->smd->getService('foo'));
    }

    public function testShouldBeAbleToCastToArray()
    {
        $options = $this->getOptions();
        $this->smd->setOptions($options);
        $service = $this->smd->toArray();
        $this->validateServiceArray($service, $options);
    }

    public function testShouldBeAbleToCastToDojoArray()
    {
        $options = $this->getOptions();
        $this->smd->setOptions($options);
        $smd = $this->smd->toDojoArray();

        $this->assertTrue(is_array($smd));

        $this->assertTrue(array_key_exists('SMDVersion', $smd));
        $this->assertTrue(array_key_exists('serviceType', $smd));
        $this->assertTrue(array_key_exists('methods', $smd));

        $this->assertEquals('.1', $smd['SMDVersion']);
        $this->assertEquals('JSON-RPC', $smd['serviceType']);
        $methods = $smd['methods'];
        $this->assertEquals(2, count($methods));

        $foo = array_shift($methods);
        $this->assertTrue(array_key_exists('name', $foo));
        $this->assertTrue(array_key_exists('serviceURL', $foo));
        $this->assertTrue(array_key_exists('parameters', $foo));
        $this->assertEquals('foo', $foo['name']);
        $this->assertEquals($this->smd->getTarget(), $foo['serviceURL']);
        $this->assertTrue(is_array($foo['parameters']));
        $this->assertEquals(1, count($foo['parameters']));

        $bar = array_shift($methods);
        $this->assertTrue(array_key_exists('name', $bar));
        $this->assertTrue(array_key_exists('serviceURL', $bar));
        $this->assertTrue(array_key_exists('parameters', $bar));
        $this->assertEquals('bar', $bar['name']);
        $this->assertEquals($this->smd->getTarget(), $bar['serviceURL']);
        $this->assertTrue(is_array($bar['parameters']));
        $this->assertEquals(1, count($bar['parameters']));
    }

    public function testShouldBeAbleToRenderAsJson()
    {
        $options = $this->getOptions();
        $this->smd->setOptions($options);
        $json = $this->smd->toJson();
        $smd  = Zend_Json::decode($json);
        $this->validateServiceArray($smd, $options);
    }

    public function testToStringImplementationShouldProxyToJson()
    {
        $options = $this->getOptions();
        $this->smd->setOptions($options);
        $json = $this->smd->__toString();
        $smd  = Zend_Json::decode($json);
        $this->validateServiceArray($smd, $options);
    }

    public function getOptions()
    {
        return array(
            'target'   => '/test/me',
            'id'       => '/test/me',
            'services' => array(
                array(
                    'name'   => 'foo',
                    'params' => array(
                        array('type' => 'boolean'),
                    ),
                    'return' => 'boolean',
                ),
                array(
                    'name'   => 'bar',
                    'params' => array(
                        array('type' => 'integer'),
                    ),
                    'return' => 'string',
                ),
            )
        );
    }

    public function validateServiceArray(array $smd, array $options)
    {
        $this->assertTrue(is_array($smd));

        $this->assertTrue(array_key_exists('SMDVersion', $smd));
        $this->assertTrue(array_key_exists('target', $smd));
        $this->assertTrue(array_key_exists('id', $smd));
        $this->assertTrue(array_key_exists('transport', $smd));
        $this->assertTrue(array_key_exists('envelope', $smd));
        $this->assertTrue(array_key_exists('contentType', $smd));
        $this->assertTrue(array_key_exists('services', $smd));

        $this->assertEquals(Zend_Json_Server_Smd::SMD_VERSION, $smd['SMDVersion']);
        $this->assertEquals($options['target'], $smd['target']);
        $this->assertEquals($options['id'], $smd['id']);
        $this->assertEquals($this->smd->getTransport(), $smd['transport']);
        $this->assertEquals($this->smd->getEnvelope(), $smd['envelope']);
        $this->assertEquals($this->smd->getContentType(), $smd['contentType']);
        $services = $smd['services'];
        $this->assertEquals(2, count($services));
        $this->assertTrue(array_key_exists('foo', $services));
        $this->assertTrue(array_key_exists('bar', $services));
    }
}

// Call Zend_Json_Server_SmdTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Json_Server_SmdTest::main") {
    Zend_Json_Server_SmdTest::main();
}


text:
/*
 * $Revision: 2524 $
 *
 * last checkin:
 *   $Author: gutwenger $
 *   $Date: 2012-07-03 09:54:22 +0200 (Tue, 03 Jul 2012) $
 ***************************************************************/

/** \file
 * \brief Declaration of upward planarization layout algorithm.
 *
 * \author Hoi-Ming Wong
 *
 * \par License:
 * This file is part of the Open Graph Drawing Framework (OGDF).
 *
 * \par
 * Copyright (C)<br>
 * See README.txt in the root directory of the OGDF installation for details.
 *
 * \par
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * Version 2 or 3 as published by the Free Software Foundation;
 * see the file LICENSE.txt included in the packaging of this file
 * for details.
 *
 * \par
 * 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.
 *
 * \par
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * \see  http://www.gnu.org/copyleft/gpl.html
 ***************************************************************/

#ifdef _MSC_VER
#pragma once
#endif

#ifndef OGDF_LAYER_BASED_UPR_LAYOUT_H
#define OGDF_LAYER_BASED_UPR_LAYOUT_H

#include <ogdf/basic/ModuleOption.h>
#include <ogdf/upward/UpwardPlanRep.h>
#include <ogdf/module/RankingModule.h>
#include <ogdf/module/UPRLayoutModule.h>
#include <ogdf/module/HierarchyLayoutModule.h>
#include <ogdf/layered/OptimalHierarchyLayout.h>
#include <ogdf/layered/FastHierarchyLayout.h>
#include <ogdf/layered/OptimalRanking.h>

namespace ogdf {

class OrderComparer
{
public:
	OrderComparer(const UpwardPlanRep &_UPR, Hierarchy &_H);

	// if vH1 and vH2 are placed on the same layer and node vH1 has to drawn on the lefthand side of vH2 (according to UPR) then return true;
	bool less(node vH1, node vH2) const ;

private:
	const UpwardPlanRep &UPR;
	Hierarchy &H;
	NodeArray<int> dfsNum;
	//EdgeArray<int> outEdgeOrder;
	mutable NodeArray<bool> crossed;

	//traverse with dfs using edge order from left to right and compute the dfs number.
	void dfs_LR( edge e,
				 NodeArray<bool> &visited,
				 NodeArray<int> &dfsNum,
				 int &num);

	//return true if vUPR1 is on the lefthand side of vUPR2 according to UPR.
	bool left(node vUPR1,
			List<edge> chain1, //if vUPR1 is associated with a long edge dummy vH1, then chain1 contain vH1
			node vUPR2 ,
			List<edge> chain2 // if vUPR2 is associated with a long edge dummy vH2, then chain2 contain vH2
			) const;

	//return true if vUPR1 is on the lefthand side of vUPR2 according to UPR.
	// pred.: source or target of both edge muss identical
	bool left(edge e1UPR, edge e2UPR) const;

	//return true if vUPR1 is on the lefthand side of vUPR2 according to UPR.
	// use only by method less for the case when both node vH1 and vH2 are long-edge dummies.
	// level: the current level of the long-edge dummies
	bool left(List<edge> &chain1, List<edge> &chain2, int level) const;

	//return true if there is a node above vUPR with rank level or lower
	bool checkUp(node vUPR, int level) const;
};

class OGDF_EXPORT LayerBasedUPRLayout : public UPRLayoutModule
{
public:

	// constructor: sets options to default values
	LayerBasedUPRLayout()
	{
		// set default value
		FastHierarchyLayout *fhl = new FastHierarchyLayout();
		fhl->nodeDistance(40.0);
		fhl->layerDistance(40.0);
		fhl->fixedLayerDistance(true);
		m_layout.set(fhl);
		OptimalRanking *opRank = new OptimalRanking();
		opRank->separateMultiEdges(false);
		m_ranking.set(opRank);
		m_numLevels = 0;
		m_maxLevelSize = 0;
	}

	// destructor
	~LayerBasedUPRLayout() { }

	// returns the number of crossings in the layout after the algorithm
	// has been applied
	int numberOfCrossings() const { return m_crossings; }

	// module option for the computation of the final layout
	void setLayout(HierarchyLayoutModule *pLayout) {
		m_layout.set(pLayout);
	}

	void setRanking(RankingModule *pRanking) {
		m_ranking.set(pRanking);
	}

	//! Use only the 3. phase of Sugiyama' framework for layout.
	void UPRLayoutSimple(const UpwardPlanRep &UPR, GraphAttributes &AG);

	//! Return the number of layers/levels. Not implemented if use methode callSimple(..).
	int numberOfLayers() { return m_numLevels; }

	//! Return the max. number of elements on a layer. Not implemented if use methode callSimple(..).
	int maxLayerSize() { return m_maxLevelSize; }

protected :

	/*
	 * @param UPR is the upward planarized representation of the input graph.
	 * @param AG has to be assigned the hierarchy layout.
	 */
	virtual void doCall(const UpwardPlanRep &UPR, GraphAttributes &AG);

	int m_crossings;

	ModuleOption<RankingModule> m_ranking;

	ModuleOption<HierarchyLayoutModule> m_layout;

	struct RankComparer {
		Hierarchy *H;
		bool less(node v1, node v2) const {
			return (H->rank(v1) < H->rank(v2));
		}
	};

private:

	// compute a ranking of the nodes of UPR.
	// Precond. a ranking module muss be set
	void computeRanking(const UpwardPlanRep &UPR, NodeArray<int> &rank);

	//! rearanging the position of the sources in order to reduce some crossings.
	void postProcessing_sourceReorder(Hierarchy &H, List<node> &sources);

	//! reduce the long edge dummies (LED)
	void postProcessing_reduceLED(Hierarchy &H, List<node> &sources) {
		forall_listiterators(node, it, sources)
			postProcessing_reduceLED(H, *it);
	}

	void postProcessing_reduceLED(Hierarchy &H, node vH);

	void post_processing_reduce(Hierarchy &H, int &i, node s, int minIdx, int maxIdx, NodeArray<bool> &markedNodes);

	//! mark all the nodes dominated by sH.	(Help method for postProcessing_reduceLED() )
	void postProcessing_markUp(Hierarchy &H, node sH, NodeArray<bool> &markedNodes);

	//! delete level i of H.
	void post_processing_deleteLvl(Hierarchy &H, int i);

	//! delete the interval [beginIdx,endIdx] on the level j.
	void post_processing_deleteInterval(Hierarchy &H, int beginIdx, int endIdx, int &j);

	//! insert the interval  [beginIdx,endIdx] of level i-1 to level i at position pos.
	void post_processing_CopyInterval(Hierarchy &H, int i, int beginIdx, int endIdx, int pos);

	int m_numLevels;
	int m_maxLevelSize;

	//------------------------ UPRLayoutSimple methods --------------------------------------------
	void callSimple(GraphAttributes &AG, adjEntry adj //left most edge of the source
					);

	// needed for UPRLayoutSimple
	void dfsSortLevels(
		adjEntry adj1,
		const NodeArray<int> &rank,
		Array<SListPure<node> > &nodes);

	// needed for UPRLayoutSimple
	void longestPathRanking(const Graph &G, NodeArray<int> &rank);

};

}

#endif


text:
<?php
namespace Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\Type as CoreType;
use Symfony\Component\HttpFoundation\Request;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Form\Issue7;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Form\Issue8;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Form\Issue16;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Form\Type as FormType;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Form\TypeHelper;
use Tests\Boekkooi\Bundle\JqueryValidationBundle\Functional\TestBundle\Issue20;

/**
 * @author Warnar Boekkooi <warnar@boekkooi.net>
 */
class FormController extends Controller
{
    public function simpleAction(Request $request)
    {
        $form = $this->createForm(FormType\SimpleFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function simpleDataAction(Request $request)
    {
        $form = $this->createForm(FormType\SimpleDataFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function dateTimeAction(Request $request)
    {
        $form = $this->createForm(FormType\DateTimeFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function includeSimpleDataAction(Request $request)
    {
        $form = $this->createForm(FormType\IncludeSimpleFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function buttonsAction(Request $request)
    {
        $form = $this->createForm(FormType\ButtonsFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView(), 'button' => true));
    }

    public function collectionAction(Request $request)
    {
        $form = $this->createForm(FormType\CollectionFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function collectionWithGroupAction(Request $request)
    {
        $form = $this->createForm(FormType\CollectionWithGroupsFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView(), 'button' => true));
    }

    public function collectionCompoundAction(Request $request)
    {
        $form = $this->createForm(FormType\CollectionCompoundFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function childDataAction(Request $request)
    {
        $form = $this->createForm(FormType\RootDataFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function viewTransformAction(Request $request)
    {
        $form = $this->createForm(FormType\ViewTransformRulesFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView(), 'button' => true));
    }

    public function collectionDateTimeAction(Request $request)
    {
        $form = $this->createForm(FormType\CollectionDateTimeFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView(), 'button' => true));
    }

    public function additionalRulesAction(Request $request)
    {
        $form = $this->createForm(FormType\AdditionalRulesFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function manualGroupsAction(Request $request)
    {
        $form = $this->createForm(FormType\ManualGroupsFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form_manual_groups.html.twig', array('form' => $form->createView()));
    }

    public function isTrueOrFalseAction(Request $request)
    {
        $form = $this->createForm(FormType\IsTrueOrFalseFormType::class);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function issue7Action(Request $request)
    {
        $resource = new Issue7\Model\Recourse();
        $resource->setContents(array(
            new Issue7\Model\Content(),
            new Issue7\Model\Content()
        ));
        $resource->setInvalidContents(array(
            new Issue7\Model\Content()
        ));

        $form = $this->createForm(Issue7\Type\RecourseType::class);
        $form->setData($resource);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function issue8Action(Request $request)
    {
        $resource = new Issue8\Model\TestRangeEntity();

        $form = $this->createForm(Issue8\Type\TestRangeType::class);
        $form->setData($resource);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function issue16Action(Request $request)
    {
        $collection = new Issue16\Model\EntityRefCollection();
        $collection->entityReferences[] = new Issue16\Model\EntityReferenceModel();

        $form = $this->createForm(Issue16\Type\EntityRefCollectionType::class, $collection);
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function issue17EmptyNameAction(Request $request)
    {
        /** @var FormInterface $form */
        $form = $this->get('form.factory')->createNamed('', TypeHelper::type(FormType\SimpleFormType::class));
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    public function issue18Action(Request $request)
    {
        /** @var FormInterface $form */
        $form = $this->get('form.factory')->createNamedBuilder('')
            ->add('submit', TypeHelper::type(CoreType\SubmitType::class))
            ->getForm();
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView(), 'button' => true));
    }

    public function issue20Action(Request $request)
    {
        $form = $this->createForm(
            Issue20\Form\Type\ScheduleFormType::class,
            new Issue20\Model\Schedule()
        );
        $this->handleForm($request, $form);

        return $this->render('::form.html.twig', array('form' => $form->createView()));
    }

    private function handleForm(Request $request, FormInterface $form)
    {
        $form->handleRequest($request);
        if ($form->isValid()) {
            $this->addNotice(date('H:i:s').': Valid');
        } elseif ($request->isMethod('POST')) {
            $this->addNotice(date('H:i:s').': Invalid');
        }
    }

    public function createForm($type, $data = null, array $options = array())
    {
        return parent::createForm(TypeHelper::type($type), $data, $options);
    }

    private function addNotice($message)
    {
        $this->get('session')->getFlashBag()->add(
            'notice',
            $message
        );
    }
}


text:
namespace gin {

namespace {

#ifdef MINIBLINK_NOT_IMPLEMENTED
base::LazyInstance<V8Platform>::Leaky g_v8_platform = LAZY_INSTANCE_INITIALIZER;
#else
static V8Platform* g_v8_platform = nullptr;
#endif // MINIBLINK_NOT_IMPLEMENTED

}  // namespace

// static
#ifdef MINIBLINK_NOT_IMPLEMENTED

V8Platform* V8Platform::Get() { return g_v8_platform.Pointer(); }

#else

V8Platform* V8Platform::Get() {
  if (!g_v8_platform)
    g_v8_platform = new V8Platform();
  return g_v8_platform;
}

class V8TaskToWebThreadTask : public blink::WebThread::Task {
public:
    V8TaskToWebThreadTask(v8::Task* task)
        : m_task(task) { }

    virtual ~V8TaskToWebThreadTask() OVERRIDE { delete m_task; }
    virtual void run() OVERRIDE { m_task->Run(); }

private:
    v8::Task* m_task;
};

#endif // MINIBLINK_NOT_IMPLEMENTED

V8Platform::V8Platform() {}

V8Platform::~V8Platform() {}

DWORD CALLBACK WorkItemCallback(void* param)
{
    v8::Task* task = (v8::Task*)param;
    task->Run();
    delete task;
    return 0;
}

void V8Platform::CallOnBackgroundThread(
    v8::Task* task,
    v8::Platform::ExpectedRuntime expected_runtime) {
#ifdef MINIBLINK_NOT_IMPLEMENTED
  base::WorkerPool::PostTask(
      FROM_HERE,
      base::Bind(&v8::Task::Run, base::Owned(task)),
      expected_runtime == v8::Platform::kLongRunningTask);
#endif // MINIBLINK_NOT_IMPLEMENTED
  ULONG flags = 0;
  if (expected_runtime == v8::Platform::kLongRunningTask)
      flags |= WT_EXECUTELONGFUNCTION;

  if (!QueueUserWorkItem(WorkItemCallback, task, flags)) {
      delete task;
      return;
  }
}

void V8Platform::CallOnForegroundThread(v8::Isolate* isolate, v8::Task* task) {
#ifdef MINIBLINK_NOT_IMPLEMENTED
  PerIsolateData::From(isolate)->task_runner()->PostTask(
      FROM_HERE, base::Bind(&v8::Task::Run, base::Owned(task)));
#else
    return blink::Platform::current()->currentThread()->postTask(FROM_HERE, new V8TaskToWebThreadTask(task));
#endif // MINIBLINK_NOT_IMPLEMENTED
}

void V8Platform::CallDelayedOnForegroundThread(v8::Isolate* isolate,
                                               v8::Task* task,
                                               double delay_in_seconds) {
#ifdef MINIBLINK_NOT_IMPLEMENTED
  PerIsolateData::From(isolate)->task_runner()->PostDelayedTask(
      FROM_HERE, base::Bind(&v8::Task::Run, base::Owned(task)),
      base::TimeDelta::FromSecondsD(delay_in_seconds));
#else
    return blink::Platform::current()->currentThread()->postDelayedTask(FROM_HERE, new V8TaskToWebThreadTask(task), (long long)(delay_in_seconds * 1000));
#endif // MINIBLINK_NOT_IMPLEMENTED
}

double V8Platform::MonotonicallyIncreasingTime() {
#ifdef MINIBLINK_NOT_IMPLEMENTED
  return base::TimeTicks::Now().ToInternalValue() /
      static_cast<double>(base::Time::kMicrosecondsPerSecond);
#else
    return blink::Platform::current()->monotonicallyIncreasingTime();
#endif // MINIBLINK_NOT_IMPLEMENTED
}

}  // namespace gin


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

//    NSDate *date = [NSDate date];
//
//    NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:60 * 60];
//
//    NSDate *date2 = [NSDate dateWithTimeInterval:1 sinceDate:date];
//
//    //2001-1-1 00:00:00 GMT 格林尼治标准时间
//    NSDate *date3 = [NSDate dateWithTimeIntervalSinceReferenceDate:1];
//    //1970-1-1 00:00:00 GMT 格林尼治标准时间
//    NSDate *date4 = [NSDate dateWithTimeIntervalSince1970:1];
//
//    NSDate *date5 = [NSDate distantFuture];
//
//    NSDate *date6 = [NSDate distantPast];
//
//
//    NSTimeInterval timeIntervalnow = [date timeIntervalSinceNow];
//    NSTimeInterval timeInterval1970 = [date timeIntervalSince1970];
//
//
//    NSDate *dateAddTimeInterval = [date dateByAddingTimeInterval:-60*5];
//    //比较谁更早,返回更早的 date
//    NSDate *earlierDate = [date earlierDate:date1];
//
//    //比较是否相同 NSOrderedSame
//    NSComparisonResult datecompare = [date compare:date];

    __unused NSString *systemTime = [VKDateManager vk_systemTimeType:DateFormatTypeHMS];

    __unused NSString *systemTimeInterval = [VKDateManager vk_systemTimeInterval];

    __unused NSString *time1 = [VKDateManager vk_convertTimeIntervalToTime:@"60" formatType:DateFormatTypeYMDHM];

    __unused NSString *custom_timeInterval = [VKDateManager vk_convertTimeToTimeInterval:@"1970-01-01 09:00:00" formatType:DateFormatTypeYMDHMS timeZone:TimeZoneTypeSystem];

    __unused NSString *intervalSince = [VKDateManager vk_intervalSinceNow:@"1434676813"];

}

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

@end


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_tab_downloaded_selected"
        android:state_selected="true"
        android:state_pressed="false" />
    <item android:drawable="@drawable/ic_tab_downloaded_unselected" />
</selector>


text:
class c302SimNetworkHomomorph : public NetworkHomomorph
{
public:

   // Constructors.
   c302SimNetworkHomomorph(Network *homomorph,
                           MutableParm& synapseWeightsParm,
                           vector<vector<pair<int, int> > > *motorConnections,
                           Random *randomizer, int tag = (-1));
   c302SimNetworkHomomorph(FilePointer *fp,
                           vector<vector<pair<int, int> > > *motorConnections,
                           Random *randomizer);

   // Destructor.
   ~c302SimNetworkHomomorph();

   // Mean absolute error (MAE).
   float meanError;

   // Optimize synapses.
   void optimize(int synapseOptimizedPathLength,
                 c302Sim *modelSim, c302Sim *evalSim);

   // c302 simulation fitness evaluation.
   void evaluate(c302Sim *modelSim, c302Sim *evalSim);

   // Clone.
   c302SimNetworkHomomorph *clone(int tag = (-1));

   // Load.
   void load(FilePointer *fp);

   // Save.
   void save(FilePointer *fp);

   // Print.
   void print(bool printNetwork = false);
};
#endif


text:
import datetime

from django.db import transaction

from registrasion.models import commerce

from .for_id import ForId

class CreditNoteController(ForId, object):

    __MODEL__ = commerce.CreditNote

    def __init__(self, credit_note):
        self.credit_note = credit_note

    @classmethod
    def generate_from_invoice(cls, invoice, value):
        ''' Generates a credit note of the specified value and pays it against
        the given invoice. You need to call InvoiceController.update_status()
        to set the status correctly, if appropriate. '''

        credit_note = commerce.CreditNote.objects.create(
            invoice=invoice,
            amount=0-value,  # Credit notes start off as a payment against inv.
            reference="ONE MOMENT",
        )
        credit_note.reference = "Generated credit note %d" % credit_note.id
        credit_note.save()

        return cls(credit_note)

    @transaction.atomic
    def apply_to_invoice(self, invoice):
        ''' Applies the total value of this credit note to the specified
        invoice. If this credit note overpays the invoice, a new credit note
        containing the residual value will be created.

        Raises ValidationError if the given invoice is not allowed to be
        paid.
        '''

        # Local import to fix import cycles. Can we do better?
        from .invoice import InvoiceController
        inv = InvoiceController(invoice)
        inv.validate_allowed_to_pay()

        # Apply payment to invoice
        commerce.CreditNoteApplication.objects.create(
            parent=self.credit_note,
            invoice=invoice,
            amount=self.credit_note.value,
            reference="Applied credit note #%d" % self.credit_note.id,
        )

        inv.update_status()

    # TODO: Add administration fee generator.
    @transaction.atomic
    def cancellation_fee(self, percentage):
        ''' Generates an invoice with a cancellation fee, and applies
        credit to the invoice.

        percentage (Decimal): The percentage of the credit note to turn into
        a cancellation fee. Must be 0 <= percentage <= 100.
        '''

        # Local import to fix import cycles. Can we do better?
        from .invoice import InvoiceController

        assert(percentage >= 0 and percentage <= 100)

        cancellation_fee = self.credit_note.value * percentage / 100
        due = datetime.timedelta(days=1)
        item = [("Cancellation fee", cancellation_fee)]
        invoice = InvoiceController.manual_invoice(
            self.credit_note.invoice.user, due, item
        )

        if not invoice.is_paid:
            self.apply_to_invoice(invoice)

        return InvoiceController(invoice)


text:
package com.boundary.plugin.sdk.jmx;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

public class VMAttach {

	public static void main(String args[]) throws Exception {
//		if (args.length != 1) {
//			System.err.println("Please provide process id");
//			System.exit(-1);
//		}
		List <VirtualMachineDescriptor> vmDescriptors = VirtualMachine.list();
		VirtualMachineDescriptor vmd = null;
		for (VirtualMachineDescriptor v: vmDescriptors) {
			System.out.println(v.displayName());
		}

		VirtualMachine vm = VirtualMachine.attach(vmd);
		String connectorAddr = vm.getAgentProperties().getProperty(
				"com.sun.management.jmxremote.localConnectorAddress");
		if (connectorAddr == null) {
			String agent = vm.getSystemProperties().getProperty("java.home")
					+ File.separator + "lib" + File.separator
					+ "management-agent.jar";
			vm.loadAgent(agent);
			connectorAddr = vm.getAgentProperties().getProperty(
					"com.sun.management.jmxremote.localConnectorAddress");
		}
		JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
		JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
		MBeanServerConnection mbsc = connector.getMBeanServerConnection();

		ObjectName objName = new ObjectName(
				ManagementFactory.THREAD_MXBEAN_NAME);
		Set<ObjectName> mbeans = mbsc.queryNames(objName, null);
		for (ObjectName name : mbeans) {
			ThreadMXBean threadBean;
			threadBean = ManagementFactory.newPlatformMXBeanProxy(mbsc,
					name.toString(), ThreadMXBean.class);
			long threadIds[] = threadBean.getAllThreadIds();
			for (long threadId : threadIds) {
				ThreadInfo threadInfo = threadBean.getThreadInfo(threadId);
				System.out.println(threadInfo.getThreadName() + " / "
						+ threadInfo.getThreadState());
			}
		}
	}
}


text:
import Ember from 'ember-metal/core';
import calculateLocationDisplay from 'ember-template-compiler/system/calculate-location-display';

/**
 @module ember
 @submodule ember-template-compiler
*/

/**
  An HTMLBars AST transformation that deprecates usage of `controller` with the `{{with}}`
  helper.

  @private
  @class DeprecateWithController
*/
function DeprecateWithController(options) {
  // set later within HTMLBars to the syntax package
  this.syntax = null;
  this.options = options || {};
}

/**
  @private
  @method transform
  @param {AST} ast The AST to be transformed.
*/
DeprecateWithController.prototype.transform = function DeprecateWithController_transform(ast) {
  const pluginContext = this;
  const walker = new pluginContext.syntax.Walker();
  const moduleName = pluginContext.options.moduleName;

  walker.visit(ast, function(node) {
    if (pluginContext.validate(node)) {
      let moduleInfo = calculateLocationDisplay(moduleName, node.loc);

      Ember.deprecate(
        `Using the {{with}} helper with a \`controller\` specified ${moduleInfo}is deprecated and will be removed in 2.0.0.`,
        false,
        { id: 'ember-template-compiler.with-controller', until: '2.0.0' }
      );
    }
  });

  return ast;
};

DeprecateWithController.prototype.validate = function TransformWithAsToHash_validate(node) {
  return (node.type === 'BlockStatement' || node.type === 'MustacheStatement') &&
    node.path.original === 'with' &&
    hashPairForKey(node.hash, 'controller');
};

function hashPairForKey(hash, key) {
  for (let i = 0, l = hash.pairs.length; i < l; i++) {
    let pair = hash.pairs[i];
    if (pair.key === key) {
      return pair;
    }
  }

  return false;
}

export default DeprecateWithController;


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "docio.h"
#include "wal.h"
#include "fdb_internal.h"
#ifdef _DOC_COMP
#include "snappy-c.h"
#endif

#include "memleak.h"

void docio_init(struct docio_handle *handle,
                struct filemgr *file,
                bool compress_document_body)
{
    handle->file = file;
    handle->curblock = BLK_NOT_FOUND;
    handle->curpos = 0;
    handle->lastbid = BLK_NOT_FOUND;
    handle->compress_document_body = compress_document_body;
    malloc_align(handle->readbuffer, FDB_SECTOR_SIZE, file->blocksize);
}

void docio_free(struct docio_handle *handle)
{
    free_align(handle->readbuffer);
}

#ifdef __CRC32
#define _add_blk_marker(file, bid, blocksize, marker, log_callback) \
    filemgr_write_offset((file), (bid), (blocksize), BLK_MARKER_SIZE, (marker), (log_callback))
#else
#define _add_blk_marker(file, bid, blocksize, marker, log_callback) \
    FDB_RESULT_SUCCESS
#endif

INLINE fdb_status _docio_fill_zero(struct docio_handle *handle, bid_t bid,
                                   size_t pos)
{
    // Fill next few bytes (sizeof(struct docio_length)) with zero
    // to avoid false positive docio_length checksum during file scanning.
    // (Note that the checksum value of zero-filled docio_length is 0x6F.)

    size_t blocksize = handle->file->blocksize;
    size_t len_size = sizeof(struct docio_length);
    uint8_t *zerobuf = alca(uint8_t, len_size);

#ifdef __CRC32
    blocksize -= BLK_MARKER_SIZE;
#endif

    if (pos + len_size <= blocksize) {
        // enough space in the block
        memset(zerobuf, 0x0, len_size);
        return filemgr_write_offset(handle->file, bid, pos, len_size,
                                    zerobuf, handle->log_callback);
    } else {
        // lack of space .. we don't need to fill zero bytes.
        return FDB_RESULT_SUCCESS;
    }
}

bid_t docio_append_doc_raw(struct docio_handle *handle, uint64_t size, void *buf)
{
    uint32_t offset;
    uint8_t marker[BLK_MARKER_SIZE];
    size_t blocksize = handle->file->blocksize;
    size_t real_blocksize = blocksize;
    err_log_callback *log_callback = handle->log_callback;
#ifdef __CRC32
    blocksize -= BLK_MARKER_SIZE;
    memset(marker, BLK_MARKER_DOC, BLK_MARKER_SIZE);
#endif

    if (handle->curblock == BLK_NOT_FOUND) {
        // allocate new block
        handle->curblock = filemgr_alloc(handle->file, log_callback);
        handle->curpos = 0;
    }
    if (!filemgr_is_writable(handle->file, handle->curblock)) {
        // allocate new block
        handle->curblock = filemgr_alloc(handle->file, log_callback);
        handle->curpos = 0;
    }

    if (size <= blocksize - handle->curpos) {
        // simply append to current block
        offset = handle->curpos;
        if (_add_blk_marker(handle->file, handle->curblock, blocksize, marker,
                            log_callback) != FDB_RESULT_SUCCESS) {
            return BLK_NOT_FOUND;
        }
        if (filemgr_write_offset(handle->file, handle->curblock, offset, size,
                                 buf, log_callback) != FDB_RESULT_SUCCESS) {
            return BLK_NOT_FOUND;
        }
        handle->curpos += size;

        if (_docio_fill_zero(handle, handle->curblock, handle->curpos) !=
            FDB_RESULT_SUCCESS) {
            return BLK_NOT_FOUND;
        }

        return handle->curblock * real_blocksize + offset;

    }else{
        // not simply fitted into current block
        bid_t begin, end, i, startpos;
        uint32_t nblock = size / blocksize;
        uint32_t remain = size % blocksize;
        uint64_t remainsize = size;

    #ifdef DOCIO_BLOCK_ALIGN
        offset = blocksize - handle->curpos;
        if (remain <= blocksize - handle->curpos &&
            filemgr_alloc_multiple_cond(handle->file, handle->curblock+1,
                                        nblock + ((remain>offset)?1:0), &begin, &end,
                                        log_callback) == handle->curblock+1) {

            // start from current block
            fdb_assert(begin == handle->curblock + 1, begin, handle->curblock+1);

            if (_add_blk_marker(handle->file, handle->curblock, blocksize,
                                marker, log_callback) != FDB_RESULT_SUCCESS) {
                return BLK_NOT_FOUND;
            }
            if (offset > 0) {
                if (filemgr_write_offset(handle->file, handle->curblock,
                                         handle->curpos, offset, buf,
                                         log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
            }
            remainsize -= offset;

            startpos = handle->curblock * real_blocksize + handle->curpos;
        } else {
            // next block to be allocated is not continuous .. allocate new multiple blocks
            filemgr_alloc_multiple(handle->file, nblock+((remain>0)?1:0),
                                   &begin, &end, log_callback);
            offset = 0;

            startpos = begin * real_blocksize;
        }

    #else
        // simple append mode .. always append at the end of file
        offset = blocksize - handle->curpos;
        if (filemgr_alloc_multiple_cond(handle->file, handle->curblock+1,
                                        nblock + ((remain>offset)?1:0), &begin, &end,
                                        log_callback) == handle->curblock+1) {
            // start from current block
            fdb_assert(begin == handle->curblock + 1, begin, handle->curblock+1);

            if (_add_blk_marker(handle->file, handle->curblock, blocksize,
                                marker, log_callback) != FDB_RESULT_SUCCESS) {
                return BLK_NOT_FOUND;
            }
            if (offset > 0) {
                if (filemgr_write_offset(handle->file, handle->curblock,
                                         handle->curpos, offset, buf,
                                         log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
            }
            remainsize -= offset;

            startpos = handle->curblock * real_blocksize + handle->curpos;
        } else {
            // next block to be allocated is not continuous .. allocate new multiple blocks
            filemgr_alloc_multiple(handle->file, nblock+((remain>0)?1:0),
                                   &begin, &end, log_callback);
            offset = 0;

            startpos = begin * real_blocksize;
        }

    #endif

        for (i=begin; i<=end; ++i) {
            handle->curblock = i;
            if (remainsize >= blocksize) {
                // write entire block
                if (_add_blk_marker(handle->file, i, blocksize, marker,
                                    log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
                if (filemgr_write_offset(handle->file, i, 0, blocksize,
                                     (uint8_t *)buf + offset,
                                     log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
                offset += blocksize;
                remainsize -= blocksize;
                handle->curpos = blocksize;

            } else {
                // write rest of document
                fdb_assert(i==end, i, end);
                if (_add_blk_marker(handle->file, i, blocksize, marker,
                                    log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
                if (filemgr_write_offset(handle->file, i, 0, remainsize,
                                     (uint8_t *)buf + offset,
                                     log_callback) != FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
                offset += remainsize;
                handle->curpos = remainsize;

                if (_docio_fill_zero(handle, i, handle->curpos) !=
                    FDB_RESULT_SUCCESS) {
                    return BLK_NOT_FOUND;
                }
            }
        }

        return startpos;
    }

    return 0;
}

#ifdef __ENDIAN_SAFE
INLINE struct docio_length _docio_length_encode(struct docio_length length)
{
    struct docio_length ret;
    ret = length;
    ret.keylen = _endian_encode(length.keylen);
    ret.metalen = _endian_encode(length.metalen);
    ret.bodylen = _endian_encode(length.bodylen);
    ret.bodylen_ondisk = _endian_encode(length.bodylen_ondisk);
    return ret;
}
INLINE struct docio_length _docio_length_decode(struct docio_length length)
{
    struct docio_length ret;
    ret = length;
    ret.keylen = _endian_decode(length.keylen);
    ret.metalen = _endian_decode(length.metalen);
    ret.bodylen = _endian_decode(length.bodylen);
    ret.bodylen_ondisk = _endian_decode(length.bodylen_ondisk);
    return ret;
}
#else
#define _docio_length_encode(a)
#define _docio_length_decode(a)
#endif

INLINE uint8_t _docio_length_checksum(struct docio_length length)
{
    return (uint8_t)(
        chksum(&length,
               sizeof(keylen_t) + sizeof(uint16_t) + sizeof(uint32_t)*2)
        & 0xff);
}

INLINE bid_t _docio_append_doc(struct docio_handle *handle, struct docio_object *doc)
{
    size_t _len;
    uint32_t offset = 0;
    uint32_t crc;
    uint64_t docsize;
    void *buf;
    bid_t ret_offset;
    fdb_seqnum_t _seqnum;
    timestamp_t _timestamp;
    struct docio_length length, _length;
    err_log_callback *log_callback = handle->log_callback;

    length = doc->length;
    length.bodylen_ondisk = length.bodylen;

#ifdef _DOC_COMP
    int ret;
    void *compbuf = NULL;
    uint32_t compbuf_len;
    if (doc->length.bodylen > 0 && handle->compress_document_body) {
        compbuf_len = snappy_max_compressed_length(length.bodylen);
        compbuf = (void *)malloc(compbuf_len);

        _len = compbuf_len;
        ret = snappy_compress((char*)doc->body, length.bodylen, (char*)compbuf, &_len);
        if (ret < 0) { // LCOV_EXCL_START
            fdb_log(log_callback, FDB_RESULT_COMPRESSION_FAIL,
                    "Error in compressing the doc body of key '%s'",
                    (char *) doc->key);
            free(compbuf);
            // we use BLK_NOT_FOUND for error code of appending instead of 0
            // because document can be written at the byte offset 0
            return BLK_NOT_FOUND;
        } // LCOV_EXCL_STOP

        length.bodylen_ondisk = compbuf_len = _len;
        length.flag |= DOCIO_COMPRESSED;

        docsize = sizeof(struct docio_length) + length.keylen + length.metalen;
        docsize += compbuf_len;
    } else {
        docsize = sizeof(struct docio_length) + length.keylen + length.metalen + length.bodylen;
        compbuf_len = length.bodylen;
    }
#else
    docsize = sizeof(struct docio_length) + length.keylen + length.metalen + length.bodylen;
#endif
    docsize += sizeof(timestamp_t);

    docsize += sizeof(fdb_seqnum_t);

#ifdef __CRC32
    docsize += sizeof(crc);
#endif

    doc->length = length;
    buf = (void *)malloc(docsize);

    _length = _docio_length_encode(length);

    // calculate checksum of LENGTH using crc
    _length.checksum = _docio_length_checksum(_length);

    memcpy((uint8_t *)buf + offset, &_length, sizeof(struct docio_length));
    offset += sizeof(struct docio_length);

    // copy key
    memcpy((uint8_t *)buf + offset, doc->key, length.keylen);
    offset += length.keylen;

    // copy timestamp
    _timestamp = _endian_encode(doc->timestamp);
    memcpy((uint8_t*)buf + offset, &_timestamp, sizeof(_timestamp));
    offset += sizeof(_timestamp);

    // copy seqeunce number (optional)
    _seqnum = _endian_encode(doc->seqnum);
    memcpy((uint8_t *)buf + offset, &_seqnum, sizeof(fdb_seqnum_t));
    offset += sizeof(fdb_seqnum_t);

    // copy metadata (optional)
    if (length.metalen > 0) {
        memcpy((uint8_t *)buf + offset, doc->meta, length.metalen);
        offset += length.metalen;
    }

    // copy body (optional)
    if (length.bodylen > 0) {
#ifdef _DOC_COMP
        if (length.flag & DOCIO_COMPRESSED) {
            // compressed body
            memcpy((uint8_t*)buf + offset, compbuf, compbuf_len);
            offset += compbuf_len;
            free(compbuf);
        } else {
            memcpy((uint8_t *)buf + offset, doc->body, length.bodylen);
            offset += length.bodylen;
        }
#else
        memcpy((uint8_t *)buf + offset, doc->body, length.bodylen);
        offset += length.bodylen;
#endif
    }

#ifdef __CRC32
    crc = chksum(buf, docsize - sizeof(crc));
    memcpy((uint8_t *)buf + offset, &crc, sizeof(crc));
#endif

    ret_offset = docio_append_doc_raw(handle, docsize, buf);
    free(buf);

    return ret_offset;
}

bid_t docio_append_commit_mark(struct docio_handle *handle, uint64_t doc_offset)
{
    uint32_t offset = 0;
    uint64_t docsize;
    uint64_t _doc_offset;
    void *buf;
    bid_t ret_offset;
    struct docio_length length, _length;

    memset(&length, 0, sizeof(struct docio_length));
    length.flag = DOCIO_TXN_COMMITTED;

    docsize = sizeof(struct docio_length) + sizeof(doc_offset);
    buf = (void *)malloc(docsize);

    _length = _docio_length_encode(length);

    // calculate checksum of LENGTH using crc
    _length.checksum = _docio_length_checksum(_length);

    memcpy((uint8_t *)buf + offset, &_length, sizeof(struct docio_length));
    offset += sizeof(struct docio_length);

    // copy doc_offset
    _doc_offset = _endian_encode(doc_offset);
    memcpy((uint8_t *)buf + offset, &_doc_offset, sizeof(_doc_offset));

    ret_offset = docio_append_doc_raw(handle, docsize, buf);
    free(buf);

    return ret_offset;
}

bid_t docio_append_doc_compact(struct docio_handle *handle, struct docio_object *doc,
                               uint8_t deleted, uint8_t txn_enabled)
{
    doc->length.flag = DOCIO_COMPACT;
    if (deleted) {
        doc->length.flag |= DOCIO_DELETED;
    }
    if (txn_enabled) {
        doc->length.flag |= DOCIO_TXN_DIRTY;
    }
    return _docio_append_doc(handle, doc);
}

bid_t docio_append_doc(struct docio_handle *handle, struct docio_object *doc,
                       uint8_t deleted, uint8_t txn_enabled)
{
    doc->length.flag = DOCIO_NORMAL;
    if (deleted) {
        doc->length.flag |= DOCIO_DELETED;
    }
    if (txn_enabled) {
        doc->length.flag |= DOCIO_TXN_DIRTY;
    }
    return _docio_append_doc(handle, doc);
}

bid_t docio_append_doc_system(struct docio_handle *handle, struct docio_object *doc)
{
    doc->length.flag = DOCIO_NORMAL | DOCIO_SYSTEM;
    return _docio_append_doc(handle, doc);
}

INLINE fdb_status _docio_read_through_buffer(struct docio_handle *handle,
                                             bid_t bid,
                                             err_log_callback *log_callback)
{
    fdb_status status = FDB_RESULT_SUCCESS;
    // to reduce the overhead from memcpy the same block
    if (handle->lastbid != bid) {
        status = filemgr_read(handle->file, bid, handle->readbuffer,
                              log_callback);
        if (status != FDB_RESULT_SUCCESS) {
            return status;
        }

        if (filemgr_is_writable(handle->file, bid)) {
            // this block can be modified later .. must be re-read
            handle->lastbid = BLK_NOT_FOUND;
        }else{
            handle->lastbid = bid;
        }
    }

    return status;
}

INLINE int _docio_check_buffer(struct docio_handle *handle)
{
    uint8_t marker[BLK_MARKER_SIZE];
    marker[0] = *(((uint8_t *)handle->readbuffer)
                 + handle->file->blocksize - BLK_MARKER_SIZE);
    return (marker[0] == BLK_MARKER_DOC);
}

static uint64_t _docio_read_length(struct docio_handle *handle,
                                   uint64_t offset,
                                   struct docio_length *length,
                                   err_log_callback *log_callback)
{
    size_t blocksize = handle->file->blocksize;
    size_t real_blocksize = blocksize;
#ifdef __CRC32
    blocksize -= BLK_MARKER_SIZE;
#endif

    if (filemgr_get_pos(handle->file) < (offset + sizeof(struct docio_length))) {
        return offset;
    }

    bid_t bid = offset / real_blocksize;
    uint32_t pos = offset % real_blocksize;
    void *buf = handle->readbuffer;
    uint32_t restsize;

    restsize = blocksize - pos;
    // read length structure
    _docio_read_through_buffer(handle, bid, log_callback);
    if (!_docio_check_buffer(handle)) {
        return offset;
    }

    if (restsize >= sizeof(struct docio_length)) {
        memcpy(length, (uint8_t *)buf + pos, sizeof(struct docio_length));
        pos += sizeof(struct docio_length);

    } else {
        memcpy(length, (uint8_t *)buf + pos, restsize);
        // read additional block
        bid++;
        _docio_read_through_buffer(handle, bid, log_callback);
        if (!_docio_check_buffer(handle)) {
            return offset;
        }
        // memcpy rest of data
        memcpy((uint8_t *)length + restsize, buf, sizeof(struct docio_length) - restsize);
        pos = sizeof(struct docio_length) - restsize;
    }

    return bid * real_blocksize + pos;
}

static uint64_t _docio_read_doc_component(struct docio_handle *handle,
                                          uint64_t offset,
                                          uint32_t len,
                                          void *buf_out,
                                          err_log_callback *log_callback)
{
    uint32_t rest_len;
    size_t blocksize = handle->file->blocksize;
    size_t real_blocksize = blocksize;
#ifdef __CRC32
    blocksize -= BLK_MARKER_SIZE;
#endif

    bid_t bid = offset / real_blocksize;
    uint32_t pos = offset % real_blocksize;
    //uint8_t buf[handle->file->blocksize];
    void *buf = handle->readbuffer;
    uint32_t restsize;

    rest_len = len;

    while(rest_len > 0) {
        _docio_read_through_buffer(handle, bid, log_callback);
        restsize = blocksize - pos;

        if (restsize >= rest_len) {
            memcpy((uint8_t *)buf_out + (len - rest_len), (uint8_t *)buf + pos, rest_len);
            pos += rest_len;
            rest_len = 0;
        }else{
            memcpy((uint8_t *)buf_out + (len - rest_len), (uint8_t *)buf + pos, restsize);
            bid++;
            pos = 0;
            rest_len -= restsize;

            if (rest_len > 0 &&
                bid >= filemgr_get_pos(handle->file) / handle->file->blocksize) {
                // no more data in the file .. the file is corrupted
                fdb_log(log_callback, FDB_RESULT_FILE_CORRUPTION,
                        "Fatal error!!! Database file '%s' is corrupted.",
                        handle->file->filename);
                // TODO: Need to return a better error code.
                return 0;
            }
        }
    }

    return bid * real_blocksize + pos;
}

#ifdef _DOC_COMP

static uint64_t _docio_read_doc_component_comp(struct docio_handle *handle,
                                               uint64_t offset,
                                               uint32_t len,
                                               uint32_t comp_len,
                                               void *buf_out,
                                               void *comp_data_out,
                                               err_log_callback *log_callback)
{
    int ret;
    size_t uncomp_size;
    uint64_t _offset;

    _offset = _docio_read_doc_component(handle, offset,
                                        comp_len, comp_data_out, log_callback);
    if (_offset == 0) {
        return 0;
    }

    uncomp_size = len;
    ret = snappy_uncompress((char*)comp_data_out, comp_len,
                            (char*)buf_out, &uncomp_size);
    if (ret < 0) return 0;

    fdb_assert(uncomp_size == len, uncomp_size, len);
    return _offset;
}

#endif

// return length.keylen = 0 if failure
struct docio_length docio_read_doc_length(struct docio_handle *handle, uint64_t offset)
{
    uint8_t checksum;
    uint64_t _offset;
    struct docio_length length, _length;
    err_log_callback *log_callback = handle->log_callback;

    _offset = _docio_read_length(handle, offset, &_length, log_callback);
    if (_offset == offset) {
        length.keylen = 0;
        return length;
    }

    // checksum check
    checksum = _docio_length_checksum(_length);
    if (checksum != _length.checksum) {
        fdb_log(log_callback, FDB_RESULT_CHECKSUM_ERROR,
                "doc_length checksum mismatch error in a database file '%s'",
                handle->file->filename);
        length.keylen = 0;
        return length;
    }

    length = _docio_length_decode(_length);
    if (length.keylen == 0 || length.keylen > FDB_MAX_KEYLEN_INTERNAL) {
        length.keylen = 0;
        return length;
    }

    // document size check
    if (offset + sizeof(struct docio_length) +
        length.keylen + length.metalen + length.bodylen_ondisk >
        filemgr_get_pos(handle->file)) {
        fdb_log(log_callback, FDB_RESULT_FILE_CORRUPTION,
                "Fatal error!!! Database file '%s' is corrupted.",
                handle->file->filename);
        length.keylen = 0;
        return length;
    }

    return length;
}

// return length.keylen = 0 if failure
void docio_read_doc_key(struct docio_handle *handle, uint64_t offset,
                        keylen_t *keylen, void *keybuf)
{
    uint8_t checksum;
    uint64_t _offset;
    struct docio_length length, _length;
    err_log_callback *log_callback = handle->log_callback;

    _offset = _docio_read_length(handle, offset, &_length, log_callback);
    if (_offset == offset) {
        *keylen = 0;
        return;
    }

    // checksum check
    checksum = _docio_length_checksum(_length);
    if (checksum != _length.checksum) {
        fdb_log(log_callback, FDB_RESULT_CHECKSUM_ERROR,
                "doc_length checksum mismatch error in a database file '%s'",
                handle->file->filename);
        *keylen = 0;
        return;
    }

    length = _docio_length_decode(_length);
    if (length.keylen == 0 || length.keylen > FDB_MAX_KEYLEN_INTERNAL) {
        *keylen = 0;
        return;
    }

    // document size check
    if (offset + sizeof(struct docio_length) +
        length.keylen + length.metalen + length.bodylen_ondisk >
        filemgr_get_pos(handle->file)) {
        fdb_log(log_callback, FDB_RESULT_FILE_CORRUPTION,
                "Fatal error!!! Database file '%s' is corrupted.",
                handle->file->filename);
        *keylen = 0;
        return;
    }

    _docio_read_doc_component(handle, _offset, length.keylen, keybuf, log_callback);
    *keylen = length.keylen;
}

void free_docio_object(struct docio_object *doc, uint8_t key_alloc,
                       uint8_t meta_alloc, uint8_t body_alloc) {
    if (!doc) {
        return;
    }

    if (key_alloc) {
        free(doc->key);
        doc->key = NULL;
    }
    if (meta_alloc) {
        free(doc->meta);
        doc->meta = NULL;
    }
    if (body_alloc) {
        free(doc->body);
        doc->body = NULL;
    }
}

uint64_t docio_read_doc_key_meta(struct docio_handle *handle, uint64_t offset,
                                 struct docio_object *doc)
{
    uint8_t checksum;
    uint64_t _offset;
    int key_alloc = 0;
    int meta_alloc = 0;
    fdb_seqnum_t _seqnum;
    timestamp_t _timestamp;
    struct docio_length _length;
    err_log_callback *log_callback = handle->log_callback;

    _offset = _docio_read_length(handle, offset, &_length, log_callback);
    if (_offset == offset) {
        return offset;
    }

    // checksum check
    checksum = _docio_length_checksum(_length);
    if (checksum != _length.checksum) {
        fdb_log(log_callback, FDB_RESULT_CHECKSUM_ERROR,
                "doc_length checksum mismatch error in a database file '%s'",
                handle->file->filename);
        return offset;
    }

    doc->length = _docio_length_decode(_length);
    if (doc->length.keylen == 0 || doc->length.keylen > FDB_MAX_KEYLEN_INTERNAL) {
        return offset;
    }

    // document size check
    if (offset + sizeof(struct docio_length) +
        doc->length.keylen + doc->length.metalen + doc->length.bodylen_ondisk >
        filemgr_get_pos(handle->file)) {
        fdb_log(log_callback, FDB_RESULT_FILE_CORRUPTION,
                "Fatal error!!! Database file '%s' is corrupted.",
                handle->file->filename);
        return offset;
    }

    if (doc->key == NULL) {
        doc->key = (void *)malloc(doc->length.keylen);
        key_alloc = 1;
    }
    if (doc->meta == NULL && doc->length.metalen) {
        doc->meta = (void *)malloc(doc->length.metalen);
        meta_alloc = 1;
    }

    fdb_assert(doc->key, handle, doc->length.keylen);

    _offset = _docio_read_doc_component(handle, _offset, doc->length.keylen,
                                        doc->key, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, 0);
        return offset;
    }

    // read timestamp
    _offset = _docio_read_doc_component(handle, _offset,
                                        sizeof(timestamp_t),
                                        &_timestamp, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, 0);
        return offset;
    }
    doc->timestamp = _endian_decode(_timestamp);

    // copy sequence number (optional)
    _offset = _docio_read_doc_component(handle, _offset, sizeof(fdb_seqnum_t),
                                        (void *)&_seqnum, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, 0);
        return offset;
    }
    doc->seqnum = _endian_decode(_seqnum);

    _offset = _docio_read_doc_component(handle, _offset, doc->length.metalen,
                                        doc->meta, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, 0);
        return offset;
    }

    uint8_t free_meta = meta_alloc && !doc->length.metalen;
    free_docio_object(doc, 0, free_meta, 0);

    return _offset;
}

uint64_t docio_read_doc(struct docio_handle *handle, uint64_t offset,
                        struct docio_object *doc)
{
    uint8_t checksum;
    uint64_t _offset;
    int key_alloc = 0;
    int meta_alloc = 0;
    int body_alloc = 0;
    fdb_seqnum_t _seqnum;
    timestamp_t _timestamp;
    void *comp_body = NULL;
    struct docio_length _length;
    err_log_callback *log_callback = handle->log_callback;

    _offset = _docio_read_length(handle, offset, &_length, log_callback);
    if (_offset == offset) {
        return offset;
    }

    // checksum check
    checksum = _docio_length_checksum(_length);
    if (checksum != _length.checksum) {
        fdb_log(log_callback, FDB_RESULT_CHECKSUM_ERROR,
                "doc_length checksum mismatch error in a database file '%s'",
                handle->file->filename);
        return offset;
    }

    doc->length = _docio_length_decode(_length);
    if (doc->length.flag & DOCIO_TXN_COMMITTED) {
        // transaction commit mark
        // read the corresponding doc offset

        // If TXN_COMMITTED flag is set, this doc is not an actual doc, but a
        // transaction commit marker. Thus, all lengths should be zero.
        if (doc->length.keylen || doc->length.metalen ||
            doc->length.bodylen || doc->length.bodylen_ondisk) {
            free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
            return offset;
        }

        uint64_t doc_offset;
        _offset = _docio_read_doc_component(handle, _offset,
                                            sizeof(doc_offset), &doc_offset,
                                            log_callback);
        if (_offset == 0) {
            free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
            return offset;
        }
        doc->doc_offset = _endian_decode(doc_offset);
        // The offset of the actual document that pointed by this commit marker
        // should not be greater than the file size.
        if (doc->doc_offset > filemgr_get_pos(handle->file)) {
            free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
            return offset;
        }
        return _offset;
    }

    if (doc->length.keylen == 0 || doc->length.keylen > FDB_MAX_KEYLEN_INTERNAL) {
        return offset;
    }

    // document size check
    if (offset + sizeof(struct docio_length) +
        doc->length.keylen + doc->length.metalen + doc->length.bodylen_ondisk >
        filemgr_get_pos(handle->file)) {
        fdb_log(log_callback, FDB_RESULT_FILE_CORRUPTION,
                "Fatal error!!! Database file '%s' is corrupted.",
                handle->file->filename);
        return offset;
    }

    if (doc->key == NULL) {
        doc->key = (void *)malloc(doc->length.keylen);
        key_alloc = 1;
    }
    if (doc->meta == NULL && doc->length.metalen) {
        doc->meta = (void *)malloc(doc->length.metalen);
        meta_alloc = 1;
    }
    if (doc->body == NULL && doc->length.bodylen) {
        doc->body = (void *)malloc(doc->length.bodylen);
        body_alloc = 1;
    }

    fdb_assert(doc->key, handle, doc->length.keylen);

    _offset = _docio_read_doc_component(handle, _offset,
                                        doc->length.keylen,
                                        doc->key,
                                        log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }

    // read timestamp
    _offset = _docio_read_doc_component(handle, _offset,
                                        sizeof(timestamp_t),
                                        &_timestamp,
                                        log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }
    doc->timestamp = _endian_decode(_timestamp);

    // copy seqeunce number (optional)
    _offset = _docio_read_doc_component(handle, _offset,
                                        sizeof(fdb_seqnum_t),
                                        (void *)&_seqnum,
                                        log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }
    doc->seqnum = _endian_decode(_seqnum);

    _offset = _docio_read_doc_component(handle, _offset, doc->length.metalen,
                                        doc->meta, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }

#ifdef _DOC_COMP
    if (doc->length.flag & DOCIO_COMPRESSED) {
        comp_body = (void*)malloc(doc->length.bodylen_ondisk);
        _offset = _docio_read_doc_component_comp(handle, _offset, doc->length.bodylen,
                                                 doc->length.bodylen_ondisk, doc->body,
                                                 comp_body, log_callback);
        if (_offset == 0) {
            if (comp_body) {
                free(comp_body);
            }
            free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
            return offset;
        }
    } else {
        _offset = _docio_read_doc_component(handle, _offset, doc->length.bodylen,
                                            doc->body, log_callback);
        if (_offset == 0) {
            free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
            return offset;
        }
    }
#else
    _offset = _docio_read_doc_component(handle, _offset, doc->length.bodylen,
                                        doc->body, log_callback);
    if (_offset == 0) {
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }
#endif

#ifdef __CRC32
    uint32_t crc_file, crc;
    _offset = _docio_read_doc_component(handle, _offset, sizeof(crc_file),
                                        (void *)&crc_file, log_callback);
    if (_offset == 0) {
        if (comp_body) {
            free(comp_body);
        }
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }

    crc = chksum((void *)&_length, sizeof(_length));
    crc = chksum_scd(doc->key, doc->length.keylen, crc);
    crc = chksum_scd((void *)&_timestamp, sizeof(timestamp_t), crc);
    crc = chksum_scd((void *)&_seqnum, sizeof(fdb_seqnum_t), crc);
    crc = chksum_scd(doc->meta, doc->length.metalen, crc);
    if (doc->length.flag & DOCIO_COMPRESSED) {
        crc = chksum_scd(comp_body, doc->length.bodylen_ondisk, crc);
        if (comp_body) {
            free(comp_body);
        }
    } else {
        crc = chksum_scd(doc->body, doc->length.bodylen, crc);
    }
    if (crc != crc_file) {
        fdb_log(log_callback, FDB_RESULT_CHECKSUM_ERROR,
                "doc_body checksum mismatch error in a database file '%s'",
                handle->file->filename);
        free_docio_object(doc, key_alloc, meta_alloc, body_alloc);
        return offset;
    }
#endif

    uint8_t free_meta = meta_alloc && !doc->length.metalen;
    uint8_t free_body = body_alloc && !doc->length.bodylen;
    free_docio_object(doc, 0, free_meta, free_body);

    return _offset;
}

int docio_check_buffer(struct docio_handle *handle, bid_t bid)
{
    err_log_callback *log_callback = handle->log_callback;
    _docio_read_through_buffer(handle, bid, log_callback);
    return _docio_check_buffer(handle);
}

int docio_check_compact_doc(struct docio_handle *handle,
                            struct docio_object *doc)
{
    if (doc->length.flag & DOCIO_COMPACT) return 1;
    else return 0;
}


text: <!DOCTYPE html>


text:
import anyTest, { TestInterface } from 'ava';
import { testReflectedProperties } from '../reflectPropertiesHelper';
import { HTMLOListElement } from '../../worker-thread/dom/HTMLOListElement';
import { createTestingDocument } from '../DocumentCreation';

const test = anyTest as TestInterface<{
  element: HTMLOListElement;
}>;

test.beforeEach((t) => {
  const document = createTestingDocument();

  t.context = {
    element: document.createElement('ol') as HTMLOListElement,
  };
});

testReflectedProperties([{ reversed: [false] }, { start: [1] }, { type: [''] }]);


text:
An [A-Frame](https://aframe.io) component to register event listeners that set
properties. Replacement for old undocumented Declarative Events API.

### Properties

The Event Set component can register multiple event handlers that set multiple
properties. Use double-underscores (`__`) to namespace individual instances of
the component:

```html
<a-entity event-set__1="_event: click; material.color: red; scale: 2 2 2,
          event-set__2="_event: mouseenter; material.color: blue">
```

| Property | Description                                           | Default Value |
| -------- | -----------                                           | ------------- |
| _event   | Event name.                                           | ''            |
| _target  | Query selector if setting property on another entity. | ''            |

`_event` and `_target` are prefixed with underscores to avoid name collisions
if case another component has `event` or `target` properties. Any key-value
property pairs provided beyond `_event` and `_target` will be what is set once
the event is emitted.

### Usage

#### Browser Installation

Install and use by directly including the [browser files](dist):

```html
<head>
  <title>My A-Frame Scene</title>
  <script src="https://aframe.io/releases/0.3.0/aframe.min.js"></script>
  <script src="https://rawgit.com/ngokevin/aframe-event-set-component/master/dist/aframe-event-set-component.min.js"></script>
</head>

<body>
  <a-scene>
    <a-box color="green"
           event-set__1="_event: click; material.color: red; scale: 2 2 2"
           event-set__2="_event: mouseenter; material.color: blue"></a-box>
    <a-camera><a-cursor></a-cursor></a-camera>
  </a-scene>
</body>
```

#### NPM Installation

Install via NPM:

```bash
npm install aframe-event-set-component
```

Then register and use.

```js
require('aframe');
require('aframe-event-set-component');
```