text:
package org.elasticsearch.gateway;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataIndexUpgradeService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.NodeEnvironment;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableSet;

/**
 *
 */
public class GatewayMetaState extends AbstractComponent implements ClusterStateListener {

    private final NodeEnvironment nodeEnv;
    private final MetaStateService metaStateService;
    private final DanglingIndicesState danglingIndicesState;
    private final MetaDataIndexUpgradeService metaDataIndexUpgradeService;

    @Nullable
    private volatile MetaData previousMetaData;

    private volatile Set<String> previouslyWrittenIndices = emptySet();

    @Inject
    public GatewayMetaState(Settings settings, NodeEnvironment nodeEnv, MetaStateService metaStateService,
                            DanglingIndicesState danglingIndicesState, TransportNodesListGatewayMetaState nodesListGatewayMetaState,
                            MetaDataIndexUpgradeService metaDataIndexUpgradeService) throws Exception {
        super(settings);
        this.nodeEnv = nodeEnv;
        this.metaStateService = metaStateService;
        this.danglingIndicesState = danglingIndicesState;
        this.metaDataIndexUpgradeService = metaDataIndexUpgradeService;
        nodesListGatewayMetaState.init(this);

        if (DiscoveryNode.dataNode(settings)) {
            ensureNoPre019ShardState(nodeEnv);
        }

        if (DiscoveryNode.masterNode(settings) || DiscoveryNode.dataNode(settings)) {
            nodeEnv.ensureAtomicMoveSupported();
        }
        if (DiscoveryNode.masterNode(settings) || DiscoveryNode.dataNode(settings)) {
            try {
                ensureNoPre019State();
                pre20Upgrade();
                long startNS = System.nanoTime();
                metaStateService.loadFullState();
                logger.debug("took {} to load state", TimeValue.timeValueMillis(TimeValue.nsecToMSec(System.nanoTime() - startNS)));
            } catch (Exception e) {
                logger.error("failed to read local state, exiting...", e);
                throw e;
            }
        }
    }

    public MetaData loadMetaState() throws Exception {
        return metaStateService.loadFullState();
    }

    @Override
    public void clusterChanged(ClusterChangedEvent event) {

        Set<String> relevantIndices = new HashSet<>();
        final ClusterState state = event.state();
        if (state.blocks().disableStatePersistence()) {
            // reset the current metadata, we need to start fresh...
            this.previousMetaData = null;
            previouslyWrittenIndices = emptySet();
            return;
        }

        MetaData newMetaData = state.metaData();
        // we don't check if metaData changed, since we might be called several times and we need to check dangling...

        boolean success = true;
        // write the state if this node is a master eligible node or if it is a data node and has shards allocated on it
        if (state.nodes().localNode().masterNode() || state.nodes().localNode().dataNode()) {
            if (previousMetaData == null) {
                try {
                    // we determine if or if not we write meta data on data only nodes by looking at the shard routing
                    // and only write if a shard of this index is allocated on this node
                    // however, closed indices do not appear in the shard routing. if the meta data for a closed index is
                    // updated it will therefore not be written in case the list of previouslyWrittenIndices is empty (because state
                    // persistence was disabled or the node was restarted), see getRelevantIndicesOnDataOnlyNode().
                    // we therefore have to check here if we have shards on disk and add their indices to the previouslyWrittenIndices list
                    if (isDataOnlyNode(state)) {
                        Set<String> newPreviouslyWrittenIndices = new HashSet<>(previouslyWrittenIndices.size());
                        for (IndexMetaData indexMetaData : newMetaData) {
                            IndexMetaData indexMetaDataOnDisk = null;
                            if (indexMetaData.getState().equals(IndexMetaData.State.CLOSE)) {
                                indexMetaDataOnDisk = metaStateService.loadIndexState(indexMetaData.getIndex().getName());
                            }
                            if (indexMetaDataOnDisk != null) {
                                newPreviouslyWrittenIndices.add(indexMetaDataOnDisk.getIndex().getName());
                            }
                        }
                        newPreviouslyWrittenIndices.addAll(previouslyWrittenIndices);
                        previouslyWrittenIndices = unmodifiableSet(newPreviouslyWrittenIndices);
                    }
                } catch (Throwable e) {
                    success = false;
                }
            }
            // check if the global state changed?
            if (previousMetaData == null || !MetaData.isGlobalStateEquals(previousMetaData, newMetaData)) {
                try {
                    metaStateService.writeGlobalState("changed", newMetaData);
                } catch (Throwable e) {
                    success = false;
                }
            }

            Iterable<IndexMetaWriteInfo> writeInfo;
            relevantIndices = getRelevantIndices(event.state(), event.previousState(), previouslyWrittenIndices);
            writeInfo = resolveStatesToBeWritten(previouslyWrittenIndices, relevantIndices, previousMetaData, event.state().metaData());
            // check and write changes in indices
            for (IndexMetaWriteInfo indexMetaWrite : writeInfo) {
                try {
                    metaStateService.writeIndex(indexMetaWrite.reason, indexMetaWrite.newMetaData, indexMetaWrite.previousMetaData);
                } catch (Throwable e) {
                    success = false;
                }
            }
        }

        danglingIndicesState.processDanglingIndices(newMetaData);

        if (success) {
            previousMetaData = newMetaData;
            previouslyWrittenIndices = unmodifiableSet(relevantIndices);
        }
    }

    public static Set<String> getRelevantIndices(ClusterState state, ClusterState previousState, Set<String> previouslyWrittenIndices) {
        Set<String> relevantIndices;
        if (isDataOnlyNode(state)) {
            relevantIndices = getRelevantIndicesOnDataOnlyNode(state, previousState, previouslyWrittenIndices);
        } else if (state.nodes().localNode().masterNode() == true) {
            relevantIndices = getRelevantIndicesForMasterEligibleNode(state);
        } else {
            relevantIndices = Collections.emptySet();
        }
        return relevantIndices;
    }

    protected static boolean isDataOnlyNode(ClusterState state) {
        return ((state.nodes().localNode().masterNode() == false) && state.nodes().localNode().dataNode());
    }

    /**
     * Throws an IAE if a pre 0.19 state is detected
     */
    private void ensureNoPre019State() throws Exception {
        for (Path dataLocation : nodeEnv.nodeDataPaths()) {
            final Path stateLocation = dataLocation.resolve(MetaDataStateFormat.STATE_DIR_NAME);
            if (!Files.exists(stateLocation)) {
                continue;
            }
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(stateLocation)) {
                for (Path stateFile : stream) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("[upgrade]: processing [" + stateFile.getFileName() + "]");
                    }
                    final String name = stateFile.getFileName().toString();
                    if (name.startsWith("metadata-")) {
                        throw new IllegalStateException("Detected pre 0.19 metadata file please upgrade to a version before "
                                + Version.CURRENT.minimumCompatibilityVersion()
                                + " first to upgrade state structures - metadata found: [" + stateFile.getParent().toAbsolutePath());
                    }
                }
            }
        }
    }

    /**
     * Elasticsearch 2.0 removed several deprecated features and as well as support for Lucene 3.x. This method calls
     * {@link MetaDataIndexUpgradeService} to makes sure that indices are compatible with the current version. The
     * MetaDataIndexUpgradeService might also update obsolete settings if needed. When this happens we rewrite
     * index metadata with new settings.
     */
    private void pre20Upgrade() throws Exception {
        MetaData metaData = loadMetaState();
        List<IndexMetaData> updateIndexMetaData = new ArrayList<>();
        for (IndexMetaData indexMetaData : metaData) {
            IndexMetaData newMetaData = metaDataIndexUpgradeService.upgradeIndexMetaData(indexMetaData);
            if (indexMetaData != newMetaData) {
                updateIndexMetaData.add(newMetaData);
            }
        }
        // We successfully checked all indices for backward compatibility and found no non-upgradable indices, which
        // means the upgrade can continue. Now it's safe to overwrite index metadata with the new version.
        for (IndexMetaData indexMetaData : updateIndexMetaData) {
            metaStateService.writeIndex("upgrade", indexMetaData, null);
        }
    }

    // shard state BWC
    private void ensureNoPre019ShardState(NodeEnvironment nodeEnv) throws Exception {
        for (Path dataLocation : nodeEnv.nodeDataPaths()) {
            final Path stateLocation = dataLocation.resolve(MetaDataStateFormat.STATE_DIR_NAME);
            if (Files.exists(stateLocation)) {
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(stateLocation, "shards-*")) {
                    for (Path stateFile : stream) {
                        throw new IllegalStateException("Detected pre 0.19 shard state file please upgrade to a version before "
                                + Version.CURRENT.minimumCompatibilityVersion()
                                + " first to upgrade state structures - shard state found: [" + stateFile.getParent().toAbsolutePath());
                    }
                }
            }
        }
    }

    /**
     * Loads the current meta state for each index in the new cluster state and checks if it has to be persisted.
     * Each index state that should be written to disk will be returned. This is only run for data only nodes.
     * It will return only the states for indices that actually have a shard allocated on the current node.
     *
     * @param previouslyWrittenIndices    A list of indices for which the state was already written before
     * @param potentiallyUnwrittenIndices The list of indices for which state should potentially be written
     * @param previousMetaData            The last meta data we know of. meta data for all indices in previouslyWrittenIndices list is persisted now
     * @param newMetaData                 The new metadata
     * @return iterable over all indices states that should be written to disk
     */
    public static Iterable<GatewayMetaState.IndexMetaWriteInfo> resolveStatesToBeWritten(Set<String> previouslyWrittenIndices, Set<String> potentiallyUnwrittenIndices, MetaData previousMetaData, MetaData newMetaData) {
        List<GatewayMetaState.IndexMetaWriteInfo> indicesToWrite = new ArrayList<>();
        for (String index : potentiallyUnwrittenIndices) {
            IndexMetaData newIndexMetaData = newMetaData.index(index);
            IndexMetaData previousIndexMetaData = previousMetaData == null ? null : previousMetaData.index(index);
            String writeReason = null;
            if (previouslyWrittenIndices.contains(index) == false || previousIndexMetaData == null) {
                writeReason = "freshly created";
            } else if (previousIndexMetaData.getVersion() != newIndexMetaData.getVersion()) {
                writeReason = "version changed from [" + previousIndexMetaData.getVersion() + "] to [" + newIndexMetaData.getVersion() + "]";
            }
            if (writeReason != null) {
                indicesToWrite.add(new GatewayMetaState.IndexMetaWriteInfo(newIndexMetaData, previousIndexMetaData, writeReason));
            }
        }
        return indicesToWrite;
    }

    public static Set<String> getRelevantIndicesOnDataOnlyNode(ClusterState state, ClusterState previousState, Set<String> previouslyWrittenIndices) {
        RoutingNode newRoutingNode = state.getRoutingNodes().node(state.nodes().localNodeId());
        if (newRoutingNode == null) {
            throw new IllegalStateException("cluster state does not contain this node - cannot write index meta state");
        }
        Set<String> indices = new HashSet<>();
        for (ShardRouting routing : newRoutingNode) {
            indices.add(routing.index().getName());
        }
        // we have to check the meta data also: closed indices will not appear in the routing table, but we must still write the state if we have it written on disk previously
        for (IndexMetaData indexMetaData : state.metaData()) {
            boolean isOrWasClosed = indexMetaData.getState().equals(IndexMetaData.State.CLOSE);
            // if the index is open we might still have to write the state if it just transitioned from closed to open
            // so we have to check for that as well.
            IndexMetaData previousMetaData = previousState.metaData().index(indexMetaData.getIndex());
            if (previousMetaData != null) {
                isOrWasClosed = isOrWasClosed || previousMetaData.getState().equals(IndexMetaData.State.CLOSE);
            }
            if (previouslyWrittenIndices.contains(indexMetaData.getIndex().getName()) && isOrWasClosed) {
                indices.add(indexMetaData.getIndex().getName());
            }
        }
        return indices;
    }

    public static Set<String> getRelevantIndicesForMasterEligibleNode(ClusterState state) {
        Set<String> relevantIndices;
        relevantIndices = new HashSet<>();
        // we have to iterate over the metadata to make sure we also capture closed indices
        for (IndexMetaData indexMetaData : state.metaData()) {
            relevantIndices.add(indexMetaData.getIndex().getName());
        }
        return relevantIndices;
    }

    public static class IndexMetaWriteInfo {
        final IndexMetaData newMetaData;
        final String reason;
        final IndexMetaData previousMetaData;

        public IndexMetaWriteInfo(IndexMetaData newMetaData, IndexMetaData previousMetaData, String reason) {
            this.newMetaData = newMetaData;
            this.reason = reason;
            this.previousMetaData = previousMetaData;
        }

        public IndexMetaData getNewMetaData() {
            return newMetaData;
        }

        public String getReason() {
            return reason;
        }
    }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PowerArgs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace ArgsTests
{
    [TestClass]
    [TestCategory(Categories.Core)]
    public class TabCompletionTests
    {
        const int MaxHistory = 10;

        public enum EnumWithShortcuts
        {
            [ArgShortcut("NumberOne")]
            One,
            Two,
            Three,
        }

        [TabCompletion(typeof(MyCompletionSource), "$", ExeName = "TestSuiteTestArgs.exe", HistoryToSave = MaxHistory)]
        public class TestArgs
        {
            public string SomeParam { get; set; }
            public int AnotherParam { get; set; }
            public bool BoolParam { get; set; }
        }

        [TabCompletion(typeof(MyCompletionSource), "$", ExeName = "TestSuiteTestArgs.exe", HistoryToSave = MaxHistory)]
        public class TestArgsWithSecureStringArgument
        {
            public SecureStringArgument Password { get; set; }
        }

        [TabCompletion(typeof(MyCompletionSource), "$", REPL = true, ExeName = "TestSuiteTestArgs.exe", HistoryToSave = MaxHistory)]
        public class TestArgsWithREPL
        {
            public string SomeParam { get; set; }
            public int AnotherParam { get; set; }
            public bool BoolParam { get; set; }

            public static List<string> SomeParamValues { get; private set; }

            public void Main()
            {
                SomeParamValues = SomeParamValues ?? new List<string>();
                SomeParamValues.Add(SomeParam);
            }
        }

        [TabCompletion("$")]
        public class TestArgsWithEnum
        {
            public EnumWithShortcuts Enum { get; set; }
        }

        [TabCompletion("$")]
        public class ArgsWithActionsAndEnums
        {
            [ArgActionMethod]
            public void Do(DayOfWeek week) { }
        }

        public class MyCompletionSource : SimpleTabCompletionSource
        {
            public MyCompletionSource() : base(MyCompletionSource.GetWords()) {}
            private static IEnumerable<string> GetWords()
            {
                return "Adam|Abdelhamed".Split('|');
            }
        }

        public class NameSource : SimpleTabCompletionSource
        {
            public NameSource() : base(new string[] { "Adam", "Joe" }) { }
        }

        [TabCompletion(typeof(MyCompletionSource), "$", ExeName = "TestSuiteTestArgs.exe", HistoryToSave = MaxHistory)]
        public class ArgAwareCompletionArgs
        {
            [ArgumentAwareTabCompletionAttribute(typeof(NameSource))]
            public string Name { get; set; }
            public string Address { get; set; }
        }

        [TestMethod]
        public void EnsureSecureStringsAreNotTabCompletable()
        {
            ConsoleProvider.Current = new TestConsoleProvider("-pa\t");
            try
            {
                var parsed = Args.Parse<TestArgsWithSecureStringArgument>("$");
            }
            catch(UnexpectedArgException ex)
            {
                // if we see 'pa' as the argument then we know that the tab completion system did not expand 'pa' to 'password'
                Assert.AreEqual("Unexpected named argument: pa", ex.Message);
            }
        }

        [TestMethod]
        public void TestActionEnumArgCompletion()
        {
            ConsoleProvider.Current = new TestConsoleProvider("Do -week Mo\t");
            var parsed = Args.ParseAction<ArgsWithActionsAndEnums>("$");
            Assert.AreEqual(DayOfWeek.Monday, parsed.Definition.SpecifiedAction.Arguments[0].RevivedValue);
        }

        [TestMethod]
        public void TestPassThrough()
        {
            ConsoleProvider.Current = new TestConsoleProvider("-s Adam -a 100");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam", parsed.SomeParam);
            Assert.AreEqual(100, parsed.AnotherParam);
        }

        [TestMethod]
        public void TestQuotesWithinArgs()
        {
            ConsoleProvider.Current = new TestConsoleProvider("-s \\\"Adam\\\" -a 100");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("\"Adam\"", parsed.SomeParam);
            Assert.AreEqual(100, parsed.AnotherParam);
        }

        [TestMethod]
        public void TestProperParsingOfQuotedArgs()
        {
            TestConsoleProvider.SimulateConsoleInput("-s \"Adam Abdelhamed\" -a 100");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam Abdelhamed", parsed.SomeParam);
            Assert.AreEqual(100, parsed.AnotherParam);
        }

        [TestMethod]
        public void TestBasicCompletion()
        {
            TestConsoleProvider.SimulateConsoleInput("-som\t Adam -an\t 100");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam", parsed.SomeParam);
            Assert.AreEqual(100, parsed.AnotherParam);
        }

        [TestMethod]
        public void TestCustomCompletion()
        {
            TestConsoleProvider.SimulateConsoleInput("-som\t Abd\t");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Abdelhamed", parsed.SomeParam);
        }

        [TestMethod]
        public void TestBackspace()
        {
            TestConsoleProvider.SimulateConsoleInput("\b-sot\bmeparam Adam");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam", parsed.SomeParam);
        }

        [TestMethod]
        public void TestArrowAndDelete()
        {
            TestConsoleProvider.SimulateConsoleInput("-sot{left}{right}{left}{delete}meparam Adam");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam", parsed.SomeParam);
        }

        [TestMethod]
        public void TestHomeAndEnd()
        {
            TestConsoleProvider.SimulateConsoleInput("someparam Adam{home}-{end} -a 100");
            var parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("Adam", parsed.SomeParam);
            Assert.AreEqual(100, parsed.AnotherParam);
        }

        [TestMethod]
        public void TestMultiTabsFileSystem()
        {
            using (var temps = new TempFiles())
            {
                temps.CreateDirectory("DummyFolder", "1", "2", "3", "4");

                TestConsoleProvider.SimulateConsoleInput("-som\t Dumm\t\\\t\t\t");
                var parsed = Args.Parse<TestArgs>("$");
                Assert.AreEqual( Path.Combine(Environment.CurrentDirectory, "DummyFolder\\3"), parsed.SomeParam);
            }
        }

        [TestMethod]
        public void TestShiftTabFileSystem()
        {
            using (var temps = new TempFiles())
            {
                temps.CreateDirectory("DummyFolder", "1", "2", "3", "4");

                TestConsoleProvider.SimulateConsoleInput("-som\t Dumm\t\\\t\t\t{shift}\t{shift}\t");
                var parsed = Args.Parse<TestArgs>("$");
                Assert.AreEqual(Path.Combine(Environment.CurrentDirectory, "DummyFolder\\1"), parsed.SomeParam);
            }
        }

        [TestMethod]
        public void TestHistoryBasic()
        {
            ClearHistory();
            TestConsoleProvider.SimulateConsoleInput("-s historytest");
            var parsed = Args.Parse<TestArgs>("$");
            TestConsoleProvider.SimulateConsoleInput("{up}");
            parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("historytest", parsed.SomeParam);
            ClearHistory();
        }

        [TestMethod]
        public void TestHistoryUpDown()
        {
            ClearHistory();
            TestConsoleProvider.SimulateConsoleInput("-s historytest1");
            var parsed = Args.Parse<TestArgs>("$");
            TestConsoleProvider.SimulateConsoleInput("-s historytest2");
            parsed = Args.Parse<TestArgs>("$");
            TestConsoleProvider.SimulateConsoleInput("{up}{up}{down}");
            parsed = Args.Parse<TestArgs>("$");
            Assert.AreEqual("historytest2", parsed.SomeParam);
            ClearHistory();
        }

        [TestMethod]
        public void TestHistoryCleanup()
        {
            ClearHistory();
            for (int i = 0; i < MaxHistory + 1; i++)
            {
                TestConsoleProvider.SimulateConsoleInput("-s historytest"+i);
                var parsed = Args.Parse<TestArgs>("$");
            }

            TestConsoleProvider.SimulateConsoleInput(Repeat("{up}", MaxHistory+1));
            var parsedAgain = Args.Parse<TestArgs>("$");
            Assert.AreEqual("historytest10", parsedAgain.SomeParam);
            ClearHistory();
        }

        [TestMethod]
        public void TestEnumCompletion()
        {
            TestConsoleProvider.SimulateConsoleInput("-e\t thr\t");
            var parsed = Args.Parse<TestArgsWithEnum>("$");
            Assert.AreEqual(EnumWithShortcuts.Three, parsed.Enum);
        }

        [TestMethod]
        public void TestEnumShortcutsCompletion()
        {
            TestConsoleProvider.SimulateConsoleInput("-e\t numb\t");
            var parsed = Args.Parse<TestArgsWithEnum>("$");
            Assert.AreEqual(EnumWithShortcuts.One, parsed.Enum);
        }

        [TabCompletion(typeof(MyLongCompletionSource), "$", ExeName = "TestSuiteTestArgs.exe", HistoryToSave = MaxHistory)]
        public class LongTestArgs
        {
            public string SomeParam { get; set; }
            public int AnotherParam { get; set; }
            public bool BoolParam { get; set; }
        }

        public class MyLongCompletionSource : SimpleTabCompletionSource
        {
            public MyLongCompletionSource() : base(MyLongCompletionSource.GetWords()) { }
            private static IEnumerable<string> GetWords()
            {
                return "AVeryLongWordSoThatTheBufferWidthOfTheConsoleWillBeExceededAndAnExceptionWouldBeRisedIfNoMeasureIsTakendddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd|Abdelhamed".Split('|');
            }
        }

        [TestMethod]
        public void TestREPL()
        {
            var provider = TestConsoleProvider.SimulateConsoleInput("-som\t Adam{enter}cls{enter}-some\t Abdelhamed{enter}quit");

            int clearCount = 0;
            provider.ClearHappened += () => { clearCount++; };

            Args.InvokeMain<TestArgsWithREPL>("$");
            Assert.AreEqual(2, TestArgsWithREPL.SomeParamValues.Count);
            Assert.AreEqual("Adam", TestArgsWithREPL.SomeParamValues[0]);
            Assert.AreEqual("Abdelhamed", TestArgsWithREPL.SomeParamValues[1]);
            Assert.AreEqual(1, clearCount);
        }

        [TestMethod]
        public void TestREPLCancelled()
        {
            var provider = TestConsoleProvider.SimulateConsoleInput("quit");
            var ret = Args.InvokeMain<TestArgsWithREPL>("$");
            Assert.IsNotNull(ret);
            Assert.IsTrue(ret.Cancelled);
        }

        [TestMethod]
        public void TestREPLExitsWhenIndicatorIsNotPresent()
        {

            var result = Args.InvokeMain<TestArgsWithREPL>("-someparam", "somevalue");
            Assert.AreEqual("somevalue", result.Args.SomeParam);
        }

        [TestMethod]
        public void TestREPLReset()
        {
            SetupCleanup.ClearAttributeCache();
            var provider = TestConsoleProvider.SimulateConsoleInput("-b{enter}-s a{enter}quit");
            var def = new CommandLineArgumentsDefinition(typeof(TestArgsWithREPL));
            var boolArg = def.FindMatchingArgument("b");
            Assert.IsNotNull(boolArg);

            bool first = true;
            bool validatedBoth = false;
            var interceptor = new AfterInvokeInterceptor((context) =>
            {
                if (first)
                {
                    first = false;
                    Assert.IsTrue((bool)boolArg.RevivedValue);
                }
                else
                {
                    Assert.IsNull(boolArg.RevivedValue);
                    validatedBoth = true;
                }
            });

            def.Metadata.Add(interceptor);

            var finalResult = Args.InvokeMain(def, "$");
            Assert.IsTrue(validatedBoth);
            Assert.IsFalse((finalResult.Value as TestArgsWithREPL).BoolParam);
        }

        [TestMethod]
        public void TestModeledActionREPL()
        {
            int invokeCount = 0;

            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            definition.Metadata.Add(new TabCompletion() { REPL = true, Indicator = "$" });

            var action = new CommandLineAction((d) =>
            {
                Assert.AreEqual("go", d.SpecifiedAction.DefaultAlias);
                if (invokeCount == 0)
                {
                    Assert.AreEqual("Hawaii", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                else if (invokeCount == 1)
                {
                    Assert.AreEqual("Mexico", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                invokeCount++;
            });

            action.Aliases.Add("go");
            action.Description = "A simple action";

            definition.Actions.Add(action);

            var destination = new CommandLineArgument(typeof(string), "destination");
            destination.Metadata.Add(new ArgRequired());
            destination.Description = "The place to go to";

            action.Arguments.Add(destination);

            var provider = TestConsoleProvider.SimulateConsoleInput("g\t -dest\t Hawaii{enter}go -dest\t Mexico{enter}quit");
            Args.InvokeAction(definition, "$");
            Assert.AreEqual(2, invokeCount);
        }

        [TestMethod]
        public void TestArgAwareCompletionPositive()
        {
            TestConsoleProvider.SimulateConsoleInput("-name a\t");
            var parsed = Args.Parse<ArgAwareCompletionArgs>("$");
            Assert.AreEqual("Adam", parsed.Name);
        }

        [TestMethod]
        public void TestArgAwareCompletionNegative()
        {
            TestConsoleProvider.SimulateConsoleInput("-address a\t");
            var parsed = Args.Parse<ArgAwareCompletionArgs>("$");
            Assert.AreNotEqual("Adam", parsed.Address);
        }

        [TabCompletion(REPL = true, Indicator="$")]
        public class ArgsWithRequiredAndREPL
        {
            [ArgRequired(PromptIfMissing = true)]
            public string SomeArg { get; set; }

            public bool ExpectMainToBeCalled { get; set; }

            public void Main()
            {
                if (ExpectMainToBeCalled == false)
                {
                    throw new Exception("Main called!");
                }
                else
                {
                    Console.WriteLine("Main called!");
                }
            }
        }

        public class ArgsWithRequiredAndNoREPL
        {
            [ArgRequired(PromptIfMissing = true)]
            public string SomeArg { get; set; }

            public bool ExpectMainToBeCalled { get; set; }

            public void Main()
            {
                if (ExpectMainToBeCalled == false)
                {
                    throw new Exception("Main called!");
                }
                else
                {
                    Console.WriteLine("Main called!");
                }
            }
        }

        [TabCompletion(REPL = true, Indicator = "$")]
        public class ArgsWithRequiredAndREPLAndConditional
        {
            [ArgRequired(PromptIfMissing = true, If = "ExpectMainToBeCalled")]
            public string SomeArg { get; set; }

            public bool ExpectMainToBeCalled { get; set; }

            public void Main()
            {
                if (ExpectMainToBeCalled == false)
                {
                    throw new Exception("Main called!");
                }
                else
                {
                    Console.WriteLine("Main called!");
                }
            }
        }

        public class ArgsWithRequiredAndNoREPLAndConditional
        {
            [ArgRequired(PromptIfMissing = true, If = "ExpectMainToBeCalled")]
            public string SomeArg { get; set; }

            public bool ExpectMainToBeCalled { get; set; }

            public void Main()
            {
                if (ExpectMainToBeCalled == false)
                {
                    throw new Exception("Main called!");
                }
                else
                {
                    Console.WriteLine("Main called!");
                }
            }
        }

        [TestMethod]
        public void TestArgRequiredCancelBehaviorWithREPL()
        {
            TestConsoleProvider.SimulateConsoleInput("-e{enter}{escape}-s\t thearg -e{enter}quit");
            var action = Args.InvokeMain<ArgsWithRequiredAndREPL>("$");
            Assert.AreEqual("thearg", action.Args.SomeArg);
        }

        [TestMethod]
        public void TestArgRequiredCancelBehaviorWithNoREPL()
        {
            try
            {
                TestConsoleProvider.SimulateConsoleInput("{escape}");
                var action = Args.InvokeMain<ArgsWithRequiredAndREPL>("");
                Assert.Fail("An exception should have been thrown");
            }
            catch(MissingArgException ex)
            {
                Assert.IsTrue(ex.Message.ToLower().Contains("somearg"));
                Console.WriteLine("Yay!");
            }
        }

        [TestMethod]
        public void TestArgRequiredCancelBehaviorWithREPLAndConditional()
        {
            TestConsoleProvider.SimulateConsoleInput("-e{enter}{escape}-s\t thearg -e{enter}quit");
            var action = Args.InvokeMain<ArgsWithRequiredAndREPLAndConditional>("$");
            Assert.AreEqual("thearg", action.Args.SomeArg);
        }

        [TestMethod]
        public void TestArgRequiredCancelBehaviorWithNoREPLAndConditional()
        {
            try
            {
                TestConsoleProvider.SimulateConsoleInput("{escape}");
                var action = Args.InvokeMain<ArgsWithRequiredAndNoREPLAndConditional>("-e");
                Assert.Fail("An exception should have been thrown");
            }
            catch (MissingArgException ex)
            {
                Assert.IsTrue(ex.Message.ToLower().Contains("somearg"));
                Console.WriteLine("Yay!");
            }
        }

        private string Repeat(string s, int num)
        {
            string ret = "";
            for (int i = 0; i < num; i++)
            {
                ret += s;
            }
            return ret;
        }

        private void ClearHistory()
        {
            (typeof(TestArgs).GetCustomAttributes(typeof(TabCompletion), true)[0] as TabCompletion).ClearHistory();
        }
    }

    public class TestConsoleProvider : PowerArgs.IConsoleProvider
    {
        public event Action<string> WriteHappened;
        public event Action ClearHappened;

        public ConsoleColor ForegroundColor { get; set; }

        public ConsoleColor BackgroundColor { get; set; }

        public static TestConsoleProvider SimulateConsoleInput(string input)
        {
            var simulator = new TestConsoleProvider(input);
            ConsoleProvider.Current = simulator;
            return simulator;
        }

        string input;
        int i;

        public bool KeyAvailable
        {
            get
            {
                return i < input.Length;
            }
        }

        public TestConsoleProvider(string input = "")
        {
            this.input = input;
            i = 0;
            BufferWidth = 80;
        }

        public void Append(string text)
        {
            input = input + text;
        }

        public void Clear()
        {
            if (ClearHappened != null) ClearHappened();
        }

        public int CursorLeft { get; set; }
        public int CursorTop { get; set; }
        public int BufferWidth { get; set; }
        public int WindowHeight { get; set; }
        public int WindowWidth { get; set; }

        bool shift = false;
        bool control = false;
        public ConsoleKeyInfo ReadKey()
        {
            if (i == input.Length) return new ConsoleKeyInfo((char)0, ConsoleKey.Enter, false, false, false);
            var c = input[i++];
            ConsoleKey key = ConsoleKey.NoName;

            if (c == '\b') key = ConsoleKey.Backspace;
            else if (c == ' ') key = ConsoleKey.Spacebar;
            else if (c == '\t') key = ConsoleKey.Tab;
            else if (c == '{' && ReadAheadLookFor("delete}")) key = ConsoleKey.Delete;
            else if (c == '{' && ReadAheadLookFor("home}")) key = ConsoleKey.Home;
            else if (c == '{' && ReadAheadLookFor("end}")) key = ConsoleKey.End;
            else if (c == '{' && ReadAheadLookFor("escape}")) key = ConsoleKey.Escape;
            else if (c == '{' && ReadAheadLookFor("left}")) key = ConsoleKey.LeftArrow;
            else if (c == '{' && ReadAheadLookFor("right}")) key = ConsoleKey.RightArrow;
            else if (c == '{' && ReadAheadLookFor("up}")) key = ConsoleKey.UpArrow;
            else if (c == '{' && ReadAheadLookFor("down}")) key = ConsoleKey.DownArrow;
            else if (c == '{' && ReadAheadLookFor("enter}")) key = ConsoleKey.Enter;
            else if (c == '{' && ReadAheadLookFor("wait}"))
            {
                Thread.Sleep(1000);
                return ReadKey();
            }
            else if (c == '{' && ReadAheadLookFor("w}"))
            {
                Thread.Sleep(100);
                return ReadKey();
            }
            else if (c == '{' && ReadAheadLookFor("shift}"))
            {
                shift = true;
                var ret = ReadKey();
                shift = false;
                return ret;
            }
            else if (c == '{' && ReadAheadLookFor("control}"))
            {
                control = true;
                var ret = ReadKey();
                control = false;
                return ret;
            }

            return new ConsoleKeyInfo(c, key, shift, false, control);
        }

        private bool ReadAheadLookFor(string toFind)
        {
            int k = 0;
            for (int j = i; j < i + toFind.Length; j++)
            {
                if (input[j] != toFind[k++])
                {
                    return false;
                }
            }
            i += toFind.Length;
            return true;
        }

        public void Write(object output)
        {
            string text = output == null ? "" : output.ToString();
            CursorLeft += text.Length;

            if (WriteHappened != null)
            {
                WriteHappened(text);
            }
        }
        public void WriteLine(object output)
        {
            if(WriteHappened != null)
            {
                string text = output == null ? "" : output.ToString();
                WriteHappened(text);
            }

            CursorLeft = 0;
            CursorTop++;
        }
        public void WriteLine()
        {
            if (WriteHappened != null)
            {
                WriteHappened(Environment.NewLine);
            }

            CursorLeft = 0;
            CursorTop++;
        }

        public int Read()
        {
            throw new NotImplementedException();
        }

        public ConsoleKeyInfo ReadKey(bool intercept)
        {
            return ReadKey();
        }

        public string ReadLine()
        {
            throw new NotImplementedException();
        }

        public void Write(ConsoleString consoleString)
        {
            Write(consoleString.ToString());
        }

        public void Write(ConsoleCharacter consoleCharacter)
        {
            Write(consoleCharacter.ToString());
        }

        public void WriteLine(ConsoleString consoleString)
        {
            WriteLine(consoleString.ToString());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
title: TL;DR Legal
created_at: 2013-11-24 22:14
updated_at: 2013-11-24 22:14
kind: blog-post
summary: tl;dr Legal does an awesome job making the various open source licenses accessible and understandable.
tags:
 - link
redirect: true
redirect_path: http://www.tldrlegal.com/
---


text:
package com.gs.collections.impl.bag.immutable;

import com.gs.collections.api.bag.Bag;
import com.gs.collections.api.bag.ImmutableBag;
import com.gs.collections.impl.factory.Bags;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Test;

public class ImmutableBagFactoryTest
{
    @Test
    public void immutables()
    {
        ImmutableBag<Object> immutableBag = Bags.immutable.of();
        Verify.assertIterableSize(0, immutableBag);
        Verify.assertIterableSize(4, Bags.immutable.of(1, 2, 2, 3));
        ImmutableBag<Object> actual = Bags.immutable.ofAll(immutableBag);
        Assert.assertSame(immutableBag, actual);
        Assert.assertEquals(immutableBag, actual);
    }

    @Test
    public void singletonBagCreation()
    {
        Bag<String> singleton = Bags.immutable.of("a");
        Verify.assertInstanceOf(ImmutableSingletonBag.class, singleton);
    }
}


text:
package org.keycloak.quarkus.runtime.configuration.mappers;

import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper.fromOption;

import java.util.Optional;
import org.keycloak.config.ClassLoaderOptions;
import org.keycloak.config.SecurityOptions;
import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.configuration.Configuration;
import org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider;

import io.smallrye.config.ConfigSourceInterceptorContext;
import io.smallrye.config.ConfigValue;

final class ClassLoaderPropertyMappers {

    private ClassLoaderPropertyMappers(){}

    public static PropertyMapper[] getMappers() {
        return new PropertyMapper[] {
                fromOption(ClassLoaderOptions.IGNORE_ARTIFACTS)
                        .to("quarkus.class-loading.removed-artifacts")
                        .transformer(ClassLoaderPropertyMappers::resolveIgnoredArtifacts)
                        .build()
        };
    }

    private static Optional<String> resolveIgnoredArtifacts(Optional<String> value, ConfigSourceInterceptorContext context) {
        if (Environment.isRebuildCheck() || Environment.isRebuild()) {
            ConfigValue fipsEnabled = Configuration.getConfigValue(
                    MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX + SecurityOptions.FIPS_MODE.getKey());

            if (fipsEnabled != null && SecurityOptions.FipsMode.valueOf(fipsEnabled.getValue()).isFipsEnabled()) {
                return Optional.of(
                        "org.bouncycastle:bcprov-jdk15on,org.bouncycastle:bcpkix-jdk15on,org.keycloak:keycloak-crypto-default");
            }

            return Optional.of(
                    "org.keycloak:keycloak-crypto-fips1402,org.bouncycastle:bc-fips,org.bouncycastle:bctls-fips,org.bouncycastle:bcpkix-fips");
        }

        return value;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/item_title"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/item_content"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" />
<!--     <Button
        android:id="@+id/button_download"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/action_download" />
    <Button
        android:id="@+id/button_cancel"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/action_cancel" />
    <Button
        android:id="@+id/button_delete"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/action_delete" />  -->
</LinearLayout>


text:
Shingle::Shingle(WordIdx &wordIdx, const string id, const string line) :
    line(line), id(id), bit_representation(0), bit_representation_length(0) {

    // get ngram shingles and store indexes from word idx
    for(uint i=0; i<line.length()-N_GRAM_LENGTH+1; i++) {
        string shingle = line.substr(i,N_GRAM_LENGTH);
        int shingle_idx = wordIdx.idx_for_word(shingle);
        shingles.insert(shingle_idx);
    }

//    cout << "shingles... ";
//    for (set<int>::iterator i=shingles.begin(); i!=shingles.end(); ++i)
//        cout << "[" << *i << "] ";
//    cout << endl;
}

Shingle::~Shingle() {
    delete [] bit_representation;
}

ostream &operator <<(ostream &os, const Shingle &obj) {
    os << "line[" << obj.line << "] ";
    os << hex;
    for(int i=0; i<obj.bit_representation_length; i++) {
        os << obj.bit_representation[i] << " ";
    }
    return os;
}

string Shingle::getId() {
    return id;
}

void Shingle::build_bit_representation(const int max_bit) {
    //cout << "building shingle bits for [" << line << "]" << endl;

    // convert shingles list<int> to int[]
    const int as_array_length = shingles.size();
    int as_array[as_array_length];
    int idx = 0;
    for (set<int>::iterator iter=shingles.begin(); iter!=shingles.end(); ++iter)
        as_array[idx++] = *iter;

//    for(int i=0;i<as_array_length;i++)
//        cout << as_array[i] << " ";
//    cout << endl;

    // use ints to set bits in longs
    set_bits_multiple(as_array, as_array_length, max_bit);

}

float Shingle::resemblance_to(Shingle &other) {
    //if (bit_representation_length != other.bit_representation_length) cerr << "expected the same!";
    //cout << "is=" << intersection_size(other) << " us=" << union_size(other) << endl;
    return (float) intersection_size(other) / union_size(other);
}

int Shingle::union_size(Shingle &other) {
    int num_bits = 0;
    long *ours = bit_representation;
    long *others = other.bit_representation;
    for(int i=0; i<bit_representation_length; i++)
        num_bits += count_number_bits_set(*ours++ | *others++);
    return num_bits;
}

int Shingle::intersection_size(Shingle &other) {
    int num_bits = 0;
    long *ours = bit_representation;
    long *others = other.bit_representation;
    for(int i=0; i<bit_representation_length; i++)
        num_bits += count_number_bits_set(*ours++ & *others++);
    return num_bits;
}

void Shingle::set_bits_multiple(int bits[], int bits_length, int max_bit) {
    bit_representation_length = (max_bit / N) +1;
    bit_representation = new long[bit_representation_length];
    for(int i=0;i<bit_representation_length;i++)
        bit_representation[i]=0;

    for(int i=0; i<bits_length; i++) {
        // in the case of vals_length >1 we want to pack
        // higher order bits in the left most array elements, eg higher order
        // bits in a lower array index
        int long_to_set = bit_representation_length-1 - (bits[i] / N);
        int bit_to_set = bits[i] % N;
//        printf("bit_representation_length %d bit %d long_to_set %d bit_to_set %d\n",bit_representation_length,bits[i],long_to_set,bit_to_set);

        // create mask and apply it to actual value
        long mask = 1;
        mask <<= bit_to_set;
        bit_representation[long_to_set] |= mask;

//        for(int i=0; i<bit_representation_length; i++) {
//            print_bits(bit_representation[i]);
//            printf("|");
//        }
//        printf("\n");

    }
}

void Shingle::print_bits(long l) {
    for (int i=N-1; i>=0; i--) {
        printf("%s",((l >> i) & 1) ? "1" : "0");
        if (i%4==0 && i!=0) printf(" ");
    }
    //printf("\n");
}


text:
import java.awt.Color;

public interface HowToColor {
	public Color getColor(int index, Color[] colorSet);
}


text:
#ifndef STAN_MATH_OPENCL_PRIM_GP_EXPONENTIAL_COV_HPP
#define STAN_MATH_OPENCL_PRIM_GP_EXPONENTIAL_COV_HPP
#ifdef STAN_OPENCL

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/square.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/kernels/gp_exponential_cov.hpp>
#include <stan/math/opencl/err.hpp>
#include <CL/opencl.hpp>

namespace stan {
namespace math {
/** \ingroup opencl
 * Matern exponential kernel on the GPU.
 *
 * @tparam T1 Type of the matrix
 * @tparam T2 Type of sigma
 * @tparam T3 Type of length_scale
 * @param x input vector or matrix
 * @param sigma standard deviation
 * @param length_scale length scale
 *
 * @return dot product covariance matrix that is positive semi-definite
 */
template <typename T1, typename T2, typename T3,
          require_all_kernel_expressions_and_none_scalar_t<T1>* = nullptr,
          require_all_arithmetic_t<T2, T3>* = nullptr>
inline matrix_cl<return_type_t<T1, T2, T3>> gp_exponential_cov(
    const T1& x, const T2 sigma, const T3 length_scale) {
  const auto& x_eval = x.eval();
  matrix_cl<return_type_t<T1, T2, T3>> res(x.cols(), x.cols());
  int block_size = 16;
  int n_blocks = (x.cols() + block_size - 1) / block_size;
  int blocked_size = block_size * n_blocks;
  try {
    opencl_kernels::gp_exponential_cov(cl::NDRange(blocked_size, blocked_size),
                                       cl::NDRange(block_size, block_size),
                                       x_eval, res, sigma * sigma,
                                       -1.0 / length_scale, x.cols(), x.rows());
  } catch (const cl::Error& e) {
    check_opencl_error("gp_exponential_cov", e);
  }
  return res;
}

/** \ingroup opencl
 * Matern exponential kernel on the GPU.
 *
 * This function is for the cross covariance
 * matrix needed to compute the posterior predictive density.
 *
 * @tparam T1 Type of the first matrix
 * @tparam T2 Type of the second matrix
 * @tparam T3 Type of sigma
 * @tparam T4 Type of length scale
 * @param x first input vector or matrix
 * @param y second input vector or matrix
 * @param sigma standard deviation
 * @param length_scale length scale
 *
 * @return dot product covariance matrix
 */
template <typename T1, typename T2, typename T3, typename T4,
          require_all_kernel_expressions_and_none_scalar_t<T1, T2>* = nullptr,
          require_all_arithmetic_t<T3, T4>* = nullptr>
inline matrix_cl<return_type_t<T1, T2, T3, T4>> gp_exponential_cov(
    const T1& x, const T2& y, const T3 sigma, const T4 length_scale) {
  check_size_match("gp_exponential_cov_cross", "x", x.rows(), "y", y.rows());
  matrix_cl<return_type_t<T1, T2, T3, T4>> res(x.cols(), y.cols());
  const auto& x_eval = x.eval();
  const auto& y_eval = y.eval();
  int block_size = 16;
  int x_blocks = (x.cols() + block_size - 1) / block_size;
  int x_blocked_size = block_size * x_blocks;
  int y_blocks = (y.cols() + block_size - 1) / block_size;
  int y_blocked_size = block_size * y_blocks;
  try {
    opencl_kernels::gp_exponential_cov_cross(
        cl::NDRange(x_blocked_size, y_blocked_size),
        cl::NDRange(block_size, block_size), x_eval, y_eval, res, sigma * sigma,
        -1.0 / length_scale, x.cols(), y.cols(), x.rows());
  } catch (const cl::Error& e) {
    check_opencl_error("gp_exponential_cov_cross", e);
  }
  return res;
}

/** \ingroup opencl
 * Squared exponential kernel on the GPU.
 *
 * @tparam T1 Type of the matrix
 * @tparam T2 Type of sigma
 * @tparam T3 Type of length_scale
 * @param x input vector or matrix
 * @param sigma standard deviation
 * @param length_scale length scale
 *
 * @return Squared distance between elements of x.
 */
template <typename T1, typename T2, typename T3,
          require_all_kernel_expressions_and_none_scalar_t<T1, T3>* = nullptr,
          require_all_arithmetic_t<T2>* = nullptr>
inline matrix_cl<return_type_t<T1, T2, T3>> gp_exponential_cov(
    const T1& x, const T2 sigma, const T3 length_scale) {
  const auto& x_eval = elt_divide(x, rowwise_broadcast(length_scale)).eval();
  matrix_cl<return_type_t<T1, T2, T3>> res(x.cols(), x.cols());
  int block_size = 16;
  int n_blocks = (x.cols() + block_size - 1) / block_size;
  int blocked_size = block_size * n_blocks;
  try {
    opencl_kernels::gp_exponential_cov(cl::NDRange(blocked_size, blocked_size),
                                       cl::NDRange(block_size, block_size),
                                       x_eval, res, sigma * sigma, -1.0,
                                       x.cols(), x.rows());
  } catch (const cl::Error& e) {
    check_opencl_error("gp_exponential_cov", e);
  }
  return res;
}

/** \ingroup opencl
 * Squared exponential kernel on the GPU.
 *
 * This function is for the cross covariance
 * matrix needed to compute the posterior predictive density.
 *
 * @tparam T1 Type of the first matrix
 * @tparam T2 Type of the second matrix
 * @tparam T3 Type of sigma
 * @tparam T4 Type of length scale
 * @param x first input vector or matrix
 * @param y second input vector or matrix
 * @param sigma standard deviation
 * @param length_scale length scale
 *
 * @return Squared distance between elements of x and y.
 */
template <
    typename T1, typename T2, typename T3, typename T4,
    require_all_kernel_expressions_and_none_scalar_t<T1, T2, T4>* = nullptr,
    require_all_arithmetic_t<T3>* = nullptr>
inline matrix_cl<return_type_t<T1, T2, T3, T4>> gp_exponential_cov(
    const T1& x, const T2& y, const T3 sigma, const T4 length_scale) {
  check_size_match("gp_exponential_cov_cross", "x", x.rows(), "y", y.rows());
  matrix_cl<return_type_t<T1, T2, T3, T4>> res(x.cols(), y.cols());
  const auto& x_eval = elt_divide(x, rowwise_broadcast(length_scale)).eval();
  const auto& y_eval = elt_divide(y, rowwise_broadcast(length_scale)).eval();
  int block_size = 16;
  int x_blocks = (x.cols() + block_size - 1) / block_size;
  int x_blocked_size = block_size * x_blocks;
  int y_blocks = (y.cols() + block_size - 1) / block_size;
  int y_blocked_size = block_size * y_blocks;
  try {
    opencl_kernels::gp_exponential_cov_cross(
        cl::NDRange(x_blocked_size, y_blocked_size),
        cl::NDRange(block_size, block_size), x_eval, y_eval, res, sigma * sigma,
        -1.0, x.cols(), y.cols(), x.rows());
  } catch (const cl::Error& e) {
    check_opencl_error("gp_exponential_cov_cross", e);
  }
  return res;
}

}  // namespace math
}  // namespace stan

#endif
#endif


text:
$snapin = Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue -PassThru

if ($snapin -eq $null) {
    Write-Error "Unable to load the Microsoft.SharePoint.PowerShell Snapin! Have you installed SharePoint?"
    return
}

# add SQL Server login for WINGTIP\SP_Workflow
# add this login to roles of securityadmin and dbcreator
$sql = "CREATE LOGIN [WINGTIP\SP_Workflow] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
        GO
        ALTER SERVER ROLE [securityadmin] ADD MEMBER [WINGTIP\SP_Workflow]
        GO
        ALTER SERVER ROLE [dbcreator] ADD MEMBER [WINGTIP\SP_Workflow]"

# invoke this SQL command
Write-Host "Granting SP_Workflow dbcreator and securityadmin rights..."
Invoke-Sqlcmd -ServerInstance "WINGTIPSERVER\SharePoint" -Query $sql

# determine path to CreateWorkflowFarmScript.ps1
$currentScriptPath = $MyInvocation.MyCommand.Path
$scriptFolder = Split-Path $currentScriptPath
$targetScriptPath = Join-Path $scriptFolder "\Script10_CreateWorkflowFarmScript.ps1"

Write-Host
Write-Host "Executing script $targetScriptPath using credentials of SP_Workflow"
Write-Host "This script will execute within its own window"

# Get the Farm Account Creds
$serviceAccountName = "WINGTIP\SP_Workflow"
$serviceAccountPassword = "Password1"
$serviceAccountSecureStringPassword = ConvertTo-SecureString -String $serviceAccountPassword -AsPlainText -Force
$serviceAccountCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $serviceAccountName, $serviceAccountSecureStringPassword

# Create a new process with UAC elevation
Start-Process $PSHOME\powershell.exe `
                -Credential $serviceAccountCredentials `
                -ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$targetScriptPath'`" -Verb Runas" -Wait

Write-Host
Write-Host "Workflow farm has now been created. Now you can run the script to register the workflow farm with the local SharePoint farm"
Write-Host

Write-Host
Read-Host -Prompt "Press ENTER to continue"


text:
package util.validator;

import net.itarray.automotion.internal.AbstractValidator;
import net.itarray.automotion.internal.DriverFacade;
import net.itarray.automotion.internal.UIValidatorBase;
import net.itarray.automotion.internal.geometry.Scalar;
import net.itarray.automotion.validation.UIElementValidator;
import net.itarray.automotion.validation.UISnapshot;
import net.itarray.automotion.validation.properties.Condition;
import org.openqa.selenium.WebElement;
import net.itarray.automotion.validation.properties.Padding;

import java.util.List;

/**
 */
@Deprecated
public class UIValidator extends AbstractValidator implements Validator {

    public UIValidator(UISnapshot snapshot, DriverFacade driver, WebElement webElement, String readableNameOfElement) {
        super(driver, new UIValidatorBase(snapshot, webElement, readableNameOfElement));
    }

    protected UIValidatorBase getBase() {
        return (UIValidatorBase) super.getBase();
    }

    @Override
    public UIValidator drawMap() {
        super.drawMap();
        return this;
    }

    @Override
    public UIValidator dontDrawMap() {
        super.dontDrawMap();
        return this;
    }

    /**
     * Change units to Pixels or % (Units.PX, Units.PERCENT)
     *
     * @param units
     * @return UIValidator
     */
    @Override
    public UIValidator changeMetricsUnitsTo(Units units) {
        getBase().changeMetricsUnitsTo(units);
        return this;
    }

    @Override
    public UIValidator changeMetricsUnitsTo(net.itarray.automotion.validation.Units units) {
        getBase().changeMetricsUnitsTo(units);
        return this;
    }

    /**
     * Verify that element which located left to is correct
     *
     * @param element
     * @return UIValidator
     */
    @Override
    public UIValidator isRightOf(WebElement element) {
        getBase().isRightOf(element);
        return this;
    }

    @Override
    public UIValidator isRightOf(WebElement element, Condition<Scalar> distanceCondition) {
        getBase().isRightOf(element, distanceCondition);
        return this;
    }

    /**
     * Verify that element which located right to is correct
     *
     * @param element
     * @return UIValidator
     */
    @Override
    public UIValidator isLeftOf(WebElement element) {
        getBase().isLeftOf(element);
        return this;
    }

    @Override
    public UIValidator isLeftOf(WebElement element, Condition<Scalar> distanceCondition) {
        getBase().isLeftOf(element, distanceCondition);
        return this;
    }

    /**
     * Verify that element which located top to is correct
     *
     * @param element
     * @return UIValidator
     */
    @Override
    public UIValidator isBelow(WebElement element) {
        getBase().isBelow(element);
        return this;
    }

    @Override
    public UIValidator isBelow(WebElement element, Condition<Scalar> distanceCondition) {
        getBase().isBelow(element, distanceCondition);
        return this;
    }

    /**
     * Verify that element which located bottom to is correct
     *
     * @param element
     * @return UIValidator
     */
    @Override
    public UIValidator isAbove(WebElement element) {
        getBase().isAbove(element);
        return this;
    }

    @Override
    public UIElementValidator isAbove(WebElement element, Condition<Scalar> distanceCondition) {
        getBase().isAbove(element, distanceCondition);
        return this;
    }

    /**
     * Verify that element is NOT overlapped with specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isNotOverlapping(WebElement element, String readableName) {
        getBase().isNotOverlapping(element, readableName);
        return this;
    }

    /**
     * Verify that element is overlapped with specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isOverlapping(WebElement element, String readableName) {
        getBase().isOverlapping(element, readableName);
        return this;
    }

    /**
     * Verify that element is NOT overlapped with every element is the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator isNotOverlapping(List<WebElement> elements) {
        getBase().isNotOverlapping(elements);
        return this;
    }

    /**
     * Verify that element has the same left offset as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isLeftAlignedWith(WebElement element, String readableName) {
        getBase().isLeftAlignedWith(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same left offset as every element is the list
     *
     * @param webElements
     * @return UIValidator
     */
    @Override
    public UIValidator isLeftAlignedWith(List<WebElement> webElements) {
        getBase().isLeftAlignedWith(webElements);
        return this;
    }

    /**
     * Verify that element has the same right offset as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isRightAlignedWith(WebElement element, String readableName) {
        getBase().isRightAlignedWith(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same right offset as every element is the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator isRightAlignedWith(List<WebElement> elements) {
        getBase().isRightAlignedWith(elements);
        return this;
    }

    /**
     * Verify that element has the same top offset as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isTopAlignedWith(WebElement element, String readableName) {
        getBase().isTopAlignedWith(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same top offset as every element is the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator isTopAlignedWith(List<WebElement> elements) {
        getBase().isTopAlignedWith(elements);
        return this;
    }

    /**
     * Verify that element has the same bottom offset as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator isBottomAlignedWith(WebElement element, String readableName) {
        getBase().isBottomAlignedWith(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same bottom offset as every element is the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator isBottomAlignedWith(List<WebElement> elements) {
        getBase().isBottomAlignedWith(elements);
        return this;
    }

    /**
     * Verify that element has the same width as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualWidthAs(WebElement element, String readableName) {
        getBase().hasEqualWidthAs(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same width as every element in the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualWidthAs(List<WebElement> elements) {
        getBase().hasEqualWidthAs(elements);
        return this;
    }

    @Override
    public UIElementValidator hasWidth(Condition<Scalar> condition) {
        getBase().hasWidth(condition);
        return this;
    }

    /**
     * Verify that element has the same height as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualHeightAs(WebElement element, String readableName) {
        getBase().hasEqualHeightAs(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same height as every element in the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualHeightAs(List<WebElement> elements) {
        getBase().hasEqualHeightAs(elements);
        return this;
    }

    @Override
    public UIValidator hasHeight(Condition<Scalar> condition) {
        getBase().hasHeight(condition);
        return this;
    }

    /**
     * Verify that element has the same size as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualSizeAs(WebElement element, String readableName) {
        getBase().hasEqualSizeAs(element, readableName);
        return this;
    }

    /**
     * Verify that element has the same size as every element in the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator hasEqualSizeAs(List<WebElement> elements) {
        getBase().hasEqualSizeAs(elements);
        return this;
    }

    /**
     * Verify that element has not the same size as specified element
     *
     * @param element
     * @param readableName
     * @return UIValidator
     */
    @Override
    public UIValidator hasDifferentSizeAs(WebElement element, String readableName) {
        getBase().hasDifferentSizeAs(element, readableName);
        return this;
    }

    /**
     * Verify that element has not the same size as every element in the list
     *
     * @param elements
     * @return UIValidator
     */
    @Override
    public UIValidator hasDifferentSizeAs(List<WebElement> elements) {
        getBase().hasDifferentSizeAs(elements);
        return this;
    }

    /**
     * Verify that min offset of element is not less than (min value is -10000)
     *
     * @param top
     * @param right
     * @param bottom
     * @param left
     * @return UIValidator
     */
    @Override
    public UIValidator minOffset(int top, int right, int bottom, int left) {
        getBase().minOffset(top, right, bottom, left);
        return this;
    }

    @Override
    public UIElementValidator hasLeftOffsetToPage(Condition<Scalar> condition) {
        getBase().hasLeftOffsetToPage(condition);
        return this;
    }

    @Override
    public UIElementValidator hasRightOffsetToPage(Condition<Scalar> condition) {
        getBase().hasRightOffsetToPage(condition);
        return this;
    }

    @Override
    public UIElementValidator hasTopOffsetToPage(Condition<Scalar> condition) {
        getBase().hasTopOffsetToPage(condition);
        return this;
    }

    @Override
    public UIElementValidator hasBottomOffsetToPage(Condition<Scalar> condition) {
        getBase().hasBottomOffsetToPage(condition);
        return this;
    }

    /**
     * Verify that max offset of element is not bigger than (min value is -10000)
     *
     * @param top
     * @param right
     * @param bottom
     * @param left
     * @return UIValidator
     */
    @Override
    public UIValidator maxOffset(int top, int right, int bottom, int left) {
        getBase().maxOffset(top, right, bottom, left);
        return this;
    }

    /**
     * Verify that element has correct CSS values
     *
     * @param cssProperty
     * @param args
     * @return UIValidator
     */
    @Override
    public UIValidator hasCssValue(String cssProperty, String... args) {
        getBase().hasCssValue(cssProperty, args);
        return this;
    }

    /**
     * Verify that concrete CSS values are absent for specified element
     *
     * @param cssProperty
     * @param args
     * @return UIValidator
     */
    @Override
    public UIValidator doesNotHaveCssValue(String cssProperty, String... args) {
        getBase().doesNotHaveCssValue(cssProperty, args);
        return this;
    }

    /**
     * Verify that element has equal left and right offsets (e.g. Bootstrap container)
     *
     * @return UIValidator
     */
    @Override
    public UIValidator isCenteredOnPageHorizontally() {
        getBase().isCenteredOnPageHorizontally();
        return this;
    }

    /**
     * Verify that element has equal top and bottom offset (aligned vertically in center)
     *
     * @return UIValidator
     */
    @Override
    public UIValidator isCenteredOnPageVertically() {
        getBase().isCenteredOnPageVertically();
        return this;
    }

    /**
     * Verify that element(s) is(are) located inside of specified element
     *
     * @param containerElement
     * @param readableContainerName
     * @return ResponsiveUIValidator
     */
    @Override
    public UIValidator isInsideOf(WebElement containerElement, String readableContainerName) {
        getBase().isInsideOf(containerElement, readableContainerName);
        return this;
    }

    @Override
    public UIValidator isInsideOf(WebElement containerElement, String readableContainerName, Padding padding) {
        getBase().isInsideOf(containerElement, readableContainerName, padding);
        return this;
    }
}


text:
(Since v2.2)

This indexing algorithm is based on the [DHT concept](https://en.wikipedia.org/wiki/Distributed_hash_table), where they keys are stored on different partition, based on the [Murmur3](https://en.wikipedia.org/wiki/MurmurHash) hash function.

Auto Sharding Index supports the following index types:
- `UNIQUE_HASH_INDEX` Does not allow duplicate keys, it fails when it encounters duplicates.
- `NOTUNIQUE_HASH_INDEX` Does allow duplicate keys.

Under the hood, this index creates multiple [Hash Indexes](Hash-Index.md), one per cluster. So if you have 8 clusters for the class "Employee", this index will create, at the beginning, 8 [Hash Indexes](Hash-Index.md).

Since this index is based on the [Hash Index](Hash-Index.md), it's able to perform index read operations in one I/O operation and write operations in a maximum of three I/O operations. The Hash Index algorithm is based on the [Extendible Hashing](http://en.wikipedia.org/wiki/Extendible_hashing) algorithm.  Despite not providing support for range queries, it is noticeably faster than [SB-Tree Index Algorithms](SB-Tree-index.md), (about twice as fast when querying through ten million records).

## Usage

Create an index by passing "AUTOSHARDING" as index engine:

```java
final OClass cls = db.createClass("Log");
cls.createProperty("key", OType.LONG);
cls.createIndex("idx_LogKey", OClass.INDEX_TYPE.UNIQUE.toString(),
    (OProgressListener) null, (ODocument) null, "AUTOSHARDING", new String[] { "key" });
```

## Performance

On multi-core hw, using this index instead of [Hash Index](Hash-Index.md) gives about +50% more throughput on insertion on a 8 cores machine.

## Distributed

The fully distributed version of this index will be supported in v3.0. In v2.2 each node has own copy of the index with all the partitions.

## Internals

This is the algorithm for the `put(key,value)`:

```
int partition = Murmur3_hash(key) % partitions;
getSubIndex(partition).put(key,value);
```

This is for the `value = get(key)`:
```
int partition = Murmur3_hash(key) % partitions;
return getSubIndex(partition).get(key);
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using DbLinq.Data.Linq.Sugar.ExpressionMutator;
using DbLinq.Data.Linq.Sugar.Expressions;

namespace DbLinq.Data.Linq.Sugar.ExpressionMutator
{
    /// <summary>
    /// Extensions to Expression, to enumerate and dynamically change operands in a uniformized way
    /// </summary>
    internal static class ExpressionMutatorExtensions
    {
        /// <summary>
        /// Enumerates all subexpressions related to this one
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static IEnumerable<Expression> GetOperands(this Expression expression)
        {
            if (expression is MutableExpression)
                return new List<Expression>(((MutableExpression)expression).Operands);
            return ExpressionMutatorFactory.GetMutator(expression).Operands;
        }

        /// <summary>
        /// Changes all operands
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="operands"></param>
        /// <param name="checkForChanges"></param>
        /// <returns>A potentially new expression with new operands</returns>
        public static T ChangeOperands<T>(this T expression, IList<Expression> operands, bool checkForChanges)
            where T : Expression
        {
            bool haveOperandsChanged = checkForChanges && HaveOperandsChanged(expression, operands);
            if (!haveOperandsChanged)
                return expression;
            var mutableExpression = expression as IMutableExpression;
            if (mutableExpression != null)
                return (T)mutableExpression.Mutate(operands);
            return (T)ExpressionMutatorFactory.GetMutator(expression).Mutate(operands);
        }

        /// <summary>
        /// Determines if operands have changed for a given expression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="operands"></param>
        /// <returns></returns>
        private static bool HaveOperandsChanged<T>(T expression, IList<Expression> operands)
            where T : Expression
        {
            var oldOperands = GetOperands(expression).ToList();
            if (operands.Count != oldOperands.Count)
                return true;

            for (int operandIndex = 0; operandIndex < operands.Count; operandIndex++)
            {
                if (operands[operandIndex] != oldOperands[operandIndex])
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Changes all operands
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="operands"></param>
        /// <returns>A potentially new expression with new operands</returns>
        public static T ChangeOperands<T>(this T expression, IList<Expression> operands)
            where T : Expression
        {
            return ChangeOperands(expression, operands, true);
        }

        /// <summary>
        /// Changes all operands
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="operands"></param>
        /// <returns>A potentially new expression with new operands</returns>
        public static T ChangeOperands<T>(this T expression, params Expression[] operands)
            where T : Expression
        {
            return ChangeOperands(expression, operands, true);
        }

        /// <summary>
        /// Returns the expression result
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static object Evaluate(this Expression expression)
        {
            var executableExpression = expression as IExecutableExpression;
            if (executableExpression != null)
                return executableExpression.Execute();
            try
            {
                // here, we may have non-evaluable expressions, so we "try"/"catch"
                // (maybe should we find something better)
                var lambda = Expression.Lambda(expression);
                var compiled = lambda.Compile();
                var value = compiled.DynamicInvoke();
                return value;
            }
            catch
            {
                throw new ArgumentException();
            }
        }

        /// <summary>
        /// Down-top pattern analysis.
        /// </summary>
        /// <param name="expression">The original expression</param>
        /// <param name="analyzer"></param>
        /// <returns>A new QueryExpression or the original one</returns>
        public static Expression Recurse(this Expression expression, Func<Expression, Expression> analyzer)
        {
            var newOperands = new List<Expression>();
            // first, work on children (down)
            foreach (var operand in GetOperands(expression))
            {
                if (operand != null)
                    newOperands.Add(Recurse(operand, analyzer));
                else
                    newOperands.Add(null);
            }
            // then on expression itself (top)
            return analyzer(expression.ChangeOperands(newOperands));
        }
    }
}


text:
<?

require_once('../includes/base.php');
require_once('../database/Funcionarios.php');

// check privileges
if ($s_type != "admin" && ($s_type != "staff")) {
  $_SESSION["s_errors"]["generic"][] = 'Não tem permissões';
  header("Location: ../index.php");
  die;
}

$funcionarios1 = Funcionarios::listEmployees();

$smarty->assign("funcionarios1", $funcionarios1);

$smarty->display('funcionarios/list.tpl');

?>


text:
<?php

namespace AppBundle\Filter\Common\Assignments;

use AppBundle;
use AppBundle\Filter\Common\Base\SimpleFilter;
use Symfony\Component\HttpFoundation\Request;

class ProductCategoryAssignmentFilter extends SimpleFilter {

	/**
	 *
	 * @var array
	 */
	protected $products = array();

	/**
	 *
	 * @var array
	 */
	protected $brands = array();

	/**
	 *
	 * @var array
	 */
	protected $segments = array();

	/**
	 *
	 * @var array
	 */
	protected $categories = array();

	/**
	 *
	 * @var integer
	 */
	protected $featured = self::ALL_VALUES;

	public function initRequestValues(Request $request) {
		parent::initRequestValues($request);

		$this->products = $this->getRequestArray($request, 'products');
		$this->brands = $this->getRequestArray($request, 'brands');
		$this->segments = $this->getRequestArray($request, 'segments');
		$this->categories = $this->getRequestArray($request, 'categories');

		$this->featured = $this->getRequestBool($request, 'featured');
	}

	public function clearRequestValues() {
		parent::clearRequestValues();

		$this->products = array();
		$this->brands = array();
		$this->segments = array();
		$this->categories = array();

		$this->featured = self::ALL_VALUES;
	}

	public function getRequestValues() {
		$values = parent::getRequestValues();

		$this->setRequestArray($values, 'products', $this->products);
		$this->setRequestArray($values, 'brands', $this->brands);
		$this->setRequestArray($values, 'segments', $this->segments);
		$this->setRequestArray($values, 'categories', $this->categories);

		$this->setRequestBool($values, 'featured', $this->featured);

		return $values;
	}

	public function setProducts($products) {
		$this->products = $products;

		return $this;
	}

	public function getProducts() {
		return $this->products;
	}

	public function setBrands($brands) {
		$this->brands = $brands;

		return $this;
	}

	public function getBrands() {
		return $this->brands;
	}

	public function setSegments($segments) {
		$this->segments = $segments;

		return $this;
	}

	public function getSegments() {
		return $this->segments;
	}

	public function setCategories($categories) {
		$this->categories = $categories;

		return $this;
	}

	public function getCategories() {
		return $this->categories;
	}

	public function setFeatured($featured) {
		$this->featured = $featured;

		return $this;
	}

	public function getFeatured() {
		return $this->featured;
	}
}


text:
'''
arrows: left, right, up, down: 2424832, 2555904, 2490368, 2621440
'''

import sys, os, re
import numpy as np
import cv2

tuneStuff = True

calFileDir = 'C:/Users/Nate/Documents/GitHub/arduino/shinyei-ppd42ns-arduino/testing/with fan/calibration-machine vision/calibration images/' # file with calibration images
images = []
for thing in os.listdir(calFileDir):
    if os.path.isfile(calFileDir + thing) and not re.search('thumbs',thing,re.IGNORECASE):
        images.append(thing)

samples =  np.empty((0,100))
responses = []

for imFile in images:
    print imFile
    im = cv2.imread(calFileDir + imFile)
    im = im[50:-50,0:-1]
    #im = im[100:-100, 150:-150] # for cropping file
    im3 = im.copy()

    gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

    # for snaps from honestech tvr software
    #gaussW = 75
    #gaussH = 75
    # from dvdriver software
    gaussW = 35
    gaussH = 35
    blur = cv2.GaussianBlur(gray,(gaussW,gaussH),0)

    if tuneStuff:
        # choose gaussian blur amount
        while True:
            #blur = cv2.bilateralFilter(im,9,gaussW,gaussH)
            cv2.imshow('norm',blur)
            key = cv2.waitKey()
            if key == 27:
                break
            if key == 2424832: # left arrow
                if gaussW > 1:
                    gaussW -= 2
            if key == 2555904: # right arrow
                gaussW += 2
            if key == 2621440: # down arrow
                if gaussH > 1:
                    gaussH -=2
            if key == 2490368: # up arrow
                gaussH += 2
            cv2.destroyAllWindows()
            blur = cv2.GaussianBlur(gray,(gaussW,gaussH),0)
            print 'gaussH, gaussW: ', gaussH, gaussW

    # choose threshold block size and constant
    # 43, -4 for snaps from honestech tvr program, 33, -4 for snaps from dvdriver
    blockSize = 59
    const = -6
    cv2.destroyAllWindows()
    thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,blockSize,const)
    if tuneStuff:
        while True:
            cv2.destroyAllWindows()
            thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,blockSize,const)
            cv2.imshow('norm',thresh)
            thresh2 = thresh.copy()
            contours, hierarchy = cv2.findContours(thresh2,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                [x,y,w,h] = cv2.boundingRect(cnt)
                roi = thresh2[y:y+h,x:x+w]
                roismall = cv2.resize(roi,(10,10))
                cv2.rectangle(thresh,(x,y),(x+w,y+h),(0,0,255),2)
            key = cv2.waitKey()
            print key
            if key == 27:
                break
            if key == 2424832: # left arrow
                if blockSize > 3:
                    blockSize -= 2
            if key == 2555904: # right arrow
                blockSize += 2
            if key == 2621440: # down arrow
                const -=1
            if key == 2490368: # up arrow
                const += 1
            print 'block size:', blockSize
            print 'const: ', const

    cv2.destroyAllWindows()

    #################      Now finding Contours         ###################

    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    keys = [i for i in range(48,58)]
    def getBoundRect(item):
        # returns 'x' value of bounding rectangle of contour
        return cv2.boundingRect(item)[0]

    srtedCntrs = sorted(contours, key = getBoundRect)
    for cnt in srtedCntrs:
        if cv2.contourArea(cnt)>100:
            [x,y,w,h] = cv2.boundingRect(cnt)

            if  h>50:
                cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
                roi = thresh[y:y+h,x:x+w]
                roismall = cv2.resize(roi,(10,10))
                cv2.imshow('norm',im)
                key = cv2.waitKey(0)

                if key == 27:  # (escape to quit)
                    sys.exit()
                elif key in keys:
                    responses.append(int(chr(key)))
                    sample = roismall.reshape((1,100))
                    samples = np.append(samples,sample,0)
                elif key == 98: # if 'b' key is pressed, it is a square
                    continue
                    responses.append(key)
                    sample = roismall.reshape((1,100))
                    samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print 'responses:', responses
print 'samples:', samples
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)


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

	<groupId>com.fjroa</groupId>
	<artifactId>ghost</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ghost</name>
	<description>Ghost Game for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- hot swapping, disable cache for template, enable live reload -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>2.2.4</version>
		</dependency>

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery-ui</artifactId>
			<version>1.9.2</version>
		</dependency>

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>bootstrap</artifactId>
			<version>3.3.7</version>
		</dependency>

		<dependency>
			<groupId>org.webjars.bower</groupId>
			<artifactId>flag-icon-css</artifactId>
			<version>2.8.0</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>app.ptd.server</groupId>
		<artifactId>ptd-server</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath/>
	</parent>

	<artifactId>web-remote-resources</artifactId>

	<packaging>war</packaging>
	<name>Public Transport Delays - Remote resources</name>
	<url>https://github.com/mvolejnik/public-transport-delays</url>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

	<build>
		<finalName>web-remote-resources</finalName>
		<plugins>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<webApp>
						<contextPath>/scheduler</contextPath>
					</webApp>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>app.ptd.server</groupId>
			<artifactId>lib-status-updates</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
                <dependency>
			<groupId>app.ptd.server</groupId>
			<artifactId>lib-remote-resources</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz-jobs</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>
		<dependency>
			<groupId>io.dropwizard.metrics</groupId>
			<artifactId>metrics-core</artifactId>
		</dependency>
        <!-- jetty dependencies -->
        <dependency>
           <groupId>jakarta.xml.bind</groupId>
            <artifactId>jakarta.xml.bind-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
             <artifactId>jaxb-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.activation</groupId>
            <artifactId>jakarta.activation</artifactId>
        </dependency>
	 <dependency>
	  <groupId>org.junit.jupiter</groupId>
	  <artifactId>junit-jupiter-api</artifactId>
	  <version>5.3.1</version>
	  <scope>test</scope>
	 </dependency>
	 <dependency>
	  <groupId>org.junit.jupiter</groupId>
	  <artifactId>junit-jupiter-params</artifactId>
	  <version>5.3.1</version>
	  <scope>test</scope>
	 </dependency>
	 <dependency>
	  <groupId>org.junit.jupiter</groupId>
	  <artifactId>junit-jupiter-engine</artifactId>
	  <version>5.3.1</version>
	  <scope>test</scope>
	 </dependency>
	</dependencies>
</project>


text:
package org.springframework.orm.hibernate3;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * This interceptor binds a new Hibernate Session to the thread before a method
 * call, closing and removing it afterwards in case of any method outcome.
 * If there already is a pre-bound Session (e.g. from HibernateTransactionManager,
 * or from a surrounding Hibernate-intercepted method), the interceptor simply
 * participates in it.
 *
 *
Application code must retrieve a Hibernate Session via the
 * {@code SessionFactoryUtils.getSession} method or - preferably -
 * Hibernate's own {@code SessionFactory.getCurrentSession()} method, to be
 * able to detect a thread-bound Session. Typically, the code will look like as follows:
 *
 *

 * public void doSomeDataAccessAction() {
 *   Session session = this.sessionFactory.getCurrentSession();
 *   ...
 *   // No need to close the Session or translate exceptions!
 * }

 *
 * Note that this interceptor automatically translates HibernateExceptions,
 * via delegating to the {@code SessionFactoryUtils.convertHibernateAccessException}
 * method that converts them to exceptions that are compatible with the
 * {@code org.springframework.dao} exception hierarchy (like HibernateTemplate does).
 * This can be turned off if the raw exceptions are preferred.
 *
 *
This class can be considered a declarative alternative to HibernateTemplate's
 * callback approach. The advantages are:
 *

 *
no anonymous classes necessary for callback implementations;
 *
the possibility to throw any application exceptions from within data access code.
 *

 *
 *
The drawback is the dependency on interceptor configuration. However, note
 * that this interceptor is usually not necessary in scenarios where the
 * data access code always executes within transactions. A transaction will always
 * have a thread-bound Session in the first place, so adding this interceptor to the
 * configuration just adds value when fine-tuning Session settings like the flush mode
 * - or when relying on exception translation.
 *
 * @author Juergen Hoeller
 * @since 1.2
 * @see org.hibernate.SessionFactory#getCurrentSession()
 * @see HibernateTransactionManager
 * @see HibernateTemplate
 * @deprecated as of Spring 3.2.7, in favor of either HibernateTemplate usage or
 * native Hibernate API usage within transactions, in combination with a general
 * {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor}.
 * Note: This class does not have an equivalent replacement in {@code orm.hibernate4}.
 * If you desperately need a scoped Session bound through AOP, consider the newly
 * introduced {@link org.springframework.orm.hibernate3.support.OpenSessionInterceptor}.
 */
@Deprecated
public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor {

	private boolean exceptionConversionEnabled = true;

	/**
	 * Set whether to convert any HibernateException raised to a Spring DataAccessException,
	 * compatible with the {@code org.springframework.dao} exception hierarchy.
	 *
Default is "true". Turn this flag off to let the caller receive raw exceptions
	 * as-is, without any wrapping.
	 * @see org.springframework.dao.DataAccessException
	 */
	public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
		this.exceptionConversionEnabled = exceptionConversionEnabled;
	}

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		Session session = getSession();
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());

		boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
		if (existingTransaction) {
			logger.debug("Found thread-bound Session for HibernateInterceptor");
		}
		else {
			if (sessionHolder != null) {
				sessionHolder.addSession(session);
			}
			else {
				TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
			}
		}

		FlushMode previousFlushMode = null;
		try {
			previousFlushMode = applyFlushMode(session, existingTransaction);
			enableFilters(session);
			Object retVal = methodInvocation.proceed();
			flushIfNecessary(session, existingTransaction);
			return retVal;
		}
		catch (HibernateException ex) {
			if (this.exceptionConversionEnabled) {
				throw convertHibernateAccessException(ex);
			}
			else {
				throw ex;
			}
		}
		finally {
			if (existingTransaction) {
				logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
				disableFilters(session);
				if (previousFlushMode != null) {
					session.setFlushMode(previousFlushMode);
				}
			}
			else {
				SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
				if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
					TransactionSynchronizationManager.unbindResource(getSessionFactory());
				}
			}
		}
	}

	/**
	 * Return a Session for use by this interceptor.
	 * @see SessionFactoryUtils#getSession
	 */
	protected Session getSession() {
		return SessionFactoryUtils.getSession(
				getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
	}

}