text:
namespace content {

namespace {
// The JavaBridge needs to use a Java thread so the callback
// will happen on a thread with a prepared Looper.
class JavaBridgeThread : public base::android::JavaHandlerThread {
 public:
  JavaBridgeThread() : base::android::JavaHandlerThread("JavaBridge") {
    Start();
  }
  virtual ~JavaBridgeThread() {
    Stop();
  }
};

base::LazyInstance<JavaBridgeThread> g_background_thread =
    LAZY_INSTANCE_INITIALIZER;

}  // namespace

GinJavaBridgeDispatcherHost::GinJavaBridgeDispatcherHost(
    WebContents* web_contents,
    jobject retained_object_set)
    : WebContentsObserver(web_contents),
      retained_object_set_(base::android::AttachCurrentThread(),
                           retained_object_set),
      allow_object_contents_inspection_(true) {
  DCHECK(retained_object_set);
}

GinJavaBridgeDispatcherHost::~GinJavaBridgeDispatcherHost() {
}

void GinJavaBridgeDispatcherHost::RenderFrameCreated(
    RenderFrameHost* render_frame_host) {
  for (NamedObjectMap::const_iterator iter = named_objects_.begin();
       iter != named_objects_.end();
       ++iter) {
    render_frame_host->Send(new GinJavaBridgeMsg_AddNamedObject(
        render_frame_host->GetRoutingID(), iter->first, iter->second));
  }
}

void GinJavaBridgeDispatcherHost::RenderFrameDeleted(
    RenderFrameHost* render_frame_host) {
  RemoveHolder(render_frame_host,
               GinJavaBoundObject::ObjectMap::iterator(&objects_),
               objects_.size());
}

GinJavaBoundObject::ObjectID GinJavaBridgeDispatcherHost::AddObject(
    const base::android::JavaRef<jobject>& object,
    const base::android::JavaRef<jclass>& safe_annotation_clazz,
    bool is_named,
    RenderFrameHost* holder) {
  DCHECK(is_named || holder);
  GinJavaBoundObject::ObjectID object_id;
  JNIEnv* env = base::android::AttachCurrentThread();
  JavaObjectWeakGlobalRef ref(env, object.obj());
  if (is_named) {
    object_id = objects_.Add(new scoped_refptr<GinJavaBoundObject>(
        GinJavaBoundObject::CreateNamed(ref, safe_annotation_clazz)));
  } else {
    object_id = objects_.Add(new scoped_refptr<GinJavaBoundObject>(
        GinJavaBoundObject::CreateTransient(
            ref, safe_annotation_clazz, holder)));
  }
#if DCHECK_IS_ON
  {
    GinJavaBoundObject::ObjectID added_object_id;
    DCHECK(FindObjectId(object, &added_object_id));
    DCHECK_EQ(object_id, added_object_id);
  }
#endif  // DCHECK_IS_ON
  base::android::ScopedJavaLocalRef<jobject> retained_object_set =
        retained_object_set_.get(env);
  if (!retained_object_set.is_null()) {
    JNI_Java_HashSet_add(env, retained_object_set, object);
  }
  return object_id;
}

bool GinJavaBridgeDispatcherHost::FindObjectId(
    const base::android::JavaRef<jobject>& object,
    GinJavaBoundObject::ObjectID* object_id) {
  JNIEnv* env = base::android::AttachCurrentThread();
  for (GinJavaBoundObject::ObjectMap::iterator it(&objects_); !it.IsAtEnd();
       it.Advance()) {
    if (env->IsSameObject(
            object.obj(),
            it.GetCurrentValue()->get()->GetLocalRef(env).obj())) {
      *object_id = it.GetCurrentKey();
      return true;
    }
  }
  return false;
}

JavaObjectWeakGlobalRef GinJavaBridgeDispatcherHost::GetObjectWeakRef(
    GinJavaBoundObject::ObjectID object_id) {
  scoped_refptr<GinJavaBoundObject>* result = objects_.Lookup(object_id);
  scoped_refptr<GinJavaBoundObject> object(result ? *result : NULL);
  if (object.get())
    return object->GetWeakRef();
  else
    return JavaObjectWeakGlobalRef();
}

void GinJavaBridgeDispatcherHost::RemoveHolder(
    RenderFrameHost* holder,
    const GinJavaBoundObject::ObjectMap::iterator& from,
    size_t count) {
  JNIEnv* env = base::android::AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> retained_object_set =
      retained_object_set_.get(env);
  size_t i = 0;
  for (GinJavaBoundObject::ObjectMap::iterator it(from);
       !it.IsAtEnd() && i < count;
       it.Advance(), ++i) {
    scoped_refptr<GinJavaBoundObject> object(*it.GetCurrentValue());
    if (object->IsNamed())
      continue;
    object->RemoveHolder(holder);
    if (!object->HasHolders()) {
      if (!retained_object_set.is_null()) {
        JNI_Java_HashSet_remove(
            env, retained_object_set, object->GetLocalRef(env));
      }
      objects_.Remove(it.GetCurrentKey());
    }
  }
}

void GinJavaBridgeDispatcherHost::AddNamedObject(
    const std::string& name,
    const base::android::JavaRef<jobject>& object,
    const base::android::JavaRef<jclass>& safe_annotation_clazz) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  GinJavaBoundObject::ObjectID object_id;
  NamedObjectMap::iterator iter = named_objects_.find(name);
  bool existing_object = FindObjectId(object, &object_id);
  if (existing_object && iter != named_objects_.end() &&
      iter->second == object_id) {
    // Nothing to do.
    return;
  }
  if (iter != named_objects_.end()) {
    RemoveNamedObject(iter->first);
  }
  if (existing_object) {
    (*objects_.Lookup(object_id))->AddName();
  } else {
    object_id = AddObject(object, safe_annotation_clazz, true, NULL);
  }
  named_objects_[name] = object_id;

  web_contents()->SendToAllFrames(
      new GinJavaBridgeMsg_AddNamedObject(MSG_ROUTING_NONE, name, object_id));
}

void GinJavaBridgeDispatcherHost::RemoveNamedObject(
    const std::string& name) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  NamedObjectMap::iterator iter = named_objects_.find(name);
  if (iter == named_objects_.end())
    return;

  scoped_refptr<GinJavaBoundObject> object(*objects_.Lookup(iter->second));
  named_objects_.erase(iter);
  object->RemoveName();

  // Not erasing from the objects map, as we can still receive method
  // invocation requests for this object, and they should work until the
  // java object is gone.
  if (!object->IsNamed()) {
    JNIEnv* env = base::android::AttachCurrentThread();
    base::android::ScopedJavaLocalRef<jobject> retained_object_set =
        retained_object_set_.get(env);
    if (!retained_object_set.is_null()) {
      JNI_Java_HashSet_remove(
          env, retained_object_set, object->GetLocalRef(env));
    }
  }

  web_contents()->SendToAllFrames(
      new GinJavaBridgeMsg_RemoveNamedObject(MSG_ROUTING_NONE, name));
}

void GinJavaBridgeDispatcherHost::SetAllowObjectContentsInspection(bool allow) {
  allow_object_contents_inspection_ = allow;
}

void GinJavaBridgeDispatcherHost::DocumentAvailableInMainFrame() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  // Called when the window object has been cleared in the main frame.
  // That means, all sub-frames have also been cleared, so only named
  // objects survived.
  JNIEnv* env = base::android::AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> retained_object_set =
      retained_object_set_.get(env);
  if (!retained_object_set.is_null()) {
    JNI_Java_HashSet_clear(env, retained_object_set);
  }

  // We also need to add back the named objects we have so far as they
  // should survive navigations.
  for (GinJavaBoundObject::ObjectMap::iterator it(&objects_); !it.IsAtEnd();
       it.Advance()) {
    scoped_refptr<GinJavaBoundObject> object(*it.GetCurrentValue());
    if (object->IsNamed()) {
      if (!retained_object_set.is_null()) {
        JNI_Java_HashSet_add(
            env, retained_object_set, object->GetLocalRef(env));
      }
    } else {
      objects_.Remove(it.GetCurrentKey());
    }
  }
}

namespace {

// TODO(mnaganov): Implement passing of a parameter into sync message handlers.
class MessageForwarder : public IPC::Sender {
 public:
  MessageForwarder(GinJavaBridgeDispatcherHost* gjbdh,
                   RenderFrameHost* render_frame_host)
      : gjbdh_(gjbdh), render_frame_host_(render_frame_host) {}
  void OnGetMethods(GinJavaBoundObject::ObjectID object_id,
                    IPC::Message* reply_msg) {
    gjbdh_->OnGetMethods(render_frame_host_,
                         object_id,
                         reply_msg);
  }
  void OnHasMethod(GinJavaBoundObject::ObjectID object_id,
                   const std::string& method_name,
                   IPC::Message* reply_msg) {
    gjbdh_->OnHasMethod(render_frame_host_,
                        object_id,
                        method_name,
                        reply_msg);
  }
  void OnInvokeMethod(GinJavaBoundObject::ObjectID object_id,
                      const std::string& method_name,
                      const base::ListValue& arguments,
                      IPC::Message* reply_msg) {
    gjbdh_->OnInvokeMethod(render_frame_host_,
                           object_id,
                           method_name,
                           arguments,
                           reply_msg);
  }
  virtual bool Send(IPC::Message* msg) OVERRIDE {
    NOTREACHED();
    return false;
  }
 private:
  GinJavaBridgeDispatcherHost* gjbdh_;
  RenderFrameHost* render_frame_host_;
};

}

bool GinJavaBridgeDispatcherHost::OnMessageReceived(
    const IPC::Message& message,
    RenderFrameHost* render_frame_host) {
  DCHECK(render_frame_host);
  bool handled = true;
  MessageForwarder forwarder(this, render_frame_host);
  IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(GinJavaBridgeDispatcherHost, message,
                                   render_frame_host)
    IPC_MESSAGE_FORWARD_DELAY_REPLY(GinJavaBridgeHostMsg_GetMethods,
                                    &forwarder,
                                    MessageForwarder::OnGetMethods)
    IPC_MESSAGE_FORWARD_DELAY_REPLY(GinJavaBridgeHostMsg_HasMethod,
                                    &forwarder,
                                    MessageForwarder::OnHasMethod)
    IPC_MESSAGE_FORWARD_DELAY_REPLY(GinJavaBridgeHostMsg_InvokeMethod,
                                    &forwarder,
                                    MessageForwarder::OnInvokeMethod)
    IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_ObjectWrapperDeleted,
                        OnObjectWrapperDeleted)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

namespace {

class IsValidRenderFrameHostHelper
    : public base::RefCounted<IsValidRenderFrameHostHelper> {
 public:
  explicit IsValidRenderFrameHostHelper(RenderFrameHost* rfh_to_match)
      : rfh_to_match_(rfh_to_match), rfh_found_(false) {}

  bool rfh_found() { return rfh_found_; }

  void OnFrame(RenderFrameHost* rfh) {
    if (rfh_to_match_ == rfh) rfh_found_ = true;
  }

 private:
  friend class base::RefCounted<IsValidRenderFrameHostHelper>;

  ~IsValidRenderFrameHostHelper() {}

  RenderFrameHost* rfh_to_match_;
  bool rfh_found_;

  DISALLOW_COPY_AND_ASSIGN(IsValidRenderFrameHostHelper);
};

}  // namespace

bool GinJavaBridgeDispatcherHost::IsValidRenderFrameHost(
    RenderFrameHost* render_frame_host) {
  scoped_refptr<IsValidRenderFrameHostHelper> helper =
      new IsValidRenderFrameHostHelper(render_frame_host);
  web_contents()->ForEachFrame(
      base::Bind(&IsValidRenderFrameHostHelper::OnFrame, helper));
  return helper->rfh_found();
}

void GinJavaBridgeDispatcherHost::SendReply(
    RenderFrameHost* render_frame_host,
    IPC::Message* reply_msg) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (IsValidRenderFrameHost(render_frame_host)) {
    render_frame_host->Send(reply_msg);
  } else {
    delete reply_msg;
  }
}

void GinJavaBridgeDispatcherHost::OnGetMethods(
    RenderFrameHost* render_frame_host,
    GinJavaBoundObject::ObjectID object_id,
    IPC::Message* reply_msg) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(render_frame_host);
  if (!allow_object_contents_inspection_) {
    IPC::WriteParam(reply_msg, std::set<std::string>());
    render_frame_host->Send(reply_msg);
    return;
  }
  scoped_refptr<GinJavaBoundObject> object(*objects_.Lookup(object_id));
  if (!object) {
    LOG(ERROR) << "WebView: Unknown object: " << object_id;
    IPC::WriteParam(reply_msg, std::set<std::string>());
    render_frame_host->Send(reply_msg);
    return;
  }
  base::PostTaskAndReplyWithResult(
      g_background_thread.Get().message_loop()->message_loop_proxy(),
      FROM_HERE,
      base::Bind(&GinJavaBoundObject::GetMethodNames, object),
      base::Bind(&GinJavaBridgeDispatcherHost::SendMethods,
                 AsWeakPtr(),
                 render_frame_host,
                 reply_msg));
}

void GinJavaBridgeDispatcherHost::SendMethods(
    RenderFrameHost* render_frame_host,
    IPC::Message* reply_msg,
    const std::set<std::string>& method_names) {
  IPC::WriteParam(reply_msg, method_names);
  SendReply(render_frame_host, reply_msg);
}

void GinJavaBridgeDispatcherHost::OnHasMethod(
    RenderFrameHost* render_frame_host,
    GinJavaBoundObject::ObjectID object_id,
    const std::string& method_name,
    IPC::Message* reply_msg) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(render_frame_host);
  scoped_refptr<GinJavaBoundObject> object(*objects_.Lookup(object_id));
  if (!object) {
    LOG(ERROR) << "WebView: Unknown object: " << object_id;
    IPC::WriteParam(reply_msg, false);
    render_frame_host->Send(reply_msg);
    return;
  }
  base::PostTaskAndReplyWithResult(
      g_background_thread.Get().message_loop()->message_loop_proxy(),
      FROM_HERE,
      base::Bind(&GinJavaBoundObject::HasMethod, object, method_name),
      base::Bind(&GinJavaBridgeDispatcherHost::SendHasMethodReply,
                 AsWeakPtr(),
                 render_frame_host,
                 reply_msg));
}

void GinJavaBridgeDispatcherHost::SendHasMethodReply(
    RenderFrameHost* render_frame_host,
    IPC::Message* reply_msg,
    bool result) {
  IPC::WriteParam(reply_msg, result);
  SendReply(render_frame_host, reply_msg);
}

void GinJavaBridgeDispatcherHost::OnInvokeMethod(
    RenderFrameHost* render_frame_host,
    GinJavaBoundObject::ObjectID object_id,
    const std::string& method_name,
    const base::ListValue& arguments,
    IPC::Message* reply_msg) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(render_frame_host);
  scoped_refptr<GinJavaBoundObject> object(*objects_.Lookup(object_id));
  if (!object) {
    LOG(ERROR) << "WebView: Unknown object: " << object_id;
    base::ListValue result;
    result.Append(base::Value::CreateNullValue());
    IPC::WriteParam(reply_msg, result);
    IPC::WriteParam(reply_msg, kGinJavaBridgeUnknownObjectId);
    render_frame_host->Send(reply_msg);
    return;
  }
  scoped_refptr<GinJavaMethodInvocationHelper> result =
      new GinJavaMethodInvocationHelper(
          make_scoped_ptr(new GinJavaBoundObjectDelegate(object))
              .PassAs<GinJavaMethodInvocationHelper::ObjectDelegate>(),
          method_name,
          arguments);
  result->Init(this);
  g_background_thread.Get()
      .message_loop()
      ->message_loop_proxy()
      ->PostTaskAndReply(
          FROM_HERE,
          base::Bind(&GinJavaMethodInvocationHelper::Invoke, result),
          base::Bind(
              &GinJavaBridgeDispatcherHost::ProcessMethodInvocationResult,
              AsWeakPtr(),
              render_frame_host,
              reply_msg,
              result));
}

void GinJavaBridgeDispatcherHost::ProcessMethodInvocationResult(
    RenderFrameHost* render_frame_host,
    IPC::Message* reply_msg,
    scoped_refptr<GinJavaMethodInvocationHelper> result) {
  if (result->HoldsPrimitiveResult()) {
    IPC::WriteParam(reply_msg, result->GetPrimitiveResult());
    IPC::WriteParam(reply_msg, result->GetInvocationError());
    SendReply(render_frame_host, reply_msg);
  } else {
    ProcessMethodInvocationObjectResult(render_frame_host, reply_msg, result);
  }
}

void GinJavaBridgeDispatcherHost::ProcessMethodInvocationObjectResult(
    RenderFrameHost* render_frame_host,
    IPC::Message* reply_msg,
    scoped_refptr<GinJavaMethodInvocationHelper> result) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!IsValidRenderFrameHost(render_frame_host)) {
    delete reply_msg;
    return;
  }
  base::ListValue wrapped_result;
  if (!result->GetObjectResult().is_null()) {
    GinJavaBoundObject::ObjectID returned_object_id;
    if (FindObjectId(result->GetObjectResult(), &returned_object_id)) {
      (*objects_.Lookup(returned_object_id))->AddHolder(render_frame_host);
    } else {
      returned_object_id = AddObject(result->GetObjectResult(),
                                     result->GetSafeAnnotationClass(),
                                     false,
                                     render_frame_host);
    }
    wrapped_result.Append(
        GinJavaBridgeValue::CreateObjectIDValue(returned_object_id).release());
  } else {
    wrapped_result.Append(base::Value::CreateNullValue());
  }
  IPC::WriteParam(reply_msg, wrapped_result);
  IPC::WriteParam(reply_msg, result->GetInvocationError());
  render_frame_host->Send(reply_msg);
}

void GinJavaBridgeDispatcherHost::OnObjectWrapperDeleted(
    RenderFrameHost* render_frame_host,
    GinJavaBoundObject::ObjectID object_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(render_frame_host);
  if (objects_.Lookup(object_id)) {
    GinJavaBoundObject::ObjectMap::iterator iter(&objects_);
    while (!iter.IsAtEnd() && iter.GetCurrentKey() != object_id)
      iter.Advance();
    DCHECK(!iter.IsAtEnd());
    RemoveHolder(render_frame_host, iter, 1);
  }
}

}  // namespace content


text:
import { remoteFunction } from 'src/util/webextensionRPC'
import { copyToClipboard } from './utils'
import { extractAnchorFromSelection } from 'src/highlighting/ui/highlight-interactions'

export const createAndCopyDirectLink = async () => {
    const selection = document.getSelection()
    const range = selection.getRangeAt(0)
    const url = window.location.href

    const anchor = await extractAnchorFromSelection(selection)
    const result: { url: string } = await remoteFunction('createDirectLink')({
        url,
        anchor,
    })
    await copyToClipboard(result.url)

    selection.removeAllRanges()
    selection.addRange(range)

    return result
}

redpajama_set_name: RedPajamaGithub


text:
package com.yahoo.pasc.paxos.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LeaderElection implements Watcher {

    private static final Logger LOG = LoggerFactory.getLogger(LeaderElection.class);

    private ZooKeeper zk;
    private int id;
    private static final String ELECTION_PATH = "/pasc_election";
    private LeadershipObserver observer;

    public LeaderElection(ZooKeeper zk, int id, LeadershipObserver observer) throws IOException {
        this.zk = zk;
        this.id = id;
        this.observer = observer;
    }

    public void start() {
        try {
            zk.create(ELECTION_PATH, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException.NoNodeException e) {
            // ignore
        } catch (KeeperException.NodeExistsException e) {
            // ignore
        } catch (Exception e) {
            LOG.warn("Unexpected exception: " + e);
        }
        try {
            zk.create(ELECTION_PATH + "/" + id, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
//            checkLeadership(zk.getChildren(ELECTION_PATH, this));
        } catch (Exception e) {
            LOG.warn("Unexpected exception: " + e);
        }
    }

    private void checkLeadership(List<String> children) {
        List<Integer> ids = new ArrayList<Integer>();
        for (String id : children) {
            ids.add(Integer.parseInt(id));
        }
        Collections.sort(ids);

        LOG.debug("Tentative leaders: " + ids);

        if (ids.isEmpty())
            return;

        observer.setLeadership(ids.get(0));
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() != EventType.NodeChildrenChanged)
            return;
        refresh();
    }

    public void refresh() {
        try {
            checkLeadership(zk.getChildren(ELECTION_PATH, this));
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


text:
import setup_util
import subprocess
import sys
import time
import os

def start(args, logfile, errfile):
  setup_util.replace_text("plain/src/main/resources/application.conf", "127.0.0.1", args.database_host)
  if os.name == 'nt':
    subprocess.check_call(".\sbt.bat assembly && del /f /s /q target\scala-2.10\cache", shell=True, cwd="plain", stderr=errfile, stdout=logfile)
  else:
    subprocess.check_call("./sbt assembly && rm -rf target/scala-2.10/cache", shell=True, cwd="plain", stderr=errfile, stdout=logfile)

  subprocess.Popen("java -jar target/scala-2.10/plain-benchmark-assembly-1.0.1.jar", cwd="plain", shell=True, stderr=errfile, stdout=logfile)
  time.sleep(10)
  return 0

def stop(logfile, errfile):
  if os.name == 'nt':
    subprocess.call("taskkill /f /im *plain-benchmark* > NUL", shell=True, stderr=errfile, stdout=logfile)
  else:
    p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
      if 'plain-benchmark' in line:
        try:
          pid = int(line.split(None, 2)[1])
          os.kill(pid, 15)
        except OSError:
          return 1

  # Takes up so much disk space
  if os.name == 'nt':
    subprocess.check_call("del /f /s /q target && del /f /s /q project", shell=True, cwd="plain", stderr=errfile, stdout=logfile)
  else:
    subprocess.check_call("rm -rf target && rm -rf project/.ivy && rm -rf project/.boot", shell=True, cwd="plain", stderr=errfile, stdout=logfile)

  return 0


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
using Azure.ResourceManager.Storage.Models;
using NUnit.Framework;
//using Newtonsoft.Json.Linq;
using CM = Azure.ResourceManager.Compute.Models;

namespace Azure.ResourceManager.Compute.Tests
{
    public class VMScaleSetTestsBase : VMTestBase
    {
        public VMScaleSetTestsBase(bool isAsync)
        : base(isAsync)
        {
        }
        [SetUp]
        public void ClearChallengeCacheforRecord()
        {
            if (Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback)
            {
                InitializeBase();
            }
        }

        [TearDown]
        public async Task CleanupResourceGroup()
        {
            await CleanupResourceGroupsAsync();
        }

        protected VirtualMachineScaleSetExtension GetTestVMSSVMExtension(
            string name = "vmssext01",
            string publisher = "Microsoft.Compute",
            string type = "VMAccessAgent",
            string version = "2.0")
        {
            var vmExtension = new VirtualMachineScaleSetExtension()
            {
                Name = name,
                Publisher = publisher,
                TypePropertiesType = type,
                TypeHandlerVersion = version,
                AutoUpgradeMinorVersion = true,
                Settings = "{}",
                ProtectedSettings = "{}"
            };
            return vmExtension;
        }

        protected VirtualMachineScaleSetExtension GetVmssServiceFabricExtension()
        {
            VirtualMachineScaleSetExtension sfExtension = new VirtualMachineScaleSetExtension(
                null, "vmsssfext01", "ServiceFabricNode", null, "Microsoft.Azure.ServiceFabric", null, "1.0", true, "{}", "{}", null, null);

            return sfExtension;
        }

        protected VirtualMachineScaleSetExtension GetAzureDiskEncryptionExtension()
        {
            // NOTE: Replace dummy values for AAD credentials and KeyVault urls below by running DiskEncryptionPreRequisites.ps1.
            // There is no ARM client implemented for key-vault in swagger test framework yet. These changes need to go sooner to
            // unblock powershell cmdlets/API for disk encryption on scale set. So recorded this test by creating required resources
            // in prod and replaced them with dummy value before check-in.
            //
            // Follow below steps to run this test again:
            //   Step 1: Execute DiskEncryptionPreRequisites.ps1. Use same subscription and region as you are running test in.
            //   Step 2: Replace aadClientId, aadClientSecret, keyVaultUrl, and keyVaultId values below with the values returned
            //           by above PS script
            //   Step 3: Run test and record session
            //   Step 4: Delete KeyVault, AAD app created by above PS script
            //   Step 5: Replace values for AAD credentials and KeyVault urls by dummy values before check-in
            string aadClientId = Guid.NewGuid().ToString();
            string aadClientSecret = Guid.NewGuid().ToString();
            string keyVaultUrl = "https://adetestkv1.vault.azure.net/";
            string keyVaultId =
                "/subscriptions/d0d8594d-65c5-481c-9a58-fea6f203f1e2/resourceGroups/adetest/providers/Microsoft.KeyVault/vaults/adetestkv1";

            string settings =
                string.Format("\"AADClientID\": \"{0}\", \"KeyVaultURL\": \"{1}\", \"KeyEncryptionKeyURL\": \"\", \"KeyVaultResourceId\":\"{2}\", \"KekVaultResourceId\": \"\", \"KeyEncryptionAlgorithm\": \"{3}\", \"VolumeType\": \"{4}\", \"EncryptionOperation\": \"{5}\"",
                                aadClientId, keyVaultUrl, keyVaultId, "", "All", "DisableEncryption");

            string protectedSettings = string.Format("\"AADClientSecret\": \"{0}\"", aadClientSecret);

            var vmExtension = new VirtualMachineScaleSetExtension(
                null, "adeext1", "ADETest", null, "Microsoft.Azure.Security", null, "2.0", null, "{ " + settings + " }", "{ " + protectedSettings + " }", null, null);
            return vmExtension;
        }

        protected VirtualMachineScaleSet CreateDefaultVMScaleSetInput(
            string rgName,
            string storageAccountName,
            ImageReference imageRef,
            string subnetId,
            bool hasManagedDisks = false,
            string healthProbeId = null,
            string loadBalancerBackendPoolId = null,
            IList<string> zones = null,
            int? osDiskSizeInGB = null,
            string machineSizeType = null,
            bool? enableUltraSSD = false,
            string diskEncryptionSetId = null,
            AutomaticRepairsPolicy automaticRepairsPolicy = null)
        {
            // Generate Container name to hold disk VHds
            string containerName = Recording.GenerateAssetName(TestPrefix);
            var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName;
            var vmssName = Recording.GenerateAssetName("vmss");
            bool createOSDisk = !hasManagedDisks || osDiskSizeInGB != null;

            string vmSize = zones == null ? VirtualMachineSizeTypes.StandardA0.ToString() : VirtualMachineSizeTypes.StandardA1V2.ToString();
            var test1 = Recording.GenerateAssetName("vmsstestnetconfig");
            var test2 = Recording.GenerateAssetName("vmsstestnetconfig");
            var virtualMachineScaleSetIpConfiguration = new VirtualMachineScaleSetIPConfiguration(test2)
            {
                Subnet = new Azure.ResourceManager.Compute.Models.ApiEntityReference()
                {
                    Id = subnetId
                }
            };

            virtualMachineScaleSetIpConfiguration.ApplicationGatewayBackendAddressPools.Clear();
            if (loadBalancerBackendPoolId != null)
            {
                virtualMachineScaleSetIpConfiguration.LoadBalancerBackendAddressPools.Add(new Models.SubResource(loadBalancerBackendPoolId));
            }

            var virtualMachineScaleSetOsDisk = !createOSDisk ? null : new VirtualMachineScaleSetOSDisk(DiskCreateOptionTypes.FromImage)
            {
                Caching = CachingTypes.None,
                Name = hasManagedDisks ? null : "test",
                DiskSizeGB = osDiskSizeInGB,
                ManagedDisk = diskEncryptionSetId == null ? null : new VirtualMachineScaleSetManagedDiskParameters()
                {
                    StorageAccountType = StorageAccountTypes.StandardLRS,
                    DiskEncryptionSet = new DiskEncryptionSetParameters()
                    {
                        Id = diskEncryptionSetId
                    }
                }
            };

            if (!hasManagedDisks)
            {
                virtualMachineScaleSetOsDisk?.VhdContainers.Add(vhdContainer);
            }

            var virtualMachineScaleSetStorageProfile = new VirtualMachineScaleSetStorageProfile()
            {
                ImageReference = imageRef,
                OsDisk = virtualMachineScaleSetOsDisk
            };

            if (hasManagedDisks)
            {
                virtualMachineScaleSetStorageProfile.DataDisks.Add(new VirtualMachineScaleSetDataDisk(1, DiskCreateOptionTypes.Empty)
                {
                    DiskSizeGB = 128,
                    ManagedDisk = diskEncryptionSetId == null
                        ? null
                        : new VirtualMachineScaleSetManagedDiskParameters()
                        {
                            StorageAccountType = StorageAccountTypes.StandardLRS,
                            DiskEncryptionSet = new DiskEncryptionSetParameters()
                            {
                                Id = diskEncryptionSetId
                            }
                        }
                });
            }

            var vmScaleSet = new VirtualMachineScaleSet(m_location)
            {
                Location = m_location,
                Tags = { { "RG", "rg" }, { "testTag", "1" } },
                Sku = new CM.Sku()
                {
                    Capacity = 2,
                    Name = machineSizeType == null ? vmSize : machineSizeType
                },
                Overprovision = false,
                UpgradePolicy = new UpgradePolicy()
                {
                    Mode = UpgradeMode.Automatic
                },
                VirtualMachineProfile = new VirtualMachineScaleSetVMProfile()
                {
                    StorageProfile = virtualMachineScaleSetStorageProfile,
                    OsProfile = new VirtualMachineScaleSetOSProfile()
                    {
                        ComputerNamePrefix = "test",
                        AdminUsername = "Foo12",
                        AdminPassword = PLACEHOLDER,
                        CustomData = Convert.ToBase64String(Encoding.UTF8.GetBytes("Custom data"))
                    },
                    NetworkProfile = new VirtualMachineScaleSetNetworkProfile()
                    {
                        HealthProbe = healthProbeId == null ? null : new ApiEntityReference
                        {
                            Id = healthProbeId
                        },
                        NetworkInterfaceConfigurations = {
                            new VirtualMachineScaleSetNetworkConfiguration(test1)
                            {
                                Primary = true,
                                IpConfigurations = {
                                    virtualMachineScaleSetIpConfiguration
                                }
                            }
                        }
                    },
                    ExtensionProfile = new VirtualMachineScaleSetExtensionProfile(),
                },
                AutomaticRepairsPolicy = automaticRepairsPolicy
            };

            vmScaleSet.Zones.InitializeFrom(zones);
            if (enableUltraSSD == true)
            {
                vmScaleSet.AdditionalCapabilities = new AdditionalCapabilities
                {
                    UltraSSDEnabled = true
                };

                VirtualMachineScaleSetOSDisk osDisk = vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk;
                osDisk.ManagedDisk = osDisk.ManagedDisk ?? new VirtualMachineScaleSetManagedDiskParameters();
                osDisk.ManagedDisk.StorageAccountType = StorageAccountTypes.PremiumLRS;

                foreach (VirtualMachineScaleSetDataDisk dataDisk in vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks)
                {
                    dataDisk.ManagedDisk = dataDisk.ManagedDisk ?? new VirtualMachineScaleSetManagedDiskParameters();
                    dataDisk.ManagedDisk.StorageAccountType = StorageAccountTypes.UltraSSDLRS;
                }
            }

            return vmScaleSet;
        }

        public async Task<(VirtualMachineScaleSet Response, VirtualMachineScaleSet Input)> CreateVMScaleSet_NoAsyncTracking(
            string rgName,
            string vmssName,
            StorageAccount storageAccount,
            ImageReference imageRef,
            VirtualMachineScaleSetExtensionProfile extensionProfile = null,
            Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
            bool createWithPublicIpAddress = false,
            bool createWithManagedDisks = false,
            bool hasDiffDisks = false,
            bool createWithHealthProbe = false,
            Subnet subnet = null,
            IList<string> zones = null,
            int? osDiskSizeInGB = null,
            string ppgId = null,
            string machineSizeType = null,
            bool? enableUltraSSD = false,
            string diskEncryptionSetId = null,
            AutomaticRepairsPolicy automaticRepairsPolicy = null)
        {
            try
            {
                var createOrUpdateResponse = await CreateVMScaleSetAndGetOperationResponse(rgName,
                                                                                vmssName,
                                                                                storageAccount,
                                                                                imageRef,
                                                                                extensionProfile,
                                                                                vmScaleSetCustomizer,
                                                                                createWithPublicIpAddress,
                                                                                createWithManagedDisks,
                                                                                hasDiffDisks,
                                                                                createWithHealthProbe,
                                                                                subnet,
                                                                                zones,
                                                                                osDiskSizeInGB,
                                                                                ppgId: ppgId,
                                                                                machineSizeType: machineSizeType,
                                                                                enableUltraSSD: enableUltraSSD,
                                                                                diskEncryptionSetId: diskEncryptionSetId,
                                                                                automaticRepairsPolicy: automaticRepairsPolicy);

                var getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);
                return (getResponse, createOrUpdateResponse.InputScaleSet);
            }
            catch
            {
                throw;
            }
        }

        //not use in track one
        //protected async Task<VirtualMachineScaleSet> CreateVMScaleSet(
        //    string rgName,
        //    string vmssName,
        //    StorageAccount storageAccount,
        //    ImageReference imageRef,
        //    VirtualMachineScaleSetExtensionProfile extensionProfile = null,
        //    Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
        //    bool createWithPublicIpAddress = false,
        //    bool createWithManagedDisks = false)
        //{
        //    try
        //    {
        //        var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse(
        //            rgName,
        //            vmssName,
        //            storageAccount,
        //            imageRef,
        //            extensionProfile,
        //            vmScaleSetCustomizer,
        //            createWithPublicIpAddress,
        //            createWithManagedDisks);

        //        var lroResponse = await VirtualMachineScaleSetsClient.StartCreateOrUpdateAsync(rgName, inputVMScaleSet.Name, inputVMScaleSet);

        //        var getResponse = await VirtualMachineScaleSetsClient.Get(rgName, inputVMScaleSet.Name);

        //        return getResponse;
        //    }
        //    catch
        //    {
        //        await ResourceGroupsClient.Delete(rgName);
        //        throw;
        //    }
        //}

        protected async Task UpdateVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSet inputVMScaleSet)
        {
            var createOrUpdateResponse = await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartCreateOrUpdateAsync(rgName, vmssName, inputVMScaleSet));
        }

        // This method is used to Update VM Scale Set but it internally calls PATCH verb instead of PUT.
        // PATCH verb is more relaxed and does not puts constraint to specify full parameters.
        protected async Task PatchVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSetUpdate inputVMScaleSet)
        {
            var patchResponse = await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartUpdateAsync(rgName, vmssName, inputVMScaleSet));
        }

        private async Task<(VirtualMachineScaleSet ResponseScaleSet, VirtualMachineScaleSet InputScaleSet)> CreateVMScaleSetAndGetOperationResponse(
            string rgName,
            string vmssName,
            StorageAccount storageAccount,
            ImageReference imageRef,
            VirtualMachineScaleSetExtensionProfile extensionProfile = null,
            Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
            bool createWithPublicIpAddress = false,
            bool createWithManagedDisks = false,
            bool hasDiffDisks = false,
            bool createWithHealthProbe = false,
            Subnet subnet = null,
            IList<string> zones = null,
            int? osDiskSizeInGB = null,
            string ppgId = null,
            string machineSizeType = null,
            bool? enableUltraSSD = false,
            string diskEncryptionSetId = null,
            AutomaticRepairsPolicy automaticRepairsPolicy = null)
        {
            // Create the resource Group, it might have been already created during StorageAccount creation.
            var resourceGroup = await ResourceGroupsOperations.CreateOrUpdateAsync(
                rgName,
                new ResourceGroup(m_location));

            var getPublicIpAddressResponse = createWithPublicIpAddress ? null : await CreatePublicIP(rgName);

            var subnetResponse = subnet ?? await CreateVNET(rgName);

            var nicResponse = await CreateNIC(
                rgName,
                subnetResponse,
                getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null);

            var loadBalancer = ((getPublicIpAddressResponse != null && createWithHealthProbe) ?
                (await CreatePublicLoadBalancerWithProbe(rgName, getPublicIpAddressResponse)) : null);

            Assert.True(createWithManagedDisks || storageAccount != null);
            var inputVMScaleSet = CreateDefaultVMScaleSetInput(rgName, storageAccount?.Name, imageRef, subnetResponse.Id, hasManagedDisks: createWithManagedDisks,
                healthProbeId: loadBalancer?.Probes?.FirstOrDefault()?.Id,
                loadBalancerBackendPoolId: loadBalancer?.BackendAddressPools?.FirstOrDefault()?.Id, zones: zones, osDiskSizeInGB: osDiskSizeInGB,
                machineSizeType: machineSizeType, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, automaticRepairsPolicy: automaticRepairsPolicy);
            if (vmScaleSetCustomizer != null)
            {
                vmScaleSetCustomizer(inputVMScaleSet);
            }

            if (hasDiffDisks)
            {
                VirtualMachineScaleSetOSDisk osDisk = new VirtualMachineScaleSetOSDisk(DiskCreateOptionTypes.FromImage);
                osDisk.Caching = CachingTypes.ReadOnly;
                osDisk.DiffDiskSettings = new DiffDiskSettings
                {
                    Option = "Local",
                    //TODO the value of "Placement" may not be given
                    //Placement = DiffDiskPlacement.CacheDisk
                };
                inputVMScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = osDisk;
            }

            inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile;

            if (ppgId != null)
            {
                inputVMScaleSet.ProximityPlacementGroup = new Azure.ResourceManager.Compute.Models.SubResource() { Id = ppgId };
            }

            VirtualMachineScaleSet createOrUpdateResponse = null;

            try
            {
                createOrUpdateResponse = await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartCreateOrUpdateAsync(rgName, vmssName, inputVMScaleSet));

                Assert.True(createOrUpdateResponse.Name == vmssName);
                Assert.True(createOrUpdateResponse.Location.ToLower() == inputVMScaleSet.Location.ToLower().Replace(" ", ""));
            }
            catch (Exception e)
            {
                if (e.Message.Contains("the allotted time"))
                {
                    createOrUpdateResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);
                }
                else
                {
                    throw;
                }
            }

            ValidateVMScaleSet(inputVMScaleSet, createOrUpdateResponse, createWithManagedDisks, ppgId: ppgId);

            return (createOrUpdateResponse, inputVMScaleSet);
        }

        protected void ValidateVMScaleSetInstanceView(VirtualMachineScaleSet vmScaleSet,
            VirtualMachineScaleSetInstanceView vmScaleSetInstanceView)
        {
            Assert.NotNull(vmScaleSetInstanceView.Statuses);
            Assert.NotNull(vmScaleSetInstanceView);
            if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null)
            {
                Assert.NotNull(vmScaleSetInstanceView.Extensions);
                int instancesCount = vmScaleSetInstanceView.Extensions.First().StatusesSummary.Sum(t => t.Count.Value);
                Assert.True(instancesCount == vmScaleSet.Sku.Capacity);
            }
        }

        protected void ValidateVMScaleSet(VirtualMachineScaleSet vmScaleSet, VirtualMachineScaleSet vmScaleSetOut, bool hasManagedDisks = false, string ppgId = null)
        {
            Assert.True(!string.IsNullOrEmpty(vmScaleSetOut.ProvisioningState));

            Assert.True(vmScaleSetOut.Sku.Name
                     == vmScaleSet.Sku.Name);

            Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk);

            if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk?.DiskSizeGB != null)
            {
                Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB);
                Assert.AreEqual(vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB, vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB);
            }

            if (!hasManagedDisks)
            {
                Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Name
                            == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name);

                if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image != null)
                {
                    Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri
                                == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri);
                }

                Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Caching
                            == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching);
            }
            else
            {
                Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk);

                if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk != null)
                {
                    VirtualMachineScaleSetOSDisk osDisk = vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk;
                    VirtualMachineScaleSetOSDisk osDiskOut =
                        vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk;

                    if (osDisk.Caching != null)
                    {
                        Assert.True(osDisk.Caching == osDiskOut.Caching);
                    }
                    else
                    {
                        Assert.NotNull(osDiskOut.Caching);
                    }

                    if (osDisk.DiffDiskSettings != null)
                    {
                        Assert.True(osDisk.DiffDiskSettings.Option == osDiskOut.DiffDiskSettings.Option);
                    }

                    Assert.NotNull(osDiskOut.ManagedDisk);
                    if (osDisk.ManagedDisk != null && osDisk.ManagedDisk.StorageAccountType != null)
                    {
                        Assert.True(osDisk.ManagedDisk.StorageAccountType == osDiskOut.ManagedDisk.StorageAccountType);
                    }
                    else
                    {
                        Assert.NotNull(osDiskOut.ManagedDisk.StorageAccountType);
                    }

                    if (osDisk.Name != null)
                    {
                        Assert.AreEqual(osDiskOut.Name, osDisk.Name);
                    }

                    Assert.True(osDiskOut.CreateOption == DiskCreateOptionTypes.FromImage);
                }

                if (vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks != null
                    && vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count > 0)
                {
                    Assert.AreEqual(
                        vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count,
                        vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.Count);

                    foreach (VirtualMachineScaleSetDataDisk dataDisk in vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks)
                    {
                        VirtualMachineScaleSetDataDisk matchingDataDisk
                            = vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.FirstOrDefault(disk => disk.Lun == dataDisk.Lun);
                        Assert.NotNull(matchingDataDisk);

                        if (dataDisk.Caching != null)
                        {
                            Assert.True(dataDisk.Caching == matchingDataDisk.Caching);
                        }
                        else
                        {
                            Assert.NotNull(matchingDataDisk.Caching);
                        }

                        if (dataDisk.ManagedDisk != null && dataDisk.ManagedDisk.StorageAccountType != null)
                        {
                            Assert.True(dataDisk.ManagedDisk.StorageAccountType == matchingDataDisk.ManagedDisk.StorageAccountType);
                        }
                        else
                        {
                            Assert.NotNull(matchingDataDisk.ManagedDisk.StorageAccountType);
                        }

                        if (dataDisk.Name != null)
                        {
                            Assert.AreEqual(dataDisk.Name, matchingDataDisk.Name);
                        }
                        Assert.True(dataDisk.CreateOption == matchingDataDisk.CreateOption);
                    }
                }
            }

            if (vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy != null)
            {
                bool expectedDisableAutomaticRollbackValue = vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback ?? false;
                Assert.True(vmScaleSetOut.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback == expectedDisableAutomaticRollbackValue);

                bool expectedEnableAutomaticOSUpgradeValue = vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade ?? false;
                Assert.True(vmScaleSetOut.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade == expectedEnableAutomaticOSUpgradeValue);
            }

            if (vmScaleSet.AutomaticRepairsPolicy != null)
            {
                bool expectedAutomaticRepairsEnabledValue = vmScaleSet.AutomaticRepairsPolicy.Enabled ?? false;
                Assert.True(vmScaleSetOut.AutomaticRepairsPolicy.Enabled == expectedAutomaticRepairsEnabledValue);

                string expectedAutomaticRepairsGracePeriodValue = vmScaleSet.AutomaticRepairsPolicy.GracePeriod ?? "PT30M";
                Assert.AreEqual(vmScaleSetOut.AutomaticRepairsPolicy.GracePeriod, expectedAutomaticRepairsGracePeriodValue);
            }

            if (vmScaleSet.VirtualMachineProfile.OsProfile.Secrets != null &&
               vmScaleSet.VirtualMachineProfile.OsProfile.Secrets.Any())
            {
                foreach (var secret in vmScaleSet.VirtualMachineProfile.OsProfile.Secrets)
                {
                    Assert.NotNull(secret.VaultCertificates);
                    var secretOut = vmScaleSetOut.VirtualMachineProfile.OsProfile.Secrets.FirstOrDefault(s => string.Equals(secret.SourceVault.Id, s.SourceVault.Id));
                    Assert.NotNull(secretOut);

                    // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above.
                    // ReSharper disable PossibleNullReferenceException

                    Assert.NotNull(secretOut.VaultCertificates);
                    var VaultCertComparer = new VaultCertComparer();
                    Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer));

                    // ReSharper enable PossibleNullReferenceException
                }
            }

            if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null &&
                vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions.Any())
            {
                foreach (var vmExtension in vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions)
                {
                    var vmExt = vmScaleSetOut.VirtualMachineProfile.ExtensionProfile.Extensions.FirstOrDefault(s => String.Compare(s.Name, vmExtension.Name, StringComparison.OrdinalIgnoreCase) == 0);
                    Assert.NotNull(vmExt);
                }
            }

            if (vmScaleSet.VirtualMachineProfile.NetworkProfile != null)
            {
                if (vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations != null && vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count > 0)
                {
                    Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations);
                    Assert.AreEqual(
                        vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count,
                        vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count);

                    foreach (var nicconfig in vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations)
                    {
                        var outnicconfig =
                            vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.First(
                                nc => string.Equals(nc.Name, nicconfig.Name, StringComparison.OrdinalIgnoreCase));
                        Assert.NotNull(outnicconfig);
                        CompareVmssNicConfig(nicconfig, outnicconfig);
                    }
                }
            }
            else
            {
                Assert.True((vmScaleSetOut.VirtualMachineProfile.NetworkProfile == null) || (vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count == 0));
            }

            if (vmScaleSet.Zones.Count != 0)
            {
                Assert.True(vmScaleSet.Zones.SequenceEqual(vmScaleSetOut.Zones), "Zones don't match");
                if (vmScaleSet.ZoneBalance.HasValue)
                {
                    Assert.AreEqual(vmScaleSet.ZoneBalance, vmScaleSetOut.ZoneBalance);
                }
                else
                {
                    if (vmScaleSet.Zones.Count > 1)
                    {
                        Assert.True(vmScaleSetOut.ZoneBalance.HasValue);
                    }
                    else
                    {
                        Assert.False(vmScaleSetOut.ZoneBalance.HasValue);
                    }
                }

                if (vmScaleSet.PlatformFaultDomainCount.HasValue)
                {
                    Assert.AreEqual(vmScaleSet.PlatformFaultDomainCount, vmScaleSetOut.PlatformFaultDomainCount);
                }
                else
                {
                    Assert.True(vmScaleSetOut.PlatformFaultDomainCount.HasValue);
                }
            }
            else
            {
                Assert.IsEmpty(vmScaleSetOut.Zones);
                Assert.Null(vmScaleSetOut.ZoneBalance);
            }

            if (ppgId != null)
            {
                Assert.AreEqual(ppgId.ToLower(), vmScaleSetOut.ProximityPlacementGroup.Id.ToLower());
            }
        }

        protected void CompareVmssNicConfig(VirtualMachineScaleSetNetworkConfiguration nicconfig,
            VirtualMachineScaleSetNetworkConfiguration outnicconfig)
        {
            if (nicconfig.IpConfigurations != null && nicconfig.IpConfigurations.Count > 0)
            {
                Assert.NotNull(outnicconfig.IpConfigurations);

                Assert.AreEqual(nicconfig.IpConfigurations.Count, outnicconfig.IpConfigurations.Count);

                foreach (var ipconfig in nicconfig.IpConfigurations)
                {
                    var outipconfig =
                        outnicconfig.IpConfigurations.First(
                            ic => string.Equals(ic.Name, ipconfig.Name, StringComparison.OrdinalIgnoreCase));
                    Assert.NotNull(outipconfig);
                    CompareIpConfigApplicationGatewayPools(ipconfig, outipconfig);
                }
            }
            else
            {
                Assert.True((outnicconfig.IpConfigurations == null) || (outnicconfig.IpConfigurations.Count == 0));
            }
        }

        protected void CompareIpConfigApplicationGatewayPools(VirtualMachineScaleSetIPConfiguration ipconfig, VirtualMachineScaleSetIPConfiguration outipconfig)
        {
            if (ipconfig.ApplicationGatewayBackendAddressPools != null && ipconfig.ApplicationGatewayBackendAddressPools.Count > 0)
            {
                Assert.NotNull(outipconfig.ApplicationGatewayBackendAddressPools);

                Assert.AreEqual(ipconfig.ApplicationGatewayBackendAddressPools.Count,
                    outipconfig.ApplicationGatewayBackendAddressPools.Count);

                foreach (var pool in ipconfig.ApplicationGatewayBackendAddressPools)
                {
                    var outPool =
                        outipconfig.ApplicationGatewayBackendAddressPools.First(
                            p => string.Equals(p.Id, pool.Id, StringComparison.OrdinalIgnoreCase));
                    Assert.NotNull(outPool);
                }
            }
            else
            {
                Assert.True((outipconfig.ApplicationGatewayBackendAddressPools == null) || (outipconfig.ApplicationGatewayBackendAddressPools.Count == 0));
            }
        }
    }
}


text:
require 'spec_helper'

RSpec.describe Ci::HasStatus do
  describe '.composite_status' do
    using RSpec::Parameterized::TableSyntax

    subject { CommitStatus.composite_status }

    shared_examples 'build status summary' do
      context 'all successful' do
        let!(:statuses) { Array.new(2) { create(type, status: :success) } }

        it { is_expected.to eq 'success' }
      end

      context 'at least one failed' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :failed)]
        end

        it { is_expected.to eq 'failed' }
      end

      context 'at least one running' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :running)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'at least one pending' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :pending)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'all waiting for resource' do
        let!(:statuses) do
          [create(type, status: :waiting_for_resource), create(type, status: :waiting_for_resource)]
        end

        it { is_expected.to eq 'waiting_for_resource' }
      end

      context 'at least one waiting for resource' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :waiting_for_resource)]
        end

        it { is_expected.to eq 'waiting_for_resource' }
      end

      context 'all preparing' do
        let!(:statuses) do
          [create(type, status: :preparing), create(type, status: :preparing)]
        end

        it { is_expected.to eq 'preparing' }
      end

      context 'at least one preparing' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :preparing)]
        end

        it { is_expected.to eq 'preparing' }
      end

      context 'success and failed but allowed to fail' do
        let!(:statuses) do
          [create(type, status: :success),
           create(type, status: :failed, allow_failure: true)]
        end

        it { is_expected.to eq 'success' }
      end

      context 'one failed but allowed to fail' do
        let!(:statuses) do
          [create(type, status: :failed, allow_failure: true)]
        end

        it { is_expected.to eq 'success' }
      end

      context 'success and canceled' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :canceled)]
        end

        it { is_expected.to eq 'canceled' }
      end

      context 'one failed and one canceled' do
        let!(:statuses) do
          [create(type, status: :failed), create(type, status: :canceled)]
        end

        it { is_expected.to eq 'failed' }
      end

      context 'one failed but allowed to fail and one canceled' do
        let!(:statuses) do
          [create(type, status: :failed, allow_failure: true),
           create(type, status: :canceled)]
        end

        it { is_expected.to eq 'canceled' }
      end

      context 'one running one canceled' do
        let!(:statuses) do
          [create(type, status: :running), create(type, status: :canceled)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'all canceled' do
        let!(:statuses) do
          [create(type, status: :canceled), create(type, status: :canceled)]
        end

        it { is_expected.to eq 'canceled' }
      end

      context 'success and canceled but allowed to fail' do
        let!(:statuses) do
          [create(type, status: :success),
           create(type, status: :canceled, allow_failure: true)]
        end

        it { is_expected.to eq 'success' }
      end

      context 'one finished and second running but allowed to fail' do
        let!(:statuses) do
          [create(type, status: :success),
           create(type, status: :running, allow_failure: true)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'when one status finished and second is still created' do
        let!(:statuses) do
          [create(type, status: :success), create(type, status: :created)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'when there is a manual status before created status' do
        let!(:statuses) do
          [create(type, status: :success),
           create(type, status: :manual, allow_failure: false),
           create(type, status: :created)]
        end

        it { is_expected.to eq 'manual' }
      end

      context 'when one status is a blocking manual action' do
        let!(:statuses) do
          [create(type, status: :failed),
           create(type, status: :manual, allow_failure: false)]
        end

        it { is_expected.to eq 'manual' }
      end

      context 'when one status is a non-blocking manual action' do
        let!(:statuses) do
          [create(type, status: :failed),
           create(type, status: :manual, allow_failure: true)]
        end

        it { is_expected.to eq 'failed' }
      end
    end

    context 'ci build statuses' do
      let(:type) { :ci_build }

      it_behaves_like 'build status summary'
    end

    context 'generic commit statuses' do
      let(:type) { :generic_commit_status }

      it_behaves_like 'build status summary'
    end
  end

  context 'for scope with one status' do
    shared_examples 'having a job' do |status|
      %i[ci_build generic_commit_status].each do |type|
        context "when it's #{status} #{type} job" do
          let!(:job) { create(type, status) }

          describe ".#{status}" do
            it 'contains the job' do
              expect(CommitStatus.public_send(status).all)
                .to contain_exactly(job)
            end
          end

          describe '.relevant' do
            if status == :created
              it 'contains nothing' do
                expect(CommitStatus.relevant.all).to be_empty
              end
            else
              it 'contains the job' do
                expect(CommitStatus.relevant.all).to contain_exactly(job)
              end
            end
          end
        end
      end
    end

    %i[created waiting_for_resource preparing running pending success
       failed canceled skipped].each do |status|
      it_behaves_like 'having a job', status
    end
  end

  context 'for scope with more statuses' do
    shared_examples 'containing the job' do |status|
      %i[ci_build generic_commit_status].each do |type|
        context "when it's #{status} #{type} job" do
          let!(:job) { create(type, status) }

          it 'contains the job' do
            is_expected.to contain_exactly(job)
          end
        end
      end
    end

    shared_examples 'not containing the job' do |status|
      %i[ci_build generic_commit_status].each do |type|
        context "when it's #{status} #{type} job" do
          let!(:job) { create(type, status) }

          it 'contains nothing' do
            is_expected.to be_empty
          end
        end
      end
    end

    describe '.running_or_pending' do
      subject { CommitStatus.running_or_pending }

      %i[running pending].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[created failed success].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.alive' do
      subject { CommitStatus.alive }

      %i[running pending waiting_for_resource preparing created].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[failed success].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.alive_or_scheduled' do
      subject { CommitStatus.alive_or_scheduled }

      %i[running pending waiting_for_resource preparing created scheduled].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[failed success canceled skipped].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.created_or_pending' do
      subject { CommitStatus.created_or_pending }

      %i[created pending].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[running failed success].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.finished' do
      subject { CommitStatus.finished }

      %i[success failed canceled].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[created running pending].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.cancelable' do
      subject { CommitStatus.cancelable }

      %i[running pending waiting_for_resource preparing created scheduled].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[failed success skipped canceled manual].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.manual' do
      subject { CommitStatus.manual }

      %i[manual].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[failed success skipped canceled].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end

    describe '.scheduled' do
      subject { CommitStatus.scheduled }

      %i[scheduled].each do |status|
        it_behaves_like 'containing the job', status
      end

      %i[failed success skipped canceled].each do |status|
        it_behaves_like 'not containing the job', status
      end
    end
  end

  describe '::DEFAULT_STATUS' do
    it 'is a status created' do
      expect(described_class::DEFAULT_STATUS).to eq 'created'
    end
  end

  describe '::BLOCKED_STATUS' do
    it 'is a status manual' do
      expect(described_class::BLOCKED_STATUS).to eq %w[manual scheduled]
    end
  end

  describe 'blocked?' do
    subject { object.blocked? }

    %w[ci_pipeline ci_stage ci_build generic_commit_status].each do |type|
      let(:object) { build(type, status: status) }

      context 'when status is scheduled' do
        let(:status) { :scheduled }

        it { is_expected.to be_truthy }
      end

      context 'when status is manual' do
        let(:status) { :manual }

        it { is_expected.to be_truthy }
      end

      context 'when status is created' do
        let(:status) { :created }

        it { is_expected.to be_falsy }
      end
    end
  end
end


text:
module.exports = ({ config }) => webpackConfig => ({
  ...webpackConfig,
  devServer: {
    clientLogLevel: 'info',
    historyApiFallback: true,
    hot: true,
    compress: true,
    host: process.env.HOST || '0.0.0.0',
    port: config.devServer.port,
    disableHostCheck: true,
    open: false,
    overlay: {
      warnings: false,
      errors: true,
    },
    proxy: config.devServer.proxyTable,
    // quiet: true,
    https: config.devServer.useHttps,
  },
});


text:
cask 'radarr' do
  version '0.2.0.1344'
  sha256 '99fb8a44f5712ce910c87c0e0a4290980edbf5584bdfc62d24ece748a4965456'

  # github.com/Radarr/Radarr was verified as official when first introduced to the cask
  url "https://github.com/Radarr/Radarr/releases/download/v#{version}/Radarr.develop.#{version}.osx-app.zip"
  appcast 'https://github.com/Radarr/Radarr/releases.atom'
  name 'Radarr'
  homepage 'https://radarr.video/'

  app 'Radarr.app'
end


text:
/* Memory mapping */
#define CONFIG_FLASH_BASE       0x08000000
#define CONFIG_FLASH_PHYSICAL_SIZE 0x0010000 /* Actually 0x8000 */
#define CONFIG_FLASH_SIZE       CONFIG_FLASH_PHYSICAL_SIZE
#define CONFIG_FLASH_BANK_SIZE  0x1000  /* TODO */
#define CONFIG_FLASH_ERASE_SIZE 0x0400  /* TODO erase bank size */
#define CONFIG_FLASH_WRITE_SIZE 0x0002  /* TODO minimum write size */

/* No page mode on STM32F, so no benefit to larger write sizes */
#define CONFIG_FLASH_WRITE_IDEAL_SIZE 0x0002

#define CONFIG_RAM_BASE         0x20000000
#define CONFIG_RAM_SIZE         0x00002800

/* Size of one firmware image in flash */
#define CONFIG_FW_IMAGE_SIZE    (32 * 1024)

#define CONFIG_FW_RO_OFF        0
#define CONFIG_FW_RO_SIZE       (CONFIG_FW_IMAGE_SIZE - CONFIG_FW_PSTATE_SIZE)
#define CONFIG_FW_RW_OFF        CONFIG_FW_IMAGE_SIZE
#define CONFIG_FW_RW_SIZE       CONFIG_FW_IMAGE_SIZE
#define CONFIG_FW_WP_RO_OFF     CONFIG_FW_RO_OFF
#define CONFIG_FW_WP_RO_SIZE    CONFIG_FW_IMAGE_SIZE

/*
 * Put pstate after RO to give RW more space and make RO write protect region
 * contiguous.
 */
#define CONFIG_FW_PSTATE_SIZE   CONFIG_FLASH_BANK_SIZE
#define CONFIG_FW_PSTATE_OFF    (CONFIG_FW_RO_OFF + CONFIG_FW_RO_SIZE)

/* Number of IRQ vectors on the NVIC */
#define CONFIG_IRQ_COUNT 59

/* Reduced history because of limited RAM */
#undef CONFIG_CONSOLE_HISTORY
#define CONFIG_CONSOLE_HISTORY 3

/* Only USART2 support */
#undef CONFIG_UART_CONSOLE
#define CONFIG_UART_CONSOLE 2

/* USB packet ram config */
#define CONFIG_USB_RAM_BASE        0x40006000
#define CONFIG_USB_RAM_SIZE        512
#define CONFIG_USB_RAM_ACCESS_TYPE uint32_t
#define CONFIG_USB_RAM_ACCESS_SIZE 4


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

using VoteSystem.Data.Entities;
using VotySystem.Data.DTO;

namespace VoteSystem.Data.Services.Contracts
{
    public interface IParticipantService
    {
        void AddRange(VoteSystemParticipantsDto voteSystemParticipants);

        void RemoveRange(IEnumerable<Participant> participants);

        void Update(Participant participant);

        Participant GetParticipantByVoteSystemIdAndVoteSystemUserId(Guid voteSystemId, Guid userId);

        IEnumerable<Participant> GetParticipantsByVoteSystemId(Guid voteSystemId);
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

input[type=button] {
  cursor: pointer;
}

/* SCROLLBOX */
#newtab-scrollbox {
  display: -moz-box;
  position: relative;
  -moz-box-flex: 1;
  -moz-user-focus: normal;
}

#newtab-scrollbox:not([page-disabled]) {
  overflow: auto;
}

/* TOGGLE */
#newtab-toggle {
  position: absolute;
  top: 12px;
  right: 12px;
}

#newtab-toggle:-moz-locale-dir(rtl) {
  left: 12px;
  right: auto;
}

/* MARGINS */
#newtab-vertical-margin {
  display: -moz-box;
  position: relative;
  -moz-box-flex: 1;
  -moz-box-orient: vertical;
}

#newtab-margin-top {
  min-height: 50px;
  max-height: 80px;
  -moz-box-flex: 1;
}

#newtab-margin-bottom {
  min-height: 40px;
  max-height: 100px;
  -moz-box-flex: 1;
}

#newtab-horizontal-margin {
  display: -moz-box;
  -moz-box-flex: 5;
}

.newtab-side-margin {
  min-width: 40px;
  max-width: 300px;
  -moz-box-flex: 1;
}

/* GRID */
#newtab-grid {
  display: -moz-box;
  -moz-box-flex: 5;
  -moz-box-orient: vertical;
  min-width: 600px;
  min-height: 400px;
  transition: 100ms ease-out;
  transition-property: opacity;
}

#newtab-grid[page-disabled] {
  opacity: 0;
}

#newtab-grid[locked],
#newtab-grid[page-disabled] {
  pointer-events: none;
}

/* ROWS */
.newtab-row {
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-direction: normal;
  -moz-box-flex: 1;
}

/* CELLS */
.newtab-cell {
  display: -moz-box;
  -moz-box-flex: 1;
}

/* SITES */
.newtab-site {
  position: relative;
  -moz-box-flex: 1;
  transition: 100ms ease-out;
  transition-property: top, left, opacity;
}

.newtab-site[frozen] {
  position: absolute;
  pointer-events: none;
}

.newtab-site[dragged] {
  transition-property: none;
  z-index: 10;
}

/* LINK + THUMBNAILS */
.newtab-link,
.newtab-thumbnail {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

.newtab-thumbnail {
  opacity: .8;
  transition: opacity 100ms ease-out;
}

.newtab-thumbnail[dragged],
.newtab-link:-moz-focusring > .newtab-thumbnail,
.newtab-site:hover > .newtab-link > .newtab-thumbnail {
  opacity: 1;
}

/* TITLES */
.newtab-title {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* CONTROLS */
.newtab-control {
  position: absolute;
  top: 4px;
  opacity: 0;
  transition: opacity 100ms ease-out;
}

.newtab-control:-moz-focusring,
.newtab-site:hover > .newtab-control {
  opacity: 1;
}

.newtab-control[dragged] {
  opacity: 0 !important;
}

@media (-moz-touch-enabled) {
  .newtab-control {
    opacity: 1;
  }
}

.newtab-control-pin:-moz-locale-dir(ltr),
.newtab-control-block:-moz-locale-dir(rtl) {
  left: 4px;
}

.newtab-control-block:-moz-locale-dir(ltr),
.newtab-control-pin:-moz-locale-dir(rtl) {
  right: 4px;
}

/* DRAG & DROP */

/*
 * This is just a temporary drag element used for dataTransfer.setDragImage()
 * so that we can use custom drag images and elements. It needs an opacity of
 * 0.01 so that the core code detects that it's in fact a visible element.
 */
.newtab-drag {
  width: 1px;
  height: 1px;
  background-color: #fff;
  opacity: 0.01;
}


text:
<?php

class #{Class} extends Misago\ActiveRecord\Base
{

}

?>