text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.Azure.Commands.Automation.Properties;
using System;
using System.Collections;
using System.Globalization;
using System.Management.Automation;
using System.Security.Permissions;
using System.Threading;
using Job = Microsoft.Azure.Commands.Automation.Model.Job;

namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
    /// <summary>
    /// Starts an Azure automation runbook.
    /// </summary>
    [Cmdlet("Start", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "AutomationRunbook", DefaultParameterSetName = AutomationCmdletParameterSets.ByAsynchronousReturnJob)]
    [OutputType(typeof(Job), ParameterSetName = new[] { AutomationCmdletParameterSets.ByAsynchronousReturnJob })]
    [OutputType(typeof(PSObject), ParameterSetName = new[] { AutomationCmdletParameterSets.BySynchronousReturnJobOutput })]
    public class StartAzureAutomationRunbook : AzureAutomationBaseCmdlet
    {
        /// <summary>
        /// True to wait for job output
        /// </summary>
        private bool wait;

        /// <summary>
        /// Timeout value
        /// </summary>
        private int timeout = Constants.MaxWaitSeconds;

        /// <summary>
        /// Polling interval
        /// </summary>
        private const int pollingIntervalInSeconds = 5;

        /// <summary>
        /// Gets or sets the runbook name
        /// </summary>
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.ByAsynchronousReturnJob, Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The runbook name.")]
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.BySynchronousReturnJobOutput, Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The runbook name.")]
        [ValidateNotNullOrEmpty]
        [Alias("RunbookName")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the runbook parameters.
        /// </summary>
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.ByAsynchronousReturnJob, Mandatory = false, HelpMessage = "The runbook parameters.")]
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.BySynchronousReturnJobOutput, Mandatory = false, HelpMessage = "The runbook parameters.")]
        public IDictionary Parameters { get; set; }

        /// <summary>
        /// Gets or sets the optional hybrid agent friendly name upon which the runbook should be executed.
        /// </summary>
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.ByAsynchronousReturnJob, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Optional name of the hybrid agent which should execute the runbook")]
        [Parameter(ParameterSetName = AutomationCmdletParameterSets.BySynchronousReturnJobOutput, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Optional name of the hybrid agent which should execute the runbook")]
        [Alias("HybridWorker")]
        public string RunOn { get; set; }

        /// <summary>
        /// Gets or sets the switch parameter to wait for job output
        /// </summary>
        [Parameter(Mandatory = false, ParameterSetName = AutomationCmdletParameterSets.BySynchronousReturnJobOutput, HelpMessage = "Wait for job to complete, suspend, or fail.")]
        public SwitchParameter Wait
        {
            get { return this.wait; }
            set { this.wait = value; }
        }

        /// <summary>
        /// Gets or sets the switch parameter to wait for job output
        /// </summary>
        [Parameter(Mandatory = false, ParameterSetName = AutomationCmdletParameterSets.BySynchronousReturnJobOutput, HelpMessage = "Maximum time in seconds to wait for job completion. Default max wait time is 10800 seconds.")]
        public int MaxWaitSeconds
        {
            get { return this.timeout; }
            set { this.timeout = value; }
        }

        /// <summary>
        /// Execute this cmdlet.
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        protected override void AutomationProcessRecord()
        {
            var job = this.AutomationClient.StartRunbook(this.ResourceGroupName, this.AutomationAccountName, this.Name, this.Parameters, this.RunOn);

            // if no wait, return job object
            if (!this.Wait.IsPresent)
            {
                this.WriteObject(job);
                return;
            }

            // wait for job completion
            if (!PollJobCompletion(job.JobId))
            {
                throw new ResourceCommonException(typeof(Job), string.Format(CultureInfo.CurrentCulture, Resources.JobCompletionMaxWaitReached));
            }

            // retrieve job streams
            var nextLink = string.Empty;
            do
            {
                var jobOutputList = this.AutomationClient.GetJobStream(this.ResourceGroupName, this.AutomationAccountName, job.JobId, null, StreamType.Output.ToString(), ref nextLink);
                foreach (var jobOutputRecord in jobOutputList)
                {
                    var response = this.AutomationClient.GetJobStreamRecordAsPsObject(this.ResourceGroupName, this.AutomationAccountName, job.JobId, jobOutputRecord.StreamRecordId);
                    this.GenerateCmdletOutput(response);
                }
            } while (!string.IsNullOrEmpty(nextLink));
        }

        private bool PollJobCompletion(Guid jobId)
        {
            var timeoutIncrement = 0;
            do
            {
                Thread.Sleep(TimeSpan.FromSeconds(pollingIntervalInSeconds));
                timeoutIncrement += pollingIntervalInSeconds;

                var job = this.AutomationClient.GetJob(this.ResourceGroupName, this.AutomationAccountName, jobId);
                if (!IsJobTerminalState(job))
                {
                    if (IsVerbose()) WriteVerbose(string.Format(Resources.JobProgressState, job.JobId, job.Status, DateTime.Now));
                }
                else
                {
                    if (IsVerbose()) WriteVerbose(string.Format(Resources.JobTerminalState, job.JobId, job.Status, DateTime.Now));
                    return true;
                }
            } while (this.MaxWaitSeconds < 0 || timeoutIncrement <= this.MaxWaitSeconds);

            return false;
        }

        private static bool IsJobTerminalState(Job job)
        {
            return job.Status.Equals(JobState.Completed.ToString(), StringComparison.OrdinalIgnoreCase) ||
                   job.Status.Equals(JobState.Failed.ToString(), StringComparison.OrdinalIgnoreCase) ||
                   job.Status.Equals(JobState.Stopped.ToString(), StringComparison.OrdinalIgnoreCase) ||
                   job.Status.Equals(JobState.Suspended.ToString(), StringComparison.OrdinalIgnoreCase);
        }
    }
}


text:
// Miscellaneous tests with the PRED type that don't fit anywhere else.
#include <memory>

#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/tsl/lib/core/status_test_util.h"
#include "tensorflow/tsl/platform/test.h"

namespace xla {
namespace {

class PredTest : public ClientLibraryTestBase {
 protected:
  void TestCompare(bool lhs, bool rhs, bool expected,
                   std::function<XlaOp(const xla::XlaOp&, const xla::XlaOp&,
                                       absl::Span<const int64_t>)>
                       op) {
    XlaBuilder builder(TestName());
    XlaOp lhs_op = ConstantR0<bool>(&builder, lhs);
    XlaOp rhs_op = ConstantR0<bool>(&builder, rhs);
    op(lhs_op, rhs_op, {});
    ComputeAndCompareR0<bool>(&builder, expected, {});
  }
};

TEST_F(PredTest, ConstantR0PredTrue) {
  XlaBuilder builder(TestName());
  ConstantR0<bool>(&builder, true);
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, ConstantR0PredFalse) {
  XlaBuilder builder(TestName());
  ConstantR0<bool>(&builder, false);
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, ConstantR0PredCompareEq) {
  TestCompare(true, false, false, &Eq);
}

TEST_F(PredTest, ConstantR0PredCompareNe) {
  TestCompare(true, false, true, &Ne);
}

TEST_F(PredTest, ConstantR0PredCompareLe) {
  TestCompare(true, false, false, &Le);
}

TEST_F(PredTest, ConstantR0PredCompareLt) {
  TestCompare(true, false, false, &Lt);
}

TEST_F(PredTest, ConstantR0PredCompareGe) {
  TestCompare(true, false, true, &Ge);
}

TEST_F(PredTest, ConstantR0PredCompareGt) {
  TestCompare(true, false, true, &Gt);
}

TEST_F(PredTest, ConstantR1Pred) {
  XlaBuilder builder(TestName());
  ConstantR1<bool>(&builder, {true, false, false, true});
  ComputeAndCompareR1<bool>(&builder, {true, false, false, true}, {});
}

TEST_F(PredTest, ConstantR2Pred) {
  XlaBuilder builder(TestName());
  ConstantR2<bool>(&builder, {{false, true, true}, {true, false, false}});
  const std::string expected = R"(pred[2,3] {
  { 0, 1, 1 },
  { 1, 0, 0 }
})";
  EXPECT_EQ(expected, ExecuteToString(&builder, {}));
}

TEST_F(PredTest, AnyR1True) {
  XlaBuilder builder(TestName());
  auto a = ConstantR1<bool>(&builder, {true, false});
  Any(a);
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, AnyR1False) {
  XlaBuilder builder(TestName());
  auto a = ConstantR1<bool>(&builder, {false, false});
  Any(a);
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, AnyR1VacuouslyFalse) {
  XlaBuilder builder(TestName());
  auto a = ConstantR1<bool>(&builder, {});
  Any(a);
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, AnyR2True) {
  XlaBuilder builder(TestName());
  auto a = ConstantR2<bool>(&builder, {
                                          {false, false, false},
                                          {false, false, false},
                                          {false, false, true},
                                      });
  Any(a);
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, AnyR2False) {
  XlaBuilder builder(TestName());
  auto a = ConstantR2<bool>(&builder, {
                                          {false, false, false},
                                          {false, false, false},
                                          {false, false, false},
                                      });
  Any(a);
  ComputeAndCompareR0<bool>(&builder, false, {});
}

}  // namespace
}  // namespace xla

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by Lilith on 07/02/2017.
 */
const ContactFormSendingService = require('../../app/lib/contact-form-sending-service');

describe('ContactFormSendingService', () => {
  }
  )


text:
<?php

namespace FrontendApi\Version1;

use App\Model\Entity\Wish;
use App\Model\Service\SessionService;
use App\Model\Service\NotificationService;
use FrontendApi\FrontendResource;
use Kdyby\Doctrine\EntityManager;
use Markatom\RestApp\Api\Response;
use Nette\Utils\DateTime;
use Markatom\RestApp\Routing\AuthorizationException;

/**
 * Resource for Wish CRUD operations.
 *
 * @author	Tomáš Jirásek
 */
class WishesResource extends FrontendResource
{

    /**
     * @param SessionService $sessionService
     * @param NotificationService $notificationService
     * @param EntityManager $em
     */
    public function __construct(SessionService $sessionService, NotificationService $notificationService, EntityManager $em)
    {
        parent::__construct($sessionService, $notificationService, $em);
    }

    /**
     * Creates wish.
     * @return Response Response with Wish object.
     */
    public function create()
    {
        $this->assumeLoggedIn();

        $data = $this->request->getData();

        $wish = new Wish;

        $wish->name = $data['name'];
        $wish->note = $data['note'];
        $wish->interpret = $data['interpret'];
        $wish->user = $this->getActiveSession()->user;
        $wish->created = new DateTime();
        $wish->modified = $wish->created;

        $this->em->persist($wish);
        $this->em->flush();

        return Response::json([
            'id' => $wish->id
        ])->setHttpStatus(Response::HTTP_CREATED);
    }

    /**
     * Read all user's wishes.
     * @return Response Response with array of Wish objects.
     */
    public function readAll()
    {
        $this->assumeLoggedIn(); // only logged can list his wishes

        $wishes = $this->em->getDao(Wish::getClassName())
            ->findBy(['user' => $this->getActiveSession()->user]);

        $wishes = array_map(function (Wish $wish) {
            return [
                'id' => $wish->id,
                'name' => $wish->name,
                'interpret' => $wish->interpret,
                'note' => $wish->note,
                'created' => self::formatDateTime($wish->created),
                'modified' => self::formatDateTime($wish->modified),
            ];
        }, $wishes);

        return response::json($wishes);
    }

    /**
     * Reads detailed information about wish.
     * @param int $id
     * @return Response
     */
    public function read($id)
    {
        /** @var Wish $wish */
        $wish = $this->em->getDao(Wish::getClassName())->find($id);

        if (!$wish) {
            return Response::json([
                'error' => 'UNKNOWN_WISH',
                'message' => 'Wish with given id not found.'
            ])->setHttpStatus(Response::HTTP_NOT_FOUND);
        }

        $this->assumeLoggedIn();

        if ($this->getActiveSession()->user !== $wish->user) {
            throw new AuthorizationException;
        }

        return Response::json([
            'id' => $wish->id,
            'name' => $wish->name,
            'interpret' => $wish->interpret,
            'note' => $wish->note,
            'created' => self::formatDateTime($wish->created),
            'modified' => self::formatDateTime($wish->modified),
        ]);
    }

    /**
     * Updates existing wish.
     * @param int $id
     * @return Response
     */
    public function update($id)
    {
        $data = $this->request->getData();

        /** @var Wish $wish */
        $wish = $this->em->getDao(Wish::getClassName())->find($id);

        if (!$wish) {
            return Response::json([
                'error' => 'UNKNOWN_WISH',
                'message' => 'Wish with given id not found.'
            ])->setHttpStatus(Response::HTTP_NOT_FOUND);
        }

        $this->assumeLoggedIn();

        if ($this->getActiveSession()->user !== $wish->user) {
            throw new AuthorizationException;
        }

        $wish->name = $data['name'];
        $wish->note = $data['note'];
        $wish->interpret = $data['interpret'];
        $wish->modified = new DateTime();

        $this->em->flush();

        return Response::json([
            'id' => $wish->id
        ]);
    }

    /**
     * Delete wish.
     * @param int $id
     * @return Response
     */
    public function delete($id)
    {
        /** @var Wish $wish */
        $wish = $this->em->getDao(Wish::getClassName())->find($id);

        if (!$wish) {
            return Response::json([
                'error' => 'UNKNOWN_WISH',
                'message' => 'Wish with given id not found.'
            ])->setHttpStatus(Response::HTTP_NOT_FOUND);
        }

        $this->assumeLoggedIn();

        if ($this->getActiveSession()->user !== $wish->user) {
            $this->assumeAdmin();
        }

        $this->em->remove($wish);

        $this->em->flush();

        return Response::blank();
    }
}


text:
package at.molindo.scrutineer;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import at.molindo.scrutineer.IdAndVersion;
import at.molindo.scrutineer.StringIdAndVersion;
import at.molindo.scrutineer.StringIdAndVersionFactory;

public class StringIdAndVersionFactoryTest {
	@Mock
	ObjectOutputStream objectOutputStream;

	@Mock
	ObjectInputStream objectInputStream;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void shouldWriteToOutputStream() throws IOException {
		final StringIdAndVersion idAndVersion = new StringIdAndVersion("2", 3);
		StringIdAndVersionFactory.INSTANCE.writeToStream(idAndVersion, objectOutputStream);
		verify(objectOutputStream).writeUTF(idAndVersion.getId());
		verify(objectOutputStream).writeLong(idAndVersion.getVersion());
	}

	@Test
	public void shouldReadFromInputStream() throws IOException {
		when(objectInputStream.readUTF()).thenReturn("10");
		when(objectInputStream.readLong()).thenReturn(10L);

		final IdAndVersion idAndVersion = StringIdAndVersion.FACTORY.readFromStream(objectInputStream);

		assertThat(idAndVersion.getId(), is("10"));
		assertThat(idAndVersion.getVersion(), is(10L));
	}

}


text:
set -e

###
# Arguments:
#
# $1    Container name
# $2    Docker run options
# $3    Image name
# 4$    Additional image arguments
#
###

if [ -f /usr/bin/apt ] ; then
    echo "Using APT package manager"

    apt-get -y update
    apt-get -y install docker.io
elif [ -f /usr/bin/yum ] ; then
    echo "Using YUM package manager"

    yum -y update
    yum install -y docker

    systemctl start docker
    systemctl enable docker
fi

if [ -z "$1" ] ; then
    NAME_ARG=
else
    NAME_ARG=" --name $1"
fi

# Docker run syntax: docker run [OPTIONS] IMAGE:TAG [COMMAND] [ARG...]
#                               |__1-2__| |___3___| |_______ 4_______|

cmd="docker run $NAME_ARG $2 -d $3 $4"

echo "Running command: $cmd"
eval $cmd


text:
package ArabeUnido;

public interface Integrante {

	public void viajar();

	public void concentrase();

	public void jugarPartidos();

	public void entrenar ();
}


text:
#{title}

#{price}

+ $5 shipping

Condition: #{condition}

#{subtitle}

#{description}


text:
/** @jsx React.DOM */

var React = require('react'),
    _ = require('underscore');

module.exports = React.createClass({

    render: function(){
        return

        { (this.props.data.length !== this.props.originalData.length) &&

You are viewing partial results

 }

;
    }
});


text:
{% if DISQUS_SITENAME and article.status != "draft" %}

Comments

	{% include 'includes/disqus_embed.html' %}

{% endif %}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="img/pp-logo.png">

    <title>Public ∏</title>

    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/bootstrap-cosmo.css" rel="stylesheet">

    <link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

    <link href="css/styles.css" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

Home

Podcast

Live

News

Gallery

About Us

Contact

                    <form class="navbar-form navbar-left" role="search" style="width: 300px;">

							<input type="text" class="form-control">

								<button class="btn btn-default btn-searchbox" type="button"></button>

                    </form>

                NASLOV

Jan 31.12.1964

EASY CHANGES // 78 //

Nerv Music records mean / Russia

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque
                penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.
                Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor
                fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla.
                Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Duis mollis, est non
                commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

                NASLOV

Naslov

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque
                penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.
                Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor
                fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla.
                Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Duis mollis, est non
                commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

                NASLOV

Naslov

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque
                penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.
                Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor
                fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla.
                Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Duis mollis, est non
                commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.


text:
/* Custom Stylesheet */
/**
 * Use this file to override Materialize files so you can update
 * the core Materialize files in the future
 *
 * Made By MaterializeCSS.com
 */

.icon-block {
  padding: 0 15px;
}
.icon-block .material-icons {
	font-size: inherit;
}

#left, #middle, #right{
  height: 26px;
  padding-top: 0.5px;
  padding-bottom: 0px;
}

.material-icons {vertical-align: middle;}


text:
@interface ASIS3BucketRequest ()
@property ( unsafe_unretained, unsafe_unretained, nonatomic) ASIS3BucketObject *currentObject;
@property  (unsafe_unretained) NSMutableArray *objects;
@property  (unsafe_unretained) NSMutableArray *commonPrefixes;
@property (assign) BOOL isTruncated;
@end

@implementation ASIS3BucketRequest

- (id)initWithURL:(NSURL *)newURL
{
	self = [super initWithURL:newURL];
	[self setObjects:[[NSMutableArray alloc] init]];
	[self setCommonPrefixes:[[NSMutableArray alloc] init]];
	return self;
}

+ (id)requestWithBucket:(NSString *)theBucket
{
	ASIS3BucketRequest *request = [[self alloc] initWithURL:nil];
	[request setBucket:theBucket];
	return request;
}

+ (id)requestWithBucket:(NSString *)theBucket subResource:(NSString *)theSubResource
{
	ASIS3BucketRequest *request = [[self alloc] initWithURL:nil];
	[request setBucket:theBucket];
	[request setSubResource:theSubResource];
	return request;
}

+ (id)PUTRequestWithBucket:(NSString *)theBucket
{
	ASIS3BucketRequest *request = [self requestWithBucket:theBucket];
	[request setRequestMethod:@"PUT"];
	return request;
}

+ (id)DELETERequestWithBucket:(NSString *)theBucket
{
	ASIS3BucketRequest *request = [self requestWithBucket:theBucket];
	[request setRequestMethod:@"DELETE"];
	return request;
}

- (NSString *)canonicalizedResource
{
	if ([self subResource]) {
		return [NSString stringWithFormat:@"/%@/?%@",[self bucket],[self subResource]];
	}
	return [NSString stringWithFormat:@"/%@/",[self bucket]];
}

- (void)buildURL
{
	NSString *baseURL;
	if ([self subResource]) {
		baseURL = [NSString stringWithFormat:@"%@://%@.%@/?%@",[self requestScheme],[self bucket],[[self class] S3Host],[self subResource]];
	} else {
		baseURL = [NSString stringWithFormat:@"%@://%@.%@",[self requestScheme],[self bucket],[[self class] S3Host]];
	}
	NSMutableArray *queryParts = [[NSMutableArray alloc] init];
	if ([self prefix]) {
		[queryParts addObject:[NSString stringWithFormat:@"prefix=%@",[[self prefix] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	}
	if ([self marker]) {
		[queryParts addObject:[NSString stringWithFormat:@"marker=%@",[[self marker] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	}
	if ([self delimiter]) {
		[queryParts addObject:[NSString stringWithFormat:@"delimiter=%@",[[self delimiter] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	}
	if ([self maxResultCount] > 0) {
		[queryParts addObject:[NSString stringWithFormat:@"max-keys=%hi",[self maxResultCount]]];
	}
	if ([queryParts count]) {
		NSString* template = @"%@?%@";
		if ([[self subResource] length] > 0) {
			template = @"%@&%@";
		}
		[self setURL:[NSURL URLWithString:[NSString stringWithFormat:template,baseURL,[queryParts componentsJoinedByString:@"&"]]]];
	} else {
		[self setURL:[NSURL URLWithString:baseURL]];

	}
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if ([elementName isEqualToString:@"Contents"]) {
		[self setCurrentObject:[ASIS3BucketObject objectWithBucket:[self bucket]]];
	}
	[super parser:parser didStartElement:elementName namespaceURI:namespaceURI qualifiedName:qName attributes:attributeDict];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	if ([elementName isEqualToString:@"Contents"]) {
		[objects addObject:currentObject];
		[self setCurrentObject:nil];
	} else if ([elementName isEqualToString:@"Key"]) {
		[[self currentObject] setKey:[self currentXMLElementContent]];
	} else if ([elementName isEqualToString:@"LastModified"]) {
		[[self currentObject] setLastModified:[[ASIS3Request S3ResponseDateFormatter] dateFromString:[self currentXMLElementContent]]];
	} else if ([elementName isEqualToString:@"ETag"]) {
		[[self currentObject] setETag:[self currentXMLElementContent]];
	} else if ([elementName isEqualToString:@"Size"]) {
		[[self currentObject] setSize:(unsigned long long)[[self currentXMLElementContent] longLongValue]];
	} else if ([elementName isEqualToString:@"ID"]) {
		[[self currentObject] setOwnerID:[self currentXMLElementContent]];
	} else if ([elementName isEqualToString:@"DisplayName"]) {
		[[self currentObject] setOwnerName:[self currentXMLElementContent]];
	} else if ([elementName isEqualToString:@"Prefix"] && [[self currentXMLElementStack] count] > 2 && [[[self currentXMLElementStack] objectAtIndex:[[self currentXMLElementStack] count]-2] isEqualToString:@"CommonPrefixes"]) {
		[[self commonPrefixes] addObject:[self currentXMLElementContent]];
	} else if ([elementName isEqualToString:@"IsTruncated"]) {
		[self setIsTruncated:[[self currentXMLElementContent] isEqualToString:@"true"]];
	} else {
		// Let ASIS3Request look for error messages
		[super parser:parser didEndElement:elementName namespaceURI:namespaceURI qualifiedName:qName];
	}
}

#pragma mark NSCopying

- (id)copyWithZone:(NSZone *)zone
{
	ASIS3BucketRequest *newRequest = [super copyWithZone:zone];
	[newRequest setBucket:[self bucket]];
	[newRequest setSubResource:[self subResource]];
	[newRequest setPrefix:[self prefix]];
	[newRequest setMarker:[self marker]];
	[newRequest setMaxResultCount:[self maxResultCount]];
	[newRequest setDelimiter:[self delimiter]];
	return newRequest;
}

@synthesize bucket;
@synthesize subResource;
@synthesize currentObject;
@synthesize objects;
@synthesize commonPrefixes;
@synthesize prefix;
@synthesize marker;
@synthesize maxResultCount;
@synthesize delimiter;
@synthesize isTruncated;

@end


text:
[The `convert` package](https://godoc.org/github.com/apparentlymart/go-cty/cty/convert)
provides a standard set of type conversion routines for moving between
types in the `cty` type system.

_Conversion_ in this context means taking a given value and producing a
new value of a different type that, in some sense, contains the same
information. For example, the number `5` can be converted to a string as
`"5"`.

Specific conversion operations are represented by type `Conversion`, which
is a function type that takes a single value as input and returns a value
or an error.

## "Safe" and "Unsafe" conversions

The `convert` package broadly organizes its supported conversions into two
types.

"Safe" conversions are ones where all values of the source type can
be represented in the target type, and thus the conversion is guaranteed to
succeed for any value of the source type.

"Unsafe" conversions, on the other hand, are able to convert only a subset
of values of the source type. Values outside of that subset will cause the
conversion function to return an error.

Converting from number to string is safe because an unambiguous string
representation can be created for any number. The converse is _unsafe_,
because while a string like `"2.5"` can be converted to a number, a string
like `"bananas"` cannot.

The calling application must choose whether to attempt unsafe conversions,
depending on whether it is willing to tolerate conversions returning errors
even though they ostensibly passed type checking. Operations that have both
safe and unsafe modes come in couplets, with the unsafe version's name
having the suffix `Unsafe`.

## Getting a Conversion

To find out if a conversion is available between two types, an application can
call either `GetConversion` or `GetConversionUnsafe`. These functions return
a valid `Conversion` if one is available, or `nil` if not.

Note that there are no conversions from a type to itself. Callers should check
if two types are equal before attempting to obtain a conversion between them.

As usual, `cty.DynamicPseudoType` serves as a special-case placeholder. It is
used in two ways, depending on whether it appears in the source or the
destination type:

* When a source type is dynamic, a special unsafe conversion is available that
  takes any value and passes it through verbatim if it matches the destination
  type, or returns an error if it does not. This can be used as part of handling
  dynamic values during a type-checking procedure, with the generated
  conversion serving as a run-time type check.

* When a _destination_ type is dynamic, a simple passthrough conversion is
  generated that does not transform the source value at all. This is supported
  so that a destination type can behave similarly to a type description used
  for a conformance check, thus allowing this package to be used to attempt
  to _make_ a type conformant, rather than merely check whether it already
  is.

## Converting a Value

A value can be converted by passing it as the argument to any conversion whose
source type matches the value's type. If the conversion is an unsafe one, the
conversion function may return an error, in which case the returned value is
invalid and must not be used.

As a convenience, the `Convert` function takes a value and a target type and
returns a converted value if a conversion is available. This is equivalent
to testing for an unsafe conversion for the value's type and then immediately
calling any discovered conversion. An error is returned if a conversion is not
available.

## Type Unification

A related idea to type _conversion_ is type _unification_. While conversion
is concerned with going from a specific source type to a specific target type,
unification is instead concerned with finding a single type that several other
types can be converted to, without any specific preference as to what the
final type is.

A good example of this would be to take a set of values provided to initialize
a list and choose a single type that all of those values can be
converted to, which then decides the element type of the final list.

The `Unify` and `UnifyUnsafe` functions are used for type unification. They
both take as input a slice of types and then return, if possible, a single
target type along with a slice of conversions corresponding to each
of the input types.

Since many type pairs support type conversions in both directions, the unify
functions must apply a preference for which direction to follow given such a
pair of types. These functions prefer safe conversions over unsafe ones
(assuming that `UnifyUnsafe` was called), and prefer lossless conversions
over potentially-lossy ones.

Type unification is a potentially-expensive operation, depending on the
complexity of the passed types and whether they are mutually conformant.

## Conversion Charts

The foundation of the available conversions is the matrix of conversions
between the primitive types. String is the most general type, since the
other two primitive types have safe conversions to string. The full
matrix for primitive types is as follows:

|         | string | number | boolean |
|---------|:------:|:------:|:-------:|
| string  |   n/a  | unsafe |  unsafe |
| number  |  safe  |   n/a  |   none  |
| boolean |  safe  |  none  |   n/a   |

The conversions for compound types are then derived from the above foundation.
For example, a list of numbers can convert to a list of strings
because a number can convert to a string.

The compound type kinds themselves have some available conversions, though:

|        |  tuple | object | list |   map  |     set    |
|--------|:------:|:------:|:----:|:------:|:----------:|
| tuple  |   n/a  |  none  | safe |  none  | safe+lossy |
| object |  none  |   n/a  | none |  safe  |    none    |
| list   | unsafe |  none  |  n/a |  none  | safe+lossy |
| map    |  none  | unsafe | none |   n/a  |    none    |
| set    | unsafe |  none  | safe |  none  |     n/a    |

Conversions between compound kinds, as shown above, are possible only
if their respective elements/attributes also have conversions available.

The conversions from structural types to collection types rely on
type unification to identify a single element type for the final collection,
and so conversion is possible only if unification is possible.


text:
#include <constants.h>
#include <g_mut_root_vp_state.h>

/** @brief stores the root VP state saves */
struct state_save_t *g_mut_root_vp_state[HYPERVISOR_MAX_PPS];


text:
// Messenger class.
// Copyright (C) 2009-2010 Lex Li
//
// 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.

/*
 * Created by SharpDevelop.
 * User: lextm
 * Date: 2009/3/29
 * Time: 17:52
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using Snmp.Core.Security;
using System.Threading.Tasks;

namespace Snmp.Core.Messaging
{
    /// <summary>
    /// Messenger class contains all static helper methods you need to send out SNMP messages.
    /// Static methods in Manager or Agent class will be removed in the future.
    /// </summary>
    /// <remarks>
    /// SNMP v3 is not supported in many methods of this class. Please use <see cref="ISnmpMessage" /> derived classes directly
    /// if you want to do v3 operations.
    /// </remarks>
    public static class Messenger
    {
        /// <summary>
        /// RFC 3416 (3.)
        /// </summary>
        private static readonly NumberGenerator RequestCounter = new NumberGenerator(int.MinValue, int.MaxValue);

        /// <summary>
        /// RFC 3412 (6.)
        /// </summary>
        private static readonly NumberGenerator MessageCounter = new NumberGenerator(0, int.MaxValue);
        private static readonly Oid IdUnsupportedSecurityLevel = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 });
        private static readonly Oid IdNotInTimeWindow = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 });
        private static readonly Oid IdUnknownSecurityName = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 });
        private static readonly Oid IdUnknownEngineID = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 });
        private static readonly Oid IdAuthenticationFailure = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 });
        private static readonly Oid IdDecryptionError = new Oid(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 });

        #region async methods

        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <returns></returns>
        public static async Task<IList<Variable>> GetAsync(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = await message.GetResponseAsync(endpoint).ConfigureAwait(false);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }

        /// <summary>
        /// Sets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <returns></returns>
        public static async Task<IList<Variable>> SetAsync(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new SetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = await message.GetResponseAsync(endpoint).ConfigureAwait(false);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }

        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static async Task<int> WalkAsync(VersionCode version, IPEndPoint endpoint, OctetString community, Oid table, IList<Variable> list, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            var result = 0;
            var tableV = new Variable(table);
            Variable seed;
            var next = tableV;
            var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
            Tuple<bool, Variable> data = new Tuple<bool, Variable>(false, next);
            do
            {
                seed = data.Item2;
                if (seed == tableV)
                {
                    data = await HasNextAsync(version, endpoint, community, seed).ConfigureAwait(false);
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }

                data = await HasNextAsync(version, endpoint, community, seed).ConfigureAwait(false);
            }
            while (data.Item1);
            return result;
        }

        /// <summary>
        /// Determines whether the specified seed has next item.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="community">The community.</param>
        /// <param name="seed">The seed.</param>
        /// <returns>
        ///     <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
        private static async Task<Tuple<bool, Variable>> HasNextAsync(VersionCode version, IPEndPoint endpoint, OctetString community, Variable seed)
        {
            if (seed == null)
            {
                throw new ArgumentNullException(nameof(seed));
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var message = new GetNextRequestMessage(
                RequestCounter.NextId,
                version,
                community,
                variables);

            var response = await message.GetResponseAsync(endpoint).ConfigureAwait(false);
            var pdu = response.Pdu();
            var errorFound = pdu.ErrorStatus.ToErrorCode() == ErrorCode.NoSuchName;
            return new Tuple<bool, Variable>(!errorFound, errorFound ? null : pdu.Variables[0]);
        }

        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static async Task<int> BulkWalkAsync(VersionCode version, IPEndPoint endpoint, OctetString community, Oid table, IList<Variable> list, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            var tableV = new Variable(table);
            var seed = tableV;
            IList<Variable> next;
            var result = 0;
            var message = report;
            var data = await BulkHasNextAsync(version, endpoint, community, seed, maxRepetitions, privacy, message).ConfigureAwait(false);
            next = data.Item2;
            message = data.Item3;
            while (data.Item1)
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
                data = await BulkHasNextAsync(version, endpoint, community, seed, maxRepetitions, privacy, message).ConfigureAwait(false);
            }

            end:
            return result;
        }

        /// <summary>
        /// Sends a TRAP v1 message.
        /// </summary>
        /// <param name="receiver">Receiver.</param>
        /// <param name="agent">Agent.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="generic">Generic code.</param>
        /// <param name="specific">Specific code.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        /// <remarks>This method only supports SNMP v1.</remarks>
        public static async Task SendTrapV1Async(EndPoint receiver, IPAddress agent, OctetString community, Oid enterprise, GenericCode generic, int specific, uint timestamp, IList<Variable> variables)
        {
            var message = new TrapV1Message(VersionCode.V1, agent, community, enterprise, generic, specific, timestamp, variables);
            await message.SendAsync(receiver).ConfigureAwait(false);
        }

        /// <summary>
        /// Sends TRAP v2 message.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="receiver">Receiver.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        /// <param name="requestId">Request ID.</param>
        /// <remarks>This method only supports SNMP v2c.</remarks>
        public static async Task SendTrapV2Async(int requestId, VersionCode version, EndPoint receiver, OctetString community, Oid enterprise, uint timestamp, IList<Variable> variables)
        {
            if (version != VersionCode.V2)
            {
                throw new NotSupportedException("Only SNMP v2c is supported");
            }

            var message = new TrapV2Message(requestId, version, community, enterprise, timestamp, variables);
            await message.SendAsync(receiver).ConfigureAwait(false);
        }

        /// <summary>
        /// Sends INFORM message.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="receiver">Receiver.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <remarks>This method supports SNMP v2c and v3.</remarks>
        public static async Task SendInformAsync(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, Oid enterprise, uint timestamp, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException(nameof(receiver));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException(nameof(enterprise));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            if (version == VersionCode.V3 && privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            if (version == VersionCode.V3 && report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            var message = version == VersionCode.V3
                                    ? new InformRequestMessage(
                                          version,
                                          MessageCounter.NextId,
                                          requestId,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables,
                                          privacy,
                                          MaxMessageSize,
                                          report)
                                    : new InformRequestMessage(
                                          requestId,
                                          version,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables);

            var response = await message.GetResponseAsync(receiver).ConfigureAwait(false);
            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    response);
            }
        }

        /// <summary>
        /// Determines whether the specified seed has next item.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="community">The community.</param>
        /// <param name="seed">The seed.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns>
        /// <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
        private static async Task<Tuple<bool, IList<Variable>, ISnmpMessage>> BulkHasNextAsync(VersionCode version, IPEndPoint receiver, OctetString community, Variable seed, int maxRepetitions, IPrivacyProvider privacy, ISnmpMessage report)
        {
            // TODO: report should be updated with latest message from agent.
            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var request = version == VersionCode.V3
                                                ? new GetBulkRequestMessage(
                                                      version,
                                                      MessageCounter.NextId,
                                                      RequestCounter.NextId,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables,
                                                      privacy,
                                                      MaxMessageSize,
                                                      report)
                                                : new GetBulkRequestMessage(
                                                      RequestCounter.NextId,
                                                      version,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables);
            var reply = await request.GetResponseAsync(receiver).ConfigureAwait(false);
            if (reply is ReportMessage)
            {
                if (reply.Pdu().Variables.Count == 0)
                {
                    // TODO: whether it is good to return?
                    return new Tuple<bool, IList<Variable>, ISnmpMessage>(false, new List<Variable>(0), report);
                }

                var id = reply.Pdu().Variables[0].Id;
                if (id != IdNotInTimeWindow)
                {
                    // var error = id.GetErrorMessage();
                    // TODO: whether it is good to return?
                    return new Tuple<bool, IList<Variable>, ISnmpMessage>(false, new List<Variable>(0), report);
                }

                // according to RFC 3414, send a second request to sync time.
                request = new GetBulkRequestMessage(
                    version,
                    MessageCounter.NextId,
                    RequestCounter.NextId,
                    community,
                    0,
                    maxRepetitions,
                    variables,
                    privacy,
                    MaxMessageSize,
                    reply);
                reply = await request.GetResponseAsync(receiver).ConfigureAwait(false);
            }
            else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    reply);
            }

            var next = reply.Pdu().Variables;
            return new Tuple<bool, IList<Variable>, ISnmpMessage>(next.Count != 0, next, request);
        }

        #endregion

        #region sync methods
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }

        /// <summary>
        /// Sets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Set(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new SetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }

        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static int Walk(VersionCode version, IPEndPoint endpoint, OctetString community, Oid table, IList<Variable> list, int timeout, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            var result = 0;
            var tableV = new Variable(table);
            Variable seed;
            var next = tableV;
            var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
            do
            {
                seed = next;
                if (seed == tableV)
                {
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }
            }
            while (HasNext(version, endpoint, community, seed, timeout, out next));
            return result;
        }

        /// <summary>
        /// Determines whether the specified seed has next item.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="community">The community.</param>
        /// <param name="seed">The seed.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="next">The next.</param>
        /// <returns>
        ///     <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
        private static bool HasNext(VersionCode version, IPEndPoint endpoint, OctetString community, Variable seed, int timeout, out Variable next)
        {
            if (seed == null)
            {
                throw new ArgumentNullException(nameof(seed));
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var message = new GetNextRequestMessage(
                RequestCounter.NextId,
                version,
                community,
                variables);

            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            var errorFound = pdu.ErrorStatus.ToErrorCode() == ErrorCode.NoSuchName;
            next = errorFound ? null : pdu.Variables[0];
            return !errorFound;
        }

        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static int BulkWalk(VersionCode version, IPEndPoint endpoint, OctetString community, Oid table, IList<Variable> list, int timeout, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            var tableV = new Variable(table);
            var seed = tableV;
            IList<Variable> next;
            var result = 0;
            var message = report;
            while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
            }

        end:
            return result;
        }

        /// <summary>
        /// Sends a TRAP v1 message.
        /// </summary>
        /// <param name="receiver">Receiver.</param>
        /// <param name="agent">Agent.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="generic">Generic code.</param>
        /// <param name="specific">Specific code.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        public static void SendTrapV1(EndPoint receiver, IPAddress agent, OctetString community, Oid enterprise, GenericCode generic, int specific, uint timestamp, IList<Variable> variables)
        {
            var message = new TrapV1Message(VersionCode.V1, agent, community, enterprise, generic, specific, timestamp, variables);
            message.Send(receiver);
        }

        /// <summary>
        /// Sends TRAP v2 message.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="receiver">Receiver.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        /// <param name="requestId">Request ID.</param>
        public static void SendTrapV2(int requestId, VersionCode version, EndPoint receiver, OctetString community, Oid enterprise, uint timestamp, IList<Variable> variables)
        {
            if (version != VersionCode.V2)
            {
                throw new NotSupportedException("Only SNMP v2c is supported");
            }

            var message = new TrapV2Message(requestId, version, community, enterprise, timestamp, variables);
            message.Send(receiver);
        }

        /// <summary>
        /// Sends INFORM message.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="receiver">Receiver.</param>
        /// <param name="community">Community name.</param>
        /// <param name="enterprise">Enterprise OID.</param>
        /// <param name="timestamp">Timestamp.</param>
        /// <param name="variables">Variable bindings.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        public static void SendInform(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, Oid enterprise, uint timestamp, IList<Variable> variables, int timeout, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException(nameof(receiver));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException(nameof(enterprise));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            if (version == VersionCode.V3 && privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            if (version == VersionCode.V3 && report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            var message = version == VersionCode.V3
                                    ? new InformRequestMessage(
                                          version,
                                          MessageCounter.NextId,
                                          requestId,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables,
                                          privacy,
                                          MaxMessageSize,
                                          report)
                                    : new InformRequestMessage(
                                          requestId,
                                          version,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables);

            var response = message.GetResponse(timeout, receiver);
            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    response);
            }
        }

        /// <summary>
        /// Determines whether the specified seed has next item.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="community">The community.</param>
        /// <param name="seed">The seed.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="next">The next.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns>
        /// <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
        private static bool BulkHasNext(VersionCode version, IPEndPoint receiver, OctetString community, Variable seed, int timeout, int maxRepetitions, out IList<Variable> next, IPrivacyProvider privacy, ref ISnmpMessage report)
        {
            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var request = version == VersionCode.V3
                                                ? new GetBulkRequestMessage(
                                                      version,
                                                      MessageCounter.NextId,
                                                      RequestCounter.NextId,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables,
                                                      privacy,
                                                      MaxMessageSize,
                                                      report)
                                                : new GetBulkRequestMessage(
                                                      RequestCounter.NextId,
                                                      version,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables);
            var reply = request.GetResponse(timeout, receiver);
            if (reply is ReportMessage)
            {
                if (reply.Pdu().Variables.Count == 0)
                {
                    // TODO: whether it is good to return?
                    next = new List<Variable>(0);
                    return false;
                }

                var id = reply.Pdu().Variables[0].Id;
                if (id != IdNotInTimeWindow)
                {
                    // var error = id.GetErrorMessage();
                    // TODO: whether it is good to return?
                    next = new List<Variable>(0);
                    return false;
                }

                // according to RFC 3414, send a second request to sync time.
                request = new GetBulkRequestMessage(
                    version,
                    MessageCounter.NextId,
                    RequestCounter.NextId,
                    community,
                    0,
                    maxRepetitions,
                    variables,
                    privacy,
                    MaxMessageSize,
                    reply);
                reply = request.GetResponse(timeout, receiver);
            }
            else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    reply);
            }

            next = reply.Pdu().Variables;
            report = request;
            return next.Count != 0;
        }

        /// <summary>
        /// Gets a table of variables.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">Table OID.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Return", Justification = "ByDesign")]
        [SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Body", Justification = "ByDesign")]
        [Obsolete("This method only works for a few scenarios. Will provide new methods in the future. If it does not work for you, parse WALK result on your own.")]
        public static Variable[,] GetTable(VersionCode version, IPEndPoint endpoint, OctetString community, Oid table, int timeout, int maxRepetitions)
        {
            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            IList<Variable> list = new List<Variable>();
            var rows = version == VersionCode.V1 ? Walk(version, endpoint, community, table, list, timeout, WalkMode.WithinSubtree) : BulkWalk(version, endpoint, community, table, list, timeout, maxRepetitions, WalkMode.WithinSubtree, null, null);

            if (rows == 0)
            {
                return new Variable[0, 0];
            }

            var cols = list.Count / rows;
            var k = 0;
            var result = new Variable[rows, cols];

            for (var j = 0; j < cols; j++)
            {
                for (var i = 0; i < rows; i++)
                {
                    result[i, j] = list[k];
                    k++;
                }
            }

            return result;
        }

        #endregion

        /// <summary>
        /// Gets the request counter.
        /// </summary>
        /// <value>The request counter.</value>
        public static int NextRequestId
        {
            get { return RequestCounter.NextId; }
        }

        /// <summary>
        /// Gets the message counter.
        /// </summary>
        /// <value>The message counter.</value>
        public static int NextMessageId
        {
            get { return MessageCounter.NextId; }
        }

        /// <summary>
        /// Max message size used in #SNMP.
        /// </summary>
        /// <remarks>
        /// You can use any value for your own application.
        /// Also this value may be changed in #SNMP in future releases.
        /// </remarks>
        public static int MaxMessageSize { get; set; } = Header.MaxMessageSize;

        /// <summary>
        /// Returns a new discovery request.
        /// </summary>
        /// <returns></returns>
        [Obsolete("Please use GetNextDiscovery")]
        public static Discovery NextDiscovery
        {
            get { return new Discovery(NextMessageId, NextRequestId, MaxMessageSize); }
        }

        /// <summary>
        /// If the privacy module returns failure, then the message can
        /// not be processed, so the usmStatsDecryptionErrors counter is
        /// incremented and an error indication (decryptionError) together
        /// with the OID and value of the incremented counter is returned
        /// to the calling module.
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid DecryptionError
        {
            get { return IdDecryptionError; }
        }

        /// <summary>
        /// If the authentication module returns failure, then the message
        /// cannot be trusted, so the usmStatsWrongDigests counter is
        /// incremented and an error indication (authenticationFailure)
        /// together with the OID and value of the incremented counter is
        /// returned to the calling module.
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid AuthenticationFailure
        {
            get { return IdAuthenticationFailure; }
        }

        /// <summary>
        /// If the value of the msgAuthoritativeEngineID field in the
        /// securityParameters is unknown then
        /// the usmStatsUnknownEngineIDs counter is incremented, and an
        /// error indication (unknownEngineID) together with the OID and
        /// value of the incremented counter is returned to the calling
        /// module.
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid UnknownEngineId
        {
            get { return IdUnknownEngineID; }
        }

        /// <summary>
        /// Information about the value of the msgUserName and
        /// msgAuthoritativeEngineID fields is extracted from the Local
        /// Configuration Datastore (LCD, usmUserTable).  If no information
        /// is available for the user, then the usmStatsUnknownUserNames
        /// counter is incremented and an error indication
        /// (unknownSecurityName) together with the OID and value of the
        /// incremented counter is returned to the calling module.
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid UnknownSecurityName
        {
            get { return IdUnknownSecurityName; }
        }

        /// <summary>
        /// If the message is considered to be outside of the Time Window
        /// then the usmStatsNotInTimeWindows counter is incremented and
        /// an error indication (notInTimeWindow) together with the OID,
        /// the value of the incremented counter, and an indication that
        /// the error must be reported with a securityLevel of authNoPriv,
        /// is returned to the calling module
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid NotInTimeWindow
        {
            get { return IdNotInTimeWindow; }
        }

        /// <summary>
        /// If the information about the user indicates that it does not
        /// support the securityLevel requested by the caller, then the
        /// usmStatsUnsupportedSecLevels counter is incremented and an error
        /// indication (unsupportedSecurityLevel) together with the OID and
        /// value of the incremented counter is returned to the calling
        /// module.
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        public static Oid UnsupportedSecurityLevel
        {
            get { return IdUnsupportedSecurityLevel; }
        }

        /// <summary>
        /// Returns a new discovery request.
        /// </summary>
        /// <param name="type">Message type.</param>
        /// <returns></returns>
        public static Discovery GetNextDiscovery(SnmpType type)
        {
            return new Discovery(NextMessageId, NextRequestId, MaxMessageSize, type);
        }

        /// <summary>
        /// Returns error message for the specific <see cref="Oid"/>.
        /// </summary>
        /// <param name="id">The OID.</param>
        /// <returns>Error message.</returns>
        public static string GetErrorMessage(this Oid id)
        {
            if (id == IdUnsupportedSecurityLevel)
            {
                return "unsupported security level";
            }

            if (id == IdNotInTimeWindow)
            {
                return "not in time window";
            }

            if (id == IdUnknownSecurityName)
            {
                return "unknown security name";
            }

            if (id == IdUnknownEngineID)
            {
                return "unknown engine ID";
            }

            if (id == IdAuthenticationFailure)
            {
                return "authentication failure";
            }

            if (id == IdDecryptionError)
            {
                return "decryption error";
            }

            return "unknown error";
        }
    }
}


text:
import flask
import sys
from flask import request

app = flask.Flask(__name__)

@app.route('/')
def hello_world():
    return flask.jsonify({
        'message': 'Hello World!',
        'python': sys.version,
        'headers': str(request.headers)
    })


text:
+++
Title = "André Ferreira"
Twitter = "_andreferreira_"
image = "andre-ferreira.jpg"
type = "speaker"
linktitle = "andre-ferreira"
+++

#### Speaker

I'm a Senior Cloud Automation Engineer at Blip / PaddyPowerBetfair, working on providing an internal PaaS layer on top of our on-premise OpenStack cloud. We've recently made a number of PoCs regarding containerisation, container orchestration and hybrid-cloud solutions with the 3 main cloud providers.
I come from a Backend background where I was developing high-throughput services. I eventually took a shot at the automation side of life and found out that there is a lot of development to be done in the land of SysAdmins.
Free time is spent with the wife, the dog, reading, gaming and developing games for fun.


text:
title: Defining custom CSS styles
page_title: Defining custom CSS styles
description: Check our Web Forms article about Defining custom CSS styles.
slug: sharepoint/2007/radeditor-for-moss/customization/defining-custom-css-styles
tags: defining,custom,css,styles
published: True
position: 0
---

# Defining custom CSS styles

Telerik RadEditor uses the same CSS files as the default rich-text editor. Those files are **HtmlEditorTableFormats.css** and **HtmlEditorCustomStyles.css,** which are located in the following folder:

`/Program Files/Common Files/Microsoft Shared/web server extensions/12/Template/Layouts/1033/Styles`

>note The folder location can be different if you are not using US English version of MOSS. The 1033 number signifies the current culture and might be different for different language versions of MOSS.

By modifying these CSS files you can add, edit, and delete CSS styles which are displayed in the "Apply CSS class" dropdown and are applied to the editor's content. When defining styles you don't have to use Microsoft's naming convention with the **.ms-rteCustom** prefix.

If you do not wish to modify the default MOSS editor CSS files, you can add your custom styles in another location:

`/Program Files/Common Files/Microsoft Shared/web server extensions/wpresources/RadEditorSharePoint/5.x.x.0**1f131a624888eeed/Resources/CssEditor.css`

This file is **not** created by default when you install RadEditor for MOSS. However, if it is present, the editor will automatically load it. Note that the folder name depends on the editor version (in this case it is 5.3.1.0). Also do not forget to back up the CssEditor.css file when you uninstall/upgrade the editor.

The CssEditor.css file will also be automatically loaded in presentation mode (i.e. when the editor is not visible) in the Web Part and Publishing field (WCM) scenarios. The file will not be loaded in presentation mode when the editor is used in a list (e.g. wiki). This is because we cannot modify the page and add it when the editor is invisible. To workaround this problem you can include this file manually to the master page (using SharePoint Designer) or add it in the MOSS core CSS styles. Either way it will be automatically loaded in presentation as well as authoring (editing) mode. For example, to add the CssEditor.css file in the default MOSS styles, open the file

`/Program Files/Common Files/Microsoft Shared/web server extensions/12/Template/Layouts/1033/Styles/CORE.CSS`

and add the following line:

`@import url("/_wpresources/RadEditorSharePoint/5.x.x.0**1f131a624888eeed/Resources/CssEditor.css");`

RadEditor for MOSS can be configured to load external CSS files as well. Thanks to the CssFiles property, you can specify a list of CSS files, which you need the editor to use. In order to do this you need to modify the respective ToolsFile.xml or ListToolsFile.xml, which are located in the `/Program Files/Common Files/Microsoft Shared/web server extensions/wpresources/RadEditorSharePoint/5.x.x.0**1f131a624888eeed/Resources/` folder. For example if you create **Styles1.css** and **Styles2.css** files in the same folder the code that you need to add is:

````XML
<root>
	....
	<cssFiles>
	   <item name="/_wpresources/RadEditorSharePoint/5.x.x.0**1f131a624888eeed/Resources/Styles1.css" />
	   <item name="/_wpresources/RadEditorSharePoint/5.x.x.0**1f131a624888eeed/Resources/Styles2.css" />
	</cssFiles>
	...
</root>
````

More information you can find in the following online help article: [External CSS Files]({%slug editor/functionality/toolbars/dropdowns/external-css-files%}).

Note that in some scenarios, it is useful to manually check what styles are applied to the editor's content before and after it is submitted. Thus, you can trace if some global styles are ruing your design. This can be easily done using [IE Dev Toolbar](https://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en) or [FireBug](http://getfirebug.com/).

>note Note the version number in the CSS file URL - this should be set to the RadEditor for MOSS version you have - e.g. 5.1.2.0 if your version is 5.12
>

>note Similarly to the default rich-text editor the Telerik RadEditor for MOSS cannot load CSS files from the "Style Library" folder.
>