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

#include "content/shell/test_runner/web_frame_test_client.h"

#include <memory>

#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "content/public/test/test_runner_support.h"
#include "content/shell/test_runner/accessibility_controller.h"
#include "content/shell/test_runner/event_sender.h"
#include "content/shell/test_runner/mock_screen_orientation_client.h"
#include "content/shell/test_runner/mock_web_speech_recognizer.h"
#include "content/shell/test_runner/test_common.h"
#include "content/shell/test_runner/test_interfaces.h"
#include "content/shell/test_runner/test_plugin.h"
#include "content/shell/test_runner/test_runner.h"
#include "content/shell/test_runner/web_frame_test_proxy.h"
#include "content/shell/test_runner/web_test_delegate.h"
#include "content/shell/test_runner/web_view_test_proxy.h"
#include "content/shell/test_runner/web_widget_test_proxy.h"
#include "net/base/net_errors.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/public/web/web_console_message.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_navigation_policy.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_user_gesture_indicator.h"
#include "third_party/blink/public/web/web_view.h"
#include "url/gurl.h"
#include "url/url_constants.h"

namespace test_runner {

namespace {

void PrintFrameDescription(WebTestDelegate* delegate,
                           blink::WebLocalFrame* frame) {
  std::string name = content::GetFrameNameForLayoutTests(frame);
  if (frame == frame->View()->MainFrame()) {
    DCHECK(name.empty());
    delegate->PrintMessage("main frame");
    return;
  }
  if (name.empty()) {
    delegate->PrintMessage("frame (anonymous)");
    return;
  }
  delegate->PrintMessage(std::string("frame \"") + name + "\"");
}

void PrintFrameuserGestureStatus(WebTestDelegate* delegate,
                                 blink::WebLocalFrame* frame,
                                 const char* msg) {
  bool is_user_gesture =
      blink::WebUserGestureIndicator::IsProcessingUserGesture(frame);
  delegate->PrintMessage(std::string("Frame with user gesture \"") +
                         (is_user_gesture ? "true" : "false") + "\"" + msg);
}

// Used to write a platform neutral file:/// URL by taking the
// filename and its directory. (e.g., converts
// "file:///tmp/foo/bar.txt" to just "bar.txt").
std::string DescriptionSuitableForTestResult(const std::string& url) {
  if (url.empty() || std::string::npos == url.find("file://"))
    return url;

  size_t pos = url.rfind('/');
  if (pos == std::string::npos || !pos)
    return "ERROR:" + url;
  pos = url.rfind('/', pos - 1);
  if (pos == std::string::npos)
    return "ERROR:" + url;

  return url.substr(pos + 1);
}

void PrintResponseDescription(WebTestDelegate* delegate,
                              const blink::WebURLResponse& response) {
  if (response.IsNull()) {
    delegate->PrintMessage("(null)");
    return;
  }
  delegate->PrintMessage(base::StringPrintf(
      "<NSURLResponse %s, http status code %d>",
      DescriptionSuitableForTestResult(response.Url().GetString().Utf8())
          .c_str(),
      response.HttpStatusCode()));
}

void BlockRequest(blink::WebURLRequest& request) {
  request.SetURL(GURL("255.255.255.255"));
}

bool IsLocalHost(const std::string& host) {
  return host == "127.0.0.1" || host == "localhost" || host == "[::1]";
}

bool IsTestHost(const std::string& host) {
  return base::EndsWith(host, ".test", base::CompareCase::INSENSITIVE_ASCII);
}

bool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {
  return host == "255.255.255.255";
}

// Used to write a platform neutral file:/// URL by only taking the filename
// (e.g., converts "file:///tmp/foo.txt" to just "foo.txt").
std::string URLSuitableForTestResult(const std::string& url) {
  if (url.empty() || std::string::npos == url.find("file://"))
    return url;

  size_t pos = url.rfind('/');
  if (pos == std::string::npos) {
#ifdef WIN32
    pos = url.rfind('\\');
    if (pos == std::string::npos)
      pos = 0;
#else
    pos = 0;
#endif
  }
  std::string filename = url.substr(pos + 1);
  if (filename.empty())
    return "file:";  // A WebKit test has this in its expected output.
  return filename;
}

// WebNavigationType debugging strings taken from PolicyDelegate.mm.
const char* kLinkClickedString = "link clicked";
const char* kFormSubmittedString = "form submitted";
const char* kBackForwardString = "back/forward";
const char* kReloadString = "reload";
const char* kFormResubmittedString = "form resubmitted";
const char* kOtherString = "other";
const char* kIllegalString = "illegal value";

// Get a debugging string from a WebNavigationType.
const char* WebNavigationTypeToString(blink::WebNavigationType type) {
  switch (type) {
    case blink::kWebNavigationTypeLinkClicked:
      return kLinkClickedString;
    case blink::kWebNavigationTypeFormSubmitted:
      return kFormSubmittedString;
    case blink::kWebNavigationTypeBackForward:
      return kBackForwardString;
    case blink::kWebNavigationTypeReload:
      return kReloadString;
    case blink::kWebNavigationTypeFormResubmitted:
      return kFormResubmittedString;
    case blink::kWebNavigationTypeOther:
      return kOtherString;
  }
  return kIllegalString;
}

}  // namespace

WebFrameTestClient::WebFrameTestClient(
    WebTestDelegate* delegate,
    WebViewTestProxyBase* web_view_test_proxy_base,
    WebFrameTestProxyBase* web_frame_test_proxy_base)
    : delegate_(delegate),
      web_view_test_proxy_base_(web_view_test_proxy_base),
      web_frame_test_proxy_base_(web_frame_test_proxy_base) {
  DCHECK(delegate_);
  DCHECK(web_frame_test_proxy_base_);
  DCHECK(web_view_test_proxy_base_);
}

WebFrameTestClient::~WebFrameTestClient() {}

void WebFrameTestClient::RunModalAlertDialog(const blink::WebString& message) {
  if (!test_runner()->ShouldDumpJavaScriptDialogs())
    return;
  delegate_->PrintMessage(std::string("ALERT: ") + message.Utf8().data() +
                          "\n");
}

bool WebFrameTestClient::RunModalConfirmDialog(
    const blink::WebString& message) {
  if (!test_runner()->ShouldDumpJavaScriptDialogs())
    return true;
  delegate_->PrintMessage(std::string("CONFIRM: ") + message.Utf8().data() +
                          "\n");
  return true;
}

bool WebFrameTestClient::RunModalPromptDialog(
    const blink::WebString& message,
    const blink::WebString& default_value,
    blink::WebString* actual_value) {
  if (!test_runner()->ShouldDumpJavaScriptDialogs())
    return true;
  delegate_->PrintMessage(std::string("PROMPT: ") + message.Utf8().data() +
                          ", default text: " + default_value.Utf8().data() +
                          "\n");
  return true;
}

bool WebFrameTestClient::RunModalBeforeUnloadDialog(bool is_reload) {
  if (test_runner()->ShouldDumpJavaScriptDialogs())
    delegate_->PrintMessage(std::string("CONFIRM NAVIGATION\n"));
  return !test_runner()->shouldStayOnPageAfterHandlingBeforeUnload();
}

void WebFrameTestClient::PostAccessibilityEvent(const blink::WebAXObject& obj,
                                                blink::WebAXEvent event) {
  // Only hook the accessibility events occured during the test run.
  // This check prevents false positives in BlinkLeakDetector.
  // The pending tasks in browser/renderer message queue may trigger
  // accessibility events,
  // and AccessibilityController will hold on to their target nodes if we don't
  // ignore them here.
  if (!test_runner()->TestIsRunning())
    return;

  const char* event_name = nullptr;
  switch (event) {
    case blink::kWebAXEventActiveDescendantChanged:
      event_name = "ActiveDescendantChanged";
      break;
    case blink::kWebAXEventAriaAttributeChanged:
      event_name = "AriaAttributeChanged";
      break;
    case blink::kWebAXEventAutocorrectionOccured:
      event_name = "AutocorrectionOccured";
      break;
    case blink::kWebAXEventBlur:
      event_name = "Blur";
      break;
    case blink::kWebAXEventCheckedStateChanged:
      event_name = "CheckedStateChanged";
      break;
    case blink::kWebAXEventChildrenChanged:
      event_name = "ChildrenChanged";
      break;
    case blink::kWebAXEventClicked:
      event_name = "Clicked";
      break;
    case blink::kWebAXEventDocumentSelectionChanged:
      event_name = "DocumentSelectionChanged";
      break;
    case blink::kWebAXEventFocus:
      event_name = "Focus";
      break;
    case blink::kWebAXEventHide:
      event_name = "Hide";
      break;
    case blink::kWebAXEventHover:
      event_name = "Hover";
      break;
    case blink::kWebAXEventInvalidStatusChanged:
      event_name = "InvalidStatusChanged";
      break;
    case blink::kWebAXEventLayoutComplete:
      event_name = "LayoutComplete";
      break;
    case blink::kWebAXEventLiveRegionChanged:
      event_name = "LiveRegionChanged";
      break;
    case blink::kWebAXEventLoadComplete:
      event_name = "LoadComplete";
      break;
    case blink::kWebAXEventLocationChanged:
      event_name = "LocationChanged";
      break;
    case blink::kWebAXEventMenuListItemSelected:
      event_name = "MenuListItemSelected";
      break;
    case blink::kWebAXEventMenuListItemUnselected:
      event_name = "MenuListItemUnselected";
      break;
    case blink::kWebAXEventMenuListValueChanged:
      event_name = "MenuListValueChanged";
      break;
    case blink::kWebAXEventRowCollapsed:
      event_name = "RowCollapsed";
      break;
    case blink::kWebAXEventRowCountChanged:
      event_name = "RowCountChanged";
      break;
    case blink::kWebAXEventRowExpanded:
      event_name = "RowExpanded";
      break;
    case blink::kWebAXEventScrollPositionChanged:
      event_name = "ScrollPositionChanged";
      break;
    case blink::kWebAXEventScrolledToAnchor:
      event_name = "ScrolledToAnchor";
      break;
    case blink::kWebAXEventSelectedChildrenChanged:
      event_name = "SelectedChildrenChanged";
      break;
    case blink::kWebAXEventSelectedTextChanged:
      event_name = "SelectedTextChanged";
      break;
    case blink::kWebAXEventShow:
      event_name = "Show";
      break;
    case blink::kWebAXEventTextChanged:
      event_name = "TextChanged";
      break;
    case blink::kWebAXEventValueChanged:
      event_name = "ValueChanged";
      break;
    default:
      event_name = "Unknown";
      break;
  }

  AccessibilityController* accessibility_controller =
      web_view_test_proxy_base_->accessibility_controller();
  accessibility_controller->NotificationReceived(obj, event_name);
  if (accessibility_controller->ShouldLogAccessibilityEvents()) {
    std::string message("AccessibilityNotification - ");
    message += event_name;

    blink::WebNode node = obj.GetNode();
    if (!node.IsNull() && node.IsElementNode()) {
      blink::WebElement element = node.To<blink::WebElement>();
      if (element.HasAttribute("id")) {
        message += " - id:";
        message += element.GetAttribute("id").Utf8().data();
      }
    }

    delegate_->PrintMessage(message + "\n");
  }
}

void WebFrameTestClient::DidChangeSelection(bool is_empty_callback) {
  if (test_runner()->shouldDumpEditingCallbacks())
    delegate_->PrintMessage(
        "EDITING DELEGATE: "
        "webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
}

void WebFrameTestClient::DidChangeContents() {
  if (test_runner()->shouldDumpEditingCallbacks())
    delegate_->PrintMessage(
        "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
}

blink::WebPlugin* WebFrameTestClient::CreatePlugin(
    const blink::WebPluginParams& params) {
  blink::WebLocalFrame* frame = web_frame_test_proxy_base_->web_frame();
  if (TestPlugin::IsSupportedMimeType(params.mime_type))
    return TestPlugin::Create(params, delegate_, frame);
  return delegate_->CreatePluginPlaceholder(params);
}

void WebFrameTestClient::ShowContextMenu(
    const blink::WebContextMenuData& context_menu_data) {
  delegate_->GetWebWidgetTestProxyBase(web_frame_test_proxy_base_->web_frame())
      ->event_sender()
      ->SetContextMenuData(context_menu_data);
}

void WebFrameTestClient::DownloadURL(
    const blink::WebURLRequest& request,
    mojo::ScopedMessagePipeHandle blob_url_token) {
  if (test_runner()->shouldWaitUntilExternalURLLoad()) {
    delegate_->PrintMessage(std::string("Download started\n"));
    delegate_->TestFinished();
  }
}

void WebFrameTestClient::LoadErrorPage(int reason) {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    delegate_->PrintMessage(base::StringPrintf(
        "- loadErrorPage: %s\n", net::ErrorToString(reason).c_str()));
  }
}

void WebFrameTestClient::DidStartProvisionalLoad(
    blink::WebDocumentLoader* document_loader,
    blink::WebURLRequest& request) {
  // PlzNavigate
  // A provisional load notification is received when a frame navigation is
  // sent to the browser. We don't want to log it again during commit.
  if (delegate_->IsNavigationInitiatedByRenderer(request))
    return;

  test_runner()->tryToSetTopLoadingFrame(
      web_frame_test_proxy_base_->web_frame());

  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didStartProvisionalLoadForFrame\n");
  }

  if (test_runner()->shouldDumpUserGestureInFrameLoadCallbacks()) {
    PrintFrameuserGestureStatus(delegate_,
                                web_frame_test_proxy_base_->web_frame(),
                                " - in didStartProvisionalLoadForFrame\n");
  }
}

void WebFrameTestClient::DidReceiveServerRedirectForProvisionalLoad() {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(
        " - didReceiveServerRedirectForProvisionalLoadForFrame\n");
  }
}

void WebFrameTestClient::DidFailProvisionalLoad(
    const blink::WebURLError& error,
    blink::WebHistoryCommitType commit_type) {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didFailProvisionalLoadWithError\n");
  }
}

void WebFrameTestClient::DidCommitProvisionalLoad(
    const blink::WebHistoryItem& history_item,
    blink::WebHistoryCommitType history_type,
    blink::WebGlobalObjectReusePolicy) {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didCommitLoadForFrame\n");
  }
}

void WebFrameTestClient::DidFinishSameDocumentNavigation(
    const blink::WebHistoryItem& history_item,
    blink::WebHistoryCommitType history_type,
    bool content_initiated) {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didCommitLoadForFrame\n");
  }
}

void WebFrameTestClient::DidReceiveTitle(const blink::WebString& title,
                                         blink::WebTextDirection direction) {
  if (test_runner()->shouldDumpFrameLoadCallbacks() &&
      web_frame_test_proxy_base_->web_frame()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(std::string(" - didReceiveTitle: ") + title.Utf8() +
                            "\n");
  }

  if (test_runner()->shouldDumpTitleChanges())
    delegate_->PrintMessage(std::string("TITLE CHANGED: '") + title.Utf8() +
                            "'\n");
}

void WebFrameTestClient::DidChangeIcon(blink::WebIconURL::Type icon_type) {
  if (test_runner()->shouldDumpIconChanges()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(std::string(" - didChangeIcons\n"));
  }
}

void WebFrameTestClient::DidFinishDocumentLoad() {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didFinishDocumentLoadForFrame\n");
  }
}

void WebFrameTestClient::DidHandleOnloadEvents() {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didHandleOnloadEventsForFrame\n");
  }
}

void WebFrameTestClient::DidFailLoad(const blink::WebURLError& error,
                                     blink::WebHistoryCommitType commit_type) {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didFailLoadWithError\n");
  }
}

void WebFrameTestClient::DidFinishLoad() {
  if (test_runner()->shouldDumpFrameLoadCallbacks()) {
    PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame());
    delegate_->PrintMessage(" - didFinishLoadForFrame\n");
  }
}

void WebFrameTestClient::DidStopLoading() {
  test_runner()->tryToClearTopLoadingFrame(
      web_frame_test_proxy_base_->web_frame());
}

void WebFrameTestClient::DidDetectXSS(const blink::WebURL& insecure_url,
                                      bool did_block_entire_page) {
  if (test_runner()->shouldDumpFrameLoadCallbacks())
    delegate_->PrintMessage("didDetectXSS\n");
}

void WebFrameTestClient::DidDispatchPingLoader(const blink::WebURL& url) {
  if (test_runner()->shouldDumpPingLoaderCallbacks())
    delegate_->PrintMessage(std::string("PingLoader dispatched to '") +
                            URLDescription(url).c_str() + "'.\n");
}

void WebFrameTestClient::WillSendRequest(blink::WebURLRequest& request) {
  // PlzNavigate
  // Navigation requests initiated by the renderer will have been logged when
  // the navigation was sent to the browser. Please see
  // the RenderFrameImpl::BeginNavigation() function.
  if (delegate_->IsNavigationInitiatedByRenderer(request))
    return;
  // Need to use GURL for host() and SchemeIs()
  GURL url = request.Url();
  std::string request_url = url.possibly_invalid_spec();

  GURL main_document_url = request.SiteForCookies();

  if (test_runner()->shouldDumpResourceLoadCallbacks()) {
    delegate_->PrintMessage(DescriptionSuitableForTestResult(request_url));
    delegate_->PrintMessage(" - willSendRequest <NSURLRequest URL ");
    delegate_->PrintMessage(
        DescriptionSuitableForTestResult(request_url).c_str());
    delegate_->PrintMessage(", main document URL ");
    delegate_->PrintMessage(URLDescription(main_document_url).c_str());
    delegate_->PrintMessage(", http method ");
    delegate_->PrintMessage(request.HttpMethod().Utf8().data());
    delegate_->PrintMessage(">\n");
  }

  if (test_runner()->httpHeadersToClear()) {
    for (const std::string& header : *test_runner()->httpHeadersToClear())
      request.ClearHTTPHeaderField(blink::WebString::FromUTF8(header));
  }

  std::string host = url.host();
  if (!host.empty() &&
      (url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) {
    if (!IsLocalHost(host) && !IsTestHost(host) &&
        !HostIsUsedBySomeTestsToGenerateError(host) &&
        ((!main_document_url.SchemeIs(url::kHttpScheme) &&
          !main_document_url.SchemeIs(url::kHttpsScheme)) ||
         IsLocalHost(main_document_url.host())) &&
        !delegate_->AllowExternalPages()) {
      delegate_->PrintMessage(std::string("Blocked access to external URL ") +
                              request_url + "\n");
      BlockRequest(request);
      return;
    }
  }

  // Set the new substituted URL.
  request.SetURL(delegate_->RewriteLayoutTestsURL(
      request.Url().GetString().Utf8(),
      test_runner()->is_web_platform_tests_mode()));
}

void WebFrameTestClient::DidReceiveResponse(
    const blink::WebURLResponse& response) {
  if (test_runner()->shouldDumpResourceLoadCallbacks()) {
    delegate_->PrintMessage(DescriptionSuitableForTestResult(
        GURL(response.Url()).possibly_invalid_spec()));
    delegate_->PrintMessage(" - didReceiveResponse ");
    PrintResponseDescription(delegate_, response);
    delegate_->PrintMessage("\n");
  }
  if (test_runner()->shouldDumpResourceResponseMIMETypes()) {
    GURL url = response.Url();
    blink::WebString mime_type = response.MimeType();
    delegate_->PrintMessage(url.ExtractFileName());
    delegate_->PrintMessage(" has MIME type ");
    // Simulate NSURLResponse's mapping of empty/unknown MIME types to
    // application/octet-stream
    delegate_->PrintMessage(mime_type.IsEmpty() ? "application/octet-stream"
                                                : mime_type.Utf8().data());
    delegate_->PrintMessage("\n");
  }
}

void WebFrameTestClient::DidAddMessageToConsole(
    const blink::WebConsoleMessage& message,
    const blink::WebString& source_name,
    unsigned source_line,
    const blink::WebString& stack_trace) {
  if (!test_runner()->ShouldDumpConsoleMessages())
    return;
  std::string level;
  switch (message.level) {
    case blink::WebConsoleMessage::kLevelVerbose:
      level = "DEBUG";
      break;
    case blink::WebConsoleMessage::kLevelInfo:
      level = "MESSAGE";
      break;
    case blink::WebConsoleMessage::kLevelWarning:
      level = "WARNING";
      break;
    case blink::WebConsoleMessage::kLevelError:
      level = "ERROR";
      break;
    default:
      level = "MESSAGE";
  }
  std::string console_message(std::string("CONSOLE ") + level + ": ");
  if (source_line) {
    console_message += base::StringPrintf("line %d: ", source_line);
  }
  // Console messages shouldn't be included in the expected output for
  // web-platform-tests because they may create non-determinism not
  // intended by the test author. They are still included in the stderr
  // output for debug purposes.
  bool dump_to_stderr = test_runner()->is_web_platform_tests_mode();
  if (!message.text.IsEmpty()) {
    std::string new_message;
    new_message = message.text.Utf8();
    size_t file_protocol = new_message.find("file://");
    if (file_protocol != std::string::npos) {
      new_message = new_message.substr(0, file_protocol) +
                    URLSuitableForTestResult(new_message.substr(file_protocol));
    }
    console_message += new_message;
  }
  console_message += "\n";

  if (dump_to_stderr) {
    delegate_->PrintMessageToStderr(console_message);
  } else {
    delegate_->PrintMessage(console_message);
  }
}

blink::WebNavigationPolicy WebFrameTestClient::DecidePolicyForNavigation(
    const blink::WebFrameClient::NavigationPolicyInfo& info) {
  // PlzNavigate
  // Navigation requests initiated by the renderer have checked navigation
  // policy when the navigation was sent to the browser. Some layout tests
  // expect that navigation policy is only checked once.
  if (delegate_->IsNavigationInitiatedByRenderer(info.url_request))
    return info.default_policy;

  if (test_runner()->shouldDumpNavigationPolicy()) {
    delegate_->PrintMessage("Default policy for navigation to '" +
                            URLDescription(info.url_request.Url()) + "' is '" +
                            WebNavigationPolicyToString(info.default_policy) +
                            "'\n");
  }

  blink::WebNavigationPolicy result;
  if (!test_runner()->policyDelegateEnabled())
    return info.default_policy;

  delegate_->PrintMessage(
      std::string("Policy delegate: attempt to load ") +
      URLDescription(info.url_request.Url()) + " with navigation type '" +
      WebNavigationTypeToString(info.navigation_type) + "'\n");
  if (test_runner()->policyDelegateIsPermissive())
    result = blink::kWebNavigationPolicyCurrentTab;
  else
    result = blink::kWebNavigationPolicyIgnore;

  if (test_runner()->policyDelegateShouldNotifyDone()) {
    test_runner()->policyDelegateDone();
    result = blink::kWebNavigationPolicyIgnore;
  }

  return result;
}

void WebFrameTestClient::CheckIfAudioSinkExistsAndIsAuthorized(
    const blink::WebString& sink_id,
    blink::WebSetSinkIdCallbacks* web_callbacks) {
  std::unique_ptr<blink::WebSetSinkIdCallbacks> callback(web_callbacks);
  std::string device_id = sink_id.Utf8();
  if (device_id == "valid" || device_id.empty())
    callback->OnSuccess();
  else if (device_id == "unauthorized")
    callback->OnError(blink::WebSetSinkIdError::kNotAuthorized);
  else
    callback->OnError(blink::WebSetSinkIdError::kNotFound);
}

blink::WebSpeechRecognizer* WebFrameTestClient::SpeechRecognizer() {
  return test_runner()->getMockWebSpeechRecognizer();
}

void WebFrameTestClient::DidClearWindowObject() {
  blink::WebLocalFrame* frame = web_frame_test_proxy_base_->web_frame();
  web_view_test_proxy_base_->test_interfaces()->BindTo(frame);
  web_view_test_proxy_base_->BindTo(frame);
  delegate_->GetWebWidgetTestProxyBase(frame)->BindTo(frame);
}

bool WebFrameTestClient::RunFileChooser(
    const blink::WebFileChooserParams& params,
    blink::WebFileChooserCompletion* completion) {
  delegate_->PrintMessage("Mock: Opening a file chooser.\n");
  // FIXME: Add ability to set file names to a file upload control.
  return false;
}

blink::WebEffectiveConnectionType
WebFrameTestClient::GetEffectiveConnectionType() {
  return test_runner()->effective_connection_type();
}

TestRunner* WebFrameTestClient::test_runner() {
  return web_view_test_proxy_base_->test_interfaces()->GetTestRunner();
}

}  // namespace test_runner

{'repo_name': 'kiwibrowser/src', 'stars': '728', 'repo_language': 'None', 'file_name': '3db76d1dd7d3a759dccc3f8fa7f68675c080cb095e4881063a6b850fdd68b8bc.pem', 'mime_type': 'text/plain', 'hash': 6140311690508272488, 'source_dataset': 'data'}


/**
 * This package contains classes/interfaces that fetch status from monitored apps.
 */
package net.anotheria.moskito.extensions.monitoring.fetcher;

{'repo_name': 'anotheria/moskito', 'stars': '199', 'repo_language': 'HTML', 'file_name': 'FibonacciAction.java', 'mime_type': 'text/x-java', 'hash': -769436672062528939, 'source_dataset': 'data'}


/*
 * Copyright (c) 2009-2020 jMonkeyEngine
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.jme3.animation;

import com.jme3.export.*;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.util.TempVars;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
import java.util.BitSet;

/**
 * Contains a list of transforms and times for each keyframe.
 *
 * @author Kirill Vainer
 * @deprecated use {@link com.jme3.anim.AnimTrack}
 */
@Deprecated
public final class BoneTrack implements JmeCloneable, Track {

    /**
     * Bone index in the skeleton which this track affects.
     */
    private int targetBoneIndex;

    /**
     * Transforms and times for track.
     */
    private CompactVector3Array translations;
    private CompactQuaternionArray rotations;
    private CompactVector3Array scales;
    private float[] times;

    /**
     * Serialization-only. Do not use.
     */
    protected BoneTrack() {
    }

    /**
     * Creates a bone track for the given bone index
     * @param targetBoneIndex the bone index
     * @param times a float array with the time of each frame
     * @param translations the translation of the bone for each frame
     * @param rotations the rotation of the bone for each frame
     */
    public BoneTrack(int targetBoneIndex, float[] times, Vector3f[] translations, Quaternion[] rotations) {
        this.targetBoneIndex = targetBoneIndex;
        this.setKeyframes(times, translations, rotations);
    }

    /**
     * Creates a bone track for the given bone index
     * @param targetBoneIndex the bone index
     * @param times a float array with the time of each frame
     * @param translations the translation of the bone for each frame
     * @param rotations the rotation of the bone for each frame
     * @param scales the scale of the bone for each frame
     */
    public BoneTrack(int targetBoneIndex, float[] times, Vector3f[] translations, Quaternion[] rotations, Vector3f[] scales) {
        this.targetBoneIndex = targetBoneIndex;
        this.setKeyframes(times, translations, rotations, scales);
    }

    /**
     * Creates a bone track for the given bone index
     * @param targetBoneIndex the bone's index
     */
    public BoneTrack(int targetBoneIndex) {
        this.targetBoneIndex = targetBoneIndex;
    }

    /**
     * @return the bone index of this bone track.
     */
    public int getTargetBoneIndex() {
        return targetBoneIndex;
    }

    /**
     * return the array of rotations of this track
     * @return an array
     */
    public Quaternion[] getRotations() {
        return rotations.toObjectArray();
    }

    /**
     * returns the array of scales for this track
     * @return an array or null
     */
    public Vector3f[] getScales() {
        return scales == null ? null : scales.toObjectArray();
    }

    /**
     * returns the arrays of time for this track
     * @return the pre-existing array
     */
    public float[] getTimes() {
        return times;
    }

    /**
     * returns the array of translations of this track
     * @return an array
     */
    public Vector3f[] getTranslations() {
        return translations.toObjectArray();
    }

    /**
     * Set the translations and rotations for this bone track
     *
     * @param times the time of each frame, measured from the start of the track
     * (not null, length>0)
     * @param translations the translation of the bone for each frame (not null,
     * same length as times)
     * @param rotations the rotation of the bone for each frame (not null, same
     * length as times)
     */
    public void setKeyframes(float[] times, Vector3f[] translations, Quaternion[] rotations) {
        if (times.length == 0) {
            throw new RuntimeException("BoneTrack with no keyframes!");
        }

        assert translations != null;
        assert times.length == translations.length;
        assert rotations != null;
        assert times.length == rotations.length;

        this.times = times;
        this.translations = new CompactVector3Array();
        this.translations.add(translations);
        this.translations.freeze();
        this.rotations = new CompactQuaternionArray();
        this.rotations.add(rotations);
        this.rotations.freeze();
    }

    /**
     * Set the translations, rotations and scales for this bone track
     *
     * @param times the time of each frame, measured from the start of the track
     * (not null, length>0)
     * @param translations the translation of the bone for each frame (not null,
     * same length as times)
     * @param rotations the rotation of the bone for each frame (not null, same
     * length as times)
     * @param scales the scale of the bone for each frame (ignored if null)
     */
    public void setKeyframes(float[] times, Vector3f[] translations, Quaternion[] rotations, Vector3f[] scales) {
        this.setKeyframes(times, translations, rotations);
        if (scales != null) {
            assert times.length == scales.length;
            this.scales = new CompactVector3Array();
            this.scales.add(scales);
            this.scales.freeze();
        }
    }

    /**
     *
     * Modify the bone which this track modifies in the skeleton to contain
     * the correct animation transforms for a given time.
     * The transforms can be interpolated in some method from the keyframes.
     *
     * @param time the current time of the animation
     * @param weight the weight of the animation
     * @param control
     * @param channel
     * @param vars
     */
    @Override
    public void setTime(float time, float weight, AnimControl control, AnimChannel channel, TempVars vars) {
        BitSet affectedBones = channel.getAffectedBones();
        if (affectedBones != null && !affectedBones.get(targetBoneIndex)) {
            return;
        }

        Bone target = control.getSkeleton().getBone(targetBoneIndex);

        Vector3f tempV = vars.vect1;
        Vector3f tempS = vars.vect2;
        Quaternion tempQ = vars.quat1;
        Vector3f tempV2 = vars.vect3;
        Vector3f tempS2 = vars.vect4;
        Quaternion tempQ2 = vars.quat2;

        int lastFrame = times.length - 1;
        if (time < 0 || lastFrame == 0) {
            rotations.get(0, tempQ);
            translations.get(0, tempV);
            if (scales != null) {
                scales.get(0, tempS);
            }
        } else if (time >= times[lastFrame]) {
            rotations.get(lastFrame, tempQ);
            translations.get(lastFrame, tempV);
            if (scales != null) {
                scales.get(lastFrame, tempS);
            }
        } else {
            int startFrame = 0;
            int endFrame = 1;
            // use lastFrame so we never overflow the array
            int i;
            for (i = 0; i < lastFrame && times[i] < time; i++) {
                startFrame = i;
                endFrame = i + 1;
            }

            float blend = (time - times[startFrame])
                    / (times[endFrame] - times[startFrame]);

            rotations.get(startFrame, tempQ);
            translations.get(startFrame, tempV);
            if (scales != null) {
                scales.get(startFrame, tempS);
            }
            rotations.get(endFrame, tempQ2);
            translations.get(endFrame, tempV2);
            if (scales != null) {
                scales.get(endFrame, tempS2);
            }
            tempQ.nlerp(tempQ2, blend);
            tempV.interpolateLocal(tempV2, blend);
            tempS.interpolateLocal(tempS2, blend);
        }

//        if (weight != 1f) {
            target.blendAnimTransforms(tempV, tempQ, scales != null ? tempS : null, weight);
//        } else {
//            target.setAnimTransforms(tempV, tempQ, scales != null ? tempS : null);
//        }
    }

    /**
     * @return the length of the track
     */
    @Override
    public float getLength() {
        return times == null ? 0 : times[times.length - 1] - times[0];
    }

    @Override
    public float[] getKeyFrameTimes() {
        return times;
    }

    /**
     * Create a deep clone of this track.
     *
     * @return a new track
     */
    @Override
    public BoneTrack clone() {
        return Cloner.deepClone(this);
    }

    /**
     * Create a shallow clone for the JME cloner.
     *
     * @return a new track
     */
    @Override
    public BoneTrack jmeClone() {
        try {
            return (BoneTrack) super.clone();
        } catch (CloneNotSupportedException exception) {
            throw new RuntimeException("Can't clone track", exception);
        }
    }

    /**
     * Callback from {@link com.jme3.util.clone.Cloner} to convert this
     * shallow-cloned track into a deep-cloned one, using the specified cloner
     * to resolve copied fields.
     *
     * @param cloner the cloner currently cloning this control (not null)
     * @param original the track from which this track was shallow-cloned
     * (unused)
     */
    @Override
    public void cloneFields(Cloner cloner, Object original) {
        translations = cloner.clone(translations);
        rotations = cloner.clone(rotations);
        scales = cloner.clone(scales);
        times = cloner.clone(times);
    }

    @Override
    public void write(JmeExporter ex) throws IOException {
        OutputCapsule oc = ex.getCapsule(this);
        oc.write(targetBoneIndex, "boneIndex", 0);
        oc.write(translations, "translations", null);
        oc.write(rotations, "rotations", null);
        oc.write(times, "times", null);
        oc.write(scales, "scales", null);
    }

    @Override
    public void read(JmeImporter im) throws IOException {
        InputCapsule ic = im.getCapsule(this);
        targetBoneIndex = ic.readInt("boneIndex", 0);

        translations = (CompactVector3Array) ic.readSavable("translations", null);
        rotations = (CompactQuaternionArray) ic.readSavable("rotations", null);
        times = ic.readFloatArray("times", null);
        scales = (CompactVector3Array) ic.readSavable("scales", null);

        //Backward compatibility for old j3o files generated before revision 6807
        if (im.getFormatVersion() == 0){
            if (translations == null) {
                Savable[] sav = ic.readSavableArray("translations", null);
                if (sav != null) {
                    translations = new CompactVector3Array();
                    Vector3f[] transCopy = new Vector3f[sav.length];
                    System.arraycopy(sav, 0, transCopy, 0, sav.length);
                    translations.add(transCopy);
                    translations.freeze();
                }
            }
            if (rotations == null) {
                Savable[] sav = ic.readSavableArray("rotations", null);
                if (sav != null) {
                    rotations = new CompactQuaternionArray();
                    Quaternion[] rotCopy = new Quaternion[sav.length];
                    System.arraycopy(sav, 0, rotCopy, 0, sav.length);
                    rotations.add(rotCopy);
                    rotations.freeze();
                }
            }
        }
    }

    public void setTime(float time, float weight, AnimControl control, AnimChannel channel) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

{'repo_name': 'jMonkeyEngine/jmonkeyengine', 'stars': '2378', 'repo_language': 'Java', 'file_name': 'Android.mk', 'mime_type': 'text/html', 'hash': -3197342395914181985, 'source_dataset': 'data'}


#
# Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#

import os ;

compile config.cpp :    <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile core.cpp :      <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile exemplars.cpp : <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile http.cpp :      <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile version.cpp :   <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile websocket.cpp : <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

compile zlib.cpp :      <variant>coverage:<build>no
                        <variant>ubasan:<build>no : ;

build-project benchmarks ;
build-project common ;
build-project core ;
build-project http ;
build-project server ;
build-project websocket ;
build-project zlib ;

{'repo_name': 'ChainSQL/chainsqld', 'stars': '142', 'repo_language': 'C++', 'file_name': 'deploy.md', 'mime_type': 'text/plain', 'hash': 2685683356676267427, 'source_dataset': 'data'}


# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc

from hfc.protos.common import common_pb2 as hfc_dot_protos_dot_common_dot_common__pb2
from hfc.protos.peer import events_pb2 as hfc_dot_protos_dot_peer_dot_events__pb2

class DeliverStub(object):
  # missing associated documentation comment in .proto file
  pass

  def __init__(self, channel):
    """Constructor.

    Args:
      channel: A grpc.Channel.
    """
    self.Deliver = channel.stream_stream(
        '/protos.Deliver/Deliver',
        request_serializer=hfc_dot_protos_dot_common_dot_common__pb2.Envelope.SerializeToString,
        response_deserializer=hfc_dot_protos_dot_peer_dot_events__pb2.DeliverResponse.FromString,
        )
    self.DeliverFiltered = channel.stream_stream(
        '/protos.Deliver/DeliverFiltered',
        request_serializer=hfc_dot_protos_dot_common_dot_common__pb2.Envelope.SerializeToString,
        response_deserializer=hfc_dot_protos_dot_peer_dot_events__pb2.DeliverResponse.FromString,
        )

class DeliverServicer(object):
  # missing associated documentation comment in .proto file
  pass

  def Deliver(self, request_iterator, context):
    """deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with
    Payload data as a marshaled orderer.SeekInfo message,
    then a stream of block replies is received
    """
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def DeliverFiltered(self, request_iterator, context):
    """deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with
    Payload data as a marshaled orderer.SeekInfo message,
    then a stream of **filtered** block replies is received
    """
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

def add_DeliverServicer_to_server(servicer, server):
  rpc_method_handlers = {
      'Deliver': grpc.stream_stream_rpc_method_handler(
          servicer.Deliver,
          request_deserializer=hfc_dot_protos_dot_common_dot_common__pb2.Envelope.FromString,
          response_serializer=hfc_dot_protos_dot_peer_dot_events__pb2.DeliverResponse.SerializeToString,
      ),
      'DeliverFiltered': grpc.stream_stream_rpc_method_handler(
          servicer.DeliverFiltered,
          request_deserializer=hfc_dot_protos_dot_common_dot_common__pb2.Envelope.FromString,
          response_serializer=hfc_dot_protos_dot_peer_dot_events__pb2.DeliverResponse.SerializeToString,
      ),
  }
  generic_handler = grpc.method_handlers_generic_handler(
      'protos.Deliver', rpc_method_handlers)
  server.add_generic_rpc_handlers((generic_handler,))

{'repo_name': 'hyperledger/fabric-sdk-py', 'stars': '270', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': 544260758503140913, 'source_dataset': 'data'}


/* 2-D two-components wavefield modeling based on original elastic anisotropic displacement
  wave equation and P-SV separation using low-rank symbol approximation in 2D TTI media.

   Authors: Jiubing Cheng (Tongji University) and Sergey Fomel (The University of Texas at Austin)

   Copyright (C) 2012 Tongji University, Shanghai, China

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#include <rsf.hh>
#include <assert.h>

/* low rank decomposition  */
#include "vecmatop.hh"
#include "serialize.hh"

using namespace std;

/* prepared head files by myself */
#include "_cjb.h"

/*#include "_fd.h"
 * when _fd.h has declared "m", we met compiling error at "m2=mid.m()";
 * "expected unqualified-id before numeric constant"
*/
#ifndef M
#define M 5   /* 10th-order finite-difference: accuracy is 2*M */
#endif
#ifndef Mix
#define Mix 5   /* order of finite-difference for mix-derivative (2*mix) */
#endif

/* head files aumatically produced from C programs */
extern "C"{
#include "zero.h"
#include "ricker.h"
#include "kykxkztaper.h"
#include "fdcoef.h"
#include "eigen2x2.h"
#include "fwpttielastic.h"
#include "seplowrank.h"
}

static std::valarray<float> vp, vs, ep, de, th;

static std::valarray<double> sinx, cosx, rkk;

/* dual-domain wave-mode separation operator based on low-rank decomp. */
static int samplexp(vector<int>& rs, vector<int>& cs, DblNumMat& resx);
static int samplezp(vector<int>& rs, vector<int>& cs, DblNumMat& resz);
static int samplexs(vector<int>& rs, vector<int>& cs, DblNumMat& resx);
static int samplezs(vector<int>& rs, vector<int>& cs, DblNumMat& resz);

static void map2d1d(float *d, DblNumMat mat, int m, int n);

static void polxp2dtti(float **ap, int nx, int nz, int im);
static void polzp2dtti(float **ap, int nx, int nz, int im);
static void polxs2dtti(float **ap, int nx, int nz, int im);
static void polzs2dtti(float **ap, int nx, int nz, int im);

/*****************************************************************************************/
int main(int argc, char* argv[])
{
   sf_init(argc,argv);

   clock_t t1, t2, t3, t4, t5, t44;
   float   timespent;

   t1=clock();

   iRSF par(0);
   int seed;
   par.get("seed",seed,time(NULL)); // seed for random number generator
   srand48(seed);

   float eps;
   par.get("eps",eps,1.e-6); // tolerance

   int npk;
   par.get("npk",npk,20); // maximum rank

   int   ns;
   float dt;

   par.get("ns",ns);
   par.get("dt",dt);

   int ireconstruct;   // flag for reconstruct the W matrix or not
   par.get("ireconstruct",ireconstruct);

   sf_warning("ns=%d dt=%f",ns,dt);
   sf_warning("npk=%d ",npk);
   sf_warning("eps=%f",eps);
   sf_warning("ireconstruct=%d ",ireconstruct);
   sf_warning("read velocity model parameters");

   /* setup I files */
   iRSF vp0, vs0("vs0"), epsi("epsi"), del("del"), the("the");
   /* Read/Write axes */
   int nxv, nzv;
   vp0.get("n1",nzv);
   vp0.get("n2",nxv);

   float az, ax;
   vp0.get("o1",az);
   vp0.get("o2",ax);

   float fx, fz;
   fx=ax*1000.0;
   fz=az*1000.0;

   float dx, dz;
   vp0.get("d1",az);
   vp0.get("d2",ax);
   dz = az*1000.0;
   dx = ax*1000.0;

   /* wave modeling space */
   int nx, nz, nxz;
   nx=nxv;
   nz=nzv;
   nxz=nx*nz;

   vp.resize(nxz);
   vs.resize(nxz);
   ep.resize(nxz);
   de.resize(nxz);
   th.resize(nxz);

   vp0>>vp;
   vs0>>vs;
   epsi>>ep;
   del>>de;
   the>>th;

   for(int i=0;i<nxz;i++)
      th[i] *= PI/180.0;

   /* Fourier spectra demension */
   int nkz,nkx,nk;
   nkx=nx;
   nkz=nz;
   nk = nkx*nkz;

   float dkz,dkx,kz0,kx0;

   dkx=2*PI/dx/nx;
   dkz=2*PI/dz/nz;

   kx0=-PI/dx;
   kz0=-PI/dz;

   sinx.resize(nk);
   cosx.resize(nk);
   rkk.resize(nk);

   double kx, kz, k2, rk;
   int    i=0, j=0, k=0, ix, iz;

   for(ix=0; ix < nkx; ix++)
   {
       kx = kx0+ix*dkx;
       if(kx==0.0) kx=0.0000000001*dkx;

       for (iz=0; iz < nkz; iz++)
       {
            kz = kz0+iz*dkz;
            if(kz==0.0) kz=0.0000000001*dkz;

            k2 = kx*kx+kz*kz;
            rk = sqrt(k2);

            sinx[i] = kx/rk;
            cosx[i] = kz/rk;
            rkk[i] = rk;

            i++;
       }
   }

   t2=clock();
   timespent=(float)(t2-t1)/CLOCKS_PER_SEC;
   sf_warning("CPU time for prereparing for low-rank decomp: %f(second)",timespent);

   /*****************************************************************************
    *  Calculating polarization deviation operator for wave-mode separation
    * ***************************************************************************/
   vector<int> md(nxz), nd(nk);
   for (k=0; k < nxz; k++)  md[k] = k;
   for (k=0; k < nk; k++)  nd[k] = k;

   vector<int> lid, rid;
   DblNumMat mid, mat;

   /********* low rank decomposition p-wave, x-component **********/
   int   m2xp, n2xp, m2zp, n2zp;
   float *ldataxp, *fmidxp, *rdataxp;
   float *ldatazp, *fmidzp, *rdatazp;

   iC( ddlowrank(nxz,nk,samplexp,eps,npk,lid,rid,mid) );
   m2xp=mid.m();
   n2xp=mid.n();
   sf_warning("m2xp=%d n2xp=%d",m2xp, n2xp);

   fmidxp  = sf_floatalloc(m2xp*n2xp);
   ldataxp = sf_floatalloc(nxz*m2xp);
   rdataxp = sf_floatalloc(n2xp*nk);

   map2d1d(fmidxp, mid, m2xp, n2xp);

   iC ( samplexp(md,lid,mat) );
   map2d1d(ldataxp, mat, nxz, m2xp);

   iC ( samplexp(rid,nd,mat) );
   map2d1d(rdataxp, mat, n2xp, nk);

   /********* reconsturct W-matrix for checking **********/
   float **w;
   float **ap;
   std::valarray<float> wx1(nk), wx2(nk);
   if(ireconstruct==1)
   {
      w = sf_floatalloc2(nk,nxz);

      sf_warning("reconstruct x-component operators based on low-rank approx.");
      reconstruct(w, ldataxp, fmidxp, rdataxp, nxz, nk, m2xp, n2xp);

      /* error check between accurate and low-rank approx. */
      float sumall=0.0;
      ap=sf_floatalloc2(nz, nx);

      oRSF Errxp1("Errxp1");
      oRSF Errxp2("Errxp2");

      Errxp1.put("n1",nkz);
      Errxp1.put("n2",nkx);
      Errxp1.put("d1",dkz);
      Errxp1.put("d2",dkx);
      Errxp1.put("o1",kz0);
      Errxp1.put("o2",kx0);

      Errxp1.put("label1","kz");
      Errxp1.put("label2","kx");
      Errxp1.put("unit1","2*pi/m");
      Errxp1.put("unit2","2*pi/m");

      Errxp2.put("n1",nkz);
      Errxp2.put("n2",nkx);
      Errxp2.put("d1",dkz);
      Errxp2.put("d2",dkx);
      Errxp2.put("o1",kz0);
      Errxp2.put("o2",kx0);

      Errxp2.put("label1","kz");
      Errxp2.put("label2","kx");
      Errxp2.put("unit1","2*pi/m");
      Errxp2.put("unit2","2*pi/m");

      for(int im=0;im<nxz;im++){
        if(im%200==0) sf_warning("---------------------------------------- finish %d percent ---",(int)(im*100.0/nxz));

        //calculate P-wave's polarization operators directly for X-component
        polxp2dtti(ap, nx, nz, im);

        float sum=0.0;
        int k=0;
        for(i=0;i<nx;i++)
        for(j=0;j<nz;j++)
        {
           float err=w[im][k]-ap[i][j];
           //if(fabs(err/ap[i][j])>0.01) sf_warning("Relative Error > 1%:  im=%d i=%d j=%d ikx=%d ikz=%d w=%f a=%f",im,i,j,k/nkz,k%nkz,w[im][k], ap[i][j]);
           sum += err*err;
           if(im==(nx/2-1)*nz+nz/4-1) wx1[k] = err;
           if(im==(nx/2-1)*nz+(nz*3)/4-1) wx2[k] = err;
           k++;
         }
         if(im%200==0) sf_warning("X-comp.Low-rank error: im=%d L2-norm=%20.18f",im, sum/nxz);
         sumall += sum/nxz;
       }// im loop
       sf_warning("X-component Low-rank average L2-norm error: %20.18f",sumall);

       Errxp1 << wx1;
       Errxp2 << wx2;

      oRSF Polxp1("Polxp1");
      oRSF Polxp2("Polxp2");

      Polxp1.put("n1",nkz);
      Polxp1.put("n2",nkx);
      Polxp1.put("d1",dkz);
      Polxp1.put("d2",dkx);
      Polxp1.put("o1",kz0);
      Polxp1.put("o2",kx0);

      Polxp1.put("label1","kz");
      Polxp1.put("label2","kx");
      Polxp1.put("unit1","2*pi/m");
      Polxp1.put("unit2","2*pi/m");

      Polxp2.put("n1",nkz);
      Polxp2.put("n2",nkx);
      Polxp2.put("d1",dkz);
      Polxp2.put("d2",dkx);
      Polxp2.put("o1",kz0);
      Polxp2.put("o2",kx0);

      Polxp2.put("label1","kz");
      Polxp2.put("label2","kx");
      Polxp2.put("unit1","2*pi/m");
      Polxp2.put("unit2","2*pi/m");

      for(i=0;i<nxz;i++){
         wx1[i]=w[(nx/2-1)*nz+nz/4-1][i];
         wx2[i]=w[(nx/2-1)*nz+(nz*3)/4-1][i];
      }

      Polxp1 << wx1;
      Polxp2 << wx2;

   }//ireconstruct==1

   /********* low rank decomposition p-wave, z-component **********/
   iC( ddlowrank(nxz,nk,samplezp,eps,npk,lid,rid,mid) );
   m2zp=mid.m();
   n2zp=mid.n();
   sf_warning("m2zp=%d n2zp=%d",m2zp, n2zp);

   fmidzp  = sf_floatalloc(m2zp*n2zp);
   ldatazp = sf_floatalloc(nxz*m2zp);
   rdatazp = sf_floatalloc(n2zp*nk);

   map2d1d(fmidzp, mid, m2zp, n2zp);

   iC ( samplezp(md,lid,mat) );
   map2d1d(ldatazp, mat, nxz, m2zp);

   iC ( samplezp(rid,nd,mat) );
   map2d1d(rdatazp, mat, n2zp, nk);

   /********* reconsturct W-matrix for checking **********/
   std::valarray<float> wz1(nk), wz2(nk);
   if(ireconstruct==1)
   {
      sf_warning("reconstruct z-component operators based on low-rank approx.");
      reconstruct(w, ldatazp, fmidzp, rdatazp, nxz, nk, m2zp, n2zp);

      /* error check between accurate and low-rank approx. */
      float sumall=0.0;

      oRSF Errzp1("Errzp1");
      oRSF Errzp2("Errzp2");

      Errzp1.put("n1",nkz);
      Errzp1.put("n2",nkx);
      Errzp1.put("d1",dkz);
      Errzp1.put("d2",dkx);
      Errzp1.put("o1",kz0);
      Errzp1.put("o2",kx0);

      Errzp1.put("label1","kz");
      Errzp1.put("label2","kx");
      Errzp1.put("unit1","2*pi/m");
      Errzp1.put("unit2","2*pi/m");

      Errzp2.put("n1",nkz);
      Errzp2.put("n2",nkx);
      Errzp2.put("d1",dkz);
      Errzp2.put("d2",dkx);
      Errzp2.put("o1",kz0);
      Errzp2.put("o2",kx0);

      Errzp2.put("label1","kz");
      Errzp2.put("label2","kx");
      Errzp2.put("unit1","2*pi/m");
      Errzp2.put("unit2","2*pi/m");

      for(int im=0;im<nxz;im++){
        if(im%200==0) sf_warning("---------------------------------------- finish %d percent ---",(int)(im*100.0/nxz));

        //calculate P-wave's polarization operators directly for X-component
        polzp2dtti(ap, nx, nz, im);

        float sum=0.0;
        int k=0;
        for(i=0;i<nx;i++)
        for(j=0;j<nz;j++)
        {
           float err=w[im][k]-ap[i][j];
           //if(fabs(err/ap[i][j])>0.01) sf_warning("Relative Error > 1%:  im=%d i=%d j=%d ikx=%d ikz=%d w=%f a=%f",im,i,j,k/nkz,k%nkz,w[im][k], ap[i][j]);
           sum += err*err;
           if(im==(nx/2-1)*nz+nz/4-1) wz1[k] = err;
           if(im==(nx/2-1)*nz+(nz*3)/4-1) wz2[k] = err;
           k++;
         }
         if(im%200==0) sf_warning("Z-comp.Low-rank error: im=%d L2-norm=%20.18f",im, sum/nxz);
         sumall += sum/nxz;
       }
       // im loop
       sf_warning("Z-component Low-rank average L2-norm error: %20.18f",sumall);

      Errzp1 << wz1;
      Errzp2 << wz2;

      oRSF Polzp1("Polzp1");
      oRSF Polzp2("Polzp2");

      Polzp1.put("n1",nkz);
      Polzp1.put("n2",nkx);
      Polzp1.put("d1",dkz);
      Polzp1.put("d2",dkx);
      Polzp1.put("o1",kz0);
      Polzp1.put("o2",kx0);

      Polzp1.put("label1","kz");
      Polzp1.put("label2","kx");
      Polzp1.put("unit1","2*pi/m");
      Polzp1.put("unit2","2*pi/m");

      Polzp2.put("n1",nkz);
      Polzp2.put("n2",nkx);
      Polzp2.put("d1",dkz);
      Polzp2.put("d2",dkx);
      Polzp2.put("o1",kz0);
      Polzp2.put("o2",kx0);

      Polzp2.put("label1","kz");
      Polzp2.put("label2","kx");
      Polzp2.put("unit1","2*pi/m");
      Polzp2.put("unit2","2*pi/m");

      for(i=0;i<nxz;i++){
         wz1[i]=w[(nx/2-1)*nz+nz/4-1][i];
         wz2[i]=w[(nx/2-1)*nz+(nz*3)/4-1][i];
      }

      Polzp1 << wz1;
      Polzp2 << wz2;

   }//ireconstruct==1

   /*****************************************************************************
   *  Calculating SV-wave polarization deviation operator for wave-mode separation
   * ***************************************************************************/
   /********* low rank decomposition SV-wave, x-component **********/
   int   m2xs, n2xs, m2zs, n2zs;
   float *ldataxs, *fmidxs, *rdataxs;
   float *ldatazs, *fmidzs, *rdatazs;

   iC( ddlowrank(nxz,nk,samplexs,eps,npk,lid,rid,mid) );
   m2xs=mid.m();
   n2xs=mid.n();
   sf_warning("m2xs=%d n2xs=%d",m2xs, n2xs);

   fmidxs  = sf_floatalloc(m2xs*n2xs);
   ldataxs = sf_floatalloc(nxz*m2xs);
   rdataxs = sf_floatalloc(n2xs*nk);

   map2d1d(fmidxs, mid, m2xs, n2xs);

   iC ( samplexs(md,lid,mat) );
   map2d1d(ldataxs, mat, nxz, m2xs);

   iC ( samplexs(rid,nd,mat) );
   map2d1d(rdataxs, mat, n2xs, nk);

   /********* reconsturct W-matrix for checking **********/
   if(ireconstruct==1)
   {
      sf_warning("reconstruct x-component operators based on low-rank approx.");
      reconstruct(w, ldataxs, fmidxs, rdataxs, nxz, nk, m2xs, n2xs);

      /* error check between accurate and low-rank approx. */
      float sumall=0.0;

      oRSF Errxs1("Errxs1");
      oRSF Errxs2("Errxs2");

      Errxs1.put("n1",nkz);
      Errxs1.put("n2",nkx);
      Errxs1.put("d1",dkz);
      Errxs1.put("d2",dkx);
      Errxs1.put("o1",kz0);
      Errxs1.put("o2",kx0);

      Errxs1.put("label1","kz");
      Errxs1.put("label2","kx");
      Errxs1.put("unit1","2*pi/m");
      Errxs1.put("unit2","2*pi/m");

      Errxs2.put("n1",nkz);
      Errxs2.put("n2",nkx);
      Errxs2.put("d1",dkz);
      Errxs2.put("d2",dkx);
      Errxs2.put("o1",kz0);
      Errxs2.put("o2",kx0);

      Errxs2.put("label1","kz");
      Errxs2.put("label2","kx");
      Errxs2.put("unit1","2*pi/m");
      Errxs2.put("unit2","2*pi/m");

      for(int im=0;im<nxz;im++){
        if(im%200==0) sf_warning("---------------------------------------- finish %d percent ---",(int)(im*100.0/nxz));

        //calculate P-wave's polarization operators directly for X-component
        polxs2dtti(ap, nx, nz, im);

        float sum=0.0;
        int k=0;
        for(i=0;i<nx;i++)
        for(j=0;j<nz;j++)
        {
           float err=w[im][k]-ap[i][j];
           //if(fabs(err/ap[i][j])>0.01) sf_warning("Relative Error > 1%:  im=%d i=%d j=%d ikx=%d ikz=%d w=%f a=%f",im,i,j,k/nkz,k%nkz,w[im][k], ap[i][j]);
           sum += err*err;
           if(im==(nx/2-1)*nz+nz/4-1) wx1[k] = err;
           if(im==(nx/2-1)*nz+(nz*3)/4-1) wx2[k] = err;
           k++;
         }
         if(im%200==0) sf_warning("X-comp.Low-rank error: im=%d L2-norm=%20.18f",im, sum/nxz);
         sumall += sum/nxz;
       }
       // im loop
       sf_warning("X-component Low-rank average L2-norm error: %20.18f",sumall);

      Errxs1 << wx1;
      Errxs2 << wx2;

      oRSF Polxs1("Polxs1");
      oRSF Polxs2("Polxs2");

      Polxs1.put("n1",nkz);
      Polxs1.put("n2",nkx);
      Polxs1.put("d1",dkz);
      Polxs1.put("d2",dkx);
      Polxs1.put("o1",kz0);
      Polxs1.put("o2",kx0);

      Polxs1.put("label1","kz");
      Polxs1.put("label2","kx");
      Polxs1.put("unit1","2*pi/m");
      Polxs1.put("unit2","2*pi/m");

      Polxs2.put("n1",nkz);
      Polxs2.put("n2",nkx);
      Polxs2.put("d1",dkz);
      Polxs2.put("d2",dkx);
      Polxs2.put("o1",kz0);
      Polxs2.put("o2",kx0);

      Polxs2.put("label1","kz");
      Polxs2.put("label2","kx");
      Polxs2.put("unit1","2*pi/m");
      Polxs2.put("unit2","2*pi/m");

      for(i=0;i<nxz;i++){
         wx1[i]=w[(nx/2-1)*nz+nz/4-1][i];
         wx2[i]=w[(nx/2-1)*nz+(nz*3)/4-1][i];
      }
      Polxs1 << wx1;
      Polxs2 << wx2;

   }//ireconstruct==1

   /********* low rank decomposition SV-wave, z-component **********/
   iC( ddlowrank(nxz,nk,samplezs,eps,npk,lid,rid,mid) );
   m2zs=mid.m();
   n2zs=mid.n();
   sf_warning("m2zs=%d n2zs=%d",m2zs, n2zs);

   fmidzs  = sf_floatalloc(m2zs*n2zs);
   ldatazs = sf_floatalloc(nxz*m2zs);
   rdatazs = sf_floatalloc(n2zs*nk);

   map2d1d(fmidzs, mid, m2zs, n2zs);

   iC ( samplezs(md,lid,mat) );
   map2d1d(ldatazs, mat, nxz, m2zs);

   iC ( samplezs(rid,nd,mat) );
   map2d1d(rdatazs, mat, n2zs, nk);

   /********* reconsturct W-matrix for checking **********/
   if(ireconstruct==1)
   {
      sf_warning("reconstruct z-component operators based on low-rank approx.");
      reconstruct(w, ldatazs, fmidzs, rdatazs, nxz, nk, m2zs, n2zs);

      /* error check between accurate and low-rank approx. */
      float sumall=0.0;

      oRSF Errzs1("Errzs1");
      oRSF Errzs2("Errzs2");

      Errzs1.put("n1",nkz);
      Errzs1.put("n2",nkx);
      Errzs1.put("d1",dkz);
      Errzs1.put("d2",dkx);
      Errzs1.put("o1",kz0);
      Errzs1.put("o2",kx0);

      Errzs1.put("label1","kz");
      Errzs1.put("label2","kx");
      Errzs1.put("unit1","2*pi/m");
      Errzs1.put("unit2","2*pi/m");

      Errzs2.put("n1",nkz);
      Errzs2.put("n2",nkx);
      Errzs2.put("d1",dkz);
      Errzs2.put("d2",dkx);
      Errzs2.put("o1",kz0);
      Errzs2.put("o2",kx0);

      Errzs2.put("label1","kz");
      Errzs2.put("label2","kx");
      Errzs2.put("unit1","2*pi/m");
      Errzs2.put("unit2","2*pi/m");

      for(int im=0;im<nxz;im++){
        if(im%200==0) sf_warning("---------------------------------------- finish %d percent ---",(int)(im*100.0/nxz));

        //calculate P-wave's polarization operators directly for X-component
        polzs2dtti(ap, nx, nz, im);

        float sum=0.0;
        int k=0;
        for(i=0;i<nx;i++)
        for(j=0;j<nz;j++)
        {
           float err=w[im][k]-ap[i][j];
           //if(fabs(err/ap[i][j])>0.01) sf_warning("Relative Error > 1%:  im=%d i=%d j=%d ikx=%d ikz=%d w=%f a=%f",im,i,j,k/nkz,k%nkz,w[im][k], ap[i][j]);
           sum += err*err;
           if(im==(nx/2-1)*nz+nz/4-1) wz1[k] = err;
           if(im==(nx/2-1)*nz+(nz*3)/4-1) wz2[k] = err;

           k++;
         }
         if(im%200==0) sf_warning("Z-comp.Low-rank error: im=%d L2-norm=%20.18f",im, sum/nxz);
         sumall += sum/nxz;
       }
       // im loop
       sf_warning("Z-component Low-rank average L2-norm error: %20.18f",sumall);

      Errzs1 << wz1;
      Errzs2 << wz2;

      oRSF Polzs1("Polzs1");
      oRSF Polzs2("Polzs2");

      Polzs1.put("n1",nkz);
      Polzs1.put("n2",nkx);
      Polzs1.put("d1",dkz);
      Polzs1.put("d2",dkx);
      Polzs1.put("o1",kz0);
      Polzs1.put("o2",kx0);

      Polzs1.put("label1","kz");
      Polzs1.put("label2","kx");
      Polzs1.put("unit1","2*pi/m");
      Polzs1.put("unit2","2*pi/m");

      Polzs2.put("n1",nkz);
      Polzs2.put("n2",nkx);
      Polzs2.put("d1",dkz);
      Polzs2.put("d2",dkx);
      Polzs2.put("o1",kz0);
      Polzs2.put("o2",kx0);

      Polzs2.put("label1","kz");
      Polzs2.put("label2","kx");
      Polzs2.put("unit1","2*pi/m");
      Polzs2.put("unit2","2*pi/m");

      for(i=0;i<nxz;i++){
         wz1[i]=w[(nx/2-1)*nz+nz/4-1][i];
         wz2[i]=w[(nx/2-1)*nz+(nz*3)/4-1][i];
      }
      Polzs1 << wz1;
      Polzs2 << wz2;

      free(*ap);
      free(*w);
   }//ireconstruct==1

   t3=clock();
   timespent=(float)(t3-t2)/CLOCKS_PER_SEC;
   sf_warning("CPU time for low-rank decomp: %f(second)",timespent);

   /****************End of Calculating Projection Deviation Operator****************/

   /****************begin to calculate wavefield****************/
   /****************begin to calculate wavefield****************/
   /*  wavelet parameter for source definition */
   float A, f0, t0;
   f0=30.0;
   t0=0.04;
   A=1;

   int nxpad, nzpad;
   nxpad=nx+2*M;
   nzpad=nz+2*M;

   sf_warning("fx=%f fz=%f dx=%f dz=%f",fx,fz,dx,dz);
   sf_warning("nx=%d nz=%d nxpad=%d nzpad=%d", nx,nz,nxpad,nzpad);

   int mm=2*M+1;

   float dt2=dt*dt;

   /* source definition */
   int ixs, izs, ixms, izms;
   ixs=nxv/2;
   izs=nzv/2;
   ixms=ixs+M;  /* source's x location */
   izms=izs+M;  /* source's z-location */

   /* setup I/O files */
   oRSF Elasticx("out"),Elasticz("Elasticz");
   oRSF ElasticSepP("ElasticSepP");
   oRSF ElasticSepSV("ElasticSepSV");

   Elasticx.put("n1",nkz);
   Elasticx.put("n2",nkx);
   Elasticx.put("d1",dz/1000);
   Elasticx.put("d2",dx/1000);
   Elasticx.put("o1",fz/1000);
   Elasticx.put("o2",fx/1000);

   Elasticz.put("n1",nkz);
   Elasticz.put("n2",nkx);
   Elasticz.put("d1",dz/1000);
   Elasticz.put("d2",dx/1000);
   Elasticz.put("o1",fz/1000);
   Elasticz.put("o2",fx/1000);

   ElasticSepP.put("n1",nkz);
   ElasticSepP.put("n2",nkx);
   ElasticSepP.put("d1",dz/1000);
   ElasticSepP.put("d2",dx/1000);
   ElasticSepP.put("o1",fz/1000);
   ElasticSepP.put("o2",fx/1000);

   ElasticSepSV.put("n1",nkz);
   ElasticSepSV.put("n2",nkx);
   ElasticSepSV.put("d1",dz/1000);
   ElasticSepSV.put("d2",dx/1000);
   ElasticSepSV.put("o1",fz/1000);
   ElasticSepSV.put("o2",fx/1000);

    float *coeff_2dx=sf_floatalloc(mm);
    float *coeff_2dz=sf_floatalloc(mm);
    float *coeff_1dx=sf_floatalloc(mm);
    float *coeff_1dz=sf_floatalloc(mm);

    coeff2d(coeff_2dx,dx);
    coeff2d(coeff_2dz,dz);
    coeff1dmix(coeff_1dx,dx);
    coeff1dmix(coeff_1dz,dz);

    float **p1=sf_floatalloc2(nzpad, nxpad);
    float **p2=sf_floatalloc2(nzpad, nxpad);
    float **p3=sf_floatalloc2(nzpad, nxpad);

    float **q1=sf_floatalloc2(nzpad, nxpad);
    float **q2=sf_floatalloc2(nzpad, nxpad);
    float **q3=sf_floatalloc2(nzpad, nxpad);

    zero2float(p1, nzpad, nxpad);
    zero2float(p2, nzpad, nxpad);
    zero2float(p3, nzpad, nxpad);

    zero2float(q1, nzpad, nxpad);
    zero2float(q2, nzpad, nxpad);
    zero2float(q3, nzpad, nxpad);

    sf_warning("==================================================");
    sf_warning("==  Porpagation Using Elastic anisotropic Eq.   ==");
    sf_warning("==================================================");

    std::valarray<float> x(nxz);
    std::valarray<float> y(nxz);
    std::valarray<float> z(nxz);

    float **vpp, **vss, **epp, **dee, **thee;

    vpp=sf_floatalloc2(nz,nx);
    vss=sf_floatalloc2(nz,nx);
    epp=sf_floatalloc2(nz,nx);
    dee=sf_floatalloc2(nz,nx);
    dee=sf_floatalloc2(nz,nx);
    thee=sf_floatalloc2(nz,nx);

    k=0;
    for(i=0;i<nx;i++)
    for(j=0;j<nz;j++)
    {
       vpp[i][j]=vp[k];
       vss[i][j]=vs[k];
       epp[i][j]=ep[k];
       dee[i][j]=de[k];
       thee[i][j]=th[k];
       k++;
    }

    t4=clock();
    timespent=(float)(t4-t3)/CLOCKS_PER_SEC;
    sf_warning("CPU time for preparing for wavefield modeling: %f(second)",timespent);

    float *pp, *qq;
    pp=sf_floatalloc(nxz);
    qq=sf_floatalloc(nxz);

    int ii, jj, im, jm;

    int *ijkx = sf_intalloc(nkx);
    int *ijkz = sf_intalloc(nkz);

    ikxikz(ijkx, ijkz, nkx, nkz);

    int iflag=0;

    for(int it=0;it<ns;it++)
    {
	float t=it*dt;

	if(it%50==0)
		sf_warning("Elastic: it= %d",it);

        // 2D exploding force source (e.g., Wu's PhD
        for(i=-1;i<=1;i++)
        for(j=-1;j<=1;j++)
        {
             if(fabs(i)+fabs(j)==2)
             {
                  p2[ixms+i][izms+j]+=i*Ricker(t, f0, t0, A);
                  q2[ixms+i][izms+j]+=j*Ricker(t, f0, t0, A);
             }
        }
        // 2D equil-energy force source (e.g., Wu's PhD)
        /*
        for(i=-1;i<=1;i++)
        for(j=-1;j<=1;j++)
        {
             if(fabs(i)+fabs(j)==2)
             {
                  if(i==-1&&j==1)
                    q2[ixms+i][izms+j]+=sqrt(2.0)*Ricker(t, f0, t0, A);
                  if(i==-1&&j==-1)
                   p2[ixms+i][izms+j]+=-sqrt(2.0)*Ricker(t, f0, t0, A);
                  if(i==1&&j==1)
                   p2[ixms+i][izms+j]+=sqrt(2.0)*Ricker(t, f0, t0, A);
                  if(i==1&&j==-1)
                    q2[ixms+i][izms+j]+=-sqrt(2.0)*Ricker(t, f0, t0, A);
             }
        }
        */

        /* fwpvtielastic: forward-propagating using original elastic equation of displacement in VTI media*/
        fwpttielastic(dt2, p1, p2, p3, q1, q2, q3, coeff_2dx, coeff_2dz, coeff_1dx, coeff_1dz,
                      dx, dz, nx, nz, nxpad, nzpad, vpp, vss, epp, dee, thee);

        /******* output wavefields: component and divergence *******/
        if(it==ns-1)
	{
              k=0;
	      for(i=0;i<nx;i++)
              {
                   im=i+M;
		   for(j=0;j<nz;j++)
		   {
                       jm=j+M;

                       x[k] = pp[k] = p3[im][jm];
                       y[k] = qq[k] = q3[im][jm];

                       k++;
		    }
              }// i loop
              Elasticx<<x;
              Elasticz<<y;

              t44=clock();
              timespent=(float)(t44-t4)/CLOCKS_PER_SEC;
              sf_warning("CPU time for wavefield modeling: %f(second)",timespent);

              /* separate qP wave  */
              sf_warning("separate qP-wave based on lowrank decomp.");
              seplowrank2d(ldataxp,rdataxp,fmidxp,pp,ijkx,ijkz,nx,nz,nxz,nk,m2xp,n2xp,iflag);
              seplowrank2d(ldatazp,rdatazp,fmidzp,qq,ijkx,ijkz,nx,nz,nxz,nk,m2zp,n2zp,iflag);

              for(i=0;i<nxz;i++)
		  z[i]=pp[i]+qq[i];

              ElasticSepP<<z;

              k=0;
	      for(i=0;i<nx;i++)
              {
                   im=i+M;
		   for(j=0;j<nz;j++)
		   {
                       jm=j+M;

                       pp[k] = p3[im][jm];
                       qq[k] = q3[im][jm];

                       k++;
		    }
              }// i loop

              /* separate qSV wave  */
              sf_warning("separate qSV-wave based on lowrank decomp.");
              seplowrank2d(ldataxs,rdataxs,fmidxs,pp,ijkx,ijkz,nx,nz,nxz,nk,m2xs,n2xs,iflag);
              seplowrank2d(ldatazs,rdatazs,fmidzs,qq,ijkx,ijkz,nx,nz,nxz,nk,m2zs,n2zs,iflag);

              for(i=0;i<nxz;i++)
		  z[i]=pp[i]+qq[i];

              ElasticSepSV<<z;

         }/* (it+1)%ntstep==0 */

         /**************************************/
 	 for(i=0,ii=M;i<nx;i++,ii++)
	    for(j=0,jj=M;j<nz;j++,jj++)
	    {
		p1[ii][jj]=p2[ii][jj];
		p2[ii][jj]=p3[ii][jj];

		q1[ii][jj]=q2[ii][jj];
		q2[ii][jj]=q3[ii][jj];
	    }

    }/* it loop */
    t5=clock();
    timespent=(float)(t5-t44)/CLOCKS_PER_SEC;
    sf_warning("CPU time for wave-modes separation.: %f(second)",timespent);

    free(ldataxp);
    free(ldatazp);
    free(rdataxp);
    free(rdatazp);
    free(fmidxp);
    free(fmidzp);
    free(ldataxs);
    free(ldatazs);
    free(rdataxs);
    free(rdatazs);
    free(fmidxs);
    free(fmidzs);

    free(pp);
    free(qq);

    free(*p1);
    free(*p2);
    free(*p3);
    free(*q1);
    free(*q2);
    free(*q3);

    free(*vpp);
    free(*vss);
    free(*epp);
    free(*dee);
    free(*thee);

    free(coeff_2dx);
    free(coeff_2dz);
    free(coeff_1dx);
    free(coeff_1dz);

    free(ijkx);
    free(ijkz);
exit(0);
}
/* P-wave dual-domain wave-mode separation operator based on low-rank decomp. */
static int samplexp(vector<int>& rs, vector<int>& cs, DblNumMat& resx)
{
    int nr = rs.size();
    int nc = cs.size();

    resx.resize(nr,nc);

    setvalue(resx,0.0);

    double   aa[2][2],ve[2][2],va[2];  /*matrix, eigeinvector and eigeinvalues*/

    double c33, c44, c11, c13c44, a11, a12, a22;

    for(int a=0; a<nr; a++)
    {
        int i=rs[a];
        double vp2 = vp[i]*vp[i];
        double vs2 = vs[i]*vs[i];
        double ep2 = 1.0+2*ep[i];
        double de2 = 1.0+2*de[i];

        double coss=cos(th[i]);
        double sins=sin(th[i]);

        for(int b=0; b<nc; b++)
        {
            double sx = sinx[cs[b]];
            double cx = cosx[cs[b]];
            if(sx==0&&cx==0)
            {
               resx(a,b) = 0.0;
               continue;
            }

            c33=vp2;
            c44=vs2;
            c11=ep2*c33;
            c13c44=sqrt((de2*c33-c44)*(c33-c44));

            // rotatiing according to tilted symmetry axis
            double s=sx*coss+cx*sins;
            double c=cx*coss-sx*sins;

            a11= c11*s*s+c44*c*c;
            a12= c13c44*s*c;
            a22= c44*s*s+c33*c*c;

            aa[0][0] = a11;
            aa[0][1] = a12;
            aa[1][0] = a12;
            aa[1][1] = a22;

            dsolveSymmetric22(aa, ve, va);

            double u1=ve[0][0];
            double u2=ve[0][1];

            /* get the closest direction to k */
            if(u1*s + u2*c <0) {
               u1 = -u1;
               u2 = -u2;
            }

            resx(a,b) = u1;

         }// b loop
    }// a loop

    return 0;
}

/* P-wave dual-domain wave-mode separation operator based on low-rank decomp. */
static int samplezp(vector<int>& rs, vector<int>& cs, DblNumMat& resz)
{
    int nr = rs.size();
    int nc = cs.size();

    resz.resize(nr,nc);

    setvalue(resz,0.0);

    double   aa[2][2],ve[2][2],va[2];  /*matrix, eigeinvector and eigeinvalues*/

    double c33, c44, c11, c13c44, a11, a12, a22;

    for(int a=0; a<nr; a++)
    {
        int i=rs[a];
        double vp2 = vp[i]*vp[i];
        double vs2 = vs[i]*vs[i];
        double ep2 = 1.0+2*ep[i];
        double de2 = 1.0+2*de[i];

        double coss=cos(th[i]);
        double sins=sin(th[i]);

        for(int b=0; b<nc; b++)
        {
            double sx = sinx[cs[b]];
            double cx = cosx[cs[b]];

            if(sx==0&&cx==0)
            {
               resz(a,b) = 0.0;
               continue;
            }

            c33=vp2;
            c44=vs2;
            c11=ep2*c33;
            c13c44=sqrt((de2*c33-c44)*(c33-c44));

            // rotatiing according to tilted symmetry axis
            double s=sx*coss+cx*sins;
            double c=cx*coss-sx*sins;

            a11= c11*s*s+c44*c*c;
            a12= c13c44*s*c;
            a22= c44*s*s+c33*c*c;

            aa[0][0] = a11;
            aa[0][1] = a12;
            aa[1][0] = a12;
            aa[1][1] = a22;

            dsolveSymmetric22(aa, ve, va);

            double u1=ve[0][0];
            double u2=ve[0][1];

            /* get the closest direction to k */
            if(u1*s + u2*c <0) {
               u1 = -u1;
               u2 = -u2;
            }

            resz(a,b) = u2;

         }// b loop
    }// a loop

    return 0;
}

/* SV-wave dual-domain wave-mode separation operator based on low-rank decomp. */
static int samplexs(vector<int>& rs, vector<int>& cs, DblNumMat& resx)
{
    int nr = rs.size();
    int nc = cs.size();

    resx.resize(nr,nc);

    setvalue(resx,0.0);

    double   aa[2][2],ve[2][2],va[2];  /*matrix, eigeinvector and eigeinvalues*/

    double c33, c44, c11, c13c44, a11, a12, a22;

    for(int a=0; a<nr; a++)
    {
        int i=rs[a];
        double vp2 = vp[i]*vp[i];
        double vs2 = vs[i]*vs[i];
        double ep2 = 1.0+2*ep[i];
        double de2 = 1.0+2*de[i];

        double coss=cos(th[i]);
        double sins=sin(th[i]);

        for(int b=0; b<nc; b++)
        {
            double sx = sinx[cs[b]];
            double cx = cosx[cs[b]];
            if(sx==0&&cx==0)
            {
               resx(a,b) = 0.0;
               continue;
            }

            c33=vp2;
            c44=vs2;
            c11=ep2*c33;
            c13c44=sqrt((de2*c33-c44)*(c33-c44));

            // rotatiing according to tilted symmetry axis
            double s=sx*coss+cx*sins;
            double c=cx*coss-sx*sins;

            a11= c11*s*s+c44*c*c;
            a12= c13c44*s*c;
            a22= c44*s*s+c33*c*c;

            aa[0][0] = a11;
            aa[0][1] = a12;
            aa[1][0] = a12;
            aa[1][1] = a22;

            dsolveSymmetric22(aa, ve, va);

            double u1=ve[1][0];
            double u2=ve[1][1];

            /* get the closest direction to k */
            if(u1*c - u2*s <0) {
               u1 = -u1;
               u2 = -u2;
            }

            resx(a,b) = u1;

         }// b loop
    }// a loop

    return 0;
}

/* SV-wave dual-domain wave-mode separation operator based on low-rank decomp. */
static int samplezs(vector<int>& rs, vector<int>& cs, DblNumMat& resz)
{
    int nr = rs.size();
    int nc = cs.size();

    resz.resize(nr,nc);

    setvalue(resz,0.0);

    double   aa[2][2],ve[2][2],va[2];  /*matrix, eigeinvector and eigeinvalues*/

    double c33, c44, c11, c13c44, a11, a12, a22;

    for(int a=0; a<nr; a++)
    {
        int i=rs[a];
        double vp2 = vp[i]*vp[i];
        double vs2 = vs[i]*vs[i];
        double ep2 = 1.0+2*ep[i];
        double de2 = 1.0+2*de[i];

        double coss=cos(th[i]);
        double sins=sin(th[i]);

        for(int b=0; b<nc; b++)
        {
            double sx = sinx[cs[b]];
            double cx = cosx[cs[b]];

            if(sx==0&&cx==0)
            {
               resz(a,b) = 0.0;
               continue;
            }

            c33=vp2;
            c44=vs2;
            c11=ep2*c33;
            c13c44=sqrt((de2*c33-c44)*(c33-c44));

            // rotatiing according to tilted symmetry axis
            double s=sx*coss+cx*sins;
            double c=cx*coss-sx*sins;

            a11= c11*s*s+c44*c*c;
            a12= c13c44*s*c;
            a22= c44*s*s+c33*c*c;

            aa[0][0] = a11;
            aa[0][1] = a12;
            aa[1][0] = a12;
            aa[1][1] = a22;

            dsolveSymmetric22(aa, ve, va);

            double u1=ve[1][0];
            double u2=ve[1][1];

            /* get the closest direction to k */
            if(u1*c - u2*s <0) {
               u1 = -u1;
               u2 = -u2;
            }

            resz(a,b) = u2;

         }// b loop
    }// a loop

    return 0;
}

static void polxp2dtti(float **ap, int nx, int nz, int im)
{
        int    i, j, k;
        double sx, cx;

        double ve[2][2], va[2];  /*eigeinvector and eigeinvalues*/
        double a[2][2];

        double vp2 = vp[im]*vp[im];
        double vs2 = vs[im]*vs[im];
        double ep2 = 1.0+2*ep[im];
        double de2 = 1.0+2*de[im];

        double u1, u2, c11, c33, c44, c13c44, a11, a12, a22;

        double coss=cos(th[im]);
        double sins=sin(th[im]);

        c33=vp2;
        c44=vs2;
        c11=ep2*c33;
        c13c44=sqrt((de2*c33-c44)*(c33-c44));

        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
                  ap[i][j]=0.0;

        k=0;
        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
           {
                sx=sinx[k];
                cx=cosx[k];
                k++;

                // rotatiing according to tilted symmetry axis
                double s=sx*coss+cx*sins;
                double c=cx*coss-sx*sins;

                a11= c11*s*s + c44*c*c;
                a12= c13c44*s*c;
                a22= c44*s*s + c33*c*c;

                a[0][0] = a11;
                a[0][1] = a12;
                a[1][0] = a12;
                a[1][1] = a22;

               dsolveSymmetric22(a, ve, va);

               u1=ve[0][0];
               u2=ve[0][1];
               /* get the closest direction to k */
               if(u1*s + u2*c <0) {
                  u1 = -u1;
               }
	       ap[i][j]=(float)(u1);
          } /* j loop */
}

static void polzp2dtti(float **ap, int nx, int nz, int im)
{
        int    i, j, k;
        double sx, cx;

        double ve[2][2], va[2];  /*eigeinvector and eigeinvalues*/
        double a[2][2];

        //double f=1.0-vs2/vp2;

        double vp2 = vp[im]*vp[im];
        double vs2 = vs[im]*vs[im];
        double ep2 = 1.0+2*ep[im];
        double de2 = 1.0+2*de[im];

        double coss=cos(th[im]);
        double sins=sin(th[im]);

        double u1, u2, c11, c33, c44, c13c44, a11, a12, a22;

        c33=vp2;
        c44=vs2;
        c11=ep2*c33;
        c13c44=sqrt((de2*c33-c44)*(c33-c44));

        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
                  ap[i][j]=0.0;

        k=0;
        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
           {
                sx=sinx[k];
                cx=cosx[k];
                k++;

                // rotatiing according to tilted symmetry axis
                double s=sx*coss+cx*sins;
                double c=cx*coss-sx*sins;

                a11= c11*s*s + c44*c*c;
                a12= c13c44*s*c;
                a22= c44*s*s + c33*c*c;

                a[0][0] = a11;
                a[0][1] = a12;
                a[1][0] = a12;
                a[1][1] = a22;

               dsolveSymmetric22(a, ve, va);

               u1=ve[0][0];
               u2=ve[0][1];
               /* get the closest direction to k */
               if(u1*s + u2*c <0) {
                  u2 = -u2;
               }
	       ap[i][j]=(float)(u2);
          } /* j loop */
}

static void polxs2dtti(float **ap, int nx, int nz, int im)
{
        int    i, j, k;
        double sx, cx;

        double ve[2][2], va[2];  /*eigeinvector and eigeinvalues*/
        double a[2][2];

        double vp2 = vp[im]*vp[im];
        double vs2 = vs[im]*vs[im];
        double ep2 = 1.0+2*ep[im];
        double de2 = 1.0+2*de[im];

        double coss=cos(th[im]);
        double sins=sin(th[im]);

        double u1, u2, c11, c33, c44, c13c44, a11, a12, a22;

        c33=vp2;
        c44=vs2;
        c11=ep2*c33;
        c13c44=sqrt((de2*c33-c44)*(c33-c44));

        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
                ap[i][j]=0.0;

        k=0;
        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
           {
                sx=sinx[k];
                cx=cosx[k];
                k++;

                // rotatiing according to tilted symmetry axis
                double s=sx*coss+cx*sins;
                double c=cx*coss-sx*sins;

                a11= c11*s*s + c44*c*c;
                a12= c13c44*s*c;
                a22= c44*s*s + c33*c*c;

                a[0][0] = a11;
                a[0][1] = a12;
                a[1][0] = a12;
                a[1][1] = a22;

               dsolveSymmetric22(a, ve, va);

               u1=ve[1][0];
               u2=ve[1][1];
               /* get the closest direction to k */
               if(u1*c - u2*s <0) {
                  u1 = -u1;
               }
	       ap[i][j]=(float)(u1);
          } /* j loop */
}

static void polzs2dtti(float **ap, int nx, int nz, int im)
{
        int    i, j, k;
        double sx, cx;

        double ve[2][2], va[2];  /*eigeinvector and eigeinvalues*/
        double a[2][2];

        //double f=1.0-vs2/vp2;

        double vp2 = vp[im]*vp[im];
        double vs2 = vs[im]*vs[im];
        double ep2 = 1.0+2*ep[im];
        double de2 = 1.0+2*de[im];

        double coss=cos(th[im]);
        double sins=sin(th[im]);

        double u1, u2, c11, c33, c44, c13c44, a11, a12, a22;

        c33=vp2;
        c44=vs2;
        c11=ep2*c33;
        c13c44=sqrt((de2*c33-c44)*(c33-c44));

        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
                  ap[i][j]=0.0;

        k=0;
        for( i=0; i<nx ; i++ )
           for( j=0; j<nz ; j++)
           {
                sx=sinx[k];
                cx=cosx[k];
                k++;

                // rotatiing according to tilted symmetry axis
                double s=sx*coss+cx*sins;
                double c=cx*coss-sx*sins;

                a11= c11*s*s + c44*c*c;
                a12= c13c44*s*c;
                a22= c44*s*s + c33*c*c;

                a[0][0] = a11;
                a[0][1] = a12;
                a[1][0] = a12;
                a[1][1] = a22;

               dsolveSymmetric22(a, ve, va);

               u1=ve[1][0];
               u2=ve[1][1];
               /* get the closest direction to k */
               if(u1*c - u2*s <0) {
                  u2 = -u2;
               }
	       ap[i][j]=(float)(u2);
          } /* j loop */
}

static void map2d1d(float *d, DblNumMat mat, int m, int n)
{
   int i, j, k;
   k=0;
   for (i=0; i < m; i++)
   for (j=0; j < n; j++)
   {
        d[k] = (float)mat(i,j);
        k++;
   }

}

{'repo_name': 'ahay/src', 'stars': '146', 'repo_language': 'TeX', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -295670717195375088, 'source_dataset': 'data'}


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * A synchronization aid that allows one or more threads to wait until
 * a set of operations being performed in other threads completes.
 *
 *
A {@code CountDownLatch} is initialized with a given count.
 * The {@link #await await} methods block until the current count reaches
 * zero due to invocations of the {@link #countDown} method, after which
 * all waiting threads are released and any subsequent invocations of
 * {@link #await await} return immediately.  This is a one-shot phenomenon
 * -- the count cannot be reset.  If you need a version that resets the
 * count, consider using a {@link CyclicBarrier}.
 *
 *
A {@code CountDownLatch} is a versatile synchronization tool
 * and can be used for a number of purposes.  A
 * {@code CountDownLatch} initialized with a count of one serves as a
 * simple on/off latch, or gate: all threads invoking {@link #await await}
 * wait at the gate until it is opened by a thread invoking {@link
 * #countDown}.  A {@code CountDownLatch} initialized to N
 * can be used to make one thread wait until N threads have
 * completed some action, or some action has been completed N times.
 *
 *
A useful property of a {@code CountDownLatch} is that it
 * doesn't require that threads calling {@code countDown} wait for
 * the count to reach zero before proceeding, it simply prevents any
 * thread from proceeding past an {@link #await await} until all
 * threads could pass.
 *
 *
Sample usage: Here is a pair of classes in which a group
 * of worker threads use two countdown latches:
 *

 *
The first is a start signal that prevents any worker from proceeding
 * until the driver is ready for them to proceed;
 *
The second is a completion signal that allows the driver to wait
 * until all workers have completed.
 *

 *
 *
 {@code
 * class Driver { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch startSignal = new CountDownLatch(1);
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       new Thread(new Worker(startSignal, doneSignal)).start();
 *
 *     doSomethingElse();            // don't let run yet
 *     startSignal.countDown();      // let all threads proceed
 *     doSomethingElse();
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class Worker implements Runnable {
 *   private final CountDownLatch startSignal;
 *   private final CountDownLatch doneSignal;
 *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
 *     this.startSignal = startSignal;
 *     this.doneSignal = doneSignal;
 *   }
 *   public void run() {
 *     try {
 *       startSignal.await();
 *       doWork();
 *       doneSignal.countDown();
 *     } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }}

 *
 *
Another typical usage would be to divide a problem into N parts,
 * describe each part with a Runnable that executes that portion and
 * counts down on the latch, and queue all the Runnables to an
 * Executor.  When all sub-parts are complete, the coordinating thread
 * will be able to pass through await. (When threads must repeatedly
 * count down in this way, instead use a {@link CyclicBarrier}.)
 *
 *
 {@code
 * class Driver2 { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *     Executor e = ...
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       e.execute(new WorkerRunnable(doneSignal, i));
 *
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class WorkerRunnable implements Runnable {
 *   private final CountDownLatch doneSignal;
 *   private final int i;
 *   WorkerRunnable(CountDownLatch doneSignal, int i) {
 *     this.doneSignal = doneSignal;
 *     this.i = i;
 *   }
 *   public void run() {
 *     try {
 *       doWork(i);
 *       doneSignal.countDown();
 *     } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }}

 *
 *
Memory consistency effects: Until the count reaches
 * zero, actions in a thread prior to calling
 * {@code countDown()}
 * happen-before
 * actions following a successful return from a corresponding
 * {@code await()} in another thread.
 *
 * @since 1.5
 * @author Doug Lea
 */
public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    private final Sync sync;

    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
     *
     *
If the current count is zero then this method returns immediately.
     *
     *
If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of two things happen:
     *

     *
The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     *
Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread.
     *

     *
     *
If the current thread:
     *

     *
has its interrupted status set on entry to this method; or
     *
is {@linkplain Thread#interrupt interrupted} while waiting,
     *

     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
     * or the specified waiting time elapses.
     *
     *
If the current count is zero then this method returns immediately
     * with the value {@code true}.
     *
     *
If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of three things happen:
     *

     *
The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     *
Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *
The specified waiting time elapses.
     *

     *
     *
If the count reaches zero then the method returns with the
     * value {@code true}.
     *
     *
If the current thread:
     *

     *
has its interrupted status set on entry to this method; or
     *
is {@linkplain Thread#interrupt interrupted} while waiting,
     *

     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     *
If the specified waiting time elapses then the value {@code false}
     * is returned.  If the time is less than or equal to zero, the method
     * will not wait at all.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the {@code timeout} argument
     * @return {@code true} if the count reached zero and {@code false}
     *         if the waiting time elapsed before the count reached zero
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *
     *
If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     *
If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

    /**
     * Returns the current count.
     *
     *
This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     */
    public long getCount() {
        return sync.getCount();
    }

    /**
     * Returns a string identifying this latch, as well as its state.
     * The state, in brackets, includes the String {@code "Count ="}
     * followed by the current count.
     *
     * @return a string identifying this latch, as well as its state
     */
    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}

{'repo_name': 'corretto/corretto-8', 'stars': '1803', 'repo_language': 'Java', 'file_name': 'FtpLoginException.java', 'mime_type': 'text/x-java', 'hash': 8020640279595396278, 'source_dataset': 'data'}


/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// Package serviceconfig defines types and methods for operating on gRPC
// service configs.
//
// This package is EXPERIMENTAL.
package serviceconfig

// Config represents an opaque data structure holding a service config.
type Config interface {
	isServiceConfig()
}

// LoadBalancingConfig represents an opaque data structure holding a load
// balancing config.
type LoadBalancingConfig interface {
	isLoadBalancingConfig()
}

// ParseResult contains a service config or an error.  Exactly one must be
// non-nil.
type ParseResult struct {
	Config Config
	Err    error
}

{'repo_name': 'IBM-Cloud/terraform-provider-ibm', 'stars': '173', 'repo_language': 'Go', 'file_name': 'id_rsa', 'mime_type': 'text/plain', 'hash': -3309148741560401712, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 9fc0d4010bbf28b4594072e72b8655ab
DefaultImporter:
  externalObjects: {}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'Unity-Technologies/AddressableAssetsWebinar', 'stars': '141', 'repo_language': 'ASP', 'file_name': 'AudioManager.asset', 'mime_type': 'text/plain', 'hash': -2902881006032521664, 'source_dataset': 'data'}