text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="qa.kurs.adressbook.tests.GroupModificationTest" tests="1" skipped="0" failures="0" errors="0" timestamp="2017-11-08T07:57:17" hostname="DESKTOP-28P1P5D" time="1.919">
  <properties/>
  <testcase name="testGroupModification" classname="qa.kurs.adressbook.tests.GroupModificationTest" time="1.919"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>


text: <!doctype html>

redpajama_set_name: RedPajamaGithub


text:
/*
 * File: TBoardTransferHandler.java
 * 		This file is part of Tico, an application to create and	perform
 * 		interactive communication boards to be used by people with
 * 		severe motor disabilities.
 *
 * Authors: Pablo Muñoz
 *
 * Date: Apr 27, 2006
 *
 * Company: Universidad de Zaragoza, CPS, DIIS
 *
 * License:
 * 		This program is free software: you can redistribute it and/or
 * 		modify it under the terms of the GNU General Public License
 * 		as published by the Free Software Foundation, either version 3
 * 		of the License, or (at your option) any later version.
 *
 * 		This program is distributed in the hope that it will be useful,
 * 		but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * 		GNU General Public License for more details.
 *
 * 		You should have received a copy of the GNU General Public License
 *     	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tico.board;

import org.jgraph.graph.GraphTransferHandler;

/**
 * Equal to GraphTransferHandler but created for future modifications.
 *
 * @author Pablo Muñoz
 * @version 1.0 Nov 20, 2006
 */
public class TBoardTransferHandler extends GraphTransferHandler {
}


text:
package org.eclipse.jface.text.templates.persistence;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import com.ibm.icu.text.MessageFormat;

/**
 * @since 3.0
 */
class TemplatePersistenceMessages {

	private static final String RESOURCE_BUNDLE= TemplatePersistenceMessages.class.getName();
	private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);

	private TemplatePersistenceMessages() {
	}

	public static String getString(String key) {
		try {
			return fgResourceBundle.getString(key);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}

	public static String getFormattedString(String key, Object arg) {
		return MessageFormat.format(getString(key), new Object[] { arg });
	}

	public static String getFormattedString(String key, Object[] args) {
		return MessageFormat.format(getString(key), args);
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import subprocess
import six
from six.moves import range  # pylint: disable=redefined-builtin

def ReadMachOTextLoadAddress(file_name):
  """
  This function returns the load address of the TEXT segment of a Mach-O file.
  """
  regex = re.compile(r".* vmaddr 0x([\dabcdef]*)")
  cmd = ["otool", "-l", file_name]
  output = six.ensure_str(subprocess.check_output(cmd)).split('\n')
  for i in range(len(output) - 3):
    # It's possible to use a regex here instead, but these conditionals are much
    # clearer.
    if ("cmd LC_SEGMENT_64" in output[i] and
        "cmdsize" in output[i + 1] and
        "segname __TEXT" in output[i + 2] and
        "vmaddr" in output[i + 3]):
      result = regex.match(output[i + 3])
      assert result
      return int(result.group(1), 16)
  return None


text:
package org.estatio.module.capex.contributions;

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

import javax.inject.Inject;

import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.Parameter;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.value.Blob;

import org.incode.module.base.dom.MimeTypeData;
import org.incode.module.base.spi.DeriveBlobFromDummyPdfArg0;
import org.incode.module.document.dom.api.DocumentService;
import org.incode.module.document.dom.impl.paperclips.Paperclip;
import org.incode.module.document.dom.impl.paperclips.PaperclipRepository;
import org.incode.module.document.dom.impl.types.DocumentType;
import org.incode.module.document.dom.impl.types.DocumentTypeRepository;

import org.estatio.module.financial.dom.BankAccount;
import org.estatio.module.invoice.dom.DocumentTypeData;

/**
 * This cannot be inlined (needs to be a mixin) because BankAccount does not know about incoming invoices or documents.
 */
@Mixin(method = "act")
public class BankAccount_attachPdfAsIbanProof {

    public static final String ROLE_NAME_FOR_IBAN_PROOF = "iban proof";

    private final BankAccount bankAccount;

    public BankAccount_attachPdfAsIbanProof(BankAccount bankAccount) {
        this.bankAccount = bankAccount;
    }

    @Action(
            semantics = SemanticsOf.IDEMPOTENT,
            commandDtoProcessor = DeriveBlobFromDummyPdfArg0.class
    )
    public BankAccount act(
            @Parameter(fileAccept = MimeTypeData.Str.APPLICATION_PDF)
            final Blob document) {

        final DocumentType ibanProofDocType = DocumentTypeData.IBAN_PROOF.findUsing(documentTypeRepository);

        final List<Paperclip> ibanProofPaperclips =
                paperclipRepository.findByAttachedToAndRoleName(bankAccount, ROLE_NAME_FOR_IBAN_PROOF);

        // delete all existing paperclips for this role whose type is also not IBAN_PROOF
        // (ie any incoming invoices that were automatically attached as candidate iban proofs)
        final Predicate<Paperclip> hasIbanProofDocType =
                paperclip -> Objects.equals(ibanProofDocType, paperclip.getDocument().getType());
        final Predicate<Paperclip> doesNotHaveIbanProofDocType = hasIbanProofDocType.negate();

        ibanProofPaperclips.stream()
                .filter(doesNotHaveIbanProofDocType).forEach(
                    paperclip -> paperclipRepository.delete(paperclip)
                );

        final String name = document.getName();
        documentService.createAndAttachDocumentForBlob(
                ibanProofDocType, bankAccount.getAtPath(), name, document, ROLE_NAME_FOR_IBAN_PROOF, bankAccount);
        return bankAccount;
    }

    @Inject
    PaperclipRepository paperclipRepository;

    @Inject
    DocumentTypeRepository documentTypeRepository;

    @Inject
    DocumentService documentService;

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cassytha dispar Schltdl.

### Remarks
null


text:
![Platform](https://img.shields.io/badge/Platforms-iOS%20%7C%20macOS%20%7C%20Linux-4E4E4E.svg?colorA=EF5138)
[![Swift support](https://img.shields.io/badge/Swift-4.0-lightgrey.svg?colorA=EF5138&colorB=4E4E4E)](#requirements)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/URLQueryItemEncoder.svg?style=flat&label=CocoaPods)](https://cocoapods.org/pods/URLQueryItemEncoder)
![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg?style=flat&colorB=64A5DE)
![Swift Package Manager compatible](https://img.shields.io/badge/SPM-compatible-brightgreen.svg?style=flat&colorB=64A5DE)
[![Twitter](https://img.shields.io/badge/twitter-@pitiphong__p-blue.svg?style=flat&colorB=64A5DE&label=Twitter)](http://twitter.com/pitiphong_p)

A Swift `Encoder` for encoding any `Encodable` value into an array of `URLQueryItem`. As part of the [SE-0166](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md), Swift has a foundation for any type to define how its value should be archived. This encoder allows you to encode those value into an array of `URLQueryItem` which represent that value in one command.

```swift
struct Language {
  let name: String
  let age: Int
}

let person = Language(name: "Swift", age: 4)
let encoder = URLQueryItemEncoder()
let items = try encoder.encode(person)
// items == [URLQueryItem(name: "name", value: "Swift"), URLQueryItem(name: "age", value: "4")]
```

# Requirements
- iOS 8+
- macOS 10.10+
- Swift 4.0+

# Installation
## Manually
This project comes with built in *`URLQueryItemEncoder framework`* target. You can drag `URLQueryItemEncoder.xcproj` file into your project, add `URLQueryItemEncoder framework` target as a target dependency and link/embed that framework. and Voila!!!
```swift
import URLQueryItemEncoder
```
Or you can copy the `URLQueryItemEncoder.swift` file into your project.

## CocoaPods
Add the following to your `Podfile`
```ruby
pod 'URLQueryItemEncoder'
use_frameworks!
```
## Carthage
Add the following to your `Cartfile`
```ruby
github "pitiphong-p/URLQueryItemEncoder"
```

## Swift Package Manager
You can use [Swift Package Manager](https://swift.org/package-manager/) and specify dependency in `Package.swift` by adding this:
```swift
dependencies: [
    .Package(url: "https://github.com/pitiphong-p/URLQueryItemEncoder.git", majorVersion: 0)
]
```

# Usage
The `URLQueryItemEncoder` has a simple and familiar API. It has only 1 method for performing the encoding and 1 strategy for choosing how to encode the `Array Index` key.

```swift
let encoder = URLQueryItemEncoder()
let items = try encoder.encode(person)
```

# Contact
### Pitiphong Phongpattranont
- [@pitiphong_p on Twitter](https://twitter.com/pitiphong_p)

# License
`URLQueryItemEncoder` is released under an MIT License.
Copyright © 2017-present Pitiphong Phongpattranont.


text:
import React from 'react'
import Content from '../../../common/markdown/privacy.md'
import { Section } from '@components/section'

const meta = {
  path: '/legal/privacy-policy',
  title: 'Privacy Policy',
}

class PrivacyPolicyPage extends React.PureComponent {
  static async getInitialProps(ctx) {
    return {
      meta
    }
  }

  render() {
    return (
      <Section>
        <Section.Pane width={1}>
          <Section.Title is="h2" pb={5}>
            {meta.title}
          </Section.Title>
          <Content />
        </Section.Pane>
      </Section>
    )
  }
}

export default PrivacyPolicyPage


text:
namespace ArkeOS.Tools.KohlCompiler.Syntax {
    public sealed class DbgStatementNode : IntrinsicStatementNode {
        public DbgStatementNode(PositionInfo position, ArgumentListNode argumentList) : base(position, argumentList) { }
    }
}


text:
<?php

declare(strict_types=1);

namespace Eelly\SDK\EellyOldCode\Api;

use Eelly\SDK\EellyClient;

class UserContacts
{
    public static function addBlack(int $fromUid, int $fromType, int $toUid, int $toType): bool
    {
        return EellyClient::requestJson('eellyOldCode/userContacts', __FUNCTION__, [
            'fromUid'  => $fromUid,
            'fromType' => $fromType,
            'toUid'    => $toUid,
            'toType'   => $toType,
        ]);
    }

    public static function unBlack(int $fromUid, int $fromType, int $toUid, int $toType): bool
    {
        return EellyClient::requestJson('eellyOldCode/userContacts', __FUNCTION__, [
            'fromUid'  => $fromUid,
            'fromType' => $fromType,
            'toUid'    => $toUid,
            'toType'   => $toType,
        ]);
    }

    public static function isBlack(int $fromUid, int $fromType, int $toUid, int $toType): bool
    {
        return EellyClient::requestJson('eellyOldCode/userContacts', __FUNCTION__, [
            'fromUid'  => $fromUid,
            'fromType' => $fromType,
            'toUid'    => $toUid,
            'toType'   => $toType,
        ]);
    }

    public static function generateContacts(int $uid, int $type): bool
    {
        return EellyClient::requestJson('eellyOldCode/userContacts', __FUNCTION__, [
            'uid'  => $uid,
            'type' => $type,
        ]);
    }

    public static function getFocusLiverNumByUserId(int $fromUid, int $fromType):int
    {
        return EellyClient::requestJson('eellyOldCode/userContacts', __FUNCTION__, [
            'fromUid'  => $fromUid,
            'fromType' => $fromType,
        ]);
    }
}


text:
//
// CSVReaderBuilderTest.cs
//
// Author:
//       tsntsumi <tsntsumi@tsntsumi.com>
//
// Copyright (c) 2016 tsntsumi
//
// 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;
using System.IO;
using System.Text;
using NUnit.Framework;
using SimpleCSV;

namespace SimpleCSVTest
{
    public class CSVReaderBuilderTest
    {
        private CSVReaderBuilder builder;
        private TextReader reader;

        [SetUp]
        public void SetUp()
        {
            reader = new StringReader("");
            builder = new CSVReaderBuilder(reader);
        }

        [Test]
        public void TestDefaultBuilder()
        {
            Assert.AreSame(reader, builder.Reader);
            Assert.Null(builder.CsvParser);
            Assert.AreEqual(CSVReader.DefaultSkipLines, builder.SkipLines);

            CSVReader csvReader = builder.Build();
            Assert.AreEqual(CSVReader.DefaultSkipLines, csvReader.SkipLines);
        }

        [Test]
        public void TestNullReader()
        {
            Assert.Throws<ArgumentNullException>(() => builder = new CSVReaderBuilder(null));
        }

        [Test]
        public void TestWithCSVParserNull()
        {
            builder.WithCSVParser(new CSVParser());
            builder.WithCSVParser(null);
            Assert.Null(builder.CsvParser);
        }

        [Test]
        public void TestWithCSVParser()
        {
            CSVParser csvParser = new CSVParser();
            builder.WithCSVParser(csvParser);
            Assert.AreSame(csvParser, builder.CsvParser);

            CSVReader actual = builder.Build();
            Assert.AreSame(csvParser, actual.Parser);
        }

        [Test]
        public void TestWithSkipLines()
        {
            builder.WithSkipLines(99);

            Assert.AreEqual(99, builder.SkipLines);

            CSVReader actual = builder.Build();
            Assert.AreEqual(99, actual.SkipLines);
        }

        [Test]
        public void TestWithSkipLinesZero()
        {
            builder.WithSkipLines(0);

            Assert.AreEqual(0, builder.SkipLines);

            CSVReader actual = builder.Build();
            Assert.AreEqual(0, actual.SkipLines);
        }

        [Test]
        public void TestWithSkipLinesNegative()
        {
            builder.WithSkipLines(-1);

            Assert.AreEqual(0, builder.SkipLines);

            CSVReader actual = builder.Build();
            Assert.AreEqual(0, actual.SkipLines);
        }

        [Test]
        public void TestWithNullFieldIndicator()
        {
            CSVReader reader = builder.WithFieldAsNull(CSVReaderNullFieldIndicator.EmptySeparators).Build();

            Assert.AreEqual(CSVReaderNullFieldIndicator.EmptySeparators, reader.Parser.NullFieldIndicator);
        }
    }
}


text:
--TEST--
Test round() function :  error conditions - incorrect number of args
--FILE--
<?php
/* Prototype  : float round  ( float $val  [, int $precision  ] )
 * Description: Returns the rounded value of val  to specified precision (number of digits
 * after the decimal point)
 * Source code: ext/standard/math.c
 */

/*
 * Pass incorrect number of arguments to round() to test behaviour
 */

echo "*** Testing round() : error conditions ***\n";

echo "\n-- Wrong nmumber of arguments --\n";
var_dump(round());
var_dump(round(500, 10, true));

?>
===Done===
--EXPECTF--
*** Testing round() : error conditions ***

-- Wrong nmumber of arguments --

Warning: round() expects at least 1 parameter, 0 given in %s on line %d
NULL
float(500)
===Done===


text:
using System;
using NUnit.Framework;
using Symbooglix;
using Microsoft.Boogie;
using System.Numerics;

namespace ExprBuilderTests.ConstantFoldingTests
{
    [TestFixture()]
    public class FoldBVCONCAT : ConstantFoldingExprBuilderTests
    {
        // Brute force
        [TestCase(8, 8)]
        public void simpleConstants(int msbMaxBitWidth, int lsbMaxBitWidth)
        {
            var cfb = GetConstantFoldingBuilder();
            for (int msbBitWidth=1; msbBitWidth <= msbMaxBitWidth ; ++msbBitWidth)
            {
                int msbMaxValue = (1 << msbBitWidth) -1;
                for (int lsbBitWidth=1; lsbBitWidth <= lsbMaxBitWidth; ++lsbBitWidth)
                {
                    int lsbMaxValue = (1 << lsbBitWidth) -1;
                    for (int msbValue = 0; msbValue <= msbMaxValue; ++msbValue)
                    {
                        Expr msbExpr = cfb.ConstantBV(msbValue, msbBitWidth);
                        for (int lsbValue = 0; lsbValue <= lsbMaxValue; ++lsbValue)
                        {
                            Expr lsbExpr = cfb.ConstantBV(lsbValue, lsbBitWidth);
                            var result = cfb.BVCONCAT(msbExpr, lsbExpr);
                            var expectedWidth = msbBitWidth + lsbBitWidth;
                            CheckIsBvType(result, expectedWidth);
                            var asLit = ExprUtil.AsLiteral(result);

                            var expectedValueInDecimalRepr = ((new BigInteger(msbValue)) << lsbBitWidth) + (new BigInteger(lsbValue));
                            Assert.IsNotNull(asLit);
                            Assert.AreEqual(expectedValueInDecimalRepr, asLit.asBvConst.Value.ToBigInteger);
                        }
                    }
                }
            }
        }

        [Test()]
        public void MSBIsZero()
        {
            var cfb = GetConstantFoldingBuilder();
            var msb = cfb.ConstantBV(0, 8);
            var lsb = GetVarAndIdExpr("x", BasicType.GetBvType(4)).Item2;
            var result = cfb.BVCONCAT(msb, lsb);

            var asBvZExt = ExprUtil.AsBVZEXT(result);
            Assert.IsNotNull(asBvZExt);
            CheckIsBvType(result, 12);
            Assert.AreSame(lsb, asBvZExt.Args[0]);
        }

        [Test()]
        public void noFold()
        {
            var pair = GetSimpleAndConstantFoldingBuilder();
            var sb = pair.Item1;
            var cfb = pair.Item2;
            var id0 = GetVarAndIdExpr("foo0", BasicType.GetBvType(8)).Item2;
            var id1 = GetVarAndIdExpr("foo1", BasicType.GetBvType(8)).Item2;
            var foldedResult = cfb.BVCONCAT(id0, id1);
            var simpleResult = sb.BVCONCAT(id0, id1);

            // FIXME: Typechecking a BvConcatExpr is broken in Boogie, it tries to change the type!
            //CheckIsBvType(foldedResult, 16);
            Assert.IsTrue(foldedResult.Type.IsBv);
            Assert.AreEqual(16, foldedResult.Type.BvBits);

            Assert.AreEqual(simpleResult, foldedResult);

            var asBvConcat = ExprUtil.AsBVCONCAT(foldedResult);
            Assert.IsNotNull(asBvConcat);
            Assert.AreSame(id0, asBvConcat.E0);
            Assert.AreSame(id1, asBvConcat.E1);
        }

        [Test()]
        public void ConcatExtractsToOriginal()
        {
            var cfb = GetConstantFoldingBuilder();
            var id = GetVarAndIdExpr("x", BasicType.GetBvType(16)).Item2;
            var msb = cfb.BVEXTRACT(id, 16, 8);
            var lsb = cfb.BVEXTRACT(id, 8, 0);
            var result = cfb.BVCONCAT(msb, lsb);
            CheckIsBvType(result, 16);
            Assert.AreSame(id, result);
        }

        [Test()]
        public void ConcatExtractsToSingleExtract()
        {
            var cfb = GetConstantFoldingBuilder();
            var id = GetVarAndIdExpr("x", BasicType.GetBvType(16)).Item2;
            var msb = cfb.BVEXTRACT(id, 16, 8);
            var lsb = cfb.BVEXTRACT(id, 8, 5);
            var result = cfb.BVCONCAT(msb, lsb);
            CheckIsBvType(result, 11);
            var asBvExtract = ExprUtil.AsBVEXTRACT(result);
            Assert.IsNotNull(asBvExtract);
            Assert.AreSame(id, asBvExtract.Bitvector);
            Assert.AreEqual(16, asBvExtract.End);
            Assert.AreEqual(5, asBvExtract.Start);
        }

        [Test()]
        public void ConcatExtractsNoFold()
        {
            var cfb = GetConstantFoldingBuilder();
            var id0 = GetVarAndIdExpr("x", BasicType.GetBvType(16)).Item2;
            var id1 = GetVarAndIdExpr("y", BasicType.GetBvType(16)).Item2;
            var msb = cfb.BVEXTRACT(id0, 16, 8);
            var lsb = cfb.BVEXTRACT(id1, 8, 0);

            // Different variables so this should not be simplified to a single extract
            var result = cfb.BVCONCAT(msb, lsb);

            // FIXME: Can't check type due to bugs in Boogie. It tries to change the type on immutabl Expr
            // CheckIsBvType(result, 16);
            Assert.IsTrue(result.Type.IsBv);
            Assert.AreEqual(16, result.Type.BvBits);

            var asBvConcat = ExprUtil.AsBVCONCAT(result);
            Assert.IsNotNull(asBvConcat);
            Assert.AreSame(msb, asBvConcat.E0);
            Assert.AreSame(lsb, asBvConcat.E1);
        }
    }
}


text:
/**
 * Stanzas and extension elements for XEP-332: HTTP over XMPP transport.
 */
package org.jivesoftware.smackx.hoxt.packet;


text:
package bits.collect;

import org.junit.Test;

import java.util.*;

/**
 * @author Philip DeCamp
 */
public class LongHashSetTest extends LongSetInterfaceTest {

    public LongHashSetTest() {
        super( true, true, true, true, true );
    }

    @Override
    protected LongSet makeEmptySet() throws UnsupportedOperationException {
        return new LongHashSet();
    }

    @Override
    protected LongSet makePopulatedSet() throws UnsupportedOperationException {
        Random rand = new Random( 100 );
        LongSet ret = new LongHashSet();

        for( int i = 0; i < 1000; i++ ) {
            long k = rand.nextInt( 500 );
            ret.add( k );
        }

        return ret;
    }

    @Override
    protected long getItemNotInPopulatedSet() throws UnsupportedOperationException {
        return Long.MIN_VALUE;
    }

    public void testAddRemoveClear() {
        Set<Long> normSet   = new HashSet<Long>();
        LongHashSet longSet = new LongHashSet();
        Random rand = new Random( 0 );

        for( int i = 0; i < 1000; i++ ) {
            Long n   = (long)rand.nextInt( 100 );
            normSet.add( n );
            longSet.add( n );
        }
        compare( normSet, longSet );

        for( int i = 0; i < 50; i++ ) {
            Long n = (long)rand.nextInt( 100 );
            normSet.remove( n );
            longSet.remove( n );
        }
        compare( normSet, longSet );

        normSet.clear();
        longSet.clear();

        compare( normSet, longSet );
    }

    public void testIterRemove() {
        Set<Long> normSet   = new HashSet<Long>();
        LongHashSet longSet = new LongHashSet();
        Random rand = new Random( 0 );

        for( int i = 0; i < 1000; i++ ) {
            Long n   = (long)rand.nextInt( 100 );
            normSet.add( n );
            longSet.add( n );
        }

        // Check remove on iterator.
        LongIterator iter = longSet.iterator();
        while( iter.hasNext() ) {
            long key = iter.next();
            if( rand.nextBoolean() ) {
                iter.remove();
                normSet.remove( key );
            }
        }
        compare( normSet, longSet );
    }

    public void testContains() {
        LongHashSet longSet = new LongHashSet();
        Random rand = new Random( 0 );

        for( int i = 0; i < 1000; i++ ) {
            Long n   = (long)rand.nextInt( 100 );
            longSet.add( n );
        }

        // Check remove on iterator.
        LongIterator iter = longSet.iterator();
        while( iter.hasNext() ) {
            long e = iter.next();
            assertTrue( "Failed contains()", longSet.contains( e ) );
            if( rand.nextBoolean() ) {
                iter.remove();
                assertFalse( "Failed containsKey()", longSet.contains( e ) );
            }
        }
    }

    private static boolean compare( Set<Long> x, LongHashSet y ) {
        assertTrue( "Size mismatch", x.size() == y.size() );

        for( Long k : x ) {
            assertTrue( "Contains mismatch", y.contains( k ) );
        }

        LongIterator iter = y.iterator();
        while( iter.hasNext() ) {
            long item = iter.next();
            assertTrue( "Contains Mismatch", y.contains( item ) && x.contains( item ) );
        }

        return true;
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#pragma once

#include <string>
#include <unordered_set>

#include "core/common/status.h"
#include "core/graph/model.h"
#include "orttraining/core/session/training_session.h"

namespace onnxruntime {
namespace training {

/**
 * The training configuration options.
 */
struct OrtModuleGraphBuilderConfiguration {
  // The names of the weights.
  std::vector<std::string> initializer_names{};
  // The names of the weights to train.
  std::vector<std::string> initializer_names_to_train{};
  // The names of inputs that require gradient.
  std::vector<std::string> input_names_require_grad{};

  // Graph configuration.
  bool use_memory_efficient_gradient = false;
  bool build_gradient_graph = true;
  bool enable_caching = false;

  // Graph transformer configuration
  TrainingGraphTransformerConfiguration graph_transformer_config{};

  // Log severity
  logging::Severity loglevel{logging::Severity::kWARNING};
};

/**
 * The information of graphs for frontend.
 */
struct GraphInfo {
  // The user inputs.
  std::vector<std::string> user_input_names{};
  // Map from user input names to corresponding user input grad names for those user inputs that require grad.
  std::unordered_map<std::string, std::string> user_input_grad_names{};
  // All initializers (trainable as well as non trainable).
  std::vector<std::string> initializer_names{};
  // Trainable initializers.
  std::vector<std::string> initializer_names_to_train{};
  // Trainable initializer grad names, ordered according to initializer_names_to_train.
  std::vector<std::string> initializer_grad_names_to_train{};
  // The user outputs.
  std::vector<std::string> user_output_names{};
  // Indices of output grads that are non-differentiable.
  std::vector<size_t> output_grad_indices_non_differentiable{};
  // Indices of output grads that need to be materialized to full size all-0 tensor.
  // Otherwise, we can use scalar-0 tensor.
  std::vector<size_t> output_grad_indices_require_full_shape{};
  // Indices of module output that are needed for backward computation
  std::vector<size_t> module_output_indices_requires_save_for_backward{};
  // Names of module outputs' gradient
  std::vector<std::string> module_output_gradient_name{};
  // Names of the frontier tensor corresponding to param
  std::unordered_map<std::string, std::string> frontier_node_arg_map{};
  // Names of the frontier NodeArgs in the order in which they will
  // be retrieved in the forward pass
  std::vector<std::string> cached_node_arg_names{};
};

class OrtModuleGraphBuilder {
 public:
  /**
   * Initialize the builder. It saves the initial model and the configuration.
   * It also removes the trainable initializers from initial model and move them to graph inputs.
   * @param model_istream The initial model as input stream.
   * @param config The configuration to control the builder.
   * @return The status of the initialization.
   */
  Status Initialize(std::istream& model_istream, const OrtModuleGraphBuilderConfiguration& config);

  /**
   * Optimize the inference graph and build the gradient graph.
   * @param input_shapes_ptr The pointer to vector of concrete shapes of the user inputs.
   * @return The status of the optimizing and building the gradient graph.
   */
  Status Build(const std::vector<std::vector<int64_t>>* input_shapes_ptr = nullptr);

  /**
   * Get gradient model.
   * @return The optimized gradient model serialized to string.
   */
  std::string GetGradientModel() const;

  /**
   * Get inference/forward model. If it's training mode, the forward model is optimized.
   * @return The inference/gradient model serialized to string.
   */
  std::string GetForwardModel() const;

  /**
   * Get the graphs information.
   * @return The graphs information.
   */
  GraphInfo GetGraphInfo() const { return graph_info_; }

 private:
  // Set concrete shapes for graph inputs.
  Status SetConcreteInputShapes(const std::vector<std::vector<int64_t>>& input_shapes);

  // Apply graph transformers
  Status OptimizeForwardGraph(std::unordered_set<std::string>& x_node_arg_names);

  // Build gradient graph.
  Status BuildGradientGraph(const std::unordered_set<std::string>& x_node_arg_names);

  // Get the "frontier" tensors- the the output of series of operations
  // that only depend on the param values, eg Casting a param
  void GetFrontierTensors();

  // Handle user outputs and output grads.
  void HandleOutputsAndGrads();

  // Reorder gradient graph outputs.
  void ReorderOutputs();

  // Find the module output that are needed for backward computation
  void FindModuleOutputNeededForBackward();

  // Update require grad info for PythonOp.
  void UpdatePythonOpInputsRequireGradInfo(
      const std::unordered_map<std::string, std::vector<int64_t>>& python_op_input_require_grad_info);

  std::shared_ptr<onnxruntime::Model> original_model_;
  // For training case, the forward_model_ is the model after applying training graph transformers.
  // For inference case, the forward_model_ is same as original_model_ and have concrete shapes set if required.
  std::shared_ptr<onnxruntime::Model> forward_model_;
  std::shared_ptr<onnxruntime::Model> gradient_model_;
  GraphInfo graph_info_;

  OrtModuleGraphBuilderConfiguration config_;
  const logging::Logger* logger_ = &logging::LoggingManager::DefaultLogger();  // use default logger for now.
};

}  // namespace training
}  // namespace onnxruntime


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.mirth.project</groupId>
  <artifactId>mirthblog</artifactId>
  <packaging>jar</packaging>
  <version>0.9</version>
  <name>mirthblog</name>
  <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk</artifactId>
      <version>1.11.22</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>
  </dependencies>
    <build>
        <resources>
            <resource>
                <directory>${env.HOME}/.aws/</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>org.mirth.project.MCAWS</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
namespace Microsoft.Azure.Management.SignalR.Models
{

    /// <summary>
    /// Defines values for UpstreamAuthType.
    /// </summary>
    public static class UpstreamAuthType
    {
        public const string None = "None";
        public const string ManagedIdentity = "ManagedIdentity";
    }
}


text: int x;  // In C99, a translation unit needs to have at least one declaration.


text:
package com.cloudspace.cardboard;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import org.ros.android.view.RosImageView;

/**
 * Contains two sub-views to provide a simple stereo HUD.
 */
public class CardboardOverlayView extends LinearLayout {
    private static final String TAG = "CardboardOverlayView";
    private CardboardOverlayEyeView mLeftView;
    private CardboardOverlayEyeView mRightView;
    AttributeSet attrs;

    public enum Side {
        LEFT(0), RIGHT(1);

        int side;

        Side(int side) {
            this.side = side;
        }
    }

    public RosImageView getRosImageView(Side side) {
        if (mRightView == null || mLeftView == null) {
            throw new IllegalStateException("Remember to call CardboardOverlayView.setTopicInformation(String topicName, String messageType)");
        }
        return side == Side.RIGHT ? mRightView.getImageView() : mLeftView.getImageView();
    }

    public void setTopicInformation(String topicName, String messageType) {
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
        params.setMargins(0, 0, 0, 0);

        mLeftView = new CardboardOverlayEyeView(getContext(), attrs, topicName, messageType);
        mLeftView.setLayoutParams(params);
        addView(mLeftView);

        mRightView = new CardboardOverlayEyeView(getContext(), attrs, topicName, messageType);
        mRightView.setLayoutParams(params);
        addView(mRightView);

        // Set some reasonable defaults.
        setDepthOffset(0.016f);
        setColor(Color.rgb(150, 255, 180));
        setVisibility(View.VISIBLE);
    }

    public CardboardOverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.attrs = attrs;
        setOrientation(HORIZONTAL);
    }

    private void setDepthOffset(float offset) {
        mLeftView.setOffset(offset);
        mRightView.setOffset(-offset);
    }

    private void setColor(int color) {
        mLeftView.setColor(color);
        mRightView.setColor(color);
    }
}


text:
<?php

namespace Proxies\__CG__\Entities;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class VilleUnite extends \Entities\VilleUnite implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setIdVille($idVille)
    {
        $this->__load();
        return parent::setIdVille($idVille);
    }

    public function getIdVille()
    {
        $this->__load();
        return parent::getIdVille();
    }

    public function setIdUnite($idUnite)
    {
        $this->__load();
        return parent::setIdUnite($idUnite);
    }

    public function getIdUnite()
    {
        $this->__load();
        return parent::getIdUnite();
    }

    public function setIdNombreUnite($idNombreUnite)
    {
        $this->__load();
        return parent::setIdNombreUnite($idNombreUnite);
    }

    public function getIdNombreUnite()
    {
        $this->__load();
        return parent::getIdNombreUnite();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'idVille', 'idUnite', 'idNombreUnite');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
module Mongoid
  class Criteria
    module Inspectable

      # Get a pretty string representation of the criteria, including the
      # selector, options, matching count and documents for inspection.
      #
      # @example Inspect the criteria.
      #   criteria.inspect
      #
      # @return [ String ] The inspection string.
      #
      # @since 1.0.0
      def inspect
%Q{#<Mongoid::Criteria
  selector: #{selector.inspect}
  options:  #{options.inspect}
  class:    #{klass}
  embedded: #{embedded?}>
}
      end
    end
  end
end


text:
<?php

use yii\db\Migration;

class m160623_095400_add extends Migration
{
    public function up()
    {
        $this->addColumn('documents', 'pdf', 'text');
    }

    public function down()
    {
        echo "m160623_095400_add cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
    <EditText
        android:id="@+id/resetpwd_edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="用户名"
        android:paddingTop="20dp"
        android:gravity="center"
        android:textSize="25sp"
        />
<EditText
    android:id="@+id/resetpwd_edit_pwd_old"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入旧密码"
    android:textSize="25sp"
    android:gravity="center"
    android:paddingTop="10dp"/>
    <EditText
        android:id="@+id/resetpwd_edit_pwd_new"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入新密码"
        android:textSize="25sp"
        android:gravity="center"
        android:paddingTop="10dp"/>
    <Button
        android:id="@+id/resetpwd_btn_sure"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确定"
        android:paddingTop="10dp"
        android:textSize="20sp"/>

</LinearLayout>


text:
ReBulk
======

[![Latest Version](http://img.shields.io/pypi/v/rebulk.svg)](https://pypi.python.org/pypi/rebulk)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg)](https://pypi.python.org/pypi/rebulk)
[![Build Status](https://img.shields.io/github/workflow/status/Toilal/rebulk/ci)](https://github.com/Toilal/rebulk/actions?query=workflow%3Aci)
[![Coveralls](http://img.shields.io/coveralls/Toilal/rebulk.svg)](https://coveralls.io/r/Toilal/rebulk?branch=master)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/relekang/python-semantic-release)

ReBulk is a python library that performs advanced searches in strings
that would be hard to implement using [re
module](https://docs.python.org/3/library/re.html) or [String
methods](https://docs.python.org/3/library/stdtypes.html#str) only.

It includes some features like `Patterns`, `Match`, `Rule` that allows
developers to build a custom and complex string matcher using a readable
and extendable API.

This project is hosted on GitHub: <https://github.com/Toilal/rebulk>

Install
=======

```sh
$ pip install rebulk
```

Usage
=====

Regular expression, string and function based patterns are declared in a
`Rebulk` object. It use a fluent API to chain `string`, `regex`, and
`functional` methods to define various patterns types.

```python
>>> from rebulk import Rebulk
>>> bulk = Rebulk().string('brown').regex(r'qu\w+').functional(lambda s: (20, 25))
```

When `Rebulk` object is fully configured, you can call `matches` method
with an input string to retrieve all `Match` objects found by registered
pattern.

```python
>>> bulk.matches("The quick brown fox jumps over the lazy dog")
[<brown:(10, 15)>, <quick:(4, 9)>, <jumps:(20, 25)>]
```

If multiple `Match` objects are found at the same position, only the
longer one is kept.

```python
>>> bulk = Rebulk().string('lakers').string('la')
>>> bulk.matches("the lakers are from la")
[<lakers:(4, 10)>, <la:(20, 22)>]
```

String Patterns
===============

String patterns are based on
[str.find](https://docs.python.org/3/library/stdtypes.html#str.find)
method to find matches, but returns all matches in the string.
`ignore_case` can be enabled to ignore case.

```python
>>> Rebulk().string('la').matches("lalalilala")
[<la:(0, 2)>, <la:(2, 4)>, <la:(6, 8)>, <la:(8, 10)>]

>>> Rebulk().string('la').matches("LalAlilAla")
[<la:(8, 10)>]

>>> Rebulk().string('la', ignore_case=True).matches("LalAlilAla")
[<La:(0, 2)>, <lA:(2, 4)>, <lA:(6, 8)>, <la:(8, 10)>]
```

You can define several patterns with a single `string` method call.

```python
>>> Rebulk().string('Winter', 'coming').matches("Winter is coming...")
[<Winter:(0, 6)>, <coming:(10, 16)>]
```

Regular Expression Patterns
===========================

Regular Expression patterns are based on a compiled regular expression.
[re.finditer](https://docs.python.org/3/library/re.html#re.finditer)
method is used to find matches.

If [regex module](https://pypi.python.org/pypi/regex) is available, it
can be used by rebulk instead of default [re
module](https://docs.python.org/3/library/re.html). Enable it with `REBULK_REGEX_ENABLED=1` environment variable.

```python
>>> Rebulk().regex(r'l\w').matches("lolita")
[<lo:(0, 2)>, <li:(2, 4)>]
```

You can define several patterns with a single `regex` method call.

```python
>>> Rebulk().regex(r'Wint\wr', r'com\w{3}').matches("Winter is coming...")
[<Winter:(0, 6)>, <coming:(10, 16)>]
```

All keyword arguments from
[re.compile](https://docs.python.org/3/library/re.html#re.compile) are
supported.

```python
>>> import re  # import required for flags constant
>>> Rebulk().regex('L[A-Z]KERS', flags=re.IGNORECASE) \
...         .matches("The LaKeRs are from La")
[<LaKeRs:(4, 10)>]

>>> Rebulk().regex('L[A-Z]', 'L[A-Z]KERS', flags=re.IGNORECASE) \
...         .matches("The LaKeRs are from La")
[<La:(20, 22)>, <LaKeRs:(4, 10)>]

>>> Rebulk().regex(('L[A-Z]', re.IGNORECASE), ('L[a-z]KeRs')) \
...         .matches("The LaKeRs are from La")
[<La:(20, 22)>, <LaKeRs:(4, 10)>]
```

If [regex module](https://pypi.python.org/pypi/regex) is available, it
automatically supports repeated captures.

```python
>>> # If regex module is available, repeated_captures is True by default.
>>> matches = Rebulk().regex(r'(\d+)(?:-(\d+))+').matches("01-02-03-04")
>>> matches[0].children # doctest:+SKIP
[<01:(0, 2)>, <02:(3, 5)>, <03:(6, 8)>, <04:(9, 11)>]

>>> # If regex module is not available, or if repeated_captures is forced to False.
>>> matches = Rebulk().regex(r'(\d+)(?:-(\d+))+', repeated_captures=False) \
...                   .matches("01-02-03-04")
>>> matches[0].children
[<01:(0, 2)+initiator=01-02-03-04>, <04:(9, 11)+initiator=01-02-03-04>]
```

-   `abbreviations`

    Defined as a list of 2-tuple, each tuple is an abbreviation. It
    simply replace `tuple[0]` with `tuple[1]` in the expression.

    \>\>\> Rebulk().regex(r\'Custom-separators\',
    abbreviations=\[(\"-\", r\"\[W\_\]+\")\])\...
    .matches(\"Custom\_separators using-abbreviations\")
    \[\<Custom\_separators:(0, 17)\>\]

Functional Patterns
===================

Functional Patterns are based on the evaluation of a function.

The function should have the same parameters as `Rebulk.matches` method,
that is the input string, and must return at least start index and end
index of the `Match` object.

```python
>>> def func(string):
...     index = string.find('?')
...     if index > -1:
...         return 0, index - 11
>>> Rebulk().functional(func).matches("Why do simple ? Forget about it ...")
[<Why:(0, 3)>]
```

You can also return a dict of keywords arguments for `Match` object.

You can define several patterns with a single `functional` method call,
and function used can return multiple matches.

Chain Patterns
==============

Chain Patterns are ordered composition of string, functional and regex
patterns. Repeater can be set to define repetition on chain part.

```python
>>> r = Rebulk().regex_defaults(flags=re.IGNORECASE)\
...             .defaults(children=True, formatter={'episode': int, 'version': int})\
...             .chain()\
...             .regex(r'e(?P<episode>\d{1,4})').repeater(1)\
...             .regex(r'v(?P<version>\d+)').repeater('?')\
...             .regex(r'[ex-](?P<episode>\d{1,4})').repeater('*')\
...             .close() # .repeater(1) could be omitted as it's the default behavior
>>> r.matches("This is E14v2-15-16-17").to_dict()  # converts matches to dict
MatchesDict([('episode', [14, 15, 16, 17]), ('version', 2)])
```

Patterns parameters
===================

All patterns have options that can be given as keyword arguments.

-   `validator`

    Function to validate `Match` value given by the pattern. Can also be
    a `dict`, to use `validator` with pattern named with key.

    ```python
    >>> def check_leap_year(match):
    ...     return int(match.value) in [1980, 1984, 1988]
    >>> matches = Rebulk().regex(r'\d{4}', validator=check_leap_year) \
    ...                   .matches("In year 1982 ...")
    >>> len(matches)
    0
    >>> matches = Rebulk().regex(r'\d{4}', validator=check_leap_year) \
    ...                   .matches("In year 1984 ...")
    >>> len(matches)
    1
    ```

Some base validator functions are available in `rebulk.validators`
module. Most of those functions have to be configured using
`functools.partial` to map them to function accepting a single `match`
argument.

-   `formatter`

    Function to convert `Match` value given by the pattern. Can also be
    a `dict`, to use `formatter` with matches named with key.

    ```python
    >>> def year_formatter(value):
    ...     return int(value)
    >>> matches = Rebulk().regex(r'\d{4}', formatter=year_formatter) \
    ...                   .matches("In year 1982 ...")
    >>> isinstance(matches[0].value, int)
    True
    ```

-   `pre_match_processor` / `post_match_processor`

    Function to mutagen or invalidate a match generated by a pattern.

    Function has a single parameter which is the Match object. If
    function returns False, it will be considered as an invalid match.
    If function returns a match instance, it will replace the original
    match with this instance in the process.

-   `post_processor`

    Function to change the default output of the pattern. Function
    parameters are Matches list and Pattern object.

-   `name`

    The name of the pattern. It is automatically passed to `Match`
    objects generated by this pattern.

-   `tags`

    A list of string that qualifies this pattern.

-   `value`

    Override value property for generated `Match` objects. Can also be a
    `dict`, to use `value` with pattern named with key.

-   `validate_all`

    By default, validator is called for returned `Match` objects only.
    Enable this option to validate them all, parent and children
    included.

-   `format_all`

    By default, formatter is called for returned `Match` values only.
    Enable this option to format them all, parent and children included.

-   `disabled`

    A `function(context)` to disable the pattern if returning `True`.

-   `children`

    If `True`, all children `Match` objects will be retrieved instead of
    a single parent `Match` object.

-   `private`

    If `True`, `Match` objects generated from this pattern are available
    internally only. They will be removed at the end of `Rebulk.matches`
    method call.

-   `private_parent`

    Force parent matches to be returned and flag them as private.

-   `private_children`

    Force children matches to be returned and flag them as private.

-   `private_names`

    Matches names that will be declared as private

-   `ignore_names`

    Matches names that will be ignored from the pattern output, after
    validation.

-   `marker`

    If `true`, `Match` objects generated from this pattern will be
    markers matches instead of standard matches. They won\'t be included
    in `Matches` sequence, but will be available in `Matches.markers`
    sequence (see `Markers` section).

Match
=====

A `Match` object is the result created by a registered pattern.

It has a `value` property defined, and position indices are available
through `start`, `end` and `span` properties.

In some case, it contains children `Match` objects in `children`
property, and each child `Match` object reference its parent in `parent`
property. Also, a `name` property can be defined for the match.

If groups are defined in a Regular Expression pattern, each group match
will be converted to a single `Match` object. If a group has a name
defined (`(?P<name>group)`), it is set as `name` property in a child
`Match` object. The whole regexp match (`re.group(0)`) will be converted
to the main `Match` object, and all subgroups (1, 2, \... n) will be
converted to `children` matches of the main `Match` object.

```python
>>> matches = Rebulk() \
...         .regex(r"One, (?P<one>\w+), Two, (?P<two>\w+), Three, (?P<three>\w+)") \
...         .matches("Zero, 0, One, 1, Two, 2, Three, 3, Four, 4")
>>> matches
[<One, 1, Two, 2, Three, 3:(9, 33)>]
>>> for child in matches[0].children:
...     '%s = %s' % (child.name, child.value)
'one = 1'
'two = 2'
'three = 3'
```

It\'s possible to retrieve only children by using `children` parameters.
You can also customize the way structure is generated with `every`,
`private_parent` and `private_children` parameters.

```python
>>> matches = Rebulk() \
...         .regex(r"One, (?P<one>\w+), Two, (?P<two>\w+), Three, (?P<three>\w+)", children=True) \
...         .matches("Zero, 0, One, 1, Two, 2, Three, 3, Four, 4")
>>> matches
[<1:(14, 15)+name=one+initiator=One, 1, Two, 2, Three, 3>, <2:(22, 23)+name=two+initiator=One, 1, Two, 2, Three, 3>, <3:(32, 33)+name=three+initiator=One, 1, Two, 2, Three, 3>]
```

Match object has the following properties that can be given to Pattern
objects

-   `formatter`

    Function to convert `Match` value given by the pattern. Can also be
    a `dict`, to use `formatter` with matches named with key.

    ```python
    >>> def year_formatter(value):
    ...     return int(value)
    >>> matches = Rebulk().regex(r'\d{4}', formatter=year_formatter) \
    ...                   .matches("In year 1982 ...")
    >>> isinstance(matches[0].value, int)
    True
    ```

-   `format_all`

    By default, formatter is called for returned `Match` values only.
    Enable this option to format them all, parent and children included.

-   `conflict_solver`

    A `function(match, conflicting_match)` used to solve conflict.
    Returned object will be removed from matches by `ConflictSolver`
    default rule. If `__default__` string is returned, it will fallback
    to default behavior keeping longer match.

Matches
=======

A `Matches` object holds the result of `Rebulk.matches` method call.
It\'s a sequence of `Match` objects and it behaves like a list.

All methods accepts a `predicate` function to filter `Match` objects
using a callable, and an `index` int to retrieve a single element from
default returned matches.

It has the following additional methods and properties on it.

-   `starting(index, predicate=None, index=None)`

    Retrieves a list of `Match` objects that starts at given index.

-   `ending(index, predicate=None, index=None)`

    Retrieves a list of `Match` objects that ends at given index.

-   `previous(match, predicate=None, index=None)`

    Retrieves a list of `Match` objects that are previous and nearest to
    match.

-   `next(match, predicate=None, index=None)`

    Retrieves a list of `Match` objects that are next and nearest to
    match.

-   `tagged(tag, predicate=None, index=None)`

    Retrieves a list of `Match` objects that have the given tag defined.

-   `named(name, predicate=None, index=None)`

    Retrieves a list of `Match` objects that have the given name.

-   `range(start=0, end=None, predicate=None, index=None)`

    Retrieves a list of `Match` objects for given range, sorted from
    start to end.

-   `holes(start=0, end=None, formatter=None, ignore=None, predicate=None, index=None)`

    Retrieves a list of *hole* `Match` objects for given range. A hole
    match is created for each range where no match is available.

-   `conflicting(match, predicate=None, index=None)`

    Retrieves a list of `Match` objects that conflicts with given match.

-   `chain_before(self, position, seps, start=0, predicate=None, index=None)`:

    Retrieves a list of chained matches, before position, matching
    predicate and separated by characters from seps only.

-   `chain_after(self, position, seps, end=None, predicate=None, index=None)`:

    Retrieves a list of chained matches, after position, matching
    predicate and separated by characters from seps only.

-   `at_match(match, predicate=None, index=None)`

    Retrieves a list of `Match` objects at the same position as match.

-   `at_span(span, predicate=None, index=None)`

    Retrieves a list of `Match` objects from given (start, end) tuple.

-   `at_index(pos, predicate=None, index=None)`

    Retrieves a list of `Match` objects from given position.

-   `names`

    Retrieves a sequence of all `Match.name` properties.

-   `tags`

    Retrieves a sequence of all `Match.tags` properties.

-   `to_dict(details=False, first_value=False, enforce_list=False)`

    Convert to an ordered dict, with `Match.name` as key and
    `Match.value` as value.

    It\'s a subclass of
    [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict),
    that contains a `matches` property which is a dict with `Match.name`
    as key and list of `Match` objects as value.

    If `first_value` is `True` and distinct values are found for the
    same name, value will be wrapped to a list. If `False`, first value
    only will be kept and values lists can be retrieved with
    `values_list` which is a dict with `Match.name` as key and list of
    `Match.value` as value.

    if `enforce_list` is `True`, all values will be wrapped to a list,
    even if a single value is found.

    If `details` is True, `Match.value` objects are replaced with
    complete `Match` object.

-   `markers`

    A custom `Matches` sequences specialized for `markers` matches (see
    below)

Markers
=======

If you have defined some patterns with `markers` property, then
`Matches.markers` points to a special `Matches` sequence that contains
only `markers` matches. This sequence supports all methods from
`Matches`.

Markers matches are not intended to be used in final result, but can be
used to implement a `Rule`.

Rules
=====

Rules are a convenient and readable way to implement advanced
conditional logic involving several `Match` objects. When a rule is
triggered, it can perform an action on `Matches` object, like filtering
out, adding additional tags or renaming.

Rules are implemented by extending the abstract `Rule` class. They are
registered using `Rebulk.rule` method by giving either a `Rule`
instance, a `Rule` class or a module containing `Rule classes` only.

For a rule to be triggered, `Rule.when` method must return `True`, or a
non empty list of `Match` objects, or any other truthy object. When
triggered, `Rule.then` method is called to perform the action with
`when_response` parameter defined as the response of `Rule.when` call.

Instead of implementing `Rule.then` method, you can define `consequence`
class property with a Consequence classe or instance, like
`RemoveMatch`, `RenameMatch` or `AppendMatch`. You can also use a list
of consequence when required : `when_response` must then be iterable,
and elements of this iterable will be given to each consequence in the
same order.

When many rules are registered, it can be useful to set `priority` class
variable to define a priority integer between all rule executions
(higher priorities will be executed first). You can also define
`dependency` to declare another Rule class as dependency for the current
rule, meaning that it will be executed before.

For all rules with the same `priority` value, `when` is called before,
and `then` is called after all.

```python
>>> from rebulk import Rule, RemoveMatch

>>> class FirstOnlyRule(Rule):
...     consequence = RemoveMatch
...
...     def when(self, matches, context):
...         grabbed = matches.named("grabbed", 0)
...         if grabbed and matches.previous(grabbed):
...             return grabbed

>>> rebulk = Rebulk()

>>> rebulk.regex("This match(.*?)grabbed", name="grabbed")
<...Rebulk object ...>
>>> rebulk.regex("if it's(.*?)first match", private=True)
<...Rebulk object at ...>
>>> rebulk.rules(FirstOnlyRule)
<...Rebulk object at ...>

>>> rebulk.matches("This match is grabbed only if it's the first match")
[<This match is grabbed:(0, 21)+name=grabbed>]
>>> rebulk.matches("if it's NOT the first match, This match is NOT grabbed")
[]
```


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="side_nav_background">#FFE9C315</color>
    <color name="side_nav_background_grad">#e2c331</color>
</resources>


text:
trade
=====

A Symfony project created on May 21, 2017, 1:46 pm.


text:
package org.hillview.test;

import com.google.common.collect.ImmutableList;
import org.hillview.dataset.LocalDataSet;
import org.hillview.dataset.ParallelDataSet;
import org.hillview.dataset.RemoteDataSet;
import org.hillview.dataset.api.IDataSet;
import org.hillview.dataset.api.IMap;
import org.hillview.dataset.api.ISketch;
import org.hillview.dataset.api.Pair;
import org.hillview.dataset.api.PartialResult;
import org.hillview.dataset.remoting.HillviewServer;
import org.hillview.utils.Converters;
import org.hillview.utils.HostAndPort;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

/**
 * Remoting tests for Hillview.
 */
@net.jcip.annotations.NotThreadSafe
public class RemotingTest extends BaseTest {
    private final static HostAndPort serverAddress = HostAndPort.fromParts("127.0.0.1",
                                                                           1234);
    @Nullable private static HillviewServer server;

    private static class IncrementMap implements IMap<int[], int[]> {
        @Override
        public int[] apply(final int[] data) {
            if (data.length == 0) {
                throw new RuntimeException("Cannot apply map against empty data");
            }

            final int[] dataNew = new int[data.length];
            for (int i = 0; i < data.length; i++) {
                dataNew[i] = data[i] + 1;
            }

            return dataNew;
        }
    }

    private static class SumSketch implements ISketch<int[], Integer> {
        @Override @Nullable
        public Integer zero() {
            return 0;
        }

        @Override @Nullable
        public Integer add(@Nullable final Integer left, @Nullable final Integer right) {
            return Converters.checkNull(left) + Converters.checkNull(right);
        }

        @Override
        public Integer create(final int[] data) {
            int sum = 0;
            for (int d : data) sum += d;
            return sum;
        }
    }

    private static class ImmutableListSketch implements ISketch<int[], List<Integer>> {
        @Override @Nullable
        public List<Integer> zero() {
            return ImmutableList.of();
        }

        @Override @Nullable
        public List<Integer> add(@Nullable final List<Integer> left,
                                 @Nullable final List<Integer> right) {
            return ImmutableList.<Integer>builder()
                                .addAll(Converters.checkNull(left))
                                .addAll(Converters.checkNull(right)).build();
        }

        @Override
        public List<Integer> create(final int[] data) {
            return ImmutableList.of(1);
        }
    }

    private static class ErrorSumSketch implements ISketch<int[], Integer> {
        @Override @Nullable
        public Integer zero() {
            return 0;
        }

        @Override @Nullable
        public Integer add(@Nullable final Integer left, @Nullable final Integer right) {
            return Converters.checkNull(left) + Converters.checkNull(right);
        }

        @Override
        public Integer create(final int[] data) {
            throw new RuntimeException("ErrorSumSketch");
        }
    }

    /*
     * Create separate server and client actor systems to test remoting.
     */
    @BeforeClass
    public static void initialize() throws Exception {
        // Server
        final int parts = 10;
        final int size = 1000;
        ArrayList<IDataSet<int[]>> al = new ArrayList<IDataSet<int[]>>(10);
        for (int i=0; i < parts; i++) {
            final int[] data = new int[size];
            for (int j = 0; j < size; j++)
                data[j] = (i * size) + j;
            LocalDataSet<int[]> lds = new LocalDataSet<>(data);
            al.add(lds);
        }
        ParallelDataSet<int[]> pds = new ParallelDataSet<int[]>(al);
        pds.setBundleInterval(0);
        server = new HillviewServer(serverAddress, pds);
    }

    @Test
    public void testMapSketchThroughClient() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final IDataSet<int[]> remoteIdsNew = remoteIds.map(new IncrementMap())
                                                      .filter(p -> p.deltaValue != null)
                                                      .toBlocking()
                                                      .last().deltaValue;
        assertNotNull(remoteIdsNew);
        final int result = remoteIdsNew.sketch(new SumSketch())
                                       .map(e -> e.deltaValue)
                                       .reduce((x, y) -> x + y)
                                       .toBlocking()
                                       .last();
        assertEquals(50005000, result);
    }

    //@Test
    public void testRaceSerialized() throws InterruptedException {
        final ExecutorService es = Executors.newFixedThreadPool(10);
        final SerializedSubject<Integer, Integer> obs1 = PublishSubject.<Integer>create().toSerialized();
        final SerializedSubject<Integer, Integer> obs2 = PublishSubject.<Integer>create().toSerialized();
        final Observable<List<Integer>> merge = Observable.merge(obs1, obs2)
                .buffer(100, TimeUnit.MILLISECONDS)
                .filter(e -> !e.isEmpty());

        merge.subscribe(new Subscriber<List<Integer>>() {
            int interrupted = 0;

            @Override
            public void onCompleted() {
                Assert.assertNotEquals(interrupted, 0);
            }

            @Override
            public void onError(final Throwable throwable) { }

            @Override
            public void onNext(final List<Integer> integer) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    this.interrupted++;
                }
            }
        });
        es.execute(() -> obs1.onNext(1));
        es.execute(() -> obs2.onNext(2));
        es.execute(() -> obs1.onNext(3));
        es.execute(() -> obs2.onNext(4));
        Thread.sleep(100);
        obs1.onCompleted();
        obs2.onCompleted();
    }

    @Test
    public void testMapSketchThroughClientUsingMemoization() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final IDataSet<int[]> remoteIdsNew = remoteIds.map(new IncrementMap())
                .filter(p -> p.deltaValue != null)
                .toBlocking()
                .last().deltaValue;
        assertNotNull(remoteIdsNew);
        final int result = remoteIdsNew.sketch(new SumSketch())
                .map(e -> e.deltaValue)
                .reduce((x, y) -> x + y)
                .toBlocking()
                .last();
        assertEquals(50005000, result);

        final IDataSet<int[]> remoteIdsNewMem = remoteIds.map(new IncrementMap())
                .filter(p -> p.deltaValue != null)
                .toBlocking()
                .last().deltaValue;
        assertNotNull(remoteIdsNewMem);
        final int memoizedResult = remoteIdsNew.sketch(new SumSketch())
                .map(e -> e.deltaValue)
                .reduce((x, y) -> x + y)
                .toBlocking()
                .last();
        assertEquals(50005000, memoizedResult);
    }

    @Test
    public void testMapSketchThroughClientWithError() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final IDataSet<int[]> remoteIdsNew = remoteIds.map(new IncrementMap())
                                                      .toBlocking()
                                                      .last().deltaValue;
        assertNotNull(remoteIdsNew);
        final Observable<PartialResult<Integer>> resultObs =
                remoteIdsNew.sketch(new ErrorSumSketch());
        TestSubscriber<PartialResult<Integer>> ts = new TestSubscriber<PartialResult<Integer>>();
        resultObs.toBlocking().subscribe(ts);
        ts.assertError(RuntimeException.class);
    }

    @Test
    public void testMapSketchThroughClientWithImmutableCollection() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final IDataSet<int[]> remoteIdsNew = remoteIds.map(new IncrementMap())
                                                      .toBlocking()
                                                      .last().deltaValue;
        assertNotNull(remoteIdsNew);
        final Observable<PartialResult<List<Integer>>> resultObs =
                remoteIdsNew.sketch(new ImmutableListSketch());
        final List<Integer> result = resultObs.map(e -> e.deltaValue)
                                              .toBlocking()
                                              .last();
        for (int val: result) {
            assertEquals(1, val);
        }
    }

    private static TestSubscriber<PartialResult<Integer>> createUnsubscribeSubscriber(int count) {
        return new TestSubscriber<PartialResult<Integer>>() {
            private int counter = 0;

            @Override
            public void onNext(final PartialResult<Integer> pr) {
                this.counter++;
                super.onNext(pr);
                if (this.counter == count)
                    this.unsubscribe();
            }
        };
    }

    @Test
    public void testUnsubscribe() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final Observable<PartialResult<Integer>> resultObs = remoteIds.sketch(new SumSketch());
        TestSubscriber<PartialResult<Integer>> ts = createUnsubscribeSubscriber(1);
        resultObs.toBlocking().subscribe(ts);
        ts.assertValueCount(1);
        ts.assertNotCompleted();
    }

    @Test
    public void testDoOnUnsubscribeByCaller() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final AtomicInteger count = new AtomicInteger(0);
        final Observable<PartialResult<Integer>> resultObs =
                remoteIds.sketch(new SumSketch()).doOnUnsubscribe(count::incrementAndGet);
        TestSubscriber<PartialResult<Integer>> ts = createUnsubscribeSubscriber(3);
        resultObs.toBlocking().subscribe(ts);
        ts.assertValueCount(3);
        ts.assertNotCompleted();
        assertEquals(1, count.get());
    }

    @Test
    public void testZip() {
        final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress);
        final IDataSet<int[]> remoteIdsLeft = Converters.checkNull(
                remoteIds.map(new IncrementMap()).toBlocking().last().deltaValue);
        final IDataSet<int[]> remoteIdsRight = Converters.checkNull(
                remoteIds.map(new IncrementMap()).toBlocking().last().deltaValue);
        final PartialResult<IDataSet<Pair<int[], int[]>>> last
                = Converters.checkNull(remoteIdsLeft.zip(remoteIdsRight)).toBlocking().last();
        assertNotNull(last);
        assertEquals(last.deltaDone, 1.0, 0.001);
    }

    @Test
    public void testIncorrectRemoteIndex() {
        try {
            // Should not succeed because the remote handle does not exist
            int nonExistentIndex = 99;
            final IDataSet<int[]> remoteIds = new RemoteDataSet<int[]>(serverAddress,
                                                                       nonExistentIndex);
            Converters.checkNull(
                    remoteIds.map(new IncrementMap()).toBlocking().last().deltaValue);
            fail();
        }
        catch (RuntimeException ignored) {
        }
        try {
            // Test with zip
            final IDataSet<int[]> remoteIdsLeft = new RemoteDataSet<int[]>(serverAddress);
            final IDataSet<int[]> remoteIdsRight = new RemoteDataSet<int[]>(serverAddress, 99);
            Converters.checkNull(remoteIdsLeft.zip(remoteIdsRight)).toBlocking().last();
            fail();
        } catch (RuntimeException ignored) {
        }
    }

    @AfterClass
    public static void shutdown() {
        if (server != null) {
            server.shutdown();
        }
    }
}


text:
#pragma once

#include <aws/core/Core_EXPORTS.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/http/HttpTypes.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/crypto/Hash.h>
#include <aws/core/auth/AWSAuthSignerProvider.h>
#include <memory>
#include <atomic>

struct aws_array_list;

namespace Aws
{
    namespace Utils
    {
        template<typename R, typename E>
        class Outcome;

        namespace Xml
        {
            class XmlDocument;
        } // namespace Xml

        namespace Json
        {
            class JsonValue;
        } // namespace Json

        namespace RateLimits
        {
            class RateLimiterInterface;
        } // namespace RateLimits

        namespace Crypto
        {
            class MD5;
        } // namespace Crypto
    } // namespace Utils

    namespace Http
    {
        class HttpClient;

        class HttpClientFactory;

        class HttpRequest;

        class HttpResponse;

        class URI;
    } // namespace Http

    namespace Auth
    {
        AWS_CORE_API extern const char SIGV4_SIGNER[];
        AWS_CORE_API extern const char NULL_SIGNER[];
    }

    class AmazonWebServiceRequest;

    namespace Client
    {
        template<typename ERROR_TYPE>
        class AWSError;
        class AWSErrorMarshaller;
        class AWSRestfulJsonErrorMarshaller;
        class AWSAuthSigner;
        struct ClientConfiguration;
        class RetryStrategy;

        typedef Utils::Outcome<std::shared_ptr<Aws::Http::HttpResponse>, AWSError<CoreErrors>> HttpResponseOutcome;
        typedef Utils::Outcome<AmazonWebServiceResult<Utils::Stream::ResponseStream>, AWSError<CoreErrors>> StreamOutcome;

        /**
         * Abstract AWS Client. Contains most of the functionality necessary to build an http request, get it signed, and send it accross the wire.
         */
        class AWS_CORE_API AWSClient
        {
        public:
            /**
             * configuration will be used for http client settings, retry strategy, throttles, and signing information.
             * supplied signer will be used for all requests, aws sdk clients will use default AuthV4Signer.
             * errorMarshaller tells the client how to convert error payloads into AWSError objects.
             */
            AWSClient(const Aws::Client::ClientConfiguration& configuration,
                const std::shared_ptr<Aws::Client::AWSAuthSigner>& signer,
                const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            /**
             * Configuration will be used for http client settings, retry strategy, throttles, and signing information.
             * Pass a signer provider to determine the proper signer for a given request; AWS services will use
             * SigV4 signer. errorMarshaller tells the client how to convert error payloads into AWSError objects.
             */
            AWSClient(const Aws::Client::ClientConfiguration& configuration,
                const std::shared_ptr<Aws::Auth::AWSAuthSignerProvider>& signerProvider,
                const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            virtual ~AWSClient() { };

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri and http method. expirationInSeconds defaults
             * to 0 which is the default 7 days. The implication of this function is using auth signer v4 to sign it.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, long long expirationInSeconds = 0);

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri, http method and customized headers. expirationInSeconds defaults
             * to 0 which is the default 7 days. The implication of this function is using auth signer v4 to sign it.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, const Aws::Http::HeaderValueCollection& customizedHeaders, long long expirationInSeconds = 0);

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri and http method and region. expirationInSeconds defaults
             * to 0 which is the default 7 days.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region, long long expirationInSeconds = 0) const;

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri, http method and customized headers. expirationInSeconds defaults
             * to 0 which is the default 7 days.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region, const Aws::Http::HeaderValueCollection& customizedHeaders, long long expirationInSeconds = 0);

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri and http method, region, and service name. expirationInSeconds defaults
             * to 0 which is the default 7 days.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region, const char* serviceName, long long expirationInSeconds = 0) const;

            /**
             * Generates a signed Uri using the injected signer. for the supplied uri, http method and customized headers. expirationInSeconds defaults
             * to 0 which is the default 7 days.
             */
            Aws::String GeneratePresignedUrl(Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region, const char* serviceName, const Aws::Http::HeaderValueCollection& customizedHeaders, long long expirationInSeconds = 0);

            Aws::String GeneratePresignedUrl(const Aws::AmazonWebServiceRequest& request, Aws::Http::URI& uri, Aws::Http::HttpMethod method,
                const Aws::Http::QueryStringParameterCollection& extraParams = Aws::Http::QueryStringParameterCollection(), long long expirationInSeconds = 0) const;

            Aws::String GeneratePresignedUrl(const Aws::AmazonWebServiceRequest& request, Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region, const char* serviceName,
                const Aws::Http::QueryStringParameterCollection& extraParams = Aws::Http::QueryStringParameterCollection(), long long expirationInSeconds = 0) const;

            Aws::String GeneratePresignedUrl(const Aws::AmazonWebServiceRequest& request, Aws::Http::URI& uri, Aws::Http::HttpMethod method, const char* region,
                const Aws::Http::QueryStringParameterCollection& extraParams = Aws::Http::QueryStringParameterCollection(), long long expirationInSeconds = 0) const;

            /**
             * Stop all requests immediately.
             * In flight requests will likely fail.
             */
            void DisableRequestProcessing();

            /**
             * Enable/ReEnable requests.
             */
            void EnableRequestProcessing();

            inline virtual const char* GetServiceClientName() const { return m_serviceName.c_str(); }
            /**
             * service client name is part of userAgent.
             * We need to update userAgent after setting this name if it's not pre-set by customer.
             * Note: this API should only be called in your extended class constructors.
             */
            virtual void SetServiceClientName(const Aws::String& name);

        protected:
            /**
             * Calls AttemptOneRequest until it either, succeeds, runs out of retries from the retry strategy,
             * or encounters and error that is not retryable.
             */
            HttpResponseOutcome AttemptExhaustively(const Aws::Http::URI& uri,
                    const Aws::AmazonWebServiceRequest& request,
                    Http::HttpMethod httpMethod,
                    const char* signerName,
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * Calls AttemptOneRequest until it either, succeeds, runs out of retries from the retry strategy,
             * or encounters and error that is not retryable. This method is for payloadless requests e.g. GET, DELETE, HEAD
             *
             * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
             * name.
             */
            HttpResponseOutcome AttemptExhaustively(const Aws::Http::URI& uri,
                    Http::HttpMethod httpMethod,
                    const char* signerName,
                    const char* requestName = "",
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * Build an Http Request from the AmazonWebServiceRequest object. Signs the request, sends it accross the wire
             * then reports the http response.
             */
            HttpResponseOutcome AttemptOneRequest(const std::shared_ptr<Http::HttpRequest>& httpRequest,
                    const Aws::AmazonWebServiceRequest& request,
                    const char* signerName,
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * Signs an Http Request, sends it accross the wire
             * then reports the http response. This method is for payloadless requests e.g. GET, DELETE, HEAD
             *
             * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
             * name.
             */
            HttpResponseOutcome AttemptOneRequest(const std::shared_ptr<Http::HttpRequest>& httpRequest,
                    const char* signerName,
                    const char* requestName = "",
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * This is used for structureless response payloads (file streams, binary data etc...). It calls AttemptExhaustively, but upon
             * return transfers ownership of the underlying stream for the http response to the caller.
             */
            StreamOutcome MakeRequestWithUnparsedResponse(const Aws::Http::URI& uri,
                    const Aws::AmazonWebServiceRequest& request,
                    Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                    const char* signerName = Aws::Auth::SIGV4_SIGNER,
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * This is used for structureless response payloads (file streams, binary data etc...). It calls AttemptExhaustively, but upon
             * return transfers ownership of the underlying stream for the http response to the caller.
             *
             * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
             * name.
             */
            StreamOutcome MakeRequestWithUnparsedResponse(const Aws::Http::URI& uri,
                    Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                    const char* signerName = Aws::Auth::SIGV4_SIGNER,
                    const char* requestName = "",
                    const char* signerRegionOverride = nullptr,
                    const char* signerServiceNameOverride = nullptr) const;

            /**
             * Abstract.  Subclassing clients should override this to tell the client how to marshall error payloads
             */
            virtual AWSError<CoreErrors> BuildAWSError(const std::shared_ptr<Aws::Http::HttpResponse>& response) const = 0;

            /**
             * Transforms the AmazonWebServicesResult object into an HttpRequest.
             */
            virtual void BuildHttpRequest(const Aws::AmazonWebServiceRequest& request,
                    const std::shared_ptr<Aws::Http::HttpRequest>& httpRequest) const;

            /**
             *  Gets the underlying ErrorMarshaller for subclasses to use.
             */
            const std::shared_ptr<AWSErrorMarshaller>& GetErrorMarshaller() const
            {
                return m_errorMarshaller;
            }

            /**
             * Gets the corresponding signer from the signers map by name.
             */
            Aws::Client::AWSAuthSigner* GetSignerByName(const char* name) const;
        protected:

            /**
              * Creates an HttpRequest instance with the given URI and sets the proper headers from the
              * AmazonWebRequest, and finally signs that request with the given the signer.
              * The similar member function BuildHttpRequest() does not sign the request.
              * This member function is used internally only by clients that perform requests (input operations) using
              * event-streams.
              */
            std::shared_ptr<Aws::Http::HttpRequest> BuildAndSignHttpRequest(const Aws::Http::URI& uri,
                                                    const Aws::AmazonWebServiceRequest& request,
                                                    Http::HttpMethod method, const char* signerName) const;

            /**
             * Performs the HTTP request via the HTTP client while enforcing rate limiters
             */
            std::shared_ptr<Aws::Http::HttpResponse> MakeHttpRequest(std::shared_ptr<Aws::Http::HttpRequest>& request) const;
            Aws::String m_region;
        private:
            /**
             * Try to adjust signer's clock
             * return true if signer's clock is adjusted, false otherwise.
             */
            bool AdjustClockSkew(HttpResponseOutcome& outcome, const char* signerName) const;
            void AddHeadersToRequest(const std::shared_ptr<Aws::Http::HttpRequest>& httpRequest, const Http::HeaderValueCollection& headerValues) const;
            void AddContentBodyToRequest(const std::shared_ptr<Aws::Http::HttpRequest>& httpRequest, const std::shared_ptr<Aws::IOStream>& body,
                                         bool needsContentMd5 = false, bool isChunked = false) const;
            void AddCommonHeaders(Aws::Http::HttpRequest& httpRequest) const;
            void InitializeGlobalStatics();
            std::shared_ptr<Aws::Http::HttpRequest> ConvertToRequestForPresigning(const Aws::AmazonWebServiceRequest& request, Aws::Http::URI& uri,
                Aws::Http::HttpMethod method, const Aws::Http::QueryStringParameterCollection& extraParams) const;

            std::shared_ptr<Aws::Http::HttpClient> m_httpClient;
            std::shared_ptr<Aws::Auth::AWSAuthSignerProvider> m_signerProvider;
            std::shared_ptr<AWSErrorMarshaller> m_errorMarshaller;
            std::shared_ptr<RetryStrategy> m_retryStrategy;
            std::shared_ptr<Aws::Utils::RateLimits::RateLimiterInterface> m_writeRateLimiter;
            std::shared_ptr<Aws::Utils::RateLimits::RateLimiterInterface> m_readRateLimiter;
            Aws::String m_userAgent;
            bool m_customizedUserAgent;
            std::shared_ptr<Aws::Utils::Crypto::Hash> m_hash;
            long m_requestTimeoutMs;
            bool m_enableClockSkewAdjustment;
            Aws::String m_serviceName;
        };

        typedef Utils::Outcome<AmazonWebServiceResult<Utils::Json::JsonValue>, AWSError<CoreErrors>> JsonOutcome;
        AWS_CORE_API Aws::String GetAuthorizationHeader(const Aws::Http::HttpRequest& httpRequest);

        /**
         *  AWSClient that handles marshalling json response bodies. You would inherit from this class
         *  to create a client that uses Json as its payload format.
         */
        class AWS_CORE_API AWSJsonClient : public AWSClient
        {
        public:
            typedef AWSClient BASECLASS;

            /**
             * Simply calls AWSClient constructor.
             */
            AWSJsonClient(const Aws::Client::ClientConfiguration& configuration,
                const std::shared_ptr<Aws::Client::AWSAuthSigner>& signer,
                const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            /**
             * Simply calls AWSClient constructor.
             */
            AWSJsonClient(const Aws::Client::ClientConfiguration& configuration,
                    const std::shared_ptr<Aws::Auth::AWSAuthSignerProvider>& signerProvider,
                    const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            virtual ~AWSJsonClient() = default;

        protected:
            /**
             * Converts/Parses an http response into a meaningful AWSError object using the json message structure.
             */
            virtual AWSError<CoreErrors> BuildAWSError(const std::shared_ptr<Aws::Http::HttpResponse>& response) const override;

            /**
             * Returns a Json document or an error from the request. Does some marshalling json and raw streams,
             * then just calls AttemptExhaustively.
             *
             * method defaults to POST
             */
            JsonOutcome MakeRequest(const Aws::Http::URI& uri,
                const Aws::AmazonWebServiceRequest& request,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* signerName = Aws::Auth::SIGV4_SIGNER,
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;

            /**
             * Returns a Json document or an error from the request. Does some marshalling json and raw streams,
             * then just calls AttemptExhaustively.
             *
             * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
             * name.
             *
             * method defaults to POST
             */
            JsonOutcome MakeRequest(const Aws::Http::URI& uri,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* signerName = Aws::Auth::SIGV4_SIGNER,
                const char* requestName = "",
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;

            JsonOutcome MakeEventStreamRequest(std::shared_ptr<Aws::Http::HttpRequest>& request) const;
        };

        typedef Utils::Outcome<AmazonWebServiceResult<Utils::Xml::XmlDocument>, AWSError<CoreErrors>> XmlOutcome;

        /**
        *  AWSClient that handles marshalling xml response bodies. You would inherit from this class
        *  to create a client that uses Xml as its payload format.
        */
        class AWS_CORE_API AWSXMLClient : public AWSClient
        {
        public:

            typedef AWSClient BASECLASS;

            AWSXMLClient(const Aws::Client::ClientConfiguration& configuration,
                const std::shared_ptr<Aws::Client::AWSAuthSigner>& signer,
                const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            AWSXMLClient(const Aws::Client::ClientConfiguration& configuration,
                const std::shared_ptr<Aws::Auth::AWSAuthSignerProvider>& signerProvider,
                const std::shared_ptr<AWSErrorMarshaller>& errorMarshaller);

            virtual ~AWSXMLClient() = default;

        protected:
            /**
             * Converts/Parses an http response into a meaningful AWSError object. Using the XML message structure.
             */
            virtual AWSError<CoreErrors> BuildAWSError(const std::shared_ptr<Aws::Http::HttpResponse>& response) const override;

            /**
             * Returns an xml document or an error from the request. Does some marshalling xml and raw streams,
             * then just calls AttemptExhaustively.
             *
             * method defaults to POST
             */
            XmlOutcome MakeRequest(const Aws::Http::URI& uri,
                const Aws::AmazonWebServiceRequest& request,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* signerName = Aws::Auth::SIGV4_SIGNER,
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;

            /**
             * Returns an xml document or an error from the request. Does some marshalling xml and raw streams,
             * then just calls AttemptExhaustively.
             *
             * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
             * name.
             *
             * method defaults to POST
             */
            XmlOutcome MakeRequest(const Aws::Http::URI& uri,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* signerName = Aws::Auth::SIGV4_SIGNER,
                const char* requestName = "",
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;

            /**
            * This is used for event stream response.
            */
            XmlOutcome MakeRequestWithEventStream(const Aws::Http::URI& uri,
                const Aws::AmazonWebServiceRequest& request,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* singerName = Aws::Auth::SIGV4_SIGNER,
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;

            /**
            * This is used for event stream response.
            * requestName is used for metrics and defaults to empty string, to avoid empty names in metrics provide a valid
            * name.
            */
            XmlOutcome MakeRequestWithEventStream(const Aws::Http::URI& uri,
                Http::HttpMethod method = Http::HttpMethod::HTTP_POST,
                const char* signerName = Aws::Auth::SIGV4_SIGNER,
                const char* requestName = "",
                const char* signerRegionOverride = nullptr,
                const char* signerServiceNameOverride = nullptr) const;
        };

    } // namespace Client
} // namespace Aws


text:
@implementation SPColorWellCell

- (void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
	// Set initial inset from cellFrame
	NSRect rect = NSInsetRect (cellFrame, 0.5f, 0.5f);

	// General inset for colored rect shown inside rect
	CGFloat insetFactor = 2.0f;

	// Draw border
	[[NSColor darkGrayColor] set];
	[NSBezierPath strokeRect: rect];
	[[NSColor grayColor] set];
	[NSBezierPath fillRect: NSInsetRect (rect, 1.0f, 1.0f)];

	// The following rectangle and triangle are needed for displaying color with alpha values
	// Draw black rectangle
	[[NSColor blackColor] set];
	[NSBezierPath fillRect: NSInsetRect (rect, insetFactor, insetFactor)];

	// Draw white triangle
	[[NSColor whiteColor] set];
	NSBezierPath *path = [NSBezierPath bezierPath];
	[path moveToPoint: NSMakePoint(rect.origin.x - insetFactor + rect.size.width, rect.origin.y + insetFactor)];
	[path lineToPoint: NSMakePoint(rect.origin.x - insetFactor + rect.size.width, rect.origin.y + rect.size.height - insetFactor)];
	[path lineToPoint: NSMakePoint(rect.origin.x + insetFactor, rect.origin.y + rect.size.height - insetFactor)];
	[path closePath];
	[path fill];

	// Draw the actual color as rect
	[(NSColor*) [self objectValue] set];
	NSRectFillUsingOperation(NSInsetRect (rect, insetFactor, insetFactor), NSCompositeSourceOver);
}

@end