text:
- [Issues and Bugs](#issue)
 - [Feature Requests](#feature)
 - [Submission Guidelines](#submit)
 - [Signing the CLA](#cla)

##  Found a Bug?
If you find a bug in the source code, you can help us by
[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.

##  Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
Please consider what kind of change it is:

* For a **Major Feature**, first open an issue and outline your proposal so that it can be
discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
and help you to craft the change so that it is successfully accepted into the project.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).

##  Submission Guidelines

###  Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:

* Search [GitHub](https://github.com/agneta/platform/pulls) for an open or closed PR
  that relates to your submission. You don't want to duplicate effort.
* Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
  We cannot accept code without this.
* Make your changes in a new git branch:

     ```shell
     git checkout -b my-fix-branch master
     ```

* Create your patch, **including appropriate test cases**.
* Commit your changes using a descriptive commit message.

     ```shell
     git commit -a
     ```
  Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.

* Push your branch to GitHub:

    ```shell
    git push origin my-fix-branch
    ```

* In GitHub, send a pull request to `agneta/platform:master`.
* If we suggest changes then:
  * Make the required updates.
  * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):

    ```shell
    git rebase master -i
    git push -f
    ```

That's it! Thank you for your contribution!

#### After your pull request is merged

After your pull request is merged, you can safely delete your branch and pull the changes
from the main (upstream) repository:

* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:

    ```shell
    git push origin --delete my-fix-branch
    ```

* Check out the master branch:

    ```shell
    git checkout master -f
    ```

* Delete the local branch:

    ```shell
    git branch -D my-fix-branch
    ```

* Update your master with the latest upstream version:

    ```shell
    git pull --ff upstream master
    ```

##  Signing the CLA

Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code
changes to be accepted, the CLA must be signed. It's a quick process, we promise!

* For individuals we have a [simple click-through form][individual-cla].

[github]: https://github.com/agneta/platform
[individual-cla]: https://cla-assistant.io/agneta/platform


text:
Changelog
=========

 - [[`v1.0.2`](https://github.com/VeliovGroup/Meteor-iron-router-protected/releases/tag/v1.0.2)] 08/11/2015
    * Fix not protected routes was blocked by protected in `configure()` method
    * Use faster `switch` instead of `if/else` statement
 - [[`v1.0.1`](https://github.com/VeliovGroup/Meteor-iron-router-protected/releases/tag/v1.0.1)] 05/28/2015
    * Protect and restrict all routes in `Router.configure()` via `protected` and `allowAccess` properties
 - [`v1.0.0`] Initial, please see docs

redpajama_set_name: RedPajamaGithub


text:
//
// XMLExamplesTest.java -- Java class XMLExamplesTest
// Project OrcTests
//
// Copyright (c) 2019 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.test.proc;

import java.lang.reflect.Field;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import orc.ast.oil.nameless.Expression;
import orc.ast.oil.xml.OrcXML;
import orc.script.OrcBindings;
import orc.script.OrcScriptEngine;
import orc.test.item.OrcForTesting;
import orc.test.util.ExpectedOutput;
import orc.test.util.TestUtils;
import orc.test.util.TestUtils.OrcTestCase;

import junit.framework.Test;
import org.xml.sax.SAXException;

/**
 * Test Orc by running annotated sample programs from the "../OrcExamples"
 * directory. Each program is compiled, written to XML, subjected to validation
 * against an XML schema, and then read back as an AST. This second AST is run.
 * Each program is given at most TestUtils.OrcTestCase.TESTING_TIMEOUT seconds
 * to complete.
 *

 * We look for one or more comment blocks formatted per
 * ExampleOutput's specs.
 *
 * @see ExpectedOutput
 * @author quark, srosario, amshali, dkitchin, jthywiss
 */
public class XMLExamplesTest {
    public static Test suite() {
        return TestUtils.buildSuite(XMLExamplesTest.class.getSimpleName(), (s, t, f, e, b) -> new XMLExamplesTestCase(s, t, f, e, b), new OrcBindings(), Paths.get("test_data"), Paths.get("../OrcExamples"));
    }

    public static class XMLExamplesTestCase extends OrcTestCase {
        public XMLExamplesTestCase(final String suiteName1, final String testName, final Path orcFile1, final ExpectedOutput expecteds1, final OrcBindings bindings1) {
            super(suiteName1, testName, orcFile1, expecteds1, bindings1);
        }

        @Override
        public void runTest() throws Throwable {
            System.out.println("\n==== Starting " + orcFile + " ====");
            final OrcScriptEngine<Object>.OrcCompiledScript compiledScript = OrcForTesting.compile(orcFile.toString(), bindings);
            final Expression expr = getAstRoot(compiledScript);

            // AST -> XML
            final scala.xml.Elem xmlFromExpr = OrcXML.astToXml(expr);

            // Locate .xsd file resource
            final ClassLoader clX = Thread.currentThread().getContextClassLoader();
            final ClassLoader clY = getClass().getClassLoader();
            final ClassLoader clZ = ClassLoader.getSystemClassLoader();
            final ClassLoader classLoader = clX != null ? clX : clY != null ? clY : clZ;
            final java.io.InputStream xsdStream = classLoader.getResource("orc/ast/oil/xml/oil.xsd").openStream();

            // Schema validation
            try {
                final SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
                final Schema schema = schemaFactory.newSchema(new StreamSource(xsdStream));
                final Validator validator = schema.newValidator();
                final StreamSource xmlsource = new StreamSource(new java.io.StringReader(xmlFromExpr.toString()));
                validator.validate(xmlsource);
            } catch (final SAXException e) {
                throw new AssertionError("XML validation failed: " + e.getMessage());
            }

            // XML -> AST
            final Expression exprFromXml = OrcXML.xmlToAst(xmlFromExpr);

            // Execution
            setAstRoot(compiledScript, exprFromXml);
            final String actual = OrcForTesting.run(compiledScript, TESTING_TIMEOUT);
            if (!expecteds.contains(actual)) {
                throw new AssertionError("Unexpected output:\n" + actual);
            }
        }
    }

    static Expression getAstRoot(final OrcScriptEngine<Object>.OrcCompiledScript compiledScript) throws SecurityException, NoSuchFieldException, IllegalAccessException {
        // Violate access controls of OrcCompiledScript.astRoot field
        final Field codeField = compiledScript.getClass().getDeclaredField("code");
        codeField.setAccessible(true);
        return (Expression) codeField.get(compiledScript);
    }

    static void setAstRoot(final OrcScriptEngine<Object>.OrcCompiledScript compiledScript, final Expression astRoot) throws SecurityException, NoSuchFieldException, IllegalAccessException {
        // Violate access controls of OrcCompiledScript.astRoot field
        final Field codeField = compiledScript.getClass().getDeclaredField("code");
        codeField.setAccessible(true);
        codeField.set(compiledScript, astRoot);
    }

}


text:
<!doctype html>

<meta charset="utf-8">
<link href="layout.css" charset="utf-8" type="text/css" rel="stylesheet"></link>
<title>SDL_SetCursor</title>

SDL_SetCursor

Use this function to set the active cursor.

Syntax

void SDL_SetCursor(SDL_Cursor* cursor)

Function Parameters

cursor	a cursor to make active  (Should this be linked to Remarks?)

Code Examples

*

int main(int argc, char** argv) {
     SDL_ShowCursor(SDL_DISABLE);
     ...
}
/* creates a blank cursor */

Remarks

*

This function sets the currently active cursor to the specified one. If the cursor is currently visible, the change will be immediately represented on the display. SDL_SetCursor(NULL) can be used to force cursor redraw, if this is desired for any reason.

*

Related Functions

SDL_CreateCursor *

SDL_GetCursor *

SDL_ShowCursor *


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Web;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.template;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.macro;
using Umbraco.Core.IO;

namespace umbraco.cms.businesslogic.packager
{
    public class CreatedPackage
    {

        public static CreatedPackage GetById(int id)
        {
            var pack = new CreatedPackage();
            pack.Data = data.Package(id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
            return pack;
        }

        public static CreatedPackage MakeNew(string name)
        {
            var pack = new CreatedPackage();
            pack.Data = data.MakeNew(name, IOHelper.MapPath(Settings.CreatedPackagesSettings));

            var e = new NewEventArgs();
            pack.OnNew(e);

            return pack;
        }

        public void Save()
        {
            var e = new SaveEventArgs();
            FireBeforeSave(e);

            if (!e.Cancel)
            {
                data.Save(this.Data, IOHelper.MapPath(Settings.CreatedPackagesSettings));
                FireAfterSave(e);
            }
        }

        public void Delete()
        {
            var e = new DeleteEventArgs();
            FireBeforeDelete(e);

            if (!e.Cancel)
            {
                data.Delete(this.Data.Id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
                FireAfterDelete(e);
            }
        }

        public PackageInstance Data { get; set; }

        public static List<CreatedPackage> GetAllCreatedPackages()
        {
            var val = new List<CreatedPackage>();

            foreach (var pack in data.GetAllPackages(IOHelper.MapPath(Settings.CreatedPackagesSettings)))
            {
                var crPack = new CreatedPackage();
                crPack.Data = pack;
                val.Add(crPack);
            }

            return val;
        }

        private static XmlDocument _packageManifest;
        private static void CreatePackageManifest()
        {
            _packageManifest = new XmlDocument();
            var xmldecl = _packageManifest.CreateXmlDeclaration("1.0", "UTF-8", "no");

            _packageManifest.AppendChild(xmldecl);

            //root node
            XmlNode umbPackage = _packageManifest.CreateElement("umbPackage");
            _packageManifest.AppendChild(umbPackage);
            //Files node
            umbPackage.AppendChild(_packageManifest.CreateElement("files"));
        }

        private static void AppendElement(XmlNode node)
        {
            var root = _packageManifest.SelectSingleNode("/umbPackage");
            root.AppendChild(node);
        }

        public void Publish()
        {

            var package = this;
            var pack = package.Data;

            try
            {

                var e = new PublishEventArgs();
                package.FireBeforePublish(e);

                if (e.Cancel == false)
                {
                    var outInt = 0;

                    //Path checking...
                    var localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder);

                    if (Directory.Exists(localPath) == false)
                        Directory.CreateDirectory(localPath);

                    //Init package file...
                    CreatePackageManifest();
                    //Info section..
                    AppendElement(utill.PackageInfo(pack, _packageManifest));

                    //Documents...
                    var contentNodeId = 0;
                    if (string.IsNullOrEmpty(pack.ContentNodeId) == false && int.TryParse(pack.ContentNodeId, out contentNodeId))
                    {
                        XmlNode documents = _packageManifest.CreateElement("Documents");

                        XmlNode documentSet = _packageManifest.CreateElement("DocumentSet");
                        XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", "");
                        importMode.Value = "root";
                        documentSet.Attributes.Append(importMode);
                        documents.AppendChild(documentSet);

                        //load content from umbraco.
                        var umbDocument = new Document(contentNodeId);
                        documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));

                        AppendElement(documents);
                    }

                    //Document types..
                    var dtl = new List<DocumentType>();
                    var docTypes = _packageManifest.CreateElement("DocumentTypes");
                    foreach (var dtId in pack.Documenttypes)
                    {
                        if (int.TryParse(dtId, out outInt))
                        {
                            DocumentType docT = new DocumentType(outInt);

                            AddDocumentType(docT, ref dtl);

                        }
                    }
                    foreach (DocumentType d in dtl)
                    {
                        docTypes.AppendChild(d.ToXml(_packageManifest));
                    }

                    AppendElement(docTypes);

                    //Templates
                    var templates = _packageManifest.CreateElement("Templates");
                    foreach (var templateId in pack.Templates)
                    {
                        if (int.TryParse(templateId, out outInt))
                        {
                            var t = new Template(outInt);
                            templates.AppendChild(t.ToXml(_packageManifest));
                        }
                    }
                    AppendElement(templates);

                    //Stylesheets
                    var stylesheets = _packageManifest.CreateElement("Stylesheets");
                    foreach (var ssId in pack.Stylesheets)
                    {
                        if (int.TryParse(ssId, out outInt))
                        {
                            var s = new StyleSheet(outInt);
                            stylesheets.AppendChild(s.ToXml(_packageManifest));
                        }
                    }
                    AppendElement(stylesheets);

                    //Macros
                    var macros = _packageManifest.CreateElement("Macros");
                    foreach (var macroId in pack.Macros)
                    {
                        if (int.TryParse(macroId, out outInt))
                        {
                            macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest));
                        }
                    }
                    AppendElement(macros);

                    //Dictionary Items
                    var dictionaryItems = _packageManifest.CreateElement("DictionaryItems");
                    foreach (var dictionaryId in pack.DictionaryItems)
                    {
                        if (int.TryParse(dictionaryId, out outInt))
                        {
                            var di = new Dictionary.DictionaryItem(outInt);
                            dictionaryItems.AppendChild(di.ToXml(_packageManifest));
                        }
                    }
                    AppendElement(dictionaryItems);

                    //Languages
                    var languages = _packageManifest.CreateElement("Languages");
                    foreach (var langId in pack.Languages)
                    {
                        if (int.TryParse(langId, out outInt))
                        {
                            var lang = new language.Language(outInt);

                            languages.AppendChild(lang.ToXml(_packageManifest));
                        }
                    }
                    AppendElement(languages);

                    //Datatypes
                    var dataTypes = _packageManifest.CreateElement("DataTypes");
                    foreach (var dtId in pack.DataTypes)
                    {
                        if (int.TryParse(dtId, out outInt))
                        {
                            datatype.DataTypeDefinition dtd = new datatype.DataTypeDefinition(outInt);
                            dataTypes.AppendChild(dtd.ToXml(_packageManifest));
                        }
                    }
                    AppendElement(dataTypes);

                    //Files
                    foreach (var fileName in pack.Files)
                    {
                        utill.AppendFileToManifest(fileName, localPath, _packageManifest);
                    }

                    //Load control on install...
                    if (string.IsNullOrEmpty(pack.LoadControl) == false)
                    {
                        XmlNode control = _packageManifest.CreateElement("control");
                        control.InnerText = pack.LoadControl;
                        utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest);
                        AppendElement(control);
                    }

                    //Actions
                    if (string.IsNullOrEmpty(pack.Actions) == false)
                    {
                        try
                        {
                            var xdActions = new XmlDocument();
                            xdActions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
                            var actions = xdActions.DocumentElement.SelectSingleNode(".");

                            if (actions != null)
                            {
                                actions = _packageManifest.ImportNode(actions, true).Clone();
                                AppendElement(actions);
                            }
                        }
                        catch { }
                    }

                    var manifestFileName = localPath + "/package.xml";

                    if (File.Exists(manifestFileName))
                        File.Delete(manifestFileName);

                    _packageManifest.Save(manifestFileName);
                    _packageManifest = null;

                    //string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension;

                    // check if there's a packages directory below media
                    var packagesDirectory = SystemDirectories.Media + "/created-packages";
                    if (Directory.Exists(IOHelper.MapPath(packagesDirectory)) == false)
                    {
                        Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));
                    }

                    var packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension;
                    utill.ZipPackage(localPath, IOHelper.MapPath(packPath));

                    pack.PackagePath = packPath;

                    if (pack.PackageGuid.Trim() == "")
                        pack.PackageGuid = Guid.NewGuid().ToString();

                    package.Save();

                    //Clean up..
                    File.Delete(localPath + "/package.xml");
                    Directory.Delete(localPath, true);

                    package.FireAfterPublish(e);
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error<CreatedPackage>("An error occurred", ex);
            }
        }

        private void AddDocumentType(DocumentType dt, ref List<DocumentType> dtl)
        {
            if (dt.MasterContentType != 0)
            {
                //first add masters
                var mDocT = new DocumentType(dt.MasterContentType);

                AddDocumentType(mDocT, ref dtl);

            }

            if (dtl.Contains(dt) == false)
            {
                dtl.Add(dt);
            }
        }

        //EVENTS
        public delegate void SaveEventHandler(CreatedPackage sender, SaveEventArgs e);
        public delegate void NewEventHandler(CreatedPackage sender, NewEventArgs e);
        public delegate void PublishEventHandler(CreatedPackage sender, PublishEventArgs e);
        public delegate void DeleteEventHandler(CreatedPackage sender, DeleteEventArgs e);

        /// <summary>
        /// Occurs when a macro is saved.
        /// </summary>
        public static event SaveEventHandler BeforeSave;
        protected virtual void FireBeforeSave(SaveEventArgs e)
        {
            if (BeforeSave != null)
                BeforeSave(this, e);
        }

        public static event SaveEventHandler AfterSave;
        protected virtual void FireAfterSave(SaveEventArgs e)
        {
            if (AfterSave != null)
                AfterSave(this, e);
        }

        public static event NewEventHandler New;
        protected virtual void OnNew(NewEventArgs e)
        {
            if (New != null)
                New(this, e);
        }

        public static event DeleteEventHandler BeforeDelete;
        protected virtual void FireBeforeDelete(DeleteEventArgs e)
        {
            if (BeforeDelete != null)
                BeforeDelete(this, e);
        }

        public static event DeleteEventHandler AfterDelete;
        protected virtual void FireAfterDelete(DeleteEventArgs e)
        {
            if (AfterDelete != null)
                AfterDelete(this, e);
        }

        public static event PublishEventHandler BeforePublish;
        protected virtual void FireBeforePublish(PublishEventArgs e)
        {
            if (BeforePublish != null)
                BeforePublish(this, e);
        }

        public static event PublishEventHandler AfterPublish;
        protected virtual void FireAfterPublish(PublishEventArgs e)
        {
            if (AfterPublish != null)
                AfterPublish(this, e);
        }

    }
}


text:
typedef uint32_t uint32;
typedef unsigned long long ulong64;
typedef unsigned char byte;

typedef std::array<byte, KVDB_KEY_SIZE> TKeyData;
typedef std::vector<byte> TValueData;
typedef std::shared_ptr<TValueData> TValueDataPtr;

//============================================================================
// Key data hash
//============================================================================
namespace std {
	template <>
	struct hash<TKeyData> {
		std::size_t operator()(const TKeyData& keyData) const {
			std::size_t h = 0;
			for (auto elem : keyData) {
				h ^= std::hash<int>{}(elem)+0x9e3779b9 + (h << 6) + (h >> 2);
			}
			return h;
		}
	};
}

namespace kvdb {

	//============================================================================
	// Base IO
	//============================================================================
	template <typename T>
	void write(std::ostream* os, const T& obj) {
		if (os != nullptr) {
			os->write((char*)&obj, sizeof(obj));
		}
	}

	template <typename T>
	void read(std::istream* is, const T& obj) {
		if (is != nullptr) {
			is->read((char*)&obj, sizeof(obj));
		}
	}

	//============================================================================
	// File position
	//============================================================================
	template <typename T>
	class TPosWrapper {

	private:
		T objT;

	public:
		ulong64 pos;

		TPosWrapper() {};
		TPosWrapper(T t, ulong64 p) : objT(t), pos(p) {};
		const T& operator()() const { return objT; }
		T& operator()() { return objT; }
		T* operator->() { return &objT; }
	};

	//============================================================================
	// File header
	//============================================================================
	typedef struct TFileHeader {
		uint32 version = 1;
		uint32 keySize = 0;
		ulong64 timestamp = 0;
		uint32  endOfHeaderOffset = 0;
	} TFileHeader;

	inline std::ostream* operator << (std::ostream* os, const TFileHeader& obj) {
		write(os, obj);
		return os;
	}

	inline std::istream* operator >> (std::istream* is, TFileHeader& obj) {
		read(is, obj);
		return is;
	}

	//============================================================================
	// Table header
	//============================================================================
	typedef struct TTableHeader {
		ulong64 recordCount = 0;
		ulong64 nextTable = 0;
	} TTableHeader;

	typedef TPosWrapper<TTableHeader> TTableHeaderInfo;

	inline std::ostream* operator << (std::ostream* os, const TTableHeader& obj) {
		write(os, obj);
		return os;
	}

	inline std::istream* operator >> (std::istream* is, TTableHeader& obj) {
		read(is, obj);
		return is;
	}

	//============================================================================
	// Key Entry
	//============================================================================
	typedef struct TKeyEntry {
		ulong64 dataPos = 0;
		ulong64 dataLength = 0;
		ulong64 initialDataLength = 0;

		TKeyData freeKeyData;
	} TKeyEntry;

	typedef TPosWrapper<TKeyEntry> TKeyEntryInfo;

	struct TKeyInfoComparatorByInitialLength {
		bool operator() (const TKeyEntryInfo& lhs, const TKeyEntryInfo& rhs) const {
			return (lhs().initialDataLength > rhs().initialDataLength);
		}
	};

	inline std::ostream* operator << (std::ostream* os, const TKeyEntry& obj) {
		write(os, obj);
		return os;
	}

	inline std::ostream* operator << (std::ostream* os, const TKeyEntryInfo& objInfo) {
		os->seekp(objInfo.pos);
		os << objInfo();
		return os;
	}

	inline std::istream* operator >> (std::istream* is, TKeyEntry& obj) {
		read(is, obj);
		return is;
	}

	//============================================================================
	// File db
	//============================================================================
	template <typename K, typename V>
	class KvFile {

	private:

		std::unordered_map<TKeyData, TKeyEntryInfo> dataMap;
		std::fstream* filePtr = nullptr;
		std::list<TKeyEntryInfo> reservedKeyList;
		std::set<TKeyEntryInfo, TKeyInfoComparatorByInitialLength> deletedKeyList;
		std::list<TTableHeaderInfo> tableList;
		mutable std::mutex fileSharedMutex;

		uint32 reservedKeys = KVDB_RESERVED_TABLE_SIZE;
		uint32 reservedValueSize = 0;

	private:

		std::shared_ptr<V> valueFromData(TValueDataPtr dataPtr) {
			if (dataPtr == nullptr) return nullptr;

			if constexpr (std::is_same<V, TValueData>::value) { //constexpr
				return std::static_pointer_cast<TValueData>(dataPtr);
			} else {
				V* temp = new V();
				memcpy(temp, dataPtr->data(), dataPtr->size());
				return std::shared_ptr<V>(temp);
			}
		}

		static TKeyData toKeyData(K key) {
			byte temp[KVDB_KEY_SIZE];
			for (int i = 0; i < KVDB_KEY_SIZE; i++) temp[i] = 0;

			memcpy(&temp, &key, sizeof(K));

			TKeyData arrayOfByte;
			for (int i = 0; i < KVDB_KEY_SIZE; i++) arrayOfByte[i] = temp[i];

			return arrayOfByte;
		}

		static void toValueData(V value, TValueData& valueData) {
			if (valueData.size() < sizeof(value)) valueData.resize(sizeof(value));
			std::memcpy(valueData.data(), &value, sizeof(value));
		}

		void rewritePair(TKeyEntryInfo& keyInfo, const TValueData& valueData) {
			// rewrite value data
			filePtr->seekp(keyInfo().dataPos);
			filePtr->write((char*)valueData.data(), valueData.size());

			// rewrite key data
			keyInfo().dataLength = valueData.size(); // new length
			filePtr << keyInfo;
		}

		void earsePair(TKeyEntryInfo& keyInfo) {
			// rewrite key data
			keyInfo().dataLength = 0; // new length
			filePtr << keyInfo;

			deletedKeyList.insert(keyInfo);
			dataMap.erase(keyInfo().freeKeyData);
		}

		void expandValueData(const TValueData& valueDataSrc, TValueData& valueDataNew) {
			valueDataNew.resize(reservedValueSize);
			for (uint32 i = 0; i < reservedValueSize; i++) {
				if (i < valueDataSrc.size()) {
					valueDataNew[i] = valueDataSrc[i];
				} else {
					valueDataNew[i] = 0;
				}
			}
		}

		void newPairFromReserved(const TKeyData& keyData, const TValueData& valueData) {
			// has reserved key slots
			TKeyEntryInfo& keyInfo = reservedKeyList.front();
			TValueData valueDataExp;

			if (valueData.size() < reservedValueSize) {
				expandValueData(valueData, valueDataExp);
			} else {
				valueDataExp = std::move(valueData);
			}

			filePtr->seekp(0, std::ios::end); // to end-of-file
			ulong64 endFile = (ulong64)(filePtr->tellp());
			filePtr->write((char*)valueDataExp.data(), valueDataExp.size());

			// fill key data
			keyInfo().dataLength = valueData.size(); // length
			keyInfo().initialDataLength = valueDataExp.size(); // length
			keyInfo().dataPos = endFile;
			keyInfo().freeKeyData = keyData;
			filePtr << keyInfo;

			// add new pair to table
			dataMap.insert({ keyInfo().freeKeyData, keyInfo });
			reservedKeyList.pop_front();
		}

		ulong64 readTable() {
			ulong64 tablePos = (ulong64)filePtr->tellg();

			TTableHeader tableHeader;
			filePtr >> tableHeader;

			for (unsigned int i = 0; i < tableHeader.recordCount; i++) {
				ulong64 pos = (ulong64)filePtr->tellg();

				TKeyEntry keyEntry;
				filePtr >> keyEntry;
				TKeyEntryInfo keyInfo(keyEntry, pos);

				if (keyInfo().dataLength > 0) {
					dataMap.insert({ keyEntry.freeKeyData, keyInfo });
				} else {
					if (keyInfo().initialDataLength == 0) {
						// reserved key slot
						reservedKeyList.push_back(keyInfo);
					} else {
						// marked as deleted pair
						deletedKeyList.insert(keyInfo);
					}
				}
			}

			tableList.push_back(TTableHeaderInfo(tableHeader, tablePos));
			return tableHeader.nextTable;
		}

		void createNewTable() {
			filePtr->seekp(0, std::ios::end); // to end-of-file
			ulong64 newTablePos = (ulong64)filePtr->tellp();

			// write new table
			TTableHeader newTable;
			newTable.recordCount = reservedKeys;
			newTable.nextTable = 0;
			filePtr << newTable;

			// write reserved keys
			for (uint32 i = 0; i < reservedKeys; i++) {
				uint32 newReservedKeyPos = (uint32)filePtr->tellp();

				TKeyEntry newReservedKey;
				filePtr << newReservedKey;

				TKeyEntryInfo keyInfo(newReservedKey, newReservedKeyPos);
				reservedKeyList.push_back(keyInfo);
			}

			// read previous last table
			TTableHeaderInfo& lastTable = tableList.back();

			// add link to new table
			lastTable().nextTable = newTablePos;

			// rewrite previous last table
			filePtr->seekp(lastTable.pos);
			filePtr << lastTable();

			// add new table to internal list
			tableList.push_back(TTableHeaderInfo(newTable, newTablePos));
		}

		bool hasReserved() {
			return reservedKeyList.size() > 0;
		}

		bool tryWriteToSuitableDeletedPair(const TKeyData& keyData, const TValueData& valueData) {
			for (auto itr = deletedKeyList.begin(); itr != deletedKeyList.end();) {
				TKeyEntryInfo keyInfo = *itr;
				if (keyInfo().initialDataLength >= valueData.size()) {
					keyInfo().freeKeyData = keyData;
					rewritePair(keyInfo, valueData);
					dataMap.insert({ keyInfo().freeKeyData, keyInfo });
					itr = deletedKeyList.erase(itr);
					return true;
				} else {
					++itr;
				}
			}
			return false;
		}

		void addNew(const TKeyData& keyData, const TValueData& valueData) {
			if (valueData.size() == 0) {
				return;
			}

			if (!tryWriteToSuitableDeletedPair(keyData, valueData)) {
				if (hasReserved()) {
					newPairFromReserved(keyData, valueData);
				} else {
					createNewTable();
					newPairFromReserved(keyData, valueData);
				}
			}
		}

		void change(const TKeyData& keyData, const TValueData& valueData) {
			TKeyEntryInfo& keyInfo = dataMap[keyData];
			if (valueData.size() > 0) {
				if (keyInfo().initialDataLength >= valueData.size()) {
					rewritePair(keyInfo, valueData);
				} else {
					//remove old and create new
					earsePair(keyInfo);
					addNew(keyData, valueData);
				}
			} else {
				// erase
				earsePair(keyInfo);
			}
		}

	public:

		KvFile() {
			assert(sizeof(K) <= KVDB_KEY_SIZE);
		}

		~KvFile() {
			close();
		}

		void setReservedValueSize(uint32 val) {
			reservedValueSize = val;
		}

		void close() {
			if (!isOpen()) return;
			filePtr->close();
			dataMap.clear();
			reservedKeyList.clear();
			deletedKeyList.clear();
			tableList.clear();
		}

		bool isOpen() const {
			return filePtr && filePtr->is_open();
		}

		bool open(const std::string& file) {
			filePtr = new std::fstream(file, std::ios::in | std::ios::out | std::ios::binary);

			if (!isOpen()) return false;

			TFileHeader fileHeader;
			filePtr >> fileHeader;

			ulong64 nextTablePos = readTable();
			while (nextTablePos > 0) {
				filePtr->seekg(nextTablePos);
				nextTablePos = readTable();
			}

			return true;
		}

		int size() {
			if (!isOpen()) {
				return 0;
			} else {
				return dataMap.size();
			}
		}

		bool isExist(const K& k) {
			TKeyData keyData = toKeyData(k);
			if (!isOpen()) return false;
			std::lock_guard<std::mutex> guard(fileSharedMutex);
			return !(dataMap.find(keyData) == dataMap.end());
		}

		TValueDataPtr loadData(const K& k) {
			TKeyData keyData = toKeyData(k);

			if (!isOpen()) return nullptr;
			std::lock_guard<std::mutex> guard(fileSharedMutex);

			auto got = dataMap.find(keyData);
			if (got == dataMap.end()) {
				return nullptr;
			}

			TKeyEntryInfo& i = dataMap[keyData];
			const TKeyEntry& e = i();

			filePtr->seekg(e.dataPos);

			TValueDataPtr dataPtr = TValueDataPtr(new TValueData);
			dataPtr->resize(e.dataLength);

			if (filePtr->read((char*)dataPtr->data(), e.dataLength)) {
				return dataPtr;
			}

			return nullptr;
		}

		std::shared_ptr<V> load(const K& k) {
			return valueFromData(loadData(k));
		}

		std::shared_ptr<V> operator[] (const K& k) {
			return valueFromData(loadData(k));
		}

		void erase(const K& k) {
			TKeyData keyData = toKeyData(k);

			if (!isOpen()) return;
			std::lock_guard<std::mutex> guard(fileSharedMutex);

			auto got = dataMap.find(keyData);
			if (got != dataMap.end()) {
				TKeyEntryInfo keyInfo = dataMap[keyData];
				earsePair(keyInfo);
			}
		}

		void save(const K& k, const V& v) {
			TKeyData keyData = toKeyData(k);
			TValueData valueData;

			if (std::is_same<V, TValueData>::value) {
				valueData = static_cast<TValueData>(v);
			} else {
				toValueData(v, valueData);
			}

			if (!isOpen()) return;
			std::lock_guard<std::mutex> guard(fileSharedMutex);

			std::unordered_map<TKeyData, TKeyEntryInfo>::const_iterator got = dataMap.find(keyData);
			if (got == dataMap.end()) {
				// pair not found
				addNew(keyData, valueData);
			} else {
				// pair found
				change(keyData, valueData);
			}
		}

		static bool create(const std::string& file, const std::unordered_map<K, V>& test) {
			std::ofstream outFile(file, std::ios::out | std::ios::binary);

			if (!outFile) return false;

			std::ofstream* outFilePtr = &outFile;

			static const ulong64 max_key_records = KVDB_RESERVED_TABLE_SIZE;
			const ulong64 keyRecords = (test.size() > max_key_records) ? test.size() : max_key_records;

			// save file header
			TFileHeader fileHeader;
			fileHeader.keySize = KVDB_KEY_SIZE;
			fileHeader.endOfHeaderOffset = sizeof(fileHeader);

			outFilePtr << fileHeader;

			TTableHeader tableHeader;
			tableHeader.recordCount = keyRecords;
			outFilePtr << tableHeader;

			ulong64 bodyDataOffset = (ulong64)(outFile.tellp()) + sizeof(TKeyEntry) * keyRecords;

			std::vector<byte> dataBody;

			for (auto& e : test) {
				TKeyEntry entry;
				entry.freeKeyData = toKeyData(e.first);
				entry.dataPos = dataBody.size() + bodyDataOffset;

				TValueData valueData;

				if (std::is_same<V, TValueData>::value) { //constexpr
					valueData = static_cast<TValueData>(e.second);
				} else {
					toValueData(e.second, valueData);
				}

				entry.dataLength = valueData.size();
				entry.initialDataLength = valueData.size();
				dataBody.insert(std::end(dataBody), std::begin(valueData), std::end(valueData));

				outFilePtr << entry;
			}

			if (test.size() < max_key_records) {
				// add empty records
				const ulong64 emptyRecords = max_key_records - test.size();
				for (int i = 0; i < emptyRecords; i++) {
					TKeyEntry entry;
					outFilePtr << entry;
				}
			}

			outFilePtr->write((char*)dataBody.data(), dataBody.size());
			outFile.close();

			return true;
		}
	};

	//-----------------------------------------------------------------------------

}


text:
package com.transilink.framework.core.dao.db;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.resource.Representation;
import org.restlet.resource.StringRepresentation;

import com.transilink.framework.core.exception.BaseException;
import com.transilink.framework.core.model.variant.VariantSet;
import com.transilink.framework.core.utils.MathUtils.MathUtil;
import com.transilink.framework.core.utils.clazzUtils.BeanUtils;
import com.transilink.framework.core.utils.clazzUtils.DBUtil;
import com.transilink.framework.core.utils.pagesUtils.Page;
import com.transilink.framework.core.utils.pagesUtils.PageContext;
import com.transilink.framework.core.utils.stringUtils.JsonUtil;
import com.transilink.framework.core.utils.stringUtils.StringUtil;

/**
 *
 * @author huangxin (3203317@qq.com)
 *
 */
@SuppressWarnings("all")
public class DbDataset implements Serializable {

	/** serialVersionUID */
	private static final long serialVersionUID = -2042432252201796659L;

	/**
	 * 构造方法
	 *
	 */
	public DbDataset() {

	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param supportPaging
	 *            是否需要分页,默认为true.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20条.
	 */
	public DbDataset(String sql, ParameterSet params, boolean supportPaging,
			int pageIndex, int pageSize) {

		this.setSql(sql);
		if (params != null) {
			this.parameterSet = params;
		}
		this.setSupportPaging(supportPaging);
		this.setPageIndex(pageIndex);
		this.setPageSize(pageSize);
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param supportPaging
	 *            是否需要分页.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20.
	 */
	public DbDataset(String sql, ParameterSet params, boolean supportPaging,
			String pageIndex, String pageSize) {
		this(sql, params, supportPaging, MathUtil.getInteger(pageIndex)
				.intValue(), MathUtil.getInteger(pageSize).intValue());
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param supportPaging
	 *            是否需要分页.
	 */
	public DbDataset(String sql, ParameterSet params, boolean supportPaging) {
		this(sql, params, supportPaging, 1, DEFAULT_PAGING_SIZE);
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20条.
	 */
	public DbDataset(String sql, ParameterSet params, int pageIndex,
			int pageSize) {

		this(sql, params, true, pageIndex, pageSize);
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20.
	 */
	public DbDataset(String sql, ParameterSet params, String pageIndex,
			String pageSize) {
		this(sql, params, true, MathUtil.getInteger(pageIndex).intValue(),
				MathUtil.getInteger(pageSize).intValue());
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20.
	 */
	public DbDataset(String sql, String pageIndex, String pageSize) {
		this(sql, null, true, MathUtil.getInteger(pageIndex).intValue(),
				MathUtil.getInteger(pageSize).intValue());
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 * @param params
	 *            查询参数.
	 * @param pageIndex
	 *            请求的页号,默认为1.
	 * @param pageSize
	 *            每页记录数,默认为20条.
	 */
	public DbDataset(String sql, int pageIndex, int pageSize) {

		this(sql, null, true, pageIndex, pageSize);
	}

	/**
	 * 构造方法.
	 *
	 * @param sql
	 *            查询sql
	 */
	public DbDataset(String sql) {
		this(sql, null, true, 1, DEFAULT_PAGING_SIZE);
	}

	private Logger log = Logger.getLogger(this.getClass());
	/**
	 * 参数集合
	 */
	private ParameterSet parameterSet = new ParameterSet();

	private String sql = null;

	/**
	 * 是否支持分页
	 */
	private boolean supportPaging = true;

	/**
	 * 默认实体对应的类型
	 */
	public static final Class DEFUALT_ENTITY_CLAZZ = Record.class;

	/**
	 * 默认每页显示的分页记录数
	 */
	public static final int DEFAULT_PAGING_SIZE = 20;

	/**
	 * 对应的实体类型
	 */
	private Class clazz;
	/**
	 * 返回Dataset所对应的数据共有几页。
	 */
	private int pageCount;

	/**
	 * 返回Dataset所对应的当前分页数据共有几行。
	 */
	private int currPageRowCount;

	/**
	 * 返回Dataset的当前页号
	 */
	private int pageIndex;

	/**
	 * 取得每页的行数。
	 */
	private int pageSize = DEFAULT_PAGING_SIZE;

	/**
	 * 获取Dataset可能存在的总记录数。
	 */
	private long possibleRecordCount;

	private List data;

	/**
	 * 参数
	 *
	 * @return
	 */
	public ParameterSet parameters() {
		if (this.parameterSet == null) {
			this.parameterSet = new ParameterSet();
		}
		return this.parameterSet;
	}

	/**
	 * 设置参数
	 *
	 * @param name
	 *            参数名
	 * @param value
	 *            参数值
	 * @return 返回当前对象.
	 */
	public DbDataset setParameter(String name, Object value) {
		this.parameters().setValue(name, value);
		return this;
	}

	/**
	 * 设置参数.
	 *
	 * @param map
	 *            参数map
	 * @param names
	 *            参数名列表
	 * @return
	 */
	public DbDataset setParameters(Map map, String[] names) {

		if (map == null || map.isEmpty()) {
			return this;
		}

		if (names == null || names.length == 0) {
			for (Iterator<Map.Entry> iterator = map.entrySet().iterator(); iterator
					.hasNext();) {
				Map.Entry entry = iterator.next();
				this.parameters().setValue(entry.getKey().toString(),
						entry.getValue());
			}

		} else {
			for (Iterator<Map.Entry> iterator = map.entrySet().iterator(); iterator
					.hasNext();) {
				Map.Entry entry = iterator.next();
				if (isExists(names, entry.getKey().toString())) {
					this.parameters().setValue(entry.getKey().toString(),
							entry.getValue());
				}
			}
		}
		return this;
	}

	/**
	 * 设置参数.
	 *
	 * @param map
	 *            参数map
	 * @return
	 */
	public DbDataset setParameters(Map map) {
		return this.setParameters(map, null);
	}

	/**
	 * 根据Bean Object批量设置参数.
	 *
	 * @param obj
	 * @return
	 */
	public DbDataset setParameters(Object obj) {
		return this.setParameters(BeanUtils.describe(obj), null);

	}

	/**
	 * 根据Bean Object批量设置参数.
	 *
	 * @param obj
	 *            参数map
	 * @param names
	 *            参数名列表
	 * @return
	 */
	public DbDataset setParameters(Object obj, String[] names) {
		return this.setParameters(BeanUtils.describe(obj), names);
	}

	/**
	 * 根据Variantset 对象批量设置参数.
	 *
	 * @param obj
	 *            variantSet
	 * @param names
	 *            参数名列表
	 * @return
	 */
	public DbDataset setParameters(VariantSet variantSet, String[] names) {
		int len = 0;
		if (variantSet == null || ((len = variantSet.count()) == 0)) {
			log.error("varinatSet 参数 为空!");
			return this;
		}
		if (names == null || names.length == 0) {
			for (int i = 0; i < len; i++) {
				this.parameters().setValue(variantSet.indexToName(i),
						variantSet.getValue(i));
			}

		} else {
			for (int i = 0; i < len; i++) {
				String key = variantSet.indexToName(i);
				if (isExists(names, key)) {
					this.parameters().setValue(variantSet.indexToName(i),
							variantSet.getValue(i));
				}
			}
		}
		return this;

	}

	/**
	 * 根据Variantset 对象批量设置参数.
	 *
	 * @param obj
	 *            参数map
	 * @return
	 */
	public DbDataset setParameters(VariantSet variantSet) {

		return this.setParameters(variantSet, null);

	}

	/**
	 * 设置参数
	 *
	 * @return
	 */
	public Object getParameter(String name) {
		return this.parameters().getValue(name);
	}

	public Class getClazz() {
		return clazz;
	}

	/**
	 * 设置数据结果集DO对象类型
	 *
	 * @param clazz
	 * @return
	 */
	public DbDataset setClazz(Class clazz) {
		this.clazz = clazz;
		return this;
	}

	public int getPageCount() {
		return pageCount;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	/**
	 * 加载数据
	 */
	/**
	 *
	 */
	public DbDataset loadData() {

		if (StringUtil.isEmpty(this.sql)) {
			throw new BaseException("请设置dataset SQl!");
		}
		// 根据TransilinkContext上下文编译字符
		String parsedSQl = translateSql(this.sql);
		if (StringUtil.isEmpty(parsedSQl)) {
			throw new BaseException("dataset SQl 解析错误!");
		}

		String querySQL = this.doGetSql(parsedSQl);

		Object[] parameters = this.doGetSqlParameters(parsedSQl);

		Class modelClazz = this.DEFUALT_ENTITY_CLAZZ;
		if (this.getClazz() != null) {
			modelClazz = this.getClazz();
		}

		if (this.isSupportPaging()) {

			PagingResultSet pagePagingResultSet = DBUtil.getPagingResultSet(
					querySQL, parameters, modelClazz, pageSize, pageIndex);
			// 结果数据
			this.setData(pagePagingResultSet.getData());
			// 分页总数
			this.setPageCount(pagePagingResultSet.getPageCount());
			// 当前页记录总数
			this.setCurrPageRowCount(this.getData().size());
			// 当前页号
			this.setPageIndex(pagePagingResultSet.getPageIndex());
			// 数据库总记录条数
			this.setPossibleRecordCount(pagePagingResultSet.getRowCount());

		} else {
			List list = DBUtil.query(querySQL, parameters, modelClazz);
			// 结果数据
			this.setData(list);
			int len = list.size();
			// 分页总数
			this.setPageCount(1);
			// 当前页记录总数
			this.setCurrPageRowCount(len);
			// 当前页号
			this.setPageIndex(1);
			// 总记录条数
			this.setPossibleRecordCount(len);
		}
		return this;
	}

	/**
	 * 转换为分页 huangxin
	 *
	 * @return
	 */
	public Page toPage() {
		Page page = new Page();
		page.setItems(this.getData());
		Long total = 0L;
		if (this.getPossibleRecordCount() > 0) {
			total = this.getPossibleRecordCount();
		}
		page.setTotal(total.intValue());
		return page;
	}

	/**
	 * 根据当前Context上下文环境翻译字符串
	 *
	 * @param sql
	 * @return
	 */
	private String translateSql(String sql) {
		Map params = new HashMap();

		for (int i = 0, len = this.parameterSet.count(); i < len; i++) {
			String name = this.parameterSet.indexToName(i);
			Object value = this.parameterSet.getValue(i);
			params.put(name, value);
		}

		return sql;
	}

	/**
	 *
	 * 翻译字符串
	 *
	 * @param sql
	 * @return
	 */
	private String doGetSql(String sql) {

		return sql.replaceAll(":(\\w*)", "?");

	}

	/**
	 * 得到解析后的sql字符
	 *
	 * @return
	 */
	public String getParsedSql() {

		// 根据TransilinkContext上下文编译字符
		String parsedSQl = translateSql(this.sql);
		if (StringUtil.isEmpty(parsedSQl)) {
			return null;
		}

		String querySQL = this.doGetSql(parsedSQl);
		return querySQL;

	}

	/**
	 * 根据SQL获取对应的参数值
	 *
	 * @param sql
	 * @return
	 */
	private Object[] doGetSqlParameters(String sql) {

		List list = new ArrayList();
		Pattern patter = Pattern.compile(":(\\w*)", Pattern.CASE_INSENSITIVE
				| Pattern.DOTALL);
		Matcher pMatcher = patter.matcher(sql);
		while (pMatcher.find()) {
			String parameName = StringUtil.trim(pMatcher.group(1));
			if (StringUtil.isValid(parameName)) {
				Object value = this.parameterSet.getValue(parameName);
				if (value != null && value instanceof String) {
				}
				list.add(value);
			}
		}
		if (list.isEmpty())
			return null;
		return list.toArray();
	}

	protected DbDataset setPageIndex(int pageIndex) {
		if (pageIndex <= 0) {
			this.pageIndex = 1;
		} else {
			this.pageIndex = pageIndex;

		}

		return this;
	}

	public int getPageSize() {

		return pageSize;
	}

	/**
	 *
	 * 设置每页显示的记录数量
	 *
	 * @param pageSize
	 */
	public DbDataset setPageSize(int pageSize) {
		if (pageSize <= 0) {
			this.pageSize = PageContext.getPageSize();
		} else {
			this.pageSize = pageSize;

		}
		return this;
	}

	/**
	 * 设置每页显示的记录数量
	 *
	 * @param pageSize
	 */
	public DbDataset setPageSize(String pageSize) {

		return this.setPageSize(MathUtil.getInteger(pageSize).intValue());

	}

	/**
	 * 得到记录总数量
	 *
	 * @return
	 */
	public long getPossibleRecordCount() {
		return possibleRecordCount;
	}

	protected DbDataset setPossibleRecordCount(long possibleRecordCount) {
		this.possibleRecordCount = possibleRecordCount;
		return this;
	}

	/**
	 * 获取当前页总记录条数
	 *
	 * @return
	 */
	public int getCurrPageRowCount() {
		return currPageRowCount;
	}

	protected DbDataset setCurrPageRowCount(int currPageRowCount) {
		this.currPageRowCount = currPageRowCount;
		return this;
	}

	public String getSql() {
		return sql;
	}

	/**
	 * 设置sql
	 *
	 * @param sql
	 */
	public DbDataset setSql(String sql) {
		this.sql = sql;
		return this;
	}

	/**
	 * 设置sql
	 *
	 * @param sql
	 */
	public DbDataset setSql(StringBuffer sql) {
		if (sql != null) {
			this.sql = sql.toString();
		} else {

			this.sql = null;

		}
		return this;
	}

	public String getPagingSql(String sql) {

		return sql;

	}

	public boolean isSupportPaging() {
		return supportPaging;
	}

	protected DbDataset setSupportPaging(boolean supportPaging) {
		this.supportPaging = supportPaging;
		return this;
	}

	/**
	 * 返回结果集数据
	 *
	 * @return
	 */
	public List getData() {
		return data;
	}

	protected DbDataset setData(List data) {
		this.data = data;
		return this;
	}

	protected DbDataset setPageCount(int pageCount) {
		this.pageCount = pageCount;
		return this;
	}

	/**
	 * 将查询结果转换为JSONArray数组,格式[{},{}],其中对象属性包括结果集对象所有属性值列表.
	 *
	 * @return
	 */
	public JSONArray toJSONArray() {
		return this.toJSONArray(null);
	}

	/**
	 * 将查询结果转换为JSONArray数组,格式[{},{}]
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public JSONArray toJSONArray(String[] names) {

		JSONArray jsonArray = new JSONArray();
		if (this.data != null && !this.data.isEmpty()) {
			for (int i = 0, len = this.data.size(); i < len; i++) {
				jsonArray.add(toJSONObject(i, names));
			}
		}
		return jsonArray;

	}

	/**
	 * 将查询结果转换为JSONObject,格式:{total:xx,data:[{name:value,name1:value1,...},..,{}
	 * ]}
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public JSONObject toJSONObject() {
		return toJSONObject(null);
	}

	/**
	 * 将查询结果转换为JSONObject,格式:{total:xx,data:[{name:value,name1:value1,...},..,{}
	 * ]}
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public JSONObject toJSONObject(String[] names) {
		JSONObject jsonObject = new JSONObject();
		JsonUtil.put(jsonObject, "total", this.getPossibleRecordCount());
		JsonUtil.put(jsonObject, "data", toJSONArray(names));
		return jsonObject;
	}

	/**
	 * 将首条记录转换为JSONObject,格式{name:value,name1:value1..}
	 *
	 * @return
	 */
	public JSONObject toSingleJSONObject() {

		return toSingleJSONObject(null);

	}

	/**
	 * 将首条记录转换为JSONObject,格式{name:value,name1:value1,...}
	 *
	 * @param names
	 *            需转换为json对象的属性列表
	 * @return
	 */
	public JSONObject toSingleJSONObject(String[] names) {
		JSONObject jsonObject = null;
		if (this.data == null || this.data.isEmpty()) {
			jsonObject = new JSONObject();
		} else {
			jsonObject = toJSONObject(0, names);
		}
		return jsonObject;

	}

	/**
	 * 将查询结果转换为JSON
	 * Presention格式:{total:xx,data:[{name:value,name1:value1,...},..,{}]}
	 *
	 * @return
	 */
	public Representation toJSONObjectPresention() {

		return this.toJSONObjectPresention(null);
	}

	/**
	 * 将查询结果转换为JSON
	 * Presention格式:{total:xx,data:[{name:value,name1:value1,...},..,{}]}
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public Representation toJSONObjectPresention(String[] names) {

		return new StringRepresentation(toJSONObject(names).toString(),
				MediaType.TEXT_PLAIN, null, CharacterSet.UTF_8);
	}

	/**
	 * 将首条记录转换为JSON Presention ,格式{name:value,name1:value1..}
	 *
	 * @return
	 */
	public Representation toSingleJSONObjectPresention() {

		return toSingleJSONObjectPresention(null);

	}

	/**
	 * 将首条记录转换为JSON Presention,格式{name:value,name1:value1,...}
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public Representation toSingleJSONObjectPresention(String[] names) {

		return new StringRepresentation(toSingleJSONObject(names).toString(),
				MediaType.TEXT_PLAIN, null, CharacterSet.UTF_8);

	}

	/**
	 * 将查询结果转换为JSON Array Presention,格式[{},{}],其中对象属性包括结果集对象所有属性值列表.
	 *
	 * @return
	 */
	public Representation toJSONArrayPresention() {
		return this.toJSONArrayPresention(null);
	}

	/**
	 * 将查询结果转换为JSONArray数组,格式[{},{}]
	 *
	 * @param names
	 *            转换为json对象的属性列表
	 * @return
	 */
	public Representation toJSONArrayPresention(String[] names) {

		return new StringRepresentation(toJSONArray(names).toString(),
				MediaType.TEXT_PLAIN, null, CharacterSet.UTF_8);

	}

	/**
	 * 将第n个对象转换为JsonObject对象,如果为空,则转为空对象{}
	 *
	 * @param index
	 * @param names
	 *            转换json对象的属性列表
	 * @return
	 */
	public JSONObject toJSONObject(int index, String names[]) {
		if (this.getData() == null || this.data.isEmpty()) {
			return new JSONObject();
		}

		Object obj = this.getData().get(index);

		return JsonUtil.toJSONObject(obj, names);

	}

	/**
	 * 判断是否存在
	 *
	 * @param names
	 * @param name
	 * @return
	 */
	private static boolean isExists(String[] names, String name) {
		boolean flag = false;
		for (int i = 0, len = names.length; i < len; i++) {
			if (name.equals(names[i])) {
				flag = true;
				break;
			}
		}
		return flag;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestApp.ViewModels;
using Xamarin.Forms;

namespace TestApp.Pages.RatingBarPages
{
    public partial class RatingBarXamlPage : ContentPage
    {
        public RatingBarXamlPage()
        {
            BindingContext = new RatingBarViewModel();
            InitializeComponent();
        }
    }
}


text:
package com.github.sample.util;

/**
 * @author laomie
 * @version V1
 * @date 2014-11-30 11:11
 */

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class TestUtil {
    public static void printRs(ResultSet rs) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String columnName = rsmd.getColumnLabel(i);
            System.out.print(columnName + "\t");
        }
        System.out.println();

        while (rs.next()) {
            for (int i = 1; i <= columnCount; i++) {
                Object obj = rs.getObject(i);
                System.out.print(obj + "\t");
            }
            System.out.println();
        }
    }

    public static String getFilePath(String relativePath) throws Exception {
        URL url = TestUtil.class.getClassLoader().getResource(relativePath);
        Path path = Paths.get(url.toURI());
        File dir = path.toFile();
        String absolutePath = dir.getAbsolutePath();
        return absolutePath;
    }
}


text:
/**
 * This package contains tooling used only to debug issues that cannot be found with research but
 * which require releasing a production or edge release with extra introspective facilities in
 * an attempt to add clarity to the exceptions or other messages that result when the bug occurs.
 *
 * NB: This package is not public API in the sense that contents of this package,
 *    even public classes / methods / etc, may change in point releases.
 */
package lombok.core.debug;


text:
namespace DX
{
    // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
    interface IDeviceNotify
    {
        virtual void OnDeviceLost() = 0;
        virtual void OnDeviceRestored() = 0;

    protected:
        ~IDeviceNotify() = default;
    };

    // Controls all the DirectX device resources.
    class DeviceResources
    {
    public:
        static constexpr unsigned int c_AllowTearing   = 0x1;
        static constexpr unsigned int c_EnableHDR      = 0x2;
        static constexpr unsigned int c_Enable4K_Xbox  = 0x4;
        static constexpr unsigned int c_EnableQHD_Xbox = 0x8;

        DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM,
                        DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D24_UNORM_S8_UINT,
                        UINT backBufferCount = 2,
                        D3D_FEATURE_LEVEL minFeatureLevel = D3D_FEATURE_LEVEL_9_3,
                        unsigned int flags = 0) noexcept;
        ~DeviceResources() = default;

        DeviceResources(DeviceResources&&) = default;
        DeviceResources& operator= (DeviceResources&&) = default;

        DeviceResources(DeviceResources const&) = delete;
        DeviceResources& operator= (DeviceResources const&) = delete;

        void CreateDeviceResources();
        void CreateWindowSizeDependentResources();
        void SetWindow(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation) noexcept;
        bool WindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation);
        void ValidateDevice();
        void HandleDeviceLost();
        void RegisterDeviceNotify(IDeviceNotify* deviceNotify) noexcept { m_deviceNotify = deviceNotify; }
        void Trim() noexcept;
        void Present();
        void UpdateColorSpace();
        void Suspend() noexcept;
        void Resume() noexcept;

        // Device Accessors.
        RECT GetOutputSize() const noexcept             { return m_outputSize; }
        DXGI_MODE_ROTATION GetRotation() const noexcept { return m_rotation; }

        // Direct3D Accessors.
        auto                    GetD3DDevice() const noexcept              { return m_d3dDevice.Get(); }
        auto                    GetD3DDeviceContext() const noexcept       { return m_d3dContext.Get(); }
        auto                    GetSwapChain() const noexcept              { return m_swapChain.Get(); }
        auto                    GetDXGIFactory() const noexcept            { return m_dxgiFactory.Get(); }
        D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const noexcept     { return m_d3dFeatureLevel; }
        ID3D11Texture2D*        GetRenderTarget() const noexcept           { return m_renderTarget.Get(); }
        ID3D11Texture2D*        GetDepthStencil() const noexcept           { return m_depthStencil.Get(); }
        ID3D11RenderTargetView* GetRenderTargetView() const noexcept       { return m_d3dRenderTargetView.Get(); }
        ID3D11DepthStencilView* GetDepthStencilView() const noexcept       { return m_d3dDepthStencilView.Get(); }
        DXGI_FORMAT             GetBackBufferFormat() const noexcept       { return m_backBufferFormat; }
        DXGI_FORMAT             GetDepthBufferFormat() const noexcept      { return m_depthBufferFormat; }
        D3D11_VIEWPORT          GetScreenViewport() const noexcept         { return m_screenViewport; }
        UINT                    GetBackBufferCount() const noexcept        { return m_backBufferCount; }
        DirectX::XMFLOAT4X4     GetOrientationTransform3D() const noexcept { return m_orientationTransform3D; }
        DXGI_COLOR_SPACE_TYPE   GetColorSpace() const noexcept             { return m_colorSpace; }
        unsigned int            GetDeviceOptions() const noexcept          { return m_options; }

    private:
        void GetHardwareAdapter(IDXGIAdapter1** ppAdapter);

        // Direct3D objects.
        Microsoft::WRL::ComPtr<IDXGIFactory2>           m_dxgiFactory;
        Microsoft::WRL::ComPtr<ID3D11Device3>           m_d3dDevice;
        Microsoft::WRL::ComPtr<ID3D11DeviceContext2>    m_d3dContext;
        Microsoft::WRL::ComPtr<IDXGISwapChain3>         m_swapChain;

        // Direct3D rendering objects. Required for 3D.
        Microsoft::WRL::ComPtr<ID3D11Texture2D>         m_renderTarget;
        Microsoft::WRL::ComPtr<ID3D11Texture2D>         m_depthStencil;
        Microsoft::WRL::ComPtr<ID3D11RenderTargetView>	m_d3dRenderTargetView;
        Microsoft::WRL::ComPtr<ID3D11DepthStencilView>	m_d3dDepthStencilView;
        D3D11_VIEWPORT                                  m_screenViewport;

        // Direct3D properties.
        DXGI_FORMAT                                     m_backBufferFormat;
        DXGI_FORMAT                                     m_depthBufferFormat;
        UINT                                            m_backBufferCount;
        D3D_FEATURE_LEVEL                               m_d3dMinFeatureLevel;

        // Cached device properties.
        IUnknown*                                       m_window;
        D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
        DXGI_MODE_ROTATION                              m_rotation;
        DWORD                                           m_dxgiFactoryFlags;
        RECT                                            m_outputSize;

        // Transforms used for display orientation.
        DirectX::XMFLOAT4X4                             m_orientationTransform3D;

        // HDR Support
        DXGI_COLOR_SPACE_TYPE                           m_colorSpace;

        // DeviceResources options (see flags above)
        unsigned int                                    m_options;

        // The IDeviceNotify can be held directly as it owns the DeviceResources.
        IDeviceNotify*                                  m_deviceNotify;
    };
}


text:
package com.chinamobile.bcbsp.io;

import com.chinamobile.bcbsp.thirdPartyInterface.HDFS.BSPHdfs;
import com.chinamobile.bcbsp.thirdPartyInterface.HDFS.BSPhdfsFSDIS;
import com.chinamobile.bcbsp.thirdPartyInterface.HDFS.impl.BSPHdfsImpl;
import com.chinamobile.bcbsp.thirdPartyInterface.HDFS.impl.BSPhdfsFSDISImpl;
import com.chinamobile.bcbsp.util.BSPJob;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.util.LineReader;

/**
 * KeyValueBSPFileInputFormat An example that extends the
 * BSPFileInputFormat<Text, Text>. This class can support Key-Value pairs
 * InputFormat.
 */
public class KeyValueBSPFileInputFormat extends BSPFileInputFormat<Text, Text> {

  /**
   * RecordReader
   *
   * This class can read data in the form of Key-Value.
   */
  public static class KVRecordReader extends RecordReader<Text, Text> {
    /** Define LOG for outputting log information */
    private static final Log LOG = LogFactory.getLog(KVRecordReader.class);
    /** Define a CompressionCodecFactory, used to compress
     * the configuration info*/
    private CompressionCodecFactory compressionCodecs = null;
    /** The split starting position */
    private long start;
    /** The split current location */
    private long pos;
    /** The split ending position */
    private long end;
    /** Define a line reader from an input stream. */
    private LineReader in;
    /** The maximum length of each line */
    private int maxLineLength;
    /** the vertex */
    private Text key = null;
    /** the whole list of edges of the vertex. */
    private Text value = null;
    /** Define a separator */
    private String separator = "\t";

    @Override
    public void initialize(InputSplit genericSplit, Configuration conf)
        throws IOException, InterruptedException {
      FileSplit split = (FileSplit) genericSplit;
      this.maxLineLength = conf.getInt("mapred.linerecordreader.maxlength",
          Integer.MAX_VALUE);
      this.separator = conf.get("key.value.separator.in.input.line", "\t");
      start = split.getStart();
      end = start + split.getLength();
      // final Path file = split.getPath();
      BSPHdfs hdfsIni = new BSPHdfsImpl();
      compressionCodecs = new CompressionCodecFactory(conf);
      // final CompressionCodec codec = compressionCodecs.getCodec(file);
      final CompressionCodec codec = compressionCodecs.getCodec(hdfsIni
          .hdfsinitialize(split));
      // FileSystem fs = file.getFileSystem(conf);
      // FSDataInputStream fileIn = fs.open(split.getPath());
      BSPhdfsFSDIS bspfileIn = new BSPhdfsFSDISImpl(split, conf);
      boolean skipFirstLine = false;
      if (codec != null) {
        in = new LineReader(codec.createInputStream(bspfileIn.getFileIn()),
            conf);
        end = Long.MAX_VALUE;
      } else {
        if (start != 0) {
          skipFirstLine = true;
          --start;
          bspfileIn.seek(start);
        }
        in = new LineReader(bspfileIn.getFileIn(), conf);
      }
      if (skipFirstLine) {
        start += in.readLine(new Text(), 0,
            (int) Math.min(Integer.MAX_VALUE, end - start));
      }
      this.pos = start;
    }

    @Override
    public synchronized void close() throws IOException {
      if (in != null) {
        in.close();
      }
    }

    @Override
    public Text getCurrentKey() throws IOException, InterruptedException {
      return key;
    }

    @Override
    public Text getCurrentValue() throws IOException, InterruptedException {
      return value;
    }

    @Override
    public float getProgress() throws IOException, InterruptedException {
      if (start == end) {
        return 0.0f;
      } else {
        return Math.min(1.0f, (pos - start) / (float) (end - start));
      }
    }

    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
      Text line = new Text();
      if (key == null) {
        key = new Text();
      }
      if (value == null) {
        value = new Text();
      }
      int newSize = 0;
      while (pos < end) {
        newSize = in.readLine(line, maxLineLength, Math.max(
            (int) Math.min(Integer.MAX_VALUE, end - pos), maxLineLength));
        if (null != line) {
          String[] kv = line.toString().split(this.separator);
          if (kv.length == 2) {
            key.set(kv[0]);
            value.set(kv[1]);
          } else {
            LOG.info("Skipped line has no separator");
            key.set(line.toString());
            value.set("");
          }
        }
        if (newSize == 0) {
          break;
        }
        pos += newSize;
        if (newSize < maxLineLength) {
          break;
        }
        LOG.info("Skipped line of size " + newSize + " at pos " +
          (pos - newSize));
      }
      if (newSize == 0) {
        key = null;
        value = null;
        return false;
      } else {
        return true;
      }
    }
  }

  @Override
  public RecordReader<Text, Text> createRecordReader(InputSplit split,
      BSPJob job) throws IOException, InterruptedException {
    return new KVRecordReader();
  }

  @Override
  protected boolean isSplitable(BSPJob job, Path file) {
    CompressionCodec codec = new CompressionCodecFactory(job.getConf())
        .getCodec(file);
    return codec == null;
  }
}


text:
package com.azure.containers.containerregistry;

import com.azure.containers.containerregistry.models.ArtifactManifestProperties;
import com.azure.containers.containerregistry.models.ArtifactTagOrder;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.HttpClient;
import com.azure.core.http.rest.Response;
import com.azure.core.test.TestMode;
import com.azure.core.util.Context;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

import static com.azure.containers.containerregistry.TestUtils.DIGEST_UNKNOWN;
import static com.azure.containers.containerregistry.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS;
import static com.azure.containers.containerregistry.TestUtils.HELLO_WORLD_REPOSITORY_NAME;
import static com.azure.containers.containerregistry.TestUtils.LATEST_TAG_NAME;
import static com.azure.containers.containerregistry.TestUtils.PAGESIZE_2;
import static com.azure.containers.containerregistry.TestUtils.REGISTRY_ENDPOINT;
import static com.azure.containers.containerregistry.TestUtils.REGISTRY_ENDPOINT_PLAYBACK;
import static com.azure.containers.containerregistry.TestUtils.REGISTRY_NAME;
import static com.azure.containers.containerregistry.TestUtils.REGISTRY_NAME_PLAYBACK;
import static com.azure.containers.containerregistry.TestUtils.TAG_UNKNOWN;
import static com.azure.containers.containerregistry.TestUtils.V1_TAG_NAME;
import static com.azure.containers.containerregistry.TestUtils.V2_TAG_NAME;
import static com.azure.containers.containerregistry.TestUtils.V3_TAG_NAME;
import static com.azure.containers.containerregistry.TestUtils.V4_TAG_NAME;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class RegistryArtifactAsyncIntegrationTests extends ContainerRegistryClientsTestBase {
    private RegistryArtifactAsync asyncClient;
    private RegistryArtifact client;

    @BeforeEach
    void beforeEach() {
        TestUtils.importImage(
            getTestMode(),
            HELLO_WORLD_REPOSITORY_NAME,
            Arrays.asList(
                LATEST_TAG_NAME,
                V1_TAG_NAME,
                V2_TAG_NAME,
                V3_TAG_NAME,
                V4_TAG_NAME));
    }

    private String getDigest(HttpClient httpClient) {
        return getContainerRegistryBuilder(httpClient)
            .buildClient()
            .getArtifact(HELLO_WORLD_REPOSITORY_NAME, LATEST_TAG_NAME).getManifestProperties().getDigest();
    }

    private RegistryArtifactAsync getRegistryArtifactAsyncClient(HttpClient httpClient, String digest) {
        return getContainerRegistryBuilder(httpClient)
            .buildAsyncClient()
            .getArtifact(HELLO_WORLD_REPOSITORY_NAME, digest);
    }

    private RegistryArtifact getRegistryArtifactClient(HttpClient httpClient, String digest) {
        return getContainerRegistryBuilder(httpClient)
            .buildClient()
            .getArtifact(HELLO_WORLD_REPOSITORY_NAME, digest);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void getMultiArchitectureImagePropertiesWithResponse(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        Mono<Response<ArtifactManifestProperties>> safeTestRegistyArtifacts = asyncClient.getManifestPropertiesWithResponse()
            .flatMap(res -> {
                validateManifestProperties(res, true, false);
                return Mono.just(res);
            }).flatMap(res -> getRegistryArtifactAsyncClient(httpClient, res.getValue().getDigest()).getManifestPropertiesWithResponse())
            .flatMap(res -> {
                validateManifestProperties(res, true, false);
                return Mono.just(getChildArtifactDigest(res.getValue().getRelatedArtifacts()));
            }).flatMap(res -> getRegistryArtifactAsyncClient(httpClient, res).getManifestPropertiesWithResponse());

        StepVerifier.create(safeTestRegistyArtifacts)
            .assertNext(res -> validateManifestProperties(res, false, true))
            .verifyComplete();

        StepVerifier.create(asyncClient.getManifestProperties())
            .assertNext(res -> validateManifestProperties(res, true, false))
            .verifyComplete();

        validateManifestProperties(client.getManifestPropertiesWithResponse(Context.NONE), true, false);
        validateManifestProperties(client.getManifestProperties(), true, false);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void getMultiArchitectureImagePropertiesWithResponseThrows(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, DIGEST_UNKNOWN);
        client = getRegistryArtifactClient(httpClient, DIGEST_UNKNOWN);

        StepVerifier.create(asyncClient.getManifestPropertiesWithResponse())
            .verifyError(ResourceNotFoundException.class);

        StepVerifier.create(asyncClient.getManifestProperties())
            .verifyError(ResourceNotFoundException.class);

        assertThrows(ResourceNotFoundException.class, () -> client.getManifestProperties());
        assertThrows(ResourceNotFoundException.class, () -> client.getManifestPropertiesWithResponse(Context.NONE));
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void listTagProperties(HttpClient httpClient) {
        String digest = getDigest(httpClient);

        asyncClient = getRegistryArtifactAsyncClient(httpClient, digest);
        client = getRegistryArtifactClient(httpClient, digest);
        StepVerifier.create(asyncClient.listTagProperties())
            .recordWith(ArrayList::new)
            .thenConsumeWhile(x -> true)
            .expectRecordedMatches(tags -> {
                validateListTags(tags);
                return true;
            })
            .verifyComplete();
        validateListTags(client.listTagProperties().stream().collect(Collectors.toList()));

        // Now do the same via tag.
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);
        StepVerifier.create(asyncClient.listTagProperties())
            .recordWith(ArrayList::new)
            .thenConsumeWhile(x -> true)
            .expectRecordedMatches(tags -> {
                validateListTags(tags);
                return true;
            })
            .verifyComplete();
        validateListTags(client.listTagProperties().stream().collect(Collectors.toList()));
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void listTagPropertiesWithPageSize(HttpClient httpClient) {

        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.listTagProperties().byPage(PAGESIZE_2))
            .recordWith(ArrayList::new)
            .thenConsumeWhile(x -> true)
            .expectRecordedMatches(pagedResList -> validateListTags(pagedResList, false))
            .verifyComplete();

        validateListTags(client.listTagProperties().streamByPage().collect(Collectors.toList()), false);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void listTagPropertiesWithInvalidPageSize(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.listTagProperties().byPage(-1))
            .verifyError(IllegalArgumentException.class);

        assertThrows(IllegalArgumentException.class, () -> client.listTagProperties().streamByPage(-1).collect(Collectors.toList()));
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void listTagPropertiesWithPageSizeAndOrderBy(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.listTagProperties(ArtifactTagOrder.LAST_UPDATED_ON_ASCENDING).byPage(PAGESIZE_2))
            .recordWith(ArrayList::new)
            .thenConsumeWhile(x -> true)
            .expectRecordedMatches(pagedResList -> validateListTags(pagedResList, true))
            .verifyComplete();

        validateListTags(client.listTagProperties(ArtifactTagOrder.LAST_UPDATED_ON_ASCENDING, Context.NONE).streamByPage(PAGESIZE_2).collect(Collectors.toList()), true);
        validateListTags(client.listTagProperties(ArtifactTagOrder.LAST_UPDATED_ON_ASCENDING).streamByPage(PAGESIZE_2).collect(Collectors.toList()), true);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void listTagPropertiesWithPageSizeNoOrderBy(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.listTagProperties(ArtifactTagOrder.NONE).byPage(PAGESIZE_2))
            .recordWith(ArrayList::new)
            .thenConsumeWhile(x -> true)
            .expectRecordedMatches(pagedResList -> validateListTags(pagedResList, false))
            .verifyComplete();

        validateListTags(client.listTagProperties(ArtifactTagOrder.NONE, Context.NONE).streamByPage(PAGESIZE_2).collect(Collectors.toList()), false);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void getTagProperties(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.getTagPropertiesWithResponse(V1_TAG_NAME))
            .assertNext(res -> validateTagProperties(res, V1_TAG_NAME))
            .verifyComplete();

        StepVerifier.create(asyncClient.getTagProperties(LATEST_TAG_NAME))
            .assertNext(res -> validateTagProperties(res, LATEST_TAG_NAME))
            .verifyComplete();

        validateTagProperties(client.getTagProperties(V1_TAG_NAME), V1_TAG_NAME);
        validateTagProperties(client.getTagPropertiesWithResponse(LATEST_TAG_NAME, Context.NONE), LATEST_TAG_NAME);
    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void getTagPropertiesWithResponseThrows(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        StepVerifier.create(asyncClient.getTagPropertiesWithResponse(TAG_UNKNOWN))
            .verifyError(ResourceNotFoundException.class);

        StepVerifier.create(asyncClient.getTagProperties(TAG_UNKNOWN))
            .verifyError(ResourceNotFoundException.class);

        assertThrows(ResourceNotFoundException.class, () -> client.getTagProperties(TAG_UNKNOWN));
        assertThrows(ResourceNotFoundException.class, () -> client.getTagPropertiesWithResponse(TAG_UNKNOWN, Context.NONE));

        assertThrows(NullPointerException.class, () -> client.getTagProperties(null));
        assertThrows(NullPointerException.class, () -> client.getTagPropertiesWithResponse(null, Context.NONE));
        assertThrows(IllegalArgumentException.class, () -> client.getTagProperties(""));
        assertThrows(IllegalArgumentException.class, () -> client.getTagPropertiesWithResponse("", Context.NONE));

        StepVerifier.create(asyncClient.getTagPropertiesWithResponse(""))
            .verifyError(IllegalArgumentException.class);

        StepVerifier.create(asyncClient.getTagProperties(""))
            .verifyError(IllegalArgumentException.class);

        StepVerifier.create(asyncClient.getTagPropertiesWithResponse(null))
            .verifyError(NullPointerException.class);

        StepVerifier.create(asyncClient.getTagProperties(null))
            .verifyError(NullPointerException.class);

    }

    @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
    @MethodSource("getHttpClients")
    public void convenienceMethods(HttpClient httpClient) {
        asyncClient = getRegistryArtifactAsyncClient(httpClient, LATEST_TAG_NAME);
        client = getRegistryArtifactClient(httpClient, LATEST_TAG_NAME);

        String registryEndpoint = REGISTRY_ENDPOINT;
        String registryName = REGISTRY_NAME;
        if (getTestMode() == TestMode.PLAYBACK) {
            registryEndpoint = REGISTRY_ENDPOINT_PLAYBACK;
            registryName = REGISTRY_NAME_PLAYBACK;
        }

        assertEquals(HELLO_WORLD_REPOSITORY_NAME, asyncClient.getRepositoryName());
        assertEquals(HELLO_WORLD_REPOSITORY_NAME, client.getRepositoryName());

        assertTrue(asyncClient.getFullyQualifiedReference().startsWith(registryName));
        assertTrue(asyncClient.getFullyQualifiedReference().endsWith(LATEST_TAG_NAME));
        assertTrue(client.getFullyQualifiedReference().startsWith(registryName));
        assertTrue(client.getFullyQualifiedReference().endsWith(LATEST_TAG_NAME));

        assertEquals(registryEndpoint, asyncClient.getRegistryEndpoint());
        assertEquals(registryEndpoint, client.getRegistryEndpoint());
    }
}


text:
package org.apereo.cas.web.support;

import org.apereo.cas.configuration.model.support.cookie.CookieProperties;
import org.apereo.cas.configuration.model.support.cookie.TicketGrantingCookieProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.web.cookie.CasCookieBuilder;
import org.apereo.cas.web.cookie.CookieGenerationContext;

import lombok.NoArgsConstructor;
import lombok.val;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 * This is {@link CookieUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@NoArgsConstructor
public class CookieUtils {

    /**
     * Gets ticket granting ticket from request.
     *
     * @param ticketGrantingTicketCookieGenerator the ticket granting ticket cookie generator
     * @param ticketRegistry                      the ticket registry
     * @param request                             the request
     * @return the ticket granting ticket from request
     */
    public static TicketGrantingTicket getTicketGrantingTicketFromRequest(final CasCookieBuilder ticketGrantingTicketCookieGenerator,
                                                                          final TicketRegistry ticketRegistry, final HttpServletRequest request) {
        val cookieValue = ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
        if (StringUtils.isNotBlank(cookieValue)) {
            val tgt = ticketRegistry.getTicket(cookieValue, TicketGrantingTicket.class);
            if (tgt != null && !tgt.isExpired()) {
                return tgt;
            }
        }
        return null;
    }

    /**
     * Gets cookie from request.
     *
     * @param cookieName the cookie name
     * @param request    the request
     * @return the cookie from request
     */
    public static Optional<Cookie> getCookieFromRequest(final String cookieName, final HttpServletRequest request) {
        val cookies = request.getCookies();
        if (cookies == null) {
            return Optional.empty();
        }
        return Arrays.stream(cookies).filter(c -> c.getName().equalsIgnoreCase(cookieName)).findFirst();
    }

    /**
     * Build cookie generation context.
     *
     * @param cookie the cookie
     * @return the cookie generation context
     */
    public static CookieGenerationContext buildCookieGenerationContext(final CookieProperties cookie) {
        return buildCookieGenerationContextBuilder(cookie).build();
    }

    /**
     * Build cookie generation context cookie.
     *
     * @param cookie the cookie
     * @return the cookie generation context
     */
    public static CookieGenerationContext buildCookieGenerationContext(final TicketGrantingCookieProperties cookie) {
        val rememberMeMaxAge = (int) Beans.newDuration(cookie.getRememberMeMaxAge()).getSeconds();
        val builder = buildCookieGenerationContextBuilder(cookie);
        return builder.rememberMeMaxAge(rememberMeMaxAge).build();
    }

    private static CookieGenerationContext.CookieGenerationContextBuilder buildCookieGenerationContextBuilder(final CookieProperties cookie) {
        return CookieGenerationContext.builder()
            .name(cookie.getName())
            .path(cookie.getPath())
            .maxAge(cookie.getMaxAge())
            .secure(cookie.isSecure())
            .domain(cookie.getDomain())
            .httpOnly(cookie.isHttpOnly());
    }
}