text:
package storage

import (
	"fmt"
	"testing"
	"time"

	"github.com/brocaar/lorawan"

	. "github.com/smartystreets/goconvey/convey"

	"github.com/brocaar/lora-app-server/internal/common"
	"github.com/brocaar/lora-app-server/internal/test"
)

func TestDeviceQueueMapping(t *testing.T) {
	conf := test.GetConfig()
	db, err := OpenDatabase(conf.PostgresDSN)
	if err != nil {
		t.Fatal(err)
	}
	common.DB = db
	nsClient := test.NewNetworkServerClient()
	common.NetworkServerPool = test.NewNetworkServerPool(nsClient)

	Convey("Given a clean database and a device", t, func() {
		test.MustResetDB(db)

		org := Organization{
			Name: "test-org",
		}
		So(CreateOrganization(common.DB, &org), ShouldBeNil)

		n := NetworkServer{
			Name:   "test-ns",
			Server: "test-ns:1234",
		}
		So(CreateNetworkServer(common.DB, &n), ShouldBeNil)

		sp := ServiceProfile{
			NetworkServerID: n.ID,
			OrganizationID:  org.ID,
			Name:            "test-sp",
		}
		So(CreateServiceProfile(common.DB, &sp), ShouldBeNil)

		dp := DeviceProfile{
			NetworkServerID: n.ID,
			OrganizationID:  org.ID,
			Name:            "test-dp",
		}
		So(CreateDeviceProfile(common.DB, &dp), ShouldBeNil)

		app := Application{
			OrganizationID:   org.ID,
			ServiceProfileID: sp.ServiceProfile.ServiceProfileID,
			Name:             "test-app",
		}
		So(CreateApplication(common.DB, &app), ShouldBeNil)

		d := Device{
			Name:            "test-device",
			DevEUI:          lorawan.EUI64{1, 2, 3, 4, 5, 6, 7, 8},
			ApplicationID:   app.ID,
			DeviceProfileID: dp.DeviceProfile.DeviceProfileID,
		}
		So(CreateDevice(common.DB, &d), ShouldBeNil)

		Convey("When creating a device-queue mapping", func() {
			dqm := DeviceQueueMapping{
				Reference: "test-123",
				DevEUI:    d.DevEUI,
				FCnt:      10,
			}
			So(CreateDeviceQueueMapping(common.DB, &dqm), ShouldBeNil)
			dqm.CreatedAt = dqm.CreatedAt.UTC().Truncate(time.Millisecond)

			Convey("Then GetDeviceQueueMappingForDevEUIAndFCnt with the same FCnt returns it", func() {
				dqmGet, err := GetDeviceQueueMappingForDevEUIAndFCnt(common.DB, d.DevEUI, 10)
				So(err, ShouldBeNil)
				dqmGet.CreatedAt = dqmGet.CreatedAt.UTC().Truncate(time.Millisecond)
				So(dqmGet, ShouldResemble, dqm)
			})

			Convey("Then DeleteDeviceQueueMapping deletes the mapping", func() {
				So(DeleteDeviceQueueMapping(common.DB, dqm.ID), ShouldBeNil)
				_, err := GetDeviceQueueMappingForDevEUIAndFCnt(common.DB, d.DevEUI, 10)
				So(err, ShouldEqual, ErrDoesNotExist)
			})

			Convey("Then FlushDeviceQueueMappingForDevEUI flushes all mappings", func() {
				So(FlushDeviceQueueMappingForDevEUI(common.DB, d.DevEUI), ShouldBeNil)
				_, err := GetDeviceQueueMappingForDevEUIAndFCnt(common.DB, d.DevEUI, 10)
				So(err, ShouldEqual, ErrDoesNotExist)
			})

		})

		Convey("Testing GetDeviceQueueMappingForDevEUIAndFCnt with different frame-counters", func() {
			tests := []struct {
				Name     string
				FCnt     uint32
				Mappings []DeviceQueueMapping

				ExpectedReference string
				ExpectedError     error
			}{
				{
					Name: "frame-counter equal",
					FCnt: 10,
					Mappings: []DeviceQueueMapping{
						{DevEUI: d.DevEUI, FCnt: 10, Reference: "test-1"},
					},
					ExpectedReference: "test-1",
				},
				{
					Name: "two mappings, first one 'expired', second matching",
					FCnt: 10,
					Mappings: []DeviceQueueMapping{
						{DevEUI: d.DevEUI, FCnt: 9, Reference: "test-1"},
						{DevEUI: d.DevEUI, FCnt: 10, Reference: "test-2"},
					},
					ExpectedReference: "test-2",
				},
				{
					Name: "one mapping with FCnt + 1 returns does not exist",
					FCnt: 4294967295,
					Mappings: []DeviceQueueMapping{
						{DevEUI: d.DevEUI, FCnt: 0, Reference: "test-1"}, // note: 4294967295 + 1 = 0 (uint32)
					},
					ExpectedError: ErrDoesNotExist,
				},
			}

			for i, test := range tests {
				Convey(fmt.Sprintf("Testing: %s [%d]", test.Name, i), func() {
					// create mappings
					for i := range test.Mappings {
						So(CreateDeviceQueueMapping(common.DB, &test.Mappings[i]), ShouldBeNil)
					}

					dqm, err := GetDeviceQueueMappingForDevEUIAndFCnt(common.DB, d.DevEUI, test.FCnt)
					if test.ExpectedError != nil {
						So(err, ShouldResemble, test.ExpectedError)
						return
					}

					So(err, ShouldEqual, nil)
					So(dqm.Reference, ShouldResemble, test.ExpectedReference)
				})
			}
		})
	})
}

redpajama_set_name: RedPajamaGithub


text:
layout: default
title: Version
---

Version Module

  Alfred
  Botman

Compatibility:

Description

This module will fetch version information of various packages (could also be other stuff).

Informations are put under cache by alfred, allowing you to retrieve latest
received versions even if the bot is offline.

Configuration

Alfred

Botman

{
   "vars": [
      "raid_status",
      "disk_full"
   ]
}

    The vars array contains the list of custom variables to be
    shown when the .version command will list matching bots.

{
   "default_cmd" : "pkg info %s | grep 'Version' | cut -d':' -f2 | tr -d ' '",
   "versions_list" : [
      "botman",
      {
         "kernel": "uname -r"
      }
   ]
}

default_cmd: default command to use to fetch version of packages.

versions_list: array of packages to list.

          If the array item is a string, then the default_cmd
          will be used to find the version number.

          If the array item is an object, then it will use the given command.

Example use:

List

Find

Alfred

(24/11/2015 08:52:29) guillaume.friloux@botnet.master.com: .version xxx
(08:52:29) Alfred Pennyworth:
Contacts that matched :
   online botman-xxx@botnet.master.com

online botman-xxx@botnet.master.com :
   kernel : 10.1-RELEASE
   botman : 1.2.13_5

Alfred

    This function allows to search over the version cache to find bots matching given package version.
    Supported conditions for package version matching are:
    <, <=, =, >=, >, !=.

(08:59:47) guillaume.friloux@botnet.master.com: .version find botman > 1.2.10
(08:59:47) Alfred Pennyworth:
Contacts that matched "botman>1.2.10" :

botman : 1.2.13_1
   online botman-aaa@botnet.master.com
   offline botman-bbb@botnet.master.com

botman : 1.2.13_5
   online botman-ccc8@xmpp-test.asp64.lan
   online botman-xxx@xmpp-test.asp64.lan

botman : 1.2.15_1
   offline botman-ddd@botnet.master.com
   online botman-eee@botnet.master.com


text: svink -d -n -i ../samples/circle.svg -p ../output/simple


text:
Using dev mode
==============

Normally chaincodes are started and maintained by peer. However in "dev"
mode, chaincode is built and started by the user. This mode is useful
during chaincode development phase for rapid code/build/run/debug cycle
turnaround.

To keep this a realistic "dev" environment, we are going to keep it "out
of the box" - with one exception: we create two channels instead of
using the default ``testchainid`` channel to show how the single running
instance can be accessed from multiple channels.

- Note: Make sure peer is not using TLS when running in dev mode.

All commands are executed from the ``fabric`` folder.

Start the orderer
-----------------

::

    ORDERER_GENERAL_GENESISPROFILE=SampleDevModeSolo orderer

The above starts the orderer in the local environment the orderer
configuration as defined in ``sampleconfig/orderer.yaml`` with the
genesisprofile directive overridden to use the SampleDevModeSolo profile
for bootstrapping the network.

Start the peer in dev mode
--------------------------

::

    peer node start --peer-chaincodedev=true

The above command starts the peer using the default ``sampleconfig/msp``
MSP. The ``--peer-chaincodedev=true`` puts it in "dev" mode.

Create channels ch1 and ch2
---------------------------

Generate the transactions for creating the channels using ``configtxgen`` tool.

::
   configtxgen -channelID ch1 -outputCreateChannelTx ch1.tx -profile SampleSingleMSPChannel
   configtxgen -channelID ch2 -outputCreateChannelTx ch2.tx -profile SampleSingleMSPChannel

where SampleSingleMSPChannel is a channel profile in ``sampleconfig/configtx.yaml``

::

    peer channel create -o 127.0.0.1:7050 -c ch1 -f ch1.tx
    peer channel create -o 127.0.0.1:7050 -c ch2 -f ch2.tx

Above assumes orderer is reachable on ``127.0.0.1:7050``. The orderer
now is tracking channels ch1 and ch2 for the default configuration.

::

    peer channel join -b ch1.block
    peer channel join -b ch2.block

The peer has now joined channels cha1 and ch2.

Start the chaincode
-------------------

::

    cd examples/chaincode/go/chaincode_example02
    go build
    CORE_CHAINCODE_LOGLEVEL=debug CORE_PEER_ADDRESS=127.0.0.1:7052 CORE_CHAINCODE_ID_NAME=mycc:0 ./chaincode_example02

The chaincode is started with peer and chaincode logs indicating successful registration with the peer.
Note that at this stage the chaincode is not associated with any channel. This is done in subsequent steps
using the ``instantiate`` command.

Use the chaincode
-----------------

Even though you are in ``--peer-chaincodedev`` mode, you still have to install the chaincode so the life-cycle system
chaincode can go through its checks normally. This requirement may be removed in future when in ``--peer-chaincodedev``
mode.

::

    peer chaincode install -n mycc -v 0 -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02

Once installed, the chaincode is ready to be instantiated.

::

    peer chaincode instantiate -n mycc -v 0 -c '{"Args":["init","a","100","b","200"]}' -o 127.0.0.1:7050 -C ch1

    peer chaincode instantiate -n mycc -v 0 -c '{"Args":["init","a","100","b","200"]}' -o 127.0.0.1:7050 -C ch2

The above instantiates the chaincode with the two channels. With default
settings it might take a few seconds for the transactions to be
committed.

::

    peer chaincode invoke -n mycc -c '{"Args":["invoke","a","b","10"]}' -o 127.0.0.1:7050 -C ch1
    peer chaincode invoke -n mycc -c '{"Args":["invoke","a","b","10"]}' -o 127.0.0.1:7050 -C ch2

The above invoke the chaincode over the two channels.

Finally, query the chaincode on the two channels.

::

    peer chaincode query -n mycc -c '{"Args":["query","a"]}' -o 127.0.0.1:7050 -C ch1
    peer chaincode query -n mycc -c '{"Args":["query","a"]}' -o 127.0.0.1:7050 -C ch2

.. Licensed under Creative Commons Attribution 4.0 International License
   https://creativecommons.org/licenses/by/4.0/


text:
swagger-client-gen
==================

This is a client part code generator for [swagger-code-gen](https://github.com/tmalbonph/swagger-code-gen) project.

### What is swagger-client-gen?

This software is a [NodeJS](http://nodejs.org) application.

It is intended for generating client side [NodeJS](http://nodejs.org) codes from a Swagger Specification file in [version 2.0](https://github.com/reverb/swagger-spec/blob/master/versions/2.0.md) document format.

It is design to be run with [npm](https://www.npmjs.org/package/npm) using `npm run-script {XXXX};` where XXXX is one of demo, generate.

### How to install

* install [grunt-cli](https://github.com/gruntjs/grunt)

 `npm install -g grunt-cli`

* install its dependencies

 `npm install`

### How to create the provided sample demo

* create demo with npm

 `npm demo`

* create demo with node

 `node demo.js`

### How to generate client code from your swagger 2.0 file

* generate with npm

 `npm run-script client -s PATH/TO/YOUR/SWAGGER/FILE -d FOLDER/TO/SAVE/GENERATED/CODES`

* generate with node

 `node client.js -s PATH/TO/YOUR/SWAGGER/FILE -d FOLDER/TO/SAVE/GENERATED/CODES`

### Sample codes

* TODO : soon will add code snippets here

### License

[MIT](https://github.com/tmalbonph/swagger-client-gen/blob/master/LICENSE)

The MIT License (MIT)

Copyright (c) 2014 tmalbonph <tmalbonph@yahoo.com>

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.

### Current status

The current version of this software is under development and working in local repository. Will soon publish beta version.


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Popsql.Tests.Utilities;
using Popsql.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Popsql.Tests.Text
{
    [TestClass]
    public class SqlWriterInsertTests
    {
        [TestMethod]
        public void WriteStartInsert_WritesInsert()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                Assert.AreEqual(SqlWriterState.StartInsert, writer.WriteState);
            }

            Assert.AreEqual("INSERT", builder.ToString());
        }

        [TestMethod]
        public void WriteStartInsert_WhenDisposed_ThrowsObjectDisposed()
        {
            StringBuilder builder = new StringBuilder();
            SqlWriter writer = new SqlWriter(builder);
            writer.Dispose();

            AssertEx.Throws<ObjectDisposedException>(() => writer.WriteStartInsert());
        }

        [TestMethod]
        public void WriteStartInto_WhenInsertStatement_WritesInto()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                Assert.AreEqual(SqlWriterState.StartInto, writer.WriteState);
            }

            Assert.AreEqual("INSERT INTO", builder.ToString());
        }

        [TestMethod]
        public void WriteTable_WhenInsertStatement_WritesTable()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                writer.WriteTable("Users");
                Assert.AreEqual(SqlWriterState.StartInto, writer.WriteState);
            }

            Assert.AreEqual("INSERT INTO [Users]", builder.ToString());
        }

        [TestMethod]
        public void WriteColumn_WhenInsertStatement_WritesColumns()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                writer.WriteTable("Users");
                writer.WriteColumn("Id");
                writer.WriteColumn("UserName");
                writer.WriteColumn("Email");
                writer.WriteCloseParenthesis();
                Assert.AreEqual(SqlWriterState.Into, writer.WriteState);
            }

            Assert.AreEqual("INSERT INTO [Users] ([Id], [UserName], [Email])", builder.ToString());
        }

        [TestMethod]
        public void WriteValue_WhenInsertStatement_WritesValues()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                writer.WriteTable("Users");
                writer.WriteColumn("Id");
                writer.WriteColumn("UserName");
                writer.WriteColumn("Email");
                writer.WriteStartValues();
                Assert.AreEqual(SqlWriterState.StartValues, writer.WriteState);
                writer.WriteValue(15);
                writer.WriteValue("My user name.");
                writer.WriteValue("myemail@mydomain.local");
                writer.WriteEndValues();
                Assert.AreEqual(SqlWriterState.EndValues, writer.WriteState);
            }

            Assert.AreEqual("INSERT INTO [Users] ([Id], [UserName], [Email]) VALUES (15, 'My user name.', 'myemail@mydomain.local')", builder.ToString());
        }

        [TestMethod]
        public void WriteValue_WhenBulkInsertStatement_WritesValues()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                writer.WriteTable("Users");
                writer.WriteColumn("Id");
                writer.WriteColumn("UserName");
                writer.WriteColumn("Email");

                writer.WriteStartValues();
                writer.WriteOpenParenthesis();
                Assert.AreEqual(SqlWriterState.StartValues, writer.WriteState);
                writer.WriteValue(15);
                writer.WriteValue("My user name.");
                writer.WriteValue("myemail@mydomain.local");
                writer.WriteEndValues();
                Assert.AreEqual(SqlWriterState.EndValues, writer.WriteState);

                writer.WriteStartValues();
                Assert.AreEqual(SqlWriterState.StartValues, writer.WriteState);
                writer.WriteValue(16);
                writer.WriteValue("My second user name.");
                writer.WriteValue("mysecondemail@mydomain.local");
                writer.WriteEndValues();
                Assert.AreEqual(SqlWriterState.EndValues, writer.WriteState);

                writer.WriteCloseParenthesis();
            }

            Assert.AreEqual("INSERT INTO [Users] ([Id], [UserName], [Email]) VALUES ((15, 'My user name.', 'myemail@mydomain.local'), (16, 'My second user name.', 'mysecondemail@mydomain.local'))", builder.ToString());
        }

        [TestMethod]
        public void WriteParameter_WhenInsertStatement_WritesParameters()
        {
            StringBuilder builder = new StringBuilder();
            using (SqlWriter writer = new SqlWriter(builder))
            {
                writer.WriteStartInsert();
                writer.WriteStartInto();
                writer.WriteTable("Users");
                writer.WriteColumn("Id");
                writer.WriteColumn("UserName");
                writer.WriteColumn("Email");
                writer.WriteStartValues();
                Assert.AreEqual(SqlWriterState.StartValues, writer.WriteState);
                writer.WriteParameter("Id");
                writer.WriteParameter("UserName");
                writer.WriteParameter("Email");
                writer.WriteEndValues();
                Assert.AreEqual(SqlWriterState.EndValues, writer.WriteState);
            }

            Assert.AreEqual("INSERT INTO [Users] ([Id], [UserName], [Email]) VALUES (@Id, @UserName, @Email)", builder.ToString());
        }
    }
}


text:
package ru.job4j.sort;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.*;

/**
 * Class SortUser.
 *
 * @author Ekaterina Turka (ekaterina2rka@gmail.com)
 * @since 29.12.2017
 */
public class SortUserTest {
    /**
     * Assert that unsorted list of users with age order (30, 20, 25) by sort command turn to set of users sorted by age
     * in ascending order. Use arrays for comparison.
     */
    @Test
    public void sort() {
        User[] expect = new User[]{
                new User("Pavel", 20),
                new User("Andrey", 25),
                new User("Ivan", 30)
        };
        Set<User> users = new SortUser().sort(Arrays.asList(expect[2], expect[0], expect[1]));
        assertArrayEquals(users.toArray(new User[2]), expect);
    }

    /**
     * Assert that unsorted list of users with name order (Andrey, Ivan, Pavel) by sortNameLength command turn to list
     * of users sorted by name length in ascending order.
     */
    @Test
    public void sortNameLength() {
        User[] users = new User[]{
                new User("Ivan", 30),
                new User("Pavel", 20),
                new User("Andrey", 25)
        };
        List<User> result = new SortUser().sortNameLength(Arrays.asList(users[2], users[0], users[1]));
        List<User> except = Arrays.asList(users);
        assertEquals(result, except);
    }

    /**
     * Assert that unsorted list of users with order ([Ivan, 20], [Andrey, 25], [Ivan, 30]) by sortByAllFields command
     * turn to list of users sorted by name and age in ascending order.
     */
    @Test
    public void sortByAllFields() {
        User[] users = new User[]{
                new User("Andrey", 25),
                new User("Ivan", 20),
                new User("Ivan", 30)
        };
        List<User> result = new SortUser().sortByAllFields(Arrays.asList(users[1], users[0], users[2]));
        List<User> except = Arrays.asList(users);
        assertEquals(result, except);
    }
}


text:
set -euo pipefail
# --- begin runfiles.bash initialization ---
if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  if [[ -f "$0.runfiles_manifest" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
  elif [[ -f "$0.runfiles/MANIFEST" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
  elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
    export RUNFILES_DIR="$0.runfiles"
  fi
fi
if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
  source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
            "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
else
  echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
  exit 1
fi
# --- end runfiles.bash initialization ---

source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }

function set_up() {
  export MSYS_NO_PATHCONV=1
  export MSYS2_ARG_CONV_EXCL="*"
}

function test_local_rule_test_in_root() {
  create_new_workspace
  cat > BUILD <<EOF
genrule(
    name = "turtle",
    outs = ["tmnt"],
    cmd = "echo 'Leonardo' > \$@",
    visibility = ["//visibility:public"],
)

load(
    "@bazel_tools//tools/build_rules:test_rules.bzl",
    "rule_test",
)

rule_test(
    name="turtle_rule_test",
    rule="//:turtle",
    generates=[
        "tmnt",
    ],
)
EOF

  bazel build //:turtle_rule_test &> $TEST_log || fail "turtle_rule_test failed"
}

function test_local_rule_test_in_subpackage() {
  create_new_workspace
  mkdir p
  cat > p/BUILD <<EOF
genrule(
    name = "turtle",
    outs = ["tmnt"],
    cmd = "echo 'Leonardo' > \$@",
    visibility = ["//visibility:public"],
)

load(
    "@bazel_tools//tools/build_rules:test_rules.bzl",
    "rule_test",
)

rule_test(
    name="turtle_rule_test",
    rule="//p:turtle",
    generates=[
        "tmnt",
    ],
)
EOF

  bazel build //p:turtle_rule_test &> $TEST_log || fail "turtle_rule_test failed"
}

function test_repository_rule_test_in_root() {
  create_new_workspace
  mkdir -p r

  cat >> WORKSPACE <<EOF
local_repository(name = "r", path = "r")
EOF
  cat > r/WORKSPACE <<EOF
workspace(name = "r")
EOF
  cat > r/BUILD <<EOF
genrule(
    name = "turtle",
    outs = ["tmnt"],
    cmd = "echo 'Leonardo' > \$@",
    visibility = ["//visibility:public"],
)
EOF
  cat > BUILD <<EOF
load(
    "@bazel_tools//tools/build_rules:test_rules.bzl",
    "rule_test",
)

rule_test(
    name="turtle_rule_test",
    rule="@r//:turtle",
    generates=[
        "tmnt",
    ],
)
EOF

  bazel build //:turtle_rule_test &> $TEST_log || fail "turtle_rule_test failed"
}

function test_repository_rule_test_in_subpackage() {
  create_new_workspace
  mkdir -p r

  cat >> WORKSPACE <<EOF
local_repository(name = "r", path = "r")
EOF
  cat > r/WORKSPACE <<EOF
workspace(name = "r")
EOF
  mkdir r/p
  cat > r/p/BUILD <<EOF
genrule(
    name = "turtle",
    outs = ["tmnt"],
    cmd = "echo 'Leonardo' > \$@",
    visibility = ["//visibility:public"],
)
EOF
  cat > BUILD <<EOF
load(
    "@bazel_tools//tools/build_rules:test_rules.bzl",
    "rule_test",
)

rule_test(
    name="turtle_rule_test",
    rule="@r//p:turtle",
    generates=[
        "tmnt",
    ],
)
EOF

  bazel build //:turtle_rule_test &> $TEST_log || fail "turtle_rule_test failed"
}

# Regression test for https://github.com/bazelbuild/bazel/issues/8723
#
# rule_test() is a macro that expands to a sh_test and _rule_test_rule.
# Expect that:
# * test- and build-rule attributes (e.g. "tags") are applied to both rules,
# * test-only attributes are applied only to the sh_rule,
# * the build rule has its own visibility
function test_kwargs_with_macro_rules() {
  create_new_workspace
  cat > BUILD <<'EOF'
load("@bazel_tools//tools/build_rules:test_rules.bzl", "rule_test")

genrule(
    name = "x",
    srcs = ["@does_not_exist//:bad"],
    outs = ["x.out"],
    cmd = "touch $@",
    tags = ["dont_build_me"],
)

rule_test(
    name = "x_test",
    rule = "//:x",
    generates = ["x.out"],
    visibility = ["//foo:__pkg__"],
    tags = ["dont_build_me"],
    args = ["x"],
    flaky = False,
    local = True,
    shard_count = 2,
    size = "small",
    timeout = "short",
)
EOF

  bazel build //:all >& "$TEST_log" && fail "should have failed" || true

  bazel build --build_tag_filters=-dont_build_me //:all >& "$TEST_log" || fail "build failed"

  bazel query --output=label 'attr(tags, dont_build_me, //:all)' >& "$TEST_log" || fail "query failed"
  expect_log '//:x_test_impl'
  expect_log '//:x_test\b'
  expect_log '//:x\b'

  bazel query --output=label 'attr(visibility, private, //:all)' >& "$TEST_log" || fail "query failed"
  expect_log '//:x_test_impl'
  expect_not_log '//:x_test\b'
  expect_not_log '//:x\b'

  bazel query --output=label 'attr(visibility, foo, //:all)' >& "$TEST_log" || fail "query failed"
  expect_log '//:x_test\b'
  expect_not_log '//:x_test_impl'
  expect_not_log '//:x\b'
}

run_suite "rule_test tests"


text:
require 'foxycart_helpers/configuration'
require 'openssl'

module FoxycartHelpers
  class ProductVerification

    def self.encode(code, name, value)
      new(code, name, value).encode
    end

    def self.encoded_name(code, name, value)
      new(code, name, value).encoded_name
    end

    def self.encoded_value(code, name, value)
      new(code, name, value).encoded_value
    end

    def encode
      digest = OpenSSL::Digest.new 'sha256'
      key = config.api_key
      data = @code + normalized_name + @value

      OpenSSL::HMAC.hexdigest digest, key, data
    end

    def encoded_name
      if @value == '--OPEN--'
        @name + '||' + encode + '||open'
      else
        @name + '||' + encode
      end
    end

    def encoded_value
      if @value == '--OPEN--'
        @name + '||' + encode + '||open'
      else
        @value + '||' + encode
      end
    end

    def config
      FoxycartHelpers.configuration
    end

    def initialize(code, name, value)
      @code = code
      @name = name
      @value = value
    end

    private

    def normalized_name
      if @name.match /^\d*:.*/
        @name.split(':').last
      else
        @name
      end
    end
  end
end


text:
package com.sinosteel.framework.core.auth;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;

public class StatelessAccessControlFilter extends AccessControlFilter
{

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
           throws Exception
	{
		return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
    {
    	String clientDigest = request.getParameter("clientDigest");
    	String username = request.getParameter("username");

    	StatelessAuthenticationToken token = new StatelessAuthenticationToken(username, clientDigest);

    	try
    	{
    		getSubject(request, response).login(token);
    		return true;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    		onLoginFail(response);

    		return false;
    	}
    }

    private void onLoginFail(ServletResponse response) throws IOException
    {
    	HttpServletResponse httpResponse = (HttpServletResponse) response;
    	httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    	httpResponse.getWriter().write("login error");
    }
}


text:
"""
pytoch/caffe2 backend via onnx
https://pytorch.org/docs/stable/onnx.html
"""

# pylint: disable=unused-argument,missing-docstring,useless-super-delegation

from threading import Lock

import caffe2.python.onnx.backend
import onnx
import torch  # needed to get version and cuda setup

import backend

class BackendPytorch(backend.Backend):
    def __init__(self):
        super(BackendPytorch, self).__init__()
        self.sess = None
        self.model = None
        self.lock = Lock()

    def version(self):
        return torch.__version__

    def name(self):
        return "pytorch"

    def image_format(self):
        return "NCHW"

    def load(self, model_path, inputs=None, outputs=None):
        self.model = onnx.load(model_path)

        # find inputs from the model if not passed in by config
        if inputs:
            self.inputs = inputs
        else:
            self.inputs = []
            initializers = set()
            for i in self.model.graph.initializer:
                initializers.add(i.name)
            for i in self.model.graph.input:
                if i.name not in initializers:
                    self.inputs.append(i.name)
        # find outputs from the model if not passed in by config
        if outputs:
            self.outputs = outputs
        else:
            self.outputs = []
            for i in self.model.graph.output:
                self.outputs.append(i.name)

        # prepare the backend
        device = "CUDA:0" if torch.cuda.is_available() else "CPU"
        self.sess = caffe2.python.onnx.backend.prepare(self.model, device)
        return self

    def predict(self, feed):
        self.lock.acquire()
        res = self.sess.run(feed)
        self.lock.release()
        return res


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>jkes</artifactId>
        <groupId>com.timeyang.jkes</groupId>
        <version>1.1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>jkes-core</artifactId>

    <repositories>
        <repository>
            <id>confluent</id>
            <url>http://packages.confluent.io/maven/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <properties>
        <jackson.version>2.8.11.1</jackson.version>
    </properties>

    <dependencies>

        <!-- elasticsearch rest client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>rest</artifactId>
            <version>5.4.1</version>
        </dependency>
        <!-- automatically discover nodes from a running Elasticsearch cluster and set them to an existing RestClient instance.  -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>sniffer</artifactId>
            <version>5.4.1</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- the kafka clients that support avro serializer -->
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.11</artifactId>
            <version>0.10.2.1-cp1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- optional dependency, only for internal use. https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
            <version>${jackson.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- json lib -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
            <scope>compile</scope>
        </dependency>

        <!-- support data types of "json org" JSON library -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-json-org</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- reflections util based on javassist -->
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
    </dependencies>

</project>


text:
<?php

namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;

use Symfony\Component\Cache\Marshaller\MarshallerInterface;

/**
 * @author Ahmed TAILOULOUTE <ahmed.tailouloute@gmail.com>
 */
class IdentityMarshaller implements MarshallerInterface
{
    /**
     * {@inheritdoc}
     */
    public function marshall(array $values, ?array &$failed): array
    {
        foreach ($values as $key => $value) {
            if (!\is_string($value)) {
                throw new \LogicException(sprintf('%s accepts only string as data.', __METHOD__));
            }
        }

        return $values;
    }

    /**
     * {@inheritdoc}
     */
    public function unmarshall(string $value): string
    {
        return $value;
    }
}


text:
using System;
using System.Buffers;
using osu.Framework.Graphics.Primitives;
using osuTK.Graphics.ES30;
using SixLabors.ImageSharp.PixelFormats;

namespace osu.Framework.Graphics.Textures
{
    public class ArrayPoolTextureUpload : ITextureUpload
    {
        public Span<Rgba32> RawData => memoryOwner.Memory.Span;

        public ReadOnlySpan<Rgba32> Data => RawData;

        private readonly IMemoryOwner<Rgba32> memoryOwner;

        /// <summary>
        /// The target mipmap level to upload into.
        /// </summary>
        public int Level { get; set; }

        /// <summary>
        /// The texture format for this upload.
        /// </summary>
        public virtual PixelFormat Format => PixelFormat.Rgba;

        /// <summary>
        /// The target bounds for this upload. If not specified, will assume to be (0, 0, width, height).
        /// </summary>
        public RectangleI Bounds { get; set; }

        /// <summary>
        /// Create an empty raw texture with an efficient shared memory backing.
        /// </summary>
        /// <param name="width">The width of the texture.</param>
        /// <param name="height">The height of the texture.</param>
        public ArrayPoolTextureUpload(int width, int height)
        {
            memoryOwner = SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.Allocate<Rgba32>(width * height);
        }

        // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter
        public bool HasBeenUploaded => disposed;

        #region IDisposable Support

#pragma warning disable IDE0032 // Use auto property
        private bool disposed;
#pragma warning restore IDE0032 // Use auto property

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                disposed = true;
                memoryOwner.Dispose();
            }
        }

        ~ArrayPoolTextureUpload()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}


text: log "Shello Worldz!  Chef be rockin!"


text:
package io.netflow.flows.cflow

import java.net.{ InetAddress, InetSocketAddress }
import java.util.UUID

import com.datastax.driver.core.utils.UUIDs
import com.twitter.util.Future
import io.netflow.lib._
import io.netflow.storage
import io.netty.buffer._
import net.liftweb.json.JsonDSL._
import org.joda.time.DateTime

import scala.util.{ Failure, Try }

/**
 * NetFlow Version 5
 *
 * *-------*---------------*------------------------------------------------------*
 * | Bytes | Contents      | Description                                          |
 * *-------*---------------*------------------------------------------------------*
 * | 0-1   | version       | The version of NetFlow records exported 005          |
 * *-------*---------------*------------------------------------------------------*
 * | 2-3   | count         | Number of flows exported in this packet (1-30)       |
 * *-------*---------------*------------------------------------------------------*
 * | 4-7   | SysUptime     | Current time in milli since the export device booted |
 * *-------*---------------*------------------------------------------------------*
 * | 8-11  | unix_secs     | Current count of seconds since 0000 UTC 1970         |
 * *-------*---------------*------------------------------------------------------*
 * | 12-15 | unix_nsecs    | Residual nanoseconds since 0000 UTC 1970             |
 * *-------*---------------*------------------------------------------------------*
 * | 16-19 | flow_sequence | Sequence counter of total flows seen                 |
 * *-------*---------------*------------------------------------------------------*
 * | 20    | engine_type   | Type of flow-switching engine                        |
 * *-------*---------------*------------------------------------------------------*
 * | 21    | engine_id     | Slot number of the flow-switching engine             |
 * *-------*---------------*------------------------------------------------------*
 * | 22-23 | sampling_int  | First two bits hold the sampling mode                |
 * |       |               | remaining 14 bits hold value of sampling interval    |
 * *-------*---------------*------------------------------------------------------*
 */

object NetFlowV5Packet {
  private val headerSize = 24
  private val flowSize = 48

  /**
   * Parse a Version 5 FlowPacket
   *
   * @param sender The sender's InetSocketAddress
   * @param buf Netty ByteBuf containing the UDP Packet
   */
  def apply(sender: InetSocketAddress, buf: ByteBuf): Try[NetFlowV5Packet] = Try[NetFlowV5Packet] {
    val version = buf.getUnsignedInteger(0, 2).toInt
    if (version != 5) return Failure(new InvalidFlowVersionException(version))

    val count = buf.getUnsignedInteger(2, 2).toInt
    if (count <= 0 || buf.readableBytes < headerSize + count * flowSize)
      return Failure(new CorruptFlowPacketException)

    val uptime = buf.getUnsignedInteger(4, 4)
    val timestamp = new DateTime(buf.getUnsignedInteger(8, 4) * 1000)
    val id = UUIDs.startOf(timestamp.getMillis)
    val flowSequence = buf.getUnsignedInteger(16, 4)
    val engineType = buf.getUnsignedInteger(20, 1).toInt
    val engineId = buf.getUnsignedInteger(21, 1).toInt
    // the first 2 bits are the sampling mode, the remaining 14 the interval
    val sampling = buf.getUnsignedInteger(22, 2).toInt
    val samplingInterval = sampling & 0x3FFF
    val samplingMode = sampling >> 14

    val flows: List[NetFlowV5] = (0 to count - 1).toList.flatMap { i =>
      apply(sender, buf.slice(headerSize + (i * flowSize), flowSize), id, uptime, timestamp, samplingInterval)
    }
    NetFlowV5Packet(id, sender, buf.readableBytes, uptime, timestamp, flows, flowSequence, engineType, engineId, samplingInterval, samplingMode)
  }

  /**
   * Parse a Version 5 Flow
   *
   * @param sender The sender's InetSocketAddress
   * @param buf Netty ByteBuf Slice containing the UDP Packet
   * @param fpId FlowPacket-UUID this Flow arrived on
   * @param uptime Millis since UNIX Epoch when the exporting device/sender booted
   * @param timestamp DateTime when this flow was exported
   * @param samplingInterval Interval samples are sent
   */
  def apply(sender: InetSocketAddress, buf: ByteBuf, fpId: UUID, uptime: Long, timestamp: DateTime, samplingInterval: Int): Option[NetFlowV5] =
    Try[NetFlowV5] {
      val sampling = NodeConfig.values.netflow.calculateSamples
      val pkts = buf.getUnsignedInteger(16, 4)
      val bytes = buf.getUnsignedInteger(20, 4)
      NetFlowV5(UUIDs.timeBased(), sender, buf.readableBytes(), uptime, timestamp,
        buf.getUnsignedInteger(32, 2).toInt, // srcPort
        buf.getUnsignedInteger(34, 2).toInt, // dstPort
        Option(buf.getUnsignedInteger(40, 2).toInt).filter(_ != -1), // srcAS
        Option(buf.getUnsignedInteger(42, 2).toInt).filter(_ != -1), // dstAS
        if (sampling) pkts * samplingInterval else pkts, // pkts
        if (sampling) bytes * samplingInterval else bytes, // bytes
        buf.getUnsignedByte(38).toInt, // proto
        buf.getUnsignedByte(39).toInt, // tos
        buf.getUnsignedByte(37).toInt, // tcpflags
        Some(buf.getUnsignedInteger(24, 4)).filter(_ != 0).map(x => timestamp.minus(uptime - x)), // start
        Some(buf.getUnsignedInteger(28, 4)).filter(_ != 0).map(x => timestamp.minus(uptime - x)), // stop
        buf.getInetAddress(0, 4), // srcAddress
        buf.getInetAddress(4, 4), // dstAddress
        Option(buf.getInetAddress(8, 4)).filter(_.getHostAddress != "0.0.0.0"), // nextHop
        buf.getUnsignedInteger(12, 2).toInt, // snmpInput
        buf.getUnsignedInteger(14, 2).toInt, // snmpOutput
        buf.getUnsignedByte(44).toInt, // srcMask
        buf.getUnsignedByte(45).toInt, // dstMask
        fpId)
    }.toOption

  private def doLayer[T](f: FlowPacketMeta[NetFlowV5Packet] => Future[T]): Future[T] = NodeConfig.values.storage match {
    case Some(StorageLayer.Cassandra) => f(storage.cassandra.NetFlowV5Packet)
    case Some(StorageLayer.Redis) => f(storage.redis.NetFlowV5Packet)
    case _ => Future.exception(NoBackendDefined)
  }

  def persist(fp: NetFlowV5Packet): Unit = doLayer(l => Future.value(l.persist(fp)))
}

case class NetFlowV5Packet(id: UUID, sender: InetSocketAddress, length: Int, uptime: Long, timestamp: DateTime, flows: List[NetFlowV5],
                           flowSequence: Long, engineType: Int, engineId: Int, samplingInterval: Int, samplingMode: Int) extends FlowPacket {
  def version = "NetFlowV5 Packet"
  def count = flows.length

  def persist() = NetFlowV5Packet.persist(this)
}

case class NetFlowV5(id: UUID, sender: InetSocketAddress, length: Int, uptime: Long, timestamp: DateTime,
                     srcPort: Int, dstPort: Int, srcAS: Option[Int], dstAS: Option[Int],
                     pkts: Long, bytes: Long, proto: Int, tos: Int, tcpflags: Int,
                     start: Option[DateTime], stop: Option[DateTime],
                     srcAddress: InetAddress, dstAddress: InetAddress, nextHop: Option[InetAddress],
                     snmpInput: Int, snmpOutput: Int, srcMask: Int, dstMask: Int, packet: UUID) extends NetFlowData[NetFlowV5] {
  def version = "NetFlowV5"

  override lazy val jsonExtra = ("srcMask" -> srcMask) ~ ("dstMask" -> dstMask) ~
    ("snmp" -> ("input" -> snmpInput) ~ ("output" -> snmpOutput))
}


text:
import {setRootDomAdapter} from '../dom/dom_adapter';
import {ListWrapper} from '../facade/collection';
import {DateWrapper, global, isBlank, isFunction, isPresent, setValueOnPath} from '../facade/lang';

import {GenericBrowserDomAdapter} from './generic_browser_adapter';

var _attrToPropMap = {
  'class': 'className',
  'innerHtml': 'innerHTML',
  'readonly': 'readOnly',
  'tabindex': 'tabIndex'
};

const DOM_KEY_LOCATION_NUMPAD = 3;

// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
var _keyMap = {
  // The following values are here for cross-browser compatibility and to match the W3C standard
  // cf http://www.w3.org/TR/DOM-Level-3-Events-key/
  '\b': 'Backspace',
  '\t': 'Tab',
  '\x7F': 'Delete',
  '\x1B': 'Escape',
  'Del': 'Delete',
  'Esc': 'Escape',
  'Left': 'ArrowLeft',
  'Right': 'ArrowRight',
  'Up': 'ArrowUp',
  'Down': 'ArrowDown',
  'Menu': 'ContextMenu',
  'Scroll': 'ScrollLock',
  'Win': 'OS'
};

// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
var _chromeNumKeyPadMap = {
  'A': '1',
  'B': '2',
  'C': '3',
  'D': '4',
  'E': '5',
  'F': '6',
  'G': '7',
  'H': '8',
  'I': '9',
  'J': '*',
  'K': '+',
  'M': '-',
  'N': '.',
  'O': '/',
  '\x60': '0',
  '\x90': 'NumLock'
};

/**
 * A `DomAdapter` powered by full browser DOM APIs.
 *
 * @security Tread carefully! Interacting with the DOM directly is dangerous and
 * can introduce XSS risks.
 */
/* tslint:disable:requireParameterType */
export class BrowserDomAdapter extends GenericBrowserDomAdapter {
  parse(templateHtml: string) { throw new Error('parse not implemented'); }
  static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); }
  hasProperty(element: any /** TODO #9100 */, name: string): boolean { return name in element; }
  setProperty(el: /*element*/ any, name: string, value: any) { el[name] = value; }
  getProperty(el: /*element*/ any, name: string): any { return el[name]; }
  invoke(el: /*element*/ any, methodName: string, args: any[]): any {
    el[methodName].apply(el, args);
  }

  // TODO(tbosch): move this into a separate environment class once we have it
  logError(error: any /** TODO #9100 */) {
    if (window.console.error) {
      window.console.error(error);
    } else {
      window.console.log(error);
    }
  }

  log(error: any /** TODO #9100 */) { window.console.log(error); }

  logGroup(error: any /** TODO #9100 */) {
    if (window.console.group) {
      window.console.group(error);
      this.logError(error);
    } else {
      window.console.log(error);
    }
  }

  logGroupEnd() {
    if (window.console.groupEnd) {
      window.console.groupEnd();
    }
  }

  get attrToPropMap(): any { return _attrToPropMap; }

  query(selector: string): any { return document.querySelector(selector); }
  querySelector(el: any /** TODO #9100 */, selector: string): HTMLElement {
    return el.querySelector(selector);
  }
  querySelectorAll(el: any /** TODO #9100 */, selector: string): any[] {
    return el.querySelectorAll(selector);
  }
  on(el: any /** TODO #9100 */, evt: any /** TODO #9100 */, listener: any /** TODO #9100 */) {
    el.addEventListener(evt, listener, false);
  }
  onAndCancel(
      el: any /** TODO #9100 */, evt: any /** TODO #9100 */,
      listener: any /** TODO #9100 */): Function {
    el.addEventListener(evt, listener, false);
    // Needed to follow Dart's subscription semantic, until fix of
    // https://code.google.com/p/dart/issues/detail?id=17406
    return () => { el.removeEventListener(evt, listener, false); };
  }
  dispatchEvent(el: any /** TODO #9100 */, evt: any /** TODO #9100 */) { el.dispatchEvent(evt); }
  createMouseEvent(eventType: string): MouseEvent {
    var evt: MouseEvent = document.createEvent('MouseEvent');
    evt.initEvent(eventType, true, true);
    return evt;
  }
  createEvent(eventType: any /** TODO #9100 */): Event {
    var evt: Event = document.createEvent('Event');
    evt.initEvent(eventType, true, true);
    return evt;
  }
  preventDefault(evt: Event) {
    evt.preventDefault();
    evt.returnValue = false;
  }
  isPrevented(evt: Event): boolean {
    return evt.defaultPrevented || isPresent(evt.returnValue) && !evt.returnValue;
  }
  getInnerHTML(el: any /** TODO #9100 */): string { return el.innerHTML; }
  getTemplateContent(el: any /** TODO #9100 */): Node {
    return 'content' in el && el instanceof HTMLTemplateElement ? el.content : null;
  }
  getOuterHTML(el: any /** TODO #9100 */): string { return el.outerHTML; }
  nodeName(node: Node): string { return node.nodeName; }
  nodeValue(node: Node): string { return node.nodeValue; }
  type(node: HTMLInputElement): string { return node.type; }
  content(node: Node): Node {
    if (this.hasProperty(node, 'content')) {
      return (<any>node).content;
    } else {
      return node;
    }
  }
  firstChild(el: any /** TODO #9100 */): Node { return el.firstChild; }
  nextSibling(el: any /** TODO #9100 */): Node { return el.nextSibling; }
  parentElement(el: any /** TODO #9100 */): Node { return el.parentNode; }
  childNodes(el: any /** TODO #9100 */): Node[] { return el.childNodes; }
  childNodesAsList(el: any /** TODO #9100 */): any[] {
    var childNodes = el.childNodes;
    var res = ListWrapper.createFixedSize(childNodes.length);
    for (var i = 0; i < childNodes.length; i++) {
      res[i] = childNodes[i];
    }
    return res;
  }
  clearNodes(el: any /** TODO #9100 */) {
    while (el.firstChild) {
      el.removeChild(el.firstChild);
    }
  }
  appendChild(el: any /** TODO #9100 */, node: any /** TODO #9100 */) { el.appendChild(node); }
  removeChild(el: any /** TODO #9100 */, node: any /** TODO #9100 */) { el.removeChild(node); }
  replaceChild(el: Node, newChild: any /** TODO #9100 */, oldChild: any /** TODO #9100 */) {
    el.replaceChild(newChild, oldChild);
  }
  remove(node: any /** TODO #9100 */): Node {
    if (node.parentNode) {
      node.parentNode.removeChild(node);
    }
    return node;
  }
  insertBefore(el: any /** TODO #9100 */, node: any /** TODO #9100 */) {
    el.parentNode.insertBefore(node, el);
  }
  insertAllBefore(el: any /** TODO #9100 */, nodes: any /** TODO #9100 */) {
    nodes.forEach((n: any /** TODO #9100 */) => el.parentNode.insertBefore(n, el));
  }
  insertAfter(el: any /** TODO #9100 */, node: any /** TODO #9100 */) {
    el.parentNode.insertBefore(node, el.nextSibling);
  }
  setInnerHTML(el: any /** TODO #9100 */, value: any /** TODO #9100 */) { el.innerHTML = value; }
  getText(el: any /** TODO #9100 */): string { return el.textContent; }
  // TODO(vicb): removed Element type because it does not support StyleElement
  setText(el: any /** TODO #9100 */, value: string) { el.textContent = value; }
  getValue(el: any /** TODO #9100 */): string { return el.value; }
  setValue(el: any /** TODO #9100 */, value: string) { el.value = value; }
  getChecked(el: any /** TODO #9100 */): boolean { return el.checked; }
  setChecked(el: any /** TODO #9100 */, value: boolean) { el.checked = value; }
  createComment(text: string): Comment { return document.createComment(text); }
  createTemplate(html: any /** TODO #9100 */): HTMLElement {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t;
  }
  createElement(tagName: any /* TODO #9100 */, doc = document): HTMLElement {
    return doc.createElement(tagName);
  }
  createElementNS(ns: any /* TODO #9100 */, tagName: any /* TODO #9100 */, doc = document):
      Element {
    return doc.createElementNS(ns, tagName);
  }
  createTextNode(text: string, doc = document): Text { return doc.createTextNode(text); }
  createScriptTag(attrName: string, attrValue: string, doc = document): HTMLScriptElement {
    var el = <HTMLScriptElement>doc.createElement('SCRIPT');
    el.setAttribute(attrName, attrValue);
    return el;
  }
  createStyleElement(css: string, doc = document): HTMLStyleElement {
    var style = <HTMLStyleElement>doc.createElement('style');
    this.appendChild(style, this.createTextNode(css));
    return style;
  }
  createShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).createShadowRoot(); }
  getShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).shadowRoot; }
  getHost(el: HTMLElement): HTMLElement { return (<any>el).host; }
  clone(node: Node): Node { return node.cloneNode(true); }
  getElementsByClassName(element: any /** TODO #9100 */, name: string): HTMLElement[] {
    return element.getElementsByClassName(name);
  }
  getElementsByTagName(element: any /** TODO #9100 */, name: string): HTMLElement[] {
    return element.getElementsByTagName(name);
  }
  classList(element: any /** TODO #9100 */): any[] {
    return <any[]>Array.prototype.slice.call(element.classList, 0);
  }
  addClass(element: any /** TODO #9100 */, className: string) { element.classList.add(className); }
  removeClass(element: any /** TODO #9100 */, className: string) {
    element.classList.remove(className);
  }
  hasClass(element: any /** TODO #9100 */, className: string): boolean {
    return element.classList.contains(className);
  }
  setStyle(element: any /** TODO #9100 */, styleName: string, styleValue: string) {
    element.style[styleName] = styleValue;
  }
  removeStyle(element: any /** TODO #9100 */, stylename: string) {
    element.style[stylename] = null;
  }
  getStyle(element: any /** TODO #9100 */, stylename: string): string {
    return element.style[stylename];
  }
  hasStyle(element: any /** TODO #9100 */, styleName: string, styleValue: string = null): boolean {
    var value = this.getStyle(element, styleName) || '';
    return styleValue ? value == styleValue : value.length > 0;
  }
  tagName(element: any /** TODO #9100 */): string { return element.tagName; }
  attributeMap(element: any /** TODO #9100 */): Map<string, string> {
    var res = new Map<string, string>();
    var elAttrs = element.attributes;
    for (var i = 0; i < elAttrs.length; i++) {
      var attrib = elAttrs[i];
      res.set(attrib.name, attrib.value);
    }
    return res;
  }
  hasAttribute(element: any /** TODO #9100 */, attribute: string): boolean {
    return element.hasAttribute(attribute);
  }
  hasAttributeNS(element: any /** TODO #9100 */, ns: string, attribute: string): boolean {
    return element.hasAttributeNS(ns, attribute);
  }
  getAttribute(element: any /** TODO #9100 */, attribute: string): string {
    return element.getAttribute(attribute);
  }
  getAttributeNS(element: any /** TODO #9100 */, ns: string, name: string): string {
    return element.getAttributeNS(ns, name);
  }
  setAttribute(element: any /** TODO #9100 */, name: string, value: string) {
    element.setAttribute(name, value);
  }
  setAttributeNS(element: any /** TODO #9100 */, ns: string, name: string, value: string) {
    element.setAttributeNS(ns, name, value);
  }
  removeAttribute(element: any /** TODO #9100 */, attribute: string) {
    element.removeAttribute(attribute);
  }
  removeAttributeNS(element: any /** TODO #9100 */, ns: string, name: string) {
    element.removeAttributeNS(ns, name);
  }
  templateAwareRoot(el: any /** TODO #9100 */): any {
    return this.isTemplateElement(el) ? this.content(el) : el;
  }
  createHtmlDocument(): HTMLDocument {
    return document.implementation.createHTMLDocument('fakeTitle');
  }
  defaultDoc(): HTMLDocument { return document; }
  getBoundingClientRect(el: any /** TODO #9100 */): any {
    try {
      return el.getBoundingClientRect();
    } catch (e) {
      return {top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0};
    }
  }
  getTitle(): string { return document.title; }
  setTitle(newTitle: string) { document.title = newTitle || ''; }
  elementMatches(n: any /** TODO #9100 */, selector: string): boolean {
    var matches = false;
    if (n instanceof HTMLElement) {
      if (n.matches) {
        matches = n.matches(selector);
      } else if (n.msMatchesSelector) {
        matches = n.msMatchesSelector(selector);
      } else if (n.webkitMatchesSelector) {
        matches = n.webkitMatchesSelector(selector);
      }
    }
    return matches;
  }
  isTemplateElement(el: any): boolean {
    return el instanceof HTMLElement && el.nodeName == 'TEMPLATE';
  }
  isTextNode(node: Node): boolean { return node.nodeType === Node.TEXT_NODE; }
  isCommentNode(node: Node): boolean { return node.nodeType === Node.COMMENT_NODE; }
  isElementNode(node: Node): boolean { return node.nodeType === Node.ELEMENT_NODE; }
  hasShadowRoot(node: any /** TODO #9100 */): boolean {
    return isPresent(node.shadowRoot) && node instanceof HTMLElement;
  }
  isShadowRoot(node: any /** TODO #9100 */): boolean { return node instanceof DocumentFragment; }
  importIntoDoc(node: Node): any {
    var toImport = node;
    if (this.isTemplateElement(node)) {
      toImport = this.content(node);
    }
    return document.importNode(toImport, true);
  }
  adoptNode(node: Node): any { return document.adoptNode(node); }
  getHref(el: Element): string { return (<any>el).href; }
  getEventKey(event: any /** TODO #9100 */): string {
    var key = event.key;
    if (isBlank(key)) {
      key = event.keyIdentifier;
      // keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
      // Safari
      // cf
      // http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
      if (isBlank(key)) {
        return 'Unidentified';
      }
      if (key.startsWith('U+')) {
        key = String.fromCharCode(parseInt(key.substring(2), 16));
        if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
          // There is a bug in Chrome for numeric keypad keys:
          // https://code.google.com/p/chromium/issues/detail?id=155654
          // 1, 2, 3 ... are reported as A, B, C ...
          key = (_chromeNumKeyPadMap as any /** TODO #9100 */)[key];
        }
      }
    }
    if (_keyMap.hasOwnProperty(key)) {
      key = (_keyMap as any /** TODO #9100 */)[key];
    }
    return key;
  }
  getGlobalEventTarget(target: string): EventTarget {
    if (target == 'window') {
      return window;
    } else if (target == 'document') {
      return document;
    } else if (target == 'body') {
      return document.body;
    }
  }
  getHistory(): History { return window.history; }
  getLocation(): Location { return window.location; }
  getBaseHref(): string {
    var href = getBaseElementHref();
    if (isBlank(href)) {
      return null;
    }
    return relativePath(href);
  }
  resetBaseElement(): void { baseElement = null; }
  getUserAgent(): string { return window.navigator.userAgent; }
  setData(element: any /** TODO #9100 */, name: string, value: string) {
    this.setAttribute(element, 'data-' + name, value);
  }
  getData(element: any /** TODO #9100 */, name: string): string {
    return this.getAttribute(element, 'data-' + name);
  }
  getComputedStyle(element: any /** TODO #9100 */): any { return getComputedStyle(element); }
  // TODO(tbosch): move this into a separate environment class once we have it
  setGlobalVar(path: string, value: any) { setValueOnPath(global, path, value); }
  supportsWebAnimation(): boolean { return isFunction((<any>Element).prototype['animate']); }
  performanceNow(): number {
    // performance.now() is not available in all browsers, see
    // http://caniuse.com/#search=performance.now
    if (isPresent(window.performance) && isPresent(window.performance.now)) {
      return window.performance.now();
    } else {
      return DateWrapper.toMillis(DateWrapper.now());
    }
  }

  supportsCookies(): boolean { return true; }

  getCookie(name: string): string { return parseCookieValue(document.cookie, name); }

  setCookie(name: string, value: string) {
    // document.cookie is magical, assigning into it assigns/overrides one cookie value, but does
    // not clear other cookies.
    document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
  }
}

var baseElement: any /** TODO #9100 */ = null;
function getBaseElementHref(): string {
  if (isBlank(baseElement)) {
    baseElement = document.querySelector('base');
    if (isBlank(baseElement)) {
      return null;
    }
  }
  return baseElement.getAttribute('href');
}

// based on urlUtils.js in AngularJS 1
var urlParsingNode: any /** TODO #9100 */ = null;
function relativePath(url: any /** TODO #9100 */): string {
  if (isBlank(urlParsingNode)) {
    urlParsingNode = document.createElement('a');
  }
  urlParsingNode.setAttribute('href', url);
  return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
                                                       '/' + urlParsingNode.pathname;
}

export function parseCookieValue(cookieStr: string, name: string): string {
  name = encodeURIComponent(name);
  for (const cookie of cookieStr.split(';')) {
    const eqIndex = cookie.indexOf('=');
    const [cookieName, cookieValue]: string[] =
        eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)];
    if (cookieName.trim() === name) {
      return decodeURIComponent(cookieValue);
    }
  }
  return null;
}


text:
typedef CGAL::Exact_circular_kernel_2 CK;

  CK ck;

#include <CGAL/_test_circles_predicates.h>
#include <CGAL/_test_circles_constructions.h>
#include <CGAL/_test_circles_extention.h>

int main() {

  _test_circle_predicat(ck);
  _test_circle_construct(ck);
  _test_circle_bbox(ck);
  _test_circular_arc_bbox(ck);
  _test_has_on(ck);

  return 0;
}


text:
"""
"""
from __future__ import absolute_import

import unittest

from . import enumerant as enum

class Host(enum.RegexCase):
    pass

class HOSTS(enum.Enumerant):
    THEATLANTIC = Host('github.com/theatlantic')
    PYPI = Host('pypi.python.org')
    FALLBACK = Host('*')

class NOFALLBACK(enum.Enumerant):
    THEATLANTIC = Host('github.com/theatlantic')
    PYPI = Host('pypi.python.org')

class EnumerantTests(unittest.TestCase):

    def test_example(self):
        urls = {
            'ours': 'https://github.com/theatlantic/python-ldap',
            'pypi': 'https://pypi.python.org/pypi/pytz/',
            'other':'https://github.com/python-pillow/Pillow'
        }

        self.assertEqual(HOSTS.match(urls['ours']), HOSTS.THEATLANTIC)
        self.assertEqual(HOSTS.match(urls['pypi']), HOSTS.PYPI)
        self.assertEqual(HOSTS.match(urls['other']), HOSTS.FALLBACK)

    def test_classproperties(self):
        self.assertEqual(set(HOSTS.cases), set([HOSTS.THEATLANTIC, HOSTS.PYPI]))
        self.assertEqual(set([HOSTS.default]), set([HOSTS.FALLBACK]))

    def test_exceptions(self):
        self.assertRaises(enum.EnumerantMatchError, lambda: NOFALLBACK.match('zzzzz'))

if __name__ == "__main__":
    unittest.main()


text:
<?php
function load_user($user_id) {
  return \Drupal\user\Entity\User::load($user_id);
}

// Get database connection
\Drupal\Core\Database\Database::setActiveConnection();
$connection = \Drupal\Core\Database\Database::getConnection();

// Get all the users
$results = $connection->query('SELECT u.uid, d.name, d.mail FROM users AS u INNER JOIN users_field_data AS d ON u.uid = d.uid;')->fetchAll();

// For each user, remove the user_picture and then save the user
if ($results) {
  foreach ($results as $record) {
    $user_id = $record->uid;
    $user_name = $record->name;
    $user_email = $record->mail;
    print "Removing user_picture from $user_name ($user_email)...\n";
    $user = load_user($user_id);
    $user->set("user_picture", NULL);
    $user->save();
  }
}
?>


text:
from asynq import asynq, result
from qcore.asserts import AssertRaises

@asynq()
def bad_function():
    yield bad_function.asynq()

def test_it():
    with AssertRaises(RuntimeError):
        bad_function()


text:
from unittest import TestCase

from mock import patch, Mock
import json
import requests

from newrelic_api.alert_policies import AlertPolicies

class NRAlertPoliciesTests(TestCase):
    def setUp(self):
        super(NRAlertPoliciesTests, self).setUp()
        self.policies = AlertPolicies(api_key='dummy_key')

        self.policies_list_response = {
            "policies": [
                {
                    "id": 12345,
                    "incident_preference": "PER_CONDITION_AND_TARGET",
                    "name": "Default Server Policy",
                    "created_at": 123456789012,
                }
            ]
        }
        self.policy_single_response = {
            "policy": self.policies_list_response['policies'][0]
        }
        self.channel_single_response = {
            "channel": {
                "id": 111222,
                "type": "user",
                "name": "Some User",
                "links": {
                    "policy_ids": []
                },
                "configuration": {
                    "user": 222333
                }
            }
        }

    @patch.object(requests, 'get')
    def test_list_success(self, mock_get):
        """
        Test alert policies .list()
        """
        mock_response = Mock(name='response')
        mock_response.json.return_value = self.policies_list_response
        mock_get.return_value = mock_response

        # Call the method
        response = self.policies.list()

        self.assertIsInstance(response, dict)

    @patch.object(requests, 'get')
    def test_list_success_with_name(self, mock_get):
        """
        Test alert policies .list() with filter_ids
        """
        mock_response = Mock(name='response')
        mock_response.json.return_value = self.policies_list_response
        mock_get.return_value = mock_response

        # Call the method
        response = self.policies.list(filter_name='Default Server Policy')

        self.assertIsInstance(response, dict)
        mock_get.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policies.json',
            headers=self.policies.headers,
            params='filter[name]=Default Server Policy'
        )

    @patch.object(requests, 'get')
    def test_list_failure(self, mock_get):
        """
        Test alert policies .list() failure case
        """
        mock_response = Mock(name='response')
        mock_response.json.side_effect = ValueError('No JSON object could be decoded')
        mock_get.return_value = mock_response

        with self.assertRaises(ValueError):
            # Call the method
            self.policies.list()

    @patch.object(requests, 'post')
    def test_create_success(self, mock_post):
        """
        Test alert policies .create() calls put with correct parameters
        """
        self.policies.create(
            name=self.policy_single_response['policy']['name'],
            incident_preference=self.policy_single_response['policy']['incident_preference']
        )

        mock_post.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policies.json',
            headers=self.policies.headers,
            data=json.dumps({
                "policy": {
                    "name": self.policy_single_response['policy']['name'],
                    "incident_preference": self.policy_single_response['policy']['incident_preference']
                }
            })
        )

    @patch.object(requests, 'put')
    def test_update_success(self, mock_put):
        """
        Test alert policies .update() calls put with correct parameters
        """
        self.policies.update(
            id=self.policy_single_response['policy']['id'],
            name=self.policy_single_response['policy']['name'],
            incident_preference=self.policy_single_response['policy']['incident_preference']
        )

        mock_put.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policies/{0}.json'.format(
                self.policy_single_response['policy']['id']
            ),
            headers=self.policies.headers,
            data=json.dumps({
                "policy": {
                    "name": self.policy_single_response['policy']['name'],
                    "incident_preference": self.policy_single_response['policy']['incident_preference']
                }
            })
        )

    @patch.object(requests, 'delete')
    def test_delete_success(self, mock_delete):
        """
        Test alert policies .delete() success
        """

        self.policies.delete(id=self.policy_single_response['policy']['id'])

        mock_delete.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policies/{0}.json'.format(
                self.policy_single_response['policy']['id']
            ),
            headers=self.policies.headers
        )

    @patch.object(requests, 'put')
    def test_associate_with_notification_channel_success(self, mock_put):
        """
        Test alert policies .associate_with_notification_channel() calls put with correct parameters
        """
        self.policies.associate_with_notification_channel(
            id=self.policy_single_response['policy']['id'],
            channel_id=self.channel_single_response['channel']['id'],
        )

        mock_put.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policy_channels.json?policy_id={0}&channel_ids={1}'.format(
                self.policy_single_response['policy']['id'],
                self.channel_single_response['channel']['id']
            ),
            headers=self.policies.headers
        )

    @patch.object(requests, 'put')
    def test_dissociate_from_notification_channel(self, mock_put):
        """
        Test alert policies .associate_with_notification_channel() calls put with correct parameters
        """
        self.policies.associate_with_notification_channel(
            id=self.policy_single_response['policy']['id'],
            channel_id=self.channel_single_response['channel']['id'],
        )

        mock_put.assert_called_once_with(
            url='https://api.newrelic.com/v2/alerts_policy_channels.json?policy_id={0}&channel_ids={1}'.format(
                self.policy_single_response['policy']['id'],
                self.channel_single_response['channel']['id']
            ),
            headers=self.policies.headers
        )


text:
@implementation SADAppDelegate

@synthesize window = _window;

#pragma mark - Accessors

- (UIWindow *)window {
    if (!_window) {
        UIScreen *screen = [UIScreen mainScreen];

        _window = [UIWindow new];
        _window.screen = screen;
        _window.frame = screen.bounds;

        SADProviderListViewController *providers = [SADProviderListViewController new];
        UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:providers];
        _window.rootViewController = navigation;
    }
    return _window;
}

- (void)setWindow:(UIWindow *)window {
    // Do nothing
}

#pragma mark - Private

- (void)configureAuthorizaionProviders {

    // consumer_key and consumer_secret are required
    SimpleAuth.configuration[@"twitter"] = @{};
    SimpleAuth.configuration[@"twitter-web"] = @{};

    // client_id and redirect_uri are required
    SimpleAuth.configuration[@"instagram"] = @{};

    // app_id is required
    SimpleAuth.configuration[@"facebook"] = @{};
    SimpleAuth.configuration[@"facebook-web"] = @{};

    // client_id and redirect_uri are required
    SimpleAuth.configuration[@"meetup"] = @{};

    // consumer_key and consumer_secret are required
    SimpleAuth.configuration[@"tumblr"] = @{};

    // client_id and redirect_uri are required
    SimpleAuth.configuration[@"foursquare-web"] = @{};

    // client_id and redirect_uri are required
    SimpleAuth.configuration[@"dropbox-web"] = @{};

    // client_id, client_secret, and redirect_uri are required
    SimpleAuth.configuration[@"linkedin-web"] = @{};

	// client_id and client_secret are required
    SimpleAuth.configuration[@"sinaweibo-web"] = @{};
}

#pragma mark - UIApplicationDelegate

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self configureAuthorizaionProviders];
    [self.window makeKeyAndVisible];
    return YES;
}

@end


text:
package org.cagrid.core.common.security;

import org.apache.cxf.configuration.Configurer;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.configuration.jsse.TLSParameterJaxBUtils;
import org.apache.cxf.configuration.security.FiltersType;
import org.apache.cxf.configuration.security.KeyManagersType;
import org.apache.cxf.configuration.security.KeyStoreType;
import org.apache.cxf.configuration.security.TrustManagersType;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;

public class SSLConfigurer implements Configurer {

    private final Configurer baseConf;
    private Logger log;
    private X509Credential credential;
    private KeyStoreType truststore;
    private KeyManagersType keystore;
    private KeyManager keyManager;
    private TrustManager[] trustManagers;
    private KeyManager[] km;

    public SSLConfigurer(Configurer baseConf) {
        log = LoggerFactory.getLogger(this.getClass().getName());
        this.baseConf = baseConf;
    }

    public X509Credential getCredential() {
        return credential;
    }

    public void setCredential(X509Credential credential) {
        this.credential = credential;
        km = null;
    }

    public KeyStoreType getTruststore() {
        return truststore;
    }

    public void setTruststore(KeyStoreType truststore) {
        this.truststore = truststore;
        trustManagers = null;
    }

    public KeyManagersType getKeystore() {
        return keystore;
    }

    public void setKeystore(KeyManagersType keystore) {
        this.keystore = keystore;
        km = null;
    }

    @Override
    public void configureBean(Object beanInstance) {
        configureBean(null, beanInstance);
    }

    @Override
    public void configureBean(String name, Object beanInstance) {
        if (beanInstance instanceof HTTPConduit) {
            HTTPConduit http = (HTTPConduit) beanInstance;
            TLSClientParameters tls = new TLSClientParameters();

                if (this.trustManagers != null) {
                    try {
                        tls.setTrustManagers(getTrustManagers());
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }

            if (getTruststore() != null) {
                try {
                    tls.setTrustManagers(getTrustManagers());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            if ((getCredential() != null) || (getKeystore() != null)) {
                try {
                    tls.setKeyManagers(getKeyManager());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            tls.setDisableCNCheck(true);
            tls.setCipherSuitesFilter(getCipherSuites());
            http.setTlsClientParameters(tls);
            HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
            httpClientPolicy.setConnectionTimeout(36000);
            httpClientPolicy.setAllowChunking(false);
            httpClientPolicy.setReceiveTimeout(120000);
            http.setClient(httpClientPolicy);

        } else {
            baseConf.configureBean(name, beanInstance);
        }
    }

    private KeyManager[] getKeyManager() throws Exception {
        if (km == null) {
            if (getCredential() != null) {
                km = new KeyManager[1];
                km[0] = credential.getKeyManager();
            } else if (getKeystore() != null) {
                km = TLSParameterJaxBUtils.getKeyManagers(this.keystore);
            }
        }
        return km;
    }

    public void setKm(KeyManager[] km) {
        this.km = km;
    }

    public TrustManager[] getTrustManagers() throws Exception {
        if (trustManagers == null) {
            if (getTruststore() != null) {
                TrustManagersType type = new TrustManagersType();
                type.setKeyStore(getTruststore());
                trustManagers = TLSParameterJaxBUtils.getTrustManagers(type);
            }
        }
        return trustManagers;
    }

    public void setTrustManagers(TrustManager[] trustManagers) {
        this.trustManagers = trustManagers;
    }

    private FiltersType getCipherSuites() {
        FiltersType filters = new FiltersType();
        filters.getInclude().add(".*_WITH_3DES_.*");
        filters.getInclude().add(".*_WITH_DES_.*");
        filters.getExclude().add(".*_WITH_NULL_.*");
        filters.getExclude().add(".*_DH_anon_.*");
        return filters;
    }

}


text:
.. django-valet-keys documentation master file, created by
   sphinx-quickstart on Fri Mar  1 13:27:16 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to django-valet-keys's documentation!
=============================================

django-valet-keys is a Django app for managing valet keys to let robots drive
around in your identity.

- `Build status on travis-ci <http://travis-ci.org/lmorchard/django-valet-keys>`_ (|build-status|)
- `Latest documentation on Read The Docs <https://django-valet-keys.readthedocs.org/en/latest/>`_
  (`source <https://github.com/lmorchard/django-valet-keys/tree/master/docs>`_)
- `Task board on Huboard <http://huboard.com/lmorchard/django-valet-keys/board>`_
  (`source <https://github.com/lmorchard/django-valet-keys/issues>`_)

.. |build-status| image:: https://secure.travis-ci.org/lmorchard/django-valet-keys.png?branch=master
           :target: http://travis-ci.org/lmorchard/django-valet-keys

Contents:

.. toctree::
   :maxdepth: 2

   overview
   getting_started
   usage
   contributing
   faqs

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. vim:set tw=78 ai fo+=n fo-=l ft=rst:


text:
<!DOCTYPE html>

<meta charset="utf-8">

<title>class User::HomepageController - Rails Application Documentation</title>

<link href="../css/fonts.css" rel="stylesheet">
<link href="../css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

User::UserController

Methods

#index

    class User::HomepageController

Public Instance Methods

          index()

          click to toggle source

GET /user

# File app/controllers/user/homepage_controller.rb, line 3
def index
  @count_skill = {
    total: Skill.all.count,
    visible: Skill.where(view: true).count
  }
end

Validate

Generated by RDoc 4.2.1.

Based on Darkfish by Michael Granger.


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>UFS - Painel Administrativo</title>
<meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<link rel="icon" type="image/png" href="dist/img/launcher-icon-2x.png" />

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

			<button id="Sign-in" class="Button Auth Sign-in"></button>

Disputa ativa:

	<button id="newMatch" class="Button">Nova disputa</button>
	<button id="unsetCurrent" class="Button">Desabilitar disputas</button>

		<button id="showResults" class="Button">Resultados</button>


text:
package org.jclouds.docker.domain;

import static org.jclouds.docker.internal.NullSafeCopies.copyOf;
import java.util.List;

import org.jclouds.json.SerializedNames;

import com.google.auto.value.AutoValue;

// TODO it may be redundant (we already have Container value class)
@AutoValue
public abstract class ContainerSummary {

   public abstract String id();

   public abstract List<String> names();

   public abstract String created();

   public abstract String image();

   public abstract String command();

   public abstract List<Port> ports();

   public abstract String status();

   ContainerSummary() {
   }

   @SerializedNames({"Id", "Names", "Created", "Image", "Command", "Ports", "Status"})
   public static ContainerSummary create(String id, List<String> names, String created, String image, String command, List<Port> ports, String status) {
      return new AutoValue_ContainerSummary(id, copyOf(names), created, image, command, copyOf(ports), status);
   }

}


text:
module Hector
  module Commands
    module Names
      def on_names
        channel = Channel.find(request.args.first)
        respond_to_names(channel)
      end

      def respond_to_names(channel)
        responses = Response.apportion_text(channel.nicknames, "353", nickname, "=", channel.name, :source => Hector.server_name)
        responses.each { |response| respond_with(response) }
        respond_with("366", nickname, channel.name, :source => Hector.server_name, :text => "End of /NAMES list.")
      end
    end
  end
end


text:
from __future__ import print_function

import sys
import mesh.patch as patch
import numpy as np
from util import msg

def init_data(my_data, rp):
    """ initialize a smooth advection problem for testing convergence """

    msg.bold("initializing the advect problem...")

    # make sure that we are passed a valid patch object
    if not isinstance(my_data, patch.CellCenterData2d):
        print("ERROR: patch invalid in advect.py")
        print(my_data.__class__)
        sys.exit()

    # get the density, momenta, and energy as separate variables
    dens = my_data.get_var("density")
    xmom = my_data.get_var("x-momentum")
    ymom = my_data.get_var("y-momentum")
    ener = my_data.get_var("energy")

    # initialize the components, remember, that ener here is rho*eint
    # + 0.5*rho*v**2, where eint is the specific internal energy
    # (erg/g)
    dens[:, :] = 1.0
    xmom[:, :] = 0.0
    ymom[:, :] = 0.0

    gamma = rp.get_param("eos.gamma")

    xmin = rp.get_param("mesh.xmin")
    xmax = rp.get_param("mesh.xmax")

    ymin = rp.get_param("mesh.ymin")
    ymax = rp.get_param("mesh.ymax")

    xctr = 0.5*(xmin + xmax)
    yctr = 0.5*(ymin + ymax)

    # this is identical to the advection/smooth problem
    dens[:, :] = 1.0 + np.exp(-60.0*((my_data.grid.x2d-xctr)**2 +
                                    (my_data.grid.y2d-yctr)**2))

    # velocity is diagonal
    u = 1.0
    v = 1.0
    xmom[:, :] = dens[:, :]*u
    ymom[:, :] = dens[:, :]*v

    # pressure is constant
    p = 1.0
    ener[:, :] = p/(gamma - 1.0) + 0.5*(xmom[:, :]**2 + ymom[:, :]**2)/dens[:, :]

def finalize():
    """ print out any information to the user at the end of the run """

    msg = """
          """

    print(msg)


text:
<!DOCTYPE html>

		<title>粒子效果-GPU运算-位移</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">


text:
package com.qikemi.packages.email.bean;

import java.util.List;

/**
 * E-mail bean
 *
 * @description 本程序用于来自谢先斌毕业论文,如有使用请联系作 者,注明出处。
 * @URL 代码地址:http://github.com/openRDF/rdf_fronts
 * @dateTime 2014-3-22 下午6:47:59
 * @author XieXianbin
 * @email a.b@hotmail.com
 */

public class MailBean {

	// 邮件服务是否身份验证
	private boolean validate = true;
	// 邮件接收者的地址
	private String toAddress;
	// 邮件主题
	private String subject;
	// 邮件的文本内容
	private String content;
	// 邮件附件的文件名
	private List<AttachFileBean> attachFileList;

	// default
	public MailBean() {}

	// sample
	public MailBean(String toAddress, String subject, String content) {
		super();
		this.toAddress = toAddress;
		this.subject = subject;
		this.content = content;
	}

	public MailBean(boolean validate, String toAddress, String subject,
			String content) {
		super();
		this.validate = validate;
		this.toAddress = toAddress;
		this.subject = subject;
		this.content = content;
	}

	public MailBean(String toAddress, String subject,
			String content, List<AttachFileBean> attachFileList) {
		super();
		this.toAddress = toAddress;
		this.subject = subject;
		this.content = content;
		this.attachFileList = attachFileList;
	}

	// full
	public MailBean(boolean validate, String toAddress, String subject,
			String content, List<AttachFileBean> attachFileList) {
		super();
		this.validate = validate;
		this.toAddress = toAddress;
		this.subject = subject;
		this.content = content;
		this.attachFileList = attachFileList;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public List<AttachFileBean> getAttachFileList() {
		return attachFileList;
	}

	public void setAttachFileList(List<AttachFileBean> attachFileList) {
		this.attachFileList = attachFileList;
	}

}


text:
namespace base {
class SequencedTaskRunner;
}

namespace content {

// Used to sequence ServiceWorkerDatabase tasks. Vends two task runners: one
// that blocks shutdown and one that doesn't. The task runners use the same
// sequence token, so no matter which runner you post to, the tasks run in the
// order they are posted. This lets you post sequenced tasks with mixed shutdown
// behaviors.
class ServiceWorkerDatabaseTaskManager {
 public:
  virtual ~ServiceWorkerDatabaseTaskManager() {}
  virtual std::unique_ptr<ServiceWorkerDatabaseTaskManager> Clone() = 0;
  virtual base::SequencedTaskRunner* GetTaskRunner() = 0;
  virtual base::SequencedTaskRunner* GetShutdownBlockingTaskRunner() = 0;
};

class ServiceWorkerDatabaseTaskManagerImpl
    : public ServiceWorkerDatabaseTaskManager {
 public:
  explicit ServiceWorkerDatabaseTaskManagerImpl(
      base::SequencedWorkerPool* pool);
  ~ServiceWorkerDatabaseTaskManagerImpl() override;

 protected:
  std::unique_ptr<ServiceWorkerDatabaseTaskManager> Clone() override;
  base::SequencedTaskRunner* GetTaskRunner() override;
  base::SequencedTaskRunner* GetShutdownBlockingTaskRunner() override;

 private:
  ServiceWorkerDatabaseTaskManagerImpl(
      const scoped_refptr<base::SequencedTaskRunner>& task_runner,
      const scoped_refptr<base::SequencedTaskRunner>&
          shutdown_blocking_task_runner);

  scoped_refptr<base::SequencedTaskRunner> task_runner_;
  scoped_refptr<base::SequencedTaskRunner> shutdown_blocking_task_runner_;

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerDatabaseTaskManagerImpl);
};

// Dummy implementation for testing. It vends whatever you give it in the ctor.
class CONTENT_EXPORT MockServiceWorkerDatabaseTaskManager
    : public NON_EXPORTED_BASE(ServiceWorkerDatabaseTaskManager) {
 public:
  explicit MockServiceWorkerDatabaseTaskManager(
      const scoped_refptr<base::SequencedTaskRunner>& task_runner);
  ~MockServiceWorkerDatabaseTaskManager() override;

 protected:
  std::unique_ptr<ServiceWorkerDatabaseTaskManager> Clone() override;
  base::SequencedTaskRunner* GetTaskRunner() override;
  base::SequencedTaskRunner* GetShutdownBlockingTaskRunner() override;

 private:
  scoped_refptr<base::SequencedTaskRunner> task_runner_;

  DISALLOW_COPY_AND_ASSIGN(MockServiceWorkerDatabaseTaskManager);
};

}  // namespace content

#endif  // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DATABASE_TASK_MANAGER_H_


text:
import {
  isEqual,
  isFn,
  Subscribable,
  FormPath,
  FormPathPattern,
  defaults,
  shallowClone,
  isStr,
  isValid
} from '@formily/shared'
import { Immer, enableAllPlugins, Draft, setAutoFreeze } from 'immer'
import { StateDirtyMap, IDirtyModelFactory, NormalRecord } from '../types'

enableAllPlugins()

setAutoFreeze(false)

const { produce } = new Immer({
  autoFreeze: false
})

type Recipe<State> = (state?: State) => any

type ExtendsState = NormalRecord & { displayName?: string }

type ExtendsProps<State> = NormalRecord & {
  computeState?: (state: Draft<State>, prevState: State) => any
  dirtyCheck?: (path: FormPathPattern, value: any, nextValue: any) => boolean
}

type Patch = {
  op: 'replace' | 'remove' | 'add'
  path: (string | number)[]
  value?: any
}

const applyPatches = (target: any, patches: Patch[]) => {
  patches.forEach(({ op, path, value }) => {
    if (op === 'replace' || op === 'add') {
      FormPath.setIn(target, path, value)
    } else if (op === 'remove') {
      FormPath.deleteIn(target, path)
    }
  })
}

type CacheKey = string | Symbol | number

export const createModel = <
  State extends ExtendsState,
  Props extends ExtendsProps<State>
>(
  Factory: IDirtyModelFactory<State, Props>
) => {
  return class Model extends Subscribable {
    factory: InstanceType<IDirtyModelFactory<State, Props>>
    state: State
    prevState: State
    props: Props
    patches: Patch[]
    dirtyStack: StateDirtyMap<State>[]
    dirtyCountStack: number[]
    batching: boolean
    cache: Map<any, any>
    displayName: string
    constructor(props: Props = {} as any) {
      super()
      this.props = defaults(Factory.defaultProps, props)
      this.displayName = Factory.displayName
      this.factory = new Factory(this.props)
      this.cache = new Map()
      this.state = this.factory.state as any
      this.state.displayName = this.displayName
      this.prevState = this.state
      this.batching = false
      this.dirtyStack = []
      this.dirtyCountStack = []
    }

    enterCalculateDirtys() {
      this.dirtyStack.push({})
      this.dirtyCountStack.push(0)
    }

    existCalculateDirtys() {
      this.dirtyStack.pop()
      this.dirtyCountStack.pop()
    }

    get dirtys(): StateDirtyMap<State> {
      return this.dirtyStack[this.dirtyStack.length - 1] || {}
    }

    set dirtys(dirtys: StateDirtyMap<State>) {
      if (this.dirtyStack.length === 0) {
        this.dirtyStack.push({})
      }
      this.dirtyStack[this.dirtyStack.length - 1] = dirtys
    }

    get dirtyCount() {
      return this.dirtyCountStack[this.dirtyCountStack.length - 1] || 0
    }

    set dirtyCount(value) {
      if (this.dirtyCountStack.length === 0) {
        this.dirtyCountStack.push(0)
      }
      this.dirtyCountStack[this.dirtyCountStack.length - 1] = value
    }

    getBaseState() {
      if (isFn(this.factory.getState)) {
        return this.factory.getState.call(this.factory, this.state)
      } else {
        return this.state
      }
    }

    getDirtysFromPatches(
      patches: Patch[],
      refresh?: boolean
    ): StateDirtyMap<State> {
      return patches.reduce(
        (buf, { path }) => {
          buf[path[0]] = true
          return buf
        },
        refresh ? {} : this.batching ? this.dirtys : {}
      )
    }

    dirtyCheck(path: FormPathPattern, nextValue: any) {
      const currentValue = FormPath.getIn(this.state, path)
      if (isFn(this.factory.dirtyCheck)) {
        if (isFn(this.props.dirtyCheck)) {
          return (
            this.factory.dirtyCheck(path, currentValue, nextValue) &&
            this.props.dirtyCheck(path, currentValue, nextValue)
          )
        } else {
          return this.factory.dirtyCheck(path, currentValue, nextValue)
        }
      } else {
        if (isFn(this.props.dirtyCheck)) {
          return this.props.dirtyCheck(path, currentValue, nextValue)
        } else {
          return !isEqual(currentValue, nextValue)
        }
      }
    }

    setState(recipe?: Recipe<State>, silent: boolean = false) {
      if (!isFn(recipe)) return
      const base = this.getBaseState()
      this.patches = []
      this.prevState = base
      this.factory.prevState = base
      this.factory.state = base
      this.factory?.beforeProduce?.()
      if (!this.batching) {
        this.enterCalculateDirtys()
      }
      produce(
        base,
        draft => {
          recipe(draft)
          if (isFn(this.props.computeState)) {
            this.props.computeState(draft, this.prevState)
          }
        },
        patches => {
          this.patches = this.patches.concat(patches)
        }
      )
      const produced = produce(
        base,
        draft => {
          applyPatches(draft, this.patches)
          const dirtys = this.getDirtysFromPatches(this.patches, true)
          if (isFn(this.factory.produce)) {
            this.factory.produce(draft, dirtys)
          }
        },
        patches => {
          patches.forEach(patch => {
            const { path, value } = patch
            if (this.dirtyCheck(path, value)) {
              this.patches.push(patch)
              this.dirtyCount++
            }
          })
        }
      )
      this.factory.state = produced
      this.state = produced
      this.dirtys = this.getDirtysFromPatches(this.patches)
      this.patches = []
      this.factory?.afterProduce?.()
      if (this.dirtyCount > 0 && !silent) {
        if (this.batching) {
          return
        }
        this.notify(this.getState(), silent)
      }
      this.existCalculateDirtys()
    }

    setSourceState(recipe?: Recipe<State>) {
      if (!isFn(recipe)) return this.state
      recipe(this.state)
    }

    getState<T extends Recipe<State>>(
      recipe?: T
    ): T extends Recipe<State> ? ReturnType<T> : State {
      if (!isFn(recipe)) return this.getBaseState()
      return recipe(this.getBaseState())
    }

    getSourceState<T extends Recipe<State>>(
      recipe?: T
    ): T extends Recipe<State> ? ReturnType<T> : State {
      if (!isFn(recipe)) return this.state as any
      return recipe(this.state)
    }

    batch(callback?: () => void) {
      this.batching = true
      this.enterCalculateDirtys()
      const prevState = this.state
      if (isFn(callback)) {
        callback()
      }
      this.prevState = prevState
      if (this.dirtyCount > 0) {
        this.notify(this.getState())
      }
      this.batching = false
      this.existCalculateDirtys()
    }

    setCache(key: CacheKey, value: any) {
      this.cache.set(
        key,
        typeof value === 'object' ? shallowClone(value) : value
      )
    }

    getCache(key: CacheKey) {
      const value = this.cache.get(key)
      if (isValid(value)) return value
      if (this.cache.size === 1) {
        let findKey = null
        this.cache.forEach((value, key) => {
          findKey = key
        })
        return this.cache.get(findKey)
      }
      return value
    }

    removeCache(key: CacheKey) {
      this.cache.delete(key)
    }

    isDirty(key?: string) {
      if (key) {
        return this.dirtys[key]
      } else {
        return this.dirtyCount > 0
      }
    }

    hasChanged = (pattern?: FormPathPattern) => {
      if (!pattern) {
        return this.dirtyCount > 0
      } else {
        const path = FormPath.parse(pattern)
        if (path.length > 1 || !isStr(pattern)) {
          return !isEqual(
            FormPath.getIn(this.prevState, path),
            FormPath.getIn(this.state, path)
          )
        } else {
          return this.dirtys[pattern]
        }
      }
    }
  }
}


text:
require 'spec_helper'

module Arel
  describe Update do
    before do
      @relation = Table.new(:users)
    end
  end
end


text:
def main():
    filename = "hello.txt"
    file = open(filename, "w")
    file.write("Hello, World!")
    file.close()

    file = open(filename, "r")
    content = file.read()
    print(content)
    file.close()

# PROGRAM RUN
if __name__ == "__main__":
    main()


text:
		<?php
		include "admin/connection.php";

		if (empty($_GET['id'])){
			$id=26;
		}else{
			$id=$_GET['id'];
		}

			$stmt=$con->prepare("SELECT * FROM tbl_category WHERE tbl_category.trust='1' and menu_id='$id'");
			$stmt->execute();
			$spacial=$stmt->fetchAll();
			foreach ($spacial as $spacailcat){
				?>
				<lo><a title="<?php echo $spacailcat['category']?>" href="<?php echo'#'. $spacailcat['id_category'];?>"><img src="img/logo/<?php echo $spacailcat['icon']?>"style="width: 40px; height: 40px;"></lo>
				<?php
			}

		?>

		<lo class="fb_book"></lo>
		<lo class="fb_youtube"></lo>
		<lo class="fb_job"></lo>


text:
package org.apache.geode.rest.internal.web.controllers.support;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.springframework.util.StringUtils;

import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;

public class RestServersResultCollector<String, Object> implements ResultCollector<String, Object> {

  private ArrayList resultList = new ArrayList();

  @Override
  public void addResult(DistributedMember memberID, String result) {
    if (!StringUtils.isEmpty(result)) {
      this.resultList.add(result);
    }
  }

  @Override
  public void endResults() {}

  @Override
  public Object getResult() throws FunctionException {
    return (Object) resultList;
  }

  @Override
  public Object getResult(long timeout, TimeUnit unit) throws FunctionException {
    return (Object) resultList;
  }

  @Override
  public void clearResults() {
    resultList.clear();
  }

}