text:
//
//  CHCircleGaugeView.h
//
//  Copyright (c) 2014 ChaiOne <http://www.chaione.com/>
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

#import <UIKit/UIKit.h>

/**
 Enumeration with the possible state of the circle gauge view.
 */
typedef NS_ENUM(NSInteger, CHCircleGaugeViewState) {
    /**
     "n/a" is displayed.
     */
    CHCircleGaugeViewStateNA,
    /**
     "%" is displayed.
     */
    CHCircleGaugeViewStatePercentSign,
    /**
     A whole number is displayed.
     */
    CHCircleGaugeViewStateScore
};

/**
 Enumeration with the possible gauge styles.
 */
typedef NS_ENUM(NSInteger, CHCircleGaugeStyle) {
    /**
     Draws the gauge inside and in the center of the track.
     */
    CHCircleGaugeStyleInside,
    /**
     Draws the gauge outside along the perimeter of the track.
     */
    CHCircleGaugeStyleOutside
};

/**
 A circle gauge is used to depict the value of a measurement.
 If gauge state is CHCircleGaugeViewStateNA, "n/a" is shown instead of a value.
 If gauge state is CHCircleGaugeViewStateScore, "%" is shown instead of a value.
 */
@interface CHCircleGaugeView : UIView

/** @name Managing the gauge */

/**
 The state of the gauge.
 */
@property (nonatomic, assign) CHCircleGaugeViewState state;

/**
 Contains the current value. Setting this property will change the state of the control to `CHCircleGaugeViewStateScore`.
 */
@property (nonatomic, assign) CGFloat value;

/**
 Sets the value the gauge should represent, with optional animation of the change.

 The current progress is represented by a floating-point value between 0.0 and 1.0,
 inclusive, where 1.0 indicates the completion of the task. The default value is 0.0.
 Values less than 0.0 and greater than 1.0 are pinned to those limits.

 Calling this will change the state of the control to `CHCircleGaugeViewStateScore`.

 @param value The new gauge value.
 @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
 */
- (void)setValue:(CGFloat)value animated:(BOOL)animated;

/** @name Configuring the gauge */

/**
 The color shown for the portion of the gauge that is always filled.
 */
@property (nonatomic, strong) UIColor *trackTintColor;

/**
 The color shown on top of `trackTintColor` for the portion of the gauge that varies based on the `value` property.
 */
@property (nonatomic, strong) UIColor *gaugeTintColor;

/**
 The color of the text.

 The default value for this property is a black color (set through the blackColor class method of UIColor). The value for the property
 can only be set to a non-nil value; setting this property to nil raises an exception.
 */
@property (nonatomic, strong) UIColor *textColor;

/**
 The font of the text.

 The default value for this property is the system font at a size of 32 points (using the systemFontOfSize: class method of UIFont).
 The value for the property can only be set to a non-nil value; setting this property to nil raises an exception.
 */
@property (nonatomic, strong) UIFont *font;

/**
 The width for the portion of the gauge that is always filled. Defaults to a value of 0.5.
 */
@property (nonatomic, assign) CGFloat trackWidth;

/**
 The width for the portion of the gauge that varies based on the `value` property. Defaults to a value of 2.
*/
@property (nonatomic, assign) CGFloat gaugeWidth;

/**
 String that is a suffix on the `value`. This string is meant to be just a few characters long. Defaults to `nil`.

 @warning The label backing the string does not auto-shrink, set a smaller font if the text gets truncated.

 @see font
 */
@property (nonatomic, copy) NSString *unitsString;

/**
 The text shown when the state of the gauge is `CHCircleGaugeViewStateNA`. Defaults to "n/a".
 */
@property (nonatomic, copy) NSString *notApplicableString;

/**
 The text shown when the state of the gauge is `CHCircleGaugeViewStatePercentSign`. Defaults to "%".
 */
@property (nonatomic, copy) NSString *noDataString;

/**
 Determines how the gauge is drawn relative to the track. Defaults to `CHCircleGaugeStyleInside`.
 */
@property (nonatomic, assign) CHCircleGaugeStyle gaugeStyle;

@end


text:
<?php declare(strict_types=1);

namespace App\Modules;

final class HomePresenter extends AbstractPresenter
{
}

redpajama_set_name: RedPajamaGithub


text:
package podtask

import (
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	mesos "github.com/mesos/mesos-go/mesosproto"
	mutil "github.com/mesos/mesos-go/mesosutil"
)

const (
	t_min_cpu = 128
	t_min_mem = 128
)

func fakePodTask(id string) (*T, error) {
	return New(api.NewDefaultContext(), "", api.Pod{
		ObjectMeta: api.ObjectMeta{
			Name:      id,
			Namespace: api.NamespaceDefault,
		},
	}, &mesos.ExecutorInfo{})
}

func TestEmptyOffer(t *testing.T) {
	t.Parallel()
	task, err := fakePodTask("foo")
	if err != nil {
		t.Fatal(err)
	}
	if ok := task.AcceptOffer(nil); ok {
		t.Fatalf("accepted nil offer")
	}
	if ok := task.AcceptOffer(&mesos.Offer{}); ok {
		t.Fatalf("accepted empty offer")
	}
}

func TestNoPortsInPodOrOffer(t *testing.T) {
	t.Parallel()
	task, err := fakePodTask("foo")
	if err != nil || task == nil {
		t.Fatal(err)
	}

	offer := &mesos.Offer{
		Resources: []*mesos.Resource{
			mutil.NewScalarResource("cpus", 0.001),
			mutil.NewScalarResource("mem", 0.001),
		},
	}
	if ok := task.AcceptOffer(offer); ok {
		t.Fatalf("accepted offer %v:", offer)
	}

	offer = &mesos.Offer{
		Resources: []*mesos.Resource{
			mutil.NewScalarResource("cpus", t_min_cpu),
			mutil.NewScalarResource("mem", t_min_mem),
		},
	}
	if ok := task.AcceptOffer(offer); !ok {
		t.Fatalf("did not accepted offer %v:", offer)
	}
}

func TestAcceptOfferPorts(t *testing.T) {
	t.Parallel()
	task, _ := fakePodTask("foo")
	pod := &task.Pod

	offer := &mesos.Offer{
		Resources: []*mesos.Resource{
			mutil.NewScalarResource("cpus", t_min_cpu),
			mutil.NewScalarResource("mem", t_min_mem),
			rangeResource("ports", []uint64{1, 1}),
		},
	}
	if ok := task.AcceptOffer(offer); !ok {
		t.Fatalf("did not accepted offer %v:", offer)
	}

	pod.Spec = api.PodSpec{
		Containers: []api.Container{{
			Ports: []api.ContainerPort{{
				HostPort: 123,
			}},
		}},
	}
	if ok := task.AcceptOffer(offer); ok {
		t.Fatalf("accepted offer %v:", offer)
	}

	pod.Spec.Containers[0].Ports[0].HostPort = 1
	if ok := task.AcceptOffer(offer); !ok {
		t.Fatalf("did not accepted offer %v:", offer)
	}

	pod.Spec.Containers[0].Ports[0].HostPort = 0
	if ok := task.AcceptOffer(offer); !ok {
		t.Fatalf("did not accepted offer %v:", offer)
	}

	offer.Resources = []*mesos.Resource{
		mutil.NewScalarResource("cpus", t_min_cpu),
		mutil.NewScalarResource("mem", t_min_mem),
	}
	if ok := task.AcceptOffer(offer); ok {
		t.Fatalf("accepted offer %v:", offer)
	}

	pod.Spec.Containers[0].Ports[0].HostPort = 1
	if ok := task.AcceptOffer(offer); ok {
		t.Fatalf("accepted offer %v:", offer)
	}
}

func TestGeneratePodName(t *testing.T) {
	p := &api.Pod{
		ObjectMeta: api.ObjectMeta{
			Name:      "foo",
			Namespace: "bar",
		},
	}
	name := generateTaskName(p)
	expected := "foo.bar.pods"
	if name != expected {
		t.Fatalf("expected %q instead of %q", expected, name)
	}

	p.Namespace = ""
	name = generateTaskName(p)
	expected = "foo.default.pods"
	if name != expected {
		t.Fatalf("expected %q instead of %q", expected, name)
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;

namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel
{
    internal class CodeStyleSeverityViewModel
    {
        private static readonly string[] s_severities = new[]
        {
            ServicesVSResources.Disabled,
            ServicesVSResources.Suggestion,
            ServicesVSResources.Warning,
            ServicesVSResources.Error
        };

        private readonly int _selectedSeverityIndex;

        private string? _selectedSeverityValue;

        private readonly CodeStyleSetting _setting;

        public string[] Severities => s_severities;

        public string SelectedSeverityValue
        {
            get
            {
                _selectedSeverityValue ??= Severities[_selectedSeverityIndex];

                return _selectedSeverityValue;
            }
            set => _selectedSeverityValue = value;
        }

        public string ToolTip => ServicesVSResources.Severity;

        public static string AutomationName => ServicesVSResources.Severity;

        public CodeStyleSeverityViewModel(CodeStyleSetting setting)
        {
            _selectedSeverityIndex = setting.Severity switch
            {
                DiagnosticSeverity.Hidden => 0,
                DiagnosticSeverity.Info => 1,
                DiagnosticSeverity.Warning => 2,
                DiagnosticSeverity.Error => 3,
                _ => throw new InvalidOperationException(),
            };

            _setting = setting;
        }

        public void SelectionChanged(int selectedIndex)
        {
            var severity = selectedIndex switch
            {
                0 => DiagnosticSeverity.Hidden,
                1 => DiagnosticSeverity.Info,
                2 => DiagnosticSeverity.Warning,
                3 => DiagnosticSeverity.Error,
                _ => throw new InvalidOperationException(),
            };

            if (_setting.Severity != severity)
            {
                _setting.ChangeSeverity(severity);
            }
        }
    }
}


text:
namespace Microsoft.Protocols.TestSuites.Common
{
    using System;
    using System.Text;

    /// <summary>
    /// A successful response body for the connect request for Mailbox Server Endpoint.
    /// </summary>
    public class ConnectSuccessResponseBody : MailboxResponseBodyBase
    {
        /// <summary>
        /// Gets an unsigned integer that specifies the return status of the operation.
        /// </summary>
        public uint ErrorCode { get; private set; }

        /// <summary>
        /// Gets an unsigned integer that specifies the number of milliseconds for the maximum polling interval.
        /// </summary>
        public uint PollsMax { get; private set; }

        /// <summary>
        /// Gets an unsigned integer that specifies the number of times to retry request types.
        /// </summary>
        public uint RetryCount { get; private set; }

        /// <summary>
        /// Gets an unsigned integer that specifies the number of milliseconds for the client to wait before retrying a failed request type.
        /// </summary>
        public uint RetryDelay { get; private set; }

        /// <summary>
        /// Gets a null-terminated ASCII string that specifies the DN prefix to be used for building message recipients.
        /// </summary>
        public string DNPrefix { get; private set; }

        /// <summary>
        /// Gets a null-terminated Unicode string that specifies the display name of the user who is specified in the UserDn field of the Connect request type request body.
        /// </summary>
        public string DisplayName { get; private set; }

        /// <summary>
        /// Parse the Connect request type success response body.
        /// </summary>
        /// <param name="rawData">The raw data which is returned by server.</param>
        /// <returns>An instance of ConnectSuccessResponseBody class.</returns>
        public static ConnectSuccessResponseBody Parse(byte[] rawData)
        {
            ConnectSuccessResponseBody responseBody = new ConnectSuccessResponseBody();
            int index = 0;
            responseBody.StatusCode = BitConverter.ToUInt32(rawData, index);
            index += 4;
            responseBody.ErrorCode = BitConverter.ToUInt32(rawData, index);
            index += 4;
            responseBody.PollsMax = BitConverter.ToUInt32(rawData, index);
            index += 4;
            responseBody.RetryCount = BitConverter.ToUInt32(rawData, index);
            index += 4;
            responseBody.RetryDelay = BitConverter.ToUInt32(rawData, index);
            index += 4;

            // The length in bytes of the unicode string to parse
            int strBytesLen = 0;

            // Find the string with '\0' end
            for (int i = index; i < rawData.Length; i++)
            {
                strBytesLen++;
                if (rawData[i] == 0)
                {
                    break;
                }
            }

            byte[] prefixBuffer = new byte[strBytesLen];
            Array.Copy(rawData, index, prefixBuffer, 0, strBytesLen);
            index += strBytesLen;
            responseBody.DNPrefix = Encoding.ASCII.GetString(prefixBuffer);

            // The length in bytes of the unicode string to parse
            strBytesLen = 0;

            // Find the string with '\0''\0' end
            for (int i = index; i < rawData.Length; i += 2)
            {
                strBytesLen += 2;
                if ((rawData[i] == 0) && (rawData[i + 1] == 0))
                {
                    break;
                }
            }

            byte[] displayNameBuffer = new byte[strBytesLen];
            Array.Copy(rawData, index, displayNameBuffer, 0, strBytesLen);
            index += strBytesLen;
            responseBody.DisplayName = Encoding.Unicode.GetString(displayNameBuffer);
            responseBody.AuxiliaryBufferSize = BitConverter.ToUInt32(rawData, index);
            index += 4;
            responseBody.AuxiliaryBuffer = new byte[responseBody.AuxiliaryBufferSize];
            Array.Copy(rawData, index, responseBody.AuxiliaryBuffer, 0, responseBody.AuxiliaryBufferSize);
            return responseBody;
        }
    }
}


text:
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"

#include "base/debug/dump_without_crashing.h"
#include "third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_element.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_event_target.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_html_link_element.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_window.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_xpath_ns_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/window_proxy.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/core/execution_context/agent.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/shadow_realm/shadow_realm_global_scope.h"
#include "third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/core/xml/xpath_ns_resolver.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
#include "third_party/blink/renderer/platform/scheduler/public/event_loop.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/text/string_buffer.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"

namespace blink {

void V8SetReturnValue(const v8::PropertyCallbackInfo<v8::Value>& info,
                      const v8::PropertyDescriptor& descriptor) {
  DCHECK(descriptor.has_configurable());
  DCHECK(descriptor.has_enumerable());
  if (descriptor.has_value()) {
    // Data property
    DCHECK(descriptor.has_writable());
    info.GetReturnValue().Set(
        V8ObjectBuilder(ScriptState::ForCurrentRealm(info))
            .Add("configurable", descriptor.configurable())
            .Add("enumerable", descriptor.enumerable())
            .Add("value", descriptor.value())
            .Add("writable", descriptor.writable())
            .V8Value());
    return;
  }
  // Accessor property
  DCHECK(descriptor.has_get() || descriptor.has_set());
  info.GetReturnValue().Set(V8ObjectBuilder(ScriptState::ForCurrentRealm(info))
                                .Add("configurable", descriptor.configurable())
                                .Add("enumerable", descriptor.enumerable())
                                .Add("get", descriptor.get())
                                .Add("set", descriptor.set())
                                .V8Value());
}

const int32_t kMaxInt32 = 0x7fffffff;
const int32_t kMinInt32 = -kMaxInt32 - 1;
const uint32_t kMaxUInt32 = 0xffffffff;
const int64_t kJSMaxInteger =
    0x20000000000000LL -
    1;  // 2^53 - 1, maximum uniquely representable integer in ECMAScript.

static double EnforceRange(double x,
                           double minimum,
                           double maximum,
                           const char* type_name,
                           ExceptionState& exception_state) {
  if (std::isnan(x) || std::isinf(x)) {
    exception_state.ThrowTypeError(
        "Value is" + String(std::isinf(x) ? " infinite and" : "") +
        " not of type '" + String(type_name) + "'.");
    return 0;
  }
  x = trunc(x);
  if (x < minimum || x > maximum) {
    exception_state.ThrowTypeError("Value is outside the '" +
                                   String(type_name) + "' value range.");
    return 0;
  }
  return x;
}

template <typename T>
struct IntTypeNumberOfValues {
  static constexpr unsigned value =
      1 << (std::numeric_limits<T>::digits + std::is_signed<T>::value);
};

template <typename T>
struct IntTypeLimits {};

template <>
struct IntTypeLimits<int8_t> {
  static constexpr int8_t kMinValue = std::numeric_limits<int8_t>::min();
  static constexpr int8_t kMaxValue = std::numeric_limits<int8_t>::max();
  static constexpr unsigned kNumberOfValues =
      IntTypeNumberOfValues<int8_t>::value;  // 2^8
};

template <>
struct IntTypeLimits<uint8_t> {
  static constexpr uint8_t kMaxValue = std::numeric_limits<uint8_t>::max();
  static constexpr unsigned kNumberOfValues =
      IntTypeNumberOfValues<uint8_t>::value;  // 2^8
};

template <>
struct IntTypeLimits<int16_t> {
  static constexpr int16_t kMinValue = std::numeric_limits<int16_t>::min();
  static constexpr int16_t kMaxValue = std::numeric_limits<int16_t>::max();
  static constexpr unsigned kNumberOfValues =
      IntTypeNumberOfValues<int16_t>::value;  // 2^16
};

template <>
struct IntTypeLimits<uint16_t> {
  static constexpr uint16_t kMaxValue = std::numeric_limits<uint16_t>::max();
  static constexpr unsigned kNumberOfValues =
      IntTypeNumberOfValues<uint16_t>::value;  // 2^16
};

template <typename T>
static inline T ToSmallerInt(v8::Isolate* isolate,
                             v8::Local<v8::Value> value,
                             IntegerConversionConfiguration configuration,
                             const char* type_name,
                             ExceptionState& exception_state) {
  typedef IntTypeLimits<T> LimitsTrait;

  // Fast case. The value is already a 32-bit integer in the right range.
  if (value->IsInt32()) {
    int32_t result = value.As<v8::Int32>()->Value();
    if (result >= LimitsTrait::kMinValue && result <= LimitsTrait::kMaxValue)
      return static_cast<T>(result);
    if (configuration == kEnforceRange) {
      exception_state.ThrowTypeError("Value is outside the '" +
                                     String(type_name) + "' value range.");
      return 0;
    }
    if (configuration == kClamp)
      return ClampTo<T>(result);
    result %= LimitsTrait::kNumberOfValues;
    return static_cast<T>(result > LimitsTrait::kMaxValue
                              ? result - LimitsTrait::kNumberOfValues
                              : result);
  }

  v8::Local<v8::Number> number_object;
  if (value->IsNumber()) {
    number_object = value.As<v8::Number>();
  } else {
    // Can the value be converted to a number?
    v8::TryCatch block(isolate);
    if (!value->ToNumber(isolate->GetCurrentContext())
             .ToLocal(&number_object)) {
      exception_state.RethrowV8Exception(block.Exception());
      return 0;
    }
  }
  DCHECK(!number_object.IsEmpty());

  if (configuration == kEnforceRange) {
    return EnforceRange(number_object->Value(), LimitsTrait::kMinValue,
                        LimitsTrait::kMaxValue, type_name, exception_state);
  }

  double number_value = number_object->Value();
  if (std::isnan(number_value) || !number_value)
    return 0;

  if (configuration == kClamp)
    return ClampTo<T>(number_value);

  if (std::isinf(number_value))
    return 0;

  // Confine number to (-kNumberOfValues, kNumberOfValues).
  number_value =
      number_value < 0 ? -floor(fabs(number_value)) : floor(fabs(number_value));
  number_value = fmod(number_value, LimitsTrait::kNumberOfValues);

  // Adjust range to [-kMinValue, kMaxValue].
  if (number_value < LimitsTrait::kMinValue)
    number_value += LimitsTrait::kNumberOfValues;
  else if (LimitsTrait::kMaxValue < number_value)
    number_value -= LimitsTrait::kNumberOfValues;

  return static_cast<T>(number_value);
}

template <typename T>
static inline T ToSmallerUInt(v8::Isolate* isolate,
                              v8::Local<v8::Value> value,
                              IntegerConversionConfiguration configuration,
                              const char* type_name,
                              ExceptionState& exception_state) {
  typedef IntTypeLimits<T> LimitsTrait;

  // Fast case. The value is a 32-bit signed integer - possibly positive?
  if (value->IsInt32()) {
    int32_t result = value.As<v8::Int32>()->Value();
    if (result >= 0 && result <= LimitsTrait::kMaxValue)
      return static_cast<T>(result);
    if (configuration == kEnforceRange) {
      exception_state.ThrowTypeError("Value is outside the '" +
                                     String(type_name) + "' value range.");
      return 0;
    }
    if (configuration == kClamp)
      return ClampTo<T>(result);
    return static_cast<T>(result);
  }

  v8::Local<v8::Number> number_object;
  if (value->IsNumber()) {
    number_object = value.As<v8::Number>();
  } else {
    // Can the value be converted to a number?
    v8::TryCatch block(isolate);
    if (!value->ToNumber(isolate->GetCurrentContext())
             .ToLocal(&number_object)) {
      exception_state.RethrowV8Exception(block.Exception());
      return 0;
    }
  }
  DCHECK(!number_object.IsEmpty());

  if (configuration == kEnforceRange) {
    return EnforceRange(number_object->Value(), 0, LimitsTrait::kMaxValue,
                        type_name, exception_state);
  }

  double number_value = number_object->Value();

  if (std::isnan(number_value) || !number_value)
    return 0;

  if (configuration == kClamp)
    return ClampTo<T>(number_value);

  if (std::isinf(number_value))
    return 0;

  // Confine number to (-kNumberOfValues, kNumberOfValues).
  double number = fmod(trunc(number_value), LimitsTrait::kNumberOfValues);

  // Adjust range to [0, kNumberOfValues).
  if (number < 0)
    number += LimitsTrait::kNumberOfValues;

  return static_cast<T>(number);
}

int8_t ToInt8(v8::Isolate* isolate,
              v8::Local<v8::Value> value,
              IntegerConversionConfiguration configuration,
              ExceptionState& exception_state) {
  return ToSmallerInt<int8_t>(isolate, value, configuration, "byte",
                              exception_state);
}

uint8_t ToUInt8(v8::Isolate* isolate,
                v8::Local<v8::Value> value,
                IntegerConversionConfiguration configuration,
                ExceptionState& exception_state) {
  return ToSmallerUInt<uint8_t>(isolate, value, configuration, "octet",
                                exception_state);
}

int16_t ToInt16(v8::Isolate* isolate,
                v8::Local<v8::Value> value,
                IntegerConversionConfiguration configuration,
                ExceptionState& exception_state) {
  return ToSmallerInt<int16_t>(isolate, value, configuration, "short",
                               exception_state);
}

uint16_t ToUInt16(v8::Isolate* isolate,
                  v8::Local<v8::Value> value,
                  IntegerConversionConfiguration configuration,
                  ExceptionState& exception_state) {
  return ToSmallerUInt<uint16_t>(isolate, value, configuration,
                                 "unsigned short", exception_state);
}

int32_t ToInt32Slow(v8::Isolate* isolate,
                    v8::Local<v8::Value> value,
                    IntegerConversionConfiguration configuration,
                    ExceptionState& exception_state) {
  DCHECK(!value->IsInt32());
  // Can the value be converted to a number?
  v8::TryCatch block(isolate);
  v8::Local<v8::Number> number_object;
  if (!value->ToNumber(isolate->GetCurrentContext()).ToLocal(&number_object)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }

  DCHECK(!number_object.IsEmpty());

  double number_value = number_object->Value();
  if (configuration == kEnforceRange) {
    return EnforceRange(number_value, kMinInt32, kMaxInt32, "long",
                        exception_state);
  }

  if (std::isnan(number_value))
    return 0;

  if (configuration == kClamp)
    return ClampTo<int32_t>(number_value);

  if (std::isinf(number_value))
    return 0;

  int32_t result;
  if (!number_object->Int32Value(isolate->GetCurrentContext()).To(&result)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  return result;
}

uint32_t ToUInt32Slow(v8::Isolate* isolate,
                      v8::Local<v8::Value> value,
                      IntegerConversionConfiguration configuration,
                      ExceptionState& exception_state) {
  DCHECK(!value->IsUint32());
  if (value->IsInt32()) {
    DCHECK_NE(configuration, kNormalConversion);
    int32_t result = value.As<v8::Int32>()->Value();
    if (result >= 0)
      return result;
    if (configuration == kEnforceRange) {
      exception_state.ThrowTypeError(
          "Value is outside the 'unsigned long' value range.");
      return 0;
    }
    DCHECK_EQ(configuration, kClamp);
    return ClampTo<uint32_t>(result);
  }

  // Can the value be converted to a number?
  v8::TryCatch block(isolate);
  v8::Local<v8::Number> number_object;
  if (!value->ToNumber(isolate->GetCurrentContext()).ToLocal(&number_object)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  DCHECK(!number_object.IsEmpty());

  if (configuration == kEnforceRange) {
    return EnforceRange(number_object->Value(), 0, kMaxUInt32, "unsigned long",
                        exception_state);
  }

  double number_value = number_object->Value();

  if (std::isnan(number_value))
    return 0;

  if (configuration == kClamp)
    return ClampTo<uint32_t>(number_value);

  if (std::isinf(number_value))
    return 0;

  uint32_t result;
  if (!number_object->Uint32Value(isolate->GetCurrentContext()).To(&result)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  return result;
}

int64_t ToInt64Slow(v8::Isolate* isolate,
                    v8::Local<v8::Value> value,
                    IntegerConversionConfiguration configuration,
                    ExceptionState& exception_state) {
  DCHECK(!value->IsInt32());

  v8::Local<v8::Number> number_object;
  // Can the value be converted to a number?
  v8::TryCatch block(isolate);
  if (!value->ToNumber(isolate->GetCurrentContext()).ToLocal(&number_object)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  DCHECK(!number_object.IsEmpty());

  double number_value = number_object->Value();

  if (configuration == kEnforceRange) {
    return EnforceRange(number_value, -kJSMaxInteger, kJSMaxInteger,
                        "long long", exception_state);
  }

  return DoubleToInteger(number_value);
}

uint64_t ToUInt64Slow(v8::Isolate* isolate,
                      v8::Local<v8::Value> value,
                      IntegerConversionConfiguration configuration,
                      ExceptionState& exception_state) {
  DCHECK(!value->IsUint32());
  if (value->IsInt32()) {
    DCHECK(configuration != kNormalConversion);
    int32_t result = value.As<v8::Int32>()->Value();
    if (result >= 0)
      return result;
    if (configuration == kEnforceRange) {
      exception_state.ThrowTypeError(
          "Value is outside the 'unsigned long long' value range.");
      return 0;
    }
    DCHECK_EQ(configuration, kClamp);
    return ClampTo<uint64_t>(result);
  }

  v8::Local<v8::Number> number_object;
  // Can the value be converted to a number?
  v8::TryCatch block(isolate);
  if (!value->ToNumber(isolate->GetCurrentContext()).ToLocal(&number_object)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  DCHECK(!number_object.IsEmpty());

  double number_value = number_object->Value();

  if (configuration == kEnforceRange) {
    return EnforceRange(number_value, 0, kJSMaxInteger, "unsigned long long",
                        exception_state);
  }

  if (std::isnan(number_value))
    return 0;

  if (configuration == kClamp)
    return ClampTo<uint64_t>(number_value);

  return DoubleToInteger(number_value);
}

float ToRestrictedFloat(v8::Isolate* isolate,
                        v8::Local<v8::Value> value,
                        ExceptionState& exception_state) {
  float number_value = ToFloat(isolate, value, exception_state);
  if (exception_state.HadException())
    return 0;
  if (!std::isfinite(number_value)) {
    exception_state.ThrowTypeError("The provided float value is non-finite.");
    return 0;
  }
  return number_value;
}

double ToDoubleSlow(v8::Isolate* isolate,
                    v8::Local<v8::Value> value,
                    ExceptionState& exception_state) {
  DCHECK(!value->IsNumber());
  v8::TryCatch block(isolate);
  v8::Local<v8::Number> number_value;
  if (!value->ToNumber(isolate->GetCurrentContext()).ToLocal(&number_value)) {
    exception_state.RethrowV8Exception(block.Exception());
    return 0;
  }
  return number_value->Value();
}

double ToRestrictedDouble(v8::Isolate* isolate,
                          v8::Local<v8::Value> value,
                          ExceptionState& exception_state) {
  double number_value = ToDouble(isolate, value, exception_state);
  if (exception_state.HadException())
    return 0;
  if (!std::isfinite(number_value)) {
    exception_state.ThrowTypeError("The provided double value is non-finite.");
    return 0;
  }
  return number_value;
}

static bool HasUnmatchedSurrogates(const String& string) {
  // By definition, 8-bit strings are confined to the Latin-1 code page and
  // have no surrogates, matched or otherwise.
  if (string.empty() || string.Is8Bit())
    return false;

  const UChar* characters = string.Characters16();
  const unsigned length = string.length();

  for (unsigned i = 0; i < length; ++i) {
    UChar c = characters[i];
    if (U16_IS_SINGLE(c))
      continue;
    if (U16_IS_TRAIL(c))
      return true;
    DCHECK(U16_IS_LEAD(c));
    if (i == length - 1)
      return true;
    UChar d = characters[i + 1];
    if (!U16_IS_TRAIL(d))
      return true;
    ++i;
  }
  return false;
}

// Replace unmatched surrogates with REPLACEMENT CHARACTER U+FFFD.
String ReplaceUnmatchedSurrogates(String string) {
  // This roughly implements https://webidl.spec.whatwg.org/#dfn-obtain-unicode
  // but since Blink strings are 16-bits internally, the output is simply
  // re-encoded to UTF-16.

  // The concept of surrogate pairs is explained at:
  // http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf#G2630

  // Blink-specific optimization to avoid making an unnecessary copy.
  if (!HasUnmatchedSurrogates(string))
    return string;
  DCHECK(!string.Is8Bit());

  // 1. Let S be the DOMString value.
  const UChar* s = string.Characters16();

  // 2. Let n be the length of S.
  const unsigned n = string.length();

  // 3. Initialize i to 0.
  unsigned i = 0;

  // 4. Initialize U to be an empty sequence of Unicode characters.
  StringBuffer<UChar> result(n);
  UChar* u = result.Characters();

  // 5. While i < n:
  while (i < n) {
    // 1. Let c be the code unit in S at index i.
    UChar c = s[i];
    // 2. Depending on the value of c:
    if (U16_IS_SINGLE(c)) {
      // c < 0xD800 or c > 0xDFFF
      // Append to U the Unicode character with code point c.
      u[i] = c;
    } else if (U16_IS_TRAIL(c)) {
      // 0xDC00 <= c <= 0xDFFF
      // Append to U a U+FFFD REPLACEMENT CHARACTER.
      u[i] = kReplacementCharacter;
    } else {
      // 0xD800 <= c <= 0xDBFF
      DCHECK(U16_IS_LEAD(c));
      if (i == n - 1) {
        // 1. If i = n-1, then append to U a U+FFFD REPLACEMENT CHARACTER.
        u[i] = kReplacementCharacter;
      } else {
        // 2. Otherwise, i < n-1:
        DCHECK_LT(i, n - 1);
        // ....1. Let d be the code unit in S at index i+1.
        UChar d = s[i + 1];
        if (U16_IS_TRAIL(d)) {
          // 2. If 0xDC00 <= d <= 0xDFFF, then:
          // ..1. Let a be c & 0x3FF.
          // ..2. Let b be d & 0x3FF.
          // ..3. Append to U the Unicode character with code point
          //      2^16+2^10*a+b.
          u[i++] = c;
          u[i] = d;
        } else {
          // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a U+FFFD
          //    REPLACEMENT CHARACTER.
          u[i] = kReplacementCharacter;
        }
      }
    }
    // 3. Set i to i+1.
    ++i;
  }

  // 6. Return U.
  DCHECK_EQ(i, string.length());
  return String::Adopt(result);
}

XPathNSResolver* ToXPathNSResolver(ScriptState* script_state,
                                   v8::Local<v8::Value> value) {
  XPathNSResolver* resolver = nullptr;
  if (V8XPathNSResolver::HasInstance(value, script_state->GetIsolate())) {
    resolver = V8XPathNSResolver::ToImpl(v8::Local<v8::Object>::Cast(value));
  } else if (value->IsObject()) {
    resolver = MakeGarbageCollected<V8CustomXPathNSResolver>(
        script_state, value.As<v8::Object>());
  }
  return resolver;
}

DOMWindow* ToDOMWindow(v8::Isolate* isolate, v8::Local<v8::Value> value) {
  return V8Window::ToImplWithTypeCheck(isolate, value);
}

LocalDOMWindow* ToLocalDOMWindow(v8::Local<v8::Context> context) {
  if (context.IsEmpty())
    return nullptr;
  return To<LocalDOMWindow>(
      ToDOMWindow(context->GetIsolate(), context->Global()));
}

LocalDOMWindow* EnteredDOMWindow(v8::Isolate* isolate) {
  LocalDOMWindow* window =
      ToLocalDOMWindow(isolate->GetEnteredOrMicrotaskContext());
  DCHECK(window);
  return window;
}

LocalDOMWindow* IncumbentDOMWindow(v8::Isolate* isolate) {
  LocalDOMWindow* window = ToLocalDOMWindow(isolate->GetIncumbentContext());
  DCHECK(window);
  return window;
}

LocalDOMWindow* CurrentDOMWindow(v8::Isolate* isolate) {
  return ToLocalDOMWindow(isolate->GetCurrentContext());
}

ExecutionContext* ToExecutionContext(v8::Local<v8::Context> context) {
  // TODO(jgruber,crbug.com/v8/10460): Change this back to a DCHECK once the
  // crash has been flushed out.
  CHECK(!context.IsEmpty());

  RUNTIME_CALL_TIMER_SCOPE(context->GetIsolate(),
                           RuntimeCallStats::CounterId::kToExecutionContext);

  v8::Local<v8::Object> global_proxy = context->Global();

  // TODO(jgruber,crbug.com/v8/10460): Change these back to a DCHECK once the
  // crash has been flushed out.
  CHECK(!global_proxy.IsEmpty());
  CHECK(global_proxy->IsObject());

  // There are several contexts other than Window, WorkerGlobalScope or
  // WorkletGlobalScope but entering into ToExecutionContext, namely GC context,
  // DevTools' context (debug context), and maybe more.  They all don't have
  // any internal field.
  if (global_proxy->InternalFieldCount() == 0)
    return nullptr;

  ScriptWrappable::TypeDispatcher dispatcher(ToScriptWrappable(global_proxy));
  if (auto* x = dispatcher.ToMostDerived<DOMWindow>())
    return x->GetExecutionContext();
  if (auto* x = dispatcher.DowncastTo<WorkerGlobalScope>())
    return x->GetExecutionContext();
  if (auto* x = dispatcher.DowncastTo<WorkletGlobalScope>())
    return x->GetExecutionContext();
  if (auto* x = dispatcher.ToMostDerived<ShadowRealmGlobalScope>())
    return x->GetExecutionContext();

  NOTREACHED();
  return nullptr;
}

ExecutionContext* CurrentExecutionContext(v8::Isolate* isolate) {
  return ToExecutionContext(isolate->GetCurrentContext());
}

LocalFrame* ToLocalFrameIfNotDetached(v8::Local<v8::Context> context) {
  LocalDOMWindow* window = ToLocalDOMWindow(context);
  if (window && window->IsCurrentlyDisplayedInFrame())
    return window->GetFrame();
  // We return 0 here because |context| is detached from the Frame. If we
  // did return |frame| we could get in trouble because the frame could be
  // navigated to another security origin.
  return nullptr;
}

static ScriptState* ToScriptStateImpl(LocalFrame* frame,
                                      DOMWrapperWorld& world) {
  if (!frame)
    return nullptr;
  v8::Local<v8::Context> context = ToV8ContextEvenIfDetached(frame, world);
  if (context.IsEmpty())
    return nullptr;
  ScriptState* script_state = ScriptState::From(context);
  if (!script_state->ContextIsValid())
    return nullptr;
  DCHECK_EQ(frame, ToLocalFrameIfNotDetached(context));
  return script_state;
}

v8::Local<v8::Context> ToV8Context(ExecutionContext* context,
                                   DOMWrapperWorld& world) {
  DCHECK(context);
  if (LocalDOMWindow* window = DynamicTo<LocalDOMWindow>(context)) {
    if (LocalFrame* frame = window->GetFrame())
      return ToV8Context(frame, world);
  } else if (auto* scope = DynamicTo<WorkerOrWorkletGlobalScope>(context)) {
    if (WorkerOrWorkletScriptController* script = scope->ScriptController()) {
      if (ScriptState* script_state = script->GetScriptState()) {
        if (script_state->ContextIsValid())
          return script_state->GetContext();
      }
    }
  }
  return v8::Local<v8::Context>();
}

v8::Local<v8::Context> ToV8Context(LocalFrame* frame, DOMWrapperWorld& world) {
  ScriptState* script_state = ToScriptStateImpl(frame, world);
  if (!script_state)
    return v8::Local<v8::Context>();
  return script_state->GetContext();
}

v8::Local<v8::Context> ToV8ContextEvenIfDetached(LocalFrame* frame,
                                                 DOMWrapperWorld& world) {
  // TODO(yukishiino): this method probably should not force context creation,
  // but it does through WindowProxy() call.
  DCHECK(frame);

  // TODO(crbug.com/1046282): The following bailout is a temporary fix
  // introduced due to crbug.com/1037985 .  Remove this temporary fix once
  // the root cause is fixed.
  if (frame->IsProvisional()) {
    base::debug::DumpWithoutCrashing();
    return v8::Local<v8::Context>();
  }

  return frame->WindowProxy(world)->ContextIfInitialized();
}

v8::Local<v8::Context> ToV8ContextMaybeEmpty(LocalFrame* frame,
                                             DOMWrapperWorld& world) {
  DCHECK(frame);

  // TODO(crbug.com/1046282): The following bailout is a temporary fix
  // introduced due to crbug.com/1037985 .  Remove this temporary fix once
  // the root cause is fixed.
  if (frame->IsProvisional()) {
    base::debug::DumpWithoutCrashing();
    return v8::Local<v8::Context>();
  }
  DCHECK(frame->WindowProxyMaybeUninitialized(world));
  v8::Local<v8::Context> context =
      frame->WindowProxyMaybeUninitialized(world)->ContextIfInitialized();

  DCHECK(context.IsEmpty() || frame == ToLocalFrameIfNotDetached(context));
  return context;
}

ScriptState* ToScriptState(ExecutionContext* context, DOMWrapperWorld& world) {
  DCHECK(context);
  if (LocalDOMWindow* window = DynamicTo<LocalDOMWindow>(context)) {
    return ToScriptState(window->GetFrame(), world);
  } else if (auto* scope = DynamicTo<WorkerOrWorkletGlobalScope>(context)) {
    if (WorkerOrWorkletScriptController* script = scope->ScriptController()) {
      if (ScriptState* script_state = script->GetScriptState()) {
        if (script_state->ContextIsValid())
          return script_state;
      }
    }
  }
  return nullptr;
}

ScriptState* ToScriptState(LocalFrame* frame, DOMWrapperWorld& world) {
  if (!frame)
    return nullptr;
  v8::HandleScope handle_scope(ToIsolate(frame));
  return ToScriptStateImpl(frame, world);
}

ScriptState* ToScriptStateForMainWorld(LocalFrame* frame) {
  return ToScriptState(frame, DOMWrapperWorld::MainWorld());
}

bool IsValidEnum(const String& value,
                 const char* const* valid_values,
                 size_t length,
                 const String& enum_name,
                 ExceptionState& exception_state) {
  for (size_t i = 0; i < length; ++i) {
    // Avoid the strlen inside String::operator== (because of the StringView).
    if (WTF::Equal(value.Impl(), valid_values[i]))
      return true;
  }
  exception_state.ThrowTypeError("The provided value '" + value +
                                 "' is not a valid enum value of type " +
                                 enum_name + ".");
  return false;
}

bool IsValidEnum(const Vector<String>& values,
                 const char* const* valid_values,
                 size_t length,
                 const String& enum_name,
                 ExceptionState& exception_state) {
  for (auto value : values) {
    if (!IsValidEnum(value, valid_values, length, enum_name, exception_state))
      return false;
  }
  return true;
}

v8::Local<v8::Function> GetEsIteratorMethod(v8::Isolate* isolate,
                                            v8::Local<v8::Object> object,
                                            ExceptionState& exception_state) {
  const v8::Local<v8::Value> key = v8::Symbol::GetIterator(isolate);

  v8::TryCatch try_catch(isolate);
  v8::Local<v8::Value> iterator_method;
  if (!object->Get(isolate->GetCurrentContext(), key)
           .ToLocal(&iterator_method)) {
    exception_state.RethrowV8Exception(try_catch.Exception());
    return v8::Local<v8::Function>();
  }

  if (iterator_method->IsNullOrUndefined())
    return v8::Local<v8::Function>();

  if (!iterator_method->IsFunction()) {
    exception_state.ThrowTypeError("Iterator must be callable function");
    return v8::Local<v8::Function>();
  }

  return iterator_method.As<v8::Function>();
}

v8::Local<v8::Object> GetEsIteratorWithMethod(
    v8::Isolate* isolate,
    v8::Local<v8::Function> getter_function,
    v8::Local<v8::Object> object,
    ExceptionState& exception_state) {
  v8::TryCatch block(isolate);
  v8::Local<v8::Value> iterator;
  if (!V8ScriptRunner::CallFunction(
           getter_function, ToExecutionContext(isolate->GetCurrentContext()),
           object, 0, nullptr, isolate)
           .ToLocal(&iterator)) {
    exception_state.RethrowV8Exception(block.Exception());
    return v8::Local<v8::Object>();
  }
  if (!iterator->IsObject()) {
    exception_state.ThrowTypeError("Iterator is not an object.");
    return v8::Local<v8::Object>();
  }
  return iterator.As<v8::Object>();
}

bool HasCallableIteratorSymbol(v8::Isolate* isolate,
                               v8::Local<v8::Value> value,
                               ExceptionState& exception_state) {
  if (!value->IsObject())
    return false;
  v8::Local<v8::Function> iterator_method =
      GetEsIteratorMethod(isolate, value.As<v8::Object>(), exception_state);
  return !iterator_method.IsEmpty();
}

v8::Isolate* ToIsolate(const LocalFrame* frame) {
  DCHECK(frame);
  return frame->GetWindowProxyManager()->GetIsolate();
}

v8::Local<v8::Value> FromJSONString(v8::Isolate* isolate,
                                    v8::Local<v8::Context> context,
                                    const String& stringified_json,
                                    ExceptionState& exception_state) {
  v8::Local<v8::Value> parsed;
  v8::TryCatch try_catch(isolate);
  if (!v8::JSON::Parse(context, V8String(isolate, stringified_json))
           .ToLocal(&parsed)) {
    if (try_catch.HasCaught())
      exception_state.RethrowV8Exception(try_catch.Exception());
  }

  return parsed;
}

Vector<String> GetOwnPropertyNames(v8::Isolate* isolate,
                                   const v8::Local<v8::Object>& object,
                                   ExceptionState& exception_state) {
  if (object.IsEmpty())
    return Vector<String>();

  v8::TryCatch try_catch(isolate);
  v8::Local<v8::Array> property_names;
  if (!object->GetOwnPropertyNames(isolate->GetCurrentContext())
           .ToLocal(&property_names)) {
    exception_state.RethrowV8Exception(try_catch.Exception());
    return Vector<String>();
  }

  return NativeValueTraits<IDLSequence<IDLString>>::NativeValue(
      isolate, property_names, exception_state);
}

v8::MicrotaskQueue* ToMicrotaskQueue(ExecutionContext* execution_context) {
  if (!execution_context)
    return nullptr;
  return execution_context->GetMicrotaskQueue();
}

v8::MicrotaskQueue* ToMicrotaskQueue(ScriptState* script_state) {
  return ToMicrotaskQueue(ExecutionContext::From(script_state));
}

scheduler::EventLoop& ToEventLoop(ExecutionContext* execution_context) {
  DCHECK(execution_context);
  return *execution_context->GetAgent()->event_loop().get();
}

scheduler::EventLoop& ToEventLoop(ScriptState* script_state) {
  return ToEventLoop(ExecutionContext::From(script_state));
}

bool IsInParallelAlgorithmRunnable(ExecutionContext* execution_context,
                                   ScriptState* script_state) {
  if (!execution_context || execution_context->IsContextDestroyed())
    return false;

  // It's possible that execution_context is the one of the
  // document tree (i.e. the execution context of the document
  // that the receiver object currently belongs to) and
  // script_state is the one of the receiver object's creation
  // context (i.e. the script state of the V8 context in which
  // the receiver object was created). So, check the both contexts.
  // TODO(yukishiino): Find the necessary and sufficient conditions of the
  // runnability.
  if (!script_state->ContextIsValid())
    return false;

  return true;
}

}  // namespace blink


text: conf.Column(c => c.Id).DataOnly();


text:
package org.apache.asterix.external.feed.message;

import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import org.apache.asterix.common.config.AsterixFeedProperties;
import org.apache.asterix.external.feed.api.IFeedMessage;
import org.apache.asterix.external.feed.api.IFeedMessageService;
import org.apache.asterix.external.util.FeedConstants;

/**
 * Sends feed report messages on behalf of an operator instance
 * to the SuperFeedManager associated with the feed.
 */
public class FeedMessageService implements IFeedMessageService {

    private static final Logger LOGGER = Logger.getLogger(FeedMessageService.class.getName());

    private final LinkedBlockingQueue<String> inbox;
    private final FeedMessageHandler mesgHandler;
    private final String nodeId;
    private ExecutorService executor;

    public FeedMessageService(AsterixFeedProperties feedProperties, String nodeId, String ccClusterIp) {
        this.inbox = new LinkedBlockingQueue<String>();
        this.mesgHandler = new FeedMessageHandler(inbox, ccClusterIp, feedProperties.getFeedCentralManagerPort());
        this.nodeId = nodeId;
        this.executor = Executors.newSingleThreadExecutor();
    }

    public void start() throws Exception {

        executor.execute(mesgHandler);
    }

    public void stop() {
        synchronized (mesgHandler.getLock()) {
            executor.shutdownNow();
        }
        mesgHandler.stop();
    }

    @Override
    public void sendMessage(IFeedMessage message) {
        try {
            JSONObject obj = message.toJSON();
            obj.put(FeedConstants.MessageConstants.NODE_ID, nodeId);
            obj.put(FeedConstants.MessageConstants.MESSAGE_TYPE, message.getMessageType().name());
            inbox.add(obj.toString());
        } catch (JSONException jse) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning("JSON exception in parsing message " + message + " exception [" + jse.getMessage() + "]");
            }
        }
    }

    private static class FeedMessageHandler implements Runnable {

        private final LinkedBlockingQueue<String> inbox;
        private final String host;
        private final int port;
        private final Object lock;

        private Socket cfmSocket;

        private static final byte[] EOL = "\n".getBytes();

        public FeedMessageHandler(LinkedBlockingQueue<String> inbox, String host, int port) {
            this.inbox = inbox;
            this.host = host;
            this.port = port;
            this.lock = new Object();
        }

        public void run() {
            try {
                cfmSocket = new Socket(host, port);
                if (cfmSocket != null) {
                    while (true) {
                        String message = inbox.take();
                        synchronized (lock) { // lock prevents message handler from sending incomplete message midst shutdown attempt
                            cfmSocket.getOutputStream().write(message.getBytes());
                            cfmSocket.getOutputStream().write(EOL);
                        }
                    }
                } else {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.warning("Unable to start feed message service");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.warning("Exception in handling incoming feed messages" + e.getMessage());
                }
            } finally {
                stop();
            }

        }

        public void stop() {
            if (cfmSocket != null) {
                try {
                    cfmSocket.close();
                } catch (Exception e) {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.warning("Exception in closing socket " + e.getMessage());
                    }
                }
            }
        }

        public Object getLock() {
            return lock;
        }

    }

}


text:
/* Custom per-build configuration settings.
 *
 * Include here those settings that you wish to override the settings in
 * www/config.js. The build process will replace www/custom_config.js with
 * a copy of this, and the app initialize with _.extend() the settings from
 * www/config.js.
 */

window.spiderOakMobile_custom_config = {
  app_label: {value: "Groups", retain: 1},
  showPreliminary: {value: false, retain: 0},
  server: {value: "spideroak.com", retain: 1},
  inhibitAdvancedLogin: {value: false, retain: 0},
  contactEmail: {value: "groups@spideroak.com", retain: 0}
};


text:
S V U I   By: Munglunch
##############################################################################

STATS:Extend EXAMPLE USAGE: Reports:NewReportType(newStat,eventList,onEvents,update,click,focus,blur)

##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack 	= _G.unpack;
local select 	= _G.select;
local pairs 	= _G.pairs;
local ipairs 	= _G.ipairs;
local type 		= _G.type;
local error 	= _G.error;
local pcall 	= _G.pcall;
local assert 	= _G.assert;
local tostring 	= _G.tostring;
local tonumber 	= _G.tonumber;
local tinsert 	= _G.tinsert;
local string 	= _G.string;
local math 		= _G.math;
local table 	= _G.table;
--[[ STRING METHODS ]]--
local lower, upper = string.lower, string.upper;
local find, format, len, split = string.find, string.format, string.len, string.split;
local match, sub, join = string.match, string.sub, string.join;
local gmatch, gsub = string.gmatch, string.gsub;
--[[ MATH METHODS ]]--
local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round;  -- Basic
--[[ TABLE METHODS ]]--
local twipe, tsort = table.wipe, table.sort;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = select(2, ...)
local L = SV.L
local Reports = SV.Reports;
--[[
##########################################################
BAG STATS
##########################################################
]]--
local StatEvents = {"PLAYER_ENTERING_WORLD", "BAG_UPDATE"};
local hexColor = "FFFFFF"
local bags_text = "%s|cff%s%d / %d|r";
local currentObject;

local function bags_events(this, e, ...)
	local f, g, h = 0, 0, 0;
	currentObject = this;
	for i = 0, NUM_BAG_SLOTS do
		f, g = f + GetContainerNumFreeSlots(i),
		g + GetContainerNumSlots(i)
	end
	h = g - f;
	this.text:SetFormattedText(bags_text, L["Bags"]..": ", hexColor, h, g)
end

local function bags_click()
	ToggleAllBags()
end

local function bags_focus(this)
	Reports:SetDataTip(this)
	for i = 1, MAX_WATCHED_TOKENS do
		local l, m, n, o, p = GetBackpackCurrencyInfo(i)
		if l and i == 1 then
			Reports.ReportTooltip:AddLine(CURRENCY)
			Reports.ReportTooltip:AddLine(" ")
		end
		if l and m then
			Reports.ReportTooltip:AddDoubleLine(l, m, 1, 1, 1)
		end
	end
	Reports:ShowDataTip()
end

local BagsColorUpdate = function()
	hexColor = SV:HexColor("highlight")
	if currentObject ~= nil then
		bags_events(currentObject)
	end
end

SV.Events:On("SHARED_MEDIA_UPDATED", BagsColorUpdate, true)
Reports:NewReportType("Bags", StatEvents,	bags_events, nil, bags_click, bags_focus);


text:
Contrib - Johnny 2017

This is a tap that optionally intercepts all data sent to/from clients and the
server and passes it to a callback of your choosing.

It is intended for quality assurance, post-incident investigations and debugging
but obviously can be abused. All data is recorded in cleartext. Please
be ethical, and if you are unwilling to properly deal with the implications of
recording user passwords or private communications, please do not enable
this module.

Some checks have been implemented to protect the privacy of users.

Files included in this module:

    outputs.py - Example callback methods. This module ships with examples of
            callbacks that send data as JSON to a file in your game/server/logs
            dir or to your native Linux syslog daemon. You can of course write
            your own to do other things like post them to Kafka topics.

    server.py - Extends the Evennia ServerSession object to pipe data to the
            callback upon receipt.

	tests.py - Unit tests that check to make sure commands with sensitive
	        arguments are having their PII scrubbed.

Installation/Configuration:

Deployment is completed by configuring a few settings in server.conf. This line
is required:

    SERVER_SESSION_CLASS = 'evennia.contrib.security.auditing.server.AuditedServerSession'

This tells Evennia to use this ServerSession instead of its own. Below are the
other possible options along with the default value that will be used if unset.

    # Where to send logs? Define the path to a module containing your callback
    # function. It should take a single dict argument as input
    AUDIT_CALLBACK = 'evennia.contrib.security.auditing.outputs.to_file'

    # Log user input? Be ethical about this; it will log all private and
    # public communications between players and/or admins (default: False).
    AUDIT_IN = False

    # Log server output? This will result in logging of ALL system
    # messages and ALL broadcasts to connected players, so on a busy game any
    # broadcast to all users will yield a single event for every connected user!
    AUDIT_OUT = False

    # The default output is a dict. Do you want to allow key:value pairs with
    # null/blank values? If you're just writing to disk, disabling this saves
    # some disk space, but whether you *want* sparse values or not is more of a
    # consideration if you're shipping logs to a NoSQL/schemaless database.
    # (default: False)
    AUDIT_ALLOW_SPARSE = False

    # If you write custom commands that handle sensitive data like passwords,
    # you must write a regular expression to remove that before writing to log.
    # AUDIT_MASKS is a list of dictionaries that define the names of commands
    # and the regexes needed to scrub them.
    # The system already has defaults to filter out sensitive login/creation
    # commands in the default command set. Your list of AUDIT_MASKS will be appended
    # to those defaults.
    #
    # In the regex, the sensitive data itself must be captured in a named group with a
    # label of 'secret' (see the Python docs on the `re` module for more info). For
    # example: `{'authentication': r"^@auth\s+(?P<secret>[\w]+)"}`
    AUDIT_MASKS = []


text:
package com.example.first;

import com.example.Marker;

@Marker
public interface InterfaceB {

}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>easyRTC - Landing Page</title>
    <link rel="stylesheet" type="text/css" href="css/landing.css" />

Local Demos

Documentation

Support: Discussion Group

easyRTC.com

easyRTC Landing Page

Congratulations! With easyRTC installed you are on the road to creating your own WebRTC enabled applications.

Local easyRTC Demos

    Demo

    Instant Messaging Demo

    Simple Video+Audio Demo

    Video+Audio HD 720p Demo

    Video Only Demo

    Audio Only Demo

    Video+Audio Demo

    Screen Sender

    Screen Receiver

    Data Channel Messaging Demo

    Data Channel File-sharing Demo

    Multiparty Chatroom Demo

    Note: Browser compatability subject to change.

easyRTC Links

easyRTC.com - Our project homepage

Support Forums

Issue tracker

easyRTC YouTube channel - with live demos

Other WebRTC Resources

W3C - WebRTC Specification Document

IETF Working Group

Google's WebRTC Project Home

Mozilla WebRTC Wiki

© 2013 - Priologic Software Inc., All Rights Reserved.

easyRTC source code released under a BSD2 Lcense. See LICENSE file in project folder for details.


text:
package com.google.android.vending.licensing;

/**
 * Callback for the license checker library.
 *

 * Upon checking with the Market server and conferring with the {@link com.google.android.vending.licensing.Policy},
 * the library calls the appropriate callback method to communicate the result.
 *

 * The callback does not occur in the original checking thread. Your
 * application should post to the appropriate handling thread or lock
 * accordingly.
 *

 * The reason that is passed back with allow/dontAllow is the base status handed
 * to the policy for allowed/disallowing the license. Policy.RETRY will call
 * allow or dontAllow depending on other statistics associated with the policy,
 * while in most cases Policy.NOT_LICENSED will call dontAllow and
 * Policy.LICENSED will Allow.
 */
public interface LicenseCheckerCallback {

    /**
     * Allow use. App should proceed as normal.
     *
     * @param reason Policy.LICENSED or Policy.RETRY typically. (although in
     *            theory the policy can return Policy.NOT_LICENSED here as well)
     */
    void allow(int reason);

    /**
     * Don't allow use. App should inform user and take appropriate action.
     *
     * @param reason Policy.NOT_LICENSED or Policy.RETRY. (although in theory
     *            the policy can return Policy.LICENSED here as well ---
     *            perhaps the call to the LVL took too long, for example)
     */
    void dontAllow(int reason);

    /** Application error codes. */
    int ERROR_INVALID_PACKAGE_NAME = 1;
    int ERROR_NON_MATCHING_UID = 2;
    int ERROR_NOT_MARKET_MANAGED = 3;
    int ERROR_CHECK_IN_PROGRESS = 4;
    int ERROR_INVALID_PUBLIC_KEY = 5;
    int ERROR_MISSING_PERMISSION = 6;

    /**
     * Error in application code. Caller did not call or set up license checker
     * correctly. Should be considered fatal.
     */
    void applicationError(int errorCode);
}


text:
#include <sbml/SBMLConstructorException.h>

#include <sbml/SBMLNamespaces.h>
#include <sbml/xml/XMLNamespaces.h>
#include <sbml/xml/XMLOutputStream.h>

#include <string>
#include <sstream>

LIBSBML_CPP_NAMESPACE_BEGIN

/** @cond doxygenLibsbmlInternal */

SBMLConstructorException::SBMLConstructorException(std::string errmsg) :
      std::invalid_argument("Level/version/namespaces combination is invalid")
    , mSBMLErrMsg(errmsg)
{
}

SBMLConstructorException::SBMLConstructorException (std::string errmsg, std::string sbmlErrMsg) :
    std::invalid_argument(errmsg)
  , mSBMLErrMsg(sbmlErrMsg)
{
}

SBMLConstructorException::SBMLConstructorException (std::string elementName, SBMLNamespaces* sbmlns) :
    std::invalid_argument("Level/version/namespaces combination is invalid")
  , mSBMLErrMsg(elementName)
{
  if (sbmlns == NULL) return;

  XMLNamespaces* xmlns = sbmlns->getNamespaces();

  if (xmlns == NULL) return;

  std::ostringstream oss;
  XMLOutputStream xos(oss);
  xos << *xmlns;
  mSBMLErrMsg.append(oss.str());

}

SBMLConstructorException::~SBMLConstructorException() throw()
{
}

/** @endcond */

LIBSBML_CPP_NAMESPACE_END


text:
<?php
/**
 * filename: data.php
 * description: this will return the score of the teams.
 */

//setting header to json
header('Content-Type: application/json');

//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root123');
define('DB_NAME', 'mydb');

//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
	die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT team, matchname, score FROM matchscore ORDER BY matchname");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
	$data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);


text:
package com.xuhao.didi.socket.common.interfaces.common_interfacies.server;

import com.xuhao.didi.core.iocore.interfaces.IIOCoreOptions;

public interface IServerManager<E extends IIOCoreOptions> extends IServerShutdown {

    void listen();

    void listen(E options);

    boolean isLive();

    IClientPool<String, IClient> getClientPool();
}


text:
import { NgModule }       from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import { jqxTabsComponent }     from 'components/angular_jqxtabs';
import { jqxCheckBoxComponent } from 'components/angular_jqxcheckbox';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, jqxTabsComponent, jqxCheckBoxComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }


text:
				to do

				1

				2

				3

				complete

				1

				2

				3

Cannot connect to the real-time module; collaboration features not available.

			Chat with online users

Chat

	<form class="ui reply form">

			<textarea rows="3"></textarea>

			Post

	</form>


text:
import _ from 'underscore';
/**
 * Livechat Department model
 */
class LivechatDepartmentAgents extends RocketChat.models._Base {
	constructor() {
		super('livechat_department_agents');
	}

	findByDepartmentId(departmentId) {
		return this.find({ departmentId });
	}

	saveAgent(agent) {
		return this.upsert({
			agentId: agent.agentId,
			departmentId: agent.departmentId,
		}, {
			$set: {
				username: agent.username,
				count: parseInt(agent.count),
				order: parseInt(agent.order),
			},
		});
	}

	removeByDepartmentIdAndAgentId(departmentId, agentId) {
		this.remove({ departmentId, agentId });
	}

	getNextAgentForDepartment(departmentId) {
		const agents = this.findByDepartmentId(departmentId).fetch();

		if (agents.length === 0) {
			return;
		}

		const onlineUsers = RocketChat.models.Users.findOnlineUserFromList(_.pluck(agents, 'username'));

		const onlineUsernames = _.pluck(onlineUsers.fetch(), 'username');

		const query = {
			departmentId,
			username: {
				$in: onlineUsernames,
			},
		};

		const sort = {
			count: 1,
			order: 1,
			username: 1,
		};
		const update = {
			$inc: {
				count: 1,
			},
		};

		const collectionObj = this.model.rawCollection();
		const findAndModify = Meteor.wrapAsync(collectionObj.findAndModify, collectionObj);

		const agent = findAndModify(query, sort, update);
		if (agent && agent.value) {
			return {
				agentId: agent.value.agentId,
				username: agent.value.username,
			};
		} else {
			return null;
		}
	}

	getOnlineForDepartment(departmentId) {
		const agents = this.findByDepartmentId(departmentId).fetch();

		if (agents.length === 0) {
			return [];
		}

		const onlineUsers = RocketChat.models.Users.findOnlineUserFromList(_.pluck(agents, 'username'));

		const onlineUsernames = _.pluck(onlineUsers.fetch(), 'username');

		const query = {
			departmentId,
			username: {
				$in: onlineUsernames,
			},
		};

		const depAgents = this.find(query);

		if (depAgents) {
			return depAgents;
		} else {
			return [];
		}
	}

	findUsersInQueue(usersList) {
		const query = {};

		if (!_.isEmpty(usersList)) {
			query.username = {
				$in: usersList,
			};
		}

		const options = {
			sort: {
				departmentId: 1,
				count: 1,
				order: 1,
				username: 1,
			},
		};

		return this.find(query, options);
	}

	replaceUsernameOfAgentByUserId(userId, username) {
		const query = { agentId: userId };

		const update = {
			$set: {
				username,
			},
		};

		return this.update(query, update, { multi: true });
	}
}

RocketChat.models.LivechatDepartmentAgents = new LivechatDepartmentAgents();


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_primary"
    android:padding="16dp" >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/sub_titles"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>

</LinearLayout>


text:
package gov.nih.nci.ncicb.cadsr.common.resource;
import java.io.Serializable;
import java.util.List;

public interface ModuleChanges extends Serializable
{

  public String getModuleId();
  public void setModuleId(String moduleId);

  public InstructionChanges getInstructionChanges();
  public void setInstructionChanges(InstructionChanges changes);

  public List getNewQuestions();
  public void setNewQuestions(List newQuestions);

  public List getUpdatedQuestions();
  public void setUpdatedQuestions(List updatedQuestions);

  public List getDeletedQuestions();
  public void setDeletedQuestions(List deletedQuestions);

  public Module getUpdatedModule();
  public void setUpdatedModule(Module updatedModule);

  public boolean isEmpty();
}


text:
angular.module('app.controllers', ['firebase'])

    .controller('fourofourCtrl', function () {

    })

    .controller('homeCtrl', function () {

    })

    .controller('accountCtrl', function () {

    })

    .controller('signupCtrl', function ($scope, $state) {
        //connects to database
        //var ref = new Firebase("https://sumbits-scroller.firebaseio.com/");
        //var sync = $firebase(ref);

        $scope.homeGo = function () {
            $state.go('home')
        };
        $scope.changeThemee = function () {
            $scope.changeTheme = 'test'
        };
        //scopes the page to find createAccount
        //creates account
        $scope.createAccount = function (usn, em, pwd) {
            //check for username existance here

            //creates cookie with username
            //put('User_Name_Cookie', usn);
            //
            ////random generate a key here
            //function Random_Gen_Key(key_length) {
            //
            //    var user_key = null;
            //
            //    for (i = 0, key_length, i++) {
            //       user_key += randomnumberthing;
            //    }
            //}
            //
            //var User_Data = {
            //    'Username': usn,
            //    'secret': user_key
            //};
            //put(Key, User_Data);

            // //creates account in firebase
            // //allowed to edit data stuff
            // fireBaseData.ref().createUser({
            //     email: em,
            //     password: pwd
            // }, function (error) {
            //     if (error == null) {
            //         console.log("User created successfully.");
            //         loginFunction(em, pwd);
            //     } else {
            //         console.log("Error creating user: ", error);
            //     }
            // });
        };

    })
//this controller is not directly linked to a webpage
//this way it is accessable by any element
// to use the controller in a element do <(element) ng-controller="animationCtrl">
    .controller('animationCtrl', function () {

    });


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AsyncGenerator.Analyzation;
using AsyncGenerator.Core.Analyzation;

namespace AsyncGenerator.Transformation.Internal
{
	internal class RootNamespaceTransformationResult : NamespaceTransformationResult
	{
		public RootNamespaceTransformationResult(INamespaceAnalyzationResult analyzationResult) : base(analyzationResult)
		{
		}

		public List<NamespaceTransformationResult> DescendantTransformedNamespaces { get; } = new List<NamespaceTransformationResult>();

		public IEnumerable<NamespaceTransformationResult> GetSelfAndDescendantTransformedNamespaces()
		{
			yield return this;
			foreach (var transformType in DescendantTransformedNamespaces)
			{
				yield return transformType;
			}
		}
	}
}


text:
<?php

namespace Dotdigitalgroup\Email\Model;

class Abandoned extends \Magento\Framework\Model\AbstractModel
{
    /**
     * @var ResourceModel\Abandoned\Collection
     */
    public $abandonedCollectionFactory;

    /**
     * @var \Magento\Framework\Stdlib\DateTime
     */
    private $dateTime;

    /**
     * Abandoned constructor.
     *
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param ResourceModel\Abandoned\CollectionFactory $abandoned
     * @param \Magento\Framework\Stdlib\DateTime $dateTime
     * @param array $data
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
     * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
     */
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Dotdigitalgroup\Email\Model\ResourceModel\Abandoned\CollectionFactory $abandoned,
        \Magento\Framework\Stdlib\DateTime $dateTime,
        array $data = [],
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null
    ) {
        $this->abandonedCollectionFactory = $abandoned;
        $this->dateTime     = $dateTime;
        parent::__construct(
            $context,
            $registry,
            $resource,
            $resourceCollection,
            $data
        );
    }

    /**
     * Constructor.
     *
     * @return null
     */
    public function _construct()
    {
        parent::_construct();
        $this->_init(\Dotdigitalgroup\Email\Model\ResourceModel\Abandoned::class);
    }

    /**
     * Prepare data to be saved to database.
     *
     * @return $this
     */
    public function beforeSave()
    {
        parent::beforeSave();
        if ($this->isObjectNew()) {
            $this->setCreatedAt($this->dateTime->formatDate(true));
        }
        $this->setUpdatedAt($this->dateTime->formatDate(true));

        return $this;
    }

    /**
     * @param int $quoteId
     * @return \Dotdigitalgroup\Email\Model\Abandoned
     */
    public function loadByQuoteId($quoteId)
    {
        $collection = $this->abandonedCollectionFactory->create()
            ->addFieldToFilter('quote_id', $quoteId)
            ->setPageSize(1);

        return $collection->getFirstItem();
    }
}


text:
'use strict';
const common = require('../common');
const dnstools = require('../common/dns');
const { Resolver } = require('dns');
const assert = require('assert');
const dgram = require('dgram');

const server = dgram.createSocket('udp4');
const resolver = new Resolver();

server.bind(0, common.mustCall(() => {
  resolver.setServers([`127.0.0.1:${server.address().port}`]);
  resolver.reverse('123.45.67.89', common.mustCall((err, res) => {
    assert.strictEqual(err.code, 'ECANCELLED');
    assert.strictEqual(err.errno, 'ECANCELLED');
    assert.strictEqual(err.syscall, 'getHostByAddr');
    assert.strictEqual(err.hostname, '123.45.67.89');
    server.close();
  }));
}));

server.on('message', common.mustCall((msg, { address, port }) => {
  const parsed = dnstools.parseDNSPacket(msg);
  const domain = parsed.questions[0].domain;
  assert.strictEqual(domain, '89.67.45.123.in-addr.arpa');

  // Do not send a reply.
  resolver.cancel();
}));


text:
package brooklyn.util.repeat;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.testng.annotations.Test;

import brooklyn.util.time.Duration;

import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.Callables;

public class RepeaterTest {

    @Test
    public void sanityTest() {
        new Repeater("Sanity test")
            .until(Callables.returning(true))
            .every(Duration.millis(10));
    }

    @Test
    public void sanityTestDescription() {
        new Repeater()
            .until(Callables.returning(true))
            .every(Duration.millis(10));
    }

    @Test
    public void sanityTestBuilder() {
        Repeater.create("Sanity test")
            .until(Callables.returning(true))
            .every(Duration.millis(10));
    }

    @Test
    public void sanityTestBuilderDescription() {
        Repeater.create()
            .until(Callables.returning(true))
            .every(Duration.millis(10));
    }

    @Test
    public void repeatSucceedsIfClosureIsNonNull() {
        new Repeater("repeatSucceedsIfClosureIsNonNull").repeat(Callables.returning(true));
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void untilFailsIfClosureIsNull() {
        new Repeater("untilFailsIfClosureIsNull").until(null);
        fail("Expected exception was not thrown");
    }

    @Test
    public void untilSucceedsIfClosureIsNonNull() {
        new Repeater("untilSucceedsIfClosureIsNonNull")
            .until(Callables.returning(true));
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void everyFailsIfPeriodIsZero() {
        new Repeater("everyFailsIfPeriodIsZero").every(Duration.ZERO);
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void everyFailsIfPeriodIsNegative() {
        new Repeater("everyFailsIfPeriodIsNegative").every(Duration.millis(-1));
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void everyFailsIfUnitsIsNull() {
        new Repeater("everyFailsIfUnitsIsNull").every(10, null);
        fail("Expected exception was not thrown");
    }

    @Test
    public void everySucceedsIfPeriodIsPositiveAndUnitsIsNonNull() {
        new Repeater("repeatSucceedsIfClosureIsNonNull").every(Duration.millis(10));
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void limitTimeToFailsIfPeriodIsZero() {
        new Repeater("limitTimeToFailsIfPeriodIsZero").limitTimeTo(0, TimeUnit.MILLISECONDS);
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void limitTimeToFailsIfPeriodIsNegative() {
        new Repeater("limitTimeToFailsIfPeriodIsNegative").limitTimeTo(-1, TimeUnit.MILLISECONDS);
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
    public void limitTimeToFailsIfUnitsIsNull() {
        new Repeater("limitTimeToFailsIfUnitsIsNull").limitTimeTo(10, null);
        fail("Expected exception was not thrown");
    }

    @Test
    public void limitTimeToSucceedsIfPeriodIsPositiveAndUnitsIsNonNull() {
        new Repeater("limitTimeToSucceedsIfClosureIsNonNull").limitTimeTo(10, TimeUnit.MILLISECONDS);
    }

    @Test
    public void everyAcceptsDuration() {
        new Repeater("everyAcceptsDuration").every(Duration.ONE_SECOND);
    }

    @Test
    public void everyAcceptsTimeUnit() {
        new Repeater("everyAcceptsTimeUnit").every(1000000L, TimeUnit.MICROSECONDS);
    }

    @Test
    public void runReturnsTrueIfExitConditionIsTrue() {
        assertTrue(new Repeater("runReturnsTrueIfExitConditionIsTrue")
            .every(Duration.millis(1))
            .until(Callables.returning(true))
            .run());
    }

    @Test
    public void runRespectsMaximumIterationLimitAndReturnsFalseIfReached() {
        final AtomicInteger iterations = new AtomicInteger();
        assertFalse(new Repeater("runRespectsMaximumIterationLimitAndReturnsFalseIfReached")
            .repeat(new Runnable() { public void run() { iterations.incrementAndGet(); } })
            .every(Duration.millis(1))
            .until(Callables.returning(false))
            .limitIterationsTo(5)
            .run());
        assertEquals(iterations.get(), 5);
    }

    /**
     * Check that the {@link Repeater} will stop after a time limit.
     *
     * The repeater is configured to run every 100ms and never stop until the limit is reached.
     * This is given as {@link Repeater#limitTimeTo(groovy.time.Duration)} and the execution time
     * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling
     * delays and other factors in a non RTOS system it is expected that the repeater will take much
     * longer to exit occasionally.
     *
     * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached()
     */
    @Test(groups="Integration")
    public void runRespectsTimeLimitAndReturnsFalseIfReached() {
        final long LIMIT = 2000l;
        Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached")
            .every(Duration.millis(100))
            .until(Callables.returning(false))
            .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS);

        Stopwatch stopwatch = Stopwatch.createStarted();
        boolean result = repeater.run();
        stopwatch.stop();

        assertFalse(result);

        long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        assertTrue(difference >= LIMIT, "Difference was: " + difference);
        assertTrue(difference < 4 * LIMIT, "Difference was: " + difference);
    }

    @Test(expectedExceptions = { IllegalStateException.class })
    public void runFailsIfUntilWasNotSet() {
        new Repeater("runFailsIfUntilWasNotSet")
            .every(Duration.millis(10))
            .run();
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { IllegalStateException.class })
    public void runFailsIfEveryWasNotSet() {
        new Repeater("runFailsIfEveryWasNotSet")
            .until(Callables.returning(true))
            .run();
        fail("Expected exception was not thrown");
    }

    @Test(expectedExceptions = { UnsupportedOperationException.class })
    public void testRethrowsException() {
        new Repeater("throwRuntimeException")
            .every(Duration.millis(10))
            .until(callableThrowingUnsupportedFail())
            .rethrowException()
            .limitIterationsTo(2)
            .run();
        fail("Expected exception was not thrown");
    }

    @Test
    public void testNoRethrowsException() {
        try {
	        boolean result = new Repeater("throwRuntimeException")
	            .every(Duration.millis(10))
	            .until(callableThrowingUnsupportedFail())
	            .limitIterationsTo(2)
	            .run();
	        assertFalse(result);
        } catch (RuntimeException re) {
            fail("Exception should not have been thrown: " + re.getMessage());
        }
    }

	private static Callable<Boolean> callableThrowingUnsupportedFail() {
        return new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                throw new UnsupportedOperationException("fail");
            }
        };
    }

}


text:
import java.io.FileNotFoundException;
import java.io.PrintStream;

class MyTestClass {
  void test() throws FileNotFoundException {
      try (PrintStream t = null) {
      System.out.println(t);
    }
  }
}


text:
using System;
using UnityEditor;

namespace Swisstalk.Platform.Unity3d.DI.Prefabs
{
    public struct PrefabComponentKey
    {
        private readonly string prefabKey;
        private readonly Type componentType;
        private readonly int hashCode;

        public PrefabComponentKey(string prefabKey, Type componentType)
        {
            this.prefabKey = prefabKey;
            this.componentType = componentType;
            this.hashCode = string.Format("{0}__{1}", prefabKey, componentType.FullName).GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (obj is PrefabComponentKey)
            {
                PrefabComponentKey other = (PrefabComponentKey)obj;
                return prefabKey == other.prefabKey && componentType == other.componentType;
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            return hashCode;
        }
    }
}


text:
/**
 */
package de.unidue.ecg.dialogScript.dialogScript;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Jump'.
 *
 *
 *
 * @see de.unidue.ecg.dialogScript.dialogScript.DialogScriptPackage#getJump()
 * @model
 * @generated
 */
public interface Jump extends EObject
{
} // Jump


text:
#pragma once
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>
#include "sco_fwd.hpp"
#include <iosfwd>
#include <limits>
#include <stdexcept>
/**
@file solver_interface.hpp
@brief Interface to convex solvers

  This is based on Gurobi's nice c++ API (though the SCO Gurobi backend uses the Gurobi c api).
  However, our intention is to allow for different solvers to be used as backends.
 */

namespace sco{

using std::string;
using std::vector;
using std::ostream;

typedef vector<double> DblVec;
typedef vector<int> IntVec;

enum ConstraintType {
  EQ,
  INEQ
};

enum CvxOptStatus {
  CVX_SOLVED,
  CVX_INFEASIBLE,
  CVX_FAILED
};

typedef vector<Var> VarVector;
typedef vector<AffExpr> AffExprVector;
typedef vector<QuadExpr> QuadExprVector;

/** @brief Convex optimization problem

Gotchas:
- after adding a variable, need to call update() before doing anything else with that variable

 */
class Model {
public:
  virtual Var addVar(const string& name)=0;
  virtual Var addVar(const string& name, double lb, double ub);

  virtual Cnt addEqCnt(const AffExpr&, const string& name)=0; // expr == 0
  virtual Cnt addIneqCnt(const AffExpr&, const string& name)=0; // expr <= 0
  virtual Cnt addIneqCnt(const QuadExpr&, const string& name)=0; // expr <= 0

  virtual void removeVar(const Var& var);
  virtual void removeCnt(const Cnt& cnt);
  virtual void removeVars(const VarVector& vars)=0;
  virtual void removeCnts(const vector<Cnt>& cnts)=0;

  virtual void update() = 0; // call after adding/deleting stuff
  virtual void setVarBounds(const Var& var, double lower, double upper);
  virtual void setVarBounds(const VarVector& vars, const vector<double>& lower, const vector<double>& upper)=0;
  virtual double getVarValue(const Var& var) const;
  virtual vector<double> getVarValues(const VarVector& vars) const=0;
  virtual CvxOptStatus optimize()=0;

  virtual void setObjective(const AffExpr&)=0;
  virtual void setObjective(const QuadExpr&)=0;
  virtual void writeToFile(const string& fname)=0;

  virtual VarVector getVars() const=0;

  virtual ModelPtr cloneModel() const { throw std::runtime_error("not implemented"); }

  virtual ~Model() {}

};

struct VarRep {
  VarRep(int _index, const string& _name, void* _creator) : index(_index), name(_name), removed(false), creator(_creator) {}
  int index;
  string name;
  bool removed;
  void* creator;
};

struct Var {
  VarRep* var_rep;
  Var() : var_rep(NULL) {}
  Var(VarRep* var_rep) : var_rep(var_rep) {}
  Var(const Var& other) : var_rep(other.var_rep) {}
  double value(const double* x) const {return x[var_rep->index];}
  double value(const vector<double>& x) const {assert(var_rep->index < (int)x.size()); return x[var_rep->index];}
};

struct CntRep {
  CntRep(int _index, void* _creator) : index(_index), removed(false), creator(_creator){}
  int index;
  bool removed;
  void* creator;
  ConstraintType type;
  string expr; // todo placeholder
};

struct Cnt {
  CntRep* cnt_rep;
  Cnt(): cnt_rep(NULL) {}
  Cnt(CntRep* cnt_rep) : cnt_rep(cnt_rep) {}
  Cnt(const Cnt& other) : cnt_rep(other.cnt_rep) {}
};

struct AffExpr { // affine expression
  double constant;
  vector<double> coeffs;
  vector<Var> vars;
  AffExpr() : constant(0) {}
  explicit AffExpr(double a) : constant(a) {}
  explicit AffExpr(const Var& v) : constant(0), coeffs(1, 1), vars(1, v) {}
  AffExpr(const AffExpr& other) :
    constant(other.constant), coeffs(other.coeffs), vars(other.vars) {}
  size_t size() const {return coeffs.size();}
  double value(const double* x) const;
  double value(const vector<double>& x) const;
};

struct QuadExpr {
  AffExpr affexpr;
  vector<double> coeffs;
  vector<Var> vars1;
  vector<Var> vars2;
  QuadExpr() {}
  QuadExpr(const QuadExpr& other) :
    affexpr(other.affexpr), coeffs(other.coeffs), vars1(other.vars1), vars2(other.vars2) {}
  explicit QuadExpr(double a) : affexpr(a) {}
  explicit QuadExpr(const Var& v) : affexpr(v) {}
  explicit QuadExpr(const AffExpr& aff) : affexpr(aff) {}
  size_t size() const {return coeffs.size();}
  double value(const double* x) const;
  double value(const vector<double>& x) const;
};

ostream& operator<<(ostream&, const Var&);
ostream& operator<<(ostream&, const Cnt&);
ostream& operator<<(ostream&, const AffExpr&);
ostream& operator<<(ostream&, const QuadExpr&);

ModelPtr createModel();

}