text:
package auto_test // import "go.pennock.tech/tabular/auto"

import (
	"bytes"
	"reflect"
	"sort"
	"testing"

	"github.com/liquidgecka/testlib"

	"go.pennock.tech/tabular"
	"go.pennock.tech/tabular/auto"
	"go.pennock.tech/tabular/csv"
	"go.pennock.tech/tabular/html"
	"go.pennock.tech/tabular/markdown"
	"go.pennock.tech/tabular/texttable"
)

func populate(T *testlib.T, tb tabular.Table) {
	tb.AddHeaders("foo", "loquacious", "x")
	tb.AddRowItems(42, ".", "fred")
	tb.AddRowItems("snerty", "word", "r")
	tb.AddSeparator()
	tb.AddRowItems(" ", true, nil)
	T.Equal(tb.Errors(), nil, "no errors just adding items")
}

func TestNewBasic(t *testing.T) {
	T := testlib.NewT(t)
	defer T.Finish()

	bare := tabular.New()

	tac := auto.New("csv")
	tdc := csv.New()

	tah := auto.New("html")
	tdh := html.New()

	tam := auto.New("markdown")
	tdm := markdown.New()

	tat := auto.New("texttable")
	tdt := texttable.New()

	taa1 := auto.New("ascii-simple")
	taa2 := auto.New("texttable.ascii-simple")
	tda := texttable.New()
	tda.SetDecorationNamed("ascii-simple")

	for _, tb := range []tabular.Table{
		bare, tac, tdc, tah, tdh, tam, tdm, tat, tdt, taa1, taa2, tda,
	} {
		populate(T, tb)
	}

	// This also serves to confirm that the tables created directly satisfy our interface.
	for i, tuple := range []struct {
		a, b  auto.RenderTable
		style string
	}{
		{tac, tdc, "csv"},
		{tah, tdh, "html"},
		{tam, tdm, "markdown"},
		{tat, tdt, "texttable"},
		{taa1, tda, "ascii-simple"},
		{taa2, tda, "texttable.ascii-simple"},
		{taa1, taa2, "texttable.ascii-simple"},
	} {
		typeA := reflect.TypeOf(tuple.a).String()
		typeB := reflect.TypeOf(tuple.b).String()
		T.Equalf(typeA, typeB, "auto [%d] tuple's pairs of identical type", i)

		ra, err := tuple.a.Render()
		T.ExpectSuccessf(err, "auto [%d] tuple.a rendered without error", i)

		bufB := &bytes.Buffer{}
		err = tuple.b.RenderTo(bufB)
		T.ExpectSuccessf(err, "auto [%d] tuple.b rendered without error", i)

		T.Equalf(ra, bufB.String(), "auto [%d] tuple renders identically", i)

		if _, ok := tuple.b.(auto.RenderTable); !ok {
			T.Fatalf("auto [%d] tuple.b does not satisfy RenderTable interface", i)
		}

		wrapped := auto.Wrap(bare, tuple.style)
		typeW := reflect.TypeOf(wrapped).String()
		T.Equalf(typeW, typeB, "auto [%d] wrapping of bare to %q of identical type", i, tuple.style)
		bufW := &bytes.Buffer{}
		err = wrapped.RenderTo(bufW)
		T.ExpectSuccessf(err, "auto [%d] bare-wrapped %q rendered without error", i, tuple.style)

		T.Equalf(ra, bufW.String(), "auto [%d] bare-wrapped %q rendered identically", i, tuple.style)
	}
}

func TestListStyles(t *testing.T) {
	T := testlib.NewT(t)
	defer T.Finish()

	available := auto.ListStyles()
	if !sort.StringsAreSorted(available) {
		T.Error("ListStyles() strings not sorted")
	}

	have := make(map[string]struct{}, len(available))
	for _, h := range available {
		if _, already := have[h]; already {
			T.Errorf("ListStyles() duplicated result: %q", h)
		}
		have[h] = struct{}{}
	}

	for _, expect := range []string{"csv", "html", "markdown", "ascii-simple", "utf8-light"} {
		if _, ok := have[expect]; !ok {
			T.Errorf("ListStyles() missing expected value %q", expect)
		}
	}
}


text:
<?php

namespace Sylius\Component\Taxonomy\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;

/**
 * @author Saša Stamenković <umpirsky@gmail.com>
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 * @author Anna Walasek <anna.walasek@lakion.com>
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface TaxonRepositoryInterface extends RepositoryInterface
{
    /**
     * @param string $parentCode
     *
     * @return TaxonInterface[]
     */
    public function findChildren($parentCode);

    /**
     * @return TaxonInterface[]
     */
    public function findRootNodes();

    /**
     * @param string|null $rootCode
     *
     * @return TaxonInterface[]
     */
    public function findNodesTreeSorted($rootCode = null);

    /**
     * @param string $slug
     * @param string $locale
     *
     * @return TaxonInterface|null
     */
    public function findOneBySlug($slug, $locale);

    /**
     * @param string $name
     * @param string $locale
     *
     * @return TaxonInterface[]
     */
    public function findByName($name, $locale);

    /**
     * @return QueryBuilder
     */
    public function createListQueryBuilder();
}

redpajama_set_name: RedPajamaGithub


text:
function New-BoxstarterPackage {
<#
.SYNOPSIS
Creates a new Chocolatey package source directory intended for a Boxstarter Install

.DESCRIPTION
New-BoxstarterPackage creates a new Directory in your local
Boxstarter repository located at $Boxstarter.LocalRepo. If no path is
provided, Boxstarter creates a minimal nuspec and
ChocolateyInstall.ps1 file. If a path is provided, Boxstarter will
copy the contents of the path to the new package directory. If the
path does not include a nuspec or ChocolateyInstall.ps1, Boxstarter
will create one. You can use Invoke-BoxstarterBuild to pack the
repository directory to a Chocolatey nupkg. If your path includes
subdirectories, you can use Get-PackageRoot inside
ChocolateyInstall.ps1 to reference the parent directory of the copied
content.

.PARAMETER Name
The name of the package to create

.PARAMETER Description
Description of the package to be written to the nuspec

.PARAMETER Path
Optional path whose contents will be copied to the repository

.LINK
http://boxstarter.org
New-PackageFromScript
about_boxstarter_chocolatey
about_boxstarter_variable_in_chocolatey
Invoke-BoxstarterBuild
Get-PackageRoot
#>
    [CmdletBinding()]
    param(
        [string]$Name,
        [string]$description,
        [string]$path,
        [switch]$quiet
    )
    if(!$boxstarter -or !$boxstarter.LocalRepo){
        throw "No Local Repository has been set in `$Boxstarter.LocalRepo."
    }
    if(!($name -match "^\w+(?:[_.-]\w+)*$") -or ($name.length -gt 100)){
        throw "Invalid Package ID"
    }
    $pkgDir = Join-Path $Boxstarter.LocalRepo $Name
    if(test-path $pkgDir) {
        throw "A LocalRepo already exists at $($boxstarter.LocalRepo)\$name. Delete the directory before calling New-BoxstarterPackage"
    }
    MkDir $pkgDir | out-null
    Pushd $pkgDir
    if($path){
        if(!(test-path $Path)){
            popd
            throw "$path could not be found"
        }
        if(test-path "$Path\$Name.nuspec") {
            Copy-Item "$path\*" . -recurse
        }
        else { Copy-Item $path . -recurse }
    }
    $pkgFile = Join-Path $pkgDir "$name.nuspec"
    if(!(test-path $pkgFile)){
        $nuspec = @"
<?xml version="1.0"?>
<package >
  <metadata>
    <id></id>
    <version>1.0.0</version>
    <authors></authors>
    <owners></owners>
    <description>Package description</description>
    <tags>Tag1 Tag2</tags>
  </metadata>
</package>
"@

        Invoke-RetriableScript {
            [xml]$xml = $args[1]
            $metadata = $xml.package.metadata
            # Why ToString()? I have no idea but psv2 breaks without it
            # What I do know is I can't wait for psv2 to die
            $metadata.id = $args[2].ToString()
            if($args[3]){$metadata.Description=$args[3]}
            $metadata.authors = $env:USERNAME
            $metadata.owners = $env:USERNAME
            $metadata.tags="Boxstarter"
            $xml.Save($args[0])
        } $pkgFile $nuspec $Name $description
    }
    if(!(test-path "tools")){
        Mkdir "tools" | out-null
    }
    $installScript=@"
try {

    Write-ChocolateySuccess '$name'
} catch {
  Write-ChocolateyFailure '$name' `$(`$_.Exception.Message)
  throw
}
"@
    if(!(test-path "tools\ChocolateyInstall.ps1")){
        new-Item "tools\ChocolateyInstall.ps1" -type file -value $installScript| out-null
    }
    Popd

    if(!$quiet){
        Write-BoxstarterMessage "A new Chocolatey package has been created at $pkgDir." -nologo
        Write-BoxstarterMessage "You may now edit the files in this package and build the final .nupkg using Invoke-BoxstarterBuild." -nologo
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
  <title>text_inset (Imlib2::Font)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
  <pre>/*
 * Get the inset of the given string using this font
 *
 * Example:
 *   font = Imlib2::Font.new 'palatino/9'
 *   inset = font.inset 'wonder what the inset for this string is...'
 *
 */
static VALUE font_text_inset(VALUE self, VALUE text) {
</pre>
</body>
</html>


text:
package org.conqat.lib.simulink.builder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.commons.collections.HashedListMap;
import org.conqat.lib.commons.collections.PairList;
import org.conqat.lib.commons.collections.UnmodifiableList;
import org.conqat.lib.commons.collections.UnmodifiableSet;
import org.conqat.lib.commons.string.StringUtils;

/**
 * A MDL section has a name, maintains sub sections and a key-value map for
 * parameters. See Simulink Documentation for details on the file format.
 *
 * @author deissenb
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: F064EF4ABE28CC33004292047D7836D9
 */
/* package */class MDLSection {

	/** Name of the section. */
	private final String name;

	/** Line number within the MDL file. */
	private final int lineNumber;

	/** The parent section. */
	private MDLSection parentSection;

	/** Parameter map. */
	private final HashMap<String, String> parameters = new HashMap<String, String>();

	/** Maps from section name to a list of sections. */
	private final HashedListMap<String, MDLSection> subSections = new HashedListMap<String, MDLSection>();

	/**
	 * Create MDL section.
	 */
	/* package */MDLSection(String name, int lineNumber) {
		this.name = name;
		this.lineNumber = lineNumber;
	}

	/**
	 * Create MDL section.
	 *
	 * @param name
	 *            section name.
	 * @param lineNumber
	 *            line number within the MDL file.
	 *
	 * @param sections
	 *            list of sub sections
	 * @param parameters
	 *            parameters of this section
	 *
	 */
	/* package */MDLSection(String name, List<MDLSection> sections,
			PairList<String, String> parameters, int lineNumber) {
		this(name, lineNumber);

		for (MDLSection section : sections) {
			addSubSection(section);
		}

		for (int i = 0; i < parameters.size(); i++) {
			this.parameters
					.put(parameters.getFirst(i), parameters.getSecond(i));
		}
	}

	/** Add sub section. */
	private void addSubSection(MDLSection section) {
		section.parentSection = this;
		subSections.add(section.getName(), section);
	}

	/** Returns the parent section. */
	public MDLSection getParentSection() {
		return parentSection;
	}

	/**
	 * Get the first sub section with a specified name or null if
	 * no section with the given name was found.
	 */
	public MDLSection getFirstSubSection(String name) {
		if (!hasSubSection(name)) {
			return null;
		}
		return subSections.getList(name).get(0);
	}

	/**
	 * Traverse section tree and return all leaves descending from this section.
	 */
	public List<MDLSection> getLeafSections() {
		ArrayList<MDLSection> result = new ArrayList<MDLSection>();
		for (MDLSection section : subSections.getValues()) {
			collectLeafSections(section, result);
		}
		return result;
	}

	/**
	 * Traverse section tree and return all leaves with a specified name
	 * descending from this section.
	 */
	public List<MDLSection> getLeafSections(String name) {
		ArrayList<MDLSection> result = new ArrayList<MDLSection>();

		for (MDLSection section : getLeafSections()) {
			if (section.getName().equals(name)) {
				result.add(section);
			}
		}

		return result;
	}

	/** Get line number. */
	public int getLineNumber() {
		return lineNumber;
	}

	/** Name of the section. */
	public String getName() {
		return name;
	}

	/** Get parameter. */
	public String getParameter(String name) {
		return parameters.get(name);
	}

	/**
	 * Gets parameter if present, otherwise returns default values.
	 */
	public String getParameter(String name, String defaultValue) {
		if (!parameters.containsKey(name)) {
			return defaultValue;
		}
		return parameters.get(name);
	}

	/**
	 * Get parameter map that includes all parameters of this section plus
	 * parameters of subsections. Parameters of subsections are separated by a
	 * dot: <section name>.<parameter name>.
	 */
	public Map<String, String> getParameterMapRecursively() {
		HashMap<String, String> map = new HashMap<String, String>();
		buildParameterMapRecursively(map, "");
		return map;
	}

	/** Get names of all parameters. */
	public UnmodifiableSet<String> getParameterNames() {
		return CollectionUtils.asUnmodifiable(parameters.keySet());
	}

	/**
	 * Get all sub sections. Returns an empty list if this section has no sub
	 * sections.
	 */
	public UnmodifiableList<MDLSection> getSubSections() {
		return CollectionUtils.asUnmodifiable(subSections.getValues());
	}

	/**
	 * Get all sub sections with a given name. Returns an empty list if this
	 * section has no sub sections with the specified name.
	 */
	public UnmodifiableList<MDLSection> getSubSections(String name) {
		if (!hasSubSection(name)) {
			return CollectionUtils.emptyList();
		}
		return CollectionUtils.asUnmodifiable(subSections.getList(name));
	}

	/** Checks if parameter with given names is present. */
	public boolean hasParameter(String name) {
		return parameters.containsKey(name);
	}

	/** Checks if this section has sub sections with specified name. */
	public boolean hasSubSection(String name) {
		return subSections.containsList(name)
				&& !subSections.getList(name).isEmpty();
	}

	/** Checks if this section has sub sections. */
	public boolean hasSubSections() {
		return !subSections.areAllListsEmpty();
	}

	/** Retruns string representation including name and line number. */
	@Override
	public String toString() {
		return name + " [l:" + lineNumber + "]";
	}

	/**
	 * Build parameter map.
	 */
	private void buildParameterMapRecursively(HashMap<String, String> map,
			String prefix) {

		if (!StringUtils.isEmpty(prefix)) {
			prefix = prefix + ".";
		}

		for (String name : parameters.keySet()) {
			map.put(prefix + name, parameters.get(name));
		}

		for (MDLSection subSection : getSubSections()) {
			subSection.buildParameterMapRecursively(map, prefix
					+ subSection.name);
		}
	}

	/**
	 * Collect the leaves of a section.
	 */
	private void collectLeafSections(MDLSection section,
			ArrayList<MDLSection> result) {
		if (!section.hasSubSections()) {
			result.add(section);
			return;
		}

		for (MDLSection child : section.getSubSections()) {
			collectLeafSections(child, result);
		}
	}
}


text:
import sys

from mongo_connector.compat import reraise
from mongo_connector.errors import UpdateDoesNotApply

class DocManagerBase(object):
    """Base class for all DocManager implementations."""

    def apply_update(self, doc, update_spec):
        """Apply an update operation to a document."""

        # Helper to cast a key for a list or dict, or raise ValueError
        def _convert_or_raise(container, key):
            if isinstance(container, dict):
                return key
            elif isinstance(container, list):
                return int(key)
            else:
                raise ValueError

        # Helper to retrieve (and/or create)
        # a dot-separated path within a document.
        def _retrieve_path(container, path, create=False):
            looking_at = container
            for part in path:
                if isinstance(looking_at, dict):
                    if create and not part in looking_at:
                        looking_at[part] = {}
                    looking_at = looking_at[part]
                elif isinstance(looking_at, list):
                    index = int(part)
                    # Do we need to create additional space in the array?
                    if create and len(looking_at) <= index:
                        # Fill buckets with None up to the index we need.
                        looking_at.extend(
                            [None] * (index - len(looking_at)))
                        # Bucket we need gets the empty dictionary.
                        looking_at.append({})
                    looking_at = looking_at[index]
                else:
                    raise ValueError
            return looking_at

        # wholesale document replacement
        if not "$set" in update_spec and not "$unset" in update_spec:
            # update spec contains the new document in its entirety
            return update_spec
        else:
            try:
                # $set
                for to_set in update_spec.get("$set", []):
                    value = update_spec['$set'][to_set]
                    if '.' in to_set:
                        path = to_set.split(".")
                        where = _retrieve_path(doc, path[:-1], create=True)
                        wl = len(where)
                        index = _convert_or_raise(where, path[-1])
                        if isinstance(where, list) and index >= wl:
                            where.extend([None] * (index + 1 - wl))
                        where[index] = value
                    else:
                        doc[to_set] = value

                # $unset
                for to_unset in update_spec.get("$unset", []):
                    if '.' in to_unset:
                        path = to_unset.split(".")
                        where = _retrieve_path(doc, path[:-1])
                        where.pop(_convert_or_raise(where, path[-1]))
                    else:
                        doc.pop(to_unset)
            except (KeyError, ValueError, AttributeError, IndexError):
                exc_t, exc_v, exc_tb = sys.exc_info()
                reraise(UpdateDoesNotApply,
                        "Cannot apply update %r to %r" % (update_spec, doc),
                        exc_tb)
            return doc

    def bulk_upsert(self, docs, namespace, timestamp):
        """Upsert each document in a set of documents.

        This method may be overridden to upsert many documents at once.
        """
        for doc in docs:
            self.upsert(doc, namespace, timestamp)

    def update(self, doc, update_spec, namespace, timestamp):
        """Update a document.

        ``update_spec`` is the update operation as provided by an oplog record
        in the "o" field.
        """
        raise NotImplementedError

    def upsert(self, document, namespace, timestamp):
        """(Re-)insert a document."""
        raise NotImplementedError

    def remove(self, document_id, namespace, timestamp):
        """Remove a document.

        ``document_id`` is a dict that provides the id of the document
        to be removed. ``namespace`` and ``timestamp`` provide the database +
        collection name and the timestamp from the corresponding oplog entry.
        """
        raise NotImplementedError

    def insert_file(self, f, namespace, timestamp):
        """Insert a file from GridFS."""
        raise NotImplementedError

    def handle_command(self, command_doc, namespace, timestamp):
        """Handle a MongoDB command."""
        raise NotImplementedError

    def search(self, start_ts, end_ts):
        """Get an iterable of documents that were inserted, updated, or deleted
        between ``start_ts`` and ``end_ts``.
        """
        raise NotImplementedError

    def commit(self):
        """Commit all outstanding writes."""
        raise NotImplementedError

    def get_last_doc(self):
        """Get the document that was modified or deleted most recently."""
        raise NotImplementedError

    def stop(self):
        """Stop all threads started by this DocManager."""
        raise NotImplementedError


text:
package io.redlink.smarti.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.*;

/**
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "conversation context")
public class Context {

    @ApiModelProperty(notes="the context type")
    private String contextType; // = "ApplicationHelp"
    @ApiModelProperty(notes="the environment type")
    private String environmentType; // = "SAP_Application"
    @ApiModelProperty(notes="the domain of the conversation")
    private String domain;
    private Map<String,List<String>> environment = new HashMap<>();

    public String getContextType() {
        return contextType;
    }

    public void setContextType(String contextType) {
        this.contextType = contextType;
    }

    public String getEnvironmentType() {
        return environmentType;
    }

    public void setEnvironmentType(String environmentType) {
        this.environmentType = environmentType;
    }

    public String getDomain() {
        return domain;
    }

    public Context setDomain(String domain) {
        this.domain = domain;
        return this;
    }

    public Map<String, List<String>> getEnvironment() {
        return environment;
    }

    public List<String> getEnvironment(String key) {
        return environment.get(key);
    }

    public void setEnvironment(Map<String, List<String>> environment) {
        this.environment = environment;
    }

    public void setEnvironment(String key, String value) {
        setEnvironment(key, new LinkedList<>(Collections.singletonList(value)));
    }

    public void setEnvironment(String key, List<String> value) {
        environment.put(key, value);
    }
}


text:
We made thousands of pre-made source code pieces for easy implementation in your own programming projects. ByteScout PDF Suite can create zugferd invoice with pdf sdk. It can be applied from VBScript. ByteScout PDF Suite is the bundle that provides six different SDK libraries to work with PDF from generating rich PDF reports to extracting data from PDF documents and converting them to HTML. This bundle includes PDF (Generator) SDK, PDF Renderer SDK, PDF Extractor SDK, PDF to HTML SDK, PDF Viewer SDK and PDF Generator SDK for Javascript.

This prolific sample source code in VBScript for ByteScout PDF Suite contains various functions and other necessary options you should do calling the API to create zugferd invoice with pdf sdk. This VBScript sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Further improvement of the code will make it more robust.

Our website gives trial version of ByteScout PDF Suite for free. It also includes documentation and source code samples.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20PDF%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20PDF%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****FileAttachmentAnnotations.vbs:**

```
' This example demonstrates how to attach a file to PDF document.

' Open pdf document
Set pdfDocument = CreateObject("Bytescout.PDF.Document")
pdfDocument.RegistrationName = "demo"
pdfDocument.RegistrationKey = "demo"

' Load existing document
pdfDocument.Load("Invoice.pdf")

Set comHelpers = pdfDocument.ComHelpers

' Attach ZUGFeRD XML file
Set fileAttachment = comHelpers.CreateFileAttachmentAnnotation("ZUGFeRD-invoice.xml", 0, 0, 0, 0)
pdfDocument.Pages.Item(0).Annotations.Add(fileAttachment)

' Instruct PDF viewer applications to show attachments pane on startup (optional)
pdfDocument.PageMode = comHelpers.PAGEMODE_ATTACHMENT

' Save document to file
pdfDocument.Save("result.pdf")

' Open document in default PDF viewer app
Set shell = CreateObject("WScript.Shell")
shell.Run "result.pdf", 1, false
```

<!-- code block end -->


text:
#include <plist/plist.h>
#include <string.h>
#include <stdlib.h>

#include "screenshotr.h"
#include "device_link_service.h"
#include "common/debug.h"

#define SCREENSHOTR_VERSION_INT1 300
#define SCREENSHOTR_VERSION_INT2 0

/**
 * Convert a device_link_service_error_t value to a screenshotr_error_t value.
 * Used internally to get correct error codes.
 *
 * @param err An device_link_service_error_t error code
 *
 * @return A matching screenshotr_error_t error code,
 *     SCREENSHOTR_E_UNKNOWN_ERROR otherwise.
 */
static screenshotr_error_t screenshotr_error(device_link_service_error_t err)
{
	switch (err) {
		case DEVICE_LINK_SERVICE_E_SUCCESS:
			return SCREENSHOTR_E_SUCCESS;
		case DEVICE_LINK_SERVICE_E_INVALID_ARG:
			return SCREENSHOTR_E_INVALID_ARG;
		case DEVICE_LINK_SERVICE_E_PLIST_ERROR:
			return SCREENSHOTR_E_PLIST_ERROR;
		case DEVICE_LINK_SERVICE_E_MUX_ERROR:
			return SCREENSHOTR_E_MUX_ERROR;
		case DEVICE_LINK_SERVICE_E_BAD_VERSION:
			return SCREENSHOTR_E_BAD_VERSION;
		default:
			break;
	}
	return SCREENSHOTR_E_UNKNOWN_ERROR;
}

LIBIMOBILEDEVICE_API screenshotr_error_t screenshotr_client_new(idevice_t device, lockdownd_service_descriptor_t service,
					   screenshotr_client_t * client)
{
	if (!device || !service || service->port == 0 || !client || *client)
		return SCREENSHOTR_E_INVALID_ARG;

	device_link_service_client_t dlclient = NULL;
	screenshotr_error_t ret = screenshotr_error(device_link_service_client_new(device, service, &dlclient));
	if (ret != SCREENSHOTR_E_SUCCESS) {
		return ret;
	}

	screenshotr_client_t client_loc = (screenshotr_client_t) malloc(sizeof(struct screenshotr_client_private));
	client_loc->parent = dlclient;

	/* perform handshake */
	ret = screenshotr_error(device_link_service_version_exchange(dlclient, SCREENSHOTR_VERSION_INT1, SCREENSHOTR_VERSION_INT2));
	if (ret != SCREENSHOTR_E_SUCCESS) {
		debug_info("version exchange failed, error %d", ret);
		screenshotr_client_free(client_loc);
		return ret;
	}

	*client = client_loc;

	return ret;
}

LIBIMOBILEDEVICE_API screenshotr_error_t screenshotr_client_start_service(idevice_t device, screenshotr_client_t * client, const char* label)
{
	screenshotr_error_t err = SCREENSHOTR_E_UNKNOWN_ERROR;
	service_client_factory_start_service(device, SCREENSHOTR_SERVICE_NAME, (void**)client, label, SERVICE_CONSTRUCTOR(screenshotr_client_new), &err);
	return err;
}

LIBIMOBILEDEVICE_API screenshotr_error_t screenshotr_client_free(screenshotr_client_t client)
{
	if (!client)
		return SCREENSHOTR_E_INVALID_ARG;
	device_link_service_disconnect(client->parent, NULL);
	screenshotr_error_t err = screenshotr_error(device_link_service_client_free(client->parent));
	free(client);
	return err;
}

LIBIMOBILEDEVICE_API screenshotr_error_t screenshotr_take_screenshot(screenshotr_client_t client, char **imgdata, uint64_t *imgsize)
{
	if (!client || !client->parent || !imgdata)
		return SCREENSHOTR_E_INVALID_ARG;

	screenshotr_error_t res = SCREENSHOTR_E_UNKNOWN_ERROR;

	plist_t dict = plist_new_dict();
	plist_dict_set_item(dict, "MessageType", plist_new_string("ScreenShotRequest"));

	res = screenshotr_error(device_link_service_send_process_message(client->parent, dict));
	plist_free(dict);
	if (res != SCREENSHOTR_E_SUCCESS) {
		debug_info("could not send plist, error %d", res);
		return res;
	}

	dict = NULL;
	res = screenshotr_error(device_link_service_receive_process_message(client->parent, &dict));
	if (res != SCREENSHOTR_E_SUCCESS) {
		debug_info("could not get screenshot data, error %d", res);
		goto leave;
	}
	if (!dict) {
		debug_info("did not receive screenshot data!");
		res = SCREENSHOTR_E_PLIST_ERROR;
		goto leave;
	}

	plist_t node = plist_dict_get_item(dict, "MessageType");
	char *strval = NULL;
	plist_get_string_val(node, &strval);
	if (!strval || strcmp(strval, "ScreenShotReply")) {
		debug_info("invalid screenshot data received!");
		res = SCREENSHOTR_E_PLIST_ERROR;
		goto leave;
	}
	node = plist_dict_get_item(dict, "ScreenShotData");
	if (!node || plist_get_node_type(node) != PLIST_DATA) {
		debug_info("no PNG data received!");
		res = SCREENSHOTR_E_PLIST_ERROR;
		goto leave;
	}

	plist_get_data_val(node, imgdata, imgsize);
	res = SCREENSHOTR_E_SUCCESS;

leave:
	if (dict)
		plist_free(dict);

	return res;
}


text:
=begin

= AppParameterCustomizations

  - version:  3.02.20130206
  - author:   Steve A.
  - custom version for the application: AmbGest

=end
module AppParameterCustomizations
                                # Custom param ID codes:
  CODE_RECEIPT_DESCRIPTION      = 10 unless defined?(CODE_RECEIPT_DESCRIPTION)
  CODE_RECEIPT_ALT_DESCRIPTION  = 12 unless defined?(CODE_RECEIPT_ALT_DESCRIPTION)

  CODE_APPOINTMENT_MINS         = 20 unless defined?(CODE_APPOINTMENT_MINS)
  CODE_MORNING_SCHEDULE         = 22 unless defined?(CODE_MORNING_SCHEDULE)
  CODE_NOON_SCHEDULE            = 24 unless defined?(CODE_NOON_SCHEDULE)

  CODE_RECEIPT_COSTS_START      = 30 unless defined?(CODE_RECEIPT_COSTS_START)
  CODE_RECEIPT_COSTS_END        = 39 unless defined?(CODE_RECEIPT_COSTS_END)

  CODE_RECEIPT_ACCOUNT_PERCENT  = 40 unless defined?(CODE_RECEIPT_ACCOUNT_PERCENT)
  #----------------------------------------------------------------------------

  # Retrieves the default receipt (/invoice) description.
  #
  def self.get_default_receipt_description()
    ::ActiveSupport::Deprecation.warn("'AppParameter.get_default_receipt_description()' is deprecated and does not support localization. Use 'as_(:default_receipt_description, {:scope=>[:agex]})' instead.")
    AppParameter.get_string_parameter( CODE_RECEIPT_DESCRIPTION )
  end

  # Retrieves the alternate receipt (/invoice) description.
  def self.get_alternate_receipt_description()
    ::ActiveSupport::Deprecation.warn("'AppParameter.get_alternate_receipt_description()' is deprecated and does not support localization. Use 'as_(:alternate_receipt_description, {:scope=>[:agex]})' instead.")
    AppParameter.get_string_parameter( CODE_RECEIPT_ALT_DESCRIPTION )
  end
  # ---------------------------------------------------------------------------
  #++

  # Retrieves the default appointment length in minutes from the Application's
  # Parameters configuration table.
  def self.get_appointment_length_in_mins()
    ap = AppParameter.find_by_id( CODE_APPOINTMENT_MINS )
    ap.nil? ? 60 : ap.a_integer
  end

  # Retrieves the morning appointment scheduling and prepares an hash containing:
  #
  # :start_time => a DateTime instance of the starting time (date part should be ignored);
  # :total_appointments => the total number of appointement to be scheduled as default.
  #
  def self.get_morning_schedule()
    prepare_schedule_hash( CODE_MORNING_SCHEDULE, "08:30" )
  end

  # Retrieves the noon appointment scheduling and prepares an hash containing:
  #
  # :start_time => a DateTime instance of the starting time (date part should be ignored);
  # :total_appointments => the total number of appointement to be scheduled as default.
  #
  def self.get_noon_schedule()
    prepare_schedule_hash( CODE_NOON_SCHEDULE, "13:30" )
  end
  # ---------------------------------------------------------------------------
  #++

  # Retrieves an array of hashes each one containing the pair:
  # :name => description of the receipt cost row;
  # :value => value (in euro cents) for this cost row.
  def self.get_receipt_costs()
    costs = []
    param_found = AppParameter.find( :all,  :conditions => ['(id >= ? and id <= ?)', CODE_RECEIPT_COSTS_START,  CODE_RECEIPT_COSTS_END] )
    param_found.each { |p| ( costs << {:name => p.a_string, :value => p.a_integer} ) }
    return costs
  end

  # Retrieves the description for the default account percent used in a receipt.
  def self.get_receipt_account_description()
    AppParameter.get_string_parameter( CODE_RECEIPT_ACCOUNT_PERCENT )
  end

  # Retrieves the integer value for the default account percent used in a receipt.
  def self.get_receipt_account_percent()
    AppParameter.get_integer_parameter( CODE_RECEIPT_ACCOUNT_PERCENT )
  end
  # ---------------------------------------------------------------------------
  #++

  private

  # Retrieves appointment scheduling and prepares an hash containing:
  #
  # :start_time => a DateTime instance of the starting time (date part should be ignored);
  # :total_appointments => the total number of appointement to be scheduled as default.
  #
  def self.prepare_schedule_hash( schedule_app_parameter_id, starting_time_string )
    ap = AppParameter.find_by_id( schedule_app_parameter_id )
    if ap.nil?
      sTemp = Date.today.year.to_s << "-" << "%02u" % Date.today.month.to_s << "-" <<
              "%02u" % Date.today.day.to_s << " " << starting_time_string
      start_time = DateTime.parse(sTemp)
      total_appointments = 4
    else
      start_time = ap.a_date
      total_appointments = ap.a_integer
    end
    return {
      :start_time => start_time, :total_appointments => total_appointments,
      :start_hour => start_time.hour, :start_min => start_time.min
    }
  end
  # ---------------------------------------------------------------------------
  #++
end
#------------------------------------------------------------------------------


text:
from swgpy.object import *

def create(kernel):
	result = Creature()

	result.template = "object/creature/npc/droid/shared_silver_protocol_base.iff"
	result.attribute_template_id = 3
	result.stfName("droid_name","3po_base")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RatesScenarioCurveBuilder</title>
<meta name="date" content="2012-08-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.param.creator

Class RatesScenarioCurveBuilder

java.lang.Object

org.drip.param.creator.RatesScenarioCurveBuilder

public class RatesScenarioCurveBuilder
extends java.lang.Object

This class implements the various ways of constructing, de-serializing, and building the Rates Scenario
                Curves Container.

Constructor Summary

Constructors

Constructor and Description

RatesScenarioCurveBuilder()

Method Summary

Methods

Modifier and Type
Method and Description

static DiscountCurve
CreateDiscountCurve(JulianDate dt,
                   java.lang.String strCurrency,
                   CalibratableComponent[] aCalibInst,
                   double[] adblQuotes,
                   java.lang.String[] astrCalibMeasure,
                   java.util.Map<JulianDate,java.util.Map<java.lang.String,java.lang.Double>> mmFixings)

Creates Discount Curve from the Rates Calibration Instruments

static RatesScenarioCurve
FromIRCSG(java.lang.String strCurrency,
         CalibratableComponent[] aCalibInst)

Creates an RatesScenarioCurve Instance from the currency and the array of the calibration
        instruments

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RatesScenarioCurveBuilder

public RatesScenarioCurveBuilder()

Method Detail

FromIRCSG

public static final RatesScenarioCurve FromIRCSG(java.lang.String strCurrency,
                           CalibratableComponent[] aCalibInst)

Creates an RatesScenarioCurve Instance from the currency and the array of the calibration
        instruments

Parameters:

strCurrency - Currency

aCalibInst - Array of the calibration instruments

Returns:

The RatesScenarioCurve instance

CreateDiscountCurve

public static final DiscountCurve CreateDiscountCurve(JulianDate dt,
                                java.lang.String strCurrency,
                                CalibratableComponent[] aCalibInst,
                                double[] adblQuotes,
                                java.lang.String[] astrCalibMeasure,
                                java.util.Map<JulianDate,java.util.Map<java.lang.String,java.lang.Double>> mmFixings)

Creates Discount Curve from the Rates Calibration Instruments

Parameters:

dt - Valuation Date

strCurrency - Currency

aCalibInst - Input Rates Calibration Instruments

adblQuotes - Input Calibration Quotes

astrCalibMeasure - Input Calibration Measures

mmFixings - (Optional) Input Fixings

Returns:

The Calibrated Discount Curve

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/**
 * Transfer module for performing operations on FTP servers. It also supports a
 * number of FTP extensions, such as GridFTP.
 */
package stork.module.ftp;


text:
using UnityEngine;
using System.Collections;

public class a_do_trap_emeraldpuzzle : a_hack_trap {

	public bool hasExecuted;

	public override void ExecuteTrap (object_base src, int triggerX, int triggerY, int State)
	{
		Debug.Log (this.name);
		if (hasExecuted==false)
		{
			//Check if 4 emeralds on on top of the plinths.
			if (CheckPlinths())
			{
				CreateRuneStone(253);
				hasExecuted=true;
			}
		}
	}

	private void CreateRuneStone(int ItemID)
	{
		ObjectLoaderInfo newobjt= ObjectLoader.newWorldObject(ItemID,0,0,1,256);
		GameObject myObj = ObjectInteraction.CreateNewObject(CurrentTileMap(),newobjt,CurrentObjectList().objInfo, GameWorldController.instance.DynamicObjectMarker().gameObject,new Vector3(64.5f,4.0f,24.5f)).gameObject;
		UnFreezeMovement(myObj);
	}

	private bool CheckPlinths()
	{
		if (CheckArea(new Vector3(59.4f,3.9f,27.0f),1.2f,167) ==true)
		{
			if (CheckArea(new Vector3(59.4f,3.9f,17.5f),1.2f,167) ==true)
			{
				if (CheckArea(new Vector3(69.0f,3.9f,17.5f),1.2f,167) ==true)
				{
					if (CheckArea(new Vector3(69.0f,3.9f,27.0f),1.2f,167) ==true)
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	private bool CheckArea(Vector3 centre, float radius, int item_id)
	{
		Collider[] hitColliders = Physics.OverlapSphere(centre, radius);
		int i = 0;
		while (i < hitColliders.Length) {
			if (hitColliders[i].gameObject.GetComponent<ObjectInteraction>()!=null)
			{
			if (hitColliders[i].gameObject.GetComponent<ObjectInteraction>().item_id==item_id)
			    {
					Debug.Log("found " + hitColliders[i].gameObject.name);
				return true;
				}
			}
			i++;
		}
	return false;
	}

	public override void PostActivate (object_base src)
	{
        //Stop trap from destroying itself.
        Debug.Log("Overridden PostActivate to test " + this.name);
        base.PostActivate(src);
    }
}


text:
Hello {{ main.username }} in your wallet

here you'll be have dashboard to add your daily costs


text:
namespace SexyFishHorse.Irc.Client.EventHandling.EventArgs
{
    using System;

    public class OnConnectedEventArgs : EventArgs
    {
    }
}


text:
.. currentmodule:: scikits.statsmodels

************
Introduction
************

Background
----------

Scipy.stats.models was originally written by Jonathan Taylor.
For some time it was part of scipy but then removed from it. During
the Google Summer of Code 2009, stats.models was corrected, tested and
enhanced and released as a new package. Since then we have continued to
improve the existing models and added new statistical methods.

Current Status
--------------

statsmodels 0.3 is a pure python package, with one optional cython based
extension. However, future releases will depend on cython generated
extensions.

statsmodels includes:

  * regression: mainly OLS and generalized least squares, GLS
    including weighted least squares and least squares with AR
    errors.
  * glm: generalized linear models
  * rlm: robust linear models
  * discretemod: regression with discrete dependent variables, Logit, Probit,
    MNLogit, Poisson, based on maximum likelihood estimators
  * datasets: for examples and tests
  * univariate time series analysis: AR, ARIMA
  * vector autoregressive models
  * descriptive statistics and process models for time series analysis
  * diagnostics and specification tests
  * additional statistical tests and functions for multiple testing
  * miscellaneous models

statsmodels contains a sandbox folder, which includes some of the original
stats.models code that has not yet been rewritten and tested. The sandbox also
contains models and functions that we are currently developing. This code is
in various stages of development from early stages to almost finished, but
not sufficiently tested or with an API that is still in flux. Some of the code
in the advanced state covers among others GARCH models, general method of
moments (GMM) estimators, kernel regression and kernel density estimation, and
various extensions to scipy.stats.distributions.

The code is written for plain NumPy arrays so that statsmodels can be used
as a library for any kind of data structure users might have. However, in
order to make the data handling easier, some time series specific models
rely on pandas, and we have plans to integrate pandas in future releases of
statsmodels.

We have also included several datasets from the public domain and by
permission for tests and examples. The datasets are set up so that it is
easy to add more datasets.

Python 3
--------

scikits.statsmodels has been ported and tested for Python 3.2. Python 3
version of the code can be obtained by running 2to3.py over the entire
statsmodels source. The numerical core of statsmodels worked almost without
changes, however there can be problems with data input and plotting.
The STATA file reader and writer in iolib.foreign has not been ported yet.
And there are still some problems with the matplotlib version for Python 3
that was used in testing. Running the test suite with Python 3.2 shows some
errors related to foreign and matplotlib.

Testing
-------

Most results have been verified with at least one other statistical package: R,
Stata or SAS. The guiding principal for the initial rewrite and for continued
development is that all numbers have to be verified. Some statistical
methods are tested with Monte Carlo studies. While we strife to follow this
test driven approach, there is no guarantee that the code is bug-free and
always works. Some auxilliary function are still insufficiently tested, some
edge cases might not be correctly taken into account, and the possibility of
numerical problems is inherent to many of the statistical models. We
especially appreciate any help and reports for these kind of problems so we
can keep improving the existing models.

Looking Forward
---------------

We would like to invite everyone to give statsmodels a test drive, use it, and
report comments, possibilities for improvement and bugs to the statsmodels
mailing list http://groups.google.com/group/pystatsmodels or file tickets on our
issue tracker at https://github.com/statsmodels/statsmodels/issues

The source code is available from https://github.com/statsmodels/statsmodels.

Our plans for the future include improving the coverage of statistical
models, methods and tests that any basic statistics package should provide.
But the main direction for the expansion of statsmodels depends on the
requirements and interests of the developers and contributers.

The current maintainers are mostly interested in econometrics and time series
analysis, but we would like to invite any users or developers to contribute
their own extensions to existing models, or new models. To speed up
improvements that are waiting in the sandbox, any help with providing test
cases, reviewing or improving the code would be very appreciated.

Planned Extensions
~~~~~~~~~~~~~~~~~~

Two big changes that are planned for the next release will improve the
usability of statsmodels especially for interactive work.

* Metainformation about data and models: Currently the models essentially
  use no information about the design matrix and just treat it as numpy
  array.
* Merge Pandas into statsmodels which will provide a data structure and
  improved handling of time series data, together with additional time series
  specific models. (Wes McKinney)
* Formulas similar to R: This will provide a faster way to interactively
  define models and contrast matrices, and will provide additional
  information especially for categorical variables. (Nathaniel Smith)

Various models that are work in progress where the time to inclusion in
statsmodels proper will depend on the available developer time and interests:

Bayesian dynamic linear models (Wes)

more Kalman filter based time series analysis (Skipper)

New models (roughly in order of completeness):
general method of moments (GMM) estimators, kernel regression,
kernel density estimation, various extensions to scipy.stats.distributions,
GARCH models, copulas, system of equation models, panel data models,
more discrete choice models, mixed effects models, survival models.

New tests: multiple comparison, more diagnostics and outlier tests, additional
non-parametric tests

Resampling approaches like bootstrap and permutation for tests and estimator
statistics.

Code Stability
~~~~~~~~~~~~~~

The existing models are mostly settled in their user interface and we do not
expect many changes anymore. One area that will need adjustment is how
formulas and meta information are included. New models that have just been
included might require adjustments as we gain more experience and obtain
feedback by users. As we expand the range of models, we keep improving the
framework for different estimators and statistical tests, so further changes
will be necessary. In 0.3 we reorganized the internal location of the code and
import paths which will make future enhancements less interruptive.
Although there is no guarantee yet on API stability, we try to keep changes
that require adjustments by existing users to a minimal level.

Financial Support
-----------------

We are grateful for the financial support that we obtained for the
developement of scikits.statsmodels:

 Google `www.google.com <http://www.google.com/>`_ : two Google Summer of Code,
 GSOC 2009 and GSOC 2010

 AQR `www.aqr.com <http://www.aqr.com/>`_ : financial sponsor for the work on
 Vector Autoregressive Models (VAR) by Wes McKinney

We would also like to thank our hosting providers, `github
<http://github.com/>`_ for the public code repository, `sourceforge
<http://sourceforge.net/>`_ for hosting our documentation and `python.org
<http://python.org>`_ for making our downloads available on pypi.

Josef Perktold and Skipper Seabold,
Wes McKinney,
Mike Crow,
Vincent Davis,


text:
import validatePresence from "./common/validate/presence";
import validateTypePath from "./common/validate/type/path";
import Cldr from "./core";
import coreLoad from "./core/load";
import itemLookup from "./item/lookup";

Cldr._raw = {};

/**
 * Cldr.load( json [, json, ...] )
 *
 * @json [JSON] CLDR data or [Array] Array of @json's.
 *
 * Load resolved or unresolved cldr data.
 * Overwrite Cldr.load().
 */
Cldr.load = function() {
  Cldr._raw = coreLoad(Cldr, Cldr._raw, arguments);
};

/**
 * Overwrite Cldr.prototype.get().
 */
Cldr.prototype.get = function(path) {
  validatePresence(path, "path");
  validateTypePath(path, "path");

  // 1: use bundle as locale on item lookup for simplification purposes, because no other extended subtag is used anyway on bundle parent lookup.
  // 2: during init(), this method is called, but bundle is yet not defined. Use "" as a workaround in this very specific scenario.
  return itemLookup(
    Cldr,
    (this.attributes && this.attributes.bundle) /* 1 */ || "" /* 2 */,
    path,
    this.attributes
  );
};

// In case cldr/unresolved is loaded after cldr/event, we trigger its overloads again. Because, .get is overwritten in here.
if (Cldr._eventInit) {
  Cldr._eventInit();
}

export default Cldr;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pluteus psichiophorus var. dennisii Singer

### Remarks
null


text:
let session = {
    secret: "override session secret in override.ts",
    cookie: {
        secure: false
    }
};

export default session;


text:
module Haggcat.TestHelper where

import           Control.Monad
import qualified Data.Aeson           as Aeson
import qualified Data.ByteString.Lazy as LBS

import           Haggcat.Client
import           Haggcat.Types

getTestConfig :: FilePath -> IO Config
getTestConfig = liftM read . readFile

loadTestClient :: IO Client
loadTestClient = loadClient =<< getTestConfig "test-files/config"

writeInstutions :: Client -> IO ()
writeInstutions client = do
    eitherInsts <- getInstitutions client
    case eitherInsts of
        Right insts -> writeFile "test-files/institutions" $ show insts
        Left msg -> error msg

loadInstitutions :: IO [Institution]
loadInstitutions = do
    content <- readFile "test-files/institutions"
    let insts = read content :: [Institution]
    return insts


text:
test_project
============

First project with github


text:
(function () {
  'use strict';

  angular
    .module('core')
    .controller('InfoController', InfoController);

  InfoController.$inject = ['$scope', '$rootScope', '$q', 'DataProvider', 'LogicProvider', 'TrackingProvider', 'CommonService'];

  function InfoController($scope, $rootScope, $q, DataProvider, LogicProvider, TrackingProvider, CommonService) {
    $scope.common = CommonService;

    $scope.questions = [
      {
        id: 'gender',
        order: 0,
        type: "multi-choice-simple",
        question: "Spol",
        choices: [
          {value: 'male', text:"Moški"},
          {value: 'female', text:"Ženksa"}
        ]
      },
      {
        id: 'status',
        order: 0,
        type: "multi-choice-simple",
        question: "Kakšen je vaš trenutni zaposlitveni status?",
        choices: [
          {value: 'osnovnosolec', text:"Osnovnošolec"},
          {value: 'dijak', text:"Dijak"},
          {value: 'student', text:"Študent"},
          {value: 'zaposlen', text:"Zaposlen"},
          {value: 'upokojenec', text:"Brezposeln"},
          {value: 'neznano', text:"Ne želim odgovoriti"}
        ]
      },
      // {
      //   id: 'brand-knowledge-2',
      //   order: 0,
      //   type: "multi-choice-simple",
      //   question: "Trenutni status",
      //   choices: [
      //     {value: -2, text:"Nič, oziroma skoraj nič. Mogoče bi znal navesti kakšno znamko."},
      //     {value: -1, text:"Dijak/inja"},
      //     {value: 0, text:"Študent/ka"},
      //     {value: 1, text:"Zaposlen/a, brezposelen/a"},
      //     {value: 2, text:"Upokojen/a"},
      //   ]
      // },
      {
        id: 'brand_knowledge',
        order: 1,
        type: "multi-choice-simple",
        question: "Kakšno je vaše poznavanje na področju avtomobilizma?",
        choices: [
          {value: -2, text: "Zelo dobro (na tem področju sem ekspert)"},
          {value: -1, text: "Dobro (o tem vem veliko)"},
          {value: -0, text: "Slabo (o tem vem nekaj malega)"},
          {value: 1,  text: "Zelo slabo (o tem ne vem ničesar)"},
          {value: 2,  text: "Ne morem oceniti svojega poznavanja."}]
      }
    ];

    $scope.answers = {

    };

    $scope.allQuestionsAnswered = function() {
      var number_of_ansers = 0;
      for(var question_id in $scope.answers) {
        if ($scope.answers.hasOwnProperty(question_id) && question_id) {
          number_of_ansers++;
        }
      }
      return $scope.answers && number_of_ansers === $scope.questions.length;
    };

    $scope.selectAnswer = function(question_id, answer_value) {
      $scope.answers[question_id] = answer_value;
    };

    $scope.submitButton = function () {
      console.log("sending answers: ", $scope.answers);
      var answer_objs = [];

      for (var question_id in $scope.answers) {
        answer_objs.push({
          question_id: question_id,
          answer_value: $scope.answers[question_id]
        });
      }

      DataProvider.submitQuestionnaireAnswer(answer_objs, [])
        .then(function() {
          var next_location = LogicProvider.getNextUserLocation($rootScope.user);
          LogicProvider.setNextUserLocation(next_location);
        })
    };

    function init() {

    }

    init();
  }
}());


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright(c) 2016-2017 IBM, Red Hat, and others.
  ~
  ~ 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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>microprofile-conference</artifactId>
        <groupId>io.microprofile.showcase</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>demo-bootstrap</artifactId>
    <name>Conference :: Bootstrap Data</name>

    <packaging>jar</packaging>

    <dependencies>

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.0.4</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?><concept xmlns="http://www.w3.org/2004/02/skos/core#">
      <prefLabel>DRUG TIERS</prefLabel>
      <definition>Drug tiers are definable by the plan. The option 'tier' was introduced in the PBP
         to allow plans the ability to group different drug types together (i.e., Generic, Brand,
         Preferred Brand). In this regard, tiers could be used to describe drug groups that are
         based on classes of drugs. If the 'tier' option is utilized, plans should provide further
         clarification on the drug type(s) covered under the tier in the PBP notes section(s). This
         option was designed to afford users additional flexibility in defining the prescription
         drug benefit.</definition>
   </concept>


text:
package org.apache.shindig.gadgets.rewrite;

/**
 * Merges adjacent style tags.
 *
 * @since 2.0.0
 */
public class StyleAdjacencyContentRewriter extends DomWalker.Rewriter {
  public StyleAdjacencyContentRewriter() {
    super(new StyleAdjacencyVisitor());
  }
}


text:
package com.diffplug.spotless.maven;

import java.io.IOException;

import org.junit.Test;

public class IncludesExcludesTest extends MavenIntegrationTest {

	private static final String JAVA_FORMATTED = "java/eclipse/JavaCodeFormatted.test";
	private static final String JAVA_UNFORMATTED = "java/eclipse/JavaCodeUnformatted.test";
	private static final String SCALA_UNFORMATTED = "scala/scalafmt/basic.dirty";
	private static final String SCALA_FORMATTED = "scala/scalafmt/basic.clean";

	@Test
	public void testDefaultIncludesJava() throws Exception {
		String unformattedCorrectLocation1 = "src/main/java/test1.java";
		String unformattedCorrectLocation2 = "src/main/java/test2.java";
		String unformattedCorrectLocation3 = "src/test/java/test3.java";
		String unformattedCorrectLocation4 = "src/test/java/test4.java";
		String formattedCorrectLocation = "src/main/java/test5.java";
		String unformattedIncorrectLocation1 = "src/main/my-java/test6.java";
		String unformattedIncorrectLocation2 = "sources/main/java/test7.java";

		writePomWithJavaSteps(
				"<eclipse>",
				"  <file>${basedir}/formatter.xml</file>",
				"</eclipse>");

		setFile("formatter.xml").toResource("java/eclipse/formatter.xml");

		writeUnformattedJava(unformattedCorrectLocation1);
		writeUnformattedJava(unformattedCorrectLocation2);
		writeUnformattedJava(unformattedCorrectLocation3);
		writeUnformattedJava(unformattedCorrectLocation4);
		writeFormattedJava(formattedCorrectLocation);
		writeUnformattedJava(unformattedIncorrectLocation1);
		writeUnformattedJava(unformattedIncorrectLocation2);

		mavenRunner().withArguments("spotless:apply").runNoError();

		assertFormattedJava(unformattedCorrectLocation1);
		assertFormattedJava(unformattedCorrectLocation2);
		assertFormattedJava(unformattedCorrectLocation3);
		assertFormattedJava(unformattedCorrectLocation4);
		assertFormattedJava(formattedCorrectLocation);
		assertUnformattedJava(unformattedIncorrectLocation1);
		assertUnformattedJava(unformattedIncorrectLocation2);
	}

	@Test
	public void testDefaultIncludesScala() throws Exception {
		String unformattedCorrectLocation1 = "src/main/scala/test1.scala";
		String unformattedCorrectLocation2 = "src/main/scala/test2.sc";
		String unformattedCorrectLocation3 = "src/test/scala/test3.sc";
		String unformattedCorrectLocation4 = "src/test/scala/test4.scala";
		String formattedCorrectLocation = "src/test/scala/test5.scala";
		String unformattedIncorrectLocation1 = "src/main/not-scala/test6.sc";
		String unformattedIncorrectLocation2 = "scala/scala/scala/test7.scala";

		writePomWithScalaSteps("<scalafmt/>");

		writeUnformattedScala(unformattedCorrectLocation1);
		writeUnformattedScala(unformattedCorrectLocation2);
		writeUnformattedScala(unformattedCorrectLocation3);
		writeUnformattedScala(unformattedCorrectLocation4);
		writeFormattedScala(formattedCorrectLocation);
		writeUnformattedScala(unformattedIncorrectLocation1);
		writeUnformattedScala(unformattedIncorrectLocation2);

		mavenRunner().withArguments("spotless:apply").runNoError();

		assertFormattedScala(unformattedCorrectLocation1);
		assertFormattedScala(unformattedCorrectLocation2);
		assertFormattedScala(unformattedCorrectLocation3);
		assertFormattedScala(unformattedCorrectLocation4);
		assertFormattedScala(formattedCorrectLocation);
		assertUnformattedScala(unformattedIncorrectLocation1);
		assertUnformattedScala(unformattedIncorrectLocation2);
	}

	@Test
	public void testInclude() throws Exception {
		String unformattedDefaultLocation1 = "src/main/scala/test1.scala";
		String unformattedDefaultLocation2 = "src/test/scala/test2.scala";
		String unformattedCustomLocation1 = "src/main/my-scala/test3.scala";
		String unformattedCustomLocation2 = "src/test/sc/test4.sc";

		writePomWithScalaSteps(
				"<includes>",
				"  <include>src/**/my-scala/*.scala</include>",
				"  <include>src/test/sc/*.sc</include>",
				"</includes>",
				"<scalafmt/>");

		writeUnformattedScala(unformattedDefaultLocation1);
		writeUnformattedScala(unformattedDefaultLocation2);
		writeUnformattedScala(unformattedCustomLocation1);
		writeUnformattedScala(unformattedCustomLocation2);

		mavenRunner().withArguments("spotless:apply").runNoError();

		// includes override default ones, so files in default location should remain unformatted
		assertUnformattedScala(unformattedDefaultLocation1);
		assertUnformattedScala(unformattedDefaultLocation2);
		// files included via "<include>" should be formatted
		assertFormattedScala(unformattedCustomLocation1);
		assertFormattedScala(unformattedCustomLocation2);
	}

	@Test
	public void testExclude() throws Exception {
		String unformatted1 = "src/main/scala/test1.scala";
		String unformatted2 = "src/main/scala/test2.sc";
		String unformatted3 = "src/test/scala/test3.scala";
		String unformatted4 = "src/test/scala/test4.sc";

		writePomWithScalaSteps(
				"<includes>",
				"  <include>src/main/scala/*.scala</include>",
				"</includes>",
				"<excludes>",
				"  <exclude>src/main/scala/*.sc</exclude>",
				"  <exclude>src/test/scala</exclude>",
				"</excludes>",
				"<scalafmt/>");

		writeUnformattedScala(unformatted1);
		writeUnformattedScala(unformatted2);
		writeUnformattedScala(unformatted3);
		writeUnformattedScala(unformatted4);

		mavenRunner().withArguments("spotless:apply").runNoError();

		assertFormattedScala(unformatted1);
		assertUnformattedScala(unformatted2);
		assertUnformattedScala(unformatted3);
		assertUnformattedScala(unformatted4);
	}

	private void writeFormattedJava(String target) throws IOException {
		setFile(target).toResource(JAVA_FORMATTED);
	}

	private void writeUnformattedJava(String target) throws IOException {
		setFile(target).toResource(JAVA_UNFORMATTED);
	}

	private void assertFormattedJava(String target) throws IOException {
		assertFile(target).sameAsResource(JAVA_FORMATTED);
	}

	private void assertUnformattedJava(String target) throws IOException {
		assertFile(target).sameAsResource(JAVA_UNFORMATTED);
	}

	private void writeFormattedScala(String target) throws IOException {
		setFile(target).toResource(SCALA_FORMATTED);
	}

	private void writeUnformattedScala(String target) throws IOException {
		setFile(target).toResource(SCALA_UNFORMATTED);
	}

	private void assertFormattedScala(String target) throws IOException {
		assertFile(target).sameAsResource(SCALA_FORMATTED);
	}

	private void assertUnformattedScala(String target) throws IOException {
		assertFile(target).sameAsResource(SCALA_UNFORMATTED);
	}
}


text:
namespace Enterprise.Organization {

    @Serenity.Decorators.registerClass()
    @Serenity.Decorators.responsive()
    export class TimeRecordApprovalDialog extends TemplateDialog<TimeRecordApprovalRow, any> {
        protected getFormKey() { return TimeRecordApprovalForm.formKey; }
        protected getIdProperty() { return TimeRecordApprovalRow.idProperty; }
        protected getLocalTextPrefix() { return TimeRecordApprovalRow.localTextPrefix; }
        protected getNameProperty() { return TimeRecordApprovalRow.nameProperty; }
        protected getService() { return TimeRecordApprovalService.baseUrl; }

        protected form = new TimeRecordApprovalForm(this.idPrefix);

    }
}


text:
layout: model
title: Detect Assertion Status (assertion_dl_biobert) - supports confidence scores
author: John Snow Labs
name: assertion_dl_biobert
date: 2021-01-26
task: Assertion Status
language: en
edition: Healthcare NLP 2.7.2
spark_version: 2.4
tags: [assertion, en, licensed, clinical, biobert]
supported: true
annotator: AssertionDLModel
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Assign assertion status to clinical entities extracted by NER based on their context in the text.

## Predicted Entities

`absent`, `present`, `conditional`, `associated_with_someone_else`, `hypothetical`, `possible`.

{:.btn-box}
[Live Demo](https://demo.johnsnowlabs.com/healthcare/ASSERTION/){:.button.button-orange}
[Open in Colab](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/2.Clinical_Assertion_Model.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/clinical/models/assertion_dl_biobert_en_2.7.2_2.4_1611647486798.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}

```python
documentAssembler = DocumentAssembler()\
    .setInputCol("text")\
    .setOutputCol("document")

sentenceDetector = SentenceDetector()\
    .setInputCols(["document"])\
    .setOutputCol("sentence")

tokenizer = Tokenizer()\
    .setInputCols(["sentence"])\
    .setOutputCol("token")

word_embeddings = BertEmbeddings.pretrained("biobert_pubmed_base_cased")\
    .setInputCols(["sentence",'token'])\
    .setOutputCol("embeddings")

clinical_ner = MedicalNerModel.pretrained("ner_clinical_biobert", "en", "clinical/models") \
    .setInputCols(["sentence", "token", "embeddings"]) \
    .setOutputCol("ner")

ner_converter = NerConverter() \
    .setInputCols(["sentence", "token", "ner"]) \
    .setOutputCol("ner_chunk")

clinical_assertion = AssertionDLModel.pretrained("assertion_dl_biobert", "en", "clinical/models") \
    .setInputCols(["sentence", "ner_chunk", "embeddings"]) \
    .setOutputCol("assertion")

nlpPipeline = Pipeline(stages=[
      documentAssembler,
      sentenceDetector,
      tokenizer,
      word_embeddings,
      clinical_ner,
      ner_converter,
      clinical_assertion
])

data = spark.createDataFrame([["""Patient has a headache for the last 2 weeks, needs to get a head CT, and appears anxious when she walks fast. No alopecia noted. She denies pain"""]]).toDF("text")

result = nlpPipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new DocumentAssembler()
    .setInputCol("text")
    .setOutputCol("document")

val sentenceDetector = new SentenceDetector()
    .setInputCols("document")
    .setOutputCol("sentence")

val tokenizer = new Tokenizer()
    .setInputCols("sentence")
    .setOutputCol("token")

val word_embeddings = BertEmbeddings.pretrained("biobert_pubmed_base_cased")
    .setInputCols(Array("sentence", "token"))
    .setOutputCol("embeddings")

clinical_ner = MedicalNerModel.pretrained("ner_clinical_biobert", "en", "clinical/models")
    .setInputCols(Array("sentence", "token", "embeddings"))
    .setOutputCol("ner")

val ner_converter = new NerConverter()
    .setInputCols(Array("sentence","token","ner"))
    .setOutputCol("ner_chunk")

val clinical_assertion = AssertionDLModel.pretrained("assertion_dl_biobert","en", "clinical/models")
    .setInputCols(Array("sentence", "ner_chunk", "embeddings"))
    .setOutputCol("assertion")

val pipeline =  new Pipeline().setStages(Array(documentAssembler,
                                               sentenceDetector,
                                               tokenizer,
                                               word_embeddings,
                                               clinical_ner,
                                               ner_converter,
                                               clinical_assertion))

val data = Seq("""Patient has a headache for the last 2 weeks, needs to get a head CT, and appears anxious when she walks fast. No alopecia noted. She denies pain""").toDF("text")

val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("en.assert.biobert").predict("""Patient has a headache for the last 2 weeks, needs to get a head CT, and appears anxious when she walks fast. No alopecia noted. She denies pain.""")
```

</div>

## Results

```bash
+----------+---------+-----------+
|chunk     |ner_label|assertion  |
+----------+---------+-----------+
|a headache|PROBLEM  |present    |
|a head CT |TEST     |present    |
|anxious   |PROBLEM  |conditional|
|alopecia  |PROBLEM  |absent     |
|pain      |PROBLEM  |absent     |
+----------+---------+-----------+
```

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|assertion_dl_biobert|
|Compatibility:|Spark NLP 2.7.2+|
|License:|Licensed|
|Edition:|Official|
|Input Labels:|[document, chunk, embeddings]|
|Output Labels:|[assertion]|
|Language:|en|

## Data Source

Trained on i2b2 assertion data.

## Benchmarking

```bash
label                            tp    fp    fn      prec       rec        f1
absent                          769    51    57  0.937805  0.930993  0.934386
present                        2575   161   102  0.941155  0.961898  0.951413
conditional                      20    14    23  0.588235  0.465116  0.519481
associated_with_someone_else     51     9    15  0.85      0.772727  0.809524
hypothetical                    129    13    15  0.908451  0.895833  0.902098
possible                        114    44    80  0.721519  0.587629  0.647727
Macro-average                  3658   292   292  0.824527  0.769033  0.795814
Micro-average                  3658   292   292  0.926076  0.926076  0.926076
```


text:
//////////////////////////////////////////////////////////////////////////////
//
//            Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
//                Distributed under The MIT License (MIT).
//             (See accompanying file License.txt or copy at
//                 https://opensource.org/licenses/MIT)
//
//           Please report any bugs, typos, or suggestions to
//              https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <Epic/Memory/Default.hpp>
#include <Epic/STL/List.hpp>
#include <Epic/STL/Vector.hpp>
#include <Epic/NullMutex.hpp>
#include <algorithm>
#include <mutex>

//////////////////////////////////////////////////////////////////////////////

namespace Epic
{
	template<class T>
	class AutoListDefaultStore;

	template<class T>
	class AutoListVectorStore;

	template<class CRTP, bool Sync = false, template<class> class Store = AutoListDefaultStore>
	class AutoList;

	enum AutoListIgnoreT { AutoListIgnore };
}

//////////////////////////////////////////////////////////////////////////////

// AutoList<CRTP, Sync, Store>
template<class CRTP, bool Sync, template<class> class Store>
class Epic::AutoList
{
	static_assert(std::is_class<std::remove_cv_t<CRTP>>::value, "AutoList can only store class types");

private:
	using Type = Epic::AutoList<CRTP, Sync, Store>;
	using Pointer = typename std::add_pointer<CRTP>::type;
	using ListStore = Store<Pointer>;
	using MutexType = std::conditional_t<Sync, std::recursive_mutex, Epic::NullMutex>;

private:
	static MutexType s_Mutex;

protected:
	AutoList()
	{
		std::lock_guard<MutexType> lock(s_Mutex);
		ListStore::Insert(Pointer(this));
	}

	AutoList(const Type&)
	{
		std::lock_guard<MutexType> lock(s_Mutex);
		ListStore::Insert(Pointer(this));
	}

	AutoList(Type&& other)
	{
		std::lock_guard<MutexType> lock(s_Mutex);
		ListStore::Erase(Pointer(&other));
		ListStore::Insert(Pointer(this));
	}

	explicit AutoList(AutoListIgnoreT) noexcept { }

	~AutoList()
	{
		std::lock_guard<MutexType> lock(s_Mutex);
		ListStore::Erase(Pointer(this));
	}

public:
	// Iterate over the instance list, calling 'fn(pInstance)' for each instance pointer in the list.
	template<typename Function>
	static inline void IterateInstances(Function fn)
	{
		{	/* CS */
			std::lock_guard<MutexType> lock(s_Mutex);

			for (auto it = ListStore::Begin(); it != ListStore::End(); it++)
				fn(*it);
		}
	}

	// Iterate over the instance list, calling 'fn(pInstance)' for each instance pointer in the list.
	// The instance may be safely removed from the AutoList without disrupting iteration.
	template<typename Function>
	static void IterateInstancesSafe(Function fn)
	{
		{	/* CS */
			std::lock_guard<MutexType> lock(s_Mutex);

			for(auto it = ListStore::SafeBegin(); it != ListStore::SafeEnd(); ++it)
				fn(*it);
		}
	}

	// Acquire an iterator to the beginning of the instance list. (Unsynchronized)
	static inline auto InstancesBegin() noexcept
	{
		return ListStore::Begin();
	}

	// Acquire an iterator to one element past the end of the instance list. (Unsynchronized)
	static inline auto InstancesEnd() noexcept
	{
		return ListStore::End();
	}
};

// AutoList Static Initializers
template<class T, bool Sync, template<class> class Store>
decltype(Epic::AutoList<T, Sync, Store>::s_Mutex) Epic::AutoList<T, Sync, Store>::s_Mutex;

//////////////////////////////////////////////////////////////////////////////

// AutoListDefaultStore<T>
template<class T>
class Epic::AutoListDefaultStore
{
	static_assert(std::is_nothrow_default_constructible<T>::value,
		"AutoListDefaultStore's value type must be no-throw default constructible.");

public:
	using Type = AutoListDefaultStore<T>;

	using Value = T;
	using AllocatedType = T;
	using Allocator = Epic::DefaultAllocatorFor<AllocatedType, Epic::eAllocatorFor::List>;

private:
	using ListType = Epic::STLList<T, Allocator>;

private:
	struct SafeIterator
	{
		using Iterator = typename ListType::iterator;
		using ConstIterator = typename ListType::const_iterator;

		Iterator itThis;
		Iterator itNext;
		ConstIterator itEnd;

		SafeIterator(const Iterator& iterThis, const ConstIterator& iterEnd)
			: itThis(iterThis), itEnd(iterEnd)
		{
			itNext = (itThis != itEnd) ? std::next(itThis) : itThis;
		}

		inline auto operator*() { return *itThis; }

		inline bool operator== (const SafeIterator& other) const noexcept
		{
			if (itThis == itEnd)
				return other.itThis == other.itEnd;

			return itThis == other.itThis;
		}

		inline bool operator!= (const SafeIterator& other) const noexcept
		{
			return !(this->operator== (other));
		}

		inline SafeIterator& operator++ () noexcept
		{
			itThis = itNext;

			if (itThis != itEnd)
				itNext = std::next(itThis);

			return *this;
		}
	};

private:
	static ListType s_Data;

public:
	static inline auto Begin() noexcept
	{
		return std::begin(s_Data);
	}

	static inline auto End() noexcept
	{
		return std::end(s_Data);
	}

	static inline auto SafeBegin() noexcept
	{
		return SafeIterator{ std::begin(s_Data), std::cend(s_Data) };
	}

	static inline auto SafeEnd() noexcept
	{
		return SafeIterator{ std::end(s_Data), std::cend(s_Data) };
	}

public:
	static void Insert(const Value& value)
	{
		s_Data.emplace_front(value);
	}

	static void Erase(const Value& value) noexcept
	{
		auto it = std::find(std::begin(s_Data), std::end(s_Data), value);
		if (it != std::end(s_Data))
			s_Data.erase(it);
	}
};

// AutoListDefaultStore Static Initializers
template<class T>
decltype(Epic::AutoListDefaultStore<T>::s_Data) Epic::AutoListDefaultStore<T>::s_Data;

//////////////////////////////////////////////////////////////////////////////

// AutoListVectorStore<T>
template<class T>
class Epic::AutoListVectorStore
{
	static_assert(std::is_nothrow_default_constructible<T>::value,
		"AutoListVectorStore's value type must be no-throw default constructible.");

public:
	using Type = AutoListVectorStore<T>;

	using Value = T;
	using AllocatedType = T;
	using Allocator = Epic::DefaultAllocatorFor<AllocatedType, Epic::eAllocatorFor::Vector>;

private:
	using ListType = Epic::STLVector<T, Allocator>;

private:
	struct SafeIterator
	{
		using Index = typename ListType::size_type;

		Index indexThis;
		Index lastSize;
		ListType* pList;

		SafeIterator(ListType* lst, Index n)
			: pList(lst), indexThis(n), lastSize(lst->size())
		{ }

		inline auto operator*() { return pList->at(indexThis); }

		inline bool operator== (const SafeIterator& other) const noexcept
		{
			if (indexThis >= pList->size())
				return other.indexThis >= other.pList->size();

			return indexThis == other.indexThis;
		}

		inline bool operator!= (const SafeIterator& other) const noexcept
		{
			return !(this->operator== (other));
		}

		inline SafeIterator& operator++ () noexcept
		{
			if (indexThis >= pList->size())
				return *this;

			if (lastSize == pList->size())
				++indexThis;

			lastSize = pList->size();

			return *this;
		}
	};

private:
	static ListType s_Data;

public:
	static inline auto Begin() noexcept
	{
		return std::begin(s_Data);
	}

	static inline auto End() noexcept
	{
		return std::end(s_Data);
	}

	static inline auto SafeBegin() noexcept
	{
		return SafeIterator{ &s_Data, 0 };
	}

	static inline auto SafeEnd() noexcept
	{
		return SafeIterator{ &s_Data, std::size(s_Data) };
	}

public:
	static void Insert(const Value& value)
	{
		s_Data.emplace_back(value);
	}

	static void Erase(const Value& value) noexcept
	{
		auto it = std::find(std::begin(s_Data), std::end(s_Data), value);
		if (it != std::end(s_Data))
			s_Data.erase(it);
	}
};

// AutoListVectorStore Static Initializers
template<class T>
decltype(Epic::AutoListVectorStore<T>::s_Data) Epic::AutoListVectorStore<T>::s_Data;


text:
package org.eclipse.collections.impl.map.immutable.primitive;

import org.eclipse.collections.impl.test.Verify;
import org.junit.Test;

public class ImmutableIntIntSingletonMapSerializationTest
{
    @Test
    public void serializedForm()
    {
        Verify.assertSerializedForm(
                1L,
                "rO0ABXNyAFBvcmcuZWNsaXBzZS5jb2xsZWN0aW9ucy5pbXBsLm1hcC5pbW11dGFibGUucHJpbWl0\n"
                        + "aXZlLkltbXV0YWJsZUludEludFNpbmdsZXRvbk1hcAAAAAAAAAABAgACSQAEa2V5MUkABnZhbHVl\n"
                        + "MXhwAAAAAQAAAAE=",
                new ImmutableIntIntSingletonMap(1, 1));
    }
}


text:
package test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"sync"
	"syscall"
	"testing"
	"time"

	"github.com/prometheus/client_golang/api/alertmanager"
	"github.com/prometheus/common/model"
	"golang.org/x/net/context"
)

// AcceptanceTest provides declarative definition of given inputs and expected
// output of an Alertmanager setup.
type AcceptanceTest struct {
	*testing.T

	opts *AcceptanceOpts

	ams        []*Alertmanager
	collectors []*Collector

	actions map[float64][]func()
}

// AcceptanceOpts defines configuration paramters for an acceptance test.
type AcceptanceOpts struct {
	Tolerance time.Duration
	baseTime  time.Time
}

func (opts *AcceptanceOpts) alertString(a *model.Alert) string {
	if a.EndsAt.IsZero() {
		return fmt.Sprintf("%s[%v:]", a, opts.relativeTime(a.StartsAt))
	}
	return fmt.Sprintf("%s[%v:%v]", a, opts.relativeTime(a.StartsAt), opts.relativeTime(a.EndsAt))
}

// expandTime returns the absolute time for the relative time
// calculated from the test's base time.
func (opts *AcceptanceOpts) expandTime(rel float64) time.Time {
	return opts.baseTime.Add(time.Duration(rel * float64(time.Second)))
}

// expandTime returns the relative time for the given time
// calculated from the test's base time.
func (opts *AcceptanceOpts) relativeTime(act time.Time) float64 {
	return float64(act.Sub(opts.baseTime)) / float64(time.Second)
}

// NewAcceptanceTest returns a new acceptance test with the base time
// set to the current time.
func NewAcceptanceTest(t *testing.T, opts *AcceptanceOpts) *AcceptanceTest {
	test := &AcceptanceTest{
		T:       t,
		opts:    opts,
		actions: map[float64][]func(){},
	}
	opts.baseTime = time.Now()

	return test
}

// freeAddress returns a new listen address not currently in use.
func freeAddress() string {
	// Let the OS allocate a free address, close it and hope
	// it is still free when starting Alertmanager.
	l, err := net.Listen("tcp4", "localhost:0")
	if err != nil {
		panic(err)
	}
	defer l.Close()

	return l.Addr().String()
}

// Do sets the given function to be executed at the given time.
func (t *AcceptanceTest) Do(at float64, f func()) {
	t.actions[at] = append(t.actions[at], f)
}

// Alertmanager returns a new structure that allows starting an instance
// of Alertmanager on a random port.
func (t *AcceptanceTest) Alertmanager(conf string) *Alertmanager {
	am := &Alertmanager{
		t:    t,
		opts: t.opts,
	}

	dir, err := ioutil.TempDir("", "am_test")
	if err != nil {
		t.Fatal(err)
	}
	am.dir = dir

	cf, err := os.Create(filepath.Join(dir, "config.yml"))
	if err != nil {
		t.Fatal(err)
	}
	am.confFile = cf
	am.UpdateConfig(conf)

	am.addr = freeAddress()
	am.mesh = freeAddress()
	am.hwaddr = "00:00:00:00:00:01"
	am.nickname = "1"

	t.Logf("AM on %s", am.addr)

	client, err := alertmanager.New(alertmanager.Config{
		Address: fmt.Sprintf("http://%s", am.addr),
	})
	if err != nil {
		t.Fatal(err)
	}
	am.client = client

	t.ams = append(t.ams, am)

	return am
}

// Collector returns a new collector bound to the test instance.
func (t *AcceptanceTest) Collector(name string) *Collector {
	co := &Collector{
		t:         t.T,
		name:      name,
		opts:      t.opts,
		collected: map[float64][]model.Alerts{},
		expected:  map[Interval][]model.Alerts{},
	}
	t.collectors = append(t.collectors, co)

	return co
}

// Run starts all Alertmanagers and runs queries against them. It then checks
// whether all expected notifications have arrived at the expected receiver.
func (t *AcceptanceTest) Run() {
	errc := make(chan error)

	for _, am := range t.ams {
		am.errc = errc

		am.Start()
		defer func(am *Alertmanager) {
			am.Terminate()
			am.cleanup()
		}(am)
	}

	go t.runActions()

	var latest float64
	for _, coll := range t.collectors {
		if l := coll.latest(); l > latest {
			latest = l
		}
	}

	deadline := t.opts.expandTime(latest)

	select {
	case <-time.After(deadline.Sub(time.Now())):
		// continue
	case err := <-errc:
		t.Error(err)
	}

	for _, coll := range t.collectors {
		report := coll.check()
		t.Log(report)
	}

	for _, am := range t.ams {
		t.Logf("stdout:\n%v", am.cmd.Stdout)
		t.Logf("stderr:\n%v", am.cmd.Stderr)
	}
}

// runActions performs the stored actions at the defined times.
func (t *AcceptanceTest) runActions() {
	var wg sync.WaitGroup

	for at, fs := range t.actions {
		ts := t.opts.expandTime(at)
		wg.Add(len(fs))

		for _, f := range fs {
			go func(f func()) {
				time.Sleep(ts.Sub(time.Now()))
				f()
				wg.Done()
			}(f)
		}
	}

	wg.Wait()
}

// Alertmanager encapsulates an Alertmanager process and allows
// declaring alerts being pushed to it at fixed points in time.
type Alertmanager struct {
	t    *AcceptanceTest
	opts *AcceptanceOpts

	addr                   string
	mesh, hwaddr, nickname string
	client                 alertmanager.Client
	cmd                    *exec.Cmd
	confFile               *os.File
	dir                    string

	errc chan<- error
}

// Start the alertmanager and wait until it is ready to receive.
func (am *Alertmanager) Start() {
	cmd := exec.Command("../../alertmanager",
		"-config.file", am.confFile.Name(),
		"-log.level", "debug",
		"-web.listen-address", am.addr,
		"-storage.path", am.dir,
		"-mesh.listen-address", am.mesh,
		"-mesh.hardware-address", am.hwaddr,
		"-mesh.nickname", am.nickname,
	)

	if am.cmd == nil {
		var outb, errb bytes.Buffer
		cmd.Stdout = &outb
		cmd.Stderr = &errb
	} else {
		cmd.Stdout = am.cmd.Stdout
		cmd.Stderr = am.cmd.Stderr
	}
	am.cmd = cmd

	if err := am.cmd.Start(); err != nil {
		am.t.Fatalf("Starting alertmanager failed: %s", err)
	}

	go func() {
		if err := am.cmd.Wait(); err != nil {
			am.errc <- err
		}
	}()

	time.Sleep(50 * time.Millisecond)
}

// Terminate kills the underlying Alertmanager process and remove intermediate
// data.
func (am *Alertmanager) Terminate() {
	syscall.Kill(am.cmd.Process.Pid, syscall.SIGTERM)
}

// Reload sends the reloading signal to the Alertmanager process.
func (am *Alertmanager) Reload() {
	syscall.Kill(am.cmd.Process.Pid, syscall.SIGHUP)
}

func (am *Alertmanager) cleanup() {
	os.RemoveAll(am.confFile.Name())
}

// Push declares alerts that are to be pushed to the Alertmanager
// server at a relative point in time.
func (am *Alertmanager) Push(at float64, alerts ...*TestAlert) {
	var nas model.Alerts
	for _, a := range alerts {
		nas = append(nas, a.nativeAlert(am.opts))
	}

	alertAPI := alertmanager.NewAlertAPI(am.client)

	am.t.Do(at, func() {
		if err := alertAPI.Push(context.Background(), nas...); err != nil {
			am.t.Errorf("Error pushing %v: %s", nas, err)
		}
	})
}

// SetSilence updates or creates the given Silence.
func (am *Alertmanager) SetSilence(at float64, sil *TestSilence) {
	am.t.Do(at, func() {
		var buf bytes.Buffer
		if err := json.NewEncoder(&buf).Encode(sil.nativeSilence(am.opts)); err != nil {
			am.t.Errorf("Error setting silence %v: %s", sil, err)
			return
		}

		resp, err := http.Post(fmt.Sprintf("http://%s/api/v1/silences", am.addr), "application/json", &buf)
		if err != nil {
			am.t.Errorf("Error setting silence %v: %s", sil, err)
			return
		}
		defer resp.Body.Close()

		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}

		var v struct {
			Status string `json:"status"`
			Data   struct {
				SilenceID string `json:"silenceId"`
			} `json:"data"`
		}
		if err := json.Unmarshal(b, &v); err != nil || resp.StatusCode/100 != 2 {
			am.t.Errorf("error setting silence %v: %s", sil, err)
			return
		}
		sil.ID = v.Data.SilenceID
	})
}

// DelSilence deletes the silence with the sid at the given time.
func (am *Alertmanager) DelSilence(at float64, sil *TestSilence) {
	am.t.Do(at, func() {
		req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%s/api/v1/silence/%s", am.addr, sil.ID), nil)
		if err != nil {
			am.t.Errorf("Error deleting silence %v: %s", sil, err)
			return
		}

		resp, err := http.DefaultClient.Do(req)
		if err != nil || resp.StatusCode/100 != 2 {
			am.t.Errorf("Error deleting silence %v: %s", sil, err)
			return
		}
	})
}

// UpdateConfig rewrites the configuration file for the Alertmanager. It does not
// initiate config reloading.
func (am *Alertmanager) UpdateConfig(conf string) {
	if _, err := am.confFile.WriteString(conf); err != nil {
		am.t.Fatal(err)
		return
	}
	if err := am.confFile.Sync(); err != nil {
		am.t.Fatal(err)
		return
	}
}


text:
<!DOCTYPE html>

    <title>WebStorage Test: Storage_example_insurance_on_trip</title>
    <link rel="author" title="Intel" href="http://www.intel.com" />
    <link rel="help" href="http://www.w3.org/TR/2011/CR-webstorage-20111208/" />
    <meta name="flags" content="interact" />
    <meta name="assert" content="Check if the user had been insurance on this trip" />

      Step 1. Check if the page show "you had not been insurance on this trip" when you first access it.

      Step 2. Check the checkbox, click the 'Run' button to refresh the page, and then check if the page show "you had been insurance on this trip".

      Test passes if the above two steps are all true.

<input id="test_checkbox" type="checkbox" onchange="sessionStorage.insurance = checked ? true : false">
        I want insurance on this trip.


text:
function quickElement() {
    'use strict';
    var obj = document.createElement(arguments[0]);
    if (arguments[2]) {
        var textNode = document.createTextNode(arguments[2]);
        obj.appendChild(textNode);
    }
    var len = arguments.length;
    for (var i = 3; i < len; i += 2) {
        obj.setAttribute(arguments[i], arguments[i + 1]);
    }
    arguments[1].appendChild(obj);
    return obj;
}

// "a" is reference to an object
function removeChildren(a) {
    'use strict';
    while (a.hasChildNodes()) {
        a.removeChild(a.lastChild);
    }
}

// ----------------------------------------------------------------------------
// Find-position functions by PPK
// See https://www.quirksmode.org/js/findpos.html
// ----------------------------------------------------------------------------
function findPosX(obj) {
    'use strict';
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft - obj.scrollLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    'use strict';
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop - obj.scrollTop;
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

//-----------------------------------------------------------------------------
// Date object extensions
// ----------------------------------------------------------------------------
(function() {
    'use strict';
    Date.prototype.getTwelveHours = function() {
        return this.getHours() % 12 || 12;
    };

    Date.prototype.getTwoDigitMonth = function() {
        return (this.getMonth() < 9) ? '0' + (this.getMonth() + 1) : (this.getMonth() + 1);
    };

    Date.prototype.getTwoDigitDate = function() {
        return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate();
    };

    Date.prototype.getTwoDigitTwelveHour = function() {
        return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours();
    };

    Date.prototype.getTwoDigitHour = function() {
        return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours();
    };

    Date.prototype.getTwoDigitMinute = function() {
        return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes();
    };

    Date.prototype.getTwoDigitSecond = function() {
        return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds();
    };

    Date.prototype.getFullMonthName = function() {
        return typeof window.CalendarNamespace === "undefined"
            ? this.getTwoDigitMonth()
            : window.CalendarNamespace.monthsOfYear[this.getMonth()];
    };

    Date.prototype.strftime = function(format) {
        var fields = {
            B: this.getFullMonthName(),
            c: this.toString(),
            d: this.getTwoDigitDate(),
            H: this.getTwoDigitHour(),
            I: this.getTwoDigitTwelveHour(),
            m: this.getTwoDigitMonth(),
            M: this.getTwoDigitMinute(),
            p: (this.getHours() >= 12) ? 'PM' : 'AM',
            S: this.getTwoDigitSecond(),
            w: '0' + this.getDay(),
            x: this.toLocaleDateString(),
            X: this.toLocaleTimeString(),
            y: ('' + this.getFullYear()).substr(2, 4),
            Y: '' + this.getFullYear(),
            '%': '%'
        };
        var result = '', i = 0;
        while (i < format.length) {
            if (format.charAt(i) === '%') {
                result = result + fields[format.charAt(i + 1)];
                ++i;
            }
            else {
                result = result + format.charAt(i);
            }
            ++i;
        }
        return result;
    };

    // ----------------------------------------------------------------------------
    // String object extensions
    // ----------------------------------------------------------------------------
    String.prototype.strptime = function(format) {
        var split_format = format.split(/[.\-/]/);
        var date = this.split(/[.\-/]/);
        var i = 0;
        var day, month, year;
        while (i < split_format.length) {
            switch (split_format[i]) {
            case "%d":
                day = date[i];
                break;
            case "%m":
                month = date[i] - 1;
                break;
            case "%Y":
                year = date[i];
                break;
            case "%y":
                // A %y value in the range of [00, 68] is in the current
                // century, while [69, 99] is in the previous century,
                // according to the Open Group Specification.
                if (parseInt(date[i], 10) >= 69) {
                    year = date[i];
                } else {
                    year = (new Date(Date.UTC(date[i], 0))).getUTCFullYear() + 100;
                }
                break;
            }
            ++i;
        }
        // Create Date object from UTC since the parsed value is supposed to be
        // in UTC, not local time. Also, the calendar uses UTC functions for
        // date extraction.
        return new Date(Date.UTC(year, month, day));
    };

})();


text:
package streamhelper

import (
	"encoding/hex"
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/google/btree"
	"github.com/pingcap/errors"
	berrors "github.com/pingcap/tidb/br/pkg/errors"
	"github.com/pingcap/tidb/br/pkg/logutil"
	"github.com/pingcap/tidb/br/pkg/redact"
	"github.com/pingcap/tidb/kv"
	"github.com/tikv/client-go/v2/oracle"
	"go.uber.org/zap/zapcore"
)

// CheckpointsCache is the heap-like cache for checkpoints.
//
// "Checkpoint" is the "Resolved TS" of some range.
// A resolved ts is a "watermark" for the system, which:
//   - implies there won't be any transactions (in some range) commit with `commit_ts` smaller than this TS.
//   - is monotonic increasing.
// A "checkpoint" is a "safe" Resolved TS, which:
//   - is a TS *less than* the real resolved ts of now.
//   - is based on range (it only promises there won't be new committed txns in the range).
//   - the checkpoint of union of ranges is the minimal checkpoint of all ranges.
// As an example:
// +----------------------------------+
// ^-----------^ (Checkpoint = 42)
//         ^---------------^ (Checkpoint = 76)
// ^-----------------------^ (Checkpoint = min(42, 76) = 42)
//
// For calculating the global checkpoint, we can make a heap-like structure:
// Checkpoint    Ranges
// 42         -> {[0, 8], [16, 100]}
// 1002       -> {[8, 16]}
// 1082       -> {[100, inf]}
// For now, the checkpoint of range [8, 16] and [100, inf] won't affect the global checkpoint
// directly, so we can try to advance only the ranges of {[0, 8], [16, 100]} (which's checkpoint is steal).
// Once them get advance, the global checkpoint would be advanced then,
// and we don't need to update all ranges (because some new ranges don't need to be advanced so quickly.)
type CheckpointsCache interface {
	fmt.Stringer
	// InsertRange inserts a range with specified TS to the cache.
	InsertRange(ts uint64, rng kv.KeyRange)
	// InsertRanges inserts a set of ranges that sharing checkpoint to the cache.
	InsertRanges(rst RangesSharesTS)
	// CheckpointTS returns the now global (union of all ranges) checkpoint of the cache.
	CheckpointTS() uint64
	// PopRangesWithGapGT pops the ranges which's checkpoint is
	PopRangesWithGapGT(d time.Duration) []*RangesSharesTS
	// Check whether the ranges in the cache is integrate.
	ConsistencyCheck() error
	// Clear the cache.
	Clear()
}

// NoOPCheckpointCache is used when cache disabled.
type NoOPCheckpointCache struct{}

func (NoOPCheckpointCache) InsertRange(ts uint64, rng kv.KeyRange) {}

func (NoOPCheckpointCache) InsertRanges(rst RangesSharesTS) {}

func (NoOPCheckpointCache) Clear() {}

func (NoOPCheckpointCache) String() string {
	return "NoOPCheckpointCache"
}

func (NoOPCheckpointCache) CheckpointTS() uint64 {
	panic("invalid state: NoOPCheckpointCache should never be used in advancing!")
}

func (NoOPCheckpointCache) PopRangesWithGapGT(d time.Duration) []*RangesSharesTS {
	panic("invalid state: NoOPCheckpointCache should never be used in advancing!")
}

func (NoOPCheckpointCache) ConsistencyCheck() error {
	return errors.Annotatef(berrors.ErrUnsupportedOperation, "invalid state: NoOPCheckpointCache should never be used in advancing!")
}

// RangesSharesTS is a set of ranges shares the same timestamp.
type RangesSharesTS struct {
	TS     uint64
	Ranges []kv.KeyRange
}

func (rst *RangesSharesTS) Zap() zapcore.ObjectMarshaler {
	return zapcore.ObjectMarshalerFunc(func(oe zapcore.ObjectEncoder) error {
		rngs := rst.Ranges
		if len(rst.Ranges) > 3 {
			rngs = rst.Ranges[:3]
		}

		oe.AddUint64("checkpoint", rst.TS)
		return oe.AddArray("items", zapcore.ArrayMarshalerFunc(func(ae zapcore.ArrayEncoder) error {
			return ae.AppendObject(zapcore.ObjectMarshalerFunc(func(oe1 zapcore.ObjectEncoder) error {
				for _, rng := range rngs {
					oe1.AddString("start-key", redact.String(hex.EncodeToString(rng.StartKey)))
					oe1.AddString("end-key", redact.String(hex.EncodeToString(rng.EndKey)))
				}
				return nil
			}))
		}))
	})
}

func (rst *RangesSharesTS) String() string {
	// Make a more friendly string.
	return fmt.Sprintf("@%sR%d", oracle.GetTimeFromTS(rst.TS).Format("0405"), len(rst.Ranges))
}

func (rst *RangesSharesTS) Less(other btree.Item) bool {
	return rst.TS < other.(*RangesSharesTS).TS
}

// Checkpoints is a heap that collects all checkpoints of
// regions, it supports query the latest checkpoint fast.
// This structure is thread safe.
type Checkpoints struct {
	tree *btree.BTree

	mu sync.Mutex
}

func NewCheckpoints() *Checkpoints {
	return &Checkpoints{
		tree: btree.New(32),
	}
}

// String formats the slowest 5 ranges sharing TS to string.
func (h *Checkpoints) String() string {
	h.mu.Lock()
	defer h.mu.Unlock()

	b := new(strings.Builder)
	count := 0
	total := h.tree.Len()
	h.tree.Ascend(func(i btree.Item) bool {
		rst := i.(*RangesSharesTS)
		b.WriteString(rst.String())
		b.WriteString(";")
		count++
		return count < 5
	})
	if total-count > 0 {
		fmt.Fprintf(b, "O%d", total-count)
	}
	return b.String()
}

// InsertRanges insert a RangesSharesTS directly to the tree.
func (h *Checkpoints) InsertRanges(r RangesSharesTS) {
	h.mu.Lock()
	defer h.mu.Unlock()
	if items := h.tree.Get(&r); items != nil {
		i := items.(*RangesSharesTS)
		i.Ranges = append(i.Ranges, r.Ranges...)
	} else {
		h.tree.ReplaceOrInsert(&r)
	}
}

// InsertRange inserts the region and its TS into the region tree.
func (h *Checkpoints) InsertRange(ts uint64, rng kv.KeyRange) {
	h.mu.Lock()
	defer h.mu.Unlock()
	r := h.tree.Get(&RangesSharesTS{TS: ts})
	if r == nil {
		r = &RangesSharesTS{TS: ts}
		h.tree.ReplaceOrInsert(r)
	}
	rr := r.(*RangesSharesTS)
	rr.Ranges = append(rr.Ranges, rng)
}

// Clear removes all records in the checkpoint cache.
func (h *Checkpoints) Clear() {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.tree.Clear(false)
}

// PopRangesWithGapGT pops ranges with gap greater than the specified duration.
// NOTE: maybe make something like `DrainIterator` for better composing?
func (h *Checkpoints) PopRangesWithGapGT(d time.Duration) []*RangesSharesTS {
	h.mu.Lock()
	defer h.mu.Unlock()
	result := []*RangesSharesTS{}
	for {
		item, ok := h.tree.Min().(*RangesSharesTS)
		if !ok {
			return result
		}
		if time.Since(oracle.GetTimeFromTS(item.TS)) >= d {
			result = append(result, item)
			h.tree.DeleteMin()
		} else {
			return result
		}
	}
}

// CheckpointTS returns the cached checkpoint TS by the current state of the cache.
func (h *Checkpoints) CheckpointTS() uint64 {
	h.mu.Lock()
	defer h.mu.Unlock()
	item, ok := h.tree.Min().(*RangesSharesTS)
	if !ok {
		return 0
	}
	return item.TS
}

// ConsistencyCheck checks whether the tree contains the full range of key space.
// TODO: add argument to it and check a sub range.
func (h *Checkpoints) ConsistencyCheck() error {
	h.mu.Lock()
	ranges := make([]kv.KeyRange, 0, 1024)
	h.tree.Ascend(func(i btree.Item) bool {
		ranges = append(ranges, i.(*RangesSharesTS).Ranges...)
		return true
	})
	h.mu.Unlock()

	r := CollapseRanges(len(ranges), func(i int) kv.KeyRange { return ranges[i] })
	if len(r) != 1 || len(r[0].StartKey) != 0 || len(r[0].EndKey) != 0 {
		return errors.Annotatef(berrors.ErrPiTRMalformedMetadata,
			"the region tree cannot cover the key space, collapsed: %s", logutil.StringifyKeys(r))
	}
	return nil
}