text:
// Copyright 2019 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 "chrome/browser/android/autofill_assistant/interaction_handler_android.h"
#include <algorithm>
#include <vector>
#include "base/android/jni_string.h"
#include "base/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/android/autofill_assistant/generic_ui_controller_android.h"
#include "chrome/browser/android/autofill_assistant/generic_ui_interactions_android.h"
#include "components/autofill_assistant/browser/basic_interactions.h"
#include "components/autofill_assistant/browser/generic_ui.pb.h"
#include "components/autofill_assistant/browser/ui_delegate.h"
#include "components/autofill_assistant/browser/user_model.h"
#include "components/autofill_assistant/browser/value_util.h"

namespace autofill_assistant {

namespace {

base::Optional<EventHandler::EventKey> CreateEventKeyFromProto(
    const EventProto& proto,
    std::map<std::string, base::android::ScopedJavaGlobalRef<jobject>>* views,
    base::android::ScopedJavaGlobalRef<jobject> jdelegate) {
  switch (proto.kind_case()) {
    case EventProto::kOnValueChanged:
      if (proto.on_value_changed().model_identifier().empty()) {
        VLOG(1) << "Invalid OnValueChangedEventProto: no model_identifier "
                   "specified";
        return base::nullopt;
      }
      return base::Optional<EventHandler::EventKey>(
          {proto.kind_case(), proto.on_value_changed().model_identifier()});
    case EventProto::kOnViewClicked:
      if (proto.on_view_clicked().view_identifier().empty()) {
        VLOG(1) << "Invalid OnViewClickedEventProto: no view_identifier "
                   "specified";
        return base::nullopt;
      }
      return base::Optional<EventHandler::EventKey>(
          {proto.kind_case(), proto.on_view_clicked().view_identifier()});
    case EventProto::kOnUserActionCalled:
      if (proto.on_user_action_called().user_action_identifier().empty()) {
        VLOG(1) << "Invalid OnUserActionCalled: no user_action_identifier "
                   "specified";
        return base::nullopt;
      }
      return base::Optional<EventHandler::EventKey>(
          {proto.kind_case(),
           proto.on_user_action_called().user_action_identifier()});
    case EventProto::kOnTextLinkClicked:
      if (!proto.on_text_link_clicked().has_text_link()) {
        VLOG(1) << "Invalid OnTextLinkClickedProto: no text_link specified";
        return base::nullopt;
      }
      return base::Optional<EventHandler::EventKey>(
          {proto.kind_case(),
           base::NumberToString(proto.on_text_link_clicked().text_link())});
    case EventProto::kOnPopupDismissed:
      if (proto.on_popup_dismissed().popup_identifier().empty()) {
        VLOG(1)
            << "Invalid OnPopupDismissedProto: no popup_identifier specified";
        return base::nullopt;
      }
      return base::Optional<EventHandler::EventKey>(
          {proto.kind_case(), proto.on_popup_dismissed().popup_identifier()});
    case EventProto::KIND_NOT_SET:
      VLOG(1) << "Error creating event: kind not set";
      return base::nullopt;
  }
}

}  // namespace

InteractionHandlerAndroid::InteractionHandlerAndroid(
    EventHandler* event_handler,
    UserModel* user_model,
    BasicInteractions* basic_interactions,
    std::map<std::string, base::android::ScopedJavaGlobalRef<jobject>>* views,
    base::android::ScopedJavaGlobalRef<jobject> jcontext,
    base::android::ScopedJavaGlobalRef<jobject> jdelegate)
    : event_handler_(event_handler),
      user_model_(user_model),
      basic_interactions_(basic_interactions),
      views_(views),
      jcontext_(jcontext),
      jdelegate_(jdelegate) {}

InteractionHandlerAndroid::~InteractionHandlerAndroid() {
  event_handler_->RemoveObserver(this);
}

base::WeakPtr<InteractionHandlerAndroid>
InteractionHandlerAndroid::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void InteractionHandlerAndroid::StartListening() {
  is_listening_ = true;
  event_handler_->AddObserver(this);
}

void InteractionHandlerAndroid::StopListening() {
  event_handler_->RemoveObserver(this);
  is_listening_ = false;
}

UserModel* InteractionHandlerAndroid::GetUserModel() const {
  return user_model_;
}

BasicInteractions* InteractionHandlerAndroid::GetBasicInteractions() const {
  return basic_interactions_;
}

bool InteractionHandlerAndroid::AddInteractionsFromProto(
    const InteractionProto& proto) {
  if (is_listening_) {
    NOTREACHED() << "Interactions can not be added while listening to events!";
    return false;
  }
  auto key = CreateEventKeyFromProto(proto.trigger_event(), views_, jdelegate_);
  if (!key) {
    VLOG(1) << "Invalid trigger event for interaction";
    return false;
  }

  for (const auto& callback_proto : proto.callbacks()) {
    auto callback = CreateInteractionCallbackFromProto(callback_proto);
    if (!callback) {
      VLOG(1) << "Invalid callback for interaction";
      return false;
    }
    // Wrap callback in condition handler if necessary.
    if (callback_proto.has_condition_model_identifier()) {
      callback = base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::RunConditionalCallback,
          basic_interactions_->GetWeakPtr(),
          callback_proto.condition_model_identifier(), *callback));
    }
    AddInteraction(*key, *callback);
  }
  return true;
}

void InteractionHandlerAndroid::AddInteraction(
    const EventHandler::EventKey& key,
    const InteractionCallback& callback) {
  interactions_[key].emplace_back(callback);
}

void InteractionHandlerAndroid::OnEvent(const EventHandler::EventKey& key) {
  auto it = interactions_.find(key);
  if (it != interactions_.end()) {
    for (auto& callback : it->second) {
      callback.Run();
    }
  }
}

void InteractionHandlerAndroid::AddRadioButtonToGroup(
    const std::string& radio_group,
    const std::string& model_identifier) {
  radio_groups_[radio_group].emplace_back(model_identifier);
}

void InteractionHandlerAndroid::UpdateRadioButtonGroup(
    const std::string& radio_group,
    const std::string& selected_model_identifier) {
  if (radio_groups_.find(radio_group) == radio_groups_.end()) {
    return;
  }
  basic_interactions_->UpdateRadioButtonGroup(radio_groups_[radio_group],
                                              selected_model_identifier);
}

base::Optional<InteractionHandlerAndroid::InteractionCallback>
InteractionHandlerAndroid::CreateInteractionCallbackFromProto(
    const CallbackProto& proto) {
  switch (proto.kind_case()) {
    case CallbackProto::kSetValue:
      if (!proto.set_value().has_value()) {
        VLOG(1) << "Error creating SetValue interaction: value "
                   "not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::SetValue, basic_interactions_->GetWeakPtr(),
          proto.set_value()));
    case CallbackProto::kShowInfoPopup: {
      return base::Optional<InteractionCallback>(
          base::BindRepeating(&android_interactions::ShowInfoPopup,
                              proto.show_info_popup().info_popup(), jcontext_));
    }
    case CallbackProto::kShowListPopup:
      if (!proto.show_list_popup().has_item_names()) {
        VLOG(1) << "Error creating ShowListPopup interaction: "
                   "item_names not set";
        return base::nullopt;
      }
      if (proto.show_list_popup()
              .selected_item_indices_model_identifier()
              .empty()) {
        VLOG(1) << "Error creating ShowListPopup interaction: "
                   "selected_item_indices_model_identifier not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::ShowListPopup, user_model_->GetWeakPtr(),
          proto.show_list_popup(), jcontext_, jdelegate_));
    case CallbackProto::kComputeValue:
      if (proto.compute_value().result_model_identifier().empty()) {
        VLOG(1) << "Error creating ComputeValue interaction: "
                   "result_model_identifier empty";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::ComputeValue,
          basic_interactions_->GetWeakPtr(), proto.compute_value()));
    case CallbackProto::kSetUserActions:
      if (!proto.set_user_actions().has_user_actions()) {
        VLOG(1) << "Error creating SetUserActions interaction: "
                   "user_actions not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::SetUserActions,
          basic_interactions_->GetWeakPtr(), proto.set_user_actions()));
    case CallbackProto::kEndAction:
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::EndAction, basic_interactions_->GetWeakPtr(),
          /* view_inflation_successful = */ true, proto.end_action()));
    case CallbackProto::kShowCalendarPopup:
      if (proto.show_calendar_popup().date_model_identifier().empty()) {
        VLOG(1) << "Error creating ShowCalendarPopup interaction: "
                   "date_model_identifier not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::ShowCalendarPopup, user_model_->GetWeakPtr(),
          proto.show_calendar_popup(), jcontext_, jdelegate_));
    case CallbackProto::kSetText:
      if (!proto.set_text().has_text()) {
        VLOG(1) << "Error creating SetText interaction: "
                   "text not set";
        return base::nullopt;
      }
      if (proto.set_text().view_identifier().empty()) {
        VLOG(1) << "Error creating SetText interaction: "
                   "view_identifier not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::SetViewText, user_model_->GetWeakPtr(),
          proto.set_text(), views_, jdelegate_));
    case CallbackProto::kToggleUserAction:
      if (proto.toggle_user_action().user_actions_model_identifier().empty()) {
        VLOG(1) << "Error creating ToggleUserAction interaction: "
                   "user_actions_model_identifier not set";
        return base::nullopt;
      }
      if (proto.toggle_user_action().user_action_identifier().empty()) {
        VLOG(1) << "Error creating ToggleUserAction interaction: "
                   "user_action_identifier not set";
        return base::nullopt;
      }
      if (!proto.toggle_user_action().has_enabled()) {
        VLOG(1) << "Error creating ToggleUserAction interaction: "
                   "enabled not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::ToggleUserAction,
          basic_interactions_->GetWeakPtr(), proto.toggle_user_action()));
    case CallbackProto::kSetViewVisibility:
      if (proto.set_view_visibility().view_identifier().empty()) {
        VLOG(1) << "Error creating SetViewVisibility interaction: "
                   "view_identifier not set";
        return base::nullopt;
      }
      if (!proto.set_view_visibility().has_visible()) {
        VLOG(1) << "Error creating SetViewVisibility interaction: "
                   "visible not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::SetViewVisibility, user_model_->GetWeakPtr(),
          proto.set_view_visibility(), views_));
    case CallbackProto::kSetViewEnabled:
      if (proto.set_view_enabled().view_identifier().empty()) {
        VLOG(1) << "Error creating SetViewEnabled interaction: "
                   "view_identifier not set";
        return base::nullopt;
      }
      if (!proto.set_view_enabled().has_enabled()) {
        VLOG(1) << "Error creating SetViewEnabled interaction: "
                   "enabled not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &android_interactions::SetViewEnabled, user_model_->GetWeakPtr(),
          proto.set_view_enabled(), views_));
    case CallbackProto::kShowGenericPopup:
      if (proto.show_generic_popup().popup_identifier().empty()) {
        VLOG(1) << "Error creating ShowGenericPopup interaction: "
                   "popup_identifier not set";
        return base::nullopt;
      }
      return base::Optional<InteractionCallback>(base::BindRepeating(
          &InteractionHandlerAndroid::CreateAndShowGenericPopup, GetWeakPtr(),
          proto.show_generic_popup()));
    case CallbackProto::KIND_NOT_SET:
      VLOG(1) << "Error creating interaction: kind not set";
      return base::nullopt;
  }
}

void InteractionHandlerAndroid::DeleteNestedUi(const std::string& identifier) {
  auto it = nested_ui_controllers_.find(identifier);
  if (it != nested_ui_controllers_.end()) {
    nested_ui_controllers_.erase(it);
  }
}

const GenericUiControllerAndroid* InteractionHandlerAndroid::CreateNestedUi(
    const GenericUserInterfaceProto& proto,
    const std::string& identifier) {
  auto nested_ui = GenericUiControllerAndroid::CreateFromProto(
      proto, jcontext_, jdelegate_, event_handler_, user_model_,
      basic_interactions_);
  const auto* nested_ui_ptr = nested_ui.get();
  if (nested_ui) {
    DCHECK(nested_ui_controllers_.find(identifier) ==
           nested_ui_controllers_.end());
    nested_ui_controllers_.emplace(identifier, std::move(nested_ui));
  }
  return nested_ui_ptr;
}

void InteractionHandlerAndroid::CreateAndShowGenericPopup(
    const ShowGenericUiPopupProto& proto) {
  auto* nested_ui =
      CreateNestedUi(proto.generic_ui(), proto.popup_identifier());
  if (!nested_ui) {
    DVLOG(2) << "Error showing popup: error creating generic UI";
    return;
  }
  AddInteraction({EventProto::kOnPopupDismissed, proto.popup_identifier()},
                 base::BindRepeating(&InteractionHandlerAndroid::DeleteNestedUi,
                                     GetWeakPtr(), proto.popup_identifier()));
  android_interactions::ShowGenericPopup(proto, nested_ui->GetRootView(),
                                         jcontext_, jdelegate_);
}

}  // namespace autofill_assistant


text:
import { VSTestService, VSTestServiceStatus } from "../../vsTest/vsTestService";
import { VSTestServiceIDE } from "../vsTest/vsTestServiceIDE";
import * as vscode from "vscode";
import { TestOutputChannel } from "../console/testOutputChannel"
/**
 * Test Manager is too much here.. need to rethink this
 */
export class TestManager {
    private testService: VSTestServiceIDE;
    public testOutputChannel: TestOutputChannel;

    /**
     * The singleton TestManager
     */
    private static _instance: TestManager = null;

    /**
     * @returns the singleton TestManager
     */
    public static getInstance(): TestManager {
        return this._instance;
    }

    public getTestService(): VSTestService {
        return this.testService;
    }

    /**
     * Initialize the Test Manager
     * @param context The visual studio code context
     */
    public static initialize(context: vscode.ExtensionContext, workspace : string): Promise<void> {
        this._instance = new TestManager(context);
        return this._instance.start(workspace);
    }

    constructor(private context: vscode.ExtensionContext) {
        this.testOutputChannel = new TestOutputChannel();
    }

    public start(workspace : string): Promise<void> {
        this.testService = new VSTestServiceIDE(workspace);

        return new Promise<void>((resolve, reject) => {
            this.testService.startTestRunner().then(() => {
                this.registerListener();
                resolve();
            });
        });
    }

    public restart(workspace : string): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (this.testService) {
                this.testService.stopService().then(() => {
                    this.start(workspace);
                    resolve();
                });
            }
            else {
                return this.start(workspace);
            }
        });
    }

    private registerListener() {
        this.testService.onDidTestServiceStatusChanged((serviceStatus) => {
            this.testOutputChannel.appendData(`Service Status: ${serviceStatus}`);
        });

        this.testService.getSession().onDidTestDiscoveryCompleted((testDiscoveryResult: VSTestProtocol.TestDiscoveryResult) => {
            if (testDiscoveryResult) {
                this.testOutputChannel.appendData(`Total test found: ${testDiscoveryResult.TotalTests}`);
            }
            else {
                this.testOutputChannel.appendData(`Total test found: 0. Error?`);
            }
        });

        this.testService.getSession().onDidTestExecutionCompleted((testRunCompleteResult: VSTestProtocol.TestRunCompleteResult) => {
            if (testRunCompleteResult) {
                this.testOutputChannel.appendData(`Total test time: ${testRunCompleteResult.TestRunCompleteArgs.ElapsedTimeInRunningTests}`);
                this.testOutputChannel.appendData(`Executed Tests: ${testRunCompleteResult.TestRunCompleteArgs.TestRunStatistics.ExecutedTests}`);
            }
        });

        this.testService.getSession().onDidTestSessionMessageReceived((message: VSTestProtocol.MessageResult) => {
            this.testOutputChannel.appendData(message.Message);
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "layout.html" %} {% block page_title %} Speaking {% endblock %} {% block content %}

    {% include "../includes/phase_banner_beta.html" %}
    <form action="hearing" method="#" class="form">

                Back

Does your condition affect your speech?

                <fieldset id="speech" class="inline">
                    <legend for="speech">
                        Does your condition affect your speech?
                    </legend>

                            <input id="speech-Yes" type="radio" name="speech" value="Yes" aria-controls="speechDetails">Yes

                            <input id="speech-No" type="radio" name="speech" value="No" aria-controls="">No

                </fieldset>

                    <fieldset id="allTime" class="form-group inline">
                        <legend for="allTime">
                            Does your condition affect your speech all the time?
                        </legend>

                                <input id="allTime-Yes" type="radio" name="allTime" value="Yes" aria-controls="">Yes

                                <input id="allTime-No" type="radio" name="allTime" value="No" aria-controls="allTimeDetails">No

                    </fieldset>

                            How often is your speech affected?
                                Include how many days out of each week or month you're affected.

                            <input type="text" class="form-control  " id="howOften" name="howOften" value="">

                            In your own words, describe how your condition affects your speech on a typical day.

Include if your speech changes depending on:

where you are

what you're doing

who you're with

                        <textarea maxlength="1500" class="form-control form-control-3-4" id="howDoes" name="howDoes"></textarea>
                        1500 characters left

                    <input type="submit" class="button" value="Continue">

				{% include "../includes/help.html" %}

    </form>

{% endblock %}


text:
[![Platform](https://img.shields.io/badge/platform-react--native-lightgrey.svg)](http://facebook.github.io/react-native/)
[![npm version](http://img.shields.io/npm/v/react-native-dropdownalert.svg)](https://www.npmjs.com/package/react-native-dropdownalert)
[![npm version](http://img.shields.io/npm/dm/react-native-dropdownalert.svg)](https://www.npmjs.com/package/react-native-dropdownalert)
[![Build Status](https://travis-ci.org/testshallpass/react-native-dropdownalert.svg?branch=master)](https://travis-ci.org/testshallpass/react-native-dropdownalert)
[![Join the chat at https://gitter.im/react-native-dropdownalert/Lobby](https://badges.gitter.im/react-native-dropdownalert/Lobby.svg)](https://gitter.im/react-native-dropdownalert/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.github.com/testshallpass/react-native-dropdownalert/master/LICENSE)

A simple alert to notify users about new chat messages, something went wrong or everything is ok. It can be dismissed by onPress, cancel onPress, automatically with `closeInterval` prop, pan responder up gesture or programmatically.

### Installation
```
npm i react-native-dropdownalert --save
```

### Demo
![screenshot](https://raw.github.com/testshallpass/react-native-dropdownalert/master/screenshots/demo.gif)

### Usage
```javascript

import DropdownAlert from 'react-native-dropdownalert'
// ...
render() {
  return (
    <View>
      // !!! Make sure it's the last component in your document tree.
      <DropdownAlert
        ref={(ref) => this.dropdown = ref}
        onClose={(data) => this.onClose(data)} />
    </View>
  )
}
// ...
handleRequestCallback(err, response) {
  if (err != null) {
    this.dropdown.alertWithType('error', 'Error', err)
  }
}
// ...
onClose(data) {
  // data = {type, title, message, action}
  // action means how the alert was dismissed. returns: automatic, programmatic, tap, pan or cancel
}
// ...
```

### Predefined Types

| info | warn | error | success |
| :---: | :---: | :---: | :---: |
|![screenshot](https://raw.github.com/testshallpass/react-native-dropdownalert/master/screenshots/info.png) |![screenshot](https://raw.github.com/testshallpass/react-native-dropdownalert/master/screenshots/warning.png) |![screenshot](https://raw.github.com/testshallpass/react-native-dropdownalert/master/screenshots/error.png)|![screenshot](https://raw.github.com/testshallpass/react-native-dropdownalert/master/screenshots/success.png)

### Props
| Name | Type | Description | Default |
| ---- | :---: | --- | --- |
| ```closeInterval``` | Number  | dismiss alert at a certain time in milliseconds | 4000
| ```imageSrc``` | String or Number  | local or network source | null
| ```startDelta``` | Number  | where the container starts (changes based on container height onLayout) | -100
| ```endDelta``` | Number  | where the container ends | 0
| ```onClose``` | Function  | Invoked when alert is closed Returns: ```data = {type, title, message, action}```  | null
| ```cancelBtnImageSrc``` | String or Number | local or network source | ```require('./assets/cancel.png')``` |
| ```titleNumOfLines``` | Number  | number of lines | 1
| ```messageNumOfLines``` | Number  | number of lines | 3
| ```onCancel``` | Function  | Cancel button action. Returns: ```data = {type, title, message, action}``` | null
| ```showCancel``` | Bool  | whether or not to show cancel button | false
| ```tapToCloseEnabled``` | Bool  | enable/disable close with tap | true
| ```panResponderEnabled``` | Bool  | enable/disable close with pan responder | true
| ```replaceEnabled``` | Bool  | enables the alert to either state change without dismissal or go to next alert with dismissal | true
| ```translucent``` | Bool  | StatusBar prop  | false
| ```activeStatusBarStyle``` | String  | StatusBar barStyle when alert is open | `light-content`
| ```activeStatusBarBackgroundColor``` | String | StatusBar backgroundColor when alert is open | It takes on the backgroundColor of alert if predefined else default or provided prop
| ```inactiveStatusBarStyle``` | String  | StatusBar barStyle when alert dismisses | `StatusBar._defaultProps.barStyle.value`
| ```inactiveStatusBarBackgroundColor``` | String  | StatusBar backgroundColor when alert dismisses | `StatusBar._defaultProps.backgroundColor.value`
| ```containerStyle``` | View.propTypes.style  | styles for container for custom type only | ```{ padding: 16, flexDirection: 'row' }```
| ```titleStyle``` | Text.propTypes.style  | styles for title for all types | ```{       fontSize: 16, textAlign: 'left', fontWeight: 'bold', color: 'white', backgroundColor: 'transparent' }```
| ```messageStyle``` | Text.propTypes.style  | styles for message for all types | ```{ fontSize: 14, textAlign: 'left', fontWeight: 'bold', color: 'white', backgroundColor: 'transparent' }```
| ```imageStyle``` | Image.propTypes.style  | styles for image for all types | ```{    padding: 8, width: 36, height: 36, alignSelf: 'center' }```
| ```cancelBtnImageStyle``` | Image.propTypes.style  | styles for image for all types | ```{    padding: 8, width: 36, height: 36, alignSelf: 'center' }```
| ```successColor``` | String  | Default background color of success message | #32A54A
| ```infoColor``` | String  | Default background color of info message | #2B73B6
| ```warnColor``` | String  | Default background color of warn message | #cd853f
| ```errorColor``` | String  | Default background color of error message | #cc3232

> Inspired by: [RKDropdownAlert](https://github.com/cwRichardKim/RKDropdownAlert)


text:
package qingcloud

import (
	"github.com/hashicorp/terraform/helper/schema"
	qc "github.com/yunify/qingcloud-sdk-go/service"
)

func modifyEipAttributes(d *schema.ResourceData, meta interface{}) error {
	clt := meta.(*QingCloudClient).eip
	input := new(qc.ModifyEIPAttributesInput)
	input.EIP = qc.String(d.Id())
	nameUpdate := false
	descriptionUpdate := false
	input.EIPName, nameUpdate = getNamePointer(d)
	input.Description, descriptionUpdate = getDescriptionPointer(d)
	if nameUpdate || descriptionUpdate {
		var err error
		simpleRetry(func() error {
			_, err = clt.ModifyEIPAttributes(input)
			return isServerBusy(err)
		})
		if err != nil {
			return err
		}
	}
	return nil
}
func changeEIPBandwidth(d *schema.ResourceData, meta interface{}) error {
	if d.HasChange(resourceEipBandwidth) && !d.IsNewResource() {
		clt := meta.(*QingCloudClient).eip
		input := new(qc.ChangeEIPsBandwidthInput)
		input.EIPs = []*string{qc.String(d.Id())}
		input.Bandwidth = qc.Int(d.Get(resourceEipBandwidth).(int))
		var err error
		simpleRetry(func() error {
			_, err = clt.ChangeEIPsBandwidth(input)
			return isServerBusy(err)
		})
		if err != nil {
			return err
		}
		if _, err := EIPTransitionStateRefresh(clt, d.Id()); err != nil {
			return nil
		}
	}
	return nil
}
func changeEIPBillMode(d *schema.ResourceData, meta interface{}) error {
	clt := meta.(*QingCloudClient).eip
	if d.HasChange(resourceEipBillMode) && !d.IsNewResource() {
		input := new(qc.ChangeEIPsBillingModeInput)
		input.EIPs = []*string{qc.String(d.Id())}
		input.BillingMode = qc.String(d.Get(resourceEipBillMode).(string))
		var err error
		simpleRetry(func() error {
			_, err = clt.ChangeEIPsBillingMode(input)
			return isServerBusy(err)
		})
		if err != nil {
			return err
		}
		if _, err := EIPTransitionStateRefresh(clt, d.Id()); err != nil {
			return nil
		}
	}
	return nil
}

func getEIPResourceMap(data *qc.EIP) map[string]interface{} {
	var a = make(map[string]interface{}, 3)
	a["resource_id"] = qc.StringValue(data.Resource.ResourceID)
	a["resource_name"] = qc.StringValue(data.Resource.ResourceName)
	a["resource_type"] = qc.StringValue(data.Resource.ResourceType)
	return a
}
func waitEipLease(d *schema.ResourceData, meta interface{}) error {
	if !d.IsNewResource() {
		return nil
	}
	clt := meta.(*QingCloudClient).eip
	input := new(qc.DescribeEIPsInput)
	input.EIPs = []*string{qc.String(d.Id())}
	input.Verbose = qc.Int(1)
	var output *qc.DescribeEIPsOutput
	var err error
	simpleRetry(func() error {
		output, err = clt.DescribeEIPs(input)
		return isServerBusy(err)
	})
	if err != nil {
		return err
	}
	//wait for lease info
	WaitForLease(output.EIPSet[0].StatusTime)
	return nil
}

func isEipDeleted(eipSet []*qc.EIP) bool {
	if len(eipSet) == 0 || qc.StringValue(eipSet[0].Status) == "ceased" || qc.StringValue(eipSet[0].Status) == "ceased" {
		return true
	}
	return false
}


text:
package com.orangerhymelabs.helenusdb.rest;

import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.jar.Manifest;

import org.restexpress.RestExpress;
import org.restexpress.common.exception.ConfigurationException;
import org.restexpress.util.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.orangerhymelabs.helenus.cassandra.CassandraConfig;
import com.orangerhymelabs.helenus.cassandra.database.DatabaseRepository;
import com.orangerhymelabs.helenus.cassandra.database.DatabaseService;
import com.orangerhymelabs.helenus.cassandra.document.DocumentRepositoryFactory;
import com.orangerhymelabs.helenus.cassandra.document.DocumentRepositoryFactoryImpl;
import com.orangerhymelabs.helenus.cassandra.document.DocumentService;
import com.orangerhymelabs.helenus.cassandra.index.IndexRepository;
import com.orangerhymelabs.helenus.cassandra.table.TableRepository;
import com.orangerhymelabs.helenus.cassandra.table.TableService;
import com.orangerhymelabs.helenusdb.rest.database.DatabaseController;
import com.orangerhymelabs.helenusdb.rest.document.DocumentController;
import com.orangerhymelabs.helenusdb.rest.table.TableController;
import com.strategicgains.restexpress.plugin.metrics.MetricsConfig;

public class Configuration
extends Environment
{
    private static final String DEFAULT_EXECUTOR_THREAD_POOL_SIZE = "20";

    private static final String PORT_PROPERTY = "port";
    private static final String BASE_URL_PROPERTY = "base.url";
    private static final String EXECUTOR_THREAD_POOL_SIZE = "executor.threadPool.size";

    private int port;
    private String baseUrl;
    private int executorThreadPoolSize;
    private MetricsConfig metricsSettings;
    private Manifest manifest;

    private DatabaseController databaseController;
    private TableController tableController;
    private DocumentController documentController;

    private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class);

    @Override
    public void fillValues(Properties p)
    {
        this.port = Integer.parseInt(p.getProperty(PORT_PROPERTY, String.valueOf(RestExpress.DEFAULT_PORT)));
        this.baseUrl = p.getProperty(BASE_URL_PROPERTY, "http://localhost:" + String.valueOf(port));
        this.executorThreadPoolSize = Integer.parseInt(p.getProperty(EXECUTOR_THREAD_POOL_SIZE, DEFAULT_EXECUTOR_THREAD_POOL_SIZE));
        this.metricsSettings = new MetricsConfig(p);
        CassandraConfig dbConfig = new CassandraConfig(p);
        initialize(dbConfig);
        loadManifest();
    }

    private void initialize(CassandraConfig dbConfig)
    {
        DatabaseRepository databaseRepository = new DatabaseRepository(dbConfig.getSession(), dbConfig.getKeyspace());
        TableRepository tableRepository = new TableRepository(dbConfig.getSession(), dbConfig.getKeyspace());
        IndexRepository indexRepository = new IndexRepository(dbConfig.getSession(), dbConfig.getKeyspace());
        DocumentRepositoryFactory documentRepositoryFactory = new DocumentRepositoryFactoryImpl(dbConfig.getSession(), dbConfig.getKeyspace(), indexRepository);

        DatabaseService databaseService = new DatabaseService(databaseRepository);
        TableService tableService = new TableService(databaseRepository, tableRepository);
        DocumentService documentService = new DocumentService(tableService, documentRepositoryFactory);

        databaseController = new DatabaseController(databaseService);
        tableController = new TableController(tableService);
        documentController = new DocumentController(documentService);

//        EventBus bus = new LocalEventBusBuilder()
//                .subscribe(new TableDeleteHandler(dbConfig.getSession()))
//                .subscribe(new DatabaseDeletedHandler(dbConfig.getSession()))
//                .build();
//        DomainEvents.addBus("local", bus);
    }

    public int getPort()
    {
        return port;
    }

    public String getBaseUrl()
    {
        return baseUrl;
    }

    public int getExecutorThreadPoolSize()
    {
        return executorThreadPoolSize;
    }

    public MetricsConfig getMetricsConfig()
    {
        return metricsSettings;
    }

    public DatabaseController getDatabaseController()
    {
        return databaseController;
    }

    public TableController getTableController()
    {
        return tableController;
    }

    public DocumentController getDocumentController()
    {
        return documentController;
    }

    public String getProjectName(String defaultName)
    {
        if (hasManifest())
        {
            String name = manifest.getMainAttributes().getValue("Project-Name");

            if (name != null)
            {
                return name;
            }
        }

        return defaultName;
    }

    public String getProjectVersion()
    {
        if (hasManifest())
        {
            String version = manifest.getMainAttributes().getValue("Project-Version");

            if (version != null)
            {
                return version;
            }

            return "0.0.0 (Project version not found in manifest)";
        }

        return "0.0.0 (Development version)";
    }

    private void loadManifest()
    {
        Class<?> type = this.getClass();
        String name = type.getSimpleName() + ".class";
        URL classUrl = type.getResource(name);

        if (classUrl != null && classUrl.getProtocol().startsWith("jar"))
        {
            String path = classUrl.toString();
            String manifestPath = path.substring(0, path.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
            try
            {
                manifest = new Manifest(new URL(manifestPath).openStream());
            } catch (IOException e)
            {
                throw new ConfigurationException(e);
            }
        }
    }

    private boolean hasManifest()
    {
        return (manifest != null);
    }
}


text:
package org.apache.bookkeeper.bookie;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.bookie.Journal.ForceWriteRequest;
import org.apache.bookkeeper.bookie.Journal.LastLogMark;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.conf.TestBKConfiguration;
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

/**
 * Test the bookie journal PageCache flush interval.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({JournalChannel.class, Journal.class})
@Slf4j
public class BookieJournalPageCacheFlushTest {

    private static final ByteBuf DATA = Unpooled.wrappedBuffer(new byte[]{});

    @Rule
    public TemporaryFolder tempDir = new TemporaryFolder();

    @SuppressWarnings("unchecked")
    private LinkedBlockingQueue<ForceWriteRequest> enableForceWriteThreadSuspension(
            CountDownLatch forceWriteThreadSuspendedLatch,
            Journal journal) throws InterruptedException {
        LinkedBlockingQueue<ForceWriteRequest> supportQueue = new LinkedBlockingQueue<>();
        BlockingQueue<ForceWriteRequest> forceWriteRequests = mock(BlockingQueue.class);
        doAnswer((Answer) (InvocationOnMock iom) -> {
            supportQueue.put(iom.getArgument(0));
            return null;
        }).when(forceWriteRequests).put(any(ForceWriteRequest.class));
        when(forceWriteRequests.take()).thenAnswer(i -> {
            // suspend the force write thread
            forceWriteThreadSuspendedLatch.await();
            return supportQueue.take();
        });
        Whitebox.setInternalState(journal, "forceWriteRequests", forceWriteRequests);
        return supportQueue;
    }

    @Test
    public void testAckAfterSyncPageCacheFlush() throws Exception {
        File journalDir = tempDir.newFolder();
        BookieImpl.checkDirectoryStructure(BookieImpl.getCurrentDirectory(journalDir));

        ServerConfiguration conf = TestBKConfiguration.newServerConfiguration()
                .setJournalDirName(journalDir.getPath())
                .setMetadataServiceUri(null)
                .setJournalAdaptiveGroupWrites(false)
                .setJournalSyncData(true)
                .setJournalPageCacheFlushIntervalMSec(5000);

        JournalChannel jc = spy(new JournalChannel(journalDir, 1));
        whenNew(JournalChannel.class).withAnyArguments().thenReturn(jc);

        LedgerDirsManager ledgerDirsManager = mock(LedgerDirsManager.class);
        Journal journal = new Journal(0, journalDir, conf, ledgerDirsManager);

        CountDownLatch forceWriteThreadSuspendedLatch = new CountDownLatch(1);
        LinkedBlockingQueue<ForceWriteRequest> supportQueue =
                enableForceWriteThreadSuspension(forceWriteThreadSuspendedLatch, journal);
        journal.start();

        LogMark lastLogMarkBeforeWrite = journal.getLastLogMark().markLog().getCurMark();
        CountDownLatch latch = new CountDownLatch(1);
        long ledgerId = 1;
        long entryId = 0;
        long startTime = System.currentTimeMillis();
        journal.logAddEntry(ledgerId, entryId, DATA, false /* ackBeforeSync */, new WriteCallback() {
            @Override
            public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {
                latch.countDown();
            }
        }, null);

        while (supportQueue.isEmpty()) {
            Thread.sleep(100);
        }

        // forceWriteRequest insert into forceWriteRequestQueue not effected by journalPageCacheFlushInterval
        assertTrue(System.currentTimeMillis() - startTime < 5000);

        assertEquals(1, latch.getCount());
        assertEquals(1, supportQueue.size());

        // in constructor of JournalChannel we are calling forceWrite(true) but it is not tracked by PowerMock
        // because the 'spy' is applied only on return from the constructor
        verify(jc, times(0)).forceWrite(true);

        // should not call forceWrite
        verify(jc, times(0)).forceWrite(false);

        // let ForceWriteThread work
        forceWriteThreadSuspendedLatch.countDown();
        // callback should complete now
        assertTrue(latch.await(20, TimeUnit.SECONDS));

        verify(jc, times(1)).forceWrite(false);
        assertEquals(0, supportQueue.size());

        // verify that log marker advanced
        LastLogMark lastLogMarkAfterForceWrite = journal.getLastLogMark();
        assertTrue(lastLogMarkAfterForceWrite.getCurMark().compare(lastLogMarkBeforeWrite) > 0);

        journal.shutdown();
    }

    @Test
    public void testAckBeforeSyncPageCacheFlush() throws Exception {
        File journalDir = tempDir.newFolder();
        BookieImpl.checkDirectoryStructure(BookieImpl.getCurrentDirectory(journalDir));

        ServerConfiguration conf = TestBKConfiguration.newServerConfiguration()
                .setJournalDirName(journalDir.getPath())
                .setMetadataServiceUri(null)
                .setJournalAdaptiveGroupWrites(false)
                .setJournalSyncData(true)
                .setJournalPageCacheFlushIntervalMSec(5000);

        JournalChannel jc = spy(new JournalChannel(journalDir, 1));
        whenNew(JournalChannel.class).withAnyArguments().thenReturn(jc);

        LedgerDirsManager ledgerDirsManager = mock(LedgerDirsManager.class);
        Journal journal = new Journal(0, journalDir, conf, ledgerDirsManager);

        CountDownLatch forceWriteThreadSuspendedLatch = new CountDownLatch(1);
        LinkedBlockingQueue<ForceWriteRequest> supportQueue =
                enableForceWriteThreadSuspension(forceWriteThreadSuspendedLatch, journal);
        journal.start();

        LogMark lastLogMarkBeforeWrite = journal.getLastLogMark().markLog().getCurMark();
        CountDownLatch latch = new CountDownLatch(1);
        long ledgerId = 1;
        long entryId = 0;
        long startTime = System.currentTimeMillis();
        journal.logAddEntry(ledgerId, entryId, DATA, true /* ackBeforeSync */, new WriteCallback() {
            @Override
            public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {
                latch.countDown();
            }
        }, null);

        while (supportQueue.isEmpty()) {
            Thread.sleep(100);
        }

        // forceWriteRequest insert into forceWriteRequestQueue not effected by journalPageCacheFlushInterval
        assertTrue(System.currentTimeMillis() - startTime < 5000);
        assertEquals(1, supportQueue.size());

        // callback should completed now
        assertTrue(latch.await(20, TimeUnit.SECONDS));

        // in constructor of JournalChannel we are calling forceWrite(true) but it is not tracked by PowerMock
        // because the 'spy' is applied only on return from the constructor
        verify(jc, times(0)).forceWrite(true);

        // we are never calling foreWrite
        verify(jc, times(0)).forceWrite(false);

        // verify that log marker did not advance
        LastLogMark lastLogMarkAfterForceWrite = journal.getLastLogMark();
        assertEquals(0, lastLogMarkAfterForceWrite.getCurMark().compare(lastLogMarkBeforeWrite));

        // let the forceWriteThread exit
        forceWriteThreadSuspendedLatch.countDown();

        journal.shutdown();
    }

    @Test
    public void testAckBeforeUnSyncPageCacheFlush() throws Exception {
        File journalDir = tempDir.newFolder();
        BookieImpl.checkDirectoryStructure(BookieImpl.getCurrentDirectory(journalDir));

        ServerConfiguration conf = TestBKConfiguration.newServerConfiguration()
                .setJournalDirName(journalDir.getPath())
                .setMetadataServiceUri(null)
                .setJournalAdaptiveGroupWrites(false)
                .setJournalSyncData(false)
                .setJournalPageCacheFlushIntervalMSec(5000);

        JournalChannel jc = spy(new JournalChannel(journalDir, 1));
        whenNew(JournalChannel.class).withAnyArguments().thenReturn(jc);

        LedgerDirsManager ledgerDirsManager = mock(LedgerDirsManager.class);
        Journal journal = new Journal(0, journalDir, conf, ledgerDirsManager);

        CountDownLatch forceWriteThreadSuspendedLatch = new CountDownLatch(1);
        LinkedBlockingQueue<ForceWriteRequest> supportQueue =
                enableForceWriteThreadSuspension(forceWriteThreadSuspendedLatch, journal);
        journal.start();

        CountDownLatch latch = new CountDownLatch(2);
        long ledgerId = 1;
        long entryId = 0;
        LogMark lastLogMarkBeforeWrite = journal.getLastLogMark().markLog().getCurMark();
        journal.logAddEntry(ledgerId, entryId, DATA, true, new WriteCallback() {
            @Override
            public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {
                latch.countDown();
            }
        }, null);

        // the forceWriteRequest should not generated because of journalPageCacheFlushIntervalMSec control
        assertEquals(0, supportQueue.size());

        // wait journalPageCacheFlushIntervalMsec timeout
        Thread.sleep(10000);

        // add an entry to journal, wake up journal main thread which is blocked on queue.take()
        journal.logAddEntry(ledgerId, entryId + 1, DATA, true, new WriteCallback() {
            @Override
            public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {
                latch.countDown();
            }
        }, null);

        // wait forceWriteRequest generated
        while (supportQueue.isEmpty()) {
            Thread.sleep(100);
        }

        // only one forceWriteRequest inserted into forceWriteRequestQueue
        assertEquals(1, supportQueue.size());

        // callback should completed now
        assertTrue(latch.await(20, TimeUnit.SECONDS));

        // in constructor of JournalChannel we are calling forceWrite(true) but it is not tracked by PowerMock
        // because the 'spy' is applied only on return from the constructor
        verify(jc, times(0)).forceWrite(true);

        // we are never calling foreWrite
        verify(jc, times(0)).forceWrite(false);

        // verify that log marker did not advance
        LastLogMark lastLogMarkAfterForceWrite = journal.getLastLogMark();
        assertEquals(0, lastLogMarkAfterForceWrite.getCurMark().compare(lastLogMarkBeforeWrite));

        // let the forceWriteThread exit
        forceWriteThreadSuspendedLatch.countDown();

        journal.shutdown();
    }
}


text:
<?php
namespace Baijian\Algorithm;

use Baijian\Algorithm\AhoCorasick;

class AhoCorasickTest extends \PHPUnit_Framework_TestCase {

    public function testEmpty() {
        $stack = array();
        $this->assertEmpty($stack);
        return $stack;
    }
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->
Full Development Platform
=========================

This project fully automates the provisioning and deployment of Apache Metron and all necessary prerequisites on a single, virtualized host running on Virtualbox.

Metron is composed of many components and installing all of these on a single host, especially a virtualized one, will greatly stress the resources of the host.   The host will require at least 8 GB of RAM and a fair amount of patience.  It is highly recommended that you shut down all unnecessary services.  To that end the vagrant file configuration defaults to disabling solr and yaf.

Getting Started
---------------

### Prerequisites

The computer used to deploy Apache Metron will need to have the following components installed.

 - [Ansible](https://github.com/ansible/ansible) (2.0.0.2 or 2.2.2.0)
 - [Docker](https://www.docker.com/community-edition)
 - [Vagrant](https://www.vagrantup.com) 1.8+
 - [Vagrant Hostmanager Plugin](https://github.com/devopsgroup-io/vagrant-hostmanager)
 - [Virtualbox](https://virtualbox.org) 5.0+
 - Python 2.7
 - Maven 3.3.9
 - C++11 compliant compiler, like [GCC](https://gcc.gnu.org/projects/cxx-status.html#cxx11)

Running the following script can help validate whether you have all the prerequisites installed and running correctly.

  ```
  metron-deployment/scripts/platform-info.sh
  ```

#### How do I install these on MacOS?

Any platform that supports these tools is suitable, but the following instructions cover installation on macOS.  The easiest means of installing these tools on a Mac is to use the excellent [Homebrew](http://brew.sh/) project.

1. Install Homebrew by following the instructions at [Homebrew](http://brew.sh/).

1. Run the following command in a terminal to install all of the required tools.

    ```
    brew cask install vagrant virtualbox docker
    brew cask install caskroom/versions/java8
    brew install maven@3.3 git
    pip install ansible==2.2.2.0
    vagrant plugin install vagrant-hostmanager
    open /Applications/Docker.app
    ```

### Deploy Metron

1. Ensure that the Docker service is running.

1. Deploy Metron

    ```
    cd metron-deployment/vagrant/full-dev-platform
    vagrant up
    ```

    Should the process fail before completing the deployment, the following command will continue the deployment process without re-instantiating the host.

    ```
    vagrant provision
    ```

### Explore Metron

Navigate to the following resources to explore your newly minted Apache Metron environment.

 - [Ambari](http://node1:8080)
 - [Metron](http://node1:5000)
 - [Services](http://node1:2812)

Connecting to the host through SSH is as simple as running the following command.

```
vagrant ssh
```

### Working with Metron

In addition to re-running the entire provisioning play book, you may now re-run an individual Ansible tag or a collection of tags in the following ways.  The following commands will re-run the `web` role on the Vagrant image. This will install components (if necessary) and start the UI.

```
./run_ansible_role.sh web
```
or

```
vagrant --ansible-tags="web" provision
```

#### Using Tags

A collection of tags is specified as a comma separated list.

```
./run_ansible_role.sh "sensors,enrichment"

```

Tags are listed in the playbooks, some frequently used tags:
+ `hdp-install` - Install HDP
+ `hdp-deploy` - Deploy and Start HDP Services (will start all Hadoop Services)
+ `sensors` - Deploy and Start Sensors.
+ `enrichment` - Deploy and Start Enrichment Topology.

Note also that there is a convenience script `./run_enrichment_role.sh`  which executes Vagrant with the `enrichment` tag.


text:
var str = 'Reverse me';

console.log(reverseString(str));

function reverseString(str){
    return str.split('').reverse().join('');
}


text:
/*
 * GeneratorsBenchmark.h
 *
 *  Created on: May 29, 2013
 *      Author: forigem
 */

#ifndef NOGTEST

#ifndef GENERATORSBENCHMARK_H_
#define GENERATORSBENCHMARK_H_

#include <gtest/gtest.h>

#include "../../auxiliary/Timer.h"

namespace NetworKit {

class GeneratorsBenchmark: public testing::Test {
protected:
	template <typename L>
	uint64_t timeOnce(L f) {
		// TODO should be moved somewhere else (Benchmark parent class or the Timer class itself)
		Aux::Timer timer;
		timer.start();
		f();
		timer.stop();
		return timer.elapsedMilliseconds();
	}
};

} /* namespace NetworKit */
#endif /* GENERATORSBENCHMARK_H_ */

#endif /*NOGTEST */


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Google.Protobuf;
using POGOLib.Official.Extensions;
using POGOLib.Official.Logging;
using POGOLib.Official.Util;
using POGOProtos.Networking.Envelopes;
using POGOProtos.Networking.Platform;
using POGOProtos.Networking.Platform.Requests;
using static POGOProtos.Networking.Envelopes.Signature.Types;
using static POGOProtos.Networking.Envelopes.RequestEnvelope.Types;

namespace POGOLib.Official.Net
{
    internal class RpcEncryption
    {

        /// <summary>
        /// The authenticated <see cref="Session"/>.
        /// </summary>
        private readonly Session _session;

        /// <summary>
        /// The <see cref="Stopwatch"/> that has been running since <see cref="Session.StartupAsync"/>.
        /// </summary>
        private readonly Stopwatch _stopwatch;

        /// <summary>
        /// The session hash for the <see cref="Signature"/> which is 16 randomly generated bytes.
        /// </summary>
        private readonly ByteString _sessionHash;

        /// <summary>
        /// Holds the value that was used in the previous <see cref="BuildLocationFixes"/> iteration.
        /// </summary>
        private long _lastTimestampSinceStart;

        internal RpcEncryption(Session session)
        {
            _session = session;
            _stopwatch = Stopwatch.StartNew();

            var sessionHash = new byte[16];
            session.Random.NextBytes(sessionHash);

            _sessionHash = ByteString.CopyFrom(sessionHash);
            _lastTimestampSinceStart = 0;
        }

        private long TimestampSinceStartMs => _stopwatch.ElapsedMilliseconds;

        /// <summary>
        /// Generates a few random <see cref="LocationFix"/>es to act like a real GPS sensor.
        /// </summary>
        /// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> these <see cref="LocationFix"/>es are used for.</param>
        /// <param name="timestampSinceStart">The milliseconds passed since starting the <see cref="Session"/> used by the current <see cref="RequestEnvelope"/>.</param>
        /// <returns></returns>
        private List<LocationFix> BuildLocationFixes(RequestEnvelope requestEnvelope, long timestampSinceStart)
        {
            var locationFixes = new List<LocationFix>();

            if (requestEnvelope.Requests.Count == 0 || requestEnvelope.Requests[0] == null)
                return locationFixes;

            // Determine amount of location fixes.
            //      We look for the amount of seconds that have passed since the last location fixes request.
            //      If that results in 0, send 1 location fix.
            var millisecondsPerFix = _session.Random.Next(995, 999);
            var providerCount = Math.Min((timestampSinceStart - _lastTimestampSinceStart) / millisecondsPerFix, _session.Random.Next(8, 11));
            if (providerCount == 0)
                providerCount = 1;

            // Determine size of the "play around" window.
            //      Not so relevant when starting up.
            var totalMilliseconds = providerCount * millisecondsPerFix;
            var baseTimestampSnapshot = Math.Max(timestampSinceStart - totalMilliseconds, 0);
            var playAroundWindow = baseTimestampSnapshot - _lastTimestampSinceStart;

            if (playAroundWindow == 0 && providerCount == 1 && millisecondsPerFix >= timestampSinceStart)
            {
                // We really need an offset for this one..
                playAroundWindow = _session.Random.Next(0, (int) timestampSinceStart);
            }
            else
            {
                // A small offset between location fixes.
                playAroundWindow = Math.Min(playAroundWindow, providerCount * 2);
            }

            // Share "play around" window over all location fixes.
            var playAroundWindowPart = playAroundWindow != 0
                ? playAroundWindow / providerCount
                : 1;

            for (var i = 0; i < providerCount; i++)
            {
                var timestampSnapshot = baseTimestampSnapshot;
                // Apply current location fix position.
                timestampSnapshot += i * millisecondsPerFix;
                // Apply an offset.
                timestampSnapshot += _session.Random.Next(0, (int) ((i + 1) * playAroundWindowPart));

                locationFixes.Add(new LocationFix
                {
                    TimestampSnapshot = (ulong) timestampSnapshot,
                    Latitude = LocationUtil.OffsetLatitudeLongitude(_session.Player.Coordinate.Latitude, _session.Random.Next(100) + 10),
                    Longitude = LocationUtil.OffsetLatitudeLongitude(_session.Player.Coordinate.Longitude, _session.Random.Next(100) + 10),
                    HorizontalAccuracy = (float) _session.Random.NextDouble(5.0, 25.0),
                    VerticalAccuracy = (float) _session.Random.NextDouble(5.0, 25.0),
                    Altitude = (float) _session.Random.NextDouble(10.0, 30.0),
                    Provider = "fused",
                    ProviderStatus = 3,
                    LocationType = 1,
                    Course = -1,
                    Speed = -1
                    // Floor = 0
                });
            }

            _lastTimestampSinceStart = timestampSinceStart;

            return locationFixes;
        }

        /// <summary>
        /// Generates the encrypted signature which is required for the <see cref="RequestEnvelope"/>.
        /// </summary>
        /// <returns>The encrypted <see cref="PlatformRequest"/>.</returns>
        internal async Task<PlatformRequest> GenerateSignatureAsync(RequestEnvelope requestEnvelope)
        {
            if (Configuration.Hasher == null)
            {
                throw new NullReferenceException($"{nameof(Configuration.Hasher)} is not set, which is required to send valid calls to PokemonGo.");
            }

            var timestampSinceStart = TimestampSinceStartMs;
            var locationFixes = BuildLocationFixes(requestEnvelope, timestampSinceStart);
            var locationFix = locationFixes.Last();

            _session.Player.Coordinate.HorizontalAccuracy = locationFix.HorizontalAccuracy;
            _session.Player.Coordinate.VerticalAccuracy = locationFix.VerticalAccuracy;
            _session.Player.Coordinate.Altitude = locationFix.Altitude;

            requestEnvelope.Accuracy = _session.Player.Coordinate.Altitude; // _session.Player.Coordinate.HorizontalAccuracy;
            requestEnvelope.MsSinceLastLocationfix = timestampSinceStart - (long) locationFix.TimestampSnapshot;

            var signature = new Signature
            {
                TimestampSinceStart = (ulong)timestampSinceStart,
                Timestamp = (ulong)TimeUtil.GetCurrentTimestampInMilliseconds(),
                SensorInfo =
                {
                    new SensorInfo
                    {
                        TimestampSnapshot = (ulong) (timestampSinceStart + _session.Random.Next(100, 250)),
                        LinearAccelerationX = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationY = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationZ = -0.7 + _session.Random.NextDouble() * 1.4,
                        RotationRateX = 0.7 * _session.Random.NextDouble(),
                        RotationRateY = 0.8 * _session.Random.NextDouble(),
                        RotationRateZ = 0.8 * _session.Random.NextDouble(),
                        AttitudePitch = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeRoll = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeYaw = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityX = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityY = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityZ = -1.0 + _session.Random.NextDouble() * 2.0,
                        MagneticFieldAccuracy = -1,
                        Status = 3
                    }
                },
                DeviceInfo = _session.DeviceInfo,
                LocationFix = { locationFixes },
                ActivityStatus = new ActivityStatus
                {
                    Stationary = true
                }
            };

            // Hashing
            signature.SessionHash = _sessionHash;
            signature.Unknown25 = Configuration.Hasher.Unknown25;

            var serializedTicket = requestEnvelope.AuthTicket != null ? requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray();
            var locationBytes = BitConverter.GetBytes(_session.Player.Coordinate.Latitude).Reverse()
                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Longitude).Reverse())
                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Altitude).Reverse()).ToArray();

            var requestsBytes = requestEnvelope.Requests.Select(x => x.ToByteArray()).ToArray();
            var hashData = await Configuration.Hasher.GetHashDataAsync(requestEnvelope, signature, locationBytes, requestsBytes, serializedTicket);

            signature.LocationHash1 = (int) hashData.LocationAuthHash;
            signature.LocationHash2 = (int) hashData.LocationHash;

            signature.RequestHash.AddRange(hashData.RequestHashes);

            var encryptedSignature = new PlatformRequest
            {
                Type = PlatformRequestType.SendEncryptedSignature,
                RequestMessage = new SendEncryptedSignatureRequest
                {
                    EncryptedSignature = ByteString.CopyFrom(Configuration.Hasher.GetEncryptedSignature(signature.ToByteArray(), (uint)timestampSinceStart))
                }.ToByteString()
            };

            return encryptedSignature;
        }

    }
}


text:
import { TestBed, waitForAsync } from '@angular/core/testing';
import { MatIconModule } from '@angular/material/icon';
import { RouterTestingModule } from '@angular/router/testing';
// import { of } from 'rxjs';
import { FakePage } from 'src/test-utils';
import { LoginApi } from '../api/login-api.service';
// import { DashboardApi } from '../api/dashboard-api.service';
import { PerformanceApi } from '../api/performance-api.service';

import { App } from './app.component';
import { AppModule } from './app.module';

describe('App', () => {
  const fakeDashboardApi = {
    // dashPerformanceEmitter: of([]),
    // eslint-disable-next-line prefer-arrow/prefer-arrow-functions
    loadAllPerformances() {
    }
  } as PerformanceApi;
  const fakeLoginApi = {loginPromise: Promise.resolve()} as LoginApi;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        App,
        FakePage,
      ],
      imports: [
        MatIconModule,
        RouterTestingModule.withRoutes([
          { path: `dashboard`, component: FakePage },
        ]),
        AppModule,
      ],
      providers: [
        { provide: PerformanceApi, useValue: fakeDashboardApi },
        { provide: LoginApi, useValue: fakeLoginApi },
      ]
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(App);
    const app = fixture.componentInstance;

    expect(app).toBeTruthy();
  });

  it(`should have as title 'rolecall'`, () => {
    const fixture = TestBed.createComponent(App);
    const app = fixture.componentInstance;

    expect(app.title).toEqual('rolecall');
  });
});


text:
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';

import { TabBar } from '../../ui-utils';

FlowRouter.route('/snippet/:snippetId/:snippetName', {
	name: 'snippetView',
	action() {
		BlazeLayout.render('main', { center: 'snippetPage', flexTabBar: null });
	},
	triggersEnter: [function() {
		TabBar.hide();
	}],
	triggersExit: [
		function() {
			TabBar.show();
		},
	],
});


text:
import gzip
import nltk
import operator
import numpy as np

from nltk.corpus import stopwords
from collections import defaultdict
from nltk.stem import SnowballStemmer
from nltk.tokenize import RegexpTokenizer

tokenizer 	= RegexpTokenizer(r'\w+')
stop 		= set(stopwords.words('english'))
stemmer 	= SnowballStemmer("english")

class Mapping:

	def __init__(self, QAfile, ReviewFile, minReview):

		self.QAfile 		= QAfile
		self.ReviewFile 	= ReviewFile
		self.minReview		= minReview
		self.V 			= 5000
		self.Vocublary  	= defaultdict(int)
		self.WordIDMap  	= {}
		self.RWordIDMap  	= {}
		self.ItemIDMap   	= {}
		self.RItemIDMap  	= {}

	def create_mappings(self):

		print "Creating Mapping\n"
		print "Reading Question Answer"

		ItemsToMaybeKeep 	= {}
		qa 			= gzip.open(self.QAfile, 'r')

		for l in qa:

			qajson 		= eval(l)
			item 		= qajson['asin']

			question    	= tokenizer.tokenize(qajson['question'])
			answer 		= tokenizer.tokenize(qajson['answer'])

			for word in question:
				if stemmer.stem(word) not in stop:
					self.Vocublary[stemmer.stem(word)]+=1

			for word in answer:
				if stemmer.stem(word) not in stop:
					self.Vocublary[stemmer.stem(word)]+=1

			if item not in ItemsToMaybeKeep:
				ItemsToMaybeKeep[item] = 0

		del qa
		print "Read Question Answer\n"

		print "Number of Items for which there exists a questions\n", len(ItemsToMaybeKeep)

		print "Reading Reviews"
		review = gzip.open(self.ReviewFile, 'r')

		for l in review:

			reviewjson 	= eval(l)
			item 		= reviewjson['asin']

			review 		= tokenizer.tokenize(reviewjson['reviewText'])

			for word in review:
				if stemmer.stem(word) not in stop:
					self.Vocublary[stemmer.stem(word)]+=1

			if item in ItemsToMaybeKeep:
				ItemsToMaybeKeep[item]+=1

		del review
		print "Read Reviews\n"

		count 	= 0

		for (key,value) in ItemsToMaybeKeep.items():
			if value >= self.minReview:
				self.ItemIDMap[key] 	= count
				self.RItemIDMap[count] 	= key
				count 			= count + 1

		temp_vocab = sorted(self.Vocublary.items(), key = operator.itemgetter(1))

		if (len(temp_vocab) > 5000):
			print "Pre-sorting Vocublary length is %d"%(len(temp_vocab))
			temp_vocab = temp_vocab[len(temp_vocab)-5000:]

		self.Vocublary 	= dict(temp_vocab)
		self.V 		= len(self.Vocublary)
		count 		= 0

		for (key,value) in self.Vocublary.items():

			self.WordIDMap[key] 	= count
			self.RWordIDMap[count] 	= key
			count 			= count + 1

		X = sorted(self.Vocublary.items(), key = operator.itemgetter(1))

		#Uncomment this for printing out the Vocubalary. It was used during different model testing
		'''
		for i in range(len(X)-1, -1, -1):
			print X[i][0]," : ",X[i][1]
		'''

		if count != self.V:
			print "\nCount does not equals to Vocublary!!\n"

		print "\nMappings Created\n"


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.communote.plugins.api.rest.v24.resource.user (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

com.communote.plugins.api.rest.v24.resource.user

Classes

CreateUserParameter

EditUserParameter

GetCollectionUserParameter

GetUserParameter

UserResource

UserResourceConverter

UserResourceHandler

UserResourceValidator


text:
ACCEPTED

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

#### Published in
Interpr. Herb. amboin. 274. 1917

#### Original name
Phaseolus max L.

### Remarks
null


text:
call = Tropo::TropoCall.new($incomingCall)
call.answer

options = { :choices => '1,2' }

result = call.ask 'Hi. For sales, press 1. For support, press 2.', options
call.log result

if result.name == 'choice'
  case result.value
  when '1'
    call.say 'sales is not available right now.'
  when '2'
	  call.say 'support is currently on the other line.'
	end
end

call.hangup


text:
@interface XCFTopicCell ()
@property (weak, nonatomic) IBOutlet UIImageView *icon;         // 头像
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;        // 作者名称
@property (weak, nonatomic) IBOutlet UIImageView *stickIcon;    // 置顶标识
@property (weak, nonatomic) IBOutlet UILabel *topicTitle;       // 标题
@property (weak, nonatomic) IBOutlet UILabel *updateTime;       // 最后回应
@property (weak, nonatomic) IBOutlet UILabel *commentsCount;    // 评论数
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topicLabelLeftCon;
@end

@implementation XCFTopicCell

- (void)setTopic:(XCFTopic *)topic {
    _topic = topic;

    if (topic.is_sticked) {
        self.stickIcon.hidden = NO;
        self.topicLabelLeftCon.constant = 30;
    } else {
        self.stickIcon.hidden = YES;
        self.topicLabelLeftCon.constant = 15;
    }

    [self.icon setHeaderWithURL:[NSURL URLWithString:topic.author.photo60]];
    self.nameLabel.text = topic.author.name;
    self.topicTitle.text = topic.content;
    self.updateTime.text = [NSString stringWithFormat:@"最后回应:%@", topic.update_time];
    self.commentsCount.text = [NSString stringWithFormat:@"%@评论", topic.n_comments];

}

@end


text:
#ifndef _BFIN_ROTARY_H
#define _BFIN_ROTARY_H

/* mode bitmasks */
#define ROT_QUAD_ENC	CNTMODE_QUADENC	/* quadrature/grey code encoder mode */
#define ROT_BIN_ENC	CNTMODE_BINENC	/* binary encoder mode */
#define ROT_UD_CNT	CNTMODE_UDCNT	/* rotary counter mode */
#define ROT_DIR_CNT	CNTMODE_DIRCNT	/* direction counter mode */

#define ROT_DEBE	DEBE		/* Debounce Enable */

#define ROT_CDGINV	CDGINV		/* CDG Pin Polarity Invert */
#define ROT_CUDINV	CUDINV		/* CUD Pin Polarity Invert */
#define ROT_CZMINV	CZMINV		/* CZM Pin Polarity Invert */

struct bfin_rotary_platform_data {
	/* set rotary UP KEY_### or BTN_### in case you prefer
	 * bfin-rotary to send EV_KEY otherwise set 0
	 */
	unsigned int rotary_up_key;
	/* set rotary DOWN KEY_### or BTN_### in case you prefer
	 * bfin-rotary to send EV_KEY otherwise set 0
	 */
	unsigned int rotary_down_key;
	/* set rotary BUTTON KEY_### or BTN_### */
	unsigned int rotary_button_key;
	/* set rotary Relative Axis REL_### in case you prefer
	 * bfin-rotary to send EV_REL otherwise set 0
	 */
	unsigned int rotary_rel_code;
	unsigned short debounce;	/* 0..17 */
	unsigned short mode;
	unsigned short pm_wakeup;
	unsigned short *pin_list;
};

/* CNT_CONFIG bitmasks */
#define CNTE		(1 << 0)	/* Counter Enable */
#define DEBE		(1 << 1)	/* Debounce Enable */
#define CDGINV		(1 << 4)	/* CDG Pin Polarity Invert */
#define CUDINV		(1 << 5)	/* CUD Pin Polarity Invert */
#define CZMINV		(1 << 6)	/* CZM Pin Polarity Invert */
#define CNTMODE_SHIFT	8
#define CNTMODE		(0x7 << CNTMODE_SHIFT)	/* Counter Operating Mode */
#define ZMZC		(1 << 1)	/* CZM Zeroes Counter Enable */
#define BNDMODE_SHIFT	12
#define BNDMODE		(0x3 << BNDMODE_SHIFT)	/* Boundary register Mode */
#define INPDIS		(1 << 15)	/* CUG and CDG Input Disable */

#define CNTMODE_QUADENC	(0 << CNTMODE_SHIFT)	/* quadrature encoder mode */
#define CNTMODE_BINENC	(1 << CNTMODE_SHIFT)	/* binary encoder mode */
#define CNTMODE_UDCNT	(2 << CNTMODE_SHIFT)	/* up/down counter mode */
#define CNTMODE_DIRCNT	(4 << CNTMODE_SHIFT)	/* direction counter mode */
#define CNTMODE_DIRTMR	(5 << CNTMODE_SHIFT)	/* direction timer mode */

#define BNDMODE_COMP	(0 << BNDMODE_SHIFT)	/* boundary compare mode */
#define BNDMODE_ZERO	(1 << BNDMODE_SHIFT)	/* boundary compare and zero mode */
#define BNDMODE_CAPT	(2 << BNDMODE_SHIFT)	/* boundary capture mode */
#define BNDMODE_AEXT	(3 << BNDMODE_SHIFT)	/* boundary auto-extend mode */

/* CNT_IMASK bitmasks */
#define ICIE		(1 << 0)	/* Illegal Gray/Binary Code Interrupt Enable */
#define UCIE		(1 << 1)	/* Up count Interrupt Enable */
#define DCIE		(1 << 2)	/* Down count Interrupt Enable */
#define MINCIE		(1 << 3)	/* Min Count Interrupt Enable */
#define MAXCIE		(1 << 4)	/* Max Count Interrupt Enable */
#define COV31IE		(1 << 5)	/* Bit 31 Overflow Interrupt Enable */
#define COV15IE		(1 << 6)	/* Bit 15 Overflow Interrupt Enable */
#define CZEROIE		(1 << 7)	/* Count to Zero Interrupt Enable */
#define CZMIE		(1 << 8)	/* CZM Pin Interrupt Enable */
#define CZMEIE		(1 << 9)	/* CZM Error Interrupt Enable */
#define CZMZIE		(1 << 10)	/* CZM Zeroes Counter Interrupt Enable */

/* CNT_STATUS bitmasks */
#define ICII		(1 << 0)	/* Illegal Gray/Binary Code Interrupt Identifier */
#define UCII		(1 << 1)	/* Up count Interrupt Identifier */
#define DCII		(1 << 2)	/* Down count Interrupt Identifier */
#define MINCII		(1 << 3)	/* Min Count Interrupt Identifier */
#define MAXCII		(1 << 4)	/* Max Count Interrupt Identifier */
#define COV31II		(1 << 5)	/* Bit 31 Overflow Interrupt Identifier */
#define COV15II		(1 << 6)	/* Bit 15 Overflow Interrupt Identifier */
#define CZEROII		(1 << 7)	/* Count to Zero Interrupt Identifier */
#define CZMII		(1 << 8)	/* CZM Pin Interrupt Identifier */
#define CZMEII		(1 << 9)	/* CZM Error Interrupt Identifier */
#define CZMZII		(1 << 10)	/* CZM Zeroes Counter Interrupt Identifier */

/* CNT_COMMAND bitmasks */
#define W1LCNT		0xf		/* Load Counter Register */
#define W1LMIN		0xf0		/* Load Min Register */
#define W1LMAX		0xf00		/* Load Max Register */
#define W1ZMONCE	(1 << 12)	/* Enable CZM Clear Counter Once */

#define W1LCNT_ZERO	(1 << 0)	/* write 1 to load CNT_COUNTER with zero */
#define W1LCNT_MIN	(1 << 2)	/* write 1 to load CNT_COUNTER from CNT_MIN */
#define W1LCNT_MAX	(1 << 3)	/* write 1 to load CNT_COUNTER from CNT_MAX */

#define W1LMIN_ZERO	(1 << 4)	/* write 1 to load CNT_MIN with zero */
#define W1LMIN_CNT	(1 << 5)	/* write 1 to load CNT_MIN from CNT_COUNTER */
#define W1LMIN_MAX	(1 << 7)	/* write 1 to load CNT_MIN from CNT_MAX */

#define W1LMAX_ZERO	(1 << 8)	/* write 1 to load CNT_MAX with zero */
#define W1LMAX_CNT	(1 << 9)	/* write 1 to load CNT_MAX from CNT_COUNTER */
#define W1LMAX_MIN	(1 << 10)	/* write 1 to load CNT_MAX from CNT_MIN */

/* CNT_DEBOUNCE bitmasks */
#define DPRESCALE	0xf		/* Load Counter Register */

#endif


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

package org.chromium.chrome.browser.autofill_assistant.user_data;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill_assistant.AssistantChevronStyle;
import org.chromium.chrome.browser.autofill_assistant.LayoutUtils;
import org.chromium.content.browser.input.PopupItemType;
import org.chromium.content.browser.input.SelectPopupDialog;
import org.chromium.content.browser.input.SelectPopupItem;
import org.chromium.content.browser.picker.InputDialogContainer;
import org.chromium.content.browser.picker.InputDialogContainer.InputActionDelegate;
import org.chromium.ui.base.ime.TextInputType;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * A section which allows the user to specify a single date/time value.
 */
public class AssistantDateSection {
    interface Delegate {
        void onDateChanged(@Nullable AssistantDateTime date);
        void onTimeSlotChanged(@Nullable Integer index);
    }

    private final Context mContext;
    private final LinearLayout mRootLayout;
    private final TextView mDateSummaryView;
    private final TextView mTimeSummaryView;
    private final int mTitleToContentPadding;
    private final Locale mLocale;
    private final DateFormat mDateTimeFormat;
    @Nullable
    private Delegate mDelegate;
    @Nullable
    private AssistantDateChoiceOptions mDateChoiceOptions;
    private @Nullable AssistantDateTime mCurrentValue;
    private @Nullable AssistantDateTime mCalendarFallbackValue;
    private @Nullable Integer mCurrentTimeSlot;
    private String mDateNotSetErrorMessage;
    private String mTimeNotSetErrorMessage;

    AssistantDateSection(Context context, ViewGroup parent, Locale locale, DateFormat dateFormat) {
        mContext = context;
        mLocale = locale;
        mDateTimeFormat = dateFormat;
        mTitleToContentPadding = context.getResources().getDimensionPixelSize(
                R.dimen.autofill_assistant_payment_request_title_padding);

        LayoutInflater inflater = LayoutUtils.createInflater(context);
        mRootLayout = (LinearLayout) inflater.inflate(R.layout.autofill_assistant_datetime, null);
        mRootLayout.setVisibility(View.GONE);

        AssistantVerticalExpander dateExpander = mRootLayout.findViewById(R.id.date_expander);
        AssistantVerticalExpander timeExpander = mRootLayout.findViewById(R.id.time_expander);

        setupExpander(context, dateExpander);
        setupExpander(context, timeExpander);
        mDateSummaryView = (TextView) dateExpander.getCollapsedView();
        mTimeSummaryView = (TextView) timeExpander.getCollapsedView();

        dateExpander.getTitleAndChevronContainer().setOnClickListener(unusedView -> {
            if (mDateChoiceOptions == null) {
                return;
            }
            InputDialogContainer inputDialogContainer =
                    new InputDialogContainer(mContext, new InputActionDelegate() {
                        @Override
                        public void cancelDateTimeDialog() {
                            // Do nothing.
                        }

                        @Override
                        public void replaceDateTime(double value) {
                            // User tapped the 'clear' button.
                            if (Double.isNaN(value)) {
                                setCurrentDate(null);
                            } else {
                                setCurrentDate(new AssistantDateTime((long) value));
                            }
                        }
                    });

            double selectedValue = Double.NaN;
            if (mCurrentValue != null) {
                selectedValue = mCurrentValue.getTimeInUtcMillis();
            } else if (mCalendarFallbackValue != null) {
                selectedValue = mCalendarFallbackValue.getTimeInUtcMillis();
            }
            inputDialogContainer.showDialog(TextInputType.DATE, selectedValue,
                    mDateChoiceOptions.getMinDate().getTimeInUtcMillis(),
                    mDateChoiceOptions.getMaxDate().getTimeInUtcMillis(), -1, null);
        });

        timeExpander.getTitleAndChevronContainer().setOnClickListener(unusedView -> {
            if (mDateChoiceOptions == null) {
                return;
            }
            List<SelectPopupItem> items = new ArrayList<>();
            for (int i = 0; i < mDateChoiceOptions.getTimeSlots().size(); i++) {
                items.add(new SelectPopupItem(
                        mDateChoiceOptions.getTimeSlots().get(i), PopupItemType.ENABLED));
            }

            SelectPopupDialog dialog = new SelectPopupDialog(context,
                    (indices)
                            -> {
                        if (indices == null) {
                            return;
                        }
                        setCurrentTimeSlot(indices[0]);
                    },
                    items, false,
                    mCurrentTimeSlot != null ? new int[] {mCurrentTimeSlot} : new int[] {});
            dialog.show();
        });

        updateDateSummaryView();
        updateTimeSummaryView();
        parent.addView(mRootLayout,
                new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    /** Common view configuration for the vertical expanders. */
    private void setupExpander(Context context, AssistantVerticalExpander expander) {
        View titleView = LayoutUtils.createInflater(context).inflate(
                R.layout.autofill_assistant_payment_request_section_title, null);
        TextView summaryView = new TextView(context);
        summaryView.setSingleLine();

        expander.setTitleView(titleView,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        expander.setCollapsedView(summaryView,
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        expander.setFixed(true);
        expander.setChevronStyle(AssistantChevronStyle.ALWAYS);
        expander.findViewById(R.id.section_title_add_button).setVisibility(View.GONE);
    }

    void setDateChoiceOptions(AssistantDateChoiceOptions dateChoiceOptions) {
        mDateChoiceOptions = dateChoiceOptions;
    }

    void setDelegate(Delegate delegate) {
        mDelegate = delegate;
    }

    View getView() {
        return mRootLayout;
    }

    void setVisible(boolean visible) {
        mRootLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    void setPaddings(int topPadding, int bottomPadding) {
        AssistantVerticalExpander dateExpander = mRootLayout.findViewById(R.id.date_expander);
        AssistantVerticalExpander timeExpander = mRootLayout.findViewById(R.id.time_expander);

        View dateTitleView = dateExpander.getTitleView();
        View timeTitleView = timeExpander.getTitleView();
        dateTitleView.setPadding(dateTitleView.getPaddingLeft(), topPadding,
                dateTitleView.getPaddingRight(), mTitleToContentPadding);
        timeTitleView.setPadding(timeTitleView.getPaddingLeft(), topPadding,
                timeTitleView.getPaddingRight(), mTitleToContentPadding);

        View dateChevronView = dateExpander.getChevronButton();
        View timeChevronView = timeExpander.getChevronButton();
        dateChevronView.setPadding(dateChevronView.getPaddingLeft(), topPadding,
                dateChevronView.getPaddingRight(), dateChevronView.getPaddingBottom());
        timeChevronView.setPadding(timeChevronView.getPaddingLeft(), topPadding,
                timeChevronView.getPaddingRight(), timeChevronView.getPaddingBottom());

        mRootLayout.setPadding(mRootLayout.getPaddingLeft(), mRootLayout.getPaddingTop(),
                mRootLayout.getPaddingRight(), bottomPadding);
    }

    void setDateTitle(String title) {
        AssistantVerticalExpander dateExpander = mRootLayout.findViewById(R.id.date_expander);
        TextView titleView = dateExpander.getTitleView().findViewById(R.id.section_title);
        titleView.setText(title);
    }

    void setTimeTitle(String title) {
        AssistantVerticalExpander dateExpander = mRootLayout.findViewById(R.id.time_expander);
        TextView titleView = dateExpander.getTitleView().findViewById(R.id.section_title);
        titleView.setText(title);
    }

    void setCurrentDate(@Nullable AssistantDateTime value) {
        mCurrentValue = value;
        updateDateSummaryView();

        if (mDelegate != null) {
            mDelegate.onDateChanged(mCurrentValue);
        }
    }

    /**
     * Sets the date that the calendar should fall back to if {@code mCurrentValue} is not set. The
     * default is the current date.
     */
    void setCalendarFallbackDate(@Nullable AssistantDateTime value) {
        mCalendarFallbackValue = value;
    }

    void setDateNotSetErrorMessage(String errorMessage) {
        mDateNotSetErrorMessage = errorMessage;
        updateDateSummaryView();
    }

    void setTimeNotSetErrorMessage(String errorMessage) {
        mTimeNotSetErrorMessage = errorMessage;
        updateTimeSummaryView();
    }

    /**
     * @param index the current timeslot. Can be null to indicate that no timeslot is selected.
     */
    void setCurrentTimeSlot(@Nullable Integer index) {
        mCurrentTimeSlot = index;
        updateTimeSummaryView();

        if (mDelegate != null) {
            mDelegate.onTimeSlotChanged(mCurrentTimeSlot);
        }
    }

    private void updateDateSummaryView() {
        if (mCurrentValue == null) {
            mDateSummaryView.setText(mDateNotSetErrorMessage);
            ApiCompatibilityUtils.setTextAppearance(
                    mDateSummaryView, R.style.TextAppearance_ErrorCaption);
            return;
        }

        Calendar calendar = Calendar.getInstance(mLocale);
        calendar.setTimeInMillis(mCurrentValue.getTimeInMillis(mLocale));
        mDateSummaryView.setText(mDateTimeFormat.format(calendar.getTime()));
        ApiCompatibilityUtils.setTextAppearance(
                mDateSummaryView, R.style.TextAppearance_TextMedium_Secondary);
    }

    private void updateTimeSummaryView() {
        if (mDateChoiceOptions == null || mCurrentTimeSlot == null) {
            mTimeSummaryView.setText(mTimeNotSetErrorMessage);
            ApiCompatibilityUtils.setTextAppearance(
                    mTimeSummaryView, R.style.TextAppearance_ErrorCaption);
            return;
        }
        mTimeSummaryView.setText(mDateChoiceOptions.getTimeSlots().get(mCurrentTimeSlot));
        ApiCompatibilityUtils.setTextAppearance(
                mTimeSummaryView, R.style.TextAppearance_TextMedium_Secondary);
    }
}


text:
namespace OJS.LocalWorker
{
    using System;
    using System.Linq;

    using OJS.Data.Models;
    using OJS.Services.Data.Participants;
    using OJS.Services.Data.ParticipantScores;
    using OJS.Services.Data.Submissions;
    using OJS.Services.Data.SubmissionsForProcessing;
    using OJS.Services.Data.TestRuns;
    using OJS.Workers.Common;
    using OJS.Workers.Common.Models;
    using OJS.Workers.ExecutionStrategies.Models;
    using OJS.Workers.SubmissionProcessors;
    using OJS.Workers.SubmissionProcessors.Models;

    public class OjsSubmissionProcessingStrategy : SubmissionProcessingStrategy<int>
    {
        private readonly ISubmissionsDataService submissionsData;
        private readonly ITestRunsDataService testRunsData;
        private readonly IParticipantsDataService participantsData;
        private readonly IParticipantScoresDataService participantScoresData;
        private readonly ISubmissionsForProcessingDataService submissionsForProcessingData;

        private Submission submission;
        private SubmissionForProcessing submissionForProcessing;

        public OjsSubmissionProcessingStrategy(
            ISubmissionsDataService submissionsData,
            ITestRunsDataService testRunsData,
            IParticipantsDataService participantsData,
            IParticipantScoresDataService participantScoresData,
            ISubmissionsForProcessingDataService submissionsForProcessingData)
        {
            this.submissionsData = submissionsData;
            this.testRunsData = testRunsData;
            this.participantsData = participantsData;
            this.participantScoresData = participantScoresData;
            this.submissionsForProcessingData = submissionsForProcessingData;
        }

        public override IOjsSubmission RetrieveSubmission()
        {
            lock (this.SubmissionsForProcessing)
            {
                if (this.SubmissionsForProcessing.IsEmpty)
                {
                    this.submissionsForProcessingData
                        .GetAllUnprocessed()
                        .OrderBy(x => x.Id)
                        .Select(x => x.SubmissionId)
                        .ToList()
                        .ForEach(this.SubmissionsForProcessing.Enqueue);
                }

                var isSubmissionRetrieved = this.SubmissionsForProcessing.TryDequeue(out var submissionId);

                if (!isSubmissionRetrieved)
                {
                    return null;
                }

                this.Logger.InfoFormat($"Submission #{submissionId} retrieved from data store successfully");

                this.submission = this.submissionsData.GetById(submissionId);

                this.submissionForProcessing = this.submissionsForProcessingData.GetBySubmission(submissionId);

                if (this.submission == null || this.submissionForProcessing == null)
                {
                    this.Logger.Error($"Cannot retrieve submission #{submissionId} from database");
                    return null;
                }

                this.SetSubmissionToProcessing();
            }

            return this.GetSubmissionModel();
        }

        public override void BeforeExecute()
        {
            this.submission.ProcessingComment = null;
            this.testRunsData.DeleteBySubmission(this.submission.Id);
        }

        public override void OnError(IOjsSubmission submissionModel)
        {
            this.submission.ProcessingComment = submissionModel.ProcessingComment;

            this.UpdateResults();
        }

        public override void SetSubmissionToProcessing()
        {
            try
            {
                this.submissionForProcessing.Processed = false;
                this.submissionForProcessing.Processing = true;

                this.submissionsForProcessingData.Update(this.submissionForProcessing);
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "Unable to set submission #{0} to processing! Exception: {1}",
                    this.submission.Id,
                    ex);
            }
        }

        public override void ReleaseSubmission()
        {
            try
            {
                this.submissionForProcessing.Processed = false;
                this.submissionForProcessing.Processing = false;
                this.submissionsForProcessingData.Update(this.submissionForProcessing);
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "Unable to release submission #{0}! Exception: {1}",
                    this.submission.Id,
                    ex);
            }
        }

        protected override void ProcessTestsExecutionResult(IExecutionResult<TestResult> executionResult)
        {
            this.submission.IsCompiledSuccessfully = executionResult.IsCompiledSuccessfully;
            this.submission.CompilerComment = executionResult.CompilerComment;

            if (!executionResult.IsCompiledSuccessfully)
            {
                this.UpdateResults();
                return;
            }

            foreach (var testResult in executionResult.Results)
            {
                var testRun = new TestRun
                {
                    CheckerComment = testResult.CheckerDetails.Comment,
                    ExpectedOutputFragment = testResult.CheckerDetails.ExpectedOutputFragment,
                    UserOutputFragment = testResult.CheckerDetails.UserOutputFragment,
                    ExecutionComment = testResult.ExecutionComment,
                    MemoryUsed = testResult.MemoryUsed,
                    ResultType = testResult.ResultType,
                    TestId = testResult.Id,
                    TimeUsed = testResult.TimeUsed
                };

                this.submission.TestRuns.Add(testRun);
            }

            this.submissionsData.Update(this.submission);

            this.UpdateResults();
        }

        private void UpdateResults()
        {
            this.CalculatePointsForSubmission();

            this.SaveParticipantScore();

            this.CacheTestRuns();

            this.SetSubmissionToProcessed();
        }

        private void CalculatePointsForSubmission()
        {
            try
            {
                // Internal joke: submission.Points = new Random().Next(0, submission.Problem.MaximumPoints + 1) + Weather.Instance.Today("Sofia").IsCloudy ? 10 : 0;
                if (this.submission.Problem.Tests.Count == 0 || this.submission.TestsWithoutTrialTestsCount == 0)
                {
                    this.submission.Points = 0;
                }
                else
                {
                    var totalTestRunsWithoutTrialTestsCount = this.submission.CorrectTestRunsWithoutTrialTestsCount + this.submission.IncorrectTestRunsWithoutTrialTestsCount;

                    var coefficient = totalTestRunsWithoutTrialTestsCount > 0
                        ? (double)this.submission.CorrectTestRunsWithoutTrialTestsCount / totalTestRunsWithoutTrialTestsCount
                        : 0;

                    this.submission.Points = (int)(coefficient * this.submission.Problem.MaximumPoints);
                }
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "CalculatePointsForSubmission on submission #{0} has thrown an exception: {1}",
                    this.submission.Id,
                    ex);

                this.submission.ProcessingComment = $"Exception in CalculatePointsForSubmission: {ex.Message}";
            }
        }

        private void SaveParticipantScore()
        {
            try
            {
                if (this.submission.ParticipantId == null || this.submission.ProblemId == null)
                {
                    return;
                }

                var participant = this.participantsData
                    .GetByIdQuery(this.submission.ParticipantId.Value)
                    .Select(p => new
                    {
                        p.IsOfficial,
                        p.User.UserName
                    })
                    .FirstOrDefault();

                if (participant == null)
                {
                    return;
                }

                ParticipantScore existingScore;

                lock (this.SharedLockObject)
                {
                    existingScore = this.participantScoresData.GetByParticipantIdProblemIdAndIsOfficial(
                        this.submission.ParticipantId.Value,
                        this.submission.ProblemId.Value,
                        participant.IsOfficial);

                    if (existingScore == null)
                    {
                        this.participantScoresData.AddBySubmissionByUsernameAndIsOfficial(
                            this.submission,
                            participant.UserName,
                            participant.IsOfficial);

                        return;
                    }
                }

                if (this.submission.Points > existingScore.Points ||
                    this.submission.Id == existingScore.SubmissionId)
                {
                    this.participantScoresData.UpdateBySubmissionAndPoints(
                        existingScore,
                        this.submission.Id,
                        this.submission.Points);
                }
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "SaveParticipantScore on submission #{0} has thrown an exception: {1}",
                    this.submission.Id,
                    ex);

                this.submission.ProcessingComment = $"Exception in SaveParticipantScore: {ex.Message}";
            }
        }

        private void SetSubmissionToProcessed()
        {
            try
            {
                this.submission.Processed = true;
                this.submissionForProcessing.Processed = true;
                this.submissionForProcessing.Processing = false;

                this.submissionsData.Update(this.submission);
                this.submissionsForProcessingData.Update(this.submissionForProcessing);
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "Unable to save changes to the submission #{0}! Exception: {1}",
                    this.submission.Id,
                    ex);
            }
        }

        private void CacheTestRuns()
        {
            try
            {
                this.submission.CacheTestRuns();
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat(
                    "CacheTestRuns on submission #{0} has thrown an exception: {1}",
                    this.submission.Id,
                    ex);

                this.submission.ProcessingComment = $"Exception in CacheTestRuns: {ex.Message}";
            }
        }

        private IOjsSubmission GetSubmissionModel() => new OjsSubmission<TestsInputModel>()
        {
            Id = this.submission.Id,
            AdditionalCompilerArguments = this.submission.SubmissionType.AdditionalCompilerArguments,
            AllowedFileExtensions = this.submission.SubmissionType.AllowedFileExtensions,
            FileContent = this.submission.Content,
            CompilerType = this.submission.SubmissionType.CompilerType,
            TimeLimit = this.submission.Problem.TimeLimit,
            MemoryLimit = this.submission.Problem.MemoryLimit,
            ExecutionStrategyType = this.submission.SubmissionType.ExecutionStrategyType,
            ExecutionType = ExecutionType.TestsExecution,
            MaxPoints = this.submission.Problem.MaximumPoints,
            Input = new TestsInputModel
            {
                TaskSkeleton = this.submission.Problem.SolutionSkeleton,
                CheckerParameter = this.submission.Problem.Checker.Parameter,
                CheckerAssemblyName = this.submission.Problem.Checker.DllFile,
                CheckerTypeName = this.submission.Problem.Checker.ClassName,
                Tests = this.submission.Problem.Tests
                    .AsQueryable()
                    .Select(t => new TestContext
                    {
                        Id = t.Id,
                        Input = t.InputDataAsString,
                        Output = t.OutputDataAsString,
                        IsTrialTest = t.IsTrialTest,
                        OrderBy = t.OrderBy
                    })
                    .ToList()
            }
        };
    }
}