text:
package io.buoyant.router

import com.twitter.finagle.{Stack, Stackable, Service, ServiceFactory, SimpleFilter, param, Path}
import com.twitter.finagle.tracing.{Trace, Tracer}
import com.twitter.finagle.service.{ReqRep, ResponseClass, ResponseClassifier}
import com.twitter.util.{Duration, Future}
import io.buoyant.router.context.ResponseClassifierCtx

object ClassifiedTracing {
  val role = Stack.Role("ClassifiedTracing")

  /**
   * Traces response classifications as one of the following:
   * - l5d.success
   * - l5d.retryable
   * - l5d.failure
   */
  private class Filter[Req, Rsp](classifier: ResponseClassifier) extends SimpleFilter[Req, Rsp] {
    def apply(req: Req, service: Service[Req, Rsp]): Future[Rsp] = {
      val f = service(req)
      if (!Trace.isActivelyTracing) f
      else f.respond { rsp =>
        classifier.applyOrElse(ReqRep(req, rsp), ResponseClassifier.Default) match {
          case ResponseClass.Ignorable =>
          case ResponseClass.Successful(fraction) =>
            Trace.recordBinary("l5d.success", fraction)
          case ResponseClass.Failed(retryable) =>
            if (retryable) Trace.record("l5d.retryable")
            else Trace.record("l5d.failure")
        }
      }
    }
  }

  /**
   * A stack module that, if a tracer is enabled, annotates traces
   * based on response classifications.
   */
  def module[Req, Rsp]: Stackable[ServiceFactory[Req, Rsp]] =
    new Stack.Module1[param.Tracer, ServiceFactory[Req, Rsp]] {
      val role = ClassifiedTracing.role
      val description = "Traces response classification annotations"
      def make(
        _tracer: param.Tracer,
        next: ServiceFactory[Req, Rsp]
      ): ServiceFactory[Req, Rsp] = {
        val param.Tracer(tracer) = _tracer
        if (tracer.isNull) next
        else {

          // We memoize on the dst path.  The assumes that the response classifier for a dst path
          // never changes.
          def mkClassifiedTracingFilter(path: Path) = {
            val param.ResponseClassifier(classifier) =
              ResponseClassifierCtx.current.getOrElse(param.ResponseClassifier.param.default)
            new Filter[Req, Rsp](classifier)
          }

          val filter = new PerDstPathFilter(mkClassifiedTracingFilter _)
          filter.andThen(next)
        }
      }
    }
}


text:
/*global runtime, gui, ops, odf, core*/

/**
 * Provides a method to paste text at the current cursor
 * position, and processes the input string to understand
 * special structuring such as paragraph splits.
 * @implements {core.Destroyable}
 * @param {!ops.Session} session
 * @param {!gui.SessionConstraints} sessionConstraints
 * @param {!gui.SessionContext} sessionContext
 * @param {!string} inputMemberId
 * @constructor
 */
gui.PasteController = function PasteController(session, sessionConstraints, sessionContext, inputMemberId) {
    "use strict";

    var odtDocument = session.getOdtDocument(),
        isEnabled = false,
        /**@const*/
        textns = odf.Namespaces.textns,
        /**@const*/
        NEXT = core.StepDirection.NEXT,
        odfUtils = odf.OdfUtils;

    /**
     * @return {undefined}
     */
    function updateEnabledState() {
        if (sessionConstraints.getState(gui.CommonConstraints.EDIT.REVIEW_MODE) === true) {
            isEnabled = /**@type{!boolean}*/(sessionContext.isLocalCursorWithinOwnAnnotation());
        } else {
            isEnabled = true;
        }
    }

    /**
     * @param {!ops.OdtCursor} cursor
     * @return {undefined}
     */
    function onCursorEvent(cursor) {
        if (cursor.getMemberId() === inputMemberId) {
            updateEnabledState();
        }
    }

    /**
     * @return {!boolean}
     */
    this.isEnabled = function () {
        return isEnabled;
    };

    /**
     * @param {!string} data
     * @return {undefined}
     */
    this.paste = function (data) {
        if (!isEnabled) {
            return;
        }

        var originalCursorPosition = odtDocument.getCursorPosition(inputMemberId),
            cursorNode = odtDocument.getCursor(inputMemberId).getNode(),
            originalParagraph = /**@type{!Element}*/(odfUtils.getParagraphElement(cursorNode)),
            paragraphStyle = originalParagraph.getAttributeNS(textns, "style-name") || "",
            /**@type{number}*/
            cursorPosition = originalCursorPosition,
            operations = [],
            currentParagraphStartPosition = odtDocument.convertDomPointToCursorStep(originalParagraph, 0, NEXT),
            paragraphs;

        paragraphs = data.replace(/\r/g, "").split("\n");
        paragraphs.forEach(function (text) {
            var insertTextOp = new ops.OpInsertText(),
                splitParagraphOp = new ops.OpSplitParagraph();

            insertTextOp.init({
                memberid: inputMemberId,
                position: cursorPosition,
                text: text,
                moveCursor: true
            });
            operations.push(insertTextOp);
            cursorPosition += text.length;

            splitParagraphOp.init({
                memberid: inputMemberId,
                position: cursorPosition,
                paragraphStyleName: paragraphStyle,
                sourceParagraphPosition: currentParagraphStartPosition,
                moveCursor: true
            });
            operations.push(splitParagraphOp);
            cursorPosition += 1; // Splitting a paragraph introduces 1 walkable position, bumping the cursor forward
            currentParagraphStartPosition = cursorPosition; // Reset the source paragraph to the newly created one
        });

        // Discard the last split paragraph op as unnecessary.
        // Reasoning through the scenarios, this produces the most intuitive behaviour:
        // 1. Paste a single line - No line split should be added
        // 2. Paste two lines - Only one paragraph split is necessary per new paragraph. As pasting MUST occur within an
        //                      existing paragraph, only a single split should occur.
        operations.pop();

        session.enqueue(operations);
    };

    /**
     * @param {!function(!Error=)} callback, passing an error object in case of error
     * @return {undefined}
     */
    this.destroy = function (callback) {
        odtDocument.unsubscribe(ops.Document.signalCursorMoved, onCursorEvent);
        sessionConstraints.unsubscribe(gui.CommonConstraints.EDIT.REVIEW_MODE, updateEnabledState);
        callback();
    };

    function init() {
        odtDocument.subscribe(ops.Document.signalCursorMoved, onCursorEvent);
        sessionConstraints.subscribe(gui.CommonConstraints.EDIT.REVIEW_MODE, updateEnabledState);
        updateEnabledState();
    }
    init();
};

redpajama_set_name: RedPajamaGithub


text:
using System.Data.Common;
using Microsoft.EntityFrameworkCore;

namespace PatientManagement.Reservation.EntityFrameworkCore
{
    public static class ReservationDbContextConfigurer
    {
        public static void Configure(DbContextOptionsBuilder<ReservationDbContext> builder, string connectionString)
        {
            builder.UseSqlServer(connectionString);
        }

        public static void Configure(DbContextOptionsBuilder<ReservationDbContext> builder, DbConnection connection)
        {
            builder.UseSqlServer(connection);
        }
    }
}


text:
import { gettext } from '@waldur/i18n';

export const helpData = {
  type: 'providers',
  key: 'Azure',
  name: gettext('Azure provider'),
  title: gettext('How to obtain credentials for Azure provider'),
};


text:
__TIB_DEFINITION_java_nio_CharArrayBuffer __TIB_java_nio_CharArrayBuffer = {
    0, // classInitializationBegan
    0, // classInitialized
    -1, // initializerThreadId
    __INIT_java_nio_CharArrayBuffer, // classInitializer
    "java.nio.CharArrayBuffer", // className
    "java.nio", // package
    JAVA_NULL, // enclosingClassName
    JAVA_NULL, // enclosingMethodName
    JAVA_NULL, // signature
    (__TIB_DEFINITION_TEMPLATE*) &__TIB_java_nio_CharBuffer, // extends
    sizeof(java_nio_CharArrayBuffer), // sizeInstance
    XMLVM_TYPE_CLASS};

JAVA_OBJECT __CLASS_java_nio_CharArrayBuffer;
JAVA_OBJECT __CLASS_java_nio_CharArrayBuffer_1ARRAY;
JAVA_OBJECT __CLASS_java_nio_CharArrayBuffer_2ARRAY;
JAVA_OBJECT __CLASS_java_nio_CharArrayBuffer_3ARRAY;
//XMLVM_BEGIN_IMPLEMENTATION
//XMLVM_END_IMPLEMENTATION

#include "xmlvm-reflection.h"

static XMLVM_FIELD_REFLECTION_DATA __field_reflection_data[] = {
};

static XMLVM_CONSTRUCTOR_REFLECTION_DATA __constructor_reflection_data[] = {
};

static JAVA_OBJECT constructor_dispatcher(JAVA_OBJECT constructor, JAVA_OBJECT arguments)
{
    XMLVM_NOT_IMPLEMENTED();
}

static XMLVM_METHOD_REFLECTION_DATA __method_reflection_data[] = {
};

static JAVA_OBJECT method_dispatcher(JAVA_OBJECT method, JAVA_OBJECT receiver, JAVA_OBJECT arguments)
{
    XMLVM_NOT_IMPLEMENTED();
}

void __INIT_java_nio_CharArrayBuffer()
{
    staticInitializerLock(&__TIB_java_nio_CharArrayBuffer);

    // While the static initializer mutex is locked, locally store the value of
    // whether class initialization began or not
    int initBegan = __TIB_java_nio_CharArrayBuffer.classInitializationBegan;

    // Whether or not class initialization had already began, it has begun now
    __TIB_java_nio_CharArrayBuffer.classInitializationBegan = 1;

    staticInitializerUnlock(&__TIB_java_nio_CharArrayBuffer);

    JAVA_LONG curThreadId = (JAVA_LONG)pthread_self();
    if (initBegan) {
        if (__TIB_java_nio_CharArrayBuffer.initializerThreadId != curThreadId) {
            // Busy wait until the other thread finishes initializing this class
            while (!__TIB_java_nio_CharArrayBuffer.classInitialized) {
                // do nothing
            }
        }
    } else {
        __TIB_java_nio_CharArrayBuffer.initializerThreadId = curThreadId;
        XMLVM_CLASS_USED("java.nio.CharArrayBuffer")
        __INIT_IMPL_java_nio_CharArrayBuffer();
    }
}

void __INIT_IMPL_java_nio_CharArrayBuffer()
{
    // Initialize base class if necessary
    XMLVM_CLASS_INIT(java_nio_CharBuffer)
    __TIB_java_nio_CharArrayBuffer.newInstanceFunc = __NEW_INSTANCE_java_nio_CharArrayBuffer;
    // Copy vtable from base class
    XMLVM_MEMCPY(__TIB_java_nio_CharArrayBuffer.vtable, __TIB_java_nio_CharBuffer.vtable, sizeof(__TIB_java_nio_CharBuffer.vtable));
    // Initialize vtable for this class
    __TIB_java_nio_CharArrayBuffer.vtable[19] = (VTABLE_PTR) &java_nio_CharArrayBuffer_get__;
    __TIB_java_nio_CharArrayBuffer.vtable[21] = (VTABLE_PTR) &java_nio_CharArrayBuffer_get___int;
    __TIB_java_nio_CharArrayBuffer.vtable[20] = (VTABLE_PTR) &java_nio_CharArrayBuffer_get___char_1ARRAY_int_int;
    __TIB_java_nio_CharArrayBuffer.vtable[9] = (VTABLE_PTR) &java_nio_CharArrayBuffer_isDirect__;
    __TIB_java_nio_CharArrayBuffer.vtable[23] = (VTABLE_PTR) &java_nio_CharArrayBuffer_order__;
    __TIB_java_nio_CharArrayBuffer.vtable[32] = (VTABLE_PTR) &java_nio_CharArrayBuffer_subSequence___int_int;
    __TIB_java_nio_CharArrayBuffer.vtable[5] = (VTABLE_PTR) &java_nio_CharArrayBuffer_toString__;
    // Initialize interface information
    __TIB_java_nio_CharArrayBuffer.numImplementedInterfaces = 4;
    __TIB_java_nio_CharArrayBuffer.implementedInterfaces = (__TIB_DEFINITION_TEMPLATE* (*)[1]) XMLVM_MALLOC(sizeof(__TIB_DEFINITION_TEMPLATE*) * 4);

    // Initialize interfaces if necessary and assign tib to implementedInterfaces

    XMLVM_CLASS_INIT(java_lang_Appendable)

    __TIB_java_nio_CharArrayBuffer.implementedInterfaces[0][0] = &__TIB_java_lang_Appendable;

    XMLVM_CLASS_INIT(java_lang_CharSequence)

    __TIB_java_nio_CharArrayBuffer.implementedInterfaces[0][1] = &__TIB_java_lang_CharSequence;

    XMLVM_CLASS_INIT(java_lang_Comparable)

    __TIB_java_nio_CharArrayBuffer.implementedInterfaces[0][2] = &__TIB_java_lang_Comparable;

    XMLVM_CLASS_INIT(java_lang_Readable)

    __TIB_java_nio_CharArrayBuffer.implementedInterfaces[0][3] = &__TIB_java_lang_Readable;
    // Initialize itable for this class
    __TIB_java_nio_CharArrayBuffer.itableBegin = &__TIB_java_nio_CharArrayBuffer.itable[0];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_Appendable_append___char] = __TIB_java_nio_CharArrayBuffer.vtable[11];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_Appendable_append___java_lang_CharSequence] = __TIB_java_nio_CharArrayBuffer.vtable[12];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_Appendable_append___java_lang_CharSequence_int_int] = __TIB_java_nio_CharArrayBuffer.vtable[13];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_CharSequence_charAt___int] = __TIB_java_nio_CharArrayBuffer.vtable[15];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_CharSequence_length__] = __TIB_java_nio_CharArrayBuffer.vtable[22];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_CharSequence_subSequence___int_int] = __TIB_java_nio_CharArrayBuffer.vtable[32];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_CharSequence_toString__] = __TIB_java_nio_CharArrayBuffer.vtable[5];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_Comparable_compareTo___java_lang_Object] = __TIB_java_nio_CharArrayBuffer.vtable[17];
    __TIB_java_nio_CharArrayBuffer.itable[XMLVM_ITABLE_IDX_java_lang_Readable_read___java_nio_CharBuffer] = __TIB_java_nio_CharArrayBuffer.vtable[30];

    __TIB_java_nio_CharArrayBuffer.declaredFields = &__field_reflection_data[0];
    __TIB_java_nio_CharArrayBuffer.numDeclaredFields = sizeof(__field_reflection_data) / sizeof(XMLVM_FIELD_REFLECTION_DATA);
    __TIB_java_nio_CharArrayBuffer.constructorDispatcherFunc = constructor_dispatcher;
    __TIB_java_nio_CharArrayBuffer.declaredConstructors = &__constructor_reflection_data[0];
    __TIB_java_nio_CharArrayBuffer.numDeclaredConstructors = sizeof(__constructor_reflection_data) / sizeof(XMLVM_CONSTRUCTOR_REFLECTION_DATA);
    __TIB_java_nio_CharArrayBuffer.methodDispatcherFunc = method_dispatcher;
    __TIB_java_nio_CharArrayBuffer.declaredMethods = &__method_reflection_data[0];
    __TIB_java_nio_CharArrayBuffer.numDeclaredMethods = sizeof(__method_reflection_data) / sizeof(XMLVM_METHOD_REFLECTION_DATA);
    __CLASS_java_nio_CharArrayBuffer = XMLVM_CREATE_CLASS_OBJECT(&__TIB_java_nio_CharArrayBuffer);
    __TIB_java_nio_CharArrayBuffer.clazz = __CLASS_java_nio_CharArrayBuffer;
    __TIB_java_nio_CharArrayBuffer.baseType = JAVA_NULL;
    __CLASS_java_nio_CharArrayBuffer_1ARRAY = XMLVM_CREATE_ARRAY_CLASS_OBJECT(__CLASS_java_nio_CharArrayBuffer);
    __CLASS_java_nio_CharArrayBuffer_2ARRAY = XMLVM_CREATE_ARRAY_CLASS_OBJECT(__CLASS_java_nio_CharArrayBuffer_1ARRAY);
    __CLASS_java_nio_CharArrayBuffer_3ARRAY = XMLVM_CREATE_ARRAY_CLASS_OBJECT(__CLASS_java_nio_CharArrayBuffer_2ARRAY);
    //XMLVM_BEGIN_WRAPPER[__INIT_java_nio_CharArrayBuffer]
    //XMLVM_END_WRAPPER

    __TIB_java_nio_CharArrayBuffer.classInitialized = 1;
}

void __DELETE_java_nio_CharArrayBuffer(void* me, void* client_data)
{
    //XMLVM_BEGIN_WRAPPER[__DELETE_java_nio_CharArrayBuffer]
    //XMLVM_END_WRAPPER
}

void __INIT_INSTANCE_MEMBERS_java_nio_CharArrayBuffer(JAVA_OBJECT me, int derivedClassWillRegisterFinalizer)
{
    __INIT_INSTANCE_MEMBERS_java_nio_CharBuffer(me, 0 || derivedClassWillRegisterFinalizer);
    ((java_nio_CharArrayBuffer*) me)->fields.java_nio_CharArrayBuffer.backingArray_ = (org_xmlvm_runtime_XMLVMArray*) JAVA_NULL;
    ((java_nio_CharArrayBuffer*) me)->fields.java_nio_CharArrayBuffer.offset_ = 0;
    //XMLVM_BEGIN_WRAPPER[__INIT_INSTANCE_MEMBERS_java_nio_CharArrayBuffer]
    //XMLVM_END_WRAPPER
}

JAVA_OBJECT __NEW_java_nio_CharArrayBuffer()
{    XMLVM_CLASS_INIT(java_nio_CharArrayBuffer)
java_nio_CharArrayBuffer* me = (java_nio_CharArrayBuffer*) XMLVM_MALLOC(sizeof(java_nio_CharArrayBuffer));
    me->tib = &__TIB_java_nio_CharArrayBuffer;
    __INIT_INSTANCE_MEMBERS_java_nio_CharArrayBuffer(me, 0);
    //XMLVM_BEGIN_WRAPPER[__NEW_java_nio_CharArrayBuffer]
    //XMLVM_END_WRAPPER
    return me;
}

JAVA_OBJECT __NEW_INSTANCE_java_nio_CharArrayBuffer()
{
    JAVA_OBJECT me = JAVA_NULL;
    return me;
}

void java_nio_CharArrayBuffer___INIT____char_1ARRAY(JAVA_OBJECT me, JAVA_OBJECT n1)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer___INIT____char_1ARRAY]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "<init>", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    _r2.o = me;
    _r3.o = n1;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 39)
    _r0.i = XMLVMArray_count(((org_xmlvm_runtime_XMLVMArray*) _r3.o));
    _r1.i = 0;
    XMLVM_CHECK_NPE(2)
    java_nio_CharArrayBuffer___INIT____int_char_1ARRAY_int(_r2.o, _r0.i, _r3.o, _r1.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 40)
    XMLVM_EXIT_METHOD()
    return;
    //XMLVM_END_WRAPPER
}

void java_nio_CharArrayBuffer___INIT____int(JAVA_OBJECT me, JAVA_INT n1)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer___INIT____int]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "<init>", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    _r2.o = me;
    _r3.i = n1;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 43)
    XMLVM_CLASS_INIT(char)
    _r0.o = XMLVMArray_createSingleDimension(__CLASS_char, _r3.i);
    _r1.i = 0;
    XMLVM_CHECK_NPE(2)
    java_nio_CharArrayBuffer___INIT____int_char_1ARRAY_int(_r2.o, _r3.i, _r0.o, _r1.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 44)
    XMLVM_EXIT_METHOD()
    return;
    //XMLVM_END_WRAPPER
}

void java_nio_CharArrayBuffer___INIT____int_char_1ARRAY_int(JAVA_OBJECT me, JAVA_INT n1, JAVA_OBJECT n2, JAVA_INT n3)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer___INIT____int_char_1ARRAY_int]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "<init>", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    _r0.o = me;
    _r1.i = n1;
    _r2.o = n2;
    _r3.i = n3;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 47)
    XMLVM_CHECK_NPE(0)
    java_nio_CharBuffer___INIT____int(_r0.o, _r1.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 48)
    XMLVM_CHECK_NPE(0)
    ((java_nio_CharArrayBuffer*) _r0.o)->fields.java_nio_CharArrayBuffer.backingArray_ = _r2.o;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 49)
    XMLVM_CHECK_NPE(0)
    ((java_nio_CharArrayBuffer*) _r0.o)->fields.java_nio_CharArrayBuffer.offset_ = _r3.i;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 50)
    XMLVM_EXIT_METHOD()
    return;
    //XMLVM_END_WRAPPER
}

JAVA_CHAR java_nio_CharArrayBuffer_get__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_get__]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "get", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    XMLVMElem _r4;
    _r4.o = me;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 54)
    XMLVM_CHECK_NPE(4)
    _r0.i = ((java_nio_Buffer*) _r4.o)->fields.java_nio_Buffer.position_;
    XMLVM_CHECK_NPE(4)
    _r1.i = ((java_nio_Buffer*) _r4.o)->fields.java_nio_Buffer.limit_;
    if (_r0.i != _r1.i) goto label12;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 55)

    // Red class access removed: java.nio.BufferUnderflowException::new-instance
    XMLVM_RED_CLASS_DEPENDENCY();

    // Red class access removed: java.nio.BufferUnderflowException::<init>
    XMLVM_RED_CLASS_DEPENDENCY();
    XMLVM_THROW_CUSTOM(_r0.o)
    label12:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 57)
    XMLVM_CHECK_NPE(4)
    _r0.o = ((java_nio_CharArrayBuffer*) _r4.o)->fields.java_nio_CharArrayBuffer.backingArray_;
    XMLVM_CHECK_NPE(4)
    _r1.i = ((java_nio_CharArrayBuffer*) _r4.o)->fields.java_nio_CharArrayBuffer.offset_;
    XMLVM_CHECK_NPE(4)
    _r2.i = ((java_nio_Buffer*) _r4.o)->fields.java_nio_Buffer.position_;
    _r3.i = _r2.i + 1;
    XMLVM_CHECK_NPE(4)
    ((java_nio_Buffer*) _r4.o)->fields.java_nio_Buffer.position_ = _r3.i;
    _r1.i = _r1.i + _r2.i;
    XMLVM_CHECK_NPE(0)
    XMLVM_CHECK_ARRAY_BOUNDS(_r0.o, _r1.i);
    _r0.i = ((JAVA_ARRAY_CHAR*) (((org_xmlvm_runtime_XMLVMArray*) _r0.o)->fields.org_xmlvm_runtime_XMLVMArray.array_))[_r1.i];
    XMLVM_EXIT_METHOD()
    return _r0.i;
    //XMLVM_END_WRAPPER
}

JAVA_CHAR java_nio_CharArrayBuffer_get___int(JAVA_OBJECT me, JAVA_INT n1)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_get___int]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "get", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    _r2.o = me;
    _r3.i = n1;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 62)
    if (_r3.i < 0) goto label6;
    XMLVM_CHECK_NPE(2)
    _r0.i = ((java_nio_Buffer*) _r2.o)->fields.java_nio_Buffer.limit_;
    if (_r3.i < _r0.i) goto label12;
    label6:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 63)
    _r0.o = __NEW_java_lang_IndexOutOfBoundsException();
    XMLVM_CHECK_NPE(0)
    java_lang_IndexOutOfBoundsException___INIT___(_r0.o);
    XMLVM_THROW_CUSTOM(_r0.o)
    label12:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 65)
    XMLVM_CHECK_NPE(2)
    _r0.o = ((java_nio_CharArrayBuffer*) _r2.o)->fields.java_nio_CharArrayBuffer.backingArray_;
    XMLVM_CHECK_NPE(2)
    _r1.i = ((java_nio_CharArrayBuffer*) _r2.o)->fields.java_nio_CharArrayBuffer.offset_;
    _r1.i = _r1.i + _r3.i;
    XMLVM_CHECK_NPE(0)
    XMLVM_CHECK_ARRAY_BOUNDS(_r0.o, _r1.i);
    _r0.i = ((JAVA_ARRAY_CHAR*) (((org_xmlvm_runtime_XMLVMArray*) _r0.o)->fields.org_xmlvm_runtime_XMLVMArray.array_))[_r1.i];
    XMLVM_EXIT_METHOD()
    return _r0.i;
    //XMLVM_END_WRAPPER
}

JAVA_OBJECT java_nio_CharArrayBuffer_get___char_1ARRAY_int_int(JAVA_OBJECT me, JAVA_OBJECT n1, JAVA_INT n2, JAVA_INT n3)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_get___char_1ARRAY_int_int]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "get", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    XMLVMElem _r4;
    XMLVMElem _r5;
    XMLVMElem _r6;
    XMLVMElem _r7;
    XMLVMElem _r8;
    _r5.o = me;
    _r6.o = n1;
    _r7.i = n2;
    _r8.i = n3;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 70)
    _r0.i = XMLVMArray_count(((org_xmlvm_runtime_XMLVMArray*) _r6.o));
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 71)
    if (_r7.i < 0) goto label13;
    if (_r8.i < 0) goto label13;
    _r1.l = (JAVA_LONG) _r7.i;
    _r3.l = (JAVA_LONG) _r8.i;
    _r1.l = _r1.l + _r3.l;
    _r3.l = (JAVA_LONG) _r0.i;
    _r0.i = _r1.l > _r3.l ? 1 : (_r1.l == _r3.l ? 0 : -1);
    if (_r0.i <= 0) goto label19;
    label13:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 72)
    _r0.o = __NEW_java_lang_IndexOutOfBoundsException();
    XMLVM_CHECK_NPE(0)
    java_lang_IndexOutOfBoundsException___INIT___(_r0.o);
    XMLVM_THROW_CUSTOM(_r0.o)
    label19:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 74)
    XMLVM_CHECK_NPE(5)
    _r0.i = java_nio_Buffer_remaining__(_r5.o);
    if (_r8.i <= _r0.i) goto label31;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 75)

    // Red class access removed: java.nio.BufferUnderflowException::new-instance
    XMLVM_RED_CLASS_DEPENDENCY();

    // Red class access removed: java.nio.BufferUnderflowException::<init>
    XMLVM_RED_CLASS_DEPENDENCY();
    XMLVM_THROW_CUSTOM(_r0.o)
    label31:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 77)
    XMLVM_CHECK_NPE(5)
    _r0.o = ((java_nio_CharArrayBuffer*) _r5.o)->fields.java_nio_CharArrayBuffer.backingArray_;
    XMLVM_CHECK_NPE(5)
    _r1.i = ((java_nio_CharArrayBuffer*) _r5.o)->fields.java_nio_CharArrayBuffer.offset_;
    XMLVM_CHECK_NPE(5)
    _r2.i = ((java_nio_Buffer*) _r5.o)->fields.java_nio_Buffer.position_;
    _r1.i = _r1.i + _r2.i;
    java_lang_System_arraycopy___java_lang_Object_int_java_lang_Object_int_int(_r0.o, _r1.i, _r6.o, _r7.i, _r8.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 78)
    XMLVM_CHECK_NPE(5)
    _r0.i = ((java_nio_Buffer*) _r5.o)->fields.java_nio_Buffer.position_;
    _r0.i = _r0.i + _r8.i;
    XMLVM_CHECK_NPE(5)
    ((java_nio_Buffer*) _r5.o)->fields.java_nio_Buffer.position_ = _r0.i;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 79)
    XMLVM_EXIT_METHOD()
    return _r5.o;
    //XMLVM_END_WRAPPER
}

JAVA_BOOLEAN java_nio_CharArrayBuffer_isDirect__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_isDirect__]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "isDirect", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    _r1.o = me;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 84)
    _r0.i = 0;
    XMLVM_EXIT_METHOD()
    return _r0.i;
    //XMLVM_END_WRAPPER
}

JAVA_OBJECT java_nio_CharArrayBuffer_order__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_order__]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "order", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    _r1.o = me;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 89)

    // Red class access removed: java.nio.ByteOrder::nativeOrder
    XMLVM_RED_CLASS_DEPENDENCY();
    XMLVM_EXIT_METHOD()
    return _r0.o;
    //XMLVM_END_WRAPPER
}

JAVA_OBJECT java_nio_CharArrayBuffer_subSequence___int_int(JAVA_OBJECT me, JAVA_INT n1, JAVA_INT n2)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_subSequence___int_int]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "subSequence", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    XMLVMElem _r4;
    _r2.o = me;
    _r3.i = n1;
    _r4.i = n2;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 94)
    if (_r3.i < 0) goto label10;
    if (_r4.i < _r3.i) goto label10;
    XMLVM_CHECK_NPE(2)
    _r0.i = java_nio_Buffer_remaining__(_r2.o);
    if (_r4.i <= _r0.i) goto label16;
    label10:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 95)
    _r0.o = __NEW_java_lang_IndexOutOfBoundsException();
    XMLVM_CHECK_NPE(0)
    java_lang_IndexOutOfBoundsException___INIT___(_r0.o);
    XMLVM_THROW_CUSTOM(_r0.o)
    label16:;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 98)
    //java_nio_CharArrayBuffer_duplicate__[18]
    XMLVM_CHECK_NPE(2)
    _r0.o = (*(JAVA_OBJECT (*)(JAVA_OBJECT)) ((java_nio_CharArrayBuffer*) _r2.o)->tib->vtable[18])(_r2.o);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 99)
    XMLVM_CHECK_NPE(2)
    _r1.i = ((java_nio_Buffer*) _r2.o)->fields.java_nio_Buffer.position_;
    _r1.i = _r1.i + _r4.i;
    XMLVM_CHECK_NPE(0)
    java_nio_Buffer_limit___int(_r0.o, _r1.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 100)
    XMLVM_CHECK_NPE(2)
    _r1.i = ((java_nio_Buffer*) _r2.o)->fields.java_nio_Buffer.position_;
    _r1.i = _r1.i + _r3.i;
    XMLVM_CHECK_NPE(0)
    java_nio_Buffer_position___int(_r0.o, _r1.i);
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 101)
    XMLVM_EXIT_METHOD()
    return _r0.o;
    //XMLVM_END_WRAPPER
}

JAVA_OBJECT java_nio_CharArrayBuffer_toString__(JAVA_OBJECT me)
{
    //XMLVM_BEGIN_WRAPPER[java_nio_CharArrayBuffer_toString__]
    XMLVM_ENTER_METHOD("java.nio.CharArrayBuffer", "toString", "?")
    XMLVMElem _r0;
    XMLVMElem _r1;
    XMLVMElem _r2;
    XMLVMElem _r3;
    _r3.o = me;
    XMLVM_SOURCE_POSITION("CharArrayBuffer.java", 106)
    XMLVM_CHECK_NPE(3)
    _r0.o = ((java_nio_CharArrayBuffer*) _r3.o)->fields.java_nio_CharArrayBuffer.backingArray_;
    XMLVM_CHECK_NPE(3)
    _r1.i = ((java_nio_CharArrayBuffer*) _r3.o)->fields.java_nio_CharArrayBuffer.offset_;
    XMLVM_CHECK_NPE(3)
    _r2.i = ((java_nio_Buffer*) _r3.o)->fields.java_nio_Buffer.position_;
    _r1.i = _r1.i + _r2.i;
    XMLVM_CHECK_NPE(3)
    _r2.i = java_nio_Buffer_remaining__(_r3.o);
    _r0.o = java_lang_String_copyValueOf___char_1ARRAY_int_int(_r0.o, _r1.i, _r2.i);
    XMLVM_EXIT_METHOD()
    return _r0.o;
    //XMLVM_END_WRAPPER
}


text:
using namespace boost::hana;

template <typename T>
using void_t = std::conditional_t<true, void, T>;

// sample(common_type-now)
template <typename ...>
auto common_type_impl = nothing;

template <typename T1, typename ...Tn>
auto common_type_impl<T1, Tn...> = monadic_fold<Maybe>(
  tuple_t<Tn...>, type<std::decay_t<T1>>,
  sfinae([](auto t, auto u) -> decltype(
    traits::decay(true ? traits::declval(t) : traits::declval(u))
  ) { return {}; })
);

template <typename ...T>
struct common_type : decltype(common_type_impl<T...>) { };
// end-sample

template <typename ...Ts>
using common_type_t = typename common_type<Ts...>::type;

//////////////////////////////////////////////////////////////////////////////
// Tests
//////////////////////////////////////////////////////////////////////////////
template <typename T, typename = void>
struct has_type : std::false_type { };

template <typename T>
struct has_type<T, void_t<typename T::type>> : std::true_type { };

struct A { }; struct B { }; struct C { };

// Ensure proper behavior in normal cases
static_assert(std::is_same<
    common_type_t<char>,
    char
>{}, "");

static_assert(std::is_same<
    common_type_t<A, A>,
    A
>{}, "");

static_assert(std::is_same<
    common_type_t<char, short, char, short>,
    int
>{}, "");

static_assert(std::is_same<
    common_type_t<char, double, short, char, short, double>,
    double
>{}, "");

static_assert(std::is_same<
    common_type_t<char, short, float, short>,
    float
>{}, "");

// Ensure SFINAE-friendliness
static_assert(!has_type<common_type<>>{}, "");
static_assert(!has_type<common_type<int, void>>{}, "");

int main() { }


text:
namespace content {

ListValue* GetFontList_SlowBlocking() {
  return new ListValue;
}

}  // namespace content


text:
'use strict';

angular.module('ui.widgets')
	.controller('RemovePatientCtrl', ['$scope', '$modalInstance', 'params',
        function($scope, $modalInstance, params) {
        	$scope.name = params.veteranObj.Name;
        	$scope.ok = function(){
        		$modalInstance.dismiss('cancel');
        	}

        	$scope.cancel = function(){
        		$modalInstance.dismiss('cancel');
        	}
        }
]);


text:
/*
*RestFavicon.js 是自动响应浏览器favicon.ico请求的模块
*
*exports fn(res, path)
*/
var fs = require('fs'),
    RestUtils = require('./RestUtils'),
	msg =  require('./msg/msg'),
    icon ={//icon对象
		DefaultPath:_restConfig.baseDir+_restConfig.favicon,
		maxAge : _restConfig.staticMaxAge,
		faviconUrl: _restConfig.favicon,
		icon : false,
	};

icon.SendFavicon = module.exports = function favicon(res, path){//输出favicon
	 var path = path || icon.DefaultPath;
     if(icon.icon)  return icon.Response(true, res); //如果有缓存,则输出缓存
 	 fs.readFile(path, function(err, buf){ //没有则去读取文件
		  if(err)  return RestUtils.errorRes(res, msg.resmsg.faviconError); //出错响应500
		  icon.Response(false, res, buf); //无缓存响应
	 });
	 return false;
  };
 icon.Response = function(iscache, res, buf){//响应favicon方法
			if(!iscache){//如果未缓存
				  icon.icon = { //设置头信息
					headers: {
					   'Content-Type': 'image/x-icon',
					   'Content-Length': buf.length,
					   'ETag': '"' + RestUtils.md5(buf) + '"',
					   'Cache-Control': 'public, max-age=' + (icon.maxAge / 1000)
					},
					body: buf
				  };
			}
			res.writeHead(200, icon.icon.headers);
			res.end(icon.icon.body);
			return true;
 }


text:
package com.dhbw.dhbw2017.programming.oo;

import com.dhbw.dhbw2017.programming.bank.v2.Bank;

/**
 * Created by flori on 22.03.2017.
 */
public class GetterSetter {

    public static void main(String[]args){
        Bank bank = new Bank("BA Bank");

        bank.setName("DHBW Bank");
    }
}


text:
UUID=atom-dock\@ozonos.org
INSTALLDIR=~/.local/share/gnome-shell/extensions/$(UUID)

all:

install: local

local:
	#Create dir if not exist
	mkdir -p $(INSTALLDIR)

	#Clear dir from contents
	-rm -rf $(INSTALLDIR)/*

	#Copy new contents in
	cp -rf . $(INSTALLDIR)

uninstall:
	#Uninstall atom-dock
	-rm -rf $(INSTALLDIR)


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>feed.link [Universal Feed Parser]</title>
<link rel="stylesheet" href="feedparser.css" type="text/css">
<link rev="made" href="mailto:mark@diveintomark.org">
<meta name="generator" content="DocBook XSL Stylesheets V1.65.1">
<meta name="keywords" content="RSS, Atom, CDF, XML, feed, parser, Python">
<link rel="start" href="index.html" title="Documentation">
<link rel="up" href="reference.html" title="Reference">
<link rel="prev" href="reference-feed-title_detail.html" title="feed.title_detail">
<link rel="next" href="reference-feed-links.html" title="feed.links">

Universal Feed Parser

Parse RSS and Atom feeds in Python.  3000 unit tests.  Open source.

Download ·

Documentation ·

Unit tests ·

Report a bug

You are here: Documentation → Reference → feed.link

 feed.link

The <acronym title="Uniform Resource Locator">URL</acronym> of the <acronym title="HyperText Markup Language">HTML</acronym> page associated with this feed.

For site feeds, this is probably the home page of the site.  For category feeds, this is probably the category's archive page.  For search feeds, this is probably the web page that displays the search results for the given search parameters.

If this is a relative <acronym title="Uniform Resource Identifier">URI</acronym>, it is resolved according to a set of rules.

Comes from

<tt class="literal">/atom10:feed/atom10:link[rel="alternate"]/@href</tt>

<tt class="literal">/atom10:feed/atom10:link[@not rel]/@href</tt>

<tt class="literal">/atom03:feed/atom03:link[rel="alternate"]/@href</tt>

<tt class="literal">/rss/channel/link</tt>

<tt class="literal">/rdf:RDF/rdf:channel/rdf:link</tt>

See also

feed.links

← feed.title_detail

feed.links →

Copyright © 2004, 2005, 2006 Mark Pilgrim


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.treelogic.proteus</groupId>
		<artifactId>proteus</artifactId>
		<version>0.0.1</version>
	</parent>
	<artifactId>proteus-visualization</artifactId>
	<name>proteus-visualization</name>

	<dependencies>
		<dependency>
			<groupId>com.treelogic.proteus</groupId>
			<artifactId>proteus-resources</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.websocket</groupId>
			<artifactId>javax.websocket-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse.jetty.websocket</groupId>
			<artifactId>javax-websocket-server-impl</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse.jetty.websocket</groupId>
			<artifactId>javax-websocket-client-impl</artifactId>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<configuration>
					<skip>false</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.apisupport.kit">
    <module_version install_time="1360799832635" last="true" origin="installer" specification_version="1.21.1">
        <file crc="2820530587" name="VERSION.txt"/>
        <file crc="1181658957" name="config/Modules/org-netbeans-modules-apisupport-kit.xml"/>
        <file crc="3252806340" name="modules/locale/org-netbeans-modules-apisupport-kit_ja.jar"/>
        <file crc="3230135066" name="modules/locale/org-netbeans-modules-apisupport-kit_pt_BR.jar"/>
        <file crc="1255660046" name="modules/locale/org-netbeans-modules-apisupport-kit_ru.jar"/>
        <file crc="3480931054" name="modules/locale/org-netbeans-modules-apisupport-kit_zh_CN.jar"/>
        <file crc="844934201" name="modules/org-netbeans-modules-apisupport-kit.jar"/>
    </module_version>
</module>


text:
package net.npe.image.psd;

import java.io.IOException;

import net.npe.io.InputReader;

public class PsdDecorder {

	static void readRaw(InputReader reader, byte [] outBuffer) throws IOException {
		for(int i=0; i<outBuffer.length; i++) {
			outBuffer[i] = reader.readByte();
		}
	}

	static void decodeRunLengthEncoding(InputReader reader, byte [] outBuffer) throws IOException {
		for(int i=0; i<outBuffer.length; ) {
			byte packet = reader.readByte();
			if((packet & 0x80) != 0) {
				int count = 1 - (int)packet;
				byte value = reader.readByte();
				for(int j=0; j<count; j++) {
					outBuffer[i++] = value;
				}
			}
			else {
				int count = packet + 1;
				for(int j=0; j<count; j++) {
					outBuffer[i++] = reader.readByte();
				}
			}
		}
	}

}


text:
package.path = package.path .. ';' .. os.getenv("DRAGGIN_FRAMEWORK") .. '/src/?.lua'

-- makes output work better on most hosts, or when running through Sublime Text.
io.stdout:setvbuf("no")

local Draggin = require "draggin/draggin"
local Display = require "draggin/display"

----------------------------------------------------------------
-- App Title
Draggin.appTitle = "World of Hello"

----------------------------------------------------------------
-- Display
-- params: <string> window text, <number> virtual width, <number> virtual height, <number> screen width, <number> screen height
Display:init(Draggin.appTitle, 1920/2, 1080/2, 1920/2, 1080/2, false)

local GameStateManager = require "draggin/gamestatemanager"
local TextState = require "textstate"

--- Main MOAIThread function of the application.
-- The whole application starts here to make sure you can always call coroutine.yield()
local function mainFunc()

	local fb = MOAIGfxDevice:getFrameBuffer()
	fb:setClearColor(0, 1, 1)

	local textstate = TextState.new()

	GameStateManager.pushState(textstate)

	Draggin:waitForAnyInput()

	os.exit()
end

-- Let's just run the main function in a co-routine so we can use functions like Draggin:waitForAnyInput()
-- coroutines wake up once every frame, at the end of the frame they need to yield or reach the end of
-- the main coroutine function, effectively destroying that coroutine
local mainThread = MOAIThread.new()
mainThread:run(mainFunc)


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

#include <memory>
#include <string>
#include <vector>

#include "base/bind.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/json/json_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "cc/test/pixel_test_utils.h"
#include "components/viz/common/switches.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "headless/app/headless_shell_switches.h"
#include "headless/lib/browser/headless_web_contents_impl.h"
#include "headless/public/devtools/domains/browser.h"
#include "headless/public/devtools/domains/dom_snapshot.h"
#include "headless/public/devtools/domains/emulation.h"
#include "headless/public/devtools/domains/headless_experimental.h"
#include "headless/public/devtools/domains/io.h"
#include "headless/public/devtools/domains/page.h"
#include "headless/public/devtools/domains/runtime.h"
#include "headless/public/devtools/domains/security.h"
#include "headless/public/devtools/domains/target.h"
#include "headless/public/headless_browser.h"
#include "headless/public/headless_devtools_client.h"
#include "headless/public/headless_web_contents.h"
#include "headless/test/headless_browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/switches.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_f.h"
#include "url/gurl.h"

using testing::ElementsAre;
using testing::ElementsAreArray;
using testing::Not;
using testing::UnorderedElementsAre;
using testing::UnorderedElementsAreArray;

namespace headless {
class HeadlessWebContentsTest : public HeadlessBrowserTest {};

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, Navigation) {
  EXPECT_TRUE(embedded_test_server()->Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/hello.html"))
          .Build();
  EXPECT_TRUE(WaitForLoad(web_contents));

  EXPECT_THAT(browser_context->GetAllWebContents(),
              UnorderedElementsAre(web_contents));
}

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, WindowOpen) {
  EXPECT_TRUE(embedded_test_server()->Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/window_open.html"))
          .Build();
  EXPECT_TRUE(WaitForLoad(web_contents));

  EXPECT_EQ(2u, browser_context->GetAllWebContents().size());

  HeadlessWebContentsImpl* child = nullptr;
  HeadlessWebContentsImpl* parent = nullptr;
  for (HeadlessWebContents* c : browser_context->GetAllWebContents()) {
    HeadlessWebContentsImpl* impl = HeadlessWebContentsImpl::From(c);
    if (impl->window_id() == 1)
      parent = impl;
    else if (impl->window_id() == 2)
      child = impl;
  }

  EXPECT_NE(nullptr, parent);
  EXPECT_NE(nullptr, child);
  EXPECT_NE(parent, child);

  // Mac doesn't have WindowTreeHosts.
  if (parent && child && parent->window_tree_host())
    EXPECT_NE(parent->window_tree_host(), child->window_tree_host());

  gfx::Rect expected_bounds(0, 0, 200, 100);
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(expected_bounds, child->web_contents()->GetViewBounds());
  EXPECT_EQ(expected_bounds, child->web_contents()->GetContainerBounds());
#else   // !BUILDFLAG(IS_MAC)
  // Mac does not support GetViewBounds() and view positions are random.
  EXPECT_EQ(expected_bounds.size(),
            child->web_contents()->GetContainerBounds().size());
#endif  // !BUILDFLAG(IS_MAC)
}

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest,
                       FocusOfHeadlessWebContents_IsIndependent) {
  EXPECT_TRUE(embedded_test_server()->Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/hello.html"))
          .Build();
  WaitForLoadAndGainFocus(web_contents);

  std::unique_ptr<runtime::EvaluateResult> has_focus =
      EvaluateScript(web_contents, "document.hasFocus()");
  EXPECT_TRUE(has_focus->GetResult()->GetValue()->GetBool());

  HeadlessWebContents* web_contents2 =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/hello.html"))
          .Build();
  WaitForLoadAndGainFocus(web_contents2);

  // Focus of different WebContents is independent.
  has_focus = EvaluateScript(web_contents, "document.hasFocus()");
  EXPECT_TRUE(has_focus->GetResult()->GetValue()->GetBool());

  has_focus = EvaluateScript(web_contents2, "document.hasFocus()");
  EXPECT_TRUE(has_focus->GetResult()->GetValue()->GetBool());
}

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, HandleSSLError) {
  net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
  https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
  ASSERT_TRUE(https_server.Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(https_server.GetURL("/hello.html"))
          .Build();

  EXPECT_FALSE(WaitForLoad(web_contents));
}

namespace {
bool DecodePNG(const protocol::Binary& png_data, SkBitmap* bitmap) {
  return gfx::PNGCodec::Decode(png_data.data(), png_data.size(), bitmap);
}
}  // namespace

// Parameter specifies whether --disable-gpu should be used.
class HeadlessWebContentsScreenshotTest
    : public HeadlessAsyncDevTooledBrowserTest,
      public ::testing::WithParamInterface<bool> {
 public:
  void SetUp() override {
    EnablePixelOutput();
    if (GetParam()) {
      UseSoftwareCompositing();
      SetUpWithoutGPU();
    } else {
      HeadlessAsyncDevTooledBrowserTest::SetUp();
    }
  }

  void RunDevTooledTest() override {
    std::unique_ptr<runtime::EvaluateParams> params =
        runtime::EvaluateParams::Builder()
            .SetExpression("document.body.style.background = '#0000ff'")
            .Build();
    devtools_client_->GetRuntime()->Evaluate(
        std::move(params),
        base::BindOnce(&HeadlessWebContentsScreenshotTest::OnPageSetupCompleted,
                       base::Unretained(this)));
  }

  void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) {
    devtools_client_->GetPage()->GetExperimental()->CaptureScreenshot(
        page::CaptureScreenshotParams::Builder().Build(),
        base::BindOnce(&HeadlessWebContentsScreenshotTest::OnScreenshotCaptured,
                       base::Unretained(this)));
  }

  void OnScreenshotCaptured(
      std::unique_ptr<page::CaptureScreenshotResult> result) {
    protocol::Binary png_data = result->GetData();
    EXPECT_GT(png_data.size(), 0U);
    SkBitmap result_bitmap;
    EXPECT_TRUE(DecodePNG(png_data, &result_bitmap));

    EXPECT_EQ(800, result_bitmap.width());
    EXPECT_EQ(600, result_bitmap.height());
    SkColor actual_color = result_bitmap.getColor(400, 300);
    SkColor expected_color = SkColorSetRGB(0x00, 0x00, 0xff);
    EXPECT_EQ(expected_color, actual_color);
    FinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessWebContentsScreenshotTest);

// Instantiate test case for both software and gpu compositing modes.
INSTANTIATE_TEST_SUITE_P(HeadlessWebContentsScreenshotTests,
                         HeadlessWebContentsScreenshotTest,
                         ::testing::Bool());

// Regression test for crbug.com/832138.
class HeadlessWebContentsScreenshotWindowPositionTest
    : public HeadlessWebContentsScreenshotTest {
 public:
  void RunDevTooledTest() override {
    browser_devtools_client_->GetBrowser()->GetExperimental()->SetWindowBounds(
        browser::SetWindowBoundsParams::Builder()
            .SetWindowId(
                HeadlessWebContentsImpl::From(web_contents_)->window_id())
            .SetBounds(browser::Bounds::Builder()
                           .SetLeft(600)
                           .SetTop(100)
                           .SetWidth(800)
                           .SetHeight(600)
                           .Build())
            .Build(),
        base::BindOnce(
            &HeadlessWebContentsScreenshotWindowPositionTest::OnWindowBoundsSet,
            base::Unretained(this)));
  }

  void OnWindowBoundsSet(
      std::unique_ptr<browser::SetWindowBoundsResult> result) {
    EXPECT_TRUE(result);
    HeadlessWebContentsScreenshotTest::RunDevTooledTest();
  }
};

#if BUILDFLAG(IS_MAC) && defined(ADDRESS_SANITIZER)
// TODO(crbug.com/1086872): Disabled due to flakiness on Mac ASAN.
DISABLED_HEADLESS_ASYNC_DEVTOOLED_TEST_P(
    HeadlessWebContentsScreenshotWindowPositionTest);
#else
HEADLESS_ASYNC_DEVTOOLED_TEST_P(
    HeadlessWebContentsScreenshotWindowPositionTest);
#endif

// Instantiate test case for both software and gpu compositing modes.
INSTANTIATE_TEST_SUITE_P(HeadlessWebContentsScreenshotWindowPositionTests,
                         HeadlessWebContentsScreenshotWindowPositionTest,
                         ::testing::Bool());

class HeadlessWebContentsSecurityTest
    : public HeadlessAsyncDevTooledBrowserTest,
      public security::ExperimentalObserver {
 public:
  void RunDevTooledTest() override {
    devtools_client_->GetSecurity()->GetExperimental()->AddObserver(this);
    devtools_client_->GetSecurity()->GetExperimental()->Enable(
        security::EnableParams::Builder().Build());
  }

  void OnSecurityStateChanged(
      const security::SecurityStateChangedParams& params) override {
    EXPECT_EQ(security::SecurityState::NEUTRAL, params.GetSecurityState());

    devtools_client_->GetSecurity()->GetExperimental()->Disable(
        security::DisableParams::Builder().Build());
    devtools_client_->GetSecurity()->GetExperimental()->RemoveObserver(this);
    FinishAsynchronousTest();
  }
};

// Regression test for https://crbug.com/733569.
class HeadlessWebContentsRequestStorageQuotaTest
    : public HeadlessAsyncDevTooledBrowserTest,
      public runtime::Observer {
 public:
  void RunDevTooledTest() override {
    EXPECT_TRUE(embedded_test_server()->Start());

    base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
    devtools_client_->GetRuntime()->AddObserver(this);
    devtools_client_->GetRuntime()->Enable(run_loop.QuitClosure());
    run_loop.Run();

    // Should not crash and call console.log() if quota request succeeds.
    devtools_client_->GetPage()->Navigate(
        embedded_test_server()->GetURL("/request_storage_quota.html").spec());
  }

  void OnConsoleAPICalled(
      const runtime::ConsoleAPICalledParams& params) override {
    FinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsRequestStorageQuotaTest);

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, BrowserTabChangeContent) {
  EXPECT_TRUE(embedded_test_server()->Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder().Build();
  EXPECT_TRUE(WaitForLoad(web_contents));

  std::string script = "window.location = '" +
                       embedded_test_server()->GetURL("/hello.html").spec() +
                       "';";
  EXPECT_FALSE(EvaluateScript(web_contents, script)->HasExceptionDetails());

  // This will time out if the previous script did not work.
  EXPECT_TRUE(WaitForLoad(web_contents));
}

IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, BrowserOpenInTab) {
  EXPECT_TRUE(embedded_test_server()->Start());

  HeadlessBrowserContext* browser_context =
      browser()->CreateBrowserContextBuilder().Build();

  HeadlessWebContents* web_contents =
      browser_context->CreateWebContentsBuilder()
          .SetInitialURL(embedded_test_server()->GetURL("/link.html"))
          .Build();
  EXPECT_TRUE(WaitForLoad(web_contents));

  EXPECT_EQ(1u, browser_context->GetAllWebContents().size());
  // Simulates a middle-button click on a link to ensure that the
  // link is opened in a new tab by the browser and not by the renderer.
  std::string script =
      "var event = new MouseEvent('click', {'button': 1});"
      "document.getElementsByTagName('a')[0].dispatchEvent(event);";
  EXPECT_FALSE(EvaluateScript(web_contents, script)->HasExceptionDetails());

  // Check that we have a new tab.
  EXPECT_EQ(2u, browser_context->GetAllWebContents().size());
}

// BeginFrameControl is not supported on MacOS.
#if !BUILDFLAG(IS_MAC)

class HeadlessWebContentsBeginFrameControlTest
    : public HeadlessBrowserTest,
      public headless_experimental::ExperimentalObserver,
      public page::Observer {
 public:
  HeadlessWebContentsBeginFrameControlTest() {}

  void SetUp() override {
    EnablePixelOutput();
    HeadlessBrowserTest::SetUp();
  }

 protected:
  virtual std::string GetTestHtmlFile() = 0;
  virtual void OnNeedsBeginFrame() {}
  virtual void OnFrameFinished(
      std::unique_ptr<headless_experimental::BeginFrameResult> result) {}

  void RunTest() {
    browser_devtools_client_ = HeadlessDevToolsClient::Create();
    devtools_client_ = HeadlessDevToolsClient::Create();
    browser_context_ = browser()->CreateBrowserContextBuilder().Build();
    browser()->SetDefaultBrowserContext(browser_context_);
    browser()->GetDevToolsTarget()->AttachClient(
        browser_devtools_client_.get());

    EXPECT_TRUE(embedded_test_server()->Start());

    browser_devtools_client_->GetTarget()->GetExperimental()->CreateTarget(
        target::CreateTargetParams::Builder()
            .SetUrl("about:blank")
            .SetWidth(200)
            .SetHeight(200)
            .SetEnableBeginFrameControl(true)
            .Build(),
        base::BindOnce(
            &HeadlessWebContentsBeginFrameControlTest::OnCreateTargetResult,
            base::Unretained(this)));

    RunAsynchronousTest();

    browser()->GetDevToolsTarget()->DetachClient(
        browser_devtools_client_.get());
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    HeadlessBrowserTest::SetUpCommandLine(command_line);
    // See bit.ly/headless-rendering for why we use these flags.
    command_line->AppendSwitch(::switches::kRunAllCompositorStagesBeforeDraw);
    command_line->AppendSwitch(::switches::kDisableNewContentRenderingTimeout);
    command_line->AppendSwitch(cc::switches::kDisableCheckerImaging);
    command_line->AppendSwitch(cc::switches::kDisableThreadedAnimation);
    command_line->AppendSwitch(blink::switches::kDisableThreadedScrolling);
  }

  void OnCreateTargetResult(
      std::unique_ptr<target::CreateTargetResult> result) {
    web_contents_ = HeadlessWebContentsImpl::From(
        browser()->GetWebContentsForDevToolsAgentHostId(result->GetTargetId()));

    web_contents_->GetDevToolsTarget()->AttachClient(devtools_client_.get());
    devtools_client_->GetHeadlessExperimental()->GetExperimental()->AddObserver(
        this);
    devtools_client_->GetHeadlessExperimental()->GetExperimental()->Enable(
        headless_experimental::EnableParams::Builder().Build());

    devtools_client_->GetPage()->GetExperimental()->StopLoading(
        page::StopLoadingParams::Builder().Build(),
        base::BindOnce(
            &HeadlessWebContentsBeginFrameControlTest::LoadingStopped,
            base::Unretained(this)));
  }

  void LoadingStopped(std::unique_ptr<page::StopLoadingResult>) {
    devtools_client_->GetPage()->AddObserver(this);
    devtools_client_->GetPage()->Enable(base::BindOnce(
        &HeadlessWebContentsBeginFrameControlTest::PageDomainEnabled,
        base::Unretained(this)));
  }

  void PageDomainEnabled() {
    devtools_client_->GetPage()->Navigate(
        page::NavigateParams::Builder()
            .SetUrl(embedded_test_server()->GetURL(GetTestHtmlFile()).spec())
            .Build());
  }

  // page::Observer implementation:
  void OnLoadEventFired(const page::LoadEventFiredParams& params) override {
    TRACE_EVENT0("headless",
                 "HeadlessWebContentsBeginFrameControlTest::OnLoadEventFired");
    devtools_client_->GetPage()->Disable();
    devtools_client_->GetPage()->RemoveObserver(this);
    page_ready_ = true;
    if (needs_begin_frames_) {
      DCHECK(!frame_in_flight_);
      OnNeedsBeginFrame();
    }
  }

  // headless_experimental::ExperimentalObserver implementation:
  void OnNeedsBeginFramesChanged(
      const headless_experimental::NeedsBeginFramesChangedParams& params)
      override {
    TRACE_EVENT1(
        "headless",
        "HeadlessWebContentsBeginFrameControlTest::OnNeedsBeginFramesChanged",
        "needs_begin_frames", params.GetNeedsBeginFrames());
    needs_begin_frames_ = params.GetNeedsBeginFrames();
    // With full-pipeline mode and surface sync, the needs_begin_frame signal
    // should become and then always stay true.
    EXPECT_TRUE(needs_begin_frames_);
    EXPECT_FALSE(frame_in_flight_);
    if (page_ready_)
      OnNeedsBeginFrame();
  }

  void BeginFrame(bool screenshot) {
    // With full-pipeline mode and surface sync, the needs_begin_frame signal
    // should always be true.
    EXPECT_TRUE(needs_begin_frames_);

    frame_in_flight_ = true;
    num_begin_frames_++;

    auto builder = headless_experimental::BeginFrameParams::Builder();
    if (screenshot) {
      builder.SetScreenshot(
          headless_experimental::ScreenshotParams::Builder().Build());
    }

    devtools_client_->GetHeadlessExperimental()->GetExperimental()->BeginFrame(
        builder.Build(),
        base::BindOnce(&HeadlessWebContentsBeginFrameControlTest::FrameFinished,
                       base::Unretained(this)));
  }

  void FrameFinished(
      std::unique_ptr<headless_experimental::BeginFrameResult> result) {
    TRACE_EVENT2("headless",
                 "HeadlessWebContentsBeginFrameControlTest::FrameFinished",
                 "has_damage", result->GetHasDamage(), "has_screenshot_data",
                 result->HasScreenshotData());

    // Post OnFrameFinished call so that any pending OnNeedsBeginFramesChanged
    // call will be executed first.
    browser()->BrowserMainThread()->PostTask(
        FROM_HERE,
        base::BindOnce(
            &HeadlessWebContentsBeginFrameControlTest::NotifyOnFrameFinished,
            base::Unretained(this), std::move(result)));
  }

  void NotifyOnFrameFinished(
      std::unique_ptr<headless_experimental::BeginFrameResult> result) {
    frame_in_flight_ = false;
    OnFrameFinished(std::move(result));
  }

  void PostFinishAsynchronousTest() {
    devtools_client_->GetHeadlessExperimental()
        ->GetExperimental()
        ->RemoveObserver(this);

    browser()->BrowserMainThread()->PostTask(
        FROM_HERE,
        base::BindOnce(
            &HeadlessWebContentsBeginFrameControlTest::FinishAsynchronousTest,
            base::Unretained(this)));
  }

  raw_ptr<HeadlessBrowserContext> browser_context_ = nullptr;  // Not owned.
  raw_ptr<HeadlessWebContentsImpl> web_contents_ = nullptr;    // Not owned.

  bool page_ready_ = false;
  bool needs_begin_frames_ = false;
  bool frame_in_flight_ = false;
  int num_begin_frames_ = 0;
  std::unique_ptr<HeadlessDevToolsClient> browser_devtools_client_;
  std::unique_ptr<HeadlessDevToolsClient> devtools_client_;
};

class HeadlessWebContentsBeginFrameControlBasicTest
    : public HeadlessWebContentsBeginFrameControlTest {
 public:
  HeadlessWebContentsBeginFrameControlBasicTest() = default;

 protected:
  std::string GetTestHtmlFile() override {
    // Blue background.
    return "/blue_page.html";
  }

  void OnNeedsBeginFrame() override { BeginFrame(true); }

  void OnFrameFinished(std::unique_ptr<headless_experimental::BeginFrameResult>
                           result) override {
    if (num_begin_frames_ == 1) {
      // First BeginFrame should have caused damage and have a screenshot.
      EXPECT_TRUE(result->GetHasDamage());
      ASSERT_TRUE(result->HasScreenshotData());
      protocol::Binary png_data = result->GetScreenshotData();
      EXPECT_LT(0u, png_data.size());
      SkBitmap result_bitmap;
      EXPECT_TRUE(DecodePNG(png_data, &result_bitmap));
      EXPECT_EQ(200, result_bitmap.width());
      EXPECT_EQ(200, result_bitmap.height());
      SkColor expected_color = SkColorSetRGB(0x00, 0x00, 0xff);
      SkColor actual_color = result_bitmap.getColor(100, 100);
      EXPECT_EQ(expected_color, actual_color);
    } else {
      DCHECK_EQ(2, num_begin_frames_);
      // Can't guarantee that the second BeginFrame didn't have damage, but it
      // should not have a screenshot.
      EXPECT_FALSE(result->HasScreenshotData());
    }

    if (num_begin_frames_ < 2) {
      // Don't capture a screenshot in the second BeginFrame.
      BeginFrame(false);
    } else {
      // Post completion to avoid deleting the WebContents on the same callstack
      // as frame finished callback.
      PostFinishAsynchronousTest();
    }
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsBeginFrameControlBasicTest);

class HeadlessWebContentsBeginFrameControlViewportTest
    : public HeadlessWebContentsBeginFrameControlTest {
 public:
  HeadlessWebContentsBeginFrameControlViewportTest() = default;

 protected:
  std::string GetTestHtmlFile() override {
    // Draws a 100x100px blue box at 200x200px.
    return "/blue_box.html";
  }

  void OnNeedsBeginFrame() override {
    // Send a first BeginFrame to initialize the surface.
    BeginFrame(false);
  }

  void SetUpViewport() {
    devtools_client_->GetEmulation()
        ->GetExperimental()
        ->SetDeviceMetricsOverride(
            emulation::SetDeviceMetricsOverrideParams::Builder()
                .SetWidth(0)
                .SetHeight(0)
                .SetDeviceScaleFactor(0)
                .SetMobile(false)
                .SetViewport(page::Viewport::Builder()
                                 .SetX(200)
                                 .SetY(200)
                                 .SetWidth(100)
                                 .SetHeight(100)
                                 .SetScale(3)
                                 .Build())
                .Build(),
            base::BindOnce(&HeadlessWebContentsBeginFrameControlViewportTest::
                               SetDeviceMetricsOverrideDone,
                           base::Unretained(this)));
  }

  void SetDeviceMetricsOverrideDone(
      std::unique_ptr<emulation::SetDeviceMetricsOverrideResult> result) {
    EXPECT_TRUE(result);
    // Take a screenshot in the second BeginFrame.
    BeginFrame(true);
  }

  void OnFrameFinished(std::unique_ptr<headless_experimental::BeginFrameResult>
                           result) override {
    if (num_begin_frames_ == 1) {
      SetUpViewport();
      return;
    }

    DCHECK_EQ(2, num_begin_frames_);
    // Second BeginFrame should have a screenshot of the configured viewport and
    // of the correct size.
    EXPECT_TRUE(result->GetHasDamage());
    EXPECT_TRUE(result->HasScreenshotData());
    if (result->HasScreenshotData()) {
      protocol::Binary png_data = result->GetScreenshotData();
      EXPECT_LT(0u, png_data.size());
      SkBitmap result_bitmap;
      EXPECT_TRUE(DecodePNG(png_data, &result_bitmap));

      // Expext a 300x300 bitmap that is all blue.
      SkBitmap expected_bitmap;
      SkImageInfo info;
      expected_bitmap.allocPixels(
          SkImageInfo::MakeN32(300, 300, kOpaque_SkAlphaType), /*row_bytes=*/0);
      expected_bitmap.eraseColor(SkColorSetRGB(0x00, 0x00, 0xff));

      EXPECT_TRUE(
          cc::MatchesBitmap(result_bitmap, expected_bitmap,
                            cc::ExactPixelComparator(/*discard_alpha=*/false)));
    }

    // Post completion to avoid deleting the WebContents on the same callstack
    // as frame finished callback.
    PostFinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(
    HeadlessWebContentsBeginFrameControlViewportTest);

#endif  // !BUILDFLAG(IS_MAC)

class CookiesEnabled : public HeadlessAsyncDevTooledBrowserTest,
                       page::Observer {
 public:
  void RunDevTooledTest() override {
    devtools_client_->GetPage()->AddObserver(this);
    devtools_client_->GetPage()->Enable();

    EXPECT_TRUE(embedded_test_server()->Start());
    devtools_client_->GetPage()->Navigate(
        embedded_test_server()->GetURL("/cookie.html").spec());
  }

  // page::Observer implementation:
  void OnLoadEventFired(const page::LoadEventFiredParams& params) override {
    devtools_client_->GetRuntime()->Evaluate(
        "window.test_result",
        base::BindOnce(&CookiesEnabled::OnResult, base::Unretained(this)));
  }

  void OnResult(std::unique_ptr<runtime::EvaluateResult> result) {
    EXPECT_TRUE(result->GetResult()->HasValue());
    const base::Value* value = result->GetResult()->GetValue();
    EXPECT_TRUE(value->is_string());
    EXPECT_EQ("0", value->GetString());
    FinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(CookiesEnabled);

namespace {
const char* kPageWhichOpensAWindow = R"(
<html>
<body>
<script>
const win = window.open('/page2.html');
if (!win)
  console.error('ready');
win.addEventListener('load', () => console.log('ready'));
</script>
</body>
</html>
)";

const char* kPage2 = R"(
<html>
<body>
Page 2.
</body>
</html>
)";
}  // namespace

class WebContentsOpenTest : public runtime::Observer,
                            public HeadlessAsyncDevTooledBrowserTest {
 public:
  void RunDevTooledTest() override {
    interceptor_->InsertResponse("http://foo.com/index.html",
                                 {kPageWhichOpensAWindow, "text/html"});
    interceptor_->InsertResponse("http://foo.com/page2.html",
                                 {kPage2, "text/html"});

    base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
    devtools_client_->GetRuntime()->AddObserver(this);
    devtools_client_->GetRuntime()->Enable(run_loop.QuitClosure());
    run_loop.Run();

    devtools_client_->GetPage()->Navigate("http://foo.com/index.html");
  }
};

class DontBlockWebContentsOpenTest : public WebContentsOpenTest {
 public:
  void CustomizeHeadlessBrowserContext(
      HeadlessBrowserContext::Builder& builder) override {
    builder.SetBlockNewWebContents(false);
  }

  void OnConsoleAPICalled(
      const runtime::ConsoleAPICalledParams& params) override {
    EXPECT_THAT(
        interceptor_->urls_requested(),
        ElementsAre("http://foo.com/index.html", "http://foo.com/page2.html"));
    FinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(DontBlockWebContentsOpenTest);

class BlockWebContentsOpenTest : public WebContentsOpenTest {
 public:
  void CustomizeHeadlessBrowserContext(
      HeadlessBrowserContext::Builder& builder) override {
    builder.SetBlockNewWebContents(true);
  }

  void OnConsoleAPICalled(
      const runtime::ConsoleAPICalledParams& params) override {
    EXPECT_THAT(interceptor_->urls_requested(),
                ElementsAre("http://foo.com/index.html"));
    FinishAsynchronousTest();
  }
};

HEADLESS_ASYNC_DEVTOOLED_TEST_F(BlockWebContentsOpenTest);

}  // namespace headless


text:
package com.opengamma.financial.analytics.model.bond;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Clock;
import org.threeten.bp.Instant;
import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.NelsonSiegelSvennsonBondCurveModel;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.provider.calculator.generic.LastTimeCalculator;
import com.opengamma.analytics.math.curve.FunctionalDoublesCurve;
import com.opengamma.analytics.math.function.ParameterizedFunction;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.statistics.leastsquare.LeastSquareResults;
import com.opengamma.analytics.math.statistics.leastsquare.NonLinearLeastSquare;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.Security;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.conversion.BondSecurityConverter;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.security.FinancialSecuritySource;
import com.opengamma.financial.security.bond.BondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.util.money.Currency;

/**
 *
 */
public class NelsonSiegelSvenssonBondCurveFunction extends AbstractFunction {
  /** Name of the property type*/
  public static final String PROPERTY_CURVE_CALCULATION_TYPE = "Nelson_Siegel_Svennson_Bond_Curve";
  /** Name of the property*/
  public static final String PROPERTY_PREFIX = "Nelson-Siegel-Svennson";
  private static final Logger s_logger = LoggerFactory.getLogger(NelsonSiegelSvenssonBondCurveFunction.class);
  private static final NonLinearLeastSquare MINIMISER = new NonLinearLeastSquare();
  private static final LastTimeCalculator LAST_DATE = LastTimeCalculator.getInstance();
  private static final NelsonSiegelSvennsonBondCurveModel MODEL = new NelsonSiegelSvennsonBondCurveModel();
  //private static final ParameterLimitsTransform[] TRANSFORMS = new ParameterLimitsTransform[] {new SingleRangeLimitTransform(0, LimitType.GREATER_THAN), new NullTransform(), new NullTransform(),
  //  new NullTransform(), new NullTransform(), new NullTransform()};
  private static final BitSet FIXED_PARAMETERS = new BitSet(6);
  //TODO remove this hard-coding
  private static final String ISSUER_NAME = "US TREASURY N/B";
  private static final Currency CURRENCY = Currency.USD;

  static {
    FIXED_PARAMETERS.set(0);
  }

  private ValueSpecification _result;
  private Set<ValueSpecification> _results;

  @Override
  public void init(final FunctionCompilationContext context) {
    _result = new ValueSpecification(ValueRequirementNames.NSS_BOND_CURVE, ComputationTargetSpecification.of(CURRENCY), createValueProperties().with(
        PROPERTY_CURVE_CALCULATION_TYPE, PROPERTY_PREFIX + "_" + CURRENCY.getCode()).get());
    _results = Sets.newHashSet(_result);
  }

  @Override
  public String getShortName() {
    return "NelsonSiegelSvennsonBondCurveFunction";
  }

  @Override
  public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
    return new AbstractInvokingCompiledFunction() {

      @SuppressWarnings("synthetic-access")
      @Override
      public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
        final HolidaySource holidaySource = OpenGammaExecutionContext.getHolidaySource(executionContext);
        final ConventionBundleSource conventionSource = OpenGammaExecutionContext.getConventionBundleSource(executionContext);
        final RegionSource regionSource = OpenGammaExecutionContext.getRegionSource(executionContext);
        final Clock snapshotClock = executionContext.getValuationClock();
        final ZonedDateTime now = ZonedDateTime.now(snapshotClock);
        final BondSecurityConverter converter = new BondSecurityConverter(holidaySource, conventionSource, regionSource);
        final FinancialSecuritySource securitySource = executionContext.getSecuritySource(FinancialSecuritySource.class);
        final Collection<Security> allBonds = new ArrayList<Security>(securitySource.getBondsWithIssuerName(ISSUER_NAME));
        final Iterator<Security> iter = allBonds.iterator();
        while (iter.hasNext()) {
          final Security sec = iter.next();
          if (sec instanceof BondSecurity) {
            final BondSecurity bond = (BondSecurity) sec;
            if (bond.getLastTradeDate().getExpiry().isBefore(now)) {
              iter.remove();
            }
            s_logger.info(bond.getLastTradeDate().toString());
          } else {
            throw new OpenGammaRuntimeException("non-bond security " + sec + " returned by getAllBondsOfIssuerType()");
          }
        }
        final int n = allBonds.size();
        final double[] t = new double[n];
        final double[] ytm = new double[n];
        int i = 0;
        for (final Security security : allBonds) {
          final GovernmentBondSecurity bondSec = (GovernmentBondSecurity) security;
          final Object ytmObject = inputs.getValue(new ValueRequirement(ValueRequirementNames.YTM, ComputationTargetType.SECURITY, security.getUniqueId()));
          if (ytmObject == null) {
            s_logger.warn("Could not get YTM for " + security.getUniqueId());
            continue;
          }
          if (!(ytmObject instanceof Double)) {
            throw new IllegalArgumentException("YTM should be a double");
          }
          final InstrumentDefinition<?> definition = converter.visitGovernmentBondSecurity(bondSec);
          final InstrumentDerivative bond = definition.toDerivative(now);
          t[i] = bond.accept(LAST_DATE);
          ytm[i++] = ((Double) ytmObject / 100);
        }
        final DoubleMatrix1D initialValues = new DoubleMatrix1D(new double[] {1, 2, 3, 4, 2, 3 });
        final ParameterizedFunction<Double, DoubleMatrix1D, Double> parameterizedFunction = MODEL.getParameterizedFunction();
        final LeastSquareResults result = MINIMISER.solve(new DoubleMatrix1D(t), new DoubleMatrix1D(ytm), parameterizedFunction, initialValues);
        final DoubleMatrix1D parameters = result.getFitParameters();
        final FunctionalDoublesCurve curve = FunctionalDoublesCurve.from(parameterizedFunction.asFunctionOfArguments(parameters));
        final YieldCurve yieldCurve = YieldCurve.from(curve);
        return Sets.newHashSet(new ComputedValue(_result, yieldCurve));
      }

      @Override
      public ComputationTargetType getTargetType() {
        return ComputationTargetType.CURRENCY;
      }

      @SuppressWarnings("synthetic-access")
      @Override
      public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
        return CURRENCY.equals(target.getValue());
      }

      @SuppressWarnings("synthetic-access")
      @Override
      public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
        if (canApplyTo(context, target)) {
          final FinancialSecuritySource securitySource = context.getSecuritySource(FinancialSecuritySource.class);
          final Collection<Security> allBonds = new ArrayList<Security>(securitySource.getBondsWithIssuerName("US TREASURY N/B"));
          final Iterator<Security> iter = allBonds.iterator();
          while (iter.hasNext()) {
            final Security sec = iter.next();
            if (sec instanceof BondSecurity) {
              final BondSecurity bond = (BondSecurity) sec;
              if (bond.getLastTradeDate().getExpiry().toInstant().isBefore(atInstant)) {
                iter.remove();
              }
              s_logger.info(bond.getLastTradeDate().toString());
            } else {
              throw new OpenGammaRuntimeException("non-bond security " + sec + " returned by getAllBondsOfIssuerType()");
            }
          }
          final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>();
          for (final Security sec : allBonds) {
            if (sec instanceof BondSecurity) {
              final BondSecurity bond = (BondSecurity) sec;
              if (!bond.getCurrency().equals(CURRENCY)) {
                throw new OpenGammaRuntimeException("Currency for bond " + bond.getUniqueId() + " (" + bond.getCurrency() + ") did not match that required (" + CURRENCY + ")");
              }
              requirements.add(new ValueRequirement(ValueRequirementNames.YTM, ComputationTargetType.SECURITY, bond.getUniqueId()));
            } else {
              throw new OpenGammaRuntimeException("non-bond security " + sec + " returned with bonds of issuer type");
            }
          }
          return requirements;
        }
        return Sets.newHashSet();
      }

      @SuppressWarnings("synthetic-access")
      @Override
      public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
        return _results;
      }

    };
  }
}


text:
import * as React from "react";
import * as ReactDOM from "react-dom";

// import SCSS!
import "./main.scss";

import { Hello } from "./components/Hello";

const mainEl = document.getElementById("main");
ReactDOM.render(<Hello compiler="TypeScript" framework="React" />, mainEl);


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualScriptDeconstruct" inherits="VisualScriptNode" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
	<brief_description>
		A Visual Script node which deconstructs a base type instance into its parts.
	</brief_description>
	<description>
		A Visual Script node which deconstructs a base type instance into its parts.
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<members>
		<member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type" default="0">
			The type to deconstruct.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
package com.google.api.ads.dfp.jaxws.v201408;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Represents the options for an API report download request.
 *             See {@link ReportService#getReportDownloadUrlWithOptions}.
 *
 *
 *
Java class for ReportDownloadOptions complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ReportDownloadOptions">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="exportFormat" type="{https://www.google.com/apis/ads/publisher/v201408}ExportFormat" minOccurs="0"/>
 *         <element name="includeReportProperties" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="includeTotalsRow" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="useGzipCompression" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReportDownloadOptions", propOrder = {
    "exportFormat",
    "includeReportProperties",
    "includeTotalsRow",
    "useGzipCompression"
})
public class ReportDownloadOptions {

    protected ExportFormat exportFormat;
    protected Boolean includeReportProperties;
    protected Boolean includeTotalsRow;
    protected Boolean useGzipCompression;

    /**
     * Gets the value of the exportFormat property.
     *
     * @return
     *     possible object is
     *     {@link ExportFormat }
     *
     */
    public ExportFormat getExportFormat() {
        return exportFormat;
    }

    /**
     * Sets the value of the exportFormat property.
     *
     * @param value
     *     allowed object is
     *     {@link ExportFormat }
     *
     */
    public void setExportFormat(ExportFormat value) {
        this.exportFormat = value;
    }

    /**
     * Gets the value of the includeReportProperties property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIncludeReportProperties() {
        return includeReportProperties;
    }

    /**
     * Sets the value of the includeReportProperties property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIncludeReportProperties(Boolean value) {
        this.includeReportProperties = value;
    }

    /**
     * Gets the value of the includeTotalsRow property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIncludeTotalsRow() {
        return includeTotalsRow;
    }

    /**
     * Sets the value of the includeTotalsRow property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIncludeTotalsRow(Boolean value) {
        this.includeTotalsRow = value;
    }

    /**
     * Gets the value of the useGzipCompression property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isUseGzipCompression() {
        return useGzipCompression;
    }

    /**
     * Sets the value of the useGzipCompression property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setUseGzipCompression(Boolean value) {
        this.useGzipCompression = value;
    }

}


text:
import React from 'react'
import moment from 'moment'
import {text, boolean, number, object, color, select} from '@kadira/storybook-addon-knobs'

import {BLUE, DARK_BLUE, INTERVALS} from './variables.js'

import HistogramLinearScaleTooltip from './components/HistogramLinearScaleTooltip.js'
import Histogram from '../components/BarHistogram.js'

const d3 = Object.assign({},
  require('d3-array'),
  require('d3-random')
)

class BarHistogramLinearScaleStory extends React.Component {
  constructor(){
    super()
    //--
    this.randomPoints = this.randomPoints.bind(this)
    //--
    this.state = {
      margin: {top: 30, right: 15, bottom: 40, left: 30},
      width: 600,
      height: 400,
      fill: BLUE,
      stroke: DARK_BLUE,
      xAxis: 'linear',
      yAxis: 'linear',
      xTicks: 10,
      yTicks: 10,
      data: [],
    }
  }

  componentDidMount() {
    this.randomPoints()
  }

  randomPoints() {
    const MAX_X = 50

    const randomX = (x) => Math.floor(Math.random() * x)

    const data = d3.range(1000).map(() => [
      Math.random(),
      1
    ])

    this.setState({data})
  }

  render() {
    const {
      data,
      margin,
      width,
      height,
      xTicks,
      yTicks,
      xAxis,
      yAxis,
      stroke,
      fill,
      ...rest
    } = this.state

    const options = {
      linear: 'linear',
      time: 'time',
      scale: 'scale',
    };

    let intervals = [].concat(INTERVALS)
    intervals.sort()
    intervals.reduce((acc, i) => Object.assign(acc, {[i]: i}), {})

    const numberOptions = {min: 0, max: 1, step: 0.1, range: true}

    return (

          <button onClick={this.randomPoints}>Randomize!</button>
          {' '}
          Visualizing {data.length} random records

        <Histogram data={data}
                    margin={object('Margin', {top: 30, right: 15, bottom: 80, left: 40})}
                    width={number('Width', width)}
                    height={number('Height', height)}
                    xTicks={number('X Ticks', xTicks)}
                    yTicks={number('Y Ticks', yTicks)}
                    padding={number('Padding', 0.4, numberOptions)}
                    stroke={color('Stroke', stroke)}
                    fill={color('Fill', fill)}
                    xGrid={boolean('X Grid', false)}
                    yGrid={boolean('Y Grid', false)}
                    xAxis={select('X Axis', options, xAxis)}
                    yAxis={select('Y Axis', options, yAxis)}
                    thresholds={select('Thresholds', intervals, 'timeDay')}
                    tooltip={<HistogramLinearScaleTooltip />}
                    {...rest}
        />

    )
  }
}

export default BarHistogramLinearScaleStory


text:
package org.diirt.datasource.formula;

import org.diirt.datasource.ExpressionLanguage;
import org.diirt.vtype.VDouble;
import org.diirt.vtype.VNumber;
import org.diirt.vtype.ValueFactory;

/**
 *
 * @author carcassi
 */
abstract class OneArgNumericFunction implements ExpressionLanguage.OneArgFunction<VDouble, VNumber>  {

    @Override
    public VDouble calculate(VNumber arg) {
        if (arg == null) {
            return null;
        }
        return ValueFactory.newVDouble(calculate(arg.getValue().doubleValue()));
    }

    abstract double calculate(double arg);

}


text:
/*
FUNCTION
<<fmax>>, <<fmaxf>>---maximum
INDEX
	fmax
INDEX
	fmaxf

ANSI_SYNOPSIS
	#include <math.h>
	double fmax(double <[x]>, double <[y]>);
	float fmaxf(float <[x]>, float <[y]>);

DESCRIPTION
The <<fmax>> functions determine the maximum numeric value of their arguments.
NaN arguments are treated as missing data:  if one argument is a NaN and the
other numeric, then the <<fmax>> functions choose the numeric value.

RETURNS
The <<fmax>> functions return the maximum numeric value of their arguments.

PORTABILITY
ANSI C, POSIX.

*/

#include "fdlibm.h"

#ifndef _DOUBLE_IS_32BITS

#ifdef __STDC__
	double fmax(double x, double y)
#else
	double fmax(x,y)
	double x;
	double y;
#endif
{
  if (__fpclassifyd(x) == FP_NAN)
    return y;
  if (__fpclassifyd(y) == FP_NAN)
    return x;

  return x > y ? x : y;
}

#endif /* _DOUBLE_IS_32BITS */


text:
#schema-format {
  margin-right: 4px;
  width: 80px;
  flex-shrink: 0;
}

#schemas .download {
  background-image: url(../images/download.png);
  background-size: 100% 100%;
  width: 15px;
  height: 18px;
  flex-shrink: 0;
  margin-right: 3px;
  align-self: center;
  cursor: pointer;
}

#schemas .download.download-all {
  background-image: url(../images/download-all.png);
}


text:
package com.usst.app.front.action;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.usst.app.baseInfo.area.model.Area;
import com.usst.app.baseInfo.area.service.AreaService;
import com.usst.app.component.file.model.FileUpload;
import com.usst.app.component.file.service.FileUploadService;
import com.usst.app.front.model.GoodsInCar;
import com.usst.app.front.model.ShoppingCar;
import com.usst.app.good.good.model.Good;
import com.usst.app.good.good.service.GoodService;
import com.usst.app.good.goodExtend.model.GoodExtend;
import com.usst.app.good.goodExtend.service.GoodExtendService;
import com.usst.app.good.goodSpecification.model.GoodSpecification;
import com.usst.app.good.goodSpecification.model.GoodSpecificationVal;
import com.usst.app.good.goodSpecification.service.GoodSpecificationService;
import com.usst.app.good.goodSpecification.service.GoodSpecificationValService;
import com.usst.app.good.groupgood.model.Groupgood;
import com.usst.app.good.groupgood.service.GroupgoodService;
import com.usst.app.good.ware.model.Ware;
import com.usst.app.good.ware.service.WareService;
import com.usst.app.store.advertise.model.Advertise;
import com.usst.app.store.advertise.service.AdvertiseService;
import com.usst.app.store.information.model.Information;
import com.usst.app.store.information.service.InformationService;
import com.usst.app.warehouse.warehouse.service.WarehouseService;
import com.usst.code.struct.BaseAction;

public class FrontGroupBuyAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(FrontGoodAction.class);
	private Groupgood groupgood;
	private GroupgoodService groupgoodService;
	private WarehouseService warehouseService;
	private List<Area> listWarehouse;
	private Integer warehousecount;
	private GoodSpecificationValService goodSpecificationValService;
	private List<GoodSpecification> list1;
	private FileUploadService fileUploadService;
	private GoodSpecificationService goodSpecificationService;
	private List<FileUpload> goodPicList;
	private GoodExtendService goodExtendService;
	private GoodExtend goodExtend;
	private List<Advertise> advertiseList;
	private AdvertiseService advertiseService;
	private InformationService informationService;
	private List<Information> informationList;
	private List list;
	private Good good;
	private GoodService goodService;
	private Ware ware;
	private List<GoodsInCar> goodsInCarList;
	private WareService wareService;
	private GoodsInCar goodInCar;
	private AreaService areaService;

	public String getOneGroupgood() {
		logger.info("start to query Goods information");
		HttpServletRequest request = getRequest();
		HttpSession session = request.getSession();
		if (StringUtils.isNotBlank(this.groupgood.getId())) {
			this.groupgood = ((Groupgood) this.groupgoodService.select("Groupgood.Groupgood_SY", this.groupgood)
					.get(0));
		}
		Area areas = new Area();
		areas.setLevel(3);
		this.listWarehouse = this.areaService.select(areas);

		this.warehousecount = ((Integer) this.groupgoodService.selectToT("Groupgood.Groupgood_warehousecount_query",
				this.groupgood));

		GoodSpecificationVal goodSpecificationVal = new GoodSpecificationVal();
		goodSpecificationVal.setGoodId(this.groupgood.getId());
		this.list = this.goodSpecificationValService.select("GoodSpecificationVal.GoodSpecificationVal_groupgood_query",
				goodSpecificationVal);
		List<GoodSpecificationVal> goodSpecificationValList = this.list;
		String[] str = new String[goodSpecificationValList.size()];
		for (int i = 0; i < goodSpecificationValList.size(); i++) {
			str[i] = ((GoodSpecificationVal) goodSpecificationValList.get(i)).getGoodSpecificationId();
		}
		GoodSpecification goodSpecification = new GoodSpecification();
		this.list1 = new ArrayList();
		if (str.length > 0) {
			goodSpecification.setIdArr(str);
			this.list1 = this.goodSpecificationService
					.select("GoodSpecification.GoodSpecification_specificationVal_query", goodSpecification);
			getRequest().setAttribute("goodSpecificationnumber", Integer.valueOf(this.list1.size()));
		}
		try {
			this.goodPicList = this.fileUploadService.getFileUploadByGoodId(this.groupgood.getId());
			getRequest().setAttribute("picSize", Integer.valueOf(this.goodPicList.size()));
		} catch (Exception e) {
			logger.error("获取相册图片出错", e);
		}
		try {
			this.goodExtend = this.goodExtendService.getByGoodId(this.groupgood.getId());
		} catch (Exception e) {
			logger.error("资料扩展信息出错", e);
		}
		this.advertiseList = this.advertiseService.getAdvertiseList();
		this.informationList = this.informationService.select(new Information());

		return "group_good";
	}

	public void addGroupGoodToCart() {
		HttpServletRequest request = getRequest();
		try {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute("shoppingCar");
			ShoppingCar shoppingCar = null;
			if (obj == null) {
				shoppingCar = new ShoppingCar();
			} else {
				shoppingCar = (ShoppingCar) obj;
			}
			if (this.ware == null) {
				this.ware = new Ware();
			}
			String goodId = this.good.getId();

			String wareId = this.ware.getId();

			Integer count = Integer.valueOf(request.getParameter("number"));

			String wareSpecificationVal = this.ware.getWareSpecificationVal();
			wareSpecificationVal = URLDecoder.decode(wareSpecificationVal, "UTF-8");

			this.goodsInCarList = shoppingCar.getGoodsInCarList();
			if (this.goodsInCarList == null) {
				this.goodsInCarList = new ArrayList();
			}
			this.good = new Good();
			this.good = ((Good) this.goodService.getModel(goodId));
			this.ware = ((Ware) this.wareService.getModel(wareId));
			if (this.ware != null) {
				this.goodInCar = new GoodsInCar();
				this.goodInCar.setId(this.ware.getId());
				this.goodInCar.setCode(this.ware.getCode());
				this.goodInCar.setName(this.good.getName());
				this.goodInCar.setPrice(this.good.getPriceGroupBuy());
				this.goodInCar.setSpecificationVal(wareSpecificationVal);
				this.goodInCar.setCount(count);
				this.goodInCar.setPreferential(Double.valueOf(0.0D));
				this.goodInCar.setCredits(this.good.getCredits());
				this.goodInCar.setPicId(this.good.getPicId());
				this.goodInCar.setPic(this.good.getPic());
				this.goodInCar
						.setTotalMoney(Double.valueOf(this.good.getPriceGroupBuy().doubleValue() * count.intValue()));
				this.goodInCar.setGoodId(this.good.getId());
				boolean sameFlag = false;
				if (this.goodsInCarList.size() > 0) {
					for (int j = 0; j < this.goodsInCarList.size(); j++) {
						GoodsInCar good = (GoodsInCar) this.goodsInCarList.get(j);
						if (good.getId().equals(this.goodInCar.getId())) {
							good.setCount(Integer.valueOf(good.getCount().intValue() + count.intValue()));

							Double itemMoney = Double
									.valueOf(good.getCount().intValue() * good.getPrice().doubleValue());
							good.setTotalMoney(itemMoney);
							sameFlag = true;
						}
					}
				}
				if (!sameFlag) {
					this.goodsInCarList.add(this.goodInCar);
				}
			}
			shoppingCar.setGoodsInCarList(this.goodsInCarList);

			session.setAttribute("shoppingCar", shoppingCar);
			session.setAttribute("shoppingCarSize", Integer.valueOf(this.goodsInCarList.size()));
			responseFlag(true);
		} catch (Exception e) {
			responseFlag(false);
			logger.error("error occur when insert a goodInCar!", e);
		}
	}

	public Integer getWarehousecount() {
		return this.warehousecount;
	}

	public void setWarehousecount(Integer warehousecount) {
		this.warehousecount = warehousecount;
	}

	public List<GoodSpecification> getList1() {
		return this.list1;
	}

	public void setList1(List<GoodSpecification> list1) {
		this.list1 = list1;
	}

	public FileUploadService getFileUploadService() {
		return this.fileUploadService;
	}

	public void setFileUploadService(FileUploadService fileUploadService) {
		this.fileUploadService = fileUploadService;
	}

	public void setGroupgood(Groupgood groupgood) {
		this.groupgood = groupgood;
	}

	public void setGroupgoodService(GroupgoodService groupgoodService) {
		this.groupgoodService = groupgoodService;
	}

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setGoodSpecificationValService(GoodSpecificationValService goodSpecificationValService) {
		this.goodSpecificationValService = goodSpecificationValService;
	}

	public void setGoodSpecificationService(GoodSpecificationService goodSpecificationService) {
		this.goodSpecificationService = goodSpecificationService;
	}

	public List<Advertise> getAdvertiseList() {
		return this.advertiseList;
	}

	public void setAdvertiseList(List<Advertise> advertiseList) {
		this.advertiseList = advertiseList;
	}

	public List<FileUpload> getGoodPicList() {
		return this.goodPicList;
	}

	public void setGoodPicList(List<FileUpload> goodPicList) {
		this.goodPicList = goodPicList;
	}

	public GoodExtend getGoodExtend() {
		return this.goodExtend;
	}

	public void setGoodExtend(GoodExtend goodExtend) {
		this.goodExtend = goodExtend;
	}

	public List<Information> getInformationList() {
		return this.informationList;
	}

	public void setInformationList(List<Information> informationList) {
		this.informationList = informationList;
	}

	public void setGoodExtendService(GoodExtendService goodExtendService) {
		this.goodExtendService = goodExtendService;
	}

	public void setAdvertiseService(AdvertiseService advertiseService) {
		this.advertiseService = advertiseService;
	}

	public void setInformationService(InformationService informationService) {
		this.informationService = informationService;
	}

	public List getList() {
		return this.list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public Groupgood getGroupgood() {
		return this.groupgood;
	}

	public Good getGood() {
		return this.good;
	}

	public void setGood(Good good) {
		this.good = good;
	}

	public GoodService getGoodService() {
		return this.goodService;
	}

	public void setGoodService(GoodService goodService) {
		this.goodService = goodService;
	}

	public Ware getWare() {
		return this.ware;
	}

	public void setWare(Ware ware) {
		this.ware = ware;
	}

	public List<GoodsInCar> getGoodsInCarList() {
		return this.goodsInCarList;
	}

	public void setGoodsInCarList(List<GoodsInCar> goodsInCarList) {
		this.goodsInCarList = goodsInCarList;
	}

	public void setWareService(WareService wareService) {
		this.wareService = wareService;
	}

	public GoodsInCar getGoodInCar() {
		return this.goodInCar;
	}

	public void setGoodInCar(GoodsInCar goodInCar) {
		this.goodInCar = goodInCar;
	}

	public AreaService getAreaService() {
		return this.areaService;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public List<Area> getListWarehouse() {
		return this.listWarehouse;
	}

	public void setListWarehouse(List<Area> listWarehouse) {
		this.listWarehouse = listWarehouse;
	}
}


text:
$sqlService = Get-Service MSSQLSERVER

while ($sqlService.Status -ne 'Running')
{
	Write-Warning "SQL Server isn't running.  Trying to start it..."
    Start-Service MSSQLSERVER
    Start-Sleep -seconds 5
    $sqlService.Refresh()
}

$testAssemblies = gci -Recurse -Include "*Test.dll" | where { $_.FullName.Contains("\bin\") }
nunit3-console.exe --out=TestStdout.log --err=TestStderr.log $testAssemblies