text:
import os
import fudge
from nose.tools import raises
from testkit import *

def test_temp_directory():
    """Test temp directory correctly deletes"""
    with temp_directory() as temp_dir:
        pass
    assert os.path.exists(temp_dir) == False

def test_in_temp_directory():
    """Test CWD to temp directory"""
    with in_temp_directory() as temp_directory:
        assert os.getcwd() == temp_directory
    assert os.path.exists(temp_directory) == False

def test_in_temp_directory_write_file():
    """Test CWD to temp directory and create file there"""
    with in_temp_directory() as temp_directory:
        # Create a test file in the directory
        test_filename = "test_file.txt"
        test_file = open(test_filename, "w")
        # Put some random data in it
        random_data = random_string(15)
        test_file.write(random_data)
        test_file.close()
        # Attempt to open the file using the full path to the temp directory
        test_file_path = os.path.join(temp_directory, test_filename)
        # Verify contents
        verify_file = open(test_file_path)
        verify_data = verify_file.read()
        assert random_data == verify_data

class TestException(Exception):
    pass

def test_temp_directory_raises_error():
    raised_error = False
    try:
        with temp_directory() as temp_dir:
            raise TestException()
    except TestException:
        raised_error = True
    assert raised_error
    assert not os.path.exists(temp_dir)

@fudge.test
def test_shunt_mixin():
    """Create an object with the ShuntMixin"""
    class FakeClass(ShuntMixin):
        def my_method(self):
            return "before-shunt"

    obj = FakeClass()
    assert obj.my_method() == 'before-shunt'

    obj.__patch_method__('my_method').returns('after-shunt')
    assert obj.my_method() == 'after-shunt'

@raises(AssertionError)
@fudge.test
def test_shunt_mixin_raises_error():
    class FakeClass(ShuntMixin):
        def my_method(self):
            return "before-shunt"

    obj = FakeClass()
    obj.__patch_method__('my_method').with_args('test')
    obj.my_method()

@fudge.test
def test_shunt_mixin_has_no_expectation_on_patch():
    class FakeClass(ShuntMixin):
        def my_method(self):
            return "before-shunt"

    obj = FakeClass()
    (obj.__patch_method__('my_method', expects_call=False).returns('test')
                    .next_call().with_args('hello').returns('world'))
    assert obj.my_method() == 'test'

@fudge.test
def test_shunt_class_factory_method():
    class FakeClass(object):
        def my_method(self):
            return "before-shunt"
    ShuntClass = shunt_class(FakeClass)
    obj = ShuntClass()
    assert obj.my_method() == 'before-shunt'

    obj.__patch_method__('my_method').returns('after-shunt')
    assert obj.my_method() == 'after-shunt'

def test_dict_to_object():
    obj = dict_to_object(dict(a=1, b=2))
    assert obj.a == 1
    assert obj.b == 2


text:
package it.unibz.inf.ontop.spec.mapping.parser;

import it.unibz.inf.ontop.dbschema.*;
import it.unibz.inf.ontop.dbschema.impl.OfflineMetadataProviderBuilder;
import it.unibz.inf.ontop.exception.OBDASpecificationException;
import it.unibz.inf.ontop.injection.OntopMappingSQLAllConfiguration;
import it.unibz.inf.ontop.model.type.DBTypeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static it.unibz.inf.ontop.utils.SQLAllMappingTestingTools.*;

public abstract class AbstractBasicMappingMistakeTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractBasicMappingMistakeTest.class);

    static {
        OfflineMetadataProviderBuilder builder = createMetadataProviderBuilder();
        DBTypeFactory dbTypeFactory = builder.getDBTypeFactory();

        NamedRelationDefinition personTable = builder.createDatabaseRelation("PERSON",
            "ID", dbTypeFactory.getDBLargeIntegerType(), false,
            "FNAME", dbTypeFactory.getDBStringType(), false);
        UniqueConstraint.primaryKeyOf(personTable.getAttribute(1));
    }

    protected void execute(String mappingFile) throws OBDASpecificationException {
        try {
            OntopMappingSQLAllConfiguration configuration = createConfiguration(mappingFile);
            configuration.loadSpecification();
        }
        catch (Exception e) {
            LOGGER.info(e.toString());
            throw e;
        }
    }

    protected abstract OntopMappingSQLAllConfiguration createConfiguration(String mappingFile);
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Terry Harrison's 28th Birthday
date: 2016-05-24
author: Judith Romero
tags: weekly links, java
status: published
summary: Nunc ultricies, nisl quis ornare mollis, diam ligula suscipit purus.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 05/06/2018
  endDate: 05/07/2018
  ctyhocn: HSVALHX
  groupCode: TH2B
published: true
---
Suspendisse molestie ante quis tempor hendrerit. Aliquam erat volutpat. Quisque odio odio, lobortis ac placerat nec, ullamcorper ut odio. Donec vehicula egestas nisi, ac luctus metus pharetra vitae. Duis molestie quis leo non malesuada. Aenean sollicitudin non dolor ut luctus. Maecenas id urna ac libero tincidunt congue. Fusce ac eros ac nisl accumsan mollis. Ut vitae interdum diam.

* Phasellus commodo risus eu urna pharetra, at faucibus erat rhoncus
* Etiam eget felis ullamcorper, faucibus diam nec, pellentesque nisi
* Etiam viverra tellus eget nunc blandit bibendum
* Cras viverra nisi ac justo fermentum, et accumsan odio viverra
* Cras mollis arcu sit amet nunc lobortis, nec iaculis diam ornare.

Duis tempus justo porta magna accumsan, vitae imperdiet lacus dignissim. Sed imperdiet felis orci, quis scelerisque magna rutrum a. Ut fringilla erat at massa auctor ultrices. Pellentesque urna risus, lacinia eu accumsan sit amet, rhoncus in arcu. Suspendisse fermentum enim a quam scelerisque, varius interdum nisi imperdiet. Vestibulum fermentum felis eu nibh volutpat, eget elementum est consectetur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam gravida libero id arcu scelerisque, sed lacinia diam accumsan. Quisque dolor turpis, elementum eget posuere non, mattis sit amet arcu.


text:
#container {
    width: 960px;
    margin: 0 auto;
}

#contentcolumn {
    max-width: 760px;
}
#q {
    width: 150px;
}

img {
    max-width: 90%;
}

.postbox {
    border-bottom: 2px solid darkgrey;
    margin-bottom: 12px;
}

.titlebox {
    text-align: right;
}

#addthisbox {margin-bottom: 12px;}

td.label {
    /* Issue #290 */
    background-color: inherit;
}

.footnote-reference {
    /* Issue 290 */
    vertical-align: super;
    font-size: xx-small;
}

.caption {
    /* Issue 292 */
    text-align: center;
    padding-top: 1em;
}

div.figure > img,
div.figure > a > img {
    /* Issue 292 */
    display: block;
    margin-left: auto;
    margin-right: auto;
}

blockquote p, blockquote {
  font-size: 17.5px;
  font-weight: 300;
  line-height: 1.25;
}

ul.bricks > li {
    display: inline;
    background-color: lightblue;
    padding: 8px;
    border-radius: 5px;
    line-height: 3;
    white-space:nowrap;
    margin: 3px;
}

.at300b, .stMainServices, .stButton, .stButton_gradient {
    box-sizing: content-box;
}

pre, pre code {
    white-space: pre;
    word-wrap: normal;
    overflow: auto;
}

article.post-micro {
    font-family: Georgia, 'Times New Roman', Times, serif;
    font-size: 1.5em;
}

.image-block {
    display: inline-block;
}

.flowr_row {
    width: 100%;
}

.tags {
    padding-left: 0;
    margin-left: 5px;
    list-style: none;
    text-align: left;
}

.tags > li {
    display: inline-block;
    min-width: 10px;
    padding: 3px 7px;
    font-size: 12px;
    font-weight: bold;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    background-color: #999;
    border-radius: 10px;
}

.tags > li a {
    color: #fff;
}

.metadata p:before,
.postlist .listdate:after,
.translationslist p:before {
    content: " — ";
}

.metadata p:first-of-type:before,
.translationslist p:first-of-type:before {
    content: "";
}

.metadata p,
.translationslist p {
    display: inline;
}

.posttranslations h3, .translationslist h3 {
    display: inline;
    font-size: 1em;
    font-weight: bold;
}

.posttranslations h3:last-child, .translationslist h3:last-child {
    display: none;
}

.entry-content {
    margin-top: 1em;
}

.navbar-brand {
    padding: 0 15px;
}

.navbar-brand #blog-title {
    padding: 15px 0;
    display: inline-block;
}

.navbar-brand #logo {
    max-width: 100%;
}

.navbar-brand>img {
    display: inline;
}

.row {
    margin: 0;
}

/* for alignment with Bootstrap's .entry-content styling */
.entry-summary {
    margin-top: 1em;
}

/* Custom page footer */
#footer {
    padding-top: 19px;
    color: #777;
    border-top: 1px solid #e5e5e5;
}

.codetable {
    table-layout: fixed;
}

.codetable pre {
    overflow-x: scroll;
}

/* hat tip bootstrap/html5 boilerplate */
@media print {
    *, *:before, *:after {
        font-family: Garamond, Junicode, serif;
    }

    body {
        font-size: 12pt;
    }

    article .entry-title a[href]:after,
    article .metadata a[href]:after,
    article .tags a[href]:after {
        content: "";
    }

    article .metadata .sourceline {
        display: none;
    }

    article .metadata .linkline a[href]:after {
        content: " (" attr(href) ")";
    }

    .navbar {
        display: none;
    }
}

p.more {
    margin-bottom: 40px;
}


text:
package org.motechproject.nms.kilkari.domain;

import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;
import org.motechproject.nms.props.domain.DayOfTheWeek;

import javax.jdo.annotations.Column;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@Entity(tableName = "nms_kk_retry_records")
public class CallRetry {
    @Field
    private String subscriptionId;

    @Field
    @Min(value = 1000000000L, message = "msisdn must be 10 digits")
    @Max(value = 9999999999L, message = "msisdn must be 10 digits")
    @Column(length = 10)
    private Long msisdn;

    @Field
    private DayOfTheWeek dayOfTheWeek;

    @Field
    private CallStage callStage;

    @Field
    private String contentFileName;

    @Field
    private String weekId;

    @Field
    private String languageLocationCode;

    @Field
    private String circle;

    @Field
    private SubscriptionOrigin subscriptionOrigin;

    public CallRetry() { }

    public CallRetry(String subscriptionId, Long msisdn, //NO CHECKSTYLE More than 7 parameters
                     DayOfTheWeek dayOfTheWeek, CallStage callStage, String contentFileName, String weekId,
                     String languageLocationCode, String circle, SubscriptionOrigin subscriptionOrigin) {
        this.subscriptionId = subscriptionId;
        this.msisdn = msisdn;
        this.dayOfTheWeek = dayOfTheWeek;
        this.callStage = callStage;
        this.contentFileName = contentFileName;
        this.weekId = weekId;
        this.languageLocationCode = languageLocationCode;
        this.circle = circle;
        this.subscriptionOrigin = subscriptionOrigin;
    }

    public String getSubscriptionId() {
        return subscriptionId;
    }

    public void setSubscriptionId(String subscriptionId) {
        this.subscriptionId = subscriptionId;
    }

    public Long getMsisdn() {
        return msisdn;
    }

    public void setMsisdn(Long msisdn) {
        this.msisdn = msisdn;
    }

    public DayOfTheWeek getDayOfTheWeek() {
        return dayOfTheWeek;
    }

    public void setDayOfTheWeek(DayOfTheWeek dayOfTheWeek) {
        this.dayOfTheWeek = dayOfTheWeek;
    }

    public CallStage getCallStage() {
        return callStage;
    }

    public void setCallStage(CallStage callStage) {
        this.callStage = callStage;
    }

    public String getContentFileName() {
        return contentFileName;
    }

    public void setContentFileName(String contentFileName) {
        this.contentFileName = contentFileName;
    }

    public String getWeekId() {
        return weekId;
    }

    public void setWeekId(String weekId) {
        this.weekId = weekId;
    }

    public String getLanguageLocationCode() {
        return languageLocationCode;
    }

    public void setLanguageLocationCode(String languageLocationCode) {
        this.languageLocationCode = languageLocationCode;
    }

    public String getCircle() {
        return circle;
    }

    public void setCircle(String circle) {
        this.circle = circle;
    }

    public SubscriptionOrigin getSubscriptionOrigin() {
        return subscriptionOrigin;
    }

    public void setSubscriptionOrigin(SubscriptionOrigin subscriptionOrigin) {
        this.subscriptionOrigin = subscriptionOrigin;
    }

    @Override
    public String toString() {
        return "CallRetry{" +
                "subscriptionId='" + subscriptionId + '\'' +
                ", msisdn=" + msisdn +
                ", dayOfTheWeek=" + dayOfTheWeek +
                ", callStage=" + callStage +
                ", contentFileName='" + contentFileName + '\'' +
                ", weekId='" + weekId + '\'' +
                ", languageLocationCode='" + languageLocationCode + '\'' +
                ", circle='" + circle + '\'' +
                ", subscriptionOrigin='" + subscriptionOrigin + '\'' +
                '}';
    }
}


text:
r"""Example of basic DEFINE_flag_dict usage.

To run this example with basic config file:
python define_config_dict_basic.py -- \
  --my_config=ml_collections/config_flags/examples/config.py
  \
  --my_config.field1=8 --my_config.nested.field=2.1 \
  --my_config.tuple='(1, 2, (1, 2))'

To run this example with parameterised config file:
python define_config_dict_basic.py -- \
  --my_config=ml_collections/config_flags/examples/parameterised_config.py:linear
  \
  --my_config.model_config.output_size=256'
"""
# pylint: enable=line-too-long

from absl import app

from ml_collections import config_flags

_CONFIG = config_flags.DEFINE_config_file('my_config')

def main(_):
  print(_CONFIG.value)

if __name__ == '__main__':
  app.run(main)


text:
namespace sandbox {

ResultCode ProxyCreateEvent(LPCWSTR name,
                            BOOL initial_state,
                            EVENT_TYPE event_type,
                            void* ipc_memory,
                            CrossCallReturn* answer) {
  CountedParameterSet<NameBased> params;
  params[NameBased::NAME] = ParamPickerMake(name);

  if (!QueryBroker(IPC_CREATEEVENT_TAG, params.GetBase()))
    return SBOX_ERROR_GENERIC;

  SharedMemIPCClient ipc(ipc_memory);
  ResultCode code = CrossCall(ipc, IPC_CREATEEVENT_TAG, name, event_type,
                              initial_state, answer);
  return code;
}

ResultCode ProxyOpenEvent(LPCWSTR name,
                          ACCESS_MASK desired_access,
                          void* ipc_memory,
                          CrossCallReturn* answer) {
  CountedParameterSet<OpenEventParams> params;
  params[OpenEventParams::NAME] = ParamPickerMake(name);
  params[OpenEventParams::ACCESS] = ParamPickerMake(desired_access);

  if (!QueryBroker(IPC_OPENEVENT_TAG, params.GetBase()))
    return SBOX_ERROR_GENERIC;

  SharedMemIPCClient ipc(ipc_memory);
  ResultCode code = CrossCall(ipc, IPC_OPENEVENT_TAG, name, desired_access,
                              answer);

  return code;
}

NTSTATUS WINAPI TargetNtCreateEvent(NtCreateEventFunction orig_CreateEvent,
                                    PHANDLE event_handle,
                                    ACCESS_MASK desired_access,
                                    POBJECT_ATTRIBUTES object_attributes,
                                    EVENT_TYPE event_type,
                                    BOOLEAN initial_state) {
  NTSTATUS status = orig_CreateEvent(event_handle, desired_access,
                                     object_attributes, event_type,
                                     initial_state);
  if (status != STATUS_ACCESS_DENIED || !object_attributes)
    return status;

  // We don't trust that the IPC can work this early.
  if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
    return status;

  do {
    if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
      break;

    void* memory = GetGlobalIPCMemory();
    if (memory == NULL)
      break;

    OBJECT_ATTRIBUTES object_attribs_copy = *object_attributes;
    // The RootDirectory points to BaseNamedObjects. We can ignore it.
    object_attribs_copy.RootDirectory = NULL;

    wchar_t* name = NULL;
    uint32 attributes = 0;
    NTSTATUS ret = AllocAndCopyName(&object_attribs_copy, &name, &attributes,
                                    NULL);
    if (!NT_SUCCESS(ret) || name == NULL)
      break;

    CrossCallReturn answer = {0};
    answer.nt_status = status;
    ResultCode code = ProxyCreateEvent(name, initial_state, event_type, memory,
                                       &answer);
    operator delete(name, NT_ALLOC);

    if (code != SBOX_ALL_OK) {
      status = answer.nt_status;
      break;
    }
    __try {
      *event_handle = answer.handle;
      status = STATUS_SUCCESS;
    } __except(EXCEPTION_EXECUTE_HANDLER) {
      break;
    }
  } while (false);

  return status;
}

NTSTATUS WINAPI TargetNtOpenEvent(NtOpenEventFunction orig_OpenEvent,
                                  PHANDLE event_handle,
                                  ACCESS_MASK desired_access,
                                  POBJECT_ATTRIBUTES object_attributes) {
  NTSTATUS status = orig_OpenEvent(event_handle, desired_access,
                                   object_attributes);
  if (status != STATUS_ACCESS_DENIED || !object_attributes)
    return status;

  // We don't trust that the IPC can work this early.
  if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
    return status;

  do {
    if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
      break;

    void* memory = GetGlobalIPCMemory();
    if (memory == NULL)
      break;

    OBJECT_ATTRIBUTES object_attribs_copy = *object_attributes;
    // The RootDirectory points to BaseNamedObjects. We can ignore it.
    object_attribs_copy.RootDirectory = NULL;

    wchar_t* name = NULL;
    uint32 attributes = 0;
    NTSTATUS ret = AllocAndCopyName(&object_attribs_copy, &name, &attributes,
                                    NULL);
    if (!NT_SUCCESS(ret) || name == NULL)
      break;

    CrossCallReturn answer = {0};
    answer.nt_status = status;
    ResultCode code = ProxyOpenEvent(name, desired_access, memory, &answer);
    operator delete(name, NT_ALLOC);

    if (code != SBOX_ALL_OK) {
      status = answer.nt_status;
      break;
    }
    __try {
      *event_handle = answer.handle;
      status = STATUS_SUCCESS;
    } __except(EXCEPTION_EXECUTE_HANDLER) {
      break;
    }
  } while (false);

  return status;
}

}  // namespace sandbox


text:
CannonSprite = class("CannonSprite", function (...)
	return BuildingBaseSprite:create(...)
end)

CannonSprite.TAG = nil
CannonSprite.subType = "ATKBuilding"

Temple:initBuildingHP(CannonSprite)

function CannonSprite:onEnter()
	self:adjustBarPosition(0, 20)
end

function CannonSprite:create()
	local cannonSprite = CannonSprite.new(IMG_BUILDING_CANNON)

	cannonSprite:onEnter()

	return cannonSprite
end


text:
namespace ixxor {
namespace itl {

template<typename T, bool is_const>
class ring_iterator;

template<typename T>
class ring
{
    template<class Tx, bool isConst> friend class ring_iterator;

public:
    using size_type = std::size_t;
    using value_type = T;
private:

    size_type pos_;
    size_type size_;
    size_type max_size_;
    std::unique_ptr<value_type[]> c_;

public:
    using iterator = ring_iterator<T, false>;
    using const_iterator = ring_iterator<T, true>;

public:
    ring();
    ring(ring const&);
    ring(ring&&);
    ring& operator=(ring const&);
    ring& operator=(ring&&);
    ring(std::initializer_list<value_type> lst);

    explicit ring(size_type count);

    bool empty() const;

    size_type size() const;
    size_type max_size() const;

    void resize(size_type count);
    void resize(size_type count, value_type const& value);

    void push_back(value_type const&);
    template<class... Args>
    void emplace_back(Args&&...);

    iterator begin() { return iterator{this, 0}; }
    const_iterator begin() const { return const_iterator{this, 0}; }
    iterator end() { return iterator{}; }
    const_iterator end() const { return const_iterator{}; }

};

//
// Implementation
//

template<class T>
ring<T>::ring():
    pos_(0u),
    size_(0u),
    max_size_(0u),
    c_(nullptr)
{
}

template<class T>
ring<T>::ring(std::initializer_list<value_type> lst):
    pos_(0u),
    size_(lst.size()),
    max_size_(lst.size()),
    c_(new value_type[lst.size()])
{
    if (size_) {
        std::copy(std::begin(lst), std::end(lst), c_.get());
    }
}

template<class T>
ring<T>::ring(ring const& other)
{
    if (other.max_size()) {
        c_.reset(new value_type[other.max_size()]);
    }
    max_size_ = other.max_size_;
    size_ = other.size_;
    pos_ = 0;
    if (size_) {
        std::copy(other.begin(), other.end(), begin());
    }
}

template<class T>
ring<T>::ring(ring&& other):
    pos_(other.pos_),
    size_(other.size_),
    max_size_(other.max_size_),
    c_(std::move(other.c_))
{
}

template<class T>
ring<T>& ring<T>::operator=(ring<T>&& other)
{
    pos_ = other.pos_;
    size_ = other.size_;
    max_size_ = other.max_size_;
    c_ = std::move(other.c_);
    return *this;
}

template<class T>
ring<T>& ring<T>::operator=(ring<T> const& other)
{
    pos_ = 0;
    size_ = other.size_;
    max_size_ = other.max_size_;
    if (max_size_) {
        c_.reset(new value_type[max_size_]);
        std::copy(other.begin(), other.end(), begin());
    }
    return *this;
}

template<class T>
ring<T>::ring(size_type count):
    ring()
{
    if (count) {
        c_.reset(new value_type[count]);
        max_size_ = count;
    }
}

template<class T>
bool ring<T>::empty() const
{
    return size_==0;
}

template<class T>
typename ring<T>::size_type
ring<T>::size() const
{
    return size_;
}

template<class T>
typename ring<T>::size_type
ring<T>::max_size() const
{
    return max_size_;
}

template<class T>
void ring<T>::resize(size_type count)
{
    assert(count > max_size_); // only enlarging supported for now...
    std::unique_ptr<value_type[]> newp(new value_type[count]);
    std::copy(begin(), end(), newp.get());
    c_ = std::move(newp);
    pos_ = 0;
    max_size_ = count;
}

template<class T>
template<class... Args>
void ring<T>::emplace_back(Args&&... args)
{
    assert(max_size_ > 0);
    value_type* arr = c_.get();
    if (size_ < max_size_) {
        arr[size_] = value_type{std::forward<Args>(args)...};
        ++size_;
        return;
    } else {
        arr[pos_] = value_type{std::forward<Args>(args)...};
        ++pos_;
        if (pos_ == size_) pos_ = 0;
    }
}

template<class T>
void ring<T>::push_back(value_type const& value)
{
    return emplace_back(value);
}

} // :: ixxor::itl
} // :: ixxor

#include "ring_iterator.ipp"

#endif


text:
class RTFusionKalman4 : public RTFusion
{
public:
    RTFusionKalman4();
    ~RTFusionKalman4();

    //  fusionType returns the type code of the fusion algorithm

    virtual int fusionType() { return RTFUSION_TYPE_KALMANSTATE4; }

    //  reset() resets the kalman state but keeps any setting changes (such as enables)

    void reset();

    //  newIMUData() should be called for subsequent updates
    //  deltaTime is in units of seconds

    void newIMUData(RTIMU_DATA& data, const RTIMUSettings *settings);

    //  the following two functions can be called to customize the covariance matrices

    void setQMatrix(RTMatrix4x4 Q) {  m_Q = Q; reset();}
    void setRkMatrix(RTMatrix4x4 Rk) { m_Rk = Rk; reset();}

private:
    void predict();
    void update();

    RTVector3 m_gyro;										// unbiased gyro data
    RTFLOAT m_timeDelta;                                    // time between predictions

    RTQuaternion m_stateQ;									// quaternion state vector
    RTQuaternion m_stateQError;                             // difference between stateQ and measuredQ

    RTMatrix4x4 m_Kk;                                       // the Kalman gain matrix
    RTMatrix4x4 m_Pkk_1;                                    // the predicted estimated covariance matrix
    RTMatrix4x4 m_Pkk;                                      // the updated estimated covariance matrix
    RTMatrix4x4 m_PDot;                                     // the derivative of the covariance matrix
    RTMatrix4x4 m_Q;                                        // process noise covariance
    RTMatrix4x4 m_Fk;                                       // the state transition matrix
    RTMatrix4x4 m_FkTranspose;                              // the state transition matrix transposed
    RTMatrix4x4 m_Rk;                                       // the measurement noise covariance

    //  Note: SInce Hk ends up being the identity matrix, these are omitted

//    RTMatrix4x4 m_Hk;                                     // map from state to measurement
//    RTMatrix4x4> m_HkTranspose;                           // transpose of map
};

#endif // _RTFUSIONKALMAN4_H


text:
package org.adridadou.ethereum.propeller

import java.io.File
import java.util.concurrent.CompletableFuture

import org.adridadou.ethereum.propeller.backend.TestConfig
import org.adridadou.ethereum.propeller.converters.e2e.SolidityConversionHelper
import org.adridadou.ethereum.propeller.keystore.AccountProvider
import org.adridadou.ethereum.propeller.values.EthValue.ether
import org.adridadou.ethereum.propeller.values.{EthAddress, SoliditySource}
import org.scalatest.check.Checkers
import org.scalatest.{FlatSpec, Matchers}

import scala.util.{Failure, Success, Try}

/**
  * Created by davidroon on 11.04.17.
  * This code is released under Apache 2 license
  */
class ContractValidationTest extends FlatSpec with Matchers with Checkers {

  private val mainAccount = SolidityConversionHelper.mainAccount
  private val ethereum = SolidityConversionHelper.facade
  private val contractSource =
    SoliditySource.from(new File("src/test/resources/validationContract.sol"))

  "Validation" should "throw an exception if an interface method doesn't match any of the solidity functions" in {
    val compiledContract =
      ethereum.compile(contractSource).findContract("validationContract").get
    val errorMessage =
      "*** unmatched *** \nsolidity:\n- (uint256) validation(uint256)\njava:\n- validation(String)"

    Try(
      ethereum.createContractProxy(
        compiledContract,
        EthAddress.of("0x38848348887728239023"),
        mainAccount,
        classOf[ValidationContractMethodMismatch]
      )
    ) match {
      case Success(_)  => fail("the call should have failed")
      case Failure(ex) => ex.getMessage shouldEqual errorMessage
    }
  }

  it should "throw an exception if the return value does not match" in {
    val compiledContract =
      ethereum.compile(contractSource).findContract("validationContract").get
    Try(
      ethereum.createContractProxy(
        compiledContract,
        EthAddress.of("0x38848348887728239023"),
        mainAccount,
        classOf[ValidationContractReturnValueMismatch]
      )
    ) match {
      case Success(_) => fail("the call should have failed")
      case Failure(ex) =>
        ex.getMessage shouldEqual "could not find decoder for (uint256) to java.lang.String"
    }
  }

  it should "ignore solidity return type if the java return type is Void" in {
    val compiledContract =
      ethereum.compile(contractSource).findContract("validationContract").get
    Try(
      ethereum.createContractProxy(
        compiledContract,
        EthAddress.of("0x38848348887728239023"),
        mainAccount,
        classOf[ValidationContract]
      )
    ) match {
      case Success(_)  => succeed
      case Failure(ex) => throw ex
    }
  }

}

trait ValidationContractMethodMismatch {
  def validation(value: String): CompletableFuture[Void]
}

trait ValidationContract {
  def validation(value: Integer): CompletableFuture[Void]
}

trait ValidationContractReturnValueMismatch {
  def validation(value: java.lang.Integer): CompletableFuture[String]
}


text:
import random

def mock(text, diversity_bias=0.5, random_seed=None):
	# Error handling
	if diversity_bias < 0 or diversity_bias > 1:
		raise ValueError('diversity_bias must be between the inclusive range [0,1]')
	# Seed the random number generator
	random.seed(random_seed)
	# Mock the text
	out = ''
	last_was_upper = True
	swap_chance = 0.5
	for c in text:
		if c.isalpha():
			if random.random() < swap_chance:
				last_was_upper = not last_was_upper
				swap_chance = 0.5
			c = c.upper() if last_was_upper else c.lower()
			swap_chance += (1-swap_chance)*diversity_bias
		out += c
	return out


text:
## Copyright 2015 JAXIO http://www.jaxio.com
##
## 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.
##
$output.java($enum.converter)##

$output.require("javax.faces.component.UIComponent")##
$output.require("javax.faces.context.FacesContext")##
$output.require("javax.faces.convert.Converter")##
$output.require($enum.model)##

/**
 * JSF converters for {@link ${enum.model.type}}.
 * It is used for multiple select. It supports null value.
 */
$output.dynamicAnnotationTakeOver("javax.inject.Named","javax.inject.Singleton")##
public class $output.currentClass implements Converter {

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
        if (arg2 != null && !arg2.isEmpty()) {
            return ${enum.model.type}.valueOf(arg2);
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
        if (arg2 instanceof $enum.model.type) {
            return (($enum.model.type)arg2).name();
        }
        return "";
    }
}


text:
package eu.monnetproject.coal.translation;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author jmccrae
 */
public class CoalTranslatorTest {

    public CoalTranslatorTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test public void noTest() { }

    /**
     * Test of translate method, of class CoalTranslator.
     */
//    @Test
//    public void testTranslate() throws SQLException {
//        System.out.println("translate");
//     //   Configurator.setConfig("com.mysql.jdsc", "username","root","password","xx","database","acquis","server","localhost");
//        String label = "gatos con juguete";
//        Language srcLang = Language.SPANISH;
//        Language trgLang = Language.ENGLISH;
//        CoalTranslator instance = new CoalTranslator(new Logger() {
//
//            @Override
//            public void log(String message) {
//                System.err.println(message);
//            }
//
//            @Override
//            public void log(String message, Throwable t) {
//                t.printStackTrace();
//            }
//        });
//        Collection<Translation> results = instance.translate(label, srcLang, trgLang);
//        for(Translation t : results) {
//            System.out.println(t.getLabel());
//        }
//    }
}


text:
#ifndef READLINE_H
#define READLINE_H

#include "qemu-common.h"

#define READLINE_CMD_BUF_SIZE 4095
#define READLINE_MAX_CMDS 64
#define READLINE_MAX_COMPLETIONS 256

typedef void ReadLineFunc(Monitor *mon, const char *str, void *opaque);
typedef void ReadLineCompletionFunc(const char *cmdline);

typedef struct ReadLineState {
    char cmd_buf[READLINE_CMD_BUF_SIZE + 1];
    int cmd_buf_index;
    int cmd_buf_size;

    char last_cmd_buf[READLINE_CMD_BUF_SIZE + 1];
    int last_cmd_buf_index;
    int last_cmd_buf_size;

    int esc_state;
    int esc_param;

    char *history[READLINE_MAX_CMDS];
    int hist_entry;

    ReadLineCompletionFunc *completion_finder;
    char *completions[READLINE_MAX_COMPLETIONS];
    int nb_completions;
    int completion_index;

    ReadLineFunc *readline_func;
    void *readline_opaque;
    int read_password;
    char prompt[256];
    Monitor *mon;
} ReadLineState;

void readline_add_completion(ReadLineState *rs, const char *str);
void readline_set_completion_index(ReadLineState *rs, int completion_index);

const char *readline_get_history(ReadLineState *rs, unsigned int index);

void readline_handle_byte(ReadLineState *rs, int ch);

void readline_start(ReadLineState *rs, const char *prompt, int read_password,
                    ReadLineFunc *readline_func, void *opaque);
void readline_restart(ReadLineState *rs);
void readline_show_prompt(ReadLineState *rs);

ReadLineState *readline_init(Monitor *mon,
                             ReadLineCompletionFunc *completion_finder);

#endif /* !READLINE_H */


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

<TITLE>
org.apache.hadoop.mapreduce.server.jobtracker (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.mapreduce.server.jobtracker

Classes

JobTrackerJspHelper

TaskTracker


text:
param(
  [string]$testCloudLocation,
  [string]$app,
  [string]$apiKey,
  [string]$devices,
  [string]$userName,
  [string]$workspace
)

Write-Verbose  "Entering script xtcEspresso.ps1"
Write-Verbose "app = $app"
Write-Verbose "apiKey = $apiKey"
Write-Verbose "devices = $devices"
Write-Verbose "userName = $userName"
Write-Verbose "workspace = $workspace"

# Import the Task.Common and Task.Internal dll that has all the cmdlets we need for Build
# Import the Task.Common and Task.Internal dll that has all the cmdlets we need for Build
$agentWorkerModulesPath = "$($env:AGENT_HOMEDIRECTORY)\externals\vstshost"
$testManagementDllPath = "$($env:AGENT_HOMEDIRECTORY)\bin"

$agentDistributedTaskInternalModulePath = "$agentWorkerModulesPath\Microsoft.TeamFoundation.DistributedTask.Task.Internal\Microsoft.TeamFoundation.DistributedTask.Task.Internal.psd1"
$agentDistributedTaskCommonModulePath = "$agentWorkerModulesPath\Microsoft.TeamFoundation.DistributedTask.Task.Common\Microsoft.TeamFoundation.DistributedTask.Task.Common.psd1"
$agentTestResultsModulePath = "$agentWorkerModulesPath\Microsoft.TeamFoundation.DistributedTask.Task.TestResults\Microsoft.TeamFoundation.DistributedTask.Task.TestResults.psd1"
$agentLegacySdkDllPath = "$agentWorkerModulesPath\Microsoft.TeamFoundation.DistributedTask.Task.LegacySDK.dll"
$testManagementWebApi = "$testManagementDllPath\Microsoft.TeamFoundation.TestManagement.WebApi.dll"

Write-Host "Importing VSTS Module $agentLegacySdkDllPath"
Import-Module $testManagementWebApi
Import-Module $agentLegacySdkDllPath

Write-Host "Importing VSTS Module $agentDistributedTaskInternalModulePath"
Import-Module $agentDistributedTaskInternalModulePath
Write-Host "Importing VSTS Module $agentDistributedTaskCommonModulePath"
Import-Module $agentDistributedTaskCommonModulePath
Write-Host "Importing VSTS Module $agentTestResultsModulePath"
Import-Module $agentTestResultsModulePath

$colItems =  (get-childitem  "$agentWorkerModulesPath" -recurse | tee-object -variable files | measure-object -property length -sum)
$files | foreach-object {write-host $_.FullName}

$parameters = ""

if(!$testCloudLocation){
    throw "Must Specify a Command for xtc"
}

if(!$app){
    throw "Must specify path to APK"
}

if (!$apiKey)
{
    throw "Must specify a Team API key."
}

if (!$devices)
{
    throw "Must specify devices to run the test on"
}

$parameters = "$parameters test $app $apiKey --devices $devices "

if (!$userName)
{
    throw "Must specify a user name"
}

if (!$workspace)
{
    throw "Must specify the workspace."
}

$parameters = "$parameters --user $userName --workspace $workspace"

if (!$testCloudLocation.EndsWith("xtc", "OrdinalIgnoreCase"))
{
    throw "xtc location must end with 'xtc'."
}

#publish results
$buildId = 1;
#$buildId = Get-TaskVariable $distributedTaskContext "build.buildId"
$indx = 0;

# submit app to test cloud
Write-Host "Submit $app to Xamarin Test Cloud."

Invoke-Tool -Path $testCloudLocation -Arguments $parameters -OutVariable toolOutput

foreach($line in $toolOutput)
{
    if($line -imatch "https://testcloud.xamarin.com/test/(.+)/")
    {
        $testCloudResults = ,$matches[0]
    }
}

#upload test summary section
if($testCloudResults)
{
    Write-Verbose "Upload Test Cloud run results summary. testCloudResults = $testCloudResults"
    $mdReportFile = Join-Path $workspace "xamarintestcloud_$buildId.md"
    foreach($result in $testCloudResults)
    {
       Write-Output $result | Out-File $mdReportFile -Append
       Write-Output [Environment]::NewLine | Out-File $mdReportFile -Append
    }
    Write-Host "##vso[task.addattachment type=Distributedtask.Core.Summary;name=Xamarin Test Cloud Results;]$mdReportFile"
}

Write-Verbose "Leaving script xtcEspresso.ps1"


text:
from qnet.utils.indices import IdxSym
from qnet.algebra.core.abstract_algebra import substitute

import sympy
import pytest

def test_idx_sym():
    """Test basic properties of the IdxSym class"""
    with pytest.raises(TypeError):
        IdxSym(sympy.symbols('i'))
    with pytest.raises(ValueError):
        IdxSym('i', primed=-1)
    with pytest.raises(ValueError):
        IdxSym('1')
    with pytest.raises(ValueError):
        IdxSym('i', primed=-1)
    with pytest.raises(ValueError):
        IdxSym('a^2')
    with pytest.raises(TypeError):
        IdxSym('1', 1)

    assert IdxSym('alpha').name == 'alpha'
    assert IdxSym('alpha_kappa').name == 'alpha_kappa'
    assert IdxSym('alpha_1,2').name == 'alpha_1,2'

    i = IdxSym('i')
    assert i.name == 'i'
    assert i.is_symbol
    assert i.is_integer
    assert i.is_finite
    assert i.is_positive is None
    assert not IdxSym('i', integer=False).is_integer
    assert IdxSym('i', positive=True).is_positive

    assert sympy.sqrt(i**2) == sympy.Abs(i)
    i_pos = IdxSym('i', positive=True)
    assert sympy.sqrt(i_pos**2) == i_pos

    assert i.primed == 0
    assert IdxSym('i', primed=1).primed == 1

    assert i != sympy.symbols('i', integer=True)
    assert i != IdxSym('i', primed=1)
    assert i != IdxSym('i', positive=True)
    assert i != IdxSym('i', integer=False)
    assert i == IdxSym('i', integer=True)
    assert IdxSym('i', primed=1) != IdxSym('i', primed=2)
    assert IdxSym('j', primed=1) != IdxSym('i', primed=1)

    expr = sympy.sqrt(IdxSym('n') + 1)
    expr2 = substitute(expr, {IdxSym('n'): IdxSym('n', primed=1)})
    assert expr2 == sympy.sqrt(IdxSym('n', primed=1) + 1)


text:
package uk.ac.ncl.openlab.intake24.sql.tools.food.localisation

import java.io.FileReader

import au.com.bytecode.opencsv.CSVReader
import org.slf4j.LoggerFactory
import uk.ac.ncl.openlab.intake24.api.data.admin.{NewLocalFoodRecord, NewMainFoodRecord}
import uk.ac.ncl.openlab.intake24.api.data.{AssociatedFood, InheritableAttributes}

import scala.collection.JavaConverters._

trait NewLocalFoodsParser {

  private val logger = LoggerFactory.getLogger(classOf[NewLocalFoodsParser])

  def buildNewLocalFoods(csvPath: String, localeCode: String, localNutrientTableId: String, assocFoods: Map[String, Seq[AssociatedFood]]) = {
    val reader = new CSVReader(new FileReader(csvPath))

    var rows = reader.readAll().asScala.toSeq

    val newFoodRecords = rows.map {
      row =>
        val parentCategories = row.drop(5).filterNot(_.isEmpty()).toSeq

        NewMainFoodRecord(row(0), row(2).replace("\"", ""), 0, InheritableAttributes(None, None, None, None), parentCategories, Seq(localeCode))
    }

    val newLocalRecords = rows.map {
      row =>

        val code = row(0)

        val associatedFoods = assocFoods.getOrElse(code, Seq())
        val portionSizeMethods = Seq() // Cannot be set right now due to circular dependencies

        code -> NewLocalFoodRecord(Some(row(3).replace("\"", "")), false, Map(localNutrientTableId -> row(4)), portionSizeMethods, associatedFoods, Seq())
    }.toMap

    reader.close()

    (newFoodRecords, newLocalRecords)
  }
}


text:
class CSprite;
class CSpriteTrail;

class CASW_Pickup_Money : public CASW_Pickup
{
	DECLARE_CLASS( CASW_Pickup_Money, CASW_Pickup );
	DECLARE_SERVERCLASS();
public:
	CASW_Pickup_Money(void);
	virtual ~CASW_Pickup_Money(void);

	virtual void Spawn();
	virtual void Precache();
	virtual void ItemTouch( CBaseEntity *pOther );
	virtual void CreateEffects();

	// money isn't picked up using E
	virtual bool AllowedToPickup(CASW_Marine *pMarine) { return false; }
	virtual bool IsUsable(CBaseEntity *pUser) { return false; }

	CHandle<CSprite>		m_pMainGlow;
	CHandle<CSpriteTrail>	m_pGlowTrail;
};

#endif // _INCLUDED_ASW_PICKUP_MONEY_H


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

using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using MimeKit;

using MailKit.Search;

namespace MailKit.Net.Imap {
	///
	/// An interface for an IMAP folder.
	///
	/// <remarks>
	/// Implemented by <see cref="MailKit.Net.Imap.ImapFolder"/>.
	/// </remarks>
	/// <example>
	///
	/// </example>
	/// <example>
	///
	/// </example>
	public interface IImapFolder : IMailFolder
	{
		///
		/// Get the specified body part headers.
		///
		/// <remarks>
		/// Gets the specified body part headers.
		/// </remarks>
		/// <returns>The body part headers.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested body part headers.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		HeaderList GetHeaders (UniqueId uid, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the specified body part headers.
		///
		/// <remarks>
		/// Gets the specified body part headers.
		/// </remarks>
		/// <returns>The body part headers.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested body part headers.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<HeaderList> GetHeadersAsync (UniqueId uid, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the specified body part headers.
		///
		/// <remarks>
		/// Gets the specified body part headers.
		/// </remarks>
		/// <returns>The body part headers.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested body part headers.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		HeaderList GetHeaders (int index, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the specified body part headers.
		///
		/// <remarks>
		/// Gets the specified body part headers.
		/// </remarks>
		/// <returns>The body part headers.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested body part headers.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<HeaderList> GetHeadersAsync (int index, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the specified body part.
		///
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message body.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		MimeEntity GetBodyPart (UniqueId uid, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the specified body part.
		///
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message body.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<MimeEntity> GetBodyPartAsync (UniqueId uid, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the specified body part.
		///
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		MimeEntity GetBodyPart (int index, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the specified body part.
		///
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<MimeEntity> GetBodyPartAsync (int index, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Gets the streams for the specified messages.</para>
		/// </remarks>
		/// <param name="uids">The uids of the messages.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uids"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="callback"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// One or more of the <paramref name="uids"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		void GetStreams (IList<UniqueId> uids, ImapFetchStreamCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Asynchronously gets the streams for the specified messages.</para>
		/// </remarks>
		/// <returns>An awaitable task.</returns>
		/// <param name="uids">The uids of the messages.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uids"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="callback"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// One or more of the <paramref name="uids"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task GetStreamsAsync (IList<UniqueId> uids, ImapFetchStreamAsyncCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Gets the streams for the specified messages.</para>
		/// </remarks>
		/// <param name="indexes">The indexes of the messages.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="callback"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// One or more of the <paramref name="indexes"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		void GetStreams (IList<int> indexes, ImapFetchStreamCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Asynchronously gets the streams for the specified messages.</para>
		/// </remarks>
		/// <returns>An awaitable task.</returns>
		/// <param name="indexes">The indexes of the messages.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="callback"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// One or more of the <paramref name="indexes"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task GetStreamsAsync (IList<int> indexes, ImapFetchStreamAsyncCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Gets the streams for the specified messages.</para>
		/// </remarks>
		/// <param name="min">The minimum index.</param>
		/// <param name="max">The maximum index, or <c>-1</c> to specify no upper bound.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <para><paramref name="min"/> is out of range.</para>
		/// <para>-or-</para>
		/// <para><paramref name="max"/> is out of range.</para>
		/// </exception>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="callback"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		void GetStreams (int min, int max, ImapFetchStreamCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Asynchronously get the streams for the specified messages.
		///
		/// <remarks>
		/// <para>Asynchronously gets the streams for the specified messages.</para>
		/// </remarks>
		/// <returns>An awaitable task.</returns>
		/// <param name="min">The minimum index.</param>
		/// <param name="max">The maximum index, or <c>-1</c> to specify no upper bound.</param>
		/// <param name="callback"></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <para><paramref name="min"/> is out of range.</para>
		/// <para>-or-</para>
		/// <para><paramref name="max"/> is out of range.</para>
		/// </exception>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="callback"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task GetStreamsAsync (int min, int max, ImapFetchStreamAsyncCallback callback, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null);

		///
		/// Search the folder for messages matching the specified query.
		///
		/// <remarks>
		/// Sends a <c>UID SEARCH</c> command with the specified query passed directly to the IMAP server
		/// with no interpretation by MailKit. This means that the query may contain any arguments that a
		/// <c>UID SEARCH</c> command is allowed to have according to the IMAP specifications and any
		/// extensions that are supported, including <c>RETURN</c> parameters.
		/// </remarks>
		/// <returns>An array of matching UIDs.</returns>
		/// <param name="query">The search query.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="query"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="query"/> is an empty string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		SearchResults Search (string query, CancellationToken cancellationToken = default (CancellationToken));

		///
		/// Asynchronously search the folder for messages matching the specified query.
		///
		/// <remarks>
		/// Sends a <c>UID SEARCH</c> command with the specified query passed directly to the IMAP server
		/// with no interpretation by MailKit. This means that the query may contain any arguments that a
		/// <c>UID SEARCH</c> command is allowed to have according to the IMAP specifications and any
		/// extensions that are supported, including <c>RETURN</c> parameters.
		/// </remarks>
		/// <returns>An array of matching UIDs.</returns>
		/// <param name="query">The search query.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="query"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="query"/> is an empty string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<SearchResults> SearchAsync (string query, CancellationToken cancellationToken = default (CancellationToken));

		///
		/// Sort messages matching the specified query.
		///
		/// <remarks>
		/// Sends a <c>UID SORT</c> command with the specified query passed directly to the IMAP server
		/// with no interpretation by MailKit. This means that the query may contain any arguments that a
		/// <c>UID SORT</c> command is allowed to have according to the IMAP specifications and any
		/// extensions that are supported, including <c>RETURN</c> parameters.
		/// </remarks>
		/// <returns>An array of matching UIDs.</returns>
		/// <param name="query">The search query.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="query"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="query"/> is an empty string.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The IMAP server does not support the SORT extension.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		SearchResults Sort (string query, CancellationToken cancellationToken = default (CancellationToken));

		///
		/// Asynchronously sort messages matching the specified query.
		///
		/// <remarks>
		/// Sends a <c>UID SORT</c> command with the specified query passed directly to the IMAP server
		/// with no interpretation by MailKit. This means that the query may contain any arguments that a
		/// <c>UID SORT</c> command is allowed to have according to the IMAP specifications and any
		/// extensions that are supported, including <c>RETURN</c> parameters.
		/// </remarks>
		/// <returns>An array of matching UIDs.</returns>
		/// <param name="query">The search query.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="query"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="query"/> is an empty string.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The IMAP server does not support the SORT extension.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		Task<SearchResults> SortAsync (string query, CancellationToken cancellationToken = default (CancellationToken));
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="https://bkwang.github.io/favicon.ico">

    <link rel="stylesheet" href="/css/style.min.css">

    <title>TinyXML-2 读取 xml 文件</title>

bkwang.github.io

TinyXML-2 读取 xml 文件
<time>August 22, 2005</time>

<SysMonitor>
<DumpDir>/tmp</DumpDir>
<Monitor>
<app keepalive='false'>/root/demo/App</app>
</Monitor>
</SysMonitor>

int LoadSysmonitorConfig(void)
{
    appInfoList = std::make_shared<EAppInfoList>();

    tinyxml2::XMLDocument doc;
    int rtn = doc.LoadFile("sysmonitor.xml");
    if ( 0 != rtn )
    {
        printf("LoadConfig, load sysmonitor.xml failed\n");
        return -1;
    }

    dumpDir = std::string(doc.FirstChildElement( "SysMonitor" )->FirstChildElement( "DumpDir" )->GetText()) + std::string("/");
    //printf("dumpDir = [%s]\n", dumpDir.c_str());

    for( tinyxml2::XMLElement* ele = doc.FirstChildElement( "SysMonitor" )->FirstChildElement( "Monitor" )->FirstChildElement(); ele; ele = ele->NextSiblingElement() )
    {
        std::shared_ptr<EAppInfo> appInfo = std::make_shared<EAppInfo>();
        ele->QueryBoolAttribute("keepalive", &appInfo->keepalive);
        appInfo->app = std::string(ele->GetText());

        //printf("app = [%s], keepalive = [%d]\n", appInfo->app.c_str(), appInfo->keepalive);
        appInfoList->push_back(appInfo)
    }

    return 0;
}


text:
from __future__ import absolute_import

import abc
import datetime
import six
import uuid

from keystone import exception
from keystone import notifications
from keystone.common import dependency
from keystone.common import extension
from keystone.common import manager
from keystone.openstack.common import log

from oslo.utils import timeutils

LOG = log.getLogger(__name__)

EXTENSION_DATA = {
    'name': 'Keystone User Registration API',
    'namespace': 'http://docs.openstack.org/identity/api/ext/'
                 'OS-REGISTRATION/v1.0',
    'alias': 'OS-REGISTRATION',
    'description': 'Handles creating users with activation through a key',
    'links': [
        {
            'rel': 'describedby',
            # TODO(garcianavalon): needs a description
            'type': 'text/html',
            'href': 'https://github.com/ging/keystone',
        }
    ]}
extension.register_admin_extension(EXTENSION_DATA['alias'], EXTENSION_DATA)
extension.register_public_extension(EXTENSION_DATA['alias'], EXTENSION_DATA)

# TODO(garcianavalon) extract as configuration options in keystone.conf
ACTIVATION_KEY_DURATION = 28800
RESET_TOKEN_DURATION = 28800
DEFAULT_ROLE_ID = ''
DEFAULT_ROLE_NAME = 'owner'

@dependency.requires('assignment_api', 'identity_api')
@dependency.provider('registration_api')
class Manager(manager.Manager):
    """Manager.

    See :mod:`keystone.common.manager.Manager` for more details on
    how this dynamically calls the backend.

    """

    def __init__(self):

        self.event_callbacks = {
            notifications.ACTIONS.deleted: {
                'user': [self.delete_user_projects],
            },
        }

        super(Manager, self).__init__(
            'keystone.contrib.user_registration.backends.sql.Registration')
        # TODO(garcianavalon) set as configuration option in keystone.conf

    def delete_user_projects(self, service, resource_type, operation,
                             payload):
        user_id = payload['resource_info']
        # cloud_project_id = ''
        # default_project_id = ''
        # projects_to_delete = []
        # for project_id in projects_to_delete:
        #     self.assignment_api.delete_project(project_id)
        #     LOG.info('Deleted project %s because user %s was deleted',
        #         project_id, user_id)

        # delete profiles
        self.driver.delete_user_profiles(user_id)

    def request_password_reset(self, user_id):
        """ Prepares a reset profile for the user"""
        profile_ref = {
            'user_id': user_id,
            'expires_at': self._calculate_expiry_date(RESET_TOKEN_DURATION),
            'id': uuid.uuid4().hex,
            'reset_token': uuid.uuid4().hex,
        }
        return self.driver.create_reset_profile(profile_ref)

    def register_user(self, user_ref, cloud_project_id):
        """ Translates the user_ref to an activation profile."""
        profile_ref = {
            'user_id': user_ref['id'],
            'project_id': user_ref['default_project_id'],
            'cloud_project_id': cloud_project_id,
            'expires_at': self._calculate_expiry_date(ACTIVATION_KEY_DURATION),
            'id': uuid.uuid4().hex,
            'activation_key': uuid.uuid4().hex,
        }
        return self.driver.create_activation_profile(profile_ref)

    def _calculate_expiry_date(self, duration_in_seconds):
        expire_delta = datetime.timedelta(seconds=duration_in_seconds)
        return timeutils.utcnow() + expire_delta

    def get_default_role(self):
        """ Obtains the default role to give the user in his default organization. If
        the role doesn't exists creates a new one.
        """
        # NOTE(garcianavalon) mimick v2 Identity API behaviour where both
        # name and id are defined in keystone.conf. But it doesn't look like the
        # perfect solution, are there other better options to handle this?
        if not DEFAULT_ROLE_ID:
            default_role = next(role
                        for role in self.assignment_api.list_roles()
                        if role['name'] == DEFAULT_ROLE_NAME)
        else:
            try:
                default_role = self.assignment_api.get_role(DEFAULT_ROLE_ID)
            except exception.RoleNotFound:
                LOG.info(("Creating the default role {0} because it does not \
                            exist.").format(DEFAULT_ROLE_ID))
                role = {'id': DEFAULT_ROLE_ID,
                        'name': DEFAULT_ROLE_NAME}
                default_role = self.assignment_api.create_role(DEFAULT_ROLE_ID, role)

        return default_role

    def new_activation_key(self, user_id):
        profile_ref = self.driver.get_activation_profile(user_id)
        profile_ref['expires_at'] = self._calculate_expiry_date(ACTIVATION_KEY_DURATION)
        profile_ref['activation_key'] = uuid.uuid4().hex
        return self.driver.store_new_activation_key(
            profile_ref['id'], profile_ref)

    def _assert_expired(self, ref):
        current_time = timeutils.normalize_time(timeutils.utcnow())
        expires = ref['expires_at']
        if current_time > timeutils.normalize_time(expires):
            raise exception.Forbidden()
        return ref

    def get_activation_profile(self, user_id, activation_key=None,
                                check_expired=True):
        profile_ref = self.driver.get_activation_profile(user_id, activation_key)
        if check_expired:
            profile_ref = self._assert_expired(profile_ref)
        return profile_ref

    def get_reset_profile(self, user_id, reset_token,
                                check_expired=True):
        profile_ref = self.driver.get_reset_profile(user_id, reset_token)
        if check_expired:
            profile_ref = self._assert_expired(profile_ref)

        return profile_ref

@six.add_metaclass(abc.ABCMeta)
class Driver(object):
    """Interface description for drivers"""

    @abc.abstractmethod
    def create_activation_profile(self, activation_profile):
        """Create an activation_profile for a newly registered user

        :param activation_profile: activation_profile data
        :type activation_profile: dict
        :returns: activation_profile

        """
        raise exception.NotImplemented()

    @abc.abstractmethod
    def store_new_activation_key(self, profile_id, profile_ref):
        """Update key and expires_at of an activation profile

        :param profile_id: profile_id
        :type profile_id: string
        :param profile_ref: the new data to store
        :type profile_ref: dict
        :returns: activation_profile

        """
        raise exception.NotImplemented()

    @abc.abstractmethod
    def get_activation_profile(self, user_id, activation_key=None):
        """Get activation_profile details for a user, if the key is valid

        :param user_id: id of user that wants to activate
        :type user_id: string
        :param activation_key: provided in the registration process
        :type activation_key: string
        :returns: activation_profile

        """
        raise exception.NotImplemented()

    @abc.abstractmethod
    def create_reset_profile(self, reset_profile):
        """Register a user reset password request

        :param reset_profile: reset_profile data
        :type reset_profile: dict
        :returns: reset_profile

        """
        raise exception.NotImplemented()

    @abc.abstractmethod
    def get_reset_profile(self, user_id, reset_token):
        """Get reset_profile details, if the token is valid

        :param user_id: id of user that wants to activate
        :type user_id: string
        :param reset_token: provided in the registration process
        :type reset_token: string
        :returns: reset_profile

        """
        raise exception.NotImplemented()

    @abc.abstractmethod
    def delete_user_profiles(self, user_id):
        """Delete all user profiles in the database

        :param user_id: id of user that wants to activate
        :type user_id: string
        :returns: None

        """
        raise exception.NotImplemented()


text:
package eu.chargetime.ocpp.model.basic;

import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.basic.types.SetVariableResultType;
import eu.chargetime.ocpp.model.validation.RequiredValidator;
import eu.chargetime.ocpp.model.validation.Validator;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.util.Arrays;
import java.util.Objects;

/**
 * This contains the field definition of the SetVariablesResponse PDU sent by the Charging Station
 * to the CSMS in response to a SetVariablesRequest.
 */
public class SetVariablesConfirmation extends Confirmation {
  private transient Validator<Object> requiredValidator = new RequiredValidator();

  private SetVariableResultType[] setVariableResult;

  /**
   * List of result statuses per Component-Variable.
   *
   * @return SetVariableResultType[]
   */
  public SetVariableResultType[] getSetVariableResult() {
    return setVariableResult;
  }

  /**
   * Required. List of result statuses per Component-Variable.
   *
   * @param setVariableResult SetVariableResultType[]
   */
  public void setSetVariableResult(SetVariableResultType[] setVariableResult) {
    requiredValidator.validate(setVariableResult);
    this.setVariableResult = setVariableResult;
  }

  @Override
  public boolean validate() {
    return setVariableResult != null
        && setVariableResult.length > 0
        && Arrays.stream(setVariableResult)
            .allMatch(setVariableResult -> setVariableResult.validate());
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    SetVariablesConfirmation that = (SetVariablesConfirmation) o;
    return Arrays.equals(setVariableResult, that.setVariableResult);
  }

  @Override
  public int hashCode() {
    return Objects.hash(setVariableResult);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this).add("setVariableResult", setVariableResult).toString();
  }
}


text:
package edu.rpi.rocs;

/**
 * Thrown when a requested function is not implemented by a WSDL endpoint.
 *
 * @author ewpatton
 *
 */
public class WSDLNotImplementedException extends WSDLException {
	private static final long serialVersionUID=18242009L;
}