text:
package edu.ucdenver.ccp.datasource.identifiers.ebi.interpro;

import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier;

public class PirID extends StringDataSourceIdentifier {

	public PirID(String resourceID) {
		super(resourceID, DataSource.PIR);
	}

}

redpajama_set_name: RedPajamaGithub


text:
//
//  WLRRoute.h
//  Pods
//
//  Created by Neo on 2016/12/18.
//
//

#ifndef WLRRoute_h
#define WLRRoute_h
#import <WLRRoute/NSError+WLRError.h>
#import <WLRRoute/NSString+WLRQuery.h>
#import <WLRRoute/UIViewController+WLRRoute.h>
#import <WLRRoute/WLRMatchResult.h>
#import <WLRRoute/WLRRegularExpression.h>
#import <WLRRoute/WLRRouteHandler.h>
#import <WLRRoute/WLRRouteMatcher.h>
#import <WLRRoute/WLRRouteMiddlewareProtocol.h>
#import <WLRRoute/WLRRouter.h>
#import <WLRRoute/WLRRouteRequest.h>
#endif /* WLRRoute_h */


text:
import { computeModalities, modalityPrettyLookup, Summary } from './summary.ts'
import { assertEquals, assertObjectMatch } from '../deps/asserts.ts'

Deno.test('Summary class and helper functions', async (t) => {
  await t.step('Constructor succeeds', () => {
    new Summary()
  })
  await t.step('computeModalities properly sorts modality counts', () => {
    const modalitiesIn = { eeg: 5, pet: 6, mri: 6, ieeg: 6 }
    const modalitiesOut = ['pet', 'ieeg', 'mri', 'eeg'].map(
      (x) => modalityPrettyLookup[x],
    )
    assertEquals(computeModalities(modalitiesIn), modalitiesOut)
  })
})


text:
require 'spec_helper'
module Alf
  describe "Reader#initialize" do

    subject{ Reader.new(*args) }

    let(:input){ nil }
    let(:options){ nil }

    let(:args){ [input, options].compact }

    before do
      subject.should be_a(Reader)
    end

    after do
      subject.input.should eq(input)
    end

    context 'with empty default options' do

      after do
        subject.options.should eq(options || {})
      end

      context "with only a path as a String" do
        let(:input){ "suppliers" }
        it 'should set the path correctly' do
          subject.path.should eq(Path("suppliers"))
        end
      end

      context "with only a path as a Path" do
        let(:input){ Path("suppliers") }
        it 'should set the path correctly' do
          subject.path.should eq(Path("suppliers"))
        end
      end

      context "with a File" do
        let(:input){ Path.here.open('r') }
        it 'should set the path correctly' do
          subject.path.should eq(Path.here)
        end
        after{ input.close rescue nil }
      end
    end

    describe "on a subclass" do
      class FooReader < Reader
        DEFAULT_OPTIONS = {:from => :subclass}
      end
      subject{ FooReader.new(*args) }

      let(:input){ "suppliers" }

      describe "without option overriding" do
        let(:options){ {:opts => true} }
        it 'should merge options' do
          subject.options.should eq(:opts => true, :from => :subclass)
        end
      end

      describe "with option overriding" do
        let(:options){ {:opts => true, :from => :overrided} }
        it 'should override options' do
          subject.options.should eq(:opts => true, :from => :overrided)
        end
      end

    end

  end
end


text:
<!DOCTYPE html>
<html lang="en">

    <head>

        <link rel="icon" href="favicon.png"/>
        <meta charset="utf-8">

        <style>
            #app {
                display: block;
                position: relative;
                margin: 2em auto 0 auto;
            }
        </style>

    </head>

    <body style="padding: 0; margin: 0; background-color: #111111;">

        <script type="text/javascript" src="./social.js"></script>

    </body>

</html>


text:
package org.elasticsearch.blobstore.cache;

import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.OriginSettingClient;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDecider;
import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot;
import org.elasticsearch.plugins.ClusterPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.repositories.blobstore.BlobStoreRepository;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.xpack.cluster.routing.allocation.DataTierAllocationDecider;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.searchablesnapshots.SearchableSnapshotShardStats;
import org.elasticsearch.xpack.searchablesnapshots.BaseSearchableSnapshotsIntegTestCase;
import org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshots;
import org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants;
import org.elasticsearch.xpack.searchablesnapshots.action.SearchableSnapshotsStatsAction;
import org.elasticsearch.xpack.searchablesnapshots.action.SearchableSnapshotsStatsRequest;
import org.elasticsearch.xpack.searchablesnapshots.cache.CacheService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static org.elasticsearch.repositories.blobstore.BlobStoreRepository.INDEX_SHARD_SNAPSHOT_FORMAT;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshots.DATA_TIERS_PREFERENCE;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants.SNAPSHOT_BLOB_CACHE_INDEX;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;

public class SearchableSnapshotsBlobStoreCacheIntegTests extends BaseSearchableSnapshotsIntegTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return CollectionUtils.appendToCopy(super.nodePlugins(), WaitForSnapshotBlobCacheShardsActivePlugin.class);
    }

    @Override
    protected int numberOfReplicas() {
        return 0;
    }

    @Override
    protected Settings nodeSettings(int nodeOrdinal) {
        return Settings.builder()
            .put(super.nodeSettings(nodeOrdinal))
            .put(
                CacheService.SNAPSHOT_CACHE_RANGE_SIZE_SETTING.getKey(),
                randomLongBetween(new ByteSizeValue(4, ByteSizeUnit.KB).getBytes(), new ByteSizeValue(20, ByteSizeUnit.KB).getBytes()) + "b"
            )
            .put(CacheService.SNAPSHOT_CACHE_SIZE_SETTING.getKey(), new ByteSizeValue(Long.MAX_VALUE, ByteSizeUnit.BYTES))
            .build();
    }

    public void testBlobStoreCache() throws Exception {
        final String indexName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
        createIndex(indexName);

        final List<IndexRequestBuilder> indexRequestBuilders = new ArrayList<>();
        for (int i = scaledRandomIntBetween(0, 10_000); i >= 0; i--) {
            indexRequestBuilders.add(client().prepareIndex(indexName).setSource("text", randomUnicodeOfLength(10), "num", i));
        }
        indexRandom(true, false, true, indexRequestBuilders);
        final long numberOfDocs = indexRequestBuilders.size();
        final NumShards numberOfShards = getNumShards(indexName);

        if (randomBoolean()) {
            logger.info("--> force-merging index before snapshotting");
            final ForceMergeResponse forceMergeResponse = client().admin()
                .indices()
                .prepareForceMerge(indexName)
                .setMaxNumSegments(1)
                .get();
            assertThat(forceMergeResponse.getSuccessfulShards(), equalTo(numberOfShards.totalNumShards));
            assertThat(forceMergeResponse.getFailedShards(), equalTo(0));
        }

        final String repositoryName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
        final Path repositoryLocation = randomRepoPath();
        createRepository(repositoryName, "fs", repositoryLocation);

        final SnapshotId snapshot = createSnapshot(repositoryName, "test-snapshot", List.of(indexName)).snapshotId();
        assertAcked(client().admin().indices().prepareDelete(indexName));

        // extract the list of blobs per shard from the snapshot directory on disk
        final Map<String, BlobStoreIndexShardSnapshot> blobsInSnapshot = blobsInSnapshot(repositoryLocation, snapshot.getUUID());
        assertThat("Failed to load all shard snapshot metadata files", blobsInSnapshot.size(), equalTo(numberOfShards.numPrimaries));

        expectThrows(
            IndexNotFoundException.class,
            ".snapshot-blob-cache system index should not be created yet",
            () -> systemClient().admin().indices().prepareGetIndex().addIndices(SNAPSHOT_BLOB_CACHE_INDEX).get()
        );

        logger.info("--> mount snapshot [{}] as an index for the first time", snapshot);
        final String restoredIndex = mountSnapshot(
            repositoryName,
            snapshot.getName(),
            indexName,
            Settings.builder()
                .put(SearchableSnapshots.SNAPSHOT_CACHE_ENABLED_SETTING.getKey(), true)
                .put(SearchableSnapshots.SNAPSHOT_CACHE_PREWARM_ENABLED_SETTING.getKey(), false)
                .build()
        );
        ensureGreen(restoredIndex);

        // wait for all async cache fills to complete
        assertBusy(() -> {
            for (final SearchableSnapshotShardStats shardStats : client().execute(
                SearchableSnapshotsStatsAction.INSTANCE,
                new SearchableSnapshotsStatsRequest()
            ).actionGet().getStats()) {
                for (final SearchableSnapshotShardStats.CacheIndexInputStats indexInputStats : shardStats.getStats()) {
                    assertThat(Strings.toString(indexInputStats), indexInputStats.getCurrentIndexCacheFills(), equalTo(0L));
                }
            }
        });

        for (final SearchableSnapshotShardStats shardStats : client().execute(
            SearchableSnapshotsStatsAction.INSTANCE,
            new SearchableSnapshotsStatsRequest()
        ).actionGet().getStats()) {
            for (final SearchableSnapshotShardStats.CacheIndexInputStats indexInputStats : shardStats.getStats()) {
                assertThat(Strings.toString(indexInputStats), indexInputStats.getBlobStoreBytesRequested().getCount(), greaterThan(0L));
            }
        }

        logger.info("--> verifying cached documents in system index [{}]", SNAPSHOT_BLOB_CACHE_INDEX);
        assertCachedBlobsInSystemIndex(repositoryName, blobsInSnapshot);

        logger.info("--> verifying system index [{}] data tiers preference", SNAPSHOT_BLOB_CACHE_INDEX);
        assertThat(
            systemClient().admin()
                .indices()
                .prepareGetSettings(SNAPSHOT_BLOB_CACHE_INDEX)
                .get()
                .getSetting(SNAPSHOT_BLOB_CACHE_INDEX, DataTierAllocationDecider.INDEX_ROUTING_PREFER),
            equalTo(DATA_TIERS_PREFERENCE)
        );

        final long numberOfCachedBlobs = systemClient().prepareSearch(SNAPSHOT_BLOB_CACHE_INDEX).get().getHits().getTotalHits().value;
        final long numberOfCacheWrites = systemClient().admin()
            .indices()
            .prepareStats(SNAPSHOT_BLOB_CACHE_INDEX)
            .clear()
            .setIndexing(true)
            .get()
            .getTotal().indexing.getTotal().getIndexCount();

        logger.info("--> verifying documents in index [{}]", restoredIndex);
        assertHitCount(client().prepareSearch(restoredIndex).setSize(0).setTrackTotalHits(true).get(), numberOfDocs);
        assertHitCount(
            client().prepareSearch(restoredIndex)
                .setQuery(QueryBuilders.rangeQuery("num").lte(numberOfDocs))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            numberOfDocs
        );
        assertHitCount(
            client().prepareSearch(restoredIndex)
                .setQuery(QueryBuilders.rangeQuery("num").gt(numberOfDocs + 1))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            0L
        );

        assertAcked(client().admin().indices().prepareDelete(restoredIndex));

        logger.info("--> mount snapshot [{}] as an index for the second time", snapshot);
        final String restoredAgainIndex = mountSnapshot(
            repositoryName,
            snapshot.getName(),
            indexName,
            Settings.builder()
                .put(SearchableSnapshots.SNAPSHOT_CACHE_ENABLED_SETTING.getKey(), true)
                .put(SearchableSnapshots.SNAPSHOT_CACHE_PREWARM_ENABLED_SETTING.getKey(), false)
                .build()
        );
        ensureGreen(restoredAgainIndex);

        logger.info("--> verifying shards of [{}] were started without using the blob store more than necessary", restoredAgainIndex);
        for (final SearchableSnapshotShardStats shardStats : client().execute(
            SearchableSnapshotsStatsAction.INSTANCE,
            new SearchableSnapshotsStatsRequest()
        ).actionGet().getStats()) {
            for (final SearchableSnapshotShardStats.CacheIndexInputStats indexInputStats : shardStats.getStats()) {
                // we read the header of each file contained within the .cfs file, which could be anywhere
                final boolean mayReadMoreThanHeader = indexInputStats.getFileName().endsWith(".cfs");
                if (indexInputStats.getFileLength() <= BlobStoreCacheService.DEFAULT_CACHED_BLOB_SIZE * 2
                    || mayReadMoreThanHeader == false) {
                    assertThat(Strings.toString(indexInputStats), indexInputStats.getBlobStoreBytesRequested().getCount(), equalTo(0L));
                }
            }
        }

        logger.info("--> verifying documents in index [{}]", restoredAgainIndex);
        assertHitCount(client().prepareSearch(restoredAgainIndex).setSize(0).setTrackTotalHits(true).get(), numberOfDocs);
        assertHitCount(
            client().prepareSearch(restoredAgainIndex)
                .setQuery(QueryBuilders.rangeQuery("num").lte(numberOfDocs))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            numberOfDocs
        );
        assertHitCount(
            client().prepareSearch(restoredAgainIndex)
                .setQuery(QueryBuilders.rangeQuery("num").gt(numberOfDocs + 1))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            0L
        );

        logger.info("--> verifying cached documents (again) in system index [{}]", SNAPSHOT_BLOB_CACHE_INDEX);
        assertCachedBlobsInSystemIndex(repositoryName, blobsInSnapshot);

        logger.info("--> verifying that no extra cached blobs were indexed [{}]", SNAPSHOT_BLOB_CACHE_INDEX);
        refreshSystemIndex();
        assertHitCount(systemClient().prepareSearch(SNAPSHOT_BLOB_CACHE_INDEX).setSize(0).get(), numberOfCachedBlobs);
        assertThat(
            systemClient().admin().indices().prepareStats(SNAPSHOT_BLOB_CACHE_INDEX).clear().setIndexing(true).get().getTotal().indexing
                .getTotal()
                .getIndexCount(),
            equalTo(numberOfCacheWrites)
        );

        logger.info("--> restarting cluster");
        internalCluster().fullRestart(new InternalTestCluster.RestartCallback() {
            @Override
            public Settings onNodeStopped(String nodeName) throws Exception {
                return Settings.builder()
                    .put(super.onNodeStopped(nodeName))
                    .put(WaitForSnapshotBlobCacheShardsActivePlugin.ENABLED.getKey(), true)
                    .build();
            }
        });
        ensureGreen(restoredAgainIndex);

        logger.info("--> verifying documents in index [{}]", restoredAgainIndex);
        assertHitCount(client().prepareSearch(restoredAgainIndex).setSize(0).setTrackTotalHits(true).get(), numberOfDocs);
        assertHitCount(
            client().prepareSearch(restoredAgainIndex)
                .setQuery(QueryBuilders.rangeQuery("num").lte(numberOfDocs))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            numberOfDocs
        );
        assertHitCount(
            client().prepareSearch(restoredAgainIndex)
                .setQuery(QueryBuilders.rangeQuery("num").gt(numberOfDocs + 1))
                .setSize(0)
                .setTrackTotalHits(true)
                .get(),
            0L
        );

        logger.info("--> verifying cached documents (after restart) in system index [{}]", SNAPSHOT_BLOB_CACHE_INDEX);
        assertCachedBlobsInSystemIndex(repositoryName, blobsInSnapshot);

        logger.info("--> verifying that no cached blobs were indexed in system index [{}] after restart", SNAPSHOT_BLOB_CACHE_INDEX);
        assertHitCount(systemClient().prepareSearch(SNAPSHOT_BLOB_CACHE_INDEX).setSize(0).get(), numberOfCachedBlobs);
        assertThat(
            systemClient().admin().indices().prepareStats(SNAPSHOT_BLOB_CACHE_INDEX).clear().setIndexing(true).get().getTotal().indexing
                .getTotal()
                .getIndexCount(),
            equalTo(0L)
        );

        // TODO also test when the index is frozen
        // TODO also test when prewarming is enabled
    }

    /**
     * @return a {@link Client} that can be used to query the blob store cache system index
     */
    private Client systemClient() {
        return new OriginSettingClient(client(), ClientHelper.SEARCHABLE_SNAPSHOTS_ORIGIN);
    }

    private void refreshSystemIndex() {
        try {
            final RefreshResponse refreshResponse = systemClient().admin().indices().prepareRefresh(SNAPSHOT_BLOB_CACHE_INDEX).get();
            assertThat(refreshResponse.getSuccessfulShards(), greaterThan(0));
            assertThat(refreshResponse.getFailedShards(), equalTo(0));
        } catch (IndexNotFoundException indexNotFoundException) {
            throw new AssertionError("unexpected", indexNotFoundException);
        }
    }

    /**
     * Reads a repository location on disk and extracts the list of blobs for each shards
     */
    private Map<String, BlobStoreIndexShardSnapshot> blobsInSnapshot(Path repositoryLocation, String snapshotId) throws IOException {
        final Map<String, BlobStoreIndexShardSnapshot> blobsPerShard = new HashMap<>();
        forEachFileRecursively(repositoryLocation.resolve("indices"), ((file, basicFileAttributes) -> {
            final String fileName = file.getFileName().toString();
            if (fileName.equals(BlobStoreRepository.SNAPSHOT_FORMAT.blobName(snapshotId))) {
                blobsPerShard.put(
                    String.join(
                        "/",
                        snapshotId,
                        file.getParent().getParent().getFileName().toString(),
                        file.getParent().getFileName().toString()
                    ),
                    INDEX_SHARD_SNAPSHOT_FORMAT.deserialize(fileName, xContentRegistry(), Streams.readFully(Files.newInputStream(file)))
                );
            }
        }));
        return Map.copyOf(blobsPerShard);
    }

    private void assertCachedBlobsInSystemIndex(final String repositoryName, final Map<String, BlobStoreIndexShardSnapshot> blobsInSnapshot)
        throws Exception {
        assertBusy(() -> {
            refreshSystemIndex();

            long numberOfCachedBlobs = 0L;
            for (Map.Entry<String, BlobStoreIndexShardSnapshot> blob : blobsInSnapshot.entrySet()) {
                for (BlobStoreIndexShardSnapshot.FileInfo fileInfo : blob.getValue().indexFiles()) {
                    if (fileInfo.name().startsWith("__") == false) {
                        continue;
                    }

                    final String path = String.join("/", repositoryName, blob.getKey(), fileInfo.physicalName());
                    if (fileInfo.length() <= BlobStoreCacheService.DEFAULT_CACHED_BLOB_SIZE * 2) {
                        // file has been fully cached
                        final GetResponse getResponse = systemClient().prepareGet(SNAPSHOT_BLOB_CACHE_INDEX, path + "/@0").get();
                        assertThat("not cached: [" + path + "/@0] for blob [" + fileInfo + "]", getResponse.isExists(), is(true));
                        final CachedBlob cachedBlob = CachedBlob.fromSource(getResponse.getSourceAsMap());
                        assertThat(cachedBlob.from(), equalTo(0L));
                        assertThat(cachedBlob.to(), equalTo(fileInfo.length()));
                        assertThat((long) cachedBlob.length(), equalTo(fileInfo.length()));
                        numberOfCachedBlobs += 1;

                    } else {
                        // first region of file has been cached
                        GetResponse getResponse = systemClient().prepareGet(SNAPSHOT_BLOB_CACHE_INDEX, path + "/@0").get();
                        assertThat(
                            "not cached: [" + path + "/@0] for first region of blob [" + fileInfo + "]",
                            getResponse.isExists(),
                            is(true)
                        );

                        CachedBlob cachedBlob = CachedBlob.fromSource(getResponse.getSourceAsMap());
                        assertThat(cachedBlob.from(), equalTo(0L));
                        assertThat(cachedBlob.to(), equalTo((long) BlobStoreCacheService.DEFAULT_CACHED_BLOB_SIZE));
                        assertThat(cachedBlob.length(), equalTo(BlobStoreCacheService.DEFAULT_CACHED_BLOB_SIZE));
                        numberOfCachedBlobs += 1;
                    }
                }
            }

            refreshSystemIndex();
            assertHitCount(systemClient().prepareSearch(SNAPSHOT_BLOB_CACHE_INDEX).setSize(0).get(), numberOfCachedBlobs);
        });
    }

    /**
     * This plugin declares an {@link AllocationDecider} that forces searchable snapshot shards to be allocated after
     * the primary shards of the snapshot blob cache index are started. This way we can ensure that searchable snapshot
     * shards can use the snapshot blob cache index after the cluster restarted.
     */
    public static class WaitForSnapshotBlobCacheShardsActivePlugin extends Plugin implements ClusterPlugin {

        public static Setting<Boolean> ENABLED = Setting.boolSetting(
            "wait_for_snapshot_blob_cache_shards_active.enabled",
            false,
            Setting.Property.NodeScope
        );

        @Override
        public List<Setting<?>> getSettings() {
            return List.of(ENABLED);
        }

        @Override
        public Collection<AllocationDecider> createAllocationDeciders(Settings settings, ClusterSettings clusterSettings) {
            if (ENABLED.get(settings) == false) {
                return List.of();
            }
            final String name = "wait_for_snapshot_blob_cache_shards_active";
            return List.of(new AllocationDecider() {

                @Override
                public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
                    return canAllocate(shardRouting, allocation);
                }

                @Override
                public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) {
                    final IndexMetadata indexMetadata = allocation.metadata().index(shardRouting.index());
                    if (SearchableSnapshotsConstants.isSearchableSnapshotStore(indexMetadata.getSettings()) == false) {
                        return allocation.decision(Decision.YES, name, "index is not a searchable snapshot shard - can allocate");
                    }
                    if (allocation.metadata().hasIndex(SNAPSHOT_BLOB_CACHE_INDEX) == false) {
                        return allocation.decision(Decision.YES, name, SNAPSHOT_BLOB_CACHE_INDEX + " is not created yet");
                    }
                    if (allocation.routingTable().hasIndex(SNAPSHOT_BLOB_CACHE_INDEX) == false) {
                        return allocation.decision(Decision.THROTTLE, name, SNAPSHOT_BLOB_CACHE_INDEX + " is not active yet");
                    }
                    final IndexRoutingTable indexRoutingTable = allocation.routingTable().index(SNAPSHOT_BLOB_CACHE_INDEX);
                    if (indexRoutingTable.allPrimaryShardsActive() == false) {
                        return allocation.decision(Decision.THROTTLE, name, SNAPSHOT_BLOB_CACHE_INDEX + " is not active yet");
                    }
                    return allocation.decision(Decision.YES, name, "primary shard for this replica is already active");
                }
            });
        }
    }
}


text:
module Sudoku
  module Solvers
    module Search

      protected

        def solve #:nodoc:
          sorted_sections = sections.sort { |a, b| values(b).nitems <=> values(a).nitems }
          failing_values = Array.new(puzzle.size, nil)
          missing_values = sorted_sections.collect { |section| options[:values].reject { |value| values(section).include?(value) } }
          entries = []
          section_index = 0
          until section_index == puzzle.size
            section = sorted_sections[section_index]
            if failing_values[section_index] == missing_values[section_index][0]
              unsolvable_puzzle! if entries.empty?
              entry = entries.pop
              self[*entry[:coord]] = nil
              missing_values[entry[:section_index]] << entry[:value]
              failing_values[entry[:section_index]] = entry[:failing_value] || entry[:value]
              unless section_index == entry[:section_index]
                failing_values[section_index] = nil
                section_index = entry[:section_index]
              end
            else
              until valid_section?(section)
                value = missing_values[section_index].shift
                section_values = values(section)
                coord = section[section_values.index(nil)] rescue unsolvable_puzzle!
                self[*coord] = value
                if valid_row?(coord[0]) && valid_column?(coord[1])
                  entries << { :section_index => section_index, :coord => coord, :value => value, :failing_value => failing_values[section_index] }
                  failing_values[section_index] = nil
                else
                  self[*coord] = nil
                  missing_values[section_index] << value
                  failing_values[section_index] ||= value
                  break
                end
              end
              section_index += 1 if missing_values[section_index].empty?
            end
          end
        end

    end
  end
end


text: /*# sourceMappingURL=../maps/mixins/vendorPrefix.css.map */


text:
<?php
/**
 * Exception for 403 Forbidden responses
 *
 * @package Requests
 */

/**
 * Exception for 403 Forbidden responses
 *
 * @package Requests
 */
class Requests_Exception_HTTP_403 extends Requests_Exception_HTTP {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 403;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Forbidden';
}


text:
using namespace llvm;

// Try to go from a Value* to a Function*. Never returns nullptr.
static Optional<Function *> parentFunctionOfValue(Value *);

// Returns possible functions called by the Inst* into the given
// SmallVectorImpl. Returns true if targets found, false otherwise.
// This is templated because InvokeInst/CallInst give us the same
// set of functions that we care about, and I don't like repeating
// myself.
template <typename Inst>
static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);

// Some instructions need to have their users tracked. Instructions like
// `add` require you to get the users of the Instruction* itself, other
// instructions like `store` require you to get the users of the first
// operand. This function gets the "proper" value to track for each
// type of instruction we support.
static Optional<Value *> getTargetValue(Instruction *);

// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
// This notes that we should ignore those.
static bool hasUsefulEdges(Instruction *);

const StratifiedIndex StratifiedLink::SetSentinel =
  std::numeric_limits<StratifiedIndex>::max();

namespace {
// StratifiedInfo Attribute things.
typedef unsigned StratifiedAttr;
LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;

LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;

// \brief StratifiedSets call for knowledge of "direction", so this is how we
// represent that locally.
enum class Level { Same, Above, Below };

// \brief Edges can be one of four "weights" -- each weight must have an inverse
// weight (Assign has Assign; Reference has Dereference).
enum class EdgeType {
  // The weight assigned when assigning from or to a value. For example, in:
  // %b = getelementptr %a, 0
  // ...The relationships are %b assign %a, and %a assign %b. This used to be
  // two edges, but having a distinction bought us nothing.
  Assign,

  // The edge used when we have an edge going from some handle to a Value.
  // Examples of this include:
  // %b = load %a              (%b Dereference %a)
  // %b = extractelement %a, 0 (%a Dereference %b)
  Dereference,

  // The edge used when our edge goes from a value to a handle that may have
  // contained it at some point. Examples:
  // %b = load %a              (%a Reference %b)
  // %b = extractelement %a, 0 (%b Reference %a)
  Reference
};

// \brief Encodes the notion of a "use"
struct Edge {
  // \brief Which value the edge is coming from
  Value *From;

  // \brief Which value the edge is pointing to
  Value *To;

  // \brief Edge weight
  EdgeType Weight;

  // \brief Whether we aliased any external values along the way that may be
  // invisible to the analysis (i.e. landingpad for exceptions, calls for
  // interprocedural analysis, etc.)
  StratifiedAttrs AdditionalAttrs;

  Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
      : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
};

// \brief Information we have about a function and would like to keep around
struct FunctionInfo {
  StratifiedSets<Value *> Sets;
  // Lots of functions have < 4 returns. Adjust as necessary.
  SmallVector<Value *, 4> ReturnedValues;

  FunctionInfo(StratifiedSets<Value *> &&S,
               SmallVector<Value *, 4> &&RV)
    : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
};

struct CFLAliasAnalysis;

struct FunctionHandle : public CallbackVH {
  FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
      : CallbackVH(Fn), CFLAA(CFLAA) {
    assert(Fn != nullptr);
    assert(CFLAA != nullptr);
  }

  virtual ~FunctionHandle() {}

  void deleted() override { removeSelfFromCache(); }
  void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }

private:
  CFLAliasAnalysis *CFLAA;

  void removeSelfFromCache();
};

struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
private:
  /// \brief Cached mapping of Functions to their StratifiedSets.
  /// If a function's sets are currently being built, it is marked
  /// in the cache as an Optional without a value. This way, if we
  /// have any kind of recursion, it is discernable from a function
  /// that simply has empty sets.
  DenseMap<Function *, Optional<FunctionInfo>> Cache;
  std::forward_list<FunctionHandle> Handles;

public:
  static char ID;

  CFLAliasAnalysis() : ImmutablePass(ID) {
    initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
  }

  virtual ~CFLAliasAnalysis() {}

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AliasAnalysis::getAnalysisUsage(AU);
  }

  void *getAdjustedAnalysisPointer(const void *ID) override {
    if (ID == &AliasAnalysis::ID)
      return (AliasAnalysis *)this;
    return this;
  }

  /// \brief Inserts the given Function into the cache.
  void scan(Function *Fn);

  void evict(Function *Fn) { Cache.erase(Fn); }

  /// \brief Ensures that the given function is available in the cache.
  /// Returns the appropriate entry from the cache.
  const Optional<FunctionInfo> &ensureCached(Function *Fn) {
    auto Iter = Cache.find(Fn);
    if (Iter == Cache.end()) {
      scan(Fn);
      Iter = Cache.find(Fn);
      assert(Iter != Cache.end());
      assert(Iter->second.hasValue());
    }
    return Iter->second;
  }

  AliasResult query(const Location &LocA, const Location &LocB);

  AliasResult alias(const Location &LocA, const Location &LocB) override {
    if (LocA.Ptr == LocB.Ptr) {
      if (LocA.Size == LocB.Size) {
        return MustAlias;
      } else {
        return PartialAlias;
      }
    }

    // Comparisons between global variables and other constants should be
    // handled by BasicAA.
    if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
      return AliasAnalysis::alias(LocA, LocB);
    }
    AliasResult QueryResult = query(LocA, LocB);
    if (QueryResult == MayAlias)
      return AliasAnalysis::alias(LocA, LocB);

    return QueryResult;
  }

  void initializePass() override { InitializeAliasAnalysis(this); }
};

void FunctionHandle::removeSelfFromCache() {
  assert(CFLAA != nullptr);
  auto *Val = getValPtr();
  CFLAA->evict(cast<Function>(Val));
  setValPtr(nullptr);
}

// \brief Gets the edges our graph should have, based on an Instruction*
class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
  CFLAliasAnalysis &AA;
  SmallVectorImpl<Edge> &Output;

public:
  GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
      : AA(AA), Output(Output) {}

  void visitInstruction(Instruction &) {
    llvm_unreachable("Unsupported instruction encountered");
  }

  void visitCastInst(CastInst &Inst) {
    Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
                          AttrNone));
  }

  void visitBinaryOperator(BinaryOperator &Inst) {
    auto *Op1 = Inst.getOperand(0);
    auto *Op2 = Inst.getOperand(1);
    Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
    Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
  }

  void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
    auto *Ptr = Inst.getPointerOperand();
    auto *Val = Inst.getNewValOperand();
    Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  }

  void visitAtomicRMWInst(AtomicRMWInst &Inst) {
    auto *Ptr = Inst.getPointerOperand();
    auto *Val = Inst.getValOperand();
    Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  }

  void visitPHINode(PHINode &Inst) {
    for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
      Value *Val = Inst.getIncomingValue(I);
      Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
    }
  }

  void visitGetElementPtrInst(GetElementPtrInst &Inst) {
    auto *Op = Inst.getPointerOperand();
    Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
    for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
      Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
  }

  void visitSelectInst(SelectInst &Inst) {
    // Condition is not processed here (The actual statement producing
    // the condition result is processed elsewhere). For select, the
    // condition is evaluated, but not loaded, stored, or assigned
    // simply as a result of being the condition of a select.

    auto *TrueVal = Inst.getTrueValue();
    Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
    auto *FalseVal = Inst.getFalseValue();
    Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
  }

  void visitAllocaInst(AllocaInst &) {}

  void visitLoadInst(LoadInst &Inst) {
    auto *Ptr = Inst.getPointerOperand();
    auto *Val = &Inst;
    Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  }

  void visitStoreInst(StoreInst &Inst) {
    auto *Ptr = Inst.getPointerOperand();
    auto *Val = Inst.getValueOperand();
    Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  }

  void visitVAArgInst(VAArgInst &Inst) {
    // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
    // two things:
    //  1. Loads a value from *((T*)*Ptr).
    //  2. Increments (stores to) *Ptr by some target-specific amount.
    // For now, we'll handle this like a landingpad instruction (by placing the
    // result in its own group, and having that group alias externals).
    auto *Val = &Inst;
    Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
  }

  static bool isFunctionExternal(Function *Fn) {
    return Fn->isDeclaration() || !Fn->hasLocalLinkage();
  }

  // Gets whether the sets at Index1 above, below, or equal to the sets at
  // Index2. Returns None if they are not in the same set chain.
  static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
                                          StratifiedIndex Index1,
                                          StratifiedIndex Index2) {
    if (Index1 == Index2)
      return Level::Same;

    const auto *Current = &Sets.getLink(Index1);
    while (Current->hasBelow()) {
      if (Current->Below == Index2)
        return Level::Below;
      Current = &Sets.getLink(Current->Below);
    }

    Current = &Sets.getLink(Index1);
    while (Current->hasAbove()) {
      if (Current->Above == Index2)
        return Level::Above;
      Current = &Sets.getLink(Current->Above);
    }

    return NoneType();
  }

  bool
  tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
                             Value *FuncValue,
                             const iterator_range<User::op_iterator> &Args) {
    const unsigned ExpectedMaxArgs = 8;
    const unsigned MaxSupportedArgs = 50;
    assert(Fns.size() > 0);

    // I put this here to give us an upper bound on time taken by IPA. Is it
    // really (realistically) needed? Keep in mind that we do have an n^2 algo.
    if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
      return false;

    // Exit early if we'll fail anyway
    for (auto *Fn : Fns) {
      if (isFunctionExternal(Fn) || Fn->isVarArg())
        return false;
      auto &MaybeInfo = AA.ensureCached(Fn);
      if (!MaybeInfo.hasValue())
        return false;
    }

    SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
    SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
    for (auto *Fn : Fns) {
      auto &Info = *AA.ensureCached(Fn);
      auto &Sets = Info.Sets;
      auto &RetVals = Info.ReturnedValues;

      Parameters.clear();
      for (auto &Param : Fn->args()) {
        auto MaybeInfo = Sets.find(&Param);
        // Did a new parameter somehow get added to the function/slip by?
        if (!MaybeInfo.hasValue())
          return false;
        Parameters.push_back(*MaybeInfo);
      }

      // Adding an edge from argument -> return value for each parameter that
      // may alias the return value
      for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
        auto &ParamInfo = Parameters[I];
        auto &ArgVal = Arguments[I];
        bool AddEdge = false;
        StratifiedAttrs Externals;
        for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
          auto MaybeInfo = Sets.find(RetVals[X]);
          if (!MaybeInfo.hasValue())
            return false;

          auto &RetInfo = *MaybeInfo;
          auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
          auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
          auto MaybeRelation =
              getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
          if (MaybeRelation.hasValue()) {
            AddEdge = true;
            Externals |= RetAttrs | ParamAttrs;
          }
        }
        if (AddEdge)
          Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
                            StratifiedAttrs().flip()));
      }

      if (Parameters.size() != Arguments.size())
        return false;

      // Adding edges between arguments for arguments that may end up aliasing
      // each other. This is necessary for functions such as
      // void foo(int** a, int** b) { *a = *b; }
      // (Technically, the proper sets for this would be those below
      // Arguments[I] and Arguments[X], but our algorithm will produce
      // extremely similar, and equally correct, results either way)
      for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
        auto &MainVal = Arguments[I];
        auto &MainInfo = Parameters[I];
        auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
        for (unsigned X = I + 1; X != E; ++X) {
          auto &SubInfo = Parameters[X];
          auto &SubVal = Arguments[X];
          auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
          auto MaybeRelation =
              getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);

          if (!MaybeRelation.hasValue())
            continue;

          auto NewAttrs = SubAttrs | MainAttrs;
          Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
        }
      }
    }
    return true;
  }

  template <typename InstT> void visitCallLikeInst(InstT &Inst) {
    SmallVector<Function *, 4> Targets;
    if (getPossibleTargets(&Inst, Targets)) {
      if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
        return;
      // Cleanup from interprocedural analysis
      Output.clear();
    }

    for (Value *V : Inst.arg_operands())
      Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
  }

  void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }

  void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }

  // Because vectors/aggregates are immutable and unaddressable,
  // there's nothing we can do to coax a value out of them, other
  // than calling Extract{Element,Value}. We can effectively treat
  // them as pointers to arbitrary memory locations we can store in
  // and load from.
  void visitExtractElementInst(ExtractElementInst &Inst) {
    auto *Ptr = Inst.getVectorOperand();
    auto *Val = &Inst;
    Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  }

  void visitInsertElementInst(InsertElementInst &Inst) {
    auto *Vec = Inst.getOperand(0);
    auto *Val = Inst.getOperand(1);
    Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
    Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  }

  void visitLandingPadInst(LandingPadInst &Inst) {
    // Exceptions come from "nowhere", from our analysis' perspective.
    // So we place the instruction its own group, noting that said group may
    // alias externals
    Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
  }

  void visitInsertValueInst(InsertValueInst &Inst) {
    auto *Agg = Inst.getOperand(0);
    auto *Val = Inst.getOperand(1);
    Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
    Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  }

  void visitExtractValueInst(ExtractValueInst &Inst) {
    auto *Ptr = Inst.getAggregateOperand();
    Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
  }

  void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
    auto *From1 = Inst.getOperand(0);
    auto *From2 = Inst.getOperand(1);
    Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
    Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
  }
};

// For a given instruction, we need to know which Value* to get the
// users of in order to build our graph. In some cases (i.e. add),
// we simply need the Instruction*. In other cases (i.e. store),
// finding the users of the Instruction* is useless; we need to find
// the users of the first operand. This handles determining which
// value to follow for us.
//
// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
// something to GetEdgesVisitor, add it here -- remove something from
// GetEdgesVisitor, remove it here.
class GetTargetValueVisitor
    : public InstVisitor<GetTargetValueVisitor, Value *> {
public:
  Value *visitInstruction(Instruction &Inst) { return &Inst; }

  Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }

  Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
    return Inst.getPointerOperand();
  }

  Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
    return Inst.getPointerOperand();
  }

  Value *visitInsertElementInst(InsertElementInst &Inst) {
    return Inst.getOperand(0);
  }

  Value *visitInsertValueInst(InsertValueInst &Inst) {
    return Inst.getAggregateOperand();
  }
};

// Set building requires a weighted bidirectional graph.
template <typename EdgeTypeT> class WeightedBidirectionalGraph {
public:
  typedef std::size_t Node;

private:
  const static Node StartNode = Node(0);

  struct Edge {
    EdgeTypeT Weight;
    Node Other;

    Edge(const EdgeTypeT &W, const Node &N)
      : Weight(W), Other(N) {}

    bool operator==(const Edge &E) const {
      return Weight == E.Weight && Other == E.Other;
    }

    bool operator!=(const Edge &E) const { return !operator==(E); }
  };

  struct NodeImpl {
    std::vector<Edge> Edges;
  };

  std::vector<NodeImpl> NodeImpls;

  bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }

  const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
  NodeImpl &getNode(Node N) { return NodeImpls[N]; }

public:
  // ----- Various Edge iterators for the graph ----- //

  // \brief Iterator for edges. Because this graph is bidirected, we don't
  // allow modificaiton of the edges using this iterator. Additionally, the
  // iterator becomes invalid if you add edges to or from the node you're
  // getting the edges of.
  struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
                                             std::tuple<EdgeTypeT, Node *>> {
    EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
        : Current(Iter) {}

    EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}

    EdgeIterator &operator++() {
      ++Current;
      return *this;
    }

    EdgeIterator operator++(int) {
      EdgeIterator Copy(Current);
      operator++();
      return Copy;
    }

    std::tuple<EdgeTypeT, Node> &operator*() {
      Store = std::make_tuple(Current->Weight, Current->Other);
      return Store;
    }

    bool operator==(const EdgeIterator &Other) const {
      return Current == Other.Current;
    }

    bool operator!=(const EdgeIterator &Other) const {
      return !operator==(Other);
    }

  private:
    typename std::vector<Edge>::const_iterator Current;
    std::tuple<EdgeTypeT, Node> Store;
  };

  // Wrapper for EdgeIterator with begin()/end() calls.
  struct EdgeIterable {
    EdgeIterable(const std::vector<Edge> &Edges)
        : BeginIter(Edges.begin()), EndIter(Edges.end()) {}

    EdgeIterator begin() { return EdgeIterator(BeginIter); }

    EdgeIterator end() { return EdgeIterator(EndIter); }

  private:
    typename std::vector<Edge>::const_iterator BeginIter;
    typename std::vector<Edge>::const_iterator EndIter;
  };

  // ----- Actual graph-related things ----- //

  WeightedBidirectionalGraph() {}

  WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
      : NodeImpls(std::move(Other.NodeImpls)) {}

  WeightedBidirectionalGraph<EdgeTypeT> &
  operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
    NodeImpls = std::move(Other.NodeImpls);
    return *this;
  }

  Node addNode() {
    auto Index = NodeImpls.size();
    auto NewNode = Node(Index);
    NodeImpls.push_back(NodeImpl());
    return NewNode;
  }

  void addEdge(Node From, Node To, const EdgeTypeT &Weight,
               const EdgeTypeT &ReverseWeight) {
    assert(inbounds(From));
    assert(inbounds(To));
    auto &FromNode = getNode(From);
    auto &ToNode = getNode(To);
    FromNode.Edges.push_back(Edge(Weight, To));
    ToNode.Edges.push_back(Edge(ReverseWeight, From));
  }

  EdgeIterable edgesFor(const Node &N) const {
    const auto &Node = getNode(N);
    return EdgeIterable(Node.Edges);
  }

  bool empty() const { return NodeImpls.empty(); }
  std::size_t size() const { return NodeImpls.size(); }

  // \brief Gets an arbitrary node in the graph as a starting point for
  // traversal.
  Node getEntryNode() {
    assert(inbounds(StartNode));
    return StartNode;
  }
};

typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
typedef DenseMap<Value *, GraphT::Node> NodeMapT;
}

// -- Setting up/registering CFLAA pass -- //
char CFLAliasAnalysis::ID = 0;

INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
                   "CFL-Based AA implementation", false, true, false)

ImmutablePass *llvm::createCFLAliasAnalysisPass() {
  return new CFLAliasAnalysis();
}

//===----------------------------------------------------------------------===//
// Function declarations that require types defined in the namespace above
//===----------------------------------------------------------------------===//

// Given an argument number, returns the appropriate Attr index to set.
static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);

// Given a Value, potentially return which AttrIndex it maps to.
static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);

// Gets the inverse of a given EdgeType.
static EdgeType flipWeight(EdgeType);

// Gets edges of the given Instruction*, writing them to the SmallVector*.
static void argsToEdges(CFLAliasAnalysis &, Instruction *,
                        SmallVectorImpl<Edge> &);

// Gets the "Level" that one should travel in StratifiedSets
// given an EdgeType.
static Level directionOfEdgeType(EdgeType);

// Builds the graph needed for constructing the StratifiedSets for the
// given function
static void buildGraphFrom(CFLAliasAnalysis &, Function *,
                           SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);

// Builds the graph + StratifiedSets for a function.
static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);

static Optional<Function *> parentFunctionOfValue(Value *Val) {
  if (auto *Inst = dyn_cast<Instruction>(Val)) {
    auto *Bb = Inst->getParent();
    return Bb->getParent();
  }

  if (auto *Arg = dyn_cast<Argument>(Val))
    return Arg->getParent();
  return NoneType();
}

template <typename Inst>
static bool getPossibleTargets(Inst *Call,
                               SmallVectorImpl<Function *> &Output) {
  if (auto *Fn = Call->getCalledFunction()) {
    Output.push_back(Fn);
    return true;
  }

  // TODO: If the call is indirect, we might be able to enumerate all potential
  // targets of the call and return them, rather than just failing.
  return false;
}

static Optional<Value *> getTargetValue(Instruction *Inst) {
  GetTargetValueVisitor V;
  return V.visit(Inst);
}

static bool hasUsefulEdges(Instruction *Inst) {
  bool IsNonInvokeTerminator =
      isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
  return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
}

static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
  if (isa<GlobalValue>(Val))
    return AttrGlobalIndex;

  if (auto *Arg = dyn_cast<Argument>(Val))
    // Only pointer arguments should have the argument attribute,
    // because things can't escape through scalars without us seeing a
    // cast, and thus, interaction with them doesn't matter.
    if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
      return argNumberToAttrIndex(Arg->getArgNo());
  return NoneType();
}

static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
  if (ArgNum >= AttrMaxNumArgs)
    return AttrAllIndex;
  return ArgNum + AttrFirstArgIndex;
}

static EdgeType flipWeight(EdgeType Initial) {
  switch (Initial) {
  case EdgeType::Assign:
    return EdgeType::Assign;
  case EdgeType::Dereference:
    return EdgeType::Reference;
  case EdgeType::Reference:
    return EdgeType::Dereference;
  }
  llvm_unreachable("Incomplete coverage of EdgeType enum");
}

static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
                        SmallVectorImpl<Edge> &Output) {
  GetEdgesVisitor v(Analysis, Output);
  v.visit(Inst);
}

static Level directionOfEdgeType(EdgeType Weight) {
  switch (Weight) {
  case EdgeType::Reference:
    return Level::Above;
  case EdgeType::Dereference:
    return Level::Below;
  case EdgeType::Assign:
    return Level::Same;
  }
  llvm_unreachable("Incomplete switch coverage");
}

// Aside: We may remove graph construction entirely, because it doesn't really
// buy us much that we don't already have. I'd like to add interprocedural
// analysis prior to this however, in case that somehow requires the graph
// produced by this for efficient execution
static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
                           SmallVectorImpl<Value *> &ReturnedValues,
                           NodeMapT &Map, GraphT &Graph) {
  const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
    auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
    auto &Iter = Pair.first;
    if (Pair.second) {
      auto NewNode = Graph.addNode();
      Iter->second = NewNode;
    }
    return Iter->second;
  };

  SmallVector<Edge, 8> Edges;
  for (auto &Bb : Fn->getBasicBlockList()) {
    for (auto &Inst : Bb.getInstList()) {
      // We don't want the edges of most "return" instructions, but we *do* want
      // to know what can be returned.
      if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
        ReturnedValues.push_back(Ret);

      if (!hasUsefulEdges(&Inst))
        continue;

      Edges.clear();
      argsToEdges(Analysis, &Inst, Edges);

      // In the case of an unused alloca (or similar), edges may be empty. Note
      // that it exists so we can potentially answer NoAlias.
      if (Edges.empty()) {
        auto MaybeVal = getTargetValue(&Inst);
        assert(MaybeVal.hasValue());
        auto *Target = *MaybeVal;
        findOrInsertNode(Target);
        continue;
      }

      for (const Edge &E : Edges) {
        auto To = findOrInsertNode(E.To);
        auto From = findOrInsertNode(E.From);
        auto FlippedWeight = flipWeight(E.Weight);
        auto Attrs = E.AdditionalAttrs;
        Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
                                std::make_pair(FlippedWeight, Attrs));
      }
    }
  }
}

static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
  NodeMapT Map;
  GraphT Graph;
  SmallVector<Value *, 4> ReturnedValues;

  buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);

  DenseMap<GraphT::Node, Value *> NodeValueMap;
  NodeValueMap.resize(Map.size());
  for (const auto &Pair : Map)
    NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));

  const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
    auto ValIter = NodeValueMap.find(Node);
    assert(ValIter != NodeValueMap.end());
    return ValIter->second;
  };

  StratifiedSetsBuilder<Value *> Builder;

  SmallVector<GraphT::Node, 16> Worklist;
  for (auto &Pair : Map) {
    Worklist.clear();

    auto *Value = Pair.first;
    Builder.add(Value);
    auto InitialNode = Pair.second;
    Worklist.push_back(InitialNode);
    while (!Worklist.empty()) {
      auto Node = Worklist.pop_back_val();
      auto *CurValue = findValueOrDie(Node);
      if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
        continue;

      for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
        auto Weight = std::get<0>(EdgeTuple);
        auto Label = Weight.first;
        auto &OtherNode = std::get<1>(EdgeTuple);
        auto *OtherValue = findValueOrDie(OtherNode);

        if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
          continue;

        bool Added;
        switch (directionOfEdgeType(Label)) {
        case Level::Above:
          Added = Builder.addAbove(CurValue, OtherValue);
          break;
        case Level::Below:
          Added = Builder.addBelow(CurValue, OtherValue);
          break;
        case Level::Same:
          Added = Builder.addWith(CurValue, OtherValue);
          break;
        }

        if (Added) {
          auto Aliasing = Weight.second;
          if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
            Aliasing.set(*MaybeCurIndex);
          if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
            Aliasing.set(*MaybeOtherIndex);
          Builder.noteAttributes(CurValue, Aliasing);
          Builder.noteAttributes(OtherValue, Aliasing);
          Worklist.push_back(OtherNode);
        }
      }
    }
  }

  // There are times when we end up with parameters not in our graph (i.e. if
  // it's only used as the condition of a branch). Other bits of code depend on
  // things that were present during construction being present in the graph.
  // So, we add all present arguments here.
  for (auto &Arg : Fn->args()) {
    Builder.add(&Arg);
  }

  return FunctionInfo(Builder.build(), std::move(ReturnedValues));
}

void CFLAliasAnalysis::scan(Function *Fn) {
  auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
  (void)InsertPair;
  assert(InsertPair.second &&
         "Trying to scan a function that has already been cached");

  FunctionInfo Info(buildSetsFrom(*this, Fn));
  Cache[Fn] = std::move(Info);
  Handles.push_front(FunctionHandle(Fn, this));
}

AliasAnalysis::AliasResult
CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
                        const AliasAnalysis::Location &LocB) {
  auto *ValA = const_cast<Value *>(LocA.Ptr);
  auto *ValB = const_cast<Value *>(LocB.Ptr);

  Function *Fn = nullptr;
  auto MaybeFnA = parentFunctionOfValue(ValA);
  auto MaybeFnB = parentFunctionOfValue(ValB);
  if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
    llvm_unreachable("Don't know how to extract the parent function "
                     "from values A or B");
  }

  if (MaybeFnA.hasValue()) {
    Fn = *MaybeFnA;
    assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
           "Interprocedural queries not supported");
  } else {
    Fn = *MaybeFnB;
  }

  assert(Fn != nullptr);
  auto &MaybeInfo = ensureCached(Fn);
  assert(MaybeInfo.hasValue());

  auto &Sets = MaybeInfo->Sets;
  auto MaybeA = Sets.find(ValA);
  if (!MaybeA.hasValue())
    return AliasAnalysis::MayAlias;

  auto MaybeB = Sets.find(ValB);
  if (!MaybeB.hasValue())
    return AliasAnalysis::MayAlias;

  auto SetA = *MaybeA;
  auto SetB = *MaybeB;
  auto AttrsA = Sets.getLink(SetA.Index).Attrs;
  auto AttrsB = Sets.getLink(SetB.Index).Attrs;
  // Stratified set attributes are used as markets to signify whether a member
  // of a StratifiedSet (or a member of a set above the current set) has
  // interacted with either arguments or globals. "Interacted with" meaning
  // its value may be different depending on the value of an argument or
  // global. The thought behind this is that, because arguments and globals
  // may alias each other, if AttrsA and AttrsB have touched args/globals,
  // we must conservatively say that they alias. However, if at least one of
  // the sets has no values that could legally be altered by changing the value
  // of an argument or global, then we don't have to be as conservative.
  if (AttrsA.any() && AttrsB.any())
    return AliasAnalysis::MayAlias;

  // We currently unify things even if the accesses to them may not be in
  // bounds, so we can't return partial alias here because we don't
  // know whether the pointer is really within the object or not.
  // IE Given an out of bounds GEP and an alloca'd pointer, we may
  // unify the two. We can't return partial alias for this case.
  // Since we do not currently track enough information to
  // differentiate

  if (SetA.Index == SetB.Index)
    return AliasAnalysis::MayAlias;

  return AliasAnalysis::NoAlias;
}


text:
#include <tinyara/net/if/ble.h>
#include "stddef.h"
#include "gap_customer.h"

trble_result_e rtw_ble_get_version(uint8_t *version)
{
    if (version == NULL)
        return TRBLE_FAIL;

    int ret;
    T_BT_VERSION_INFO ble_version;
    ret = gap_get_bt_version_info(&ble_version);

    if(ret)
    {
        version[0] = (uint8_t) (ble_version.lmp_subversion >> 8);
        version[1] = (uint8_t) ble_version.lmp_subversion;
        version[2] = (uint8_t) ble_version.btgap_buildnum;
        return TRBLE_SUCCESS;
    }
    return TRBLE_FAIL;
}


text:
#pragma once
#ifndef __BENCH_PROFILER_CLOCK_CYCLE_H__
#define __BENCH_PROFILER_CLOCK_CYCLE_H__

#include <cassert>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>

#ifndef __BENCH_EXPORT_H__
#include "bench/export.h"
#endif

#ifndef __BENCH_PROFILER_BASE_H__
#include "bench/profiler_base.h"
#endif

namespace bench
{

    /**
    * \class bench::profiler_clock_cycle
    *
    * \brief CPU profiler using performance counter and clock cycles.
    * All values are in microseconds (us).
    */
    class BENCH_API profiler_clock_cycle final
        : public bench::profiler_base
    {

        //////////////////////////////////////
        //				MEMBERS				//
        //////////////////////////////////////

    private:
        uint64_t				clock_cycle_start_;	//!< Specifies CPU clock cycles at start() call.
        uint64_t				clock_cycle_end_;		//!< Specifies CPU clock cycles at stop() call.
        uint64_t				clock_cycle_num_;		//!< Specifies CPU clock cycles between start() and stop() calls.

        //////////////////////////////////////
        //				METHODS				//
        //////////////////////////////////////

    public:
        profiler_clock_cycle(void) = delete;
        profiler_clock_cycle(profiler_clock_cycle & p_arg) = delete;
        profiler_clock_cycle(profiler_clock_cycle && p_arg) = delete;
        void operator=(profiler_clock_cycle & p_arg) = delete;
        void operator=(profiler_clock_cycle && p_arg) = delete;

    public:
        explicit profiler_clock_cycle(
            bench::profiler_base_properties const * p_props)
            noexcept;

        ~profiler_clock_cycle(
            void)
            noexcept;

    public:
        void start(
            void)
            override final;

        void stop(
            void)
            override final;

        ///////////////////////////////////////////////////////////////////////////////////////
        //		GET / SET
        ///////////////////////////////////////////////////////////////////////////////////////

    public:
        uint64_t get_value(
            void)
            const noexcept override final;

    }; // class profiler_clock_cycle

} // namespace bench

///////////////////////////////////////////////////////////////////////////////////////////////////
//		GET / SET
///////////////////////////////////////////////////////////////////////////////////////////////////

//=================================================================================================
inline uint64_t bench::profiler_clock_cycle::get_value(
    void)
    const noexcept
{
    return clock_cycle_num_;
}

#endif // __BENCH_PROFILER_CLOCK_CYCLE_H__


text:
<?php

/**
 * Returns information about customers
 *
 * @package     Nails
 * @subpackage  module-invoice
 * @category    Controller
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Invoice\Api\Controller;

use Nails\Api\Controller\CrudController;
use Nails\Api\Exception\ApiException;
use Nails\Invoice\Constants;

/**
 * Class Customer
 *
 * @package Nails\Invoice\Api\Controller
 */
class Customer extends CrudController
{
    const CONFIG_MODEL_NAME     = 'Customer';
    const CONFIG_MODEL_PROVIDER = Constants::MODULE_SLUG;

    // --------------------------------------------------------------------------

    /**
     * @param string $sAction
     * @param null   $oItem
     *
     * @throws ApiException
     */
    protected function userCan($sAction, $oItem = null)
    {
        switch ($sAction) {
            case static::ACTION_CREATE:
                if (!userHasPermission('admin:invoice:customer:create')) {
                    throw new ApiException(
                        'You are not authorised to access this resource.',
                        401
                    );
                }
                break;

            case static::ACTION_READ;
                if (!userHasPermission('admin:invoice:customer:browse')) {
                    throw new ApiException(
                        'You are not authorised to access this resource.',
                        401
                    );
                }
                break;

            case static::ACTION_UPDATE;
                if (!userHasPermission('admin:invoice:customer:edit')) {
                    throw new ApiException(
                        'You are not authorised to access this resource.',
                        401
                    );
                }
                break;

            case static::ACTION_DELETE;
                if (!userHasPermission('admin:invoice:customer:delete')) {
                    throw new ApiException(
                        'You are not authorised to access this resource.',
                        401
                    );
                }
                break;
        }
    }

    // --------------------------------------------------------------------------

    /**
     * @param \stdClass $oObj
     *
     * @return object|\stdClass
     */
    protected function formatObject($oObj)
    {
        $sLabel = $oObj->label;
        $sEmail = $oObj->billing_email ?: $oObj->email;
        if (!empty($sEmail)) {
            $sLabel .= ' (' . $sEmail . ')';
        }

        return (object) [
            'id'    => $oObj->id,
            'label' => $sLabel . ' - ID ' . $oObj->id,
        ];
    }
}


text:
package org.bergefall.dbstorage;

import static org.bergefall.common.MetaTraderConstants.DefaultEqPrice;
import static org.bergefall.common.MetaTraderConstants.DefaultVal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.TreeSet;

import org.bergefall.common.data.MarketDataCtx;

/**
 * Use this class to read historical prices from MySQL DB.
 * @author ola
 *
 */
public class ReadHistoricalEqPrices extends EqHsAccess {

	private static final String cSymbSelect = "SELECT * FROM META_TRADER.EQ_HS as EQ where EQ.SYMBOL = \'";

	public Set<MarketDataCtx> getPricesByCriteria(DataCriterias criteria) {
		if (!init()) {
			return new TreeSet<>();
		}
		//Build select statement.
		String selectQ = getSelectQueryFromCriteria(criteria);
		PreparedStatement statement = null;
		try {
			statement = connect.prepareStatement(selectQ);
			statement.setTimestamp(1, criteria.from);
			statement.setTimestamp(2, criteria.to);
		} catch (SQLException e) {

		}

		return issueStatement(statement);
	}

	public Set<MarketDataCtx> getAllPricesForSymb(String symbol) {
		if (!init()) {
			return new TreeSet<>();
		}
		String query = cSymbSelect + symbol + "\'";

		PreparedStatement statement = null;
		try {
			statement = connect.prepareStatement(query);
		} catch (SQLException e) {

		}

		return issueStatement(statement);
	}

	private Set<MarketDataCtx> issueStatement(PreparedStatement statement) {
		Set<MarketDataCtx> historicalPrices = new TreeSet<>();
		if (!init()) {
			return historicalPrices;
		}

		try {
			ResultSet resultSet = statement.executeQuery();
			addPricesFromResultSet(resultSet, historicalPrices);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (null != statement) {
				try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return historicalPrices;
	}

	protected void addPricesFromResultSet(ResultSet resultSet, Set<MarketDataCtx> prices) {
		if (null == resultSet || null == prices) {
			return;
		}

		try {
			while(resultSet.next()) {
				String symb = resultSet.getString(cSymbolColName);
				Timestamp timestamp = resultSet.getTimestamp(cDateTimeColName);
				LocalDateTime ldt = null == timestamp ? null : timestamp.toLocalDateTime();

				MarketDataCtx ctx = new MarketDataCtx(symb, ldt,
						getPrice(getLongCol(resultSet, cOpenColName)),
						getPrice(getLongCol(resultSet, cCloseColName)),
					    getPrice(getLongCol(resultSet, cAvgColName)),
					    getPrice(getLongCol(resultSet, cHighColName)),
					    getPrice(getLongCol(resultSet, cLowColName)),
					    getPrice(getLongCol(resultSet, cAskColName)),
					    getPrice(getLongCol(resultSet, cBidColName)),
					    getValWithDefault(getLongCol(resultSet, cTradesNrColName)),
					    getValWithDefault(getLongCol(resultSet, cTotVolColName)),
					    getValWithDefault(getLongCol(resultSet, cTurnoverColName)));
				prices.add(ctx);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private Long getLongCol(ResultSet result, String col) throws SQLException {
		if (hasColumn(result, col)) {
			return result.getLong(col);
		}
		return null;
	}

	private long getPrice(Long price) {
		return null == price ? DefaultEqPrice : price.longValue();
	}

	private long getValWithDefault(Long value) {
		return null == value ? DefaultVal : value.longValue();
	}

}


text:
XLS Reader that is small, fast and has no dependencies.

## Issues

There is almost no error-handling yet.

Formatting is not supported.
Expect
`string` from strings,
`bool` from some formulas,
`datetime` from cells with default date formats,
`double` from everything else.

## Usage

```
using Pervexel;
...
using (var file = File.OpenRead(@"c:\stuff.xls") {

	var compound = new CompoundStream(file);
	if (!compound.Open("Workbook"))
		return;

	var workbook = new WorkbookReader(compound);
	if (!workbook.Open(worksheet))
		return;

	while (workbook.Read()) {
		Console.Write(workbook.Row + " " + workbook.Column + ": " + workbook.Value));
	}
}
...
```


text:
layout: project
tags: [ full-model-system ]
title: Cleveland TN Model
github: https://github.com/wsp-sag/ClevelandTNModel
short-description: Travel model for Cleveland TN MPO
---


text:
(function() {
    'use strict';

    angular
        .module('app')
        .directive('navbar', navbar);

    /* Directive */
    function navbar() {
        var directive = {
            restrict: 'E',
            templateUrl: 'app/shared/navbar/navbar.html',
            controller: NavbarController,
        };

        return directive;

        function NavbarController($scope, $location) {
            // default navbar state
            $scope.navbarCollapsed = true;

            // testing the location to set the active element
            $scope.isActive = function (currentLocation) {
                return currentLocation == $location.path();
            };

        }
    }
})();


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.

package com.microsoft.tfs.plugin.impl;

import com.microsoft.teamfoundation.build.webapi.BuildHttpClient;
import com.microsoft.teamfoundation.core.webapi.CoreHttpClient;
import com.microsoft.teamfoundation.distributedtask.webapi.TaskHttpClient;
import hudson.Util;
import hudson.util.Secret;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.glassfish.jersey.SslConfigurator;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.RequestEntityProcessing;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import java.net.URI;
import java.util.logging.Logger;

/**
 * This class encapsulates all REST calls to TFS.
 *
 * The http connection uses basic auth to authenticate.
 */
public class TfsClient {
    private static final Logger logger = Logger.getLogger(TfsClient.class.getName());

    public static final String PROXY_URL_PROPERTY = "proxy_url";
    public static final String KEYSTORE_PATH_PROPERTY = "keystore_path";
    public static final String KEYSTORE_PASSWORD_PROPERTY = "keystore_password";
    public static final String TRUST_STORE_TYPE_PROPERTY = "trust_store_type";
    public static final String TRUST_MANAGER_FACTORY_ALGORITHM_PROPERTY = "trust_manager_factory_algorithm";
    public static final String SECURITY_PROTOCOL_PROPERTY = "security_protocol";

    private BuildHttpClient buildClient;
    private CoreHttpClient projectClient;
    private TaskHttpClient taskHttpClient;

    /*
     * Creating a tfs client
     */
    /* default */ TfsClient(URI uri, TfsClientFactoryImpl.ServiceProvider provider, String username, Secret password) {
        Client client = getClient(uri, provider, username, password);

        projectClient = new CoreHttpClient(client, uri);
        buildClient = new BuildHttpClient(client, uri);
        taskHttpClient = new TaskHttpClient(client, uri);
    }

    /**
     * get Build subarea client
     */
    public BuildHttpClient getBuildClient() {
        return buildClient;
    }

    /**
     * get Project subarea client
     */
    public CoreHttpClient getProjectClient() {
        return projectClient;
    }

    /**
     * get DistributedTask subarea client
     */
    public TaskHttpClient getTaskHttpClient() {
        return taskHttpClient;
    }

    /*
     * Creating a apache http client based JAX-RS client
     */
    private Client getClient(URI uri, TfsClientFactoryImpl.ServiceProvider provider, String username, Secret password) {
        ClientConfig clientConfig = new ClientConfig();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (TfsClientFactoryImpl.ServiceProvider.TFS == provider) {
            /* NTLM auth for on premise installation */

            String domain = null;
            int idx = Math.max(username.indexOf('/'), username.indexOf('\\'));
            if (idx > 0) {
                domain = username.substring(0, idx);
                username = username.substring(idx + 1);
            }

            credentialsProvider.setCredentials(
                    new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM),
                    new NTCredentials(username, Secret.toString(password), uri.getHost(), domain));

            logger.info("Using NTLM authentication for on premise TeamFoundationServer");

        }  else if (TfsClientFactoryImpl.ServiceProvider.VSO == provider) {
            // Basic Auth for VSO services
            credentialsProvider.setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(username, Secret.toString(password)));

            logger.info("Using user/pass authentication for Visual Studio Online services");

            // Preemptive send basic auth header, or we will be redirected for oauth login
            clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
        }

        clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

        if (System.getProperty(PROXY_URL_PROPERTY) != null) {
            clientConfig.property(ClientProperties.PROXY_URI, System.getProperty(PROXY_URL_PROPERTY));
            clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
        }

        clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
        clientConfig.connectorProvider(new ApacheConnectorProvider());

        return ClientBuilder.newClient(clientConfig);
    }

    /*
     * Setting up ssl proxy
     */
    private static SslConfigurator getSslConfigurator() {
        String keystorePath = System.getProperty(KEYSTORE_PATH_PROPERTY);
        String keystorePassword = System.getProperty(KEYSTORE_PASSWORD_PROPERTY);

        String trustStoreType = System.getProperty(TRUST_STORE_TYPE_PROPERTY);
        if (Util.fixEmptyAndTrim(trustStoreType) == null) {
            trustStoreType = "JKS";
        }

        String trustManagerFactoryAlgorithm = System.getProperty(TRUST_MANAGER_FACTORY_ALGORITHM_PROPERTY);
        if (Util.fixEmptyAndTrim(trustManagerFactoryAlgorithm) == null) {
            trustManagerFactoryAlgorithm = "PKIX";
        }

        String securityProtocol = System.getProperty(SECURITY_PROTOCOL_PROPERTY);
        if (Util.fixEmptyAndTrim(securityProtocol) == null) {
            securityProtocol = "SSL";
        }

        SslConfigurator sslConfigurator = SslConfigurator.newInstance();
        return sslConfigurator.trustStoreFile(keystorePath)
                .trustStorePassword(keystorePassword)
                .trustStoreType(trustStoreType)
                .trustManagerFactoryAlgorithm(trustManagerFactoryAlgorithm)
                .securityProtocol(securityProtocol);
    }
}


text:
define(['../array/slice'], function(slice){

    /**
     * Return a function that will execute in the given context, optionally adding any additional supplied parameters to the beginning of the arguments collection.
     * @param {Function} fn  Function.
     * @param {object} context   Execution context.
     * @param {rest} args    Arguments (0...n arguments).
     * @return {Function} Wrapped Function.
     */
    function bind(fn, context, args){
        var argsArr = slice(arguments, 2); //curried args
        return function(){
            return fn.apply(context, argsArr.concat(slice(arguments)));
        };
    }

    return bind;
});


text:
package com.hokolinks.model.exceptions;

public class LinkGenerationException extends HokoException {
    public LinkGenerationException() {
        super(4, "Could not generate Smartlink. Please try again later.");
    }
}


text:
"""
    This module provides mechanisms to use signal handlers in Python.

    Functions:

    signal(sig,action) -- set the action for a given signal (done)
    pause(sig) -- wait until a signal arrives [Unix only]
    alarm(seconds) -- cause SIGALRM after a specified time [Unix only]
    getsignal(sig) -- get the signal action for a given signal
    default_int_handler(action) -- default SIGINT handler (done, but acts string)

    Constants:

    SIG_DFL -- used to refer to the system default handler
    SIG_IGN -- used to ignore the signal
    NSIG -- number of defined signals

    SIGINT, SIGTERM, etc. -- signal numbers

    *** IMPORTANT NOTICES ***
    A signal handler function is called with two arguments:
    the first is the signal number, the second is the interrupted stack frame.

    According to http://java.sun.com/products/jdk/faq/faq-sun-packages.html
    'writing java programs that rely on sun.* is risky: they are not portable, and are not supported.'

    However, in Jython, like Python, we let you decide what makes
    sense for your application. If sun.misc.Signal is not available,
    an ImportError is raised.
"""

try:
    import sun.misc.Signal
except ImportError:
    raise ImportError("signal module requires sun.misc.Signal, which is not available on this platform")

import os
import sun.misc.SignalHandler
import sys
import threading
import time
from java.lang import IllegalArgumentException
from java.util.concurrent.atomic import AtomicReference

debug = 0

def _init_signals():
    # install signals by checking for standard names
    # using IllegalArgumentException to diagnose

    possible_signals = """
        SIGABRT
        SIGALRM
        SIGBUS
        SIGCHLD
        SIGCONT
        SIGFPE
        SIGHUP
        SIGILL
        SIGINFO
        SIGINT
        SIGIOT
        SIGKILL
        SIGPIPE
        SIGPOLL
        SIGPROF
        SIGQUIT
        SIGSEGV
        SIGSTOP
        SIGSYS
        SIGTERM
        SIGTRAP
        SIGTSTP
        SIGTTIN
        SIGTTOU
        SIGURG
        SIGUSR1
        SIGUSR2
        SIGVTALRM
        SIGWINCH
        SIGXCPU
        SIGXFSZ
    """.split()

    _module = __import__(__name__)
    signals = {}
    signals_by_name = {}
    for signal_name in possible_signals:
        try:
            java_signal = sun.misc.Signal(signal_name[3:])
        except IllegalArgumentException:
            continue

        signal_number = java_signal.getNumber()
        signals[signal_number] = java_signal
        signals_by_name[signal_name] = java_signal
        setattr(_module, signal_name, signal_number) # install as a module constant
    return signals

_signals = _init_signals()
NSIG = max(_signals.iterkeys()) + 1
SIG_DFL = sun.misc.SignalHandler.SIG_DFL # default system handler
SIG_IGN = sun.misc.SignalHandler.SIG_IGN # handler to ignore a signal

class JythonSignalHandler(sun.misc.SignalHandler):
    def __init__(self, action):
        self.action = action

    def handle(self, signal):
        # passing a frame here probably don't make sense in a threaded system,
        # but perhaps revisit
        self.action(signal.getNumber(), None)

def signal(sig, action):
    """
    signal(sig, action) -> action

    Set the action for the given signal.  The action can be SIG_DFL,
    SIG_IGN, or a callable Python object.  The previous action is
    returned.  See getsignal() for possible return values.

    *** IMPORTANT NOTICE ***
    A signal handler function is called with two arguments:
    the first is the signal number, the second is the interrupted stack frame.
    """
    # maybe keep a weak ref map of handlers we have returned?

    try:
        signal = _signals[sig]
    except KeyError:
        raise ValueError("signal number out of range")

    if callable(action):
        prev = sun.misc.Signal.handle(signal, JythonSignalHandler(action))
    elif action in (SIG_IGN, SIG_DFL) or isinstance(action, sun.misc.SignalHandler):
        prev = sun.misc.Signal.handle(signal, action)
    else:
        raise TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object")

    if isinstance(prev, JythonSignalHandler):
        return prev.action
    else:
        return prev

# dangerous! don't use!
def getsignal(sig):
    """getsignal(sig) -> action

    Return the current action for the given signal.  The return value can be:
    SIG_IGN -- if the signal is being ignored
    SIG_DFL -- if the default action for the signal is in effect
    None -- if an unknown handler is in effect
    anything else -- the callable Python object used as a handler

    Note for Jython: this function is NOT threadsafe. The underlying
    Java support only enables getting the current signal handler by
    setting a new one. So this is completely prone to race conditions.
    """
    try:
        signal = _signals[sig]
    except KeyError:
        raise ValueError("signal number out of range")
    current = sun.misc.Signal.handle(signal, SIG_DFL)
    sun.misc.Signal.handle(signal, current) # and reinstall

    if isinstance(current, JythonSignalHandler):
        return current.action
    else:
        return current

def default_int_handler(sig, frame):
    """
    default_int_handler(...)

    The default handler for SIGINT installed by Python.
    It raises KeyboardInterrupt.
    """
    raise KeyboardInterrupt

def pause():
    raise NotImplementedError

_alarm_timer_holder = AtomicReference()

def _alarm_handler(sig, frame):
    print "Alarm clock"
    os._exit(0)

# install a default alarm handler, the one we get by default doesn't
# work terribly well since it throws a bus error (at least on OS X)!
try:
    SIGALRM
    signal(SIGALRM, _alarm_handler)
except NameError:
    pass

class _Alarm(object):
    def __init__(self, interval, task):
        self.interval = interval
        self.task = task
        self.scheduled = None
        self.timer = threading.Timer(self.interval, self.task)

    def start(self):
        self.timer.start()
        self.scheduled = time.time() + self.interval

    def cancel(self):
        self.timer.cancel()
        now = time.time()
        if self.scheduled and self.scheduled > now:
            return self.scheduled - now
        else:
            return 0

def alarm(time):
    try:
        SIGALRM
    except NameError:
        raise NotImplementedError("alarm not implemented on this platform")

    def raise_alarm():
        sun.misc.Signal.raise(_signals[SIGALRM])

    if time > 0:
        new_alarm_timer = _Alarm(time, raise_alarm)
    else:
        new_alarm_timer = None
    old_alarm_timer = _alarm_timer_holder.getAndSet(new_alarm_timer)
    if old_alarm_timer:
        scheduled = int(old_alarm_timer.cancel())
    else:
        scheduled = 0

    if new_alarm_timer:
        new_alarm_timer.start()
    return scheduled


text:
package test.example.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import test.example.mvc.model.A;
import test.example.mvc.model.B;

import javax.validation.Valid;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/")
public class HomeController {

	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {
        A a = new A();
        a.setaOne("a1");
        B b = new B();
        b.setbOne("b1");
		model.addAttribute("a", a);
		model.addAttribute("b", b);
		return "home";
	}

    /**
     * This method would be my first choice but I can't figure out why it's NOT called
     * or how to pass the two arguments
     */
    @RequestMapping( value = "add1", method = RequestMethod.POST, params = "a, b")
    public String add1_1 ( @Valid A a, BindingResult resultA,
                         @Valid B b , BindingResult resultB,
                         Model model) {

        model.addAttribute("result", "Method add1_1 called");
        model.addAttribute("a1",a.getaOne());
        model.addAttribute("a2",a.getaTwo());
        model.addAttribute("b1",b.getbOne());
        model.addAttribute("b2",b.getbTwo());
        return "result";
    }

    /**
     * NOT working at all.
     * This is a test if parameters may be added to the
     * URL of a POST request but I do not got it working.
     */
    @RequestMapping( value = "urlparams", method = RequestMethod.POST, params = "c, d")
    public String params ( @ModelAttribute int c, @ModelAttribute int d) {
        return "result";
    }

    /**
     *  This method is working
     *  !! BUT
     *  The the single member of the parameters need to be posted using
     *  application/x-www-form-urlencoded one by one
     *  see $("#add11").click( -function
     *  I have not found a way of passing the two objects as objects
     *  There is one caveat, though!
     *  Passing each member separately means, the member names of all
     *  object passed have to be unique!
     *  If that prerequisite is met Spring seems to be able to sort
     *  out the members and construct the object from it.
     *
     *  It is working when passing only object two A or B.
     *  see the jQuery function for various test on formatting the
     *  data to be posted in various ways.
     */
    @RequestMapping( value = "add1", method = RequestMethod.POST)
    public String add1_2 ( @Valid A a, BindingResult resultA,
                         @Valid B b , BindingResult resultB,
                         Model model) {
        if (resultA.hasErrors() || resultB.hasErrors()) {
            return "home";
        }
        model.addAttribute("result","Method add1_2 called: "+a.getaOne()+b.getbOne());
        // add the parsed attribues to the model to
        // display them below the form for verification
        model.addAttribute("a1",a.getaOne());
        model.addAttribute("a2",a.getaTwo());
        model.addAttribute("b1",b.getbOne());
        model.addAttribute("b2",b.getbTwo());
        return "result";
    }

    /**
     * JSON
     * The first parameter is filled ONLY,
     * be it a class test.example.mvc.model.A or
     * a class java.util.LinkedHashMap
     */
    @RequestMapping( value = "add21", method = RequestMethod.POST)
    public ModelAndView add2_1 ( @RequestBody A a, B b) {
        System.out.println( a.getClass());
        ModelAndView mv = new ModelAndView("result");
        mv.addObject("a1",a.getaOne());
        mv.addObject("a2",a.getaTwo());
        mv.addObject("b1",b.getbOne());
        mv.addObject("b2",b.getbTwo());
        mv.addObject("result", "add2_1 called");
        return mv;
    }

    /**
     * JSON
     * This is working for a SINGLE object only
     */
    @RequestMapping( value = "add22", method = RequestMethod.POST)
    public ModelAndView add2_2 ( @RequestBody A a) {
        System.out.println( a.getClass());
        ModelAndView mv = new ModelAndView("result");
        mv.addObject("a1",a.getaOne());
        mv.addObject("a2",a.getaTwo());
        mv.addObject("result", "add2_2 called");
        return mv;
    }

    /**
     * JSON
     * Using some sort of wrapper object (Object o).
     * The data is send within an java.uitl.LinkedHashMap but
     * validating by annotations is lost
     */
    @RequestMapping( value = "add23", method = RequestMethod.POST)
    public ModelAndView add2_3 ( @RequestBody Object o) {
        System.out.println( o.getClass());
        ModelAndView mv = new ModelAndView("result");
        LinkedHashMap map = (LinkedHashMap) o;
        // How to extract a and b from o  elegantly and safe AND VALIDATE?
//        mv.addObject("a1",a.getaOne());
//        mv.addObject("a2",a.getaTwo());
//        mv.addObject("b1",b.getbOne());
//        mv.addObject("b2",b.getbTwo());
        mv.addObject("result", "add2_3 called");
        return mv;
    }

}


text:
La Clase Console es una Clase con todos sus miembros (propiedades y métodos) estáticos. Solo necesitas saber el nombre de la Clase para empezar a trabajar con ella. También necesitaremos el espacio de nombre System para poder invocarla, escrito en la primera sección del fichero CS.
La documentación de Microsoft es muchas veces tu aliada, las descripciones y explicaciones son geniales aunque a veces los ejemplos son demasiado complicados. Para lo que estamos, viene genial. Así que dejo el enlace:

[Console (MSDN)](https://msdn.microsoft.com/es-es/library/system.console(v=vs.110).aspx)

## Escribiendo en consola

¿Cómo lanzar un mensaje por pantalla? Invocando al método WriteLine().

WriteLine() es un método que devuelve nada (void, por lo que no tiene return), es estático y puede recibir como parámetro una cadena de texto. Esta cadena de texto será nuestro mensaje por pantalla.

En tu programa, puedes empezar a escribir:

```cs
Console.WriteLine("hey there");
```

Cuando pulsas F5, se ejecutará pero ¡oh! Es apenas un flash. ¿Por qué? Porque la consola de Windows, a diferencia de la de GNULinux, necesita de un método para esperar un ENTER después de haber ejecutado cierto código.
Este método es ReadLine()

ReadLine() es un método estático que devuelve un string (cuyo uso veremos a la hora de tomar datos) y no recibe parámetros. Espera a que introduzcas un ENTER por teclado. Entonces:

```cs
Console.WriteLine("hey there");
Console.ReadLine();
```

Existe otro método, llamado Write(), que funciona de forma similar a WriteLine(), pero que a diferencia del anterior este no hace salto de línea, no "escribe línea" como deja ver su nombre. Devuelve void, es estático y puede recibir una cadena de texto como parámetro.

```cs
Console.WriteLine("Escribiendo con salto de línea");
Console.Write("Escribiendo sin salto de línea");
Console.ReadLine();
```

Y ahora podemos empezar a escribir líneas y líneas de código.

### Posicionando un cursor

La consola es un sistema de entrada y salida en el sistema, más personalizable de lo que cabe esperar de la monócroma pantalla. Es posible.

En concreto, podemos decidir la posición en la que el cursor se posiciona, para que no todas las líneas se ajusten en el borde izquierdo, en la posición más alta posible. La consola es una cuadrícula, con coordenadas desde el borde superior y el izquierdo, que podemos seleccionar a nuestro antojo. En concreto, sus medidas son de 80 columnas por 24 filas, empezando desde 0.

¿Cómo se juega con las posiciones? Tenemos dos alternativas, mediante propiedades y métodos.

Mediante propiedades, podemos establecer y leer los dos valores de columnas y filas de forma separada, en forma de integers.

```cs
Console.CursorLeft = 10;
Console.CursorTop = 5;
```

Mediante método, podemos invocar el método estático que devuelve void que establece una posición concreta de filas y columnas:

```cs
Console.SetCursorPosition(10, 5);
```

### La vida está llena de color

La consola es, por lo general, monocroma. Blanco sobre negro de forma habitual cuando invocamos la CMD. Y aunque a veces se pueda configurar, no estamos limitados a la configuración que el usuario determine por defecto en su sistema.

Existe en la Clase Console unas propiedades que establecen el color de fondo y el color de letra en la consola. Son dos propiedades que reciben valores de la enumeración ConsoleColor. ¿Qué es una enumeración? Puedes consultarlo [en este enlace](enum.md).

Y la puesta en práctica:

```cs
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Black;
```

Estas propiedades cambiadas establecen que lo siguiente que se escriba, detrás de estas líneas, tendrán el fondo azul y la letra de color negro. ¿Cómo hacer entonces para que se establezca desde el principio?

Podemos entonces invocar el método estático de la consola que limpia de todo contenido su interior, estableciendo estos colores desde el inicio de su uso.

```cs
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
```

### Ocultando el cursor

En ocasiones, ya sea porque quieres hacer que la consola muestre algo de una forma estática sin invitar al usuario a teclear, puedes necesitar ocultar el cursor, el *prompt*. Es posible de una forma sencilla gracias a una propiedad estática de la Clase Console que trabaja con *booleanos*.

Veamos como funciona:

```cs
Console.CursorVisible = false;
```

Y después de esa línea, el cursor dejará de ser visible.

### Un *prompt* diferente

Igual que el *prompt* se oculta, también se puede modificar de otra forma. Por lo general, este es solo una línea, fina, que parpadea. Pero cargando nuevos valores, podemos modificar el grueso de esa línea hasta ocupar todo el espacio que se le otorga a un caracter.

```cs
Console.CursorSize = 15;
```

### En conclusión

Las opciones, combinadas, permiten una combinación que les dará variedad a nuestras aplicaciones de consola.


text:
define(['./lessc'], function(less) {
    var fs = require.nodeRequire('fs');
    var path = require.nodeRequire('path');

    less.Parser.importer = function (file, paths, callback, env) {
        var pathname, data;

        // TODO: Undo this at some point,
        // or use different approach.
        var paths = [].concat(paths);
        paths.push('.');

        for (var i = 0; i < paths.length; i++) {
            try {
                pathname = path.join(paths[i], file);
                fs.statSync(pathname);
                break;
            } catch (e) {
                pathname = null;
            }
        }

        paths = paths.slice(0, paths.length - 1);

        if (!pathname) {
            if (typeof(env.errback) === "function") {
                env.errback(file, paths, callback);
            } else {
                callback({ type: 'File', message: "'" + file + "' wasn't found.\n" });
            }
            return;
        }

        function parseFile(e, data) {
            if (e) return callback(e);
                env.contents = env.contents || {};
                env.contents[pathname] = data;      // Updating top importing parser content cache.
            new(less.Parser)({
                    paths: [path.dirname(pathname)].concat(paths),
                    filename: pathname,
                    contents: env.contents,
                    files: env.files,
                    syncImport: env.syncImport,
                    dumpLineNumbers: env.dumpLineNumbers
            }).parse(data, function (e, root) {
                    callback(e, root, pathname);
            });
        };

        try {
            data = fs.readFileSync(pathname, 'utf-8');
            parseFile(null, data);
        } catch (e) {
            parseFile(e);
        }
    }
    return less;
});


text:
BIN = `npm bin`

lib/quesoParser.js: lib/grammar.jison lib/tokens.jisonlex
	${BIN}/jison $^ -o $@

test: lib/quesoParser.js
	${BIN}/mocha --reporter spec

watch:
	${BIN}/nodemon -x 'make test' -e 'js jison jisonlex' -q

.PHONY: test watch


text:
var GP_CONFIG = {
            bundleId: "myBundleId",
            loadingText: "my loading text...",
            credentials: {
                uri: "https://FIXME.ng.bluemix.example.com/translate",
                instanceId: "myServiceInstanceHexadecimalId",
                userId: "myReaderUserId",
                password: "myReaderPassword"
            }};

var GP_CREDENTIAL_ONLY_CONFIG = {
            credentials: {
                uri: "https://FIXME.ng.bluemix.example.com/translate",
                instanceId: "myServiceInstanceHexadecimalId",
                userId: "myReaderUserId",
                password: "myReaderPassword"
            }};