text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

        <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
        <link rel="stylesheet" type="text/css" href="css/flat-ui.css" />
        <link rel="stylesheet" href="css/pp-icons.css">
        <link rel="stylesheet" type="text/css" href="css/application.css" />

        <title>PushPress</title>

    	Toggle Debug View

Hello

Check-In

Connection Unavailable.

							<button id="check-connection" class="btn btn-primary">Try again</button>

		       		<form class="form" id="login-form">

Login

			        		<input type="text" name="email" id="email" class="col-xs-12 form-control" placeholder="email address" >

			        		<input type="password" name="password" id="password" class="col-xs-12 form-control" placeholder="password" >

	            				<input type="checkbox" value="production" name="environment" id="environment" data-toggle="checkbox">
	            				Live Server

			        	<button type="submit" class="col-xs-5 col-sm-3 btn btn-primary single-use cta"> Login</button>
		        	</form>

Select Client


text:
class RefTraceResults {

     public:

     RefTraceResults( ) : penalty(0), gaps(0), meta_events(0) { }
     RefTraceResults( const int penalty, const int gaps, const int meta_events )
          : penalty(penalty), gaps(gaps), meta_events(meta_events) { }

     int penalty;
     int gaps;
     int meta_events;

};

class RefTraceHeuristics {

     public:

     RefTraceHeuristics( ) : max_offset_diff(10), max_error_rate(0.05),
          offset_add(1), max_twiddle(3), min_group_frac(0.75),
          min_group_save(1000000000) { }

     RefTraceHeuristics( const int max_offset_diffx, const double max_error_ratex,
          const int offset_addx, const int max_twiddlex,
          const double min_group_fracx, const int min_group_savex )
          : max_offset_diff(max_offset_diffx), max_error_rate(max_error_ratex),
          offset_add(offset_addx), max_twiddle(max_twiddlex),
          min_group_frac(min_group_fracx), min_group_save(min_group_savex)
     {    RefTraceHeuristics rth;
          if ( max_offset_diff < 0 ) max_offset_diff = rth.max_offset_diff;
          if ( max_error_rate < 0 ) max_error_rate = rth.max_error_rate;
          if ( offset_add < 0 ) offset_add = rth.offset_add;
          if ( max_twiddle < 0 ) max_twiddle = rth.max_twiddle;
          if ( min_group_frac < 0 ) min_group_frac = rth.min_group_frac;
          if ( min_group_save < 0 ) min_group_save = rth.min_group_save;    }

     int max_offset_diff;
     double max_error_rate;
     int offset_add;
     int max_twiddle;
     double min_group_frac;
     int min_group_save;

};

// BEST_GLOBAL_OUT: if provided, name of fastb file to write two basevectors to:
// first the best assembly sequence, then the best reference sequence.

class SupportedHyperBasevector;
class ReadOriginTracker;
class ref_data;
class RefTraceControl;
class long_logging;

RefTraceResults RefTrace( const ref_data& ref,
     const HyperBasevector& hb, const vec<int>& inv,
     const int verbosity, const long_logging& logc,
     ostream& out, RefTraceHeuristics rth,
     const String& BEST_GLOBAL_OUT, const Bool fix_bug);

RefTraceResults RefTraceAndCallVaraint( const ref_data& ref,
     const HyperBasevector& hb, const vec<int>& inv,
     const int verbosity, const long_logging& logc,
     ostream& out, ostream& callsOut, RefTraceHeuristics rth,
     const String& BEST_GLOBAL_OUT, const Bool fix_bug,
     const RefTraceControl& ref_trace_control,
     const ReadOriginTracker* p_read_tracker = NULL);

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.butterfly.vv.db;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "provice")
public class Province {
	@DatabaseField
	long _id;
	@DatabaseField(id = true)
	String pcode;
	@DatabaseField
	String pname;

	public long get_id() {
		return _id;
	}
	public void set_id(long _id) {
		this._id = _id;
	}
	public String getPcode() {
		return pcode;
	}
	public void setPcode(String pcode) {
		this.pcode = pcode;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	@Override
	public String toString() {
		return "Province [_id=" + _id + ", pcode=" + pcode + ", pname=" + pname
				+ "]";
	}
}


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

#include <string>
#include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h"

#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_context_menu_model.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/scripting_permissions_modifier.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
#include "chrome/browser/ui/views/extensions/extensions_request_access_button.h"
#include "chrome/browser/ui/views/extensions/extensions_toolbar_button.h"
#include "chrome/browser/ui/views/extensions/extensions_toolbar_interactive_uitest.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_host_test_helper.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/uninstall_reason.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_features.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/test_extension_dir.h"
#include "net/dns/mock_host_resolver.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/bubble/bubble_dialog_model_host.h"
#include "ui/views/layout/animating_layout_manager_test_util.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"

namespace {

constexpr char kInjectionSucceededMessage[] = "injection succeeded";

class BlockedActionWaiter
    : public extensions::ExtensionActionRunner::TestObserver {
 public:
  explicit BlockedActionWaiter(extensions::ExtensionActionRunner* runner)
      : runner_(runner), run_loop_(std::make_unique<base::RunLoop>()) {
    runner_->set_observer_for_testing(this);
  }
  BlockedActionWaiter(const BlockedActionWaiter&) = delete;
  BlockedActionWaiter& operator=(const BlockedActionWaiter&) = delete;
  ~BlockedActionWaiter() { runner_->set_observer_for_testing(nullptr); }

  void WaitAndReset() {
    run_loop_->Run();
    run_loop_ = std::make_unique<base::RunLoop>();
  }

 private:
  // ExtensionActionRunner::TestObserver:
  void OnBlockedActionAdded() override { run_loop_->Quit(); }

  raw_ptr<extensions::ExtensionActionRunner> runner_;
  std::unique_ptr<base::RunLoop> run_loop_;
};

views::Widget* CreateBubble(views::View* anchor_point) {
  std::unique_ptr<ui::DialogModel> dialog_model =
      ui::DialogModel::Builder().SetTitle(u"Title").Build();
  auto bubble = std::make_unique<views::BubbleDialogModelHost>(
      std::move(dialog_model), anchor_point, views::BubbleBorder::TOP_RIGHT);

  return views::BubbleDialogDelegate::CreateBubble(std::move(bubble));
}

}  // namespace

using SiteAccess = extensions::SitePermissionsHelper::SiteAccess;
using SiteInteraction = extensions::SitePermissionsHelper::SiteInteraction;

class ExtensionsToolbarContainerUITest : public ExtensionsToolbarUITest {
 public:
  enum class ExtensionRemovalMethod {
    kDisable,
    kUninstall,
    kBlocklist,
    kTerminate,
  };

  ExtensionsToolbarContainerUITest() = default;
  ExtensionsToolbarContainerUITest(const ExtensionsToolbarContainerUITest&) =
      delete;
  ExtensionsToolbarContainerUITest& operator=(
      const ExtensionsToolbarContainerUITest&) = delete;
  ~ExtensionsToolbarContainerUITest() override = default;

  void SetUpOnMainThread() override {
    ExtensionsToolbarUITest::SetUpOnMainThread();
    // InProcessBrowserTest will create the browser and request the hosting
    // NativeWidget's window activate. However, the NativeWidget's window can
    // resolve this activation request asynchronously. Showing the extension
    // popup is also done asynchronously.
    // Extension popups will close their bubble Widget if the hosting window
    // recieves activation. If we do not wait for the activation first this
    // results in a race condition whereby if the bubble is created first it is
    // immediately closed when the activation event is propagated. Thus ensure
    // we first wait for the browser window activation here.
    ui_test_utils::BrowserActivationWaiter(browser()).WaitForActivation();
  }

  void ClickOnAction(ToolbarActionView* action) {
    ui::MouseEvent click_down_event(ui::ET_MOUSE_PRESSED, gfx::Point(),
                                    gfx::Point(), base::TimeTicks(),
                                    ui::EF_LEFT_MOUSE_BUTTON, 0);
    ui::MouseEvent click_up_event(ui::ET_MOUSE_RELEASED, gfx::Point(),
                                  gfx::Point(), base::TimeTicks(),
                                  ui::EF_LEFT_MOUSE_BUTTON, 0);
    action->OnMouseEvent(&click_down_event);
    action->OnMouseEvent(&click_up_event);
  }

  void ShowUi(const std::string& name) override { NOTREACHED(); }

  void RemoveExtension(ExtensionRemovalMethod method,
                       const std::string& extension_id) {
    extensions::ExtensionService* const extension_service =
        extensions::ExtensionSystem::Get(browser()->profile())
            ->extension_service();
    switch (method) {
      case ExtensionRemovalMethod::kDisable:
        extension_service->DisableExtension(
            extension_id, extensions::disable_reason::DISABLE_USER_ACTION);
        break;
      case ExtensionRemovalMethod::kUninstall:
        extension_service->UninstallExtension(
            extension_id, extensions::UNINSTALL_REASON_FOR_TESTING, nullptr);
        break;
      case ExtensionRemovalMethod::kBlocklist:
        extension_service->BlocklistExtensionForTest(extension_id);
        break;
      case ExtensionRemovalMethod::kTerminate:
        extension_service->TerminateExtension(extension_id);
        break;
    }

    // Removing an extension can result in the container changing visibility.
    // Allow it to finish laying out appropriately.
    auto* container = GetExtensionsToolbarContainer();
    container->GetWidget()->LayoutRootViewIfNecessary();
  }

  void VerifyContainerVisibility(ExtensionRemovalMethod method,
                                 bool expected_visibility) {
    // An empty container should not be shown.
    EXPECT_FALSE(GetExtensionsToolbarContainer()->GetVisible());

    // Loading the first extension should show the button (and container).
    LoadTestExtension("extensions/uitest/long_name");
    EXPECT_TRUE(GetExtensionsToolbarContainer()->IsDrawn());

    // Add another extension so we can make sure that removing some don't change
    // the visibility.
    LoadTestExtension("extensions/uitest/window_open");

    // Remove 1/2 extensions, should still be drawn.
    RemoveExtension(method, extensions()[0]->id());
    EXPECT_TRUE(GetExtensionsToolbarContainer()->IsDrawn());

    // Removing the last extension. All actions now have the same state.
    RemoveExtension(method, extensions()[1]->id());

    // Container should remain visible during the removal animation.
    EXPECT_TRUE(GetExtensionsToolbarContainer()->IsDrawn());
    views::test::WaitForAnimatingLayoutManager(GetExtensionsToolbarContainer());
    EXPECT_EQ(expected_visibility, GetExtensionsToolbarContainer()->IsDrawn());
  }
};

// TODO(devlin): There are probably some tests from
// ExtensionsMenuViewInteractiveUITest that should move here (if they test the
// toolbar container more than the menu).

// Tests that invocation metrics are properly recorded when triggering
// extensions from the toolbar.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest, InvocationMetrics) {
  base::HistogramTester histogram_tester;
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/uitest/extension_with_action_and_command");

  EXPECT_EQ(1u, GetToolbarActionViews().size());
  EXPECT_EQ(0u, GetVisibleToolbarActionViews().size());

  ToolbarActionsModel* const model = ToolbarActionsModel::Get(profile());
  model->SetActionVisibility(extension->id(), true);

  auto* container = GetExtensionsToolbarContainer();
  container->GetWidget()->LayoutRootViewIfNecessary();

  ASSERT_EQ(1u, GetVisibleToolbarActionViews().size());
  ToolbarActionView* const action = GetVisibleToolbarActionViews()[0];

  constexpr char kHistogramName[] = "Extensions.Toolbar.InvocationSource";
  histogram_tester.ExpectTotalCount(kHistogramName, 0);

  // Trigger the extension by clicking on it.
  ClickOnAction(action);

  histogram_tester.ExpectTotalCount(kHistogramName, 1);
  histogram_tester.ExpectBucketCount(
      kHistogramName,
      ToolbarActionViewController::InvocationSource::kToolbarButton, 1);
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       InvisibleWithoutExtension_Disable) {
  VerifyContainerVisibility(ExtensionRemovalMethod::kDisable, false);
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       InvisibleWithoutExtension_Uninstall) {
  VerifyContainerVisibility(ExtensionRemovalMethod::kUninstall, false);
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       InvisibleWithoutExtension_Blocklist) {
  VerifyContainerVisibility(ExtensionRemovalMethod::kBlocklist, false);
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       InvisibleWithoutExtension_Terminate) {
  // TODO(pbos): Keep the container visible when extensions are terminated
  // (crash). This lets users find and restart them. Then update this test
  // expectation to be kept visible by terminated extensions. Also update the
  // test name to reflect that the container should be visible with only
  // terminated extensions.
  VerifyContainerVisibility(ExtensionRemovalMethod::kTerminate, false);
}

// Tests that clicking on a second extension action will close a first if its
// popup was open.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       ClickingOnASecondActionClosesTheFirst) {
  std::vector<std::unique_ptr<extensions::TestExtensionDir>> test_dirs;
  auto load_extension = [&](const char* extension_name) {
    constexpr char kManifestTemplate[] =
        R"({
             "name": "%s",
             "manifest_version": 3,
             "action": { "default_popup": "popup.html" },
             "version": "0.1"
           })";
    constexpr char kPopupHtml[] =
        R"(<html><script src="popup.js"></script></html>)";
    constexpr char kPopupJsTemplate[] =
        R"(chrome.test.sendMessage('%s popup opened');)";

    auto test_dir = std::make_unique<extensions::TestExtensionDir>();
    test_dir->WriteManifest(
        base::StringPrintf(kManifestTemplate, extension_name));
    test_dir->WriteFile(FILE_PATH_LITERAL("popup.html"), kPopupHtml);
    test_dir->WriteFile(FILE_PATH_LITERAL("popup.js"),
                        base::StringPrintf(kPopupJsTemplate, extension_name));
    scoped_refptr<const extensions::Extension> extension =
        extensions::ChromeTestExtensionLoader(browser()->profile())
            .LoadExtension(test_dir->UnpackedPath());
    test_dirs.push_back(std::move(test_dir));
    return extension;
  };

  // Load up a couple extensions with actions in the toolbar.
  scoped_refptr<const extensions::Extension> alpha = load_extension("alpha");
  ASSERT_TRUE(alpha);
  scoped_refptr<const extensions::Extension> beta = load_extension("beta");
  ASSERT_TRUE(beta);

  // Pin each to the toolbar, and grab their views.
  ToolbarActionsModel* const model = ToolbarActionsModel::Get(profile());
  model->SetActionVisibility(alpha->id(), true);
  model->SetActionVisibility(beta->id(), true);

  auto* container = GetExtensionsToolbarContainer();
  container->GetWidget()->LayoutRootViewIfNecessary();

  auto toolbar_views = GetVisibleToolbarActionViews();
  ASSERT_EQ(2u, toolbar_views.size());

  ToolbarActionView* const alpha_action = toolbar_views[0];
  EXPECT_EQ(alpha->id(), alpha_action->view_controller()->GetId());
  ToolbarActionView* const beta_action = toolbar_views[1];
  EXPECT_EQ(beta->id(), beta_action->view_controller()->GetId());

  extensions::ProcessManager* const process_manager =
      extensions::ProcessManager::Get(profile());

  // To start, neither extensions should have any render frames (which here
  // equates to no open popus).
  EXPECT_EQ(
      0u, process_manager->GetRenderFrameHostsForExtension(alpha->id()).size());
  EXPECT_EQ(
      0u, process_manager->GetRenderFrameHostsForExtension(beta->id()).size());

  {
    // Click on Alpha and wait for it to open the popup.
    ExtensionTestMessageListener listener("alpha popup opened");
    ClickOnAction(alpha_action);
    EXPECT_TRUE(listener.WaitUntilSatisfied());
  }

  // Verify that Alpha (and only Alpha) has an active frame (i.e., popup).
  ASSERT_EQ(
      1u, process_manager->GetRenderFrameHostsForExtension(alpha->id()).size());
  EXPECT_EQ(
      0u, process_manager->GetRenderFrameHostsForExtension(beta->id()).size());
  // And confirm this matches the underlying controller's state.
  EXPECT_TRUE(alpha_action->view_controller()->IsShowingPopup());
  EXPECT_FALSE(beta_action->view_controller()->IsShowingPopup());

  {
    // Click on Beta. This should result in Beta's popup opening and Alpha's
    // closing.
    content::RenderFrameHost* const popup_frame =
        *process_manager->GetRenderFrameHostsForExtension(alpha->id()).begin();
    content::WebContentsDestroyedWatcher popup_destroyed(
        content::WebContents::FromRenderFrameHost(popup_frame));
    ExtensionTestMessageListener listener("beta popup opened");
    ClickOnAction(beta_action);
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    popup_destroyed.Wait();
  }

  // Beta (and only Beta) should have an active popup.
  EXPECT_EQ(
      0u, process_manager->GetRenderFrameHostsForExtension(alpha->id()).size());
  ASSERT_EQ(
      1u, process_manager->GetRenderFrameHostsForExtension(beta->id()).size());
  EXPECT_FALSE(alpha_action->view_controller()->IsShowingPopup());
  EXPECT_TRUE(beta_action->view_controller()->IsShowingPopup());
}

// Tests that clicking an extension toolbar icon when the popup is open closes
// the popup.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       DoubleClickToolbarActionToClose) {
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/ui/browser_action_popup");
  ASSERT_TRUE(extension);

  ToolbarActionsModel* const toolbar_model =
      ToolbarActionsModel::Get(profile());
  toolbar_model->SetActionVisibility(extension->id(), true);
  EXPECT_TRUE(toolbar_model->IsActionPinned(extension->id()));

  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();
  views::test::WaitForAnimatingLayoutManager(container);

  ToolbarActionViewController* const view_controller =
      container->GetActionForId(extension->id());
  EXPECT_TRUE(container->IsActionVisibleOnToolbar(view_controller));
  ToolbarActionView* const action_view =
      container->GetViewForId(extension->id());
  EXPECT_TRUE(action_view->GetVisible());

  ExtensionTestMessageListener listener("Popup opened");
  EXPECT_TRUE(ui_test_utils::SendMouseMoveSync(
      ui_test_utils::GetCenterInScreenCoordinates(action_view)));
  EXPECT_TRUE(ui_controls::SendMouseClick(ui_controls::LEFT));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  EXPECT_TRUE(view_controller->IsShowingPopup());
  EXPECT_EQ(view_controller, container->popup_owner_for_testing());

  extensions::ExtensionHostTestHelper host_helper(profile(), extension->id());
  EXPECT_TRUE(
      ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::DOWN));
  host_helper.WaitForHostDestroyed();

  EXPECT_FALSE(view_controller->IsShowingPopup());
  EXPECT_EQ(nullptr, container->popup_owner_for_testing());

  // Releasing the mouse shouldn't result in the popup being shown again.
  EXPECT_TRUE(
      ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::UP));
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(view_controller->IsShowingPopup());
  EXPECT_EQ(nullptr, container->popup_owner_for_testing());
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       ShowWidgetForExtension_Pinned) {
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();
  ToolbarActionViewController* const action =
      container->GetActionForId(extension->id());

  ToolbarActionsModel* const model = ToolbarActionsModel::Get(profile());
  model->SetActionVisibility(extension->id(), true);
  container->GetWidget()->LayoutRootViewIfNecessary();

  auto visible_actions = GetVisibleToolbarActionViews();
  ASSERT_EQ(1u, visible_actions.size());
  EXPECT_EQ(extension->id(), visible_actions[0]->view_controller()->GetId());

  views::Widget* bubble = CreateBubble(container->GetExtensionsButton());
  container->ShowWidgetForExtension(bubble, extension->id());

  views::Widget* const bubble_widget =
      container->GetAnchoredWidgetForExtensionForTesting(extension->id());
  ASSERT_TRUE(bubble_widget);
  views::test::WidgetVisibleWaiter(bubble_widget).Wait();

  views::test::WidgetDestroyedWaiter destroyed_waiter(bubble_widget);
  bubble_widget->CloseWithReason(
      views::Widget::ClosedReason::kCloseButtonClicked);
  destroyed_waiter.Wait();

  EXPECT_TRUE(container->IsActionVisibleOnToolbar(action));
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       ShowWidgetForExtension_Unpinned) {
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();
  ToolbarActionViewController* const action =
      container->GetActionForId(extension->id());

  EXPECT_EQ(0u, GetVisibleToolbarActionViews().size());

  views::Widget* bubble = CreateBubble(container->GetExtensionsButton());
  container->ShowWidgetForExtension(bubble, extension->id());

  views::Widget* const bubble_widget =
      container->GetAnchoredWidgetForExtensionForTesting(extension->id());
  ASSERT_TRUE(bubble_widget);
  views::test::WidgetVisibleWaiter(bubble_widget).Wait();

  EXPECT_TRUE(container->IsActionVisibleOnToolbar(action));

  views::test::WidgetDestroyedWaiter destroyed_waiter(bubble_widget);
  bubble_widget->CloseWithReason(
      views::Widget::ClosedReason::kCloseButtonClicked);
  destroyed_waiter.Wait();

  EXPECT_FALSE(container->IsActionVisibleOnToolbar(action));
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       ShowWidgetForExtension_NoAction) {
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  // Disable the extension. Disabled extensions don't display in the toolbar.
  extensions::ExtensionService* const extension_service =
      extensions::ExtensionSystem::Get(profile())->extension_service();
  extension_service->DisableExtension(
      extension->id(), extensions::disable_reason::DISABLE_USER_ACTION);

  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();
  EXPECT_FALSE(container->GetActionForId(extension->id()));

  EXPECT_EQ(0u, GetVisibleToolbarActionViews().size());

  views::Widget* bubble = CreateBubble(container->GetExtensionsButton());
  container->ShowWidgetForExtension(bubble, extension->id());

  views::Widget* const bubble_widget =
      container->GetAnchoredWidgetForExtensionForTesting(extension->id());
  ASSERT_TRUE(bubble_widget);
  views::test::WidgetVisibleWaiter(bubble_widget).Wait();

  EXPECT_EQ(0u, GetVisibleToolbarActionViews().size());

  views::test::WidgetDestroyedWaiter destroyed_waiter(bubble_widget);
  bubble_widget->CloseWithReason(
      views::Widget::ClosedReason::kCloseButtonClicked);
  destroyed_waiter.Wait();
}

IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       UninstallExtensionWithActivelyShownWidget) {
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();

  ToolbarActionsModel* const model = ToolbarActionsModel::Get(profile());
  model->SetActionVisibility(extension->id(), true);
  container->GetWidget()->LayoutRootViewIfNecessary();

  auto visible_actions = GetVisibleToolbarActionViews();
  ASSERT_EQ(1u, visible_actions.size());
  EXPECT_EQ(extension->id(), visible_actions[0]->view_controller()->GetId());

  views::Widget* bubble = CreateBubble(container->GetExtensionsButton());
  container->ShowWidgetForExtension(bubble, extension->id());

  views::Widget* const bubble_widget =
      container->GetAnchoredWidgetForExtensionForTesting(extension->id());
  ASSERT_TRUE(bubble_widget);
  views::test::WidgetVisibleWaiter(bubble_widget).Wait();

  extensions::ExtensionService* const extension_service =
      extensions::ExtensionSystem::Get(profile())->extension_service();
  extension_service->UninstallExtension(
      extension->id(), extensions::UNINSTALL_REASON_FOR_TESTING, nullptr);

  EXPECT_EQ(0u, GetVisibleToolbarActionViews().size());
  EXPECT_FALSE(container->GetActionForId(extension->id()));

  // TODO(devlin): When the extension is removed, we don't currently remove any
  // widgets associated with it. This test ensures we don't crash (yay!), but we
  // should very likely close the bubble as well. I wouldn't be surprised if
  // some bubble handlers don't expect the extension to be gone.
  views::test::WidgetDestroyedWaiter destroyed_waiter(bubble_widget);
  bubble_widget->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
  destroyed_waiter.Wait();
}

// Verifies that dragging extension icons is disabled in incognito windows.
// https://crbug.com/1203833.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       IncognitoDraggingIsDisabled) {
  // Load an extension, pin it, and enable it in incognito.
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  ToolbarActionsModel* const toolbar_model =
      ToolbarActionsModel::Get(profile());
  toolbar_model->SetActionVisibility(extension->id(), true);

  {
    extensions::TestExtensionRegistryObserver observer(
        extensions::ExtensionRegistry::Get(profile()), extension->id());
    extensions::util::SetIsIncognitoEnabled(extension->id(), profile(), true);
    ASSERT_TRUE(observer.WaitForExtensionLoaded());
  }

  Browser* incognito_browser = CreateIncognitoBrowser();

  views::test::WaitForAnimatingLayoutManager(GetExtensionsToolbarContainer());
  views::test::WaitForAnimatingLayoutManager(
      GetExtensionsToolbarContainerForBrowser(incognito_browser));

  // Verify the extension has a (visible) action for both the incognito and
  // on-the-record browser.
  std::vector<ToolbarActionView*> on_the_record_views = GetToolbarActionViews();
  ASSERT_EQ(1u, on_the_record_views.size());
  ToolbarActionView* on_the_record_view = on_the_record_views[0];
  EXPECT_EQ(extension->id(), on_the_record_view->view_controller()->GetId());
  EXPECT_TRUE(on_the_record_view->GetVisible());

  std::vector<ToolbarActionView*> incognito_views =
      GetToolbarActionViewsForBrowser(incognito_browser);
  ASSERT_EQ(1u, incognito_views.size());
  ToolbarActionView* incognito_view = incognito_views[0];
  EXPECT_EQ(extension->id(), incognito_view->view_controller()->GetId());
  EXPECT_TRUE(incognito_view->GetVisible());

  // Dragging should be enabled for the on-the-record view, but not the
  // incognito view.
  EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE,
            on_the_record_view->GetDragOperationsForTest(gfx::Point()));
  EXPECT_EQ(ui::DragDropTypes::DRAG_NONE,
            incognito_view->GetDragOperationsForTest(gfx::Point()));

  // The two views should have the same notifiable event. This is important to
  // test, since it can be dependent on draggability.
  EXPECT_EQ(on_the_record_view->button_controller()->notify_action(),
            incognito_view->button_controller()->notify_action());
}

// Tests unloading an extension while the action is being slid out prior to the
// popup being shown. Regression test for https://crbug.com/1345477.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerUITest,
                       UnloadingExtensionWhileAboutToShowPopup) {
  // Load an extension.
  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/simple_with_popup");
  ASSERT_TRUE(extension);

  // It should be unpinned.
  ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer();
  ToolbarActionViewController* const view_controller =
      container->GetActionForId(extension->id());
  EXPECT_FALSE(container->IsActionVisibleOnToolbar(view_controller));

  // Execute the action, which results in the extension sliding out while we
  // get ready to show the popup.
  view_controller->ExecuteUserAction(
      ToolbarActionViewController::InvocationSource::kMenuEntry);

  // Unload the extension (before the popup is ready). This results in the
  // toolbar action being removed. The pending popup will never be shown. This
  // shouldn't crash.
  RemoveExtension(ExtensionRemovalMethod::kDisable, extension->id());

  EXPECT_EQ(nullptr, container->GetActionForId(extension->id()));
}

namespace {

class IncognitoExtensionsToolbarContainerUITest
    : public ExtensionsToolbarContainerUITest {
 public:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionsToolbarContainerUITest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kIncognito);
  }
};

}  // namespace

// Tests that first loading an extension action in an incognito profile, then
// removing the incognito profile and using the extension action in a normal
// profile doesn't crash.
// Regression test for crbug.com/663726.
IN_PROC_BROWSER_TEST_F(IncognitoExtensionsToolbarContainerUITest,
                       TestExtensionFirstLoadedInIncognitoMode) {
  EXPECT_TRUE(browser()->profile()->IsOffTheRecord());

  scoped_refptr<const extensions::Extension> extension =
      LoadTestExtension("extensions/api_test/browser_action_with_icon",
                        /*allow_incognito=*/true);
  ASSERT_TRUE(extension);
  Browser* second_browser = CreateBrowser(profile()->GetOriginalProfile());
  EXPECT_FALSE(second_browser->profile()->IsOffTheRecord());

  CloseBrowserSynchronously(browser());

  std::vector<ToolbarActionView*> extension_views =
      GetToolbarActionViewsForBrowser(second_browser);
  ASSERT_EQ(1u, extension_views.size());

  gfx::ImageSkia icon = extension_views[0]->GetIconForTest();
  // Force the image to try and load a representation.
  icon.GetRepresentation(2.0);
}

class ExtensionsToolbarRuntimeHostPermissionsBrowserTest
    : public ExtensionsToolbarContainerUITest {
 public:
  enum class ContentScriptRunLocation {
    DOCUMENT_START,
    DOCUMENT_IDLE,
  };

  ExtensionsToolbarRuntimeHostPermissionsBrowserTest() = default;
  ExtensionsToolbarRuntimeHostPermissionsBrowserTest(
      const ExtensionsToolbarRuntimeHostPermissionsBrowserTest&) = delete;
  ExtensionsToolbarRuntimeHostPermissionsBrowserTest& operator=(
      const ExtensionsToolbarRuntimeHostPermissionsBrowserTest&) = delete;
  ~ExtensionsToolbarRuntimeHostPermissionsBrowserTest() override = default;

  void SetUpOnMainThread() override {
    ExtensionsToolbarContainerUITest::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void LoadAllUrlsExtension(ContentScriptRunLocation run_location) {
    std::string run_location_str;
    switch (run_location) {
      case ContentScriptRunLocation::DOCUMENT_START:
        run_location_str = "document_start";
        break;
      case ContentScriptRunLocation::DOCUMENT_IDLE:
        run_location_str = "document_idle";
        break;
    }
    extension_dir_.WriteManifest(base::StringPrintf(R"({
             "name": "All Urls Extension",
             "description": "Runs a content script everywhere",
             "manifest_version": 2,
             "version": "0.1",
             "content_scripts": [{
               "matches": ["<all_urls>"],
               "js": ["script.js"],
               "run_at": "%s"
             }]
           })",
                                                    run_location_str.c_str()));
    extension_dir_.WriteFile(
        FILE_PATH_LITERAL("script.js"),
        base::StringPrintf("chrome.test.sendMessage('%s');",
                           kInjectionSucceededMessage));

    extension_ = extensions::ChromeTestExtensionLoader(profile()).LoadExtension(
        extension_dir_.UnpackedPath());
    ASSERT_TRUE(extension_);
    AppendExtension(extension_);
    extensions::ScriptingPermissionsModifier(profile(), extension_)
        .SetWithholdHostPermissions(true);
  }

  const extensions::Extension* extension() const { return extension_.get(); }

  extensions::ExtensionContextMenuModel* GetExtensionContextMenu() {
    ToolbarActionViewController* const controller =
        GetExtensionsToolbarContainer()->GetActionForId(extension_->id());
    return static_cast<extensions::ExtensionContextMenuModel*>(
        controller->GetContextMenu(extensions::ExtensionContextMenuModel::
                                       ContextMenuSource::kToolbarAction));
  }

  std::u16string GetActionTooltip() {
    return GetExtensionsToolbarContainer()
        ->GetViewForId(extension_->id())
        ->GetTooltipText();
  }

 private:
  extensions::TestExtensionDir extension_dir_;
  scoped_refptr<const extensions::Extension> extension_;
};

// Tests page access modifications through the context menu which require a page
// refresh.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarRuntimeHostPermissionsBrowserTest,
                       ContextMenuPageAccess_RefreshRequired) {
  LoadAllUrlsExtension(ContentScriptRunLocation::DOCUMENT_START);
  std::u16string tooltip_wants_access = base::JoinString(
      {u"All Urls Extension",
       l10n_util::GetStringUTF16(IDS_EXTENSIONS_WANTS_ACCESS_TO_SITE)},
      u"\n");
  std::u16string tooltip_has_access = base::JoinString(
      {u"All Urls Extension",
       l10n_util::GetStringUTF16(IDS_EXTENSIONS_HAS_ACCESS_TO_SITE)},
      u"\n");

  ExtensionTestMessageListener injection_listener(kInjectionSucceededMessage);
  injection_listener.set_extension_id(extension()->id());

  GURL url = embedded_test_server()->GetURL("example.com", "/title1.html");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  extensions::ExtensionActionRunner* runner =
      extensions::ExtensionActionRunner::GetForWebContents(web_contents);
  BlockedActionWaiter blocked_action_waiter(runner);
  {
    content::TestNavigationObserver observer(web_contents);
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
    EXPECT_TRUE(observer.last_navigation_succeeded());
  }

  // Access to |url| should have been withheld.
  blocked_action_waiter.WaitAndReset();
  EXPECT_TRUE(runner->WantsToRun(extension()));
  extensions::PermissionsManager* permissions_manager =
      extensions::PermissionsManager::Get(profile());
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_wants_access, GetActionTooltip());
  EXPECT_FALSE(injection_listener.was_satisfied());

  extensions::ExtensionContextMenuModel* extension_menu =
      GetExtensionContextMenu();
  ASSERT_TRUE(extension_menu);

  // Allow the extension to run on this site. This should show a refresh page
  // bubble. Accept the bubble.
  {
    content::TestNavigationObserver observer(web_contents);
    runner->accept_bubble_for_testing(true);
    extension_menu->ExecuteCommand(
        extensions::ExtensionContextMenuModel::PAGE_ACCESS_RUN_ON_SITE,
        0 /* event_flags */);
    observer.WaitForNavigationFinished();
    EXPECT_TRUE(observer.last_navigation_succeeded());
  }

  // The extension should have injected and the extension should no longer want
  // to run.
  ASSERT_TRUE(injection_listener.WaitUntilSatisfied());
  injection_listener.Reset();
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_has_access, GetActionTooltip());
  EXPECT_FALSE(runner->WantsToRun(extension()));

  // Now navigate to a different host. The extension should have blocked
  // actions.
  {
    url = embedded_test_server()->GetURL("abc.com", "/title1.html");
    content::TestNavigationObserver observer(web_contents);
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
    EXPECT_TRUE(observer.last_navigation_succeeded());
  }
  blocked_action_waiter.WaitAndReset();
  EXPECT_TRUE(runner->WantsToRun(extension()));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_wants_access, GetActionTooltip());
  EXPECT_FALSE(injection_listener.was_satisfied());

  // Allow the extension to run on all sites this time. This should again show a
  // refresh bubble. Dismiss it.
  runner->accept_bubble_for_testing(false);
  extension_menu->ExecuteCommand(
      extensions::ExtensionContextMenuModel::PAGE_ACCESS_RUN_ON_ALL_SITES,
      0 /* event_flags */);

  // Permissions to the extension shouldn't have been granted, and the extension
  // should still be in wants-to-run state.
  EXPECT_TRUE(runner->WantsToRun(extension()));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_wants_access, GetActionTooltip());
  EXPECT_FALSE(injection_listener.was_satisfied());
}

// Tests page access modifications through the context menu which don't require
// a page refresh.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarRuntimeHostPermissionsBrowserTest,
                       ContextMenuPageAccess_RefreshNotRequired) {
  LoadAllUrlsExtension(ContentScriptRunLocation::DOCUMENT_IDLE);
  std::u16string tooltip_wants_access = base::JoinString(
      {u"All Urls Extension",
       l10n_util::GetStringUTF16(IDS_EXTENSIONS_WANTS_ACCESS_TO_SITE)},
      u"\n");
  std::u16string tooltip_has_access = base::JoinString(
      {u"All Urls Extension",
       l10n_util::GetStringUTF16(IDS_EXTENSIONS_HAS_ACCESS_TO_SITE)},
      u"\n");

  ExtensionTestMessageListener injection_listener(kInjectionSucceededMessage);
  injection_listener.set_extension_id(extension()->id());

  GURL url = embedded_test_server()->GetURL("example.com", "/title1.html");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  extensions::ExtensionActionRunner* runner =
      extensions::ExtensionActionRunner::GetForWebContents(web_contents);
  BlockedActionWaiter blocked_action_waiter(runner);
  {
    content::TestNavigationObserver observer(web_contents);
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
    EXPECT_TRUE(observer.last_navigation_succeeded());
  }

  // Access to |url| should have been withheld.
  blocked_action_waiter.WaitAndReset();
  EXPECT_TRUE(runner->WantsToRun(extension()));
  extensions::PermissionsManager* permissions_manager =
      extensions::PermissionsManager::Get(profile());
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_wants_access, GetActionTooltip());
  EXPECT_FALSE(injection_listener.was_satisfied());

  extensions::ExtensionContextMenuModel* extension_menu =
      GetExtensionContextMenu();
  ASSERT_TRUE(extension_menu);

  // Allow the extension to run on this site. Since the blocked actions don't
  // require a refresh, the permission should be granted and the page actions
  // should run.
  extension_menu->ExecuteCommand(
      extensions::ExtensionContextMenuModel::PAGE_ACCESS_RUN_ON_SITE,
      0 /* event_flags */);
  ASSERT_TRUE(injection_listener.WaitUntilSatisfied());
  EXPECT_FALSE(runner->WantsToRun(extension()));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension(), url));
  EXPECT_EQ(tooltip_has_access, GetActionTooltip());
}

class ExtensionsToolbarContainerFeatureUITest
    : public ExtensionsToolbarContainerUITest {
 public:
  ExtensionsToolbarContainerFeatureUITest() {
    scoped_feature_list_.InitAndEnableFeature(
        extensions_features::kExtensionsMenuAccessControl);
  }
  ExtensionsToolbarContainerFeatureUITest(
      const ExtensionsToolbarContainerFeatureUITest&) = delete;
  const ExtensionsToolbarContainerFeatureUITest& operator=(
      const ExtensionsToolbarContainerFeatureUITest&) = delete;
  ~ExtensionsToolbarContainerFeatureUITest() override = default;

  void SetUpOnMainThread() override {
    ExtensionsToolbarContainerUITest::SetUpOnMainThread();
    ASSERT_TRUE(embedded_test_server()->Start());
    web_contents_ = browser()->tab_strip_model()->GetActiveWebContents();
  }

  void NavigateToUrl(const GURL& url) {
    content::TestNavigationObserver observer(web_contents_);
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
    EXPECT_TRUE(observer.last_navigation_succeeded());
    WaitForAnimation();
  }

  ExtensionsRequestAccessButton* request_access_button() {
    return GetExtensionsToolbarContainer()
        ->GetExtensionsToolbarControls()
        ->request_access_button_for_testing();
  }
  content::WebContents* web_contents() { return web_contents_; }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;

  raw_ptr<content::WebContents> web_contents_ = nullptr;
};

// Tests that clicking the request access button grants one time access to the
// extensions listed which requires a page refresh.
IN_PROC_BROWSER_TEST_F(ExtensionsToolbarContainerFeatureUITest,
                       ClickingRequestAccessButtonRunsAction_RefreshRequired) {
  constexpr char kExtensionAName[] = "A Extension";
  constexpr char kExtensionBName[] = "B Extension";
  constexpr char kExtensionCName[] = "C Extension";
  auto extensionA = InstallExtensionWithHostPermissions(
      kExtensionAName, "<all_urls>",
      /*content_script_run_location=*/"document_start");
  auto extensionB = InstallExtensionWithHostPermissions(kExtensionBName,
                                                        "http://example.com/");
  auto extensionC =
      InstallExtensionWithHostPermissions(kExtensionCName, "<all_urls>");

  // Withheld site access for extensions A and B.
  extensions::ScriptingPermissionsModifier(profile(), extensionA)
      .SetWithholdHostPermissions(true);
  extensions::ScriptingPermissionsModifier(profile(), extensionB)
      .SetWithholdHostPermissions(true);

  // Navigate to a site where extensions A and B have withheld access.
  GURL url = embedded_test_server()->GetURL("example.com", "/title1.html");
  NavigateToUrl(url);

  // Verify request access button is visible because extensions A and B have
  // pending site interaction.
  extensions::SitePermissionsHelper permissions(browser()->profile());
  EXPECT_TRUE(request_access_button()->GetVisible());
  EXPECT_THAT(request_access_button()->GetExtensionsNamesForTesting(),
              testing::ElementsAre(kExtensionAName, kExtensionBName));

  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionA, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionB, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionC, url),
            SiteAccess::kOnAllSites);

  // Click the request access button to grant one-time access. A reload page
  // dialog will appear since extension A needs a page reload to run its action.
  auto* action_runner =
      extensions::ExtensionActionRunner::GetForWebContents(web_contents());
  action_runner->accept_bubble_for_testing(false);
  ClickButton(request_access_button());
  WaitForAnimation();

  // Site interaction should stay the same because dialog wasn't accepted.
  EXPECT_TRUE(request_access_button()->GetVisible());
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);

  // Click the request access button again, and this time accept the dialog and
  // wait for the page refresh.
  content::TestNavigationObserver observer(web_contents());
  extensions::ExtensionActionRunner::GetForWebContents(web_contents())
      ->accept_bubble_for_testing(true);
  ClickButton(request_access_button());
  observer.WaitForNavigationFinished();
  EXPECT_TRUE(observer.last_navigation_succeeded());
  WaitForAnimation();

  // Extension A and B should have active site interaction, since their actions
  // ran, but keep the same site access since this is a one-time access grant.
  // The request access button should be hidden.
  EXPECT_FALSE(request_access_button()->GetVisible());
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionA, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionB, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionC, url),
            SiteAccess::kOnAllSites);

  // Re-navigate to the same url. Refreshing the page doesn't remove the action,
  // thus we need to navigate to another page and then navigate back to the
  // original page.
  NavigateToUrl(embedded_test_server()->GetURL("other.com", "/title1.html"));
  NavigateToUrl(url);

  // Extension A and B should have pending access again and the request access
  // button should be visible.
  EXPECT_TRUE(request_access_button()->GetVisible());
  EXPECT_THAT(request_access_button()->GetExtensionsNamesForTesting(),
              testing::ElementsAre(kExtensionAName, kExtensionBName));
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
}

// Tests that clicking the request access button grants one time access to the
// extensions listed without needing a page refresh.
IN_PROC_BROWSER_TEST_F(
    ExtensionsToolbarContainerFeatureUITest,
    ClickingRequestAccessButtonRunsAction_RefreshNotRequired) {
  constexpr char kExtensionAName[] = "A Extension";
  constexpr char kExtensionBName[] = "B Extension";
  constexpr char kExtensionCName[] = "C Extension";
  auto extensionA = InstallExtensionWithHostPermissions(
      kExtensionAName, "<all_urls>", "document_idle");
  auto extensionB = InstallExtensionWithHostPermissions(kExtensionBName,
                                                        "http://example.com/");
  auto extensionC =
      InstallExtensionWithHostPermissions(kExtensionCName, "<all_urls>");

  // Withheld site access for extensions A and B.
  extensions::ScriptingPermissionsModifier(profile(), extensionA)
      .SetWithholdHostPermissions(true);
  extensions::ScriptingPermissionsModifier(profile(), extensionB)
      .SetWithholdHostPermissions(true);

  // Navigate to a site where extensions A and B have withheld access.
  GURL url = embedded_test_server()->GetURL("example.com", "/title1.html");
  NavigateToUrl(url);

  // Verify request access button is visible because extensions A and B have
  // pending site interaction.
  EXPECT_TRUE(request_access_button()->GetVisible());
  EXPECT_THAT(request_access_button()->GetExtensionsNamesForTesting(),
              testing::ElementsAre(kExtensionAName, kExtensionBName));
  extensions::SitePermissionsHelper permissions(browser()->profile());
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionA, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionB, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionC, url),
            SiteAccess::kOnAllSites);

  // Click the request access button to grant one-time access. Since no
  // extensions need page refresh to run their actions, it immediately grants
  // access.
  ClickButton(request_access_button());
  WaitForAnimation();

  // Extension A and B should have active site interaction, since their action
  // run, but keep the same site access since this is a one-time access grant.
  // The request access button should be hidden.
  EXPECT_FALSE(request_access_button()->GetVisible());
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionA, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionB, url), SiteAccess::kOnClick);
  EXPECT_EQ(permissions.GetSiteAccess(*extensionC, url),
            SiteAccess::kOnAllSites);

  // Re-navigate to the same url. Refreshing the page doesn't remove the action,
  // thus we need to navigate to another page and then navigate back to the
  // original page.
  NavigateToUrl(embedded_test_server()->GetURL("other.com", "/title1.html"));
  NavigateToUrl(url);

  // Extension A and B should have pending access again and the request access
  // button should be visible.
  EXPECT_TRUE(request_access_button()->GetVisible());
  EXPECT_THAT(request_access_button()->GetExtensionsNamesForTesting(),
              testing::ElementsAre(kExtensionAName, kExtensionBName));
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionA, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionB, web_contents()),
            SiteInteraction::kWithheld);
  EXPECT_EQ(permissions.GetSiteInteraction(*extensionC, web_contents()),
            SiteInteraction::kGranted);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Connect.Tech 2017 CFP</title>

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

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                Connect.Tech 2017

                Home

                About

                Speakers

                Schedule

                Sponsors

                Location

                Register

                2014 Connect.JS

                2015 Connect.JS

                2016 Connect.JS

CONNECT . TECH

THE SOUTHEAST'S PREMIERE

 FRONT-END CONFERENCE

                COBB GALLERIA • ATLANTA

                    September 20-22, 2017

                CALL FOR PAPERS (scroll down :)

 DEADLINE EXTENDED TO MAY 8!

The CONNECT.TECH / Connect.JS 2017 call for proposals is now open, and closes May 8.

Before submitting a talk, please review these guidelines.

The conference will be in Atlanta, GA on September 20-22.

                        Workshop day is September 20, main conference days are September 21, 22

Notifications for acceptance will go out on a rolling basis; submit early and often!

Rejection notices will go out on May 30 or earlier.

We look forward to reviewing your submissions!

PLEASE TAKE 30 SECONDS TO REVIEW THESE GUIDELINES!

Once you've signed up on the CFP site, click 'Create New Event'. Make sure you also mark your availability.

 Select the track accordingly in the CFP system:

Core JavaScript & Frameworks

Node.JS / Server-side JS

Web/HTML/CSS

AngularJS

React.JS

Mobile

Design & UI & UX

Native iOS

Native Android

Mobile frameworks, UX, Design, Tools, Testing

Presentations (lectures) are 50 mins + 5 min for questions. Break apart longer sessions into PARTS I, II, etc. Longer, deep dive sessions, are given priority.

As we are a low-cost community conference, we have limited resources for covering presenter travel. Please ask your company if they can cover your travel first. Please mark accordingly if need travel reimbursement (see below).

DO NOT CHANGE YOUR "COVER TRAVEL" SELECTION ONCE YOUR SESSION HAS BEEN ACCEPTED! WE GET A NOTIFICATION WHEN THIS FLAG HAS BEEN FLIPPED, AND WE WILL RE-EVALUATE YOUR ACCEPTANCE! If you need to change this flag, please email us first!

Please email hello@connect.tech if you have any questions.

While creating your profile, be sure to fill in these sections. Your photo will be taken from Twitter!

This CFP system calls a presentation/session an EVENT. Create a new one for each of your proposed talks.

Set Event Type to lecture. Be sure to pick the correct track also.

Finally, set your availability for presenting. We can not guarantee we will be able to fit your availability, but we'll do our best.

            Read the Connect.Tech Code Of Conduct Here

I've read everything and am ready to submit<input type='checkbox' onclick="showLink()"></input>

Click here submit a session!

Interested in Sponsoring?

Email us at hello@connect.tech!

Back to Connect.Tech 2017 Homepage

  hello@connect-js.com

Copyright © Connect.Tech 2015


text:
[![Stories in Ready](https://badge.waffle.io/schjan/Kurswahl.png)](http://waffle.io/schjan/Kurswahl)
Kurswahl
========

###Wofür?
Das primäre Ziel des Projektes _Kurswahl_ ist, Schulen das Einwahlverfahren für Nachmittagskurse ("AGs") zu vereinfachen.

###Lizenz
Copyright 2013 Jannis Schaefer and contributors

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.


text:
  Saint-Aubin-sur-Mer est
       un village
       situé dans le département de Seine-Maritime en Haute-Normandie. Elle comptait 267 habitants en 2008.

À proximité de Saint-Aubin-sur-Mer sont situées les communes de
Saint-Pierre-le-Vieux située à 4 km, 216 habitants,
Sainte-Marguerite-sur-Mer à 5 km, 509 habitants,
La Chapelle-sur-Dun à 3 km, 195 habitants,
Quiberville à 3 km, 506 habitants,
Longueil à 5 km, 541 habitants,
La Gaillarde à 5 km, 426 habitants,
 entre autres. De plus, Saint-Aubin-sur-Mer est située à seulement 15 km de Dieppe.

Le nombre d'habitations, à Saint-Aubin-sur-Mer, se décomposait en 2011 en zero appartements et 230 maisons soit
 un marché relativement équilibré.

Si vous pensez demenager à Saint-Aubin-sur-Mer, vous pourrez aisément trouver une maison à acheter.

La commune propose quelques  aménagements, elle dispose, entre autres, de un terrain de tennis.


text:
using System;

namespace Behaviors
{
	[AttributeUsage(AttributeTargets.All)]
	public class PreserveAttribute : Attribute
	{
		public bool AllMembers;
		public bool Conditional;

		public PreserveAttribute(bool allMembers, bool conditional)
		{
			AllMembers = allMembers;
			Conditional = conditional;
		}

		public PreserveAttribute()
		{
		}
	}
}


text:
package big

import "fmt"

const _RoundingMode_name = "ToNearestEvenToNearestAwayToZeroAwayFromZeroToNegativeInfToPositiveInf"

var _RoundingMode_index = [...]uint8{0, 13, 26, 32, 44, 57, 70}

func (i RoundingMode) String() string {
	if i+1 >= RoundingMode(len(_RoundingMode_index)) {
		return fmt.Sprintf("RoundingMode(%d)", i)
	}
	return _RoundingMode_name[_RoundingMode_index[i]:_RoundingMode_index[i+1]]
}


text:
<?php

namespace Schoolcontact\FormationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use Schoolcontact\FormationBundle\Entity\Departement;
use Schoolcontact\FormationBundle\Entity\Diplome;
use Schoolcontact\FormationBundle\Entity\Ecole;
use Schoolcontact\FormationBundle\Entity\Formation;
use Schoolcontact\FormationBundle\Entity\Region;
use Schoolcontact\FormationBundle\Entity\Ville;
use Schoolcontact\UserBundle\Entity\Domaine;
use Schoolcontact\UserBundle\Entity\User;

use Schoolcontact\FormationBundle\Form\AddEcoleType;
use Schoolcontact\FormationBundle\Form\AddUsersType;
use Schoolcontact\FormationBundle\Form\AddFormationType;

class DomaineController extends Controller
{

}


text:
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}

import com.thesamet.proto.e2e.repeatables.RepeatablesTest
import com.thesamet.proto.e2e.repeatables.RepeatablesTest.Nested
import scalapb.GeneratedMessage
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest._
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class JavaSerializationSpec extends FlatSpec with ScalaCheckDrivenPropertyChecks with MustMatchers {

  val nestedGen =
    Arbitrary.arbitrary[Option[Int]].map(s => Nested(nestedField = s))

  val oneEnum = Gen.choose(0, 1).map(i => RepeatablesTest.Enum.fromValue(i))

  val repGen = for {
    strings <- Gen.listOf(Arbitrary.arbitrary[String])
    ints <- Gen.listOf(Arbitrary.arbitrary[Int])
    doubles <- Gen.listOf(Arbitrary.arbitrary[Double])
    nesteds <- Gen.listOf(nestedGen)
    longs <- Gen.listOf(Arbitrary.arbitrary[Long])
    enums <- Gen.listOf(oneEnum)
  } yield RepeatablesTest(
    strings = strings, ints = ints, doubles = doubles,
    nesteds = nesteds, packedLongs = longs, enums = enums
  )

  def checkJavaSerialization[T <: GeneratedMessage](a: T) = {
    val baos = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(baos)

    val inputA = a.companion.parseFrom(a.toByteArray)

    oos.writeObject(inputA)
    oos.close()

    val ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
    val b = ois.readObject().asInstanceOf[T]
    val abytes = a.toByteArray
    val bbytes = b.toByteArray

    abytes mustBe bbytes
  }

  "a message" should "invert toJson (single)" in {
    val rep = RepeatablesTest(strings=Seq("s1", "s2"), ints=Seq(14, 19), doubles=Seq(3.14, 2.17), nesteds=Seq(Nested()))
    checkJavaSerialization(rep)
  }

  "fromJson" should "invert toJson" in {
    forAll(repGen) {
      rep => checkJavaSerialization(rep)
    }
  }
}


text:
package io.cdep.cdep.yml;

import io.cdep.cdep.Coordinate;
import io.cdep.cdep.yml.cdepmanifest.HardNameDependency;
import net.java.quickcheck.Generator;

import static net.java.quickcheck.generator.PrimitiveGenerators.strings;

public class HardnameGenerator implements Generator<HardNameDependency> {
  Generator<Coordinate> compileGenerator = new CoordinateGenerator();
  Generator<String> sha256Generator = strings();

  @Override
  public HardNameDependency next() {
    String compile = compileGenerator.next().toString();
    String sha256 = sha256Generator.next();
    return new HardNameDependency(compile, sha256);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EasyNetQ.Consumer;

/// <inheritdoc />
public class HandlerCollection : IHandlerCollection
{
    private readonly IDictionary<Type, IMessageHandler> handlers = new Dictionary<Type, IMessageHandler>();

    /// <summary>
    ///     Creates HandlerCollection
    /// </summary>
    public HandlerCollection()
    {
        ThrowOnNoMatchingHandler = true;
    }

    /// <inheritdoc />
    public IHandlerRegistration Add<T>(IMessageHandler<T> handler)
    {
        if (handlers.ContainsKey(typeof(T)))
        {
            throw new EasyNetQException("There is already a handler for message type '{0}'", typeof(T).Name);
        }

        handlers.Add(typeof(T), (m, i, c) => handler((IMessage<T>)m, i, c));
        return this;
    }

    /// <inheritdoc />
    public IMessageHandler<T> GetHandler<T>()
    {
        var handler = GetHandler(typeof(T));
        return (m, i, c) => handler(m, i, c);
    }

    /// <inheritdoc />
    public IMessageHandler GetHandler(Type messageType)
    {
        if (handlers.TryGetValue(messageType, out var func))
        {
            return func;
        }

        // no exact handler match found, so let's see if we can find a handler that
        // handles a supertype of the consumed message.
        var handlerType = handlers.Keys.FirstOrDefault(type => type.IsAssignableFrom(messageType));
        if (handlerType != null)
        {
            return handlers[handlerType];
        }

        if (ThrowOnNoMatchingHandler)
        {
            throw new EasyNetQException("No handler found for message type {0}", messageType.Name);
        }

        return (_, _, _) => Task.FromResult(AckStrategies.Ack);
    }

    /// <inheritdoc />
    public bool ThrowOnNoMatchingHandler { get; set; }
}


text:
    #if AMDT_BUILD_CONFIGURATION == AMDT_DEBUG_BUILD

        #if AMDT_BUILD_ACCESS == AMDT_PUBLIC_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer-d.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64-d.exe";
        #elif AMDT_BUILD_ACCESS == AMDT_NDA_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer-d-nda.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64-d-nda.exe";
        #elif AMDT_BUILD_ACCESS == AMDT_INTERNAL_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer-d-internal.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64-d-internal.exe";
        #else
            #error Unknown build access
        #endif

    #else

        #if AMDT_BUILD_ACCESS == AMDT_PUBLIC_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64.exe";
        #elif AMDT_BUILD_ACCESS == AMDT_NDA_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer-nda.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64-nda.exe";
        #elif AMDT_BUILD_ACCESS == AMDT_INTERNAL_ACCESS
            const std::string ANALYZER_CLI_WIN_X86 = "CodeXLAnalyzer-internal.exe";
            const std::string ANALYZER_CLI_WIN_X64 = "CodeXLAnalyzer-x64-internal.exe";
        #else
            #error Unknown build access
        #endif
    #endif // AMDT_DEBUG_BUILD
#else
    const std::string ANALYZER_CLI_LINUX_X64 = "CodeXLAnalyzer-bin";
#endif

const std::string KA_STR_CL_CLI_CMD_PREFIX = "-s cl";
const std::string KA_STR_VK_CLI_CMD_PREFIX = "-s vulkan";
const std::string KA_STR_GLShaderCommandLineOption = "-s opengl";
const std::string KA_STR_DXShaderCommandLineOption =  "-s hlsl";
const std::string KA_STR_D3D_FXC_ShaderCommandLineOption = "-s DXAsm";
const std::string KA_STR_DX_LOCATION = "--DXLocation";
const std::string KA_STR_FXC = "--FXC";

// **********************************************
// INTERNALLY-LINKED AUXILIARY FUNCTIONS - BEGIN

static std::string GenerateGLShaderOptions(const std::string& shaderType)
{
    std::stringstream outputStream;
    outputStream << KA_STR_GLShaderCommandLineOption << " " << "-p " << " " << shaderType << " ";
    return outputStream.str();
}

static std::string GenerateOptions(const BuildType buildType, kaPipelineShaders shadersPaths)
{
    std::stringstream outputStream;

    switch (buildType)
    {
        case VK_BUILD :
            outputStream << KA_STR_VK_CLI_CMD_PREFIX << " ";
            break;

        case GL_BUILD:
            outputStream << KA_STR_GLShaderCommandLineOption << " ";
            break;

        default:
            GT_ASSERT_EX(false, (L"Unknown Build Type given : " + to_wstring(buildType)).c_str());
            break;
    }

    if (!shadersPaths.m_vertexShader.isEmpty())
    {
        outputStream << " --vert " << "\"" <<  shadersPaths.m_vertexShader.asASCIICharArray() << "\"";
    }

    if (!shadersPaths.m_tessControlShader.isEmpty())
    {
        outputStream << " --tesc " << "\"" <<  shadersPaths.m_tessControlShader.asASCIICharArray() << "\"";
    }

    if (!shadersPaths.m_tessEvaluationShader.isEmpty())
    {
        outputStream << " --tese " << "\"" <<  shadersPaths.m_tessEvaluationShader.asASCIICharArray() << "\"";
    }

    if (!shadersPaths.m_geometryShader.isEmpty())
    {
        outputStream << " --geom " << "\"" <<  shadersPaths.m_geometryShader.asASCIICharArray() << "\"";
    }

    if (!shadersPaths.m_fragmentShader.isEmpty())
    {
        outputStream << " --frag " << "\"" <<  shadersPaths.m_fragmentShader.asASCIICharArray() << "\"";
    }

    if (!shadersPaths.m_computeShader.isEmpty())
    {
        outputStream << " --comp " << "\"" <<  shadersPaths.m_computeShader.asASCIICharArray() << "\"";
    }

    return outputStream.str();
}

#ifdef _WIN32

// Splits a given string to sub-elements according to the given delimiter.
static void split(const std::string& s, char delim, std::vector<std::string>& elems)
{
    elems.clear();
    std::stringstream ss(s);
    std::string item;

    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
}

// Splits the user-defined list of macros into pairs of key-value strings.
static bool ExtractDxCompilerDefines(const QString& userDefines,
                                     std::vector<std::pair<std::string, std::string>>& extractedDefines)
{
    bool ret = false;
    extractedDefines.clear();
    const char DELIMITER = ';';
    const char EQUALS_SYMBOL = '=';
    const std::string& definesStr = userDefines.toStdString();

    std::vector<std::string> defines;
    split(definesStr, DELIMITER, defines);

    for (size_t i = 0; i < defines.size(); ++i)
    {
        const std::string& currDefinition = defines[i];

        // Split the definition to key and value.
        size_t equalsSymbolIndex = currDefinition.find(EQUALS_SYMBOL);

        if (equalsSymbolIndex != std::string::npos)
        {
            // We have both key and value.
            std::string key = currDefinition.substr(0, equalsSymbolIndex);
            std::string value = currDefinition.substr(equalsSymbolIndex + 1);

            // Add the key value definition to our container.
            std::pair<std::string, std::string> pair(key, value);
            extractedDefines.push_back(pair);
        }
        else
        {
            // We only have a single definition (not a key-value pair).
            // Add the key value definition to our container.
            std::pair<std::string, std::string> pair(currDefinition, " ");
            extractedDefines.push_back(pair);
        }
    }

    ret = !extractedDefines.empty();
    return ret;
}

// Splits the user-defined list of include paths into a list of path strings.
static bool ExtractDxCompilerIncludes(const QString& userIncludes,
                                      std::vector<std::string>& extractedIncludes)
{
    bool ret = false;
    extractedIncludes.clear();
    const char DELIMITER = ';';
    const std::string& definesStr = userIncludes.toStdString();

    if (!userIncludes.contains(DELIMITER))
    {
        // Edge case: only a single include directory, without a delimiter.
        const QString& includeDir = userIncludes.trimmed();

        if (!includeDir.isEmpty())
        {
            extractedIncludes.push_back(includeDir.toStdString());
        }
    }
    else
    {
        std::vector<std::string> paths;
        split(definesStr, DELIMITER, paths);

        // Copy the paths.
        if (!paths.empty())
        {
            std::copy(paths.begin(), paths.end(), std::back_inserter(extractedIncludes));
        }
    }

    ret = !extractedIncludes.empty();
    return ret;
}

#endif

static std::string GenerateDeviceArgList(const std::set<std::string>& devices)
{
    std::stringstream outputStream;

    for (const std::string& device : devices)
    {
        outputStream << "-c " << "\"" << device << "\"" << " ";
    }

    return outputStream.str();
}

static std::string GenerateDeviceArg(const std::string& device)
{
    std::stringstream outputStream;
    outputStream << "-c " << "\"" << device << "\"" << " ";
    return outputStream.str();
}

static std::string GenerateKernelOptions()
{
    std::stringstream outputStream;
    outputStream << KA_STR_CL_CLI_CMD_PREFIX << " " << "--kernel all ";
    return outputStream.str();
}

static std::string GetCliExecutableName(AnalyzerBuildArchitecture& bitness)
{
    std::stringstream outputStream;
    const gtString OS_PATH_SEPRATOR(osFilePath::osPathSeparator);
    bool areWrappingQuotesRequired = false;

    // Get the binary directory.
    static gtString s_cxlBinDir;

    if (s_cxlBinDir.isEmpty())
    {
        osFilePath cxlBinPath(osFilePath::OS_CODEXL_BINARIES_PATH);
        s_cxlBinDir = cxlBinPath.fileDirectoryAsString();
    }

    // If the path contains space characters then wrapping quote characters are required at the beginning and the end of the complete Cli executable path
    if (s_cxlBinDir.find(L' ') != -1)
    {
        areWrappingQuotesRequired = true;
    }

    if (areWrappingQuotesRequired)
    {
        outputStream << "\"";
    }

    outputStream << s_cxlBinDir.asASCIICharArray() << OS_PATH_SEPRATOR.asASCIICharArray();

#if _WIN32

    if (bitness == kaBuildArch32_bit)
    {
        outputStream << ANALYZER_CLI_WIN_X86;
    }
    else
    {
        outputStream << ANALYZER_CLI_WIN_X64;
    }

#else
    GT_UNREFERENCED_PARAMETER(bitness);
    outputStream << ANALYZER_CLI_LINUX_X64;
#endif

    if (areWrappingQuotesRequired)
    {
        outputStream << "\"";
    }

    return outputStream.str();
}

// INTERNALLY-LINKED AUXILIARY FUNCTIONS - END
// **********************************************

//-----------------------------------------------------------------------------
/// \brief Name: GenerateCLICommandForDevice
/// \brief Description: Generates CLI Command according to configuration parameters
static std::string GenerateCLICommandForDevice(AnalyzerBuildArchitecture bitness,
                                               const std::string& buildType,
                                               const std::string& device,
                                               const std::string& buildOptions,
                                               const std::string& baseISAFilename,
                                               const std::string& baseILFilename,
                                               const std::string& baseAnalysFilename,
                                               const std::string& baseDxAsmFileName,
                                               const std::string& binaryFileName,
                                               const std::string& sourceCodeFullPathName)
{
    std::stringstream outputStream;

    // The executable name returned by the GetCliExecutableName() function is already wrapped in quotes if it contains spaces
    outputStream << GetCliExecutableName(bitness) << " ";
    outputStream << buildType << " " << GenerateDeviceArg(device) << " ";

    outputStream << buildOptions << " ";

    if (!baseISAFilename.empty())
    {
        outputStream << "--isa " << "\"" << baseISAFilename << "\"" << " ";
    }

    if (!baseILFilename.empty())
    {
        outputStream << "--il " << "\"" << baseILFilename << "\"" << " ";
    }

    if (!baseAnalysFilename.empty())
    {
        outputStream << "-a " << "\"" << baseAnalysFilename << "\"" << " ";
    }

    if (!binaryFileName.empty())
    {
        outputStream << "-b " << "\"" << binaryFileName << "\"" << " ";
    }

    if (!baseDxAsmFileName.empty())
    {
        outputStream << "--DumpMSIntermediate " << "\"" << baseDxAsmFileName << "\"" << " ";
    }

    if (!sourceCodeFullPathName.empty())
    {
        outputStream << "\"" << sourceCodeFullPathName << "\"";
    }

    return outputStream.str();
}

//-----------------------------------------------------------------------------
/// \brief Name: GenerateVulkanCLICommandForDevice
/// \brief Description: Generates Vulkan CLI Command according to configuration parameters
static std::string GenerateCLICommandForDevice(AnalyzerBuildArchitecture bitness,
                                               const std::string& vulkanBuildOptions,
                                               const std::string& device,
                                               const std::string& baseISAFilename,
                                               const std::string& baseILFilename,
                                               const std::string& baseStatisticsFilename,
                                               const std::string& binaryFileName)

{
    std::stringstream outputStream;

    // The executable name returned by the GetCliExecutableName() function is already wrapped in quotes if it contains spaces
    outputStream << GetCliExecutableName(bitness) << " ";
    outputStream << vulkanBuildOptions << " " << GenerateDeviceArg(device) << " ";

    if (!baseISAFilename.empty())
    {
        outputStream << "--isa " << "\"" << baseISAFilename << "\"" << " ";
    }

    if (!baseILFilename.empty())
    {
        outputStream << "--il " << "\"" << baseILFilename << "\"" << " ";
    }

    if (!baseStatisticsFilename.empty())
    {
        outputStream << "-a " << "\"" << baseStatisticsFilename << "\"" << " ";
    }

    if (!binaryFileName.empty())
    {
        outputStream << " -b " << "\"" << binaryFileName << "\"" << " ";
    }

    return outputStream.str();
}

static std::string GenerateCLICommandForMultipleDevices(AnalyzerBuildArchitecture bitness,
                                                        const std::string& buildType,
                                                        const std::set<std::string>& deviceList,
                                                        const std::string& baseISAFilename,
                                                        const std::string& baseILFilename,
                                                        const std::string& baseAnalysFilename, const std::string& baseDxAsmFileName,
                                                        const std::string& binaryFileName,
                                                        const std::string& sourceCodeFullPathName)
{
    std::stringstream outputStream;

    // The executable name returned by the GetCliExecutableName() function is already wrapped in quotes if it contains spaces
    outputStream << GetCliExecutableName(bitness) << " ";
    outputStream << buildType << " " << GenerateDeviceArgList(deviceList) << " ";

    if (!baseISAFilename.empty())
    {
        outputStream << "--isa " << "\"" << baseISAFilename << "\"" << " ";
    }

    if (!baseILFilename.empty())
    {
        outputStream << "--il " << "\"" << baseILFilename << "\"" << " ";
    }

    if (!baseAnalysFilename.empty())
    {
        outputStream << "-a " << "\"" << baseAnalysFilename << "\"" << " ";
    }

    if (!baseDxAsmFileName.empty())
    {
        outputStream << "--DumpMSIntermediate " << "\"" << baseDxAsmFileName << "\"" << " ";
    }

    if (!binaryFileName.empty())
    {
        outputStream << "-b " << "\"" << binaryFileName << "\"" << " ";
    }

    outputStream << "\"" << sourceCodeFullPathName << "\"";

    return outputStream.str();
}

static bool ExecAndGrabOutput(const char* cmd, const bool& shouldBeCancelled, std::string& cmdOutput)
{
    bool ret = true;
    bool isBuildCancelled = kaBackendManager::instance().IsBuildCancelled();

    if (!isBuildCancelled)
    {
        gtString cmdOutputAsGtStr;
        ret = osExecAndGrabOutput(cmd, shouldBeCancelled, cmdOutputAsGtStr);

        if (ret && !cmdOutputAsGtStr.isEmpty())
        {
            cmdOutput = cmdOutputAsGtStr.asASCIICharArray();
        }
    }

    return ret;
}

//-----------------------------------------------------------------------------
bool LaunchOpenGLSession(AnalyzerBuildArchitecture bitness, const std::string& shaderType,
                         const std::string& baseISAFilename, const std::string& baseILFilename,
                         const std::string& baseAnalysFilename, const std::set<std::string>& SelectedDevices,
                         const std::string& sourceCodeFullPathName, const bool& shouldBeCancelled, std::string& cliOutput)
{
    bool retVal = false;
    std::string GLShaderOptions = GenerateGLShaderOptions(shaderType);

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForMultipleDevices(bitness, GLShaderOptions, SelectedDevices, baseISAFilename,
                                                                   baseILFilename, baseAnalysFilename, "", "", sourceCodeFullPathName);

    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldBeCancelled, cliOutput);

    retVal = !cliOutput.empty();
    return retVal;
}

//-----------------------------------------------------------------------------
bool LaunchOpenGLSessionForDevice(AnalyzerBuildArchitecture bitness, const std::string& shaderType,
                                  const std::string& baseISAFilename, const std::string& baseILFilename,
                                  const std::string& baseAnalysFilename, const std::string& SelectedDevice,
                                  const std::string& sourceCodeFullPathName, const bool& shouldBeCancelled, std::string& cliOutput)
{
    bool retVal = false;
    std::string GLShaderOptions = GenerateGLShaderOptions(shaderType);

    // Build options are always empty for OpenGL build
    std::string buildOptions;

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForDevice(bitness, GLShaderOptions, SelectedDevice, buildOptions, baseISAFilename,
                                                          baseILFilename, baseAnalysFilename, "", "", sourceCodeFullPathName);

    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldBeCancelled, cliOutput);

    retVal = !cliOutput.empty();
    return retVal;
}

#if _WIN32

static std::string GenerateDXShaderOptions(const std::string& dxTarget, const std::string& dxEntryPoint, bool isFxc)
{
    std::stringstream outputStream;

    if (!isFxc)
    {
        outputStream << KA_STR_DXShaderCommandLineOption << " " << "-p" << " " << dxTarget << " " << "-f" << " " << dxEntryPoint;
    }
    else
    {
        outputStream << KA_STR_D3D_FXC_ShaderCommandLineOption << " " << "-p " << dxTarget << " " << "-f " << dxEntryPoint << " ";
    }

    return outputStream.str();
}

static std::string GenerateDXBuilderOptions(const std::string& buildOptions, const DXAdditionalBuildOptions& additionalBuildOptions)
{
    std::stringstream outputStream;

    if (!buildOptions.empty())
    {
        std::vector<std::string> buildOptionsElems;
        split(buildOptions, ' ', buildOptionsElems);

        for (const std::string& buildOptElem : buildOptionsElems)
        {
            outputStream << "-D " << buildOptElem << " ";
        }
    }

    if (!additionalBuildOptions.m_builderPath.isEmpty())
    {
        outputStream << " " << KA_STR_DX_LOCATION << " \"" << additionalBuildOptions.m_builderPath.toStdString() << "\" ";
    }

    // Handle custom include paths.
    std::vector<std::string> includePaths;
    bool isInlucdePathsHandled = ExtractDxCompilerIncludes(additionalBuildOptions.m_additionalIncludes, includePaths);

    if (isInlucdePathsHandled)
    {
        for (const std::string& incPath : includePaths)
        {
            outputStream << "-I \"" << incPath << "\" ";
        }
    }

    // Handle user-defined macro definitions.
    std::vector<std::pair<std::string, std::string>> userMacros;
    bool isUserMacrosHandled = ExtractDxCompilerDefines(additionalBuildOptions.m_additionalMacros, userMacros);

    if (isUserMacrosHandled)
    {
        for (const auto& definedMacro : userMacros)
        {
            outputStream << "-D " << definedMacro.first;

            if (!definedMacro.second.empty())
            {
                outputStream << "=" << definedMacro.second << " ";
            }
        }
    }

    if (additionalBuildOptions.m_buildOptionsMask != 0)
    {
        outputStream << "--DXFlags " << additionalBuildOptions.m_buildOptionsMask << " ";
    }

    return outputStream.str();
}

//-----------------------------------------------------------------------------
bool LaunchDXSessionForDevice(AnalyzerBuildArchitecture& bitness,
                              const::string& dxTarget,
                              const std::string& dxEntryPoint,
                              const std::string& buildOptions,
                              const DXAdditionalBuildOptions& additionalBuildOptions,
                              const std::string& baseISAFilename,
                              const std::string& baseBinFName,
                              const std::string& baseILFilename,
                              const std::string& baseAnalysFilename,
                              const std::string& dxAsmFileName,
                              const std::string& selectedDevice,
                              const std::string& sourceCodeFullPathName,
                              const bool& shouldBeCanceled,
                              std::string& cliOutput)
{
    GT_UNREFERENCED_PARAMETER(baseILFilename);
    bool retVal = true;

    std::stringstream dxOptionsOutputStream;

    // Check if the compilation should go through FXC.
    bool isFxc = (additionalBuildOptions.m_builderType == KA_STR_DX_FXC_BUILD_TYPE);

    dxOptionsOutputStream << GenerateDXShaderOptions(dxTarget, dxEntryPoint, isFxc);
    std::string compilerBuildOptions;

    if (!isFxc)
    {
        compilerBuildOptions = GenerateDXBuilderOptions(buildOptions, additionalBuildOptions);
    }
    else
    {
        std::string fixedDxAsmFile;

        // Fix the DX ASM file name.
        if (!dxAsmFileName.empty())
        {
            // Convert the original name to a structure that we can work with.
            gtString fileNameAsGtstr;
            fileNameAsGtstr << dxAsmFileName.c_str();
            osFilePath dxAsmFilePath(fileNameAsGtstr);
            gtString originalFileName;
            dxAsmFilePath.getFileName(originalFileName);

            if (!originalFileName.isEmpty())
            {
                // Disassemble the file name, and reconstruct it, this time
                // including the entry point.
                std::vector<std::string> fileNameElems;
                split(originalFileName.asASCIICharArray(), '_', fileNameElems);

                if (fileNameElems.size() > 1)
                {
                    std::stringstream tmpStream;
                    tmpStream << fileNameElems[0] << "_" << dxEntryPoint;

                    for (size_t i = 1; i < fileNameElems.size(); ++i)
                    {
                        tmpStream << "_" << fileNameElems[i];
                    }

                    gtString fixedFilesNameAsGtStr;
                    fixedFilesNameAsGtStr << tmpStream.str().c_str();
                    dxAsmFilePath.setFileName(fixedFilesNameAsGtStr);
                    fixedDxAsmFile = dxAsmFilePath.asString().asASCIICharArray();
                }
            }

        }

        // Wrap FXC's path arguments with this string to make sure that the command
        // is being processed successfully by both Analyzer CLI and FXC.
        const char* PATH_WRAPPER = "\\\"";

        // Get the object file path.
        gtString isaFullPath;
        isaFullPath << baseISAFilename.c_str();
        osFilePath isaOutputDirFullPath;
        isaOutputDirFullPath.setFullPathFromString(isaFullPath);

        // Generate the obj file name.
        std::stringstream objFileName;
        objFileName << isaOutputDirFullPath.fileDirectoryAsString().asASCIICharArray() << "\\";
        objFileName << selectedDevice << "_obj.obj";

        // Add the name of the obj file that is expected to be generated by the FXC.
        dxOptionsOutputStream << "\"" << objFileName.str() << "\"";

        // Build the command string for FXC invocation.
        dxOptionsOutputStream << " --FXC \"\\";
        dxOptionsOutputStream << "\"" << additionalBuildOptions.m_builderPath.toStdString().c_str() << "\\\" ";
        dxOptionsOutputStream << additionalBuildOptions.m_buildOptions.toStdString().c_str() << " ";

        // Handle custom include paths.
        std::vector<std::string> includePaths;
        bool isInlucdePathsHandled = ExtractDxCompilerIncludes(additionalBuildOptions.m_additionalIncludes, includePaths);

        if (isInlucdePathsHandled)
        {
            for (const std::string& incPath : includePaths)
            {
                dxOptionsOutputStream << "/I " << PATH_WRAPPER << incPath << PATH_WRAPPER << " ";
            }
        }

        // Handle user-defined macro definitions.
        std::vector<std::pair<std::string, std::string>> userMacros;
        bool isUserMacrosHandled = ExtractDxCompilerDefines(additionalBuildOptions.m_additionalMacros, userMacros);

        if (isUserMacrosHandled)
        {
            for (const auto& definedMacro : userMacros)
            {
                dxOptionsOutputStream << "/D " << definedMacro.first << "=" << definedMacro.second << " ";
            }
        }

        dxOptionsOutputStream << "/T " << dxTarget << " /E " << dxEntryPoint << " /Fc " << PATH_WRAPPER << fixedDxAsmFile << PATH_WRAPPER << " /Fo " << PATH_WRAPPER <<
                              objFileName.str() << PATH_WRAPPER << " " << PATH_WRAPPER << sourceCodeFullPathName << PATH_WRAPPER << "\"";
    }

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForDevice(bitness,
                                                          dxOptionsOutputStream.str(),
                                                          selectedDevice,
                                                          compilerBuildOptions,
                                                          baseISAFilename,
                                                          baseILFilename,
                                                          baseAnalysFilename,
                                                          ((!isFxc) ? dxAsmFileName : ""),
                                                          baseBinFName,
                                                          ((!isFxc) ? sourceCodeFullPathName : ""));

    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldBeCanceled, cliOutput);
    retVal = retVal && !cliOutput.empty();
    return retVal;
}
#endif

bool LaunchOpenCLSession(AnalyzerBuildArchitecture bitness,
                         const std::string& baseISAFilename,
                         const std::string& baseILFilename,
                         const std::string& baseAnalysFilename,
                         const std::string& binaryFilename,
                         const std::set<std::string>& SelectedDevices,
                         const std::string& sourceCodeFullPathName, const bool& shouldBeCancelled,
                         std::string& cliOutput)
{
    bool retVal = false;

    // Generate the kernel options.
    std::string kernelOptions = GenerateKernelOptions();

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForMultipleDevices(bitness, kernelOptions, SelectedDevices, baseISAFilename,
                                                                   baseILFilename, baseAnalysFilename, "", binaryFilename, sourceCodeFullPathName);

    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldBeCancelled, cliOutput);
    retVal = !cliOutput.empty();

    return retVal;
}

//-----------------------------------------------------------------------------
bool LaunchOpenCLSessionForDevice(AnalyzerBuildArchitecture bitness,
                                  const std::string& baseISAFilename,
                                  const std::string& baseILFilename,
                                  const std::string& baseAnalysFilename,
                                  const std::string& binaryFilename,
                                  const std::string& Device,
                                  const std::string& sourceCodeFullPathName,
                                  const std::string& buildOptions,
                                  const bool& shouldBeCancelled,
                                  std::string& cliOutput)
{
    bool retVal = false;
    // Generate the kernel options.
    std::string kernelOptions = GenerateKernelOptions();

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForDevice(bitness, kernelOptions, Device, buildOptions, baseISAFilename,
                                                          baseILFilename, baseAnalysFilename, "", binaryFilename, sourceCodeFullPathName);

    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldBeCancelled, cliOutput);
    retVal = !cliOutput.empty();

    return retVal;
}

bool LaunchVulkanSession(AnalyzerBuildArchitecture bitness, const kaPipelineShaders& inputShaders, const std::string& baseISAFilename,
                         const std::string& baseILFilename, const std::string& baseAnalysFilename, const std::string& binaryFilename,
                         const std::set<std::string>& selectedDevices, const bool& shouldCancel, std::string& cliOutput)
{
    // TODO: implement this function.

    GT_UNREFERENCED_PARAMETER(bitness);
    GT_UNREFERENCED_PARAMETER(inputShaders);
    GT_UNREFERENCED_PARAMETER(baseISAFilename);
    GT_UNREFERENCED_PARAMETER(baseILFilename);
    GT_UNREFERENCED_PARAMETER(baseAnalysFilename);
    GT_UNREFERENCED_PARAMETER(binaryFilename);
    GT_UNREFERENCED_PARAMETER(selectedDevices);
    GT_UNREFERENCED_PARAMETER(shouldCancel);
    GT_UNREFERENCED_PARAMETER(cliOutput);
    return false;
}

bool LaunchRenderSessionForDevice(const BuildType buildType, AnalyzerBuildArchitecture bitness, const kaPipelineShaders& inputShaders,
                                  const std::string& baseISAFilename, const std::string& baseILFilename,
                                  const std::string& baseStatisticsFilename, const std::string& binaryFilename,
                                  const std::string& device, const bool& shouldCancel, std::string& cliOutput)
{
    bool retVal = false;

    std::string buildOptions = GenerateOptions(buildType, inputShaders);

    // Generate the CLI command.
    std::string commandLine = GenerateCLICommandForDevice(bitness, buildOptions,
                                                          device, baseISAFilename,
                                                          baseILFilename, baseStatisticsFilename,
                                                          binaryFilename);
    // Execute the CLI.
    ExecAndGrabOutput(commandLine.c_str(), shouldCancel, cliOutput);

    retVal = !cliOutput.empty();
    return retVal;
}


text:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ang2app</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <app-root></app-root>
</body>
</html>


text:
package main

import (
	"flag"
	"fmt"
	"net/url"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"strings"
	"syscall"
	"time"
)

var (
	_method         = flag.String("m", "GET", "HTTP Metod")
	_url            = flag.String("u", "http://localhost", "URL")
	_connection     = flag.Int("c", 64, "Connections count")
	_threads        = flag.Int("t", 4, "Threads count")
	_mrq            = flag.Int("mrq", -1, "Max request per second")
	_source         = flag.String("s", "", "POST/PUT Body source file with \"\\n\" delimeter or URLs on GET/DELETE")
	_duration       = flag.Duration("d", time.Duration(30)*time.Second, "Test duration")
	_verbose        = flag.Bool("v", false, "Live stats view")
	_excludeSeconds = flag.Duration("es", time.Duration(0)*time.Second, "Exclude first seconds from stats")
	_help           = flag.Bool("h", false, "Help")
	_cpuprofile     = flag.String("cpuprofile", "", "write cpu profile to file")
)

type RequestStats struct {
	ResponseCode int
	Duration     time.Duration
	NetIn        int64
	NetOut       int64
}

type Config struct {
	Method            string
	Host              string
	Url               *url.URL
	Connections       int
	Threads           int
	MRQ               int
	Verbose           bool
	ExcludeSeconds    time.Duration
	Source            *Source
	Duration          time.Duration
	ConnectionManager *ConnectionManager
	WorkerQuit        chan bool
	WorkerQuited      chan bool
	StatsQuit         chan bool
	StatsQuited       chan bool
	RequestStats      chan *RequestStats
}

func main() {
	flag.Parse()

	if *_help {
		flag.Usage()
		return
	}

	var (
		sourceData *Source
		err        error
	)

	*_method = strings.ToUpper(*_method)

	if len(*_source) > 0 && FileExists(*_source) {
		sourceData, err = LoadSource(*_source, "\n")
		if err != nil {
			fmt.Printf("ERROR: Can not load source file %s\n", *_source)
			return
		}
	} else {
		sourceData = &Source{}
	}

	URL, err := url.Parse(*_url)
	if err != nil {
		fmt.Printf("ERROR: URL is broken %s\n", *_url)
		return
	}

	if *_cpuprofile != "" {
		f, err := os.Create(*_cpuprofile)
		if err != nil {
			fmt.Printf("Can not start cpu proffile %v\n", err)
			return
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	config := &Config{
		Method:         *_method,
		Host:           URL.Host,
		Url:            URL,
		Connections:    *_connection,
		Threads:        *_threads,
		MRQ:            *_mrq,
		Verbose:        *_verbose,
		ExcludeSeconds: *_excludeSeconds,
		Source:         sourceData,
		Duration:       *_duration,
		WorkerQuit:     make(chan bool, *_threads),
		WorkerQuited:   make(chan bool, *_threads),
		StatsQuit:      make(chan bool, 1),
		StatsQuited:    make(chan bool, 1),
		RequestStats:   make(chan *RequestStats, *_connection*512),
	}

	if strings.Index(config.Host, ":") > -1 {
		h := strings.SplitN(config.Host, ":", 2)
		config.Host = h[0]
	}

	runtime.GOMAXPROCS(*_threads)

	logUrl := config.Url.String()
	if *_method != "POST" && *_method == "PUT" {
		logUrl = config.Url.Host
	}

	if config.MRQ == -1 {
		fmt.Printf("Running test threads: %d, connections: %d in %v %s %s\n", *_threads, config.Connections, config.Duration, config.Method, logUrl)
	} else {
		fmt.Printf("Running test threads: %d, connections: %d, max req/sec: %d, in %v %s %s\n", *_threads, config.Connections, config.MRQ, config.Duration, config.Method, logUrl)
	}

	config.ConnectionManager = NewConnectionManager(config)

	//check any connect
	anyConnected := false
	for i := 0; i < config.Connections && !anyConnected; i++ {
		connection := config.ConnectionManager.conns[i]
		if connection.IsConnected() {
			anyConnected = true
		}
	}
	if !anyConnected {
		fmt.Printf("Can not connect to %s\n", config.Url.Host)
		return
	}

	go StartStatsAggregator(config)

	for i := 0; i < config.Threads; i++ {
		go NewThread(config)
	}

	//Start SIGTERM listen
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)

	//Wait timers or SIGTERM
	select {
	case <-time.After(config.Duration):
	case <-signalChan:
	}
	for i := 0; i < config.Threads; i++ {
		config.WorkerQuit <- true
	}
	//Wait for threads complete
	for i := 0; i < config.Threads; i++ {
		<-config.WorkerQuited
	}

	//Stop stats aggregator
	config.StatsQuit <- true
	//Close connections
	for i := 0; i < config.Connections; i++ {
		connection := config.ConnectionManager.conns[i]
		if !connection.IsConnected() {
			continue
		}
		connection.conn.Close()
	}
	//Wait stats aggregator complete
	<-config.StatsQuited
	//Print result
	PrintStats(os.Stdout, config)
}

func FileExists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}