text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/scheme_registry.h"
#include "third_party/blink/public/mojom/use_counter/css_property_id.mojom-blink.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"

namespace {
const char kExtensionFeaturesHistogramName[] =
    "Blink.UseCounter.Extensions.Features";

const char kExtensionUrl[] = "chrome-extension://dummysite/";

int GetPageVisitsBucketforHistogram(const std::string& histogram_name) {
  if (histogram_name.find("CSS") == std::string::npos)
    return static_cast<int>(blink::mojom::WebFeature::kPageVisits);
  // For CSS histograms, the page visits bucket should be 1.
  return static_cast<int>(
      blink::mojom::blink::CSSSampleId::kTotalPagesMeasured);
}

}  // namespace

namespace blink {
using WebFeature = mojom::WebFeature;

class UseCounterImplTest : public testing::Test {
 public:
  class DummyLocalFrameClient : public EmptyLocalFrameClient {
   public:
    DummyLocalFrameClient() = default;
    const std::vector<UseCounterFeature>& observed_features() const {
      return observed_features_;
    }

   private:
    void DidObserveNewFeatureUsage(const UseCounterFeature& feature) override {
      observed_features_.push_back(feature);
    }
    std::vector<UseCounterFeature> observed_features_;
  };

  UseCounterImplTest()
      : dummy_(std::make_unique<DummyPageHolder>(
            /* initial_view_size= */ gfx::Size(),
            /* chrome_client= */ nullptr,
            /* local_frame_client= */
            MakeGarbageCollected<DummyLocalFrameClient>())) {
    Page::InsertOrdinaryPageForTesting(&dummy_->GetPage());
  }

  int ToSampleId(CSSPropertyID property) const {
    return static_cast<int>(GetCSSSampleId(property));
  }

  bool IsInternal(CSSPropertyID property) const {
    return CSSProperty::Get(property).IsInternal();
  }

 protected:
  LocalFrame* GetFrame() { return &dummy_->GetFrame(); }
  void SetIsViewSource() { dummy_->GetDocument().SetIsViewSource(true); }
  void SetURL(const KURL& url) { dummy_->GetDocument().SetURL(url); }
  Document& GetDocument() { return dummy_->GetDocument(); }

  std::unique_ptr<DummyPageHolder> dummy_;
  HistogramTester histogram_tester_;

  void UpdateAllLifecyclePhases(Document& document) {
    document.View()->UpdateAllLifecyclePhasesForTest();
  }
};

class UseCounterImplBrowserReportTest
    : public UseCounterImplTest,
      public ::testing::WithParamInterface</* URL */ const char*> {};

INSTANTIATE_TEST_SUITE_P(All,
                         UseCounterImplBrowserReportTest,
                         ::testing::Values("chrome-extension://dummysite/",
                                           "file://dummyfile",
                                           "data:;base64,",
                                           "ftp://ftp.dummy/dummy.txt",
                                           "http://foo.com",
                                           "https://bar.com"));

// UseCounter should not send events to browser when handling page with
// Non HTTP Family URLs, as these events will be discarded on the browser side
// in |MetricsWebContentsObserver::DoesTimingUpdateHaveError|.
TEST_P(UseCounterImplBrowserReportTest, ReportOnlyHTTPFamily) {
  KURL url = url_test_helpers::ToKURL(GetParam());
  SetURL(url);
  UseCounterImpl use_counter;
  use_counter.DidCommitLoad(GetFrame());

  // Count every feature types in UseCounterFeatureType.
  use_counter.Count(mojom::WebFeature::kFetch, GetFrame());
  use_counter.Count(CSSPropertyID::kHeight,
                    UseCounterImpl::CSSPropertyType::kDefault, GetFrame());
  use_counter.Count(CSSPropertyID::kHeight,
                    UseCounterImpl::CSSPropertyType::kAnimation, GetFrame());

  auto* dummy_client =
      static_cast<UseCounterImplBrowserReportTest::DummyLocalFrameClient*>(
          GetFrame()->Client());

  EXPECT_EQ(!dummy_client->observed_features().empty(),
            url.ProtocolIsInHTTPFamily());
}

TEST_F(UseCounterImplTest, RecordingExtensions) {
  const std::string histogram = kExtensionFeaturesHistogramName;
  constexpr auto item = mojom::WebFeature::kFetch;
  constexpr auto second_item = WebFeature::kFetchBodyStream;
  const std::string url = kExtensionUrl;
  CommonSchemeRegistry::RegisterURLSchemeAsExtension("chrome-extension");
  UseCounterImpl::Context context = UseCounterImpl::kExtensionContext;
  int page_visits_bucket = GetPageVisitsBucketforHistogram(histogram);

  UseCounterImpl use_counter0(context, UseCounterImpl::kCommited);

  // Test recording a single (arbitrary) counter
  EXPECT_FALSE(use_counter0.IsCounted(item));
  use_counter0.Count(item, GetFrame());
  EXPECT_TRUE(use_counter0.IsCounted(item));
  histogram_tester_.ExpectUniqueSample(histogram, static_cast<int>(item), 1);
  // Test that repeated measurements have no effect
  use_counter0.Count(item, GetFrame());
  histogram_tester_.ExpectUniqueSample(histogram, static_cast<int>(item), 1);

  // Test recording a different sample
  EXPECT_FALSE(use_counter0.IsCounted(second_item));
  use_counter0.Count(second_item, GetFrame());
  EXPECT_TRUE(use_counter0.IsCounted(second_item));
  histogram_tester_.ExpectBucketCount(histogram, static_cast<int>(item), 1);
  histogram_tester_.ExpectBucketCount(histogram, static_cast<int>(second_item),
                                      1);
  histogram_tester_.ExpectTotalCount(histogram, 2);

  // After a page load, the histograms will be updated, even when the URL
  // scheme is internal
  UseCounterImpl use_counter1(context);
  SetURL(url_test_helpers::ToKURL(url));
  use_counter1.DidCommitLoad(GetFrame());
  histogram_tester_.ExpectBucketCount(histogram, static_cast<int>(item), 1);
  histogram_tester_.ExpectBucketCount(histogram, static_cast<int>(second_item),
                                      1);
  histogram_tester_.ExpectBucketCount(histogram, page_visits_bucket, 1);
  histogram_tester_.ExpectTotalCount(histogram, 3);

  // Now a repeat measurement should get recorded again, exactly once
  EXPECT_FALSE(use_counter1.IsCounted(item));
  use_counter1.Count(item, GetFrame());
  use_counter1.Count(item, GetFrame());
  EXPECT_TRUE(use_counter1.IsCounted(item));
  histogram_tester_.ExpectBucketCount(histogram, static_cast<int>(item), 2);
  histogram_tester_.ExpectTotalCount(histogram, 4);
  CommonSchemeRegistry::RemoveURLSchemeAsExtensionForTest("chrome-extension");
}

TEST_F(UseCounterImplTest, CSSSelectorPseudoWhere) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorPseudoWhere;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "");
  EXPECT_TRUE(document.IsUseCounted(feature));
  EXPECT_FALSE(document.IsUseCounted(WebFeature::kCSSSelectorPseudoIs));
}

/*
 * Counter-specific tests
 *
 * NOTE: Most individual UseCounters don't need dedicated test cases.  They are
 * "tested" by analyzing the data they generate including on some known pages.
 * Feel free to add tests for counters where the triggering logic is
 * non-trivial, but it's not required. Manual analysis is necessary to trust the
 * data anyway, real-world pages are full of edge-cases and surprises that you
 * won't find in unit testing anyway.
 */

TEST_F(UseCounterImplTest, CSSSelectorPseudoAnyLink) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorPseudoAnyLink;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "");
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSSelectorPseudoWebkitAnyLink) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorPseudoWebkitAnyLink;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "");
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSTypedOMStylePropertyMap) {
  UseCounterImpl use_counter;
  WebFeature feature = WebFeature::kCSSTypedOMStylePropertyMap;
  EXPECT_FALSE(GetDocument().IsUseCounted(feature));
  GetDocument().CountUse(feature);
  EXPECT_TRUE(GetDocument().IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSSelectorPseudoIs) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorPseudoIs;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "");
  EXPECT_TRUE(document.IsUseCounted(feature));
  EXPECT_FALSE(document.IsUseCounted(WebFeature::kCSSSelectorPseudoWhere));
}

TEST_F(UseCounterImplTest, CSSSelectorPseudoDir) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorPseudoDir;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "");
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSGridLayoutPercentageColumnIndefiniteWidth) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kGridRowTrackPercentIndefiniteHeight;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "
"
      "
");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSFlexibleBox) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSFlexibleBox;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "
flexbox
");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSFlexibleBoxInline) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSFlexibleBox;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "
flexbox
");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSFlexibleBoxButton) {
  // LayoutButton is a subclass of LayoutFlexibleBox, however we don't want it
  // to be counted as usage of flexboxes as it's an implementation detail.
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSFlexibleBox;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML("<button>button</button>");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, HTMLRootContained) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kHTMLRootContained;
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.documentElement()->SetInlineStyleProperty(CSSPropertyID::kDisplay,
                                                     "none");
  document.documentElement()->SetInlineStyleProperty(CSSPropertyID::kContain,
                                                     "paint");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.documentElement()->SetInlineStyleProperty(CSSPropertyID::kDisplay,
                                                     "block");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, HTMLBodyContained) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kHTMLBodyContained;
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.body()->SetInlineStyleProperty(CSSPropertyID::kDisplay, "none");
  document.body()->SetInlineStyleProperty(CSSPropertyID::kContain, "paint");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.body()->SetInlineStyleProperty(CSSPropertyID::kDisplay, "block");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

class DeprecationTest : public testing::Test {
 public:
  DeprecationTest()
      : dummy_(std::make_unique<DummyPageHolder>()),
        deprecation_(dummy_->GetPage().GetDeprecation()),
        use_counter_(dummy_->GetDocument().Loader()->GetUseCounter()) {
    Page::InsertOrdinaryPageForTesting(&dummy_->GetPage());
  }

 protected:
  LocalFrame* GetFrame() { return &dummy_->GetFrame(); }

  std::unique_ptr<DummyPageHolder> dummy_;
  Deprecation& deprecation_;
  UseCounterImpl& use_counter_;
};

TEST_F(DeprecationTest, InspectorDisablesDeprecation) {
  // The specific feature we use here isn't important.
  WebFeature feature =
      WebFeature::kCSSSelectorInternalMediaControlsOverlayCastButton;

  deprecation_.MuteForInspector();
  Deprecation::CountDeprecation(GetFrame()->DomWindow(), feature);
  EXPECT_FALSE(use_counter_.IsCounted(feature));

  deprecation_.MuteForInspector();
  Deprecation::CountDeprecation(GetFrame()->DomWindow(), feature);
  EXPECT_FALSE(use_counter_.IsCounted(feature));

  deprecation_.UnmuteForInspector();
  Deprecation::CountDeprecation(GetFrame()->DomWindow(), feature);
  EXPECT_FALSE(use_counter_.IsCounted(feature));

  deprecation_.UnmuteForInspector();
  Deprecation::CountDeprecation(GetFrame()->DomWindow(), feature);
  EXPECT_TRUE(use_counter_.IsCounted(feature));
}

TEST_F(UseCounterImplTest, CSSUnknownNamespacePrefixInSelector) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSUnknownNamespacePrefixInSelector;
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.documentElement()->setInnerHTML(R"HTML(

  )HTML");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  document.documentElement()->setInnerHTML("");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSSelectorHostContextInLiveProfile) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorHostContextInLiveProfile;

  document.body()->setInnerHTML(R"HTML(

  )HTML");

  Element* host = document.getElementById("host");
  ASSERT_TRUE(host);
  ShadowRoot& shadow_root =
      host->AttachShadowRootInternal(ShadowRootType::kOpen);
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  shadow_root.setInnerHTML(R"HTML(

  )HTML");

  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSSelectorHostContextInSnapshotProfile) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSSelectorHostContextInSnapshotProfile;

  document.body()->setInnerHTML(R"HTML(

  )HTML");

  Element* host = document.getElementById("host");
  ASSERT_TRUE(host);
  ShadowRoot& shadow_root =
      host->AttachShadowRootInternal(ShadowRootType::kOpen);
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  shadow_root.setInnerHTML("");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));

  Element* span = shadow_root.QuerySelector(":host-context(#parent) span");
  EXPECT_TRUE(span);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, UniqueCSSSampleIds) {
  HashSet<int> ids;

  for (CSSPropertyID property : CSSPropertyIDList()) {
    if (IsInternal(property))
      continue;
    EXPECT_FALSE(ids.Contains(ToSampleId(property)));
    ids.insert(ToSampleId(property));
  }

  for (CSSPropertyID property : kCSSPropertyAliasList) {
    EXPECT_FALSE(ids.Contains(ToSampleId(property)));
    ids.insert(ToSampleId(property));
  }
}

TEST_F(UseCounterImplTest, MaximumCSSSampleId) {
  int max_sample_id = 0;

  for (CSSPropertyID property : CSSPropertyIDList()) {
    if (IsInternal(property))
      continue;
    max_sample_id = std::max(max_sample_id, ToSampleId(property));
  }

  for (CSSPropertyID property : kCSSPropertyAliasList)
    max_sample_id = std::max(max_sample_id, ToSampleId(property));

  EXPECT_EQ(static_cast<int>(mojom::blink::CSSSampleId::kMaxValue),
            max_sample_id);
}

TEST_F(UseCounterImplTest, CSSMarkerPseudoElementUA) {
  // Check that UA styles for list markers are not counted.
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kHasMarkerPseudoElement;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.body()->setInnerHTML(R"HTML(

  )HTML");
  UpdateAllLifecyclePhases(document);
  EXPECT_FALSE(document.IsUseCounted(feature));
}

TEST_F(UseCounterImplTest, CSSMarkerPseudoElementAuthor) {
  // Check that author styles for list markers are counted.
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kHasMarkerPseudoElement;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.body()->setInnerHTML(R"HTML(

  )HTML");
  UpdateAllLifecyclePhases(document);
  EXPECT_TRUE(document.IsUseCounted(feature));
}

}  // namespace blink


text:
<?xml version="1.0" encoding="utf-8"?>

<page color="#00759A" watermark="Watermark.png">

	<title>
		<number>1</number>
		<heading size="110" translate="true">GOD LOVES YOU AND OFFERS A WONDERFUL PLAN FOR YOUR LIFE.</heading>
	</title>

	<button tap-events="im-here">
		<buttontext translate="true">God's Love</buttontext>
		<panel>
			<text translate="true">"For God so loved the world that He gave His one and only Son, that whoever believes in Him shall not perish but have eternal life."</text>
            <text size="80" textalign="right" translate="true">(John 3:16, NIV)</text>
		</panel>
	</button>

	<button tap-events="rejected">
		<buttontext translate="true">God's Plan</buttontext>
		<panel>
			<text size="97" translate="true">[Christ speaking] "I came that they might have life, and might have it abundantly" [that it might be full and meaningful].</text>
            <text size="80" textalign="right" translate="true">(John 10:10)</text>
		</panel>
	</button>

	<question listeners="im-here" size="96" translate="true">Why is it that most people
are not experiencing the
abundant life?  Because...</question>

</page>

redpajama_set_name: RedPajamaGithub


text:
from django.conf import settings

def conf(request):
    return {
        'conf': {
            'docs_enabled': 'docs' in settings.INSTALLED_APPS,
        },
    }


text:
"""Double op is a user's defined op for testing purpose."""

from tensorflow.lite.python.testdata import double_op_wrapper
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import load_library
from tensorflow.python.platform import resource_loader

_double_op = load_library.load_op_library(
    resource_loader.get_path_to_datafile('_double_op.so'))

def double(input_tensor):
  """Double op applies element-wise double to input data."""
  if (input_tensor.dtype != dtypes.int32 and
      input_tensor.dtype != dtypes.float32):
    raise ValueError('Double op only accept int32 or float32 values.')
  return double_op_wrapper.double(input_tensor)


text:
import sys
from options import parser
from utils import container, target

def addOptions(parser):
    pass

def execCommand(args, following_args):
    if not target.get_current_target():
        print >>sys.stderr, 'Error: No target currently selected. Select a target before building your project'
        sys.exit(1)
    container.pass_through(args.subcommand_name, *following_args)


text:
package org.paukov.exercise.linkedlist;

/**
 * 148. Sort List (Medium).
 * https://leetcode.com/problems/sort-list/
 *
 * Sort a linked list in O(n log n) time using constant space complexity.
 *
 * Example 1:
 *
 * Input: 4->2->1->3
 * Output: 1->2->3->4
 * Example 2:
 *
 * Input: -1->5->3->4->0
 * Output: -1->0->3->4->5
 */
public class LC148_SortList {

  //Definition for singly-linked list.
  static class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
      val = x;
    }
  }

  // My initial accepted solution.
  // Better ideas here: https://leetcode.com/problems/sort-list/discuss/166324/c%2B%2B-and-java-legit-solution.-O(nlogn)-time-and-O(1)-space!-No-recursion!-With-detailed-explaination
  public ListNode sortList(ListNode head) {
    if (head==null){
      return null;
    }
    if (head.next==null){
      return head;
    }

    ListNode curr = new ListNode(head.val);
    ListNode prev = null;
    ListNode res = curr;
    head = head.next;

    while(head !=null){
      int val = head.val;

      while(curr!=null && curr.val<=val){
        prev = curr;
        curr = curr.next;
      }

      ListNode node = new ListNode(val);
      node.next = curr;

      if (prev!=null){
        prev.next = node;
      } else {
        res = node;
      }

      head = head.next;
      curr = res;
      prev = null;

    }

    return res;
  }

}


text:
function ParsedResult(result){

    result = result || {};

    this.index = result.index;
    this.text  = result.text;

    this.number = result.number;
    this.numberMin = result.numberMin;
    this.numberMax = result.numberMax;
    this.currency = result.currency;

    this.tags = result.tags || {};
    if (result.tag) {
    	this.tags[result.tag] = true;
    }
}

ParsedResult.prototype.clone = function() {
    return new ParsedResult(this);
}

exports.ParsedResult = ParsedResult;


text:
package com.urbanairship.datacube.bucketers;

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

import org.joda.time.DateTime;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;

public class HourDayMonthBucketer implements Bucketer<DateTime> {
    public static final BucketType hours = new BucketType("hour", new byte[]{1});
    public static final BucketType days = new BucketType("day", new byte[]{2});
    public static final BucketType months = new BucketType("month", new byte[]{3});
    public static final BucketType years = new BucketType("year", new byte[]{4});
    public static final BucketType weeks = new BucketType("weeks", new byte[]{5});

    static final Set<BucketType> ALL_BUCKET_TYPES = ImmutableSet.<BucketType>builder().
            add(hours).add(days).add(months).add(years).add(weeks).build();

    private final List<BucketType> bucketTypes;

    // TODO move this class to TimeBucker and have HourDayMonthBucketer be a subclass that
    // just calls super(ImmutableList.of(hours, days, months))
    public HourDayMonthBucketer() {
        this(ImmutableList.of(hours, days, months));
    }

    public HourDayMonthBucketer(List<BucketType> bucketTypes) {
        this.bucketTypes = ImmutableList.copyOf(bucketTypes); // defensive copy
        for(BucketType bucketType: bucketTypes) {
            if(!ALL_BUCKET_TYPES.contains(bucketType)) {
                throw new IllegalArgumentException("Invalid bucket type " + bucketType +
                        ", expected one of " + ALL_BUCKET_TYPES);
            }
        }
    }

    @Override
    public SetMultimap<BucketType, CSerializable> bucketForWrite(
            DateTime coordinate) {
        ImmutableSetMultimap.Builder<BucketType,CSerializable> builder =
                ImmutableSetMultimap.builder();
        for(BucketType bucketType: bucketTypes) {
            builder.put(bucketType, bucket(coordinate, bucketType));
        }
        return builder.build();
    }

    @Override
    public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
        DateTime inputTime = (DateTime)coordinateField;
        return bucket(inputTime, bucketType);
    }

    private CSerializable bucket(DateTime inputTime, BucketType bucketType) {
        DateTime returnVal;
        if(bucketType == hours) {
            returnVal = hourFloor(inputTime);
        } else if(bucketType == days) {
            returnVal = dayFloor(inputTime);
        } else if(bucketType == months) {
            returnVal = monthFloor(inputTime);
        } else if(bucketType == years) {
            returnVal = yearFloor(inputTime);
        } else if(bucketType == weeks) {
            returnVal = weekFloor(inputTime);
        } else {
            throw new RuntimeException("Unexpected bucket type " + bucketType);
        }
        return new LongSerializable(returnVal.getMillis());
    }

    @Override
    public List<BucketType> getBucketTypes() {
        return ImmutableList.of(hours, days, months, years, weeks);
    }

    public static DateTime hourFloor(DateTime dt) {
        return dt.withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0);
    }

    public static DateTime dayFloor(DateTime dt) {
        return hourFloor(dt).withHourOfDay(0);
    }

    public static DateTime monthFloor(DateTime dt) {
        return dayFloor(dt).withDayOfMonth(1);
    }

    public static DateTime yearFloor(DateTime dt) {
        return monthFloor(dt).withMonthOfYear(1);
    }

    public static DateTime weekFloor(DateTime dt) {
        return dayFloor(dt.minusDays(dt.getDayOfWeek() -1));
    }
}


text:
package well

import (
	"context"
	"sync"

	"github.com/cybozu-go/log"
)

// Environment implements context-based goroutine management.
type Environment struct {
	ctx       context.Context
	cancel    context.CancelFunc
	wg        sync.WaitGroup
	generator *IDGenerator

	mu       sync.RWMutex
	stopped  bool
	stopCh   chan struct{}
	canceled bool
	err      error
}

// NewEnvironment creates a new Environment.
//
// This does *not* install signal handlers for SIGINT/SIGTERM
// for new environments.  Only the global environment will be
// canceled on these signals.
func NewEnvironment(ctx context.Context) *Environment {
	ctx, cancel := context.WithCancel(ctx)
	e := &Environment{
		ctx:       ctx,
		cancel:    cancel,
		generator: NewIDGenerator(),
		stopCh:    make(chan struct{}),
	}
	return e
}

// Stop just declares no further Go will be called.
//
// Calling Stop is optional if and only if Cancel is guaranteed
// to be called at some point.  For instance, if the program runs
// until SIGINT or SIGTERM, Stop is optional.
func (e *Environment) Stop() {
	e.mu.Lock()

	if !e.stopped {
		e.stopped = true
		close(e.stopCh)
	}

	e.mu.Unlock()
}

// Cancel cancels the base context.
//
// Passed err will be returned by Wait().
// Once canceled, Go() will not start new goroutines.
//
// Note that calling Cancel(nil) is perfectly valid.
// Unlike Stop(), Cancel(nil) cancels the base context and can
// gracefully stop goroutines started by Server.Serve or
// HTTPServer.ListenAndServe.
//
// This returns true if the caller is the first that calls Cancel.
// For second and later calls, Cancel does nothing and returns false.
func (e *Environment) Cancel(err error) bool {
	e.mu.Lock()
	defer e.mu.Unlock()

	if e.canceled {
		return false
	}
	e.canceled = true
	e.err = err
	e.cancel()

	if e.stopped {
		return true
	}

	e.stopped = true
	close(e.stopCh)
	return true
}

// Wait waits for Stop or Cancel, and for all goroutines started by
// Go to finish.
//
// The returned err is the one passed to Cancel, or nil.
// err can be tested by IsSignaled to determine whether the
// program got SIGINT or SIGTERM.
func (e *Environment) Wait() error {
	<-e.stopCh
	if log.Enabled(log.LvDebug) {
		log.Debug("well: waiting for all goroutines to complete", nil)
	}
	e.wg.Wait()
	e.cancel() // in case no one calls Cancel

	e.mu.Lock()
	defer e.mu.Unlock()

	return e.err
}

// Go starts a goroutine that executes f.
//
// f takes a drived context from the base context.  The context
// will be canceled when f returns.
//
// Goroutines started by this function will be waited for by
// Wait until all such goroutines return.
//
// If f returns non-nil error, Cancel is called immediately
// with that error.
//
// f should watch ctx.Done() channel and return quickly when the
// channel is closed.
func (e *Environment) Go(f func(ctx context.Context) error) {
	e.mu.RLock()
	if e.stopped {
		e.mu.RUnlock()
		return
	}
	e.wg.Add(1)
	e.mu.RUnlock()

	go func() {
		ctx, cancel := context.WithCancel(e.ctx)
		defer cancel()
		err := f(ctx)
		if err != nil {
			e.Cancel(err)
		}
		e.wg.Done()
	}()
}

// GoWithID calls Go with a context having a new request tracking ID.
func (e *Environment) GoWithID(f func(ctx context.Context) error) {
	e.Go(func(ctx context.Context) error {
		return f(WithRequestID(ctx, e.generator.Generate()))
	})
}


text:
<TagDefinition version="2">
 <Tags>
  <Tag name="Idle"/>
  <Tag name="Move"/>
  <Tag name="Interaction"/>
  <Tag name="Emote"/>
  <Tag name="Aiming"/>
  <Tag name="AimPose"/>
  <Tag name="Looking"/>
  <Tag name="LookPose"/>
  <Tag name="Weapon"/>
  <Tag name="AttachmentTop"/>
  <Tag name="AttachmentBottom"/>
  <Tag name="LadderGetOn"/>
  <Tag name="LadderGetOff"/>
  <Tag name="LadderClimb"/>
  <Tag name="LedgeGrab"/>
 </Tags>
</TagDefinition>


text:
package edu.umass.cs.voice;

import java.util.Arrays;

public class FeatureExtractor {

	private static final int FFT_SIZE = 8192;
	private static final int BITRATE = 8000;
    private static final int MFCCS_VALUE = 12;
    private static final int MEL_BANDS = 20;

    private static FFT featureFFT = new FFT(FFT_SIZE);
    private static Window featureWin = new Window(BITRATE);
    private static MFCC featureMFCC = new MFCC(FFT_SIZE, MFCCS_VALUE, MEL_BANDS, BITRATE);

    public static double[] ComputeFeaturesForFrame(short[] data16bit, int size, int index)
	{
		double[] fftBufferR = new double[FFT_SIZE];
        double[] fftBufferI = new double[FFT_SIZE];
        double[] featureCepstrum = new double[MFCCS_VALUE];

        // Frequency analysis
        Arrays.fill(fftBufferR, 0);
        Arrays.fill(fftBufferI, 0);

        // Convert audio buffer to doubles
        for (int i = 0; i < size; i++)
        {
                fftBufferR[i] = data16bit[index+i];
        }

        // In-place windowing
        featureWin.applyWindow(fftBufferR);

        // In-place FFT
        featureFFT.fft(fftBufferR, fftBufferI);

        // Get MFCCs
        featureCepstrum = featureMFCC.cepstrum(fftBufferR, fftBufferI);

        return featureCepstrum;
	}

}


text:
package id.tamkin.identity.dao;

import id.tamkin.identity.entity.UserPassword;
import org.springframework.data.repository.CrudRepository;

public interface UserPasswordDao extends CrudRepository<UserPassword, String> {
}


text:
@import WMF.WMFLegacyFetcher;

@class MWKDataStore;

NS_ASSUME_NONNULL_BEGIN

extern NSString *const WMFArticleSaveToDiskDidFailNotification;
extern NSString *const WMFArticleSaveToDiskDidFailErrorKey;
extern NSString *const WMFArticleSaveToDiskDidFailArticleURLKey;

@interface SavedArticlesFetcher : WMFLegacyFetcher <NSProgressReporting>

@property (nonatomic, strong) NSProgress *progress;

@property (nonatomic, strong, readonly) NSNumber *fetchesInProcessCount;

- (instancetype)initWithDataStore:(MWKDataStore *)dataStore;

- (void)start;
- (void)stop;

@end

NS_ASSUME_NONNULL_END


text:
namespace visionaray
{
namespace cuda
{

graphics_resource::graphics_resource()
    : resource_(0)
    , dev_ptr_(0)
{
}

graphics_resource::~graphics_resource()
{
    unregister();
}

cudaGraphicsResource_t graphics_resource::get() const
{
    return resource_;
}

cudaError_t graphics_resource::register_buffer(unsigned buffer, cudaGraphicsRegisterFlags flags)
{
    unregister();
    return cudaGraphicsGLRegisterBuffer(&resource_, buffer, flags);
}

cudaError_t graphics_resource::register_image(unsigned image, unsigned target, cudaGraphicsRegisterFlags flags)
{
    unregister();
    return cudaGraphicsGLRegisterImage(&resource_, image, target, flags);
}

cudaError_t graphics_resource::unregister()
{
    if (resource_ == 0)
    {
        return cudaSuccess;
    }

    auto result = cudaGraphicsUnregisterResource(resource_);
    resource_ = 0;
    return result;
}

void* graphics_resource::map(size_t* size)
{
    auto err = cudaGraphicsMapResources(1, &resource_);
    if (err != cudaSuccess)
    {
        return 0;
    }

    err = cudaGraphicsResourceGetMappedPointer(&dev_ptr_, size, resource_);
    if (err != cudaSuccess)
    {
        cudaGraphicsUnmapResources(1, &resource_);
        dev_ptr_ = 0;
    }

    return dev_ptr_;
}

void* graphics_resource::map()
{
    size_t size = 0;
    return map(&size);
}

void graphics_resource::unmap()
{
    if (dev_ptr_ == 0)
    {
        return;
    }

    cudaGraphicsUnmapResources(1, &resource_);
    dev_ptr_ = 0;
}

void* graphics_resource::dev_ptr() const
{
    return dev_ptr_;
}

} // cuda
} // visionaray

#endif // VSNRAY_HAVE_CUDA


text:
'use strict';

/**
 * @ngdoc function
 * @name wavesApp.controller:SimpleresponseCtrl
 * @description
 * # SimpleresponseCtrl
 * Controller of the wavesApp
 */
angular.module('wavesApp')
  .controller('SimpleResponseCtrl', ['$rootScope', '$scope', '$state', '$stateParams', 'speechSynthesis',
    function ($rootScope, $scope, $state, $stateParams, speechSynthesis) {
    if($stateParams.response){
      $scope.response = $stateParams.response.content;
      // speechSynthesis.say($scope.response, {lang:'es-AR'}, {
      //   onend: function(e) {
          // $rootScope.speechRecognition.start();
      //   }
      // });
    }else{
      $state.go('boot')
    }
  }]);


text:
public class Bike {
	private String color;
	private int price;
	private int size;

	/**Constructors*/

	public Bike (String color, int size){
		this.color = color;
		this.size = size;
	}

	/**Limitations. A value that are not in the right area will give a error message. */
	public Bike (String color, int size, int price){
		for(int i = 0; i < Constants.bikeColors.length; i++){
			if(0 == color.compareTo(Constants.bikeColors[i].toString())){
				this.color = color;
				break;
			} else {
				this.color = "ERROR";
			}
		}
		if(size > Constants.MIN_SIZE && size <= Constants.MAX_SIZE){
			this.size = size;
		} else{
			this.size = 404;
		}

		if(price > Constants.MIN_PRICE && price <= Constants.MAX_PRICE){
			this.price = price;
		} else {
			this.price = 404;
		}

	}

	/**Methods*/
	public String getColor(){
		return this.color;
	}
	public int getSize(){
		return this.size;
	}
	public int getPrice(){
		return this.price;
	}
	public void setPrice (int price){

	}

}


text:
namespace IoT {
namespace Devices {

class IORemoteObject: public IoT::Devices::IIO, public Poco::RemotingNG::RemoteObject
	/// The interface for general purpose input/output (GPIO)
	/// ports.
	///
	/// This class represents a single GPIO pin.
	/// Mapping to physical pins is configured when setting up
	/// the specific IO implementation class, typically using a
	/// configuration file.
	///
	/// Implementations supporting dynamically changing pin directions
	/// should expose a string property named "direction" that takes the
	/// values "in" and "out".
{
public:
	typedef Poco::AutoPtr<IORemoteObject> Ptr;

	IORemoteObject(const Poco::RemotingNG::Identifiable::ObjectId& oid, Poco::SharedPtr<IoT::Devices::IO> pServiceObject);
		/// Creates a IORemoteObject.

	virtual ~IORemoteObject();
		/// Destroys the IORemoteObject.

	virtual bool getFeature(const std::string& name) const;
		/// Returns true if the feature with the given name
		/// is enabled, or false otherwise.

	virtual bool getPropertyBool(const std::string& name) const;
		/// Returns the value of the device property with
		/// the given name.
		///
		/// Throws a Poco::NotFoundException if the property
		/// with the given name is unknown.

	virtual double getPropertyDouble(const std::string& name) const;
		/// Returns the value of the device property with
		/// the given name.
		///
		/// Throws a Poco::NotFoundException if the property
		/// with the given name is unknown.

	virtual int getPropertyInt(const std::string& name) const;
		/// Returns the value of the device property with
		/// the given name.
		///
		/// Throws a Poco::NotFoundException if the property
		/// with the given name is unknown.

	virtual std::string getPropertyString(const std::string& name) const;
		/// Returns the value of the device property with
		/// the given name.
		///
		/// Throws a Poco::NotFoundException if the property
		/// with the given name is unknown.

	virtual bool hasFeature(const std::string& name) const;
		/// Returns true if the feature with the given name
		/// is known, or false otherwise.

	virtual bool hasProperty(const std::string& name) const;
		/// Returns true if the property with the given name
		/// exists, or false otherwise.

	virtual std::string remoting__enableEvents(Poco::RemotingNG::Listener::Ptr pListener, bool enable = bool(true));

	virtual void remoting__enableRemoteEvents(const std::string& protocol);

	virtual bool remoting__hasEvents() const;

	virtual const Poco::RemotingNG::Identifiable::TypeId& remoting__typeId() const;

	virtual bool sentPaMessage(const std::string& name) const;
		/// Returns true if the feature with the given name
		/// is known, or false otherwise.

	virtual void set(bool state);
		/// Sets the state of an output pin to the given state.

	virtual void setFeature(const std::string& name, bool enable);
		/// Enables or disables the feature with the given name.
		///
		/// Which features are supported is defined by the
		/// actual device implementation.

	virtual void setPropertyBool(const std::string& name, bool value);
		/// Sets a device property.
		///
		/// Which properties are supported is defined by the
		/// actual device implementation.

	virtual void setPropertyDouble(const std::string& name, double value);
		/// Sets a device property.
		///
		/// Which properties are supported is defined by the
		/// actual device implementation.

	virtual void setPropertyInt(const std::string& name, int value);
		/// Sets a device property.
		///
		/// Which properties are supported is defined by the
		/// actual device implementation.

	virtual void setPropertyString(const std::string& name, const std::string& value);
		/// Sets a device property.
		///
		/// Which properties are supported is defined by the
		/// actual device implementation.

	virtual bool state() const;
		/// Returns the current state of the pin.

protected:
	void event__stateChanged(const bool& data);

private:
	Poco::SharedPtr<IoT::Devices::IO> _pServiceObject;
};

inline bool IORemoteObject::getFeature(const std::string& name) const
{
	return _pServiceObject->getFeature(name);
}

inline bool IORemoteObject::getPropertyBool(const std::string& name) const
{
	return _pServiceObject->getPropertyBool(name);
}

inline double IORemoteObject::getPropertyDouble(const std::string& name) const
{
	return _pServiceObject->getPropertyDouble(name);
}

inline int IORemoteObject::getPropertyInt(const std::string& name) const
{
	return _pServiceObject->getPropertyInt(name);
}

inline std::string IORemoteObject::getPropertyString(const std::string& name) const
{
	return _pServiceObject->getPropertyString(name);
}

inline bool IORemoteObject::hasFeature(const std::string& name) const
{
	return _pServiceObject->hasFeature(name);
}

inline bool IORemoteObject::hasProperty(const std::string& name) const
{
	return _pServiceObject->hasProperty(name);
}

inline const Poco::RemotingNG::Identifiable::TypeId& IORemoteObject::remoting__typeId() const
{
	return IIO::remoting__typeId();
}

inline bool IORemoteObject::sentPaMessage(const std::string& name) const
{
	return _pServiceObject->sentPaMessage(name);
}

inline void IORemoteObject::set(bool state)
{
	_pServiceObject->set(state);
}

inline void IORemoteObject::setFeature(const std::string& name, bool enable)
{
	_pServiceObject->setFeature(name, enable);
}

inline void IORemoteObject::setPropertyBool(const std::string& name, bool value)
{
	_pServiceObject->setPropertyBool(name, value);
}

inline void IORemoteObject::setPropertyDouble(const std::string& name, double value)
{
	_pServiceObject->setPropertyDouble(name, value);
}

inline void IORemoteObject::setPropertyInt(const std::string& name, int value)
{
	_pServiceObject->setPropertyInt(name, value);
}

inline void IORemoteObject::setPropertyString(const std::string& name, const std::string& value)
{
	_pServiceObject->setPropertyString(name, value);
}

inline bool IORemoteObject::state() const
{
	return _pServiceObject->state();
}

} // namespace Devices
} // namespace IoT

#endif // IoT_Devices_IORemoteObject_INCLUDED


text:
module.exports = {
  resolveTestPath: () => {},
  testPathForConsistencyCheck: 'foo/__tests__/bar.test.js',
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class twitter4j.FilterQuery (twitter4j-stream 3.0.4 API)</title>
<meta name="date" content="2013-10-08">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
twitter4j.FilterQuery

Uses of FilterQuery in twitter4j

Methods in twitter4j that return FilterQuery

Modifier and Type
Method and Description

FilterQuery
FilterQuery.count(int count)

Sets count

FilterQuery
FilterQuery.follow(long[] follow)

Sets follow

FilterQuery
FilterQuery.language(String[] language)

Sets language

FilterQuery
FilterQuery.locations(double[][] locations)

Sets locations

FilterQuery
FilterQuery.track(String[] track)

Sets track

Methods in twitter4j with parameters of type FilterQuery

Modifier and Type
Method and Description

void
TwitterStream.filter(FilterQuery query)

Start consuming public statuses that match one or more filter predicates.

StatusStream
TwitterStream.getFilterStream(FilterQuery query)

Deprecated.

use TwitterStream.filter(FilterQuery) instead

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2013. All Rights Reserved.


text:
import cuttsum.events
import cuttsum.corpora
from cuttsum.pipeline import InputStreamResource
from cuttsum.classifiers import NuggetRegressor
import cuttsum.judgements
import pandas as pd
import numpy as np
from datetime import datetime
from cuttsum.misc import event2semsim
from sklearn.cluster import AffinityPropagation
from collections import defaultdict
from sklearn.metrics.pairwise import cosine_similarity

matches_df = cuttsum.judgements.get_merged_dataframe()
def get_input_stream(event, gold_probs, extractor="goose", thresh=.8, delay=None, topk=20):
    max_nuggets = 3
    corpus = cuttsum.corpora.get_raw_corpus(event)
    res = InputStreamResource()
    df = pd.concat(
        res.get_dataframes(event, corpus, extractor, thresh, delay, topk))

    selector = (df["n conf"] == 1) & (df["nugget probs"].apply(len) == 0)
    df.loc[selector, "nugget probs"] = df.loc[selector, "nuggets"].apply(lambda x: {n:1 for n in x})

    df["true probs"] = df["nugget probs"].apply(lambda x: [val for key, val in x.items()] +[0])
    df["true probs"] = df["true probs"].apply(lambda x: np.max(x))
    df.loc[(df["n conf"] == 1) & (df["nuggets"].apply(len) == 0), "true probs"] = 0

    if gold_probs is True:
        df["probs"] = df["true probs"]
    else:
        df["probs"] = NuggetRegressor().predict(event, df)

    df["nuggets"] = df["nugget probs"].apply(
        lambda x: set([key for key, val in x.items() if val > .9]))

    nid2time = {}
    nids = set(matches_df[matches_df["query id"] == event.query_id]["nugget id"].tolist())
    for nid in nids:
        ts = matches_df[matches_df["nugget id"] == nid]["update id"].apply(lambda x: int(x.split("-")[0])).tolist()
        ts.sort()
        nid2time[nid] = ts[0]

    fltr_nuggets = []
    for name, row in df.iterrows():
        fltr_nuggets.append(
            set([nug for nug in row["nuggets"] if nid2time[nug] <= row["timestamp"]]))
    #print df[["nuggets", "timestamp"]].apply(lambda y: print y[0]) #  datetime.utcfromtimestamp(int(y["timestamp"])))
    #print nids
    df["nuggets"] = fltr_nuggets

    df["nuggets"] = df["nuggets"].apply(lambda x: x if len(x) <= max_nuggets else set([]))

    return df

event2nuggets = defaultdict(set)
event2size = {}

data = []
for event in cuttsum.events.get_events():
    if event.query_num == 7 or event.query_num > 25: continue
    print event
    istream = get_input_stream(event, False)
    event2size[event] = len(istream)

    for nuggets in istream["nuggets"].tolist():
        event2nuggets[event].update(nuggets)

    with open("clusters/{}.tsv".format(event.query_id), "r") as f:
        df = pd.read_csv(f, sep="\t", converters={"stems": eval, "nuggets": eval})
    data.append((event, df))

all_results = []
for thresh in np.arange(.05, .95, .05):
    print thresh
    results = []

    for event, df in data:
        cache = None
        semsim = event2semsim(event)
        nuggets = set()
        for ts, batch in df.groupby("timestamp"):
            X = semsim.transform(batch["stems"].apply(lambda x: ' '.join(x)).tolist())
            for i, (_, row) in enumerate(batch.iterrows()):
                if cache is None:
                    cache = X[i]
                    nuggets.update(row["nuggets"])
                else:
                    K = cosine_similarity(cache, X[i])
                    if (K < thresh).all():
                        cache = np.vstack([cache, X[i]])
                        nuggets.update(row["nuggets"])

        egain = len(nuggets) / float(cache.shape[0])
        comp = len(nuggets) / float(len(event2nuggets[event]))
        f1 = 2 * (egain * comp) / (comp + egain) if comp + egain > 0 else 0
        results.append({"thr": thresh, "event": event.query_id, "E[gain]": egain, "Comp.": comp, "F1": f1, "size": event2size[event]})
        all_results.append({"thr": thresh, "event": event.query_id, "E[gain]": egain, "Comp.": comp, "F1": f1, "size": event2size[event]})
        print pd.DataFrame(results, columns=["thr", "event", "size", "E[gain]", "Comp.", "F1"])

df = pd.DataFrame(all_results, columns=["thr", "event", "size", "E[gain]", "Comp.", "F1"])
with open("filters.tsv", "w") as f:
    df.to_csv(f, sep="\t", index=False)


text:
#ifndef SLIDE_PLAY_BOARD_UTILITY_HPP_
#define SLIDE_PLAY_BOARD_UTILITY_HPP_

#include "Direction.hpp"
#include "Point.hpp"

namespace slide
{

template<typename Base>
class PlayBoardUtility : public Base
{
public:
    using Base::Base;
    using Base::selected;

    /**************************************************************************
     * The move operations
     *************************************************************************/

    void moveUp() {
        Base::move(Direction::Up);
    }

    void moveRight() {
        Base::move(Direction::Right);
    }

    void moveDown() {
        Base::move(Direction::Down);
    }

    void moveLeft() {
        Base::move(Direction::Left);
    }

    void moveVertically(int dstY) {
        const int n = selected.y - dstY;
        rep(i, n)  moveUp();
        rep(i, -n) moveDown();
    }

    void moveHorizontally(int dstX) {
        const int n = selected.x - dstX;
        rep(i, n)  moveLeft();
        rep(i, -n) moveRight();
    }

    /**************************************************************************
     * The select operations
     *************************************************************************/

    void select(Point newSelect) {
        Base::select(newSelect);
    }

    void select(int y, int x) {
        Base::select(Point(y, x));
    }
};

} // end of namespace slide

#endif


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Ill. bot. Himal. Mts. 1(6):215; 2(6): t. 61. 1835

#### Original name
null

### Remarks
null


text:
title: Install conda
excerpt: Quick installation guide for conda, along with tips for managing environments.
tags: [conda, hpc, bash, python, r]
redirect_from:
  - /r_bioconda
  - /r_hpc
  - /posts/r-bioconda.html
  - /posts/r-hpc.html
---

{%- include library.md -%}

# Install [conda][]

We recommend installing [conda][] using either [Miniconda][] (minimal; faster) or [Anaconda][] (complete distribution).

## Updating

Once you have conda installed on your machine, ensure the base installation is up to date. Note that this may require `sudo` permissions for a shared installation; for example, this can apply when conda is installed into `/usr/local/bin/`.

### Miniconda

```sh
conda deactivate
conda update --name="base" --channel="defaults" conda
conda update --name="base" --channel="defaults" --all
```

### Anaconda

**Important:** Don't run `conda update --all` on an Anaconda installation. This can lead to an unstable base environment.

```sh
conda deactivate
conda update --name="base" --channel="defaults" conda
conda update --name="base" --channel="defaults" anaconda
```

## `.bashrc` configuration

As of the conda v4.4 update, the recommended activation configuration has changed. Now a profile script must be sourced in `.bashrc`:

```sh
source "$CONDA_DIR/etc/profile.d/conda.sh"
```

Previously, up to v4.3, the location of the `bin/` directory should be exported into `$PATH` in `~/.bashrc`:

```sh
export PATH="$CONDA_DIR/bin:$PATH"
```

This method is no longer recommended. Source the activation script instead.

My [koopa][] bootloader handles conda activation automatically, and is recommended for deployment across virtual machine instances.

Also, if you prefer [zsh][] over [bash][], note that conda also supports that shell (refer to the documentation for configuration).

## Set up channels

Ensure that [bioconda][] channels are added in the following order:

```sh
conda config --add channels defaults
conda config --add channels bioconda
conda config --add channels conda-forge
```

A `.condarc` file should be created that contains the following:

```
channels:
  - conda-forge
  - bioconda
  - defaults
```

Note that the `r` channel should not be in your `.condarc` file. This is no longer recommended.

# Manging environments

A list of installed [conda][] environments can be obtained with:

```sh
conda env list
```

There are two ways to create (and activate) an environment:

```sh
conda create --name="default" shellcheck
conda activate default
```

```sh
conda create --name="default"
conda activate default
conda install shellcheck
```

Typically I prefer using the first method, but either approaches work.

An environment can be deactivated with:

```sh
conda deactivate
```

Here's how to remove an environment:

```sh
conda env remove --name="default"
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
EdgeEndBuilder
</TITLE>

<META NAME="keywords" CONTENT="com.vividsolutions.jts.operation.relate.EdgeEndBuilder class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.vividsolutions.jts.operation.relate

Class EdgeEndBuilder

java.lang.Object
  com.vividsolutions.jts.operation.relate.EdgeEndBuilder

public class EdgeEndBuilder
extends java.lang.Object

Computes the EdgeEnds which arise from a noded Edge.

Version:

1.7

Constructor Summary

EdgeEndBuilder()

Method Summary

 void
computeEdgeEnds(Edge edge,
                java.util.List l)

          Creates stub edges for all the intersections in this
 Edge (if any) and inserts them into the graph.

 java.util.List
computeEdgeEnds(java.util.Iterator edges)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EdgeEndBuilder

public EdgeEndBuilder()

Method Detail

computeEdgeEnds

public java.util.List computeEdgeEnds(java.util.Iterator edges)

computeEdgeEnds

public void computeEdgeEnds(Edge edge,
                            java.util.List l)

Creates stub edges for all the intersections in this
 Edge (if any) and inserts them into the graph.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text: <meta http-equiv="REFRESH" content="0;url=https://tailhq.github.io/DynaML/">


text:
package com.tectonica.jonix.onix2;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixElement;
import com.tectonica.jonix.common.codelist.IllustrationAndOtherContentTypes;
import com.tectonica.jonix.common.codelist.Languages;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.codelist.TextCaseFlags;
import com.tectonica.jonix.common.codelist.TextFormats;
import com.tectonica.jonix.common.codelist.TransliterationSchemes;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Illustration or other content type code

 *

 * An ONIX code which identifies the type of illustration or other content to which an occurrence of the composite
 * refers. Mandatory in each occurrence of the <Illustrations> composite, and non-repeating.
 *

 *

 *

 * Format
 * Fixed-length, two numeric digits.
 *

 *

 * Codelist
 * List 25
 *

 *

 * Reference name
 * <tt><IllustrationType></tt>
 *

 *

 * Short tag
 * <tt><b256></tt>
 *

 *

 * Example
 * <tt><b256>09</b256></tt> Illustrations (unspecified)
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Illustrations}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link Illustrations} ⯈ {@link IllustrationType}

 *

 */
public class IllustrationType implements OnixElement<IllustrationAndOtherContentTypes>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "IllustrationType";
    public static final String shortname = "b256";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    public TextFormats textformat;

    public TextCaseFlags textcase;

    public Languages language;

    public TransliterationSchemes transliteration;

    /**
     * (type: DateOrDateTime)
     */
    public String datestamp;

    public RecordSourceTypes sourcetype;

    public String sourcename;

    /////////////////////////////////////////////////////////////////////////////////
    // VALUE MEMBER
    /////////////////////////////////////////////////////////////////////////////////

    public IllustrationAndOtherContentTypes value;

    /**
     * Internal API, use the {@link #value()} method or the {@link #value} field instead
     */
    @Override
    public IllustrationAndOtherContentTypes _value() {
        return value;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // SERVICES
    /////////////////////////////////////////////////////////////////////////////////

    private final boolean exists;
    public static final IllustrationType EMPTY = new IllustrationType();

    public IllustrationType() {
        exists = false;
    }

    public IllustrationType(org.w3c.dom.Element element) {
        exists = true;
        textformat = TextFormats.byCode(JPU.getAttribute(element, "textformat"));
        textcase = TextCaseFlags.byCode(JPU.getAttribute(element, "textcase"));
        language = Languages.byCode(JPU.getAttribute(element, "language"));
        transliteration = TransliterationSchemes.byCode(JPU.getAttribute(element, "transliteration"));
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
        sourcename = JPU.getAttribute(element, "sourcename");

        value = IllustrationAndOtherContentTypes.byCode(JPU.getContentAsString(element));
    }

    /**
     * @return whether this tag (<IllustrationType> or <b256>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }
}


text:
package io.subutai.core.environment.impl.workflow.creation.steps;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

import com.google.common.collect.Maps;

import io.subutai.common.environment.HostAddresses;
import io.subutai.common.environment.Topology;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.EnvironmentContainerHost;
import io.subutai.common.peer.Peer;
import io.subutai.common.peer.PeerException;
import io.subutai.common.tracker.TrackerOperation;
import io.subutai.common.util.PeerUtil;
import io.subutai.core.environment.api.exception.EnvironmentManagerException;
import io.subutai.core.environment.impl.entity.LocalEnvironment;

public class RegisterHostsStep
{
    private final Topology topology;
    private final LocalEnvironment environment;
    private final TrackerOperation trackerOperation;
    PeerUtil<Object> hostUtil = new PeerUtil<>();

    public RegisterHostsStep( final Topology topology, final LocalEnvironment environment,
                              final TrackerOperation trackerOperation )
    {
        this.topology = topology;
        this.environment = environment;
        this.trackerOperation = trackerOperation;
    }

    public void execute() throws EnvironmentManagerException, PeerException
    {
        if ( !environment.getContainerHosts().isEmpty() && topology.registerHosts() )
        {
            registerHosts( environment.getContainerHosts() );
        }
    }

    void registerHosts( Set<EnvironmentContainerHost> hosts ) throws EnvironmentManagerException, PeerException
    {

        Set<Peer> peers = environment.getPeers();

        final Map<String, String> hostAddresses = Maps.newHashMap();

        for ( ContainerHost host : hosts )
        {
            hostAddresses.put( host.getHostname(), host.getIp() );
        }

        for ( final Peer peer : peers )
        {
            hostUtil.addPeerTask( new PeerUtil.PeerTask<>( peer, new Callable<Object>()
            {
                @Override
                public Object call() throws Exception
                {
                    peer.configureHostsInEnvironment( environment.getEnvironmentId(),
                            new HostAddresses( hostAddresses ) );

                    return null;
                }
            } ) );
        }

        PeerUtil.PeerTaskResults<Object> hostResults = hostUtil.executeParallel();

        for ( PeerUtil.PeerTaskResult hostResult : hostResults.getResults() )
        {

            if ( hostResult.hasSucceeded() )
            {
                trackerOperation
                        .addLog( String.format( "Registered hosts on peer %s", hostResult.getPeer().getName() ) );
            }
            else
            {
                trackerOperation.addLog( String.format( "Failed to register hosts on peer %s. Reason: %s",
                        hostResult.getPeer().getName(), hostResult.getFailureReason() ) );
            }
        }

        if ( hostResults.hasFailures() )
        {
            throw new EnvironmentManagerException( "Failed to register hosts on all peers" );
        }
    }
}


text:
require('./sass/fullpage.sass');
require('./sass/code.sass');
import React, { Component } from 'react';
import CodeBlock from '../components/CodeBlock';
import ArtTemplate from 'art-template/dist/template';

export default class Slide extends Component {

	constructor() {
		super();

		this.state = {};

		this.state.codeCom = this._codeCom = `// 普通文本替换
var A = 'ok';
return ''.replace(/{{A}}/g, A);`;

		this.state.codeArt = this._codeArt = `// Art-template
var A = 'ok';
// var A = 'javascript:alert(1)';
// var A = 'javascript:%61lert(1)'; // work
// var A = 'j%61vascript:alert(1)'; // not work
// var A = 'javascript:%61\\\\u006cert(1)'; //work
// var A = 'javascript:\\\\u00%360lert(1)'; // work
// var A = 'javascript:%6\\\\u0031lert(1)'; // not work
// var A = 'javascript:alert(1)'; // work
var render = ArtTemplate.compile('');
return render({A:A});`;

		this.state.codeJSX = this._codeJSX = `// JSX
var A = 'ok';
var s = {href: A};
return React.renderToString(React.createElement('a', s));
// equal to >`;

	}

	getComResult() {
		try {
			var fun = new Function(this._codeCom);
			return fun();
		} catch(e) {
			return e.toString();
		}
	}

	getArtResult() {
		try {
			var fun = new Function('ArtTemplate', this._codeArt);
			return fun(ArtTemplate);
		} catch(e) {
			return e.toString();
		}
	}

	getJSXResult() {
		try {
			var fun = new Function('React', this._codeJSX);
			return fun(React);
		} catch(e) {
			return e.toString();
		}
	}

	update(v, type) {
		this['_code' + type] = v;
	}

	apply(e, type) {
		e.stopPropagation();
		let s = {};
		s['code'+type] = this['_code'+type];
		s['res'+type] = this['get'+type+'Result']();
		this.setState(s);
	}

	render() {
		return (

对url注入

						<CodeBlock id='codeCom' onChange={(v)=>this.update(v, 'Com')}>
							{this.state.codeCom}
						</CodeBlock>
						this.apply(e, 'Com')}>应用

{this.state.resCom}

						<CodeBlock id='codeArt'  onChange={(v)=>this.update(v, 'Art')}>
							{this.state.codeArt}
						</CodeBlock>
						this.apply(e, 'Art')}>应用

{this.state.resArt}

						<CodeBlock id='codeJSX' onChange={(v)=>this.update(v, 'JSX')}>
							{this.state.codeJSX}
						</CodeBlock>
						this.apply(e, 'JSX')}>应用

{this.state.resJSX}

		)
	}

}


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

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>SAML redirect</title>

        <link rel='stylesheet' href="<?php echo SimpleSAML_Module::getModuleURL('themeoso/oso.css'); ?>" type='text/css' />

One moment while you are redirected...

Note: Since your browser does not support JavaScript, you must press the button below once to proceed.

        <form method="post" action="<?php echo htmlspecialchars($this->data['destination']); ?>">

        <input type="submit" class="display_none" />
<?php
if (array_key_exists('post', $this->data)) {
        $post = $this->data['post'];
} else {
        // For backwards compatibility
        assert('array_key_exists("response", $this->data)');
        assert('array_key_exists("RelayStateName", $this->data)');
        assert('array_key_exists("RelayState", $this->data)');

        $post = array(
                'SAMLResponse' => $this->data['response'],
                $this->data['RelayStateName'] => $this->data['RelayState'],
        );
}

/**
 * Write out one or more INPUT elements for the given name-value pair.
 *
 * If the value is a string, this function will write a single INPUT element.
 * If the value is an array, it will write multiple INPUT elements to
 * recreate the array.
 *
 * @param string $name  The name of the element.
 * @param string|array $value  The value of the element.
 */
function printItem($name, $value) {
        assert('is_string($name)');
        assert('is_string($value) || is_array($value)');

        if (is_string($value)) {
                echo '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
                return;
        }

        // This is an array...
        foreach ($value as $index => $item) {
                printItem($name . '[' . $index . ']', $item);
        }
}

foreach ($post as $name => $value) {
        printItem($name, $value);
}
?>

                        <button type="submit" class="btn">Submit</button>

        </form>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Leeuwenhoek ned. Tidjdschr. 20: 11 (1954)

#### Original name
Papulaspora pulmonaria Beverw., 1954

### Remarks
null


text:
package org.apache.cassandra.db;

import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import org.junit.Test;

import static junit.framework.Assert.assertNull;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.marshal.CompositeType;
import static org.apache.cassandra.Util.getBytes;
import org.apache.cassandra.Util;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.utils.ByteBufferUtil;

public class RemoveSubColumnTest extends SchemaLoader
{
    @Test
    public void testRemoveSubColumn() throws IOException, ExecutionException, InterruptedException
    {
        Table table = Table.open("Keyspace1");
        ColumnFamilyStore store = table.getColumnFamilyStore("Super1");
        RowMutation rm;
        DecoratedKey dk = Util.dk("key1");

        // add data
        rm = new RowMutation("Keyspace1", dk.key);
        Util.addMutation(rm, "Super1", "SC1", 1, "asdf", 0);
        rm.apply();
        store.forceBlockingFlush();

        ByteBuffer cname = CompositeType.build(ByteBufferUtil.bytes("SC1"), getBytes(1L));
        // remove
        rm = new RowMutation("Keyspace1", dk.key);
        rm.delete("Super1", cname, 1);
        rm.apply();

        ColumnFamily retrieved = store.getColumnFamily(QueryFilter.getIdentityFilter(dk, "Super1"));
        assert retrieved.getColumn(cname).isMarkedForDelete();
        assertNull(Util.cloneAndRemoveDeleted(retrieved, Integer.MAX_VALUE));
    }

    @Test
    public void testRemoveSubColumnAndContainer() throws IOException, ExecutionException, InterruptedException
    {
        Table table = Table.open("Keyspace1");
        ColumnFamilyStore store = table.getColumnFamilyStore("Super1");
        RowMutation rm;
        DecoratedKey dk = Util.dk("key2");

        // add data
        rm = new RowMutation("Keyspace1", dk.key);
        Util.addMutation(rm, "Super1", "SC1", 1, "asdf", 0);
        rm.apply();
        store.forceBlockingFlush();

        // remove the SC
        ByteBuffer scName = ByteBufferUtil.bytes("SC1");
        ByteBuffer cname = CompositeType.build(scName, getBytes(1L));
        rm = new RowMutation("Keyspace1", dk.key);
        rm.deleteRange("Super1", SuperColumns.startOf(scName), SuperColumns.endOf(scName), 1);
        rm.apply();

        // Mark current time and make sure the next insert happens at least
        // one second after the previous one (since gc resolution is the second)
        int gcbefore = (int)(System.currentTimeMillis() / 1000);
        Thread.currentThread().sleep(1000);

        // remove the column itself
        rm = new RowMutation("Keyspace1", dk.key);
        rm.delete("Super1", cname, 2);
        rm.apply();

        ColumnFamily retrieved = store.getColumnFamily(QueryFilter.getIdentityFilter(dk, "Super1"), gcbefore);
        assert retrieved.getColumn(cname).isMarkedForDelete();
        assertNull(Util.cloneAndRemoveDeleted(retrieved, Integer.MAX_VALUE));
    }
}


text:
package dfa.analyses.taintTests;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import codeprocessor.CodeProcessor;
import codeprocessor.GraphBuilder;
import dfa.analyses.TaintElement;
import dfa.analyses.TaintFactory;
import dfa.framework.DFADirection;
import dfa.framework.DataFlowAnalysis;
import dfa.framework.SimpleBlockGraph;
import dfaTests.TestMethod;

public class TestTaintFactory {

    private static TaintFactory factory;

    @BeforeClass
    public static void setUp() {
        factory = new TaintFactory();
    }

    @Test
    public void basicTests() {
        Assert.assertEquals(DFADirection.FORWARD, factory.getDirection());
        Assert.assertEquals("Taint-Analysis", factory.getName());
    }

    @Test
    public void testGetAnalysis() {
        // we need to do setup here, because soot acts weird
        TestMethod testMethod = getSomeCode();
        CodeProcessor cp = new CodeProcessor(testMethod.method);

        Assert.assertTrue(cp.wasSuccessful());

        GraphBuilder gb = new GraphBuilder(cp.getPath(), cp.getClassName());
        SimpleBlockGraph bg = gb.buildGraph(testMethod.signature);

        DataFlowAnalysis<TaintElement> analysis = factory.getAnalysis(bg);
        Assert.assertTrue(analysis instanceof DataFlowAnalysis);
    }

    private static TestMethod getSomeCode() {
        String signature = "void f()";
        // @formatter:off
        String method =
                "public void f() {"
                + "int x = 0;"
                + "}";
        // @formatter:on
        return new TestMethod(signature, method);
    }

}


text:
angular-floatThead
=============

**angular-floatThead** is a very simple wrapper around the awesome floatThead library by [@mkoryak](https://github.com/mkoryak/floatThead/)

## Installation

#### via bower:
```
$ bower install angular-float-thead
```

## Usage

1. This is just a wrapper over the original jQuery floatThead library, so first make sure you have the main library installed as per https://github.com/mkoryak/floatThead

2. Include angular-float-thead as a dependency for your app after running `bower install`

  ```js
  angular.module('myApp', ['floatThead'])
  ```

3. Specify ```float-thead``` on your table element and optionally pass through a floatThead object as a parameter, eg: ```<table float-thead="floatTheadOptions">```

4. Add floatTheadOptions to `$scope` on your controller

  ```js
  $scope.floatTheadOptions = {
      scrollingTop: 60,
      useAbsolutePositioning: false
    };
  ```

5. If you want the directive to reinitialize when your tables data changes then specify an ```ng-model``` on your table and it will watch the collection/object and call 'reflow' when the data changes.

for eg:

```<table float-thead="floatTheadOptions" ng-model="collectionOrObjectToWatch">```


text:
<?php

namespace Google\Service\Compute;

class AcceleratorType extends \Google\Model
{
  /**
   * @var string
   */
  public $creationTimestamp;
  protected $deprecatedType = DeprecationStatus::class;
  protected $deprecatedDataType = '';
  /**
   * @var string
   */
  public $description;
  /**
   * @var string
   */
  public $id;
  /**
   * @var string
   */
  public $kind;
  /**
   * @var int
   */
  public $maximumCardsPerInstance;
  /**
   * @var string
   */
  public $name;
  /**
   * @var string
   */
  public $selfLink;
  /**
   * @var string
   */
  public $zone;

  /**
   * @param string
   */
  public function setCreationTimestamp($creationTimestamp)
  {
    $this->creationTimestamp = $creationTimestamp;
  }
  /**
   * @return string
   */
  public function getCreationTimestamp()
  {
    return $this->creationTimestamp;
  }
  /**
   * @param DeprecationStatus
   */
  public function setDeprecated(DeprecationStatus $deprecated)
  {
    $this->deprecated = $deprecated;
  }
  /**
   * @return DeprecationStatus
   */
  public function getDeprecated()
  {
    return $this->deprecated;
  }
  /**
   * @param string
   */
  public function setDescription($description)
  {
    $this->description = $description;
  }
  /**
   * @return string
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setId($id)
  {
    $this->id = $id;
  }
  /**
   * @return string
   */
  public function getId()
  {
    return $this->id;
  }
  /**
   * @param string
   */
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  /**
   * @return string
   */
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param int
   */
  public function setMaximumCardsPerInstance($maximumCardsPerInstance)
  {
    $this->maximumCardsPerInstance = $maximumCardsPerInstance;
  }
  /**
   * @return int
   */
  public function getMaximumCardsPerInstance()
  {
    return $this->maximumCardsPerInstance;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param string
   */
  public function setSelfLink($selfLink)
  {
    $this->selfLink = $selfLink;
  }
  /**
   * @return string
   */
  public function getSelfLink()
  {
    return $this->selfLink;
  }
  /**
   * @param string
   */
  public function setZone($zone)
  {
    $this->zone = $zone;
  }
  /**
   * @return string
   */
  public function getZone()
  {
    return $this->zone;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AcceleratorType::class, 'Google_Service_Compute_AcceleratorType');


text:
import pasync from 'pasync';
import axios from 'axios';
import url from 'url';

// ------------------------------------
// Constants
// ------------------------------------
export const SET_TICKET_DETAILS = 'SET_TICKET_DETAILS';
export const SET_EVENT_DETAILS = 'SET_EVENT_DETAILS';
export const SET_EVENT_INFO = 'SET_EVENT_INFO';
export const SET_USER_INFO = 'SET_USER_INFO';
export const UPDATE_ORDER = 'UPDATE_ORDER';
export const REDIRECT = 'REDIRECT';
export const ERROR = 'ERROR';
export const SET_RESERVE_TOKEN = 'SET_RESERVE_TOKEN';

export function getReserveToken(ticketId) {
  return async(dispatch) => {
    let options = {
      url: `${SHAKEDOWN_URL}/tickets/${ticketId}/reserve`,
      method: 'get',
      json: true,
      withCredentials: true
    }

    let { data } = await axios(options);
    console.log('data:', data.reserveToken)
    dispatch({
      type: SET_RESERVE_TOKEN,
      payload: data.reserveToken
    })
  }
}

export function deleteReserveToken(ticketId) {
  return async(dispatch, getState) => {

    const reserveToken = getState().ticket.reserveToken

    let options = {
      url: `${SHAKEDOWN_URL}/tickets/${ticketId}/reserve?reserveToken=${reserveToken}`,
      method: 'delete',
      json: true,
      withCredentials: true
    };
    await axios(options);
    dispatch({
      type: SET_RESERVE_TOKEN,
      payload: null
    });
  };
}

export function getEventInfo(id) {
  return async (dispatch, getState) => {
    let res = await axios({
      url: `${SHAKEDOWN_URL}/events/${id}`,
      method: 'get',
      withCredentials: true
    });

    dispatch({
      type: SET_EVENT_INFO,
      payload: res.data.event
    });
  };
}

export function getTicketInfo(ticketId) {
  return async (dispatch, getState) => {
    const reserveToken = getState().ticket.reserveToken
    let { data: { ticket } } = await axios({
      url: `${SHAKEDOWN_URL}/tickets/${ticketId}?reserveToken=${reserveToken}`,
      method: 'get',
      withCredentials: true
    });

    dispatch({
      type: SET_TICKET_DETAILS,
      payload: ticket
    });

    return ticket;
  };
}

export function buyTicketsStripe(token, ticketId, transferToUser) {
  return async (dispatch, getState) => {
    const reserveToken = getState().ticket.reserveToken
    let options = {
      url: `${SHAKEDOWN_URL}/payment/${ticketId}`,
      method: 'post',
      json: true,
      data: {
        reserveToken,
        token: token.id,
        transferToUser
      },
      withCredentials: true
    };

    let { data } = await axios(options);
    if (data.error) {
      console.log('error: ', data.error)
      return dispatch({
        type: ERROR,
        payload: data.error
      });
    }

    dispatch({
      type: ERROR,
      payload: null
    });

    if (data.passwordChangeUrl) {
      let passwordChangeUrl = url.parse(data.passwordChangeUrl).pathname;
      dispatch({
        type: REDIRECT,
        payload: passwordChangeUrl
      });
    } else {
      dispatch({
        type: REDIRECT,
        payload: '/my-profile'
      });
    }
  };
};

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [SET_RESERVE_TOKEN]: (state, action) => {
    return {
      ...state,
      reserveToken: action.payload
    };
  },
  [SET_TICKET_DETAILS]: (state, action) => {
    return {
      ...state,
      ticket: action.payload
    };
  },
  [SET_EVENT_INFO]: (state, action) => {
    return {
      ...state,
      currentEvent: action.payload
    };
  },
  [SET_EVENT_DETAILS]: (state, action) => {
    return {
      ...state,
      currentEvent: {
        ...state.currentEvent,
        ...action.payload
      }
    };
  },
  [UPDATE_ORDER]: (state, action) => {
    return {
      ...state,
      order: action.payload
    };
  },
  [REDIRECT]: (state, action) => {
    return {
      ...state,
      redirect: action.payload
    };
  },
  [ERROR]: (state, action) => {
    return {
      ...state,
      error: action.payload
    };
  }
};

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  ticket: {},
  currentEvent: {},
  reserveToken: null,
};

export default function eventReducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];

  return handler ? handler(state, action) : state;
}


text:
{% extends "bootstrap/base.html" %}
{% block title %}Spotify Connect{% endblock %}
{% from "bootstrap/utils.html" import flashed_messages %}

{% block navbar %}

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Spotify Connect

                Currently Active Device?:

            Set Display Name

            Login
            Logout

{% endblock %}

{% block content %}

      {{flashed_messages(container=False)}}

Loading...

Loading...

Loading...

                        <input id="volumeSlider" type="text" data-slider-id='volumeSlider' data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="0" data-slider-enabled="false" data-type="playback" data-action="volume"/>

                        <button data-type="playback" data-action="shuffle" type="button" class="btn btn-default">

                        </button>
                        <button data-type="playback" data-action="repeat" type="button" class="btn btn-default">

                        </button>

                        <button data-type="playback" data-action="prev" type="button" class="btn btn-default">

                        </button>
                        <button data-type="playback" data-action="play" type="button" class="btn btn-default">

                        </button>
                        <button style="display:none" data-type="playback" data-action="pause" type="button" class="btn btn-default">

                        </button>
                        <button data-type="playback" data-action="next" type="button" class="btn btn-default">

                        </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Login

        <form action="{{url_for('login_password')}}" method="POST">

              <input type="text" class="form-control" placeholder="Username" name="username">

              <input type="password" class="form-control" placeholder="Password" name="password">

            <button type="submit" class="btn btn-primary">Login</button>

        </form>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Set display name

        <form action="{{url_for('info_display_name')}}" method="POST" id="displayNameForm">

              <input type="text" class="form-control" placeholder="Display name" autocomplete="off" name="displayName">

                <button type="submit" class="btn btn-primary">Submit</button>

        </form>

{% endblock %}

{% block scripts %}
{{super()}}

{% endblock %}

{% block styles %}
{{super()}}
<link href="{{url_for('static', filename='css/bootstrap-slider.css')}}" rel="stylesheet">

{% endblock %}


text:
.. _debug-probes:

Debug Probes
############

A *debug probe* is special hardware which allows you to control execution of a
Zephyr application running on a separate board. Debug probes usually allow
reading and writing registers and memory, and support breakpoint debugging of
the Zephyr application on your host workstation using tools like GDB. They may
also support other debug software and more advanced features such as
:ref:`tracing program execution <tracing>`. For details on the related host
software supported by Zephyr, see :ref:`debug-host-tools`.

Debug probes are usually connected to your host workstation via USB; they
are sometimes also accessible via an IP network or other means. They usually
connect to the device running Zephyr using the JTAG or SWD protocols. Debug
probes are either separate hardware devices or circuitry integrated into the same
board which runs Zephyr.

Many supported boards in Zephyr include a second microcontroller that serves as
an onboard debug probe, usb-to-serial adapter, and sometimes a drag-and-drop
flash programmer. This eliminates the need to purchase an external debug probe
and provides a variety of debug host tool options.

Several hardware vendors have their own branded onboard debug probe
implementations: NXP LPC boards have LPC-Link2, NXP Kinetis (former Freescale)
boards have OpenSDA, and ST boards have ST-LINK. Each onboard debug probe
microcontroller can support one or more types of firmware that communicate with
their respective debug host tools. For example, an OpenSDA microcontroller can
be programmed with DAPLink firmware to communicate with pyOCD or OpenOCD debug
host tools, or with J-Link firmware to communicate with J-Link debug host
tools.

Some supported boards in Zephyr do not include an onboard debug probe and
therefore require an external debug probe. In addition, boards that do include
an onboard debug probe often also have an SWD or JTAG header to enable the use
of an external debug probe instead. One reason this may be useful is that the
onboard debug probe may have limitations, such as lack of support for advanced
debuggers or high-speed tracing. You may need to adjust jumpers to prevent the
onboard debug probe from interfering with the external debug probe.

.. _lpclink2-jlink-onboard-debug-probe:

LPC-Link2 J-Link Onboard Debug Probe
************************************

The LPC-Link2 J-Link is an onboard debug probe and usb-to-serial adapter
supported on many NXP LPC and i.MX RT development boards.

This debug probe is compatible with the following debug host tools:

- :ref:`jlink-debug-host-tools`

This probe is realized by programming the LPC-Link2 microcontroller with J-Link
LPC-Link2 firmware. Download and install `LPCScrypt`_ to get the firmware and
programming scripts.

.. note:: Verify the firmware supports your board by visiting `Firmware for LPCXpresso`_

1. Put the LPC-Link2 microcontroller into DFU boot mode by attaching the DFU
   jumper, then powering up the board.

#. Run the ``program_JLINK`` script.

#. Remove the DFU jumper and power cycle the board.

.. _opensda-daplink-onboard-debug-probe:

OpenSDA DAPLink Onboard Debug Probe
***********************************

The OpenSDA DAPLink is an onboard debug probe and usb-to-serial adapter
supported on many NXP Kinetis and i.MX RT development boards. It also includes
drag-and-drop flash programming support.

This debug probe is compatible with the following debug host tools:

- :ref:`pyocd-debug-host-tools`
- :ref:`openocd-debug-host-tools`

This probe is realized by programming the OpenSDA microcontroller with DAPLink
OpenSDA firmware. NXP provides `OpenSDA DAPLink Board-Specific Firmwares`_.

Install the debug host tools before you program the firmware.

As with all OpenSDA debug probes, the steps for programming the firmware are:

1. Put the OpenSDA microcontroller into bootloader mode by holding the reset
   button while you power on the board. Note that "bootloader mode" in this
   context applies to the OpenSDA microcontroller itself, not the target
   microcontroller of your Zephyr application.

#. After you power on the board, release the reset button. A USB mass storage
   device called **BOOTLOADER** or **MAINTENANCE** will enumerate.

#. Copy the OpenSDA firmware binary to the USB mass storage device.

#. Power cycle the board, this time without holding the reset button. You
   should see three USB devices enumerate: a CDC device (serial port), a HID
   device (debug port), and a mass storage device (drag-and-drop flash
   programming).

.. _opensda-jlink-onboard-debug-probe:

OpenSDA J-Link Onboard Debug Probe
**********************************

The OpenSDA J-Link is an onboard debug probe and usb-to-serial adapter
supported on many NXP Kinetis and i.MX RT development boards.

This debug probe is compatible with the following debug host tools:

- :ref:`jlink-debug-host-tools`

This probe is realized by programming the OpenSDA microcontroller with J-Link
OpenSDA firmware. Segger provides `OpenSDA J-Link Generic Firmwares`_ and
`OpenSDA J-Link Board-Specific Firmwares`_, where the latter is generally
recommended when available. Board-specific firmwares are required for i.MX RT
boards to support their external flash memories, whereas generic firmwares are
compatible with all Kinetis boards.

Install the debug host tools before you program the firmware.

As with all OpenSDA debug probes, the steps for programming the firmware are:

1. Put the OpenSDA microcontroller into bootloader mode by holding the reset
   button while you power on the board. Note that "bootloader mode" in this
   context applies to the OpenSDA microcontroller itself, not the target
   microcontroller of your Zephyr application.

#. After you power on the board, release the reset button. A USB mass storage
   device called **BOOTLOADER** or **MAINTENANCE** will enumerate.

#. Copy the OpenSDA firmware binary to the USB mass storage device.

#. Power cycle the board, this time without holding the reset button. You
   should see two USB devices enumerate: a CDC device (serial port) and a
   vendor-specific device (debug port).

.. _stlink-v21-onboard-debug-probe:

ST-LINK/V2-1 Onboard Debug Probe
********************************

ST-LINK/V2-1 is a serial and debug adapter built into all Nucleo and Discovery
boards. It provides a bridge between your computer (or other USB host) and the
embedded target processor, which can be used for debugging, flash programming,
and serial communication, all over a simple USB cable.

It is compatible with the following host debug tools:

- :ref:`openocd-debug-host-tools`
- :ref:`jlink-debug-host-tools`

For some STM32 based boards, it is also compatible with:

- :ref:`pyocd-debug-host-tools`

While it works out of the box with OpenOCD, it requires some flashing
to work with J-Link. To do this, SEGGER offers a firmware upgrading the
ST-LINK/V2-1 on board on the Nucleo and Discovery boards. This firmware makes
the ST-LINK/V2-1 compatible with J-LinkOB, allowing users to take advantage of
most J-Link features like the ultra fast flash download and debugging speed or
the free-to-use GDBServer.

More informations about upgrading ST-LINK/V2-1 to JLink or restore ST-Link/V2-1
firmware please visit: `Segger over ST-Link`_

Flash and debug with ST-Link
============================

Using OpenOCD
-------------

OpenOCD is available by default on ST-Link and configured as the default flash
and debug tool. Flash and debug can be done as follows:

  .. zephyr-app-commands::
     :zephyr-app: samples/hello_world
     :goals: flash

  .. zephyr-app-commands::
     :zephyr-app: samples/hello_world
     :goals: debug

Using Segger J-Link
-------------------

Once STLink is flashed with SEGGER FW and J-Link GDB server is installed on your
host computer, you can flash and debug as follows:

Use CMake with ``-DZEPHYR_BOARD_FLASH_RUNNER=jlink`` to change the default OpenOCD
runner to J-Link. Alternatively, you might add the following line to your
application ``CMakeList.txt`` file.

  .. code-block:: cmake

     set(ZEPHYR_BOARD_FLASH_RUNNER jlink)

If you use West (Zephyr's meta-tool) you can modify the default runner using
the ``--runner`` (or ``-r``) option.

  .. code-block:: console

     west flash --runner jlink

To attach a debugger to your board and open up a debug console with ``jlink``.

  .. code-block:: console

     west debug --runner jlink

For more information about West and available options, see :ref:`west`.

If you configured your Zephyr application to use `Segger RTT`_ console instead,
open telnet:

  .. code-block:: console

     $ telnet localhost 19021
     Trying ::1...
     Trying 127.0.0.1...
     Connected to localhost.
     Escape character is '^]'.
     SEGGER J-Link V6.30f - Real time terminal output
     J-Link STLink V21 compiled Jun 26 2017 10:35:16 V1.0, SN=773895351
     Process: JLinkGDBServerCLExe
     Zephyr Shell, Zephyr version: 1.12.99
     Type 'help' for a list of available commands
     shell>

If you get no RTT output you might need to disable other consoles which conflict
with the RTT one if they are enabled by default in the particular sample or
application you are running, such as disable UART_CONSOLE in menucon

.. _jlink-external-debug-probe:

J-Link External Debug Probe
***************************

`Segger J-Link`_ is a family of external debug probes, including J-Link EDU,
J-Link PLUS, J-Link ULTRA+, and J-Link PRO, that support a large number of
devices from different hardware architectures and vendors.

This debug probe is compatible with the following debug host tools:

- :ref:`jlink-debug-host-tools`
- :ref:`openocd-debug-host-tools`

Install the debug host tools before you program the firmware.

.. _LPCScrypt:
   https://www.nxp.com/lpcscrypt

.. _Firmware for LPCXpresso:
   https://www.segger.com/products/debug-probes/j-link/models/other-j-links/lpcxpresso-on-board/

.. _OpenSDA DAPLink Board-Specific Firmwares:
   https://www.nxp.com/opensda

.. _OpenSDA J-Link Generic Firmwares:
   https://www.segger.com/downloads/jlink/#JLinkOpenSDAGenericFirmwares

.. _OpenSDA J-Link Board-Specific Firmwares:
   https://www.segger.com/downloads/jlink/#JLinkOpenSDABoardSpecificFirmwares

.. _Segger J-Link:
   https://www.segger.com/products/debug-probes/j-link/

.. _Segger over ST-Link:
   https://www.segger.com/products/debug-probes/j-link/models/other-j-links/st-link-on-board/

.. _Segger RTT:
    https://www.segger.com/jlink-rtt.html


text:
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');

gulp.task("default", function () {
  gulp.src('sass/style.scss')
    .pipe(sass({outputStyle: 'compressed'}))
    .pipe(autoprefixer())
    .pipe(gulp.dest('static/css/'));
});

gulp.task("watch", function () {
  gulp.watch('sass/style.scss', function() {
    gulp.src('sass/style.scss')
      .pipe(sass({outputStyle: 'compressed'}))
      .pipe(autoprefixer())
      .pipe(gulp.dest('static/css/'));
  });
});


text:
@import url(//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800);
@import url(//fonts.googleapis.com/css?family=Droid+Sans:400,700);
@import url(//fonts.googleapis.com/css?family=Droid+Sans+Mono);


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::REST::Controller::ga4gh::references;

use Moose;
use namespace::autoclean;
use Try::Tiny;
use Data::Dumper;

require EnsEMBL::REST;
EnsEMBL::REST->turn_on_config_serialisers(__PACKAGE__);

=pod

POST requests : /ga4gh/references/search -d { "referenceSetId": = "",
                                              "md5checksums": [],
                                              "accessions": [],
                                              "pageSize": "",
                                              "pageToken": "",
                                             }

GET /ga4gh/references/id
GET /ga4gh/references/{id}/bases?start=100&end=200

=cut

BEGIN {extends 'Catalyst::Controller::REST'; }

sub searchReferences_POST {
  my ( $self, $c ) = @_;

  my $references;

  my $post_data = $c->req->data;

  $c->go( 'ReturnError', 'custom', [ ' Cannot find "referenceSetId" key in your request' ] )
    unless exists $post_data->{referenceSetId} ;

   ## set a default page size if not supplied or not a number
   $post_data->{pageSize} = 50 unless (defined  $post_data->{pageSize} && $post_data->{pageSize} =~ /\d+/);

  try {
    $references = $c->model('ga4gh::references')->fetch_references( $post_data );
  } catch {
    $c->go('ReturnError', 'from_ensembl', [$_]);
  };

  $self->status_ok($c, entity => $references);

}

sub searchReferences: Chained('/') PathPart('ga4gh/references/search') ActionClass('REST')  {}

sub id: Chained('/') PathPart('ga4gh/references') ActionClass('REST') {}

sub id_GET {
  my ($self, $c, $id, $bases) = @_;
  my $references;

  $c->go( 'ReturnError', 'custom', [ ' Error - id required for GET request' ])
    unless defined $id;

  try {
    $references = $c->model('ga4gh::references')->getReference($id, $bases);
  } catch {
    $c->go('ReturnError', 'from_ensembl', [qq{$_}]) if $_ =~ /STACK/;
    $c->go('ReturnError', 'custom', [qq{$_}]);
  };

  ## Return 404 for get requests on unknown ids
  $c->go( 'ReturnError', 'not_found', [qq{ reference $id not found}]) unless defined $references;

  $self->status_ok($c, entity => $references);
}

__PACKAGE__->meta->make_immutable;

1;