text:
#include "third_party/blink/renderer/core/dom/layout_tree_builder.h"

#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/generated_children.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg_names.h"

namespace blink {

LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(
    Element& element,
    Node::AttachContext& context,
    const ComputedStyle* style,
    LegacyLayout legacy)
    : LayoutTreeBuilder(element, context, style), legacy_(legacy) {
  DCHECK(style_);
  DCHECK(!style_->IsEnsuredInDisplayNone());
}

LayoutObject* LayoutTreeBuilderForElement::NextLayoutObject() const {
  if (node_->IsFirstLetterPseudoElement())
    return context_.next_sibling;
  if (node_->IsInTopLayer())
    return LayoutTreeBuilderTraversal::NextInTopLayer(*node_);
  return LayoutTreeBuilder::NextLayoutObject();
}

LayoutObject* LayoutTreeBuilderForElement::ParentLayoutObject() const {
  if (node_->IsInTopLayer())
    return node_->GetDocument().GetLayoutView();
  return context_.parent;
}

DISABLE_CFI_PERF
void LayoutTreeBuilderForElement::CreateLayoutObject() {
  LayoutObject* parent_layout_object = ParentLayoutObject();
  if (!parent_layout_object)
    return;
  if (!parent_layout_object->CanHaveChildren())
    return;

  // If we are in the top layer and the parent layout object without top layer
  // adjustment can't have children, then don't render.
  // https://github.com/w3c/csswg-drafts/issues/6939#issuecomment-1016671534
  if (node_->IsInTopLayer() && context_.parent &&
      !context_.parent->CanHaveChildren() &&
      node_->GetPseudoId() != kPseudoIdBackdrop) {
    return;
  }

  if (node_->IsPseudoElement() &&
      !CanHaveGeneratedChildren(*parent_layout_object))
    return;
  if (!node_->LayoutObjectIsNeeded(*style_))
    return;

  LayoutObject* new_layout_object = node_->CreateLayoutObject(*style_, legacy_);
  if (!new_layout_object)
    return;

  if (!parent_layout_object->IsChildAllowed(new_layout_object, *style_)) {
    new_layout_object->Destroy();
    return;
  }

  // Make sure the LayoutObject already knows it is going to be added to a
  // LayoutFlowThread before we set the style for the first time. Otherwise code
  // using IsInsideFlowThread() in the StyleWillChange and StyleDidChange will
  // fail.
  new_layout_object->SetIsInsideFlowThread(
      parent_layout_object->IsInsideFlowThread());

  LayoutObject* next_layout_object = NextLayoutObject();
  // SetStyle() can depend on LayoutObject() already being set.
  node_->SetLayoutObject(new_layout_object);

  DCHECK(!new_layout_object->Style());
  new_layout_object->SetStyle(style_);

  // Note: Adding new_layout_object instead of LayoutObject(). LayoutObject()
  // may be a child of new_layout_object.
  parent_layout_object->AddChild(new_layout_object, next_layout_object);
}

scoped_refptr<const ComputedStyle>
LayoutTreeBuilderForText::CreateInlineWrapperStyleForDisplayContentsIfNeeded()
    const {
  // If the parent element is not a display:contents element, the style and the
  // parent style will be the same ComputedStyle object. Early out here.
  if (style_ == context_.parent->Style())
    return nullptr;

  return node_->GetDocument()
      .GetStyleResolver()
      .CreateInheritedDisplayContentsStyleIfNeeded(*style_,
                                                   context_.parent->StyleRef());
}

LayoutObject*
LayoutTreeBuilderForText::CreateInlineWrapperForDisplayContentsIfNeeded(
    const ComputedStyle* wrapper_style) const {
  if (!wrapper_style)
    return nullptr;

  // Text nodes which are children of display:contents element which modifies
  // inherited properties, need to have an anonymous inline wrapper having those
  // inherited properties because the layout code expects the LayoutObject
  // parent of text nodes to have the same inherited properties.
  LayoutObject* inline_wrapper =
      LayoutInline::CreateAnonymous(&node_->GetDocument());
  inline_wrapper->SetStyle(wrapper_style);
  if (!context_.parent->IsChildAllowed(inline_wrapper, *wrapper_style)) {
    inline_wrapper->Destroy();
    return nullptr;
  }
  context_.parent->AddChild(inline_wrapper, NextLayoutObject());
  return inline_wrapper;
}

void LayoutTreeBuilderForText::CreateLayoutObject() {
  const ComputedStyle* style = style_.get();
  LayoutObject* layout_object_parent = context_.parent;
  LayoutObject* next_layout_object = NextLayoutObject();
  scoped_refptr<const ComputedStyle> nullable_wrapper_style =
      CreateInlineWrapperStyleForDisplayContentsIfNeeded();
  if (LayoutObject* wrapper = CreateInlineWrapperForDisplayContentsIfNeeded(
          nullable_wrapper_style.get())) {
    layout_object_parent = wrapper;
    next_layout_object = nullptr;
  }
  // SVG <text> doesn't accept anonymous LayoutInlines. But the Text should have
  // the adjusted ComputedStyle.
  if (nullable_wrapper_style)
    style = nullable_wrapper_style.get();

  LegacyLayout legacy_layout =
      layout_object_parent->ForceLegacyLayoutForChildren()
          ? LegacyLayout::kForce
          : LegacyLayout::kAuto;
  LayoutText* new_layout_object =
      node_->CreateTextLayoutObject(*style, legacy_layout);
  if (!layout_object_parent->IsChildAllowed(new_layout_object, *style)) {
    new_layout_object->Destroy();
    return;
  }

  // Make sure the LayoutObject already knows it is going to be added to a
  // LayoutFlowThread before we set the style for the first time. Otherwise code
  // using IsInsideFlowThread() in the StyleWillChange and StyleDidChange will
  // fail.
  new_layout_object->SetIsInsideFlowThread(
      context_.parent->IsInsideFlowThread());

  node_->SetLayoutObject(new_layout_object);
  DCHECK(!new_layout_object->Style());
  new_layout_object->SetStyle(style);

  layout_object_parent->AddChild(new_layout_object, next_layout_object);
}

}  // namespace blink


text:
package day1;

import java.io.File;
import java.util.HashMap;
import java.util.Scanner;

public class TripCalculator {

	public static final Character UP_SYMBOL = '(';
	public static final Character DOWN_SYMBOL = ')';

	public static int calculate(String inputFile){

		//load input stuffs
		File file = new File(inputFile);
		StringBuilder stops = new StringBuilder("");

		try{

			Scanner scanner = new Scanner(file);
			while(scanner.hasNextLine()){
				String line = scanner.nextLine();
				stops.append(line);
			}
			scanner.close();

		} catch(Exception e){
			System.out.println("File exploded. No idea why.");
			e.printStackTrace();
		}

		//figure out how many of each stop type Santa visited
		char[] allStops = new char[stops.length()];
		stops.getChars(0, stops.length(), allStops, 0);
		HashMap<Character, Integer> stopTypes = new HashMap<Character, Integer>();
		for( int i = 0; i < allStops.length; ++i){
			char currentStop = allStops[i];
			if(stopTypes.containsKey(currentStop)){
				stopTypes.put(currentStop, stopTypes.get(currentStop)+1);
			}
			else {
				stopTypes.put(currentStop, 1);
			}
		}

		//calculate where Santa ended up
		//TODO make this configurable

		int floorsUp = 0;
		if(stopTypes.containsKey(UP_SYMBOL)){
			floorsUp = stopTypes.get(UP_SYMBOL);
		}

		int floorsDown = 0;
		if(stopTypes.containsKey(DOWN_SYMBOL)){
			floorsDown = stopTypes.get(DOWN_SYMBOL);
		}

		return floorsUp - floorsDown;
	}

	public static void main(String[] args){
		System.out.println(calculate("resources/day1.txt"));

		System.out.println("Math test.");
		System.out.println(47/3);
	}

}

redpajama_set_name: RedPajamaGithub


text:
(function() {

    var app = angular.module('bbUniqueModule', []);

    //assuming you have a data service you're passing in
    app.directive('bbUnique', ['$q', 'dataService' ,function($q, dataService){
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope,elem,attrs,ngModel){

                ngModel.$asyncValidators.unique = function(modelValue,viewValue){
                var deffered = $q.defer(),
                    currentValue = modelValue || viewValue,//if model value is not there, default to view
                    key = attrs.bbUniqueKey,
                    property = attrs.bbUniqueProperty;

                    if(key && property){
                        dataService.checkUniqueValue(key,property,currentValue)
                            .then(function(unique){
                                if(unique){
                                    deferred.resolve(); //got a unique val
                                }
                                else{
                                    deferred.reject();
                                }
                            });

                    return deferred.promise;

                    }
                    else{
                        return $q.when(true);
                    }

                }

            }
        }
    }]);

}());


text:
package com.zimbra.doc.soap;

import java.util.List;

public interface DescriptionNode {
    public DescriptionNode getParent();
    public List<DescriptionNode> getChildren();
    public void writeDescription(StringBuilder desc, int depth);
    public String getDescription();
    public String getSummary();
    public String getXPath();
    public String xmlLinkTargetName();
    public String tableLinkTargetName();
}


text:
<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><?php wp_title('|', true, 'right'); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <?php wp_head(); ?>

  <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
    <link rel="icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico" type="image/x-icon" />
</head>


text:
local filesystem
do
  local ok
  ok, filesystem = pcall(require, "filesystem")
  if not ok then
    --compatibility as a standalone script without OpenComputers: requires Lua File System
    local lfs = require("lfs")
    filesystem = {
      list = lfs.dir,
      exists = function(path)
        return lfs.attributes(path) ~= nil
      end,
      isDirectory = function(path)
        local attributes = lfs.attributes(path)
        return attributes and (attributes.mode == "directory") or false
      end,
      concat = function(a, b)
        return a .. "/" .. b
      end,
    }
  end
end

return {
  list = function(path, includeWorkingDir, includeDuplicates)
    if checkArg then
      checkArg(1, path,              "string",  "nil")
      checkArg(2, includeWorkingDir, "boolean", "nil")
      checkArg(3, includeDuplicates, "boolean", "nil")
    end
    path = path or package.path

    local knownLibs = {}

    local function findLibs(path, dir, prefix, ext, subPath, libPrefix)
      if path then
        dir, prefix, ext, subPath = path:match("^(.-)([^/]*)%?([^/]*)(.-)$")
        libPrefix = ""
        if (dir:sub(1, 2) ~= "./" and dir ~= "") and not (filesystem.exists(dir) and filesystem.isDirectory(dir)) then
          return
        end
      end
      --don't search working dir
      if dir and prefix and ext and ((dir:sub(1, 2) ~= "./" and dir ~= "") or includeWorkingDir) then
        local list = {}
        for file in filesystem.list(dir) do
          table.insert(list, file)
        end
        table.sort(list)
        for _, file in ipairs(list) do
          if file:sub(1, #prefix) == prefix then
            if file:sub(-#ext, -1) == ext then
              local libname = libPrefix .. file:sub(#prefix + 1, -#ext - 1)
              local absolutePath = dir .. file .. subPath:sub(2, -1)
              if absolutePath:sub(1, 1) ~= "/" then
                absolutePath = filesystem.concat(os.getenv("PWD") or "", absolutePath)
              end
              if filesystem.exists(absolutePath) and not filesystem.isDirectory(absolutePath) then
                if not knownLibs[libname] then
                  if not includeDuplicates then
                    knownLibs[libname] = true
                  end
                  coroutine.yield(libname, absolutePath)
                end
              end
            end
          end
          if file:sub(-1, -1) == "/" then
            --directory: recursion
            --(expects "dir" to end with a slash if it isn't empty
            findLibs(nil, dir .. file, prefix, ext, subPath, libPrefix .. file:sub(1, -2) .. ".")
          end
        end
      end
    end

    return coroutine.wrap(function()
      for path in path:gmatch("[^;]+") do
        findLibs(path)
      end
      coroutine.yield()
    end)
  end,
}


text:
//>>built
define("dojo/jaxer",["./main"],function(_1){
if(typeof print=="function"){
console.debug=Jaxer.Log.debug;
console.warn=Jaxer.Log.warn;
console.error=Jaxer.Log.error;
console.info=Jaxer.Log.info;
console.log=Jaxer.Log.warn;
}
onserverload=_1._loadInit;
return _1;
});


text:
require "fileutils"

VERSION = Gem::Version.new(RUBY_VERSION)
FILE_PATH = Pathname.new(File.dirname(__FILE__))

def assert_source_specs(source_specs)
  relative_path = Pathname.new(source_specs).relative_path_from(FILE_PATH).to_s

  describe relative_path do
    tests = []
    current_test = nil

    File.foreach(source_specs).with_index do |line, index|
      case
      when line =~ /^#~# ORIGINAL ?([\w\s]+)$/
        # save old test
        tests.push current_test if current_test

        # start a new test

        name = $~[1].strip
        name = "unnamed test" if name.empty?

        current_test = { name: name, line: index + 1, options: {}, original: "" }
      when line =~ /^#~# EXPECTED$/
        current_test[:expected] = ""
      when line =~ /^#~# PENDING$/
        current_test[:pending] = true
      when line =~ /^#~# (.+)$/
        current_test[:options] = eval("{ #{$~[1]} }")
      when current_test[:expected]
        current_test[:expected] += line
      when current_test[:original]
        current_test[:original] += line
      end
    end

    tests.concat([current_test]).each do |test|
      it "formats #{test[:name]} (line: #{test[:line]})" do
        pending if test[:pending]
        formatted = described_class.format(test[:original], **test[:options])
        expected = test[:expected].rstrip + "\n"
        expect(formatted).to eq(expected)
        idempotency_check = described_class.format(formatted, **test[:options])
        expect(idempotency_check).to eq(formatted)
      end
    end
  end
end

def assert_format(code, expected = code, **options)
  expected = expected.rstrip + "\n"

  line = caller_locations[0].lineno

  ex = it "formats #{code.inspect} (line: #{line})" do
    actual = Rufo.format(code, **options)
    if actual != expected
      fail "Expected\n\n~~~\n#{code}\n~~~\nto format to:\n\n~~~\n#{expected}\n~~~\n\nbut got:\n\n~~~\n#{actual}\n~~~\n\n  diff = #{expected.inspect}\n         #{actual.inspect}"
    end

    second = Rufo.format(actual, **options)
    if second != actual
      fail "Idempotency check failed. Expected\n\n~~~\n#{actual}\n~~~\nto format to:\n\n~~~\n#{actual}\n~~~\n\nbut got:\n\n~~~\n#{second}\n~~~\n\n  diff = #{second.inspect}\n         #{actual.inspect}"
    end
  end

  # This is so we can do `rspec spec/rufo_spec.rb:26` and
  # refer to line numbers for assert_format
  ex.metadata[:line_number] = line
end

RSpec.describe Rufo::Formatter do
  Dir[File.join(FILE_PATH, "/formatter_source_specs/*")].each do |source_specs|
    assert_source_specs(source_specs) if File.file?(source_specs)
  end

  if VERSION >= Gem::Version.new("2.6")
    Dir[File.join(FILE_PATH, "/formatter_source_specs/2.6/*")].each do |source_specs|
      assert_source_specs(source_specs) if File.file?(source_specs)
    end
  end

  if VERSION >= Gem::Version.new("2.7")
    Dir[File.join(FILE_PATH, "/formatter_source_specs/2.7/*")].each do |source_specs|
      assert_source_specs(source_specs) if File.file?(source_specs)
    end
  end

  if VERSION >= Gem::Version.new("3.0")
    Dir[File.join(FILE_PATH, "/formatter_source_specs/3.0/*")].each do |source_specs|
      assert_source_specs(source_specs) if File.file?(source_specs)
    end
  end

  # Empty
  describe "empty" do
    assert_format "", ""
    assert_format "   ", "   "
    assert_format "\n", ""
    assert_format "\n\n", ""
    assert_format "\n\n\n", ""
  end

  describe "Syntax errors not handled by Ripper" do
    it "raises an unknown syntax error" do
      expect {
        Rufo.format("def foo; FOO = 1; end")
      }.to raise_error(Rufo::UnknownSyntaxError)
    end
  end
end


text:
using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;

static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("npapi");

// Test passing arguments to a plugin.
TEST_F(NPAPITesterBase, Arguments) {
  const FilePath test_case(FILE_PATH_LITERAL("arguments.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("arguments", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Test invoking many plugins within a single page.
TEST_F(NPAPITesterBase, ManyPlugins) {
  const FilePath test_case(FILE_PATH_LITERAL("many_plugins.html"));
  GURL url(ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case));
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  for (int i = 1; i <= 15; i++) {
    SCOPED_TRACE(StringPrintf("Waiting for plugin #%d", i));
    ASSERT_NO_FATAL_FAILURE(WaitForFinish(
        "arguments",
        base::IntToString(i),
        url,
        kTestCompleteCookie,
        kTestCompleteSuccess,
        TestTimeouts::action_max_timeout_ms()));
  }
}

// Test various calls to GetURL from a plugin.
TEST_F(NPAPITesterBase, GetURL) {
  const FilePath test_case(FILE_PATH_LITERAL("geturl.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("geturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITesterBase, GetJavaScriptURL) {
  const FilePath test_case(FILE_PATH_LITERAL("get_javascript_url.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Test that calling GetURL with a javascript URL and target=_self
// works properly when the plugin is embedded in a subframe.
TEST_F(NPAPITesterBase, GetJavaScriptURL2) {
  const FilePath test_case(FILE_PATH_LITERAL("get_javascript_url2.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("getjavascripturl2", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Test is flaky on linux/cros builders.  http://crbug.com/71904
#if defined(OS_POSIX)
#define MAYBE_GetURLRedirectNotification FLAKY_GetURLRedirectNotification
#else
#define MAYBE_GetURLRedirectNotification GetURLRedirectNotification
#endif
TEST_F(NPAPITesterBase, MAYBE_GetURLRedirectNotification) {
  const FilePath test_case(FILE_PATH_LITERAL("geturl_redirect_notify.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("geturlredirectnotify", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
TEST_F(NPAPITesterBase, NPObjectProxy) {
  const FilePath test_case(FILE_PATH_LITERAL("npobject_proxy.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
// http://crbug.com/44960
TEST_F(NPAPIVisiblePluginTester,
       FLAKY_SelfDeletePluginInvokeInSynchronousPaint) {
  if (ProxyLauncher::in_process_renderer())
    return;

  show_window_ = true;
  const FilePath test_case(
      FILE_PATH_LITERAL("execute_script_delete_in_paint.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("execute_script_delete_in_paint", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}
#endif

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
  if (ProxyLauncher::in_process_renderer())
    return;

  show_window_ = true;
  const FilePath test_case(FILE_PATH_LITERAL("self_delete_plugin_stream.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("self_delete_plugin_stream", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}

#if defined(OS_WIN)
// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
  show_window_ = true;
  const FilePath test_case(FILE_PATH_LITERAL("verify_plugin_window_rect.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
TEST_F(NPAPIVisiblePluginTester, CreateInstanceInPaint) {
  show_window_ = true;
  const FilePath test_case(FILE_PATH_LITERAL("create_instance_in_paint.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("create_instance_in_paint", "2", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Tests that putting up an alert in response to a paint doesn't deadlock.
TEST_F(NPAPIVisiblePluginTester, AlertInWindowMessage) {
  show_window_ = true;
  const FilePath test_case(FILE_PATH_LITERAL("alert_in_window_message.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  bool modal_dialog_showing = false;
  ui::MessageBoxFlags::DialogButton available_buttons;
  ASSERT_TRUE(automation()->WaitForAppModalDialog());
  ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
      &available_buttons));
  ASSERT_TRUE(modal_dialog_showing);
  ASSERT_NE((ui::MessageBoxFlags::DIALOGBUTTON_OK & available_buttons), 0);
  ASSERT_TRUE(automation()->ClickAppModalDialogButton(
      ui::MessageBoxFlags::DIALOGBUTTON_OK));

  modal_dialog_showing = false;
  ASSERT_TRUE(automation()->WaitForAppModalDialog());
  ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
      &available_buttons));
  ASSERT_TRUE(modal_dialog_showing);
  ASSERT_NE((ui::MessageBoxFlags::DIALOGBUTTON_OK & available_buttons), 0);
  ASSERT_TRUE(automation()->ClickAppModalDialogButton(
      ui::MessageBoxFlags::DIALOGBUTTON_OK));
}

TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
  if (ProxyLauncher::in_process_renderer())
    return;

  show_window_ = true;
  const FilePath test_case(FILE_PATH_LITERAL("npobject_lifetime_test.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("npobject_lifetime_test", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}

// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
  const FilePath test_case(FILE_PATH_LITERAL("new_fails.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(
      FILE_PATH_LITERAL("execute_script_delete_in_npn_evaluate.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}

TEST_F(NPAPIVisiblePluginTester, SelfDeleteCreatePluginInNPNEvaluate) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(
      FILE_PATH_LITERAL("npn_plugin_delete_create_in_evaluate.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("npobject_delete_create_plugin_in_evaluate", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}

#endif

// FLAKY. See bug http://crbug.com/17645. This bug report indicates that this
// test is crashy. I could not repro the crash on my local setup. Leaving this
// marked as FLAKY for now while we watch this on the builders.
TEST_F(NPAPIVisiblePluginTester, FLAKY_OpenPopupWindowWithPlugin) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(
      FILE_PATH_LITERAL("get_javascript_open_popup_with_plugin.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("plugin_popup_with_plugin_target", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_timeout_ms());
}

// Test checking the privacy mode is off.
TEST_F(NPAPITesterBase, PrivateDisabled) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(FILE_PATH_LITERAL("private.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("private", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NPAPITesterBase, ScheduleTimer) {
  const FilePath test_case(FILE_PATH_LITERAL("schedule_timer.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("schedule_timer", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NPAPITesterBase, PluginThreadAsyncCall) {
  const FilePath test_case(FILE_PATH_LITERAL("plugin_thread_async_call.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("plugin_thread_async_call", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

// Test checking the privacy mode is on.
TEST_F(NPAPIIncognitoTester, PrivateEnabled) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(FILE_PATH_LITERAL("private.html?private"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("private", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
TEST_F(NPAPIVisiblePluginTester, MultipleInstancesSyncCalls) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(
      FILE_PATH_LITERAL("multiple_instances_sync_calls.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("multiple_instances_sync_calls", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}
#endif

TEST_F(NPAPIVisiblePluginTester, GetURLRequestFailWrite) {
  if (ProxyLauncher::in_process_renderer())
    return;

  GURL url(URLRequestMockHTTPJob::GetMockUrl(
               FilePath(FILE_PATH_LITERAL(
                            "npapi/plugin_url_request_fail_write.html"))));

  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  WaitForFinish("geturl_fail_write", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

#if defined(OS_WIN)
TEST_F(NPAPITesterBase, EnsureScriptingWorksInDestroy) {
  if (ProxyLauncher::in_process_renderer())
    return;

  const FilePath test_case(
      FILE_PATH_LITERAL("ensure_scripting_works_in_destroy.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
  WaitForFinish("ensure_scripting_works_in_destroy", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
}

// This test uses a Windows Event to signal to the plugin that it should crash
// on NP_Initialize.
TEST_F(NPAPITesterBase, NoHangIfInitCrashes) {
  if (ProxyLauncher::in_process_renderer())
    return;

  // Only Windows implements the crash service for now.
#if defined(OS_WIN)
  expected_crashes_ = 1;
#endif

  HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit");
  SetEvent(crash_event);
  const FilePath test_case(FILE_PATH_LITERAL("no_hang_if_init_crashes.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
  NavigateToURL(url);
  WaitForFinish("no_hang_if_init_crashes", "1", url,
                kTestCompleteCookie, kTestCompleteSuccess,
                TestTimeouts::action_max_timeout_ms());
  CloseHandle(crash_event);
}

#endif

TEST_F(NPAPIVisiblePluginTester, PluginReferrerTest) {
  if (ProxyLauncher::in_process_renderer())
    return;

  GURL url(URLRequestMockHTTPJob::GetMockUrl(
               FilePath(FILE_PATH_LITERAL(
                            "npapi/plugin_url_request_referrer_test.html"))));

  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  WaitForFinish("plugin_referrer_test", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}

#if defined(OS_MACOSX)
TEST_F(NPAPIVisiblePluginTester, PluginConvertPointTest) {
  if (ProxyLauncher::in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window(browser->GetWindow());
  ASSERT_TRUE(window.get());
  window->SetBounds(gfx::Rect(50, 50, 400, 400));

  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath(FILE_PATH_LITERAL("npapi/convert_point.html"))));
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  // TODO(stuartmorgan): When the automation system supports sending clicks,
  // change the test to trigger on mouse-down rather than window focus.
  ASSERT_TRUE(browser->BringToFront());
  WaitForFinish("convert_point", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}
#endif

TEST_F(NPAPIVisiblePluginTester, ClickToPlay) {
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
                                                CONTENT_SETTING_BLOCK));

  GURL url(URLRequestMockHTTPJob::GetMockUrl(
               FilePath(FILE_PATH_LITERAL("npapi/click_to_play.html"))));
  ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));

  scoped_refptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(tab->LoadBlockedPlugins());

  WaitForFinish("setup", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, TestTimeouts::action_max_timeout_ms());
}


text:
============
Installation
============

npm::

    npm install redux-db --save

yarn::

    yarn add redux-db

bower::

    bower install redux-db


text:
package com.elastisys.scale.cloudpool.aws.commons.poolclient;

import static com.elastisys.scale.commons.util.precond.Preconditions.checkArgument;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.amazonaws.services.ec2.model.InstanceType;
import com.elastisys.scale.cloudpool.aws.commons.ScalingTags;
import com.elastisys.scale.cloudpool.commons.basepool.config.BaseCloudPoolConfig;
import com.elastisys.scale.commons.json.JsonUtils;

/**
 * EC2-specific server provisioning template.
 *
 * @see BaseCloudPoolConfig#getProvisioningTemplate()
 */
public class Ec2ProvisioningTemplate {
    /**
     * The name of the instance type to launch. For example, {@code m1.medium}.
     */
    private final String instanceType;
    /**
     * The name of the Amazon machine image used to boot new instances. For
     * example, {@code ami-da05a4a0}.
     */
    private final String amiId;
    /**
     * The IDs of one or more VPC subnets into which created instances are to be
     * launched. The subnets also implicitly determine the availability zones
     * that instances can be launched into. At least one subnet must be
     * specified. A best effort attempt will be made to place instances evenly
     * across the subnets. All subnets are assumed to belong to the same
     * VPC.
     */
    private final List<String> subnetIds;
    /**
     * Indicates if created instances are to be assigned a public IP address.
     */
    private final Boolean assignPublicIp;

    /**
     * The name of the key pair to use for new instances. May be
     * null. If you do not specify a key pair, you can't connect to
     * the instance unless you choose an AMI that is configured to allow users
     * another way to log in.
     */
    private final String keyPair;

    /**
     * The ARN of an IAM instance profile to assign to created instances. May be
     * null if no IAM role is to be delegated to instances. For
     * example,
     * {@code arn:aws:iam::123456789012:instance-profile/my-iam-profile}
     */
    private final String iamInstanceProfileARN;

    /**
     * Zero or more security group IDs to apply to created instances. May be
     * null, in which case EC2 assigns a default security group.
     * All security groups are assumed to belong to the VPC of the
     * {@link #subnetIds}..
     */
    private final List<String> securityGroupIds;
    /**
     * A base 64-encoded blob
     * of data used to pass custom data (such as a boot script) to started
     * instances. Refer to the AWS
     * documentation for details. May be null.
     */
    private final String encodedUserData;

    /**
     * Indicates whether created instances are to be optimized for Amazon EBS
     * I/O. This optimization provides dedicated throughput to Amazon EBS and an
     * optimized configuration stack to provide optimal Amazon EBS I/O
     * performance. Note that this optimization isn't available with all
     * instance types. Additional usage charges apply when using an
     * EBS-optimized instance.
     */
    private final Boolean ebsOptimized;

    /**
     * Tags that are to be set on created instances in addition to the
     * {@link ScalingTags#CLOUD_POOL_TAG} and
     * {@link ScalingTags#INSTANCE_NAME_TAG} that are always set by the
     * cloudpool.
     */
    private final Map<String, String> tags;

    /**
     * Creates a new {@link Ec2ProvisioningTemplate} without cloud-specific
     * {@link #extensions}.
     *
     * @param instanceType
     *            The name of the instance type to launch. For example,
     *            {@code m1.medium}.
     * @param amiId
     *            The name of the Amazon machine image used to boot new servers.
     *            For example, {@code ami-da05a4a0}.
     * @param subnetIds
     *            The IDs of one or more VPC subnets into which created
     *            instances are to be launched. The subnets also implicitly
     *            determine the availability zones that instances can be
     *            launched into. At least one must be specified. A best effort
     *            attempt will be made to place instances evenly across the
     *            subnets. All subnets are assumed to belong to the same
     *            VPC.
     * @param assignPublicIp
     *            Indicates if created instances are to be assigned a public IP
     *            address. May be null, which is interpreted as
     *            false.
     * @param keyPair
     *            The name of the key pair to use for new instances. May be
     *            null. If you do not specify a key pair, you can't
     *            connect to the instance unless you choose an AMI that is
     *            configured to allow users another way to log in.
     * @param iamInstanceProfileARN
     *            The ARN of an IAM instance profile to assign to created
     *            instances. May be null if no IAM role is to be
     *            delegated to instances. For example,
     *            {@code arn:aws:iam::123456789012:instance-profile/my-iam-profile}
     * @param securityGroupIds
     *            Zero or more security group IDs to apply to created instances.
     *            May be null, in which case EC2 assigns a default
     *            security group. All security groups are assumed to belong
     *            to the VPC of the {@link #subnetIds}..
     * @param encodedUserData
     *            A base
     *            64-encoded blob of data used to pass custom data (such as
     *            a boot script) to started instances. Refer to the AWS
     *            documentation for details. May be null.
     * @param ebsOptimized
     *            Indicates whether created instances are to be optimized for
     *            Amazon EBS I/O. This optimization provides dedicated
     *            throughput to Amazon EBS and an optimized configuration stack
     *            to provide optimal Amazon EBS I/O performance. Note that this
     *            optimization isn't available with all instance types.
     *            Additional usage charges apply when using an EBS-optimized
     *            instance. May be null, which is interpreted as
     *            false.
     * @param tags
     *            Tags that are to be set on created instances in addition to
     *            the {@link ScalingTags#CLOUD_POOL_TAG} and
     *            {@link ScalingTags#INSTANCE_NAME_TAG} that are always set by
     *            the cloudpool. May be null.
     */
    public Ec2ProvisioningTemplate(String instanceType, String amiId, List<String> subnetIds, Boolean assignPublicIp,
            String keyPair, String iamInstanceProfileARN, List<String> securityGroupIds, String encodedUserData,
            Boolean ebsOptimized, Map<String, String> tags) {
        this.instanceType = instanceType;
        this.amiId = amiId;
        this.subnetIds = subnetIds;
        this.assignPublicIp = assignPublicIp;
        this.keyPair = keyPair;
        this.iamInstanceProfileARN = iamInstanceProfileARN;
        this.securityGroupIds = securityGroupIds;
        this.encodedUserData = encodedUserData;
        this.ebsOptimized = ebsOptimized;
        this.tags = tags;
    }

    /**
     * The name of the instance type to launch. For example, {@code m1.medium}.
     *
     * @return
     */
    public InstanceType getInstanceType() {
        return InstanceType.fromValue(this.instanceType);
    }

    /**
     * The name of the Amazon machine image used to boot new servers. For
     * example, {@code ami-da05a4a0}.
     *
     * @return
     */
    public String getAmiId() {
        return this.amiId;
    }

    /**
     * The IDs of one or more VPC subnets into which created instances are to be
     * launched. The subnets also implicitly determine the availability zones
     * that instances can be launched into. At least one must be specified. A
     * best effort attempt will be made to place instances evenly across the
     * subnets. All subnets are assumed to belong to the same VPC.
     *
     * @return
     */
    public List<String> getSubnetIds() {
        return this.subnetIds;
    }

    /**
     * Indicates if created instances are to be assigned a public IP address.
     *
     * @return
     */
    public boolean isAssignPublicIp() {
        return Optional.ofNullable(this.assignPublicIp).orElse(false);
    }

    /**
     * The name of the key pair to use for new instances. May be
     * null. If none is specified, you can't connect to the
     * instance unless you choose an AMI that is configured to allow users
     * another way to log in.
     *
     * @return
     */
    public String getKeyPair() {
        return this.keyPair;
    }

    /**
     * The ARN of an IAM instance profile to assign to created instances. May be
     * null if no IAM role is to be delegated to instances. For
     * example,
     * {@code arn:aws:iam::123456789012:instance-profile/my-iam-profile}
     *
     * @return
     */
    public String getIamInstanceProfileARN() {
        return this.iamInstanceProfileARN;
    }

    /**
     * Zero or more security group IDs to apply to created instances. If empty
     * EC2 will assign a default security group. All security groups are
     * assumed to belong to the VPC of the {@link #subnetIds}..
     *
     * @return
     */
    public List<String> getSecurityGroupIds() {
        return Optional.ofNullable(this.securityGroupIds).orElse(Collections.emptyList());
    }

    /**
     * A base 64-encoded blob
     * of data used to pass custom data (such as a boot script) to started
     * instances. Refer to the AWS
     * documentation for details. May be null.
     *
     * @return
     */
    public String getEncodedUserData() {
        return this.encodedUserData;
    }

    /**
     * Indicates whether created instances are to be optimized for Amazon EBS
     * I/O. This optimization provides dedicated throughput to Amazon EBS and an
     * optimized configuration stack to provide optimal Amazon EBS I/O
     * performance. Note that this optimization isn't available with all
     * instance types. Additional usage charges apply when using an
     * EBS-optimized instance.
     *
     * @return
     */
    public boolean isEbsOptimized() {
        return Optional.ofNullable(this.ebsOptimized).orElse(false);
    }

    /**
     * Tags that are to be set on created instances in addition to the
     * {@link ScalingTags#CLOUD_POOL_TAG} and
     * {@link ScalingTags#INSTANCE_NAME_TAG} that are always set by the
     * cloudpool.
     *
     * @return
     */
    public Map<String, String> getTags() {
        return Optional.ofNullable(this.tags).orElse(Collections.emptyMap());
    }

    /**
     * Performs basic validation of this configuration.
     *
     * @throws IllegalArgumentException
     */
    public void validate() throws IllegalArgumentException {
        checkArgument(this.instanceType != null, "provisioningTemplate: missing instanceType");
        try {
            InstanceType.fromValue(this.instanceType);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(
                    String.format("provisioingTemplate: unrecognized instanceType: %s", this.instanceType));
        }

        checkArgument(this.amiId != null, "provisioningTemplate: missing amiId");
        checkArgument(this.subnetIds != null, "provisioningTemplate: missing subnetIds");
        checkArgument(!this.subnetIds.isEmpty(), "provisioningTemplate: at least one subnet id must be specified");
    }

    /**
     * Returns a copy of this {@link Ec2ProvisioningTemplate} with an additional
     * tag set.
     *
     * @param tagKey
     * @param tagValue
     * @return
     */
    public Ec2ProvisioningTemplate withTag(String tagKey, String tagValue) {
        Map<String, String> tagsCopy = new HashMap<>(this.tags);
        tagsCopy.put(tagKey, tagValue);
        return new Ec2ProvisioningTemplate(this.instanceType, this.amiId, this.subnetIds, this.assignPublicIp,
                this.keyPair, this.iamInstanceProfileARN, this.securityGroupIds, this.encodedUserData,
                this.ebsOptimized, tagsCopy);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.instanceType, this.amiId, this.subnetIds, this.assignPublicIp, this.keyPair,
                this.iamInstanceProfileARN, this.securityGroupIds, this.encodedUserData, this.ebsOptimized);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Ec2ProvisioningTemplate) {
            Ec2ProvisioningTemplate that = (Ec2ProvisioningTemplate) obj;
            return Objects.equals(this.instanceType, that.instanceType) //
                    && Objects.equals(this.amiId, that.amiId) //
                    && Objects.equals(this.subnetIds, that.subnetIds) //
                    && Objects.equals(this.assignPublicIp, that.assignPublicIp) //
                    && Objects.equals(this.keyPair, that.keyPair) //
                    && Objects.equals(this.iamInstanceProfileARN, that.iamInstanceProfileARN) //
                    && Objects.equals(this.securityGroupIds, that.securityGroupIds) //
                    && Objects.equals(this.encodedUserData, that.encodedUserData) //
                    && Objects.equals(this.ebsOptimized, that.ebsOptimized);
        }
        return false;
    }

    @Override
    public String toString() {
        return JsonUtils.toPrettyString(JsonUtils.toJson(this));
    }

}


text:
package com.earnstone.perf;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public final class PerfUtils {

	public static final int DoublePercision = 3;
	public static final String FormatDefault = "0.###";
	public static final NumberFormat Formatter = new DecimalFormat(FormatDefault);

	public static final double MillisInSec = 1000;
	public static final double MillisInMin = 60 * MillisInSec;
	public static final double MillisInHour = 60 * MillisInMin;
	public static final double MillisInDay = 24 * MillisInHour;

	public enum TimePrecision {
		Milli, Sec, Min, Hour, Day
	}

	public static double round(double value) {
		if (Double.isNaN(value))
			return value;

		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(DoublePercision, BigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}

	public static double getMillisForPrecision(TimePrecision tp) {

		if (tp.equals(TimePrecision.Sec))
			return MillisInSec;
		else if (tp.equals(TimePrecision.Min))
			return MillisInMin;
		else if (tp.equals(TimePrecision.Hour))
			return MillisInHour;
		else if (tp.equals(TimePrecision.Day))
			return MillisInDay;
		else
			return 1;
	}
}


text:
package geospace;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PropertyManager {
    private Properties properties;

    private PropertyManager() {
        this.properties = new Properties();
        try {
            this.properties.load(new FileInputStream("./resources/geospace.properties"));
        } catch (IOException ex) {
            Logger.getLogger(PropertyManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static class PropertyManagerSingleton {
        public static final PropertyManager instance = new PropertyManager();
    }

    public static PropertyManager getInstance() {
        return PropertyManagerSingleton.instance;
    }

    public String getProperty(String propertyName) {
        return this.properties.getProperty(propertyName);
    }

    public String getProperty(String propertyName, String defaultValue) {
        return this.properties.getProperty(propertyName, defaultValue);
    }

    public Integer getInteger(String propertyName) {
        String value = this.properties.getProperty(propertyName);
        return Integer.valueOf(value);
    }

    public Integer getInteger(String propertyName, Integer defaultValue) {
        String value = this.properties.getProperty(propertyName);
        return value == null ? defaultValue : Integer.valueOf(value);
    }

    public boolean getBoolean(String propertyName) {
        String value = this.properties.getProperty(propertyName);

        if(value == null) {
            return false;
        }

        return value.equalsIgnoreCase("true");
    }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Raphiospora viridescens A. Massal.

### Remarks
null


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

<function>
    <description>
Changes the value of a given cell to the provided value.

If the parameter `formula` is true then the `value` is treated and stored as formula, otherwise the `value` is stored as text. Default is false.
    </description>
    <deprecated>
Deprecated because the purpose of this construct might be unclear.

Can be replaced by Excel.setCellFormula or Excel.setCellValue.
    </deprecated>
    <examples>
        <example title="Usage">
            Changing a cell value

                use Excel;
                var workbook = Excel.loadWorkbook("workbook.xlsx");
                var sheet = Excel.loadSheet(workbook, "firstsheet");
                Excel.setCell(sheet, "A", 9, 32);

        </example>
    </examples>
    <references>
        <reference>setCellFormula</reference>
        <reference>setCellValue</reference>
        <reference>loadSheet</reference>
        <reference>loadWorkbook</reference>
        <reference>getCell</reference>
        <reference>createWorkbook</reference>
        <reference>loadWorkbook</reference>
        <reference>save</reference>
        <reference>System.print</reference>
    </references>
    <tags>
        Excel, cell, change, value, set, formula
    </tags>
</function>


text:
layout: page
title: Stephenson Omega Enterprises Seminar
date: 2016-05-24
author: Bryan Stevens
tags: weekly links, java
status: published
summary: Aenean quis leo eu libero.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/10/2019
  endDate: 01/14/2019
  ctyhocn: ICTSCHX
  groupCode: SOES
published: true
---
Sed sem nisl, finibus eleifend diam quis, vestibulum cursus libero. Ut nec mi non purus luctus mollis nec vitae elit. Nulla dictum faucibus risus, at blandit metus varius consequat. Mauris non arcu nulla. Praesent vitae sodales ante. Duis tincidunt lectus nec mi viverra, ut porta sem tempor. Vestibulum pulvinar, mauris at vulputate egestas, dui mi tincidunt libero, aliquam condimentum nulla dui nec tortor. Quisque blandit vitae dolor et congue. Nam finibus bibendum turpis nec condimentum.

* Curabitur dignissim nulla eget eros commodo, sit amet ultricies lorem luctus
* Donec non diam finibus, euismod nunc ut, tincidunt sem
* Aliquam non mi ac justo congue egestas.

Sed et aliquet magna. Integer sagittis eros nec consectetur vehicula. Sed hendrerit ante ac ornare consectetur. Cras ac lectus interdum augue lacinia pharetra. Nullam ac iaculis tortor, sit amet varius leo. Morbi viverra libero vel nibh malesuada vulputate. Fusce sed ornare ex, in semper risus. Etiam consequat, neque sit amet pharetra malesuada, metus elit maximus risus, vitae malesuada erat libero vitae quam. Cras interdum ligula nunc, et rhoncus sapien porta in. Sed cursus nisi at elit vulputate tincidunt. Quisque vel justo nec felis scelerisque elementum quis vel massa. Mauris in lobortis eros, in placerat velit. Nunc tempor orci mauris, nec vehicula tortor tempus in. Donec pharetra purus et ligula pretium, vitae pellentesque sapien laoreet. Quisque vestibulum ex sed magna commodo cursus. In sit amet volutpat lacus, non blandit lacus.


text:
package algorithms.h4.positionallist;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class LinkedPositionalListTest {

	LinkedPositionalList<String> poslist;

	Position<String> first;
	Position<String> last;

	@Before
	public void setUp() {
		poslist = new LinkedPositionalList<String>();
		first = poslist.prepend("first");
		last = poslist.append("last");

	}

	@Test
	public void testConstructor() {
		LinkedPositionalList<String> poslist = new LinkedPositionalList<String>();
		assertTrue(poslist.isEmpty());
		assertEquals(0, poslist.size());
	}

	@Test
	public void testAppendandPrepend() {

		assertEquals(2, poslist.size());
		assertFalse(poslist.isEmpty());

	}

	@Test
	public void testGet(){
		assertEquals("first", first.getElement());
		assertEquals("last", last.getElement());
	}

	@Test
	public void testBeforeAndAfter(){

		assertEquals(first, poslist.before(last));
		assertEquals(last, poslist.after(first));

	}

	@Test
	public void testAddBeforeAndAddAfter(){

		Position<String> second = poslist.addAfter(first, "addAfter");
		Position<String> third =poslist.addBefore(last, "addBefore");

		assertEquals(second, poslist.after(first));
		assertEquals(third, poslist.before(last));

	}

	@Test
	public void testSet(){
		assertEquals("first", poslist.set(first, "replaced"));
		assertEquals("replaced", poslist.first().getElement());
	}

	@Test
	public void testRemove(){
		assertEquals("last", poslist.remove(last));
		assertEquals(1, poslist.size());
		assertEquals(first, poslist.last());
	}

	@Test
	public void testAddBeforeAndAddAfterAtEnd(){

		Position<String> before = poslist.addBefore(first, "before");
		Position<String> after =poslist.addAfter(last, "after");

		assertEquals(before, poslist.before(first));
		assertEquals(after, poslist.after(last));
	}

	@Test
	public void testHasNext(){
		assertTrue(poslist.hasNext(first));
		assertFalse(poslist.hasNext(last));
	}

	@Test
	public void testIterator(){
		poslist.addAfter(first, "middle");

		StringBuilder str = new StringBuilder();

		for(String s : poslist){
			str.append(s);
			str.append(" ");
		}

		assertEquals("first middle last ", str.toString());

	}

	@Test
	public void testAddBeforeAndAfterSentinels(){
		LinkedPositionalList<String> poslist = new LinkedPositionalList<String>();
		Position<String> header = poslist.last();
		Position<String> trailer = poslist.first();
		Position<String> before = poslist.addBefore(header, "before");
		Position<String> after = poslist.addAfter(trailer, "after");

		/*
		 * What do you want to happen?
		 * 1) Undefined behavior: you should not add before or after the respective sentinel
		 * 1.1) You might want to avoid leaking the sentinel returning null in the position method
		 * 2) Throw an exception: check if an illegal add happens and throw an exception
		 * 3) Assume adding before or after the respective sentinel effectively means adding it in first or last position respectively
		 */

	}
}


text:
module ApplicationProxy
  def application_proxy
    @application_proxy ||= -> (env) do
      Rails.application.call(env).tap do |(status, headers, body)|
        rack_response = ::Rack::MockResponse.new(status, headers, body, env['rack.errors'].flush)
        response = ::ActionDispatch::TestResponse.from_response(rack_response)
        instance_variable_set(:@response, response)
      end
    end
  end
end

RSpec.configure do |config|
  config.include ApplicationProxy
end


text:
package com.nankai.exchange.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nankai.exchange.biz.IQueryOrderBiz;
import com.nankai.exchange.biz.impl.QueryOrderBizImpl;
import com.nankai.exchange.po.TradeOrder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class AOrderServlet
 */
public class AOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");

		//int userid = 2;
		String userid1 = request.getParameter("userid");

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create();
		int userid = gson.fromJson(userid1, int.class);

		IQueryOrderBiz queryOrderBiz = new QueryOrderBizImpl();
		List<TradeOrder> lstTradeOrders = queryOrderBiz.queryOrder(userid);

		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();

		String gson_info = gson.toJson(lstTradeOrders);

		out.println(gson_info);

		out.flush();
		out.close();
	}

}


text:
// Copyright 2019 Google LLC
//
// 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.

package com.google.corp.gtech.ads.datacatalyst.components.mldatawindowingpipeline.feature.accumulator;

import com.google.common.collect.ImmutableMap;
import com.google.corp.gtech.ads.datacatalyst.components.mldatawindowingpipeline.model.LookbackWindow;
import java.util.Map;
import org.joda.time.Duration;

/**
 * Feature accumulator to extract the average by the tenure value of a fact. Example: Extract the
 * average value of the fact 'page_views' as a feature.
 */
public class AverageByTenureValueFeatureAccumulator extends WindowBasedFeatureAccumulator {

  private double sum;

  public AverageByTenureValueFeatureAccumulator(
      String column, ImmutableMap<String, String> values, String defaultValue) {
    super(column, values, defaultValue);
  }

  @Override
  public Map<String, Object> getFeatures() {
    String featureName = getValueToFeatureName().values().iterator().next();
    return ImmutableMap.of(featureName, roundedFeatureValue(sum / Math.max(getTenure(), 1)));
  }

  @Override
  public void accumulate(String value) {
    super.accumulate(value);
    sum += Double.parseDouble(value);
  }

  // Window size or the period the instance has been active in the window whichever is lesser.
  // Example: Window size is 30 days but the instance has only activity for the last 10 days of that
  // window. For this case, tenure is 10 days.
  private long getTenure() {
    final LookbackWindow window = getWindow();

    // The difference of window's endTime and startTime.
    long windowSizeInDays =
        new Duration(window.getStartTime(), window.getEndTime()).getStandardDays();
    long activityPeriodInDays =
        new Duration(
                window.getFirstActivityTime().getMillis(), window.getEffectiveDate().getMillis())
            .getStandardDays();

    return Math.min(windowSizeInDays, activityPeriodInDays);
  }
}


text:
package org.eclipse.jdt.internal.ui.text.java;

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

import org.eclipse.core.commands.IParameterValues;

/**
 * Map of parameters for the specific content assist command.
 *
 * @since 3.2
 */
public final class ContentAssistComputerParameter implements IParameterValues {
	/*
	 * @see org.eclipse.core.commands.IParameterValues#getParameterValues()
	 */
	public Map<String, String> getParameterValues() {
		Collection<CompletionProposalCategory> descriptors= CompletionProposalComputerRegistry.getDefault().getProposalCategories();
		Map<String, String> map= new HashMap<String, String>(descriptors.size());
		for (Iterator<CompletionProposalCategory> it= descriptors.iterator(); it.hasNext();) {
			CompletionProposalCategory category= it.next();
			map.put(category.getDisplayName(), category.getId());
		}
		return map;
	}
}


text:
class UpdaterBodyImpl : public Updater::UpdaterBody
{
public:
    virtual ~UpdaterBodyImpl() {}
    virtual bool Execute(Updater::RingBuffer *buffer, Updater::CallbackInterface *interface);
    virtual void Stop() {}
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

// Given a binary tree, find the maximum path sum.

// The path may start and end at any node in the tree.

// For example:
// Given the below binary tree,

//       1
//      / \
//     2   3
// Return 6.

// https://leetcode.com/problems/binary-tree-maximum-path-sum/
namespace LocalLeet
{
    public class Q124
    {
        public int MaxPathSum(BinaryTree root)
        {
            return MaxPathSumInt(root).Item2;
        }

        // Item1, answer that including root, can be combine with upstream node, so it can only connect to 1 child
        // Item2, answer
        public Tuple<int, int> MaxPathSumInt(BinaryTree root)
        {
            if (root == null)
            {
                return Tuple.Create(0, 0);
            }
            if (root.Left == null && root.Right == null)
            {
                return Tuple.Create(root.Value, root.Value);
            }
            if (root.Left == null)
            {
                var rAnswer = MaxPathSumInt(root.Right);
                int item1 = Math.Max(0, rAnswer.Item1) + root.Value;
                int item2 = (new[] { item1, rAnswer.Item2 }).Max();
                return Tuple.Create(item1, item2);
            }
            if (root.Right == null)
            {
                var lAnswer = MaxPathSumInt(root.Left);
                int item1 = Math.Max(0, lAnswer.Item1) + root.Value;
                int item2 = (new[] { item1, lAnswer.Item2 }).Max();
                return Tuple.Create(item1, item2);
            }
            // left and right both exist
            var ll = MaxPathSumInt(root.Left);
            var rr = MaxPathSumInt(root.Right);
            int a1 = Math.Max(0, Math.Max(ll.Item1, rr.Item1)) + root.Value;
            int a2 = (new[] { a1, ll.Item2, rr.Item2, (root.Value + ll.Item1 + rr.Item1) }).Max();
            return Tuple.Create(a1, a2);
        }

        [Fact]
        public void Q124_BinaryTreeMaximumPathSum()
        {
            TestHelper.Run(input => MaxPathSum(input[0].ToBinaryTree()).ToString());
        }
    }
}


text:
/// <reference path="jquery-2.1.1.js" />
/// <reference path="modernizr-2.7.2.js" />
/// <autosync enabled="true" />
/// <reference path="bootstrap.js" />
/// <reference path="knockout-2.3.0.js" />
/// <reference path="app/_run.js" />
/// <reference path="app/app.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.signalr-2.0.0.js" />
/// <reference path="moment-with-langs.js" />
/// <reference path="moment.js" />


text:
package sarama

import (
	"encoding/binary"
	"fmt"
	"io"
)

type protocolBody interface {
	encoder
	versionedDecoder
	key() int16
	version() int16
	requiredVersion() KafkaVersion
}

type request struct {
	correlationID int32
	clientID      string
	body          protocolBody
}

func (r *request) encode(pe packetEncoder) (err error) {
	pe.push(&lengthField{})
	pe.putInt16(r.body.key())
	pe.putInt16(r.body.version())
	pe.putInt32(r.correlationID)
	err = pe.putString(r.clientID)
	if err != nil {
		return err
	}
	err = r.body.encode(pe)
	if err != nil {
		return err
	}
	return pe.pop()
}

func (r *request) decode(pd packetDecoder) (err error) {
	var key int16
	if key, err = pd.getInt16(); err != nil {
		return err
	}
	var version int16
	if version, err = pd.getInt16(); err != nil {
		return err
	}
	if r.correlationID, err = pd.getInt32(); err != nil {
		return err
	}
	r.clientID, err = pd.getString()

	r.body = allocateBody(key, version)
	if r.body == nil {
		return PacketDecodingError{fmt.Sprintf("unknown request key (%d)", key)}
	}
	return r.body.decode(pd, version)
}

func decodeRequest(r io.Reader) (req *request, bytesRead int, err error) {
	lengthBytes := make([]byte, 4)
	if _, err := io.ReadFull(r, lengthBytes); err != nil {
		return nil, bytesRead, err
	}
	bytesRead += len(lengthBytes)

	length := int32(binary.BigEndian.Uint32(lengthBytes))
	if length <= 4 || length > MaxRequestSize {
		return nil, bytesRead, PacketDecodingError{fmt.Sprintf("message of length %d too large or too small", length)}
	}

	encodedReq := make([]byte, length)
	if _, err := io.ReadFull(r, encodedReq); err != nil {
		return nil, bytesRead, err
	}
	bytesRead += len(encodedReq)

	req = &request{}
	if err := decode(encodedReq, req); err != nil {
		return nil, bytesRead, err
	}
	return req, bytesRead, nil
}

func allocateBody(key, version int16) protocolBody {
	switch key {
	case 0:
		return &ProduceRequest{}
	case 1:
		return &FetchRequest{}
	case 2:
		return &OffsetRequest{Version: version}
	case 3:
		return &MetadataRequest{}
	case 8:
		return &OffsetCommitRequest{Version: version}
	case 9:
		return &OffsetFetchRequest{}
	case 10:
		return &FindCoordinatorRequest{}
	case 11:
		return &JoinGroupRequest{}
	case 12:
		return &HeartbeatRequest{}
	case 13:
		return &LeaveGroupRequest{}
	case 14:
		return &SyncGroupRequest{}
	case 15:
		return &DescribeGroupsRequest{}
	case 16:
		return &ListGroupsRequest{}
	case 17:
		return &SaslHandshakeRequest{}
	case 18:
		return &ApiVersionsRequest{}
	case 19:
		return &CreateTopicsRequest{}
	case 20:
		return &DeleteTopicsRequest{}
	case 21:
		return &DeleteRecordsRequest{}
	case 22:
		return &InitProducerIDRequest{}
	case 24:
		return &AddPartitionsToTxnRequest{}
	case 25:
		return &AddOffsetsToTxnRequest{}
	case 26:
		return &EndTxnRequest{}
	case 28:
		return &TxnOffsetCommitRequest{}
	case 29:
		return &DescribeAclsRequest{}
	case 30:
		return &CreateAclsRequest{}
	case 31:
		return &DeleteAclsRequest{}
	case 32:
		return &DescribeConfigsRequest{}
	case 33:
		return &AlterConfigsRequest{}
	case 37:
		return &CreatePartitionsRequest{}
	case 42:
		return &DeleteGroupsRequest{}
	}
	return nil
}


text:
Perl shell from the 90s

psh (c) 1998 Marcel Turcotte and Bob MacCallum

Would be very happy for someone to drag it into the 21st century (but it still works fine for me).

##Description

(See also https://gnp.github.io/psh/)

Simple perl shell, uses AUTOLOAD to make system calls for commands which
are not defined.  Multiple line entry is accomplished by adding a
trailing backslash, or by leaving an unbalanced (, { or [ (or <<EOF).
Force execution (the balancing check isn't very clever) by terminating
a line with ;; (two semicolons)

If you need a unix command instead of its perl namesake (eg. grep) then
prepend an underscore, eg: _grep('pattern', 'file') or you could use
system() or backticks

##.pshrc   ($ENV{HOME}/.pshrc)

You can put your own functions and other startup code in your .pshrc

To use unix `ls' (for example) without having to write ls() put prototypes
in your .pshrc like this
  sub ls;
  sub emacs;

or see http://perldoc.perl.org/5.8.8/Shell.html

Aliases are done like this:

  sub ll { ls('-l', @_) };

##changing the behaviour in .pshrc

the $prompt variable is evalled to make the prompt

adjust $psh_history_size = 50
to change the size of the history between invocations (default 100)

##Miscellaneous

If you need to `source' a perl program use perl's `do' function
or if it's a module, use `use' of course.

line editing/file/command/variable completion by the Gnu ReadLine library

plus... Control-g : kill-whole-line

add your own changes using .inputrc or in your .pshrc using
  $readline_terminal->parse_and_bind("Control-g: kill-whole-line");
  (see the GNU Readline user manual)

some `built-in' variables that you can use

$lr is the last result

to echo $lr after each command set

$echolr = 1

##Job control (backgrounding)

Control-z will background a running job (not suspend it like csh)
***this does not work for unix/system commands, use bg (see below) ***
the `listjobs' command will list process ids (pid) of running jobs
to kill a job use: kill 9, pid  (the perl function)

to background perl code or other commands from the outset use:
bg { code }


text:
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<title>Suppression de la fiche candidat en cours...</title>
</head>
<body>
	<?php
		header('Location: admin-bo.php');

		try {
			$bdd = new PDO('mysql:host=localhost;dbname=candidat;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
		} catch (Exception $e) {
			die('Erreur : ' . $e->getMessage());
		}

		if(!empty($_POST['idfiche'])) {
			$suppression = $bdd->prepare('DELETE FROM informatique WHERE id = :idfiche');
		$suppression->execute(array(
			'idfiche' => strip_tags($_POST['idfiche'])
			));

		$suppression->closeCursor();
		}
	?>
</body>
</html>


text:
**[SEGY](../ReferencePages/Formats/SEGY.md)**
**[Karat](../ReferencePages/Formats/Karat.md)**

## Символы

**[SEGYData](../ReferencePages/Symbols/SEGYData.md)**
**[SEGYElement](../ReferencePages/Symbols/SEGYElement.md)**
**[KaratData](../ReferencePages/Symbols/KaratData.md)**

## Туториалы

- [Фомарты Файлов - Примеры Использования](../Tutorials/ExampleOfUse.md)


text:
/*
 * $Id: MulticastDataLink.cpp 6893 2015-01-29 15:27:49Z wilsonj $
 *
 *
 * Distributed under the OpenDDS License.
 * See: http://www.opendds.org/license.html
 */

#include "MulticastDataLink.h"
#include "MulticastSession.h"
#include "MulticastSessionFactory.h"
#include "MulticastTransport.h"

#include "ace/Default_Constants.h"
#include "ace/Global_Macros.h"
#include "ace/Log_Msg.h"
#include "ace/Truncate.h"
#include "ace/OS_NS_sys_socket.h"

#include "tao/ORB_Core.h"

#include "dds/DCPS/Service_Participant.h"

#ifndef __ACE_INLINE__
# include "MulticastDataLink.inl"
#endif  /* __ACE_INLINE__ */

namespace OpenDDS {
namespace DCPS {

MulticastDataLink::MulticastDataLink(MulticastTransport* transport,
    MulticastSessionFactory* session_factory,
    MulticastPeer local_peer,
    bool is_active)
: DataLink(transport, 0 /*priority*/, false /*loopback*/, is_active),
  transport_(transport),
  session_factory_(session_factory, false),
  local_peer_(local_peer),
  config_(0),
  reactor_task_(0),
  send_buffer_(0)
{
}

MulticastDataLink::~MulticastDataLink()
{
  if (this->send_buffer_) {
    this->send_strategy_->send_buffer(0);
    delete this->send_buffer_;
  }
}

void
MulticastDataLink::configure(MulticastInst* config,
    TransportReactorTask* reactor_task)
{
  this->config_ = config;
  this->reactor_task_ = reactor_task;
}

void
MulticastDataLink::send_strategy(MulticastSendStrategy* send_strategy)
{
  // A send buffer may be bound to the send strategy to ensure a
  // configured number of most-recent datagrams are retained:
  if (this->session_factory_->requires_send_buffer()) {
    ACE_NEW_NORETURN(this->send_buffer_,
        SingleSendBuffer(this->config_->nak_depth_,
            this->config_->max_samples_per_packet_));
    if (!this->send_buffer_) {
      ACE_ERROR((LM_ERROR,
          ACE_TEXT("(%P|%t) ERROR: ")
          ACE_TEXT("MulticastDataLink::send_strategy: ")
          ACE_TEXT("failed to create SingleSendBuffer!\n")));
      return;
    }
    send_strategy->send_buffer(this->send_buffer_);
  }
  this->send_strategy_ = send_strategy;
}

void
MulticastDataLink::receive_strategy(MulticastReceiveStrategy* recv_strategy)
{
  this->recv_strategy_ = recv_strategy;
}

bool
MulticastDataLink::join(const ACE_INET_Addr& group_address)
{
  const std::string& net_if = this->config_->local_address_;
  if (this->socket_.join(group_address, 1,
      net_if.empty() ? 0 :
          ACE_TEXT_CHAR_TO_TCHAR(net_if.c_str())) != 0) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: MulticastDataLink::join: ")
        ACE_TEXT("ACE_SOCK_Dgram_Mcast::join failed %m.\n")),
        false);
  }
  VDBG_LVL((LM_DEBUG, ACE_TEXT("(%P|%t) MulticastDataLink::join OK\n")), 6);

  ACE_HANDLE handle = this->socket_.get_handle();
  char ttl = this->config_->ttl_;

  if (ACE_OS::setsockopt(handle,
      IPPROTO_IP,
      IP_MULTICAST_TTL,
      &ttl,
      sizeof(ttl)) < 0) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::join: ")
        ACE_TEXT("ACE_OS::setsockopt TTL failed.\n")),
        false);
  }

  int rcv_buffer_size = ACE_Utils::truncate_cast<int>(this->config_->rcv_buffer_size_);
  if (rcv_buffer_size != 0
      && ACE_OS::setsockopt(handle, SOL_SOCKET,
          SO_RCVBUF,
          (char *) &rcv_buffer_size,
          sizeof (int)) < 0) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::join: ")
        ACE_TEXT("ACE_OS::setsockopt RCVBUF failed.\n")),
        false);
  }

#if defined (ACE_DEFAULT_MAX_SOCKET_BUFSIZ)
  int snd_size = ACE_DEFAULT_MAX_SOCKET_BUFSIZ;

  if (ACE_OS::setsockopt(handle, SOL_SOCKET,
      SO_SNDBUF,
      (char *) &snd_size,
      sizeof(snd_size)) < 0
      && errno != ENOTSUP) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::join: ")
        ACE_TEXT("ACE_OS::setsockopt SNDBUF failed to set the send buffer size to %d errno %m\n"),
        snd_size),
        false);
  }
#endif /* ACE_DEFAULT_MAX_SOCKET_BUFSIZ */

  if (start(static_rchandle_cast<TransportSendStrategy>(this->send_strategy_),
      static_rchandle_cast<TransportStrategy>(this->recv_strategy_))
      != 0) {
    this->socket_.close();
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::join: ")
        ACE_TEXT("DataLink::start failed!\n")),
        false);
  }

  return true;
}

MulticastSession*
MulticastDataLink::find_session(MulticastPeer remote_peer)
{
  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_,
      0);

  MulticastSessionMap::iterator it(this->sessions_.find(remote_peer));
  if (it != this->sessions_.end()) {
    MulticastSession_rch sess = it->second;
    return sess._retn();
  }
  else return 0;
}

MulticastSession*
MulticastDataLink::find_or_create_session(MulticastPeer remote_peer)
{
  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_,
      0);

  MulticastSessionMap::iterator it(this->sessions_.find(remote_peer));
  if (it != this->sessions_.end()) {
    MulticastSession_rch sess = it->second;
    return sess._retn();
  }

  MulticastSession_rch session =
    this->session_factory_->create(transport()->reactor(), transport()->reactor_owner(), this, remote_peer);
  if (session.is_nil()) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::find_or_create_session: ")
        ACE_TEXT("failed to create session for remote peer: 0x%x!\n"),
        remote_peer),
        0);
  }

  std::pair<MulticastSessionMap::iterator, bool> pair = this->sessions_.insert(
      MulticastSessionMap::value_type(remote_peer, session));
  if (pair.first == this->sessions_.end()) {
    ACE_ERROR_RETURN((LM_ERROR,
        ACE_TEXT("(%P|%t) ERROR: ")
        ACE_TEXT("MulticastDataLink::find_or_create_session: ")
        ACE_TEXT("failed to insert session for remote peer: 0x%x!\n"),
        remote_peer),
        0);
  }
  return session._retn();
}

bool
MulticastDataLink::check_header(const TransportHeader& header)
{
  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_,
      false);

  MulticastSessionMap::iterator it(this->sessions_.find(header.source_));
  if (it == this->sessions_.end() && is_active()) {
    return false;
  }
  if (it != this->sessions_.end() && it->second->acked()) {
    return it->second->check_header(header);
  }

  return true;
}

bool
MulticastDataLink::check_header(const DataSampleHeader& header)
{
  if (header.message_id_ == TRANSPORT_CONTROL) return true;

  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_,
      false);

  // Skip data sample unless there is a session for it.
  return (this->sessions_.count(receive_strategy()->received_header().source_) > 0);
}

bool
MulticastDataLink::reassemble(ReceivedDataSample& data,
    const TransportHeader& header)
{
  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_,
      false);

  MulticastSessionMap::iterator it(this->sessions_.find(header.source_));
  if (it == this->sessions_.end()) return false;
  if (it->second->acked()) {
    return it->second->reassemble(data, header);
  }
  return false;
}

void
MulticastDataLink::sample_received(ReceivedDataSample& sample)
{
  switch (sample.header_.message_id_) {
  case TRANSPORT_CONTROL: {
    // Transport control samples are delivered to all sessions
    // regardless of association status:
    {
      char* const ptr = sample.sample_ ? sample.sample_->rd_ptr() : 0;

      ACE_GUARD(ACE_SYNCH_RECURSIVE_MUTEX,
          guard,
          this->session_lock_);

      const TransportHeader& theader = receive_strategy()->received_header();

      if (!is_active() && sample.header_.submessage_id_ == MULTICAST_SYN &&
          sessions_.find(theader.source_) == sessions_.end()) {
        // We have received a SYN but there is no session (yet) for this source.
        // Depending on the data, we may need to send SYNACK.

        guard.release();
        syn_received_no_session(theader.source_, sample.sample_,
            theader.swap_bytes());
        if (ptr) {
          sample.sample_->rd_ptr(ptr);
        }
        return;
      }

      MulticastSessionMap temp_sessions(sessions_);
      guard.release();

      for (MulticastSessionMap::iterator it(temp_sessions.begin());
          it != temp_sessions.end(); ++it) {
        it->second->control_received(sample.header_.submessage_id_,
            sample.sample_);
        // reset read pointer
        if (ptr) {
          sample.sample_->rd_ptr(ptr);
        }
      }
    }
  } break;

  case SAMPLE_ACK:
    ack_received(sample);
    break;

  default:
    if (!duplicate_data_sample(sample.header_)) {
      data_received(sample);
    }
    break;
  }
}

bool
MulticastDataLink::duplicate_data_sample(const DataSampleHeader& header)
{
  if (header.sequence_ == SequenceNumber::SEQUENCENUMBER_UNKNOWN()
      || header.publication_id_ == GUID_UNKNOWN) {
    return false;
  }
  ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX, guard, session_lock_, false);
  return !data_samples_seen_[header.publication_id_].insert(header.sequence_);
}

void
MulticastDataLink::release_remote_i(const RepoId& remote)
{
  ACE_GUARD(ACE_SYNCH_RECURSIVE_MUTEX, guard, session_lock_);
  data_samples_seen_.erase(remote);
}

void
MulticastDataLink::syn_received_no_session(MulticastPeer source,
    ACE_Message_Block* data,
    bool swap_bytes)
{
  Serializer serializer_read(data, swap_bytes);

  MulticastPeer local_peer;
  serializer_read >> local_peer;

  if (local_peer != local_peer_) {
    return;
  }

  VDBG_LVL((LM_DEBUG, "(%P|%t) MulticastDataLink[%C]::syn_received_no_session "
      "send_synack local 0x%x remote 0x%x\n",
      config_->name().c_str(), local_peer, source), 2);

  ACE_Message_Block* synack_data = new ACE_Message_Block(sizeof(MulticastPeer));

  Serializer serializer_write(synack_data);
  serializer_write << source;

  DataSampleHeader header;
  ACE_Message_Block* control =
      create_control(MULTICAST_SYNACK, header, synack_data);

  const int error = send_control(header, control);
  if (error != SEND_CONTROL_OK) {
    ACE_ERROR((LM_ERROR, "(%P|%t) MulticastDataLink::syn_received_no_session: "
        "ERROR: send_control failed: %d!\n", error));
    return;
  }

  transport_->passive_connection(local_peer, source);
}

void
MulticastDataLink::stop_i()
{
  ACE_GUARD(ACE_SYNCH_RECURSIVE_MUTEX,
      guard,
      this->session_lock_);

  for (MulticastSessionMap::iterator it(this->sessions_.begin());
      it != this->sessions_.end(); ++it) {
    it->second->stop();
  }
  this->sessions_.clear();

  this->socket_.close();
}

} // namespace DCPS
} // namespace OpenDDS


text:
import Application from '@ember/application';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from 'sharedrop/config/environment';
import * as Sentry from '@sentry/browser';
import { Ember as EmberIntegration } from '@sentry/integrations';

Sentry.init({
  dsn:
    'https://ba1292a9c759401dbbda4272f183408d@o432021.ingest.sentry.io/5384091',
  integrations: [new EmberIntegration()],
});

export default class App extends Application {
  modulePrefix = config.modulePrefix;

  podModulePrefix = config.podModulePrefix;

  Resolver = Resolver;
}

loadInitializers(App, config.modulePrefix);


text:
class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :likeable, polymorphic: true, touch: true
end


text:
'''

    Copyright 2012 Joe Harris

    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.

'''

'''

    Trivial example of how to request CDN-enabled container meta data. See:

    http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_CDN-Enabled_Container_Metadata-d1e2711.html

'''

import os, sys

# make sure our local copy of txcloudfiles is in sys.path
PATH_TO_TXCF = '../txcloudfiles/'
try:
    import txcloudfiles
except ImportError:
    txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
    if txcfpath not in sys.path:
        sys.path.insert(0, txcfpath)

from twisted.internet import reactor
from txcloudfiles import get_auth, UK_ENDPOINT, US_ENDPOINT, DataUsage

def _got_session(session):
    print '> got session: %s' % session
    container_name = 'some_test_container'
    def _ok((response, container)):
        '''
            'response' is a transport.Response() instance.
            'container' is a cfaccount.Container() instance.
        '''
        for k,v in response.headers.items():
            print k,v
        print '> got response: %s' % response
        print '> got CDN-enabled container: %s' % container
        print 'URL:', container.get_cdn_url()
        print 'SSL URL:', container.get_ssl_url()
        print 'streaming URL:', container.get_stream_url()
        print 'TTL:', container.get_ttl()
        print 'logging:',  container.get_logging()
        reactor.stop()
    print '> sending request'
    # 'container' here is any name of an existing empty container. Can be a Container() object if you like.
    session.get_cdn_container_metadata(container=container_name).addCallback(_ok).addErrback(_error)

def _error(e):
    '''
        'e' here will be a twisted.python.failure.Failure() instance wrapping
        a ResponseError() object. ResponseError() instances contain information
        about the request to help you find out why it errored through its
        ResponseError().request attribute.
    '''
    print 'error!'
    print e.printTraceback()
    reactor.stop()

auth = get_auth(UK_ENDPOINT, os.environ.get('TXCFUSR', ''), os.environ.get('TXCFAPI', ''))
auth.get_session().addCallback(_got_session).addErrback(_error)

reactor.run()

'''

    EOF

'''


text:
// RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc692.allisonsPracticeBot;

import org.usfirst.frc692.allisonsPracticeBot.commands.*;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.*;

/**
 * This class is the glue that binds the controls on the physical operator
 * interface to the commands and command groups that allow control of the robot.
 */
public class OI {
    //// CREATING BUTTONS
    // One type of button is a joystick button which is any button on a joystick.
    // You create one by telling it which joystick it's on and which button
    // number it is.
    // Joystick stick = new Joystick(port);
    // Button button = new JoystickButton(stick, buttonNumber);

    // There are a few additional built in buttons you can use. Additionally,
    // by subclassing Button you can create custom triggers and bind those to
    // commands the same as any other Button.

    //// TRIGGERING COMMANDS WITH BUTTONS
    // Once you have a button, it's trivial to bind it to a button in one of
    // three ways:

    // Start the command when the button is pressed and let it run the command
    // until it is finished as determined by it's isFinished method.
    // button.whenPressed(new ExampleCommand());

    // Run the command while the button is being held down and interrupt it once
    // the button is released.
    // button.whileHeld(new ExampleCommand());

    // Start the command when the button is released  and let it run the command
    // until it is finished as determined by it's isFinished method.
    // button.whenReleased(new ExampleCommand());

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
    public Joystick operatorOne;
    public Joystick operatorTwo;
    public Joystick driver;

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS

    public OI() {
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS

        driver = new Joystick(2);

        operatorTwo = new Joystick(1);

        operatorOne = new Joystick(0);

        // SmartDashboard Buttons
        SmartDashboard.putData("Autonomous Command", new AutonomousCommand());

        SmartDashboard.putData("driveFoward", new driveFoward());

        SmartDashboard.putData("driveBackward", new driveBackward());

        SmartDashboard.putData("driveLeft", new driveLeft());

        SmartDashboard.putData("driveRight", new driveRight());

        SmartDashboard.putData("driveJoystickValue", new driveJoystickValue());

        SmartDashboard.putData("caterpillarIn", new caterpillarIn());

        SmartDashboard.putData("caterpillarOut", new caterpillarOut());

        SmartDashboard.putData("caterpillarJoystickValue", new caterpillarJoystickValue());

        SmartDashboard.putData("gatherIn", new gatherIn());

        SmartDashboard.putData("gatherOut", new gatherOut());

        SmartDashboard.putData("GatherJoystickValue", new GatherJoystickValue());

        SmartDashboard.putData("elevatorDown", new elevatorDown());

        SmartDashboard.putData("ElevatorUp", new ElevatorUp());

        SmartDashboard.putData("elevatorJoystickValue", new elevatorJoystickValue());

        SmartDashboard.putData("flapperIn", new flapperIn());

        SmartDashboard.putData("flapperOut", new flapperOut());

        SmartDashboard.putData("driveTurnLeft", new driveTurnLeft());

        SmartDashboard.putData("driveTurnRight", new driveTurnRight());

        SmartDashboard.putData("gatherStop", new gatherStop());

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
    }

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
    public Joystick getoperatorOne() {
        return operatorOne;
    }

    public Joystick getoperatorTwo() {
        return operatorTwo;
    }

    public Joystick getdriver() {
        return driver;
    }

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
}


text:
swoole_mysql: simple query
--SKIPIF--
<?php require __DIR__ . "/../inc/skipif.inc"; ?>
--INI--
assert.active=1
assert.warning=1
assert.bail=0
assert.quiet_eval=0

--FILE--
<?php
require_once __DIR__ . "/../inc/zan.inc";

fork_exec(function() {
    require_once __DIR__ . "/../../apitest/swoole_mysql/swoole_mysql_query.php";
});
?>
--EXPECT--
SUCCESS


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="DOUBLE data type" />
<meta name="abstract" content="The DOUBLE data type is a synonym for the DOUBLE PRECISION data type." />
<meta name="description" content="The DOUBLE data type is a synonym for the DOUBLE PRECISION data type." />
<meta content="DOUBLE data type" name="DC.subject" />
<meta content="DOUBLE data type" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj31068.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj42002" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>DOUBLE data type</title>

DOUBLE data type

The DOUBLE data type is a synonym for the DOUBLE PRECISION data
type.

See DOUBLE PRECISION data type.

Syntax

DOUBLE

Parent topic: Data types


text:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Terminal } from './terminal';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { TerminalService } from './terminalservice';
import { FormsModule } from '@angular/forms';
import { Component } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
    template: `<p-terminal welcomeMessage="Welcome to PrimeNG" prompt="primeng $"></p-terminal>`
})
class TestTerminalComponent {
    subscription: Subscription;

    constructor(private terminalService: TerminalService) {
        this.terminalService.commandHandler.subscribe((command) => {
            let response = command === 'd' ? 'Command succeed' : 'Unknown command: ' + command;
            this.terminalService.sendResponse(response);
        });
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}

describe('Terminal', () => {
    let terminal: Terminal;
    let fixture: ComponentFixture<TestTerminalComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [NoopAnimationsModule, FormsModule],
            declarations: [Terminal, TestTerminalComponent],
            providers: [TerminalService]
        });

        fixture = TestBed.createComponent(TestTerminalComponent);
        terminal = fixture.debugElement.children[0].componentInstance;
    });

    it('should display by default', () => {
        fixture.detectChanges();

        const terminalEl = fixture.debugElement.query(By.css('div'));
        expect(terminalEl.nativeElement).toBeTruthy();
    });

    it('should handle command', () => {
        fixture.detectChanges();

        terminal.command = 'd';
        let event = { keyCode: 13 };
        terminal.handleCommand(event as KeyboardEvent);
        fixture.detectChanges();

        terminal.cd.detectChanges();
        expect(terminal.command).toEqual('');
        const commandEl = fixture.debugElement.query(By.css('.p-terminal-command'));
        const responseEl = fixture.debugElement.query(By.css('.p-terminal-content')).queryAll(By.css('div'))[1];
        expect(commandEl.nativeElement.textContent).toEqual('d');
        expect(responseEl.nativeElement.textContent).toEqual('Command succeed');
    });

    it('should not handle command', () => {
        fixture.detectChanges();

        terminal.command = 'dd';
        let event = { keyCode: 13 };
        terminal.handleCommand(event as KeyboardEvent);
        fixture.detectChanges();

        terminal.cd.detectChanges();
        expect(terminal.command).toEqual('');
        const commandEl = fixture.debugElement.query(By.css('.p-terminal-command'));
        const responseEl = fixture.debugElement.query(By.css('.p-terminal-content')).queryAll(By.css('div'))[1];
        expect(commandEl.nativeElement.textContent).toEqual('dd');
        expect(responseEl.nativeElement.textContent).toEqual('Unknown command: dd');
    });
});


text:
<?php

namespace Magento\PageCache\Model\App\FrontController;

use Magento\Framework\App\FrontController;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;

class MessageBox
{
    /**
     * Name of cookie that holds private content version
     */
    const COOKIE_NAME = 'message_box_display';

    /**
     * Ten years cookie period
     */
    const COOKIE_PERIOD = 315360000;

    /**
     * Cookie manager
     *
     * @var \Magento\Framework\Stdlib\CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * Cookie metadata factory
     *
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    protected $cookieMetadataFactory;

    /**
     * Request
     *
     * @var \Magento\Framework\App\Request\Http
     */
    protected $request;

    /**
     * Scope config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $config;

    /**
     * Message manager
     *
     * @var \Magento\Framework\Message\Manager
     */
    protected $messageManager;

    /**
     * @param CookieManagerInterface $cookieManager
     * @param CookieMetadataFactory $cookieMetadataFactory
     * @param \Magento\Framework\App\Request\Http $request
     * @param \Magento\PageCache\Model\Config $config
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     */
    public function __construct(
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory,
        \Magento\Framework\App\Request\Http $request,
        \Magento\PageCache\Model\Config $config,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->request = $request;
        $this->config = $config;
        $this->messageManager = $messageManager;
    }

    /**
     * Set Cookie for msg box when it displays first
     *
     * @param FrontController $subject
     * @param \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface $result
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterDispatch(FrontController $subject, $result)
    {
        if ($this->request->isPost() && $this->messageManager->hasMessages()) {
            $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata()
                ->setDuration(self::COOKIE_PERIOD)
                ->setPath('/')
                ->setHttpOnly(false);
            $this->cookieManager->setPublicCookie(self::COOKIE_NAME, 1, $publicCookieMetadata);
        }
        return $result;
    }
}


text:
// Copyright 2014 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.

package org.chromium.sync;

/**
 * Contains all of the command line switches that are specific to the sync/
 * portion of Chromium on Android.
 */
public abstract class SyncSwitches {
    // It's currently necessary for people wanting to try out the Push API to disable Chrome Sync's
    // use of GCM (as Android only grants a single registration ID, and they can't both use it).
    // Accordingly, this switch lets you disable Sync's ability to receive GCM messages in order to
    // make it possible to try out the Push API. Don't use this in production!
    // TODO(johnme): Remove this command line switch once disabling sync is no longer necessary.
    public static final String DISABLE_SYNC_GCM_IN_ORDER_TO_TRY_PUSH_API =
            "disable-sync-gcm-in-order-to-try-push-api";

    // Prevent instantiation.
    private SyncSwitches() {}
}