text:
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DotNetCommons.Test;

[TestClass]
public class CommonCollectionExtensionsTest
{
    private List<string> _list = null!;
    private Dictionary<string, int> _dictI = null!;
    private Dictionary<string, decimal> _dictD = null!;

    [TestInitialize]
    public void Setup()
    {
        _list = new List<string> { "A", "AB", "C", "D" };
        _dictI = new Dictionary<string, int> { ["A"] = 1, ["B"] = 0 };
        _dictD = new Dictionary<string, decimal> { ["A"] = 1, ["B"] = 0 };
    }

    [TestMethod]
    public void TestAddIfNotNull()
    {
        var list = new List<string>();

        ((List<string>?)null).AddIfNotNull("hello");

        list.AddIfNotNull("hello");
        list.AddIfNotNull("");
        list.AddIfNotNull(null);

        Assert.AreEqual(2, list.Count);
    }

    [TestMethod]
    public void TestAddRangeIfNotNull()
    {
        var list = new List<string>();

        ((List<string>?)null).AddRangeIfNotNull(null);
        ((List<string>?)null).AddRangeIfNotNull(list);

        list.AddRangeIfNotNull(null);
        list.AddRangeIfNotNull(new[] { "hello", "", null });

        Assert.AreEqual(2, list.Count);
    }

    [TestMethod]
    public void TestBatch()
    {
        var batches = new[] { 'a', 'b', 'c', 'd', 'e', 'f' }.Batch(3)
            .Select(x => string.Join("", x))
            .ToList();

        Assert.AreEqual(2, batches.Count);
        Assert.AreEqual("abc", batches[0]);
        Assert.AreEqual("def", batches[1]);

        batches = new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }.Batch(3)
            .Select(x => string.Join("", x))
            .ToList();

        Assert.AreEqual(3, batches.Count);
        Assert.AreEqual("abc", batches[0]);
        Assert.AreEqual("def", batches[1]);
        Assert.AreEqual("gh", batches[2]);

        batches = new[] { 'a' }.Batch(3)
            .Select(x => string.Join("", x))
            .ToList();

        Assert.AreEqual(1, batches.Count);
        Assert.AreEqual("a", batches[0]);

        batches = Array.Empty<char>().Batch(3)
            .Select(x => string.Join("", x))
            .ToList();

        Assert.AreEqual(0, batches.Count);
    }

    [TestMethod]
    public void TestExtractAt()
    {
        var item = _list.ExtractAt(1);

        Assert.AreEqual(item, "AB");
        Assert.AreEqual("A,C,D", string.Join(",", _list));
    }

    [TestMethod]
    public void TestExtractAtOrDefault()
    {
        var item = _list.ExtractAtOrDefault(1);

        Assert.AreEqual(item, "AB");
        Assert.AreEqual("A,C,D", string.Join(",", _list));

        item = _list.ExtractAtOrDefault(99);

        Assert.IsNull(item);
        Assert.AreEqual("A,C,D", string.Join(",", _list));
    }

    [TestMethod]
    public void TestExtractAll()
    {
        var items = _list.ExtractAll();

        Assert.AreEqual(4, items.Count);
        Assert.AreEqual(0, _list.Count);
    }

    [TestMethod]
    public void TestExtractAll_WithPredicate()
    {
        var items = _list.ExtractAll(x => x.StartsWith("A"));

        Assert.AreEqual("A,AB", string.Join(",", items));
        Assert.AreEqual("C,D", string.Join(",", _list));
    }

    [TestMethod]
    public void TestExtractFirst()
    {
        Assert.AreEqual("A", _list.ExtractFirst());
    }

    [TestMethod]
    public void TestExtractFirstOrDefault()
    {
        Assert.AreEqual("A", _list.ExtractFirstOrDefault());
        _list.Clear();
        Assert.IsNull(_list.ExtractFirstOrDefault());
    }

    [TestMethod]
    public void TestExtractLast()
    {
        Assert.AreEqual("D", _list.ExtractLast());
    }

    [TestMethod]
    public void TestExtractLastOrDefault()
    {
        Assert.AreEqual("D", _list.ExtractLastOrDefault());
        _list.Clear();
        Assert.IsNull(_list.ExtractLastOrDefault());
    }

    [TestMethod]
    public void TestExtractRange()
    {
        var list = Enumerable.Range(1, 10).ToList();

        var extract = list.ExtractRange(3, 2);

        Assert.AreEqual("4,5", string.Join(",", extract));
        Assert.AreEqual("1,2,3,6,7,8,9,10", string.Join(",", list));
    }

    [TestMethod]
    public void TestIncrementInteger()
    {
        Assert.AreEqual(2, _dictI.Increment("A"));
        Assert.AreEqual(2, _dictI.Increment("Z", 2));
    }

    [TestMethod]
    public void TestIntersect()
    {
        var list1 = new[] { 1, 2, 3, 4, 5 };
        var list2 = new[] { 4, 5, 6, 7 };

        var intersect = list1.Intersect(list2);
        CollectionAssert.AreEqual(new[] { 1, 2, 3 }, intersect.Left);
        CollectionAssert.AreEqual(new[] { (4, 4), (5, 5) }, intersect.Both);
        CollectionAssert.AreEqual(new[] { 6, 7 }, intersect.Right);

        list1 = new[] { 1, 2, 3, 4, 5 };
        list2 = new[] { 4, 5 };

        intersect = list1.Intersect(list2);
        CollectionAssert.AreEqual(new[] { 1, 2, 3 }, intersect.Left);
        CollectionAssert.AreEqual(new[] { (4, 4), (5, 5) }, intersect.Both);
        CollectionAssert.AreEqual(Array.Empty<int>(), intersect.Right);

        list1 = Array.Empty<int>();
        list2 = new[] { 4, 5 };

        intersect = list1.Intersect(list2);
        CollectionAssert.AreEqual(Array.Empty<int>(), intersect.Left);
        CollectionAssert.AreEqual(Array.Empty<int>(), intersect.Both);
        CollectionAssert.AreEqual(new[] { 4, 5 }, intersect.Right);
    }

    [TestMethod]
    public void TestIncrementDecimal()
    {
        Assert.AreEqual(2.99M, _dictD.Increment("A", 1.99M));
        Assert.AreEqual(2.45M, _dictD.Increment("Z", 2.45M));
    }

    [TestMethod]
    public void TestMinMax()
    {
        var list = new[] { 4, 7, 9, 3, 2, 10, 99, 64, 5 };

        var (min, max) = list.MinMax();
        Assert.AreEqual(2, min);
        Assert.AreEqual(99, max);

        list = new[] { 4 };

        (min, max) = list.MinMax();
        Assert.AreEqual(4, min);
        Assert.AreEqual(4, max);
    }

    [TestMethod]
    public void TestMinMax_WithSelector()
    {
        var list = new int?[] { 4, 7, 9, 3, 2, 10, 99, 64, 5 };

        var (min, max) = list.MinMax(x => x!.Value);
        Assert.AreEqual(2, min);
        Assert.AreEqual(99, max);
    }

    [TestMethod]
    public void TestRepeat()
    {
        var list = new[] { 1, 2, 3 };

        Assert.AreEqual("123123123", string.Join("", list.Repeat(3)));
        Assert.AreEqual("123", string.Join("", list.Repeat(1)));
        Assert.AreEqual("", string.Join("", list.Repeat(0)));

        list = new[] { 1 };

        Assert.AreEqual("111", string.Join("", list.Repeat(3)));
        Assert.AreEqual("1", string.Join("", list.Repeat(1)));
        Assert.AreEqual("", string.Join("", list.Repeat(0)));

        list = Array.Empty<int>();

        Assert.AreEqual("", string.Join("", list.Repeat(3)));
        Assert.AreEqual("", string.Join("", list.Repeat(1)));
        Assert.AreEqual("", string.Join("", list.Repeat(0)));
    }

    [TestMethod]
    public void TestSwap()
    {
        var list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsTrue(list.Swap(0, 1));
        Assert.AreEqual("2,1,3,4,5", string.Join(",", list));

        list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsTrue(list.Swap(1, 2));
        Assert.AreEqual("1,3,2,4,5", string.Join(",", list));

        list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsTrue(list.Swap(0, 4));
        Assert.AreEqual("5,2,3,4,1", string.Join(",", list));

        list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsTrue(list.Swap(3, 4));
        Assert.AreEqual("1,2,3,5,4", string.Join(",", list));

        list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsFalse(list.Swap(-1, 0));
        Assert.AreEqual("1,2,3,4,5", string.Join(",", list));

        list = new[] { 1, 2, 3, 4, 5 };
        Assert.IsFalse(list.Swap(0, 5));
        Assert.AreEqual("1,2,3,4,5", string.Join(",", list));
    }

    public class TreeNode
    {
        public string Name { get; }
        public List<TreeNode> Children { get; } = new List<TreeNode>();

        public TreeNode(string name, params TreeNode[] children)
        {
            Name = name;
            Children.AddRange(children);
        }
    }

    private static List<TreeNode> MakeTreeNodes()
    {
        return new List<TreeNode>
        {
            new TreeNode("Top",
                new TreeNode("TopLeft"),
                new TreeNode("TopRight")
            ),
            new TreeNode("Middle"),
            new TreeNode("Bottom",
                new TreeNode("BottomLeft",
                    new TreeNode("BottomLeftDeep")
                ),
                new TreeNode("BottomRight",
                    new TreeNode("BottomRightDeep")
                )
            )
        };
    }

    [TestMethod]
    public void TestWalkTree_DepthFirst()
    {
        var names = MakeTreeNodes()
            .WalkTree(n => n.Children, WalkTreeMode.DepthFirst)
            .Select(n => n.Name)
            .ToList();

        names.Count.Should().Be(9);

        var text = string.Join(",", names);
        text.Should().Be("Top,TopLeft,TopRight,Middle,Bottom,BottomLeft,BottomLeftDeep,BottomRight,BottomRightDeep");
    }

    [TestMethod]
    public void TestWalkTree_ShallowFirst()
    {
        var names = MakeTreeNodes()
            .WalkTree(n => n.Children, WalkTreeMode.ShallowFirst)
            .Select(n => n.Name)
            .ToList();

        names.Count.Should().Be(9);

        var text = string.Join(",", names);
        text.Should().Be("Top,Middle,Bottom,TopLeft,TopRight,BottomLeft,BottomRight,BottomLeftDeep,BottomRightDeep");
    }

    [TestMethod]
    public void TestWalkTree_BreakInMiddle()
    {
        var nodes = MakeTreeNodes();
        var names = new List<string>();

        foreach (var node in nodes.WalkTree(n => n.Children, WalkTreeMode.ShallowFirst))
        {
            names.Add(node.Name);
            if (names.Count >= 5)
                break;
        }

        names.Count.Should().Be(5);
        var text = string.Join(",", names);
        text.Should().Be("Top,Middle,Bottom,TopLeft,TopRight");
    }
}


text:
type: doc
layout: reference
category: "Other"
title: "Equality"
---

# Equality

In Kotlin there are two types of equality:

* Structural equality (a check for `equals()`).
* Referential equality (two references point to the same object);

## Structural equality

Structural equality is checked by the `==` operation (and its negated counterpart `!=`). By convention, an expression like `a == b` is translated to:

``` kotlin
a?.equals(b) ?: (b === null)
```

I.e. if `a` is not `null`, it calls the `equals(Any?)` function, otherwise (i.e. `a` is `null`) it checks that `b` is referentially equal to `null`.

Note that there's no point in optimizing your code when comparing to `null` explicitly: `a == null` will be automatically translated to `a === null`.

## Floating point numbers equality

When an equality check operands are statically known to be `Float` or `Double` (nullable or not), the check follows the IEEE 754
Standard for Floating-Point Arithmetic.

Otherwise, the structural equality is used, which disagrees with the standard so that `NaN` is equal to itself, and `-0.0` is not equal to `0.0`.

See: [Floating Point Numbers Comparison](basic-types.html#floating-point-numbers-comparison).

## Referential equality

Referential equality is checked by the `===` operation (and its negated counterpart `!==`). `a === b` evaluates to
true if and only if `a` and `b` point to the same object. For values which are represented as primitive types at runtime
(for example, `Int`), the `===` equality check is equivalent to the `==` check.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

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

    <meta name="description" content="Assures Quality with business logic">
    <meta name="author" content="Nerdwallet QA Team">
    <link rel="icon" href="images/favicon.ico">

     <title>Q: The Data Scientist</title>

    <link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="bootstrap-3.3.5-dist/css/bootstrap-theme.min.css" rel="stylesheet">

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

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
    Toggle navigation

    </button>

    Q: The Data scientist

<button type="button" class="btn btn-sm btn-primary">View Meta</button>

<button type="button" class="btn btn-sm btn-primary">Terminal</button>

About Q - An analytics Framework

Q is a vector language, designed for efficient implementation of counting, sorting and data transformations. It uses a
single data structure — a table.

In designing Q, we wanted it to be a data model as Codd defines one
A data model is a combination of at least three components:

A collection of data structure types (the building blocks);

A collection of operators or rules of inference, which can be applied to any
valid instances of the data types listed in (1), to retrieve, derive, or modify
data from any parts of those structures in any combinations desired;

A collection of general integrity rules, which implicitly or explicitly define
the set of consistent database states or changes of states or both.

QA Team @ NerdWallet


text:
package com.tyrfing.games.tyrlib3.view.graphics;

import java.util.ArrayList;
import java.util.List;

import com.tyrfing.games.tyrlib3.model.graphics.VertexLayout;
import com.tyrfing.games.tyrlib3.model.math.Vector3F;
import com.tyrfing.games.tyrlib3.view.graphics.materials.Material;
import com.tyrfing.games.tyrlib3.view.graphics.renderables.Renderable;

/**
 * Creates a new renderable consisting of the inputed meshs and using
 * one uniform material
 * @author Sascha
 *
 */

public class MeshMixer {

	private List<Renderable> inputRenderables;
	private List<Vector3F> inputOffsets;
	private List<Vector3F> inputScales;
	private int countVertices;
	private int countIndices;
	private Material material;

	public MeshMixer(Material material) {
		inputRenderables = new ArrayList<Renderable>();
		inputOffsets = new ArrayList<Vector3F>();
		inputScales = new ArrayList<Vector3F>();
		this.material = material;
	}

	public void addRenderable(Renderable renderable, Vector3F offset, Vector3F scale) {
		inputRenderables.add(renderable);
		inputOffsets.add(offset);
		inputScales.add(scale);
		Mesh mesh = renderable.getMesh();
		countVertices += mesh.getVertexData().length / renderable.getMaterial().getByteStride();
		countIndices += mesh.getDrawOrder().length;
	}

	public void addRenderable(Renderable renderable) {
		addRenderable(renderable, renderable.getRelativePos(), new Vector3F(1,1,1));
	}

	/**
	 * Create the renderable
	 * @return
	 */

	public Renderable create() {
		float[] vertexData = new float[countVertices * material.getByteStride()];
		short[] drawOrder = new short[countIndices];

		short vertexAdd = 0;
		short drawOrderAdd = 0;

		for (int i = 0; i < inputRenderables.size(); ++i) {
			Renderable inputRenderable = inputRenderables.get(i);
			Mesh inputMesh = inputRenderable.getMesh();
			Material inputMat = inputRenderable.getMaterial();

			Vector3F pos = inputOffsets.get(i);
			Vector3F scale = inputScales.get(i);

			float[] vertexDataMesh = inputMesh.getVertexData();
			short[] drawOrderMesh = inputMesh.getDrawOrder();

			short vertexStart = vertexAdd;

			for (int j = 0; j < vertexDataMesh.length; j += inputMat.getByteStride()) {
				for (int option : VertexLayout.LAYOUT_OPTIONS) {
					if (inputMat.getVertexLayout().hasVertexAttribute(option) && material.getVertexLayout().hasVertexAttribute(option)) {
						int infoPos = inputMat.getVertexLayout().getPos(option);
						int infoSize = inputMat.getVertexLayout().getSize(option);
						for (int k = 0; k < infoSize; ++k) {
							vertexData[vertexAdd + material.getVertexLayout().getPos(option) + k] = vertexDataMesh[j + infoPos + k];
						}
					}
				}

				int posOffset = material.getPositionOffset();
				vertexData[vertexAdd + posOffset + 0] = scale.x * vertexData[vertexAdd + posOffset + 0] + pos.x;
				vertexData[vertexAdd + posOffset + 1] = scale.y * vertexData[vertexAdd + posOffset + 1] + pos.y;
				vertexData[vertexAdd + posOffset + 2] = scale.z * vertexData[vertexAdd + posOffset + 2] + pos.z;

				vertexData[vertexAdd + material.getVertexLayout().getPos(VertexLayout.TEXTURE_WEIGHT) + 0] = 1;

				vertexAdd += material.getByteStride();
			}

			for (int j = 0; j < drawOrderMesh.length; ++j) {
				drawOrder[drawOrderAdd++] = (short) (drawOrderMesh[j] + vertexStart / material.getByteStride());
			}
		}

		Mesh mesh = new Mesh(vertexData, drawOrder, countVertices);
		Renderable renderable = new Renderable(mesh, material);

		return renderable;
	}

}


text:
namespace RiemannSphere {

	class DrawSymbols {

	public:

		DrawSymbols(Easy3D::Camera *camera,
					Easy3D::Render *render,
					const Easy3D::Utility::Path& infinity,
					const Easy3D::Utility::Path& zero,
					const Easy3D::Utility::Path& point);

		void drawInfinity(const Easy3D::Vec3& pos,
							const Easy3D::Vec2& scale,
							float cstart=0.0f,float cend=1.0f,
							Easy3D::Color color=Easy3D::Color());

		void drawZero(const Easy3D::Vec3& pos,
						const Easy3D::Vec2& scale,
						float cstart=0.0f,float cend=1.0f,
                      Easy3D::Color color=Easy3D::Color());

		void drawPoint(const Easy3D::Vec3& pos,
                       const Easy3D::Vec2& scale,
                       float cstart=0.0f,float cend=1.0f,
                       Easy3D::Color color=Easy3D::Color());

	protected:

		Easy3D::Texture infinity,zero,point;
		Easy3D::Camera *camera;
		Easy3D::Render *render;

		float getColorIntensity(const Easy3D::Vec3& dir,
								float cstart,float cend);

		void drawSymbolIn3DScene(const Easy3D::Vec3& pos,
									const Easy3D::Vec2& scale,
									const Easy3D::Color& color=Easy3D::Color());
	};

};

#endif


text:
package sys

import "github.com/e-XpertSolutions/f5-rest-client/f5"

// CryptoClientConfigList holds a list of CryptoClient configuration.
type CryptoClientConfigList struct {
	Items    []CryptoClientConfig `json:"items"`
	Kind     string               `json:"kind"`
	SelfLink string               `json:"selflink"`
}

// CryptoClientConfig holds the configuration of a single CryptoClient.
type CryptoClientConfig struct {
}

// CryptoClientEndpoint represents the REST resource for managing CryptoClient.
const CryptoClientEndpoint = "/crypto/client"

// CryptoClientResource provides an API to manage CryptoClient configurations.
type CryptoClientResource struct {
	c *f5.Client
}

// ListAll  lists all the CryptoClient configurations.
func (r *CryptoClientResource) ListAll() (*CryptoClientConfigList, error) {
	var list CryptoClientConfigList
	if err := r.c.ReadQuery(BasePath+CryptoClientEndpoint, &list); err != nil {
		return nil, err
	}
	return &list, nil
}

// Get a single CryptoClient configuration identified by id.
func (r *CryptoClientResource) Get(id string) (*CryptoClientConfig, error) {
	var item CryptoClientConfig
	if err := r.c.ReadQuery(BasePath+CryptoClientEndpoint, &item); err != nil {
		return nil, err
	}
	return &item, nil
}

// Create a new CryptoClient configuration.
func (r *CryptoClientResource) Create(item CryptoClientConfig) error {
	if err := r.c.ModQuery("POST", BasePath+CryptoClientEndpoint, item); err != nil {
		return err
	}
	return nil
}

// Edit a CryptoClient configuration identified by id.
func (r *CryptoClientResource) Edit(id string, item CryptoClientConfig) error {
	if err := r.c.ModQuery("PUT", BasePath+CryptoClientEndpoint+"/"+id, item); err != nil {
		return err
	}
	return nil
}

// Delete a single CryptoClient configuration identified by id.
func (r *CryptoClientResource) Delete(id string) error {
	if err := r.c.ModQuery("DELETE", BasePath+CryptoClientEndpoint+"/"+id, nil); err != nil {
		return err
	}
	return nil
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;

namespace Microsoft.Azure.Commands.RecoveryServices.Test.ScenarioTests
{
    public class RecoveryServicesTests : RecoveryServicesTestsBase
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void EnumerationTests()
        {
            this.RunPowerShellTest("Test-RecoveryServicesEnumerationTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void E2E_DeleteAndDissociateTest()
        {
            this.RunPowerShellTest("Test-E2E_DeleteAndDissociate -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        public void E2E_CreateAndAssociateTest()
        {
            this.RunPowerShellTest("Test-E2E_CreateAndAssociate -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void StorageMappingTest()
        {
            this.RunPowerShellTest("Test-StorageMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void StorageUnMappingTest()
        {
            this.RunPowerShellTest("Test-StorageUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        public void NetworkMappingTest()
        {
            this.RunPowerShellTest("Test-NetworkMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        public void NetworkUnMappingTest()
        {
            this.RunPowerShellTest("Test-NetworkUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void ProtectionTests()
        {
            this.RunPowerShellTest("Test-RecoveryServicesProtectionTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void AzureNetworkMappingTest()
        {
            this.RunPowerShellTest("Test-AzureNetworkMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void AzureNetworkUnMappingTest()
        {
            this.RunPowerShellTest("Test-AzureNetworkUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void FailbackTest()
        {
            this.RunPowerShellTest("Test-Failback -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void RRAfterFailoverTest()
        {
            this.RunPowerShellTest("Test-RRAfterFailover -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void RRAfterFailbackTest()
        {
            this.RunPowerShellTest("Test-RRAfterFailback -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void CommitPFOTest()
        {
            this.RunPowerShellTest("Test-CommitPFO -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void CommitAfterFailbackTest()
        {
            this.RunPowerShellTest("Test-CommitAfterFailback -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void PFOTest()
        {
            this.RunPowerShellTest("Test-PFO -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void UFOTest()
        {
            this.RunPowerShellTest("Test-UFO -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void TFOTest()
        {
            this.RunPowerShellTest("Test-TFO -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void EnableProtectionTest()
        {
            this.RunPowerShellTest("Test-EnableProtection -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void DisableProtectionTest()
        {
            this.RunPowerShellTest("Test-DisableProtection -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void PFORPTest()
        {
            this.RunPowerShellTest("Test-PFORP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void TFORPTest()
        {
            this.RunPowerShellTest("Test-TFORP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void UFORPTest()
        {
            this.RunPowerShellTest("Test-UFORP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void FailbackRPTest()
        {
            this.RunPowerShellTest("Test-FailbackRP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void RRRPTest()
        {
            this.RunPowerShellTest("Test-RRRP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        public void CommitRPTest()
        {
            this.RunPowerShellTest("Test-CommitRP -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
        }

        [Fact]
        public void VaultUpgradeTest()
        {
            this.RunPowerShellTest(
                "Test-VaultUpgrade" +
                " -ResourceType \"" + resourceType + "\"" +
                " -VaultName \"" + vaultName + "\"" +
                " -Location \"" + location + "\"" +
                " -TargetResourceGroupName \"" + targetRgName + "\"");
        }
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name battleshipApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the battleshipApp
 */
angular.module('battleshipApp')
  .controller('BoardCtrl', function ($scope) {
    $scope.board = {
        o : 'o	',
        hit : 'x	'
    };
  });


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>Director HTML5 Tests</title>
    <link rel="stylesheet" href="/files/node_modules/qunitjs/qunit/qunit.css">

Note: in order to execute HTML5 mode test this file needs to be served with provided nodejs backend. Start the server from director/test/browser/backend and go to http://localhost:8080/ to launch the tests.


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find, findAll, fillIn, typeIn } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import a11yAudit from 'ember-a11y-testing/test-support/audit';

module('Integration | Component | Bootstrap Inputs | Url', function(hooks) {
  setupRenderingTest(hooks);

  test('it has no a11y errors', async function(assert) {
    assert.expect(1);
    await render(hbs`{{bootstrap-inputs/-url label='label' value='http://wild.land'}}`);
    return a11yAudit(this.$()).then(() => {
      assert.ok(true, 'no a11y errors found!');
    });
  });

  test('it renders a label and input', async function(assert) {
    assert.expect(2);
    await render(hbs`{{bootstrap-inputs/-url label='label' value='http://wild.land'}}`);
    assert.equal(findAll('input[type="url"]:enabled').length, 1);
    assert.equal(findAll('label').length, 1);
  });

  test('it uses value', async function(assert) {
    assert.expect(1);
    this.set('value', 'http://wild.land');
    await render(hbs`{{bootstrap-inputs/-url label='label' value=value}}`);
    assert.equal(find('input[type="url"]').value, this.get('value'));
  });

  test('it uses label', async function(assert) {
    assert.expect(1);
    this.set('label', 'Some label');
    await render(hbs`{{bootstrap-inputs/-url label=label value='http://wild.land'}}`);
    assert.equal(find('label').textContent.trim(), this.get('label'));
  });

  test('it supports onChange', async function(assert) {
    assert.expect(2);
    this.set('onChange', () => {
      assert.ok(true);
    });
    await render(hbs`{{bootstrap-inputs/-url onChange=onChange label='label' value='http://wild.land'}}`);
    await fillIn('input', 'http://wild.land/tests');
    await typeIn('input', 'http://wild.land/ember');
  });

  test('it supports disabled', async function(assert) {
    assert.expect(1);
    await render(hbs`{{bootstrap-inputs/-url label='label' value='http://wild.land' disabled=true}}`);
    assert.equal(findAll('input[type="url"]:disabled').length, 1);
  });

  test('it supports formDisabled', async function(assert) {
    assert.expect(1);
    await render(hbs`{{bootstrap-inputs/-url label='label' value='http://wild.land' formDisabled=true}}`);
    assert.equal(findAll('input[type="url"]:disabled').length, 1);
  });
});


text:
import "./styles"

import React from "react"
import HomeHead from "./HomeHead"
import HomeBody from "./HomeBody"

const Home = (props) => (
  <div className="ad-Home">
    <HomeHead />
    <HomeBody { ...props } />
  </div>
)

export default Home


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Music.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Message;

/**
 * Class Music.
 *
 * @property string $url
 * @property string $hq_url
 * @property string $title
 * @property string $description
 * @property string $thumb_media_id
 * @property string $format
 */
class Music extends AbstractMessage
{
    /**
     * Message type.
     *
     * @var string
     */
    protected $type = 'music';

    /**
     * Properties.
     *
     * @var array
     */
    protected $properties = [
        'title',
        'description',
        'url',
        'hq_url',
        'thumb_media_id',
        'format',
    ];

    /**
     * 设置音乐封面.
     *
     * @param string $mediaId
     *
     * @return $this
     */
    public function thumb($mediaId)
    {
        $this->setAttribute('thumb_media_id', $mediaId);

        return $this;
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" >
    <shape>
      <solid
          android:color="#BC1212" />
      </shape>
  </item>
  <item>
    <shape>
      <gradient
          android:startColor="#D83131"
          android:endColor="#BF3535"
          android:angle="270" />
    </shape>
  </item>
</selector>


text:
<?php

/**
 * Form model for displaying a list of authorization items.
 */
class AddAuthItemForm extends CFormModel
{
	/**
	 * @var array a list of authorization items.
	 */
	public $items;

	/**
	 * Returns the attribute labels.
	 * @return array attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'items' => Yii::t('AuthModule.main', 'Items'),
		);
	}

	/**
	 * Returns the validation rules for attributes.
	 * @return array validation rules.
	 */
	public function rules()
	{
		return array(
			array('items', 'required'),
		);
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>
  File: README

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

    Index »
    File: README

(no frames)

      Class List

      Method List

      File List

PVImpact Green Button Gem Demo

Overview

The Green Button Standard is a secure way of transmitting energy usage
information developed by the United States Department of Energy.

This gem provides functionality to download Green Button XML formatted data
from remote APIs, process the data and persist the data in database; it
also provides functionality to retrieve Green Button data persisted in
database.

This is the demo app for the pvimpact-greenbutton gem.

Setup Prerequisites

PostgreSQL 9.4

Ruby 2.1.5

RubyGems 2.x

Ruby on Rails 3.2

Yard - for generating documentation

yard-tomdoc - for
generating documentation

Bundler - for building

RSpec - for testing

PostgreSQL

PostgreSQL database server can be downloaded from here.

Alternatively,

on Linux, you may run apt-get install postgresql-9.4 to
install

If you encounter error afterwards when executing bundle
install for do_postgres gem,  please install the dev
version instead apt-get install postgresql-9.3
postgresql-server-dev-9.3 libpq-dev,  for more information refer to
github.com/datamapper/do/issues/66

on OS X, you may install it using homebrew
brew install postgresql

Ruby

Ruby can be downloaded from here.

Alternatively, you can use rvm to manage
different Ruby versions: rvm install 2.1.5

Alternatively,

on Linux, you may run apt-get install ruby-full

on OS X, ruby 2.0 is pre-installed, but you may install 2.1.5 using homebrew brew install ruby

RubyGems

RubyGems can be downloaded from here.

Ruby on Rails

Ruby on Rails can be downloaded from here.

Alternatively, you may run gem install rails to install.

Yard and yard-tomdoc

Yard can be downloaded from here

Alternatively, you may run gem install yard to install Yard,
and run gem install yard-tomdoc to install yard-tomdoc.

Bundler

Bundler can be downloaded from here.

Alternatively, you may run gem install bundler to install.

RSpec

RSpec can be downloaded from here.

Alternatively, you may run gem install rspec to install.

Installation Instructions

Gem

Open terminal/command line, go to directory
/pvimpact-greenbutton

Run command bundle install to build the gem

Demo Application

Make sure you have all prerequisites installed on your system.

Make sure you have started PostgreSQL database (e.g. postgres -D
/usr/local/pgsql/data)

Create PostgreSQL database pvimpact_greenbutton_demo

Open terminal/command line, run psql

Run create database pvimpact_greenbutton_demo; in the
psql terminal

(Optional) Adjust the database connection information in
/config/application.rb

Open terminal/command line, go to directory
/pvimpact-greenbutton-demo.

Run command bundle install to install dependencies and build
the application.

Run command rails server to start the application

Now the application should be running at
http://0.0.0.0:3000/demo/index, and you should see messages
like the following in console:

[2015-03-28 01:51:51] INFO  WEBrick 1.3.1
[2015-03-28 01:51:51] INFO  ruby 2.1.2 (2014-05-08) [x86_64-darwin14.0]
[2015-03-28 01:51:51] INFO  WEBrick::HTTPServer#start: pid=66750 port=3000

Usage Examples

You may now open browser to visit
http://0.0.0.0:3000/demo/index, and test the gem functionality
using the UI. The pre-filled Resource URI and Access Token should be
working.

  Generated on Tue Apr  7 22:31:41 2015 by
  yard
  0.8.7.6 (ruby-2.1.5).


text:
directory "/home/oracle/oracle" do
  owner "oracle"
  group "dba"
  recursive true
end

execute "unzip1" do
  command "unzip /tmp/oracle/\\*.zip"
  user "oracle"
  cwd "/home/oracle/oracle"
end

template "/etc/oraInst.loc" do
  mode "0644"
  owner "root"
  group "root"
  source "oraInst.loc.erb"
end

template "/home/oracle/db.rsp" do
  owner "oracle"
  group "dba"
  source "db.rsp.erb"
end

directory "/u01/app/" do
  owner "oracle"
  group "dba"
  recursive true
end

directory "/u01/app/oracle" do
  owner "oracle"
  group "dba"
  recursive true
end

#need to wrap this to get it to run in a login shell like environment
execute "install" do
  command "su -l -c 'cd /home/oracle/oracle/database && ./runInstaller -ignoreSysPrereqs -silent -noconfig -responseFile /home/oracle/db.rsp -waitforcompletion' oracle"
  user "root"
  returns [0, 6]
end

execute "root.sh" do
  command "/u01/app/oracle/product/11.2.0/dbhome_1/root.sh"
  user "root"
end

directory "/home/oracle/oracle" do
  action :delete
  recursive true
end

directory "/tmp/oracle" do
  action :delete
  recursive true
end


text:
package com.pokevian.app.smartfleet.service;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pokevian.app.smartfleet.model.VehicleData.VehicleTrip;
import com.pokevian.app.smartfleet.volley.GsonRequest.GsonDateTypeAdapter;

import java.sql.Date;

@SuppressWarnings("unused")
public class TripStore {

    private final String PREFS_NAME = "trip-store";
    private final String PREF_TRIP = "trip";

    private final SharedPreferences mPrefs;
    private final Gson mGson;

    private static TripStore mInstance;

    private TripStore(Context context) {
        mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        mGson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new GsonDateTypeAdapter())
                .create();
    }

    public static TripStore getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new TripStore(context);
        }
        return mInstance;
    }

    public void storeTrip(VehicleTrip trip) {
        SharedPreferences.Editor editor = mPrefs.edit();
        String value = mGson.toJson(trip);
        editor.putString(PREF_TRIP, value);
        editor.apply();
    }

    public VehicleTrip getTrip() {
        String value = mPrefs.getString(PREF_TRIP, null);
        if (!TextUtils.isEmpty(value)) {
            return mGson.fromJson(value, VehicleTrip.class);
        } else {
            return null;
        }
    }

    public boolean hasTrip() {
        return mPrefs.contains(PREF_TRIP);
    }

    public void clear() {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.clear();
        editor.apply();
    }

}


text:
package org.jboss.arquillian.test.impl;

import java.lang.reflect.Method;
import java.util.List;

import org.jboss.arquillian.core.spi.Manager;
import org.jboss.arquillian.test.spi.LifecycleMethodExecutor;
import org.jboss.arquillian.test.spi.TestMethodExecutor;
import org.jboss.arquillian.test.spi.context.ClassContext;
import org.jboss.arquillian.test.spi.context.SuiteContext;
import org.jboss.arquillian.test.spi.context.TestContext;
import org.jboss.arquillian.test.spi.event.suite.After;
import org.jboss.arquillian.test.spi.event.suite.AfterClass;
import org.jboss.arquillian.test.spi.event.suite.AfterSuite;
import org.jboss.arquillian.test.spi.event.suite.Before;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeSuite;
import org.jboss.arquillian.test.test.AbstractTestTestBase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Verifies that the {@link EventTestRunnerAdaptor} creates and fires the proper events.
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@RunWith(MockitoJUnitRunner.class)
public class EventTestRunnerAdaptorTestCase extends AbstractTestTestBase
{

   @Override
   protected void addExtensions(List<Class<?>> extensions)
   {
      extensions.add(TestContextHandler.class);
   }

   @Override
   protected void startContexts(Manager manager)
   {
      // this is a test of the Context activation, don't auto start
   }

   @Test
   public void shouldHandleLifeCycleEvents() throws Exception
   {
      Manager manager = getManager();
      EventTestRunnerAdaptor adaptor = new EventTestRunnerAdaptor(manager);

      Class<?> testClass = getClass();
      Method testMethod = testClass.getMethod("shouldHandleLifeCycleEvents");
      Object testInstance = this;

      TestMethodExecutor testExecutor = Mockito.mock(TestMethodExecutor.class);
      Mockito.when(testExecutor.getInstance()).thenReturn(testInstance);
      Mockito.when(testExecutor.getMethod()).thenReturn(testMethod);

      verifyNoActiveContext(manager);

      adaptor.beforeSuite();
      assertEventFired(BeforeSuite.class, 1);
      assertEventFiredInContext(BeforeSuite.class, SuiteContext.class);

      verifyNoActiveContext(manager);

      adaptor.beforeClass(testClass, LifecycleMethodExecutor.NO_OP);
      assertEventFired(BeforeClass.class, 1);
      assertEventFiredInContext(BeforeClass.class, SuiteContext.class);
      assertEventFiredInContext(BeforeClass.class, ClassContext.class);

      verifyNoActiveContext(manager);

      adaptor.before(testInstance, testMethod, LifecycleMethodExecutor.NO_OP);
      assertEventFired(Before.class, 1);
      assertEventFiredInContext(Before.class, SuiteContext.class);
      assertEventFiredInContext(Before.class, ClassContext.class);
      assertEventFiredInContext(Before.class, TestContext.class);

      verifyNoActiveContext(manager);

      adaptor.test(testExecutor);
      assertEventFired(org.jboss.arquillian.test.spi.event.suite.Test.class, 1);
      assertEventFiredInContext(org.jboss.arquillian.test.spi.event.suite.Test.class, SuiteContext.class);
      assertEventFiredInContext(org.jboss.arquillian.test.spi.event.suite.Test.class, ClassContext.class);
      assertEventFiredInContext(org.jboss.arquillian.test.spi.event.suite.Test.class, TestContext.class);

      verifyNoActiveContext(manager);

      adaptor.after(testInstance, testMethod, LifecycleMethodExecutor.NO_OP);
      assertEventFired(After.class, 1);
      assertEventFiredInContext(After.class, SuiteContext.class);
      assertEventFiredInContext(After.class, ClassContext.class);
      assertEventFiredInContext(After.class, TestContext.class);

      verifyNoActiveContext(manager);

      adaptor.afterClass(testClass, LifecycleMethodExecutor.NO_OP);
      assertEventFired(AfterClass.class, 1);
      assertEventFiredInContext(AfterClass.class, SuiteContext.class);
      assertEventFiredInContext(AfterClass.class, ClassContext.class);

      verifyNoActiveContext(manager);

      adaptor.afterSuite();
      assertEventFired(AfterSuite.class, 1);
      assertEventFiredInContext(AfterSuite.class, SuiteContext.class);

      verifyNoActiveContext(manager);
   }

   private void verifyNoActiveContext(Manager manager)
   {
      verify(false, false, false, manager);
   }

   private void verify(boolean suite, boolean clazz, boolean test, Manager manager)
   {
      Assert.assertEquals(
            "SuiteContext should" + (!suite ? " not":"") + " be active",
            suite, manager.getContext(SuiteContext.class).isActive());
      Assert.assertEquals(
            "ClassContext should" + (!clazz ? " not":"") + " be active",
            clazz, manager.getContext(ClassContext.class).isActive());
      Assert.assertEquals(
            "TestContext should" + (!test ? " not":"") + " be active",
            test, manager.getContext(TestContext.class).isActive());
   }
}


text:
'use strict';
var server = require('./app.js');
var log = require('./lib/logger');
var port = process.env.PORT || 3000;

server.listen(port, function () {
    log.info('Slang listening on port ' + port);
});


text:
from si import *
import logging

def plot_timeseries_with_pyplot(ts):
	try:
		import matplotlib.pyplot as plt
	except ImportError:
		logging.error("pyplot could not be imported")
		return

	serieses = set([x[1].pre_str() + unit_find(x[1].unit)
					for x in ts.datapoints])
	serieses = {s:([],[]) for s in serieses}

	for d in ts.datapoints:
		u = d[1].pre_str() + unit_find(d[1].unit)
		serieses[u][0].append(d[0])
		serieses[u][1].append(d[1].value)

	for s in serieses:
		plt.plot(*serieses[s])

	plt.legend(serieses.keys())
	plt.show()
	return


text:
- npm
- gulp

## Install dependencies

		$ npm install

## Run local server

		$ gulp serve


text:
using namespace std;
using namespace OIC::Service;

HueLight::HueLight()
{
    m_connector = nullptr;
}

HueLight::HueLight(HueConnector *connector, std::string address)
{
    m_address = address;
    m_connector = connector;
    initAttributes();
}

HueLight::~HueLight()
{
    m_connector = nullptr;
}

void HueLight::initAttributes()
{
    BundleResource::setAttribute("on-off", false, false);
    BundleResource::setAttribute("dim", 0, false);
    BundleResource::setAttribute("color", 0, false);
}

RCSResourceAttributes HueLight::handleGetAttributesRequest()
{
    cout << "HueLight::handleGetAttributesRequest" << endl;
    // TODO read from HueLight and update attribute data
    return BundleResource::getAttributes();
}

void HueLight::handleSetAttributesRequest(const RCSResourceAttributes &value)
{
    cout << "HueLight::handleSetAttributesRequest" << std::endl;

    // TODO construct single write

    for (RCSResourceAttributes::const_iterator it = value.begin(); it != value.end(); it++)
    {
        std::string attributeName = it->key();
        RCSResourceAttributes::Value attrValue = it->value();

        if (attributeName == "on-off")
        {
            //m_connector->transmit(this->m_address + "/state", "{\"on\":" + attrValue.toString() + "}");
        }

        if (attributeName == "dim")
        {
            // needs conversion * 2.5
            //m_connector->transmit(this->m_address + "/state", "{\"bri\":" + attrValue.toString() + "}");
        }

        if (attributeName == "color")
        {
            // needs conversion *650
            //m_connector->transmit(this->m_address + "/state", "{\"hue\":" + attrValue.toString() + "}");
        }
    }

    BundleResource::setAttributes(value);
}


text:
import * as _ from "lodash";

export function convertToBytes(sprite: Uint8Array): number[] {
    let parts = _.chunk(sprite, 8);
    return convertToInt(parts);
}

export function convertToInt(parts: number[][]): number[] {
    return parts.map((x) => {
        let val = 0;
        for (let i = 0; i < 8; i++) {
            val += x[7-i] == 0 ? 0 : Math.pow(2, i);
        }
        return val;
    });
}

export function toHexString(value: number): string {
    return '$' + _.padStart(value.toString(16), 2, '0');
}


text:
A tiny [Think](http://freeverse.com/mac/product/?id=7013) clone that actually
works with a dual (or single) screen setup.

## Install

1. Download [here](http://github.com/downloads/felixge/focus-app/Focus.app.zip)
2. Install by unzipping an moving the contained file to `/Applications`

## What does it do?

It basically does the same thing the original Think app does. By default it
hides all windows, except a single one that you are focusing on. It provides
the same shortcuts as Think to re-focus on the current window or designate a
new window to be the focused one.

## How to use it?

1. Start Focus.app, it will cover all you screens with a black backdrop
2. Bring up an app using `Alt + Tab` or selecting it from your dock
3. Focus on the currently active app using `Option + Command + Tab`
4. Go back to the black backdrop using `Option + Command + Return`
5. Re-focus on the app you last focused on using `Control + Command + Return`

Clicking on the backdrop performs the same re-focusing as
`Control + Command + Return`.

## Dependencies

- Some code was taken from [Shortcut Recorder](http://wafflesoftware.net/shortcut/)
(BSD License) to enable the global shortcuts

## License

The Focus.app is licensed under the MIT license. The dependencies
have their own licenses.


text:
require 'snail/configurable'
require 'snail/constants'
require 'snail_helpers'

require 'cgi'
require 'fileutils'
require 'logger'
require 'active_support/core_ext/string/output_safety'

if defined? ActionView
  ActionView::Base.class_eval { include SnailHelpers }
end

class Snail
  include Configurable

  # this will be raised whenever formatting or validation is run on an unsupported or unknown country
  class UnknownCountryError < ArgumentError; end

  # My made-up standard fields.
  attr_accessor :name
  attr_accessor :line_1
  attr_accessor :line_2
  attr_accessor :city
  attr_accessor :region
  attr_accessor :postal_code
  attr_accessor :country

  # Aliases for easier assignment compatibility
  {
    :full_name  => :name,
    :street     => :line_1,
    :town       => :city,
    :state      => :region,
    :province   => :region,
    :zip        => :postal_code,
    :zip_code   => :postal_code,
    :postcode   => :postal_code
  }.each do |new, existing|
    alias_method "#{new}=", "#{existing}="
  end

  def self.home_country
    @home_country ||= "USA"
  end

  def self.home_country=(val)
    @home_country = val
  end

  def to_s
    [name, line_1, line_2, city_line, country_line].select{|line| !(line.nil? or line.empty?)}.join("\n")
  end

  def to_html
    "<address>#{CGI.escapeHTML(to_s).gsub("\n", '<br />')}</address>".html_safe
  end

  # this method will get much larger. completeness is out of my scope at this time.
  # currently it's based on the sampling of city line formats from frank's compulsive guide.
  def city_line
    case country
    when 'China', 'India'
      "#{city}, #{region}  #{postal_code}"
    when 'Brazil'
      "#{postal_code} #{city}-#{region}"
    when 'Mexico', 'Slovakia'
      "#{postal_code} #{city}, #{region}"
    when 'Italy'
      "#{postal_code} #{city} (#{region})"
    when 'Belarus'
      "#{postal_code} #{city}-(#{region})"
    when 'USA', 'Canada', 'Australia', nil, ""
      "#{city} #{region}  #{postal_code}"
    when 'Israel', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Italy', 'Norway', 'Spain', 'Sweden', 'Turkey', 'Cyprus', 'Portugal', 'Macedonia', 'Bosnia and Herzegovina'
      "#{postal_code} #{city}"
    when 'Kuwait', 'Syria', 'Oman', 'Estonia','Luxembourg', 'Belgium', 'Iceland', 'Switzerland', 'Austria', 'Moldova', 'Montenegro', 'Serbia', 'Bulgaria', 'Georgia', 'Poland', 'Armenia', 'Croatia', 'Romania', 'Azerbaijan'
      "#{postal_code} #{city}"
    when 'Netherlands'
      "#{postal_code}  #{city}"
    when 'Ireland'
      "#{city}, #{region}"
    when 'England', 'Scotland', 'Wales', 'United Kingdom', 'Russia', 'Russian Federation', 'Ukraine', 'Jordan', 'Lebanon','Iran, Islamic Republic of', 'Iran', 'Saudi Arabia', 'New Zealand'
      "#{city}  #{postal_code}" # Locally these may be on separate lines. The USPS prefers the city line above the country line, though.
    when 'Ecuador'
      "#{postal_code} #{city}"
    when 'Hong Kong', 'Syria', 'Iraq', 'Yemen', 'Qatar', 'Albania'
      "#{city}"
    when 'United Arab Emirates'
      "#{postal_code}\n#{city}"
    when 'Japan'
      "#{city}, #{region}\n#{postal_code}"
    when 'Egypt', 'South Africa','Isle of Man', 'Kazakhstan', 'Hungary'
      "#{city}\n#{postal_code}"
    when 'Latvia'
      "#{city}, LV-#{postal_code}"
    when 'Lithuania'
      "LT-#{postal_code} #{city}"
    when 'Slovenia'
      "SI-#{postal_code} #{city}"
    when 'Czech Republic'
      "#{postal_code} #{region}\n#{city}"
    else
      logger.error "[Snail] Unknown Country: #{country}"
      "#{city} #{region}  #{postal_code}"
    end
  end

  def country_line
    self.class.home_country.to_s.upcase == country.to_s.upcase ? nil : country.to_s.upcase
  end

private

  def logger
    if @logger
      return @logger
    end

    # Rails.logger can be nil, even with Rails being defined
    if Kernel.const_get(:Rails) && Rails.respond_to?(:logger) && Rails.logger
      @logger = Rails.logger
    else
      # FileUtils.mkdir_p('log') # For Ruby 1.8.7
      @logger = Logger.new('log/snail.log')
    end
  end
end


text:
package org.datagr4m.drawing.layout.algorithms.forceAtlas;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.datagr4m.drawing.layout.IRunnableLayout;
import org.datagr4m.drawing.layout.algorithms.forceAtlas.forces.FAAttraction;
import org.datagr4m.drawing.layout.algorithms.forceAtlas.forces.FARepulsion;
import org.datagr4m.drawing.layout.algorithms.forceAtlas.forces.standalone.StandaloneForce;
import org.datagr4m.drawing.layout.algorithms.forceAtlas.monitoring.MeanMoveAnalysis;
import org.datagr4m.drawing.layout.algorithms.forces.IForce;
import org.datagr4m.drawing.layout.algorithms.forces.ItemForceVector;
import org.datagr4m.drawing.model.items.IBoundedItem;
import org.datagr4m.drawing.model.items.hierarchical.graph.IHierarchicalGraphModel;
import org.jzy3d.maths.Coord2d;

public class ForceAtlasLayout implements IRunnableLayout {
    public static double INERTIA_DEFAULT = 0.1d; // 0.1d;
    public static double REPULSION_DEFAULT = 200d;
    public static double ATTRACTION_DEFAULT = 10d;
    public static double MAX_DISPLACEMENT_DEFAULT = 10d;
    public static double FREEZE_STRENGTH_DEFAULT = 80d;
    public static double FREEZE_INERTIA_DEFAULT = 0.2d;
    public static boolean FREEZE_BALANCE_DEFAULT = true;
    public static double GRAVITY_DEFAULT = 30d;//30d;
    public static double SPEED_DEFAULT = 1d;
    public static double COOLING_DEFAULT = 1d;

    public static boolean OUTBOUND_ATTRACTION_DEFAULT = false;
    public static boolean ADJUST_SIZE_DEFAULT = true;
    public static boolean MAINTAIN_TO_CENTER_DEFAULT = true;

    private static final long serialVersionUID = 1526844201583879045L;
    protected IHierarchicalGraphModel model;
    protected Map<IBoundedItem, ItemForceVector> itemForces = new HashMap<IBoundedItem, ItemForceVector>();

    //Properties
    public double inertia;
    private double repulsionStrength;
    private double attractionStrength;
    private double maxDisplacement;
    private boolean freezeBalance;
    private double freezeStrength;
    private double freezeInertia;
    private double gravity;
    private double speed;
    private double cooling;
    private boolean outboundAttractionDistribution;
    private boolean adjustSizes;
    protected boolean maintainToCenter = true;

    protected IInitializer initializer = new RandomInitializer();

    protected boolean enableMeanMoveLogging = false;
    protected MeanMoveAnalysis meanMoveAnalysis = new MeanMoveAnalysis();

    protected int counter = 0;

    public ForceAtlasLayout(IHierarchicalGraphModel model) {
        this.model = model;
        resetPropertiesValues();
    }

    @Override
    public void resetPropertiesValues() {
        setInertia(INERTIA_DEFAULT);//0.1;
        setRepulsionStrength(REPULSION_DEFAULT);
        setAttractionStrength(ATTRACTION_DEFAULT);
        setMaxDisplacement(MAX_DISPLACEMENT_DEFAULT);
        setFreezeBalance(FREEZE_BALANCE_DEFAULT);
        setFreezeStrength(FREEZE_STRENGTH_DEFAULT);
        setFreezeInertia(FREEZE_INERTIA_DEFAULT);
        setGravity(GRAVITY_DEFAULT);//30d
        setOutboundAttractionDistribution(OUTBOUND_ATTRACTION_DEFAULT);
        setAdjustSizes(ADJUST_SIZE_DEFAULT);
        setSpeed(SPEED_DEFAULT);
        setCooling(COOLING_DEFAULT);
        setMaintainToCenter(MAINTAIN_TO_CENTER_DEFAULT);
    }

    @Override
    public void initAlgo() {
        if(initializer!=null){
            initializer.apply(model);
        }
    }

    @Override
    public void goAlgo() {
        Collection<IBoundedItem> items = model.getChildren();

        // init at each step
        initItemVectors(items);
        initForces(items);

        // compute additive forces
        applyRepulsion(items);
        applyAttraction(items);
        applyStandaloneForces();
        applyGravity(items);
        applySpeed(items);

        // apply forces
        applyForces(items);

        if(enableMeanMoveLogging){
            meanMoveAnalysis.makeAnalysis(this, items);
        }
        incCounter();

        // beautifier
        if(maintainToCenter)
            offsetToCenter(items);
    }

    public void incCounter() {
        counter++;
    }

    protected void initItemVectors(Collection<IBoundedItem> items){
        for(IBoundedItem item: items){
            ItemForceVector itemForce = new ItemForceVector();
            itemForce.old_dx = itemForce.dx;
            itemForce.old_dy = itemForce.dy;
            itemForce.dx *= inertia;
            itemForce.dy *= inertia;
            itemForces.put(item, itemForce);
        }
    }

    protected void initForces(Collection<IBoundedItem> items){
        // repulsion force
        for(IBoundedItem item: items){
            Collection<IForce> forces = model.getRepulsors(item);
            for(IForce force: forces){
                if(force instanceof FARepulsion){
                    FARepulsion far = (FARepulsion)force;
                    ItemForceVector v1 = itemForces.get(force.getOwner());
                    ItemForceVector v2 = itemForces.get(force.getSource());
                    int d1 = model.getNodeDegree(force.getOwner());
                    int d2 = model.getNodeDegree(force.getSource());
                    far.setAll(d1, v1, d2, v2);
                }
                else{
                    throw new RuntimeException("unexpected force object: " + force);
                }
            }
        }

        //attraction force
        Collection<IForce> forces = model.getAttractorForces();
        for(IForce force: forces){
            if(force instanceof FAAttraction){
                FAAttraction faa = (FAAttraction)force;
                ItemForceVector v1 = itemForces.get(faa.getOwner());
                ItemForceVector v2 = itemForces.get(faa.getSource());
                int d1 = model.getNodeDegree(faa.getOwner());
                int d2 = model.getNodeDegree(faa.getSource());

                if(v2==null)
                    throw new RuntimeException("trying to set a source force with a null value for " + faa.getSource().getLabel() + " in " + model.getLabel() + " with " + faa.getOwner().getLabel());
                if(v1==null)
                    throw new RuntimeException("trying to set an owner force with a null value for " + faa.getOwner().getLabel() + " in " + model.getLabel() + " with " + faa.getSource().getLabel());

                faa.setAll(d1, v1, d2, v2);
            }
            else{
                throw new RuntimeException("unexpected force object: " + force);
            }
        }

        // standalone force (no setting)
        Collection<StandaloneForce> dforces = model.getForces();
        for(StandaloneForce force: dforces){
            StandaloneForce sf = force;
            ItemForceVector v1 = itemForces.get(sf.getOwner());
            ItemForceVector v2 = itemForces.get(sf.getSource());
            int d1 = model.getNodeDegree(sf.getOwner());
            int d2 = model.getNodeDegree(sf.getSource());
            sf.setAll(d1, v1, d2, v2);
        }
    }

    /***********************/

    protected void applyRepulsion(Collection<IBoundedItem> items){
        for(IBoundedItem item: items){
            Collection<IForce> forces = model.getRepulsors(item);
            //Logger.getLogger(ForceAtlasLayout.class).info("forces:"+forces.size());
            for(IForce force: forces){
                if(force instanceof FARepulsion){
                    ((FARepulsion)force).apply(getRepulsionStrength(), isAdjustSizes());
                }
                else{
                    throw new RuntimeException("unexpected force object: " + force);
                }
            }
        }
    }

    protected void applyAttraction(Collection<IBoundedItem> items){
        for(IBoundedItem item: items){
            Collection<IForce> forces = model.getAttractors(item);
            for(IForce force: forces){
                if(force instanceof FAAttraction){
                    ((FAAttraction)force).apply(getAttractionStrength(), isAdjustSizes(), isOutboundAttractionDistribution());
                }
                else{
                    throw new RuntimeException("unexpected force object: " + force);
                }
            }
        }
    }

    protected void applyStandaloneForces(){
        for(IForce force: model.getForces()){
            if(force instanceof StandaloneForce){
                ((StandaloneForce)force).apply();
            }
            else{
                throw new RuntimeException("unexpected force object: " + force);
            }
        }
    }

    protected void applyGravity(Collection<IBoundedItem> items){
        for(IBoundedItem item: items){
            float nx = item.getPosition().x;
            float ny = item.getPosition().y;
            double d = 0.0001 + Math.sqrt(nx * nx + ny * ny);
            double gf = 0.0001 * getGravity() * d;
            ItemForceVector layoutData = itemForces.get(item);
            layoutData.dx -= gf * nx / d;
            layoutData.dy -= gf * ny / d;
        }
    }

    protected void applySpeed(Collection<IBoundedItem> items){
        if (isFreezeBalance()) {
            for(IBoundedItem item: items){
                ItemForceVector layoutData = itemForces.get(item);
                layoutData.dx *= getSpeed() * 10f;
                layoutData.dy *= getSpeed() * 10f;
            }
        } else {
            for(IBoundedItem item: items){
                ItemForceVector layoutData = itemForces.get(item);
                layoutData.dx *= getSpeed();
                layoutData.dy *= getSpeed();
            }
        }
    }

    protected void applyForces(Collection<IBoundedItem> items){
        for(IBoundedItem item: items) {
            if (!item.locked()) {
                ItemForceVector nLayout = itemForces.get(item);

                double d = 0.0001 + Math.sqrt(nLayout.dx * nLayout.dx + nLayout.dy * nLayout.dy);
                float ratio;
                if (isFreezeBalance()) {
                    nLayout.freeze = (float) (getFreezeInertia() * nLayout.freeze + (1 - getFreezeInertia()) * 0.1 * getFreezeStrength() * (Math.sqrt(Math.sqrt((nLayout.old_dx - nLayout.dx) * (nLayout.old_dx - nLayout.dx) + (nLayout.old_dy - nLayout.dy) * (nLayout.old_dy - nLayout.dy)))));
                    ratio = (float) Math.min((d / (d * (1f + nLayout.freeze))), getMaxDisplacement() / d);
                } else {
                    ratio = (float) Math.min(1, getMaxDisplacement() / d);
                }
                nLayout.dx *= ratio / getCooling();
                nLayout.dy *= ratio / getCooling();
                item.shiftPosition(nLayout.dx, nLayout.dy);

                //logForceMove(item, nLayout);
                //Logger.getLogger(ForceAtlasLayout.class).info(item.getPosition());
            }
            else
                ;//logForceMove(item);

        }
    }

    public int getCounter() {
        return counter;
    }

    /*  */

    @Override
    public void endAlgo() {
        for (IBoundedItem i : itemForces.keySet()) {
            itemForces.put(i, null);
        }
    }

    @Override
    public boolean canAlgo() {
        return true;
    }

    public void offsetToCenter(Collection<IBoundedItem> items){
        Coord2d bary = getBarycentre(items).mul(-1);

        for(IBoundedItem item: items)
            item.shiftPosition(bary);
    }

    public Coord2d getBarycentre(Collection<IBoundedItem> items){
        Coord2d mean = new Coord2d();
        for(IBoundedItem item: items)
            mean.addSelf(item.getPosition());
        mean.divSelf(items.size());
        return mean;
    }

    /***********/

    public void setInertia(Double inertia) {
        this.inertia = inertia;
    }

    public Double getInertia() {
        return inertia;
    }

    public Double getRepulsionStrength() {
        return repulsionStrength;
    }

    public void setRepulsionStrength(Double repulsionStrength) {
        this.repulsionStrength = repulsionStrength;
    }

    public Double getAttractionStrength() {
        return attractionStrength;
    }

    public void setAttractionStrength(Double attractionStrength) {
        this.attractionStrength = attractionStrength;
    }

    public Double getMaxDisplacement() {
        return maxDisplacement;
    }

    public void setMaxDisplacement(Double maxDisplacement) {
        this.maxDisplacement = maxDisplacement;
    }

    public Boolean isFreezeBalance() {
        return freezeBalance;
    }

    public void setFreezeBalance(Boolean freezeBalance) {
        this.freezeBalance = freezeBalance;
    }

    public Double getFreezeStrength() {
        return freezeStrength;
    }

    public void setFreezeStrength(Double freezeStrength) {
        this.freezeStrength = freezeStrength;
    }

    public Double getFreezeInertia() {
        return freezeInertia;
    }

    public void setFreezeInertia(Double freezeInertia) {
        this.freezeInertia = freezeInertia;
    }

    public Double getGravity() {
        return gravity;
    }

    public void setGravity(Double gravity) {
        this.gravity = gravity;
    }

    public Double getSpeed() {
        return speed;
    }

    public void setSpeed(Double speed) {
        this.speed = speed;
    }

    public Double getCooling() {
        return cooling;
    }

    public void setCooling(Double cooling) {
        this.cooling = cooling;
    }

    public Boolean isOutboundAttractionDistribution() {
        return outboundAttractionDistribution;
    }

    public void setOutboundAttractionDistribution(Boolean outboundAttractionDistribution) {
        this.outboundAttractionDistribution = outboundAttractionDistribution;
    }

    public Boolean isAdjustSizes() {
        return adjustSizes;
    }

    public void setAdjustSizes(Boolean adjustSizes) {
        this.adjustSizes = adjustSizes;
    }

    public boolean isMaintainToCenter() {
        return maintainToCenter;
    }

    public void setMaintainToCenter(boolean maintainToCenter) {
        this.maintainToCenter = maintainToCenter;
    }

    public IInitializer getInitializer() {
        return initializer;
    }

    public void setInitializer(IInitializer initializer) {
        this.initializer = initializer;
    }

    public boolean isEnableMeanMoveLogging() {
        return enableMeanMoveLogging;
    }

    public void setEnableMeanMoveLogging(boolean enableMeanMoveLogging) {
        this.enableMeanMoveLogging = enableMeanMoveLogging;
        //Logger.getLogger(this.getClass()).warn("logging for " + model.getLabel() + " : " + this.enableMeanMoveLogging);
    }

    public MeanMoveAnalysis getMeanMoveAnalysis() {
        return meanMoveAnalysis;
    }

    public IHierarchicalGraphModel getModel() {
        return model;
    }

    /********************/

    public float getMaxItemRadius(){
        float maxRadius = 0; // we don't want a multiplier less than 1
        for(IBoundedItem item: model.getChildren()){
            if(item.getRadialBounds()>maxRadius)
                maxRadius = item.getRadialBounds();
            //Logger.getLogger(ForceAtlasLayout.class).info("item radius:" + item.getRadius());
        }
        return maxRadius;
    }
}


text:
#ifndef FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_MULTI_AGENT_Q_SOURCE_PROVIDER_HPP
#define FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_MULTI_AGENT_Q_SOURCE_PROVIDER_HPP

class MultiAgentQSourceProvider {

};

#endif //FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_MULTI_AGENT_Q_SOURCE_PROVIDER_HPP


text:
package boofcv.alg.feature.detect.template;

import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageUInt8;
import org.junit.Test;

/**
 * @author Peter Abeles
 */
public class TestTemplateNCC {

	@Test
	public void instanceF32() {
		TemplateNCC.F32 alg = new TemplateNCC.F32();

		new GeneralTemplateMatchTests<ImageFloat32>(alg, ImageFloat32.class) {
		}.allTests();
	}

	@Test
	public void instanceU8() {
		TemplateNCC.U8 alg = new TemplateNCC.U8();

		new GeneralTemplateMatchTests<ImageUInt8>(alg, ImageUInt8.class) {
		}.allTests();
	}
}


text:
namespace libj {

class String : LIBJ_IMMUTABLE(String)
 public:
    enum Encoding {
        UTF8,
        UTF16,
        UTF16BE,
        UTF16LE,
        UTF32,
        UTF32BE,
        UTF32LE,
    };

    static CPtr create();

    static CPtr create(Char c, Size n = 1);

    static CPtr create(const std::u16string& s16);

    static CPtr create(const std::u32string& s32);

    static CPtr create(
        const void* data,
        Encoding enc = UTF8,
        Size len = NO_SIZE,
        Size max = NO_SIZE);

    static CPtr intern(CPtr str);

    static CPtr intern(
        const void* data,
        Encoding enc = UTF8,
        Size len = NO_SIZE,
        Size max = NO_SIZE);

    static CPtr valueOf(const Value& val);

    virtual Size length() const = 0;

    virtual Char charAt(Size index) const = 0;

    virtual CPtr concat(CPtr str) const = 0;

    virtual CPtr substring(Size from) const = 0;

    virtual CPtr substring(Size from, Size to) const = 0;

    virtual CPtr replace(Char oldC, Char newC) const = 0;

    virtual CPtr replace(CPtr oldS, CPtr newS) const = 0;

    virtual Size indexOf(Char c, Size from = 0) const = 0;

    virtual Size indexOf(CPtr str, Size from = 0) const = 0;

    virtual Size lastIndexOf(Char c, Size from = NO_POS) const = 0;

    virtual Size lastIndexOf(CPtr str, Size from = NO_POS) const = 0;

    virtual Boolean isEmpty() const = 0;

    virtual Boolean isInterned() const = 0;

    virtual Boolean startsWith(CPtr str, Size from = 0) const = 0;

    virtual Boolean endsWith(CPtr str) const = 0;

    virtual Int compareTo(CPtr str) const = 0;

    virtual Int compareTo(Object::CPtr obj) const = 0;

    virtual Boolean equals(CPtr str) const = 0;

    virtual Boolean equals(Object::CPtr obj) const = 0;

    virtual CPtr toLowerCase() const = 0;

    virtual CPtr toUpperCase() const = 0;

    virtual const Char* data() const = 0;

    virtual std::string toStdString(Encoding enc = UTF8) const = 0;

    virtual std::u16string toStdU16String() const = 0;

    virtual std::u32string toStdU32String() const = 0;
};

String::CPtr str();

String::CPtr str(const char* utf8);

String::CPtr str(const char16_t* utf16);

String::CPtr str(const char32_t* utf32);

}  // namespace libj

#include <libj/impl/string.h>

#if defined(LIBJ_USE_CXX11) && !defined(LIBJ_USE_MSVC)
# ifdef LIBJ_USE_UTF32
#  define LIBJ_U(S) U##S
# else
#  define LIBJ_U(S) u##S
# endif
#else
# define  LIBJ_U(S) S
#endif

#ifdef LIBJ_DEBUG
# define LIBJ_STATIC_CONST_STRING_DEF(N, V) \
    static const libj::String::CPtr N = libj::String::intern(V);
#else
# define LIBJ_STATIC_CONST_STRING_DEF(N, V) \
    static const libj::String::CPtr N = libj::String::create(V);
#endif

#endif  // LIBJ_STRING_H_


text:
void runtime∕race·Initialize(uintptr *racectx);
void runtime∕race·MapShadow(void *addr, uintptr size);
void runtime∕race·Finalize(void);
void runtime∕race·FinalizerGoroutine(uintptr racectx);
void runtime∕race·Read(uintptr racectx, void *addr, void *pc);
void runtime∕race·Write(uintptr racectx, void *addr, void *pc);
void runtime∕race·ReadRange(uintptr racectx, void *addr, uintptr sz, uintptr step, void *pc);
void runtime∕race·WriteRange(uintptr racectx, void *addr, uintptr sz, uintptr step, void *pc);
void runtime∕race·FuncEnter(uintptr racectx, void *pc);
void runtime∕race·FuncExit(uintptr racectx);
void runtime∕race·Malloc(uintptr racectx, void *p, uintptr sz, void *pc);
void runtime∕race·Free(void *p);
void runtime∕race·GoStart(uintptr racectx, uintptr *chracectx, void *pc);
void runtime∕race·GoEnd(uintptr racectx);
void runtime∕race·Acquire(uintptr racectx, void *addr);
void runtime∕race·Release(uintptr racectx, void *addr);
void runtime∕race·ReleaseMerge(uintptr racectx, void *addr);

extern byte noptrdata[];
extern byte enoptrbss[];

static bool onstack(uintptr argp);

uintptr
runtime·raceinit(void)
{
	uintptr racectx, start, size;

	m->racecall = true;
	runtime∕race·Initialize(&racectx);
	// Round data segment to page boundaries, because it's used in mmap().
	start = (uintptr)noptrdata & ~(PageSize-1);
	size = ROUND((uintptr)enoptrbss - start, PageSize);
	runtime∕race·MapShadow((void*)start, size);
	m->racecall = false;
	return racectx;
}

void
runtime·racefini(void)
{
	m->racecall = true;
	runtime∕race·Finalize();
	m->racecall = false;
}

void
runtime·racemapshadow(void *addr, uintptr size)
{
	m->racecall = true;
	runtime∕race·MapShadow(addr, size);
	m->racecall = false;
}

// Called from instrumented code.
// If we split stack, getcallerpc() can return runtime·lessstack().
#pragma textflag 7
void
runtime·racewrite(uintptr addr)
{
	if(!onstack(addr)) {
		m->racecall = true;
		runtime∕race·Write(g->racectx, (void*)addr, runtime·getcallerpc(&addr));
		m->racecall = false;
	}
}

// Called from instrumented code.
// If we split stack, getcallerpc() can return runtime·lessstack().
#pragma textflag 7
void
runtime·raceread(uintptr addr)
{
	if(!onstack(addr)) {
		m->racecall = true;
		runtime∕race·Read(g->racectx, (void*)addr, runtime·getcallerpc(&addr));
		m->racecall = false;
	}
}

// Called from runtime·racefuncenter (assembly).
#pragma textflag 7
void
runtime·racefuncenter1(uintptr pc)
{
	// If the caller PC is lessstack, use slower runtime·callers
	// to walk across the stack split to find the real caller.
	if(pc == (uintptr)runtime·lessstack)
		runtime·callers(2, &pc, 1);

	m->racecall = true;
	runtime∕race·FuncEnter(g->racectx, (void*)pc);
	m->racecall = false;
}

// Called from instrumented code.
#pragma textflag 7
void
runtime·racefuncexit(void)
{
	m->racecall = true;
	runtime∕race·FuncExit(g->racectx);
	m->racecall = false;
}

void
runtime·racemalloc(void *p, uintptr sz, void *pc)
{
	// use m->curg because runtime·stackalloc() is called from g0
	if(m->curg == nil)
		return;
	m->racecall = true;
	runtime∕race·Malloc(m->curg->racectx, p, sz, pc);
	m->racecall = false;
}

void
runtime·racefree(void *p)
{
	m->racecall = true;
	runtime∕race·Free(p);
	m->racecall = false;
}

uintptr
runtime·racegostart(void *pc)
{
	uintptr racectx;

	m->racecall = true;
	runtime∕race·GoStart(g->racectx, &racectx, pc);
	m->racecall = false;
	return racectx;
}

void
runtime·racegoend(void)
{
	m->racecall = true;
	runtime∕race·GoEnd(g->racectx);
	m->racecall = false;
}

static void
memoryaccess(void *addr, uintptr callpc, uintptr pc, bool write)
{
	uintptr racectx;

	if(!onstack((uintptr)addr)) {
		m->racecall = true;
		racectx = g->racectx;
		if(callpc) {
			if(callpc == (uintptr)runtime·lessstack)
				runtime·callers(3, &callpc, 1);
			runtime∕race·FuncEnter(racectx, (void*)callpc);
		}
		if(write)
			runtime∕race·Write(racectx, addr, (void*)pc);
		else
			runtime∕race·Read(racectx, addr, (void*)pc);
		if(callpc)
			runtime∕race·FuncExit(racectx);
		m->racecall = false;
	}
}

void
runtime·racewritepc(void *addr, void *callpc, void *pc)
{
	memoryaccess(addr, (uintptr)callpc, (uintptr)pc, true);
}

void
runtime·racereadpc(void *addr, void *callpc, void *pc)
{
	memoryaccess(addr, (uintptr)callpc, (uintptr)pc, false);
}

static void
rangeaccess(void *addr, uintptr size, uintptr step, uintptr callpc, uintptr pc, bool write)
{
	uintptr racectx;

	if(!onstack((uintptr)addr)) {
		m->racecall = true;
		racectx = g->racectx;
		if(callpc) {
			if(callpc == (uintptr)runtime·lessstack)
				runtime·callers(3, &callpc, 1);
			runtime∕race·FuncEnter(racectx, (void*)callpc);
		}
		if(write)
			runtime∕race·WriteRange(racectx, addr, size, step, (void*)pc);
		else
			runtime∕race·ReadRange(racectx, addr, size, step, (void*)pc);
		if(callpc)
			runtime∕race·FuncExit(racectx);
		m->racecall = false;
	}
}

void
runtime·racewriterangepc(void *addr, uintptr sz, uintptr step, void *callpc, void *pc)
{
	rangeaccess(addr, sz, step, (uintptr)callpc, (uintptr)pc, true);
}

void
runtime·racereadrangepc(void *addr, uintptr sz, uintptr step, void *callpc, void *pc)
{
	rangeaccess(addr, sz, step, (uintptr)callpc, (uintptr)pc, false);
}

void
runtime·raceacquire(void *addr)
{
	runtime·raceacquireg(g, addr);
}

void
runtime·raceacquireg(G *gp, void *addr)
{
	if(g->raceignore)
		return;
	m->racecall = true;
	runtime∕race·Acquire(gp->racectx, addr);
	m->racecall = false;
}

void
runtime·racerelease(void *addr)
{
	runtime·racereleaseg(g, addr);
}

void
runtime·racereleaseg(G *gp, void *addr)
{
	if(g->raceignore)
		return;
	m->racecall = true;
	runtime∕race·Release(gp->racectx, addr);
	m->racecall = false;
}

void
runtime·racereleasemerge(void *addr)
{
	runtime·racereleasemergeg(g, addr);
}

void
runtime·racereleasemergeg(G *gp, void *addr)
{
	if(g->raceignore)
		return;
	m->racecall = true;
	runtime∕race·ReleaseMerge(gp->racectx, addr);
	m->racecall = false;
}

void
runtime·racefingo(void)
{
	m->racecall = true;
	runtime∕race·FinalizerGoroutine(g->racectx);
	m->racecall = false;
}

// func RaceAcquire(addr unsafe.Pointer)
void
runtime·RaceAcquire(void *addr)
{
	runtime·raceacquire(addr);
}

// func RaceRelease(addr unsafe.Pointer)
void
runtime·RaceRelease(void *addr)
{
	runtime·racerelease(addr);
}

// func RaceReleaseMerge(addr unsafe.Pointer)
void
runtime·RaceReleaseMerge(void *addr)
{
	runtime·racereleasemerge(addr);
}

// func RaceSemacquire(s *uint32)
void runtime·RaceSemacquire(uint32 *s)
{
	runtime·semacquire(s);
}

// func RaceSemrelease(s *uint32)
void runtime·RaceSemrelease(uint32 *s)
{
	runtime·semrelease(s);
}

// func RaceRead(addr unsafe.Pointer)
#pragma textflag 7
void
runtime·RaceRead(void *addr)
{
	memoryaccess(addr, 0, (uintptr)runtime·getcallerpc(&addr), false);
}

// func RaceWrite(addr unsafe.Pointer)
#pragma textflag 7
void
runtime·RaceWrite(void *addr)
{
	memoryaccess(addr, 0, (uintptr)runtime·getcallerpc(&addr), true);
}

// func RaceDisable()
void runtime·RaceDisable(void)
{
	g->raceignore++;
}

// func RaceEnable()
void runtime·RaceEnable(void)
{
	g->raceignore--;
}

static bool
onstack(uintptr argp)
{
	// noptrdata, data, bss, noptrbss
	// the layout is in ../../cmd/ld/data.c
	if((byte*)argp >= noptrdata && (byte*)argp < enoptrbss)
		return false;
	if((byte*)argp >= runtime·mheap->arena_start && (byte*)argp < runtime·mheap->arena_used)
		return false;
	return true;
}


text:
using System;
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.ServiceBus.Models;

namespace Azure.ResourceManager.ServiceBus
{
    /// <summary> A class representing the ServiceBusNamespace data model. </summary>
    public partial class ServiceBusNamespaceData : TrackedResourceData
    {
        /// <summary> Initializes a new instance of ServiceBusNamespaceData. </summary>
        /// <param name="location"> The location. </param>
        public ServiceBusNamespaceData(AzureLocation location) : base(location)
        {
            PrivateEndpointConnections = new ChangeTrackingList<ServiceBusPrivateEndpointConnectionData>();
        }

        /// <summary> Initializes a new instance of ServiceBusNamespaceData. </summary>
        /// <param name="id"> The id. </param>
        /// <param name="name"> The name. </param>
        /// <param name="resourceType"> The resourceType. </param>
        /// <param name="systemData"> The systemData. </param>
        /// <param name="tags"> The tags. </param>
        /// <param name="location"> The location. </param>
        /// <param name="sku"> Properties of SKU. </param>
        /// <param name="identity"> Properties of BYOK Identity description. </param>
        /// <param name="provisioningState"> Provisioning state of the namespace. </param>
        /// <param name="status"> Status of the namespace. </param>
        /// <param name="createdOn"> The time the namespace was created. </param>
        /// <param name="updatedOn"> The time the namespace was updated. </param>
        /// <param name="serviceBusEndpoint"> Endpoint you can use to perform Service Bus operations. </param>
        /// <param name="metricId"> Identifier for Azure Insights metrics. </param>
        /// <param name="isZoneRedundant"> Enabling this property creates a Premium Service Bus Namespace in regions supported availability zones. </param>
        /// <param name="encryption"> Properties of BYOK Encryption description. </param>
        /// <param name="privateEndpointConnections"> List of private endpoint connections. </param>
        /// <param name="disableLocalAuth"> This property disables SAS authentication for the Service Bus namespace. </param>
        /// <param name="alternateName"> Alternate name for namespace. </param>
        internal ServiceBusNamespaceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary<string, string> tags, AzureLocation location, ServiceBusSku sku, ManagedServiceIdentity identity, string provisioningState, string status, DateTimeOffset? createdOn, DateTimeOffset? updatedOn, string serviceBusEndpoint, string metricId, bool? isZoneRedundant, ServiceBusEncryption encryption, IList<ServiceBusPrivateEndpointConnectionData> privateEndpointConnections, bool? disableLocalAuth, string alternateName) : base(id, name, resourceType, systemData, tags, location)
        {
            Sku = sku;
            Identity = identity;
            ProvisioningState = provisioningState;
            Status = status;
            CreatedOn = createdOn;
            UpdatedOn = updatedOn;
            ServiceBusEndpoint = serviceBusEndpoint;
            MetricId = metricId;
            IsZoneRedundant = isZoneRedundant;
            Encryption = encryption;
            PrivateEndpointConnections = privateEndpointConnections;
            DisableLocalAuth = disableLocalAuth;
            AlternateName = alternateName;
        }

        /// <summary> Properties of SKU. </summary>
        public ServiceBusSku Sku { get; set; }
        /// <summary> Properties of BYOK Identity description. </summary>
        public ManagedServiceIdentity Identity { get; set; }
        /// <summary> Provisioning state of the namespace. </summary>
        public string ProvisioningState { get; }
        /// <summary> Status of the namespace. </summary>
        public string Status { get; }
        /// <summary> The time the namespace was created. </summary>
        public DateTimeOffset? CreatedOn { get; }
        /// <summary> The time the namespace was updated. </summary>
        public DateTimeOffset? UpdatedOn { get; }
        /// <summary> Endpoint you can use to perform Service Bus operations. </summary>
        public string ServiceBusEndpoint { get; }
        /// <summary> Identifier for Azure Insights metrics. </summary>
        public string MetricId { get; }
        /// <summary> Enabling this property creates a Premium Service Bus Namespace in regions supported availability zones. </summary>
        public bool? IsZoneRedundant { get; set; }
        /// <summary> Properties of BYOK Encryption description. </summary>
        public ServiceBusEncryption Encryption { get; set; }
        /// <summary> List of private endpoint connections. </summary>
        public IList<ServiceBusPrivateEndpointConnectionData> PrivateEndpointConnections { get; }
        /// <summary> This property disables SAS authentication for the Service Bus namespace. </summary>
        public bool? DisableLocalAuth { get; set; }
        /// <summary> Alternate name for namespace. </summary>
        public string AlternateName { get; set; }
    }
}


text:
package reflex;

import org.antlr.runtime.RecognitionException;
import org.junit.Test;

public class FromJsonTest extends ResourceBasedTest {

    @Test
    public void testFromJson() throws RecognitionException {
        runTestFor("/fromjson.rfx");
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Str = (function () {
    function Str() {
    }
    Str.endsWith = function (input, suffix) {
        return input.indexOf(suffix, input.length - suffix.length) !== -1;
    };
    Str.trim = function (str) {
        return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
    Str.format = function (formatString) {
        var args = arguments;
        return formatString.replace(/{(\d+)}/g, function (match, num) {
            var replacementIndex = parseInt(num, 10) + 1;
            return typeof args[replacementIndex] !== 'undefined' ? args[replacementIndex] : match;
        });
    };
    return Str;
})();
var DAL;
(function (DAL) {
    'use strict';
    var BaseExternalInvoker = (function () {
        function BaseExternalInvoker() {
            this.invoke = function (event, data) {
                if (event === null) {
                    throw 'event is null or undefined';
                }
                if (data === null) {
                    throw 'data is null or undefined';
                }
                throw 'Invoker.invoke has not been implemented, or you are using the base invoker.';
            };
            this.responder = function (event, data) {
                if (event === null) {
                    throw 'event is null or undefined';
                }
                if (data === null) {
                    throw 'data is null or undefined';
                }
                throw 'Invoker.responder delegate was not provided.';
            };
        }
        return BaseExternalInvoker;
    })();
    DAL.BaseExternalInvoker = BaseExternalInvoker;
    var SignalRExternalInvoker = (function (_super) {
        __extends(SignalRExternalInvoker, _super);
        function SignalRExternalInvoker() {
            var _this = this;
            _super.call(this);
            var intervalLoop;
            var connection = $.hubConnection();
            var queue = [];
            var hub = connection.createHubProxy('eventHub');
            var writeConnectionLog = function (connectionState) {
                var prefix = !logConfig.SupportCustomLogs ? '' : '%c';
                var suffix = !logConfig.SupportCustomLogs ? '' : 'background: #222; color: #bada55';
                logR.custom(prefix + ' © ' + connectionState + ' © ', suffix);
            };
            var writeTransportLog = function (transportType, details) {
                var prefix = !logConfig.SupportCustomLogs ? '' : '%c';
                var suffix = !logConfig.SupportCustomLogs ? '' : 'background: #222; color: #bada55';
                logR.custom(prefix + transportType, suffix, details);
            };
            /* tslint:disable: no-any */
            //We must use the `any` type here since we don't know what this might contain!
            //We need to disable the TSLint rule temporarily to allow this to work and to make TSLint not complain
            hub.on('eventReceived', function () {
                var msgs = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    msgs[_i - 0] = arguments[_i];
                }
                /* tslint:enable: no-any */
                var event = msgs[0], data = msgs[1];
                writeTransportLog(' ↓ Reply ↓ ', 'Event: ' + event);
                _this.responder(event, data);
            });
            var stopQueue = function () {
                writeTransportLog(' ! Queue Stopped ! ', DateTime.NowString());
                window.clearInterval(intervalLoop);
            };
            var startQueue = function () {
                var sendRequest = function (qi) {
                    if ($.signalR.connectionState.connected) {
                        writeTransportLog(' ↑ Request ↑ ', 'Event: ' + qi.Event);
                        hub.invoke('raiseEvent', qi.Event, qi.Data);
                    }
                    else {
                        stopQueue();
                    }
                };
                var process = function () {
                    for (var i = 0; i < queue.length; i++) {
                        var qi = queue.splice(0, 1)[0];
                        if (qi) {
                            sendRequest(qi);
                        }
                        else {
                            break;
                        }
                    }
                };
                intervalLoop = window.setInterval(process, 10);
            };
            connection.stateChanged(function (change) {
                //Call the optional function if it really is a function when the state is changed
                if ($.isFunction(_this.onStateChange)) {
                    //Send the change state and the SignalR connection object
                    _this.onStateChange.call(_this, change, connection);
                }
                switch (change.newState) {
                    case $.signalR.connectionState.reconnecting:
                        writeConnectionLog('Re-connecting');
                        stopQueue();
                        break;
                    case $.signalR.connectionState.connected:
                        writeConnectionLog('Connected');
                        startQueue();
                        break;
                    case $.signalR.connectionState.disconnected:
                        writeConnectionLog('Disconnected');
                        stopQueue();
                        break;
                    default:
                }
            });
            connection.start();
            /* tslint:disable: no-any */
            //We must use the `any` type here since we don't know what this might contain!
            //We need to disable the TSLint rule temporarily to allow this to work and to make TSLint not complain
            this.invoke = function (event, data) {
                /* tslint:enable: no-any */
                queue.push({
                    Event: event,
                    Data: data
                });
            };
        }
        SignalRExternalInvoker.prototype.onStateChange = function (change, connection) {
            //do nothing by default
        };
        return SignalRExternalInvoker;
    })(BaseExternalInvoker);
    DAL.SignalRExternalInvoker = SignalRExternalInvoker;
    var QueueItem = (function () {
        function QueueItem() {
        }
        return QueueItem;
    })();
})(DAL || (DAL = {}));
var DateTime = (function () {
    function DateTime() {
    }
    DateTime.NowString = function () {
        var now = new Date();
        var hoursTwentyForFormat = now.getHours();
        var hoursTwelveFormat;
        if (hoursTwentyForFormat === 0) {
            hoursTwelveFormat = 12;
        }
        else {
            hoursTwelveFormat = hoursTwentyForFormat > 12 ? hoursTwentyForFormat - 12 : hoursTwentyForFormat;
        }
        function addZero(num) {
            return (num >= 0 && num < 10) ? "0" + num : num + "";
        }
        var dateBits = addZero(now.getMonth() + 1) + '/' + addZero(now.getDate()) + '/' + now.getFullYear();
        var timeBits = addZero(hoursTwelveFormat) + ':' + addZero(now.getMinutes());
        var todBits = now.getHours() >= 12 ? "PM" : "AM";
        var strDateTime = dateBits + ' ' + timeBits + ' ' + todBits;
        return strDateTime;
    };
    return DateTime;
})();
//# sourceMappingURL=Sunset.js.map


text:
package org.apache.hadoop.hive.ql.exec.repl;

import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.repl.ranger.RangerRestClient;
import org.apache.hadoop.hive.ql.exec.repl.ranger.RangerRestClientImpl;
import org.apache.hadoop.hive.ql.exec.repl.ranger.NoOpRangerRestClient;
import org.apache.hadoop.hive.ql.exec.repl.ranger.RangerPolicy;
import org.apache.hadoop.hive.ql.exec.repl.ranger.RangerExportPolicyList;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.repl.ReplLogger;
import org.apache.hadoop.hive.ql.parse.repl.load.log.RangerLoadLogger;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Status;
import org.apache.hadoop.hive.ql.plan.api.StageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.REPL_RANGER_ADD_DENY_POLICY_TARGET;
/**
 * RangerLoadTask.
 *
 * Rask to import Ranger authorization policies.
 **/
public class RangerLoadTask extends Task<RangerLoadWork> implements Serializable {
  private static final long serialVersionUID = 1L;

  private static final Logger LOG = LoggerFactory.getLogger(RangerLoadTask.class);

  private transient RangerRestClient rangerRestClient;

  private transient ReplLogger replLogger;

  public RangerLoadTask() {
    super();
  }

  @VisibleForTesting
  RangerLoadTask(final RangerRestClient rangerRestClient, final HiveConf conf, final RangerLoadWork work) {
    this.conf = conf;
    this.work = work;
    this.rangerRestClient = rangerRestClient;
  }

  @Override
  public String getName() {
    return "RANGER_LOAD";
  }

  @Override
  public int execute() {
    try {
      LOG.info("Importing Ranger Metadata");
      RangerExportPolicyList rangerExportPolicyList = null;
      List<RangerPolicy> rangerPolicies = null;
      if (rangerRestClient == null) {
        rangerRestClient = getRangerRestClient();
      }
      URL url = work.getRangerConfigResource();
      if (url == null) {
        throw new SemanticException("Ranger configuration is not valid "
          + ReplUtils.RANGER_CONFIGURATION_RESOURCE_NAME);
      }
      conf.addResource(url);
      String rangerHiveServiceName = conf.get(ReplUtils.RANGER_HIVE_SERVICE_NAME);
      String rangerEndpoint = conf.get(ReplUtils.RANGER_REST_URL);
      if (StringUtils.isEmpty(rangerEndpoint) || !rangerRestClient.checkConnection(rangerEndpoint)) {
        throw new SemanticException("Ranger endpoint is not valid " + rangerEndpoint);
      }
      if (work.getCurrentDumpPath() != null) {
        LOG.info("Importing Ranger Metadata from {} ", work.getCurrentDumpPath());
        rangerExportPolicyList = rangerRestClient.readRangerPoliciesFromJsonFile(new Path(work.getCurrentDumpPath(),
                ReplUtils.HIVE_RANGER_POLICIES_FILE_NAME), conf);
        int expectedPolicyCount = rangerExportPolicyList == null ? 0 : rangerExportPolicyList.getListSize();
        replLogger = new RangerLoadLogger(work.getSourceDbName(), work.getTargetDbName(),
          work.getCurrentDumpPath().toString(), expectedPolicyCount);
        replLogger.startLog();
        Map<String, Long> metricMap = new HashMap<>();
        metricMap.put(ReplUtils.MetricName.POLICIES.name(), (long) expectedPolicyCount);
        work.getMetricCollector().reportStageStart(getName(), metricMap);
        if (rangerExportPolicyList != null && !CollectionUtils.isEmpty(rangerExportPolicyList.getPolicies())) {
          rangerPolicies = rangerExportPolicyList.getPolicies();
        }
      }

      if (CollectionUtils.isEmpty(rangerPolicies)) {
        LOG.info("There are no ranger policies to import");
        rangerPolicies = new ArrayList<>();
      }
      List<RangerPolicy> rangerPoliciesWithDenyPolicy = rangerPolicies;
      if (conf.getBoolVar(REPL_RANGER_ADD_DENY_POLICY_TARGET)) {
        rangerPoliciesWithDenyPolicy = rangerRestClient.addDenyPolicies(rangerPolicies,
          rangerHiveServiceName, work.getSourceDbName(), work.getTargetDbName());
      }

      List<RangerPolicy> updatedRangerPolicies = rangerRestClient.changeDataSet(rangerPoliciesWithDenyPolicy,
          work.getSourceDbName(), work.getTargetDbName());

      long importCount = 0;
      if (!CollectionUtils.isEmpty(updatedRangerPolicies)) {
        if (rangerExportPolicyList == null) {
          rangerExportPolicyList = new RangerExportPolicyList();
        }
        rangerExportPolicyList.setPolicies(updatedRangerPolicies);
        rangerRestClient.importRangerPolicies(rangerExportPolicyList, work.getTargetDbName(), rangerEndpoint,
                rangerHiveServiceName);
        LOG.info("Number of ranger policies imported {}", rangerExportPolicyList.getListSize());
        importCount = rangerExportPolicyList.getListSize();
        work.getMetricCollector().reportStageProgress(getName(), ReplUtils.MetricName.POLICIES.name(), importCount);
        replLogger.endLog(importCount);
        LOG.info("Ranger policy import finished {} ", importCount);
      }
      work.getMetricCollector().reportStageEnd(getName(), Status.SUCCESS);
      return 0;
    } catch (Exception e) {
      LOG.error("Failed", e);
      setException(e);
      try {
        work.getMetricCollector().reportStageEnd(getName(), Status.FAILED);
      } catch (SemanticException ex) {
        LOG.error("Failed to collect Metrics", ex);
      }
      return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode();
    }
  }

  private RangerRestClient getRangerRestClient() {
    if (conf.getBoolVar(HiveConf.ConfVars.HIVE_IN_TEST_REPL) || conf.getBoolVar(HiveConf.ConfVars.HIVE_IN_TEST)) {
      return new NoOpRangerRestClient();
    }
    return new RangerRestClientImpl();
  }

  @Override
  public StageType getType() {
    return StageType.RANGER_LOAD;
  }

  @Override
  public boolean canExecuteInParallel() {
    return false;
  }
}


text:
package org.drools.lang.api;

import org.drools.lang.descr.AndDescr;
import org.drools.lang.descr.QueryDescr;

/**
 *  A descriptor builder for queries
 */
public interface QueryDescrBuilder
    extends
    AnnotatedDescrBuilder<QueryDescrBuilder>,
    ParameterSupportBuilder<QueryDescrBuilder>,
    DescrBuilder<PackageDescrBuilder, QueryDescr> {

    public QueryDescrBuilder name( String name );

    public CEDescrBuilder<QueryDescrBuilder, AndDescr> lhs();

}